@mapled/vanilla 0.1.1 → 0.2.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.
package/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
  <html lang="en">
14
14
  <head>
15
15
  <title data-mapled-bind="home.headline">Studio Nord</title>
16
- <script src="https://cdn.jsdelivr.net/npm/@mapled/vanilla@0.1.1/dist/mapled.js" data-mapled-key="mk_live_…" defer></script>
16
+ <script src="https://cdn.jsdelivr.net/npm/@mapled/vanilla@0.2.1/dist/mapled.js" data-mapled-key="mk_live_…" defer></script>
17
17
  </head>
18
18
  <body>
19
19
  <h1 data-mapled-bind="home.headline">Websites, built by hand</h1>
@@ -87,7 +87,7 @@ The key is the project's **delivery key** (Mapled: Integrations → Your site).
87
87
  </article>
88
88
  ```
89
89
 
90
- `post.html?slug=hello-world` shows the post whose slug field is `hello-world`. `data-mapled-slug="about-us"` names the record in the page instead. Tell Mapled the page's address as `/post.html?slug=[slug]` in the site manifest (with a `route_param` binding on the slug field), and **Preview** in the record's editor opens the right page.
90
+ `post.html?slug=hello-world` shows the post whose slug field is `hello-world`. `data-mapled-slug="about-us"` names the record in the page instead. Tell Mapled the page's address as `/post.html?slug=[slug]` in the site manifest (with a `route_param` binding on the slug field) — `npx @mapled/cli scan --write` writes it from the attributes — and **Preview** in the record's editor opens the right page.
91
91
 
92
92
  ### Forms
93
93
 
@@ -133,7 +133,7 @@ The key is the project's **delivery key** (Mapled: Integrations → Your site).
133
133
 
134
134
  ## Preview
135
135
 
136
- Nothing to set up in the page. **Preview** in Mapled opens the page with a one-time token — `https://your-site/post.html?slug=hello&mapled-preview=mpv_…` — and the script, before its first read, takes the token out of the address bar, trades it for a draft session and keeps the session for the tab. The page shows drafts until the tab closes or the session ends, and `<html>` carries `data-mapled-preview` meanwhile:
136
+ Nothing to set up in the page. **Preview** in Mapled opens the page with a one-time token — `https://your-site/post.html?slug=hello&mapled-preview=mpv_…` — and the script, before its first read, takes the token out of the address bar, trades it for a draft session and keeps the session for the tab. The page shows drafts until the tab closes or the session ends, and `<html>` carries `data-mapled-preview` meanwhile; a form posted from that tab is filed as a test submission — not counted, nobody notified, no workflow started:
137
137
 
138
138
  ```html
139
139
  <!-- preview-bar.html -->
@@ -143,11 +143,11 @@ Nothing to set up in the page. **Preview** in Mapled opens the page with a one-t
143
143
  </style>
144
144
  ```
145
145
 
146
- Mapled has to know where the site lives and that it renders in the browser: the site manifest's `framework` is `"plain-html"` (your AI agent's `push_site_manifest`, or `npx @mapled/cli bindings push`) — or the project was created as plain HTML — and **Production domain** in Project settings holds the site's public address (an agent sets it with `set_site_url`). `npx @mapled/cli doctor` checks all of it, the script tag's version included.
146
+ Mapled has to know where the site lives and that it renders in the browser: the site manifest's `framework` is `"plain-html"` (your AI agent's `push_site_manifest`, or `npx @mapled/cli scan --write` and `npx @mapled/cli bindings push` — the scan reads the pages' attributes into the manifest) — or the project was created as plain HTML — and **Production domain** in Project settings holds the site's public address (an agent sets it with `set_site_url`). `npx @mapled/cli doctor` checks all of it, the script tag's version included.
147
147
 
148
148
  ## Live updates
149
149
 
150
- A publish shows when the page is loaded again. To follow publishes while a page is open, add `data-mapled-live` to the script tag — `data-mapled-live="30"` for the seconds between checks (60 by default, 15 at least). A check is a request of the delivery key's budget (1,200 a minute), made only while the tab is visible; a quiet one costs next to nothing.
150
+ A publish shows when the page is loaded again. To follow publishes while a page is open, add `data-mapled-live` to the script tag — `data-mapled-live="30"` for the seconds between checks (60 by default, 15 at least). A check is a request of the delivery key's budget (1,200 a minute), made only while the tab is visible; a quiet one costs next to nothing. The page knows the release it filled from, and the watch starts there: a publish that landed between the fill and the first check, or while a tab opened in the background waited to be shown, fills the page at once — and a page left as written because Mapled was out of reach fills itself from the first release the watch hears.
151
151
 
152
152
  ## What content can and can't do to the page
153
153
 
@@ -172,13 +172,13 @@ const report = await page.ready;
172
172
  if (report.state === "fallback") console.info("Showing the page as written.");
173
173
  ```
174
174
 
175
- `mount({ key, apiUrl?, root?, live?, fetch? })` answers `{ ready, report, refresh(), endPreview(), stop(), client }` — `client` is the [`@mapled/client`](https://www.npmjs.com/package/@mapled/client) the page reads through, for reads of your own. The script tag does the same from its attributes (`data-mapled-key`, `data-mapled-api`, `data-mapled-live`) and leaves the result at `Mapled.page`; a tag without a key only defines `Mapled.mount`. `VERSION` is the package's version, `Mapled.version` in a page.
175
+ `mount({ key, apiUrl?, locale?, root?, live?, fetch? })` answers `{ ready, report, refresh(), endPreview(), stop(), client }` — `client` is the [`@mapled/client`](https://www.npmjs.com/package/@mapled/client) the page reads through, for reads of your own. The script tag does the same from its attributes (`data-mapled-key`, `data-mapled-api`, `data-mapled-live`, `data-mapled-locale`) and leaves the result at `Mapled.page`; a tag without a key only defines `Mapled.mount`. `VERSION` is the package's version, `Mapled.version` in a page.
176
176
 
177
177
  ## Every attribute
178
178
 
179
179
  | Attribute | On | Says |
180
180
  |---|---|---|
181
- | `data-mapled-key`, `data-mapled-api`, `data-mapled-live` | the script tag | the delivery key; another API origin; follow publishes |
181
+ | `data-mapled-key`, `data-mapled-api`, `data-mapled-live`, `data-mapled-locale` | the script tag | the delivery key; another API origin; follow publishes; read in one of the project's languages (`data-mapled-locale="ru"` — a translated field shows in it, or in the first language of the project's fallback chain that has a value) |
182
182
  | `data-mapled-bind` | an element | the path whose value fills it |
183
183
  | `data-mapled-format` | with `data-mapled-bind` | `text` (default), `markdown`, `date`, `datetime`, `number` |
184
184
  | `data-mapled-width` | an `<img>` | the width of the picture to ask for, 16–4096 |
package/dist/mapled.js CHANGED
@@ -1,18 +1,18 @@
1
- /*! @mapled/vanilla 0.1.1 | MIT | https://mapled.io */
2
- "use strict";(()=>{var $t=Object.defineProperty;var Ct=(e,t,n)=>t in e?$t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var me=(e,t,n)=>Ct(e,typeof t!="symbol"?t+"":t,n);var ge="mapled-preview",ne="mapled:preview",Lt=/^mpv_[A-Za-z0-9]{16,96}$/,Ge=/^mps_[A-Za-z0-9]{16,96}$/,Xe=new WeakMap,Ut=4e3;function he(){if(typeof window>"u"||typeof document>"u")return null;try{let e=window.sessionStorage,t=Xe.get(window);return t||Xe.set(window,t={memory:null,exchanging:null,epoch:0}),{location:window.location,history:window.history,sessionStorage:e,page:t}}catch{return null}}function Nt(e){try{let t=e.getItem(ne);if(!t)return null;let n=JSON.parse(t),r=typeof n?.expiresAt=="string"?Date.parse(n.expiresAt):NaN;return typeof n?.draftToken!="string"||!Ge.test(n.draftToken)||!(r>Date.now())?(e.removeItem(ne),null):{draftToken:n.draftToken,expiresAt:n.expiresAt}}catch{return null}}function D(e){let t=Nt(e.sessionStorage);if(t)return t;let n=e.page.memory;return n&&Date.parse(n.expiresAt)>Date.now()?n:(e.page.memory=null,null)}function _(){let e=he();return e?D(e):null}function Ve(e){let t;try{t=new URL(e.location.href)}catch{return null}let n=t.searchParams.get(ge);if(n===null)return null;t.searchParams.delete(ge);try{e.history.replaceState(e.history.state,"",`${t.pathname}${t.search}${t.hash}`)}catch{}return n}function ye(){let e=he();if(e){e.page.memory=null,e.page.epoch++,e.page.exchanging=null,Ve(e);try{e.sessionStorage.removeItem(ne)}catch{}}}function Ze(e={}){let t=he();if(!t)return Promise.resolve(null);let n=Ve(t);if(n===null)return t.page.exchanging?t.page.exchanging.done:Promise.resolve(D(t));if(!Lt.test(n))return Promise.resolve(D(t));if(t.page.exchanging?.token===n)return t.page.exchanging.done;let r=(e.apiUrl??"https://api.mapled.io").replace(/\/+$/,""),s=(e.appUrl??"https://app.mapled.io").replace(/\/+$/,""),l=e.fetch??fetch,c=++t.page.epoch,a=(async()=>{try{let o=await l(`${r}/v1/delivery/preview/exchange`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:n}),cache:"no-store"});if(o.ok){let i=await o.json();if(typeof i.draftToken!="string"||typeof i.expiresAt!="string"||!Ge.test(i.draftToken)||!(Date.parse(i.expiresAt)>Date.now())||t.page.epoch!==c)return D(t);let d={draftToken:i.draftToken,expiresAt:i.expiresAt};t.page.memory=d;try{t.sessionStorage.setItem(ne,JSON.stringify(d))}catch{}return d}if(o.status===401&&t.page.epoch===c){let i=await o.json().catch(()=>null),d=i?.error?.projectId;if(t.page.epoch===c&&i?.error?.code==="PREVIEW_EXPIRED"&&typeof d=="string"&&/^[0-9a-f-]{8,64}$/i.test(d))return t.location.assign(`${s}/preview/expired?project=${encodeURIComponent(d)}`),await new Promise(p=>setTimeout(p,Ut)),D(t)}return D(t)}catch{return D(t)}})(),f={token:n,done:a};return t.page.exchanging=f,a.then(()=>{t.page.exchanging===f&&(t.page.exchanging=null)}),a}async function Ye(e){return(await Ze(e))?.draftToken??null}function be(e){if(!e||typeof e!="object")return;let{release:t,publishedAt:n}=e;if(t===null)return n===null?null:void 0;if(!(!Number.isInteger(t)||t<1||typeof n!="string"))return{release:t,publishedAt:n}}function Je(e){let t=typeof e.key=="string"&&e.key.length>0;if(!t&&!e.endpoint)throw new Error("Mapled: watchRelease needs an endpoint or a delivery key.");let n=t?`${(e.apiUrl??"https://api.mapled.io").replace(/\/+$/,"")}/v1/delivery/release`:e.endpoint,r=t?{accept:"application/json","x-mapled-key":e.key}:{accept:"application/json"},s=(t?Math.max(15,e.interval??60):Math.max(2,e.interval??10))*1e3,l=e.fetch??fetch,c=typeof document>"u"?null:document,a,f=0,o=!1,i,d=null,p=()=>!c||c.visibilityState!=="hidden",k=()=>{o||!p()||(i=setTimeout(T,Math.min(s*2**f,3e5)))};async function T(){if(o||d)return;let M=new AbortController;d=M;let S=null;try{let C=await l(n,{cache:"no-cache",headers:r,signal:M.signal}),O=C.ok?be(await C.json()):void 0;if(o)return;O===void 0?f+=1:(f=0,a===void 0?a=O?O.release:null:O&&O.release>(a??0)&&(S={next:O,previous:a},a=O.release))}catch{if(o)return;f+=1}finally{d===M&&(d=null)}k(),S&&e.onPublish(S.next,S.previous)}let x=()=>{clearTimeout(i),p()&&T()};return c?.addEventListener("visibilitychange",x),p()&&T(),()=>{o=!0,clearTimeout(i),d?.abort(),c?.removeEventListener("visibilitychange",x)}}function Qe(e){let t={};return e.forEach((n,r)=>{typeof n!="string"||r in t||(t[r]=n)}),t}async function we(e,t,n){if(!n?.key)throw new Error("Mapled: a delivery key is required.");let r=(n.apiUrl??"https://api.mapled.io").replace(/\/+$/,""),s=typeof HTMLFormElement<"u"&&t instanceof HTMLFormElement?Qe(new FormData(t)):typeof FormData<"u"&&t instanceof FormData?Qe(t):{...t},l=n.page??(typeof window<"u"&&typeof document<"u"?window.location.pathname:void 0),c={...s};n.consent&&(c._consent=n.consent),l&&c._page===void 0&&(c._page=l),n.test&&(c._test=!0);let a;try{a=await(n.fetch??fetch)(`${r}/v1/delivery/forms/${encodeURIComponent(e)}`,{method:"POST",headers:{"content-type":"application/json","x-mapled-key":n.key},body:JSON.stringify(c)})}catch{return{ok:!1,status:0,code:"NETWORK",message:"Mapled couldn't be reached. Try again in a minute."}}if(a.ok)return{ok:!0};let f=`The submission wasn't accepted (${a.status}).`,o;try{let i=await a.json();i.error?.message&&(f=i.error.message),typeof i.error?.code=="string"&&(o=i.error.code)}catch{}return{ok:!1,status:a.status,code:o,message:f}}var ke=/^[a-z0-9][a-z0-9-]{0,63}$/,et=new Set;function It(e){if(typeof process<"u")return;let t=e?.aliases;if(!(!t||typeof t!="object")){for(let[n,r]of Object.entries(t))if(!(!r||typeof r!="object"||!ke.test(n)))for(let[s,l]of Object.entries(r)){if(typeof l!="string"||!ke.test(s)||!ke.test(l))continue;let c=`${n}.${s}`;et.has(c)||(et.add(c),console.warn(`[mapled] \u201C${s}\u201D in \u201C${n}\u201D was renamed to \u201C${l}\u201D. The old key keeps working until its alias is removed in Mapled \u2014 use \u201C${l}\u201D instead.`))}}}function rt(e,t={}){let n=(t.apiUrl??"https://api.mapled.io").replace(/\/+$/,""),r=new URLSearchParams;t.width&&r.set("w",String(t.width)),t.height&&r.set("h",String(t.height)),t.fit&&r.set("fit",t.fit),t.format&&r.set("fmt",t.format),t.quality&&r.set("q",String(t.quality));let s=r.toString();return`${n}/files/${encodeURIComponent(e)}${s?`?${s}`:""}`}var j=class extends Error{constructor(n,r,s){super(r);me(this,"status");me(this,"code");this.name="MapledError",this.status=n,this.code=s}},tt=e=>Number.isInteger(e)&&e>=1,nt=()=>new Error("Mapled: release must be a positive whole number.");function st(e){let t=(e.apiUrl??"https://api.mapled.io").replace(/\/+$/,"");if(!e.key)throw new Error("Mapled: a delivery key is required.");if(e.release!==void 0&&!tt(e.release))throw nt();let n=(o,i)=>(e.fetch??fetch)(o,i);async function r(){return e.draft===null?null:typeof e.draft=="string"?e.draft||null:typeof e.draft=="function"?await e.draft()||null:Ye({apiUrl:t,appUrl:e.appUrl,fetch:e.fetch})}async function s(o){let i=`Mapled request failed (${o.status}).`,d;try{let p=await o.json();p.error?.message&&(i=p.error.message),typeof p.error?.code=="string"&&(d=p.error.code)}catch{}return new j(o.status,i,d)}async function l(o,i,d){let p=await r(),k=d.release??e.release;if(k!==void 0&&!tt(k))throw nt();k!==void 0&&!p&&i.set("release",String(k));let T=i.toString(),x=await n(`${t}${o}${T?`?${T}`:""}`,{headers:p?{"x-mapled-key":e.key,"x-mapled-draft":p}:{"x-mapled-key":e.key},...p?{cache:"no-store"}:{},...d.signal?{signal:d.signal}:{}});if(!x.ok)throw await s(x);let M=await x.json();return It(M),M}let c=(o,i)=>(i.expand?.length&&o.set("expand",i.expand.join(",")),i.fields?.length&&o.set("fields",i.fields.join(",")),o),a=async(o,i)=>{try{return(await l(o,c(new URLSearchParams,i),i)).record}catch(d){if(d instanceof j&&d.status===404&&d.code!=="RELEASE_NOT_FOUND")return null;throw d}};return{async getRecords(o,i={}){let d=new URLSearchParams;for(let[p,k]of Object.entries(i.filter??{}))if(k!==null&&typeof k=="object")for(let[T,x]of Object.entries(k))x!==void 0&&d.set(`filter[${p}][${T}]`,Array.isArray(x)?x.join(","):String(x));else d.set(`filter[${p}]`,String(k));return i.sort&&d.set("sort",i.sort),i.limit!==void 0&&d.set("limit",String(i.limit)),i.offset!==void 0&&d.set("offset",String(i.offset)),c(d,i),l(`/v1/delivery/collections/${encodeURIComponent(o)}/records`,d,i)},getRecord(o,i,d={}){return a(`/v1/delivery/collections/${encodeURIComponent(o)}/records/${encodeURIComponent(i)}`,d)},getRecordBySlug(o,i,d={}){return a(`/v1/delivery/collections/${encodeURIComponent(o)}/records/by-slug/${encodeURIComponent(i)}`,d)},getSingle(o,i={}){return a(`/v1/delivery/singles/${encodeURIComponent(o)}`,i)},async isPreview(){return await r()!==null},watch(o,i={}){return Je({key:e.key,apiUrl:t,interval:i.interval,onPublish:o,fetch:e.fetch})},async getRelease(o={}){let i=await n(`${t}/v1/delivery/release`,{headers:{"x-mapled-key":e.key},cache:"no-cache",...o.signal?{signal:o.signal}:{}});if(!i.ok)throw await s(i);let d=be(await i.json());if(d===void 0)throw new Error("Mapled: the release pointer didn't come back as one \u2014 check the API origin.");return d}}}var Dt=/^[a-z0-9][a-z0-9_-]{0,63}$/;function H(e){if(typeof e!="string")return null;let t=e.trim().split(".");if(t.length>8)return null;for(let n of t)if(!Dt.test(n))return null;return t}var re=(e,t)=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function Se(e,t){let n=e.data,r=e.expanded;for(let s=0;s<t.length;s++){let l=t[s],c=s<t.length-1?re(r,l):void 0;if(c!==void 0){if(c===null||Array.isArray(c))return;n=re(c,"data"),r=re(c,"expanded");continue}if(n=re(n,l),r=void 0,n===void 0)return}return n}var W=e=>e==null||e===""||Array.isArray(e)&&e.length===0;function Ae(e){return typeof e=="string"?e:typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":Array.isArray(e)&&e.every(t=>typeof t=="string"||typeof t=="number")?e.join(", "):null}var Ft=new Set(["http:","https:","mailto:","tel:"]),_t=new Set(["http:","https:"]),jt=2048;function F(e,t,n){if(typeof e!="string"||e.length>jt)return null;let r;try{r=new URL(e,t)}catch{return null}return!(n==="link"?Ft:_t).has(r.protocol)||r.username!==""||r.password!==""?null:r.href}var Kt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ot=e=>typeof e=="string"&&Kt.test(e);function it(e,t,n){let r=[],s=e.replace(/\{([^{}]*)\}/g,(c,a)=>{let f=H(a);if(!f)return r.push({ok:!1,reason:"bad-path",path:a.trim().slice(0,80)}),"";let o=n(f);if(typeof o!="string"&&typeof o!="number"||o==="")return r.push({ok:!1,reason:"empty",path:f.join(".")}),"";try{return encodeURIComponent(String(o))}catch{return r.push({ok:!1,reason:"unsafe-url",path:f.join(".")}),""}});if(r[0])return r[0];let l=F(s,t,"link");return l===null?{ok:!1,reason:"unsafe-url",path:e.slice(0,80)}:{ok:!0,url:l}}var Bt=1e5,lt=8,ut=2048,qt="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",at={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",copy:"\xA9",reg:"\xAE",trade:"\u2122",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",laquo:"\xAB",raquo:"\xBB"};function ct(e,t,n){let r=t.createDocumentFragment();if(typeof e!="string"||e==="")return r;let s=e.replace(/\r\n?/g,`
3
- `).replace(/\t/g," ").replace(/\u0000/g,"\uFFFD"),l={doc:t,base:n};if(s.length>Bt){for(let c of s.split(/\n{2,}/))c.trim()!==""&&(P(l,"p",r).textContent=c.trim());return r}return Pe(l,s.split(`
4
- `),r,0),r}function P(e,t,n){let r=e.doc.createElement(t);return n.appendChild(r),r}var Re=e=>e.trim()==="",G=e=>e.length-e.trimStart().length;function dt(e){let t=G(e);if(t>3)return null;let n=0;for(;n<7&&e[t+n]==="#";)n++;if(n===0||n>6)return null;let r=e[t+n];if(r!==void 0&&r!==" ")return null;let s=e.slice(t+n).trim(),l=s.length;for(;l>0&&s[l-1]==="#";)l--;return l<s.length&&(l===0||s[l-1]===" ")&&(s=s.slice(0,l).trim()),{level:n,text:s}}function xe(e){if(G(e)>3)return!1;let t=e.replace(/ /g,""),n=t[0];if(t.length<3||n!=="-"&&n!=="*"&&n!=="_")return!1;for(let r of t)if(r!==n)return!1;return!0}function ve(e){let t=/^ {0,3}(`{3,}|~{3,})/.exec(e);if(!t)return null;let n=t[1][0];return n==="`"&&e.slice(t[0].length).includes("`")?null:{mark:n,size:t[1].length}}function X(e){let t=/^( {0,3})([-*+]|\d{1,9}[.)])( +|$)/.exec(e);if(!t)return null;let n=t[2],r=t[3].length,s=n.length>1||/\d/.test(n);return{indent:t[1].length,width:n.length+(r>=1&&r<=4?r:1),ordered:s,start:s?parseInt(n,10):1,rest:e.slice(t[0].length)}}var Te=e=>/^ {0,3}>/.test(e);function zt(e){if(dt(e)!==null||ve(e)!==null||Te(e)||xe(e))return!0;let t=X(e);return t!==null&&t.rest!==""&&(!t.ordered||t.start===1)}function Pe(e,t,n,r){if(r>=lt){let l=t.join(`
5
- `).trim();l!==""&&(P(e,"p",n).textContent=l);return}let s=0;for(;s<t.length;){let l=t[s];if(Re(l)){s++;continue}let c=ve(l);if(c){let i=[],d=G(l);for(s++;s<t.length;){let p=t[s],k=ve(p);if(k&&k.mark===c.mark&&k.size>=c.size&&p.trim().length===k.size)break;i.push(p.slice(Math.min(d,G(p)))),s++}s++,P(e,"code",P(e,"pre",n)).textContent=i.length>0?`${i.join(`
1
+ /*! @mapled/vanilla 0.2.1 | MIT | https://mapled.io */
2
+ "use strict";(()=>{var Ct=Object.defineProperty;var Lt=(e,t,n)=>t in e?Ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var be=(e,t,n)=>Lt(e,typeof t!="symbol"?t+"":t,n);var we="mapled-preview",ie="mapled:preview",Nt=/^mpv_[A-Za-z0-9]{16,96}$/,Ze=/^mps_[A-Za-z0-9]{16,96}$/,Ve=new WeakMap,Ut=4e3;function ke(){if(typeof window>"u"||typeof document>"u")return null;try{let e=window.sessionStorage,t=Ve.get(window);return t||Ve.set(window,t={memory:null,exchanging:null,epoch:0}),{location:window.location,history:window.history,sessionStorage:e,page:t}}catch{return null}}function It(e){try{let t=e.getItem(ie);if(!t)return null;let n=JSON.parse(t),r=typeof n?.expiresAt=="string"?Date.parse(n.expiresAt):NaN;return typeof n?.draftToken!="string"||!Ze.test(n.draftToken)||!(r>Date.now())?(e.removeItem(ie),null):{draftToken:n.draftToken,expiresAt:n.expiresAt}}catch{return null}}function K(e){let t=It(e.sessionStorage);if(t)return t;let n=e.page.memory;return n&&Date.parse(n.expiresAt)>Date.now()?n:(e.page.memory=null,null)}function B(){let e=ke();return e?K(e):null}function Ye(e){let t;try{t=new URL(e.location.href)}catch{return null}let n=t.searchParams.get(we);if(n===null)return null;t.searchParams.delete(we);try{e.history.replaceState(e.history.state,"",`${t.pathname}${t.search}${t.hash}`)}catch{}return n}function Se(){let e=ke();if(e){e.page.memory=null,e.page.epoch++,e.page.exchanging=null,Ye(e);try{e.sessionStorage.removeItem(ie)}catch{}}}function Je(e={}){let t=ke();if(!t)return Promise.resolve(null);let n=Ye(t);if(n===null)return t.page.exchanging?t.page.exchanging.done:Promise.resolve(K(t));if(!Nt.test(n))return Promise.resolve(K(t));if(t.page.exchanging?.token===n)return t.page.exchanging.done;let r=(e.apiUrl??"https://api.mapled.io").replace(/\/+$/,""),s=(e.appUrl??"https://app.mapled.io").replace(/\/+$/,""),o=e.fetch??fetch,c=++t.page.epoch,a=(async()=>{try{let i=await o(`${r}/v1/delivery/preview/exchange`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:n}),cache:"no-store"});if(i.ok){let p=await i.json();if(typeof p.draftToken!="string"||typeof p.expiresAt!="string"||!Ze.test(p.draftToken)||!(Date.parse(p.expiresAt)>Date.now())||t.page.epoch!==c)return K(t);let d={draftToken:p.draftToken,expiresAt:p.expiresAt};t.page.memory=d;try{t.sessionStorage.setItem(ie,JSON.stringify(d))}catch{}return d}if(i.status===401&&t.page.epoch===c){let p=await i.json().catch(()=>null),d=p?.error?.projectId;if(t.page.epoch===c&&p?.error?.code==="PREVIEW_EXPIRED"&&typeof d=="string"&&/^[0-9a-f-]{8,64}$/i.test(d))return t.location.assign(`${s}/preview/expired?project=${encodeURIComponent(d)}`),await new Promise(l=>setTimeout(l,Ut)),K(t)}return K(t)}catch{return K(t)}})(),f={token:n,done:a};return t.page.exchanging=f,a.then(()=>{t.page.exchanging===f&&(t.page.exchanging=null)}),a}async function Qe(e){return(await Je(e))?.draftToken??null}function Ae(e){if(!e||typeof e!="object")return;let{release:t,publishedAt:n}=e;if(t===null)return n===null?null:void 0;if(!(!Number.isInteger(t)||t<1||typeof n!="string"))return{release:t,publishedAt:n}}var Dt=1e4;function Ft(e,t){let n=typeof document>"u"?void 0:globalThis.performance?.timeOrigin;if(n===void 0)return!1;let r=Date.parse(t.get("date")??""),s=Number.isNaN(r)?0:r+(Number(t.get("age"))||0)*1e3-Date.now();return Date.parse(e)>n+s-Dt}function et(e,t){return(n,r)=>{if(e!==void 0)return e;let s=t?.();return s!==void 0?s:Ft(n.publishedAt,r)?null:n.release}}function tt(e,t,n){let r=typeof e.key=="string"&&e.key.length>0;if(!r&&!e.endpoint)throw new Error("Mapled: watchRelease needs an endpoint or a delivery key.");let s=r?`${(e.apiUrl??"https://api.mapled.io").replace(/\/+$/,"")}/v1/delivery/release`:e.endpoint,o=r?{accept:"application/json","x-mapled-key":e.key}:{accept:"application/json"},c=(r?Math.max(15,e.interval??60):Math.max(2,e.interval??10))*1e3,a=e.fetch??fetch,f=typeof document>"u"?null:document,i,p=null,d=0,l=null,g=0,S=!1,x,P=null,b=()=>!f||f.visibilityState!=="hidden",C=()=>{S||!b()||(x=setTimeout(L,Math.min(c*2**g,3e5)))};async function L(){if(S||P)return;let N=new AbortController;P=N;let U=null;try{let G=await a(s,{cache:"no-cache",headers:o,signal:N.signal}),O=G.ok?Ae(await G.json()):void 0;if(S)return;O===void 0?g+=1:(g=0,i===void 0&&(i=O?t(O,G.headers):null),O&&O.release>(p?.release??0)&&(p=O),O&&O.release>(i??0)?(U={next:O,previous:i},i=O.release,d=O.release,l=null):O&&l!==null&&typeof i=="number"&&O.release>=i&&i>d&&(U={next:O,previous:l},d=i,l=null))}catch{if(S)return;g+=1}finally{P===N&&(P=null)}C(),U&&e.onPublish(U.next,U.previous)}let $=()=>{clearTimeout(x),b()&&L()};f?.addEventListener("visibilitychange",$);let z=n?.(N=>{if(S||typeof i!="number"||N>=i||i<=d||(l=l===null?N:Math.min(l,N),p===null||p.release<i))return;d=i;let U=l;l=null,e.onPublish(p,U)});return b()&&L(),()=>{S=!0,clearTimeout(x),P?.abort(),z?.(),f?.removeEventListener("visibilitychange",$)}}function nt(e){let t={};return e.forEach((n,r)=>{typeof n!="string"||r in t||(t[r]=n)}),t}async function ve(e,t,n){if(!n?.key)throw new Error("Mapled: a delivery key is required.");let r=(n.apiUrl??"https://api.mapled.io").replace(/\/+$/,""),s=typeof HTMLFormElement<"u"&&t instanceof HTMLFormElement?nt(new FormData(t)):typeof FormData<"u"&&t instanceof FormData?nt(t):{...t},o=n.page??(typeof window<"u"&&typeof document<"u"?window.location.pathname:void 0),c={...s};n.consent&&(c._consent=n.consent),o&&c._page===void 0&&(c._page=o),n.test&&(c._test=!0);let a=B()?.draftToken,f={"content-type":"application/json","x-mapled-key":n.key};a&&(f["x-mapled-draft"]=a);let i;try{i=await(n.fetch??fetch)(`${r}/v1/delivery/forms/${encodeURIComponent(e)}`,{method:"POST",headers:f,body:JSON.stringify(c)})}catch{return{ok:!1,status:0,code:"NETWORK",message:"Mapled couldn't be reached. Try again in a minute."}}if(i.ok)return{ok:!0};let p=`The submission wasn't accepted (${i.status}).`,d;try{let l=await i.json();l.error?.message&&(p=l.error.message),typeof l.error?.code=="string"&&(d=l.error.code)}catch{}return{ok:!1,status:i.status,code:d,message:p}}var Re=/^[a-z0-9][a-z0-9-]{0,63}$/,rt=new Set;function _t(e){if(typeof process<"u")return;let t=e?.aliases;if(!(!t||typeof t!="object")){for(let[n,r]of Object.entries(t))if(!(!r||typeof r!="object"||!Re.test(n)))for(let[s,o]of Object.entries(r)){if(typeof o!="string"||!Re.test(s)||!Re.test(o))continue;let c=`${n}.${s}`;rt.has(c)||(rt.add(c),console.warn(`[mapled] \u201C${s}\u201D in \u201C${n}\u201D was renamed to \u201C${o}\u201D. The old key keeps working until its alias is removed in Mapled \u2014 use \u201C${o}\u201D instead.`))}}}function it(e,t={}){let n=(t.apiUrl??"https://api.mapled.io").replace(/\/+$/,""),r=new URLSearchParams;t.width&&r.set("w",String(t.width)),t.height&&r.set("h",String(t.height)),t.fit&&r.set("fit",t.fit),t.format&&r.set("fmt",t.format),t.quality&&r.set("q",String(t.quality));let s=r.toString();return`${n}/files/${encodeURIComponent(e)}${s?`?${s}`:""}`}var W=class extends Error{constructor(n,r,s){super(r);be(this,"status");be(this,"code");this.name="MapledError",this.status=n,this.code=s}},st=e=>Number.isInteger(e)&&e>=1,ot=()=>new Error("Mapled: release must be a positive whole number.");function at(e){let t=(e.apiUrl??"https://api.mapled.io").replace(/\/+$/,"");if(!e.key)throw new Error("Mapled: a delivery key is required.");if(e.release!==void 0&&!st(e.release))throw ot();let n=(d,l)=>(e.fetch??fetch)(d,l),r,s=new Set;async function o(){return e.draft===null?null:typeof e.draft=="string"?e.draft||null:typeof e.draft=="function"?await e.draft()||null:Qe({apiUrl:t,appUrl:e.appUrl,fetch:e.fetch})}async function c(d){let l=`Mapled request failed (${d.status}).`,g;try{let S=await d.json();S.error?.message&&(l=S.error.message),typeof S.error?.code=="string"&&(g=S.error.code)}catch{}return new W(d.status,l,g)}async function a(d,l,g){let S=await o(),x=g.release??e.release;if(x!==void 0&&!st(x))throw ot();x!==void 0&&!S&&l.set("release",String(x));let P=g.locale||e.locale;P&&l.set("locale",P);let b=l.toString(),C=await n(`${t}${d}${b?`?${b}`:""}`,{headers:S?{"x-mapled-key":e.key,"x-mapled-draft":S}:{"x-mapled-key":e.key},...S?{cache:"no-store"}:{},...g.signal?{signal:g.signal}:{}});if(!C.ok)throw await c(C);let L=await C.json();if(!S){let $=Number(C.headers.get("x-mapled-release"));if(Number.isInteger($)&&$>=1){r=r===void 0?$:Math.min(r,$);for(let z of s)Promise.resolve().then(()=>z($))}}return _t(L),L}let f=(d,l)=>(l.expand?.length&&d.set("expand",l.expand.join(",")),l.fields?.length&&d.set("fields",l.fields.join(",")),d),i=async(d,l)=>{try{return(await a(d,f(new URLSearchParams,l),l)).record}catch(g){if(g instanceof W&&g.status===404&&g.code!=="RELEASE_NOT_FOUND")return null;throw g}};return{async getRecords(d,l={}){let g=new URLSearchParams;for(let[S,x]of Object.entries(l.filter??{}))if(x!==null&&typeof x=="object")for(let[P,b]of Object.entries(x))b!==void 0&&g.set(`filter[${S}][${P}]`,Array.isArray(b)?b.join(","):String(b));else g.set(`filter[${S}]`,String(x));return l.sort&&g.set("sort",l.sort),l.limit!==void 0&&g.set("limit",String(l.limit)),l.offset!==void 0&&g.set("offset",String(l.offset)),f(g,l),a(`/v1/delivery/collections/${encodeURIComponent(d)}/records`,g,l)},getRecord(d,l,g={}){return i(`/v1/delivery/collections/${encodeURIComponent(d)}/records/${encodeURIComponent(l)}`,g)},getRecordBySlug(d,l,g={}){return i(`/v1/delivery/collections/${encodeURIComponent(d)}/records/by-slug/${encodeURIComponent(l)}`,g)},getSingle(d,l={}){return i(`/v1/delivery/singles/${encodeURIComponent(d)}`,l)},async isPreview(){return await o()!==null},watch(d,l={}){return tt({key:e.key,apiUrl:t,interval:l.interval,onPublish:d,fetch:e.fetch},et(l.from,()=>r),g=>(s.add(g),()=>{s.delete(g)}))},async getRelease(d={}){let l=await n(`${t}/v1/delivery/release`,{headers:{"x-mapled-key":e.key},cache:"no-cache",...d.signal?{signal:d.signal}:{}});if(!l.ok)throw await c(l);let g=Ae(await l.json());if(g===void 0)throw new Error("Mapled: the release pointer didn't come back as one \u2014 check the API origin.");return g}}}var jt=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Z(e){if(typeof e!="string")return null;let t=e.trim().split(".");if(t.length>8)return null;for(let n of t)if(!jt.test(n))return null;return t}var ae=(e,t)=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function Te(e,t){let n=e.data,r=e.expanded;for(let s=0;s<t.length;s++){let o=t[s],c=s<t.length-1?ae(r,o):void 0;if(c!==void 0){if(c===null||Array.isArray(c))return;n=ae(c,"data"),r=ae(c,"expanded");continue}if(n=ae(n,o),r=void 0,n===void 0)return}return n}var Y=e=>e==null||e===""||Array.isArray(e)&&e.length===0;function Ee(e){return typeof e=="string"?e:typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":Array.isArray(e)&&e.every(t=>typeof t=="string"||typeof t=="number")?e.join(", "):null}var Kt=new Set(["http:","https:","mailto:","tel:"]),Bt=new Set(["http:","https:"]),Ht=2048;function H(e,t,n){if(typeof e!="string"||e.length>Ht)return null;let r;try{r=new URL(e,t)}catch{return null}return!(n==="link"?Kt:Bt).has(r.protocol)||r.username!==""||r.password!==""?null:r.href}var qt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,lt=e=>typeof e=="string"&&qt.test(e);function ut(e,t,n){let r=[],s=e.replace(/\{([^{}]*)\}/g,(c,a)=>{let f=Z(a);if(!f)return r.push({ok:!1,reason:"bad-path",path:a.trim().slice(0,80)}),"";let i=n(f);if(typeof i!="string"&&typeof i!="number"||i==="")return r.push({ok:!1,reason:"empty",path:f.join(".")}),"";try{return encodeURIComponent(String(i))}catch{return r.push({ok:!1,reason:"unsafe-url",path:f.join(".")}),""}});if(r[0])return r[0];let o=H(s,t,"link");return o===null?{ok:!1,reason:"unsafe-url",path:e.slice(0,80)}:{ok:!0,url:o}}var zt=1e5,dt=8,ft=2048,Wt="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",ct={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",copy:"\xA9",reg:"\xAE",trade:"\u2122",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",laquo:"\xAB",raquo:"\xBB"};function pt(e,t,n){let r=t.createDocumentFragment();if(typeof e!="string"||e==="")return r;let s=e.replace(/\r\n?/g,`
3
+ `).replace(/\t/g," ").replace(/\u0000/g,"\uFFFD"),o={doc:t,base:n};if(s.length>zt){for(let c of s.split(/\n{2,}/))c.trim()!==""&&(M(o,"p",r).textContent=c.trim());return r}return Ce(o,s.split(`
4
+ `),r,0),r}function M(e,t,n){let r=e.doc.createElement(t);return n.appendChild(r),r}var xe=e=>e.trim()==="",Q=e=>e.length-e.trimStart().length;function mt(e){let t=Q(e);if(t>3)return null;let n=0;for(;n<7&&e[t+n]==="#";)n++;if(n===0||n>6)return null;let r=e[t+n];if(r!==void 0&&r!==" ")return null;let s=e.slice(t+n).trim(),o=s.length;for(;o>0&&s[o-1]==="#";)o--;return o<s.length&&(o===0||s[o-1]===" ")&&(s=s.slice(0,o).trim()),{level:n,text:s}}function $e(e){if(Q(e)>3)return!1;let t=e.replace(/ /g,""),n=t[0];if(t.length<3||n!=="-"&&n!=="*"&&n!=="_")return!1;for(let r of t)if(r!==n)return!1;return!0}function Pe(e){let t=/^ {0,3}(`{3,}|~{3,})/.exec(e);if(!t)return null;let n=t[1][0];return n==="`"&&e.slice(t[0].length).includes("`")?null:{mark:n,size:t[1].length}}function J(e){let t=/^( {0,3})([-*+]|\d{1,9}[.)])( +|$)/.exec(e);if(!t)return null;let n=t[2],r=t[3].length,s=n.length>1||/\d/.test(n);return{indent:t[1].length,width:n.length+(r>=1&&r<=4?r:1),ordered:s,start:s?parseInt(n,10):1,rest:e.slice(t[0].length)}}var Me=e=>/^ {0,3}>/.test(e);function Xt(e){if(mt(e)!==null||Pe(e)!==null||Me(e)||$e(e))return!0;let t=J(e);return t!==null&&t.rest!==""&&(!t.ordered||t.start===1)}function Ce(e,t,n,r){if(r>=dt){let o=t.join(`
5
+ `).trim();o!==""&&(M(e,"p",n).textContent=o);return}let s=0;for(;s<t.length;){let o=t[s];if(xe(o)){s++;continue}let c=Pe(o);if(c){let p=[],d=Q(o);for(s++;s<t.length;){let l=t[s],g=Pe(l);if(g&&g.mark===c.mark&&g.size>=c.size&&l.trim().length===g.size)break;p.push(l.slice(Math.min(d,Q(l)))),s++}s++,M(e,"code",M(e,"pre",n)).textContent=p.length>0?`${p.join(`
6
6
  `)}
7
- `:"";continue}let a=dt(l);if(a){oe(e,a.text,P(e,`h${a.level}`,n),r),s++;continue}if(xe(l)){P(e,"hr",n),s++;continue}if(Te(l)){let i=[];for(;s<t.length&&Te(t[s]);)i.push(t[s].replace(/^ {0,3}> ?/,"")),s++;Pe(e,i,P(e,"blockquote",n),r+1);continue}let f=X(l);if(f){s=Ht(e,t,s,f,n,r);continue}let o=[l.trimStart()];for(s++;s<t.length&&!Re(t[s])&&!zt(t[s]);)o.push(t[s].trimStart()),s++;oe(e,o.join(`
8
- `),P(e,"p",n),r)}}function Ht(e,t,n,r,s,l){let c=P(e,r.ordered?"ol":"ul",s);r.ordered&&r.start!==1&&c.setAttribute("start",String(r.start));let a=[],f=!1;for(;n<t.length;){let o=X(t[n]);if(!o||o.ordered!==r.ordered||o.indent!==r.indent||xe(t[n]))break;let i=o.indent+o.width,d=[o.rest];n++;let p=!1;for(;n<t.length;){let k=t[n];if(Re(k)){p=!0,d.push(""),n++;continue}if(G(k)<i)break;p&&d.some(T=>T!=="")&&!X(k.slice(i))&&(f=!0),p=!1,d.push(k.slice(i)),n++}for(;d.length>0&&d[d.length-1]==="";)d.pop();if(p&&n<t.length){let k=X(t[n]);k&&k.ordered===r.ordered&&k.indent===r.indent&&(f=!0)}a.push({lines:d,el:P(e,"li",c)})}for(let o of a)if(Pe(e,o.lines,o.el,l+1),!f){for(let i of Array.from(o.el.childNodes))if(i.nodeName==="P"){for(;i.firstChild;)o.el.insertBefore(i.firstChild,i);o.el.removeChild(i)}}return n}var Me=e=>e===void 0||e===" "||e===`
9
- `,ft=e=>e!==void 0&&/[\p{L}\p{N}]/u.test(e);function se(e,t,n,r,s=""){let l=Math.min(e.length,r);for(let c=n;c<l;c++){if(e[c]===t)return c;if(s.includes(e[c]))return-1}return-1}function V(e,t,n){let r=t;for(;e[r]===n;)r++;return r}function pt(e,t){if(e[t]==="\\")return t+2;if(e[t]==="`"){let n=V(e,t,"`"),r=mt(e,n,n-t);return r===-1?n:r+(n-t)}return-1}function mt(e,t,n){let r=e.indexOf("`",t);for(;r!==-1;){let s=V(e,r,"`");if(s-r===n)return r;r=e.indexOf("`",s)}return-1}function Wt(e,t,n){let r=n[0],s=t;for(;s<e.length;){let l=pt(e,s);if(l!==-1){s=l;continue}if(e[s]!==r){s++;continue}let c=V(e,s,r),a=c-s;if((n.length===1?a===1||a>=3:a>=n.length)&&s>t&&!Me(e[s-1])&&(r!=="_"||!ft(e[c])))return c-n.length;s=c}return-1}function Xt(e,t){let n=se(e,";",t+1,t+34,`
10
- &`);if(n===-1)return null;let r=e.slice(t+1,n);if(r[0]==="#"){let l=r[1]==="x"||r[1]==="X",c=r.slice(l?2:1);if(!(l?/^[0-9a-fA-F]{1,6}$/:/^[0-9]{1,7}$/).test(c))return null;let a=parseInt(c,l?16:10);return{char:a>0&&a<=1114111&&!(a>=55296&&a<=57343)?String.fromCodePoint(a):"\uFFFD",end:n+1}}let s=Object.prototype.hasOwnProperty.call(at,r)?at[r]:void 0;return s===void 0?null:{char:s,end:n+1}}var gt=e=>e.replace(/\\([!-/:-@[-`{-~])/g,"$1");function Gt(e,t){if(e[t]!=="(")return null;let n=Math.min(e.length,t+ut+1024),r=t+1;for(;r<n&&Me(e[r])&&e[r]!==void 0;)r++;let s="";if(e[r]==="<"){let c=se(e,">",r+1,n,`
7
+ `:"";continue}let a=mt(o);if(a){ue(e,a.text,M(e,`h${a.level}`,n),r),s++;continue}if($e(o)){M(e,"hr",n),s++;continue}if(Me(o)){let p=[];for(;s<t.length&&Me(t[s]);)p.push(t[s].replace(/^ {0,3}> ?/,"")),s++;Ce(e,p,M(e,"blockquote",n),r+1);continue}let f=J(o);if(f){s=Gt(e,t,s,f,n,r);continue}let i=[o.trimStart()];for(s++;s<t.length&&!xe(t[s])&&!Xt(t[s]);)i.push(t[s].trimStart()),s++;ue(e,i.join(`
8
+ `),M(e,"p",n),r)}}function Gt(e,t,n,r,s,o){let c=M(e,r.ordered?"ol":"ul",s);r.ordered&&r.start!==1&&c.setAttribute("start",String(r.start));let a=[],f=!1;for(;n<t.length;){let i=J(t[n]);if(!i||i.ordered!==r.ordered||i.indent!==r.indent||$e(t[n]))break;let p=i.indent+i.width,d=[i.rest];n++;let l=!1;for(;n<t.length;){let g=t[n];if(xe(g)){l=!0,d.push(""),n++;continue}if(Q(g)<p)break;l&&d.some(S=>S!=="")&&!J(g.slice(p))&&(f=!0),l=!1,d.push(g.slice(p)),n++}for(;d.length>0&&d[d.length-1]==="";)d.pop();if(l&&n<t.length){let g=J(t[n]);g&&g.ordered===r.ordered&&g.indent===r.indent&&(f=!0)}a.push({lines:d,el:M(e,"li",c)})}for(let i of a)if(Ce(e,i.lines,i.el,o+1),!f){for(let p of Array.from(i.el.childNodes))if(p.nodeName==="P"){for(;p.firstChild;)i.el.insertBefore(p.firstChild,p);i.el.removeChild(p)}}return n}var Le=e=>e===void 0||e===" "||e===`
9
+ `,gt=e=>e!==void 0&&/[\p{L}\p{N}]/u.test(e);function le(e,t,n,r,s=""){let o=Math.min(e.length,r);for(let c=n;c<o;c++){if(e[c]===t)return c;if(s.includes(e[c]))return-1}return-1}function ee(e,t,n){let r=t;for(;e[r]===n;)r++;return r}function ht(e,t){if(e[t]==="\\")return t+2;if(e[t]==="`"){let n=ee(e,t,"`"),r=yt(e,n,n-t);return r===-1?n:r+(n-t)}return-1}function yt(e,t,n){let r=e.indexOf("`",t);for(;r!==-1;){let s=ee(e,r,"`");if(s-r===n)return r;r=e.indexOf("`",s)}return-1}function Vt(e,t,n){let r=n[0],s=t;for(;s<e.length;){let o=ht(e,s);if(o!==-1){s=o;continue}if(e[s]!==r){s++;continue}let c=ee(e,s,r),a=c-s;if((n.length===1?a===1||a>=3:a>=n.length)&&s>t&&!Le(e[s-1])&&(r!=="_"||!gt(e[c])))return c-n.length;s=c}return-1}function Zt(e,t){let n=le(e,";",t+1,t+34,`
10
+ &`);if(n===-1)return null;let r=e.slice(t+1,n);if(r[0]==="#"){let o=r[1]==="x"||r[1]==="X",c=r.slice(o?2:1);if(!(o?/^[0-9a-fA-F]{1,6}$/:/^[0-9]{1,7}$/).test(c))return null;let a=parseInt(c,o?16:10);return{char:a>0&&a<=1114111&&!(a>=55296&&a<=57343)?String.fromCodePoint(a):"\uFFFD",end:n+1}}let s=Object.prototype.hasOwnProperty.call(ct,r)?ct[r]:void 0;return s===void 0?null:{char:s,end:n+1}}var bt=e=>e.replace(/\\([!-/:-@[-`{-~])/g,"$1");function Yt(e,t){if(e[t]!=="(")return null;let n=Math.min(e.length,t+ft+1024),r=t+1;for(;r<n&&Le(e[r])&&e[r]!==void 0;)r++;let s="";if(e[r]==="<"){let c=le(e,">",r+1,n,`
11
11
  <`);if(c===-1)return null;s=e.slice(r+1,c),r=c+1}else{let c=r,a=0;for(;r<n;){let f=e[r];if(f==="\\"&&r+1<n){r+=2;continue}if(f===" "||f===`
12
12
  `)break;if(f==="("&&a++,f===")"){if(a===0)break;a--}r++}s=e.slice(c,r)}for(;r<n&&(e[r]===" "||e[r]===`
13
- `);)r++;let l=e[r];if(l==='"'||l==="'"||l==="("){let c=se(e,l==="("?")":l,r+1,n);if(c===-1)return null;for(r=c+1;r<n&&(e[r]===" "||e[r]===`
14
- `);)r++}return e[r]!==")"?null:{address:gt(s),end:r+1}}function Ee(e,t,n=!1){let r=t+1;for(;r<e.length;){let l=pt(e,r);if(l!==-1){r=l;continue}if(!n&&e[r]==="!"&&e[r+1]==="["){let c=Ee(e,r+1,!0);if(!c)return null;r=c.end;continue}if(e[r]==="[")return null;if(e[r]==="]")break;r++}if(r>=e.length)return null;let s=Gt(e,r+1);return s?{label:e.slice(t+1,r),address:s.address,end:s.end}:null}var Vt=/^(?:[a-z][a-z0-9+.-]{1,31}:[^\s<>]*|[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+)$/i;function oe(e,t,n,r){if(r>=lt){n.appendChild(e.doc.createTextNode(t));return}let s="",l=()=>{s!==""&&n.appendChild(e.doc.createTextNode(s)),s=""},c=new Set,a=0;for(;a<t.length;){let f=t[a];if(f==="\\"){let o=t[a+1];if(o===`
15
- `)for(l(),P(e,"br",n),a+=2;t[a]===" ";)a++;else o!==void 0&&qt.includes(o)?(s+=o,a+=2):(s+=f,a++);continue}if(f===`
16
- `){let o=s.endsWith(" "),i=s.length;for(;i>0&&s[i-1]===" ";)i--;for(s=s.slice(0,i),o?(l(),P(e,"br",n)):s+=`
17
- `,a++;t[a]===" ";)a++;continue}if(f==="`"){let o=V(t,a,"`"),i=mt(t,o,o-a);if(i===-1){s+=t.slice(a,o),a=o;continue}let d=t.slice(o,i).replace(/\n/g," ");d.length>1&&d.startsWith(" ")&&d.endsWith(" ")&&d.trim()!==""&&(d=d.slice(1,-1)),l(),P(e,"code",n).textContent=d,a=i+(o-a);continue}if(f==="!"&&t[a+1]==="["){let o=Ee(t,a+1);if(o){let i=gt(o.label),d=F(o.address.trim(),e.base,"media");if(d===null)s+=i;else{l();let p=P(e,"img",n);p.setAttribute("src",d),p.setAttribute("alt",i),p.setAttribute("loading","lazy")}a=o.end;continue}}if(f==="["){let o=Ee(t,a);if(o){let i=F(o.address.trim(),e.base,"link");l();let d=i===null?n:P(e,"a",n);i!==null&&d.setAttribute("href",i),oe(e,o.label,d,r+1),a=o.end;continue}}if(f==="<"){let o=se(t,">",a+1,a+ut,`
18
- <`),i=o===-1?null:t.slice(a+1,o);if(i!==null&&Vt.test(i)){let d=F(i.includes(":")?i:`mailto:${i}`,e.base,"link");if(d!==null){l();let p=P(e,"a",n);p.setAttribute("href",d),p.textContent=i,a=o+1;continue}}}if(f==="&"){let o=Xt(t,a);if(o){s+=o.char,a=o.end;continue}}if(f==="*"||f==="_"||f==="~"){let o=V(t,a,f),i=o-a,d=!Me(t[o])&&(f!=="_"||!ft(t[a-1])),p=f==="~"?i>=2?[["~~",["del"]]]:[]:[...i>=3?[[f.repeat(3),["em","strong"]]]:[],...i>=2?[[f.repeat(2),["strong"]]]:[],[f,["em"]]],k=!1;if(d)for(let[T,x]of p){if(c.has(T))continue;let M=a+T.length,S=Wt(t,M,T);if(S===-1){c.add(T);continue}if(S===M)continue;l();let C=n;for(let O of x)C=P(e,O,C);oe(e,t.slice(M,S),C,r+1),a=S+T.length,k=!0;break}k||(s+=t.slice(a,o),a=o);continue}s+=f,a++}l()}var Zt="http://www.w3.org/1999/xhtml",Yt=new Set(["script","style","iframe","frame","frameset","object","embed","applet","base","link","meta","template","noscript"]),ie={href:{on:["a","area"],holds:"link"},src:{on:["img","video","audio","source"],holds:"media"},alt:{on:["img","area"],holds:"text"},title:{on:null,holds:"text"},"aria-label":{on:null,holds:"text"},placeholder:{on:["input","textarea"],holds:"text"},datetime:{on:["time","del","ins"],holds:"text"}},ae=e=>e.namespaceURI===Zt,Z=e=>!Yt.has(e.localName.toLowerCase());function Oe(e,t){if(!Z(e))return"refused-element";let n=Ae(t);return n===null?"type":(e.textContent=n,null)}function ht(e,t,n){return!Z(e)||!ae(e)?"refused-element":typeof t!="string"?"type":(e.replaceChildren(ct(t,e.ownerDocument,n.base)),null)}function yt(e,t,n){return typeof e!="string"?null:ot(e)?rt(e,{...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{width:n}:{}}):F(e,t.base,"media")}function bt(e,t,n,r){if(!ae(e)||e.localName!=="img")return"refused-element";if(typeof t!="string")return"type";let s=yt(t,n,r);return s===null?"unsafe-url":(e.removeAttribute("srcset"),e.setAttribute("src",s),null)}function wt(e,t,n,r,s){let l=t.toLowerCase(),c=Object.prototype.hasOwnProperty.call(ie,l)?ie[l]:void 0;if(!c)return"unsupported";if(!Z(e)||!ae(e))return"refused-element";if(c.on!==null&&!c.on.includes(e.localName))return"unsupported";if(c.holds==="text"){let f=Ae(n);return f===null?"type":(e.setAttribute(l,f),null)}if(typeof n!="string")return"type";let a=c.holds==="media"?yt(n,r,e.localName==="img"?s:void 0):F(n,r.base,"link");return a===null?"unsafe-url":(e.setAttribute(l,a),null)}function kt(e,t){return!ae(e)||e.localName!=="a"&&e.localName!=="area"?"unsupported":(e.setAttribute("href",t),null)}function K(e,t){t?e.removeAttribute("hidden"):e.setAttribute("hidden","")}var St=["text","markdown","date","datetime","number"],Jt=/^\d{4}-\d{2}-\d{2}$/,Qt=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;function At(e,t,n){let r=n&&/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(n)?n:void 0;try{if(t==="number"){let c=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return Number.isFinite(c)?new Intl.NumberFormat(r).format(c):null}if(typeof e!="string"||!Qt.test(e))return null;let s=new Date(e);if(Number.isNaN(s.getTime()))return null;let l=Jt.test(e);return new Intl.DateTimeFormat(r,{dateStyle:"long",...t==="datetime"&&!l?{timeStyle:"short"}:{},...l?{timeZone:"UTC"}:{}}).format(s)}catch{return null}}var w="data-mapled-",en=new Set(["bind","format","width","show","hide","link","list","each","record","slug","slug-param","sort","limit","filter","expand","empty","form","form-state","form-sent","form-failed","consent","end-preview","state","preview","key","api","live"]),Ce=/^[a-z0-9][a-z0-9_-]{0,63}$/,tn=/^mk_[A-Za-z0-9_]{8,128}$/,nn=4,rn=100,sn=2;function J(e,t=0){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let{data:n,expanded:r}=e;if(n===null||typeof n!="object"||Array.isArray(n))return!1;if(r===void 0)return!0;if(r===null||typeof r!="object"||Array.isArray(r))return!1;let s=Object.values(r);return t>=sn?s.length===0:s.every(l=>l===null||(Array.isArray(l)?l.every(c=>J(c,t+1)):J(l,t+1)))}var on=e=>Array.isArray(e)&&e.every(t=>J(t));function N(e){let t=e.getAttribute("id");return`${e.localName}${t&&/^[\w-]{1,40}$/.test(t)?`#${t}`:""}`}var ue=e=>(e??"").split(",").map(t=>t.trim()).filter(t=>/^[a-z0-9][a-z0-9_.-]{0,127}$/.test(t)),Rt=e=>Array.from(e.children).find(t=>t.localName==="template")??null;function $e(e,t){let n=null,r=()=>n??(n={format:"text",attrs:[],expand:[]});for(let a of Array.from(e.attributes)){if(!a.name.startsWith(w))continue;let f=a.name.slice(w.length);if(f==="bind")r().bind=a.value;else if(f.startsWith("bind-")){let o=f.slice(5);Object.prototype.hasOwnProperty.call(ie,o)?r().attrs.push([o,a.value]):t.push({path:a.value.slice(0,80),reason:"unsupported",on:`${N(e)}[${a.name.slice(0,60)}]`})}else f==="show"?r().show=a.value:f==="hide"?r().hide=a.value:f==="link"?r().link=a.value:en.has(f)||t.push({path:a.value.slice(0,80),reason:"unsupported",on:`${N(e)}[${a.name.slice(0,60)}]`})}if(!n)return null;let s=n,l=e.getAttribute(`${w}format`);l!==null&&(St.includes(l)?s.format=l:t.push({path:l.slice(0,80),reason:"bad-path",on:`${N(e)}[${w}format]`}));let c=parseInt(e.getAttribute(`${w}width`)??"",10);return c>=16&&c<=4096&&(s.width=c),s.expand=ue(e.getAttribute(`${w}expand`)),s}function an(e,t){let n={},r=e.getAttribute(`${w}sort`);r!==null&&(/^-?[a-z0-9][a-z0-9_-]{0,63}$/.test(r.trim())?n.sort=r.trim():t.push({path:r.slice(0,80),reason:"bad-path",on:`${N(e)}[${w}sort]`}));let s=parseInt(e.getAttribute(`${w}limit`)??"",10);s>=1&&s<=100&&(n.limit=s);let l=e.getAttribute(`${w}filter`);if(l!==null)for(let a of l.split(";")){if(a.trim()==="")continue;let f=a.indexOf("="),o=f===-1?"":a.slice(0,f).trim(),i=f===-1?"":a.slice(f+1).trim();Ce.test(o)&&i!==""&&i.length<=200?(n.filter??(n.filter={}))[o]=i:t.push({path:a.trim().slice(0,80),reason:"bad-path",on:`${N(e)}[${w}filter]`})}let c=ue(e.getAttribute(`${w}expand`));return c.length>0&&(n.expand=c),n}function le(e,t){let n={bound:[],eaches:[],lists:[],records:[],issues:[]},r=s=>{if(s.hasAttributes()){let l=s.getAttribute(`${w}list`),c=s.getAttribute(`${w}record`),a=s.getAttribute(`${w}each`);if(l!==null||c!==null){let o=(l??c??"").trim();if(!t)n.issues.push({path:o.slice(0,80),reason:"unsupported",on:N(s)});else if(!Ce.test(o))n.issues.push({path:o.slice(0,80),reason:"bad-path",on:N(s)});else if(l!==null)n.lists.push({el:s,collection:o,options:an(s,n.issues)});else{let i=s.getAttribute(`${w}slug-param`),d=s.getAttribute(`${w}slug`)??(i===null?null:new URLSearchParams(s.ownerDocument.location?.search??"").get(i)),p=le(s,!0);for(let T of p.records)n.issues.push({path:T.collection,reason:"unsupported",on:N(T.el)});n.lists.push(...p.lists),n.issues.push(...p.issues);let k=$e(s,n.issues);k&&p.bound.unshift({el:s,d:k}),n.records.push({el:s,collection:o,slug:d!==null&&d.trim()!==""&&d.length<=200?d.trim():null,expand:ue(s.getAttribute(`${w}expand`)),block:{...p,lists:[],records:[],issues:[]}})}return}if(a!==null){n.eaches.push({el:s,path:a});return}let f=$e(s,n.issues);f&&n.bound.push({el:s,d:f})}for(let l of Array.from(s.children))r(l)};for(let s of Array.from(e.children))r(s);return n}function vt(e){let t=new Map,n=(r,s=[])=>{let l=H(r)?.[0];if(!l)return;let c=t.get(l)??new Set;for(let a of s)c.add(a);t.set(l,c)};for(let{d:r}of e.bound){n(r.bind,r.expand);for(let[,s]of r.attrs)n(s,r.expand);n(r.show,r.expand),n(r.hide,r.expand);for(let s of(r.link??"").matchAll(/\{([^{}]*)\}/g))n(s[1],r.expand)}for(let r of e.eaches)n(r.path,ue(r.el.getAttribute(`${w}expand`)));return t}function Y(e,t){let n=H(t);if(!n)return{status:"bad-path"};if(e.kind==="record")return{status:"value",value:Se(e.source,n)};if(n.length<2)return{status:"bad-path"};let r=e.singles.get(n[0]);return!r||r.status!=="ok"?{status:r?.status==="failed"?"failed":"missing"}:{status:"value",value:Se(r.value,n.slice(1))}}function Le(e){if(typeof e?.key!="string"||!tn.test(e.key))throw new Error("Mapled: data-mapled-key takes the delivery key (mk_\u2026) \u2014 the one key that is safe in a page. A server key or a secret never goes into HTML.");if(typeof document>"u")throw new Error("Mapled: @mapled/vanilla fills a page \u2014 it runs in a browser. On a server read with @mapled/client.");let t=e.root??document.documentElement,n=t.ownerDocument,r=st({key:e.key,apiUrl:e.apiUrl,appUrl:e.appUrl,fetch:e.fetch}),s={apiUrl:e.apiUrl,base:n.baseURI},l=new Map,c=u=>{let m=l.get(u);return m||l.set(u,m={attrs:new Map}),m},a=u=>{let m=c(u);m.nodes??(m.nodes=Array.from(u.childNodes))},f=(u,m)=>{let A=c(u);A.attrs.has(m)||A.attrs.set(m,u.getAttribute(m))},o=()=>{for(let[u,m]of l){m.nodes&&u.replaceChildren(...m.nodes);for(let[A,g]of m.attrs)g===null?u.removeAttribute(A):u.setAttribute(A,g)}l.clear()},i=[],d=0,p=(u,m,A)=>i.push({path:(m??"").trim().slice(0,120),reason:A,on:N(u)});function k(u,m,A){if(m.bind!==void 0){let g=Y(A,m.bind);if(g.status!=="value")p(u,m.bind,g.status);else if(!Z(u))p(u,m.bind,"refused-element");else{let y=u.localName==="img";if(y?(f(u,"src"),f(u,"srcset"),f(u,"hidden")):a(u),W(g.value))y?K(u,!1):u.textContent="",p(u,m.bind,"empty");else{let b;if(y)b=bt(u,g.value,s,m.width);else if(m.format==="markdown")b=ht(u,g.value,s);else if(m.format==="text")b=Oe(u,g.value);else{let R=At(g.value,m.format,u.closest("[lang]")?.getAttribute("lang")??void 0);b=R===null?"type":Oe(u,R)}b?p(u,m.bind,b):d++}}}for(let[g,y]of m.attrs){let b=Y(A,y);if(b.status!=="value"){p(u,y,b.status);continue}if(f(u,g),W(b.value)){g==="alt"?u.setAttribute("alt",""):u.removeAttribute(g),p(u,y,"empty");continue}let R=u.getAttribute(g),v=wt(u,g,b.value,s,m.width);v?(R===null&&u.removeAttribute(g),p(u,y,v)):d++}for(let[g,y]of[[m.show,!0],[m.hide,!1]]){if(g===void 0)continue;let b=Y(A,g);if(b.status!=="value"){p(u,g,b.status);continue}f(u,"hidden");let R=!W(b.value)&&b.value!==!1;K(u,R===y),d++}if(m.link!==void 0){let g=[],y=it(m.link,s.base,b=>{let R=Y(A,b.join("."));if(R.status==="value")return R.value;g.push(R.status)});if(g[0])p(u,m.link,g[0]);else if(!y.ok)p(u,y.path,y.reason);else{f(u,"href");let b=kt(u,y.url);b?p(u,m.link,b):d++}}}function T(u,m,A){let g=Rt(u);if(!g){p(u,"template","unsupported");return}a(u);let y=[g];for(let R of Array.from(u.children))R.hasAttribute(`${w}empty`)&&(f(R,"hidden"),K(R,m.length===0),y.push(R));let b=[];for(let R of m.slice(0,rn)){let v=g.content.cloneNode(!0);x(le(v,!1),{kind:"record",source:R},A+1),b.push(...Array.from(v.childNodes))}u.replaceChildren(...y,...b),d++}function x(u,m,A){i.push(...u.issues);for(let{el:g,d:y}of u.bound)k(g,y,m);for(let g of u.eaches){let y=Y(m,g.path);if(y.status!=="value"){p(g.el,g.path,y.status);continue}if(A>=nn){p(g.el,g.path,"unsupported");continue}let b=y.value,R=Array.isArray(b)?b:W(b)?[]:[b];if(R.some(v=>v===null||typeof v!="object"||Array.isArray(v))){p(g.el,g.path,"type");continue}R.length===0&&p(g.el,g.path,"empty"),T(g.el,R.map(v=>({data:v})),A)}}async function M(u,m){try{let A=await u();return A===null?{status:"missing"}:m(A)?{status:"ok",value:A}:{status:"failed",answered:!0}}catch(A){return A instanceof j&&A.status===404&&A.code!=="RELEASE_NOT_FOUND"?{status:"missing"}:{status:"failed"}}}let S=null,C="",O=null,q,Ue=!1,Q=0,Ne=-1,xt=3,Pt=typeof e.live=="number"?e.live:void 0;function Ie(){o(),S={state:"fallback",release:null,preview:!1,bound:0,issues:[]},t.setAttribute(`${w}state`,"fallback"),t.removeAttribute(`${w}preview`)}function De(){Q++,clearTimeout(q),S?.preview&&Ie()}function Mt(){clearTimeout(q);let u=_();if(!u||Ue)return;let m=Date.parse(u.expiresAt)-Date.now();q=setTimeout(()=>{_()===null&&De(),de()},Math.min(Math.max(m,0)+1,2147483647))}async function Fe(u,m=1){let A=S===null;A&&t.setAttribute(`${w}state`,"loading");let g=Q,y=await r.isPreview().catch(()=>!1),b=y?_()?.draftToken??null:null;if(S!==null&&S.preview&&!y&&Ie(),!y&&u!==void 0&&S!==null&&S.state==="ready"&&!S.preview&&S.release!==null&&u<=S.release)return S;let R=h=>{S=h,Ne=g,t.setAttribute(`${w}state`,h.state),t.toggleAttribute(`${w}preview`,h.preview);let E=h.issues.filter(U=>U.reason!=="empty"),$=E.map(U=>`${U.path} (${U.reason}) on ${U.on}`).join("; ");return $!==C&&(C=$,E.length>0&&console.warn(`[mapled] ${E.length===1?"1 place":`${E.length} places`} couldn't be filled: ${$}`)),n.dispatchEvent(new CustomEvent(A?"mapled:ready":"mapled:update",{detail:h})),h.preview?Mt():(clearTimeout(q),e.live&&O===null&&(O=r.watch(U=>{de(U.release)},{interval:Pt}))),h},v=null;if(!y)if(u!==void 0)v=u;else try{let h=await r.getRelease();if(h===null)return o(),R({state:"unpublished",release:null,preview:y,bound:0,issues:[]});v=h.release}catch{return S!==null&&S.state==="ready"?S:R({state:"fallback",release:null,preview:y,bound:0,issues:[]})}let L=v===null?{}:{release:v},I=le(t,!0),ze=$e(t,I.issues);ze&&I.bound.unshift({el:t,d:ze});let fe=new Map,pe=new Map,ee=new Map,te=[];for(let[h,E]of vt(I))te.push(M(()=>r.getSingle(h,{...L,...E.size>0?{expand:[...E]}:{}}),J).then($=>fe.set(h,$)));for(let h of I.lists){let E=Rt(h.el),$=E?[...vt(le(E.content,!1)).keys()]:[];te.push(M(async()=>(await r.getRecords(h.collection,{...h.options,...L,...$.length>0?{fields:$}:{}})).records,on).then(U=>pe.set(h,U)))}for(let h of I.records){if(h.slug===null){ee.set(h,{status:"missing"});continue}let E=h.slug;te.push(M(()=>r.getRecordBySlug(h.collection,E,{...L,...h.expand.length>0?{expand:h.expand}:{}}),J).then($=>ee.set(h,$)))}await Promise.all(te);let He=await r.isPreview().catch(()=>!1)?_()?.draftToken??null:null;if(g!==Q||He!==b)return m<xt?Fe(u,m+1):(o(),R({state:"fallback",release:null,preview:He!==null,bound:0,issues:[]}));let We=[...fe.values(),...pe.values(),...ee.values()];if(We.length>0&&We.every(h=>h.status==="failed"&&!h.answered))return S!==null&&S.state==="ready"?S:R({state:"fallback",release:v,preview:y,bound:0,issues:[]});o(),i=[],d=0,x(I,{kind:"page",singles:fe},0);for(let h of I.lists){let E=pe.get(h);E?.status==="ok"?T(h.el,E.value,0):p(h.el,h.collection,E?.status??"failed")}for(let h of I.records){let E=ee.get(h);E?.status==="ok"?x(h.block,{kind:"record",source:E.value},0):p(h.el,h.collection,E?.status??"failed")}return Ke(),R({state:"ready",release:v,preview:y,bound:d,issues:i})}let _e=new WeakSet,je=new WeakSet;function Ke(){for(let u of Array.from(t.querySelectorAll(`form[${w}form]`)))_e.has(u)||(_e.add(u),u.addEventListener("submit",m=>{m.preventDefault(),Ot(u)}))}async function Ot(u){if(u.getAttribute(`${w}form-state`)==="sending")return;let m=(u.getAttribute(`${w}form`)??"").trim(),A=u.querySelector(`[${w}form-sent]`),g=u.querySelector(`[${w}form-failed]`),y=Array.from(u.querySelectorAll("button, input[type=submit]")).filter(L=>!L.disabled);u.setAttribute(`${w}form-state`,"sending");for(let L of y)L.disabled=!0;let b=u.querySelector(`input[type=checkbox][${w}consent]`),R=b?.checked?(b.labels?.[0]?.textContent??b.closest("label")?.textContent??"").trim().slice(0,500):"",v=Ce.test(m)?await we(m,u,{key:e.key,apiUrl:e.apiUrl,fetch:e.fetch,...R?{consent:R}:{}}):{ok:!1,status:0,code:"BAD_FORM",message:"This form isn't set up yet."};for(let L of y)L.disabled=!1;u.setAttribute(`${w}form-state`,v.ok?"sent":"failed"),v.ok&&u.reset(),A&&K(A,v.ok),g&&(!v.ok&&(je.has(g)||(g.textContent??"").trim()==="")&&(je.add(g),g.textContent=v.message),K(g,!v.ok)),n.dispatchEvent(new CustomEvent("mapled:form",{detail:v.ok?{form:m,ok:!0}:{form:m,ok:!1,status:v.status,code:v.code}}))}Ke();let ce=async u=>{try{return await Fe(u)}catch(m){return console.error(`[mapled] ${m instanceof Error?m.message:"The page couldn't be filled."}`),S??{state:"fallback",release:null,preview:!1,bound:0,issues:[]}}},z=ce(),de=u=>z=z.then(()=>ce(u)),Be=()=>{ye(),De();let u=Q;return z=z.then(()=>Ne>=u&&S!==null?S:ce())},qe=u=>{u.target?.closest?.(`[${w}end-preview]`)&&(u.preventDefault(),Be())};return n.addEventListener("click",qe),{ready:z,get report(){return S},refresh:()=>de(),endPreview:Be,stop:()=>{Ue=!0,O?.(),O=()=>{},clearTimeout(q),n.removeEventListener("click",qe)},client:r}}var Tt="0.1.1";var Et={version:Tt,mount:Le,page:null};window.Mapled=Et;var B=document.currentScript;if(B instanceof HTMLScriptElement&&B.hasAttribute("data-mapled-key")){let e=B.getAttribute("data-mapled-live"),t=e===null?NaN:parseInt(e,10),n=()=>{try{Et.page=Le({key:B.getAttribute("data-mapled-key")??"",...B.getAttribute("data-mapled-api")?{apiUrl:B.getAttribute("data-mapled-api")}:{},...e===null?{}:{live:Number.isFinite(t)?t:!0}})}catch(r){console.error(r instanceof Error?r.message:"Mapled couldn't start.")}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",n,{once:!0}):n()}})();
13
+ `);)r++;let o=e[r];if(o==='"'||o==="'"||o==="("){let c=le(e,o==="("?")":o,r+1,n);if(c===-1)return null;for(r=c+1;r<n&&(e[r]===" "||e[r]===`
14
+ `);)r++}return e[r]!==")"?null:{address:bt(s),end:r+1}}function Oe(e,t,n=!1){let r=t+1;for(;r<e.length;){let o=ht(e,r);if(o!==-1){r=o;continue}if(!n&&e[r]==="!"&&e[r+1]==="["){let c=Oe(e,r+1,!0);if(!c)return null;r=c.end;continue}if(e[r]==="[")return null;if(e[r]==="]")break;r++}if(r>=e.length)return null;let s=Yt(e,r+1);return s?{label:e.slice(t+1,r),address:s.address,end:s.end}:null}var Jt=/^(?:[a-z][a-z0-9+.-]{1,31}:[^\s<>]*|[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+)$/i;function ue(e,t,n,r){if(r>=dt){n.appendChild(e.doc.createTextNode(t));return}let s="",o=()=>{s!==""&&n.appendChild(e.doc.createTextNode(s)),s=""},c=new Set,a=0;for(;a<t.length;){let f=t[a];if(f==="\\"){let i=t[a+1];if(i===`
15
+ `)for(o(),M(e,"br",n),a+=2;t[a]===" ";)a++;else i!==void 0&&Wt.includes(i)?(s+=i,a+=2):(s+=f,a++);continue}if(f===`
16
+ `){let i=s.endsWith(" "),p=s.length;for(;p>0&&s[p-1]===" ";)p--;for(s=s.slice(0,p),i?(o(),M(e,"br",n)):s+=`
17
+ `,a++;t[a]===" ";)a++;continue}if(f==="`"){let i=ee(t,a,"`"),p=yt(t,i,i-a);if(p===-1){s+=t.slice(a,i),a=i;continue}let d=t.slice(i,p).replace(/\n/g," ");d.length>1&&d.startsWith(" ")&&d.endsWith(" ")&&d.trim()!==""&&(d=d.slice(1,-1)),o(),M(e,"code",n).textContent=d,a=p+(i-a);continue}if(f==="!"&&t[a+1]==="["){let i=Oe(t,a+1);if(i){let p=bt(i.label),d=H(i.address.trim(),e.base,"media");if(d===null)s+=p;else{o();let l=M(e,"img",n);l.setAttribute("src",d),l.setAttribute("alt",p),l.setAttribute("loading","lazy")}a=i.end;continue}}if(f==="["){let i=Oe(t,a);if(i){let p=H(i.address.trim(),e.base,"link");o();let d=p===null?n:M(e,"a",n);p!==null&&d.setAttribute("href",p),ue(e,i.label,d,r+1),a=i.end;continue}}if(f==="<"){let i=le(t,">",a+1,a+ft,`
18
+ <`),p=i===-1?null:t.slice(a+1,i);if(p!==null&&Jt.test(p)){let d=H(p.includes(":")?p:`mailto:${p}`,e.base,"link");if(d!==null){o();let l=M(e,"a",n);l.setAttribute("href",d),l.textContent=p,a=i+1;continue}}}if(f==="&"){let i=Zt(t,a);if(i){s+=i.char,a=i.end;continue}}if(f==="*"||f==="_"||f==="~"){let i=ee(t,a,f),p=i-a,d=!Le(t[i])&&(f!=="_"||!gt(t[a-1])),l=f==="~"?p>=2?[["~~",["del"]]]:[]:[...p>=3?[[f.repeat(3),["em","strong"]]]:[],...p>=2?[[f.repeat(2),["strong"]]]:[],[f,["em"]]],g=!1;if(d)for(let[S,x]of l){if(c.has(S))continue;let P=a+S.length,b=Vt(t,P,S);if(b===-1){c.add(S);continue}if(b===P)continue;o();let C=n;for(let L of x)C=M(e,L,C);ue(e,t.slice(P,b),C,r+1),a=b+S.length,g=!0;break}g||(s+=t.slice(a,i),a=i);continue}s+=f,a++}o()}var Qt="http://www.w3.org/1999/xhtml",en=new Set(["script","style","iframe","frame","frameset","object","embed","applet","base","link","meta","template","noscript"]),ce={href:{on:["a","area"],holds:"link"},src:{on:["img","video","audio","source"],holds:"media"},alt:{on:["img","area"],holds:"text"},title:{on:null,holds:"text"},"aria-label":{on:null,holds:"text"},placeholder:{on:["input","textarea"],holds:"text"},datetime:{on:["time","del","ins"],holds:"text"}},de=e=>e.namespaceURI===Qt,te=e=>!en.has(e.localName.toLowerCase());function Ne(e,t){if(!te(e))return"refused-element";let n=Ee(t);return n===null?"type":(e.textContent=n,null)}function wt(e,t,n){return!te(e)||!de(e)?"refused-element":typeof t!="string"?"type":(e.replaceChildren(pt(t,e.ownerDocument,n.base)),null)}function kt(e,t,n){return typeof e!="string"?null:lt(e)?it(e,{...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{width:n}:{}}):H(e,t.base,"media")}function St(e,t,n,r){if(!de(e)||e.localName!=="img")return"refused-element";if(typeof t!="string")return"type";let s=kt(t,n,r);return s===null?"unsafe-url":(e.removeAttribute("srcset"),e.setAttribute("src",s),null)}function At(e,t,n,r,s){let o=t.toLowerCase(),c=Object.prototype.hasOwnProperty.call(ce,o)?ce[o]:void 0;if(!c)return"unsupported";if(!te(e)||!de(e))return"refused-element";if(c.on!==null&&!c.on.includes(e.localName))return"unsupported";if(c.holds==="text"){let f=Ee(n);return f===null?"type":(e.setAttribute(o,f),null)}if(typeof n!="string")return"type";let a=c.holds==="media"?kt(n,r,e.localName==="img"?s:void 0):H(n,r.base,"link");return a===null?"unsafe-url":(e.setAttribute(o,a),null)}function vt(e,t){return!de(e)||e.localName!=="a"&&e.localName!=="area"?"unsupported":(e.setAttribute("href",t),null)}function X(e,t){t?e.removeAttribute("hidden"):e.setAttribute("hidden","")}var Rt=["text","markdown","date","datetime","number"],tn=/^\d{4}-\d{2}-\d{2}$/,nn=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;function Tt(e,t,n){let r=n&&/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(n)?n:void 0;try{if(t==="number"){let c=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return Number.isFinite(c)?new Intl.NumberFormat(r).format(c):null}if(typeof e!="string"||!nn.test(e))return null;let s=new Date(e);if(Number.isNaN(s.getTime()))return null;let o=tn.test(e);return new Intl.DateTimeFormat(r,{dateStyle:"long",...t==="datetime"&&!o?{timeStyle:"short"}:{},...o?{timeZone:"UTC"}:{}}).format(s)}catch{return null}}var A="data-mapled-",rn=new Set(["bind","format","width","show","hide","link","list","each","record","slug","slug-param","sort","limit","filter","expand","empty","form","form-state","form-sent","form-failed","consent","end-preview","state","preview","key","api","live","locale"]),Ie=/^[a-z0-9][a-z0-9_-]{0,63}$/,sn=/^mk_[A-Za-z0-9_]{8,128}$/,on=4,an=100,ln=2;function re(e,t=0){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let{data:n,expanded:r}=e;if(n===null||typeof n!="object"||Array.isArray(n))return!1;if(r===void 0)return!0;if(r===null||typeof r!="object"||Array.isArray(r))return!1;let s=Object.values(r);return t>=ln?s.length===0:s.every(o=>o===null||(Array.isArray(o)?o.every(c=>re(c,t+1)):re(o,t+1)))}var un=e=>Array.isArray(e)&&e.every(t=>re(t));function _(e){let t=e.getAttribute("id");return`${e.localName}${t&&/^[\w-]{1,40}$/.test(t)?`#${t}`:""}`}var pe=e=>(e??"").split(",").map(t=>t.trim()).filter(t=>/^[a-z0-9][a-z0-9_.-]{0,127}$/.test(t)),Et=e=>Array.from(e.children).find(t=>t.localName==="template")??null;function Ue(e,t){let n=null,r=()=>n??(n={format:"text",attrs:[],expand:[]});for(let a of Array.from(e.attributes)){if(!a.name.startsWith(A))continue;let f=a.name.slice(A.length);if(f==="bind")r().bind=a.value;else if(f.startsWith("bind-")){let i=f.slice(5);Object.prototype.hasOwnProperty.call(ce,i)?r().attrs.push([i,a.value]):t.push({path:a.value.slice(0,80),reason:"unsupported",on:`${_(e)}[${a.name.slice(0,60)}]`})}else f==="show"?r().show=a.value:f==="hide"?r().hide=a.value:f==="link"?r().link=a.value:rn.has(f)||t.push({path:a.value.slice(0,80),reason:"unsupported",on:`${_(e)}[${a.name.slice(0,60)}]`})}if(!n)return null;let s=n,o=e.getAttribute(`${A}format`);o!==null&&(Rt.includes(o)?s.format=o:t.push({path:o.slice(0,80),reason:"bad-path",on:`${_(e)}[${A}format]`}));let c=parseInt(e.getAttribute(`${A}width`)??"",10);return c>=16&&c<=4096&&(s.width=c),s.expand=pe(e.getAttribute(`${A}expand`)),s}function cn(e,t){let n={},r=e.getAttribute(`${A}sort`);r!==null&&(/^-?[a-z0-9][a-z0-9_-]{0,63}$/.test(r.trim())?n.sort=r.trim():t.push({path:r.slice(0,80),reason:"bad-path",on:`${_(e)}[${A}sort]`}));let s=parseInt(e.getAttribute(`${A}limit`)??"",10);s>=1&&s<=100&&(n.limit=s);let o=e.getAttribute(`${A}filter`);if(o!==null)for(let a of o.split(";")){if(a.trim()==="")continue;let f=a.indexOf("="),i=f===-1?"":a.slice(0,f).trim(),p=f===-1?"":a.slice(f+1).trim();Ie.test(i)&&p!==""&&p.length<=200?(n.filter??(n.filter={}))[i]=p:t.push({path:a.trim().slice(0,80),reason:"bad-path",on:`${_(e)}[${A}filter]`})}let c=pe(e.getAttribute(`${A}expand`));return c.length>0&&(n.expand=c),n}function fe(e,t){let n={bound:[],eaches:[],lists:[],records:[],issues:[]},r=s=>{if(s.hasAttributes()){let o=s.getAttribute(`${A}list`),c=s.getAttribute(`${A}record`),a=s.getAttribute(`${A}each`);if(o!==null||c!==null){let i=(o??c??"").trim();if(!t)n.issues.push({path:i.slice(0,80),reason:"unsupported",on:_(s)});else if(!Ie.test(i))n.issues.push({path:i.slice(0,80),reason:"bad-path",on:_(s)});else if(o!==null)n.lists.push({el:s,collection:i,options:cn(s,n.issues)});else{let p=s.getAttribute(`${A}slug-param`),d=s.getAttribute(`${A}slug`)??(p===null?null:new URLSearchParams(s.ownerDocument.location?.search??"").get(p)),l=fe(s,!0);for(let S of l.records)n.issues.push({path:S.collection,reason:"unsupported",on:_(S.el)});n.lists.push(...l.lists),n.issues.push(...l.issues);let g=Ue(s,n.issues);g&&l.bound.unshift({el:s,d:g}),n.records.push({el:s,collection:i,slug:d!==null&&d.trim()!==""&&d.length<=200?d.trim():null,expand:pe(s.getAttribute(`${A}expand`)),block:{...l,lists:[],records:[],issues:[]}})}return}if(a!==null){n.eaches.push({el:s,path:a});return}let f=Ue(s,n.issues);f&&n.bound.push({el:s,d:f})}for(let o of Array.from(s.children))r(o)};for(let s of Array.from(e.children))r(s);return n}function xt(e){let t=new Map,n=(r,s=[])=>{let o=Z(r)?.[0];if(!o)return;let c=t.get(o)??new Set;for(let a of s)c.add(a);t.set(o,c)};for(let{d:r}of e.bound){n(r.bind,r.expand);for(let[,s]of r.attrs)n(s,r.expand);n(r.show,r.expand),n(r.hide,r.expand);for(let s of(r.link??"").matchAll(/\{([^{}]*)\}/g))n(s[1],r.expand)}for(let r of e.eaches)n(r.path,pe(r.el.getAttribute(`${A}expand`)));return t}function ne(e,t){let n=Z(t);if(!n)return{status:"bad-path"};if(e.kind==="record")return{status:"value",value:Te(e.source,n)};if(n.length<2)return{status:"bad-path"};let r=e.singles.get(n[0]);return!r||r.status!=="ok"?{status:r?.status==="failed"?"failed":"missing"}:{status:"value",value:Te(r.value,n.slice(1))}}function De(e){if(typeof e?.key!="string"||!sn.test(e.key))throw new Error("Mapled: data-mapled-key takes the delivery key (mk_\u2026) \u2014 the one key that is safe in a page. A server key or a secret never goes into HTML.");if(typeof document>"u")throw new Error("Mapled: @mapled/vanilla fills a page \u2014 it runs in a browser. On a server read with @mapled/client.");let t=e.root??document.documentElement,n=t.ownerDocument,r=at({key:e.key,apiUrl:e.apiUrl,appUrl:e.appUrl,fetch:e.fetch,...e.locale?{locale:e.locale}:{}}),s={apiUrl:e.apiUrl,base:n.baseURI},o=new Map,c=u=>{let m=o.get(u);return m||o.set(u,m={attrs:new Map}),m},a=u=>{let m=c(u);m.nodes??(m.nodes=Array.from(u.childNodes))},f=(u,m)=>{let v=c(u);v.attrs.has(m)||v.attrs.set(m,u.getAttribute(m))},i=()=>{for(let[u,m]of o){m.nodes&&u.replaceChildren(...m.nodes);for(let[v,h]of m.attrs)h===null?u.removeAttribute(v):u.setAttribute(v,h)}o.clear()},p=[],d=0,l=(u,m,v)=>p.push({path:(m??"").trim().slice(0,120),reason:v,on:_(u)});function g(u,m,v){if(m.bind!==void 0){let h=ne(v,m.bind);if(h.status!=="value")l(u,m.bind,h.status);else if(!te(u))l(u,m.bind,"refused-element");else{let w=u.localName==="img";if(w?(f(u,"src"),f(u,"srcset"),f(u,"hidden")):a(u),Y(h.value))w?X(u,!1):u.textContent="",l(u,m.bind,"empty");else{let k;if(w)k=St(u,h.value,s,m.width);else if(m.format==="markdown")k=wt(u,h.value,s);else if(m.format==="text")k=Ne(u,h.value);else{let R=Tt(h.value,m.format,u.closest("[lang]")?.getAttribute("lang")??void 0);k=R===null?"type":Ne(u,R)}k?l(u,m.bind,k):d++}}}for(let[h,w]of m.attrs){let k=ne(v,w);if(k.status!=="value"){l(u,w,k.status);continue}if(f(u,h),Y(k.value)){h==="alt"?u.setAttribute("alt",""):u.removeAttribute(h),l(u,w,"empty");continue}let R=u.getAttribute(h),T=At(u,h,k.value,s,m.width);T?(R===null&&u.removeAttribute(h),l(u,w,T)):d++}for(let[h,w]of[[m.show,!0],[m.hide,!1]]){if(h===void 0)continue;let k=ne(v,h);if(k.status!=="value"){l(u,h,k.status);continue}f(u,"hidden");let R=!Y(k.value)&&k.value!==!1;X(u,R===w),d++}if(m.link!==void 0){let h=[],w=ut(m.link,s.base,k=>{let R=ne(v,k.join("."));if(R.status==="value")return R.value;h.push(R.status)});if(h[0])l(u,m.link,h[0]);else if(!w.ok)l(u,w.path,w.reason);else{f(u,"href");let k=vt(u,w.url);k?l(u,m.link,k):d++}}}function S(u,m,v){let h=Et(u);if(!h){l(u,"template","unsupported");return}a(u);let w=[h];for(let R of Array.from(u.children))R.hasAttribute(`${A}empty`)&&(f(R,"hidden"),X(R,m.length===0),w.push(R));let k=[];for(let R of m.slice(0,an)){let T=h.content.cloneNode(!0);x(fe(T,!1),{kind:"record",source:R},v+1),k.push(...Array.from(T.childNodes))}u.replaceChildren(...w,...k),d++}function x(u,m,v){p.push(...u.issues);for(let{el:h,d:w}of u.bound)g(h,w,m);for(let h of u.eaches){let w=ne(m,h.path);if(w.status!=="value"){l(h.el,h.path,w.status);continue}if(v>=on){l(h.el,h.path,"unsupported");continue}let k=w.value,R=Array.isArray(k)?k:Y(k)?[]:[k];if(R.some(T=>T===null||typeof T!="object"||Array.isArray(T))){l(h.el,h.path,"type");continue}R.length===0&&l(h.el,h.path,"empty"),S(h.el,R.map(T=>({data:T})),v)}}async function P(u,m){try{let v=await u();return v===null?{status:"missing"}:m(v)?{status:"ok",value:v}:{status:"failed",answered:!0}}catch(v){return v instanceof W&&v.status===404&&v.code!=="RELEASE_NOT_FOUND"?{status:"missing"}:{status:"failed"}}}let b=null,C="",L=null,$,z=!1,N=0,U=-1,G=3,O=typeof e.live=="number"?e.live:void 0;function Fe(){i(),b={state:"fallback",release:null,preview:!1,bound:0,issues:[]},t.setAttribute(`${A}state`,"fallback"),t.removeAttribute(`${A}preview`)}function _e(){N++,clearTimeout($),b?.preview&&Fe()}function Ot(){clearTimeout($);let u=B();if(!u||z)return;let m=Date.parse(u.expiresAt)-Date.now();$=setTimeout(()=>{B()===null&&_e(),ge()},Math.min(Math.max(m,0)+1,2147483647))}async function je(u,m=1){let v=b===null;v&&t.setAttribute(`${A}state`,"loading");let h=N,w=await r.isPreview().catch(()=>!1),k=w?B()?.draftToken??null:null;if(b!==null&&b.preview&&!w&&Fe(),!w&&u!==void 0&&b!==null&&b.state==="ready"&&!b.preview&&b.release!==null&&u<=b.release)return b;let R=y=>{b=y,U=h,t.setAttribute(`${A}state`,y.state),t.toggleAttribute(`${A}preview`,y.preview);let E=y.issues.filter(F=>F.reason!=="empty"),I=E.map(F=>`${F.path} (${F.reason}) on ${F.on}`).join("; ");return I!==C&&(C=I,E.length>0&&console.warn(`[mapled] ${E.length===1?"1 place":`${E.length} places`} couldn't be filled: ${I}`)),n.dispatchEvent(new CustomEvent(v?"mapled:ready":"mapled:update",{detail:y})),y.preview?Ot():(clearTimeout($),e.live&&L===null&&(L=r.watch(F=>{ge(F.release)},{interval:O,from:y.state==="ready"?y.release:null}))),y},T=null;if(!w)if(u!==void 0)T=u;else try{let y=await r.getRelease();if(y===null)return i(),R({state:"unpublished",release:null,preview:w,bound:0,issues:[]});T=y.release}catch{return b!==null&&b.state==="ready"?b:R({state:"fallback",release:null,preview:w,bound:0,issues:[]})}let D=T===null?{}:{release:T},j=fe(t,!0),We=Ue(t,j.issues);We&&j.bound.unshift({el:t,d:We});let he=new Map,ye=new Map,se=new Map,oe=[];for(let[y,E]of xt(j))oe.push(P(()=>r.getSingle(y,{...D,...E.size>0?{expand:[...E]}:{}}),re).then(I=>he.set(y,I)));for(let y of j.lists){let E=Et(y.el),I=E?[...xt(fe(E.content,!1)).keys()]:[];oe.push(P(async()=>(await r.getRecords(y.collection,{...y.options,...D,...I.length>0?{fields:I}:{}})).records,un).then(F=>ye.set(y,F)))}for(let y of j.records){if(y.slug===null){se.set(y,{status:"missing"});continue}let E=y.slug;oe.push(P(()=>r.getRecordBySlug(y.collection,E,{...D,...y.expand.length>0?{expand:y.expand}:{}}),re).then(I=>se.set(y,I)))}await Promise.all(oe);let Xe=await r.isPreview().catch(()=>!1)?B()?.draftToken??null:null;if(h!==N||Xe!==k)return m<G?je(u,m+1):(i(),R({state:"fallback",release:null,preview:Xe!==null,bound:0,issues:[]}));let Ge=[...he.values(),...ye.values(),...se.values()];if(Ge.length>0&&Ge.every(y=>y.status==="failed"&&!y.answered))return b!==null&&b.state==="ready"?b:R({state:"fallback",release:T,preview:w,bound:0,issues:[]});i(),p=[],d=0,x(j,{kind:"page",singles:he},0);for(let y of j.lists){let E=ye.get(y);E?.status==="ok"?S(y.el,E.value,0):l(y.el,y.collection,E?.status??"failed")}for(let y of j.records){let E=se.get(y);E?.status==="ok"?x(y.block,{kind:"record",source:E.value},0):l(y.el,y.collection,E?.status??"failed")}return He(),R({state:"ready",release:T,preview:w,bound:d,issues:p})}let Ke=new WeakSet,Be=new WeakSet;function He(){for(let u of Array.from(t.querySelectorAll(`form[${A}form]`)))Ke.has(u)||(Ke.add(u),u.addEventListener("submit",m=>{m.preventDefault(),$t(u)}))}async function $t(u){if(u.getAttribute(`${A}form-state`)==="sending")return;let m=(u.getAttribute(`${A}form`)??"").trim(),v=u.querySelector(`[${A}form-sent]`),h=u.querySelector(`[${A}form-failed]`),w=Array.from(u.querySelectorAll("button, input[type=submit]")).filter(D=>!D.disabled);u.setAttribute(`${A}form-state`,"sending");for(let D of w)D.disabled=!0;let k=u.querySelector(`input[type=checkbox][${A}consent]`),R=k?.checked?(k.labels?.[0]?.textContent??k.closest("label")?.textContent??"").trim().slice(0,500):"",T=Ie.test(m)?await ve(m,u,{key:e.key,apiUrl:e.apiUrl,fetch:e.fetch,...R?{consent:R}:{}}):{ok:!1,status:0,code:"BAD_FORM",message:"This form isn't set up yet."};for(let D of w)D.disabled=!1;u.setAttribute(`${A}form-state`,T.ok?"sent":"failed"),T.ok&&u.reset(),v&&X(v,T.ok),h&&(!T.ok&&(Be.has(h)||(h.textContent??"").trim()==="")&&(Be.add(h),h.textContent=T.message),X(h,!T.ok)),n.dispatchEvent(new CustomEvent("mapled:form",{detail:T.ok?{form:m,ok:!0}:{form:m,ok:!1,status:T.status,code:T.code}}))}He();let me=async u=>{try{return await je(u)}catch(m){return console.error(`[mapled] ${m instanceof Error?m.message:"The page couldn't be filled."}`),b??{state:"fallback",release:null,preview:!1,bound:0,issues:[]}}},V=me(),ge=u=>V=V.then(()=>me(u)),qe=()=>{Se(),_e();let u=N;return V=V.then(()=>U>=u&&b!==null?b:me())},ze=u=>{u.target?.closest?.(`[${A}end-preview]`)&&(u.preventDefault(),qe())};return n.addEventListener("click",ze),{ready:V,get report(){return b},refresh:()=>ge(),endPreview:qe,stop:()=>{z=!0,L?.(),L=()=>{},clearTimeout($),n.removeEventListener("click",ze)},client:r}}var Pt="0.2.1";var Mt={version:Pt,mount:De,page:null};window.Mapled=Mt;var q=document.currentScript;if(q instanceof HTMLScriptElement&&q.hasAttribute("data-mapled-key")){let e=q.getAttribute("data-mapled-live"),t=e===null?NaN:parseInt(e,10),n=()=>{try{Mt.page=De({key:q.getAttribute("data-mapled-key")??"",...q.getAttribute("data-mapled-api")?{apiUrl:q.getAttribute("data-mapled-api")}:{},...q.getAttribute("data-mapled-locale")?{locale:q.getAttribute("data-mapled-locale")}:{},...e===null?{}:{live:Number.isFinite(t)?t:!0}})}catch(r){console.error(r instanceof Error?r.message:"Mapled couldn't start.")}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",n,{once:!0}):n()}})();
@@ -1 +1 @@
1
- sha384-2vgQ4g9re/eiYxEa/H3WKpWI5C9L4wCB/62c8Kq+LOfZDzmqc2ozqMGC8mZoOUqk
1
+ sha384-6apTHYxXrozzwFCqNU+70Z9pa/FDnhArNomcKQNWbeKRX4scjFiOc9d7wWKCOvTU
package/dist/runtime.d.ts CHANGED
@@ -57,6 +57,10 @@ export type MountOptions = {
57
57
  /** The project's delivery key — the one key that is safe in a page. */
58
58
  key: string;
59
59
  apiUrl?: string;
60
+ /** Read in this language: a translated field shows in it, or in the
61
+ first language of the project's fallback chain that has a value.
62
+ One of the project's languages (`pt_br` → `pt-BR`). */
63
+ locale?: string;
60
64
  /** Mapled's app — where an expired preview link sends the person. */
61
65
  appUrl?: string;
62
66
  /** Where to look for attributes (default: the whole document). */
package/dist/runtime.js CHANGED
@@ -41,7 +41,7 @@ const P = "data-mapled-";
41
41
  /** Every attribute the runtime reads or writes, besides `bind-…`. */
42
42
  export const NAMES = new Set([
43
43
  "bind", "format", "width", "show", "hide", "link", "list", "each", "record", "slug", "slug-param", "sort", "limit", "filter", "expand", "empty",
44
- "form", "form-state", "form-sent", "form-failed", "consent", "end-preview", "state", "preview", "key", "api", "live",
44
+ "form", "form-state", "form-sent", "form-failed", "consent", "end-preview", "state", "preview", "key", "api", "live", "locale",
45
45
  ]);
46
46
  const KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
47
47
  const DELIVERY_KEY = /^mk_[A-Za-z0-9_]{8,128}$/;
@@ -260,7 +260,13 @@ export function mount(options) {
260
260
  throw new Error("Mapled: @mapled/vanilla fills a page — it runs in a browser. On a server read with @mapled/client.");
261
261
  const root = options.root ?? document.documentElement;
262
262
  const doc = root.ownerDocument;
263
- const client = createClient({ key: options.key, apiUrl: options.apiUrl, appUrl: options.appUrl, fetch: options.fetch });
263
+ const client = createClient({
264
+ key: options.key,
265
+ apiUrl: options.apiUrl,
266
+ appUrl: options.appUrl,
267
+ fetch: options.fetch,
268
+ ...(options.locale ? { locale: options.locale } : {}),
269
+ });
264
270
  const sinks = { apiUrl: options.apiUrl, base: doc.baseURI };
265
271
  /** what the author wrote, for everything a run changed: the next run starts from it */
266
272
  const originals = new Map();
@@ -538,9 +544,11 @@ export function mount(options) {
538
544
  watchExpiry();
539
545
  else {
540
546
  clearTimeout(expiry);
541
- // drafts don't move with releases: a tab watches once it shows what is published
547
+ // drafts don't move with releases: a tab watches once it shows what is published — from the release it shows
548
+ // (its reads are pinned to it), so a publish that landed between the fill and the watch's first answer, or
549
+ // while a background tab waited to be shown, is news; a page as written shows no release: the first named is
542
550
  if (options.live && stopWatching === null)
543
- stopWatching = client.watch((next) => void refresh(next.release), { interval });
551
+ stopWatching = client.watch((next) => void refresh(next.release), { interval, from: report.state === "ready" ? report.release : null });
544
552
  }
545
553
  return report;
546
554
  };
package/dist/version.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  /** The package's version — what the banner of the single file and
2
2
  `Mapled.version` say. Kept equal to package.json by version.test.ts. */
3
- export declare const VERSION = "0.1.1";
3
+ export declare const VERSION = "0.2.1";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  /** The package's version — what the banner of the single file and
2
2
  `Mapled.version` say. Kept equal to package.json by version.test.ts. */
3
- export const VERSION = "0.1.1";
3
+ export const VERSION = "0.2.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mapled/vanilla",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "The browser runtime of Mapled, the hosted headless CMS for sites built with AI — published content in a plain HTML site: one script tag and data-mapled attributes, no framework and no build step.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://mapled.io",
@@ -41,7 +41,7 @@
41
41
  "typecheck": "tsc --noEmit -p tsconfig.json"
42
42
  },
43
43
  "dependencies": {
44
- "@mapled/client": "^0.1.1"
44
+ "@mapled/client": "^0.2.1"
45
45
  },
46
46
  "devDependencies": {
47
47
  "esbuild": "^0.28.2",