@panphora/clayjs 1.3.0 → 1.4.0

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.
@@ -42,6 +42,7 @@ import {
42
42
  model,
43
43
  checkSource,
44
44
  locate,
45
+ nodeAt,
45
46
  pair,
46
47
  render,
47
48
  verify
@@ -62,6 +63,11 @@ const state = {
62
63
  saves: 0,
63
64
  reprints: 0,
64
65
  lastReprint: null,
66
+ partialReprints: 0,
67
+ lastPartialReprint: null,
68
+ // What the last render produced, so the save the host accepts can be counted and
69
+ // announced as what it was. Cleared once reported.
70
+ lastOutcome: null,
65
71
  lastRenderMs: null,
66
72
  lastBytes: null,
67
73
  timing: { fetch: null, model: null, pair: null, refresh: null },
@@ -154,38 +160,95 @@ function install(sourceUrl) {
154
160
  * pass as "the verifier is blind" is a mistake this project has already made once.
155
161
  * `{ corrupt: 'drop-first-text' }` is the one that must be REJECTED: it changes the
156
162
  * tree, which is exactly what the verifier is for.
163
+ *
164
+ * A render that does not verify is not thrown away whole. verify says where it first
165
+ * differs; that element is printed in full and the render tried again, widening to the
166
+ * parent while it still fails. Everything outside the printed elements is still the
167
+ * author's bytes. Only when the widening reaches <html>, or the failure has no node to
168
+ * point at (the prologue, a parse-error count), is today's full serialization sent.
169
+ *
170
+ * Nothing is counted or announced here. A render is not a save: an autosave that
171
+ * found nothing changed, a refused save and a failed request all rendered. The
172
+ * outcome is recorded, and `adopt` reports it when the host accepts these exact bytes.
157
173
  */
158
174
  export function renderSave(clone, today, opts = {}) {
159
175
  if (!state.installed) return today;
160
- state.saves++;
161
- let out;
162
- try {
163
- out = render(clone, state.map, state.model, originalSnapshotNode, opts);
164
- } catch (err) {
165
- return reprint('render threw: ' + (err && err.message ? err.message : err), today);
176
+ state.lastOutcome = null;
177
+ const print = new Set();
178
+ let firstDiff = null;
179
+ for (let round = 0; round <= MAX_PRINT_ROUNDS; round++) {
180
+ let out;
181
+ try {
182
+ out = render(clone, state.map, state.model, originalSnapshotNode, { ...opts, print });
183
+ } catch (err) {
184
+ return fallback('render threw: ' + (err && err.message ? err.message : err), today);
185
+ }
186
+ const v = verify(out.text, today, document, clone, state.model.parseErrors);
187
+ if (v.ok) {
188
+ state.lastRenderMs = out.ms;
189
+ state.lastBytes = out.text.length;
190
+ state.lastOutcome = print.size
191
+ ? { text: out.text, scope: 'partial', reason: firstDiff, printed: print.size }
192
+ : { text: out.text, scope: null };
193
+ return out.text;
194
+ }
195
+ if (firstDiff === null) firstDiff = v.diff;
196
+ if (!v.at || !widen(clone, nodeAt(clone, v.at), print)) return fallback(firstDiff, today);
197
+ }
198
+ return fallback(firstDiff, today);
199
+ }
200
+
201
+ const MAX_PRINT_ROUNDS = 8;
202
+
203
+ /**
204
+ * Add the next element to print: the one holding `node`, or, when that is already
205
+ * inside a printed element, that element's parent. false when the only element left is
206
+ * the root, which is the full serialization by another name.
207
+ */
208
+ function widen(clone, node, print) {
209
+ let el = node && node.nodeType === 1 ? node : node && node.parentNode;
210
+ for (let a = el; a && a !== clone; a = a.parentNode) {
211
+ if (print.has(a)) { print.delete(a); el = a.parentNode; break; }
166
212
  }
167
- const v = verify(out.text, today, document, clone, state.model.parseErrors);
168
- if (!v.ok) return reprint(v.diff, today);
169
- state.lastRenderMs = out.ms;
170
- state.lastBytes = out.text.length;
171
- return out.text;
213
+ if (!el || el.nodeType !== 1 || el === clone) return false;
214
+ print.add(el);
215
+ return true;
216
+ }
217
+
218
+ /** Send today's full serialization, and remember that this render was a fallback. */
219
+ function fallback(reason, today) {
220
+ state.lastOutcome = { text: today, scope: 'full', reason };
221
+ return today;
172
222
  }
173
223
 
174
224
  /**
175
225
  * The fallback, and the alarm.
176
226
  *
177
- * Both halves matter. The bytes are today's, so the floor of this whole mechanism is
178
- * the behaviour it replaces. The event and the counter are how a reprint gets fixed
227
+ * Reported for a save the host accepted. The bytes that went out were today's, so the
228
+ * floor of this whole mechanism is the behaviour it replaces. The event and the
229
+ * counter are how a reprint gets fixed
179
230
  * in the renderer or in the page, which is the only place it should ever be fixed: a
180
231
  * verifier loosened to make this counter look better would pass exactly the writes it
181
232
  * exists to stop.
182
233
  */
183
- function reprint(reason, today) {
234
+ function reprint(reason) {
184
235
  state.reprints++;
185
236
  state.lastReprint = reason;
186
237
  console.warn('clayjs: source map did not verify, saving the full serialization instead:', reason);
187
- document.dispatchEvent(new CustomEvent('clay:save-reprinted', { detail: { reason } }));
188
- return today;
238
+ document.dispatchEvent(new CustomEvent('clay:save-reprinted', { detail: { reason, scope: 'full' } }));
239
+ }
240
+
241
+ /**
242
+ * Part of the document was printed rather than copied. Counted apart from a full
243
+ * reprint because they are different news: this one kept the author's bytes everywhere
244
+ * else, and its rate says how often the renderer and the page disagree about one
245
+ * element, which is where the next renderer fix is.
246
+ */
247
+ function partialReprint(reason, printed) {
248
+ state.partialReprints++;
249
+ state.lastPartialReprint = reason;
250
+ console.info(`clayjs: source map printed ${printed} element(s) in full to match the page:`, reason);
251
+ document.dispatchEvent(new CustomEvent('clay:save-reprinted', { detail: { reason, scope: 'partial', printed } }));
189
252
  }
190
253
 
191
254
  /**
@@ -196,28 +259,41 @@ function reprint(reason, today) {
196
259
  * and the page being told about it. Only the most recent accepted bytes matter, so a
197
260
  * burst of saves costs one refresh.
198
261
  *
199
- * One caveat, worth knowing rather than working around: a host that rewrites on the
200
- * way in leaves this model describing something slightly different from disk.
201
- * htmlclay strips the save token from the root tag, which was never meant to reach
202
- * disk, so the model carries one attribute the file does not. It is self-correcting
203
- * rather than cumulative — the next render copies the token's bytes back out of the
204
- * model and the host strips them again — so the file stays put and only the model's
205
- * idea of the root tag is one attribute long.
262
+ * It is also where a save is counted, because it is the one place that knows a save
263
+ * reached the file.
206
264
  */
207
265
  function adopt(bytes) {
208
266
  if (!state.installed) return;
267
+ report(bytes);
209
268
  state.pendingBytes = bytes;
210
269
  scheduleRefresh();
211
270
  }
212
271
 
272
+ /**
273
+ * Count and announce an accepted save, if these are the bytes the last render
274
+ * produced. Bytes this module did not render (a caller of `saveHtml` with its own
275
+ * string, or an older render) are not its save to report.
276
+ */
277
+ function report(bytes) {
278
+ const outcome = state.lastOutcome;
279
+ if (!outcome || outcome.text !== bytes) return;
280
+ state.lastOutcome = null;
281
+ state.saves++;
282
+ if (outcome.scope === 'full') reprint(outcome.reason);
283
+ else if (outcome.scope === 'partial') partialReprint(outcome.reason, outcome.printed);
284
+ }
285
+
213
286
  /**
214
287
  * A morph replaced live nodes, so the map is keyed by objects that are no longer in
215
- * the page. Re-pair against the same model: for a peer frame the bytes on disk did
216
- * not change, and for a disk frame they changed to something this tab cannot see, so
217
- * the model is the best available answer either way.
288
+ * the page, and it has to be re-paired either way. A DISK frame also carries the bytes
289
+ * now on disk, written by somebody else: those become the model, the same as bytes this
290
+ * tab saved, or the next save would copy the old formatting back over theirs. A peer
291
+ * frame changed nothing on disk, so the model stays.
218
292
  */
219
- function queueRepair() {
293
+ function queueRepair(event) {
220
294
  if (!state.installed) return;
295
+ const detail = event && event.detail;
296
+ if (detail && detail.source === 'disk' && typeof detail.html === 'string') state.pendingBytes = detail.html;
221
297
  scheduleRefresh();
222
298
  }
223
299
 
@@ -232,45 +308,51 @@ function queueRepair() {
232
308
  function scheduleRefresh() {
233
309
  if (state.refreshQueued) return;
234
310
  state.refreshQueued = true;
235
- const run = () => {
236
- state.refreshQueued = false;
237
- if (!state.installed) return;
238
- const bytes = state.pendingBytes;
239
- state.pendingBytes = null;
240
- const t = now();
241
- // The two halves fail independently, so they are tried independently. A refused
242
- // re-model used to skip the re-pair with it, and the re-pair is the half that
243
- // cannot be skipped: a morph replaced live nodes, so the old map is keyed by
244
- // objects no longer in the page, and every save after that reprints the whole
245
- // document until something else queues a refresh. The previous model still
246
- // describes real bytes, so re-pairing against it is the right answer.
247
- let m = state.model;
248
- if (bytes !== null) {
249
- try {
250
- const next = model(bytes);
251
- const refused = checkSource(next, document);
252
- if (refused) throw new Error(refused);
253
- m = next;
254
- } catch (err) {
255
- console.warn('clayjs: source map kept the previous model, the accepted bytes did not model:', err);
256
- }
257
- }
311
+ if (typeof requestIdleCallback === 'function') requestIdleCallback(refreshNow, { timeout: 2000 });
312
+ else setTimeout(refreshNow, 0);
313
+ }
314
+
315
+ /**
316
+ * Run a queued refresh now. A no-op when none is queued, which is also what makes the
317
+ * idle callback of a refresh that `text()` or `locate()` already ran harmless.
318
+ */
319
+ function refreshNow() {
320
+ if (!state.refreshQueued) return;
321
+ state.refreshQueued = false;
322
+ if (!state.installed) return;
323
+ const bytes = state.pendingBytes;
324
+ state.pendingBytes = null;
325
+ const t = now();
326
+ // The two halves fail independently, so they are tried independently. A refused
327
+ // re-model used to skip the re-pair with it, and the re-pair is the half that
328
+ // cannot be skipped: a morph replaced live nodes, so the old map is keyed by
329
+ // objects no longer in the page, and every save after that reprints the whole
330
+ // document until something else queues a refresh. The previous model still
331
+ // describes real bytes, so re-pairing against it is the right answer.
332
+ let m = state.model;
333
+ if (bytes !== null) {
258
334
  try {
259
- const { map, stats } = pairAgainstPage(m);
260
- state.model = m;
261
- state.map = map;
262
- state.stats = stats;
263
- state.refreshes++;
264
- state.timing.refresh = now() - t;
335
+ const next = model(bytes);
336
+ const refused = checkSource(next, document);
337
+ if (refused) throw new Error(refused);
338
+ m = next;
265
339
  } catch (err) {
266
- // The map is now stale rather than wrong: it still describes the pairing as of
267
- // the last successful refresh. Renders off a stale map verify or fall back like
268
- // any other, so this costs formatting fidelity and nothing else.
269
- console.warn('clayjs: source map could not re-pair, continuing on the previous map:', err);
340
+ console.warn('clayjs: source map kept the previous model, the accepted bytes did not model:', err);
270
341
  }
271
- };
272
- if (typeof requestIdleCallback === 'function') requestIdleCallback(run, { timeout: 2000 });
273
- else setTimeout(run, 0);
342
+ }
343
+ try {
344
+ const { map, stats } = pairAgainstPage(m);
345
+ state.model = m;
346
+ state.map = map;
347
+ state.stats = stats;
348
+ state.refreshes++;
349
+ state.timing.refresh = now() - t;
350
+ } catch (err) {
351
+ // The map is now stale rather than wrong: it still describes the pairing as of
352
+ // the last successful refresh. Renders off a stale map verify or fall back like
353
+ // any other, so this costs formatting fidelity and nothing else.
354
+ console.warn('clayjs: source map could not re-pair, continuing on the previous map:', err);
355
+ }
274
356
  }
275
357
 
276
358
  function summary() {
@@ -287,6 +369,8 @@ function summary() {
287
369
  saves: state.saves,
288
370
  reprints: state.reprints,
289
371
  lastReprint: state.lastReprint,
372
+ partialReprints: state.partialReprints,
373
+ lastPartialReprint: state.lastPartialReprint,
290
374
  lastRenderMs: state.lastRenderMs,
291
375
  lastBytes: state.lastBytes,
292
376
  refreshes: state.refreshes,
@@ -297,8 +381,8 @@ function summary() {
297
381
  export const source = {
298
382
  ready: null,
299
383
  stats: summary,
300
- /** The bytes this module believes are on disk right now. */
301
- text: () => (state.model ? state.model.src : null),
384
+ /** The bytes this module believes are on disk right now. A refresh still queued from a save or a disk frame runs first, so this is never the file before that. */
385
+ text: () => { refreshNow(); return state.model ? state.model.src : null; },
302
386
  /**
303
387
  * Where a live element is in those bytes: `{ from, to, line, column }`, or null.
304
388
  *
@@ -312,7 +396,7 @@ export const source = {
312
396
  * agent that cannot tell "this element is new" from "this document has no map" will eventually
313
397
  * write into a file it was never modelling.
314
398
  */
315
- locate: (node) => (state.installed && node ? locate(node, state.map, state.model) : null),
399
+ locate: (node) => { refreshNow(); return state.installed && node ? locate(node, state.map, state.model) : null; },
316
400
  /** What did not pair, for working out why a document reprints more than it should. */
317
401
  unpaired: () => (state.stats
318
402
  ? { live: state.stats.unmatchedLive.slice(0, 50), source: state.stats.unmatchedSource.slice(0, 50) }
@@ -1562,6 +1562,9 @@ class LiveSync {
1562
1562
  source: 'disk',
1563
1563
  etag: typeof etag === 'string' && etag ? etag : null,
1564
1564
  by: by || null,
1565
+ // The bytes now on disk, exactly as they arrived. The source map models them
1566
+ // so this tab's next save copies from the file somebody else just wrote.
1567
+ html,
1565
1568
  }
1566
1569
  }));
1567
1570
  } finally {
@@ -48,20 +48,24 @@ export function serializeControlToAttributes(el) {
48
48
  }
49
49
  }
50
50
 
51
+ // Writes only what changes what a reload would show. A control whose attributes
52
+ // already reload as its live state is left exactly as the author wrote it, because a
53
+ // source-preserving save copies the author's bytes for every node the save did not
54
+ // change, and a rewrite here is a change.
51
55
  export function finalizeControlForSave(target, source = target) {
52
56
  const tag = target.tagName;
53
57
  if (tag === "INPUT") {
54
58
  const type = inputType(target);
55
59
  if (type === "checkbox" || type === "radio") {
56
- if (source.checked) target.setAttribute("checked", "");
57
- else target.removeAttribute("checked");
58
- } else {
60
+ if (!source.checked) target.removeAttribute("checked");
61
+ else if (!target.hasAttribute("checked")) target.setAttribute("checked", "");
62
+ } else if (source.value !== (target.getAttribute("value") ?? "")) {
59
63
  target.setAttribute("value", source.value);
60
64
  }
61
65
  return;
62
66
  }
63
67
  if (tag === "TEXTAREA") {
64
- target.textContent = source.value;
68
+ if (target.textContent !== source.value) target.textContent = source.value;
65
69
  target.removeAttribute("data-value");
66
70
  return;
67
71
  }
@@ -69,8 +73,8 @@ export function finalizeControlForSave(target, source = target) {
69
73
  const tOpts = target.options;
70
74
  const sOpts = source.options;
71
75
  for (let i = 0; i < tOpts.length; i++) {
72
- if (sOpts[i] && sOpts[i].selected) tOpts[i].setAttribute("selected", "");
73
- else tOpts[i].removeAttribute("selected");
76
+ if (!(sOpts[i] && sOpts[i].selected)) tOpts[i].removeAttribute("selected");
77
+ else if (!tOpts[i].hasAttribute("selected")) tOpts[i].setAttribute("selected", "");
74
78
  }
75
79
  }
76
80
  }
@@ -1,5 +1,5 @@
1
- var HyperMorph=(()=>{var ke=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var st=Object.prototype.hasOwnProperty;var it=(e,n)=>{for(var t in n)ke(e,t,{get:n[t],enumerable:!0})},ot=(e,n,t,y)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of rt(n))!st.call(e,u)&&u!==t&&ke(e,u,{get:()=>n[u],enumerable:!(y=nt(n,u))||y.enumerable});return e};var at=e=>ot(ke({},"__esModule",{value:!0}),e);var Ht={};it(Ht,{HyperMorph:()=>fe,default:()=>Bt,defaults:()=>Ct,findChangedRoots:()=>Lt,mergeJson:()=>Se,mergeScriptText:()=>ve,morph:()=>xt,parseJsonRelaxed:()=>ge,parseRulesRelaxed:()=>Ee,spliceProtected:()=>Rt});var Pe={includeClasses:!0,includeAttributes:["href","src","name","type","role","aria-label","alt","title"],excludeAttributePrefixes:["data-morph-","data-hyper-","data-im-"],textHintLength:64,excludeIds:!0,maxPathDepth:4,landmarks:["HEADER","NAV","MAIN","ASIDE","FOOTER","SECTION","ARTICLE"],weights:{signature:100,pathSegment:10,textMatch:20,textMismatch:25,uniqueCandidate:50,positionPenalty:1,maxDriftPenalty:19,slotMatch:30},minConfidence:101,maxScoredCandidates:16};function ut(e){let n=5381;for(let t=0;t<e.length;t++)n=(n<<5)+n^e.charCodeAt(t);return Math.abs(n).toString(36)}function ct(e){if(e.classList&&e.classList.length>0)return Array.from(e.classList).sort().join(" ");let n=e.getAttribute?.("class");return n?n.split(/\s+/).filter(Boolean).sort().join(" "):""}function lt(e,n){let t=[];for(let y of e.attributes||[]){let u=y.name;u==="id"||u==="class"||n.excludeAttributePrefixes.some(b=>u.startsWith(b))||n.includeAttributes.includes(u)&&t.push(`${u}=${y.value}`)}return t.sort().join("|")}function ft(e,n){return(e.textContent||"").replace(/\s+/g," ").trim().slice(0,n.textHintLength)}function dt(e,n){let t=[e.tagName];return n.includeClasses&&t.push(ct(e)),t.push(lt(e,n)),ut(t.join("|"))}function ht(e){let n=e.tagName,t=1,y=e.previousElementSibling;for(;y;)y.tagName===n&&t++,y=y.previousElementSibling;return t}function pt(e,n){return e.getAttribute?.("id")||e.getAttribute?.("role")?!0:n.landmarks.includes(e.tagName)}function gt(e){let n=e.getAttribute?.("id");if(n)return`#${n}`;let t=e.getAttribute?.("role");return t?`@${t}`:e.tagName}function mt(e,n){let t=[],y=e;for(;y&&y.tagName&&t.length<n.maxPathDepth;){let u=`${y.tagName}:${ht(y)}`;if(t.unshift(u),y!==e&&pt(y,n)){t.unshift(gt(y));break}y=y.parentElement}return t}function yt(e,n){let t=0,y=e.length-1,u=n.length-1;for(;y>=0&&u>=0&&e[y]===n[u];)t++,y--,u--;return t}function X(e,n,t){if(t.has(e))return t.get(e);let y={signature:dt(e,n),path:mt(e,n),textHint:ft(e,n)};return t.set(e,y),y}function qe(e,n,t,y){if(y.has(e))return y.get(e);let u=new Map,b=e.querySelectorAll("*"),S=0;for(let d of b){let M=X(d,n,t);M.domIndex=S++,!n.shouldIgnore?.(d)&&(u.has(M.signature)||u.set(M.signature,[]),u.get(M.signature).push(d))}return y.set(e,u),u}function bt(e,n,t){t.delete(e),n.delete(e);let y=e.querySelectorAll("*");for(let u of y)n.delete(u)}function we(e,n,t,y,u){let b=X(e,t,y),S=X(n,t,y),d=t.weights,M={},$=0;if(b.signature!==S.signature)return{score:0,breakdown:{rejected:"signature mismatch"}};$+=d.signature,M.signature=d.signature;let H=yt(b.path,S.path)*d.pathSegment;$+=H,M.path=H;let I=!0;if(b.textHint&&S.textHint?b.textHint===S.textHint?($+=d.textMatch,M.text=d.textMatch):($-=d.textMismatch,M.text=-d.textMismatch,I=!1):b.textHint!==S.textHint&&($-=d.textMismatch,M.text=-d.textMismatch,I=!1),u.candidateCount===1&&I&&($+=d.uniqueCandidate,M.unique=d.uniqueCandidate),typeof b.domIndex=="number"&&typeof S.domIndex=="number"){let k=Math.abs(b.domIndex-S.domIndex),E=Math.min(k*d.positionPenalty,d.maxDriftPenalty);$-=E,M.drift=-E}return{score:$,breakdown:M}}function De(e,n,t,y,u){if(t.excludeIds&&e.getAttribute("id"))return null;let b=qe(n,t,y,u),S=X(e,t,y);if(typeof S.domIndex!="number"){let I=0,k=e.previousElementSibling;for(;k;)I++,k=k.previousElementSibling;S.domIndex=I}let d=b.get(S.signature)||[],M=t.excludeIds?d.filter(I=>!I.getAttribute("id")):d;if(M.length===0)return null;let $=null,q=0,H=null;for(let I of M){let{score:k,breakdown:E}=we(e,I,t,y,{candidateCount:M.length});k>q&&(q=k,$=I,H=E)}return q<t.minConfidence?null:{element:$,confidence:q,breakdown:H}}function At(e,n,t,y){let u=[],b=t.weights.signature+t.weights.slotMatch,S={slot:b};function d(H){if(H.children)return H.children;let I=H.childNodes;if(!I)return[];let k=[];for(let E=0;E<I.length;E++)I[E].nodeType===1&&k.push(I[E]);return k}function M(H,I){let k=d(H),E=d(I);if(k.length===E.length)for(let K=0;K<k.length;K++){let U=k[K],J=E[K];if(t.shouldIgnore?.(U)||t.shouldIgnore?.(J)||t.excludeIds&&(U.getAttribute("id")||J.getAttribute("id"))||U.tagName!==J.tagName)continue;let Q=X(U,t,y).signature,ee=X(J,t,y).signature;Q!==ee&&u.push({newEl:U,oldEl:J,score:b,breakdown:S}),M(U,J)}}function $(H,I){for(;;){if(H.tagName===I.tagName)return[H,I];let k=d(H);if(!H.tagName&&k.length===1){H=k[0];continue}let E=d(I);if(E.length===1&&E[0].tagName===H.tagName){I=E[0];continue}return null}}let q=$(e,n);return q&&M(q[0],q[1]),u}function ze(e,n,t,y,u){let b=n.querySelectorAll("*"),S=qe(e,t,y,u),d=0;for(let k of b){let E=X(k,t,y);E.domIndex=d++}let M=[],$=new Map;function q(k,E,K){let U=new Set;if(k.textHint){let G=$.get(k.signature);if(!G){G=new Map;for(let ne of E){let ye=X(ne,t,y).textHint,re=G.get(ye);re||(re=[],G.set(ye,re)),re.push(ne)}$.set(k.signature,G)}let de=G.get(k.textHint);if(de)for(let ne=0;ne<de.length&&ne<K;ne++)U.add(de[ne])}let J=0,Q=E.length;for(;J<Q;){let G=J+Q>>1;X(E[G],t,y).domIndex<k.domIndex?J=G+1:Q=G}let ee=Math.max(0,Math.min(J-(K>>1),E.length-K)),te=Math.min(ee+K,E.length);for(let G=ee;G<te;G++)U.add(E[G]);return[...U]}for(let k of b){if(t.shouldIgnore?.(k)||t.excludeIds&&k.getAttribute("id"))continue;let E=X(k,t,y),K=S.get(E.signature)||[],U=t.excludeIds?K.filter(ee=>!ee.getAttribute("id")):K,J=t.maxScoredCandidates,Q=J&&U.length>J?q(E,U,J):U;for(let ee of Q){let{score:te,breakdown:G}=we(k,ee,t,y,{candidateCount:U.length});te>=t.minConfidence&&M.push({newEl:k,oldEl:ee,score:te,breakdown:G})}}if(t.weights.slotMatch>0){let k=At(n,e,t,y);for(let E of k)M.push(E)}M.sort((k,E)=>E.score-k.score);let H=new Map,I=new Set;for(let{newEl:k,oldEl:E}of M)H.has(k)||I.has(E)||(H.set(k,E),I.add(E));return H}function _e(e,n,t,y){let u=X(e,t,y),b=X(n,t,y),{score:S,breakdown:d}=we(e,n,t,y,{candidateCount:1});return{matches:S>=t.minConfidence,score:S,breakdown:d,newMeta:{signature:u.signature,path:u.path,textHint:u.textHint},oldMeta:{signature:b.signature,path:b.path,textHint:b.textHint}}}function Fe(e={}){let n={...Pe,...e,weights:{...Pe.weights,...e.weights}},t=new WeakMap,y=new WeakMap;return{findMatch:(u,b)=>De(u,b,n,t,y),computeMatches:(u,b)=>ze(u,b,n,t,y),explain:(u,b)=>_e(u,b,n,t),invalidate:u=>bt(u,t,y),session:()=>{let u=new WeakMap,b=new WeakMap;return{findMatch:(S,d)=>De(S,d,n,u,b),computeMatches:(S,d)=>ze(S,d,n,u,b),explain:(S,d)=>_e(S,d,n,u)}},getConfig:()=>({...n})}}function Te(e,n){for(;;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]==="/"&&e[n+1]==="/"){for(;n<e.length&&e[n]!==`
2
- `;)n++;continue}if(e[n]==="/"&&e[n+1]==="*"){let t=e.indexOf("*/",n+2);if(t===-1)return e.length;n=t+2;continue}return n}}function Ve(e){return e.replace(/\\'/g,"'").replace(/(\\*)"/g,(n,t)=>t.length%2===0?t+'\\"':n)}var St=/^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$/,vt=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function ge(e){try{return JSON.parse(e)}catch{return JSON.parse(Mt(e))}}function Mt(e){let n="",t=0,y=(u,b)=>{throw new Error(`Invalid relaxed JSON: ${u} at position ${b}`)};for(;t<e.length&&(t=Te(e,t),!(t>=e.length));){let u=e[t];if("{}[]:".includes(u)){n+=u,t++;continue}if(u===","){let d=Te(e,t+1);if(e[d]==="}"||e[d]==="]"){t++;continue}n+=u,t++;continue}if(u==='"'||u==="'"){let d=t+1;for(;d<e.length&&e[d]!==u;)e[d]==="\\"&&d++,d++;d>=e.length&&y("unterminated string",t);let M=e.slice(t+1,d);u==="'"&&(M=Ve(M)),n+='"'+M+'"',t=d+1;continue}let b=t;for(;b<e.length&&/[A-Za-z0-9_$.+\-]/.test(e[b]);)b++;b===t&&y("unexpected character "+JSON.stringify(u),t);let S=e.slice(t,b);if(S==="true"||S==="false"||S==="null"||St.test(S)){n+=S,t=b;continue}if(vt.test(S)){if(e[Te(e,b)]===":"){n+='"'+S+'"',t=b;continue}y("unquoted value "+JSON.stringify(S),t)}y("invalid token "+JSON.stringify(S),t)}return n}function Ee(e){try{return JSON.parse(e)}catch{}let n={BRACE_OPEN:"{",BRACE_CLOSE:"}",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",COLON:":",COMMA:",",STRING:"STRING",SELECTOR:"SELECTOR",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",BOOLEAN:"BOOLEAN"};function t(u){let b=[],S=0;for(;S<u.length;){let d=u[S];if(/\s/.test(d)){S++;continue}if("{}".includes(d)){b.push({type:d,value:d}),S++;continue}if(d==="["){let H=!1,I=S+1;for(;I<u.length&&/\s/.test(u[I]);)I++;if(I<u.length&&/[a-zA-Z_]/.test(u[I])&&(H=!0),!H){b.push({type:d,value:d}),S++;continue}}if(d==="]"){b.push({type:d,value:d}),S++;continue}if(d===":"){b.push({type:n.COLON,value:d}),S++;continue}if(d===","){b.push({type:n.COMMA,value:d}),S++;continue}if(d==='"'||d==="'"){let H=d,I=S+1;for(;I<u.length&&u[I]!==H;)u[I]==="\\"&&I++,I++;b.push({type:n.STRING,value:u.substring(S+1,I),quoted:!0,sourceQuote:H}),S=I+1;continue}let M=S,$;for(;M<u.length&&!/[{},]/.test(u[M]);)if(u[M]===":"){let H=[":first",":last",":nth-child",":nth-of-type",":first-child",":last-child",":first-of-type",":last-of-type",":only-child",":only-of-type",":hover",":focus",":active",":visited",":disabled",":enabled",":checked",":empty",":root",":target",":not",":before",":after",":nth-last-child",":nth-last-of-type"],I=!1;for(let k of H){let E=k.substring(1);if(u.substring(M+1,M+1+E.length)===E){I=!0,M+=E.length;break}}if(!I)break}else if(u[M]==="["){for(M++;M<u.length&&u[M]!=="]";){if(u[M]==='"'||u[M]==="'"){let H=u[M];for(M++;M<u.length&&u[M]!==H;)u[M]==="\\"&&M++,M++}M++}M<u.length&&u[M]==="]"&&M++}else M++;$=u.substring(S,M);let q=n.IDENTIFIER;/^-?\d+(\.\d+)?$/.test($)?q=n.NUMBER:$==="true"||$==="false"||$==="null"?q=n.BOOLEAN:/^[.#@\[]|[.#@\[]| /.test($)&&(q=n.SELECTOR),b.push({type:q,value:$,quoted:!1}),S=M}return b}function y(u){let b="";for(let S=0;S<u.length;S++){let d=u[S];if("{}".includes(d.type)||"[]".includes(d.type)){b+=d.value;continue}if(d.type===n.COLON){b+=d.value;continue}if(d.type===n.COMMA){let M=u[S+1];if(M&&(M.type==="}"||M.type==="]"))continue;b+=d.value;continue}if(d.type===n.STRING){let M=d.value;d.sourceQuote==="'"&&(M=Ve(M)),b+=`"${M}"`;continue}if(d.type===n.NUMBER||d.type===n.BOOLEAN){b+=d.value;continue}b+=`"${d.value}"`}return b}try{let u=t(e),b=y(u);return JSON.parse(b)}catch(u){throw new Error("Invalid extraction rules syntax: "+u.message)}}var V=Symbol("hyper-morph-json-merge:missing"),Ke=["id","_id","uuid","key","slug","code","name"];function le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function me(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Nt(e,n,t){Object.defineProperty(e,n,{value:t,enumerable:!0,writable:!0,configurable:!0})}function ie(e,n){if(e===n)return!0;if(Array.isArray(e)&&Array.isArray(n)){if(e.length!==n.length)return!1;for(let t=0;t<e.length;t++)if(!ie(e[t],n[t]))return!1;return!0}if(le(e)&&le(n)){let t=Object.keys(e);if(t.length!==Object.keys(n).length)return!1;for(let y of t)if(!me(n,y)||!ie(e[y],n[y]))return!1;return!0}return!1}function Ue(e,n,t,y){return ie(n,t)?n:ie(n,e)?t:ie(t,e)?n:le(n)&&le(t)?kt(le(e)?e:{},n,t,y):Array.isArray(n)&&Array.isArray(t)?It(Array.isArray(e)?e:[],n,t,y):t}function Je(e,n,t,y){return n===V&&t===V?V:n===V?e===V?t:ie(t,e)?V:t:t===V?e===V?n:V:Ue(e,n,t,y)}function kt(e,n,t,y){let u={},b=new Set([...Object.keys(e),...Object.keys(n),...Object.keys(t)]);for(let S of b){let d=Je(me(e,S)?e[S]:V,me(n,S)?n[S]:V,me(t,S)?t[S]:V,y);d!==V&&Nt(u,S,d)}return u}function wt(e){return e===null||typeof e!="object"}function Ae(e){return typeof e+":"+String(e)}function Tt(e,n){for(let t of n){let y=new Set;for(let u of t){if(!me(u,e))return!1;let b=u[e];if(typeof b!="string"&&typeof b!="number")return!1;let S=Ae(b);if(y.has(S))return!1;y.add(S)}}return!0}function Et(e,n,t,y){let u=[e,n,t],b=!0;for(let S of u)for(let d of S)le(d)||(b=!1);if(b){for(let S of y.keyCandidates)if(Tt(S,u))return{kind:"keyed",field:S};return null}for(let S of u){let d=new Set;for(let M of S){if(!wt(M))return null;let $=Ae(M);if(d.has($))return null;d.add($)}}return{kind:"self"}}function It(e,n,t,y){let u=Et(e,n,t,y);if(!u)return t;let b=u.kind==="self"?Ae:k=>Ae(k[u.field]),S=k=>{let E=new Map;for(let K of k)E.set(b(K),K);return E},d=S(e),M=S(n),$=S(t),q=new Map,H=new Set([...d.keys(),...M.keys(),...$.keys()]);for(let k of H){let E=Je(d.has(k)?d.get(k):V,M.has(k)?M.get(k):V,$.has(k)?$.get(k):V,y);E!==V&&q.set(k,E)}let I=[];for(let k of t){let E=b(k);q.has(E)&&I.push(E)}for(let k=0;k<n.length;k++){let E=b(n[k]);if(!q.has(E)||I.includes(E))continue;let K=0;for(let U=k-1;U>=0;U--){let J=I.indexOf(b(n[U]));if(J!==-1){K=J+1;break}}I.splice(K,0,E)}return I.map(k=>q.get(k))}function Se(e,n,t,y={}){let u=y.keyCandidates?[...y.keyCandidates,...Ke]:Ke;return Ue(e===void 0?V:e,n,t,{keyCandidates:u})}function ve(e,n,t,y={}){let u=y.parse||ge,b=[],S=(H,I)=>{if(typeof H!="string")return V;try{return u(H)}catch(k){return b.push(`${I} side is not valid JSON (${k.message})`),V}},d=S(n,"local"),M=S(t,"remote");if(d===V)return{text:t,warnings:b};if(M===V)return{text:n,warnings:b};let $=S(e,"base"),q=Se($===V?void 0:$,d,M,y);return ie(q,M)?{text:t,warnings:b}:ie(q,d)?{text:n,warnings:b}:{text:JSON.stringify(q,null,2),warnings:b}}var Ot=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),_t=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),qt=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui"]);function We(e){let n=Ot[e];if(!n)throw new Error(`Unknown region capability: ${e}`);return[...n.tokens,...n.bundles].flatMap(t=>[`[clay~="${t}"]`,`[${t}]`]).join(", ")}var fe=(function(){"use strict";let e=()=>{},n='[editor-ui],[clay~="editor-ui"],[save-ignore],[snapshot-remove],[no-snapshot],[no-save],[save-remove],[freeze],[save-freeze],[clay~="no-save"],[clay~="no-snapshot"],[clay~="freeze"]',t=`${We("history")},[no-undo],[clay~="no-undo"]`;function y(r){if(r?.nodeType!==1)return!1;if(r.matches(n))return!0;if(r.tagName==="LINK"||r.tagName==="SCRIPT"){let p=r.getAttribute("src")||r.getAttribute("href")||"";if(p.startsWith("chrome-extension://")||p.startsWith("moz-extension://")||p.startsWith("safari-web-extension://"))return!0}return!1}function u(r){return r?.nodeType!==1?!1:r.closest(n)?!0:y(r)}function b(r,p,h){if(h){let w=h.identityOf(r);if(w&&!h.disabled.has(w.key))return"hm-merge:"+w.key}if(p!=="smart")return r.outerHTML;let N=r.getAttribute("src"),A=r.getAttribute("type")||"text/javascript";if(N)try{let w=new URL(N,window.location.href);return`ext:${A}:${w.origin}${w.pathname}${w.search}`}catch{return`ext:${A}:${N}`}else{let w=r.textContent.trim(),a=5381;for(let c=0;c<w.length;c++)a=(a<<5)+a^w.charCodeAt(c);return`inline:${A}:${Math.abs(a).toString(36)}`}}let S="http://www.w3.org/1999/xhtml";function d(r){return r?.nodeType===1&&r.tagName==="SCRIPT"&&r.namespaceURI===S}function M(r){let p=document.createElement("div");p.innerHTML="<script><\/script>";let h=p.firstChild;for(let N of r.attributes)h.setAttribute(N.name,N.value);return h.textContent=r.textContent,h}function $(r){if(d(r))return M(r);if(r?.nodeType===1)for(let p of r.querySelectorAll("script"))d(p)&&p.replaceWith(M(p));return r}function q(r){let p=(r.getAttribute("type")||"").split(";")[0].trim().toLowerCase();return p==="application/json"||p.endsWith("+json")}let H={match:r=>r.hasAttribute("merge"),identity:r=>r.getAttribute("merge")};function I(r,p,h){if(h.merge===!1)return null;let N=[H,...h.mergeTags||[]],A=new WeakMap,w=i=>{if(A.has(i))return A.get(i);let g=null;if(d(i)&&!i.getAttribute("src")&&!u(i)){let m=i;for(let T=0;T<N.length;T++)if(N[T].match(m)){if(!q(m))console.warn("[hyper-morph] merge ignored: script type is not JSON",m);else{let R=N[T].identity(m);R!=null&&R!==""&&(g={key:T+":"+R,raw:R,recognizer:N[T]})}break}}return A.set(i,g),g},a=new Set,c=i=>{let g=new Map,m=T=>{let R=w(T);R&&(g.has(R.key)?(a.add(R.key),console.warn(`[hyper-morph] merge disabled for duplicate identity "${R.raw}"`)):g.set(R.key,T))};d(i)&&m(i);for(let T of i.querySelectorAll("script"))m(T);return g},l=c(r),s=c(p.__hyperMorphRoot||p);if(l.size===0&&s.size===0)return null;let o=null;return{identityOf:w,disabled:a,oldByKey:l,newByKey:s,baseTexts:()=>{if(o)return o;o=new Map;let i=h.mergeBase;if(!i)return o;let g;typeof i=="string"?g=new DOMParser().parseFromString(i,"text/html").documentElement:i?.nodeType===9?g=i.documentElement:g=i;let m=T=>{let R=w(T);R&&!o.has(R.key)&&o.set(R.key,T.textContent)};d(g)&&m(g);for(let T of g.querySelectorAll("script"))m(T);return o}}}function k(r,p,h){let N=r.merge;if(!N)return!1;let A=N.identityOf(p);if(!A||N.disabled.has(A.key))return!1;let w=N.identityOf(h);if(!w||w.key!==A.key)return!1;let a=p,c=h,l=c.getAttribute("merge-key")||a.getAttribute("merge-key"),{text:s,warnings:o}=ve(N.baseTexts().get(A.key),a.textContent,c.textContent,{parse:A.recognizer.parse,keyCandidates:l?l.split(/[\s,]+/).filter(Boolean):void 0});for(let f of o)console.warn(`[hyper-morph] merge "${A.raw}": ${f}`);return a.textContent!==s&&(a.textContent=s),!0}let E={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:r=>r.getAttribute("im-preserve")==="true",shouldReAppend:r=>r.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},scripts:{handle:!0,matchMode:"outerHTML",shouldPreserve:r=>r.getAttribute("im-preserve")==="true",shouldReAppend:r=>r.getAttribute("im-re-append")==="true",shouldRemove:e,afterScriptsHandled:e},restoreFocus:!0},K={computeMatches(r,p,h=u){let{computeMatches:N}=Fe({shouldIgnore:h}).session();return N(r,p)}};function U(r,p,h={}){r=Xe(r);let N=Oe(p),A=Qe(r,N,h),w=A.scripts.handle?new Set(Array.from(r.querySelectorAll("script")).map(s=>b(s,A.scripts.matchMode,A.merge))):null,a=ne(A),c;try{c=Ge(A,r,N,s=>s.morphStyle==="innerHTML"?(re(s,r,N),Array.from(r.childNodes)):de(s,r,N))}catch(s){throw Q(A),s}let l=s=>{a&&ye(A,a),J(A);let o=w?Ze(s,w,A):[];return o.length>0?Promise.all(o).then(()=>s):s};if(c instanceof Promise)return c.then(s=>{try{return l(s)}catch(o){throw Q(A),o}},s=>{throw Q(A),s});try{return l(c)}catch(s){throw Q(A),s}}function J(r){let p=r.pantry;if(p){for(let h of Array.from(p.childNodes))r.callbacks.beforeNodeRemoved(h)!==!1&&r.callbacks.afterNodeRemoved(h);for(let h of Array.from(p.childNodes))p.removeChild(h);p.remove(),r.pantry=null,r.stagedNodes.clear()}}function Q(r){let p=r.pantry;if(!p)return;let h=Array.from(r.stagedNodes.entries()).reverse();for(let[N,A]of h){if(!p.contains(N))continue;let w=A.nextSibling?.parentNode===A.parent?A.nextSibling:null;try{te(A.parent,N,w)}catch{}}for(let N of Array.from(p.childNodes))p.removeChild(N);p.remove(),r.pantry=null,r.stagedNodes.clear()}function ee(r){if(r.pantry)return r.pantry;let p=r.target.ownerDocument,h=p.createElement("div");return h.hidden=!0,h.setAttribute("mutations-ignore",""),p.body.insertAdjacentElement("afterend",h),r.pantry=h,h}function te(r,p,h){if(r.moveBefore)try{r.moveBefore(p,h)}catch{r.insertBefore(p,h)}else r.insertBefore(p,h)}function G(r,p){!r.stagedNodes.has(p)&&p.parentNode&&r.stagedNodes.set(p,{parent:p.parentNode,nextSibling:p.nextSibling}),te(ee(r),p,null)}function de(r,p,h){let N=Oe(p);return re(r,N,h,p,p.nextSibling),Array.from(N.childNodes)}function ne(r){if(!r.config.restoreFocus)return null;let p=document.activeElement;if(!(p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement))return null;let{id:h,selectionStart:N,selectionEnd:A}=p;return{element:p,id:h,selectionStart:N,selectionEnd:A}}function ye(r,p){let h=p.element;if(p.id&&p.id!==document.activeElement?.getAttribute("id")&&(h=r.target.querySelector(`[id="${CSS.escape(p.id)}"]`),h?.focus()),h&&!h.selectionEnd&&p.selectionEnd!=null)try{h.setSelectionRange(p.selectionStart,p.selectionEnd)}catch{}}let re=(function(){function r(s,o,f,i=null,g=null){o?.tagName==="TEMPLATE"&&f?.tagName==="TEMPLATE"&&(o=o.content,f=f.content),i||=o.firstChild;for(let m of f.childNodes){if(s.shouldIgnore(m))continue;if(i&&i!=g){let R=N(s,m,i,g);if(R){R!==i&&w(s,i,R),be(R,m,s),i=R.nextSibling;continue}}if(m?.nodeType===1){let R=m.getAttribute("id");if(s.persistentIds.has(R)){let v=a(o,R,i,s);be(v,m,s),i=v.nextSibling;continue}if(!s.idMap.has(m)){let v=s.hyperMatches.get(m);if(v&&!s.idMap.has(v)&&!l(v,o)){te(o,v,i),be(v,m,s),i=v.nextSibling;continue}}}let T=p(o,m,i,s);T&&(i=T.nextSibling)}for(;i&&i!=g;){let m=i;i=i.nextSibling,s.shouldIgnore(m)||A(s,m)}}function p(s,o,f,i){if(i.callbacks.beforeNodeAdded(o)===!1)return null;let g=s.ownerDocument||s.realParentNode?.ownerDocument||i.target.ownerDocument;if(i.idMap.has(o)){let m=o,T=g.createElementNS(m.namespaceURI,m.localName);return s.insertBefore(T,f),be(T,o,i),i.callbacks.afterNodeAdded(T),T}else{let m=$(h(o,g,i));return m?(s.insertBefore(m,f),i.callbacks.afterNodeAdded(m),m):null}}function h(s,o,f){if(f.shouldIgnore(s))return null;let i=o.importNode(s,!1),g=s.nodeType===1&&s.tagName==="TEMPLATE"?s.content:s,m=i.nodeType===1&&i.tagName==="TEMPLATE"?i.content:i;for(let T of Array.from(g.childNodes||[])){let R=h(T,o,f);R&&m.appendChild(R)}return i}let N=(function(){function s(i,g,m,T){let R=g?.nodeType===1&&!i.idMap.has(g)?i.hyperMatches.get(g):null,v=null,O=g.nextSibling,P=0,B=m;for(;B&&B!=T;){if(i.shouldIgnore(B)){B=B.nextSibling;continue}if(f(B,g)){if(o(i,B,g)||B===R&&!i.idMap.has(B))return B;if(v===null){let F=B?.nodeType===1&&i.hyperMatchedOldElements.has(B);!i.idMap.has(B)&&!F&&(v=B)}}if(v===null&&O&&f(B,O)&&(P++,O=O.nextSibling,P>=2&&(v=void 0)),i.activeElementAndParents.includes(B))break;B=B.nextSibling}return v||null}function o(i,g,m){let T=i.idMap.get(g),R=i.idMap.get(m);if(!R||!T)return!1;for(let v of T)if(R.has(v))return!0;return!1}function f(i,g){let m=i,T=g;return m.nodeType===T.nodeType&&m.tagName===T.tagName&&(!m.getAttribute?.("id")||m.getAttribute?.("id")===T.getAttribute?.("id"))}return s})();function A(s,o){let f=o?.nodeType===1&&s.hyperMatchedOldElements.has(o)&&!s.idMap.has(o);if(s.idMap.has(o)||f)G(s,o);else{if(s.callbacks.beforeNodeRemoved(o)===!1)return;o.parentNode?.removeChild(o),s.callbacks.afterNodeRemoved(o)}}function w(s,o,f){let i=o;for(;i&&i!==f;){let g=i;i=i.nextSibling,s.shouldIgnore(g)||A(s,g)}return i}function a(s,o,f,i){let g=i.target.ownerDocument?.defaultView?.CSS?.escape?i.target.ownerDocument.defaultView.CSS.escape(o):String(o).replace(/["\\]/g,"\\$&"),m=i.target.getAttribute?.("id")===o&&i.target||i.target.querySelector(`[id="${g}"]`)||i.pantry?.querySelector(`[id="${g}"]`);return c(m,i),te(s,m,f),m}function c(s,o){let f=s.getAttribute("id");for(;s=s.parentNode;){let i=o.idMap.get(s);i&&(i.delete(f),i.size||o.idMap.delete(s))}}function l(s,o){let f=o?.nodeType===1?o:o.realParentNode;return!!f&&s.contains(f)}return r})(),be=(function(){function r(a,c,l){return l.ignoreActive&&a===document.activeElement?null:(l.callbacks.beforeNodeMorphed(a,c)===!1||(a?.tagName==="HEAD"&&l.head.ignore||(a?.tagName==="HEAD"&&l.head.style!=="morph"?Ie(a,c,l):(p(a,c,l),k(l,a,c)||w(a,l)||re(l,a,c))),l.callbacks.afterNodeMorphed(a,c)),a)}function p(a,c,l){let s=c.nodeType;if(s===1){let o=a,f=c,i=o.attributes,g=f.attributes;for(let m of g)A(m.name,o,"update",l)||o.getAttribute(m.name)!==m.value&&o.setAttribute(m.name,m.value);for(let m=i.length-1;0<=m;m--){let T=i[m];if(T&&!f.hasAttribute(T.name)){if(A(T.name,o,"remove",l))continue;o.removeAttribute(T.name)}}w(o,l)||h(o,f,l)}(s===8||s===3)&&a.nodeValue!==c.nodeValue&&(a.nodeValue=c.nodeValue)}function h(a,c,l){if(a.tagName==="INPUT"&&c.tagName==="INPUT"&&c.type!=="file"){let s=c.value,o=a.value;N(a,c,"checked",l),N(a,c,"disabled",l),l.formStateSync==="property"&&a.indeterminate!==c.indeterminate&&(a.indeterminate=c.indeterminate),l.formStateSync==="property"?o!==s&&(A("value",a,"update",l)||(a.value=s)):c.hasAttribute("value")?o!==s&&(A("value",a,"update",l)||(a.setAttribute("value",s),a.value=s)):A("value",a,"remove",l)||(a.value="",a.removeAttribute("value"))}else if(a.tagName==="OPTION"&&c.tagName==="OPTION")N(a,c,"selected",l);else if(a.tagName==="TEXTAREA"&&c.tagName==="TEXTAREA"){let s=c.value,o=a.value;if(A("value",a,"update",l)||(s!==o&&(a.value=s),l.formStateSync==="property"))return;a.firstChild&&a.firstChild.nodeValue!==s&&(a.firstChild.nodeValue=s)}}function N(a,c,l,s){let o=c[l],f=a[l];if(o!==f){let i=A(l,a,"update",s);if(i||(a[l]=c[l]),s.formStateSync==="property")return;o?i||a.setAttribute(l,""):A(l,a,"remove",s)||a.removeAttribute(l)}}function A(a,c,l,s){return a==="value"&&s.ignoreActiveValue&&c===document.activeElement?!0:s.callbacks.beforeAttributeUpdated(a,c,l)===!1}function w(a,c){return!!c.ignoreActiveValue&&a===document.activeElement&&a!==document.body}return r})();function Ge(r,p,h,N){if(r.head.block){let A=p.querySelector("head"),w=h.querySelector("head");if(A&&w){let a=Ie(A,w,r);return Promise.all(a).then(()=>(r.head.block=!1,r.head.ignore=!0,N(r)))}}return N(r)}function Ye(r){return r.tagName==="SCRIPT"?!!r.getAttribute("src"):r.tagName==="LINK"?(r.getAttribute("rel")||"").toLowerCase().split(/\s+/).includes("stylesheet")&&!!r.getAttribute("href"):!1}function Ie(r,p,h){let N=[],A=[],w=[],a=[],c=h.scripts.matchMode,l=f=>{if(f.tagName==="SCRIPT")return b(f,c,h.merge);if(f.tagName==="LINK"&&c==="smart"){let i=f.getAttribute("href");if(i)try{let g=new URL(i,window.location.href);return`link:${f.getAttribute("rel")||""}:${g.origin}${g.pathname}${g.search}`}catch{}}return f.outerHTML},s=new Map;for(let f of p.children){if(h.shouldIgnore(f))continue;let i=l(f),g=s.get(i);g||(g=[],s.set(i,g)),g.push(f)}for(let f of r.children){let i=l(f),g=s.get(i),m=!!(g&&g.length),T=h.head.shouldReAppend(f),R=h.head.shouldPreserve(f);if(m||R)if(T)A.push(f);else{if(g&&g.length){let v=g.pop();g.length||s.delete(i),k(h,f,v)}w.push(f)}else h.head.style==="append"?T&&(A.push(f),a.push(f)):h.head.shouldRemove(f)!==!1&&!h.shouldIgnore(f)&&A.push(f)}for(let f of s.values())a.push(...f);let o=[];for(let f of a){let i=document.createRange().createContextualFragment(f.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(i)!==!1){if(i instanceof Element&&Ye(i)){let g,m=new Promise(function(T){g=T});i.addEventListener("load",function(){g()}),i.addEventListener("error",function(){g()}),o.push(m)}r.appendChild(i),h.callbacks.afterNodeAdded(i),N.push(i)}}for(let f of A)h.callbacks.beforeNodeRemoved(f)!==!1&&(r.removeChild(f),h.callbacks.afterNodeRemoved(f));return h.head.afterHeadMorphed(r,{added:N,kept:w,removed:A}),o}function Ze(r,p,h){if(!h.scripts.handle)return[];let N=[],A=[],w=[],a=[],c=h.scripts.matchMode,l=[];for(let o of r)if(o instanceof Element){d(o)&&l.push(o);for(let f of o.querySelectorAll("script"))d(f)&&l.push(f)}for(let o of l){if(o.closest("head")||h.shouldIgnore(o))continue;let f=b(o,c,h.merge),i=p.has(f),g=h.scripts.shouldPreserve(o),m=h.scripts.shouldReAppend(o);i||g?m?(A.push(o),a.push(o)):w.push(o):a.push(o)}let s=[];for(let o of a){if(h.callbacks.beforeNodeAdded(o)===!1)continue;let f=document.createElement("script");for(let i of o.attributes)f.setAttribute(i.name,i.value);if(f.textContent=o.textContent,f.src){let i,g=new Promise(function(m){i=m});f.addEventListener("load",function(){i()}),f.addEventListener("error",function(){i()}),s.push(g)}o.replaceWith(f),h.callbacks.afterNodeAdded(f),N.push(f)}return h.scripts.afterScriptsHandled(h.target,{added:N,kept:w,removed:A}),s}let Qe=(function(){function r(c,l,s){let o=s.policy==="history"?t:n,f=s.policy==="raw"?()=>!1:P=>{if(P?.nodeType!==1)return!1;if(s.policy!=="history"&&u(P))return!0;let B=P.closest(o);return!(!B||s.policy==="history"&&B===c&&B.matches('[no-undo],[clay~="no-undo"]')&&!B.matches('[editor-ui],[clay~="editor-ui"]'))},{persistentIds:i,idMap:g}=w(c,l,f),m=K.computeMatches(c,l,f);if(typeof s.key=="function"){let P=new Map,B=new Set,F=x=>{let L=s.key(x);L!=null&&(P.has(L)?B.add(L):P.set(L,x))};c instanceof Element&&F(c);for(let x of c.querySelectorAll("*"))F(x);for(let x of B)P.delete(x);let Y=new Map;for(let[x,L]of m)Y.set(L,x);let Z=l.__hyperMorphRoot||l,z=new Map,C=new Set,D=x=>{let L=s.key(x);L!=null&&(z.has(L)?C.add(L):z.set(L,x))};Z instanceof Element&&D(Z);for(let x of Z.querySelectorAll("*"))D(x);for(let x of C)z.delete(x);for(let[x,L]of z){let _=P.get(x);if(!_||_.tagName!==L.tagName)continue;let oe=Y.get(_);oe&&oe!==L&&m.delete(oe);let ae=m.get(L);ae&&ae!==_&&Y.delete(ae),m.set(L,_),Y.set(_,L)}}let T=p(s),R=I(c,l,T.scripts);if(R){let P=new Map;for(let[B,F]of m)P.set(F,B);for(let[B,F]of R.newByKey){if(R.disabled.has(B))continue;let Y=R.oldByKey.get(B);if(!Y)continue;let Z=P.get(Y);Z&&Z!==F&&m.delete(Z);let z=m.get(F);z&&z!==Y&&P.delete(z),m.set(F,Y),P.set(Y,F)}}let v=new Set;for(let P of m.values())v.add(P);let O=T.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(O))throw new Error(`Do not understand how to morph style ${O}`);return{target:c,newContent:l,config:T,morphStyle:O,ignoreActive:T.ignoreActive,ignoreActiveValue:T.ignoreActiveValue,restoreFocus:T.restoreFocus,formStateSync:T.formStateSync||"attribute",idMap:g,persistentIds:i,hyperMatches:m,hyperMatchedOldElements:v,merge:R,pantry:null,stagedNodes:new Map,activeElementAndParents:h(c),callbacks:T.callbacks,head:T.head,scripts:T.scripts,shouldIgnore:f}}function p(c){let l=Object.assign({},E);return Object.assign(l,c),l.callbacks=Object.assign({},E.callbacks,c.callbacks),l.head=Object.assign({},E.head,c.head),l.scripts=Object.assign({},E.scripts,c.scripts),l}function h(c){let l=[],s=c.ownerDocument?.activeElement;if(s?.tagName!=="BODY"&&c.contains(s))for(;s&&(l.push(s),s!==c);)s=s.parentElement;return l}function N(c){let l=Array.from(c.querySelectorAll("[id]"));return c.getAttribute?.("id")&&l.push(c),l}function A(c,l,s,o){for(let f of o){let i=f.getAttribute("id");if(l.has(i)){let g=f;for(;g;){let m=c.get(g);if(m==null&&(m=new Set,c.set(g,m)),m.add(i),g===s)break;g=g.parentElement}}}}function w(c,l,s){let o=N(c).filter(T=>!s(T)),f=N(l).filter(T=>!s(T)),i=a(o,f),g=new Map;A(g,i,c,o);let m=l.__hyperMorphRoot||l;return A(g,i,m,f),{persistentIds:i,idMap:g}}function a(c,l){let s=new Set,o=new Map;for(let i of c){let g=i.getAttribute("id");o.has(g)?s.add(g):o.set(g,i.tagName)}let f=new Set;for(let i of l){let g=i.getAttribute("id");f.has(g)?s.add(g):o.get(g)===i.tagName&&f.add(g)}for(let i of s)f.delete(i);return f}return r})(),{normalizeElement:Xe,normalizeParent:Oe}=(function(){let r=new WeakSet;function p(a){return a?.nodeType===9?a.documentElement:a}function h(a){if(a==null)return document.createElement("div");if(typeof a=="string")return h(w(a));if(r.has(a))return a;if(a&&typeof a=="object"&&"nodeType"in a){if(a.parentNode)return new N(a);{let c=a.ownerDocument.createElement("div");return c.append(a),c}}else{let l=[...a][0]?.ownerDocument?.createElement("div")||document.createElement("div");for(let s of[...a])l.append(s);return l}}class N{constructor(c){this.originalNode=c,this.realParentNode=c.parentNode,this.previousSibling=c.previousSibling,this.nextSibling=c.nextSibling}get childNodes(){let c=[],l=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;l&&l!=this.nextSibling;)c.push(l),l=l.nextSibling;return c}querySelectorAll(c){return this.childNodes.reduce((l,s)=>{if(s instanceof Element){s.matches(c)&&l.push(s);let o=s.querySelectorAll(c);for(let f=0;f<o.length;f++)l.push(o[f])}return l},[])}insertBefore(c,l){return this.realParentNode.insertBefore(c,l)}moveBefore(c,l){return this.realParentNode.moveBefore(c,l)}get __hyperMorphRoot(){return this.originalNode}}function A(a){let c=f=>`<${f}(?:\\s(?:[^>"']|"[^"]*"|'[^']*')*)?>`,l=a.replace(/<!--[\s\S]*?-->/g,"");for(let f of["script","style","textarea","title"])l=l.replace(new RegExp(`${c(f)}[\\s\\S]*?</${f}\\s*>`,"gi"),"");let s=new RegExp(`${c("svg")}[\\s\\S]*?</svg\\s*>`,"gi"),o;do o=l,l=l.replace(s,"");while(l!==o);return l}function w(a){let c=new DOMParser,l=A(a);if(l.match(/<\/html>/)||l.match(/<\/head>/)||l.match(/<\/body>/)){let s=c.parseFromString(a,"text/html");if(l.match(/<\/html>/))return r.add(s),s;{let o=s.firstChild;return o&&r.add(o),o}}else{let o=c.parseFromString("<body><template>"+a+"</template></body>","text/html").body.querySelector("template").content;return r.add(o),o}}return{normalizeElement:p,normalizeParent:h}})(),xe=Symbol("hyper-morph-duplicate-key"),Ce=[r=>r.getAttribute("data-id"),r=>r.getAttribute("id")];function he(r,p){return p.map(h=>{let N=new Map;for(let A of r){if(A.nodeType!==1)continue;let w=h(A);w==null||w===""||N.set(w,N.has(w)?xe:A)}return N})}function Le(r,p,h,N){for(let A=0;A<N.length;A++){let w=N[A](r);if(w==null||w===""||p[A].get(w)!==r)continue;let a=h[A].get(w);if(!(!a||a===xe)&&a.tagName===r.tagName)return a}return null}function ue(r,p,h){for(let N=0;N<h.length;N++){let A=h[N](r);if(!(A==null||A==="")&&p[N].get(A)===r)return!0}return!1}function et(r,p,h={}){let N=h.skip||(()=>!1),A=h.ignoreAttr||(()=>!1),w=h.tiers&&h.tiers.length?h.tiers:Ce,a=null;function c(){return a||(a=he([r,...r.querySelectorAll("*")],w)),a}let l=null;function s(){return l||(l=he([p,...p.querySelectorAll("*")],w)),l}function o(C){return!C.parentElement||!C.parentElement.parentElement}function f(C,D,x){return o(C)||ue(C,c(),w)?(x.push({type:"subtree",el:C,base:D}),!1):!0}function i(C,D){let x=[];for(let L of C.attributes)A(C,L.name)||D.getAttribute(L.name)!==L.value&&x.push(L.name);for(let L of D.attributes)A(C,L.name)||C.hasAttribute(L.name)||x.push(L.name);return x}function g(C){let D=[],x=null,L=()=>{x!==null&&(D.push({nodeType:3,nodeValue:x}),x=null)};for(let _ of C.childNodes){if(_.nodeType===3){x=(x===null?"":x)+_.nodeValue;continue}_.nodeType===1&&N(_)||(L(),(_.nodeType===1||_.nodeType===8)&&D.push(_))}return L(),D}function m(C,D){if(C.nodeType!==D.nodeType)return!1;if(C.nodeType!==1)return!0;if(C.tagName!==D.tagName)return!1;for(let x of w){let L=x(C),_=x(D);if(L!=null&&L!==""&&_!=null&&_!==""&&L!==_)return!1}return!0}function T(C){let D="";for(let x of C)x.nodeType===3&&x.nodeValue.trim()!==""?D+="\0"+x.nodeValue:x.nodeType===8&&(D+=""+x.nodeValue);return D}function R(C,D,x){let L=g(C),_=g(D);if(L.length===_.length){let j=!0;for(let W=0;W<L.length;W++)if(!m(L[W],_[W])){j=!1;break}if(j){for(let W=0;W<L.length;W++){let ce=L[W];if(ce.nodeType===1){if(v(ce,_[W],x))return!0}else if(ce.nodeValue!==_[W].nodeValue)return!0}return!1}}let oe=L.filter(j=>j.nodeType===1),ae=_.filter(j=>j.nodeType===1);if(T(L)!==T(_))return!0;let Re=he(oe,w),Be=he(ae,w),Me=[],Ne=new Set,He=[];for(let j of oe){let W=Le(j,Re,Be,w);W&&!Ne.has(W)?(Me.push([j,W]),Ne.add(W)):He.push(j)}let se=[];for(let j of He)ue(j,Re,w)?x.push({type:"subtree",el:j,base:null}):se.push(j);let pe=[];for(let j of ae)Ne.has(j)||(ue(j,Be,w)?x.push({type:"deletion",el:j}):pe.push(j));if(se.length!==pe.length)return!0;for(let j=0;j<se.length;j++)if(!m(se[j],pe[j]))return!0;let je=new Map(Me);for(let j=0;j<se.length;j++)je.set(se[j],pe[j]);let $e=-1;for(let j of oe){let W=je.get(j);if(!W)continue;let ce=ae.indexOf(W);if(ce<$e)return!0;$e=ce}for(let j=0;j<se.length;j++)if(v(se[j],pe[j],x))return!0;for(let[j,W]of Me)if(v(j,W,x))return!0;return!1}function v(C,D,x){if(C.tagName!==D.tagName)return f(C,D,x);let L=i(C,D),_=[];if(R(C,D,_))return f(C,D,x);if(L.length){if(!o(C)&&!ue(D,s(),w))return!0;x.push({type:"attrs",el:C,names:L,base:D})}return x.push(..._),!1}let O=[],P=i(r,p);P.length&&O.push({type:"attrs",el:r,names:P});let B=(C,D)=>Array.from(C.children).find(x=>x.tagName===D)||null,F=B(r,"HEAD"),Y=B(p,"HEAD");if(F&&Y){let C=[];v(F,Y,C),C.length&&O.push({type:"head",el:F})}else(F||Y)&&F&&O.push({type:"head",el:F});let Z=B(r,"BODY"),z=B(p,"BODY");return Z&&z?v(Z,z,O):Z&&O.push({type:"subtree",el:Z,base:null}),{entries:O}}function tt(r,p,h={}){let N=h.tiers&&h.tiers.length?h.tiers:Ce,A=r.documentElement,w=[],a=0,c=v=>({ok:!1,placed:w,held:v,skippedAttrs:a});if(!A)return c(null);function l(v){let O=[v,...v.querySelectorAll("*")];return he(O,N)}let s=l(A),o=new Map,f=v=>{let O=v.getRootNode(),P=o.get(O);if(!P){let B=O.nodeType===9?O.documentElement:O;P=l(B),o.set(O,P)}return P};function i(v){if(!v.parentElement&&v.tagName==="HTML")return A;if(v.parentElement&&!v.parentElement.parentElement&&v.parentElement.tagName==="HTML"){if(v.tagName==="BODY")return r.body||null;if(v.tagName==="HEAD")return r.head||null}return null}function g(v){let O=i(v);return O||Le(v,f(v),s,N)}function m(v){if(!v)return null;let O=g(v);return O&&O.isConnected?O:null}function T(v){for(let O=0;O<N.length;O++){let P=N[O](v);P!=null&&P!==""&&s[O].set(P,v)}}for(let v of p){if(v.type!=="deletion")continue;let O=g(v.el);O&&O!==A&&O.remove()}let R=p.filter(v=>v.type!=="deletion").sort((v,O)=>v.el===O.el?0:v.el.compareDocumentPosition(O.el)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1);for(let v of R){if(v.type==="head"){let z=r.importNode(v.el,!0);r.head?r.head.replaceWith(z):A.insertBefore(z,A.firstChild),w.push({entry:v,imported:z});continue}if(v.type==="attrs"){let z=m(v.el)||m(v.base);if(!z){a++;continue}for(let C of v.names)v.el.hasAttribute(C)?z.setAttribute(C,v.el.getAttribute(C)):z.removeAttribute(C);continue}let O=v.el;if(i(O))return c(v);let P=m(O)||m(v.base);if(P){let z=r.importNode(O,!0);P.replaceWith(z),T(z),w.push({entry:v,imported:z});continue}if(v.base!=null&&!ue(v.base,f(v.base),N)||!ue(O,f(O),N))return c(v);let B=O.parentElement;if(!B)return c(v);let F=m(B);if(!F)return c(v);let Y=null;for(let z=O.previousElementSibling;z;z=z.previousElementSibling){let C=m(z);if(C&&C.parentNode===F){Y=C;break}}let Z=r.importNode(O,!0);if(Y)F.insertBefore(Z,Y.nextSibling);else{let z=Array.prototype.indexOf.call(B.children,O);F.insertBefore(Z,F.children[z]||null)}T(Z),w.push({entry:v,imported:Z})}return{ok:!0,placed:w,held:null,skippedAttrs:a}}return{morph:U,defaults:E,findChangedRoots:et,spliceProtected:tt,mergeJson:Se,mergeScriptText:ve,parseJsonRelaxed:ge,parseRulesRelaxed:Ee}})();var xt=fe.morph,Ct=fe.defaults,Lt=fe.findChangedRoots,Rt=fe.spliceProtected;var Bt=fe;return at(Ht);})();
1
+ var HyperMorph=(()=>{var we=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var st=Object.prototype.hasOwnProperty;var it=(e,t)=>{for(var n in t)we(e,n,{get:t[n],enumerable:!0})},ot=(e,t,n,g)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of rt(t))!st.call(e,u)&&u!==n&&we(e,u,{get:()=>t[u],enumerable:!(g=nt(t,u))||g.enumerable});return e};var at=e=>ot(we({},"__esModule",{value:!0}),e);var Ht={};it(Ht,{HyperMorph:()=>de,default:()=>Bt,defaults:()=>Ct,findChangedRoots:()=>Lt,mergeJson:()=>ve,mergeScriptText:()=>Me,morph:()=>xt,parseJsonRelaxed:()=>me,parseRulesRelaxed:()=>Ie,spliceProtected:()=>Rt});var Pe={includeClasses:!0,includeAttributes:["href","src","name","type","role","aria-label","alt","title"],excludeAttributePrefixes:["data-morph-","data-hyper-","data-im-"],textHintLength:64,excludeIds:!0,maxPathDepth:4,landmarks:["HEADER","NAV","MAIN","ASIDE","FOOTER","SECTION","ARTICLE"],weights:{signature:100,pathSegment:10,textMatch:20,textMismatch:25,uniqueCandidate:50,positionPenalty:1,maxDriftPenalty:19,slotMatch:30},minConfidence:101,maxScoredCandidates:16};function ut(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return Math.abs(t).toString(36)}function ct(e){if(e.classList&&e.classList.length>0)return Array.from(e.classList).sort().join(" ");let t=e.getAttribute?.("class");return t?t.split(/\s+/).filter(Boolean).sort().join(" "):""}function lt(e,t){let n=[];for(let g of e.attributes||[]){let u=g.name;u==="id"||u==="class"||t.excludeAttributePrefixes.some(y=>u.startsWith(y))||t.includeAttributes.includes(u)&&n.push(`${u}=${g.value}`)}return n.sort().join("|")}function ft(e,t){return(e.textContent||"").replace(/\s+/g," ").trim().slice(0,t.textHintLength)}function dt(e,t){let n=[e.tagName];return t.includeClasses&&n.push(ct(e)),n.push(lt(e,t)),ut(n.join("|"))}function ht(e){let t=e.tagName,n=1,g=e.previousElementSibling;for(;g;)g.tagName===t&&n++,g=g.previousElementSibling;return n}function pt(e,t){return e.getAttribute?.("id")||e.getAttribute?.("role")?!0:t.landmarks.includes(e.tagName)}function gt(e){let t=e.getAttribute?.("id");if(t)return`#${t}`;let n=e.getAttribute?.("role");return n?`@${n}`:e.tagName}function mt(e,t){let n=[],g=e;for(;g&&g.tagName&&n.length<t.maxPathDepth;){let u=`${g.tagName}:${ht(g)}`;if(n.unshift(u),g!==e&&pt(g,t)){n.unshift(gt(g));break}g=g.parentElement}return n}function yt(e,t){let n=0,g=e.length-1,u=t.length-1;for(;g>=0&&u>=0&&e[g]===t[u];)n++,g--,u--;return n}function X(e,t,n){if(n.has(e))return n.get(e);let g={signature:dt(e,t),path:mt(e,t),textHint:ft(e,t)};return n.set(e,g),g}function qe(e,t,n,g){if(g.has(e))return g.get(e);let u=new Map,y=e.querySelectorAll("*"),S=0;for(let d of y){let M=X(d,t,n);M.domIndex=S++,!t.shouldIgnore?.(d)&&(u.has(M.signature)||u.set(M.signature,[]),u.get(M.signature).push(d))}return g.set(e,u),u}function bt(e,t,n){n.delete(e),t.delete(e);let g=e.querySelectorAll("*");for(let u of g)t.delete(u)}function Te(e,t,n,g,u){let y=X(e,n,g),S=X(t,n,g),d=n.weights,M={},P=0;if(y.signature!==S.signature)return{score:0,breakdown:{rejected:"signature mismatch"}};P+=d.signature,M.signature=d.signature;let B=yt(y.path,S.path)*d.pathSegment;P+=B,M.path=B;let I=!0;if(y.textHint&&S.textHint?y.textHint===S.textHint?(P+=d.textMatch,M.text=d.textMatch):(P-=d.textMismatch,M.text=-d.textMismatch,I=!1):y.textHint!==S.textHint&&(P-=d.textMismatch,M.text=-d.textMismatch,I=!1),u.candidateCount===1&&I&&(P+=d.uniqueCandidate,M.unique=d.uniqueCandidate),typeof y.domIndex=="number"&&typeof S.domIndex=="number"){let k=Math.abs(y.domIndex-S.domIndex),E=Math.min(k*d.positionPenalty,d.maxDriftPenalty);P-=E,M.drift=-E}return{score:P,breakdown:M}}function De(e,t,n,g,u){if(n.excludeIds&&e.getAttribute("id"))return null;let y=qe(t,n,g,u),S=X(e,n,g);if(typeof S.domIndex!="number"){let I=0,k=e.previousElementSibling;for(;k;)I++,k=k.previousElementSibling;S.domIndex=I}let d=y.get(S.signature)||[],M=n.excludeIds?d.filter(I=>!I.getAttribute("id")):d;if(M.length===0)return null;let P=null,q=0,B=null;for(let I of M){let{score:k,breakdown:E}=Te(e,I,n,g,{candidateCount:M.length});k>q&&(q=k,P=I,B=E)}return q<n.minConfidence?null:{element:P,confidence:q,breakdown:B}}function At(e,t,n,g){let u=[],y=n.weights.signature+n.weights.slotMatch,S={slot:y};function d(B){if(B.children)return B.children;let I=B.childNodes;if(!I)return[];let k=[];for(let E=0;E<I.length;E++)I[E].nodeType===1&&k.push(I[E]);return k}function M(B,I){let k=d(B),E=d(I);if(k.length===E.length)for(let U=0;U<k.length;U++){let J=k[U],W=E[U];if(n.shouldIgnore?.(J)||n.shouldIgnore?.(W)||n.excludeIds&&(J.getAttribute("id")||W.getAttribute("id"))||J.tagName!==W.tagName)continue;let Q=X(J,n,g).signature,ee=X(W,n,g).signature;Q!==ee&&u.push({newEl:J,oldEl:W,score:y,breakdown:S}),M(J,W)}}function P(B,I){for(;;){if(B.tagName===I.tagName)return[B,I];let k=d(B);if(!B.tagName&&k.length===1){B=k[0];continue}let E=d(I);if(E.length===1&&E[0].tagName===B.tagName){I=E[0];continue}return null}}let q=P(e,t);return q&&M(q[0],q[1]),u}function ze(e,t,n,g,u){let y=t.querySelectorAll("*"),S=qe(e,n,g,u),d=0;for(let k of y){let E=X(k,n,g);E.domIndex=d++}let M=[],P=new Map;function q(k,E,U){let J=new Set;if(k.textHint){let Z=P.get(k.signature);if(!Z){Z=new Map;for(let re of E){let be=X(re,n,g).textHint,se=Z.get(be);se||(se=[],Z.set(be,se)),se.push(re)}P.set(k.signature,Z)}let he=Z.get(k.textHint);if(he)for(let re=0;re<he.length&&re<U;re++)J.add(he[re])}let W=0,Q=E.length;for(;W<Q;){let Z=W+Q>>1;X(E[Z],n,g).domIndex<k.domIndex?W=Z+1:Q=Z}let ee=Math.max(0,Math.min(W-(U>>1),E.length-U)),ne=Math.min(ee+U,E.length);for(let Z=ee;Z<ne;Z++)J.add(E[Z]);return[...J]}for(let k of y){if(n.shouldIgnore?.(k)||n.excludeIds&&k.getAttribute("id"))continue;let E=X(k,n,g),U=S.get(E.signature)||[],J=n.excludeIds?U.filter(ee=>!ee.getAttribute("id")):U,W=n.maxScoredCandidates,Q=W&&J.length>W?q(E,J,W):J;for(let ee of Q){let{score:ne,breakdown:Z}=Te(k,ee,n,g,{candidateCount:J.length});ne>=n.minConfidence&&M.push({newEl:k,oldEl:ee,score:ne,breakdown:Z})}}if(n.weights.slotMatch>0){let k=At(t,e,n,g);for(let E of k)M.push(E)}M.sort((k,E)=>E.score-k.score);let B=new Map,I=new Set;for(let{newEl:k,oldEl:E}of M)B.has(k)||I.has(E)||(B.set(k,E),I.add(E));return B}function _e(e,t,n,g){let u=X(e,n,g),y=X(t,n,g),{score:S,breakdown:d}=Te(e,t,n,g,{candidateCount:1});return{matches:S>=n.minConfidence,score:S,breakdown:d,newMeta:{signature:u.signature,path:u.path,textHint:u.textHint},oldMeta:{signature:y.signature,path:y.path,textHint:y.textHint}}}function Fe(e={}){let t={...Pe,...e,weights:{...Pe.weights,...e.weights}},n=new WeakMap,g=new WeakMap;return{findMatch:(u,y)=>De(u,y,t,n,g),computeMatches:(u,y)=>ze(u,y,t,n,g),explain:(u,y)=>_e(u,y,t,n),invalidate:u=>bt(u,n,g),session:()=>{let u=new WeakMap,y=new WeakMap;return{findMatch:(S,d)=>De(S,d,t,u,y),computeMatches:(S,d)=>ze(S,d,t,u,y),explain:(S,d)=>_e(S,d,t,u)}},getConfig:()=>({...t})}}function Ee(e,t){for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(e[t]==="/"&&e[t+1]==="/"){for(;t<e.length&&e[t]!==`
2
+ `;)t++;continue}if(e[t]==="/"&&e[t+1]==="*"){let n=e.indexOf("*/",t+2);if(n===-1)return e.length;t=n+2;continue}return t}}function Ve(e){return e.replace(/\\'/g,"'").replace(/(\\*)"/g,(t,n)=>n.length%2===0?n+'\\"':t)}var St=/^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$/,vt=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function me(e){try{return JSON.parse(e)}catch{return JSON.parse(Mt(e))}}function Mt(e){let t="",n=0,g=(u,y)=>{throw new Error(`Invalid relaxed JSON: ${u} at position ${y}`)};for(;n<e.length&&(n=Ee(e,n),!(n>=e.length));){let u=e[n];if("{}[]:".includes(u)){t+=u,n++;continue}if(u===","){let d=Ee(e,n+1);if(e[d]==="}"||e[d]==="]"){n++;continue}t+=u,n++;continue}if(u==='"'||u==="'"){let d=n+1;for(;d<e.length&&e[d]!==u;)e[d]==="\\"&&d++,d++;d>=e.length&&g("unterminated string",n);let M=e.slice(n+1,d);u==="'"&&(M=Ve(M)),t+='"'+M+'"',n=d+1;continue}let y=n;for(;y<e.length&&/[A-Za-z0-9_$.+\-]/.test(e[y]);)y++;y===n&&g("unexpected character "+JSON.stringify(u),n);let S=e.slice(n,y);if(S==="true"||S==="false"||S==="null"||St.test(S)){t+=S,n=y;continue}if(vt.test(S)){if(e[Ee(e,y)]===":"){t+='"'+S+'"',n=y;continue}g("unquoted value "+JSON.stringify(S),n)}g("invalid token "+JSON.stringify(S),n)}return t}function Ie(e){try{return JSON.parse(e)}catch{}let t={BRACE_OPEN:"{",BRACE_CLOSE:"}",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",COLON:":",COMMA:",",STRING:"STRING",SELECTOR:"SELECTOR",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",BOOLEAN:"BOOLEAN"};function n(u){let y=[],S=0;for(;S<u.length;){let d=u[S];if(/\s/.test(d)){S++;continue}if("{}".includes(d)){y.push({type:d,value:d}),S++;continue}if(d==="["){let B=!1,I=S+1;for(;I<u.length&&/\s/.test(u[I]);)I++;if(I<u.length&&/[a-zA-Z_]/.test(u[I])&&(B=!0),!B){y.push({type:d,value:d}),S++;continue}}if(d==="]"){y.push({type:d,value:d}),S++;continue}if(d===":"){y.push({type:t.COLON,value:d}),S++;continue}if(d===","){y.push({type:t.COMMA,value:d}),S++;continue}if(d==='"'||d==="'"){let B=d,I=S+1;for(;I<u.length&&u[I]!==B;)u[I]==="\\"&&I++,I++;y.push({type:t.STRING,value:u.substring(S+1,I),quoted:!0,sourceQuote:B}),S=I+1;continue}let M=S,P;for(;M<u.length&&!/[{},]/.test(u[M]);)if(u[M]===":"){let B=[":first",":last",":nth-child",":nth-of-type",":first-child",":last-child",":first-of-type",":last-of-type",":only-child",":only-of-type",":hover",":focus",":active",":visited",":disabled",":enabled",":checked",":empty",":root",":target",":not",":before",":after",":nth-last-child",":nth-last-of-type"],I=!1;for(let k of B){let E=k.substring(1);if(u.substring(M+1,M+1+E.length)===E){I=!0,M+=E.length;break}}if(!I)break}else if(u[M]==="["){for(M++;M<u.length&&u[M]!=="]";){if(u[M]==='"'||u[M]==="'"){let B=u[M];for(M++;M<u.length&&u[M]!==B;)u[M]==="\\"&&M++,M++}M++}M<u.length&&u[M]==="]"&&M++}else M++;P=u.substring(S,M);let q=t.IDENTIFIER;/^-?\d+(\.\d+)?$/.test(P)?q=t.NUMBER:P==="true"||P==="false"||P==="null"?q=t.BOOLEAN:/^[.#@\[]|[.#@\[]| /.test(P)&&(q=t.SELECTOR),y.push({type:q,value:P,quoted:!1}),S=M}return y}function g(u){let y="";for(let S=0;S<u.length;S++){let d=u[S];if("{}".includes(d.type)||"[]".includes(d.type)){y+=d.value;continue}if(d.type===t.COLON){y+=d.value;continue}if(d.type===t.COMMA){let M=u[S+1];if(M&&(M.type==="}"||M.type==="]"))continue;y+=d.value;continue}if(d.type===t.STRING){let M=d.value;d.sourceQuote==="'"&&(M=Ve(M)),y+=`"${M}"`;continue}if(d.type===t.NUMBER||d.type===t.BOOLEAN){y+=d.value;continue}y+=`"${d.value}"`}return y}try{let u=n(e),y=g(u);return JSON.parse(y)}catch(u){throw new Error("Invalid extraction rules syntax: "+u.message)}}var F=Symbol("hyper-morph-json-merge:missing"),Ke=["id","_id","uuid","key","slug","code","name"];function fe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ye(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Nt(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function oe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!oe(e[n],t[n]))return!1;return!0}if(fe(e)&&fe(t)){let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let g of n)if(!ye(t,g)||!oe(e[g],t[g]))return!1;return!0}return!1}function Ue(e,t,n,g){return oe(t,n)?t:oe(t,e)?n:oe(n,e)?t:fe(t)&&fe(n)?kt(fe(e)?e:{},t,n,g):Array.isArray(t)&&Array.isArray(n)?It(Array.isArray(e)?e:[],t,n,g):n}function Je(e,t,n,g){return t===F&&n===F?F:t===F?e===F?n:oe(n,e)?F:n:n===F?e===F?t:F:Ue(e,t,n,g)}function kt(e,t,n,g){let u={},y=new Set([...Object.keys(e),...Object.keys(t),...Object.keys(n)]);for(let S of y){let d=Je(ye(e,S)?e[S]:F,ye(t,S)?t[S]:F,ye(n,S)?n[S]:F,g);d!==F&&Nt(u,S,d)}return u}function wt(e){return e===null||typeof e!="object"}function Se(e){return typeof e+":"+String(e)}function Tt(e,t){for(let n of t){let g=new Set;for(let u of n){if(!ye(u,e))return!1;let y=u[e];if(typeof y!="string"&&typeof y!="number")return!1;let S=Se(y);if(g.has(S))return!1;g.add(S)}}return!0}function Et(e,t,n,g){let u=[e,t,n],y=!0;for(let S of u)for(let d of S)fe(d)||(y=!1);if(y){for(let S of g.keyCandidates)if(Tt(S,u))return{kind:"keyed",field:S};return null}for(let S of u){let d=new Set;for(let M of S){if(!wt(M))return null;let P=Se(M);if(d.has(P))return null;d.add(P)}}return{kind:"self"}}function It(e,t,n,g){let u=Et(e,t,n,g);if(!u)return n;let y=u.kind==="self"?Se:k=>Se(k[u.field]),S=k=>{let E=new Map;for(let U of k)E.set(y(U),U);return E},d=S(e),M=S(t),P=S(n),q=new Map,B=new Set([...d.keys(),...M.keys(),...P.keys()]);for(let k of B){let E=Je(d.has(k)?d.get(k):F,M.has(k)?M.get(k):F,P.has(k)?P.get(k):F,g);E!==F&&q.set(k,E)}let I=[];for(let k of n){let E=y(k);q.has(E)&&I.push(E)}for(let k=0;k<t.length;k++){let E=y(t[k]);if(!q.has(E)||I.includes(E))continue;let U=0;for(let J=k-1;J>=0;J--){let W=I.indexOf(y(t[J]));if(W!==-1){U=W+1;break}}I.splice(U,0,E)}return I.map(k=>q.get(k))}function ve(e,t,n,g={}){let u=g.keyCandidates?[...g.keyCandidates,...Ke]:Ke;return Ue(e===void 0?F:e,t,n,{keyCandidates:u})}function Me(e,t,n,g={}){let u=g.parse||me,y=[],S=(B,I)=>{if(typeof B!="string")return F;try{return u(B)}catch(k){return y.push(`${I} side is not valid JSON (${k.message})`),F}},d=S(t,"local"),M=S(n,"remote");if(d===F)return{text:n,warnings:y};if(M===F)return{text:t,warnings:y};let P=S(e,"base"),q=ve(P===F?void 0:P,d,M,g);return oe(q,M)?{text:n,warnings:y}:oe(q,d)?{text:t,warnings:y}:{text:JSON.stringify(q,null,2),warnings:y}}var Ot=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),_t=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),qt=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui"]);function We(e){let t=Ot[e];if(!t)throw new Error(`Unknown region capability: ${e}`);return[...t.tokens,...t.bundles].flatMap(n=>[`[clay~="${n}"]`,`[${n}]`]).join(", ")}var de=(function(){"use strict";let e=()=>{},t='[editor-ui],[clay~="editor-ui"],[save-ignore],[snapshot-remove],[no-snapshot],[no-save],[save-remove],[freeze],[save-freeze],[clay~="no-save"],[clay~="no-snapshot"],[clay~="freeze"]',n=`${We("history")},[no-undo],[clay~="no-undo"]`;function g(r){if(r?.nodeType!==1)return!1;if(r.matches(t))return!0;if(r.tagName==="LINK"||r.tagName==="SCRIPT"){let p=r.getAttribute("src")||r.getAttribute("href")||"";if(p.startsWith("chrome-extension://")||p.startsWith("moz-extension://")||p.startsWith("safari-web-extension://"))return!0}return!1}function u(r){return r?.nodeType!==1?!1:r.closest(t)?!0:g(r)}function y(r,p,h){if(h){let w=h.identityOf(r);if(w&&!h.disabled.has(w.key))return"hm-merge:"+w.key}if(p!=="smart")return r.outerHTML;let N=r.getAttribute("src"),b=r.getAttribute("type")||"text/javascript";if(N)try{let w=new URL(N,window.location.href);return`ext:${b}:${w.origin}${w.pathname}${w.search}`}catch{return`ext:${b}:${N}`}else{let w=r.textContent.trim(),a=5381;for(let c=0;c<w.length;c++)a=(a<<5)+a^w.charCodeAt(c);return`inline:${b}:${Math.abs(a).toString(36)}`}}let S="http://www.w3.org/1999/xhtml";function d(r){return r?.nodeType===1&&r.tagName==="SCRIPT"&&r.namespaceURI===S}function M(r){let p=document.createElement("div");p.innerHTML="<script><\/script>";let h=p.firstChild;for(let N of r.attributes)h.setAttribute(N.name,N.value);return h.textContent=r.textContent,h}function P(r){if(d(r))return M(r);if(r?.nodeType===1)for(let p of r.querySelectorAll("script"))d(p)&&p.replaceWith(M(p));return r}function q(r){let p=(r.getAttribute("type")||"").split(";")[0].trim().toLowerCase();return p==="application/json"||p.endsWith("+json")}let B={match:r=>r.hasAttribute("merge"),identity:r=>r.getAttribute("merge")};function I(r,p,h){if(h.merge===!1)return null;let N=[B,...h.mergeTags||[]],b=new WeakMap,w=i=>{if(b.has(i))return b.get(i);let m=null;if(d(i)&&!i.getAttribute("src")&&!u(i)){let v=i;for(let T=0;T<N.length;T++)if(N[T].match(v)){if(!q(v))console.warn("[hyper-morph] merge ignored: script type is not JSON",v);else{let L=N[T].identity(v);L!=null&&L!==""&&(m={key:T+":"+L,raw:L,recognizer:N[T]})}break}}return b.set(i,m),m},a=new Set,c=i=>{let m=new Map,v=T=>{let L=w(T);L&&(m.has(L.key)?(a.add(L.key),console.warn(`[hyper-morph] merge disabled for duplicate identity "${L.raw}"`)):m.set(L.key,T))};d(i)&&v(i);for(let T of i.querySelectorAll("script"))v(T);return m},l=c(r),s=c(p.__hyperMorphRoot||p);if(l.size===0&&s.size===0)return null;let o=null;return{identityOf:w,disabled:a,oldByKey:l,newByKey:s,baseTexts:()=>{if(o)return o;o=new Map;let i=h.mergeBase;if(!i)return o;let m;typeof i=="string"?m=new DOMParser().parseFromString(i,"text/html").documentElement:i?.nodeType===9?m=i.documentElement:m=i;let v=T=>{let L=w(T);L&&!o.has(L.key)&&o.set(L.key,T.textContent)};d(m)&&v(m);for(let T of m.querySelectorAll("script"))v(T);return o}}}function k(r,p,h){let N=r.merge;if(!N)return!1;let b=N.identityOf(p);if(!b||N.disabled.has(b.key))return!1;let w=N.identityOf(h);if(!w||w.key!==b.key)return!1;let a=p,c=h,l=c.getAttribute("merge-key")||a.getAttribute("merge-key"),{text:s,warnings:o}=Me(N.baseTexts().get(b.key),a.textContent,c.textContent,{parse:b.recognizer.parse,keyCandidates:l?l.split(/[\s,]+/).filter(Boolean):void 0});for(let f of o)console.warn(`[hyper-morph] merge "${b.raw}": ${f}`);return a.textContent!==s&&(a.textContent=s),!0}let E={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:r=>r.getAttribute("im-preserve")==="true",shouldReAppend:r=>r.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},scripts:{handle:!0,matchMode:"outerHTML",shouldPreserve:r=>r.getAttribute("im-preserve")==="true",shouldReAppend:r=>r.getAttribute("im-re-append")==="true",shouldRemove:e,afterScriptsHandled:e},restoreFocus:!0},U={computeMatches(r,p,h=u){let{computeMatches:N}=Fe({shouldIgnore:h}).session();return N(r,p)}};function J(r,p,h={}){r=Xe(r);let N=xe(p),b=Qe(r,N,h),w=b.scripts.handle?new Set(Array.from(r.querySelectorAll("script")).map(s=>y(s,b.scripts.matchMode,b.merge))):null,a=re(b),c;try{c=Ge(b,r,N,s=>s.morphStyle==="innerHTML"?(se(s,r,N),Array.from(r.childNodes)):he(s,r,N))}catch(s){throw Q(b),s}let l=s=>{a&&be(b,a),W(b);let o=w?Ze(s,w,b):[];return o.length>0?Promise.all(o).then(()=>s):s};if(c instanceof Promise)return c.then(s=>{try{return l(s)}catch(o){throw Q(b),o}},s=>{throw Q(b),s});try{return l(c)}catch(s){throw Q(b),s}}function W(r){let p=r.pantry;if(p){for(let h of Array.from(p.childNodes))r.callbacks.beforeNodeRemoved(h)!==!1&&r.callbacks.afterNodeRemoved(h);for(let h of Array.from(p.childNodes))p.removeChild(h);p.remove(),r.pantry=null,r.stagedNodes.clear()}}function Q(r){let p=r.pantry;if(!p)return;let h=Array.from(r.stagedNodes.entries()).reverse();for(let[N,b]of h){if(!p.contains(N))continue;let w=b.nextSibling?.parentNode===b.parent?b.nextSibling:null;try{ne(b.parent,N,w)}catch{}}for(let N of Array.from(p.childNodes))p.removeChild(N);p.remove(),r.pantry=null,r.stagedNodes.clear()}function ee(r){if(r.pantry)return r.pantry;let p=r.target.ownerDocument,h=p.createElement("div");return h.hidden=!0,h.setAttribute("mutations-ignore",""),p.body.insertAdjacentElement("afterend",h),r.pantry=h,h}function ne(r,p,h){if(r.moveBefore)try{r.moveBefore(p,h)}catch{r.insertBefore(p,h)}else r.insertBefore(p,h)}function Z(r,p){!r.stagedNodes.has(p)&&p.parentNode&&r.stagedNodes.set(p,{parent:p.parentNode,nextSibling:p.nextSibling}),ne(ee(r),p,null)}function he(r,p,h){let N=xe(p);return se(r,N,h,p,p.nextSibling),Array.from(N.childNodes)}function re(r){if(!r.config.restoreFocus)return null;let p=document.activeElement;if(!(p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement))return null;let{id:h,selectionStart:N,selectionEnd:b}=p;return{element:p,id:h,selectionStart:N,selectionEnd:b}}function be(r,p){let h=p.element;if(p.id&&p.id!==document.activeElement?.getAttribute("id")&&(h=r.target.querySelector(`[id="${CSS.escape(p.id)}"]`),h?.focus()),h&&!h.selectionEnd&&p.selectionEnd!=null)try{h.setSelectionRange(p.selectionStart,p.selectionEnd)}catch{}}let se=(function(){function r(s,o,f,i=null,m=null){o?.tagName==="TEMPLATE"&&f?.tagName==="TEMPLATE"&&(o=o.content,f=f.content),i||=o.firstChild;for(let v of f.childNodes){if(s.shouldIgnore(v))continue;if(i&&i!=m){let L=N(s,v,i,m);if(L){L!==i&&w(s,i,L),Ae(L,v,s),i=L.nextSibling;continue}}if(v?.nodeType===1){let L=v.getAttribute("id");if(s.persistentIds.has(L)){let A=a(o,L,i,s);Ae(A,v,s),i=A.nextSibling;continue}if(!s.idMap.has(v)){let A=s.hyperMatches.get(v);if(A&&!s.idMap.has(A)&&!l(A,o)){ne(o,A,i),Ae(A,v,s),i=A.nextSibling;continue}}}let T=p(o,v,i,s);T&&(i=T.nextSibling)}for(;i&&i!=m;){let v=i;i=i.nextSibling,s.shouldIgnore(v)||b(s,v)}}function p(s,o,f,i){if(i.callbacks.beforeNodeAdded(o)===!1)return null;let m=s.ownerDocument||s.realParentNode?.ownerDocument||i.target.ownerDocument;if(i.idMap.has(o)){let v=o,T=m.createElementNS(v.namespaceURI,v.localName);return s.insertBefore(T,f),Ae(T,o,i),i.callbacks.afterNodeAdded(T),T}else{let v=P(h(o,m,i));return v?(s.insertBefore(v,f),i.callbacks.afterNodeAdded(v),v):null}}function h(s,o,f){if(f.shouldIgnore(s))return null;let i=o.importNode(s,!1),m=s.nodeType===1&&s.tagName==="TEMPLATE"?s.content:s,v=i.nodeType===1&&i.tagName==="TEMPLATE"?i.content:i;for(let T of Array.from(m.childNodes||[])){let L=h(T,o,f);L&&v.appendChild(L)}return i}let N=(function(){function s(i,m,v,T){let L=m?.nodeType===1&&!i.idMap.has(m)?i.hyperMatches.get(m):null,A=null,x=m.nextSibling,V=0,C=v;for(;C&&C!=T;){if(i.shouldIgnore(C)){C=C.nextSibling;continue}if(f(C,m)){if(o(i,C,m)||C===L&&!i.idMap.has(C))return C;if(A===null){let z=C?.nodeType===1&&i.hyperMatchedOldElements.has(C);!i.idMap.has(C)&&!z&&(A=C)}}if(A===null&&x&&f(C,x)&&(V++,x=x.nextSibling,V>=2&&(A=void 0)),i.activeElementAndParents.includes(C))break;C=C.nextSibling}return A||null}function o(i,m,v){let T=i.idMap.get(m),L=i.idMap.get(v);if(!L||!T)return!1;for(let A of T)if(L.has(A))return!0;return!1}function f(i,m){let v=i,T=m;return v.nodeType===T.nodeType&&v.tagName===T.tagName&&(!v.getAttribute?.("id")||v.getAttribute?.("id")===T.getAttribute?.("id"))}return s})();function b(s,o){let f=o?.nodeType===1&&s.hyperMatchedOldElements.has(o)&&!s.idMap.has(o);if(s.idMap.has(o)||f)Z(s,o);else{if(s.callbacks.beforeNodeRemoved(o)===!1)return;o.parentNode?.removeChild(o),s.callbacks.afterNodeRemoved(o)}}function w(s,o,f){let i=o;for(;i&&i!==f;){let m=i;i=i.nextSibling,s.shouldIgnore(m)||b(s,m)}return i}function a(s,o,f,i){let m=i.target.ownerDocument?.defaultView?.CSS?.escape?i.target.ownerDocument.defaultView.CSS.escape(o):String(o).replace(/["\\]/g,"\\$&"),v=i.target.getAttribute?.("id")===o&&i.target||i.target.querySelector(`[id="${m}"]`)||i.pantry?.querySelector(`[id="${m}"]`);return c(v,i),ne(s,v,f),v}function c(s,o){let f=s.getAttribute("id");for(;s=s.parentNode;){let i=o.idMap.get(s);i&&(i.delete(f),i.size||o.idMap.delete(s))}}function l(s,o){let f=o?.nodeType===1?o:o.realParentNode;return!!f&&s.contains(f)}return r})(),Ae=(function(){function r(a,c,l){return l.ignoreActive&&a===document.activeElement?null:(l.callbacks.beforeNodeMorphed(a,c)===!1||(a?.tagName==="HEAD"&&l.head.ignore||(a?.tagName==="HEAD"&&l.head.style!=="morph"?Oe(a,c,l):(p(a,c,l),k(l,a,c)||w(a,l)||se(l,a,c))),l.callbacks.afterNodeMorphed(a,c)),a)}function p(a,c,l){let s=c.nodeType;if(s===1){let o=a,f=c,i=o.attributes,m=f.attributes;for(let v of m)b(v.name,o,"update",l)||o.getAttribute(v.name)!==v.value&&o.setAttribute(v.name,v.value);for(let v=i.length-1;0<=v;v--){let T=i[v];if(T&&!f.hasAttribute(T.name)){if(b(T.name,o,"remove",l))continue;o.removeAttribute(T.name)}}w(o,l)||h(o,f,l)}(s===8||s===3)&&a.nodeValue!==c.nodeValue&&(a.nodeValue=c.nodeValue)}function h(a,c,l){if(a.tagName==="INPUT"&&c.tagName==="INPUT"&&c.type!=="file"){let s=c.value,o=a.value;N(a,c,"checked",l),N(a,c,"disabled",l),l.formStateSync==="property"&&a.indeterminate!==c.indeterminate&&(a.indeterminate=c.indeterminate),l.formStateSync==="property"?o!==s&&(b("value",a,"update",l)||(a.value=s)):c.hasAttribute("value")?o!==s&&(b("value",a,"update",l)||(a.setAttribute("value",s),a.value=s)):b("value",a,"remove",l)||(a.value="",a.removeAttribute("value"))}else if(a.tagName==="OPTION"&&c.tagName==="OPTION")N(a,c,"selected",l);else if(a.tagName==="TEXTAREA"&&c.tagName==="TEXTAREA"){let s=c.value,o=a.value;if(b("value",a,"update",l)||(s!==o&&(a.value=s),l.formStateSync==="property"))return;a.firstChild&&a.firstChild.nodeValue!==s&&(a.firstChild.nodeValue=s)}}function N(a,c,l,s){let o=c[l],f=a[l];if(o!==f){let i=b(l,a,"update",s);if(i||(a[l]=c[l]),s.formStateSync==="property")return;o?i||a.setAttribute(l,""):b(l,a,"remove",s)||a.removeAttribute(l)}}function b(a,c,l,s){return a==="value"&&s.ignoreActiveValue&&c===document.activeElement?!0:s.callbacks.beforeAttributeUpdated(a,c,l)===!1}function w(a,c){return!!c.ignoreActiveValue&&a===document.activeElement&&a!==document.body}return r})();function Ge(r,p,h,N){if(r.head.block){let b=p.querySelector("head"),w=h.querySelector("head");if(b&&w){let a=Oe(b,w,r);return Promise.all(a).then(()=>(r.head.block=!1,r.head.ignore=!0,N(r)))}}return N(r)}function Ye(r){return r.tagName==="SCRIPT"?!!r.getAttribute("src"):r.tagName==="LINK"?(r.getAttribute("rel")||"").toLowerCase().split(/\s+/).includes("stylesheet")&&!!r.getAttribute("href"):!1}function Oe(r,p,h){let N=[],b=[],w=[],a=[],c=h.scripts.matchMode,l=f=>{if(f.tagName==="SCRIPT")return y(f,c,h.merge);if(f.tagName==="LINK"&&c==="smart"){let i=f.getAttribute("href");if(i)try{let m=new URL(i,window.location.href);return`link:${f.getAttribute("rel")||""}:${m.origin}${m.pathname}${m.search}`}catch{}}return f.outerHTML},s=new Map;for(let f of p.children){if(h.shouldIgnore(f))continue;let i=l(f),m=s.get(i);m||(m=[],s.set(i,m)),m.push(f)}for(let f of r.children){let i=l(f),m=s.get(i),v=!!(m&&m.length),T=h.head.shouldReAppend(f),L=h.head.shouldPreserve(f);if(v||L)if(T)b.push(f);else{if(m&&m.length){let A=m.pop();m.length||s.delete(i),k(h,f,A)}w.push(f)}else h.head.style==="append"?T&&(b.push(f),a.push(f)):h.head.shouldRemove(f)!==!1&&!h.shouldIgnore(f)&&b.push(f)}for(let f of s.values())a.push(...f);let o=[];for(let f of a){let i=document.createRange().createContextualFragment(f.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(i)!==!1){if(i instanceof Element&&Ye(i)){let m,v=new Promise(function(T){m=T});i.addEventListener("load",function(){m()}),i.addEventListener("error",function(){m()}),o.push(v)}r.appendChild(i),h.callbacks.afterNodeAdded(i),N.push(i)}}for(let f of b)h.callbacks.beforeNodeRemoved(f)!==!1&&(r.removeChild(f),h.callbacks.afterNodeRemoved(f));return h.head.afterHeadMorphed(r,{added:N,kept:w,removed:b}),o}function Ze(r,p,h){if(!h.scripts.handle)return[];let N=[],b=[],w=[],a=[],c=h.scripts.matchMode,l=[];for(let o of r)if(o instanceof Element){d(o)&&l.push(o);for(let f of o.querySelectorAll("script"))d(f)&&l.push(f)}for(let o of l){if(o.closest("head")||h.shouldIgnore(o))continue;let f=y(o,c,h.merge),i=p.has(f),m=h.scripts.shouldPreserve(o),v=h.scripts.shouldReAppend(o);i||m?v?(b.push(o),a.push(o)):w.push(o):a.push(o)}let s=[];for(let o of a){if(h.callbacks.beforeNodeAdded(o)===!1)continue;let f=document.createElement("script");for(let i of o.attributes)f.setAttribute(i.name,i.value);if(f.textContent=o.textContent,f.src){let i,m=new Promise(function(v){i=v});f.addEventListener("load",function(){i()}),f.addEventListener("error",function(){i()}),s.push(m)}o.replaceWith(f),h.callbacks.afterNodeAdded(f),N.push(f)}return h.scripts.afterScriptsHandled(h.target,{added:N,kept:w,removed:b}),s}let Qe=(function(){function r(c,l,s){let o=s.policy==="history"?n:t,f=(C,z)=>{let K=C.closest(z);return K&&(c.contains(K)||l.contains(K))?K:null},i=s.policy==="raw"?()=>!1:C=>{if(C?.nodeType!==1)return!1;if(s.policy!=="history"&&(g(C)||f(C,t)))return!0;let z=f(C,o);return!(!z||s.policy==="history"&&z===c&&z.matches('[no-undo],[clay~="no-undo"]')&&!z.matches('[editor-ui],[clay~="editor-ui"]'))},{persistentIds:m,idMap:v}=w(c,l,i),T=U.computeMatches(c,l,i);if(typeof s.key=="function"){let C=new Map,z=new Set,K=R=>{let H=s.key(R);H!=null&&(C.has(H)?z.add(H):C.set(H,R))};c instanceof Element&&K(c);for(let R of c.querySelectorAll("*"))K(R);for(let R of z)C.delete(R);let G=new Map;for(let[R,H]of T)G.set(H,R);let _=l.__hyperMorphRoot||l,O=new Map,D=new Set,$=R=>{let H=s.key(R);H!=null&&(O.has(H)?D.add(H):O.set(H,R))};_ instanceof Element&&$(_);for(let R of _.querySelectorAll("*"))$(R);for(let R of D)O.delete(R);for(let[R,H]of O){let te=C.get(R);if(!te||te.tagName!==H.tagName)continue;let ae=G.get(te);ae&&ae!==H&&T.delete(ae);let ce=T.get(H);ce&&ce!==te&&G.delete(ce),T.set(H,te),G.set(te,H)}}let L=p(s),A=I(c,l,L.scripts);if(A){let C=new Map;for(let[z,K]of T)C.set(K,z);for(let[z,K]of A.newByKey){if(A.disabled.has(z))continue;let G=A.oldByKey.get(z);if(!G)continue;let _=C.get(G);_&&_!==K&&T.delete(_);let O=T.get(K);O&&O!==G&&C.delete(O),T.set(K,G),C.set(G,K)}}let x=new Set;for(let C of T.values())x.add(C);let V=L.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(V))throw new Error(`Do not understand how to morph style ${V}`);return{target:c,newContent:l,config:L,morphStyle:V,ignoreActive:L.ignoreActive,ignoreActiveValue:L.ignoreActiveValue,restoreFocus:L.restoreFocus,formStateSync:L.formStateSync||"attribute",idMap:v,persistentIds:m,hyperMatches:T,hyperMatchedOldElements:x,merge:A,pantry:null,stagedNodes:new Map,activeElementAndParents:h(c),callbacks:L.callbacks,head:L.head,scripts:L.scripts,shouldIgnore:i}}function p(c){let l=Object.assign({},E);return Object.assign(l,c),l.callbacks=Object.assign({},E.callbacks,c.callbacks),l.head=Object.assign({},E.head,c.head),l.scripts=Object.assign({},E.scripts,c.scripts),l}function h(c){let l=[],s=c.ownerDocument?.activeElement;if(s?.tagName!=="BODY"&&c.contains(s))for(;s&&(l.push(s),s!==c);)s=s.parentElement;return l}function N(c){let l=Array.from(c.querySelectorAll("[id]"));return c.getAttribute?.("id")&&l.push(c),l}function b(c,l,s,o){for(let f of o){let i=f.getAttribute("id");if(l.has(i)){let m=f;for(;m;){let v=c.get(m);if(v==null&&(v=new Set,c.set(m,v)),v.add(i),m===s)break;m=m.parentElement}}}}function w(c,l,s){let o=N(c).filter(T=>!s(T)),f=N(l).filter(T=>!s(T)),i=a(o,f),m=new Map;b(m,i,c,o);let v=l.__hyperMorphRoot||l;return b(m,i,v,f),{persistentIds:i,idMap:m}}function a(c,l){let s=new Set,o=new Map;for(let i of c){let m=i.getAttribute("id");o.has(m)?s.add(m):o.set(m,i.tagName)}let f=new Set;for(let i of l){let m=i.getAttribute("id");f.has(m)?s.add(m):o.get(m)===i.tagName&&f.add(m)}for(let i of s)f.delete(i);return f}return r})(),{normalizeElement:Xe,normalizeParent:xe}=(function(){let r=new WeakSet;function p(a){return a?.nodeType===9?a.documentElement:a}function h(a){if(a==null)return document.createElement("div");if(typeof a=="string")return h(w(a));if(r.has(a))return a;if(a&&typeof a=="object"&&"nodeType"in a){if(a.parentNode)return new N(a);{let c=a.ownerDocument.createElement("div");return c.append(a),c}}else{let l=[...a][0]?.ownerDocument?.createElement("div")||document.createElement("div");for(let s of[...a])l.append(s);return l}}class N{constructor(c){this.originalNode=c,this.realParentNode=c.parentNode,this.previousSibling=c.previousSibling,this.nextSibling=c.nextSibling}get childNodes(){let c=[],l=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;l&&l!=this.nextSibling;)c.push(l),l=l.nextSibling;return c}querySelectorAll(c){return this.childNodes.reduce((l,s)=>{if(s instanceof Element){s.matches(c)&&l.push(s);let o=s.querySelectorAll(c);for(let f=0;f<o.length;f++)l.push(o[f])}return l},[])}insertBefore(c,l){return this.realParentNode.insertBefore(c,l)}moveBefore(c,l){return this.realParentNode.moveBefore(c,l)}get __hyperMorphRoot(){return this.originalNode}}function b(a){let c=f=>`<${f}(?:\\s(?:[^>"']|"[^"]*"|'[^']*')*)?>`,l=a.replace(/<!--[\s\S]*?-->/g,"");for(let f of["script","style","textarea","title"])l=l.replace(new RegExp(`${c(f)}[\\s\\S]*?</${f}\\s*>`,"gi"),"");let s=new RegExp(`${c("svg")}[\\s\\S]*?</svg\\s*>`,"gi"),o;do o=l,l=l.replace(s,"");while(l!==o);return l}function w(a){let c=new DOMParser,l=b(a);if(l.match(/<\/html>/)||l.match(/<\/head>/)||l.match(/<\/body>/)){let s=c.parseFromString(a,"text/html");if(l.match(/<\/html>/))return r.add(s),s;{let o=s.firstChild;return o&&r.add(o),o}}else{let o=c.parseFromString("<body><template>"+a+"</template></body>","text/html").body.querySelector("template").content;return r.add(o),o}}return{normalizeElement:p,normalizeParent:h}})(),Ce=Symbol("hyper-morph-duplicate-key"),Le=[r=>r.getAttribute("data-id"),r=>r.getAttribute("id")];function pe(r,p){return p.map(h=>{let N=new Map;for(let b of r){if(b.nodeType!==1)continue;let w=h(b);w==null||w===""||N.set(w,N.has(w)?Ce:b)}return N})}function Re(r,p,h,N){for(let b=0;b<N.length;b++){let w=N[b](r);if(w==null||w===""||p[b].get(w)!==r)continue;let a=h[b].get(w);if(!(!a||a===Ce)&&a.tagName===r.tagName)return a}return null}function ue(r,p,h){for(let N=0;N<h.length;N++){let b=h[N](r);if(!(b==null||b==="")&&p[N].get(b)===r)return!0}return!1}function et(r,p,h={}){let N=h.skip||(()=>!1),b=h.ignoreAttr||(()=>!1),w=h.tiers&&h.tiers.length?h.tiers:Le,a=null;function c(){return a||(a=pe([r,...r.querySelectorAll("*")],w)),a}let l=null;function s(){return l||(l=pe([p,...p.querySelectorAll("*")],w)),l}function o(O){return!O.parentElement||!O.parentElement.parentElement}function f(O,D,$){return o(O)||ue(O,c(),w)?($.push({type:"subtree",el:O,base:D}),!1):!0}function i(O,D){let $=[];for(let R of O.attributes)b(O,R.name)||D.getAttribute(R.name)!==R.value&&$.push(R.name);for(let R of D.attributes)b(O,R.name)||O.hasAttribute(R.name)||$.push(R.name);return $}function m(O){let D=[],$=null,R=()=>{$!==null&&(D.push({nodeType:3,nodeValue:$}),$=null)};for(let H of O.childNodes){if(H.nodeType===3){$=($===null?"":$)+H.nodeValue;continue}H.nodeType===1&&N(H)||(R(),(H.nodeType===1||H.nodeType===8)&&D.push(H))}return R(),D}function v(O,D){if(O.nodeType!==D.nodeType)return!1;if(O.nodeType!==1)return!0;if(O.tagName!==D.tagName)return!1;for(let $ of w){let R=$(O),H=$(D);if(R!=null&&R!==""&&H!=null&&H!==""&&R!==H)return!1}return!0}function T(O){let D="";for(let $ of O)$.nodeType===3&&$.nodeValue.trim()!==""?D+="\0"+$.nodeValue:$.nodeType===8&&(D+=""+$.nodeValue);return D}function L(O,D,$){let R=m(O),H=m(D);if(R.length===H.length){let j=!0;for(let Y=0;Y<R.length;Y++)if(!v(R[Y],H[Y])){j=!1;break}if(j){for(let Y=0;Y<R.length;Y++){let le=R[Y];if(le.nodeType===1){if(A(le,H[Y],$))return!0}else if(le.nodeValue!==H[Y].nodeValue)return!0}return!1}}let te=R.filter(j=>j.nodeType===1),ae=H.filter(j=>j.nodeType===1);if(T(R)!==T(H))return!0;let ce=pe(te,w),Be=pe(ae,w),Ne=[],ke=new Set,He=[];for(let j of te){let Y=Re(j,ce,Be,w);Y&&!ke.has(Y)?(Ne.push([j,Y]),ke.add(Y)):He.push(j)}let ie=[];for(let j of He)ue(j,ce,w)?$.push({type:"subtree",el:j,base:null}):ie.push(j);let ge=[];for(let j of ae)ke.has(j)||(ue(j,Be,w)?$.push({type:"deletion",el:j}):ge.push(j));if(ie.length!==ge.length)return!0;for(let j=0;j<ie.length;j++)if(!v(ie[j],ge[j]))return!0;let je=new Map(Ne);for(let j=0;j<ie.length;j++)je.set(ie[j],ge[j]);let $e=-1;for(let j of te){let Y=je.get(j);if(!Y)continue;let le=ae.indexOf(Y);if(le<$e)return!0;$e=le}for(let j=0;j<ie.length;j++)if(A(ie[j],ge[j],$))return!0;for(let[j,Y]of Ne)if(A(j,Y,$))return!0;return!1}function A(O,D,$){if(O.tagName!==D.tagName)return f(O,D,$);let R=i(O,D),H=[];if(L(O,D,H))return f(O,D,$);if(R.length){if(!o(O)&&!ue(D,s(),w))return!0;$.push({type:"attrs",el:O,names:R,base:D})}return $.push(...H),!1}let x=[],V=i(r,p);V.length&&x.push({type:"attrs",el:r,names:V});let C=(O,D)=>Array.from(O.children).find($=>$.tagName===D)||null,z=C(r,"HEAD"),K=C(p,"HEAD");if(z&&K){let O=[];A(z,K,O),O.length&&x.push({type:"head",el:z})}else(z||K)&&z&&x.push({type:"head",el:z});let G=C(r,"BODY"),_=C(p,"BODY");return G&&_?A(G,_,x):G&&x.push({type:"subtree",el:G,base:null}),{entries:x}}function tt(r,p,h={}){let N=h.tiers&&h.tiers.length?h.tiers:Le,b=r.documentElement,w=[],a=0,c=A=>({ok:!1,placed:w,held:A,skippedAttrs:a});if(!b)return c(null);function l(A){let x=[A,...A.querySelectorAll("*")];return pe(x,N)}let s=l(b),o=new Map,f=A=>{let x=A.getRootNode(),V=o.get(x);if(!V){let C=x.nodeType===9?x.documentElement:x;V=l(C),o.set(x,V)}return V};function i(A){if(!A.parentElement&&A.tagName==="HTML")return b;if(A.parentElement&&!A.parentElement.parentElement&&A.parentElement.tagName==="HTML"){if(A.tagName==="BODY")return r.body||null;if(A.tagName==="HEAD")return r.head||null}return null}function m(A){let x=i(A);return x||Re(A,f(A),s,N)}function v(A){if(!A)return null;let x=m(A);return x&&x.isConnected?x:null}function T(A){for(let x=0;x<N.length;x++){let V=N[x](A);V!=null&&V!==""&&s[x].set(V,A)}}for(let A of p){if(A.type!=="deletion")continue;let x=m(A.el);x&&x!==b&&x.remove()}let L=p.filter(A=>A.type!=="deletion").sort((A,x)=>A.el===x.el?0:A.el.compareDocumentPosition(x.el)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1);for(let A of L){if(A.type==="head"){let _=r.importNode(A.el,!0);r.head?r.head.replaceWith(_):b.insertBefore(_,b.firstChild),w.push({entry:A,imported:_});continue}if(A.type==="attrs"){let _=v(A.el)||v(A.base);if(!_){a++;continue}for(let O of A.names)A.el.hasAttribute(O)?_.setAttribute(O,A.el.getAttribute(O)):_.removeAttribute(O);continue}let x=A.el;if(i(x))return c(A);let V=v(x)||v(A.base);if(V){let _=r.importNode(x,!0);V.replaceWith(_),T(_),w.push({entry:A,imported:_});continue}if(A.base!=null&&!ue(A.base,f(A.base),N)||!ue(x,f(x),N))return c(A);let C=x.parentElement;if(!C)return c(A);let z=v(C);if(!z)return c(A);let K=null;for(let _=x.previousElementSibling;_;_=_.previousElementSibling){let O=v(_);if(O&&O.parentNode===z){K=O;break}}let G=r.importNode(x,!0);if(K)z.insertBefore(G,K.nextSibling);else{let _=Array.prototype.indexOf.call(C.children,x);z.insertBefore(G,z.children[_]||null)}T(G),w.push({entry:A,imported:G})}return{ok:!0,placed:w,held:null,skippedAttrs:a}}return{morph:J,defaults:E,findChangedRoots:et,spliceProtected:tt,mergeJson:ve,mergeScriptText:Me,parseJsonRelaxed:me,parseRulesRelaxed:Ie}})();var xt=de.morph,Ct=de.defaults,Lt=de.findChangedRoots,Rt=de.spliceProtected;var Bt=de;return at(Ht);})();
3
3
 
4
4
  // Convenience morph wrapper with data-id support
5
5
  var morph = function(oldEl, newEl, options = {}) {