@valbuild/ui 0.108.0 → 0.108.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -127,8 +127,8 @@ All routes will be filtered out due to malformed exclude pattern.`)}return e.fil
127
127
  `)}:{title:`Changes cannot be saved: the server could not be reached.`,detail:[`Nothing is known about these changes — the request did not complete, so they may or may not have arrived. They will be sent again once the connection is back.`,`The last error was: ${t}`,a,o].join(`
128
128
 
129
129
  `)}}var mb=class e{constructor(){this.target=new EventTarget}static{this.ANY=`val:any`}emit(t){this.target.dispatchEvent(new CustomEvent(e.ANY,{detail:t})),this.target.dispatchEvent(new CustomEvent(t.type,{detail:t}))}on(e,t){let n=e=>{t(e.detail)};return this.target.addEventListener(e,n),()=>this.target.removeEventListener(e,n)}onAny(t){let n=e=>{t(e.detail)};return this.target.addEventListener(e.ANY,n),()=>this.target.removeEventListener(e.ANY,n)}},hb={work:()=>{}},qae=class{constructor(e=hb){this.activity=e,this.events=new mb,this.schemas={},this.versions=new Map,this.previewDeclared=new Map}receive(e){this.activity.work(`schema:receive`,void 0,Object.keys(e).length),this.schemas={...this.schemas,...e};for(let t of Object.keys(e))this.versions.set(t,(this.versions.get(t)??0)+1);this.events.emit({type:`schema:init`,modules:Object.keys(e)})}get(e){return this.schemas[e]}all(){return this.schemas}version(e){return this.versions.get(e)??0}declaresPreview(e){let t=this.version(e),n=this.previewDeclared.get(e);if(n!==void 0&&n.version===t)return n.declared;let r=this.schemas[e],i=r!==void 0&&gb(r);return this.previewDeclared.set(e,{version:t,declared:i}),i}};function gb(e,t=new Set){if(t.has(e))return!1;switch(t.add(e),e.type){case`array`:return e.preview===!0||gb(e.item,t);case`record`:return e.preview===!0||gb(e.item,t);case`object`:return Object.values(e.items).some(e=>gb(e,t));case`union`:return e.items.some(e=>gb(e,t));default:return!1}}function _b(e){for(var t=e,n=[...arguments].slice(1),r=0,i=n;r<i.length;r++){var a=i[r];t=a(t)}return t}function vb(e){return T(e)}function yb(e,t){if(e===t)return!0;if(z(e)===`object`&&z(t)===`object`&&e!==null&&t!==null){if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(var n=0;n<e.length;++n)if(!yb(e[n],t[n]))return!1;return!0}if(!Array.isArray(e)&&!Array.isArray(t)){var r=Object.entries(e);if(r.length!==Object.keys(t).length)return!1;for(var i=0,a=r;i<a.length;i++){var o=Se(a[i],2),s=o[0],c=o[1],l=t[s];if(l===void 0||!yb(c,l))return!1}return!0}}return!1}function bb(e){return Array.isArray(e)?e.map(bb):z(e)===`object`&&e!==null?Object.fromEntries(Object.entries(e).map(function(e){var t=Se(e,2),n=t[0],r=t[1];return[n,bb(r)]})):e}function xb(e){return/^(0|[1-9][0-9]*)$/g.test(e)?D(Number(e)):O(new ir(`Invalid array index "${e}"`))}function Jae(e,t){return e===`-`?D(t.length):_b(xb(e),te(function(e){return e<=t.length},function(){return new ir(`Array index out of bounds`)}))}function Sb(e,t){return _b(xb(e),te(function(e){return e<t.length},function(){return new ir(`Array index out of bounds`)}))}function Yae(e,t,n){if(Array.isArray(e))return _b(Sb(t,e),F(function(t){var r=e[t];return e[t]=n,r}));if(z(e)===`object`&&e!==null){if(Object.prototype.hasOwnProperty.call(e,t)){var r=e[t];return e[t]=n,D(r)}return O(new ir(`Cannot replace object element which does not exist`))}return O(new ir(`Cannot replace in non-object/array`))}function Xae(e,t,n){return vb(t)?_b(wb(e,t),I(function(e){var t=Se(e,2),r=t[0],i=t[1];return Yae(r,i,n)}),F(function(t){return[e,t]})):D([n,e])}function Cb(e,t){return Array.isArray(e)?_b(xb(t),I(function(t){return t>=e.length?O(new ir(`Array index out of bounds`)):D(e[t])})):z(e)===`object`&&e!==null?Object.prototype.hasOwnProperty.call(e,t)?D(e[t]):D(void 0):O(new ir(`Cannot access non-object/array`))}function wb(e,t){for(var n=e,r=t[0],i=0;i<t.length-1;++i,r=t[i]){var a=Cb(n,r);if(A(a))return a;if(a.value===void 0)return O(new ir(`Path refers to non-existing object/array`));n=a.value}return D([n,r])}function Tb(e,t){return _b(t,P(function(e,t){return _b(Cb(e,t),te(function(e){return e!==void 0},function(){return new ir(`Path refers to non-existing object/array`)}))},e))}function Zae(e,t){if(Array.isArray(e))return _b(Sb(t,e),F(function(t){return Se(e.splice(t,1),1)[0]}));if(z(e)===`object`&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)){var n=e[t];return delete e[t],D(n)}return O(new ir(`Cannot remove from non-object/array`))}function Eb(e,t){return _b(wb(e,t),I(function(e){var t=Se(e,2),n=t[0],r=t[1];return Zae(n,r)}))}function Qae(e,t,n){if(Array.isArray(e))return _b(Jae(t,e),F(function(t){e.splice(t,0,n)}));if(z(e)===`object`&&e!==null){var r;return Object.prototype.hasOwnProperty.call(e,t)&&(r=e[t]),e[t]=n,D(r)}return O(new ir(`Cannot add to non-object/array`))}function Db(e,t,n){return vb(t)?_b(wb(e,t),I(function(e){var t=Se(e,2),r=t[0],i=t[1];return Qae(r,i,n)}),F(function(t){return[e,t]})):D([n,e])}function Ob(e){return Se(e,1)[0]}var kb=function(){function e(){Oe(this,e)}return Ae(e,[{key:`get`,value:function(e,t){return Tb(e,t)}},{key:`add`,value:function(e,t,n){return _b(Db(e,t,n),F(Ob))}},{key:`remove`,value:function(e,t){return _b(Eb(e,t),F(function(){return e}))}},{key:`replace`,value:function(e,t,n){return _b(Xae(e,t,n),F(Ob))}},{key:`move`,value:function(e,t,n){return _b(Eb(e,t),I(function(t){return Db(e,n,t)}),F(Ob))}},{key:`copy`,value:function(e,t,n){return _b(Tb(e,t),I(function(t){return Db(e,n,bb(t))}),F(Ob))}},{key:`test`,value:function(e,t,n){return _b(Tb(e,t),F(function(e){return yb(n,e)}))}}])}();function $ae(e,t,n){switch(n.op){case`add`:return t.add(e,n.path,n.value);case`remove`:return t.remove(e,n.path);case`replace`:return t.replace(e,n.path,n.value);case`move`:return t.move(e,n.from,n.path);case`copy`:return t.copy(e,n.from,n.path);case`test`:return t.test(e,n.path,n.value)?D(e):O(new ir(`Test failed`));case`file`:return O(new ir(`Cannot apply a file patch here`))}}function Ab(e,t,n){return _b(n,P(function(e,n){return $ae(e,t,n)},e))}function jb(e,t){return e===t||e.startsWith(t+`.`)||e.startsWith(t+`?p=`)}function eoe(e,t){for(let n of e)if(jb(t,n)||jb(n,t))return!0;return!1}var Mb=new kb;function toe(e,t){if(e.status!==t.status||e.errors.length!==t.errors.length)return!1;for(let n=0;n<e.errors.length;n++){let r=e.errors[n],i=t.errors[n];if(r.moduleFilePath!==i.moduleFilePath||r.key!==i.key||r.message!==i.message)return!1}return!0}var noe=class{constructor(e,t=hb,n){this.schemaStore=e,this.activity=t,this.fetchJsonEntry=n,this.events=new mb,this.sources={},this.baseSources={},this.chains=new Map,this.revisions=new Map,this.peeked=new Map,this.peekedBase=new Map,this.jsonEntries=new Map,this.baseJsonEntries=new Map,this.loadingEntries=new Map,this.entryFailures=new Map,this.substituted=new WeakMap,this.listenerTargets=new Map,this.listenersByModule=new Map,this.globalRevision=0,this.deferredAnnouncements=new Set,this.batchDepth=0,this.allSourcesAt=null,this.allEntriesProgressCache=null,this.pendingEntryLoads=new Map,this.entriesStatusCache=new Map}bump(e){if(this.revisions.set(e,(this.revisions.get(e)??0)+1),this.globalRevision++,this.allSourcesAt=null,this.batchDepth>0){this.deferredAnnouncements.add(e);return}this.events.emit({type:`source:change`,moduleFilePath:e})}async batched(e){this.batchDepth++;try{return await e()}finally{if(this.batchDepth--,this.batchDepth===0&&this.deferredAnnouncements.size>0){let e=[...this.deferredAnnouncements];this.deferredAnnouncements.clear();for(let t of e)this.events.emit({type:`source:change`,moduleFilePath:t});this.events.emit({type:`source:patch-apply`,success:[],failed:[],modules:e})}}}sourcesVersion(){return this.globalRevision}allSources(){let e=this.allSourcesAt;if(e!==null&&e.n===this.globalRevision)return e.sources;let t={};for(let e of Object.keys(this.sources)){let n=this.moduleSource(e);n!==void 0&&(t[e]=n)}return this.allSourcesAt={n:this.globalRevision,sources:t},t}allEntriesProgress(){let e=0,t=0,n=0;for(let r of Object.keys(this.sources)){let i=this.entriesProgress(r);e+=i.total,t+=i.loaded,n+=i.failed}let r={total:e,loaded:t,failed:n},i=this.allEntriesProgressCache;return i!==null&&i.total===r.total&&i.loaded===r.loaded&&i.failed===r.failed?i:(this.allEntriesProgressCache=r,r)}receiveJsonEntry(e,t,n){let r=this.jsonEntries.get(e);r===void 0&&(r=new Map,this.jsonEntries.set(e,r)),r.set(t,n);let i=this.baseJsonEntries.get(e);i===void 0&&(i=new Map,this.baseJsonEntries.set(e,i)),i.set(t,bb(n)),this.activity.work(`source:receive-json-entry`,e),this.bump(e),!(this.batchDepth>0)&&this.events.emit({type:`source:patch-apply`,success:[],failed:[],modules:[e]})}markJsonEntriesStale(e){this.jsonEntries.has(e)&&(this.jsonEntries.delete(e),this.baseJsonEntries.delete(e),this.bump(e))}async loadEntries(e,t){let n=this.jsonEntries.get(e),r=t.filter(e=>n?.has(e)!==!0);if(r.length===0)return;let i=this.pendingEntryLoads.get(e);if(i===void 0){let t=new Set;i={keys:t,request:(async()=>{await Promise.resolve(),this.pendingEntryLoads.delete(e),await this.batched(()=>Promise.all([...t].map(t=>this.loadEntry(e,t))))})()},this.pendingEntryLoads.set(e,i)}for(let e of r)i.keys.add(e);await i.request}async loadAllEntries(e){let t=this.sources[e];if(t===void 0||!Lb(t))return;let n=[];for(let[e,r]of Object.entries(t))V.isJson(r)&&n.push(e);await this.loadEntries(e,n)}entriesStatus(e){let t=[],n=!1;for(let r of e){let e=this.sources[r];if(e===void 0){n=!0;continue}if(!Lb(e))continue;let i=this.jsonEntries.get(r);for(let[a,o]of Object.entries(e)){if(!V.isJson(o)||i?.has(a)===!0)continue;let e=this.entryFailures.get(Rb(r,a));if(e!==void 0){t.push({moduleFilePath:r,key:a,message:e});continue}n=!0}}let r=t.length>0?{status:`error`,errors:t}:{status:n?`incomplete`:`complete`,errors:t},i=e.join(`
130
- `),a=this.entriesStatusCache.get(i);return a!==void 0&&toe(a,r)?a:(this.entriesStatusCache.set(i,r),r)}entryError(e,t){return this.entryFailures.get(Rb(e,t))}hasUnloadedEntries(e){let t=this.sources[e];if(t===void 0||!Lb(t))return!1;let n=this.jsonEntries.get(e);for(let[e,r]of Object.entries(t))if(V.isJson(r)&&n?.has(e)!==!0)return!0;return!1}peek(e){let t=this.computePeek(e,this.sources,this.jsonEntries),n=this.peeked.get(e);return n!==void 0&&Pb(n,t)?n:(this.peeked.set(e,t),t)}computePeek(e,t,n){let[r,i]=V.splitModuleFilePathAndModulePath(e),a=t[r];if(a===void 0||this.schemaStore.get(r)===void 0)return{status:`module-loading`};let o=Ib(this.substitutedSource(r,a,n),i);if(o.status===`needs-entry`){let e=Rb(r,o.key);if(this.loadingEntries.has(e))return{status:`entry-loading`,key:o.key};let t=this.entryFailures.get(e);return t===void 0?{status:`entry-missing`,key:o.key}:{status:`entry-failed`,key:o.key,message:t}}let s=this.revisionOf(r);return o.status===`found`?{status:`ready`,revision:s,data:o.value}:o.status===`absent`?{status:`absent`,revision:s}:{status:`module-loading`}}storePatched(e,t,n,r){let i=r?.sources??this.sources,a=(r?.entries??this.jsonEntries).get(e);if(a===void 0||a.size===0||!Lb(n)||!Lb(t)){i[e]=n;return}let o={...n};for(let e of[...a.keys()]){if(!(e in o)){a.delete(e);continue}V.isJson(t[e])&&(a.set(e,o[e]),o[e]=t[e])}i[e]=o}async loadEntry(e,t){if(this.fetchJsonEntry===void 0)return{status:`error`,message:`Cannot read inside '${t}' of ${e}: no jsonValues fetch is configured. Refusing rather than reporting the path absent.`};let n=Rb(e,t),r=this.loadingEntries.get(n);if(r!==void 0){this.activity.work(`source:share-json-entry-load`,e),await r;let t=this.entryFailures.get(n);return t===void 0?{status:`ok`}:{status:`error`,message:t}}let i;this.entryFailures.delete(n);let a=(async()=>{this.activity.work(`source:load-json-entry`,e);let r=await this.fetchJsonEntry(e,t);if(r.status===`error`){i=r.message,this.entryFailures.set(n,r.message);return}this.receiveJsonEntry(e,t,r.content)})().finally(()=>{this.loadingEntries.delete(n)});return this.loadingEntries.set(n,a),await a,i===void 0?{status:`ok`}:{status:`error`,message:i}}peekBase(e){let t=this.computePeek(e,this.baseSources,this.baseJsonEntries),n=this.peekedBase.get(e);return n!==void 0&&Pb(n,t)?n:(this.peekedBase.set(e,t),t)}entriesProgress(e){let t=this.sources[e];if(t===void 0||!Lb(t))return{total:0,loaded:0,failed:0};let n=this.jsonEntries.get(e),r=0,i=0,a=0;for(let[o,s]of Object.entries(t))V.isJson(s)&&(r++,n?.has(o)===!0?i++:this.entryFailures.has(Rb(e,o))&&a++);return{total:r,loaded:i,failed:a}}async retryEntry(e,t){return this.entryFailures.delete(Rb(e,t)),this.loadEntry(e,t)}promoteToBase(e){for(let t of e){let e=this.sources[t];if(e===void 0)continue;this.activity.work(`source:promote-to-base`,t),this.baseSources[t]=bb(e);let n=this.jsonEntries.get(t);n!==void 0&&this.baseJsonEntries.set(t,new Map([...n].map(([e,t])=>[e,bb(t)])))}}promotePublished(e,t){let n=new Set(e);for(let e of t){let t=this.chains.get(e)??[],r=t.filter(e=>!n.has(e.record.patchId));if(r.length===t.length)continue;if(r.length===0){this.promoteToBase([e]),this.chains.set(e,[]);continue}let i=this.baseSources[e];if(i===void 0){this.chains.set(e,r);continue}let a=bb(this.substitutedSource(e,i,this.baseJsonEntries)),o=!0;for(let r of t){if(!n.has(r.record.patchId))continue;let t=r.record.patch.filter(e=>e.op!==`file`);if(t.length===0)continue;this.activity.work(`source:apply-patch`,r.record.patchId);let i=Ab(bb(a),Mb,t);if(!ne.isOk(i)){console.error(`Val: could not rebuild the base after a partial save. The value on screen is right; the base behind it is stale until the next load.`,{moduleFilePath:e,patchId:r.record.patchId,error:i.error}),o=!1;break}a=i.value}o&&(this.activity.work(`source:promote-to-base`,e),this.storePatched(e,i,a,{sources:this.baseSources,entries:this.baseJsonEntries}),this.chains.set(e,r))}}forgetPublished(e){let t=new Set(e);for(let[e,n]of this.chains){let r=n.filter(e=>!t.has(e.record.patchId));r.length!==n.length&&this.chains.set(e,r)}}revisionOf(e){return{module:e,n:this.revisions.get(e)??0}}listenTo(e){let t=e.events.on(`patch:receive`,t=>{this.applyPatches(e.recordsFor(t.patches),`external`,()=>void 0)}),n=e.events.on(`patch:create`,t=>{this.applyPatches(e.recordsFor(t.patches),`internal`,t=>e.creatorOf(t))}),r=e.events.on(`patch:drop`,e=>{this.dropFromChains(e.patches,e.modules)});return()=>{t(),n(),r()}}dropFromChains(e,t){let n=new Set(e),r=[],i=[];for(let e of t){let t=this.chains.get(e);if(t!==void 0){let r=t.filter(e=>!n.has(e.record.patchId));if(r.length===t.length)continue;for(let e of t)n.has(e.record.patchId)&&i.push(...Fb(e.record));this.chains.set(e,r)}let a=this.baseSources[e];if(a===void 0)continue;this.activity.work(`source:rebuild-module`,e),this.sources[e]=bb(a);let o=this.baseJsonEntries.get(e);o!==void 0&&this.jsonEntries.set(e,new Map([...o].map(([e,t])=>[e,bb(t)]))),this.bump(e),r.push(e)}if(r.length>0){this.events.emit({type:`source:patch-drop`,modules:r});for(let e of r){let t=this.chains.get(e);t!==void 0&&t.length!==0&&this.applyEntries(t.map(e=>({record:e.record,origin:`external`,creatorFieldId:void 0})))}i.length>0&&this.wakeListeners(new Set(r),[{origin:`external`,creatorFieldId:void 0,paths:i}])}}receive(e){for(let[t,n]of Object.entries(e)){this.activity.work(`source:clone-module`,t);let e=bb(n);this.baseSources[t]=e,this.sources[t]=bb(e),this.bump(t)}this.events.emit({type:`source:init`,sources:Object.keys(e)});for(let t of Object.keys(e)){let e=this.chains.get(t);e!==void 0&&e.length!==0&&this.applyEntries(e)}let t=Object.keys(e).filter(e=>this.sources[e]!==void 0);t.length>0&&this.wakeListeners(new Set(t),[{origin:`external`,creatorFieldId:void 0,paths:t}])}async get(e,t){let[n,r]=V.splitModuleFilePathAndModulePath(e),i=this.revisionOf(n),a=this.sources[n];if(t!==null&&t.module===n&&t.n===i.n&&a!==void 0&&this.schemaStore.get(n)!==void 0)return{status:`unchanged`,revision:i};if(a===void 0||this.schemaStore.get(n)===void 0)return{status:`module-loading`};this.activity.work(`source:read-path`,e);let o=Ib(this.substitutedSource(n,a),r);if(o.status===`needs-entry`){let e=await this.loadEntry(n,o.key);if(e.status===`error`)return{status:`error`,message:e.message};let t=this.sources[n];if(t===void 0)return{status:`module-loading`};if(o=Ib(this.substitutedSource(n,t),r),o.status===`needs-entry`)return{status:`error`,message:`Entry '${o.key}' of ${n} was loaded but its content is still missing.`}}let s=this.revisionOf(n);return o.status===`absent`?{status:`absent`,revision:s}:o.status===`error`?{status:`error`,message:o.message}:{status:`resolved-head`,data:o.value,revision:s}}async isCurrent(e){return e.n===this.revisionOf(e.module).n}moduleSource(e){let t=this.sources[e];if(t===void 0)return;let n=this.jsonEntries.get(e);return n===void 0||n.size===0?t:this.substitutedSource(e,t)}substitutedSource(e,t,n=this.jsonEntries){let r=n.get(e);if(r===void 0||r.size===0||!Lb(t))return t;let i=this.revisions.get(e)??0,a=this.substituted.get(t);if(a!==void 0&&a.n===i)return a.source;this.activity.work(`source:substitute-json-entries`,e);let o=roe(t,r);return this.substituted.set(t,{n:i,source:o}),o}loadedModules(){return Object.keys(this.sources)}listenedPaths(e){let t=this.listenersByModule.get(e);return t===void 0?[]:[...t]}addListener(e,t,n){let r=this.listenerTargets.get(e);r||(r=new Map,this.listenerTargets.set(e,r));let i=r.get(t);i||(i={target:new EventTarget,count:0},r.set(t,i));let a=i,o=r,[s]=V.splitModuleFilePathAndModulePath(e),c=this.listenersByModule.get(s);c===void 0&&(c=new Set,this.listenersByModule.set(s,c)),c.add(e);let l=e=>{n(e.detail)};a.target.addEventListener(Nb,l),a.count++;let[u]=V.splitModuleFilePathAndModulePath(e);this.events.emit({type:`source:listen`,path:e,moduleFilePath:u});let d=!1;return()=>{if(!d&&(d=!0,a.target.removeEventListener(Nb,l),a.count--,this.events.emit({type:`source:unlisten`,path:e,moduleFilePath:u}),a.count<=0&&o.get(t)===a&&(o.delete(t),o.size===0&&this.listenerTargets.get(e)===o))){this.listenerTargets.delete(e);let t=this.listenersByModule.get(s);t!==void 0&&(t.delete(e),t.size===0&&this.listenersByModule.delete(s))}}}applyPatches(e,t,n){if(e.length===0)return;let r=e.map(e=>({record:e,origin:t,creatorFieldId:n(e.patchId)}));for(let e of r){let t=e.record.moduleFilePath,n=this.chains.get(t);n===void 0?this.chains.set(t,[e]):n.push(e)}this.applyEntries(r)}applyEntries(e){if(e.length===0)return;let t=[],n=[],r=[],i=new Set,a=[];for(let{record:o,origin:s,creatorFieldId:c}of e){let e=this.sources[o.moduleFilePath],l=e===void 0?void 0:this.substitutedSource(o.moduleFilePath,e);if(l===void 0||e===void 0){this.activity.work(`source:skip-unloaded`,o.moduleFilePath);continue}let u=o.patch.filter(e=>e.op!==`file`);if(u.length===0){t.push(o.patchId);continue}this.activity.work(`source:clone-module`,o.moduleFilePath),this.activity.work(`source:apply-patch`,o.patchId);let d=Ab(bb(l),Mb,u);if(ne.isOk(d)){this.storePatched(o.moduleFilePath,e,d.value),this.bump(o.moduleFilePath),t.push(o.patchId),i.add(o.moduleFilePath);let n=Fb(o);r.push(...n);let l=a.find(e=>e.origin===s&&e.creatorFieldId===c);l===void 0?a.push({origin:s,creatorFieldId:c,paths:[...n]}):l.paths.push(...n)}else n.push({patchId:o.patchId,message:d.error.message})}(t.length!==0||n.length!==0)&&(this.events.emit({type:`source:patch-apply`,success:t,failed:n,modules:[...i]}),r.length!==0&&this.wakeListeners(i,a))}wakeListeners(e,t){let n=new Set;for(let t of e){let e=this.listenersByModule.get(t);if(e!==void 0)for(let t of e)n.add(t)}this.activity.work(`source:scan-listeners`,void 0,n.size);for(let e of n){let n=this.listenerTargets.get(e);if(n===void 0)continue;let r=t.filter(t=>eoe(t.paths,e));if(r.length===0)continue;let[i]=V.splitModuleFilePathAndModulePath(e),a=this.revisionOf(i);for(let[t,i]of n){let n=r.find(e=>e.creatorFieldId!==t);if(n===void 0)continue;this.activity.work(`source:wake-listener`,e);let o={type:`${n.origin}-patch`,path:e,revision:a};i.target.dispatchEvent(new CustomEvent(Nb,{detail:o}))}}}},Nb=`val:field-changed`;function Pb(e,t){return e.status===t.status?e.status===`ready`&&t.status===`ready`?e.data===t.data&&e.revision.n===t.revision.n:e.status===`absent`&&t.status===`absent`?e.revision.n===t.revision.n:e.status===`entry-failed`&&t.status===`entry-failed`?e.key===t.key&&e.message===t.message:e.status===`entry-missing`&&t.status===`entry-missing`||e.status===`entry-loading`&&t.status===`entry-loading`?e.key===t.key:e.status===`module-loading`:!1}function Fb(e){let t=[],n=n=>{t.push(V.joinModuleFilePathAndModulePath(e.moduleFilePath,V.patchPathToModulePath(n)))};for(let t of e.patch)t.op!==`file`&&(n(t.path),(t.op===`move`||t.op===`copy`)&&(n(t.from),r(t.from)),(t.op===`add`||t.op===`remove`||t.op===`move`)&&r(t.path));return t;function r(e){if(e.length===0)return;let t=e[e.length-1];Number.isInteger(Number(t))&&n(e.slice(0,-1))}}function Ib(e,t){let n=V.splitModulePath(t),r=e;for(let e=0;e<n.length;e++){let t=n[e];if(typeof r!=`object`||!r)return{status:`absent`};if(Array.isArray(r)){let e=Number(t);if(!Number.isInteger(e)||e<0||e>=r.length)return{status:`absent`};r=r[e];continue}if(!(t in r))return{status:`absent`};if(r=r[t],e===0&&e<n.length-1&&V.isJson(r))return{status:`needs-entry`,key:t}}return{status:`found`,value:r}}function roe(e,t){if(t===void 0||t.size===0||!Lb(e))return e;let n=null;for(let[r,i]of t)V.isJson(e[r])&&(n===null&&(n={...e}),n[r]=i);return n??e}function Lb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rb(e,t){return`${e}\0${t}`}var ioe=new TextEncoder;function aoe(e){let t=[],n=[];for(let r of e)r.op===`file`?(t.push(r),n.push({...r,value:typeof r.value==`string`?V.getSHA256Hash(ioe.encode(r.value)):r.value})):n.push(r);return{patchOps:n,fileOps:t}}var ooe=class{setPublishInFlight(e){this.publishInFlight=e}setParentRefSource(e){this.parentRefSource=e}constructor(e,t=()=>crypto.randomUUID(),n=hb,r){this.fetchPatches=e,this.newPatchId=t,this.activity=n,this.uploadFile=r,this.events=new mb,this.ordered=[],this.dataById=new Map,this.originById=new Map,this.appliedIds=new Set,this.failedById=new Map,this.fetching=new Set,this.creatorByPatchId=new Map,this.sessionByPatchId=new Map,this.pendingIds=new Set,this.verifying=new Set,this.notDeliveredOnce=new Set,this.publishInFlight=()=>!1,this.lastBaseSha=null,this.publishedIds=new Set,this.publishedModuleFilePaths=new Set,this.version=0,this.parentRefSource=()=>null,this.statSeen=!1,this.publishErrorById=new Map,this.publishErrorsAt=null,this.filePatchIdsAt=null}listenTo(e,t){let n=e.events.on(`stat:receive`,t=>{let n=e.currentBaseSha(),r=this.lastBaseSha!==null&&n!==null&&n!==this.lastBaseSha;n!==null&&(this.lastBaseSha=n),this.onStatPatchIds(t.patches,r)}),r=t.events.on(`source:patch-apply`,e=>{for(let t of e.success)this.appliedIds.add(t),this.failedById.delete(t);for(let t of e.failed)this.failedById.set(t.patchId,t.message),this.appliedIds.delete(t.patchId);this.events.emit({type:`patch:head`,head:this.currentHead()})});return()=>{n(),r()}}async onStatPatchIds(e,t=!1){this.statSeen=!0;let n=new Set(e.filter(e=>this.publishedIds.has(e)&&!this.dataById.has(e)));n.size>0&&console.debug(`Val: ignoring published changes named by a stat that predates the publish.`,{patchIds:[...n]});let r=n.size>0?e.filter(e=>!n.has(e)):e,i=new Set(r);for(let e of r)this.originById.has(e)||this.originById.set(e,`external`);let a=this.ordered.filter(e=>!i.has(e));this.ordered=[...r,...a],this.bump(),this.reconcileVanished(a.filter(e=>!this.pendingIds.has(e)),t);let o=r.filter(e=>!this.dataById.has(e)&&!this.fetching.has(e));if(this.events.emit({type:`patch:head`,head:this.currentHead()}),o.length===0)return;for(let e of o)this.fetching.add(e);this.activity.work(`patch:fetch`,void 0,o.length);let s=await this.fetchPatches(o);s.error!==void 0&&this.events.emit({type:`patch:fetch-failed`,patches:o,message:s.error});let c=[];for(let e of s.patches)this.fetching.delete(e.patchId),this.notDeliveredOnce.delete(e.patchId),this.dataById.set(e.patchId,e),c.push(e.patchId),this.bump();for(let[e,t]of Object.entries(s.errors??{}))this.fetching.delete(e),this.notDeliveredOnce.delete(e),this.failedById.set(e,t);let l=[],u=[];for(let e of o)if(this.fetching.delete(e)&&!this.dataById.has(e)&&this.ordered.includes(e)){if(!this.notDeliveredOnce.has(e)){this.notDeliveredOnce.add(e),u.push(e);continue}this.failedById.set(e,`The server said this change exists, but did not send it.`),l.push(e)}u.length>0&&console.warn(`Val: the server named these unpublished changes and did not send them. Asking again on the next stat before reporting it — an announcement can be older than a delete.`,{patchIds:u}),c.length>0&&this.events.emit({type:`patch:receive`,patches:c}),l.length>0&&this.events.emit({type:`patch:announced-not-delivered`,patches:l})}async reconcileVanished(e,t){if(this.publishInFlight())return;let n=e.filter(e=>!this.verifying.has(e));if(n.length!==0){for(let e of n)this.verifying.add(e);this.activity.work(`patch:verify-vanished`,void 0,n.length);try{let e=await this.fetchPatches(n);e.error!==void 0&&this.events.emit({type:`patch:fetch-failed`,patches:n,message:e.error});let r=new Set;for(let t of e.patches)r.add(t.patchId);for(let t of Object.keys(e.errors??{}))r.add(t);let i=n.filter(e=>!r.has(e)&&this.ordered.includes(e)&&!this.pendingIds.has(e));i.length>0&&(t?this.forgetPublished(i):this.drop(i))}finally{for(let e of n)this.verifying.delete(e)}}}async createPatch(e,t,n,r,i,a,o,s=`image`,c=!1){let l=a??this.newPatchId(),u=this.parentRefSource(),{patchOps:d,fileOps:f}=aoe(t),p=c?[]:f.filter(e=>typeof e.value==`string`),m=f.filter(e=>e.value===null);if((p.length>0||m.length>0)&&!this.uploadFile)return{status:`upload-failed`,message:`This patch carries files, but no upload seam is configured. Refusing rather than dropping the bytes.`,rolledBack:[],orphaned:[]};let h=this.uploadFile,g=[];if(h)for(let e of p){this.activity.work(`patch:upload-file`,e.filePath);let t=g.length,n=await h({patchId:l,parentRef:u,filePath:e.filePath,data:e.value,type:s,remote:e.remote,metadata:e.metadata,onProgress:i===void 0?void 0:(e,n)=>i(e,n,t,p.length)});if(n.status===`error`){let e=[],t=[];for(let n of g)this.activity.work(`patch:rollback-file`,n.filePath),(await h({patchId:l,parentRef:u,filePath:n.filePath,data:null,type:s,remote:n.remote})).status===`ok`?e.push(n.filePath):t.push(n.filePath);return{status:`upload-failed`,message:n.message,rolledBack:e,orphaned:t}}g.push({filePath:e.filePath,remote:e.remote===!0})}let _={patchId:l,moduleFilePath:e,patch:d,meta:n,createdAt:new Date().toISOString()};if(this.dataById.set(l,_),this.originById.set(l,`internal`),this.pendingIds.add(l),r!==void 0&&this.creatorByPatchId.set(l,r),o!==void 0&&this.sessionByPatchId.set(l,o),this.ordered=[...this.ordered,l],this.bump(),this.activity.work(`patch:create`,l),this.events.emit({type:`patch:create`,patches:[l]}),h)for(let e of m)this.activity.work(`patch:delete-file`,e.filePath),await h({patchId:l,parentRef:u,filePath:e.filePath,data:null,type:s,remote:e.remote});return{status:`created`,record:_}}unsavedRecords(){let e=[];for(let t of this.ordered){if(!this.pendingIds.has(t))continue;let n=this.dataById.get(t);n&&e.push(n)}return e}mintPatchId(){return this.newPatchId()}sessionOf(e){return this.sessionByPatchId.get(e)}isPending(e){return this.pendingIds.has(e)}pendingPatchIds(){return this.ordered.filter(e=>this.pendingIds.has(e))}markPublished(e){let t=!1;for(let n of e)this.publishedIds.has(n)||(this.publishedIds.add(n),t=!0);t&&this.bump()}publishedPatchIds(){return this.publishedIds}publishedModules(){return[...this.publishedModuleFilePaths]}markSaved(e){let t=[];for(let n of e)this.pendingIds.delete(n)&&t.push(n);t.length!==0&&(this.bump(),this.activity.work(`patch:mark-saved`,void 0,t.length))}forgetPublished(e){let t=[];for(let n of e){if(!this.dataById.has(n)&&!this.ordered.includes(n))continue;let e=this.dataById.get(n)?.moduleFilePath;e!==void 0&&this.publishedModuleFilePaths.add(e),this.dataById.delete(n),this.originById.delete(n),this.pendingIds.delete(n),this.appliedIds.delete(n),this.failedById.delete(n),this.creatorByPatchId.delete(n),this.sessionByPatchId.delete(n),this.fetching.delete(n),this.notDeliveredOnce.delete(n),this.publishErrorById.delete(n),t.push(n)}if(t.length===0)return;let n=new Set(t);this.ordered=this.ordered.filter(e=>!n.has(e)),this.bump(),this.activity.work(`patch:forget-published`,void 0,t.length),this.events.emit({type:`patch:head`,head:this.currentHead()})}drop(e){let t=[],n=new Set;for(let r of e){let e=this.dataById.get(r);e===void 0&&!this.ordered.includes(r)||(e!==void 0&&n.add(e.moduleFilePath),this.dataById.delete(r),this.originById.delete(r),this.pendingIds.delete(r),this.appliedIds.delete(r),this.failedById.delete(r),this.creatorByPatchId.delete(r),this.sessionByPatchId.delete(r),this.fetching.delete(r),this.notDeliveredOnce.delete(r),this.publishErrorById.delete(r),this.publishedIds.delete(r),t.push(r))}if(t.length===0)return;let r=new Set(t);this.ordered=this.ordered.filter(e=>!r.has(e)),this.bump(),this.activity.work(`patch:drop`,void 0,t.length),this.events.emit({type:`patch:drop`,patches:t,modules:[...n]}),this.events.emit({type:`patch:head`,head:this.currentHead()})}async getHead(){return this.currentHead()}recordsFor(e){let t=new Set(e),n=[];for(let e of this.ordered){if(!t.has(e))continue;let r=this.dataById.get(e);r&&n.push(r)}return n}allRecords(){return this.recordsFor(this.ordered)}chainVersion(){return this.version}recordPublishErrors(e){let t=Object.entries(e);if(t.length!==0){for(let[e,n]of t)this.publishErrorById.set(e,n);this.bump()}}publishErrors(){let e=this.publishErrorsAt;if(e!==null&&e.n===this.version)return e.byModule;let t={};for(let[e,n]of this.publishErrorById){let r=this.dataById.get(e);if(r===void 0)continue;let i=t[r.moduleFilePath]??{};i[e]={message:n,source:`server`},t[r.moduleFilePath]=i}return this.publishErrorsAt={n:this.version,byModule:t},t}bump(){this.version++,this.events.emit({type:`patch:chain`,version:this.version})}originOf(e){return this.originById.get(e)??`external`}chainSettled(){if(!this.statSeen)return!1;for(let e of this.ordered)if(!this.failedById.has(e)&&(!this.dataById.has(e)||!this.appliedIds.has(e)&&!this.pendingIds.has(e)))return!1;return!0}chainProgress(){let e=[],t=[],n=[],r=0;for(let i of this.ordered){if(this.failedById.has(i)){n.push(i),r++;continue}if(!this.dataById.has(i)){e.push(i);continue}if(!this.appliedIds.has(i)&&!this.pendingIds.has(i)){t.push(i);continue}r++}return{total:this.ordered.length,settled:r,unfetched:e,unapplied:t,failed:n,statSeen:this.statSeen}}currentHead(){if(this.ordered.length===0)return{type:`empty`};let e=this.ordered[this.ordered.length-1],t=this.originOf(e),n=this.dataById.get(e)??null;return this.failedById.has(e)?{type:`${t}-failed`,patchId:e,patch:n}:n===null||!this.appliedIds.has(e)?{type:`${t}-partial`,patchId:e,patch:n}:{type:`${t}-complete`,patchId:e,patch:n}}creatorOf(e){return this.creatorByPatchId.get(e)}filePatchIds(){let e=this.filePatchIdsAt;if(e!==null&&e.n===this.version)return e.map;let t=new Map;for(let e of this.ordered){let n=this.dataById.get(e);if(n!==void 0&&!(n.appliedAt||this.publishedIds.has(e)))for(let r of n.patch)r.op===`file`&&t.set(r.filePath,e)}return this.filePatchIdsAt={n:this.version,map:t},t}hasUnsavedFrom(e,t){for(let n of this.pendingIds)if(this.creatorByPatchId.get(n)===t&&this.dataById.get(n)?.moduleFilePath===e)return!0;return!1}},soe=class{constructor(){this.events=new mb,this.patches=[],this.baseSha=null}receiveStat(e){this.patches=[...e.patches],e.baseSha!==void 0&&(this.baseSha=e.baseSha),this.events.emit({type:`stat:receive`,patches:[...this.patches]}),e.removed!==void 0&&e.removed.length>0&&this.events.emit({type:`patch:removed-by-server`,removed:e.removed})}currentPatchIds(){return[...this.patches]}currentBaseSha(){return this.baseSha}},coe=class{constructor(e=hb){this.activity=e,this.events=new mb,this.transient=[],this.snapshot=null,this.networkErrorSince=null,this.schemaError=null,this.freshness=`current`,this.nextId=0}reportError(e,t){let n=this.transient.find(t=>t.message===e);if(n!==void 0){n.timestamp=Date.now(),n.details=t??n.details,this.announce();return}this.transient=[...this.transient,{id:`status-${++this.nextId}`,message:e,timestamp:Date.now(),details:t}],this.activity.work(`status:report-error`),this.announce()}dismissErrors(e){let t=new Set(e),n=this.transient.filter(e=>!t.has(e.id));n.length!==this.transient.length&&(this.transient=n,this.announce())}reportNetworkError(){this.networkErrorSince===null&&(this.networkErrorSince=Date.now(),this.announce())}clearNetworkError(){this.networkErrorSince!==null&&(this.networkErrorSince=null,this.announce())}reportSchemaError(e){this.schemaError!==e&&(this.schemaError=e,this.announce())}reportSchemaOutOfDate(){this.freshness!==`out-of-date`&&(this.freshness=`out-of-date`,this.activity.work(`status:schema-out-of-date`),this.announce())}current(){return this.snapshot===null&&(this.snapshot={errors:this.transient,networkErrorSince:this.networkErrorSince,schemaError:this.schemaError,schema:this.freshness}),this.snapshot}announce(){this.snapshot=null,this.events.emit({type:`status:change`})}};function loe(e,t,n){let r=[];for(let i of e){if(n(i.patchId)!==t)break;r.push(i)}return r}function uoe(e,t){return e.status===t.status?e.status===`in-sync`||t.status===`in-sync`?!0:e.patches.length===t.patches.length&&e.patches.every((e,n)=>e===t.patches[n])?e.status===`retrying`&&t.status===`retrying`?e.attempt===t.attempt&&e.reason===t.reason:!0:!1:!1}var doe=class{constructor(e,t,n,r=hb,i,a=e=>Math.min(3e4,500*2**(e-1)),o=e=>new Promise(t=>setTimeout(t,e))){this.patchStore=e,this.savePatches=t,this.resync=n,this.activity=r,this.sessionId=i,this.backoffMs=a,this.sleep=o,this.events=new mb,this.baseSha=null,this.statPatchIds=[],this.savedNotInStat=[],this.inFlight=null,this.attempt=0,this.reportedStuck=!1,this.state={status:`in-sync`},this.stopped=!1}listenTo(){return this.patchStore.events.on(`patch:create`,()=>{this.flush()})}receiveStat(e,t){this.baseSha=e,this.statPatchIds=[...t];let n=new Set(t);this.savedNotInStat=this.savedNotInStat.filter(e=>!n.has(e))}currentState(){return this.state}currentParentRef(){if(this.baseSha===null)return null;let e=this.savedNotInStat[this.savedNotInStat.length-1]??this.statPatchIds[this.statPatchIds.length-1];return e===void 0?{type:`head`,headBaseSha:this.baseSha}:{type:`patch`,patchId:e}}async flush(){if(this.inFlight!==null)return this.inFlight.then(()=>this.flush());let e=this.drain().finally(()=>{this.inFlight=null});return this.inFlight=e,e}async drain(){for(;;){let e=this.patchStore.unsavedRecords();if(e.length===0){this.setState({status:`in-sync`});return}if(this.stopped)return;let t=this.savePatches;if(t===void 0){this.setState({status:`pending`,patches:e.map(e=>e.patchId)});return}let n=this.currentParentRef(),r=this.patchStore.sessionOf(e[0].patchId),i=loe(e,r,e=>this.patchStore.sessionOf(e)),a=i.map(e=>e.patchId);if(n===null){this.setState({status:`retrying`,patches:a,reason:`network-error`,message:`Cannot save yet: the server has not said what the chain starts from.`,attempt:this.attempt});return}this.setState({status:`saving`,patches:a}),this.activity.work(`patch:save`,void 0,i.length),this.events.emit({type:`patch:save`,patches:a,parentRef:n});let o=await t({patches:i.map(e=>({path:e.moduleFilePath,patchId:e.patchId,patch:e.patch})),parentRef:n,sessionId:r??this.sessionId});if(this.stopped||await this.handle(o,a))return}}async handle(e,t){return e.status===`saved`?(this.attempt=0,this.reportedStuck=!1,this.savedNotInStat.push(...e.newPatchIds),this.patchStore.markSaved(e.newPatchIds),this.events.emit({type:`patch:saved`,patches:e.newPatchIds,parentRef:e.parentRef}),!1):e.status===`rejected`?(this.reportedStuck=!1,this.attempt=0,this.patchStore.drop(t),this.events.emit({type:`patch:save-rejected`,patches:t,message:e.message,errors:e.errors}),!1):(this.attempt++,e.status===`conflict`?(this.activity.work(`patch:save-conflict`),this.savedNotInStat=[],this.setState({status:`retrying`,patches:t,reason:`conflict`,message:e.message,attempt:this.attempt}),this.events.emit({type:`patch:save-conflict`,patches:t,message:e.message}),await this.resync(),this.stopped?!0:(this.attempt>=2&&this.reportStuck(t,`conflict`,e.message),await this.sleep(this.backoffMs(this.attempt)),this.stopped)):(this.activity.work(`patch:save-retry`),this.setState({status:`retrying`,patches:t,reason:e.status,message:e.message,attempt:this.attempt}),e.status!==`unauthorized`&&this.attempt>=2&&this.reportStuck(t,e.status,e.message),await this.sleep(this.backoffMs(this.attempt)),this.stopped))}reportStuck(e,t,n){this.reportedStuck||(this.reportedStuck=!0,this.events.emit({type:`patch:save-stuck`,patches:e,reason:t,message:n,attempt:this.attempt}))}setState(e){uoe(this.state,e)||(this.state=e,this.events.emit({type:`patch:sync-state`,state:e}))}dispose(){this.stopped=!0}},foe=class{constructor(e,t,n=hb){this.schemaStore=e,this.sourceStore=t,this.activity=n,this.events=new mb,this.instances={},this.receivedAt=null,this.moduleFailures=[]}initializedAt(){return this.receivedAt}failures(){return this.moduleFailures}receive(e){let t={},n={},r=[],i=[];for(let a of e)try{let e=V.getValPath(a);if(e===void 0){i.push({moduleFilePath:null,message:`Module has no path`});continue}let o=e,s=V.getSchema(a);if(s===void 0){i.push({moduleFilePath:o,message:`Module has no schema`});continue}this.activity.work(`host:serialize-schema`,o),t[o]=s.executeSerialize(),n[o]=JSON.parse(JSON.stringify(V.getSource(a))),this.instances[o]=s,r.push(o)}catch(e){i.push({moduleFilePath:V.getValPath(a)??null,message:e instanceof Error?e.message:String(e)})}this.moduleFailures=i,this.receivedAt=Date.now(),this.events.emit({type:`host:receive`,modules:r}),this.schemaStore.receive(t),this.sourceStore.receive(n)}async preview(e,t){let n=this.instances[e];if(!n)return{status:`unknown-module`};let r=this.sourceStore.moduleSource(e);if(r===void 0)return{status:`unknown-module`};try{this.activity.work(`host:execute-preview`,e);let i=t!==void 0&&t.length>0?vr([...t]):void 0;return{status:`previewed`,preview:n.executePreview(e,r,i)}}catch(e){return{status:`error`,message:e instanceof Error?e.message:String(e)}}}validateSpeculative(e,t){let n=this.instances[e];return n?(this.activity.work(`host:execute-validate`,e),{status:`validated`,errors:n.executeValidate(e,t)}):{status:`unknown-module`}}async customValidate(e,t){let n=this.instances[e];if(!n)return{status:`unknown-module`};let r=this.sourceStore.moduleSource(e);if(r===void 0)return{status:`unknown-module`};if(t.length===0)return{status:`validated`,errors:!1};try{return this.activity.work(`host:execute-validate`,e),{status:`validated`,errors:n.executeValidate(e,r)}}catch(e){return{status:`error`,message:e instanceof Error?e.message:String(e)}}}has(e){return this.instances[e]!==void 0}loadedModules(){return Object.keys(this.instances)}};function poe(e,t){let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n){let n=r;if(!(n in t)||e[n]!==t[n])return!1}return!0}function moe(e,t){return e.status===t.status?e.status===`previewed`&&t.status===`previewed`?e.preview===t.preview:e.status===`error`&&t.status===`error`?e.message===t.message:!0:!1}var hoe=class{constructor(e,t,n,r=hb){this.host=e,this.sourceStore=t,this.schemaStore=n,this.activity=r,this.events=new mb,this.previews=new Map,this.stale=new Set,this.peeked=new Map,this.pendingForget=new Map,this.inFlight=new Map,this.pendingReads=new Map,this.listenersByModule=new Map,this.allPreviews=null,this.generation=0}listenTo(){let e=this.sourceStore.events.on(`source:listen`,e=>{let t=this.listenersByModule.get(e.moduleFilePath)??0;this.listenersByModule.set(e.moduleFilePath,t+1);let n=this.pendingForget.get(e.moduleFilePath);n!==void 0&&(clearTimeout(n),this.pendingForget.delete(e.moduleFilePath)),!(this.previews.has(e.moduleFilePath)||this.inFlight.has(e.moduleFilePath)||this.pendingReads.has(e.moduleFilePath))&&this.refresh(e.moduleFilePath)}),t=this.sourceStore.events.on(`source:unlisten`,e=>{let t=(this.listenersByModule.get(e.moduleFilePath)??0)-1;if(t>0){this.listenersByModule.set(e.moduleFilePath,t);return}this.listenersByModule.delete(e.moduleFilePath);let n=e.moduleFilePath,r=this.pendingForget.get(n);r!==void 0&&clearTimeout(r),this.pendingForget.set(n,setTimeout(()=>{this.pendingForget.delete(n),!((this.listenersByModule.get(n)??0)>0)&&(this.previews.delete(n),this.stale.delete(n),this.pendingReads.delete(n))},0))}),n=this.sourceStore.events.on(`source:patch-apply`,e=>{this.invalidate(e.modules)}),r=this.sourceStore.events.on(`source:init`,e=>{this.invalidate(e.sources)}),i=this.schemaStore.events.on(`schema:init`,e=>{this.invalidate(e.modules)});return()=>{e(),t(),n(),r(),i();for(let e of this.pendingForget.values())clearTimeout(e);this.pendingForget.clear()}}invalidate(e){this.generation++;let t=e.filter(e=>!this.stale.has(e)&&this.previews.has(e));for(let t of e)this.stale.add(t);t.length>0&&this.events.emit({type:`preview:invalidate`,modules:t})}async get(e){let[t]=V.splitModuleFilePathAndModulePath(e);this.stale.has(t)||!this.covers(t,e)?(this.activity.work(`preview:cache-miss`,t),await this.refreshFor(t,e)):this.activity.work(`preview:cache-hit`,t);let n=this.previews.get(t);if(n===void 0)return{status:`no-preview`};let r=n.preview[e]??n.preview[t];return r===void 0?{status:`no-preview-at-path`}:{status:`previewed`,preview:r}}covers(e,t){let n=this.previews.get(e);return n===void 0?!1:n.scope===null||n.scope.has(t)}async refreshFor(e,t){let n=this.pendingReads.get(e);if(n!==void 0)return this.activity.work(`preview:share-in-flight`,e),n.paths.add(t),n.request;let r=new Set([t]),i=(async()=>{await Promise.resolve(),this.pendingReads.delete(e),await this.computePreview(e,r)})();return n={paths:r,request:i},this.pendingReads.set(e,n),i}async refresh(e){return this.computePreview(e,new Set)}async computePreview(e,t,n=!1){let r=n?void 0:this.inFlight.get(e);if(r!==void 0){let n=r.scope,i=n===null||[...t].every(e=>n.has(e));return this.activity.work(`preview:share-in-flight`,e),await r.request,i?void 0:this.computePreview(e,t,!0)}let i=new Set(this.sourceStore.listenedPaths(e));for(let e of t)i.add(e);let a=this.generation,o=(async()=>{let t=this.schemaStore.declaresPreview(e)?await this.host.preview(e,[...i]):{status:`previewed`,preview:{}};t.status===`previewed`?(this.previews.set(e,{preview:t.preview,scope:i.size===0?null:i}),this.generation===a&&this.stale.delete(e),this.events.emit({type:`preview:result`,moduleFilePath:e})):t.status===`unknown-module`?(this.previews.delete(e),this.generation===a&&this.stale.delete(e)):(this.previews.delete(e),this.generation===a&&this.stale.delete(e),this.events.emit({type:`preview:error`,moduleFilePath:e,message:t.message}))})().finally(()=>{this.inFlight.get(e)?.request===o&&this.inFlight.delete(e)});return this.inFlight.set(e,{scope:i.size===0?null:i,request:o}),o}peek(e){let t=this.computePeek(e),n=this.peeked.get(e);return n!==void 0&&moe(n,t)?n:(this.peeked.set(e,t),t)}all(){let e={};for(let[t,n]of this.previews)e[t]=this.stale.has(t)?null:n.preview;let t=this.allPreviews;return t!==null&&poe(t,e)?t:(this.allPreviews=e,e)}computePeek(e){let[t]=V.splitModuleFilePathAndModulePath(e);if(!this.schemaStore.declaresPreview(t))return{status:`no-preview`};if(this.stale.has(t))return{status:`needs-preview`};let n=this.previews.get(t);if(n===void 0||!this.covers(t,e))return{status:`needs-preview`};let r=n.preview[e]??n.preview[t];return r===void 0?{status:`no-preview-at-path`}:{status:`previewed`,preview:r}}};function zb(e,t){if(!t||t.length===0)return new Set([e.type]);let n=new Set,r=e,i=-1;for(let e of t){if(i++,!r)break;if(r.type===`array`)r=r.item;else if(r.type===`record`)r=r.item;else if(r.type===`object`)r=r.items[e];else if(r.type===`richtext`)break;else if(r.type===`union`){if(typeof r.key==`string`){let e=r.items;for(let r of e){let e=zb(r,t.slice(i));for(let t of Array.from(e.values()))n.add(t)}return n}if(i!==t.length-1)throw Error(`Found string union (primitive), but path has more parts: `+t.join(`/`)+` at `+e);break}else if(r.type===`boolean`||r.type===`number`||r.type===`string`||r.type===`date`||r.type===`dateTime`||r.type===`color`||r.type===`file`||r.type===`image`||r.type===`keyOf`||r.type===`route`||r.type===`literal`){if((r.type===`image`||r.type===`file`)&&t[i]===`metadata`)break;if(i!==t.length-1)throw Error(`Found `+r.type+` (primitive), but path has more parts: `+t.join(`/`)+` at `+e);break}else{let n=r.type;return console.error(`Unexecpted resolved schema type: ${n} in ${t.join(`/`)} at ${e}`),new Set([n])}}return r&&(n.add(r.type),r.type===`union`&&(typeof r.key==`string`?n.add(`object`):n.add(`string`))),n}var goe=class{constructor(){this.patchSetMetadata={},this.orderedInsertKeys=[],this.insertedPatches=new Set}reset(){this.patchSetMetadata={},this.orderedInsertKeys=[],this.insertedPatches=new Set}getInsertedPatches(){return this.insertedPatches}insertPath(e,t,n,r,i,a,o,s){let c=t.length>0?`${e}?${t.join(`/`)}`:e,l=[];for(let e=this.orderedInsertKeys.length-1;e>=0;e--){let t=this.orderedInsertKeys[e];c===t?(this.orderedInsertKeys.splice(e,1),this.orderedInsertKeys.unshift(c)):c.startsWith(t)?(c=t,this.orderedInsertKeys.splice(e,1),this.orderedInsertKeys.unshift(c)):t.startsWith(c)&&l.push(e)}for(let n of l){let a=this.orderedInsertKeys[n];this.orderedInsertKeys.splice(n,1);let s=this.patchSetMetadata[a];if(this.patchSetMetadata[c]||(this.patchSetMetadata[c]={moduleFilePath:e,patchPath:t,patches:[],authors:[],opTypes:[],schemaTypes:Array.from(o),lastUpdated:r,lastUpdatedBy:i}),s)for(let e of s.patches.slice())this.patchSetMetadata[c].patches.unshift(e),e.author!==null&&this.patchSetMetadata[c].authors.unshift(e.author),this.patchSetMetadata[c].opTypes.unshift(e.opType);else throw Error(`Could not find patch set metadata or patch metadata for (inserted) patch set path: ${a}`);a!==c&&delete this.patchSetMetadata[a]}this.patchSetMetadata[c]||(this.patchSetMetadata[c]={moduleFilePath:e,patchPath:t,patches:[],authors:[],opTypes:[],schemaTypes:o,lastUpdated:r,lastUpdatedBy:i}),i!==null&&!this.patchSetMetadata[c].authors.includes(i)&&this.patchSetMetadata[c].authors.unshift(i),this.patchSetMetadata[c].lastUpdatedBy=i,this.patchSetMetadata[c].lastUpdated=r,this.patchSetMetadata[c].opTypes.includes(a)||this.patchSetMetadata[c].opTypes.unshift(a),this.patchSetMetadata[c].patches.unshift({patchPath:s,patchId:n,author:i,createdAt:r,opType:a,schemaTypes:o}),this.orderedInsertKeys.includes(c)||this.orderedInsertKeys.unshift(c)}insert(e,t,n,r,i,a){if(!this.insertedPatches.has(r)){if(!t){this.insertPath(e,[],r,i,a,n.op,[],n.path);return}if(this.insertedPatches.add(r),n.op!==`file`&&n.op!==`test`)try{if(n.op===`replace`){let o=zb(t,n.path);this.insertPath(e,n.path,r,i,a,n.op,Array.from(o),n.path)}else if(n.op===`add`||n.op===`remove`||n.op===`move`||n.op===`copy`){let o=n.path.slice(0,-1),s=zb(t,o);if(s.size===1&&s.has(`array`)){if(this.insertPath(e,o,r,i,a,n.op,Array.from(s),n.path),n.op===`move`){let o=n.from.slice(0,-1),s=zb(t,o);this.insertPath(e,o,r,i,a,n.op,Array.from(s),n.path)}}else if(s.size===1&&s.has(`record`)){let o=n.path,s=zb(t,o);if(this.insertPath(e,o,r,i,a,n.op,Array.from(s),n.path),n.op===`move`){let o=n.from,s=zb(t,o);this.insertPath(e,o,r,i,a,n.op,Array.from(s),n.path)}}else if(s.size===1&&!(s.has(`image`)||s.has(`file`)))throw Error(`Cannot perform op: '${n.op}' on non-array or non-record schema. Type: ${s.values().next().value}`);else this.insertPath(e,o,r,i,a,n.op,[t.type],n.path)}else throw Error(`Unreachable op: `+n)}catch(o){o instanceof Error?console.error(`Could not resolve path while creating patch set`,o.message):console.error(`Could not resolve path while creating patch set`,o),this.insertPath(e,[],r,i,a,n.op,[t.type],n.path)}}}isInserted(e){return this.insertedPatches.has(e)}serialize(){return this.orderedInsertKeys.map(e=>{if(e in this.patchSetMetadata)return this.patchSetMetadata[e];throw Error(`Could not find patch set metadata or patch metadata for (inserted) patch set path: ${e}`)})}},_oe=class{constructor(e=hb){this.activity=e,this.events=new mb,this.patchSets=new goe}insertRecords(e,t,n){n&&this.patchSets.reset();let r=new Set;for(let n of e){let e=t[n.moduleFilePath];this.activity.work(`patch-set:insert`,n.patchId,n.patch.length);for(let t of n.patch)this.patchSets.insert(n.moduleFilePath,e,t,n.patchId,n.createdAt??new Date(0).toISOString(),n.authorId??null),t.op!==`file`&&t.op!==`test`&&r.add(`${n.moduleFilePath}?${t.path.join(`/`)}`)}this.events.emit({type:`patch-set:update`,patchSetPaths:[...r]})}async getPatchSets(e){return e.mode!==`current`&&this.insertRecords(e.records,e.schemas,e.mode===`rebuild`),this.activity.work(`patch-set:serialize`),this.patchSets.serialize()}reset(e){if(e!==void 0)throw Error(`PatchSetStore.reset: per-module reset is not supported — PatchSets has no per-module removal`);this.patchSets.reset(),this.events.emit({type:`patch-set:update`,patchSetPaths:[]})}},voe=class{constructor(){this.inserted=[],this.mustRebuild=!0}plan(e){if(this.mustRebuild||this.inserted.length>e.length)return{mode:`rebuild`,patchIds:[...e]};for(let t=0;t<this.inserted.length;t++)if(this.inserted[t]!==e[t])return{mode:`rebuild`,patchIds:[...e]};let t=e.slice(this.inserted.length);return t.length===0?{mode:`current`}:{mode:`append`,patchIds:t}}covers(e){if(e.mode!==`current`){if(e.mode===`rebuild`){this.inserted=[...e.patchIds],this.mustRebuild=!1;return}this.inserted=[...this.inserted,...e.patchIds]}}invalidate(){this.mustRebuild=!0,this.inserted=[]}insertedPatchIds(){return[...this.inserted]}};function Bb(e){if(e.customValidate===!0)return!0;switch(e.type){case`object`:return Object.values(e.items).some(Bb);case`array`:return Bb(e.item);case`record`:return Bb(e.item)||e.key!==void 0&&Bb(e.key);case`union`:return e.items.some(Bb);default:return!1}}function yoe(e,t,n){let r=[],i=new Set,a=(e,t,n)=>{if(t!==void 0&&!V.isJson(n)){if(n===null){t.customValidate===!0&&r.push(e);return}switch(t.customValidate===!0&&r.push(e),t.type){case`object`:if(!Vb(n))return;for(let r in t.items)r in n&&a(My(e,r),t.items[r],n[r]);return;case`record`:{if(!Vb(n))return;let r=Bb(t.item);for(let o in n){let s=n[o];if(V.isJson(s)){(t.customValidate===!0||r)&&i.add(o);continue}a(My(e,o),t.item,s)}return}case`array`:if(!Array.isArray(n))return;for(let r=0;r<n.length;r++)a(My(e,r),t.item,n[r]);return;case`union`:{let i=t.key;if(typeof i!=`string`||!Vb(n))return;let o=n[i];if(typeof o!=`string`)return;let s=t.items.filter(e=>e.type===`object`).find(e=>{let t=e.items[i];return t?.type===`literal`&&t.value===o});if(s){s.customValidate===!0&&t.customValidate!==!0&&r.push(e);for(let t in s.items)t in n&&a(My(e,t),s.items[t],n[t])}return}default:return}}};return a(e,t,n),{paths:r,needsJsonKeys:Array.from(i)}}function Vb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Hb={status:`stale`},boe=class e{constructor(e,t,n,r,i=hb){this.schemaStore=e,this.sourceStore=t,this.schemaValidation=n,this.host=r,this.activity=i,this.events=new mb,this.results=new Map,this.stale=new Set,this.inFlight=new Map,this.generation=0}listenTo(){let e=this.sourceStore.events.on(`source:init`,e=>{this.invalidate(e.sources)}),t=this.sourceStore.events.on(`source:patch-apply`,e=>{this.invalidate(e.modules)}),n=this.schemaStore.events.on(`schema:init`,e=>{this.invalidate(e.modules)});return()=>{e(),t(),n()}}invalidate(e){if(this.generation++,e.length===0)return;let t=e.filter(e=>this.results.has(e));for(let t of e)this.stale.add(t),this.results.delete(t);t.length>0&&this.events.emit({type:`validation:invalidate`,modules:t})}async validate(e){let t=this.results.get(e);if(t!==void 0&&!this.stale.has(e))return this.activity.work(`validation:cache-hit`,e),t;let n=this.inFlight.get(e);if(n)return this.activity.work(`validation:share-in-flight`,e),n;this.activity.work(`validation:cache-miss`,e);let r=this.run(e).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,r),r}static{this.MAX_RECOMPUTES=5}async run(t){let n=Hb;for(let r=0;r<e.MAX_RECOMPUTES;r++)if(n=await this.runOnce(t),n.status!==`validated`||!this.stale.has(t))return n;return n}async runOnce(e){let t=this.generation,n=this.schemaStore.get(e),r=this.sourceStore.moduleSource(e);if(n===void 0||r===void 0)return{status:`unknown-module`};this.activity.work(`validation:schema-validate`,e);let i=await this.schemaValidation.validate(e,r,n,String(this.schemaStore.version(e)));this.activity.work(`validation:collect-custom-targets`,e);let a=yoe(e,n,r).paths,o=i,s=`not-needed`;if(a.length>0){let t=await this.host.customValidate(e,a);t.status===`validated`?(this.activity.work(`validation:merge`,e),o=xoe(i,t.errors),s=`ran`):s=t.status===`unknown-module`?`unavailable`:`error`}let c={status:`validated`,errors:o,customValidatePaths:a,customValidateStatus:s,jsonEntriesLoaded:!this.sourceStore.hasUnloadedEntries(e)};return this.results.set(e,c),this.generation===t&&this.stale.delete(e),this.events.emit({type:`validation:result`,moduleFilePath:e,errors:o,customValidatePaths:a,customValidateStatus:s}),c}peek(e){let t=this.results.get(e);return t!==void 0&&!this.stale.has(e)?t:Hb}};function xoe(e,t){if(e===!1)return t;if(t===!1)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=e,i=n[t];if(!i){n[t]=r;continue}let a=new Set(i.map(e=>e.message));n[t]=[...i,...r.filter(e=>!a.has(e.message))]}return n}var Soe=`modulepreload`,Coe=function(e){return`/api/val/static/`+e},Ub={},woe=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Coe(t,n),t=s(t),t in Ub)return;Ub[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Soe,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Wb=s(((e,t)=>{t.exports={}})),Gb;function Kb(e,t,n){let r=typeof n,i=typeof e;if(r!==`undefined`){if(i!==`undefined`){if(n){if(i===`function`&&r===i)return function(t){return e(n(t))};if(t=e.constructor,t===n.constructor){if(t===Array)return n.concat(e);if(t===Map){var a=new Map(n);for(var o of e)a.set(o[0],o[1]);return a}if(t===Set){o=new Set(n);for(a of e.values())o.add(a);return o}}}return e}return n}return i===`undefined`?t:e}function qb(e,t){return e===void 0?t:e}function Jb(){return Object.create(null)}function Yb(e){return typeof e==`string`}function Xb(e){return typeof e==`object`}function Zb(e,t){if(Yb(t))e=e[t];else for(let n=0;e&&n<t.length;n++)e=e[t[n]];return e}var Toe=/[^\p{L}\p{N}]+/u,Eoe=/(\d{3})/g,Doe=/(\D)(\d{3})/g,Ooe=/(\d{3})(\D)/g,Qb=/[\u0300-\u036f]/g;function $b(e={}){if(!this||this.constructor!==$b)return new $b(...arguments);if(arguments.length)for(e=0;e<arguments.length;e++)this.assign(arguments[e]);else this.assign(e)}Gb=$b.prototype,Gb.assign=function(e){this.normalize=Kb(e.normalize,!0,this.normalize);let t=e.include,n=t||e.exclude||e.split,r;if(n||n===``){if(typeof n==`object`&&n.constructor!==RegExp){let e=``;r=!t,t||(e+=`\\p{Z}`),n.letter&&(e+=`\\p{L}`),n.number&&(e+=`\\p{N}`,r=!!t),n.symbol&&(e+=`\\p{S}`),n.punctuation&&(e+=`\\p{P}`),n.control&&(e+=`\\p{C}`),(n=n.char)&&(e+=typeof n==`object`?n.join(``):n);try{this.split=RegExp(`[`+(t?`^`:``)+e+`]+`,`u`)}catch{this.split=/\s+/}}else this.split=n,r=n===!1||`a1a`.split(n).length<2;this.numeric=Kb(e.numeric,r)}else{try{this.split=Kb(this.split,Toe)}catch{this.split=/\s+/}this.numeric=Kb(e.numeric,Kb(this.numeric,!0))}if(this.prepare=Kb(e.prepare,null,this.prepare),this.finalize=Kb(e.finalize,null,this.finalize),n=e.filter,this.filter=typeof n==`function`?n:Kb(n&&new Set(n),null,this.filter),this.dedupe=Kb(e.dedupe,!0,this.dedupe),this.matcher=Kb((n=e.matcher)&&new Map(n),null,this.matcher),this.mapper=Kb((n=e.mapper)&&new Map(n),null,this.mapper),this.stemmer=Kb((n=e.stemmer)&&new Map(n),null,this.stemmer),this.replacer=Kb(e.replacer,null,this.replacer),this.minlength=Kb(e.minlength,1,this.minlength),this.maxlength=Kb(e.maxlength,1024,this.maxlength),this.rtl=Kb(e.rtl,!1,this.rtl),(this.cache=n=Kb(e.cache,!0,this.cache))&&(this.F=null,this.L=typeof n==`number`?n:2e5,this.B=new Map,this.D=new Map,this.I=this.H=128),this.h=``,this.J=null,this.A=``,this.K=null,this.matcher)for(let e of this.matcher.keys())this.h+=(this.h?`|`:``)+e;if(this.stemmer)for(let e of this.stemmer.keys())this.A+=(this.A?`|`:``)+e;return this},Gb.addStemmer=function(e,t){return this.stemmer||=new Map,this.stemmer.set(e,t),this.A+=(this.A?`|`:``)+e,this.K=null,this.cache&&ex(this),this},Gb.addFilter=function(e){return typeof e==`function`?this.filter=e:(this.filter||=new Set,this.filter.add(e)),this.cache&&ex(this),this},Gb.addMapper=function(e,t){return typeof e==`object`?this.addReplacer(e,t):e.length>1?this.addMatcher(e,t):(this.mapper||=new Map,this.mapper.set(e,t),this.cache&&ex(this),this)},Gb.addMatcher=function(e,t){return typeof e==`object`?this.addReplacer(e,t):e.length<2&&(this.dedupe||this.mapper)?this.addMapper(e,t):(this.matcher||=new Map,this.matcher.set(e,t),this.h+=(this.h?`|`:``)+e,this.J=null,this.cache&&ex(this),this)},Gb.addReplacer=function(e,t){return typeof e==`string`?this.addMatcher(e,t):(this.replacer||=[],this.replacer.push(e,t),this.cache&&ex(this),this)},Gb.encode=function(e,t){if(this.cache&&e.length<=this.H){if(this.F){if(this.B.has(e))return this.B.get(e)}else this.F=setTimeout(ex,50,this)}this.normalize&&(e=typeof this.normalize==`function`?this.normalize(e):Qb?e.normalize(`NFKD`).replace(Qb,``).toLowerCase():e.toLowerCase()),this.prepare&&(e=this.prepare(e)),this.numeric&&e.length>3&&(e=e.replace(Doe,`$1 $2`).replace(Ooe,`$1 $2`).replace(Eoe,`$1 `));let n=!(this.dedupe||this.mapper||this.filter||this.matcher||this.stemmer||this.replacer),r=[],i=Jb(),a,o,s=this.split||this.split===``?e.split(this.split):[e];for(let e=0,l,u;e<s.length;e++)if((l=u=s[e])&&!(l.length<this.minlength||l.length>this.maxlength)){if(t){if(i[l])continue;i[l]=1}else{if(a===l)continue;a=l}if(n)r.push(l);else if(!this.filter||(typeof this.filter==`function`?this.filter(l):!this.filter.has(l))){if(this.cache&&l.length<=this.I){if(this.F){var c=this.D.get(l);if(c||c===``){c&&r.push(c);continue}}else this.F=setTimeout(ex,50,this)}if(this.stemmer){this.K||=RegExp(`(?!^)(`+this.A+`)$`);let e;for(;e!==l&&l.length>2;)e=l,l=l.replace(this.K,e=>this.stemmer.get(e))}if(l&&(this.mapper||this.dedupe&&l.length>1)){c=``;for(let e=0,t=``,n,r;e<l.length;e++)n=l.charAt(e),n===t&&this.dedupe||((r=this.mapper&&this.mapper.get(n))||r===``?r===t&&this.dedupe||!(t=r)||(c+=r):c+=t=n);l=c}if(this.matcher&&l.length>1&&(this.J||=RegExp(`(`+this.h+`)`,`g`),l=l.replace(this.J,e=>this.matcher.get(e))),l&&this.replacer)for(c=0;l&&c<this.replacer.length;c+=2)l=l.replace(this.replacer[c],this.replacer[c+1]);if(this.cache&&u.length<=this.I&&(this.D.set(u,l),this.D.size>this.L&&(this.D.clear(),this.I=this.I/1.1|0)),l){if(l!==u){if(t){if(i[l])continue;i[l]=1}else{if(o===l)continue;o=l}}r.push(l)}}}return this.finalize&&(r=this.finalize(r)||r),this.cache&&e.length<=this.H&&(this.B.set(e,r),this.B.size>this.L&&(this.B.clear(),this.H=this.H/1.1|0)),r};function ex(e){e.F=null,e.B.clear(),e.D.clear()}function tx(e,t,n){n||(t||typeof e!=`object`?typeof t==`object`&&(n=t,t=0):n=e),n&&(e=n.query||e,t=n.limit||t);let r=``+(t||0);n&&(r+=(n.offset||0)+!!n.context+!!n.suggest+(n.resolve!==!1)+(n.resolution||this.resolution)+(n.boost||0)),e=(``+e).toLowerCase(),this.cache||=new nx;let i=this.cache.get(e+r);if(!i){let a=n&&n.cache;a&&(n.cache=!1),i=this.search(e,t,n),a&&(n.cache=a),this.cache.set(e+r,i)}return i}function nx(e){this.limit=e&&e!==!0?e:1e3,this.cache=new Map,this.h=``}nx.prototype.set=function(e,t){this.cache.set(this.h=e,t),this.cache.size>this.limit&&this.cache.delete(this.cache.keys().next().value)},nx.prototype.get=function(e){let t=this.cache.get(e);return t&&this.h!==e&&(this.cache.delete(e),this.cache.set(this.h=e,t)),t},nx.prototype.remove=function(e){for(let t of this.cache){let n=t[0];t[1].includes(e)&&this.cache.delete(n)}},nx.prototype.clear=function(){this.cache.clear(),this.h=``};var rx={normalize:!1,numeric:!1,dedupe:!1},ix={},ax=new Map([[`b`,`p`],[`v`,`f`],[`w`,`f`],[`z`,`s`],[`x`,`s`],[`d`,`t`],[`n`,`m`],[`c`,`k`],[`g`,`k`],[`j`,`k`],[`q`,`k`],[`i`,`e`],[`y`,`e`],[`u`,`o`]]),ox=new Map([[`ae`,`a`],[`oe`,`o`],[`sh`,`s`],[`kh`,`k`],[`th`,`t`],[`ph`,`f`],[`pf`,`f`]]),sx=[/([^aeo])h(.)/g,`$1$2`,/([aeo])h([^aeo]|$)/g,`$1$2`,/(.)\1+/g,`$1`],cx={a:``,e:``,i:``,o:``,u:``,y:``,b:1,f:1,p:1,v:1,c:2,g:2,j:2,k:2,q:2,s:2,x:2,z:2,ß:2,d:3,t:3,l:4,m:5,n:5,r:6},lx={Exact:rx,Default:ix,Normalize:ix,LatinBalance:{mapper:ax},LatinAdvanced:{mapper:ax,matcher:ox,replacer:sx},LatinExtra:{mapper:ax,replacer:sx.concat([/(?!^)[aeo]/g,``]),matcher:ox},LatinSoundex:{dedupe:!1,include:{letter:!0},finalize:function(e){for(let n=0;n<e.length;n++){var t=e[n];let r=t.charAt(0),i=cx[r];for(let e=1,n;e<t.length&&(n=t.charAt(e),n===`h`||n===`w`||!(n=cx[n])||n===i||(r+=n,i=n,r.length!==4));e++);e[n]=r}}},CJK:{split:``},LatinExact:rx,LatinDefault:ix,LatinSimple:ix};function ux(e,t,n,r){let i=[];for(let a=0,o;a<e.index.length;a++)if(o=e.index[a],t>=o.length)t-=o.length;else{t=o[r?`splice`:`slice`](t,n);let a=t.length;if(a&&(i=i.length?i.concat(t):t,n-=a,r&&(e.length-=a),!n))break;t=0}return i}function dx(e){if(!this||this.constructor!==dx)return new dx(e);this.index=e?[e]:[],this.length=e?e.length:0;let t=this;return new Proxy([],{get(e,n){if(n===`length`)return t.length;if(n===`push`)return function(e){t.index[t.index.length-1].push(e),t.length++};if(n===`pop`)return function(){if(t.length)return t.length--,t.index[t.index.length-1].pop()};if(n===`indexOf`)return function(e){let n=0;for(let r=0,i,a;r<t.index.length;r++){if(i=t.index[r],a=i.indexOf(e),a>=0)return n+a;n+=i.length}return-1};if(n===`includes`)return function(e){for(let n=0;n<t.index.length;n++)if(t.index[n].includes(e))return!0;return!1};if(n===`slice`)return function(e,n){return ux(t,e||0,n||t.length,!1)};if(n===`splice`)return function(e,n){return ux(t,e||0,n||t.length,!0)};if(n===`constructor`)return Array;if(typeof n!=`symbol`)return(e=t.index[n/2**31|0])&&e[n]},set(e,n,r){return e=n/2**31|0,(t.index[e]||(t.index[e]=[]))[n]=r,t.length++,!0}})}dx.prototype.clear=function(){this.index.length=0},dx.prototype.push=function(){};function fx(e=8){if(!this||this.constructor!==fx)return new fx(e);this.index=Jb(),this.h=[],this.size=0,e>32?(this.B=hx,this.A=BigInt(e)):(this.B=mx,this.A=e)}fx.prototype.get=function(e){let t=this.index[this.B(e)];return t&&t.get(e)},fx.prototype.set=function(e,t){var n=this.B(e);let r=this.index[n];r?(n=r.size,r.set(e,t),(n-=r.size)&&this.size++):(this.index[n]=r=new Map([[e,t]]),this.h.push(r),this.size++)};function px(e=8){if(!this||this.constructor!==px)return new px(e);this.index=Jb(),this.h=[],this.size=0,e>32?(this.B=hx,this.A=BigInt(e)):(this.B=mx,this.A=e)}px.prototype.add=function(e){var t=this.B(e);let n=this.index[t];n?(t=n.size,n.add(e),(t-=n.size)&&this.size++):(this.index[t]=n=new Set([e]),this.h.push(n),this.size++)},Gb=fx.prototype,Gb.has=px.prototype.has=function(e){let t=this.index[this.B(e)];return t&&t.has(e)},Gb.delete=px.prototype.delete=function(e){let t=this.index[this.B(e)];t&&t.delete(e)&&this.size--},Gb.clear=px.prototype.clear=function(){this.index=Jb(),this.h=[],this.size=0},Gb.values=px.prototype.values=function*(){for(let e=0;e<this.h.length;e++)for(let t of this.h[e].values())yield t},Gb.keys=px.prototype.keys=function*(){for(let e=0;e<this.h.length;e++)for(let t of this.h[e].keys())yield t},Gb.entries=px.prototype.entries=function*(){for(let e=0;e<this.h.length;e++)for(let t of this.h[e].entries())yield t};function mx(e){let t=2**this.A-1;if(typeof e==`number`)return e&t;let n=0,r=this.A+1;for(let i=0;i<e.length;i++)n=(n*r^e.charCodeAt(i))&t;return this.A===32?n+2**31:n}function hx(e){let t=BigInt(2)**this.A-BigInt(1);var n=typeof e;if(n===`bigint`)return e&t;if(n===`number`)return BigInt(e)&t;n=BigInt(0);let r=this.A+BigInt(1);for(let i=0;i<e.length;i++)n=(n*r^BigInt(e.charCodeAt(i)))&t;return n}var gx,_x;async function koe(e){e=e.data;var t=e.task;let n=e.id,r=e.args;switch(t){case`init`:_x=e.options||{},(t=e.factory)?(Function(`return `+t)()(self),gx=new self.FlexSearch.Index(_x),delete self.FlexSearch):gx=new tS(_x),postMessage({id:n});break;default:let i;t===`export`&&(r[1]?(r[0]=_x.export,r[2]=0,r[3]=1):r=null),t===`import`?r[0]&&(e=await _x.import.call(gx,r[0]),gx.import(r[0],e)):((i=r&&gx[t].apply(gx,r))&&i.then&&(i=await i),i&&i.await&&(i=await i.await),t===`search`&&i.result&&(i=i.result)),postMessage(t===`search`?{id:n,msg:i}:{id:n})}}function vx(e){Sx.call(e,`add`),Sx.call(e,`append`),Sx.call(e,`search`),Sx.call(e,`update`),Sx.call(e,`remove`),Sx.call(e,`searchCache`)}var yx,bx,xx;function Aoe(){yx=xx=0}function Sx(e){this[e+`Async`]=function(){let t=arguments;var n=t[t.length-1];let r;if(typeof n==`function`&&(r=n,delete t[t.length-1]),yx?xx||=Date.now()-bx>=this.priority*this.priority*3:(yx=setTimeout(Aoe,0),bx=Date.now()),xx){let n=this;return new Promise(r=>{setTimeout(function(){r(n[e+`Async`].apply(n,t))},0)})}let i=this[e].apply(this,t);return n=i.then?i:new Promise(e=>e(i)),r&&n.then(r),n}}var Cx=0;function wx(e={},t){function n(n){function o(e){e=e.data||e;let t=e.id,n=t&&a.h[t];n&&(n(e.msg),delete a.h[t])}if(this.worker=n,this.h=Jb(),this.worker)return i?this.worker.on(`message`,o):this.worker.onmessage=o,e.config?new Promise(function(t){Cx>1e9&&(Cx=0),a.h[++Cx]=function(){t(a)},a.worker.postMessage({id:Cx,task:`init`,factory:r,options:e})}):(this.priority=e.priority||4,this.encoder=t||null,this.worker.postMessage({task:`init`,factory:r,options:e}),this)}if(!this||this.constructor!==wx)return new wx(e);let r=typeof self<`u`?self._factory:typeof window<`u`?window._factory:null;r&&=r.toString();let i=typeof window>`u`,a=this,o=joe(r,i,e.worker);return o.then?o.then(function(e){return n.call(a,e)}):n.call(this,o)}Tx(`add`),Tx(`append`),Tx(`search`),Tx(`update`),Tx(`remove`),Tx(`clear`),Tx(`export`),Tx(`import`),wx.prototype.searchCache=tx,vx(wx.prototype);function Tx(e){wx.prototype[e]=function(){let t=this,n=[].slice.call(arguments);var r=n[n.length-1];let i;return typeof r==`function`&&(i=r,n.pop()),r=new Promise(function(r){e===`export`&&typeof n[0]==`function`&&(n[0]=null),Cx>1e9&&(Cx=0),t.h[++Cx]=r,t.worker.postMessage({task:e,id:Cx,args:n})}),i?(r.then(i),this):r}}function joe(e,t,n){return t?typeof module<`u`?new(Wb()).Worker(__dirname+`/worker/node.js`):woe(()=>Promise.resolve().then(()=>u(Wb(),1)).then(function(e){return new e.Worker(import.meta.dirname+`/node/node.mjs`)}),void 0):e?new window.Worker(URL.createObjectURL(new Blob([`onmessage=`+koe.toString()],{type:`text/javascript`}))):new window.Worker(typeof n==`string`?n:import.meta.url.replace(`/worker.js`,`/worker/worker.js`).replace(`flexsearch.bundle.module.min.js`,`module/worker/worker.js`).replace(`flexsearch.bundle.module.min.mjs`,`module/worker/worker.js`),{type:`module`})}Rx.prototype.add=function(e,t,n){if(Xb(e)&&(t=e,e=Zb(t,this.key)),t&&(e||e===0)){if(!n&&this.reg.has(e))return this.update(e,t);for(let a=0,o;a<this.field.length;a++){o=this.B[a];var r=this.index.get(this.field[a]);if(typeof o==`function`){var i=o(t);i&&r.add(e,i,n,!0)}else i=o.G,(!i||i(t))&&(o.constructor===String?o=[``+o]:Yb(o)&&(o=[o]),Dx(t,o,this.D,0,r,e,o[0],n))}if(this.tag)for(r=0;r<this.A.length;r++){var a=this.A[r];i=this.tag.get(this.F[r]);let s=Jb();if(typeof a==`function`){if(a=a(t),!a)continue}else{var o=a.G;if(o&&!o(t))continue;a.constructor===String&&(a=``+a),a=Zb(t,a)}if(i&&a){Yb(a)&&(a=[a]);for(let t=0,r,c;t<a.length;t++)if(r=a[t],!s[r]&&(s[r]=1,(o=i.get(r))?c=o:i.set(r,c=[]),!n||!c.includes(e))){if(c.length===2**31-1){if(o=new dx(c),this.fastupdate)for(let e of this.reg.values())e.includes(c)&&(e[e.indexOf(c)]=o);i.set(r,c=o)}c.push(e),this.fastupdate&&((o=this.reg.get(e))?o.push(c):this.reg.set(e,[c]))}}}if(this.store&&(!n||!this.store.has(e))){let r;if(this.h){r=Jb();for(let e=0,i;e<this.h.length;e++){if(i=this.h[e],(n=i.G)&&!n(t))continue;let a;if(typeof i==`function`){if(a=i(t),!a)continue;i=[i.O]}else if(Yb(i)||i.constructor===String){r[i]=t[i];continue}Ex(t,r,i,0,i[0],a)}}this.store.set(e,r||t)}this.worker&&(this.fastupdate||this.reg.add(e))}return this};function Ex(e,t,n,r,i,a){if(e=e[i],r===n.length-1)t[i]=a||e;else if(e){if(e.constructor===Array)for(t=t[i]=Array(e.length),i=0;i<e.length;i++)Ex(e,t,n,r,i);else t=t[i]||(t[i]=Jb()),i=n[++r],Ex(e,t,n,r,i)}}function Dx(e,t,n,r,i,a,o,s){if(e=e[o]){if(r===t.length-1){if(e.constructor===Array){if(n[r]){for(t=0;t<e.length;t++)i.add(a,e[t],!0,!0);return}e=e.join(` `)}i.add(a,e,s,!0)}else if(e.constructor===Array)for(o=0;o<e.length;o++)Dx(e,t,n,r,i,a,o,s);else o=t[++r],Dx(e,t,n,r,i,a,o,s)}}function Ox(e,t,n,r){if(!e.length)return e;if(e.length===1)return e=e[0],e=n||e.length>t?e.slice(n,n+t):e,r?Lx.call(this,e):e;let i=[];for(let a=0,o,s;a<e.length;a++)if((o=e[a])&&(s=o.length)){if(n){if(n>=s){n-=s;continue}o=o.slice(n,n+t),s=o.length,n=0}if(s>t&&(o=o.slice(0,t),s=t),!i.length&&s>=t)return r?Lx.call(this,o):o;if(i.push(o),t-=s,!t)break}return i=i.length>1?[].concat.apply([],i):i[0],r?Lx.call(this,i):i}function kx(e,t,n,r){var i=r[0];if(i[0]&&i[0].query)return e[t].apply(e,i);if(!(t!==`and`&&t!==`not`||e.result.length||e.await||i.suggest))return r.length>1&&(i=r[r.length-1]),(r=i.resolve)?e.await||e.result:e;let a=[],o=0,s=0,c,l,u,d,f;for(t=0;t<r.length;t++)if(i=r[t]){var p=void 0;if(i.constructor===Mx)p=i.await||i.result;else if(i.then||i.constructor===Array)p=i;else{o=i.limit||0,s=i.offset||0,u=i.suggest,l=i.resolve,c=((d=i.highlight||e.highlight)||i.enrich)&&l,p=i.queue;let n=i.async||p,r=i.index,m=i.query;if(r?e.index||=r:r=e.index,m||i.tag){let o=i.field||i.pluck;if(o&&(!m||e.query&&!d||(e.query=m,e.field=o,e.highlight=d),r=r.index.get(o)),p&&(f||e.await)){f=1;let o,s=e.C.length,c=new Promise(function(e){o=e});(function(t,r){c.h=function(){r.index=null,r.resolve=!1;let i=n?t.searchAsync(r):t.search(r);return i.then?i.then(function(t){return e.C[s]=t=t.result||t,o(t),t}):(i=i.result||i,o(i),i)}})(r,Object.assign({},i)),e.C.push(c),a[t]=c;continue}i.resolve=!1,i.index=null,p=n?r.searchAsync(i):r.search(i),i.resolve=l,i.index=r}else if(i.and)p=Ax(i,`and`,r);else if(i.or)p=Ax(i,`or`,r);else if(i.not)p=Ax(i,`not`,r);else if(i.xor)p=Ax(i,`xor`,r);else continue}p.await?(f=1,p=p.await):p.then?(f=1,p=p.then(function(e){return e.result||e})):p=p.result||p,a[t]=p}if(f&&!e.await&&(e.await=new Promise(function(t){e.return=t})),f){let t=Promise.all(a).then(function(r){for(let i=0;i<e.C.length;i++)if(e.C[i]===t){e.C[i]=function(){return n.call(e,r,o,s,c,l,u,d)};break}Nx(e)});e.C.push(t)}else if(e.await)e.C.push(function(){return n.call(e,a,o,s,c,l,u,d)});else return n.call(e,a,o,s,c,l,u,d);return l?e.await||e.result:e}function Ax(e,t,n){e=e[t];let r=e[0]||e;return r.index||=n,n=new Mx(r),e.length>1&&(n=n[t].apply(n,e.slice(1))),n}Mx.prototype.or=function(){return kx(this,`or`,Moe,arguments)};function Moe(e,t,n,r,i,a,o){return e.length&&(this.result.length&&e.push(this.result),e.length<2?this.result=e[0]:(this.result=Fx(e,t,n,!1,this.h),n=0)),i&&(this.await=null),i?this.resolve(t,n,r,o):this}Mx.prototype.and=function(){return kx(this,`and`,Noe,arguments)};function Noe(e,t,n,r,i,a,o){if(!a&&!this.result.length)return i?this.result:this;let s;if(e.length){if(this.result.length&&e.unshift(this.result),e.length<2)this.result=e[0];else{let r=0;for(let t=0,n,i;t<e.length;t++)if((n=e[t])&&(i=n.length))r<i&&(r=i);else if(!a){r=0;break}r?(this.result=Px(e,r,t,n,a,this.h,i),s=!0):this.result=[]}}else a||(this.result=e);return i&&(this.await=null),i?this.resolve(t,n,r,o,s):this}Mx.prototype.xor=function(){return kx(this,`xor`,Poe,arguments)};function Poe(e,t,n,r,i,a,o){if(e.length){if(this.result.length&&e.unshift(this.result),e.length<2)this.result=e[0];else{a:{a=n;var s=this.h;let r=[],o=Jb(),c=0;for(let t=0,n;t<e.length;t++)if(n=e[t]){c<n.length&&(c=n.length);for(let e=0,t;e<n.length;e++)if(t=n[e])for(let e=0,n;e<t.length;e++)n=t[e],o[n]=o[n]?2:1}for(let n=0,l,u=0;n<c;n++)for(let c=0,d;c<e.length;c++)if((d=e[c])&&(l=d[n])){for(let d=0,f;d<l.length;d++)if(f=l[d],o[f]===1){if(a)a--;else if(i){if(r.push(f),r.length===t){e=r;break a}}else{let i=n+(c?s:0);if(r[i]||(r[i]=[]),r[i].push(f),++u===t){e=r;break a}}}}e=r}this.result=e,s=!0}}else a||(this.result=e);return i&&(this.await=null),i?this.resolve(t,n,r,o,s):this}Mx.prototype.not=function(){return kx(this,`not`,Foe,arguments)};function Foe(e,t,n,r,i,a,o){if(!a&&!this.result.length)return i?this.result:this;if(e.length&&this.result.length){a:{a=n;var s=[];e=new Set(e.flat().flat());for(let n=0,r,o=0;n<this.result.length;n++)if(r=this.result[n]){for(let c=0,l;c<r.length;c++)if(l=r[c],!e.has(l)){if(a)a--;else if(i){if(s.push(l),s.length===t){e=s;break a}}else if(s[n]||(s[n]=[]),s[n].push(l),++o===t){e=s;break a}}}e=s}this.result=e,s=!0}return i&&(this.await=null),i?this.resolve(t,n,r,o,s):this}function jx(e,t,n,r,i){let a,o,s;typeof i==`string`?(a=i,i=``):a=i.template,o=a.indexOf(`$1`),s=a.substring(o+2),o=a.substring(0,o);let c=i&&i.boundary,l=!i||i.clip!==!1,u=i&&i.merge&&s&&o&&RegExp(s+` `+o,`g`);i&&=i.ellipsis;var d=0;if(typeof i==`object`){var f=i.template;d=f.length-2,i=i.pattern}typeof i!=`string`&&(i=i===!1?``:`...`),d&&(i=f.replace(`$1`,i)),f=i.length-d;let p,m;typeof c==`object`&&(p=c.before,p===0&&(p=-1),m=c.after,m===0&&(m=-1),c=c.total||9e5),d=new Map;for(let N=0,P,F,I;N<t.length;N++){let L;if(r)L=t,I=r;else{var h=t[N];if(I=h.field,!I)continue;L=h.result}F=n.get(I),P=F.encoder,h=d.get(P),typeof h!=`string`&&(h=P.encode(e),d.set(P,h));for(let e=0;e<L.length;e++){var g=L[e].doc;if(!g||(g=Zb(g,I),!g))continue;var _=g.trim().split(/\s+/);if(!_.length)continue;g=``;var v=[];let t=[];for(var y=-1,b=-1,x=0,S=0;S<_.length;S++){var C=_[S],w=P.encode(C);w=w.length>1?w.join(` `):w[0];let e;if(w&&C){for(var T=C.length,E=(P.split?C.replace(P.split,``):C).length-w.length,D=``,O=0,k=0;k<h.length;k++){var A=h[k];if(A){var j=A.length;j+=E<0?0:E,O&&j<=O||(A=w.indexOf(A),A>-1&&(D=(A?C.substring(0,A):``)+o+C.substring(A,A+j)+s+(A+j<T?C.substring(A+j):``),O=j,e=!0))}}D&&(c&&(y<0&&(y=g.length+ +!!g),b=g.length+ +!!g+D.length,x+=T,t.push(v.length),v.push({match:D})),g+=(g?` `:``)+D)}if(!e)C=_[S],g+=(g?` `:``)+C,c&&v.push({text:C});else if(c&&x>=c)break}if(x=t.length*(a.length-2),p||m||c&&g.length-x>c){if(x=c+x-f*2,S=b-y,p>0&&(S+=p),m>0&&(S+=m),S<=x)_=p?y-(p>0?p:0):y-((x-S)/2|0),v=m?b+(m>0?m:0):_+x,l||(_>0&&g.charAt(_)!==` `&&g.charAt(_-1)!==` `&&(_=g.indexOf(` `,_),_<0&&(_=0)),v<g.length&&g.charAt(v-1)!==` `&&g.charAt(v)!==` `&&(v=g.lastIndexOf(` `,v),v<b?v=b:++v)),g=(_?i:``)+g.substring(_,v)+(v<g.length?i:``);else{for(b=[],y={},x={},S={},C={},w={},D=E=T=0,k=O=1;;){var M=void 0;for(let e=0,n;e<t.length;e++){if(n=t[e],D){if(E!==D){if(S[e+1])continue;if(n+=D,y[n]){T-=f,x[e+1]=1,S[e+1]=1;continue}if(n>=v.length-1){if(n>=v.length){S[e+1]=1,n>=_.length&&(x[e+1]=1);continue}T-=f}if(g=v[n].text,j=m&&w[e]){if(j>0){if(g.length>j){if(S[e+1]=1,l)g=g.substring(0,j);else continue}(j-=g.length)||(j=-1),w[e]=j}else{S[e+1]=1;continue}}if(T+g.length+1<=c)g=` `+g,b[e]+=g;else if(l)M=c-T-1,M>0&&(g=` `+g.substring(0,M),b[e]+=g),S[e+1]=1;else{S[e+1]=1;continue}}else{if(S[e])continue;if(n-=E,y[n]){T-=f,S[e]=1,x[e]=1;continue}if(n<=0){if(n<0){S[e]=1,x[e]=1;continue}T-=f}if(g=v[n].text,j=p&&C[e]){if(j>0){if(g.length>j){if(S[e]=1,l)g=g.substring(g.length-j);else continue}(j-=g.length)||(j=-1),C[e]=j}else{S[e]=1;continue}}if(T+g.length+1<=c)g+=` `,b[e]=g+b[e];else if(l)M=g.length+1-(c-T),M>=0&&M<g.length&&(g=g.substring(M)+` `,b[e]=g+b[e]),S[e]=1;else{S[e]=1;continue}}}else{g=v[n].match,p&&(C[e]=p),m&&(w[e]=m),e&&T++;let t;if(n?!e&&f&&(T+=f):(x[e]=1,S[e]=1),n>=_.length-1||n<v.length-1&&v[n+1].match?t=1:f&&(T+=f),T-=a.length-2,!e||T+g.length<=c)b[e]=g;else{M=O=k=x[e]=0;break}t&&(x[e+1]=1,S[e+1]=1)}T+=g.length,M=y[n]=1}if(M)E===D?D++:E++;else{if(E===D?O=0:k=0,!O&&!k)break;O?(E++,D=E):D++}}g=``;for(let e=0,t;e<b.length;e++)t=(x[e]?e?` `:``:(e&&!i?` `:``)+i)+b[e],g+=t;i&&!x[b.length]&&(g+=i)}}u&&(g=g.replace(u,` `)),L[e].highlight=g}if(r)break}return t}function Mx(e,t){if(!this||this.constructor!==Mx)return new Mx(e,t);let n=0,r,i,a,o,s,c;if(e&&e.index){let r=e;if(t=r.index,n=r.boost||0,i=r.query){a=r.field||r.pluck,o=r.highlight;let n=r.resolve;e=r.async||r.queue,r.resolve=!1,r.index=null,e=e?t.searchAsync(r):t.search(r),r.resolve=n,r.index=t,e=e.result||e}else e=[]}if(e&&e.then){let t=this;e=e.then(function(e){t.C[0]=t.result=e.result||e,Nx(t)}),r=[e],e=[],s=new Promise(function(e){c=e})}this.index=t||null,this.result=e||[],this.h=n,this.C=r||[],this.await=s||null,this.return=c||null,this.highlight=o||null,this.query=i||``,this.field=a||``}Gb=Mx.prototype,Gb.limit=function(e){if(this.await){let t=this;this.C.push(function(){return t.limit(e).result})}else if(this.result.length){let t=[];for(let n=0,r;n<this.result.length;n++)if(r=this.result[n]){if(r.length<=e){if(t[n]=r,e-=r.length,!e)break}else{t[n]=r.slice(0,e);break}}this.result=t}return this},Gb.offset=function(e){if(this.await){let t=this;this.C.push(function(){return t.offset(e).result})}else if(this.result.length){let t=[];for(let n=0,r;n<this.result.length;n++)(r=this.result[n])&&(r.length<=e?e-=r.length:(t[n]=r.slice(e),e=0));this.result=t}return this},Gb.boost=function(e){if(this.await){let t=this;this.C.push(function(){return t.boost(e).result})}else this.h+=e;return this};function Nx(e,t){let n=e.result;var r=e.await;e.await=null;for(let t=0,i;t<e.C.length;t++)if(i=e.C[t]){if(typeof i==`function`)n=i(),e.C[t]=n=n.result||n,t--;else if(i.h)n=i.h(),e.C[t]=n=n.result||n,t--;else if(i.then)return e.await=r}return r=e.return,e.C=[],e.return=null,t||r(n),n}Gb.resolve=function(e,t,n,r,i){let a=this.await?Nx(this,!0):this.result;if(a.then){let o=this;return a.then(function(){return o.resolve(e,t,n,r,i)})}return a.length&&(typeof e==`object`?(r=e.highlight||this.highlight,n=!!r||e.enrich,t=e.offset,e=e.limit):(r||=this.highlight,n=!!r||n),a=i?n?Lx.call(this.index,a):a:Ox.call(this.index,a,e||100,t,n)),this.finalize(a,r)},Gb.finalize=function(e,t){if(e.then){let n=this;return e.then(function(e){return n.finalize(e,t)})}t&&e.length&&this.query&&(e=jx(this.query,e,this.index.index,this.field,t));let n=this.return;return this.highlight=this.index=this.result=this.C=this.await=this.return=null,this.query=this.field=``,n&&n(e),e};function Px(e,t,n,r,i,a,o){let s=e.length,c=[],l,u;l=Jb();for(let d=0,f,p,m,h;d<t;d++)for(let t=0;t<s;t++)if(m=e[t],d<m.length&&(f=m[d]))for(let e=0;e<f.length;e++){if(p=f[e],(u=l[p])?l[p]++:(u=0,l[p]=1),h=c[u]||(c[u]=[]),!o){let e=d+(t||!i?0:a||0);h=h[e]||(h[e]=[])}if(h.push(p),o&&n&&u===s-1&&h.length-r===n)return r?h.slice(r):h}if(e=c.length){if(i)c=c.length>1?Fx(c,n,r,o,a):(c=c[0])&&n&&c.length>n||r?c.slice(r,n+r):c;else{if(e<s)return[];if(c=c[e-1],n||r){if(o)(c.length>n||r)&&(c=c.slice(r,n+r));else{i=[];for(let e=0,t;e<c.length;e++)if(t=c[e]){if(r&&t.length>r)r-=t.length;else if((n&&t.length>n||r)&&(t=t.slice(r,n+r),n-=t.length,r&&(r-=t.length)),i.push(t),!n)break}c=i}}}}return c}function Fx(e,t,n,r,i){let a=[],o=Jb(),s;var c=e.length;let l;if(r){for(i=c-1;i>=0;i--)if(l=(r=e[i])&&r.length){for(c=0;c<l;c++)if(s=r[c],!o[s]){if(o[s]=1,n)n--;else if(a.push(s),a.length===t)return a}}}else for(let u=c-1,d,f=0;u>=0;u--){d=e[u];for(let e=0;e<d.length;e++)if(l=(r=d[e])&&r.length){for(let d=0;d<l;d++)if(s=r[d],!o[s]){if(o[s]=1,n)n--;else{let n=(e+(u<c-1&&i||0))/(u+1)|0;if((a[n]||(a[n]=[])).push(s),++f===t)return a}}}}return a}function Ioe(e,t,n,r,i){let a=Jb(),o=[];for(let e=0,n;e<t.length;e++){n=t[e];for(let e=0;e<n.length;e++)a[n[e]]=1}if(i){for(let t=0,i;t<e.length;t++)if(i=e[t],a[i]){if(r)r--;else if(o.push(i),a[i]=0,n&&--n===0)break}}else for(let n=0,r,i;n<e.result.length;n++)for(r=e.result[n],t=0;t<r.length;t++)i=r[t],a[i]&&((o[n]||(o[n]=[])).push(i),a[i]=0);return o}Rx.prototype.search=function(e,t,n,r){n||(!t&&Xb(e)?(n=e,e=``):Xb(t)&&(n=t,t=0));let i=[];var a=[];let o,s,c,l,u,d,f=0,p=!0,m;if(n){n.constructor===Array&&(n={index:n}),e=n.query||e,o=n.pluck,s=n.merge,l=n.boost,d=o||n.field||(d=n.index)&&(d.index?null:d);var h=this.tag&&n.tag;c=n.suggest,p=n.resolve!==!1,u=n.cache,m=p&&this.store&&n.highlight;var g=!!m||p&&this.store&&n.enrich;t=n.limit||t;var _=n.offset||0;if(t||=p?100:0,h&&(!this.db||!r)){h.constructor!==Array&&(h=[h]);var v=[];for(let e=0,t;e<h.length;e++)if(t=h[e],t.field&&t.tag){var y=t.tag;if(y.constructor===Array)for(var b=0;b<y.length;b++)v.push(t.field,y[b]);else v.push(t.field,y)}else{y=Object.keys(t);for(let e=0,n,r;e<y.length;e++)if(n=y[e],r=t[n],r.constructor===Array)for(b=0;b<r.length;b++)v.push(n,r[b]);else v.push(n,r)}if(h=v,!e){if(a=[],v.length)for(h=0;h<v.length;h+=2){if(this.db){if(r=this.index.get(v[h]),!r)continue;a.push(r=r.db.tag(v[h+1],t,_,g))}else r=Loe.call(this,v[h],v[h+1],t,_,g);i.push(p?{field:v[h],tag:v[h+1],result:r}:[r])}if(a.length){let e=this;return Promise.all(a).then(function(t){for(let e=0;e<t.length;e++)p?i[e].result=t[e]:i[e]=t[e];return p?i:new Mx(i.length>1?Px(i,1,0,0,c,l):i[0],e)})}return p?i:new Mx(i.length>1?Px(i,1,0,0,c,l):i[0],this)}}p||o||!(d||=this.field)||(Yb(d)?o=d:(d.constructor===Array&&d.length===1&&(d=d[0]),o=d.field||d.index)),d&&d.constructor!==Array&&(d=[d])}d||=this.field;let x;v=(this.worker||this.db)&&!r&&[];for(let o=0,s,l,C;o<d.length;o++){if(l=d[o],this.db&&this.tag&&!this.B[o])continue;let w;if(Yb(l)||(w=l,l=w.field,e=w.query||e,t=qb(w.limit,t),_=qb(w.offset,_),c=qb(w.suggest,c),m=p&&this.store&&qb(w.highlight,m),g=!!m||p&&this.store&&qb(w.enrich,g),u=qb(w.cache,u)),r)s=r[o];else{y=w||n||{},b=y.enrich;var S=this.index.get(l);if(h&&(this.db&&(y.tag=h,y.field=d,x=S.db.support_tag_search),!x&&b&&(y.enrich=!1),x||(y.limit=0,y.offset=0)),s=u?S.searchCache(e,h&&!x?0:t,y):S.search(e,h&&!x?0:t,y),h&&!x&&(y.limit=t,y.offset=_),b&&(y.enrich=b),v){v[o]=s;continue}}if(C=(s=s.result||s)&&s.length,h&&C){if(y=[],b=0,this.db&&r){if(!x)for(S=d.length;S<r.length;S++){let e=r[S];if(e&&e.length)b++,y.push(e);else if(!c)return p?i:new Mx(i,this)}}else for(let e=0,t,n;e<h.length;e+=2){if(t=this.tag.get(h[e]),!t){if(c)continue;return p?i:new Mx(i,this)}if((t&&=t.get(h[e+1]))&&t.length)b++,y.push(t);else if(!c)return p?i:new Mx(i,this)}if(b){if(s=Ioe(s,y,t,_,p),C=s.length,!C&&!c)return p?s:new Mx(s,this);b--}}if(C)a[f]=l,i.push(s),f++;else if(d.length===1)return p?i:new Mx(i,this)}if(v){if(this.db&&h&&h.length&&!x)for(g=0;g<h.length;g+=2){if(a=this.index.get(h[g]),!a){if(c)continue;return p?i:new Mx(i,this)}v.push(a.db.tag(h[g+1],t,_,!1))}let r=this;return Promise.all(v).then(function(i){return n&&(n.resolve=p),i.length&&(i=r.search(e,t,n,i)),i})}if(!f)return p?i:new Mx(i,this);if(o&&(!g||!this.store))return i=i[0],p?i:new Mx(i,this);for(v=[],_=0;_<a.length;_++){if(h=i[_],g&&h.length&&h[0].doc===void 0&&(this.db?v.push(h=this.index.get(this.field[0]).db.enrich(h)):h=Lx.call(this,h)),o)return p?m?jx(e,h,this.index,o,m):h:new Mx(h,this);i[_]={field:a[_],result:h}}if(g&&this.db&&v.length){let t=this;return Promise.all(v).then(function(n){for(let e=0;e<n.length;e++)i[e].result=n[e];return m&&(i=jx(e,i,t.index,o,m)),s?Ix(i):i})}return m&&(i=jx(e,i,this.index,o,m)),s?Ix(i):i};function Ix(e){let t=[],n=Jb(),r=Jb();for(let i=0,a,o,s,c,l,u,d;i<e.length;i++){a=e[i],o=a.field,s=a.result;for(let e=0;e<s.length;e++)l=s[e],typeof l==`object`?c=l.id:l={id:c=l},(u=n[c])?u.push(o):(l.field=n[c]=[o],t.push(l)),(d=l.highlight)&&(u=r[c],u||(r[c]=u={},l.highlight=u),u[o]=d)}return t}function Loe(e,t,n,r,i){return e=this.tag.get(e),!e||(e=e.get(t),!e)?[]:(t=e.length-r,t>0&&((n&&t>n||r)&&(e=e.slice(r,r+n)),i&&(e=Lx.call(this,e))),e)}function Lx(e){if(!this||!this.store)return e;if(this.db)return this.index.get(this.field[0]).db.enrich(e);let t=Array(e.length);for(let n=0,r;n<e.length;n++)r=e[n],t[n]={id:r,doc:this.store.get(r)};return t}function Rx(e){if(!this||this.constructor!==Rx)return new Rx(e);let t=e.document||e.doc||e,n,r;if(this.B=[],this.field=[],this.D=[],this.key=(n=t.key||t.id)&&zx(n,this.D)||`id`,(r=e.keystore||0)&&(this.keystore=r),this.fastupdate=!!e.fastupdate,this.reg=!this.fastupdate||e.worker||e.db?r?new px(r):new Set:r?new fx(r):new Map,this.h=(n=t.store||null)&&n&&n!==!0&&[],this.store=n?r?new fx(r):new Map:null,this.cache=(n=e.cache||null)&&new nx(n),e.cache=!1,this.worker=e.worker||!1,this.priority=e.priority||4,this.index=Roe.call(this,e,t),this.tag=null,(n=t.tag)&&(typeof n==`string`&&(n=[n]),n.length)){this.tag=new Map,this.A=[],this.F=[];for(let e=0,t,r;e<n.length;e++){if(t=n[e],r=t.field||t,!r)throw Error(`The tag field from the document descriptor is undefined.`);t.custom?this.A[e]=t.custom:(this.A[e]=zx(r,this.D),t.filter&&(typeof this.A[e]==`string`&&(this.A[e]=new String(this.A[e])),this.A[e].G=t.filter)),this.F[e]=r,this.tag.set(r,new Map)}}if(this.worker){this.fastupdate=!1,e=[];for(let t of this.index.values())t.then&&e.push(t);if(e.length){let t=this;return Promise.all(e).then(function(e){let n=0;for(let r of t.index.entries()){let i=r[0],a=r[1];a.then&&(a=e[n],t.index.set(i,a),n++)}return t})}}else e.db&&(this.fastupdate=!1,this.mount(e.db))}Gb=Rx.prototype,Gb.mount=function(e){let t=this.field;if(this.tag)for(let e=0,r;e<this.F.length;e++){r=this.F[e];var n=void 0;this.index.set(r,n=new tS({},this.reg)),t===this.field&&(t=t.slice(0)),t.push(r),n.tag=this.tag.get(r)}n=[];let r={db:e.db,type:e.type,fastupdate:e.fastupdate};for(let i=0,a,o;i<t.length;i++){r.field=o=t[i],a=this.index.get(o);let s=new e.constructor(e.id,r);s.id=e.id,n[i]=s.mount(a),a.document=!0,i?a.bypass=!0:a.store=this.store}let i=this;return this.db=Promise.all(n).then(function(){i.db=!0})},Gb.commit=async function(){let e=[];for(let t of this.index.values())e.push(t.commit());await Promise.all(e),this.reg.clear()},Gb.destroy=function(){let e=[];for(let t of this.index.values())e.push(t.destroy());return Promise.all(e)};function Roe(e,t){let n=new Map,r=t.index||t.field||t;Yb(r)&&(r=[r]);for(let t=0,a,o;t<r.length;t++){if(a=r[t],Yb(a)||(o=a,a=a.field),o=Xb(o)?Object.assign({},e,o):e,this.worker){var i=void 0;i=(i=o.encoder)&&i.encode?i:new $b(typeof i==`string`?lx[i]:i||{}),i=new wx(o,i),n.set(a,i)}this.worker||n.set(a,new tS(o,this.reg)),o.custom?this.B[t]=o.custom:(this.B[t]=zx(a,this.D),o.filter&&(typeof this.B[t]==`string`&&(this.B[t]=new String(this.B[t])),this.B[t].G=o.filter)),this.field[t]=a}if(this.h){e=t.store,Yb(e)&&(e=[e]);for(let t=0,n,r;t<e.length;t++)n=e[t],r=n.field||n,n.custom?(this.h[t]=n.custom,n.custom.O=r):(this.h[t]=zx(r,this.D),n.filter&&(typeof this.h[t]==`string`&&(this.h[t]=new String(this.h[t])),this.h[t].G=n.filter))}return n}function zx(e,t){let n=e.split(`:`),r=0;for(let i=0;i<n.length;i++)e=n[i],e[e.length-1]===`]`&&(e=e.substring(0,e.length-2))&&(t[r]=!0),e&&(n[r++]=e);return r<n.length&&(n.length=r),r>1?n:n[0]}Gb.append=function(e,t){return this.add(e,t,!0)},Gb.update=function(e,t){return this.remove(e).add(e,t)},Gb.remove=function(e){Xb(e)&&(e=Zb(e,this.key));for(var t of this.index.values())t.remove(e,!0);if(this.reg.has(e)){if(this.tag&&!this.fastupdate)for(let n of this.tag.values())for(let r of n){t=r[0];let i=r[1],a=i.indexOf(e);a>-1&&(i.length>1?i.splice(a,1):n.delete(t))}this.store&&this.store.delete(e),this.reg.delete(e)}return this.cache&&this.cache.remove(e),this},Gb.clear=function(){let e=[];for(let t of this.index.values()){let n=t.clear();n.then&&e.push(n)}if(this.tag)for(let e of this.tag.values())e.clear();return this.store&&this.store.clear(),this.cache&&this.cache.clear(),e.length?Promise.all(e):this},Gb.contain=function(e){return this.db?this.index.get(this.field[0]).db.has(e):this.reg.has(e)},Gb.cleanup=function(){for(let e of this.index.values())e.cleanup();return this},Gb.get=function(e){return this.db?this.index.get(this.field[0]).db.enrich(e).then(function(e){return e[0]&&e[0].doc||null}):this.store.get(e)||null},Gb.set=function(e,t){return typeof e==`object`&&(t=e,e=Zb(t,this.key)),this.store.set(e,t),this},Gb.searchCache=tx,Gb.export=zoe,Gb.import=Boe,vx(Rx.prototype);function Bx(e,t=0){let n=[],r=[];t&&=25e4/t*5e3|0;for(let i of e.entries())r.push(i),r.length===t&&(n.push(r),r=[]);return r.length&&n.push(r),n}function Vx(e,t){t||=new Map;for(let n=0,r;n<e.length;n++)r=e[n],t.set(r[0],r[1]);return t}function Hx(e,t=0){let n=[],r=[];t&&=25e4/t*1e3|0;for(let i of e.entries())r.push([i[0],Bx(i[1])[0]||[]]),r.length===t&&(n.push(r),r=[]);return r.length&&n.push(r),n}function Ux(e,t){t||=new Map;for(let n=0,r,i;n<e.length;n++)r=e[n],i=t.get(r[0]),t.set(r[0],Vx(r[1],i));return t}function Wx(e){let t=[],n=[];for(let r of e.keys())n.push(r),n.length===25e4&&(t.push(n),n=[]);return n.length&&t.push(n),t}function Gx(e,t){t||=new Set;for(let n=0;n<e.length;n++)t.add(e[n]);return t}function Kx(e,t,n,r,i,a,o=0){let s=r&&r.constructor===Array;var c=s?r.shift():r;if(!c)return this.export(e,t,i,a+1);if((c=e((t?t+`.`:``)+(o+1)+`.`+n,JSON.stringify(c)))&&c.then){let l=this;return c.then(function(){return Kx.call(l,e,t,n,s?r:null,i,a,o+1)})}return Kx.call(this,e,t,n,s?r:null,i,a,o+1)}function zoe(e,t,n=0,r=0){if(n<this.field.length){let i=this.field[n];if((t=this.index.get(i).export(e,i,n,r=1))&&t.then){let r=this;return t.then(function(){return r.export(e,i,n+1)})}return this.export(e,i,n+1)}let i,a;switch(r){case 0:i=`reg`,a=Wx(this.reg),t=null;break;case 1:i=`tag`,a=this.tag&&Hx(this.tag,this.reg.size),t=null;break;case 2:i=`doc`,a=this.store&&Bx(this.store),t=null;break;default:return}return Kx.call(this,e,t,i,a||null,n,r)}function Boe(e,t){var n=e.split(`.`);n[n.length-1]===`json`&&n.pop();let r=n.length>2?n[0]:``;if(n=n.length>2?n[2]:n[1],this.worker&&r)return this.index.get(r).import(e);if(t){if(typeof t==`string`&&(t=JSON.parse(t)),r)return this.index.get(r).import(n,t);switch(n){case`reg`:this.fastupdate=!1,this.reg=Gx(t,this.reg);for(let e=0,t;e<this.field.length;e++)t=this.index.get(this.field[e]),t.fastupdate=!1,t.reg=this.reg;if(this.worker){t=[];for(let n of this.index.values())t.push(n.import(e));return Promise.all(t)}break;case`tag`:this.tag=Ux(t,this.tag);break;case`doc`:this.store=Vx(t,this.store)}}}function qx(e,t){let n=``;for(let r of e.entries()){e=r[0];let i=r[1],a=``;for(let e=0,n;e<i.length;e++){n=i[e]||[``];let r=``;for(let e=0;e<n.length;e++)r+=(r?`,`:``)+(t===`string`?`"`+n[e]+`"`:n[e]);r=`[`+r+`]`,a+=(a?`,`:``)+r}a=`["`+e+`",[`+a+`]]`,n+=(n?`,`:``)+a}return n}tS.prototype.remove=function(e,t){let n=this.reg.size&&(this.fastupdate?this.reg.get(e):this.reg.has(e));if(n){if(this.fastupdate){for(let t=0,r,i;t<n.length;t++)if((r=n[t])&&(i=r.length)){if(r[i-1]===e)r.pop();else{let t=r.indexOf(e);t>=0&&r.splice(t,1)}}}else Jx(this.map,e),this.depth&&Jx(this.ctx,e);t||this.reg.delete(e)}return this.db&&(this.commit_task.push({del:e}),this.M&&nS(this)),this.cache&&this.cache.remove(e),this};function Jx(e,t){let n=0;var r=t===void 0;if(e.constructor===Array){for(let i=0,a,o,s;i<e.length;i++)if((a=e[i])&&a.length){if(r)return 1;if(o=a.indexOf(t),o>=0){if(a.length>1)return a.splice(o,1),1;if(delete e[i],n)return 1;s=1}else{if(s)return 1;n++}}}else for(let i of e.entries())r=i[0],Jx(i[1],t)?n++:e.delete(r);return n}var Voe={memory:{resolution:1},performance:{resolution:3,fastupdate:!0,context:{depth:1,resolution:1}},match:{tokenize:`forward`},score:{resolution:9,context:{depth:2,resolution:3}}};tS.prototype.add=function(e,t,n,r){if(t&&(e||e===0)){if(!r&&!n&&this.reg.has(e))return this.update(e,t);r=this.depth,t=this.encoder.encode(t,!r);let l=t.length;if(l){let u=Jb(),d=Jb(),f=this.resolution;for(let p=0;p<l;p++){let m=t[this.rtl?l-1-p:p];var i=m.length;if(i&&(r||!d[m])){var a=this.score?this.score(t,m,p,null,0):Xx(f,l,p),o=``;switch(this.tokenize){case`tolerant`:if(Yx(this,d,m,a,e,n),i>2){for(let t=1,r,s,c,l;t<i-1;t++)r=m.charAt(t),s=m.charAt(t+1),c=m.substring(0,t)+s,l=m.substring(t+2),o=c+r+l,Yx(this,d,o,a,e,n),o=c+l,Yx(this,d,o,a,e,n);Yx(this,d,m.substring(0,m.length-1),a,e,n)}break;case`full`:if(i>2){for(let r=0,c;r<i;r++)for(a=i;a>r;a--){o=m.substring(r,a),c=this.rtl?i-1-r:r;var s=this.score?this.score(t,m,p,o,c):Xx(f,l,p,i,c);Yx(this,d,o,s,e,n)}break}case`bidirectional`:case`reverse`:if(i>1){for(s=i-1;s>0;s--){o=m[this.rtl?i-1-s:s]+o;var c=this.score?this.score(t,m,p,o,s):Xx(f,l,p,i,s);Yx(this,d,o,c,e,n)}o=``}case`forward`:if(i>1){for(s=0;s<i;s++)o+=m[this.rtl?i-1-s:s],Yx(this,d,o,a,e,n);break}default:if(Yx(this,d,m,a,e,n),r&&l>1&&p<l-1)for(i=this.N,o=m,a=Math.min(r+1,this.rtl?p+1:l-p),s=1;s<a;s++){m=t[this.rtl?l-1-p-s:p+s],c=this.bidirectional&&m>o;let r=this.score?this.score(t,o,p,m,s-1):Xx(i+(l/2>i?0:1),l,p,a-1,s-1);Yx(this,u,c?o:m,r,e,n,c?m:o)}}}}this.fastupdate||this.reg.add(e)}}return this.db&&(this.commit_task.push(n?{ins:e}:{del:e}),this.M&&nS(this)),this};function Yx(e,t,n,r,i,a,o){let s,c;if(!(s=t[n])||o&&!s[o]){if(o?(t=s||(t[n]=Jb()),t[o]=1,c=e.ctx,(s=c.get(o))?c=s:c.set(o,c=e.keystore?new fx(e.keystore):new Map)):(c=e.map,t[n]=1),(s=c.get(n))?c=s:c.set(n,c=s=[]),a){for(let n=0,a;n<s.length;n++)if((a=s[n])&&a.includes(i)){if(n<=r)return;a.splice(a.indexOf(i),1),e.fastupdate&&(t=e.reg.get(i))&&t.splice(t.indexOf(a),1);break}}if(c=c[r]||(c[r]=[]),c.push(i),c.length===2**31-1){if(t=new dx(c),e.fastupdate)for(let n of e.reg.values())n.includes(c)&&(n[n.indexOf(c)]=t);s[r]=c=t}e.fastupdate&&((r=e.reg.get(i))?r.push(c):e.reg.set(i,[c]))}}function Xx(e,t,n,r,i){return n&&e>1?t+(r||0)<=e?n+(i||0):(e-1)/(t+(r||0))*(n+(i||0))+1|0:0}tS.prototype.search=function(e,t,n){if(n||(t||typeof e!=`object`?typeof t==`object`&&(n=t,t=0):(n=e,e=``)),n&&n.cache)return n.cache=!1,e=this.searchCache(e,t,n),n.cache=!0,e;let r=[],i,a,o,s=0,c,l,u,d,f;n&&(e=n.query||e,t=n.limit||t,s=n.offset||0,a=n.context,o=n.suggest,f=(c=n.resolve)&&n.enrich,u=n.boost,d=n.resolution,l=this.db&&n.tag),c===void 0&&(c=this.resolve),a=this.depth&&a!==!1;let p=this.encoder.encode(e,!a);if(i=p.length,t||=c?100:0,i===1)return Qx.call(this,p[0],``,t,s,c,f,l);if(i===2&&a&&!o)return Qx.call(this,p[1],p[0],t,s,c,f,l);let m=Jb(),h=0,g;if(a&&(g=p[0],h=1),d||d===0||(d=g?this.N:this.resolution),this.db){if(this.db.search&&(n=this.db.search(this,p,t,s,o,c,f,l),n!==!1))return n;let e=this;return async function(){for(let t,n;h<i;h++){if((n=p[h])&&!m[n]){if(m[n]=1,t=await eS(e,n,g,0,0,!1,!1),t=$x(t,r,o,d)){r=t;break}g&&(o&&t&&r.length||(g=n))}o&&g&&h===i-1&&!r.length&&(d=e.resolution,g=``,h=-1,m=Jb())}return Zx(r,d,t,s,o,u,c)}()}for(let e,t;h<i;h++){if((t=p[h])&&!m[t]){if(m[t]=1,e=eS(this,t,g,0,0,!1,!1),e=$x(e,r,o,d)){r=e;break}g&&(o&&e&&r.length||(g=t))}o&&g&&h===i-1&&!r.length&&(d=this.resolution,g=``,h=-1,m=Jb())}return Zx(r,d,t,s,o,u,c)};function Zx(e,t,n,r,i,a,o){let s=e.length,c=e;if(s>1)c=Px(e,t,n,r,i,a,o);else if(s===1)return o?Ox.call(null,e[0],n,r):new Mx(e[0],this);return o?c:new Mx(c,this)}function Qx(e,t,n,r,i,a,o){return e=eS(this,e,t,n,r,i,a,o),this.db?e.then(function(e){return i?e||[]:new Mx(e,this)}):e&&e.length?i?Ox.call(this,e,n,r):new Mx(e,this):i?[]:new Mx([],this)}function $x(e,t,n,r){let i=[];if(e&&e.length){if(e.length<=r){t.push(e);return}for(let t=0,n;t<r;t++)(n=e[t])&&(i[t]=n);if(i.length){t.push(i);return}}if(!n)return i}function eS(e,t,n,r,i,a,o,s){let c;return n&&(c=e.bidirectional&&t>n)&&(c=n,n=t,t=c),e.db?e.db.get(t,n,r,i,a,o,s):(e=n?(e=e.ctx.get(n))&&e.get(t):e.map.get(t),e)}function tS(e,t){if(!this||this.constructor!==tS)return new tS(e);if(e){var n=Yb(e)?e:e.preset;n&&(e=Object.assign({},Voe[n],e))}else e={};n=e.context;let r=n===!0?{depth:1}:n||{},i=Yb(e.encoder)?lx[e.encoder]:e.encode||e.encoder||{};this.encoder=i.encode?i:typeof i==`object`?new $b(i):{encode:i},this.resolution=e.resolution||9,this.tokenize=n=(n=e.tokenize)&&n!=="default"&&n!==`exact`&&n||`strict`,this.depth=n===`strict`&&r.depth||0,this.bidirectional=r.bidirectional!==!1,this.fastupdate=!!e.fastupdate,this.score=e.score||null,(n=e.keystore||0)&&(this.keystore=n),this.map=n?new fx(n):new Map,this.ctx=n?new fx(n):new Map,this.reg=t||(this.fastupdate?n?new fx(n):new Map:n?new px(n):new Set),this.N=r.resolution||3,this.rtl=i.rtl||e.rtl||!1,this.cache=(n=e.cache||null)&&new nx(n),this.resolve=e.resolve!==!1,(n=e.db)&&(this.db=this.mount(n)),this.M=e.commit!==!1,this.commit_task=[],this.commit_timer=null,this.priority=e.priority||4}Gb=tS.prototype,Gb.mount=function(e){return this.commit_timer&&=(clearTimeout(this.commit_timer),null),e.mount(this)},Gb.commit=function(){return this.commit_timer&&=(clearTimeout(this.commit_timer),null),this.db.commit(this)},Gb.destroy=function(){return this.commit_timer&&=(clearTimeout(this.commit_timer),null),this.db.destroy()};function nS(e){e.commit_timer||=setTimeout(function(){e.commit_timer=null,e.db.commit(e)},1)}Gb.clear=function(){return this.map.clear(),this.ctx.clear(),this.reg.clear(),this.cache&&this.cache.clear(),this.db?(this.commit_timer&&clearTimeout(this.commit_timer),this.commit_timer=null,this.commit_task=[],this.db.clear()):this},Gb.append=function(e,t){return this.add(e,t,!0)},Gb.contain=function(e){return this.db?this.db.has(e):this.reg.has(e)},Gb.update=function(e,t){let n=this,r=this.remove(e);return r&&r.then?r.then(()=>n.add(e,t)):this.add(e,t)},Gb.cleanup=function(){return this.fastupdate?(Jx(this.map),this.depth&&Jx(this.ctx),this):this},Gb.searchCache=tx,Gb.export=function(e,t,n=0,r=0){let i,a;switch(r){case 0:i=`reg`,a=Wx(this.reg);break;case 1:i=`cfg`,a=null;break;case 2:i=`map`,a=Bx(this.map,this.reg.size);break;case 3:i=`ctx`,a=Hx(this.ctx,this.reg.size);break;default:return}return Kx.call(this,e,t,i,a,n,r)},Gb.import=function(e,t){if(t)switch(typeof t==`string`&&(t=JSON.parse(t)),e=e.split(`.`),e[e.length-1]===`json`&&e.pop(),e.length===3&&e.shift(),e=e.length>1?e[1]:e[0],e){case`reg`:this.fastupdate=!1,this.reg=Gx(t,this.reg);break;case`map`:this.map=Vx(t,this.map);break;case`ctx`:this.ctx=Ux(t,this.ctx)}},Gb.serialize=function(e=!0){let t=``,n=``,r=``;if(this.reg.size){let e;for(var i of this.reg.keys())e||=typeof i,t+=(t?`,`:``)+(e===`string`?`"`+i+`"`:i);t=`index.reg=new Set([`+t+`]);`,n=qx(this.map,e),n=`index.map=new Map([`+n+`]);`;for(let t of this.ctx.entries()){i=t[0];let n=qx(t[1],e);n=`new Map([`+n+`])`,n=`["`+i+`",`+n+`]`,r+=(r?`,`:``)+n}r=`index.ctx=new Map([`+r+`]);`}return e?`function inject(index){`+t+n+r+`}`:t+n+r},vx(tS.prototype);var rS=typeof window<`u`&&(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB),iS=[`map`,`ctx`,`tag`,`reg`,`cfg`],aS=Jb();function oS(e,t={}){if(!this||this.constructor!==oS)return new oS(e,t);typeof e==`object`&&(t=e,e=e.name),e||console.info(`Default storage space was used, because a name was not passed.`),this.id=`flexsearch`+(e?`:`+e.toLowerCase().replace(/[^a-z0-9_\-]/g,``):``),this.field=t.field?t.field.toLowerCase().replace(/[^a-z0-9_\-]/g,``):``,this.type=t.type,this.fastupdate=this.support_tag_search=!1,this.db=null,this.h={}}Gb=oS.prototype,Gb.mount=function(e){return e.index?e.mount(this):(e.db=this,this.open())},Gb.open=function(){if(this.db)return this.db;let e=this;navigator.storage&&navigator.storage.persist&&navigator.storage.persist(),aS[e.id]||(aS[e.id]=[]),aS[e.id].push(e.field);let t=rS.open(e.id,1);return t.onupgradeneeded=function(){let t=e.db=this.result;for(let n=0,r;n<iS.length;n++){r=iS[n];for(let n=0,i;n<aS[e.id].length;n++)i=aS[e.id][n],t.objectStoreNames.contains(r+(r===`reg`?``:i?`:`+i:``))||t.createObjectStore(r+(r===`reg`?``:i?`:`+i:``))}},e.db=cS(t,function(t){e.db=t,e.db.onversionchange=function(){e.close()}})},Gb.close=function(){this.db&&this.db.close(),this.db=null},Gb.destroy=function(){return cS(rS.deleteDatabase(this.id))},Gb.clear=function(){let e=[];for(let t=0,n;t<iS.length;t++){n=iS[t];for(let t=0,r;t<aS[this.id].length;t++)r=aS[this.id][t],e.push(n+(n===`reg`?``:r?`:`+r:``))}let t=this.db.transaction(e,`readwrite`);for(let n=0;n<e.length;n++)t.objectStore(e[n]).clear();return cS(t)},Gb.get=function(e,t,n=0,r=0,i=!0,a=!1){e=this.db.transaction((t?`ctx`:`map`)+(this.field?`:`+this.field:``),`readonly`).objectStore((t?`ctx`:`map`)+(this.field?`:`+this.field:``)).get(t?t+`:`+e:e);let o=this;return cS(e).then(function(e){let t=[];if(!e||!e.length)return t;if(i){if(!n&&!r&&e.length===1)return e[0];for(let i=0,a;i<e.length;i++)if((a=e[i])&&a.length){if(r>=a.length){r-=a.length;continue}let e=n?r+Math.min(a.length-r,n):a.length;for(let n=r;n<e;n++)t.push(a[n]);if(r=0,t.length===n)break}return a?o.enrich(t):t}return e})},Gb.tag=function(e,t=0,n=0,r=!1){e=this.db.transaction(`tag`+(this.field?`:`+this.field:``),`readonly`).objectStore(`tag`+(this.field?`:`+this.field:``)).get(e);let i=this;return cS(e).then(function(e){return!e||!e.length||n>=e.length?[]:!t&&!n?e:(e=e.slice(n,n+t),r?i.enrich(e):e)})},Gb.enrich=function(e){typeof e!=`object`&&(e=[e]);let t=this.db.transaction(`reg`,`readonly`).objectStore(`reg`),n=[];for(let r=0;r<e.length;r++)n[r]=cS(t.get(e[r]));return Promise.all(n).then(function(t){for(let n=0;n<t.length;n++)t[n]={id:e[n],doc:t[n]?JSON.parse(t[n]):null};return t})},Gb.has=function(e){return e=this.db.transaction(`reg`,`readonly`).objectStore(`reg`).getKey(e),cS(e).then(function(e){return!!e})},Gb.search=null,Gb.info=function(){},Gb.transaction=function(e,t,n){e+=e===`reg`?``:this.field?`:`+this.field:``;let r=this.h[e+`:`+t];if(r)return n.call(this,r);let i=this.db.transaction(e,t);this.h[e+`:`+t]=r=i.objectStore(e);let a=n.call(this,r);return this.h[e+`:`+t]=null,cS(i).finally(function(){return a})},Gb.commit=async function(e){let t=e.commit_task,n=[];e.commit_task=[];for(let e=0,r;e<t.length;e++)r=t[e],r.del&&n.push(r.del);n.length&&await this.remove(n),e.reg.size&&(await this.transaction(`map`,`readwrite`,function(t){for(let n of e.map){let e=n[0],r=n[1];r.length&&(t.get(e).onsuccess=function(){let n=this.result;var i;if(n&&n.length){let e=Math.max(n.length,r.length);for(let t=0,a,o;t<e;t++)if((o=r[t])&&o.length){if((a=n[t])&&a.length)for(i=0;i<o.length;i++)a.push(o[i]);else n[t]=o;i=1}}else n=r,i=1;i&&t.put(n,e)})}}),await this.transaction(`ctx`,`readwrite`,function(t){for(let n of e.ctx){let e=n[0],r=n[1];for(let n of r){let r=n[0],i=n[1];i.length&&(t.get(e+`:`+r).onsuccess=function(){let n=this.result;var a;if(n&&n.length){let e=Math.max(n.length,i.length);for(let t=0,r,o;t<e;t++)if((o=i[t])&&o.length){if((r=n[t])&&r.length)for(a=0;a<o.length;a++)r.push(o[a]);else n[t]=o;a=1}}else n=i,a=1;a&&t.put(n,e+`:`+r)})}}}),e.store?await this.transaction(`reg`,`readwrite`,function(t){for(let n of e.store){let e=n[0],r=n[1];t.put(typeof r==`object`?JSON.stringify(r):1,e)}}):e.bypass||await this.transaction(`reg`,`readwrite`,function(t){for(let n of e.reg.keys())t.put(1,n)}),e.tag&&await this.transaction(`tag`,`readwrite`,function(t){for(let n of e.tag){let e=n[0],r=n[1];r.length&&(t.get(e).onsuccess=function(){let n=this.result;n=n&&n.length?n.concat(r):r,t.put(n,e)})}}),e.map.clear(),e.ctx.clear(),e.tag&&e.tag.clear(),e.store&&e.store.clear(),e.document||e.reg.clear())};function sS(e,t,n){let r=e.value,i,a=0;for(let e=0,o;e<r.length;e++){if(o=n?r:r[e]){for(let n=0,a,s;n<t.length;n++)if(s=t[n],a=o.indexOf(s),a>=0){if(i=1,o.length>1)o.splice(a,1);else{r[e]=[];break}}a+=o.length}if(n)break}a?i&&e.update(r):e.delete(),e.continue()}Gb.remove=function(e){return typeof e!=`object`&&(e=[e]),Promise.all([this.transaction(`map`,`readwrite`,function(t){t.openCursor().onsuccess=function(){let t=this.result;t&&sS(t,e)}}),this.transaction(`ctx`,`readwrite`,function(t){t.openCursor().onsuccess=function(){let t=this.result;t&&sS(t,e)}}),this.transaction(`tag`,`readwrite`,function(t){t.openCursor().onsuccess=function(){let t=this.result;t&&sS(t,e,!0)}}),this.transaction(`reg`,`readwrite`,function(t){for(let n=0;n<e.length;n++)t.delete(e[n])})])};function cS(e,t){return new Promise((n,r)=>{e.onsuccess=e.oncomplete=function(){t&&t(this.result),t=null,n(this.result)},e.onerror=e.onblocked=r,e=null})}var Hoe={Index:tS,Charset:lx,Encoder:$b,Document:Rx,Worker:wx,Resolver:Mx,IndexedDB:oS,Language:{}};function lS(e,t,n,r){if(!t?.type)throw Error(`Schema not found for `+n);if(e!==null&&!V.isJson(e)){if(t.type===`string`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`number`){typeof e==`number`&&r({source:e,schema:t,path:n});return}if(t.type===`boolean`){typeof e==`boolean`&&r({source:e,schema:t,path:n});return}if(t.type===`richtext`){r({source:e,schema:t,path:n});return}if(t.type===`file`||t.type===`image`){e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`date`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`dateTime`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`color`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`keyOf`){(typeof e==`string`||typeof e==`number`)&&r({source:e,schema:t,path:n});return}if(t.type===`literal`){r({source:e,schema:t,path:n});return}if(t.type===`route`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`array`){if(!Array.isArray(e))return;if(!t.item)throw Error(`Schema (`+t.type+`) item not found for `+n);for(let i=0;i<e.length;i++){let a=My(n,i);lS(e[i],t.item,a,r)}return}if(t.type===`object`||t.type===`record`){if(typeof e!=`object`||!e||Array.isArray(e))return;for(let i in e){let a=t.type===`object`?t.items?.[i]:t.item;if(!a)continue;let o=My(n,i);lS(e[i],a,o,r)}return}if(t.type===`union`){let i=t.key;if(typeof i==`string`){if(e&&typeof e==`object`&&!Array.isArray(e)&&i in e){let a=e[i];if(typeof a==`string`){let o=t.items.filter(e=>e.type===`object`).find(e=>{let t=e.items[i];return t?.type===`literal`&&t.value===a});o&&lS(e,o,n,r)}}}else typeof e==`string`&&r({source:e,schema:t,path:n});return}throw Error(`Unsupported schema type: `+JSON.stringify(t))}}function Uoe(e){let t=``;function n(e){if(typeof e==`string`)t+=e;else if(e&&typeof e==`object`&&`children`in e&&Array.isArray(e.children))for(let t of e.children)n(t)}return n({children:e}),t}function uS(e){let t=V.remote.splitRemoteRef(e);return t.status===`success`?`/${t.filePath}`:e}function Woe(e){let t=uS(e);return t.split(`/`).pop()||t}function dS(e){let t=uS(e);return{cleanPath:t,filename:t.split(`/`).pop()||t,folder:t.replace(/^\/public(?=\/|$)/,``).replace(/\/[^/]+$/,``)||`/`}}function fS(){return{index:new Hoe.Index({tokenize:`forward`}),pathToLabel:new Map,docsByModule:new Map}}function Goe(e,t,n,r){let{index:i,pathToLabel:a,docsByModule:o}=e;pS(e,t);let s=new Set;o.set(t,s),lS(n,r,t+`?p=`,({source:e,schema:t,path:n})=>{if(e===null)return;let r=``,o=``;if(t.type===`string`||t.type===`number`||t.type===`boolean`||t.type===`date`||t.type===`dateTime`||t.type===`color`||t.type===`keyOf`||t.type===`route`)r=e?.toString()??``,o=e?.toString()??``;else if(t.type===`literal`)r=t.value.toString(),o=t.value.toString();else if(t.type===`richtext`)r=Uoe(e),o=r.substring(0,50)||`richtext`;else if((t.type===`file`||t.type===`image`)&&typeof e==`object`&&e&&`path`in e&&typeof e.path==`string`){let{filename:t,folder:n}=dS(e.path),i=`alt`in e?e.alt:``;r=t+` `+n+` `+i,o=t}if(r){let[,e]=V.splitModuleFilePathAndModulePath(n),t=qoe(e)+` `;i.add(n,t+` `+n+` `+r),a.set(n,o),s.add(n)}})}function pS(e,t){let{index:n,pathToLabel:r,docsByModule:i}=e,a=i.get(t);if(a!==void 0){for(let e of a)n.remove(e),r.delete(e);i.delete(t)}}var Koe=new Set([`/`,`-`,`_`,`.`,`:`,`?`,`&`,`=`,`@`,`"`,`'`]);function qoe(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];Koe.has(r)?t+=` `:t+=r}return t}function Joe(e,t,n=50,r=0){if(e===null||!t.trim())return{results:[],total:0};let{index:i,pathToLabel:a}=e,o=i.search(t,{limit:r+n}),s=o.length;return{results:o.slice(r,r+n).map(e=>({path:e,label:a.get(e)||e})),total:s}}var Yoe=class{constructor(e=hb){this.activity=e,this.events=new mb,this.index=null,this.indexed=new Set,this.partial=new Set}async reindex(e){let t=Object.keys(e);this.index===null&&(this.index=fS());let n=[];for(let r of t){this.activity.work(`search:index-module`,r);let t=e[r];Goe(this.index,r,t.source,t.schema),this.indexed.has(r)||n.push(r),this.indexed.add(r),t.complete?this.partial.delete(r):this.partial.add(r)}let r={new:n,all:[...this.indexed]};return this.events.emit({type:`search:build-index`,...r}),r}async forget(e){this.index!==null&&pS(this.index,e),this.indexed.delete(e),this.partial.delete(e)}async buildIndex(e){return this.activity.work(`search:build-index`,void 0,Object.keys(e).length),this.index=fS(),this.indexed=new Set,this.partial.clear(),this.reindex(e)}async search(e,t,n){if(this.index===null)return{status:`no-index`};this.activity.work(`search:query`,e);let{results:r,total:i}=Joe(this.index,e,t,n);return{status:`results`,results:r,total:i,partialModules:[...this.partial]}}},Xoe=class{constructor(e=hb){this.activity=e,this.events=new mb,this.byModule=new Map,this.incomplete=new Map}async forget(e){this.byModule.delete(e),this.incomplete.delete(e)}async rescan(e){let t=Object.keys(e);for(let n of t){this.activity.work(`references:scan-module`,n);let t=e[n],r=new Map;mS(n,t.schema,t.source,r),this.byModule.set(n,r),t.complete?this.incomplete.delete(n):this.incomplete.set(n,Qoe(t.schema))}return this.events.emit({type:`references:scan`,modules:t}),t}async find(e){this.activity.work(`references:query`,e.kind);let t=[];for(let n of this.byModule.values())for(let[r,i]of n)Zoe(i,e)&&t.push(r);let n=[];for(let[t,r]of this.incomplete)r.has(e.kind)&&n.push(t);return n.length>0?{status:`partial`,refs:t,awaiting:n}:{status:`complete`,refs:t}}async at(e){let[t]=V.splitModuleFilePathAndModulePath(e);return this.byModule.get(t)?.get(e)??null}};function Zoe(e,t){return!(e.kind!==t.kind||t.kind!==`route`&&e.target!==t.module||t.value!==void 0&&e.value!==t.value)}function Qoe(e){let t=new Set,n=new Set,r=e=>{if(!(e===void 0||n.has(e)))switch(n.add(e),e.type){case`keyOf`:t.add(`keyOf`);return;case`image`:case`file`:t.add(`file`);return;case`route`:t.add(`route`);return;case`object`:for(let t of Object.values(e.items))r(t);return;case`array`:case`record`:r(e.item);return;case`union`:for(let t of e.items)r(t);return;default:return}};return e?.type===`record`?r(e.item):r(e),t}function mS(e,t,n,r){if(t!==void 0&&!V.isJson(n))switch(t.type){case`keyOf`:r.set(e,{kind:`keyOf`,target:t.path,value:typeof n==`string`?n:null});return;case`image`:case`file`:if(t.referencedModule===void 0)return;r.set(e,{kind:`file`,target:t.referencedModule,value:$oe(n)});return;case`route`:r.set(e,{kind:`route`,target:null,value:typeof n==`string`?n:null});return;case`object`:if(!hS(n))return;for(let i in t.items){let a=n[i];a!==void 0&&mS(My(e,i),t.items[i],a,r)}return;case`record`:if(!hS(n))return;for(let i in n)mS(My(e,i),t.item,n[i],r);return;case`array`:if(!Array.isArray(n))return;for(let i=0;i<n.length;i++)mS(My(e,i),t.item,n[i],r);return;case`union`:for(let i of t.items)mS(e,i,n,r);return;default:return}}function $oe(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e.path;return typeof t==`string`?t:null}function hS(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var gS=class{constructor(e){this.invalidateEvent=e,this.events=new mb,this.stale=new Set,this.covered=new Set}mark(e){let t=e.filter(e=>!this.stale.has(e));for(let t of e)this.stale.add(t);t.length>0&&this.events.emit({type:this.invalidateEvent,modules:t})}needsPass(){return this.covered.size===0||this.stale.size>0}target(e){return this.covered.size===0?e:[...this.stale]}covers(e){for(let t of e)this.covered.add(t),this.stale.delete(t)}forget(e){this.stale.delete(e),this.covered.delete(e)}coveredModules(){return[...this.covered]}staleModules(){return[...this.stale]}},ese=300;function tse(e,t,n){let r=[];for(let i of e){if(!t.has(i)||n.has(i))break;r.push(i)}return r}var nse=5e3,rse=class{constructor(){this.validator=new pb}async validate(e,t,n,r){return this.validator.validate(e,t,n,r)}};function ise(e){let t=e.activity??hb,n=new qae(t),r=new ooe(e.fetchPatches,e.createPatchId,t,e.uploadFile),i=new noe(n,t,e.fetchJsonEntry),a=new soe,o=new coe(t),s=new doe(r,e.savePatches,e.resyncChain??(async()=>{}),t,e.sessionId,e.saveBackoffMs,e.saveSleep);r.setParentRefSource(()=>s.currentParentRef());let c=new foe(n,i,t),l=e.hostBridge??c,u=new hoe(l,i,n,t),d=new boe(n,i,e.schemaValidation??new rse,l,t),f=e.workerRealm?.search??new Yoe(t),p=e.workerRealm?.patchSets??new _oe(t),m=e.workerRealm?.references??new Xoe(t),h=new gS(`search:invalidate`),g=new gS(`references:invalidate`),_=new voe,v=!1,y=!1,b=e.mode??`fs`,x=null;r.setPublishInFlight(()=>v);let S=new Map;async function C(t){let n=[];for(let{patchId:e,message:a}of t){let t=r.recordsFor([e])[0],o=t?.moduleFilePath,s=o!==void 0&&i.hasUnloadedEntries(o),c=(S.get(e)??0)+1;if(S.set(e,c),console.error(s?`Val: a patch could not be applied, and this module still has unloaded .jsonValues() entries — so it may apply once they arrive. Keeping it. If the edit never appears, please report this.`:`Val: discarding a patch that cannot be applied. If you see this often, please report it — it means a patch is being generated that does not fit the source it targets.`,{patchId:e,reason:a,module:o??`(record already gone)`,ops:t?.patch?.map(e=>({op:e.op,path:`path`in e?e.path:void 0})),origin:r.originOf(e),savedOnServer:!r.isPending(e),attempt:c}),!s){if(c>3){console.error(`Val: giving up on deleting an unapplicable patch — it keeps coming back. It is out of this session's chain so it cannot block saving, but it is still on the server.`,{patchId:e,attempts:c}),r.drop([e]);continue}n.push(e)}}if(n.length===0)return;if(r.drop(n),o.reportError(n.length===1?`An edit could not be applied and has been discarded.`:`${n.length} edits could not be applied and have been discarded.`,`This usually means a patch was generated that does not fit the content it targets. The browser console has the failing operation.`),e.discardPatches===void 0){console.error(`Val: cannot delete the patch on the server — this system has no discard seam. It will return on the next reload.`,{patchIds:n});return}let a=await e.discardPatches(n);a.status===`error`&&console.error(`Val: could not delete an unapplicable patch on the server.`,{patchIds:n,error:a.message})}let w=null;function T(){w===null&&(w=setTimeout(()=>{w=null;let e=new Set;for(let t of r.allRecords())e.add(t.moduleFilePath);for(let t of e)d.validate(t)},ese))}let E=[r.listenTo(a,i),i.listenTo(r),s.listenTo(),a.events.on(`patch:removed-by-server`,e=>{o.reportError(e.removed.length===1?`An unpublished change was removed because the server could not read it.`:`${e.removed.length} unpublished changes were removed because the server could not read them.`,`They are gone and the fields are back to their published values. The server log and .val/patches/patches.repair.log say which, and why.`),console.error(`Val: the server removed these unpublished changes.`,e.removed)}),r.events.on(`patch:fetch-failed`,e=>{o.reportError(`Unpublished changes could not be loaded.`,`${e.patches.length} ${e.patches.length===1?`change is`:`changes are`} affected: ${e.message} Until this succeeds, the editor shows published content for the fields they touch.`)}),r.events.on(`patch:announced-not-delivered`,e=>{o.reportError(e.patches.length===1?`An unpublished change could not be loaded.`:`${e.patches.length} unpublished changes could not be loaded.`,`The server listed them but did not send them, so they are not shown. Reload before editing: anything you change now is written on top of content that is missing them.`),console.error(`Val: the server announced these unpublished changes and did not send them.`,{patchIds:e.patches})}),s.events.on(`patch:save-rejected`,e=>{o.reportError(e.patches.length===1?`An edit could not be saved and has been reverted.`:`${e.patches.length} edits could not be saved and have been reverted.`,e.errors?Object.entries(e.errors).map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
131
- `):e.message)}),s.events.on(`patch:save-stuck`,e=>{let t=Kae(e.reason,e.message,e.attempt,e.patches.length);o.reportError(t.title,t.detail)}),a.events.on(`stat:receive`,e=>{let t=a.currentBaseSha();t!==null&&(s.receiveStat(t,e.patches),s.flush())}),u.listenTo(),d.listenTo(),r.events.on(`patch:chain`,()=>{T()}),i.events.on(`source:patch-apply`,e=>{e.failed.length!==0&&C(e.failed)}),i.events.on(`source:patch-apply`,e=>{h.mark(e.modules),g.mark(e.modules)}),i.events.on(`source:init`,e=>{h.mark(e.sources),g.mark(e.sources)}),n.events.on(`schema:init`,()=>{_.invalidate()}),r.events.on(`patch:drop`,()=>{_.invalidate()})];function D(e,r){if(e.mode===`current`)return{mode:`current`};let i=new Set(e.patchIds),a=r.filter(e=>i.has(e.patchId)),o=n.all(),s={};for(let e of a){let t=o[e.moduleFilePath];t!==void 0&&(s[e.moduleFilePath]=t)}return t.work(`patch-set:gather`,void 0,a.length),{mode:e.mode,records:a,schemas:s}}function O(e){let r=n.all(),a={};t.work(`search:gather-snapshot`,void 0,e.length);for(let t of e){let e=r[t],n=i.moduleSource(t);e!==void 0&&n!==void 0&&(a[t]={source:n,schema:e,complete:!i.hasUnloadedEntries(t)})}return a}async function k(){if(!g.needsPass())return;let e=g.target(i.loadedModules()),t=await m.rescan(A(e));g.covers(t)}function A(e){let t=n.all(),r={};for(let n of e){let e=t[n],a=i.moduleSource(n);e!==void 0&&a!==void 0&&(r[n]={source:a,schema:e,complete:!i.hasUnloadedEntries(n)})}return r}return{host:c,stat:a,status:o,schemaStore:n,sourceStore:i,patchStore:r,patchSync:s,previewStore:u,validationStore:d,searchStore:f,patchSetStore:p,referenceStore:m,async findReferences(e){return await k(),m.find(e)},async referenceAt(e){return await k(),m.at(e)},async getPatchSets(){if(x!==null)return x;let e=(async()=>{let e=r.allRecords(),t=_.plan(e.map(e=>e.patchId)),n=D(t,e),i=await p.getPatchSets(n);return _.covers(t),i})().finally(()=>{x=null});return x=e,e},async search(e,t,n){if(h.needsPass()){let e=h.target(i.loadedModules()),t=await f.reindex(O(e));h.covers(t.all)}let r=await f.search(e,t,n);return r.status===`no-index`?r:{...r,staleModules:h.staleModules()}},async buildSearchIndex(){let e=i.loadedModules(),t=await f.buildIndex(O(e));return h.covers(t.all),t},async validateEverything(){if(!y){y=!0,d.events.emit({type:`validation:full-pass`,running:!0});try{for(let e of i.loadedModules())await d.validate(e)}finally{y=!1,d.events.emit({type:`validation:full-pass`,running:!1})}}},async publish(t,a,c){let l=c?.exact===!0;if(e.publishPatches===void 0)return{status:`failed`,message:`This system has no publish seam configured.`,retryable:!1};if(v)return{status:`refused`,reason:`already-publishing`};v=!0;try{!l&&e.savePatches!==void 0&&r.unsavedRecords().length>0&&s.currentState().status!==`retrying`&&await Promise.race([s.flush().catch(()=>void 0),new Promise(t=>{let n=setTimeout(t,e.saveFlushTimeoutMs??nse);typeof n==`object`&&`unref`in n&&n.unref()})]);let c=e.savePatches===void 0||l?[]:r.unsavedRecords();if(c.length>0)return{status:`refused`,reason:`unsaved-changes`,patchIds:c.map(e=>e.patchId)};let u=r.allRecords().map(e=>e.patchId),f=l?tse(u,new Set(t),new Set(r.unsavedRecords().map(e=>e.patchId))):u;if(f.length===0)return{status:`nothing-to-publish`};let p=new Set;for(let e of r.recordsFor(f))p.add(e.moduleFilePath);let m=r.chainVersion(),h=[];for(let e of p){let t=await d.validate(e);if(t.status!==`validated`||t.errors===!1)continue;let r=ab(t.errors,n.all(),i.allSources());Object.keys(r).length>0&&h.push(e)}if(h.length>0)return{status:`refused`,reason:`validation-errors`,modules:h};if(!l&&r.chainVersion()!==m)return{status:`refused`,reason:`chain-moved`};let g=await e.publishPatches({patchIds:f,message:a});if(g.status===`patch-errors`)return r.recordPublishErrors(g.errors),{status:`failed`,message:g.message,patchErrors:g.errors,retryable:!1};if(g.status!==`published`)return{status:`failed`,message:g.message,retryable:g.status===`not-fast-forward`||g.status===`network-error`};let _=g.removed??[];return _.length>0&&(r.drop(_.map(e=>e.patchId)),o.reportError(_.length===1?`An edit could not be applied and was removed.`:`${_.length} edits could not be applied and were removed.`,_.map(e=>`${e.moduleFilePath}: ${e.message}`).join(`
130
+ `),a=this.entriesStatusCache.get(i);return a!==void 0&&toe(a,r)?a:(this.entriesStatusCache.set(i,r),r)}entryError(e,t){return this.entryFailures.get(Rb(e,t))}hasUnloadedEntries(e){let t=this.sources[e];if(t===void 0||!Lb(t))return!1;let n=this.jsonEntries.get(e);for(let[e,r]of Object.entries(t))if(V.isJson(r)&&n?.has(e)!==!0)return!0;return!1}peek(e){let t=this.computePeek(e,this.sources,this.jsonEntries),n=this.peeked.get(e);return n!==void 0&&Pb(n,t)?n:(this.peeked.set(e,t),t)}computePeek(e,t,n){let[r,i]=V.splitModuleFilePathAndModulePath(e),a=t[r];if(a===void 0||this.schemaStore.get(r)===void 0)return{status:`module-loading`};let o=Ib(this.substitutedSource(r,a,n),i);if(o.status===`needs-entry`){let e=Rb(r,o.key);if(this.loadingEntries.has(e))return{status:`entry-loading`,key:o.key};let t=this.entryFailures.get(e);return t===void 0?{status:`entry-missing`,key:o.key}:{status:`entry-failed`,key:o.key,message:t}}let s=this.revisionOf(r);return o.status===`found`?{status:`ready`,revision:s,data:o.value}:o.status===`absent`?{status:`absent`,revision:s}:{status:`module-loading`}}storePatched(e,t,n,r){let i=r?.sources??this.sources,a=(r?.entries??this.jsonEntries).get(e);if(a===void 0||a.size===0||!Lb(n)||!Lb(t)){i[e]=n;return}let o={...n};for(let e of[...a.keys()]){if(!(e in o)){a.delete(e);continue}V.isJson(t[e])&&(a.set(e,o[e]),o[e]=t[e])}i[e]=o}async loadEntry(e,t){if(this.fetchJsonEntry===void 0)return{status:`error`,message:`Cannot read inside '${t}' of ${e}: no jsonValues fetch is configured. Refusing rather than reporting the path absent.`};let n=Rb(e,t),r=this.loadingEntries.get(n);if(r!==void 0){this.activity.work(`source:share-json-entry-load`,e),await r;let t=this.entryFailures.get(n);return t===void 0?{status:`ok`}:{status:`error`,message:t}}let i;this.entryFailures.delete(n);let a=(async()=>{this.activity.work(`source:load-json-entry`,e);let r=await this.fetchJsonEntry(e,t);if(r.status===`error`){i=r.message,this.entryFailures.set(n,r.message);return}this.receiveJsonEntry(e,t,r.content)})().finally(()=>{this.loadingEntries.delete(n)});return this.loadingEntries.set(n,a),await a,i===void 0?{status:`ok`}:{status:`error`,message:i}}peekBase(e){let t=this.computePeek(e,this.baseSources,this.baseJsonEntries),n=this.peekedBase.get(e);return n!==void 0&&Pb(n,t)?n:(this.peekedBase.set(e,t),t)}entriesProgress(e){let t=this.sources[e];if(t===void 0||!Lb(t))return{total:0,loaded:0,failed:0};let n=this.jsonEntries.get(e),r=0,i=0,a=0;for(let[o,s]of Object.entries(t))V.isJson(s)&&(r++,n?.has(o)===!0?i++:this.entryFailures.has(Rb(e,o))&&a++);return{total:r,loaded:i,failed:a}}async retryEntry(e,t){return this.entryFailures.delete(Rb(e,t)),this.loadEntry(e,t)}promoteToBase(e){for(let t of e){let e=this.sources[t];if(e===void 0)continue;this.activity.work(`source:promote-to-base`,t),this.baseSources[t]=bb(e);let n=this.jsonEntries.get(t);n!==void 0&&this.baseJsonEntries.set(t,new Map([...n].map(([e,t])=>[e,bb(t)])))}}promotePublished(e,t){let n=new Set(e);for(let e of t){let t=this.chains.get(e)??[],r=t.filter(e=>!n.has(e.record.patchId));if(r.length===t.length)continue;if(r.length===0){this.promoteToBase([e]),this.chains.set(e,[]);continue}let i=this.baseSources[e];if(i===void 0){this.chains.set(e,r);continue}let a=bb(this.substitutedSource(e,i,this.baseJsonEntries)),o=!0;for(let r of t){if(!n.has(r.record.patchId))continue;let t=r.record.patch.filter(e=>e.op!==`file`);if(t.length===0)continue;this.activity.work(`source:apply-patch`,r.record.patchId);let i=Ab(bb(a),Mb,t);if(!ne.isOk(i)){console.error(`Val: could not rebuild the base after a partial save. The value on screen is right; the base behind it is stale until the next load.`,{moduleFilePath:e,patchId:r.record.patchId,error:i.error}),o=!1;break}a=i.value}o&&(this.activity.work(`source:promote-to-base`,e),this.storePatched(e,i,a,{sources:this.baseSources,entries:this.baseJsonEntries}),this.chains.set(e,r))}}forgetPublished(e){let t=new Set(e);for(let[e,n]of this.chains){let r=n.filter(e=>!t.has(e.record.patchId));r.length!==n.length&&this.chains.set(e,r)}}revisionOf(e){return{module:e,n:this.revisions.get(e)??0}}listenTo(e){let t=e.events.on(`patch:receive`,t=>{this.applyPatches(e.recordsFor(t.patches),`external`,()=>void 0)}),n=e.events.on(`patch:create`,t=>{this.applyPatches(e.recordsFor(t.patches),`internal`,t=>e.creatorOf(t))}),r=e.events.on(`patch:drop`,e=>{this.dropFromChains(e.patches,e.modules)});return()=>{t(),n(),r()}}dropFromChains(e,t){let n=new Set(e),r=[],i=[];for(let e of t){let t=this.chains.get(e);if(t!==void 0){let r=t.filter(e=>!n.has(e.record.patchId));if(r.length===t.length)continue;for(let e of t)n.has(e.record.patchId)&&i.push(...Fb(e.record));this.chains.set(e,r)}let a=this.baseSources[e];if(a===void 0)continue;this.activity.work(`source:rebuild-module`,e),this.sources[e]=bb(a);let o=this.baseJsonEntries.get(e);o!==void 0&&this.jsonEntries.set(e,new Map([...o].map(([e,t])=>[e,bb(t)]))),this.bump(e),r.push(e)}if(r.length>0){this.events.emit({type:`source:patch-drop`,modules:r});for(let e of r){let t=this.chains.get(e);t!==void 0&&t.length!==0&&this.applyEntries(t.map(e=>({record:e.record,origin:`external`,creatorFieldId:void 0})))}i.length>0&&this.wakeListeners(new Set(r),[{origin:`external`,creatorFieldId:void 0,paths:i}])}}receive(e){for(let[t,n]of Object.entries(e)){this.activity.work(`source:clone-module`,t);let e=bb(n);this.baseSources[t]=e,this.sources[t]=bb(e),this.bump(t)}this.events.emit({type:`source:init`,sources:Object.keys(e)});for(let t of Object.keys(e)){let e=this.chains.get(t);e!==void 0&&e.length!==0&&this.applyEntries(e)}let t=Object.keys(e).filter(e=>this.sources[e]!==void 0);t.length>0&&this.wakeListeners(new Set(t),[{origin:`external`,creatorFieldId:void 0,paths:t}])}async get(e,t){let[n,r]=V.splitModuleFilePathAndModulePath(e),i=this.revisionOf(n),a=this.sources[n];if(t!==null&&t.module===n&&t.n===i.n&&a!==void 0&&this.schemaStore.get(n)!==void 0)return{status:`unchanged`,revision:i};if(a===void 0||this.schemaStore.get(n)===void 0)return{status:`module-loading`};this.activity.work(`source:read-path`,e);let o=Ib(this.substitutedSource(n,a),r);if(o.status===`needs-entry`){let e=await this.loadEntry(n,o.key);if(e.status===`error`)return{status:`error`,message:e.message};let t=this.sources[n];if(t===void 0)return{status:`module-loading`};if(o=Ib(this.substitutedSource(n,t),r),o.status===`needs-entry`)return{status:`error`,message:`Entry '${o.key}' of ${n} was loaded but its content is still missing.`}}let s=this.revisionOf(n);return o.status===`absent`?{status:`absent`,revision:s}:o.status===`error`?{status:`error`,message:o.message}:{status:`resolved-head`,data:o.value,revision:s}}async isCurrent(e){return e.n===this.revisionOf(e.module).n}moduleSource(e){let t=this.sources[e];if(t===void 0)return;let n=this.jsonEntries.get(e);return n===void 0||n.size===0?t:this.substitutedSource(e,t)}substitutedSource(e,t,n=this.jsonEntries){let r=n.get(e);if(r===void 0||r.size===0||!Lb(t))return t;let i=this.revisions.get(e)??0,a=this.substituted.get(t);if(a!==void 0&&a.n===i)return a.source;this.activity.work(`source:substitute-json-entries`,e);let o=roe(t,r);return this.substituted.set(t,{n:i,source:o}),o}loadedModules(){return Object.keys(this.sources)}listenedPaths(e){let t=this.listenersByModule.get(e);return t===void 0?[]:[...t]}addListener(e,t,n){let r=this.listenerTargets.get(e);r||(r=new Map,this.listenerTargets.set(e,r));let i=r.get(t);i||(i={target:new EventTarget,count:0},r.set(t,i));let a=i,o=r,[s]=V.splitModuleFilePathAndModulePath(e),c=this.listenersByModule.get(s);c===void 0&&(c=new Set,this.listenersByModule.set(s,c)),c.add(e);let l=e=>{n(e.detail)};a.target.addEventListener(Nb,l),a.count++;let[u]=V.splitModuleFilePathAndModulePath(e);this.events.emit({type:`source:listen`,path:e,moduleFilePath:u});let d=!1;return()=>{if(!d&&(d=!0,a.target.removeEventListener(Nb,l),a.count--,this.events.emit({type:`source:unlisten`,path:e,moduleFilePath:u}),a.count<=0&&o.get(t)===a&&(o.delete(t),o.size===0&&this.listenerTargets.get(e)===o))){this.listenerTargets.delete(e);let t=this.listenersByModule.get(s);t!==void 0&&(t.delete(e),t.size===0&&this.listenersByModule.delete(s))}}}applyPatches(e,t,n){if(e.length===0)return;let r=e.map(e=>({record:e,origin:t,creatorFieldId:n(e.patchId)}));for(let e of r){let t=e.record.moduleFilePath,n=this.chains.get(t);n===void 0?this.chains.set(t,[e]):n.push(e)}this.applyEntries(r)}applyEntries(e){if(e.length===0)return;let t=[],n=[],r=[],i=new Set,a=[];for(let{record:o,origin:s,creatorFieldId:c}of e){let e=this.sources[o.moduleFilePath],l=e===void 0?void 0:this.substitutedSource(o.moduleFilePath,e);if(l===void 0||e===void 0){this.activity.work(`source:skip-unloaded`,o.moduleFilePath);continue}let u=o.patch.filter(e=>e.op!==`file`);if(u.length===0){t.push(o.patchId);continue}this.activity.work(`source:clone-module`,o.moduleFilePath),this.activity.work(`source:apply-patch`,o.patchId);let d=Ab(bb(l),Mb,u);if(ne.isOk(d)){this.storePatched(o.moduleFilePath,e,d.value),this.bump(o.moduleFilePath),t.push(o.patchId),i.add(o.moduleFilePath);let n=Fb(o);r.push(...n);let l=a.find(e=>e.origin===s&&e.creatorFieldId===c);l===void 0?a.push({origin:s,creatorFieldId:c,paths:[...n]}):l.paths.push(...n)}else n.push({patchId:o.patchId,message:d.error.message})}(t.length!==0||n.length!==0)&&(this.events.emit({type:`source:patch-apply`,success:t,failed:n,modules:[...i]}),r.length!==0&&this.wakeListeners(i,a))}wakeListeners(e,t){let n=new Set;for(let t of e){let e=this.listenersByModule.get(t);if(e!==void 0)for(let t of e)n.add(t)}this.activity.work(`source:scan-listeners`,void 0,n.size);for(let e of n){let n=this.listenerTargets.get(e);if(n===void 0)continue;let r=t.filter(t=>eoe(t.paths,e));if(r.length===0)continue;let[i]=V.splitModuleFilePathAndModulePath(e),a=this.revisionOf(i);for(let[t,i]of n){let n=r.find(e=>e.creatorFieldId!==t);if(n===void 0)continue;this.activity.work(`source:wake-listener`,e);let o={type:`${n.origin}-patch`,path:e,revision:a};i.target.dispatchEvent(new CustomEvent(Nb,{detail:o}))}}}},Nb=`val:field-changed`;function Pb(e,t){return e.status===t.status?e.status===`ready`&&t.status===`ready`?e.data===t.data&&e.revision.n===t.revision.n:e.status===`absent`&&t.status===`absent`?e.revision.n===t.revision.n:e.status===`entry-failed`&&t.status===`entry-failed`?e.key===t.key&&e.message===t.message:e.status===`entry-missing`&&t.status===`entry-missing`||e.status===`entry-loading`&&t.status===`entry-loading`?e.key===t.key:e.status===`module-loading`:!1}function Fb(e){let t=[],n=n=>{t.push(V.joinModuleFilePathAndModulePath(e.moduleFilePath,V.patchPathToModulePath(n)))};for(let t of e.patch)t.op!==`file`&&(n(t.path),(t.op===`move`||t.op===`copy`)&&(n(t.from),r(t.from)),(t.op===`add`||t.op===`remove`||t.op===`move`)&&r(t.path));return t;function r(e){if(e.length===0)return;let t=e[e.length-1];Number.isInteger(Number(t))&&n(e.slice(0,-1))}}function Ib(e,t){let n=V.splitModulePath(t),r=e;for(let e=0;e<n.length;e++){let t=n[e];if(typeof r!=`object`||!r)return{status:`absent`};if(Array.isArray(r)){let e=Number(t);if(!Number.isInteger(e)||e<0||e>=r.length)return{status:`absent`};r=r[e];continue}if(!(t in r))return{status:`absent`};if(r=r[t],e===0&&e<n.length-1&&V.isJson(r))return{status:`needs-entry`,key:t}}return{status:`found`,value:r}}function roe(e,t){if(t===void 0||t.size===0||!Lb(e))return e;let n=null;for(let[r,i]of t)V.isJson(e[r])&&(n===null&&(n={...e}),n[r]=i);return n??e}function Lb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rb(e,t){return`${e}\0${t}`}var ioe=new TextEncoder;function aoe(e){let t=[],n=[];for(let r of e)r.op===`file`?(t.push(r),n.push({...r,value:typeof r.value==`string`?V.getSHA256Hash(ioe.encode(r.value)):r.value})):n.push(r);return{patchOps:n,fileOps:t}}var ooe=class{setPublishInFlight(e){this.publishInFlight=e}setParentRefSource(e){this.parentRefSource=e}constructor(e,t=()=>crypto.randomUUID(),n=hb,r){this.fetchPatches=e,this.newPatchId=t,this.activity=n,this.uploadFile=r,this.events=new mb,this.ordered=[],this.dataById=new Map,this.originById=new Map,this.appliedIds=new Set,this.failedById=new Map,this.fetching=new Set,this.creatorByPatchId=new Map,this.sessionByPatchId=new Map,this.pendingIds=new Set,this.verifying=new Set,this.notDeliveredOnce=new Set,this.publishInFlight=()=>!1,this.lastBaseSha=null,this.publishedIds=new Set,this.publishedModuleFilePaths=new Set,this.version=0,this.parentRefSource=()=>null,this.statSeen=!1,this.publishErrorById=new Map,this.publishErrorsAt=null,this.filePatchIdsAt=null}listenTo(e,t){let n=e.events.on(`stat:receive`,t=>{let n=e.currentBaseSha(),r=this.lastBaseSha!==null&&n!==null&&n!==this.lastBaseSha;n!==null&&(this.lastBaseSha=n),this.onStatPatchIds(t.patches,r)}),r=t.events.on(`source:patch-apply`,e=>{for(let t of e.success)this.appliedIds.add(t),this.failedById.delete(t);for(let t of e.failed)this.failedById.set(t.patchId,t.message),this.appliedIds.delete(t.patchId);this.events.emit({type:`patch:head`,head:this.currentHead()})});return()=>{n(),r()}}async onStatPatchIds(e,t=!1){this.statSeen=!0;let n=new Set(e.filter(e=>this.publishedIds.has(e)&&!this.dataById.has(e)));n.size>0&&console.debug(`Val: ignoring published changes named by a stat that predates the publish.`,{patchIds:[...n]});let r=n.size>0?e.filter(e=>!n.has(e)):e,i=new Set(r);for(let e of r)this.originById.has(e)||this.originById.set(e,`external`);let a=this.ordered.filter(e=>!i.has(e));this.ordered=[...r,...a],this.bump(),this.reconcileVanished(a.filter(e=>!this.pendingIds.has(e)),t);let o=r.filter(e=>!this.dataById.has(e)&&!this.fetching.has(e));if(this.events.emit({type:`patch:head`,head:this.currentHead()}),o.length===0)return;for(let e of o)this.fetching.add(e);this.activity.work(`patch:fetch`,void 0,o.length);let s=await this.fetchPatches(o);s.error!==void 0&&this.events.emit({type:`patch:fetch-failed`,patches:o,message:s.error});let c=[];for(let e of s.patches)this.fetching.delete(e.patchId),this.notDeliveredOnce.delete(e.patchId),this.dataById.set(e.patchId,e),c.push(e.patchId),this.bump();for(let[e,t]of Object.entries(s.errors??{}))this.fetching.delete(e),this.notDeliveredOnce.delete(e),this.failedById.set(e,t);let l=[],u=[];for(let e of o)if(this.fetching.delete(e)&&!this.dataById.has(e)&&this.ordered.includes(e)){if(!this.notDeliveredOnce.has(e)){this.notDeliveredOnce.add(e),u.push(e);continue}this.failedById.set(e,`The server said this change exists, but did not send it.`),l.push(e)}u.length>0&&console.warn(`Val: the server named these unpublished changes and did not send them. Asking again on the next stat before reporting it — an announcement can be older than a delete.`,{patchIds:u}),c.length>0&&this.events.emit({type:`patch:receive`,patches:c}),l.length>0&&this.events.emit({type:`patch:announced-not-delivered`,patches:l})}async reconcileVanished(e,t){if(this.publishInFlight())return;let n=e.filter(e=>!this.verifying.has(e));if(n.length!==0){for(let e of n)this.verifying.add(e);this.activity.work(`patch:verify-vanished`,void 0,n.length);try{let e=await this.fetchPatches(n);e.error!==void 0&&this.events.emit({type:`patch:fetch-failed`,patches:n,message:e.error});let r=new Set;for(let t of e.patches)r.add(t.patchId);for(let t of Object.keys(e.errors??{}))r.add(t);let i=n.filter(e=>!r.has(e)&&this.ordered.includes(e)&&!this.pendingIds.has(e));i.length>0&&(t?this.forgetPublished(i):this.drop(i))}finally{for(let e of n)this.verifying.delete(e)}}}async createPatch(e,t,n,r,i,a,o,s=`image`,c=!1){let l=a??this.newPatchId(),u=this.parentRefSource(),{patchOps:d,fileOps:f}=aoe(t),p=c?[]:f.filter(e=>typeof e.value==`string`),m=f.filter(e=>e.value===null);if((p.length>0||m.length>0)&&!this.uploadFile)return{status:`upload-failed`,message:`This patch carries files, but no upload seam is configured. Refusing rather than dropping the bytes.`,rolledBack:[],orphaned:[]};let h=this.uploadFile,g=[];if(h)for(let e of p){this.activity.work(`patch:upload-file`,e.filePath);let t=g.length,n=await h({patchId:l,parentRef:u,filePath:e.filePath,data:e.value,type:s,remote:e.remote,metadata:e.metadata,onProgress:i===void 0?void 0:(e,n)=>i(e,n,t,p.length)});if(n.status===`error`){let e=[],t=[];for(let n of g)this.activity.work(`patch:rollback-file`,n.filePath),(await h({patchId:l,parentRef:u,filePath:n.filePath,data:null,type:s,remote:n.remote})).status===`ok`?e.push(n.filePath):t.push(n.filePath);return{status:`upload-failed`,message:n.message,rolledBack:e,orphaned:t}}g.push({filePath:e.filePath,remote:e.remote===!0})}let _={patchId:l,moduleFilePath:e,patch:d,meta:n,createdAt:new Date().toISOString()};if(this.dataById.set(l,_),this.originById.set(l,`internal`),this.pendingIds.add(l),r!==void 0&&this.creatorByPatchId.set(l,r),o!==void 0&&this.sessionByPatchId.set(l,o),this.ordered=[...this.ordered,l],this.bump(),this.activity.work(`patch:create`,l),this.events.emit({type:`patch:create`,patches:[l]}),h)for(let e of m)this.activity.work(`patch:delete-file`,e.filePath),await h({patchId:l,parentRef:u,filePath:e.filePath,data:null,type:s,remote:e.remote});return{status:`created`,record:_}}unsavedRecords(){let e=[];for(let t of this.ordered){if(!this.pendingIds.has(t))continue;let n=this.dataById.get(t);n&&e.push(n)}return e}mintPatchId(){return this.newPatchId()}sessionOf(e){return this.sessionByPatchId.get(e)}isPending(e){return this.pendingIds.has(e)}pendingPatchIds(){return this.ordered.filter(e=>this.pendingIds.has(e))}markPublished(e){let t=!1;for(let n of e)this.publishedIds.has(n)||(this.publishedIds.add(n),t=!0);t&&this.bump()}publishedPatchIds(){return this.publishedIds}publishedModules(){return[...this.publishedModuleFilePaths]}markSaved(e){let t=[];for(let n of e)this.pendingIds.delete(n)&&t.push(n);t.length!==0&&(this.bump(),this.activity.work(`patch:mark-saved`,void 0,t.length))}forgetPublished(e){let t=[];for(let n of e){if(!this.dataById.has(n)&&!this.ordered.includes(n))continue;let e=this.dataById.get(n)?.moduleFilePath;e!==void 0&&this.publishedModuleFilePaths.add(e),this.dataById.delete(n),this.originById.delete(n),this.pendingIds.delete(n),this.appliedIds.delete(n),this.failedById.delete(n),this.creatorByPatchId.delete(n),this.sessionByPatchId.delete(n),this.fetching.delete(n),this.notDeliveredOnce.delete(n),this.publishErrorById.delete(n),t.push(n)}if(t.length===0)return;let n=new Set(t);this.ordered=this.ordered.filter(e=>!n.has(e)),this.bump(),this.activity.work(`patch:forget-published`,void 0,t.length),this.events.emit({type:`patch:head`,head:this.currentHead()})}drop(e){let t=[],n=new Set;for(let r of e){let e=this.dataById.get(r);e===void 0&&!this.ordered.includes(r)||(e!==void 0&&n.add(e.moduleFilePath),this.dataById.delete(r),this.originById.delete(r),this.pendingIds.delete(r),this.appliedIds.delete(r),this.failedById.delete(r),this.creatorByPatchId.delete(r),this.sessionByPatchId.delete(r),this.fetching.delete(r),this.notDeliveredOnce.delete(r),this.publishErrorById.delete(r),this.publishedIds.delete(r),t.push(r))}if(t.length===0)return;let r=new Set(t);this.ordered=this.ordered.filter(e=>!r.has(e)),this.bump(),this.activity.work(`patch:drop`,void 0,t.length),this.events.emit({type:`patch:drop`,patches:t,modules:[...n]}),this.events.emit({type:`patch:head`,head:this.currentHead()})}async getHead(){return this.currentHead()}recordsFor(e){let t=new Set(e),n=[];for(let e of this.ordered){if(!t.has(e))continue;let r=this.dataById.get(e);r&&n.push(r)}return n}allRecords(){return this.recordsFor(this.ordered)}chainVersion(){return this.version}recordPublishErrors(e){let t=Object.entries(e);if(t.length!==0){for(let[e,n]of t)this.publishErrorById.set(e,n);this.bump()}}publishErrors(){let e=this.publishErrorsAt;if(e!==null&&e.n===this.version)return e.byModule;let t={};for(let[e,n]of this.publishErrorById){let r=this.dataById.get(e);if(r===void 0)continue;let i=t[r.moduleFilePath]??{};i[e]={message:n,source:`server`},t[r.moduleFilePath]=i}return this.publishErrorsAt={n:this.version,byModule:t},t}bump(){this.version++,this.events.emit({type:`patch:chain`,version:this.version})}originOf(e){return this.originById.get(e)??`external`}chainSettled(){if(!this.statSeen)return!1;for(let e of this.ordered)if(!this.failedById.has(e)&&(!this.dataById.has(e)||!this.appliedIds.has(e)&&!this.pendingIds.has(e)))return!1;return!0}chainProgress(){let e=[],t=[],n=[],r=0;for(let i of this.ordered){if(this.failedById.has(i)){n.push(i),r++;continue}if(!this.dataById.has(i)){e.push(i);continue}if(!this.appliedIds.has(i)&&!this.pendingIds.has(i)){t.push(i);continue}r++}return{total:this.ordered.length,settled:r,unfetched:e,unapplied:t,failed:n,statSeen:this.statSeen}}currentHead(){if(this.ordered.length===0)return{type:`empty`};let e=this.ordered[this.ordered.length-1],t=this.originOf(e),n=this.dataById.get(e)??null;return this.failedById.has(e)?{type:`${t}-failed`,patchId:e,patch:n}:n===null||!this.appliedIds.has(e)?{type:`${t}-partial`,patchId:e,patch:n}:{type:`${t}-complete`,patchId:e,patch:n}}creatorOf(e){return this.creatorByPatchId.get(e)}filePatchIds(){let e=this.filePatchIdsAt;if(e!==null&&e.n===this.version)return e.map;let t=new Map;for(let e of this.ordered){let n=this.dataById.get(e);if(n!==void 0&&!(n.appliedAt||this.publishedIds.has(e)))for(let r of n.patch)r.op===`file`&&t.set(r.filePath,e)}return this.filePatchIdsAt={n:this.version,map:t},t}hasUnsavedFrom(e,t){for(let n of this.pendingIds)if(this.creatorByPatchId.get(n)===t&&this.dataById.get(n)?.moduleFilePath===e)return!0;return!1}},soe=class{constructor(){this.events=new mb,this.patches=[],this.baseSha=null}receiveStat(e){this.patches=[...e.patches],e.baseSha!==void 0&&(this.baseSha=e.baseSha),this.events.emit({type:`stat:receive`,patches:[...this.patches]}),e.removed!==void 0&&e.removed.length>0&&this.events.emit({type:`patch:removed-by-server`,removed:e.removed})}currentPatchIds(){return[...this.patches]}currentBaseSha(){return this.baseSha}},coe=class{constructor(e=hb){this.activity=e,this.events=new mb,this.transient=[],this.snapshot=null,this.networkErrorSince=null,this.schemaError=null,this.freshness=`current`,this.nextId=0}reportError(e,t){let n=this.transient.find(t=>t.message===e);if(n!==void 0){n.timestamp=Date.now(),n.details=t??n.details,this.announce();return}this.transient=[...this.transient,{id:`status-${++this.nextId}`,message:e,timestamp:Date.now(),details:t}],this.activity.work(`status:report-error`),this.announce()}dismissErrors(e){let t=new Set(e),n=this.transient.filter(e=>!t.has(e.id));n.length!==this.transient.length&&(this.transient=n,this.announce())}reportNetworkError(){this.networkErrorSince===null&&(this.networkErrorSince=Date.now(),this.announce())}clearNetworkError(){this.networkErrorSince!==null&&(this.networkErrorSince=null,this.announce())}reportSchemaError(e){this.schemaError!==e&&(this.schemaError=e,this.announce())}reportSchemaOutOfDate(){this.freshness!==`out-of-date`&&(this.freshness=`out-of-date`,this.activity.work(`status:schema-out-of-date`),this.announce())}current(){return this.snapshot===null&&(this.snapshot={errors:this.transient,networkErrorSince:this.networkErrorSince,schemaError:this.schemaError,schema:this.freshness}),this.snapshot}announce(){this.snapshot=null,this.events.emit({type:`status:change`})}};function loe(e,t,n){let r=[];for(let i of e){if(n(i.patchId)!==t)break;r.push(i)}return r}function uoe(e,t){return e.status===t.status?e.status===`in-sync`||t.status===`in-sync`?!0:e.patches.length===t.patches.length&&e.patches.every((e,n)=>e===t.patches[n])?e.status===`retrying`&&t.status===`retrying`?e.attempt===t.attempt&&e.reason===t.reason:!0:!1:!1}var doe=class{constructor(e,t,n,r=hb,i,a=e=>Math.min(3e4,500*2**(e-1)),o=e=>new Promise(t=>setTimeout(t,e))){this.patchStore=e,this.savePatches=t,this.resync=n,this.activity=r,this.sessionId=i,this.backoffMs=a,this.sleep=o,this.events=new mb,this.baseSha=null,this.statPatchIds=[],this.savedNotInStat=[],this.inFlight=null,this.attempt=0,this.reportedStuck=!1,this.state={status:`in-sync`},this.stopped=!1}listenTo(){return this.patchStore.events.on(`patch:create`,()=>{this.flush()})}receiveStat(e,t){this.baseSha=e,this.statPatchIds=[...t];let n=new Set(t);this.savedNotInStat=this.savedNotInStat.filter(e=>!n.has(e))}forget(e){if(e.length===0)return;let t=new Set(e);this.savedNotInStat=this.savedNotInStat.filter(e=>!t.has(e)),this.statPatchIds=this.statPatchIds.filter(e=>!t.has(e))}currentState(){return this.state}currentParentRef(){if(this.baseSha===null)return null;let e=this.savedNotInStat[this.savedNotInStat.length-1]??this.statPatchIds[this.statPatchIds.length-1];return e===void 0?{type:`head`,headBaseSha:this.baseSha}:{type:`patch`,patchId:e}}async flush(){if(this.inFlight!==null)return this.inFlight.then(()=>this.flush());let e=this.drain().finally(()=>{this.inFlight=null});return this.inFlight=e,e}async drain(){for(;;){let e=this.patchStore.unsavedRecords();if(e.length===0){this.setState({status:`in-sync`});return}if(this.stopped)return;let t=this.savePatches;if(t===void 0){this.setState({status:`pending`,patches:e.map(e=>e.patchId)});return}let n=this.currentParentRef(),r=this.patchStore.sessionOf(e[0].patchId),i=loe(e,r,e=>this.patchStore.sessionOf(e)),a=i.map(e=>e.patchId);if(n===null){this.setState({status:`retrying`,patches:a,reason:`network-error`,message:`Cannot save yet: the server has not said what the chain starts from.`,attempt:this.attempt});return}this.setState({status:`saving`,patches:a}),this.activity.work(`patch:save`,void 0,i.length),this.events.emit({type:`patch:save`,patches:a,parentRef:n});let o=await t({patches:i.map(e=>({path:e.moduleFilePath,patchId:e.patchId,patch:e.patch})),parentRef:n,sessionId:r??this.sessionId});if(this.stopped||await this.handle(o,a))return}}async handle(e,t){return e.status===`saved`?(this.attempt=0,this.reportedStuck=!1,this.savedNotInStat.push(...e.newPatchIds),this.patchStore.markSaved(e.newPatchIds),this.events.emit({type:`patch:saved`,patches:e.newPatchIds,parentRef:e.parentRef}),!1):e.status===`rejected`?(this.reportedStuck=!1,this.attempt=0,this.patchStore.drop(t),this.events.emit({type:`patch:save-rejected`,patches:t,message:e.message,errors:e.errors}),!1):(this.attempt++,e.status===`conflict`?(this.activity.work(`patch:save-conflict`),this.savedNotInStat=[],this.setState({status:`retrying`,patches:t,reason:`conflict`,message:e.message,attempt:this.attempt}),this.events.emit({type:`patch:save-conflict`,patches:t,message:e.message}),await this.resync(),this.stopped?!0:(this.attempt>=2&&this.reportStuck(t,`conflict`,e.message),await this.sleep(this.backoffMs(this.attempt)),this.stopped)):(this.activity.work(`patch:save-retry`),this.setState({status:`retrying`,patches:t,reason:e.status,message:e.message,attempt:this.attempt}),e.status!==`unauthorized`&&this.attempt>=2&&this.reportStuck(t,e.status,e.message),await this.sleep(this.backoffMs(this.attempt)),this.stopped))}reportStuck(e,t,n){this.reportedStuck||(this.reportedStuck=!0,this.events.emit({type:`patch:save-stuck`,patches:e,reason:t,message:n,attempt:this.attempt}))}setState(e){uoe(this.state,e)||(this.state=e,this.events.emit({type:`patch:sync-state`,state:e}))}dispose(){this.stopped=!0}},foe=class{constructor(e,t,n=hb){this.schemaStore=e,this.sourceStore=t,this.activity=n,this.events=new mb,this.instances={},this.receivedAt=null,this.moduleFailures=[]}initializedAt(){return this.receivedAt}failures(){return this.moduleFailures}receive(e){let t={},n={},r=[],i=[];for(let a of e)try{let e=V.getValPath(a);if(e===void 0){i.push({moduleFilePath:null,message:`Module has no path`});continue}let o=e,s=V.getSchema(a);if(s===void 0){i.push({moduleFilePath:o,message:`Module has no schema`});continue}this.activity.work(`host:serialize-schema`,o),t[o]=s.executeSerialize(),n[o]=JSON.parse(JSON.stringify(V.getSource(a))),this.instances[o]=s,r.push(o)}catch(e){i.push({moduleFilePath:V.getValPath(a)??null,message:e instanceof Error?e.message:String(e)})}this.moduleFailures=i,this.receivedAt=Date.now(),this.events.emit({type:`host:receive`,modules:r}),this.schemaStore.receive(t),this.sourceStore.receive(n)}async preview(e,t){let n=this.instances[e];if(!n)return{status:`unknown-module`};let r=this.sourceStore.moduleSource(e);if(r===void 0)return{status:`unknown-module`};try{this.activity.work(`host:execute-preview`,e);let i=t!==void 0&&t.length>0?vr([...t]):void 0;return{status:`previewed`,preview:n.executePreview(e,r,i)}}catch(e){return{status:`error`,message:e instanceof Error?e.message:String(e)}}}validateSpeculative(e,t){let n=this.instances[e];return n?(this.activity.work(`host:execute-validate`,e),{status:`validated`,errors:n.executeValidate(e,t)}):{status:`unknown-module`}}async customValidate(e,t){let n=this.instances[e];if(!n)return{status:`unknown-module`};let r=this.sourceStore.moduleSource(e);if(r===void 0)return{status:`unknown-module`};if(t.length===0)return{status:`validated`,errors:!1};try{return this.activity.work(`host:execute-validate`,e),{status:`validated`,errors:n.executeValidate(e,r)}}catch(e){return{status:`error`,message:e instanceof Error?e.message:String(e)}}}has(e){return this.instances[e]!==void 0}loadedModules(){return Object.keys(this.instances)}};function poe(e,t){let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n){let n=r;if(!(n in t)||e[n]!==t[n])return!1}return!0}function moe(e,t){return e.status===t.status?e.status===`previewed`&&t.status===`previewed`?e.preview===t.preview:e.status===`error`&&t.status===`error`?e.message===t.message:!0:!1}var hoe=class{constructor(e,t,n,r=hb){this.host=e,this.sourceStore=t,this.schemaStore=n,this.activity=r,this.events=new mb,this.previews=new Map,this.stale=new Set,this.peeked=new Map,this.pendingForget=new Map,this.inFlight=new Map,this.pendingReads=new Map,this.listenersByModule=new Map,this.allPreviews=null,this.generation=0}listenTo(){let e=this.sourceStore.events.on(`source:listen`,e=>{let t=this.listenersByModule.get(e.moduleFilePath)??0;this.listenersByModule.set(e.moduleFilePath,t+1);let n=this.pendingForget.get(e.moduleFilePath);n!==void 0&&(clearTimeout(n),this.pendingForget.delete(e.moduleFilePath)),!(this.previews.has(e.moduleFilePath)||this.inFlight.has(e.moduleFilePath)||this.pendingReads.has(e.moduleFilePath))&&this.refresh(e.moduleFilePath)}),t=this.sourceStore.events.on(`source:unlisten`,e=>{let t=(this.listenersByModule.get(e.moduleFilePath)??0)-1;if(t>0){this.listenersByModule.set(e.moduleFilePath,t);return}this.listenersByModule.delete(e.moduleFilePath);let n=e.moduleFilePath,r=this.pendingForget.get(n);r!==void 0&&clearTimeout(r),this.pendingForget.set(n,setTimeout(()=>{this.pendingForget.delete(n),!((this.listenersByModule.get(n)??0)>0)&&(this.previews.delete(n),this.stale.delete(n),this.pendingReads.delete(n))},0))}),n=this.sourceStore.events.on(`source:patch-apply`,e=>{this.invalidate(e.modules)}),r=this.sourceStore.events.on(`source:init`,e=>{this.invalidate(e.sources)}),i=this.schemaStore.events.on(`schema:init`,e=>{this.invalidate(e.modules)});return()=>{e(),t(),n(),r(),i();for(let e of this.pendingForget.values())clearTimeout(e);this.pendingForget.clear()}}invalidate(e){this.generation++;let t=e.filter(e=>!this.stale.has(e)&&this.previews.has(e));for(let t of e)this.stale.add(t);t.length>0&&this.events.emit({type:`preview:invalidate`,modules:t})}async get(e){let[t]=V.splitModuleFilePathAndModulePath(e);this.stale.has(t)||!this.covers(t,e)?(this.activity.work(`preview:cache-miss`,t),await this.refreshFor(t,e)):this.activity.work(`preview:cache-hit`,t);let n=this.previews.get(t);if(n===void 0)return{status:`no-preview`};let r=n.preview[e]??n.preview[t];return r===void 0?{status:`no-preview-at-path`}:{status:`previewed`,preview:r}}covers(e,t){let n=this.previews.get(e);return n===void 0?!1:n.scope===null||n.scope.has(t)}async refreshFor(e,t){let n=this.pendingReads.get(e);if(n!==void 0)return this.activity.work(`preview:share-in-flight`,e),n.paths.add(t),n.request;let r=new Set([t]),i=(async()=>{await Promise.resolve(),this.pendingReads.delete(e),await this.computePreview(e,r)})();return n={paths:r,request:i},this.pendingReads.set(e,n),i}async refresh(e){return this.computePreview(e,new Set)}async computePreview(e,t,n=!1){let r=n?void 0:this.inFlight.get(e);if(r!==void 0){let n=r.scope,i=n===null||[...t].every(e=>n.has(e));return this.activity.work(`preview:share-in-flight`,e),await r.request,i?void 0:this.computePreview(e,t,!0)}let i=new Set(this.sourceStore.listenedPaths(e));for(let e of t)i.add(e);let a=this.generation,o=(async()=>{let t=this.schemaStore.declaresPreview(e)?await this.host.preview(e,[...i]):{status:`previewed`,preview:{}};t.status===`previewed`?(this.previews.set(e,{preview:t.preview,scope:i.size===0?null:i}),this.generation===a&&this.stale.delete(e),this.events.emit({type:`preview:result`,moduleFilePath:e})):t.status===`unknown-module`?(this.previews.delete(e),this.generation===a&&this.stale.delete(e)):(this.previews.delete(e),this.generation===a&&this.stale.delete(e),this.events.emit({type:`preview:error`,moduleFilePath:e,message:t.message}))})().finally(()=>{this.inFlight.get(e)?.request===o&&this.inFlight.delete(e)});return this.inFlight.set(e,{scope:i.size===0?null:i,request:o}),o}peek(e){let t=this.computePeek(e),n=this.peeked.get(e);return n!==void 0&&moe(n,t)?n:(this.peeked.set(e,t),t)}all(){let e={};for(let[t,n]of this.previews)e[t]=this.stale.has(t)?null:n.preview;let t=this.allPreviews;return t!==null&&poe(t,e)?t:(this.allPreviews=e,e)}computePeek(e){let[t]=V.splitModuleFilePathAndModulePath(e);if(!this.schemaStore.declaresPreview(t))return{status:`no-preview`};if(this.stale.has(t))return{status:`needs-preview`};let n=this.previews.get(t);if(n===void 0||!this.covers(t,e))return{status:`needs-preview`};let r=n.preview[e]??n.preview[t];return r===void 0?{status:`no-preview-at-path`}:{status:`previewed`,preview:r}}};function zb(e,t){if(!t||t.length===0)return new Set([e.type]);let n=new Set,r=e,i=-1;for(let e of t){if(i++,!r)break;if(r.type===`array`)r=r.item;else if(r.type===`record`)r=r.item;else if(r.type===`object`)r=r.items[e];else if(r.type===`richtext`)break;else if(r.type===`union`){if(typeof r.key==`string`){let e=r.items;for(let r of e){let e=zb(r,t.slice(i));for(let t of Array.from(e.values()))n.add(t)}return n}if(i!==t.length-1)throw Error(`Found string union (primitive), but path has more parts: `+t.join(`/`)+` at `+e);break}else if(r.type===`boolean`||r.type===`number`||r.type===`string`||r.type===`date`||r.type===`dateTime`||r.type===`color`||r.type===`file`||r.type===`image`||r.type===`keyOf`||r.type===`route`||r.type===`literal`){if((r.type===`image`||r.type===`file`)&&t[i]===`metadata`)break;if(i!==t.length-1)throw Error(`Found `+r.type+` (primitive), but path has more parts: `+t.join(`/`)+` at `+e);break}else{let n=r.type;return console.error(`Unexecpted resolved schema type: ${n} in ${t.join(`/`)} at ${e}`),new Set([n])}}return r&&(n.add(r.type),r.type===`union`&&(typeof r.key==`string`?n.add(`object`):n.add(`string`))),n}var goe=class{constructor(){this.patchSetMetadata={},this.orderedInsertKeys=[],this.insertedPatches=new Set}reset(){this.patchSetMetadata={},this.orderedInsertKeys=[],this.insertedPatches=new Set}getInsertedPatches(){return this.insertedPatches}insertPath(e,t,n,r,i,a,o,s){let c=t.length>0?`${e}?${t.join(`/`)}`:e,l=[];for(let e=this.orderedInsertKeys.length-1;e>=0;e--){let t=this.orderedInsertKeys[e];c===t?(this.orderedInsertKeys.splice(e,1),this.orderedInsertKeys.unshift(c)):c.startsWith(t)?(c=t,this.orderedInsertKeys.splice(e,1),this.orderedInsertKeys.unshift(c)):t.startsWith(c)&&l.push(e)}for(let n of l){let a=this.orderedInsertKeys[n];this.orderedInsertKeys.splice(n,1);let s=this.patchSetMetadata[a];if(this.patchSetMetadata[c]||(this.patchSetMetadata[c]={moduleFilePath:e,patchPath:t,patches:[],authors:[],opTypes:[],schemaTypes:Array.from(o),lastUpdated:r,lastUpdatedBy:i}),s)for(let e of s.patches.slice())this.patchSetMetadata[c].patches.unshift(e),e.author!==null&&this.patchSetMetadata[c].authors.unshift(e.author),this.patchSetMetadata[c].opTypes.unshift(e.opType);else throw Error(`Could not find patch set metadata or patch metadata for (inserted) patch set path: ${a}`);a!==c&&delete this.patchSetMetadata[a]}this.patchSetMetadata[c]||(this.patchSetMetadata[c]={moduleFilePath:e,patchPath:t,patches:[],authors:[],opTypes:[],schemaTypes:o,lastUpdated:r,lastUpdatedBy:i}),i!==null&&!this.patchSetMetadata[c].authors.includes(i)&&this.patchSetMetadata[c].authors.unshift(i),this.patchSetMetadata[c].lastUpdatedBy=i,this.patchSetMetadata[c].lastUpdated=r,this.patchSetMetadata[c].opTypes.includes(a)||this.patchSetMetadata[c].opTypes.unshift(a),this.patchSetMetadata[c].patches.unshift({patchPath:s,patchId:n,author:i,createdAt:r,opType:a,schemaTypes:o}),this.orderedInsertKeys.includes(c)||this.orderedInsertKeys.unshift(c)}insert(e,t,n,r,i,a){if(!this.insertedPatches.has(r)){if(!t){this.insertPath(e,[],r,i,a,n.op,[],n.path);return}if(this.insertedPatches.add(r),n.op!==`file`&&n.op!==`test`)try{if(n.op===`replace`){let o=zb(t,n.path);this.insertPath(e,n.path,r,i,a,n.op,Array.from(o),n.path)}else if(n.op===`add`||n.op===`remove`||n.op===`move`||n.op===`copy`){let o=n.path.slice(0,-1),s=zb(t,o);if(s.size===1&&s.has(`array`)){if(this.insertPath(e,o,r,i,a,n.op,Array.from(s),n.path),n.op===`move`){let o=n.from.slice(0,-1),s=zb(t,o);this.insertPath(e,o,r,i,a,n.op,Array.from(s),n.path)}}else if(s.size===1&&s.has(`record`)){let o=n.path,s=zb(t,o);if(this.insertPath(e,o,r,i,a,n.op,Array.from(s),n.path),n.op===`move`){let o=n.from,s=zb(t,o);this.insertPath(e,o,r,i,a,n.op,Array.from(s),n.path)}}else if(s.size===1&&!(s.has(`image`)||s.has(`file`)))throw Error(`Cannot perform op: '${n.op}' on non-array or non-record schema. Type: ${s.values().next().value}`);else this.insertPath(e,o,r,i,a,n.op,[t.type],n.path)}else throw Error(`Unreachable op: `+n)}catch(o){o instanceof Error?console.error(`Could not resolve path while creating patch set`,o.message):console.error(`Could not resolve path while creating patch set`,o),this.insertPath(e,[],r,i,a,n.op,[t.type],n.path)}}}isInserted(e){return this.insertedPatches.has(e)}serialize(){return this.orderedInsertKeys.map(e=>{if(e in this.patchSetMetadata)return this.patchSetMetadata[e];throw Error(`Could not find patch set metadata or patch metadata for (inserted) patch set path: ${e}`)})}},_oe=class{constructor(e=hb){this.activity=e,this.events=new mb,this.patchSets=new goe}insertRecords(e,t,n){n&&this.patchSets.reset();let r=new Set;for(let n of e){let e=t[n.moduleFilePath];this.activity.work(`patch-set:insert`,n.patchId,n.patch.length);for(let t of n.patch)this.patchSets.insert(n.moduleFilePath,e,t,n.patchId,n.createdAt??new Date(0).toISOString(),n.authorId??null),t.op!==`file`&&t.op!==`test`&&r.add(`${n.moduleFilePath}?${t.path.join(`/`)}`)}this.events.emit({type:`patch-set:update`,patchSetPaths:[...r]})}async getPatchSets(e){return e.mode!==`current`&&this.insertRecords(e.records,e.schemas,e.mode===`rebuild`),this.activity.work(`patch-set:serialize`),this.patchSets.serialize()}reset(e){if(e!==void 0)throw Error(`PatchSetStore.reset: per-module reset is not supported — PatchSets has no per-module removal`);this.patchSets.reset(),this.events.emit({type:`patch-set:update`,patchSetPaths:[]})}},voe=class{constructor(){this.inserted=[],this.mustRebuild=!0}plan(e){if(this.mustRebuild||this.inserted.length>e.length)return{mode:`rebuild`,patchIds:[...e]};for(let t=0;t<this.inserted.length;t++)if(this.inserted[t]!==e[t])return{mode:`rebuild`,patchIds:[...e]};let t=e.slice(this.inserted.length);return t.length===0?{mode:`current`}:{mode:`append`,patchIds:t}}covers(e){if(e.mode!==`current`){if(e.mode===`rebuild`){this.inserted=[...e.patchIds],this.mustRebuild=!1;return}this.inserted=[...this.inserted,...e.patchIds]}}invalidate(){this.mustRebuild=!0,this.inserted=[]}insertedPatchIds(){return[...this.inserted]}};function Bb(e){if(e.customValidate===!0)return!0;switch(e.type){case`object`:return Object.values(e.items).some(Bb);case`array`:return Bb(e.item);case`record`:return Bb(e.item)||e.key!==void 0&&Bb(e.key);case`union`:return e.items.some(Bb);default:return!1}}function yoe(e,t,n){let r=[],i=new Set,a=(e,t,n)=>{if(t!==void 0&&!V.isJson(n)){if(n===null){t.customValidate===!0&&r.push(e);return}switch(t.customValidate===!0&&r.push(e),t.type){case`object`:if(!Vb(n))return;for(let r in t.items)r in n&&a(My(e,r),t.items[r],n[r]);return;case`record`:{if(!Vb(n))return;let r=Bb(t.item);for(let o in n){let s=n[o];if(V.isJson(s)){(t.customValidate===!0||r)&&i.add(o);continue}a(My(e,o),t.item,s)}return}case`array`:if(!Array.isArray(n))return;for(let r=0;r<n.length;r++)a(My(e,r),t.item,n[r]);return;case`union`:{let i=t.key;if(typeof i!=`string`||!Vb(n))return;let o=n[i];if(typeof o!=`string`)return;let s=t.items.filter(e=>e.type===`object`).find(e=>{let t=e.items[i];return t?.type===`literal`&&t.value===o});if(s){s.customValidate===!0&&t.customValidate!==!0&&r.push(e);for(let t in s.items)t in n&&a(My(e,t),s.items[t],n[t])}return}default:return}}};return a(e,t,n),{paths:r,needsJsonKeys:Array.from(i)}}function Vb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Hb={status:`stale`},boe=class e{constructor(e,t,n,r,i=hb){this.schemaStore=e,this.sourceStore=t,this.schemaValidation=n,this.host=r,this.activity=i,this.events=new mb,this.results=new Map,this.stale=new Set,this.inFlight=new Map,this.generation=0}listenTo(){let e=this.sourceStore.events.on(`source:init`,e=>{this.invalidate(e.sources)}),t=this.sourceStore.events.on(`source:patch-apply`,e=>{this.invalidate(e.modules)}),n=this.schemaStore.events.on(`schema:init`,e=>{this.invalidate(e.modules)});return()=>{e(),t(),n()}}invalidate(e){if(this.generation++,e.length===0)return;let t=e.filter(e=>this.results.has(e));for(let t of e)this.stale.add(t),this.results.delete(t);t.length>0&&this.events.emit({type:`validation:invalidate`,modules:t})}async validate(e){let t=this.results.get(e);if(t!==void 0&&!this.stale.has(e))return this.activity.work(`validation:cache-hit`,e),t;let n=this.inFlight.get(e);if(n)return this.activity.work(`validation:share-in-flight`,e),n;this.activity.work(`validation:cache-miss`,e);let r=this.run(e).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,r),r}static{this.MAX_RECOMPUTES=5}async run(t){let n=Hb;for(let r=0;r<e.MAX_RECOMPUTES;r++)if(n=await this.runOnce(t),n.status!==`validated`||!this.stale.has(t))return n;return n}async runOnce(e){let t=this.generation,n=this.schemaStore.get(e),r=this.sourceStore.moduleSource(e);if(n===void 0||r===void 0)return{status:`unknown-module`};this.activity.work(`validation:schema-validate`,e);let i=await this.schemaValidation.validate(e,r,n,String(this.schemaStore.version(e)));this.activity.work(`validation:collect-custom-targets`,e);let a=yoe(e,n,r).paths,o=i,s=`not-needed`;if(a.length>0){let t=await this.host.customValidate(e,a);t.status===`validated`?(this.activity.work(`validation:merge`,e),o=xoe(i,t.errors),s=`ran`):s=t.status===`unknown-module`?`unavailable`:`error`}let c={status:`validated`,errors:o,customValidatePaths:a,customValidateStatus:s,jsonEntriesLoaded:!this.sourceStore.hasUnloadedEntries(e)};return this.results.set(e,c),this.generation===t&&this.stale.delete(e),this.events.emit({type:`validation:result`,moduleFilePath:e,errors:o,customValidatePaths:a,customValidateStatus:s}),c}peek(e){let t=this.results.get(e);return t!==void 0&&!this.stale.has(e)?t:Hb}};function xoe(e,t){if(e===!1)return t;if(t===!1)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=e,i=n[t];if(!i){n[t]=r;continue}let a=new Set(i.map(e=>e.message));n[t]=[...i,...r.filter(e=>!a.has(e.message))]}return n}var Soe=`modulepreload`,Coe=function(e){return`/api/val/static/`+e},Ub={},woe=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Coe(t,n),t=s(t),t in Ub)return;Ub[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Soe,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Wb=s(((e,t)=>{t.exports={}})),Gb;function Kb(e,t,n){let r=typeof n,i=typeof e;if(r!==`undefined`){if(i!==`undefined`){if(n){if(i===`function`&&r===i)return function(t){return e(n(t))};if(t=e.constructor,t===n.constructor){if(t===Array)return n.concat(e);if(t===Map){var a=new Map(n);for(var o of e)a.set(o[0],o[1]);return a}if(t===Set){o=new Set(n);for(a of e.values())o.add(a);return o}}}return e}return n}return i===`undefined`?t:e}function qb(e,t){return e===void 0?t:e}function Jb(){return Object.create(null)}function Yb(e){return typeof e==`string`}function Xb(e){return typeof e==`object`}function Zb(e,t){if(Yb(t))e=e[t];else for(let n=0;e&&n<t.length;n++)e=e[t[n]];return e}var Toe=/[^\p{L}\p{N}]+/u,Eoe=/(\d{3})/g,Doe=/(\D)(\d{3})/g,Ooe=/(\d{3})(\D)/g,Qb=/[\u0300-\u036f]/g;function $b(e={}){if(!this||this.constructor!==$b)return new $b(...arguments);if(arguments.length)for(e=0;e<arguments.length;e++)this.assign(arguments[e]);else this.assign(e)}Gb=$b.prototype,Gb.assign=function(e){this.normalize=Kb(e.normalize,!0,this.normalize);let t=e.include,n=t||e.exclude||e.split,r;if(n||n===``){if(typeof n==`object`&&n.constructor!==RegExp){let e=``;r=!t,t||(e+=`\\p{Z}`),n.letter&&(e+=`\\p{L}`),n.number&&(e+=`\\p{N}`,r=!!t),n.symbol&&(e+=`\\p{S}`),n.punctuation&&(e+=`\\p{P}`),n.control&&(e+=`\\p{C}`),(n=n.char)&&(e+=typeof n==`object`?n.join(``):n);try{this.split=RegExp(`[`+(t?`^`:``)+e+`]+`,`u`)}catch{this.split=/\s+/}}else this.split=n,r=n===!1||`a1a`.split(n).length<2;this.numeric=Kb(e.numeric,r)}else{try{this.split=Kb(this.split,Toe)}catch{this.split=/\s+/}this.numeric=Kb(e.numeric,Kb(this.numeric,!0))}if(this.prepare=Kb(e.prepare,null,this.prepare),this.finalize=Kb(e.finalize,null,this.finalize),n=e.filter,this.filter=typeof n==`function`?n:Kb(n&&new Set(n),null,this.filter),this.dedupe=Kb(e.dedupe,!0,this.dedupe),this.matcher=Kb((n=e.matcher)&&new Map(n),null,this.matcher),this.mapper=Kb((n=e.mapper)&&new Map(n),null,this.mapper),this.stemmer=Kb((n=e.stemmer)&&new Map(n),null,this.stemmer),this.replacer=Kb(e.replacer,null,this.replacer),this.minlength=Kb(e.minlength,1,this.minlength),this.maxlength=Kb(e.maxlength,1024,this.maxlength),this.rtl=Kb(e.rtl,!1,this.rtl),(this.cache=n=Kb(e.cache,!0,this.cache))&&(this.F=null,this.L=typeof n==`number`?n:2e5,this.B=new Map,this.D=new Map,this.I=this.H=128),this.h=``,this.J=null,this.A=``,this.K=null,this.matcher)for(let e of this.matcher.keys())this.h+=(this.h?`|`:``)+e;if(this.stemmer)for(let e of this.stemmer.keys())this.A+=(this.A?`|`:``)+e;return this},Gb.addStemmer=function(e,t){return this.stemmer||=new Map,this.stemmer.set(e,t),this.A+=(this.A?`|`:``)+e,this.K=null,this.cache&&ex(this),this},Gb.addFilter=function(e){return typeof e==`function`?this.filter=e:(this.filter||=new Set,this.filter.add(e)),this.cache&&ex(this),this},Gb.addMapper=function(e,t){return typeof e==`object`?this.addReplacer(e,t):e.length>1?this.addMatcher(e,t):(this.mapper||=new Map,this.mapper.set(e,t),this.cache&&ex(this),this)},Gb.addMatcher=function(e,t){return typeof e==`object`?this.addReplacer(e,t):e.length<2&&(this.dedupe||this.mapper)?this.addMapper(e,t):(this.matcher||=new Map,this.matcher.set(e,t),this.h+=(this.h?`|`:``)+e,this.J=null,this.cache&&ex(this),this)},Gb.addReplacer=function(e,t){return typeof e==`string`?this.addMatcher(e,t):(this.replacer||=[],this.replacer.push(e,t),this.cache&&ex(this),this)},Gb.encode=function(e,t){if(this.cache&&e.length<=this.H){if(this.F){if(this.B.has(e))return this.B.get(e)}else this.F=setTimeout(ex,50,this)}this.normalize&&(e=typeof this.normalize==`function`?this.normalize(e):Qb?e.normalize(`NFKD`).replace(Qb,``).toLowerCase():e.toLowerCase()),this.prepare&&(e=this.prepare(e)),this.numeric&&e.length>3&&(e=e.replace(Doe,`$1 $2`).replace(Ooe,`$1 $2`).replace(Eoe,`$1 `));let n=!(this.dedupe||this.mapper||this.filter||this.matcher||this.stemmer||this.replacer),r=[],i=Jb(),a,o,s=this.split||this.split===``?e.split(this.split):[e];for(let e=0,l,u;e<s.length;e++)if((l=u=s[e])&&!(l.length<this.minlength||l.length>this.maxlength)){if(t){if(i[l])continue;i[l]=1}else{if(a===l)continue;a=l}if(n)r.push(l);else if(!this.filter||(typeof this.filter==`function`?this.filter(l):!this.filter.has(l))){if(this.cache&&l.length<=this.I){if(this.F){var c=this.D.get(l);if(c||c===``){c&&r.push(c);continue}}else this.F=setTimeout(ex,50,this)}if(this.stemmer){this.K||=RegExp(`(?!^)(`+this.A+`)$`);let e;for(;e!==l&&l.length>2;)e=l,l=l.replace(this.K,e=>this.stemmer.get(e))}if(l&&(this.mapper||this.dedupe&&l.length>1)){c=``;for(let e=0,t=``,n,r;e<l.length;e++)n=l.charAt(e),n===t&&this.dedupe||((r=this.mapper&&this.mapper.get(n))||r===``?r===t&&this.dedupe||!(t=r)||(c+=r):c+=t=n);l=c}if(this.matcher&&l.length>1&&(this.J||=RegExp(`(`+this.h+`)`,`g`),l=l.replace(this.J,e=>this.matcher.get(e))),l&&this.replacer)for(c=0;l&&c<this.replacer.length;c+=2)l=l.replace(this.replacer[c],this.replacer[c+1]);if(this.cache&&u.length<=this.I&&(this.D.set(u,l),this.D.size>this.L&&(this.D.clear(),this.I=this.I/1.1|0)),l){if(l!==u){if(t){if(i[l])continue;i[l]=1}else{if(o===l)continue;o=l}}r.push(l)}}}return this.finalize&&(r=this.finalize(r)||r),this.cache&&e.length<=this.H&&(this.B.set(e,r),this.B.size>this.L&&(this.B.clear(),this.H=this.H/1.1|0)),r};function ex(e){e.F=null,e.B.clear(),e.D.clear()}function tx(e,t,n){n||(t||typeof e!=`object`?typeof t==`object`&&(n=t,t=0):n=e),n&&(e=n.query||e,t=n.limit||t);let r=``+(t||0);n&&(r+=(n.offset||0)+!!n.context+!!n.suggest+(n.resolve!==!1)+(n.resolution||this.resolution)+(n.boost||0)),e=(``+e).toLowerCase(),this.cache||=new nx;let i=this.cache.get(e+r);if(!i){let a=n&&n.cache;a&&(n.cache=!1),i=this.search(e,t,n),a&&(n.cache=a),this.cache.set(e+r,i)}return i}function nx(e){this.limit=e&&e!==!0?e:1e3,this.cache=new Map,this.h=``}nx.prototype.set=function(e,t){this.cache.set(this.h=e,t),this.cache.size>this.limit&&this.cache.delete(this.cache.keys().next().value)},nx.prototype.get=function(e){let t=this.cache.get(e);return t&&this.h!==e&&(this.cache.delete(e),this.cache.set(this.h=e,t)),t},nx.prototype.remove=function(e){for(let t of this.cache){let n=t[0];t[1].includes(e)&&this.cache.delete(n)}},nx.prototype.clear=function(){this.cache.clear(),this.h=``};var rx={normalize:!1,numeric:!1,dedupe:!1},ix={},ax=new Map([[`b`,`p`],[`v`,`f`],[`w`,`f`],[`z`,`s`],[`x`,`s`],[`d`,`t`],[`n`,`m`],[`c`,`k`],[`g`,`k`],[`j`,`k`],[`q`,`k`],[`i`,`e`],[`y`,`e`],[`u`,`o`]]),ox=new Map([[`ae`,`a`],[`oe`,`o`],[`sh`,`s`],[`kh`,`k`],[`th`,`t`],[`ph`,`f`],[`pf`,`f`]]),sx=[/([^aeo])h(.)/g,`$1$2`,/([aeo])h([^aeo]|$)/g,`$1$2`,/(.)\1+/g,`$1`],cx={a:``,e:``,i:``,o:``,u:``,y:``,b:1,f:1,p:1,v:1,c:2,g:2,j:2,k:2,q:2,s:2,x:2,z:2,ß:2,d:3,t:3,l:4,m:5,n:5,r:6},lx={Exact:rx,Default:ix,Normalize:ix,LatinBalance:{mapper:ax},LatinAdvanced:{mapper:ax,matcher:ox,replacer:sx},LatinExtra:{mapper:ax,replacer:sx.concat([/(?!^)[aeo]/g,``]),matcher:ox},LatinSoundex:{dedupe:!1,include:{letter:!0},finalize:function(e){for(let n=0;n<e.length;n++){var t=e[n];let r=t.charAt(0),i=cx[r];for(let e=1,n;e<t.length&&(n=t.charAt(e),n===`h`||n===`w`||!(n=cx[n])||n===i||(r+=n,i=n,r.length!==4));e++);e[n]=r}}},CJK:{split:``},LatinExact:rx,LatinDefault:ix,LatinSimple:ix};function ux(e,t,n,r){let i=[];for(let a=0,o;a<e.index.length;a++)if(o=e.index[a],t>=o.length)t-=o.length;else{t=o[r?`splice`:`slice`](t,n);let a=t.length;if(a&&(i=i.length?i.concat(t):t,n-=a,r&&(e.length-=a),!n))break;t=0}return i}function dx(e){if(!this||this.constructor!==dx)return new dx(e);this.index=e?[e]:[],this.length=e?e.length:0;let t=this;return new Proxy([],{get(e,n){if(n===`length`)return t.length;if(n===`push`)return function(e){t.index[t.index.length-1].push(e),t.length++};if(n===`pop`)return function(){if(t.length)return t.length--,t.index[t.index.length-1].pop()};if(n===`indexOf`)return function(e){let n=0;for(let r=0,i,a;r<t.index.length;r++){if(i=t.index[r],a=i.indexOf(e),a>=0)return n+a;n+=i.length}return-1};if(n===`includes`)return function(e){for(let n=0;n<t.index.length;n++)if(t.index[n].includes(e))return!0;return!1};if(n===`slice`)return function(e,n){return ux(t,e||0,n||t.length,!1)};if(n===`splice`)return function(e,n){return ux(t,e||0,n||t.length,!0)};if(n===`constructor`)return Array;if(typeof n!=`symbol`)return(e=t.index[n/2**31|0])&&e[n]},set(e,n,r){return e=n/2**31|0,(t.index[e]||(t.index[e]=[]))[n]=r,t.length++,!0}})}dx.prototype.clear=function(){this.index.length=0},dx.prototype.push=function(){};function fx(e=8){if(!this||this.constructor!==fx)return new fx(e);this.index=Jb(),this.h=[],this.size=0,e>32?(this.B=hx,this.A=BigInt(e)):(this.B=mx,this.A=e)}fx.prototype.get=function(e){let t=this.index[this.B(e)];return t&&t.get(e)},fx.prototype.set=function(e,t){var n=this.B(e);let r=this.index[n];r?(n=r.size,r.set(e,t),(n-=r.size)&&this.size++):(this.index[n]=r=new Map([[e,t]]),this.h.push(r),this.size++)};function px(e=8){if(!this||this.constructor!==px)return new px(e);this.index=Jb(),this.h=[],this.size=0,e>32?(this.B=hx,this.A=BigInt(e)):(this.B=mx,this.A=e)}px.prototype.add=function(e){var t=this.B(e);let n=this.index[t];n?(t=n.size,n.add(e),(t-=n.size)&&this.size++):(this.index[t]=n=new Set([e]),this.h.push(n),this.size++)},Gb=fx.prototype,Gb.has=px.prototype.has=function(e){let t=this.index[this.B(e)];return t&&t.has(e)},Gb.delete=px.prototype.delete=function(e){let t=this.index[this.B(e)];t&&t.delete(e)&&this.size--},Gb.clear=px.prototype.clear=function(){this.index=Jb(),this.h=[],this.size=0},Gb.values=px.prototype.values=function*(){for(let e=0;e<this.h.length;e++)for(let t of this.h[e].values())yield t},Gb.keys=px.prototype.keys=function*(){for(let e=0;e<this.h.length;e++)for(let t of this.h[e].keys())yield t},Gb.entries=px.prototype.entries=function*(){for(let e=0;e<this.h.length;e++)for(let t of this.h[e].entries())yield t};function mx(e){let t=2**this.A-1;if(typeof e==`number`)return e&t;let n=0,r=this.A+1;for(let i=0;i<e.length;i++)n=(n*r^e.charCodeAt(i))&t;return this.A===32?n+2**31:n}function hx(e){let t=BigInt(2)**this.A-BigInt(1);var n=typeof e;if(n===`bigint`)return e&t;if(n===`number`)return BigInt(e)&t;n=BigInt(0);let r=this.A+BigInt(1);for(let i=0;i<e.length;i++)n=(n*r^BigInt(e.charCodeAt(i)))&t;return n}var gx,_x;async function koe(e){e=e.data;var t=e.task;let n=e.id,r=e.args;switch(t){case`init`:_x=e.options||{},(t=e.factory)?(Function(`return `+t)()(self),gx=new self.FlexSearch.Index(_x),delete self.FlexSearch):gx=new tS(_x),postMessage({id:n});break;default:let i;t===`export`&&(r[1]?(r[0]=_x.export,r[2]=0,r[3]=1):r=null),t===`import`?r[0]&&(e=await _x.import.call(gx,r[0]),gx.import(r[0],e)):((i=r&&gx[t].apply(gx,r))&&i.then&&(i=await i),i&&i.await&&(i=await i.await),t===`search`&&i.result&&(i=i.result)),postMessage(t===`search`?{id:n,msg:i}:{id:n})}}function vx(e){Sx.call(e,`add`),Sx.call(e,`append`),Sx.call(e,`search`),Sx.call(e,`update`),Sx.call(e,`remove`),Sx.call(e,`searchCache`)}var yx,bx,xx;function Aoe(){yx=xx=0}function Sx(e){this[e+`Async`]=function(){let t=arguments;var n=t[t.length-1];let r;if(typeof n==`function`&&(r=n,delete t[t.length-1]),yx?xx||=Date.now()-bx>=this.priority*this.priority*3:(yx=setTimeout(Aoe,0),bx=Date.now()),xx){let n=this;return new Promise(r=>{setTimeout(function(){r(n[e+`Async`].apply(n,t))},0)})}let i=this[e].apply(this,t);return n=i.then?i:new Promise(e=>e(i)),r&&n.then(r),n}}var Cx=0;function wx(e={},t){function n(n){function o(e){e=e.data||e;let t=e.id,n=t&&a.h[t];n&&(n(e.msg),delete a.h[t])}if(this.worker=n,this.h=Jb(),this.worker)return i?this.worker.on(`message`,o):this.worker.onmessage=o,e.config?new Promise(function(t){Cx>1e9&&(Cx=0),a.h[++Cx]=function(){t(a)},a.worker.postMessage({id:Cx,task:`init`,factory:r,options:e})}):(this.priority=e.priority||4,this.encoder=t||null,this.worker.postMessage({task:`init`,factory:r,options:e}),this)}if(!this||this.constructor!==wx)return new wx(e);let r=typeof self<`u`?self._factory:typeof window<`u`?window._factory:null;r&&=r.toString();let i=typeof window>`u`,a=this,o=joe(r,i,e.worker);return o.then?o.then(function(e){return n.call(a,e)}):n.call(this,o)}Tx(`add`),Tx(`append`),Tx(`search`),Tx(`update`),Tx(`remove`),Tx(`clear`),Tx(`export`),Tx(`import`),wx.prototype.searchCache=tx,vx(wx.prototype);function Tx(e){wx.prototype[e]=function(){let t=this,n=[].slice.call(arguments);var r=n[n.length-1];let i;return typeof r==`function`&&(i=r,n.pop()),r=new Promise(function(r){e===`export`&&typeof n[0]==`function`&&(n[0]=null),Cx>1e9&&(Cx=0),t.h[++Cx]=r,t.worker.postMessage({task:e,id:Cx,args:n})}),i?(r.then(i),this):r}}function joe(e,t,n){return t?typeof module<`u`?new(Wb()).Worker(__dirname+`/worker/node.js`):woe(()=>Promise.resolve().then(()=>u(Wb(),1)).then(function(e){return new e.Worker(import.meta.dirname+`/node/node.mjs`)}),void 0):e?new window.Worker(URL.createObjectURL(new Blob([`onmessage=`+koe.toString()],{type:`text/javascript`}))):new window.Worker(typeof n==`string`?n:import.meta.url.replace(`/worker.js`,`/worker/worker.js`).replace(`flexsearch.bundle.module.min.js`,`module/worker/worker.js`).replace(`flexsearch.bundle.module.min.mjs`,`module/worker/worker.js`),{type:`module`})}Rx.prototype.add=function(e,t,n){if(Xb(e)&&(t=e,e=Zb(t,this.key)),t&&(e||e===0)){if(!n&&this.reg.has(e))return this.update(e,t);for(let a=0,o;a<this.field.length;a++){o=this.B[a];var r=this.index.get(this.field[a]);if(typeof o==`function`){var i=o(t);i&&r.add(e,i,n,!0)}else i=o.G,(!i||i(t))&&(o.constructor===String?o=[``+o]:Yb(o)&&(o=[o]),Dx(t,o,this.D,0,r,e,o[0],n))}if(this.tag)for(r=0;r<this.A.length;r++){var a=this.A[r];i=this.tag.get(this.F[r]);let s=Jb();if(typeof a==`function`){if(a=a(t),!a)continue}else{var o=a.G;if(o&&!o(t))continue;a.constructor===String&&(a=``+a),a=Zb(t,a)}if(i&&a){Yb(a)&&(a=[a]);for(let t=0,r,c;t<a.length;t++)if(r=a[t],!s[r]&&(s[r]=1,(o=i.get(r))?c=o:i.set(r,c=[]),!n||!c.includes(e))){if(c.length===2**31-1){if(o=new dx(c),this.fastupdate)for(let e of this.reg.values())e.includes(c)&&(e[e.indexOf(c)]=o);i.set(r,c=o)}c.push(e),this.fastupdate&&((o=this.reg.get(e))?o.push(c):this.reg.set(e,[c]))}}}if(this.store&&(!n||!this.store.has(e))){let r;if(this.h){r=Jb();for(let e=0,i;e<this.h.length;e++){if(i=this.h[e],(n=i.G)&&!n(t))continue;let a;if(typeof i==`function`){if(a=i(t),!a)continue;i=[i.O]}else if(Yb(i)||i.constructor===String){r[i]=t[i];continue}Ex(t,r,i,0,i[0],a)}}this.store.set(e,r||t)}this.worker&&(this.fastupdate||this.reg.add(e))}return this};function Ex(e,t,n,r,i,a){if(e=e[i],r===n.length-1)t[i]=a||e;else if(e){if(e.constructor===Array)for(t=t[i]=Array(e.length),i=0;i<e.length;i++)Ex(e,t,n,r,i);else t=t[i]||(t[i]=Jb()),i=n[++r],Ex(e,t,n,r,i)}}function Dx(e,t,n,r,i,a,o,s){if(e=e[o]){if(r===t.length-1){if(e.constructor===Array){if(n[r]){for(t=0;t<e.length;t++)i.add(a,e[t],!0,!0);return}e=e.join(` `)}i.add(a,e,s,!0)}else if(e.constructor===Array)for(o=0;o<e.length;o++)Dx(e,t,n,r,i,a,o,s);else o=t[++r],Dx(e,t,n,r,i,a,o,s)}}function Ox(e,t,n,r){if(!e.length)return e;if(e.length===1)return e=e[0],e=n||e.length>t?e.slice(n,n+t):e,r?Lx.call(this,e):e;let i=[];for(let a=0,o,s;a<e.length;a++)if((o=e[a])&&(s=o.length)){if(n){if(n>=s){n-=s;continue}o=o.slice(n,n+t),s=o.length,n=0}if(s>t&&(o=o.slice(0,t),s=t),!i.length&&s>=t)return r?Lx.call(this,o):o;if(i.push(o),t-=s,!t)break}return i=i.length>1?[].concat.apply([],i):i[0],r?Lx.call(this,i):i}function kx(e,t,n,r){var i=r[0];if(i[0]&&i[0].query)return e[t].apply(e,i);if(!(t!==`and`&&t!==`not`||e.result.length||e.await||i.suggest))return r.length>1&&(i=r[r.length-1]),(r=i.resolve)?e.await||e.result:e;let a=[],o=0,s=0,c,l,u,d,f;for(t=0;t<r.length;t++)if(i=r[t]){var p=void 0;if(i.constructor===Mx)p=i.await||i.result;else if(i.then||i.constructor===Array)p=i;else{o=i.limit||0,s=i.offset||0,u=i.suggest,l=i.resolve,c=((d=i.highlight||e.highlight)||i.enrich)&&l,p=i.queue;let n=i.async||p,r=i.index,m=i.query;if(r?e.index||=r:r=e.index,m||i.tag){let o=i.field||i.pluck;if(o&&(!m||e.query&&!d||(e.query=m,e.field=o,e.highlight=d),r=r.index.get(o)),p&&(f||e.await)){f=1;let o,s=e.C.length,c=new Promise(function(e){o=e});(function(t,r){c.h=function(){r.index=null,r.resolve=!1;let i=n?t.searchAsync(r):t.search(r);return i.then?i.then(function(t){return e.C[s]=t=t.result||t,o(t),t}):(i=i.result||i,o(i),i)}})(r,Object.assign({},i)),e.C.push(c),a[t]=c;continue}i.resolve=!1,i.index=null,p=n?r.searchAsync(i):r.search(i),i.resolve=l,i.index=r}else if(i.and)p=Ax(i,`and`,r);else if(i.or)p=Ax(i,`or`,r);else if(i.not)p=Ax(i,`not`,r);else if(i.xor)p=Ax(i,`xor`,r);else continue}p.await?(f=1,p=p.await):p.then?(f=1,p=p.then(function(e){return e.result||e})):p=p.result||p,a[t]=p}if(f&&!e.await&&(e.await=new Promise(function(t){e.return=t})),f){let t=Promise.all(a).then(function(r){for(let i=0;i<e.C.length;i++)if(e.C[i]===t){e.C[i]=function(){return n.call(e,r,o,s,c,l,u,d)};break}Nx(e)});e.C.push(t)}else if(e.await)e.C.push(function(){return n.call(e,a,o,s,c,l,u,d)});else return n.call(e,a,o,s,c,l,u,d);return l?e.await||e.result:e}function Ax(e,t,n){e=e[t];let r=e[0]||e;return r.index||=n,n=new Mx(r),e.length>1&&(n=n[t].apply(n,e.slice(1))),n}Mx.prototype.or=function(){return kx(this,`or`,Moe,arguments)};function Moe(e,t,n,r,i,a,o){return e.length&&(this.result.length&&e.push(this.result),e.length<2?this.result=e[0]:(this.result=Fx(e,t,n,!1,this.h),n=0)),i&&(this.await=null),i?this.resolve(t,n,r,o):this}Mx.prototype.and=function(){return kx(this,`and`,Noe,arguments)};function Noe(e,t,n,r,i,a,o){if(!a&&!this.result.length)return i?this.result:this;let s;if(e.length){if(this.result.length&&e.unshift(this.result),e.length<2)this.result=e[0];else{let r=0;for(let t=0,n,i;t<e.length;t++)if((n=e[t])&&(i=n.length))r<i&&(r=i);else if(!a){r=0;break}r?(this.result=Px(e,r,t,n,a,this.h,i),s=!0):this.result=[]}}else a||(this.result=e);return i&&(this.await=null),i?this.resolve(t,n,r,o,s):this}Mx.prototype.xor=function(){return kx(this,`xor`,Poe,arguments)};function Poe(e,t,n,r,i,a,o){if(e.length){if(this.result.length&&e.unshift(this.result),e.length<2)this.result=e[0];else{a:{a=n;var s=this.h;let r=[],o=Jb(),c=0;for(let t=0,n;t<e.length;t++)if(n=e[t]){c<n.length&&(c=n.length);for(let e=0,t;e<n.length;e++)if(t=n[e])for(let e=0,n;e<t.length;e++)n=t[e],o[n]=o[n]?2:1}for(let n=0,l,u=0;n<c;n++)for(let c=0,d;c<e.length;c++)if((d=e[c])&&(l=d[n])){for(let d=0,f;d<l.length;d++)if(f=l[d],o[f]===1){if(a)a--;else if(i){if(r.push(f),r.length===t){e=r;break a}}else{let i=n+(c?s:0);if(r[i]||(r[i]=[]),r[i].push(f),++u===t){e=r;break a}}}}e=r}this.result=e,s=!0}}else a||(this.result=e);return i&&(this.await=null),i?this.resolve(t,n,r,o,s):this}Mx.prototype.not=function(){return kx(this,`not`,Foe,arguments)};function Foe(e,t,n,r,i,a,o){if(!a&&!this.result.length)return i?this.result:this;if(e.length&&this.result.length){a:{a=n;var s=[];e=new Set(e.flat().flat());for(let n=0,r,o=0;n<this.result.length;n++)if(r=this.result[n]){for(let c=0,l;c<r.length;c++)if(l=r[c],!e.has(l)){if(a)a--;else if(i){if(s.push(l),s.length===t){e=s;break a}}else if(s[n]||(s[n]=[]),s[n].push(l),++o===t){e=s;break a}}}e=s}this.result=e,s=!0}return i&&(this.await=null),i?this.resolve(t,n,r,o,s):this}function jx(e,t,n,r,i){let a,o,s;typeof i==`string`?(a=i,i=``):a=i.template,o=a.indexOf(`$1`),s=a.substring(o+2),o=a.substring(0,o);let c=i&&i.boundary,l=!i||i.clip!==!1,u=i&&i.merge&&s&&o&&RegExp(s+` `+o,`g`);i&&=i.ellipsis;var d=0;if(typeof i==`object`){var f=i.template;d=f.length-2,i=i.pattern}typeof i!=`string`&&(i=i===!1?``:`...`),d&&(i=f.replace(`$1`,i)),f=i.length-d;let p,m;typeof c==`object`&&(p=c.before,p===0&&(p=-1),m=c.after,m===0&&(m=-1),c=c.total||9e5),d=new Map;for(let N=0,P,F,I;N<t.length;N++){let L;if(r)L=t,I=r;else{var h=t[N];if(I=h.field,!I)continue;L=h.result}F=n.get(I),P=F.encoder,h=d.get(P),typeof h!=`string`&&(h=P.encode(e),d.set(P,h));for(let e=0;e<L.length;e++){var g=L[e].doc;if(!g||(g=Zb(g,I),!g))continue;var _=g.trim().split(/\s+/);if(!_.length)continue;g=``;var v=[];let t=[];for(var y=-1,b=-1,x=0,S=0;S<_.length;S++){var C=_[S],w=P.encode(C);w=w.length>1?w.join(` `):w[0];let e;if(w&&C){for(var T=C.length,E=(P.split?C.replace(P.split,``):C).length-w.length,D=``,O=0,k=0;k<h.length;k++){var A=h[k];if(A){var j=A.length;j+=E<0?0:E,O&&j<=O||(A=w.indexOf(A),A>-1&&(D=(A?C.substring(0,A):``)+o+C.substring(A,A+j)+s+(A+j<T?C.substring(A+j):``),O=j,e=!0))}}D&&(c&&(y<0&&(y=g.length+ +!!g),b=g.length+ +!!g+D.length,x+=T,t.push(v.length),v.push({match:D})),g+=(g?` `:``)+D)}if(!e)C=_[S],g+=(g?` `:``)+C,c&&v.push({text:C});else if(c&&x>=c)break}if(x=t.length*(a.length-2),p||m||c&&g.length-x>c){if(x=c+x-f*2,S=b-y,p>0&&(S+=p),m>0&&(S+=m),S<=x)_=p?y-(p>0?p:0):y-((x-S)/2|0),v=m?b+(m>0?m:0):_+x,l||(_>0&&g.charAt(_)!==` `&&g.charAt(_-1)!==` `&&(_=g.indexOf(` `,_),_<0&&(_=0)),v<g.length&&g.charAt(v-1)!==` `&&g.charAt(v)!==` `&&(v=g.lastIndexOf(` `,v),v<b?v=b:++v)),g=(_?i:``)+g.substring(_,v)+(v<g.length?i:``);else{for(b=[],y={},x={},S={},C={},w={},D=E=T=0,k=O=1;;){var M=void 0;for(let e=0,n;e<t.length;e++){if(n=t[e],D){if(E!==D){if(S[e+1])continue;if(n+=D,y[n]){T-=f,x[e+1]=1,S[e+1]=1;continue}if(n>=v.length-1){if(n>=v.length){S[e+1]=1,n>=_.length&&(x[e+1]=1);continue}T-=f}if(g=v[n].text,j=m&&w[e]){if(j>0){if(g.length>j){if(S[e+1]=1,l)g=g.substring(0,j);else continue}(j-=g.length)||(j=-1),w[e]=j}else{S[e+1]=1;continue}}if(T+g.length+1<=c)g=` `+g,b[e]+=g;else if(l)M=c-T-1,M>0&&(g=` `+g.substring(0,M),b[e]+=g),S[e+1]=1;else{S[e+1]=1;continue}}else{if(S[e])continue;if(n-=E,y[n]){T-=f,S[e]=1,x[e]=1;continue}if(n<=0){if(n<0){S[e]=1,x[e]=1;continue}T-=f}if(g=v[n].text,j=p&&C[e]){if(j>0){if(g.length>j){if(S[e]=1,l)g=g.substring(g.length-j);else continue}(j-=g.length)||(j=-1),C[e]=j}else{S[e]=1;continue}}if(T+g.length+1<=c)g+=` `,b[e]=g+b[e];else if(l)M=g.length+1-(c-T),M>=0&&M<g.length&&(g=g.substring(M)+` `,b[e]=g+b[e]),S[e]=1;else{S[e]=1;continue}}}else{g=v[n].match,p&&(C[e]=p),m&&(w[e]=m),e&&T++;let t;if(n?!e&&f&&(T+=f):(x[e]=1,S[e]=1),n>=_.length-1||n<v.length-1&&v[n+1].match?t=1:f&&(T+=f),T-=a.length-2,!e||T+g.length<=c)b[e]=g;else{M=O=k=x[e]=0;break}t&&(x[e+1]=1,S[e+1]=1)}T+=g.length,M=y[n]=1}if(M)E===D?D++:E++;else{if(E===D?O=0:k=0,!O&&!k)break;O?(E++,D=E):D++}}g=``;for(let e=0,t;e<b.length;e++)t=(x[e]?e?` `:``:(e&&!i?` `:``)+i)+b[e],g+=t;i&&!x[b.length]&&(g+=i)}}u&&(g=g.replace(u,` `)),L[e].highlight=g}if(r)break}return t}function Mx(e,t){if(!this||this.constructor!==Mx)return new Mx(e,t);let n=0,r,i,a,o,s,c;if(e&&e.index){let r=e;if(t=r.index,n=r.boost||0,i=r.query){a=r.field||r.pluck,o=r.highlight;let n=r.resolve;e=r.async||r.queue,r.resolve=!1,r.index=null,e=e?t.searchAsync(r):t.search(r),r.resolve=n,r.index=t,e=e.result||e}else e=[]}if(e&&e.then){let t=this;e=e.then(function(e){t.C[0]=t.result=e.result||e,Nx(t)}),r=[e],e=[],s=new Promise(function(e){c=e})}this.index=t||null,this.result=e||[],this.h=n,this.C=r||[],this.await=s||null,this.return=c||null,this.highlight=o||null,this.query=i||``,this.field=a||``}Gb=Mx.prototype,Gb.limit=function(e){if(this.await){let t=this;this.C.push(function(){return t.limit(e).result})}else if(this.result.length){let t=[];for(let n=0,r;n<this.result.length;n++)if(r=this.result[n]){if(r.length<=e){if(t[n]=r,e-=r.length,!e)break}else{t[n]=r.slice(0,e);break}}this.result=t}return this},Gb.offset=function(e){if(this.await){let t=this;this.C.push(function(){return t.offset(e).result})}else if(this.result.length){let t=[];for(let n=0,r;n<this.result.length;n++)(r=this.result[n])&&(r.length<=e?e-=r.length:(t[n]=r.slice(e),e=0));this.result=t}return this},Gb.boost=function(e){if(this.await){let t=this;this.C.push(function(){return t.boost(e).result})}else this.h+=e;return this};function Nx(e,t){let n=e.result;var r=e.await;e.await=null;for(let t=0,i;t<e.C.length;t++)if(i=e.C[t]){if(typeof i==`function`)n=i(),e.C[t]=n=n.result||n,t--;else if(i.h)n=i.h(),e.C[t]=n=n.result||n,t--;else if(i.then)return e.await=r}return r=e.return,e.C=[],e.return=null,t||r(n),n}Gb.resolve=function(e,t,n,r,i){let a=this.await?Nx(this,!0):this.result;if(a.then){let o=this;return a.then(function(){return o.resolve(e,t,n,r,i)})}return a.length&&(typeof e==`object`?(r=e.highlight||this.highlight,n=!!r||e.enrich,t=e.offset,e=e.limit):(r||=this.highlight,n=!!r||n),a=i?n?Lx.call(this.index,a):a:Ox.call(this.index,a,e||100,t,n)),this.finalize(a,r)},Gb.finalize=function(e,t){if(e.then){let n=this;return e.then(function(e){return n.finalize(e,t)})}t&&e.length&&this.query&&(e=jx(this.query,e,this.index.index,this.field,t));let n=this.return;return this.highlight=this.index=this.result=this.C=this.await=this.return=null,this.query=this.field=``,n&&n(e),e};function Px(e,t,n,r,i,a,o){let s=e.length,c=[],l,u;l=Jb();for(let d=0,f,p,m,h;d<t;d++)for(let t=0;t<s;t++)if(m=e[t],d<m.length&&(f=m[d]))for(let e=0;e<f.length;e++){if(p=f[e],(u=l[p])?l[p]++:(u=0,l[p]=1),h=c[u]||(c[u]=[]),!o){let e=d+(t||!i?0:a||0);h=h[e]||(h[e]=[])}if(h.push(p),o&&n&&u===s-1&&h.length-r===n)return r?h.slice(r):h}if(e=c.length){if(i)c=c.length>1?Fx(c,n,r,o,a):(c=c[0])&&n&&c.length>n||r?c.slice(r,n+r):c;else{if(e<s)return[];if(c=c[e-1],n||r){if(o)(c.length>n||r)&&(c=c.slice(r,n+r));else{i=[];for(let e=0,t;e<c.length;e++)if(t=c[e]){if(r&&t.length>r)r-=t.length;else if((n&&t.length>n||r)&&(t=t.slice(r,n+r),n-=t.length,r&&(r-=t.length)),i.push(t),!n)break}c=i}}}}return c}function Fx(e,t,n,r,i){let a=[],o=Jb(),s;var c=e.length;let l;if(r){for(i=c-1;i>=0;i--)if(l=(r=e[i])&&r.length){for(c=0;c<l;c++)if(s=r[c],!o[s]){if(o[s]=1,n)n--;else if(a.push(s),a.length===t)return a}}}else for(let u=c-1,d,f=0;u>=0;u--){d=e[u];for(let e=0;e<d.length;e++)if(l=(r=d[e])&&r.length){for(let d=0;d<l;d++)if(s=r[d],!o[s]){if(o[s]=1,n)n--;else{let n=(e+(u<c-1&&i||0))/(u+1)|0;if((a[n]||(a[n]=[])).push(s),++f===t)return a}}}}return a}function Ioe(e,t,n,r,i){let a=Jb(),o=[];for(let e=0,n;e<t.length;e++){n=t[e];for(let e=0;e<n.length;e++)a[n[e]]=1}if(i){for(let t=0,i;t<e.length;t++)if(i=e[t],a[i]){if(r)r--;else if(o.push(i),a[i]=0,n&&--n===0)break}}else for(let n=0,r,i;n<e.result.length;n++)for(r=e.result[n],t=0;t<r.length;t++)i=r[t],a[i]&&((o[n]||(o[n]=[])).push(i),a[i]=0);return o}Rx.prototype.search=function(e,t,n,r){n||(!t&&Xb(e)?(n=e,e=``):Xb(t)&&(n=t,t=0));let i=[];var a=[];let o,s,c,l,u,d,f=0,p=!0,m;if(n){n.constructor===Array&&(n={index:n}),e=n.query||e,o=n.pluck,s=n.merge,l=n.boost,d=o||n.field||(d=n.index)&&(d.index?null:d);var h=this.tag&&n.tag;c=n.suggest,p=n.resolve!==!1,u=n.cache,m=p&&this.store&&n.highlight;var g=!!m||p&&this.store&&n.enrich;t=n.limit||t;var _=n.offset||0;if(t||=p?100:0,h&&(!this.db||!r)){h.constructor!==Array&&(h=[h]);var v=[];for(let e=0,t;e<h.length;e++)if(t=h[e],t.field&&t.tag){var y=t.tag;if(y.constructor===Array)for(var b=0;b<y.length;b++)v.push(t.field,y[b]);else v.push(t.field,y)}else{y=Object.keys(t);for(let e=0,n,r;e<y.length;e++)if(n=y[e],r=t[n],r.constructor===Array)for(b=0;b<r.length;b++)v.push(n,r[b]);else v.push(n,r)}if(h=v,!e){if(a=[],v.length)for(h=0;h<v.length;h+=2){if(this.db){if(r=this.index.get(v[h]),!r)continue;a.push(r=r.db.tag(v[h+1],t,_,g))}else r=Loe.call(this,v[h],v[h+1],t,_,g);i.push(p?{field:v[h],tag:v[h+1],result:r}:[r])}if(a.length){let e=this;return Promise.all(a).then(function(t){for(let e=0;e<t.length;e++)p?i[e].result=t[e]:i[e]=t[e];return p?i:new Mx(i.length>1?Px(i,1,0,0,c,l):i[0],e)})}return p?i:new Mx(i.length>1?Px(i,1,0,0,c,l):i[0],this)}}p||o||!(d||=this.field)||(Yb(d)?o=d:(d.constructor===Array&&d.length===1&&(d=d[0]),o=d.field||d.index)),d&&d.constructor!==Array&&(d=[d])}d||=this.field;let x;v=(this.worker||this.db)&&!r&&[];for(let o=0,s,l,C;o<d.length;o++){if(l=d[o],this.db&&this.tag&&!this.B[o])continue;let w;if(Yb(l)||(w=l,l=w.field,e=w.query||e,t=qb(w.limit,t),_=qb(w.offset,_),c=qb(w.suggest,c),m=p&&this.store&&qb(w.highlight,m),g=!!m||p&&this.store&&qb(w.enrich,g),u=qb(w.cache,u)),r)s=r[o];else{y=w||n||{},b=y.enrich;var S=this.index.get(l);if(h&&(this.db&&(y.tag=h,y.field=d,x=S.db.support_tag_search),!x&&b&&(y.enrich=!1),x||(y.limit=0,y.offset=0)),s=u?S.searchCache(e,h&&!x?0:t,y):S.search(e,h&&!x?0:t,y),h&&!x&&(y.limit=t,y.offset=_),b&&(y.enrich=b),v){v[o]=s;continue}}if(C=(s=s.result||s)&&s.length,h&&C){if(y=[],b=0,this.db&&r){if(!x)for(S=d.length;S<r.length;S++){let e=r[S];if(e&&e.length)b++,y.push(e);else if(!c)return p?i:new Mx(i,this)}}else for(let e=0,t,n;e<h.length;e+=2){if(t=this.tag.get(h[e]),!t){if(c)continue;return p?i:new Mx(i,this)}if((t&&=t.get(h[e+1]))&&t.length)b++,y.push(t);else if(!c)return p?i:new Mx(i,this)}if(b){if(s=Ioe(s,y,t,_,p),C=s.length,!C&&!c)return p?s:new Mx(s,this);b--}}if(C)a[f]=l,i.push(s),f++;else if(d.length===1)return p?i:new Mx(i,this)}if(v){if(this.db&&h&&h.length&&!x)for(g=0;g<h.length;g+=2){if(a=this.index.get(h[g]),!a){if(c)continue;return p?i:new Mx(i,this)}v.push(a.db.tag(h[g+1],t,_,!1))}let r=this;return Promise.all(v).then(function(i){return n&&(n.resolve=p),i.length&&(i=r.search(e,t,n,i)),i})}if(!f)return p?i:new Mx(i,this);if(o&&(!g||!this.store))return i=i[0],p?i:new Mx(i,this);for(v=[],_=0;_<a.length;_++){if(h=i[_],g&&h.length&&h[0].doc===void 0&&(this.db?v.push(h=this.index.get(this.field[0]).db.enrich(h)):h=Lx.call(this,h)),o)return p?m?jx(e,h,this.index,o,m):h:new Mx(h,this);i[_]={field:a[_],result:h}}if(g&&this.db&&v.length){let t=this;return Promise.all(v).then(function(n){for(let e=0;e<n.length;e++)i[e].result=n[e];return m&&(i=jx(e,i,t.index,o,m)),s?Ix(i):i})}return m&&(i=jx(e,i,this.index,o,m)),s?Ix(i):i};function Ix(e){let t=[],n=Jb(),r=Jb();for(let i=0,a,o,s,c,l,u,d;i<e.length;i++){a=e[i],o=a.field,s=a.result;for(let e=0;e<s.length;e++)l=s[e],typeof l==`object`?c=l.id:l={id:c=l},(u=n[c])?u.push(o):(l.field=n[c]=[o],t.push(l)),(d=l.highlight)&&(u=r[c],u||(r[c]=u={},l.highlight=u),u[o]=d)}return t}function Loe(e,t,n,r,i){return e=this.tag.get(e),!e||(e=e.get(t),!e)?[]:(t=e.length-r,t>0&&((n&&t>n||r)&&(e=e.slice(r,r+n)),i&&(e=Lx.call(this,e))),e)}function Lx(e){if(!this||!this.store)return e;if(this.db)return this.index.get(this.field[0]).db.enrich(e);let t=Array(e.length);for(let n=0,r;n<e.length;n++)r=e[n],t[n]={id:r,doc:this.store.get(r)};return t}function Rx(e){if(!this||this.constructor!==Rx)return new Rx(e);let t=e.document||e.doc||e,n,r;if(this.B=[],this.field=[],this.D=[],this.key=(n=t.key||t.id)&&zx(n,this.D)||`id`,(r=e.keystore||0)&&(this.keystore=r),this.fastupdate=!!e.fastupdate,this.reg=!this.fastupdate||e.worker||e.db?r?new px(r):new Set:r?new fx(r):new Map,this.h=(n=t.store||null)&&n&&n!==!0&&[],this.store=n?r?new fx(r):new Map:null,this.cache=(n=e.cache||null)&&new nx(n),e.cache=!1,this.worker=e.worker||!1,this.priority=e.priority||4,this.index=Roe.call(this,e,t),this.tag=null,(n=t.tag)&&(typeof n==`string`&&(n=[n]),n.length)){this.tag=new Map,this.A=[],this.F=[];for(let e=0,t,r;e<n.length;e++){if(t=n[e],r=t.field||t,!r)throw Error(`The tag field from the document descriptor is undefined.`);t.custom?this.A[e]=t.custom:(this.A[e]=zx(r,this.D),t.filter&&(typeof this.A[e]==`string`&&(this.A[e]=new String(this.A[e])),this.A[e].G=t.filter)),this.F[e]=r,this.tag.set(r,new Map)}}if(this.worker){this.fastupdate=!1,e=[];for(let t of this.index.values())t.then&&e.push(t);if(e.length){let t=this;return Promise.all(e).then(function(e){let n=0;for(let r of t.index.entries()){let i=r[0],a=r[1];a.then&&(a=e[n],t.index.set(i,a),n++)}return t})}}else e.db&&(this.fastupdate=!1,this.mount(e.db))}Gb=Rx.prototype,Gb.mount=function(e){let t=this.field;if(this.tag)for(let e=0,r;e<this.F.length;e++){r=this.F[e];var n=void 0;this.index.set(r,n=new tS({},this.reg)),t===this.field&&(t=t.slice(0)),t.push(r),n.tag=this.tag.get(r)}n=[];let r={db:e.db,type:e.type,fastupdate:e.fastupdate};for(let i=0,a,o;i<t.length;i++){r.field=o=t[i],a=this.index.get(o);let s=new e.constructor(e.id,r);s.id=e.id,n[i]=s.mount(a),a.document=!0,i?a.bypass=!0:a.store=this.store}let i=this;return this.db=Promise.all(n).then(function(){i.db=!0})},Gb.commit=async function(){let e=[];for(let t of this.index.values())e.push(t.commit());await Promise.all(e),this.reg.clear()},Gb.destroy=function(){let e=[];for(let t of this.index.values())e.push(t.destroy());return Promise.all(e)};function Roe(e,t){let n=new Map,r=t.index||t.field||t;Yb(r)&&(r=[r]);for(let t=0,a,o;t<r.length;t++){if(a=r[t],Yb(a)||(o=a,a=a.field),o=Xb(o)?Object.assign({},e,o):e,this.worker){var i=void 0;i=(i=o.encoder)&&i.encode?i:new $b(typeof i==`string`?lx[i]:i||{}),i=new wx(o,i),n.set(a,i)}this.worker||n.set(a,new tS(o,this.reg)),o.custom?this.B[t]=o.custom:(this.B[t]=zx(a,this.D),o.filter&&(typeof this.B[t]==`string`&&(this.B[t]=new String(this.B[t])),this.B[t].G=o.filter)),this.field[t]=a}if(this.h){e=t.store,Yb(e)&&(e=[e]);for(let t=0,n,r;t<e.length;t++)n=e[t],r=n.field||n,n.custom?(this.h[t]=n.custom,n.custom.O=r):(this.h[t]=zx(r,this.D),n.filter&&(typeof this.h[t]==`string`&&(this.h[t]=new String(this.h[t])),this.h[t].G=n.filter))}return n}function zx(e,t){let n=e.split(`:`),r=0;for(let i=0;i<n.length;i++)e=n[i],e[e.length-1]===`]`&&(e=e.substring(0,e.length-2))&&(t[r]=!0),e&&(n[r++]=e);return r<n.length&&(n.length=r),r>1?n:n[0]}Gb.append=function(e,t){return this.add(e,t,!0)},Gb.update=function(e,t){return this.remove(e).add(e,t)},Gb.remove=function(e){Xb(e)&&(e=Zb(e,this.key));for(var t of this.index.values())t.remove(e,!0);if(this.reg.has(e)){if(this.tag&&!this.fastupdate)for(let n of this.tag.values())for(let r of n){t=r[0];let i=r[1],a=i.indexOf(e);a>-1&&(i.length>1?i.splice(a,1):n.delete(t))}this.store&&this.store.delete(e),this.reg.delete(e)}return this.cache&&this.cache.remove(e),this},Gb.clear=function(){let e=[];for(let t of this.index.values()){let n=t.clear();n.then&&e.push(n)}if(this.tag)for(let e of this.tag.values())e.clear();return this.store&&this.store.clear(),this.cache&&this.cache.clear(),e.length?Promise.all(e):this},Gb.contain=function(e){return this.db?this.index.get(this.field[0]).db.has(e):this.reg.has(e)},Gb.cleanup=function(){for(let e of this.index.values())e.cleanup();return this},Gb.get=function(e){return this.db?this.index.get(this.field[0]).db.enrich(e).then(function(e){return e[0]&&e[0].doc||null}):this.store.get(e)||null},Gb.set=function(e,t){return typeof e==`object`&&(t=e,e=Zb(t,this.key)),this.store.set(e,t),this},Gb.searchCache=tx,Gb.export=zoe,Gb.import=Boe,vx(Rx.prototype);function Bx(e,t=0){let n=[],r=[];t&&=25e4/t*5e3|0;for(let i of e.entries())r.push(i),r.length===t&&(n.push(r),r=[]);return r.length&&n.push(r),n}function Vx(e,t){t||=new Map;for(let n=0,r;n<e.length;n++)r=e[n],t.set(r[0],r[1]);return t}function Hx(e,t=0){let n=[],r=[];t&&=25e4/t*1e3|0;for(let i of e.entries())r.push([i[0],Bx(i[1])[0]||[]]),r.length===t&&(n.push(r),r=[]);return r.length&&n.push(r),n}function Ux(e,t){t||=new Map;for(let n=0,r,i;n<e.length;n++)r=e[n],i=t.get(r[0]),t.set(r[0],Vx(r[1],i));return t}function Wx(e){let t=[],n=[];for(let r of e.keys())n.push(r),n.length===25e4&&(t.push(n),n=[]);return n.length&&t.push(n),t}function Gx(e,t){t||=new Set;for(let n=0;n<e.length;n++)t.add(e[n]);return t}function Kx(e,t,n,r,i,a,o=0){let s=r&&r.constructor===Array;var c=s?r.shift():r;if(!c)return this.export(e,t,i,a+1);if((c=e((t?t+`.`:``)+(o+1)+`.`+n,JSON.stringify(c)))&&c.then){let l=this;return c.then(function(){return Kx.call(l,e,t,n,s?r:null,i,a,o+1)})}return Kx.call(this,e,t,n,s?r:null,i,a,o+1)}function zoe(e,t,n=0,r=0){if(n<this.field.length){let i=this.field[n];if((t=this.index.get(i).export(e,i,n,r=1))&&t.then){let r=this;return t.then(function(){return r.export(e,i,n+1)})}return this.export(e,i,n+1)}let i,a;switch(r){case 0:i=`reg`,a=Wx(this.reg),t=null;break;case 1:i=`tag`,a=this.tag&&Hx(this.tag,this.reg.size),t=null;break;case 2:i=`doc`,a=this.store&&Bx(this.store),t=null;break;default:return}return Kx.call(this,e,t,i,a||null,n,r)}function Boe(e,t){var n=e.split(`.`);n[n.length-1]===`json`&&n.pop();let r=n.length>2?n[0]:``;if(n=n.length>2?n[2]:n[1],this.worker&&r)return this.index.get(r).import(e);if(t){if(typeof t==`string`&&(t=JSON.parse(t)),r)return this.index.get(r).import(n,t);switch(n){case`reg`:this.fastupdate=!1,this.reg=Gx(t,this.reg);for(let e=0,t;e<this.field.length;e++)t=this.index.get(this.field[e]),t.fastupdate=!1,t.reg=this.reg;if(this.worker){t=[];for(let n of this.index.values())t.push(n.import(e));return Promise.all(t)}break;case`tag`:this.tag=Ux(t,this.tag);break;case`doc`:this.store=Vx(t,this.store)}}}function qx(e,t){let n=``;for(let r of e.entries()){e=r[0];let i=r[1],a=``;for(let e=0,n;e<i.length;e++){n=i[e]||[``];let r=``;for(let e=0;e<n.length;e++)r+=(r?`,`:``)+(t===`string`?`"`+n[e]+`"`:n[e]);r=`[`+r+`]`,a+=(a?`,`:``)+r}a=`["`+e+`",[`+a+`]]`,n+=(n?`,`:``)+a}return n}tS.prototype.remove=function(e,t){let n=this.reg.size&&(this.fastupdate?this.reg.get(e):this.reg.has(e));if(n){if(this.fastupdate){for(let t=0,r,i;t<n.length;t++)if((r=n[t])&&(i=r.length)){if(r[i-1]===e)r.pop();else{let t=r.indexOf(e);t>=0&&r.splice(t,1)}}}else Jx(this.map,e),this.depth&&Jx(this.ctx,e);t||this.reg.delete(e)}return this.db&&(this.commit_task.push({del:e}),this.M&&nS(this)),this.cache&&this.cache.remove(e),this};function Jx(e,t){let n=0;var r=t===void 0;if(e.constructor===Array){for(let i=0,a,o,s;i<e.length;i++)if((a=e[i])&&a.length){if(r)return 1;if(o=a.indexOf(t),o>=0){if(a.length>1)return a.splice(o,1),1;if(delete e[i],n)return 1;s=1}else{if(s)return 1;n++}}}else for(let i of e.entries())r=i[0],Jx(i[1],t)?n++:e.delete(r);return n}var Voe={memory:{resolution:1},performance:{resolution:3,fastupdate:!0,context:{depth:1,resolution:1}},match:{tokenize:`forward`},score:{resolution:9,context:{depth:2,resolution:3}}};tS.prototype.add=function(e,t,n,r){if(t&&(e||e===0)){if(!r&&!n&&this.reg.has(e))return this.update(e,t);r=this.depth,t=this.encoder.encode(t,!r);let l=t.length;if(l){let u=Jb(),d=Jb(),f=this.resolution;for(let p=0;p<l;p++){let m=t[this.rtl?l-1-p:p];var i=m.length;if(i&&(r||!d[m])){var a=this.score?this.score(t,m,p,null,0):Xx(f,l,p),o=``;switch(this.tokenize){case`tolerant`:if(Yx(this,d,m,a,e,n),i>2){for(let t=1,r,s,c,l;t<i-1;t++)r=m.charAt(t),s=m.charAt(t+1),c=m.substring(0,t)+s,l=m.substring(t+2),o=c+r+l,Yx(this,d,o,a,e,n),o=c+l,Yx(this,d,o,a,e,n);Yx(this,d,m.substring(0,m.length-1),a,e,n)}break;case`full`:if(i>2){for(let r=0,c;r<i;r++)for(a=i;a>r;a--){o=m.substring(r,a),c=this.rtl?i-1-r:r;var s=this.score?this.score(t,m,p,o,c):Xx(f,l,p,i,c);Yx(this,d,o,s,e,n)}break}case`bidirectional`:case`reverse`:if(i>1){for(s=i-1;s>0;s--){o=m[this.rtl?i-1-s:s]+o;var c=this.score?this.score(t,m,p,o,s):Xx(f,l,p,i,s);Yx(this,d,o,c,e,n)}o=``}case`forward`:if(i>1){for(s=0;s<i;s++)o+=m[this.rtl?i-1-s:s],Yx(this,d,o,a,e,n);break}default:if(Yx(this,d,m,a,e,n),r&&l>1&&p<l-1)for(i=this.N,o=m,a=Math.min(r+1,this.rtl?p+1:l-p),s=1;s<a;s++){m=t[this.rtl?l-1-p-s:p+s],c=this.bidirectional&&m>o;let r=this.score?this.score(t,o,p,m,s-1):Xx(i+(l/2>i?0:1),l,p,a-1,s-1);Yx(this,u,c?o:m,r,e,n,c?m:o)}}}}this.fastupdate||this.reg.add(e)}}return this.db&&(this.commit_task.push(n?{ins:e}:{del:e}),this.M&&nS(this)),this};function Yx(e,t,n,r,i,a,o){let s,c;if(!(s=t[n])||o&&!s[o]){if(o?(t=s||(t[n]=Jb()),t[o]=1,c=e.ctx,(s=c.get(o))?c=s:c.set(o,c=e.keystore?new fx(e.keystore):new Map)):(c=e.map,t[n]=1),(s=c.get(n))?c=s:c.set(n,c=s=[]),a){for(let n=0,a;n<s.length;n++)if((a=s[n])&&a.includes(i)){if(n<=r)return;a.splice(a.indexOf(i),1),e.fastupdate&&(t=e.reg.get(i))&&t.splice(t.indexOf(a),1);break}}if(c=c[r]||(c[r]=[]),c.push(i),c.length===2**31-1){if(t=new dx(c),e.fastupdate)for(let n of e.reg.values())n.includes(c)&&(n[n.indexOf(c)]=t);s[r]=c=t}e.fastupdate&&((r=e.reg.get(i))?r.push(c):e.reg.set(i,[c]))}}function Xx(e,t,n,r,i){return n&&e>1?t+(r||0)<=e?n+(i||0):(e-1)/(t+(r||0))*(n+(i||0))+1|0:0}tS.prototype.search=function(e,t,n){if(n||(t||typeof e!=`object`?typeof t==`object`&&(n=t,t=0):(n=e,e=``)),n&&n.cache)return n.cache=!1,e=this.searchCache(e,t,n),n.cache=!0,e;let r=[],i,a,o,s=0,c,l,u,d,f;n&&(e=n.query||e,t=n.limit||t,s=n.offset||0,a=n.context,o=n.suggest,f=(c=n.resolve)&&n.enrich,u=n.boost,d=n.resolution,l=this.db&&n.tag),c===void 0&&(c=this.resolve),a=this.depth&&a!==!1;let p=this.encoder.encode(e,!a);if(i=p.length,t||=c?100:0,i===1)return Qx.call(this,p[0],``,t,s,c,f,l);if(i===2&&a&&!o)return Qx.call(this,p[1],p[0],t,s,c,f,l);let m=Jb(),h=0,g;if(a&&(g=p[0],h=1),d||d===0||(d=g?this.N:this.resolution),this.db){if(this.db.search&&(n=this.db.search(this,p,t,s,o,c,f,l),n!==!1))return n;let e=this;return async function(){for(let t,n;h<i;h++){if((n=p[h])&&!m[n]){if(m[n]=1,t=await eS(e,n,g,0,0,!1,!1),t=$x(t,r,o,d)){r=t;break}g&&(o&&t&&r.length||(g=n))}o&&g&&h===i-1&&!r.length&&(d=e.resolution,g=``,h=-1,m=Jb())}return Zx(r,d,t,s,o,u,c)}()}for(let e,t;h<i;h++){if((t=p[h])&&!m[t]){if(m[t]=1,e=eS(this,t,g,0,0,!1,!1),e=$x(e,r,o,d)){r=e;break}g&&(o&&e&&r.length||(g=t))}o&&g&&h===i-1&&!r.length&&(d=this.resolution,g=``,h=-1,m=Jb())}return Zx(r,d,t,s,o,u,c)};function Zx(e,t,n,r,i,a,o){let s=e.length,c=e;if(s>1)c=Px(e,t,n,r,i,a,o);else if(s===1)return o?Ox.call(null,e[0],n,r):new Mx(e[0],this);return o?c:new Mx(c,this)}function Qx(e,t,n,r,i,a,o){return e=eS(this,e,t,n,r,i,a,o),this.db?e.then(function(e){return i?e||[]:new Mx(e,this)}):e&&e.length?i?Ox.call(this,e,n,r):new Mx(e,this):i?[]:new Mx([],this)}function $x(e,t,n,r){let i=[];if(e&&e.length){if(e.length<=r){t.push(e);return}for(let t=0,n;t<r;t++)(n=e[t])&&(i[t]=n);if(i.length){t.push(i);return}}if(!n)return i}function eS(e,t,n,r,i,a,o,s){let c;return n&&(c=e.bidirectional&&t>n)&&(c=n,n=t,t=c),e.db?e.db.get(t,n,r,i,a,o,s):(e=n?(e=e.ctx.get(n))&&e.get(t):e.map.get(t),e)}function tS(e,t){if(!this||this.constructor!==tS)return new tS(e);if(e){var n=Yb(e)?e:e.preset;n&&(e=Object.assign({},Voe[n],e))}else e={};n=e.context;let r=n===!0?{depth:1}:n||{},i=Yb(e.encoder)?lx[e.encoder]:e.encode||e.encoder||{};this.encoder=i.encode?i:typeof i==`object`?new $b(i):{encode:i},this.resolution=e.resolution||9,this.tokenize=n=(n=e.tokenize)&&n!=="default"&&n!==`exact`&&n||`strict`,this.depth=n===`strict`&&r.depth||0,this.bidirectional=r.bidirectional!==!1,this.fastupdate=!!e.fastupdate,this.score=e.score||null,(n=e.keystore||0)&&(this.keystore=n),this.map=n?new fx(n):new Map,this.ctx=n?new fx(n):new Map,this.reg=t||(this.fastupdate?n?new fx(n):new Map:n?new px(n):new Set),this.N=r.resolution||3,this.rtl=i.rtl||e.rtl||!1,this.cache=(n=e.cache||null)&&new nx(n),this.resolve=e.resolve!==!1,(n=e.db)&&(this.db=this.mount(n)),this.M=e.commit!==!1,this.commit_task=[],this.commit_timer=null,this.priority=e.priority||4}Gb=tS.prototype,Gb.mount=function(e){return this.commit_timer&&=(clearTimeout(this.commit_timer),null),e.mount(this)},Gb.commit=function(){return this.commit_timer&&=(clearTimeout(this.commit_timer),null),this.db.commit(this)},Gb.destroy=function(){return this.commit_timer&&=(clearTimeout(this.commit_timer),null),this.db.destroy()};function nS(e){e.commit_timer||=setTimeout(function(){e.commit_timer=null,e.db.commit(e)},1)}Gb.clear=function(){return this.map.clear(),this.ctx.clear(),this.reg.clear(),this.cache&&this.cache.clear(),this.db?(this.commit_timer&&clearTimeout(this.commit_timer),this.commit_timer=null,this.commit_task=[],this.db.clear()):this},Gb.append=function(e,t){return this.add(e,t,!0)},Gb.contain=function(e){return this.db?this.db.has(e):this.reg.has(e)},Gb.update=function(e,t){let n=this,r=this.remove(e);return r&&r.then?r.then(()=>n.add(e,t)):this.add(e,t)},Gb.cleanup=function(){return this.fastupdate?(Jx(this.map),this.depth&&Jx(this.ctx),this):this},Gb.searchCache=tx,Gb.export=function(e,t,n=0,r=0){let i,a;switch(r){case 0:i=`reg`,a=Wx(this.reg);break;case 1:i=`cfg`,a=null;break;case 2:i=`map`,a=Bx(this.map,this.reg.size);break;case 3:i=`ctx`,a=Hx(this.ctx,this.reg.size);break;default:return}return Kx.call(this,e,t,i,a,n,r)},Gb.import=function(e,t){if(t)switch(typeof t==`string`&&(t=JSON.parse(t)),e=e.split(`.`),e[e.length-1]===`json`&&e.pop(),e.length===3&&e.shift(),e=e.length>1?e[1]:e[0],e){case`reg`:this.fastupdate=!1,this.reg=Gx(t,this.reg);break;case`map`:this.map=Vx(t,this.map);break;case`ctx`:this.ctx=Ux(t,this.ctx)}},Gb.serialize=function(e=!0){let t=``,n=``,r=``;if(this.reg.size){let e;for(var i of this.reg.keys())e||=typeof i,t+=(t?`,`:``)+(e===`string`?`"`+i+`"`:i);t=`index.reg=new Set([`+t+`]);`,n=qx(this.map,e),n=`index.map=new Map([`+n+`]);`;for(let t of this.ctx.entries()){i=t[0];let n=qx(t[1],e);n=`new Map([`+n+`])`,n=`["`+i+`",`+n+`]`,r+=(r?`,`:``)+n}r=`index.ctx=new Map([`+r+`]);`}return e?`function inject(index){`+t+n+r+`}`:t+n+r},vx(tS.prototype);var rS=typeof window<`u`&&(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB),iS=[`map`,`ctx`,`tag`,`reg`,`cfg`],aS=Jb();function oS(e,t={}){if(!this||this.constructor!==oS)return new oS(e,t);typeof e==`object`&&(t=e,e=e.name),e||console.info(`Default storage space was used, because a name was not passed.`),this.id=`flexsearch`+(e?`:`+e.toLowerCase().replace(/[^a-z0-9_\-]/g,``):``),this.field=t.field?t.field.toLowerCase().replace(/[^a-z0-9_\-]/g,``):``,this.type=t.type,this.fastupdate=this.support_tag_search=!1,this.db=null,this.h={}}Gb=oS.prototype,Gb.mount=function(e){return e.index?e.mount(this):(e.db=this,this.open())},Gb.open=function(){if(this.db)return this.db;let e=this;navigator.storage&&navigator.storage.persist&&navigator.storage.persist(),aS[e.id]||(aS[e.id]=[]),aS[e.id].push(e.field);let t=rS.open(e.id,1);return t.onupgradeneeded=function(){let t=e.db=this.result;for(let n=0,r;n<iS.length;n++){r=iS[n];for(let n=0,i;n<aS[e.id].length;n++)i=aS[e.id][n],t.objectStoreNames.contains(r+(r===`reg`?``:i?`:`+i:``))||t.createObjectStore(r+(r===`reg`?``:i?`:`+i:``))}},e.db=cS(t,function(t){e.db=t,e.db.onversionchange=function(){e.close()}})},Gb.close=function(){this.db&&this.db.close(),this.db=null},Gb.destroy=function(){return cS(rS.deleteDatabase(this.id))},Gb.clear=function(){let e=[];for(let t=0,n;t<iS.length;t++){n=iS[t];for(let t=0,r;t<aS[this.id].length;t++)r=aS[this.id][t],e.push(n+(n===`reg`?``:r?`:`+r:``))}let t=this.db.transaction(e,`readwrite`);for(let n=0;n<e.length;n++)t.objectStore(e[n]).clear();return cS(t)},Gb.get=function(e,t,n=0,r=0,i=!0,a=!1){e=this.db.transaction((t?`ctx`:`map`)+(this.field?`:`+this.field:``),`readonly`).objectStore((t?`ctx`:`map`)+(this.field?`:`+this.field:``)).get(t?t+`:`+e:e);let o=this;return cS(e).then(function(e){let t=[];if(!e||!e.length)return t;if(i){if(!n&&!r&&e.length===1)return e[0];for(let i=0,a;i<e.length;i++)if((a=e[i])&&a.length){if(r>=a.length){r-=a.length;continue}let e=n?r+Math.min(a.length-r,n):a.length;for(let n=r;n<e;n++)t.push(a[n]);if(r=0,t.length===n)break}return a?o.enrich(t):t}return e})},Gb.tag=function(e,t=0,n=0,r=!1){e=this.db.transaction(`tag`+(this.field?`:`+this.field:``),`readonly`).objectStore(`tag`+(this.field?`:`+this.field:``)).get(e);let i=this;return cS(e).then(function(e){return!e||!e.length||n>=e.length?[]:!t&&!n?e:(e=e.slice(n,n+t),r?i.enrich(e):e)})},Gb.enrich=function(e){typeof e!=`object`&&(e=[e]);let t=this.db.transaction(`reg`,`readonly`).objectStore(`reg`),n=[];for(let r=0;r<e.length;r++)n[r]=cS(t.get(e[r]));return Promise.all(n).then(function(t){for(let n=0;n<t.length;n++)t[n]={id:e[n],doc:t[n]?JSON.parse(t[n]):null};return t})},Gb.has=function(e){return e=this.db.transaction(`reg`,`readonly`).objectStore(`reg`).getKey(e),cS(e).then(function(e){return!!e})},Gb.search=null,Gb.info=function(){},Gb.transaction=function(e,t,n){e+=e===`reg`?``:this.field?`:`+this.field:``;let r=this.h[e+`:`+t];if(r)return n.call(this,r);let i=this.db.transaction(e,t);this.h[e+`:`+t]=r=i.objectStore(e);let a=n.call(this,r);return this.h[e+`:`+t]=null,cS(i).finally(function(){return a})},Gb.commit=async function(e){let t=e.commit_task,n=[];e.commit_task=[];for(let e=0,r;e<t.length;e++)r=t[e],r.del&&n.push(r.del);n.length&&await this.remove(n),e.reg.size&&(await this.transaction(`map`,`readwrite`,function(t){for(let n of e.map){let e=n[0],r=n[1];r.length&&(t.get(e).onsuccess=function(){let n=this.result;var i;if(n&&n.length){let e=Math.max(n.length,r.length);for(let t=0,a,o;t<e;t++)if((o=r[t])&&o.length){if((a=n[t])&&a.length)for(i=0;i<o.length;i++)a.push(o[i]);else n[t]=o;i=1}}else n=r,i=1;i&&t.put(n,e)})}}),await this.transaction(`ctx`,`readwrite`,function(t){for(let n of e.ctx){let e=n[0],r=n[1];for(let n of r){let r=n[0],i=n[1];i.length&&(t.get(e+`:`+r).onsuccess=function(){let n=this.result;var a;if(n&&n.length){let e=Math.max(n.length,i.length);for(let t=0,r,o;t<e;t++)if((o=i[t])&&o.length){if((r=n[t])&&r.length)for(a=0;a<o.length;a++)r.push(o[a]);else n[t]=o;a=1}}else n=i,a=1;a&&t.put(n,e+`:`+r)})}}}),e.store?await this.transaction(`reg`,`readwrite`,function(t){for(let n of e.store){let e=n[0],r=n[1];t.put(typeof r==`object`?JSON.stringify(r):1,e)}}):e.bypass||await this.transaction(`reg`,`readwrite`,function(t){for(let n of e.reg.keys())t.put(1,n)}),e.tag&&await this.transaction(`tag`,`readwrite`,function(t){for(let n of e.tag){let e=n[0],r=n[1];r.length&&(t.get(e).onsuccess=function(){let n=this.result;n=n&&n.length?n.concat(r):r,t.put(n,e)})}}),e.map.clear(),e.ctx.clear(),e.tag&&e.tag.clear(),e.store&&e.store.clear(),e.document||e.reg.clear())};function sS(e,t,n){let r=e.value,i,a=0;for(let e=0,o;e<r.length;e++){if(o=n?r:r[e]){for(let n=0,a,s;n<t.length;n++)if(s=t[n],a=o.indexOf(s),a>=0){if(i=1,o.length>1)o.splice(a,1);else{r[e]=[];break}}a+=o.length}if(n)break}a?i&&e.update(r):e.delete(),e.continue()}Gb.remove=function(e){return typeof e!=`object`&&(e=[e]),Promise.all([this.transaction(`map`,`readwrite`,function(t){t.openCursor().onsuccess=function(){let t=this.result;t&&sS(t,e)}}),this.transaction(`ctx`,`readwrite`,function(t){t.openCursor().onsuccess=function(){let t=this.result;t&&sS(t,e)}}),this.transaction(`tag`,`readwrite`,function(t){t.openCursor().onsuccess=function(){let t=this.result;t&&sS(t,e,!0)}}),this.transaction(`reg`,`readwrite`,function(t){for(let n=0;n<e.length;n++)t.delete(e[n])})])};function cS(e,t){return new Promise((n,r)=>{e.onsuccess=e.oncomplete=function(){t&&t(this.result),t=null,n(this.result)},e.onerror=e.onblocked=r,e=null})}var Hoe={Index:tS,Charset:lx,Encoder:$b,Document:Rx,Worker:wx,Resolver:Mx,IndexedDB:oS,Language:{}};function lS(e,t,n,r){if(!t?.type)throw Error(`Schema not found for `+n);if(e!==null&&!V.isJson(e)){if(t.type===`string`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`number`){typeof e==`number`&&r({source:e,schema:t,path:n});return}if(t.type===`boolean`){typeof e==`boolean`&&r({source:e,schema:t,path:n});return}if(t.type===`richtext`){r({source:e,schema:t,path:n});return}if(t.type===`file`||t.type===`image`){e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`date`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`dateTime`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`color`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`keyOf`){(typeof e==`string`||typeof e==`number`)&&r({source:e,schema:t,path:n});return}if(t.type===`literal`){r({source:e,schema:t,path:n});return}if(t.type===`route`){typeof e==`string`&&r({source:e,schema:t,path:n});return}if(t.type===`array`){if(!Array.isArray(e))return;if(!t.item)throw Error(`Schema (`+t.type+`) item not found for `+n);for(let i=0;i<e.length;i++){let a=My(n,i);lS(e[i],t.item,a,r)}return}if(t.type===`object`||t.type===`record`){if(typeof e!=`object`||!e||Array.isArray(e))return;for(let i in e){let a=t.type===`object`?t.items?.[i]:t.item;if(!a)continue;let o=My(n,i);lS(e[i],a,o,r)}return}if(t.type===`union`){let i=t.key;if(typeof i==`string`){if(e&&typeof e==`object`&&!Array.isArray(e)&&i in e){let a=e[i];if(typeof a==`string`){let o=t.items.filter(e=>e.type===`object`).find(e=>{let t=e.items[i];return t?.type===`literal`&&t.value===a});o&&lS(e,o,n,r)}}}else typeof e==`string`&&r({source:e,schema:t,path:n});return}throw Error(`Unsupported schema type: `+JSON.stringify(t))}}function Uoe(e){let t=``;function n(e){if(typeof e==`string`)t+=e;else if(e&&typeof e==`object`&&`children`in e&&Array.isArray(e.children))for(let t of e.children)n(t)}return n({children:e}),t}function uS(e){let t=V.remote.splitRemoteRef(e);return t.status===`success`?`/${t.filePath}`:e}function Woe(e){let t=uS(e);return t.split(`/`).pop()||t}function dS(e){let t=uS(e);return{cleanPath:t,filename:t.split(`/`).pop()||t,folder:t.replace(/^\/public(?=\/|$)/,``).replace(/\/[^/]+$/,``)||`/`}}function fS(){return{index:new Hoe.Index({tokenize:`forward`}),pathToLabel:new Map,docsByModule:new Map}}function Goe(e,t,n,r){let{index:i,pathToLabel:a,docsByModule:o}=e;pS(e,t);let s=new Set;o.set(t,s),lS(n,r,t+`?p=`,({source:e,schema:t,path:n})=>{if(e===null)return;let r=``,o=``;if(t.type===`string`||t.type===`number`||t.type===`boolean`||t.type===`date`||t.type===`dateTime`||t.type===`color`||t.type===`keyOf`||t.type===`route`)r=e?.toString()??``,o=e?.toString()??``;else if(t.type===`literal`)r=t.value.toString(),o=t.value.toString();else if(t.type===`richtext`)r=Uoe(e),o=r.substring(0,50)||`richtext`;else if((t.type===`file`||t.type===`image`)&&typeof e==`object`&&e&&`path`in e&&typeof e.path==`string`){let{filename:t,folder:n}=dS(e.path),i=`alt`in e?e.alt:``;r=t+` `+n+` `+i,o=t}if(r){let[,e]=V.splitModuleFilePathAndModulePath(n),t=qoe(e)+` `;i.add(n,t+` `+n+` `+r),a.set(n,o),s.add(n)}})}function pS(e,t){let{index:n,pathToLabel:r,docsByModule:i}=e,a=i.get(t);if(a!==void 0){for(let e of a)n.remove(e),r.delete(e);i.delete(t)}}var Koe=new Set([`/`,`-`,`_`,`.`,`:`,`?`,`&`,`=`,`@`,`"`,`'`]);function qoe(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];Koe.has(r)?t+=` `:t+=r}return t}function Joe(e,t,n=50,r=0){if(e===null||!t.trim())return{results:[],total:0};let{index:i,pathToLabel:a}=e,o=i.search(t,{limit:r+n}),s=o.length;return{results:o.slice(r,r+n).map(e=>({path:e,label:a.get(e)||e})),total:s}}var Yoe=class{constructor(e=hb){this.activity=e,this.events=new mb,this.index=null,this.indexed=new Set,this.partial=new Set}async reindex(e){let t=Object.keys(e);this.index===null&&(this.index=fS());let n=[];for(let r of t){this.activity.work(`search:index-module`,r);let t=e[r];Goe(this.index,r,t.source,t.schema),this.indexed.has(r)||n.push(r),this.indexed.add(r),t.complete?this.partial.delete(r):this.partial.add(r)}let r={new:n,all:[...this.indexed]};return this.events.emit({type:`search:build-index`,...r}),r}async forget(e){this.index!==null&&pS(this.index,e),this.indexed.delete(e),this.partial.delete(e)}async buildIndex(e){return this.activity.work(`search:build-index`,void 0,Object.keys(e).length),this.index=fS(),this.indexed=new Set,this.partial.clear(),this.reindex(e)}async search(e,t,n){if(this.index===null)return{status:`no-index`};this.activity.work(`search:query`,e);let{results:r,total:i}=Joe(this.index,e,t,n);return{status:`results`,results:r,total:i,partialModules:[...this.partial]}}},Xoe=class{constructor(e=hb){this.activity=e,this.events=new mb,this.byModule=new Map,this.incomplete=new Map}async forget(e){this.byModule.delete(e),this.incomplete.delete(e)}async rescan(e){let t=Object.keys(e);for(let n of t){this.activity.work(`references:scan-module`,n);let t=e[n],r=new Map;mS(n,t.schema,t.source,r),this.byModule.set(n,r),t.complete?this.incomplete.delete(n):this.incomplete.set(n,Qoe(t.schema))}return this.events.emit({type:`references:scan`,modules:t}),t}async find(e){this.activity.work(`references:query`,e.kind);let t=[];for(let n of this.byModule.values())for(let[r,i]of n)Zoe(i,e)&&t.push(r);let n=[];for(let[t,r]of this.incomplete)r.has(e.kind)&&n.push(t);return n.length>0?{status:`partial`,refs:t,awaiting:n}:{status:`complete`,refs:t}}async at(e){let[t]=V.splitModuleFilePathAndModulePath(e);return this.byModule.get(t)?.get(e)??null}};function Zoe(e,t){return!(e.kind!==t.kind||t.kind!==`route`&&e.target!==t.module||t.value!==void 0&&e.value!==t.value)}function Qoe(e){let t=new Set,n=new Set,r=e=>{if(!(e===void 0||n.has(e)))switch(n.add(e),e.type){case`keyOf`:t.add(`keyOf`);return;case`image`:case`file`:t.add(`file`);return;case`route`:t.add(`route`);return;case`object`:for(let t of Object.values(e.items))r(t);return;case`array`:case`record`:r(e.item);return;case`union`:for(let t of e.items)r(t);return;default:return}};return e?.type===`record`?r(e.item):r(e),t}function mS(e,t,n,r){if(t!==void 0&&!V.isJson(n))switch(t.type){case`keyOf`:r.set(e,{kind:`keyOf`,target:t.path,value:typeof n==`string`?n:null});return;case`image`:case`file`:if(t.referencedModule===void 0)return;r.set(e,{kind:`file`,target:t.referencedModule,value:$oe(n)});return;case`route`:r.set(e,{kind:`route`,target:null,value:typeof n==`string`?n:null});return;case`object`:if(!hS(n))return;for(let i in t.items){let a=n[i];a!==void 0&&mS(My(e,i),t.items[i],a,r)}return;case`record`:if(!hS(n))return;for(let i in n)mS(My(e,i),t.item,n[i],r);return;case`array`:if(!Array.isArray(n))return;for(let i=0;i<n.length;i++)mS(My(e,i),t.item,n[i],r);return;case`union`:for(let i of t.items)mS(e,i,n,r);return;default:return}}function $oe(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e.path;return typeof t==`string`?t:null}function hS(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var gS=class{constructor(e){this.invalidateEvent=e,this.events=new mb,this.stale=new Set,this.covered=new Set}mark(e){let t=e.filter(e=>!this.stale.has(e));for(let t of e)this.stale.add(t);t.length>0&&this.events.emit({type:this.invalidateEvent,modules:t})}needsPass(){return this.covered.size===0||this.stale.size>0}target(e){return this.covered.size===0?e:[...this.stale]}covers(e){for(let t of e)this.covered.add(t),this.stale.delete(t)}forget(e){this.stale.delete(e),this.covered.delete(e)}coveredModules(){return[...this.covered]}staleModules(){return[...this.stale]}},ese=300;function tse(e,t,n){let r=[];for(let i of e){if(!t.has(i)||n.has(i))break;r.push(i)}return r}var nse=5e3,rse=class{constructor(){this.validator=new pb}async validate(e,t,n,r){return this.validator.validate(e,t,n,r)}};function ise(e){let t=e.activity??hb,n=new qae(t),r=new ooe(e.fetchPatches,e.createPatchId,t,e.uploadFile),i=new noe(n,t,e.fetchJsonEntry),a=new soe,o=new coe(t),s=new doe(r,e.savePatches,e.resyncChain??(async()=>{}),t,e.sessionId,e.saveBackoffMs,e.saveSleep);r.setParentRefSource(()=>s.currentParentRef());let c=new foe(n,i,t),l=e.hostBridge??c,u=new hoe(l,i,n,t),d=new boe(n,i,e.schemaValidation??new rse,l,t),f=e.workerRealm?.search??new Yoe(t),p=e.workerRealm?.patchSets??new _oe(t),m=e.workerRealm?.references??new Xoe(t),h=new gS(`search:invalidate`),g=new gS(`references:invalidate`),_=new voe,v=!1,y=!1,b=e.mode??`fs`,x=null;r.setPublishInFlight(()=>v);let S=new Map;async function C(t){let n=[];for(let{patchId:e,message:a}of t){let t=r.recordsFor([e])[0],o=t?.moduleFilePath,s=o!==void 0&&i.hasUnloadedEntries(o),c=(S.get(e)??0)+1;if(S.set(e,c),console.error(s?`Val: a patch could not be applied, and this module still has unloaded .jsonValues() entries — so it may apply once they arrive. Keeping it. If the edit never appears, please report this.`:`Val: discarding a patch that cannot be applied. If you see this often, please report it — it means a patch is being generated that does not fit the source it targets.`,{patchId:e,reason:a,module:o??`(record already gone)`,ops:t?.patch?.map(e=>({op:e.op,path:`path`in e?e.path:void 0})),origin:r.originOf(e),savedOnServer:!r.isPending(e),attempt:c}),!s){if(c>3){console.error(`Val: giving up on deleting an unapplicable patch — it keeps coming back. It is out of this session's chain so it cannot block saving, but it is still on the server.`,{patchId:e,attempts:c}),r.drop([e]);continue}n.push(e)}}if(n.length===0)return;if(r.drop(n),o.reportError(n.length===1?`An edit could not be applied and has been discarded.`:`${n.length} edits could not be applied and have been discarded.`,`This usually means a patch was generated that does not fit the content it targets. The browser console has the failing operation.`),e.discardPatches===void 0){console.error(`Val: cannot delete the patch on the server — this system has no discard seam. It will return on the next reload.`,{patchIds:n});return}let a=await e.discardPatches(n);a.status===`error`&&console.error(`Val: could not delete an unapplicable patch on the server.`,{patchIds:n,error:a.message})}let w=null;function T(){w===null&&(w=setTimeout(()=>{w=null;let e=new Set;for(let t of r.allRecords())e.add(t.moduleFilePath);for(let t of e)d.validate(t)},ese))}let E=[r.listenTo(a,i),i.listenTo(r),s.listenTo(),a.events.on(`patch:removed-by-server`,e=>{o.reportError(e.removed.length===1?`An unpublished change was removed because the server could not read it.`:`${e.removed.length} unpublished changes were removed because the server could not read them.`,`They are gone and the fields are back to their published values. The server log and .val/patches/patches.repair.log say which, and why.`),console.error(`Val: the server removed these unpublished changes.`,e.removed)}),r.events.on(`patch:fetch-failed`,e=>{o.reportError(`Unpublished changes could not be loaded.`,`${e.patches.length} ${e.patches.length===1?`change is`:`changes are`} affected: ${e.message} Until this succeeds, the editor shows published content for the fields they touch.`)}),r.events.on(`patch:announced-not-delivered`,e=>{o.reportError(e.patches.length===1?`An unpublished change could not be loaded.`:`${e.patches.length} unpublished changes could not be loaded.`,`The server listed them but did not send them, so they are not shown. Reload before editing: anything you change now is written on top of content that is missing them.`),console.error(`Val: the server announced these unpublished changes and did not send them.`,{patchIds:e.patches})}),s.events.on(`patch:save-rejected`,e=>{o.reportError(e.patches.length===1?`An edit could not be saved and has been reverted.`:`${e.patches.length} edits could not be saved and have been reverted.`,e.errors?Object.entries(e.errors).map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
131
+ `):e.message)}),s.events.on(`patch:save-stuck`,e=>{let t=Kae(e.reason,e.message,e.attempt,e.patches.length);o.reportError(t.title,t.detail)}),a.events.on(`stat:receive`,e=>{let t=a.currentBaseSha();t!==null&&(s.receiveStat(t,e.patches),s.flush())}),u.listenTo(),d.listenTo(),r.events.on(`patch:chain`,()=>{T()}),i.events.on(`source:patch-apply`,e=>{e.failed.length!==0&&C(e.failed)}),i.events.on(`source:patch-apply`,e=>{h.mark(e.modules),g.mark(e.modules)}),i.events.on(`source:init`,e=>{h.mark(e.sources),g.mark(e.sources)}),n.events.on(`schema:init`,()=>{_.invalidate()}),r.events.on(`patch:drop`,()=>{_.invalidate()}),r.events.on(`patch:drop`,e=>{s.forget(e.patches)})];function D(e,r){if(e.mode===`current`)return{mode:`current`};let i=new Set(e.patchIds),a=r.filter(e=>i.has(e.patchId)),o=n.all(),s={};for(let e of a){let t=o[e.moduleFilePath];t!==void 0&&(s[e.moduleFilePath]=t)}return t.work(`patch-set:gather`,void 0,a.length),{mode:e.mode,records:a,schemas:s}}function O(e){let r=n.all(),a={};t.work(`search:gather-snapshot`,void 0,e.length);for(let t of e){let e=r[t],n=i.moduleSource(t);e!==void 0&&n!==void 0&&(a[t]={source:n,schema:e,complete:!i.hasUnloadedEntries(t)})}return a}async function k(){if(!g.needsPass())return;let e=g.target(i.loadedModules()),t=await m.rescan(A(e));g.covers(t)}function A(e){let t=n.all(),r={};for(let n of e){let e=t[n],a=i.moduleSource(n);e!==void 0&&a!==void 0&&(r[n]={source:a,schema:e,complete:!i.hasUnloadedEntries(n)})}return r}return{host:c,stat:a,status:o,schemaStore:n,sourceStore:i,patchStore:r,patchSync:s,previewStore:u,validationStore:d,searchStore:f,patchSetStore:p,referenceStore:m,async findReferences(e){return await k(),m.find(e)},async referenceAt(e){return await k(),m.at(e)},async getPatchSets(){if(x!==null)return x;let e=(async()=>{let e=r.allRecords(),t=_.plan(e.map(e=>e.patchId)),n=D(t,e),i=await p.getPatchSets(n);return _.covers(t),i})().finally(()=>{x=null});return x=e,e},async search(e,t,n){if(h.needsPass()){let e=h.target(i.loadedModules()),t=await f.reindex(O(e));h.covers(t.all)}let r=await f.search(e,t,n);return r.status===`no-index`?r:{...r,staleModules:h.staleModules()}},async buildSearchIndex(){let e=i.loadedModules(),t=await f.buildIndex(O(e));return h.covers(t.all),t},async validateEverything(){if(!y){y=!0,d.events.emit({type:`validation:full-pass`,running:!0});try{for(let e of i.loadedModules())await d.validate(e)}finally{y=!1,d.events.emit({type:`validation:full-pass`,running:!1})}}},async publish(t,a,c){let l=c?.exact===!0;if(e.publishPatches===void 0)return{status:`failed`,message:`This system has no publish seam configured.`,retryable:!1};if(v)return{status:`refused`,reason:`already-publishing`};v=!0;try{!l&&e.savePatches!==void 0&&r.unsavedRecords().length>0&&s.currentState().status!==`retrying`&&await Promise.race([s.flush().catch(()=>void 0),new Promise(t=>{let n=setTimeout(t,e.saveFlushTimeoutMs??nse);typeof n==`object`&&`unref`in n&&n.unref()})]);let c=e.savePatches===void 0||l?[]:r.unsavedRecords();if(c.length>0)return{status:`refused`,reason:`unsaved-changes`,patchIds:c.map(e=>e.patchId)};let u=r.allRecords().map(e=>e.patchId),f=l?tse(u,new Set(t),new Set(r.unsavedRecords().map(e=>e.patchId))):u;if(f.length===0)return{status:`nothing-to-publish`};let p=new Set;for(let e of r.recordsFor(f))p.add(e.moduleFilePath);let m=r.chainVersion(),h=[];for(let e of p){let t=await d.validate(e);if(t.status!==`validated`||t.errors===!1)continue;let r=ab(t.errors,n.all(),i.allSources());Object.keys(r).length>0&&h.push(e)}if(h.length>0)return{status:`refused`,reason:`validation-errors`,modules:h};if(!l&&r.chainVersion()!==m)return{status:`refused`,reason:`chain-moved`};let g=await e.publishPatches({patchIds:f,message:a});if(g.status===`patch-errors`)return r.recordPublishErrors(g.errors),{status:`failed`,message:g.message,patchErrors:g.errors,retryable:!1};if(g.status!==`published`)return{status:`failed`,message:g.message,retryable:g.status===`not-fast-forward`||g.status===`network-error`};let _=g.removed??[];return _.length>0&&(r.drop(_.map(e=>e.patchId)),o.reportError(_.length===1?`An edit could not be applied and was removed.`:`${_.length} edits could not be applied and were removed.`,_.map(e=>`${e.moduleFilePath}: ${e.message}`).join(`
132
132
  `)),console.error(`Val: the save removed these changes because they could not be applied.`,_)),r.markPublished(f),b===`fs`&&(i.promotePublished(f,[...p]),r.forgetPublished(f)),{status:`published`,patchIds:f,..._.length>0?{removed:_}:{}}}finally{v=!1}},async discard(t){if(e.discardPatches===void 0)return{status:`failed`,message:`This system has no discard seam configured.`};let n=await e.discardPatches(t);return n.status===`error`?{status:`failed`,message:n.message}:(r.drop(n.patchIds),{status:`discarded`})},patchErrors(){return r.publishErrors()},setMode(e){b=e},dispose(){for(let e of E)e();w!==null&&(clearTimeout(w),w=null),s.dispose()}}}function ase(){let e=null,t=!1,n=0,r=new Map,i=null;function a(){if(e!==null||t)return e;try{e=new Worker(new URL(`/api/val/static/assets/validation.worker-BxrXN_Qo.js`,``+import.meta.url),{type:`module`}),e.onmessage=e=>{let t=e.data,n=r.get(t.id);n!==void 0&&(r.delete(t.id),t.type===`result`?n.resolve(t.errors):n.reject(Error(t.error)))},e.onerror=n=>{let i=Error(`Validation worker failed: ${n.message??`unknown error`}`);for(let e of r.values())e.reject(i);r.clear(),e?.terminate(),e=null,t=!0}}catch(n){console.warn(`Val: could not create the validation worker; validating on the main thread instead.`,n),t=!0,e=null}return e}return{async validate(e,t,o,s){let c=a();if(c===null)return i??=new pb,i.validate(e,t,o,s);let l=`val-${++n}`,u=new Promise((e,t)=>{r.set(l,{resolve:e,reject:t})}),d={type:`validate`,id:l,moduleFilePath:e,source:t,serializedSchema:o,schemaSha:s};c.postMessage(d);try{return await u}catch(n){return console.warn(`Val: validation worker could not validate '${e}'; validating on the main thread instead.`,n),i??=new pb,i.validate(e,t,o,s)}}}}var ose=1500,sse=36;function cse(e){return`&${e}=`.length+sse}function lse(e){return Math.max(1,Math.floor(ose/cse(e)))}function _S(e,t){if(e.length===0)return[];let n=lse(t),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}function use(e,t){let n=null,r=ise({schemaValidation:t?.schemaValidation??ase(),...t?.uploadSettings===void 0?{}:{uploadFile:async({patchId:e,parentRef:n,filePath:r,data:i,type:a,remote:o,metadata:s,onProgress:c})=>{let l=await t.uploadSettings();if(l.status===`error`)return{status:`error`,message:`Could not find where to upload files: ${l.error}`};let u=r;if(o){let e=V.remote.splitRemoteRef(r);if(e.status===`error`)return{status:`error`,message:`Could not read the file path out of a remote ref (${e.error}). This is most likely a Val bug.`};u=`/`+e.filePath}let d=JSON.stringify({filePath:u,parentRef:n??{type:`head`,headBaseSha:``},data:i,type:a,metadata:s,remote:o});return new Promise(t=>{let n=new XMLHttpRequest;c!==void 0&&n.upload.addEventListener(`progress`,e=>{e.lengthComputable&&c(e.loaded,e.total)}),n.addEventListener(`load`,()=>{if(n.status>=200&&n.status<300){t({status:`ok`});return}t({status:`error`,message:`Could not upload ${u}: HTTP ${n.status} ${n.statusText}`})}),n.addEventListener(`error`,()=>{t({status:`error`,message:`Could not upload ${u} (network error?)`})}),n.responseType=`text`,n.open(`POST`,`${l.data.baseUrl}/patches/${e}/files`),n.setRequestHeader(`Content-Type`,`application/json`),l.data.nonce!==null&&n.setRequestHeader(`x-val-auth-nonce`,l.data.nonce),n.send(d)})}},fetchPatches:async t=>{let n=[],r={},i,a=0,o=0;for(let s of _S(t,`patch_id`)){a++;let t=await e(`/patches`,`GET`,{query:{exclude_patch_ops:!1,patch_id:s}});if(t.status!==200){let e=`message`in t.json?t.json.message:`GET /patches failed with status ${t.status??`network`}`;for(let t of s)r[t]=e;i=e,o++;continue}for(let e of t.json.patches){if(e.patch===void 0){r[e.patchId]=`No ops for patch ${e.patchId}`;continue}n.push({patchId:e.patchId,moduleFilePath:e.path,patch:e.patch,createdAt:e.createdAt,authorId:e.authorId??void 0,appliedAt:e.appliedAt??null})}}return{patches:n,errors:r,...a>0&&o===a?{error:i}:{}}},fetchJsonEntry:async(t,n)=>{let r=await e(`/json`,`GET`,{query:{path:t,key:void 0,keys:[n],offset:void 0,limit:void 0,apply_patches:!1}});if(r.status!==200||!(`entries`in r.json))return{status:`error`,message:r.status!==200&&`message`in r.json?r.json.message:`GET /json failed with status ${r.status??`network`}`};let i=r.json.entries.find(e=>e.key===n);if(i===void 0){let e=r.json.errors.find(e=>e.key===n);return e===void 0?{status:`error`,message:`Entry not found: ${n} in ${t}`}:{status:`error`,message:e.message}}return{status:`ok`,content:i.content??null}},mode:t?.mode,publishPatches:async({patchIds:t,message:n})=>{let r=await e(`/save`,`POST`,{body:{message:n,patchIds:t}});if(r.status===null)return{status:`network-error`,message:`message`in r.json?r.json.message:`Network error`};if(r.status===200)return{status:`published`,removed:r.json.removed};if(r.status===409)return{status:`not-fast-forward`,message:r.json.message};if(r.status===400){let e={},t=`details`in r.json?r.json.details:void 0;if(Array.isArray(t))for(let n of t)typeof n==`object`&&n&&`patchId`in n&&`message`in n&&(e[n.patchId]=String(n.message));else if(typeof t==`object`&&t&&`unappliablePatches`in t&&t.unappliablePatches!==void 0)for(let[n,r]of Object.entries(t.unappliablePatches))e[n]=r.message;return{status:`patch-errors`,message:r.json.message,errors:e}}return{status:`error`,message:`message`in r.json?r.json.message:`POST /save failed with status ${r.status}`}},discardPatches:async t=>{let n=[];for(let r of _S(t,`id`)){let t=await e(`/patches`,`DELETE`,{query:{id:r}});if(t.status!==200)return{status:`error`,message:t.status!==null&&`message`in t.json?t.json.message:`DELETE /patches failed with status ${t.status??`network`}`};n.push(...t.json)}return{status:`discarded`,patchIds:n}},...t?.writes===!0?{savePatches:async({patches:t,parentRef:n,sessionId:r})=>{let i=await e(`/patches`,`PUT`,{body:{patches:t,parentRef:n,sessionId:r}});if(i.status===null){let e=`message`in i.json?i.json.message:`Network error`;return{status:`type`in i.json&&i.json.type===`client_side_validation_error`?`unparseable-response`:`network-error`,message:e}}return i.status===409?{status:`conflict`,message:i.json.message}:i.status===400?{status:`rejected`,message:i.json.message,errors:Object.fromEntries(Object.entries(i.json.errors??{}).map(([e,t])=>[e,t.map(e=>e.error.message)]))}:i.status===200?{status:`saved`,newPatchIds:i.json.newPatchIds,parentRef:i.json.parentRef}:{status:`unauthorized`,message:`message`in i.json?i.json.message:`PUT /patches failed with status ${i.status}`}}}:{},...t?.writes?{resyncChain:async()=>{let t=await e(`/stat`,`POST`,{body:null});t.status===200&&n?.stat.receiveStat({baseSha:t.json.baseSha,patches:t.json.patches})}}:{}});return n=r,r}var vS=b.createContext(new Proxy({},{get:()=>{throw Error(`Cannot use ValRemoteContext outside of ValRemoteProvider`)}}));function dse({children:e,remoteFiles:t}){return(0,Y.jsx)(vS.Provider,{value:{remoteFiles:t},children:e})}function yS(){let{remoteFiles:e}=(0,b.useContext)(vS);return e}function bS(){let{remoteFiles:e}=(0,b.useContext)(vS),[t,n]=(0,b.useState)(null);function r(e){return Math.floor(Math.random()*e)}return(0,b.useEffect)(()=>{e.status===`ready`&&e.buckets.length>0&&t===null&&n(e.buckets[r(e.buckets.length)])},[e,t]),t}var xS=(0,b.createContext)({isAIChatEnabled:!1,canMentionField:!1,openAIChat:()=>{},setOpenAIChatImpl:()=>{},chatEditorRef:{current:null},insertFieldRef:()=>{},flushPendingFieldRefs:()=>{}});function fse({isAIChatEnabled:e,isAIChatOnline:t,children:n}){let r=(0,b.useRef)(null),i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=(0,b.useRef)([]),c=(0,b.useCallback)(()=>{r.current?.()},[]),l=(0,b.useCallback)(e=>{r.current=e,o(e!==null)},[]),u=(0,b.useCallback)(e=>{c();let t=i.current;if(t===null){s.current.push(e);return}t.insertFieldRef(e)},[c]),d=(0,b.useCallback)(()=>{let e=i.current;if(e===null||s.current.length===0)return;let t=s.current;s.current=[];for(let n of t)e.insertFieldRef(n)},[]),f=(0,b.useMemo)(()=>({isAIChatEnabled:e,canMentionField:e&&t&&a,openAIChat:c,setOpenAIChatImpl:l,chatEditorRef:i,insertFieldRef:u,flushPendingFieldRefs:d}),[e,t,a,c,l,u,d]);return(0,Y.jsx)(xS.Provider,{value:f,children:n})}function SS(){return(0,b.useContext)(xS)}function CS(){return SS().insertFieldRef}var pse=ou([`openai-gpt-5.1`]),wS=K({name:U(),description:U(),parameters:K({type:q(`object`),properties:iu(U(),Wl()),required:G(U()).optional()}),timeoutMs:Xl([Fl().nonnegative(),Bl()]).optional()}),mse=K({id:U(),systemPrompt:U(),model:pse,tools:G(wS).optional(),description:U().optional()}),hse=K({type:q(`ai_tool_call`),id:U(),toolCallId:U(),name:U(),arguments:Wl()}),gse=ou([`max_iterations_reached`,`token_limit_reached`,`authentication_required`,`session_not_found`,`internal_error`]),_se=K({type:q(`ai_error`),id:U(),code:gse,message:U()}),vse=Ql(`type`,[K({type:q(`ai_response`),id:U(),sessionId:U(),response:U(),metadata:K({model:U().optional(),tokensUsed:Fl().optional()}).optional()}),K({type:q(`ai_streaming`),id:U(),chunk:U()}),hse,_se,K({type:q(`ai_agent_handoff`),id:U(),sessionId:U(),fromAgent:U(),toAgent:U(),reason:U().optional()})]),yse=Xl([K({type:q(`text`),text:U()}),K({type:q(`image_key`),key:U()})]);K({type:q(`ai_prompt`),id:U(),sessionId:_l().optional(),message:Xl([U(),G(yse)]),context:U().optional(),maxIterations:Fl().int().min(1).max(200).optional(),agents:G(mse).min(1)}),K({type:q(`ai_tool_result`),toolCallId:U(),result:Wl(),isError:W().optional()}),K({type:q(`ai_get_sessions`),id:U(),limit:Fl().int().min(1).max(100).optional(),cursor:K({updatedAt:U(),id:U().uuid()}).optional()}),K({type:q(`ai_set_session_name`),id:U(),sessionId:U().uuid(),name:U()}),K({type:q(`ai_get_sessions_with_messages`),id:U(),limit:Fl().int().min(1).max(100).optional(),cursor:K({updatedAt:U(),id:U().uuid()}).optional()});var bse=3e3,xse=5;function Sse(e,t){let n=(0,b.useRef)(null),[r,i]=(0,b.useState)(!1),[a,o]=(0,b.useState)(!1),[s,c]=(0,b.useState)(null),l=(0,b.useRef)(new Set),u=(0,b.useRef)(null),d=(0,b.useRef)(0),f=(0,b.useRef)(e);f.current=e;let p=(0,b.useRef)(t);p.current=t;let m=(0,b.useCallback)(e=>{if(d.current>=xse){console.warn(`Giving up on the AI connection:`,e),c(e);return}_.current()},[]),h=(0,b.useCallback)(async()=>{if(f.current){d.current+=1;try{let e=await p.current(`/ai/initialize`,`POST`,{});if(e.status===401){o(!0);return}if(e.status!==200){m(typeof e.json.message==`string`?e.json.message:`The assistant could not be started (${e.status})`);return}o(!1);let t=new WebSocket(e.json.wsUrl+`?nonce=`+encodeURIComponent(e.json.nonce));t.onopen=()=>{d.current=0,c(null),i(!0)},t.onmessage=e=>{try{let t=JSON.parse(e.data),n=vse.safeParse(t);if(!n.success){console.error(`Could not parse AI WebSocket message`,n.error,`Original message:`,t);return}for(let e of l.current)e(n.data)}catch(e){console.error(`Error processing AI WebSocket message`,e)}},t.onclose=()=>{i(!1),n.current===t&&(n.current=null,m(`Lost the connection to the assistant`))},t.onerror=()=>{console.warn(`AI WebSocket error`),t.close()},n.current=t}catch(e){m(e instanceof Error?e.message:`Could not reach the assistant`)}}},[m]),g=(0,b.useCallback)(()=>{u.current||=setTimeout(()=>{u.current=null,f.current&&h()},bse)},[h]),_=(0,b.useRef)(g);_.current=g;let v=(0,b.useCallback)(()=>{u.current&&=(clearTimeout(u.current),null),d.current=0,c(null),o(!1),h()},[h]);return(0,b.useEffect)(()=>(e&&h(),()=>{u.current&&=(clearTimeout(u.current),null),n.current&&=(n.current.close(),null)}),[e,h]),{subscribeToMessages:(0,b.useCallback)(e=>(l.current.add(e),()=>{l.current.delete(e)}),[]),send:(0,b.useCallback)(e=>n.current?.readyState===WebSocket.OPEN?(n.current.send(JSON.stringify(e)),!0):(console.warn(`AI WebSocket not open, cannot send`),!1),[]),isConnected:r,authError:a,connectionError:s,retryConnection:v}}K({type:q(`ai_prompt`),id:U(),sessionId:U().uuid().optional(),message:U(),context:U().optional(),maxIterations:Fl().int().min(1).max(200).optional(),agents:G(K({id:U(),systemPrompt:U(),model:U(),tools:G(wS).optional(),description:U().optional()})).min(1)});var TS=class extends Error{constructor(e,t){super(e),this.name=`SessionImageToPatchError`,this.availableKeys=t}},ES=b.createContext(new Proxy({},{get:()=>{throw Error(`Cannot use ValContext outside of ValProvider`)}}));function DS({children:e,client:t,config:n,valModules:r,dispatchValEvents:i,theme:a,setTheme:o}){let[s,c,l,u,d,f]=ep(t),p=`data`in s&&!!s.data&&(`data`in s&&s.data?s.data.config?.ai?.chat?.experimental?.enable===!0:!1),{subscribeToMessages:m,send:h,isConnected:g,authError:_,connectionError:v,retryConnection:y}=Sse(p,t),x=(0,b.useCallback)(async e=>{let n=await t(`/ai/sessions`,`GET`,{query:{limit:e?.limit===void 0?void 0:String(e.limit),cursor_updatedAt:e?.cursor?.updatedAt,cursor_id:e?.cursor?.id}});if(n.status===200)return n.json;throw Error(`ai/sessions failed: ${n.status??`network`}: ${n.json.message}`)},[t]),S=(0,b.useCallback)(async(e,n)=>{let r=await t(`/ai/messages`,`GET`,{path:`/${encodeURIComponent(e)}/messages`,query:{limit:n?.limit===void 0?void 0:String(n.limit),cursor_updatedAt:n?.cursor?.updatedAt,cursor_id:n?.cursor?.id}});if(r.status===200)return r.json;throw Error(`ai/sessions/messages failed: ${r.status??`network`}: ${r.json.message}`)},[t]),C=(0,b.useCallback)(async(e,n)=>{let r=await t(`/ai/sessions`,`PATCH`,{path:`/${encodeURIComponent(e)}`,body:{name:n}});if(r.status!==200)throw Error(`ai/sessions/rename failed: ${r.status??`network`}: ${r.json.message}`)},[t]),w=(0,b.useCallback)(async e=>{let n=await t(`/ai/session-image-to-patch-file`,`POST`,{body:e});if(n.status===200)return n.json;throw n.status===400?new TS(`ai/session-image-to-patch-file failed: 400: ${n.json.message}`,n.json.details?.availableKeys):new TS(`ai/session-image-to-patch-file failed: ${n.status??`network`}: ${n.json.message}`)},[t]),T=`data`in s&&s.data?s.data.config:void 0,[E,D]=(0,b.useState)();(0,b.useEffect)(()=>{if(E===void 0||E===!0){if(f){let e=setTimeout(()=>{D(f)},2e3);return()=>{clearTimeout(e)}}f||D(!1)}},[f,E]);let O=`data`in s&&s.data?s.data.baseSha:void 0,k=`data`in s&&s.data?s.data.patches:void 0,A=`data`in s&&s.data?s.data.mode:void 0,j=`data`in s&&s.data?s.data.removed:void 0,M=(0,b.useMemo)(()=>O!==void 0&&k!==void 0?{baseSha:O,patches:k,removed:j}:null,[O,k,j]),N=(0,b.useCallback)(async()=>{let e=await t(`/direct-file-upload-settings`,`POST`,{}),n=0;for(;e.status===null&&n<5;)console.warn(`Failed to get direct file upload settings, retrying...`,e),await new Promise(e=>setTimeout(e,500*(n+1))),e=await t(`/direct-file-upload-settings`,`POST`,{}),n++;return e.status===200?{status:`success`,data:e.json}:{status:`error`,error:`Could not get direct file upload settings`}},[t]),P=(0,b.useMemo)(()=>use(t,{writes:!0,uploadSettings:N}),[t,N]);(0,b.useEffect)(()=>{(A===`fs`||A===`http`)&&P.setMode(A)},[P,A]);let[F,I]=(0,b.useState)([]),L=(0,b.useRef)(new Set),ee=`data`in s&&s.data?.deployments?s.data.deployments.map(e=>`${e.deploymentId}:${e.deploymentState}:${e.updatedAt}`).join(`,`):``,te=`data`in s&&s.data?.commits?s.data.commits.map(e=>e.commitSha).join(`,`):``;(0,b.useEffect)(()=>{`data`in s&&s.data&&I(e=>s.data?.deployments&&s.data.deployments?.length>0||s.data?.commits&&s.data.commits?.length>0?sp(e,s.data?.commits||[],s.data?.deployments||[]).filter(e=>!L.current.has(e.commitSha)):e)},[ee,te]);let ne=(0,b.useCallback)(e=>{I(t=>t.filter(t=>t.commitSha!==e)),L.current.add(e)},[]),[re,ie]=(0,b.useState)(new Set);(0,b.useEffect)(()=>{`data`in s&&s.data?.commitSha&&ie(e=>{if(s.data?.commitSha===void 0||e.has(s.data.commitSha))return e;let t=new Set(e);return t.add(s.data.commitSha),t})},[s]);let[ae,oe]=(0,b.useState)({status:`not-asked`}),[se,ce]=(0,b.useState)(!1),le=(0,b.useSyncExternalStore)((0,b.useCallback)(e=>P.schemaStore.events.on(`schema:init`,e),[P]),(0,b.useCallback)(()=>P.schemaStore.all(),[P]),(0,b.useCallback)(()=>P.schemaStore.all(),[P]));(0,b.useEffect)(()=>{if(le){let e=le,t=!1;for(let n of Object.values(e))try{if(nr(n)){t=!0;break}}catch(e){console.error(`Val: could not tell whether a schema needs remote files. Remote uploads may be unavailable.`,e)}ce(t)}},[le]),(0,b.useEffect)(()=>{let e=0;function n(){e++,ae.status!==`ready`&&e<10&&t(`/remote/settings`,`GET`,{}).then(e=>{e.status===200?oe({status:`ready`,coreVersion:e.json.coreVersion,buckets:e.json.remoteFileBuckets.map(e=>e.bucket),publicProjectId:e.json.publicProjectId}):(`errorCode`in e.json&&e.json.errorCode?oe({status:`inactive`,reason:e.json.errorCode,message:e.json.message}):oe({status:`inactive`,reason:`unknown-error`,message:`An unknown error has occurred`}),setTimeout(n,5e3))}).catch(e=>{console.error(`Error getting remote settings`,e),oe({status:`inactive`,reason:`unknown-error`,message:`An unknown error has occurred`}),setTimeout(n,5e3)})}se&&(oe({status:`loading`}),n())},[se]);let[ue,de]=(0,b.useState)({type:`not-asked`}),fe=(0,b.useSyncExternalStore)((0,b.useCallback)(e=>P.patchStore.events.on(`patch:chain`,e),[P]),(0,b.useCallback)(()=>P.patchStore.pendingPatchIds().length,[P]),(0,b.useCallback)(()=>P.patchStore.pendingPatchIds().length,[P]));(0,b.useEffect)(()=>{let e=e=>{fe>0&&(e.preventDefault(),e.returnValue=``)};return window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`beforeunload`,e)}},[fe]);let{state:pe,retry:me}=Dse(t,l,`data`in s&&s.data?s.data.mode:`unknown`,f,T?.project);return(0,Y.jsx)(ES.Provider,{value:{client:t,publishSummaryState:ue,setPublishSummaryState:de,profileId:`data`in s&&s.data?s.data.profileId:null,mode:`data`in s&&s.data?s.data.mode:`unknown`,profileAuthError:pe.status===`auth-error`?pe.error:null,profilesError:pe.status===`error`?{message:pe.error,willRetry:pe.willRetry}:null,retryProfiles:me,serviceUnavailable:E,baseSha:O,observedCommitShas:re,deployments:F,dismissDeployment:ne,authenticationState:l,config:T,profiles:`data`in pe&&pe.data?pe.data:{},remoteFiles:ae,subscribeToWsMessages:m,sendWsMessage:h,isWsConnected:g,aiAuthError:_,aiConnectionError:v,retryAiConnection:y,aiGetSessions:x,aiGetSessionMessages:S,aiSetSessionName:C,aiSessionImagesToPatchFile:w},children:(0,Y.jsx)(xg,{children:(0,Y.jsx)(fse,{isAIChatEnabled:p,isAIChatOnline:p&&g,children:a!==void 0&&o?(0,Y.jsx)(hae,{theme:a,setTheme:o,config:T,children:(0,Y.jsx)(Uae,{system:P,valModules:r??null,stat:M,children:(0,Y.jsx)(Bae,{children:(0,Y.jsx)(Use,{children:(0,Y.jsx)(gae,{children:(0,Y.jsx)(dse,{remoteFiles:ae,children:(0,Y.jsxs)(Cae,{getDirectFileUploadSettings:N,config:T,children:[(0,Y.jsx)(Gae,{enabled:i}),(0,Y.jsx)(yae,{}),e,(0,Y.jsx)(Cse,{})]})})})})})})}):e})})})}function Cse(){return OS().schema===`out-of-date`?(0,Y.jsx)(_ae,{}):null}function OS(){let e=Oy(),t=(0,b.useCallback)(t=>e===null?()=>{}:e.system.status.events.on(`status:change`,t),[e]),n=(0,b.useCallback)(()=>e===null?wse:e.system.status.current(),[e]);return(0,b.useSyncExternalStore)(t,n,n)}var wse={errors:[],networkErrorSince:null,schemaError:null,schema:`current`},Tse=5,Ese=1e3;function Dse(e,t,n,r,i){let[a,o]=(0,b.useState)({status:`not-asked`}),s=(0,b.useRef)(0),c=(0,b.useRef)(null),l=(0,b.useCallback)(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null)},[]);(0,b.useEffect)(()=>l,[l]);let u=(0,b.useRef)(()=>void 0),d=(0,b.useCallback)(async()=>{s.current+=1,o(e=>({status:`loading`,data:`data`in e?e.data:void 0}));let t=await e(`/profiles`,`GET`,{});if(t.status===200){let e={};for(let n of t.json.profiles)e[n.profileId]={fullName:n.fullName,email:n.email,avatar:n.avatar};s.current=0,o({status:`done`,data:e})}else if(n===`fs`&&t.status===401){let e=`message`in t.json&&typeof t.json.message==`string`?t.json.message:`Could not authenticate while getting profiles`;o(t=>({status:`auth-error`,error:e,data:`data`in t?t.data:void 0}))}else{let e=s.current<Tse;if(e||console.error(`Could not get profiles`,t.json),o(n=>({status:`error`,error:Jf(t.json),willRetry:e,data:`data`in n?n.data:void 0})),e){let e=Ese*2**(s.current-1);c.current=setTimeout(()=>{c.current=null,u.current()},e)}}},[e,n]);u.current=()=>void d();let f=(0,b.useCallback)(()=>{l(),s.current=0,u.current()},[l]);return(0,b.useEffect)(()=>{t!==`not-asked`&&t!==`loading`&&(n===`fs`||t===`authorized`)&&(n===`fs`&&!i||r||a.status===`not-asked`&&d())},[t,d,n,a.status,r,i]),{state:a,retry:f}}function kS(){let{authenticationState:e}=(0,b.useContext)(ES);return e}function Ose(){let{serviceUnavailable:e}=(0,b.useContext)(ES);return e===!0?`service-unavailable`:`connected`}function AS(){let e=Oy();return{addModuleFilePatch:(0,b.useCallback)((t,n,r)=>{if(e===null){console.error(`Val: cannot write patch: no store system is mounted`);return}e.system.patchStore.createPatch(t,n).then(e=>{e.status!==`created`&&console.error(`Val: could not write patch`,e.message)})},[e])}}function jS(){let e=Oy();return{deletePatches:(0,b.useCallback)(t=>{if(e===null){console.error(`Val: cannot discard: no store system is mounted`);return}for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100);e.system.discard(r).then(e=>{e.status===`failed`&&console.error(`Val: could not discard patches`,e.message)})}},[e])}}function kse(){let{subscribeToWsMessages:e,sendWsMessage:t,isWsConnected:n,aiAuthError:r,aiGetSessions:i,aiGetSessionMessages:a,aiSetSessionName:o,aiSessionImagesToPatchFile:s}=(0,b.useContext)(ES);return{subscribeToWsMessages:e,sendWsMessage:t,isWsConnected:n,aiAuthError:r,aiGetSessions:i,aiGetSessionMessages:a,aiSetSessionName:o,aiSessionImagesToPatchFile:s}}function MS(){let{deployments:e,dismissDeployment:t,observedCommitShas:n}=(0,b.useContext)(ES);return{deployments:e,dismissDeployment:t,observedCommitShas:n}}function NS(){let e=Oy(),t=PS(),[n,r]=(0,b.useState)({status:`not-asked`}),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(e===null)return;let t=!1;return e.system.getPatchSets().then(e=>{if(t)return;let n=JSON.stringify(e);n!==i.current&&(i.current=n,r({status:`success`,data:e}))}).catch(e=>{t||r({status:`error`,error:e instanceof Error?e.message:String(e)})}),()=>{t=!0}},[e,t]),n}function PS(){let e=Oy(),t=(0,b.useCallback)(t=>e===null?()=>{}:e.system.patchStore.events.on(`patch:chain`,t),[e]),n=(0,b.useCallback)(()=>e===null?0:e.system.patchStore.chainVersion(),[e]);return(0,b.useSyncExternalStore)(t,n,n)}function Ase(){let e=Oy(),[t,n]=(0,b.useState)(0);return(0,b.useEffect)(()=>{if(e!==null)return e.system.patchStore.events.on(`patch:head`,()=>{n(e=>e+1)})},[e]),t}function FS(){let e=Oy(),t=PS();return(0,b.useMemo)(()=>{let t=new Set;if(e===null)return t;let n=e.system.patchStore.publishedPatchIds();for(let r of e.system.patchStore.allRecords())(r.appliedAt||n.has(r.patchId))&&t.add(r.patchId);return t},[e,t])}function jse(){let e=Oy(),t=PS();return(0,b.useMemo)(()=>{if(e===null)return[];let t=[],n=new Set;for(let r of e.system.patchStore.allRecords()){let e=r.appliedAt?.commitSha;e!==void 0&&!n.has(e)&&(n.add(e),t.unshift(e))}return t},[e,t])}function IS(){let e=Oy(),t=PS();return(0,b.useMemo)(()=>{if(e===null)return[];let t=e.system.patchStore;return t.allRecords().map(e=>e.patchId).filter(e=>!t.isPending(e))},[e,t])}function LS(){let e=Oy(),t=PS();return(0,b.useMemo)(()=>e===null?[]:e.system.patchStore.pendingPatchIds(),[e,t])}function Mse(){let e=Oy();PS();let[t,n]=(0,b.useState)(!1),r=t||e!==null&&e.system.patchStore.chainSettled();return(0,b.useEffect)(()=>{r&&n(!0)},[r]),r}function Nse(){let e=Oy();return(0,b.useCallback)(()=>e===null?{total:0,settled:0,unfetched:[],unapplied:[],failed:[],statSeen:!1}:e.system.patchStore.chainProgress(),[e])}function Pse(){let e=Oy(),[t,n]=(0,b.useState)(null);return(0,b.useEffect)(()=>{if(e!==null)return e.system.patchStore.events.on(`patch:fetch-failed`,e=>{n(e.message)})},[e]),t}function RS(){let e=Oy(),t=PS();return(0,b.useMemo)(()=>e===null?[]:e.system.patchStore.allRecords().map(e=>e.patchId),[e,t])}function zS(e){let t=Oy(),n=PS();return(0,b.useMemo)(()=>{if(t===null)return null;let[n,r]=V.splitModuleFilePathAndModulePath(e),i=t.system.patchStore,a=[];for(let e of i.allRecords())e.moduleFilePath===n&&(!r||e.patch.some(e=>V.patchPathToModulePath(e.path)===r))&&a.push(BS(e,i.isPending(e.patchId)));return a},[t,n,e])}function Fse(e){let t=Oy(),n=PS();return(0,b.useMemo)(()=>{if(t===null)return[];let n=t.system.patchStore;return n.allRecords().filter(t=>t.moduleFilePath===e).map(e=>BS(e,n.isPending(e.patchId)))},[t,n,e])}function BS(e,t){return{moduleFilePath:e.moduleFilePath,patch:e.patch,isPending:t,createdAt:e.createdAt??``,authorId:e.authorId??null,isCommitted:e.appliedAt??void 0}}function VS(){let{mode:e}=(0,b.useContext)(ES);return e}function Ise(){let e=Oy(),t=(0,b.useCallback)(t=>e===null?()=>{}:e.system.host.events.on(`host:receive`,t),[e]),n=(0,b.useCallback)(()=>e===null?null:e.system.host.initializedAt(),[e]);return(0,b.useSyncExternalStore)(t,n,n)}function Lse(){let e=Oy(),t=(0,b.useCallback)(t=>e===null?()=>{}:e.system.sourceStore.events.on(`source:change`,t),[e]),n=(0,b.useCallback)(()=>e===null?0:e.system.sourceStore.sourcesVersion(),[e]);return(0,b.useSyncExternalStore)(t,n,n)}var Rse=Xl([K({type:q(`not-asked`),isGenerating:W().optional()}),K({type:q(`manual`).or(q(`ai`)),text:U(),patchIds:G(U()).nullable(),isGenerating:W()})]);function HS(){let{client:e,publishSummaryState:t,setPublishSummaryState:n,config:r}=(0,b.useContext)(ES),i=Oy(),a=RS(),{patchErrors:o}=qS(),s=(0,b.useMemo)(()=>o?Object.values(o).some(e=>Object.keys(e).length>0):!1,[o]),[c,l]=(0,b.useState)(!1);(0,b.useEffect)(()=>{r?.ai?.commitMessages?.disabled===void 0||r.ai.commitMessages.disabled===!1?l(!0):l(!1)},[r]),(0,b.useEffect)(()=>{if(t.type===`not-asked`){let e=Bse(r?.project);e&&e.type!==`not-asked`&&a.length>0&&n(e)}},[t,r,n]);let u=(0,b.useCallback)(async()=>{if(a===null)return{type:`error`,message:`Empty patch set`};if(`isGenerating`in t&&t.isGenerating)return{type:`error`,message:`Already generating summary`};n(e=>({...e,isGenerating:!0}));try{let t=await e(`/commit-summary`,`GET`,{query:{patch_id:a}});return t.status===200?t.json.commitSummary?{type:`ai`,text:t.json.commitSummary}:{type:`error`,message:`Commit summary could not be generated`}:{type:`error`,message:t.json.message}}finally{n(e=>({...e,isGenerating:!1}))}},[e,a,t]),[d,f]=(0,b.useState)(!1),p=(0,b.useCallback)(async e=>a===null?{status:`error`,message:`No changes to publish`}:d?{status:`error`,message:`Already publishing`}:i===null?{status:`error`,message:`No store system is mounted`}:(f(!0),(async()=>{let t=await i.system.publish(a,e);return t.status===`refused`&&t.reason===`chain-moved`?i.system.publish(a,e):t})().then(e=>{if(e.status===`published`)Vse(r?.project),n(e=>({type:`not-asked`,isGenerating:e.isGenerating}));else if(e.status===`refused`){let t=Xf(e);i.system.status.reportError(t.message,t.details)}else e.status===`failed`&&i.system.status.reportError(`Could not publish`,e.patchErrors?Object.entries(e.patchErrors).map(([e,t])=>`${e}: ${t}`).join(`
133
133
  `):e.message);return e}).finally(()=>{f(!1)})),[i,a,d,r?.project,n]),m=(0,b.useCallback)(e=>{n(t=>{let n;return n=e.type===`not-asked`?{type:`not-asked`,isGenerating:t.isGenerating}:{type:e.type,text:e.text,patchIds:a,isGenerating:!!t.isGenerating},zse(n,r?.project),n})},[a,n,r?.project]);return{publish:p,publishDisabled:d||s===!0,isPublishing:d,generateSummary:u,canGenerate:c,summary:t,setSummary:m}}function zse(e,t){try{localStorage.setItem(`val-publish-summary-`+(t||`unknown`),JSON.stringify(e))}catch(e){console.error(`Error setting publish summary in local storage`,e)}return e}function Bse(e){try{let t=localStorage.getItem(`val-publish-summary-`+(e||`unknown`));if(t){let e=Rse.safeParse(JSON.parse(t));if(e.success)return e.data;console.warn(`Error parsing publish summary from local storage`,e.error)}}catch(e){console.error(`Error getting publish summary from local storage`,e)}return null}function Vse(e){try{localStorage.removeItem(`val-publish-summary-`+(e||`unknown`))}catch(e){console.error(`Error deleting publish summary from local storage`,e)}}function US(){let{profileId:e,profiles:t,mode:n}=(0,b.useContext)(ES);if(e)return t[e]??null;if(n===`fs`){let[e]=Object.values(t);return e??null}return null}var Hse=700,WS=(0,b.createContext)({autoPublish:!1,setAutoPublish:()=>{}}),GS=`val-auto-publish`;function Use({children:e}){let t=Oy(),n=VS(),[r,i]=(0,b.useState)(()=>{try{return localStorage.getItem(GS)===`true`}catch{return!1}}),a=IS(),o=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!r||n!==`fs`||t===null||a.length===0)return;let e=a.join(`,`);if(o.current===e)return;let i=!1,s=setTimeout(()=>{t.system.publish(a,void 0,{exact:!0}).then(n=>{if(!i){if(n.status===`failed`){o.current=e,t.system.status.reportError(`Changes could not be saved to disk.`,n.message);return}o.current=null,n.status===`published`&&t.system.patchStore.allRecords().length===0&&t.system.validateEverything()}})},Hse);return()=>{i=!0,clearTimeout(s)}},[r,n,t,a]);let s=(0,b.useMemo)(()=>({autoPublish:r,setAutoPublish:e=>{i(e);try{localStorage.setItem(GS,e.toString())}catch{}}}),[r]);return(0,Y.jsx)(WS.Provider,{value:s,children:e})}function KS(){return(0,b.useContext)(WS)}function Wse(){let e=Oy();return{globalTransientErrors:OS().errors,removeGlobalTransientErrors:t=>{e?.system.status.dismissErrors(t)}}}function Gse(){let{remoteFiles:e,profileAuthError:t}=(0,b.useContext)(ES),n=OS();return n.networkErrorSince===null?n.schemaError===null?t===null?e.status===`inactive`?{type:`remote-files-error`,error:e.message,reason:e.reason}:null:{type:`profiles-auth-error`,error:t}:{type:`schema-error`,schemaError:n.schemaError.length}:{type:`network-error`,networkError:n.networkErrorSince}}function qS(){let e=Oy(),t=OS();return(0,b.useMemo)(()=>e===null?{patchErrors:void 0}:{patchErrors:e.system.patchErrors()},[e,t])}function Kse(){let{aiAuthError:e,aiConnectionError:t,retryAiConnection:n}=(0,b.useContext)(ES);return(0,b.useMemo)(()=>e||t===null?null:{message:t,retry:n},[e,t,n])}function JS(){let{profiles:e}=(0,b.useContext)(ES);return e}function qse(){let{profilesError:e,retryProfiles:t}=(0,b.useContext)(ES);return(0,b.useMemo)(()=>e===null||e.willRetry?null:{message:e.message,retry:t},[e,t])}function YS(e,t){let n=Oy(),r=Ise(),i=Lse(),a=(0,b.useMemo)(()=>n===null?null:(e??[]).map(e=>n.system.sourceStore.moduleSource(e)),[n,i,e]);return(0,b.useMemo)(()=>{if(r===null)return{status:`loading`};if(!a)return{status:`not-found`,data:[],notFoundPaths:e||[]};let n=[],i=[],o=[];if(!e||e.length===0)return{status:`success`,data:[]};for(let r=0;r<e.length;r++){let s=e?.[r];if(s===void 0)throw Error(`While resolving shallow modules at paths, we unexpectedly got an undefined module file path`);let c=a?.[r];if(c===void 0){o.push(s);continue}let l=Jse(s,``,t,c);l.status===`success`?n.push(l.data):i.push({moduleFilePath:s,message:l.error})}return o.length>0?{status:`not-found`,data:n,notFoundPaths:o}:i.length>0?{status:`error`,data:n,errors:i}:{status:`success`,data:n}},[a,t,r,e])}function XS(){let e=Yy();return(0,b.useMemo)(()=>{if(e.status===`success`){let t=null;for(let n in e.data){let e=Af(n);if(e){if(t===null)t=e;else if(t!==e)return{status:`error`,error:`Found multiple different src folders in the same project`}}}return{status:`success`,data:t}}return e},[e])}function Jse(e,t,n,r){if(r===null)return{status:`success`,data:null};let i=n;if(i===`object`||i===`record`){if(typeof r!=`object`)return{status:`error`,error:`Expected object, got ${typeof r}`};if(qf(r))return{status:`error`,error:`Expected object, got array`};let n={};for(let i of Object.keys(r))n[i]=Ny(e,t,i);return{status:`success`,data:n}}if(i===`array`){if(typeof r!=`object`||!qf(r))return{status:`error`,error:`Expected array, got ${typeof r}`};let n=[];for(let i=0;i<r.length;i++)n.push(Ny(e,t,i));return{status:`success`,data:n}}if(i===`boolean`)return typeof r!=`boolean`&&r!==null?{status:`error`,error:`Expected boolean, got ${typeof r}`}:{status:`success`,data:r};if(i===`number`)return typeof r!=`number`&&r!==null?{status:`error`,error:`Expected number, got ${typeof r}`}:{status:`success`,data:r};if(i===`richtext`)return typeof r!=`object`||!qf(r)?{status:`error`,error:`Expected richtext (i.e. array), got ${typeof r}`}:{status:`success`,data:r};if(i===`date`||i===`dateTime`||i===`color`||i===`string`||i===`literal`)return typeof r!=`string`&&r!==null?{status:`error`,error:`Expected string, got ${typeof r}: ${JSON.stringify(r)}`}:{status:`success`,data:r};if(i===`file`||i===`image`)return typeof r!=`object`||!(`path`in r)||typeof r.path!=`string`?{status:`error`,error:`Expected object with a path property, got ${typeof r}`}:{status:`success`,data:r};if(i===`keyOf`||i===`route`)return typeof r==`string`?{status:`success`,data:r}:{status:`error`,error:`Expected string, got ${typeof r}`};if(i===`union`){if(typeof r==`string`)return{status:`success`,data:r};if(typeof r!=`object`)return{status:`error`,error:`Expected object, got ${typeof r}`};if(qf(r))return{status:`error`,error:`Expected object, got array`};let n={};for(let i of Object.keys(r))n[i]=Ny(e,t,i);return{status:`success`,data:n}}return{status:`error`,error:`Unknown schema type: ${i}`}}function ZS(e){let[t,n]=(0,b.useState)(()=>QS());return(0,b.useEffect)(()=>{if(!e)return;let t=window.visualViewport,r=()=>n(QS());return r(),t&&(t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r)),window.addEventListener(`orientationchange`,r),()=>{t&&(t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)),window.removeEventListener(`orientationchange`,r)}},[e]),t}var Yse=.75;function Xse(e){let{viewportHeight:t,viewportOffsetTop:n,windowHeight:r}=e,i=t??r,a=n??0;return{height:i,offsetTop:a,keyboardInset:Math.max(0,r-(a+i)),isKeyboardOpen:i<r*Yse}}function QS(){return typeof window>`u`?{height:0,offsetTop:0,keyboardInset:0,isKeyboardOpen:!1}:Xse({viewportHeight:window.visualViewport?.height,viewportOffsetTop:window.visualViewport?.offsetTop,windowHeight:window.innerHeight})}function $S(e){(0,b.useEffect)(()=>{if(!e)return;let{overflow:t,touchAction:n}=document.body.style;return document.body.style.overflow=`hidden`,document.body.style.touchAction=`none`,()=>{document.body.style.overflow=t,document.body.style.touchAction=n}},[e])}function eC({side:e,width:t,title:n,mobileVariant:r,breakpoint:i,onClose:a,headerAction:o,subheader:s,sticky:c,footer:l,hidden:u=!1,children:d}){let f=i===`mobile`&&!u,p=(0,b.useRef)(null),m=ZS(f);return $S(f),(0,b.useEffect)(()=>{if(u)return;let e=e=>{e.key===`Escape`&&a()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a,u]),(0,Y.jsxs)(Y.Fragment,{children:[!u&&(0,Y.jsx)(`div`,{onClick:a,"aria-hidden":!0,className:X(`absolute inset-0 z-window`,f?`bg-black/40`:`bg-transparent`)}),(0,Y.jsxs)(`div`,{ref:p,role:`dialog`,"aria-label":n,style:f?r===`sheet`?{top:m.offsetTop,height:m.height}:{bottom:m.keyboardInset,maxHeight:m.height*.85}:{width:t},className:X(`absolute z-full flex flex-col`,`bg-bg-float border border-border-float shadow-lg`,u&&`hidden`,f?r===`sheet`?`fixed left-0 w-[min(20rem,88vw)] border-l-0 rounded-r-lg`:`fixed inset-x-0 rounded-t-xl border-b-0`:X(`top-16 bottom-14 rounded-lg`,e===`right`?`right-3`:i===`desktop`?`left-[4.75rem]`:`left-3`)),children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0 h-11 pl-4 pr-2 border-b border-border-float`,children:[(0,Y.jsx)(`span`,{className:`text-[0.8125rem] font-semibold tracking-tight truncate`,children:n}),(0,Y.jsxs)(`div`,{className:`ml-auto flex items-center gap-1`,children:[o,(0,Y.jsx)(`button`,{type:`button`,onClick:a,"aria-label":`Close ${n}`,className:`grid place-items-center w-7 h-7 rounded-md text-fg-secondary hover:bg-bg-float-raised hover:text-fg-primary`,children:(0,Y.jsx)(my,{size:15})})]})]}),s!==void 0&&(0,Y.jsx)(`div`,{className:`shrink-0 px-2 py-2 border-b border-border-float`,children:s}),c!==void 0&&(0,Y.jsx)(`div`,{className:`shrink-0 px-3 py-2 border-b border-border-float`,children:c}),(0,Y.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto overscroll-contain scrollbar-slim`,children:d}),l!==void 0&&(0,Y.jsx)(`div`,{className:`shrink-0 border-t border-border-float`,children:l})]})]})}function tC({children:e,className:t,divided:n}){return(0,Y.jsx)(`div`,{className:X(`px-4 pt-4 pb-1.5 text-[0.6875rem] font-semibold uppercase tracking-wider text-fg-secondary-alt`,n&&`mt-3 border-t border-border-float`,t),children:e})}function nC({children:e}){return(0,Y.jsx)(`div`,{className:`px-4 py-6 text-xs text-fg-secondary-alt`,children:e})}function Zse({breakpoint:e,hidden:t,onClose:n,children:r}){return(0,Y.jsx)(eC,{side:`right`,width:420,title:`AI assistant`,mobileVariant:`bottom-sheet`,breakpoint:e,hidden:t,onClose:n,children:(0,Y.jsx)(`div`,{className:`h-full overflow-hidden`,children:r})})}function rC({value:e,onChange:t,placeholder:n}){return(0,Y.jsxs)(`div`,{className:`relative`,children:[(0,Y.jsx)(zie,{size:14,"aria-hidden":!0,className:`absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-secondary-alt`}),(0,Y.jsx)(`input`,{type:`search`,value:e,onChange:e=>t(e.target.value),placeholder:n,"aria-label":n,className:X(`w-full h-8 pl-8 pr-2 rounded-md text-xs`,`bg-bg-float-raised border border-transparent text-fg-primary`,`placeholder:text-fg-secondary-alt`,`focus:outline-none focus:border-border-brand-primary`)})]})}function iC({depth:e=0,selected:t,onClick:n,leading:r,label:i,meta:a,errorCount:o,hasDraft:s,trailing:c,action:l,expanded:u,title:d}){let f=o!==void 0&&o>0,p=[s?`Unpublished changes`:null,f?`${o} validation error${o===1?``:`s`}`:null].filter(e=>e!==null),m=(0,b.useId)();return(0,Y.jsxs)(`div`,{className:`group/row flex items-center pr-2`,style:{paddingLeft:8+e*12},children:[(0,Y.jsxs)(`button`,{type:`button`,onClick:n,title:d,"aria-current":t?`true`:void 0,"aria-expanded":u,"aria-describedby":p.length>0?m:void 0,className:X(`group flex items-center gap-1.5 min-w-0 flex-1 h-7 px-1.5 rounded-md text-xs text-left`,t?`bg-bg-float-raised text-fg-primary font-medium`:`text-fg-secondary hover:bg-bg-float-raised hover:text-fg-primary`),children:[r!==void 0&&(0,Y.jsx)(`span`,{className:`shrink-0 grid place-items-center w-3.5 h-3.5`,children:r}),(0,Y.jsx)(`span`,{className:`truncate`,children:i}),a!==void 0&&(0,Y.jsx)(`span`,{className:`truncate text-fg-secondary-alt font-normal`,children:a}),p.length>0&&(0,Y.jsx)(`span`,{id:m,hidden:!0,children:p.join(`, `)}),(0,Y.jsxs)(`span`,{"aria-hidden":!0,className:`ml-auto flex items-center gap-1.5 shrink-0`,children:[s&&(0,Y.jsx)(`span`,{title:`Unpublished changes`,className:`w-1.5 h-1.5 rounded-full bg-fg-secondary`}),f&&(0,Y.jsx)(`span`,{title:`${o} validation error${o===1?``:`s`}`,className:`min-w-[1rem] h-4 px-1 grid place-items-center rounded bg-bg-error-primary text-fg-error-primary text-[0.625rem] font-semibold tabular-nums`,children:o}),c]})]}),l]})}function aC({rows:e=8}){return(0,Y.jsx)(`div`,{className:`py-2`,"aria-busy":`true`,"aria-label":`Loading`,children:Array.from({length:e},(e,t)=>(0,Y.jsx)(`div`,{className:`flex items-center h-7 px-3.5`,children:(0,Y.jsx)(`span`,{className:`h-2.5 rounded bg-bg-float-raised animate-pulse`,style:{width:`${45+t*17%45}%`}})},t))})}function oC({message:e,onRetry:t}){return(0,Y.jsxs)(`div`,{className:`flex gap-2.5 px-4 py-4`,children:[(0,Y.jsx)(ly,{size:14,className:`mt-0.5 shrink-0 text-fg-error-on-surface`}),(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`p`,{className:`text-xs text-fg-primary`,children:e}),t&&(0,Y.jsx)(`button`,{type:`button`,onClick:t,className:`mt-2 h-7 px-2 rounded-md text-xs text-fg-secondary border border-border-float hover:bg-bg-float-raised hover:text-fg-primary`,children:`Try again`})]})]})}function Qse(e){let t=[],n=new Map([]);for(let r of e){let e=r.moduleFilePath.split(`/`).filter(Boolean).slice(0,-1),i=t,a=``;for(let t of e){a=`${a}/${t}`;let e=n.get(a);e||(e={kind:`directory`,id:a,name:t,children:[]},n.set(a,e),i.push(e)),i=e.children}i.push({kind:`module`,id:r.id,module:r})}return t}function sC(e){return[...e].sort((e,t)=>{if(e.kind!==t.kind)return e.kind===`directory`?-1:1;let n=e.kind===`directory`?e.name:e.module.name,r=t.kind===`directory`?t.name:t.module.name;return n.localeCompare(r)}).map(e=>e.kind===`directory`?{...e,children:sC(e.children)}:e)}function cC(e){return e.flatMap(e=>e.kind===`directory`?[e.id,...cC(e.children)]:[])}function $se(e,t){if(t===null)return[];let n=(e,r)=>{for(let i of e){if(i.id===t)return r;if(i.kind===`directory`){let e=n(i.children,[...r,i.id]);if(e)return e}}return null};return n(e,[])??[]}function ece({breakpoint:e,data:t,selectedId:n,onSelect:r,onClose:i,navSwitcher:a,isLoading:o,loadError:s,onRetryLoad:c}){let[l,u]=(0,b.useState)(``),d=(0,b.useMemo)(()=>sC(Qse(t)),[t]),[f,p]=(0,b.useState)(()=>new Set),m=(0,b.useMemo)(()=>$se(d,n).join(`\0`),[d,n]);(0,b.useEffect)(()=>{if(!m)return;let e=m.split(`\0`);p(t=>{if(!e.some(e=>t.has(e)))return t;let n=new Set(t);for(let t of e)n.delete(t);return n})},[m]);let h=e=>p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),g=(0,b.useMemo)(()=>{if(!l)return d;let e=l.toLowerCase(),t=n=>n.flatMap(n=>{if(n.kind===`module`)return n.module.name.toLowerCase().includes(e)||n.module.moduleFilePath.toLowerCase().includes(e)?[n]:[];let r=t(n.children);return r.length===0&&!n.name.toLowerCase().includes(e)?[]:[{...n,children:r}]});return t(d)},[d,l]),_=(0,b.useMemo)(()=>l?new Set(cC(g)):null,[l,g]),v=t.length,y=(e,t)=>{if(e.kind===`module`)return(0,Y.jsx)(iC,{depth:t,selected:n===e.id,title:e.module.moduleFilePath,onClick:()=>r(e.module),leading:(0,Y.jsx)(av,{size:13,className:`text-fg-secondary-alt`}),label:e.module.name,errorCount:e.module.errorCount,hasDraft:e.module.hasDraft},e.id);let i=_?_.has(e.id):!f.has(e.id);return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(iC,{depth:t,title:e.id,onClick:()=>{_||h(e.id)},leading:(0,Y.jsx)(`span`,{className:`text-fg-secondary-alt`,children:i?(0,Y.jsx)(cv,{size:13}):(0,Y.jsx)(uv,{size:13})}),label:e.name,errorCount:i?void 0:lC(e),hasDraft:i?void 0:uC(e)}),i&&e.children.map(e=>y(e,t+1))]},e.id)};return(0,Y.jsx)(eC,{side:`left`,width:300,title:`Data`,mobileVariant:`sheet`,breakpoint:e,onClose:i,subheader:a,sticky:o||s?void 0:(0,Y.jsx)(rC,{value:l,onChange:u,placeholder:`Filter data files…`}),children:(0,Y.jsx)(`div`,{className:`py-2`,children:o?(0,Y.jsx)(aC,{}):s?(0,Y.jsx)(oC,{message:s,onRetry:c}):v===0?(0,Y.jsx)(nC,{children:`No data files yet.`}):g.length===0?(0,Y.jsx)(nC,{children:`No data files match this filter.`}):g.map(e=>y(e,0))})})}function lC(e){let t=e.kind===`module`?e.module.errorCount??0:e.children.reduce((e,t)=>e+(lC(t)??0),0);return t===0?void 0:t}function uC(e){return(e.kind===`module`?e.module.hasDraft===!0:e.children.some(e=>uC(e)===!0))?!0:void 0}var tce=1048;function nce(){return(0,Y.jsx)(`div`,{className:`grid place-items-center min-h-[60svh] text-center`,children:(0,Y.jsxs)(`div`,{className:`max-w-xs`,children:[(0,Y.jsx)(Tv,{size:28,className:`mx-auto mb-4 text-fg-secondary-alt`,strokeWidth:1.25}),(0,Y.jsx)(`h2`,{className:`text-[0.9375rem] font-medium tracking-tight`,children:`No item selected`}),(0,Y.jsx)(`p`,{className:`mt-2 text-xs text-fg-secondary-alt leading-relaxed`,children:`Pick a page, a media file or a data item from the navigation to start editing.`})]})})}function rce({title:e,urlPath:t,sourcePath:n,isDevMode:r,hasDraft:i}){return(0,Y.jsxs)(`article`,{children:[(0,Y.jsxs)(`header`,{className:`pb-7 mb-8 border-b border-border-float`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 mb-2.5`,children:[(0,Y.jsx)(`span`,{className:`inline-flex items-center h-5 px-1.5 rounded bg-bg-float-raised font-mono text-[0.6875rem] text-fg-secondary-alt`,children:t}),i&&(0,Y.jsx)(`span`,{className:`inline-flex items-center h-5 px-1.5 rounded bg-bg-float-raised text-fg-primary text-[0.625rem] font-medium uppercase tracking-wide`,children:`Draft`})]}),(0,Y.jsx)(`h1`,{className:`text-[1.75rem] leading-tight font-semibold tracking-[-0.02em]`,children:e}),r&&n&&(0,Y.jsx)(`p`,{className:`mt-2.5 font-mono text-[0.6875rem] text-fg-secondary-alt`,children:n})]}),(0,Y.jsxs)(`div`,{className:`space-y-8`,children:[(0,Y.jsx)(dC,{label:`Title`,hint:`Shown in the browser tab and search results`,children:(0,Y.jsx)(ice,{value:`Build better websites`})}),(0,Y.jsx)(dC,{label:`Meta description`,children:(0,Y.jsx)(ace,{value:`Val is a Git-based CMS for developers. Content lives in your repository as TypeScript, validated by the same types your app uses.`})}),(0,Y.jsx)(dC,{label:`Hero image`,children:(0,Y.jsxs)(`div`,{className:`flex gap-3`,children:[(0,Y.jsx)(`div`,{className:`grid place-items-center w-40 h-24 rounded-md bg-bg-float-raised border border-border-float text-fg-secondary-alt`,children:(0,Y.jsx)(Nv,{size:18,strokeWidth:1.5})}),(0,Y.jsxs)(`div`,{className:`text-xs text-fg-secondary-alt space-y-1 pt-1`,children:[(0,Y.jsx)(`p`,{className:`font-mono`,children:`/public/val/hero_a1b2c.png`}),(0,Y.jsx)(`p`,{children:`2400 × 1260 · image/png`})]})]})}),(0,Y.jsx)(dC,{label:`Body`,children:(0,Y.jsxs)(`div`,{className:`rounded-md border border-border-float bg-bg-surface`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 px-2 h-8 border-b border-border-float`,children:[[`B`,`I`,`H2`,`H3`].map(e=>(0,Y.jsx)(`span`,{className:`grid place-items-center w-6 h-6 rounded text-[0.6875rem] text-fg-secondary`,children:e},e)),(0,Y.jsx)(`span`,{className:`grid place-items-center w-6 h-6 rounded text-fg-secondary`,children:(0,Y.jsx)(Lv,{size:12})})]}),(0,Y.jsxs)(`div`,{className:`px-3 py-3 space-y-3 text-[0.9375rem] text-fg-primary leading-relaxed`,children:[(0,Y.jsx)(`p`,{children:`Content lives next to your code. Every change is a patch, every patch is reviewable, and publishing is a commit.`}),(0,Y.jsx)(`p`,{className:`text-fg-secondary`,children:`Editors get a real editor. Developers get types, validation and a diff.`})]})]})}),(0,Y.jsx)(dC,{label:`Sections`,hint:`4 items`,children:(0,Y.jsx)(`ul`,{className:`space-y-1.5`,children:[`Hero`,`Features`,`Logos`,`Call to action`].map(e=>(0,Y.jsxs)(`li`,{className:`flex items-center gap-2 h-10 px-2.5 rounded-md border border-border-float bg-bg-surface`,children:[(0,Y.jsx)(jv,{size:14,className:`shrink-0 text-fg-secondary-alt`}),(0,Y.jsx)(`span`,{className:`text-[0.8125rem]`,children:e}),(0,Y.jsx)(cv,{size:14,className:`ml-auto shrink-0 text-fg-secondary-alt`})]},e))})})]})]})}function dC({label:e,hint:t,children:n}){return(0,Y.jsxs)(`section`,{children:[(0,Y.jsxs)(`div`,{className:`flex items-baseline gap-2 mb-2`,children:[(0,Y.jsx)(`h2`,{className:`text-[0.8125rem] font-medium leading-none text-fg-primary`,children:e}),t&&(0,Y.jsx)(`span`,{className:`text-[0.6875rem] leading-none text-fg-secondary-alt`,children:t})]}),n]})}function ice({value:e,className:t}){return(0,Y.jsx)(`div`,{className:X(`h-10 px-3 flex items-center rounded-md border border-border-float bg-bg-surface text-[0.9375rem]`,t),children:e})}function ace({value:e}){return(0,Y.jsx)(`div`,{className:`px-3 py-2.5 rounded-md border border-border-float bg-bg-surface text-[0.9375rem] leading-relaxed text-fg-secondary`,children:e})}function fC(){let[e,t]=(0,b.useState)(()=>typeof window>`u`?!1:window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);return(0,b.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),n=()=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}function oce(e){let[t,n]=(0,b.useState)(e===`fields`),[r,i]=(0,b.useState)(e);return r!==e&&(i(e),n(e===`fields`)),[t,n]}function sce({page:e,device:t,selectedFieldId:n,attachedFieldIds:r,onSelectField:i,isSelectMode:a}){let o=t=>e.fields[t]?.value??``,s=t===`mobile`,c=({id:e,as:t=`div`,className:o,children:s})=>(0,Y.jsx)(t,{"data-field-id":e,onClick:t=>{a&&(t.stopPropagation(),i(e))},className:X(`relative transition-shadow`,a&&`cursor-pointer rounded-[2px] shadow-[0_0_0_1px_var(--bg-page-selection-soft)] hover:shadow-[0_0_0_2px_var(--bg-page-selection)]`,a&&(n===e||r.includes(e))&&`shadow-[0_0_0_2px_var(--bg-page-selection)]`,o),children:s});return(0,Y.jsxs)(`div`,{className:`bg-[#fdf8f3] text-[#2b1a12] font-sans`,children:[(0,Y.jsxs)(`header`,{className:X(`flex items-center gap-8 border-b border-[#e8d9c9]`,s?`px-5 h-16`:`px-10 h-20`),children:[(0,Y.jsx)(`span`,{className:`text-xl font-bold tracking-tight text-[#c2410c]`,children:`Nordic Retail`}),!s&&(0,Y.jsx)(`nav`,{className:`flex gap-6 text-sm`,children:[`Shop`,`Stores`,`Journal`,`About`].map(e=>(0,Y.jsx)(`span`,{children:e},e))})]}),(0,Y.jsxs)(`section`,{className:X(s?`px-5 py-10`:`px-10 py-16`),children:[(0,Y.jsx)(c,{id:`eyebrow`,as:`p`,className:`mb-4 inline-block text-sm font-semibold uppercase tracking-[0.2em] text-[#c2410c]`,children:o(`eyebrow`)}),(0,Y.jsx)(c,{id:`headline`,as:`h1`,className:X(`mb-6 font-bold leading-[1.05] tracking-tight`,s?`text-4xl`:`text-6xl max-w-2xl`),children:o(`headline`)}),(0,Y.jsx)(c,{id:`intro`,as:`p`,className:X(`mb-8 leading-relaxed text-[#6b4f3f]`,s?`text-base`:`text-lg max-w-xl`),children:o(`intro`)}),(0,Y.jsx)(c,{id:`ctaLabel`,as:`span`,className:`inline-block rounded-full bg-[#c2410c] px-6 py-3 text-sm font-medium text-white`,children:o(`ctaLabel`)})]}),(0,Y.jsx)(`section`,{className:X(s?`px-5 pb-12`:`px-10 pb-20`),children:(0,Y.jsx)(`div`,{className:X(`grid gap-5`,s?`grid-cols-1`:`grid-cols-3`),children:[1,2,3].map(e=>(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(c,{id:`cat${e}Image`,className:`mb-3 grid aspect-[4/5] place-items-center rounded-lg bg-[#efe1d3] text-[#c9ab8e]`,children:(0,Y.jsx)(Nv,{size:28,strokeWidth:1.25})}),(0,Y.jsx)(c,{id:`cat${e}Title`,as:`p`,className:`font-medium`,children:o(`cat${e}Title`)}),(0,Y.jsx)(c,{id:`cat${e}Price`,as:`p`,className:`text-sm text-[#6b4f3f]`,children:o(`cat${e}Price`)})]},e))})}),(0,Y.jsxs)(`section`,{className:X(`bg-[#f3e7da]`,s?`px-5 py-10`:`px-10 py-16`),children:[(0,Y.jsx)(c,{id:`storyTitle`,as:`h2`,className:X(`mb-4 font-bold tracking-tight`,s?`text-2xl`:`text-4xl`),children:o(`storyTitle`)}),(0,Y.jsx)(c,{id:`storyBody`,as:`p`,className:X(`leading-relaxed text-[#6b4f3f]`,s?`text-base`:`text-lg max-w-2xl`),children:o(`storyBody`)})]}),(0,Y.jsx)(`footer`,{className:X(`border-t border-[#e8d9c9] text-sm text-[#6b4f3f]`,s?`px-5 py-8`:`px-10 py-10`),children:(0,Y.jsx)(c,{id:`footerNote`,as:`span`,className:`inline-block`,children:o(`footerNote`)})})]})}var pC={desktop:Gie,tablet:sae,mobile:tae};function cce({device:e,onDeviceChange:t,scale:n,onZoomIn:r,onZoomOut:i,onFit:a,isPicking:o,onPickingChange:s,onReload:c,isRefreshing:l,className:u}){return(0,Y.jsxs)(`div`,{className:X(`flex items-center gap-1 rounded-lg border border-border-float bg-bg-float p-1 shadow-lg`,`max-w-[calc(100%-1.5rem)] overflow-x-auto scrollbar-none [&>*]:shrink-0`,u),children:[Object.keys(pC).map(n=>{let r=pC[n];return(0,Y.jsx)(`button`,{type:`button`,"aria-label":`${n} width`,"aria-pressed":e===n,onClick:()=>t(n),className:X(`grid h-7 w-7 place-items-center rounded-md`,e===n?`bg-bg-float-raised text-fg-primary`:`text-fg-secondary hover:bg-bg-float-raised hover:text-fg-primary`),children:(0,Y.jsx)(r,{size:14})},n)}),(0,Y.jsx)(mC,{}),(0,Y.jsx)(`button`,{type:`button`,"aria-label":`Zoom out`,onClick:i,className:`grid h-7 w-7 place-items-center rounded-md text-fg-secondary hover:bg-bg-float-raised hover:text-fg-primary`,children:(0,Y.jsx)(Wv,{size:14})}),(0,Y.jsxs)(`span`,{className:`w-11 text-center text-[0.6875rem] tabular-nums text-fg-secondary`,children:[Math.round(n*100),`%`]}),(0,Y.jsx)(`button`,{type:`button`,"aria-label":`Zoom in`,onClick:r,className:`grid h-7 w-7 place-items-center rounded-md text-fg-secondary hover:bg-bg-float-raised hover:text-fg-primary`,children:(0,Y.jsx)(ey,{size:14})}),(0,Y.jsx)(`button`,{type:`button`,"aria-label":`Fit page to screen`,onClick:a,className:`grid h-7 w-7 place-items-center rounded-md text-fg-secondary hover:bg-bg-float-raised hover:text-fg-primary`,children:(0,Y.jsx)(Hie,{size:13})}),s&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(mC,{}),(0,Y.jsx)(`button`,{type:`button`,"aria-label":o?`Stop selecting on the page`:`Select on the page`,"aria-pressed":o,title:o?`Clicking the page selects what it hits`:`Clicking the page follows links, as a visitor would`,onClick:()=>s(!o),className:X(`grid h-7 w-7 place-items-center rounded-md`,o?`bg-bg-page-selection-fill text-fg-brand-primary ring-1 ring-inset ring-bg-page-selection`:`text-fg-secondary hover:bg-bg-float-raised hover:text-fg-primary`),children:(0,Y.jsx)(Gv,{size:14})})]}),c&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(mC,{}),(0,Y.jsx)(`button`,{type:`button`,"aria-label":l?`Updating the page`:`Reload the page`,title:l?`The page is re-rendering with your change`:`Reload the page`,onClick:c,className:X(`grid h-7 w-7 place-items-center rounded-md hover:bg-bg-float-raised hover:text-fg-primary`,l?`text-fg-brand-primary`:`text-fg-secondary`),children:(0,Y.jsx)(Zie,{size:13,className:X(l&&`animate-spin`)})})]})]})}function mC(){return(0,Y.jsx)(`span`,{"aria-hidden":!0,className:`mx-0.5 h-5 w-px bg-border-float`})}var lce=.1,uce=(0,b.forwardRef)(function({pageWidth:e,scale:t,onScaleChange:n,autoFit:r=!1,onUserZoom:i,initialScroll:a,onScrollChange:o,children:s,className:c},l){let u=(0,b.useRef)(null),d=(0,b.useRef)(null),[f,p]=(0,b.useState)(0);(0,b.useEffect)(()=>{let e=d.current;if(!e)return;let t=new ResizeObserver(()=>p(e.offsetHeight));return t.observe(e),p(e.offsetHeight),()=>t.disconnect()},[]);let m=(0,b.useRef)(t);m.current=t;let h=(0,b.useRef)(f);h.current=f;let g=(0,b.useRef)(null);(0,b.useLayoutEffect)(()=>{let e=g.current,t=u.current;e===null||!t||(g.current=null,t.scrollLeft=e.x,t.scrollTop=e.y)},[t]);let _=(0,b.useCallback)((t,r,a)=>{let o=u.current;if(!o)return;i?.();let s=m.current,c=hC(t),l=pce(o,{width:e,height:h.current},s,c,r,a);if(c===s){o.scrollLeft=l.x,o.scrollTop=l.y;return}g.current=l,m.current=c,n(c)},[e,n,i]),v=(0,b.useCallback)(()=>{let t=u.current,n=m.current;if(!t)return{x:0,y:0};let r={width:e,height:h.current};return{x:(t.scrollLeft+t.clientWidth/2-gC(t.clientWidth,r.width*n))/n,y:(t.scrollTop+t.clientHeight/2-gC(t.clientHeight,r.height*n))/n}},[e]),y=(0,b.useCallback)(()=>{let t=u.current;if(!t||h.current===0)return;let r=fce({width:e,height:h.current},{width:t.clientWidth,height:t.clientHeight});if(g.current={x:0,y:0},r===m.current){t.scrollLeft=0,t.scrollTop=0,g.current=null;return}m.current=r,n(r)},[e,n]),x=(0,b.useRef)(null),S=(0,b.useCallback)(e=>{if(e.phase===`end`){x.current=null;return}let t=dce(e.span,m.current);if(e.phase===`start`||x.current===null){x.current={span:t,center:e.center,scale:m.current};return}let n=x.current;n.span<=0||_(n.scale*(t/n.span),e.center,n.center)},[_]);(0,b.useImperativeHandle)(l,()=>({zoomBy:(e,t)=>{let n=t??v();_(m.current*e,n,n)},fit:y,pinch:S}),[_,v,y,S]);let[C,w]=(0,b.useState)({width:0,height:0});(0,b.useEffect)(()=>{let e=u.current;if(!e)return;let t=()=>w(t=>t.width===e.clientWidth&&t.height===e.clientHeight?t:{width:e.clientWidth,height:e.clientHeight}),n=new ResizeObserver(t);return n.observe(e),t(),()=>n.disconnect()},[]),(0,b.useEffect)(()=>{!r||f===0||C.height===0||y()},[r,f,C,e,y]),(0,b.useEffect)(()=>{let t=u.current;if(!t)return;let n=n=>{if(!n.ctrlKey&&!n.metaKey)return;n.preventDefault();let r=t.getBoundingClientRect(),i=m.current,a={width:e,height:h.current},o={x:(n.clientX-r.left+t.scrollLeft-gC(t.clientWidth,a.width*i))/i,y:(n.clientY-r.top+t.scrollTop-gC(t.clientHeight,a.height*i))/i};_(i*(1-n.deltaY/300),o,o)};return t.addEventListener(`wheel`,n,{passive:!1}),()=>t.removeEventListener(`wheel`,n)},[_,e]);let T=(0,b.useRef)(null),E=(0,b.useCallback)(()=>{!o||T.current!==null||(T.current=requestAnimationFrame(()=>{T.current=null;let e=u.current;e&&o({x:e.scrollLeft,y:e.scrollTop})}))},[o]);(0,b.useEffect)(()=>()=>{T.current!==null&&cancelAnimationFrame(T.current)},[]);let D=(0,b.useRef)(!1);return(0,b.useLayoutEffect)(()=>{if(D.current||!a)return;let e=u.current;!e||f===0||(D.current=!0,e.scrollLeft=a.x,e.scrollTop=a.y)},[a,f]),(0,Y.jsx)(`div`,{ref:u,onScroll:E,className:X(`relative overflow-auto overscroll-contain bg-bg-canvas scrollbar-slim`,`[background-image:radial-gradient(var(--border-float)_1px,transparent_1px)] [background-size:24px_24px]`,c),children:(0,Y.jsx)(`div`,{className:`flex h-max min-h-full w-max min-w-full items-center justify-center`,children:(0,Y.jsx)(`div`,{style:{width:e*t,height:f*t},className:`shrink-0`,children:(0,Y.jsx)(`div`,{ref:d,style:{width:e,transform:`scale(${t})`,transformOrigin:`0 0`},className:`will-change-transform`,children:s})})})})});function dce(e,t){return e*t}function hC(e){return Math.min(2,Math.max(lce,e))}function fce(e,t){let n={width:Math.max(1,t.width-48),height:Math.max(1,t.height-48)};return hC(Math.min(n.width/e.width,n.height/e.height))}function gC(e,t){return Math.max(0,(e-t)/2)}function pce(e,t,n,r,i,a){let o=gC(e.clientWidth,t.width*n)-e.scrollLeft+i.x*n,s=gC(e.clientHeight,t.height*n)-e.scrollTop+i.y*n;return{x:gC(e.clientWidth,t.width*r)+a.x*r-o,y:gC(e.clientHeight,t.height*r)+a.y*r-s}}function mce({page:e,selectedFieldId:t,onSelectField:n,onChangeField:r,onAttachField:i,attachedFieldIds:a,isDevMode:o}){let[s,c]=(0,b.useState)(``),l=(0,b.useRef)(null),u=(0,b.useMemo)(()=>{let t=s.trim().toLowerCase();return e.sections.map(n=>({...n,fields:n.fieldIds.map(t=>e.fields[t]).filter(e=>e!==void 0&&(t===``||e.label.toLowerCase().includes(t)||e.value.toLowerCase().includes(t)))})).filter(e=>e.fields.length>0)},[e,s]);return(0,b.useEffect)(()=>{if(!t)return;let e=l.current,n=e?.querySelector(`[data-field-row="${t}"]`);if(!e||!n)return;let r=n.offsetTop-e.offsetTop,i=r+n.offsetHeight;r<e.scrollTop?e.scrollTo({top:r,behavior:`smooth`}):i>e.scrollTop+e.clientHeight&&e.scrollTo({top:i-e.clientHeight,behavior:`smooth`})},[t]),(0,Y.jsxs)(`div`,{className:`flex h-full flex-col bg-bg-float`,children:[(0,Y.jsx)(`div`,{className:`shrink-0 border-b border-border-float px-3 py-2`,children:(0,Y.jsx)(rC,{value:s,onChange:c,placeholder:`Filter fields…`})}),(0,Y.jsxs)(`div`,{ref:l,className:`min-h-0 flex-1 overflow-y-auto pb-4 scrollbar-slim`,children:[u.length===0&&(0,Y.jsx)(`p`,{className:`px-4 py-6 text-xs text-fg-secondary-alt`,children:`No fields match this filter.`}),u.map(e=>(0,Y.jsxs)(`section`,{children:[(0,Y.jsx)(`h3`,{className:`px-4 pb-1.5 pt-4 text-[0.6875rem] font-semibold uppercase tracking-wider text-fg-secondary-alt`,children:e.name}),e.fields.map(e=>(0,Y.jsx)(gce,{field:e,selected:t===e.id,attached:a.includes(e.id),onSelect:()=>n(e.id),onChange:t=>r(e.id,t),onAttach:()=>i(e.id),isDevMode:o},e.id))]},e.id))]})]})}var hce={string:uy,text:uy,richtext:uy,image:Nv,link:Lv};function gce({field:e,selected:t,attached:n,onSelect:r,onChange:i,onAttach:a,isDevMode:o}){let s=hce[e.type];return(0,Y.jsxs)(`div`,{"data-field-row":e.id,onFocusCapture:r,onClick:r,className:X(`px-3 py-2 border-l-2 transition-colors`,t?`border-bg-page-selection bg-bg-float-raised`:`border-transparent hover:bg-bg-float-raised/60`),children:[(0,Y.jsxs)(`div`,{className:`mb-1.5 flex items-center gap-1.5`,children:[(0,Y.jsx)(s,{size:12,className:`shrink-0 text-fg-secondary-alt`}),(0,Y.jsx)(`span`,{className:`text-[0.8125rem] font-medium`,children:e.label}),n&&(0,Y.jsx)(`span`,{title:`Attached to the assistant`,className:`text-fg-secondary-alt`,children:(0,Y.jsx)(Qv,{size:11})}),(0,Y.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a()},className:`ml-auto rounded px-1.5 py-0.5 text-[0.625rem] text-fg-secondary-alt opacity-0 transition-opacity hover:bg-bg-float-raised hover:text-fg-primary focus:opacity-100 group-hover:opacity-100 [div:hover>div>&]:opacity-100`,children:`Ask AI`})]}),e.type===`image`?(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-border-float bg-bg-surface px-2 py-1.5`,children:[(0,Y.jsx)(`span`,{className:`grid h-8 w-8 shrink-0 place-items-center rounded bg-bg-float-raised text-fg-secondary-alt`,children:(0,Y.jsx)(Nv,{size:13})}),(0,Y.jsx)(`span`,{className:`truncate font-mono text-[0.6875rem] text-fg-secondary`,children:e.value})]}):e.type===`text`||e.type===`richtext`?(0,Y.jsx)(`textarea`,{value:e.value,onChange:e=>i(e.target.value),rows:3,"aria-label":e.label,className:`w-full resize-none rounded-md border border-border-float bg-bg-surface px-2 py-1.5 text-xs leading-relaxed focus:border-border-brand-primary focus:outline-none`}):(0,Y.jsx)(`input`,{value:e.value,onChange:e=>i(e.target.value),"aria-label":e.label,className:X(`h-8 w-full rounded-md border border-border-float bg-bg-surface px-2 text-xs focus:border-border-brand-primary focus:outline-none`,e.type===`link`&&`font-mono`)}),o&&(0,Y.jsx)(`p`,{className:`mt-1 truncate font-mono text-[0.625rem] text-fg-secondary-alt`,children:e.sourcePath})]})}function _C(e){let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e[r]!==e[r].toLowerCase();r===0?(t+=e[r].toUpperCase(),n=!1):n&&i?(n=!1,t+=` `+e[r].toUpperCase()):(t+=e[r].toLowerCase(),n=!0)}return t=t.replace(/[-–—]/g,``),t}function vC(e){let t=e;(t.endsWith(`.val.ts`)||t.endsWith(`.val.js`))&&(t=t.slice(0,-7));let n=t.match(/^\(([^)]+)\)$/);if(n)return _C(n[1]);if(t.match(/^\[\[\.\.\.([^\]]+)\]\]$/)||t.match(/^\[\.\.\.([^\]]+)\]$/))return`…`;let r=t.match(/^\[([^\]]+)\]$/);return _C(r?r[1]:t)}var yC=u(s(((e,t)=>{(function(){var e={}.hasOwnProperty;function n(){for(var e=``,t=0;t<arguments.length;t++){var n=arguments[t];n&&(e=i(e,r(n)))}return e}function r(t){if(typeof t==`string`||typeof t==`number`)return t;if(typeof t!=`object`)return``;if(Array.isArray(t))return n.apply(null,t);if(t.toString!==Object.prototype.toString&&!t.toString.toString().includes(`[native code]`))return t.toString();var r=``;for(var a in t)e.call(t,a)&&t[a]&&(r=i(r,a));return r}function i(e,t){return t?e?e+` `+t:e+t:e}t!==void 0&&t.exports?(n.default=n,t.exports=n):typeof define==`function`&&typeof define.amd==`object`&&define.amd?define(`classnames`,[],function(){return n}):window.classNames=n})()}))());function bC({path:e,type:t}){return(0,Y.jsx)(`div`,{id:e,className:(0,yC.default)(`pt-6`,{"w-full flex items-center justify-center":t===`module`,"text-left":t!==`module`}),children:(0,Y.jsx)(Vv,{size:t===`module`?24:16,className:`animate-spin`})})}function xC({path:e,type:t}){let[n,r]=(0,b.useState)(!1);return(0,b.useEffect)(()=>{let e=setTimeout(()=>{r(!0)},2e3);return()=>{clearTimeout(e)}},[]),e.length===0?null:n?(0,Y.jsxs)(`div`,{id:e,className:`pt-6 flex flex-col items-center justify-center text-center gap-4`,children:[(0,Y.jsx)(`div`,{className:`flex items-center justify-center w-16 h-16 rounded-full bg-bg-tertiary`,children:(0,Y.jsx)(fv,{className:`w-8 h-8 text-fg-tertiary`})}),(0,Y.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Y.jsx)(`h2`,{className:`text-lg font-semibold text-fg-primary`,children:`Not Found`}),(0,Y.jsxs)(`p`,{className:`text-sm text-fg-tertiary max-w-md`,children:[`The path`,` `,(0,Y.jsx)(`code`,{className:`px-1.5 py-0.5 bg-bg-tertiary rounded text-fg-secondary font-mono text-xs`,children:e}),` `,`can no longer be found.`]})]}),(0,Y.jsxs)(`button`,{onClick:()=>{window.location.href=window.origin+xf(`/val`)},className:`mt-2 inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-fg-primary bg-bg-secondary hover:bg-bg-tertiary rounded-md transition-colors`,children:[(0,Y.jsx)(cie,{className:`w-4 h-4`}),`Go Home`]})]}):(0,Y.jsx)(bC,{path:e,type:t})}function SC({error:e,path:t}){return(0,Y.jsx)(`div`,{id:t,children:(0,Y.jsx)(`div`,{className:`p-4 bg-bg-error-primary text-fg-error-primary`,children:e})})}function CC({actualType:e,expectedType:t,path:n}){return(0,Y.jsx)(`div`,{id:n,children:(0,Y.jsxs)(`div`,{children:[`Schema mismatch: actual: `,e,` vs expected: `,t,` `]})})}var _ce=365.2425,wC=6048e5,vce=864e5,TC=86400;TC*7,TC*_ce/12*3;var EC=Symbol.for(`constructDateFrom`);function DC(e,t){return typeof e==`function`?e(t):e&&typeof e==`object`&&EC in e?e[EC](t):e instanceof Date?new e.constructor(t):new Date(t)}function OC(e,t){return DC(t||e,e)}function kC(e,t,n){let r=OC(e,n?.in);return isNaN(t)?DC(n?.in||e,NaN):(t&&r.setDate(r.getDate()+t),r)}function AC(e,t,n){let r=OC(e,n?.in);if(isNaN(t))return DC(n?.in||e,NaN);if(!t)return r;let i=r.getDate(),a=DC(n?.in||e,r.getTime());return a.setMonth(r.getMonth()+t+1,0),i>=a.getDate()?a:(r.setFullYear(a.getFullYear(),a.getMonth(),i),r)}var yce={};function jC(){return yce}function MC(e,t){let n=jC(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,i=OC(e,t?.in),a=i.getDay(),o=(a<r?7:0)+a-r;return i.setDate(i.getDate()-o),i.setHours(0,0,0,0),i}function NC(e,t){return MC(e,{...t,weekStartsOn:1})}function PC(e,t){let n=OC(e,t?.in),r=n.getFullYear(),i=DC(n,0);i.setFullYear(r+1,0,4),i.setHours(0,0,0,0);let a=NC(i),o=DC(n,0);o.setFullYear(r,0,4),o.setHours(0,0,0,0);let s=NC(o);return n.getTime()>=a.getTime()?r+1:n.getTime()>=s.getTime()?r:r-1}function FC(e){let t=OC(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-n}function IC(e,...t){let n=DC.bind(null,e||t.find(e=>typeof e==`object`));return t.map(n)}function LC(e,t){let n=OC(e,t?.in);return n.setHours(0,0,0,0),n}function RC(e,t,n){let[r,i]=IC(n?.in,e,t),a=LC(r),o=LC(i),s=+a-FC(a),c=+o-FC(o);return Math.round((s-c)/vce)}function bce(e,t){let n=PC(e,t),r=DC(t?.in||e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),NC(r)}function xce(e,t,n){return kC(e,t*7,n)}function Sce(e,t,n){return AC(e,t*12,n)}function Cce(e,t){let n,r=t?.in;return e.forEach(e=>{!r&&typeof e==`object`&&(r=DC.bind(null,e));let t=OC(e,r);(!n||n<t||isNaN(+t))&&(n=t)}),DC(r,n||NaN)}function wce(e,t){let n,r=t?.in;return e.forEach(e=>{!r&&typeof e==`object`&&(r=DC.bind(null,e));let t=OC(e,r);(!n||n>t||isNaN(+t))&&(n=t)}),DC(r,n||NaN)}function Tce(e,t,n){let[r,i]=IC(n?.in,e,t);return+LC(r)==+LC(i)}function zC(e){return e instanceof Date||typeof e==`object`&&Object.prototype.toString.call(e)===`[object Date]`}function Ece(e){return!(!zC(e)&&typeof e!=`number`||isNaN(+OC(e)))}function BC(e,t,n){let[r,i]=IC(n?.in,e,t),a=r.getFullYear()-i.getFullYear(),o=r.getMonth()-i.getMonth();return a*12+o}function Dce(e,t){let n=OC(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function VC(e,t){let[n,r]=IC(e,t.start,t.end);return{start:n,end:r}}function Oce(e,t){let{start:n,end:r}=VC(t?.in,e),i=+n>+r,a=i?+n:+r,o=i?r:n;o.setHours(0,0,0,0),o.setDate(1);let s=t?.step??1;if(!s)return[];s<0&&(s=-s,i=!i);let c=[];for(;+o<=a;)c.push(DC(n,o)),o.setMonth(o.getMonth()+s);return i?c.reverse():c}function kce(e,t){let n=OC(e,t?.in);return n.setDate(1),n.setHours(0,0,0,0),n}function Ace(e,t){let n=OC(e,t?.in),r=n.getFullYear();return n.setFullYear(r+1,0,0),n.setHours(23,59,59,999),n}function HC(e,t){let n=OC(e,t?.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}function jce(e,t){let{start:n,end:r}=VC(t?.in,e),i=+n>+r,a=i?+n:+r,o=i?r:n;o.setHours(0,0,0,0),o.setMonth(0,1);let s=t?.step??1;if(!s)return[];s<0&&(s=-s,i=!i);let c=[];for(;+o<=a;)c.push(DC(n,o)),o.setFullYear(o.getFullYear()+s);return i?c.reverse():c}function UC(e,t){let n=jC(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,i=OC(e,t?.in),a=i.getDay(),o=(a<r?-7:0)+6-(a-r);return i.setDate(i.getDate()+o),i.setHours(23,59,59,999),i}function Mce(e,t){return UC(e,{...t,weekStartsOn:1})}var Nce={lessThanXSeconds:{one:`less than a second`,other:`less than {{count}} seconds`},xSeconds:{one:`1 second`,other:`{{count}} seconds`},halfAMinute:`half a minute`,lessThanXMinutes:{one:`less than a minute`,other:`less than {{count}} minutes`},xMinutes:{one:`1 minute`,other:`{{count}} minutes`},aboutXHours:{one:`about 1 hour`,other:`about {{count}} hours`},xHours:{one:`1 hour`,other:`{{count}} hours`},xDays:{one:`1 day`,other:`{{count}} days`},aboutXWeeks:{one:`about 1 week`,other:`about {{count}} weeks`},xWeeks:{one:`1 week`,other:`{{count}} weeks`},aboutXMonths:{one:`about 1 month`,other:`about {{count}} months`},xMonths:{one:`1 month`,other:`{{count}} months`},aboutXYears:{one:`about 1 year`,other:`about {{count}} years`},xYears:{one:`1 year`,other:`{{count}} years`},overXYears:{one:`over 1 year`,other:`over {{count}} years`},almostXYears:{one:`almost 1 year`,other:`almost {{count}} years`}},Pce=(e,t,n)=>{let r,i=Nce[e];return r=typeof i==`string`?i:t===1?i.one:i.other.replace(`{{count}}`,t.toString()),n?.addSuffix?n.comparison&&n.comparison>0?`in `+r:r+` ago`:r};function WC(e){return(t={})=>{let n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}var Fce={date:WC({formats:{full:`EEEE, MMMM do, y`,long:`MMMM do, y`,medium:`MMM d, y`,short:`MM/dd/yyyy`},defaultWidth:`full`}),time:WC({formats:{full:`h:mm:ss a zzzz`,long:`h:mm:ss a z`,medium:`h:mm:ss a`,short:`h:mm a`},defaultWidth:`full`}),dateTime:WC({formats:{full:`{{date}} 'at' {{time}}`,long:`{{date}} 'at' {{time}}`,medium:`{{date}}, {{time}}`,short:`{{date}}, {{time}}`},defaultWidth:`full`})},Ice={lastWeek:`'last' eeee 'at' p`,yesterday:`'yesterday at' p`,today:`'today at' p`,tomorrow:`'tomorrow at' p`,nextWeek:`eeee 'at' p`,other:`P`},Lce=(e,t,n,r)=>Ice[e];function GC(e){return(t,n)=>{let r=n?.context?String(n.context):`standalone`,i;if(r===`formatting`&&e.formattingValues){let t=e.defaultFormattingWidth||e.defaultWidth,r=n?.width?String(n.width):t;i=e.formattingValues[r]||e.formattingValues[t]}else{let t=e.defaultWidth,r=n?.width?String(n.width):e.defaultWidth;i=e.values[r]||e.values[t]}let a=e.argumentCallback?e.argumentCallback(t):t;return i[a]}}var Rce={ordinalNumber:(e,t)=>{let n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+`st`;case 2:return n+`nd`;case 3:return n+`rd`}return n+`th`},era:GC({values:{narrow:[`B`,`A`],abbreviated:[`BC`,`AD`],wide:[`Before Christ`,`Anno Domini`]},defaultWidth:`wide`}),quarter:GC({values:{narrow:[`1`,`2`,`3`,`4`],abbreviated:[`Q1`,`Q2`,`Q3`,`Q4`],wide:[`1st quarter`,`2nd quarter`,`3rd quarter`,`4th quarter`]},defaultWidth:`wide`,argumentCallback:e=>e-1}),month:GC({values:{narrow:[`J`,`F`,`M`,`A`,`M`,`J`,`J`,`A`,`S`,`O`,`N`,`D`],abbreviated:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],wide:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`]},defaultWidth:`wide`}),day:GC({values:{narrow:[`S`,`M`,`T`,`W`,`T`,`F`,`S`],short:[`Su`,`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`],abbreviated:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],wide:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`]},defaultWidth:`wide`}),dayPeriod:GC({values:{narrow:{am:`a`,pm:`p`,midnight:`mi`,noon:`n`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},abbreviated:{am:`AM`,pm:`PM`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},wide:{am:`a.m.`,pm:`p.m.`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`}},defaultWidth:`wide`,formattingValues:{narrow:{am:`a`,pm:`p`,midnight:`mi`,noon:`n`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`},abbreviated:{am:`AM`,pm:`PM`,midnight:`midnight`,noon:`noon`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`},wide:{am:`a.m.`,pm:`p.m.`,midnight:`midnight`,noon:`noon`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`}},defaultFormattingWidth:`wide`})};function KC(e){return(t,n={})=>{let r=n.width,i=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],a=t.match(i);if(!a)return null;let o=a[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(s)?Bce(s,e=>e.test(o)):zce(s,e=>e.test(o)),l;l=e.valueCallback?e.valueCallback(c):c,l=n.valueCallback?n.valueCallback(l):l;let u=t.slice(o.length);return{value:l,rest:u}}}function zce(e,t){for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function Bce(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function Vce(e){return(t,n={})=>{let r=t.match(e.matchPattern);if(!r)return null;let i=r[0],a=t.match(e.parsePattern);if(!a)return null;let o=e.valueCallback?e.valueCallback(a[0]):a[0];o=n.valueCallback?n.valueCallback(o):o;let s=t.slice(i.length);return{value:o,rest:s}}}var qC={code:`en-US`,formatDistance:Pce,formatLong:Fce,formatRelative:Lce,localize:Rce,match:{ordinalNumber:Vce({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:KC({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:`wide`,parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:`any`}),quarter:KC({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:`wide`,parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:`any`,valueCallback:e=>e+1}),month:KC({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:`wide`,parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:`any`}),day:KC({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:`wide`,parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:`any`}),dayPeriod:KC({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:`any`,parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:`any`})},options:{weekStartsOn:0,firstWeekContainsDate:1}};function Hce(e,t){let n=OC(e,t?.in);return RC(n,HC(n))+1}function JC(e,t){let n=OC(e,t?.in),r=+NC(n)-bce(n);return Math.round(r/wC)+1}function YC(e,t){let n=OC(e,t?.in),r=n.getFullYear(),i=jC(),a=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??i.firstWeekContainsDate??i.locale?.options?.firstWeekContainsDate??1,o=DC(t?.in||e,0);o.setFullYear(r+1,0,a),o.setHours(0,0,0,0);let s=MC(o,t),c=DC(t?.in||e,0);c.setFullYear(r,0,a),c.setHours(0,0,0,0);let l=MC(c,t);return+n>=+s?r+1:+n>=+l?r:r-1}function Uce(e,t){let n=jC(),r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=YC(e,t),a=DC(t?.in||e,0);return a.setFullYear(i,0,r),a.setHours(0,0,0,0),MC(a,t)}function XC(e,t){let n=OC(e,t?.in),r=+MC(n,t)-Uce(n,t);return Math.round(r/wC)+1}function ZC(e,t){return(e<0?`-`:``)+Math.abs(e).toString().padStart(t,`0`)}var QC={y(e,t){let n=e.getFullYear(),r=n>0?n:1-n;return ZC(t===`yy`?r%100:r,t.length)},M(e,t){let n=e.getMonth();return t===`M`?String(n+1):ZC(n+1,2)},d(e,t){return ZC(e.getDate(),t.length)},a(e,t){let n=e.getHours()/12>=1?`pm`:`am`;switch(t){case`a`:case`aa`:return n.toUpperCase();case`aaa`:return n;case`aaaaa`:return n[0];default:return n===`am`?`a.m.`:`p.m.`}},h(e,t){return ZC(e.getHours()%12||12,t.length)},H(e,t){return ZC(e.getHours(),t.length)},m(e,t){return ZC(e.getMinutes(),t.length)},s(e,t){return ZC(e.getSeconds(),t.length)},S(e,t){let n=t.length,r=e.getMilliseconds();return ZC(Math.trunc(r*10**(n-3)),t.length)}},$C={am:`am`,pm:`pm`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},ew={G:function(e,t,n){let r=+(e.getFullYear()>0);switch(t){case`G`:case`GG`:case`GGG`:return n.era(r,{width:`abbreviated`});case`GGGGG`:return n.era(r,{width:`narrow`});default:return n.era(r,{width:`wide`})}},y:function(e,t,n){if(t===`yo`){let t=e.getFullYear(),r=t>0?t:1-t;return n.ordinalNumber(r,{unit:`year`})}return QC.y(e,t)},Y:function(e,t,n,r){let i=YC(e,r),a=i>0?i:1-i;return t===`YY`?ZC(a%100,2):t===`Yo`?n.ordinalNumber(a,{unit:`year`}):ZC(a,t.length)},R:function(e,t){return ZC(PC(e),t.length)},u:function(e,t){return ZC(e.getFullYear(),t.length)},Q:function(e,t,n){let r=Math.ceil((e.getMonth()+1)/3);switch(t){case`Q`:return String(r);case`QQ`:return ZC(r,2);case`Qo`:return n.ordinalNumber(r,{unit:`quarter`});case`QQQ`:return n.quarter(r,{width:`abbreviated`,context:`formatting`});case`QQQQQ`:return n.quarter(r,{width:`narrow`,context:`formatting`});default:return n.quarter(r,{width:`wide`,context:`formatting`})}},q:function(e,t,n){let r=Math.ceil((e.getMonth()+1)/3);switch(t){case`q`:return String(r);case`qq`:return ZC(r,2);case`qo`:return n.ordinalNumber(r,{unit:`quarter`});case`qqq`:return n.quarter(r,{width:`abbreviated`,context:`standalone`});case`qqqqq`:return n.quarter(r,{width:`narrow`,context:`standalone`});default:return n.quarter(r,{width:`wide`,context:`standalone`})}},M:function(e,t,n){let r=e.getMonth();switch(t){case`M`:case`MM`:return QC.M(e,t);case`Mo`:return n.ordinalNumber(r+1,{unit:`month`});case`MMM`:return n.month(r,{width:`abbreviated`,context:`formatting`});case`MMMMM`:return n.month(r,{width:`narrow`,context:`formatting`});default:return n.month(r,{width:`wide`,context:`formatting`})}},L:function(e,t,n){let r=e.getMonth();switch(t){case`L`:return String(r+1);case`LL`:return ZC(r+1,2);case`Lo`:return n.ordinalNumber(r+1,{unit:`month`});case`LLL`:return n.month(r,{width:`abbreviated`,context:`standalone`});case`LLLLL`:return n.month(r,{width:`narrow`,context:`standalone`});default:return n.month(r,{width:`wide`,context:`standalone`})}},w:function(e,t,n,r){let i=XC(e,r);return t===`wo`?n.ordinalNumber(i,{unit:`week`}):ZC(i,t.length)},I:function(e,t,n){let r=JC(e);return t===`Io`?n.ordinalNumber(r,{unit:`week`}):ZC(r,t.length)},d:function(e,t,n){return t===`do`?n.ordinalNumber(e.getDate(),{unit:`date`}):QC.d(e,t)},D:function(e,t,n){let r=Hce(e);return t===`Do`?n.ordinalNumber(r,{unit:`dayOfYear`}):ZC(r,t.length)},E:function(e,t,n){let r=e.getDay();switch(t){case`E`:case`EE`:case`EEE`:return n.day(r,{width:`abbreviated`,context:`formatting`});case`EEEEE`:return n.day(r,{width:`narrow`,context:`formatting`});case`EEEEEE`:return n.day(r,{width:`short`,context:`formatting`});default:return n.day(r,{width:`wide`,context:`formatting`})}},e:function(e,t,n,r){let i=e.getDay(),a=(i-r.weekStartsOn+8)%7||7;switch(t){case`e`:return String(a);case`ee`:return ZC(a,2);case`eo`:return n.ordinalNumber(a,{unit:`day`});case`eee`:return n.day(i,{width:`abbreviated`,context:`formatting`});case`eeeee`:return n.day(i,{width:`narrow`,context:`formatting`});case`eeeeee`:return n.day(i,{width:`short`,context:`formatting`});default:return n.day(i,{width:`wide`,context:`formatting`})}},c:function(e,t,n,r){let i=e.getDay(),a=(i-r.weekStartsOn+8)%7||7;switch(t){case`c`:return String(a);case`cc`:return ZC(a,t.length);case`co`:return n.ordinalNumber(a,{unit:`day`});case`ccc`:return n.day(i,{width:`abbreviated`,context:`standalone`});case`ccccc`:return n.day(i,{width:`narrow`,context:`standalone`});case`cccccc`:return n.day(i,{width:`short`,context:`standalone`});default:return n.day(i,{width:`wide`,context:`standalone`})}},i:function(e,t,n){let r=e.getDay(),i=r===0?7:r;switch(t){case`i`:return String(i);case`ii`:return ZC(i,t.length);case`io`:return n.ordinalNumber(i,{unit:`day`});case`iii`:return n.day(r,{width:`abbreviated`,context:`formatting`});case`iiiii`:return n.day(r,{width:`narrow`,context:`formatting`});case`iiiiii`:return n.day(r,{width:`short`,context:`formatting`});default:return n.day(r,{width:`wide`,context:`formatting`})}},a:function(e,t,n){let r=e.getHours()/12>=1?`pm`:`am`;switch(t){case`a`:case`aa`:return n.dayPeriod(r,{width:`abbreviated`,context:`formatting`});case`aaa`:return n.dayPeriod(r,{width:`abbreviated`,context:`formatting`}).toLowerCase();case`aaaaa`:return n.dayPeriod(r,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(r,{width:`wide`,context:`formatting`})}},b:function(e,t,n){let r=e.getHours(),i;switch(i=r===12?$C.noon:r===0?$C.midnight:r/12>=1?`pm`:`am`,t){case`b`:case`bb`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`});case`bbb`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`}).toLowerCase();case`bbbbb`:return n.dayPeriod(i,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(i,{width:`wide`,context:`formatting`})}},B:function(e,t,n){let r=e.getHours(),i;switch(i=r>=17?$C.evening:r>=12?$C.afternoon:r>=4?$C.morning:$C.night,t){case`B`:case`BB`:case`BBB`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`});case`BBBBB`:return n.dayPeriod(i,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(i,{width:`wide`,context:`formatting`})}},h:function(e,t,n){if(t===`ho`){let t=e.getHours()%12;return t===0&&(t=12),n.ordinalNumber(t,{unit:`hour`})}return QC.h(e,t)},H:function(e,t,n){return t===`Ho`?n.ordinalNumber(e.getHours(),{unit:`hour`}):QC.H(e,t)},K:function(e,t,n){let r=e.getHours()%12;return t===`Ko`?n.ordinalNumber(r,{unit:`hour`}):ZC(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t===`ko`?n.ordinalNumber(r,{unit:`hour`}):ZC(r,t.length)},m:function(e,t,n){return t===`mo`?n.ordinalNumber(e.getMinutes(),{unit:`minute`}):QC.m(e,t)},s:function(e,t,n){return t===`so`?n.ordinalNumber(e.getSeconds(),{unit:`second`}):QC.s(e,t)},S:function(e,t){return QC.S(e,t)},X:function(e,t,n){let r=e.getTimezoneOffset();if(r===0)return`Z`;switch(t){case`X`:return nw(r);case`XXXX`:case`XX`:return rw(r);default:return rw(r,`:`)}},x:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`x`:return nw(r);case`xxxx`:case`xx`:return rw(r);default:return rw(r,`:`)}},O:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`O`:case`OO`:case`OOO`:return`GMT`+tw(r,`:`);default:return`GMT`+rw(r,`:`)}},z:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`z`:case`zz`:case`zzz`:return`GMT`+tw(r,`:`);default:return`GMT`+rw(r,`:`)}},t:function(e,t,n){return ZC(Math.trunc(e/1e3),t.length)},T:function(e,t,n){return ZC(+e,t.length)}};function tw(e,t=``){let n=e>0?`-`:`+`,r=Math.abs(e),i=Math.trunc(r/60),a=r%60;return a===0?n+String(i):n+String(i)+t+ZC(a,2)}function nw(e,t){return e%60==0?(e>0?`-`:`+`)+ZC(Math.abs(e)/60,2):rw(e,t)}function rw(e,t=``){let n=e>0?`-`:`+`,r=Math.abs(e),i=ZC(Math.trunc(r/60),2),a=ZC(r%60,2);return n+i+t+a}var iw=(e,t)=>{switch(e){case`P`:return t.date({width:`short`});case`PP`:return t.date({width:`medium`});case`PPP`:return t.date({width:`long`});default:return t.date({width:`full`})}},aw=(e,t)=>{switch(e){case`p`:return t.time({width:`short`});case`pp`:return t.time({width:`medium`});case`ppp`:return t.time({width:`long`});default:return t.time({width:`full`})}},Wce={p:aw,P:(e,t)=>{let n=e.match(/(P+)(p+)?/)||[],r=n[1],i=n[2];if(!i)return iw(e,t);let a;switch(r){case`P`:a=t.dateTime({width:`short`});break;case`PP`:a=t.dateTime({width:`medium`});break;case`PPP`:a=t.dateTime({width:`long`});break;default:a=t.dateTime({width:`full`})}return a.replace(`{{date}}`,iw(r,t)).replace(`{{time}}`,aw(i,t))}},Gce=/^D+$/,Kce=/^Y+$/,qce=[`D`,`DD`,`YY`,`YYYY`];function Jce(e){return Gce.test(e)}function Yce(e){return Kce.test(e)}function Xce(e,t,n){let r=Zce(e,t,n);if(console.warn(r),qce.includes(e))throw RangeError(r)}function Zce(e,t,n){let r=e[0]===`Y`?`years`:`days of the month`;return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var Qce=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,$ce=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,ele=/^'([^]*?)'?$/,tle=/''/g,nle=/[a-zA-Z]/;function ow(e,t,n){let r=jC(),i=n?.locale??r.locale??qC,a=n?.firstWeekContainsDate??n?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=OC(e,n?.in);if(!Ece(s))throw RangeError(`Invalid time value`);let c=t.match($ce).map(e=>{let t=e[0];if(t===`p`||t===`P`){let n=Wce[t];return n(e,i.formatLong)}return e}).join(``).match(Qce).map(e=>{if(e===`''`)return{isToken:!1,value:`'`};let t=e[0];if(t===`'`)return{isToken:!1,value:rle(e)};if(ew[t])return{isToken:!0,value:e};if(t.match(nle))throw RangeError("Format string contains an unescaped latin alphabet character `"+t+"`");return{isToken:!1,value:e}});i.localize.preprocessor&&(c=i.localize.preprocessor(s,c));let l={firstWeekContainsDate:a,weekStartsOn:o,locale:i};return c.map(r=>{if(!r.isToken)return r.value;let a=r.value;(!n?.useAdditionalWeekYearTokens&&Yce(a)||!n?.useAdditionalDayOfYearTokens&&Jce(a))&&Xce(a,t,String(e));let o=ew[a[0]];return o(s,a,i.localize,l)}).join(``)}function rle(e){let t=e.match(ele);return t?t[1].replace(tle,`'`):e}function ile(e,t){let n=OC(e,t?.in),r=n.getFullYear(),i=n.getMonth(),a=DC(n,0);return a.setFullYear(r,i+1,0),a.setHours(0,0,0,0),a.getDate()}function ale(e,t){return OC(e,t?.in).getMonth()}function ole(e,t){return OC(e,t?.in).getFullYear()}function sle(e,t){return+OC(e)>+OC(t)}function cle(e,t){return+OC(e)<+OC(t)}function lle(e,t,n){let[r,i]=IC(n?.in,e,t);return r.getFullYear()===i.getFullYear()&&r.getMonth()===i.getMonth()}function ule(e,t,n){let[r,i]=IC(n?.in,e,t);return r.getFullYear()===i.getFullYear()}function dle(e,t,n){let r=OC(e,n?.in),i=r.getFullYear(),a=r.getDate(),o=DC(n?.in||e,0);o.setFullYear(i,t,15),o.setHours(0,0,0,0);let s=ile(o);return r.setMonth(t,Math.min(a,s)),r}function fle(e,t,n){let r=OC(e,n?.in);return isNaN(+r)?DC(n?.in||e,NaN):(r.setFullYear(t),r)}function ple(e,t){return t?.to&&e>t.to?t.to:t?.from&&e<t.from?t.from:e}function mle(e,t){if(!t)return e;let n=Date.parse(e);if(Number.isNaN(n))return e;if(t.to){let e=Date.parse(t.to);if(!Number.isNaN(e)&&n>e)return new Date(e).toISOString()}if(t.from){let e=Date.parse(t.from);if(!Number.isNaN(e)&&n<e)return new Date(e).toISOString()}return e}function sw(e){if(e.type===`object`)return Object.fromEntries(Object.keys(e.items).map(t=>[t,sw(e.items[t])]));if(e.type===`array`)return[];if(e.type===`record`)return{};if(e.opt)return null;if(e.type===`richtext`)return[];if(e.type===`string`)return``;if(e.type===`boolean`)return!1;if(e.type===`number`)return 0;if(e.type===`keyOf`)return e.values===`string`?``:e.values[0];if(e.type===`route`)return``;if(e.type===`file`||e.type===`image`)return null;if(e.type===`literal`)return e.value;if(e.type===`union`)return typeof e.key==`string`?sw(e.items[0]):e.key.value;if(e.type===`date`)return ple(ow(new Date,`yyyy-MM-dd`),e.options);if(e.type===`dateTime`)return mle(new Date().toISOString(),e.options);if(e.type===`color`)return V.color.formatColor({r:128,g:128,b:128,a:1},e.options?.format??`hsl`);throw Error(`Unexpected schema type: `+JSON.stringify(e))}function cw({error:e,path:t,schema:n}){let{addPatch:r,patchPath:i}=Wy(t);return(0,Y.jsxs)(`div`,{id:t,className:`flex justify-between items-center px-2 py-3 rounded-lg bg-bg-error-primary text-fg-primary`,children:[(0,Y.jsxs)(`div`,{children:[`Source error: `,e]}),(0,Y.jsxs)(`div`,{className:`flex gap-2 items-center`,children:[n&&n.status===`success`&&n.data.type!==`file`&&n.data.type!==`image`&&(0,Y.jsx)(kg,{variant:`outline`,className:`hover:bg-bg-error-secondary-hover`,onClick:()=>{r([{op:`replace`,path:i,value:sw(n.data)}],n.data.type)},children:`Fix`}),(0,Y.jsx)(ly,{size:16})]})]})}var lw=`/val/compare`,uw=`/val/errors`,dw=b.createContext(new Proxy({},{get:()=>{throw Error(`ValRouter context not provided`)}})),fw=`/val/~`,hle=[`p`,`error-field`,`field`],pw=`data-val-studio-path`;function mw(e,t){let n=Array.from(e.querySelectorAll(`[${pw}]`));for(let e of n)if(e.getAttribute(pw)===t)return e;return null}function hw(e,t=100){let n=()=>{let r=document.getElementById(`val-shadow-root`)?.shadowRoot,i=r?mw(r,e):null;i&&r?gw(r,i):t>0&&(t--,setTimeout(n,100))};n()}var gle=16;function gw(e,t){let n=e.getElementById(`val-content-area`);if(n){let e=Number(n.dataset.scrollClearance),r=Number.isFinite(e)?e:gle,i=t.getBoundingClientRect().top-n.getBoundingClientRect().top;n.scrollTo({top:Math.max(0,n.scrollTop+i-r),behavior:`smooth`})}t.classList.remove(`val-scroll-highlight`),t.offsetWidth,t.classList.add(`val-scroll-highlight`),t.addEventListener(`animationend`,()=>t.classList.remove(`val-scroll-highlight`),{once:!0})}function _w({children:e,overlay:t}){let[n,r]=(0,b.useState)(!1),[i,a]=(0,b.useState)(``),[o,s]=(0,b.useState)(null),[c,l]=(0,b.useState)(!1),[u,d]=(0,b.useState)(!1),[f,p]=(0,b.useState)([]),[m,h]=(0,b.useState)(()=>typeof window>`u`?null:new URLSearchParams(window.location.search).get(`session`)),g=(0,b.useRef)([]);(0,b.useEffect)(()=>{let e=()=>{if(h(new URLSearchParams(location.search).get(`session`)),location.pathname===`/val/compare`||location.pathname===`/val/compare/`){l(!0),d(!1),p([]),a(``),r(!0);return}if(location.pathname===`/val/errors`||location.pathname===`/val/errors/`){d(!0),l(!1),p(new URLSearchParams(location.search).getAll(`error-field`)),a(``),r(!0);return}l(!1),d(!1),p([]);let e=location.pathname.indexOf(fw);if(e>-1){let t=new URLSearchParams(location.search).get(`p`),n=location.pathname.slice(e+6)+(t?`?p=${t}`:``);a(n);let r=new URLSearchParams(location.search).get(`field`);s(r||null);let i=g.current.pop();if(i)setTimeout(()=>{let e=document.getElementById(`val-shadow-root`)?.shadowRoot?.getElementById(`val-content-area`);i&&e?.scrollTo(0,i)},50);else if(location.hash){let e=decodeURIComponent(location.hash.slice(1));window.history.replaceState(null,``,location.pathname+location.search),e&&hw(e)}else r&&hw(r)}else(location.pathname===`/val`||location.pathname===`/val/`||location.pathname===fw)&&a(``);r(!0)};return e(),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`popstate`,e)}},[]);let _=(0,b.useCallback)((e,n)=>{let r=e===lw,i=e===uw,a=i&&n?.errorFields&&n.errorFields.length>0?`?`+n.errorFields.map(e=>`error-field=${encodeURIComponent(e)}`).join(`&`):``,o=r?lw:i?uw+a:`${fw}${e}`,s=new URLSearchParams(typeof window>`u`?``:window.location.search);for(let e of hle)s.delete(e);let c=m;if(t&&c==null)try{c=sessionStorage.getItem(wf)}catch{c=null}c?s.set(`session`,c):s.delete(`session`);let l=!r&&!i&&n?.scrollToPath!==e?n?.scrollToPath??null:null;l&&s.set(`field`,l);let u=s.toString();return u?`${o}${o.includes(`?`)?`&`:`?`}${u}`:o},[t,m]),v=(0,b.useCallback)((e,n)=>{let r=e===lw,i=e===uw,o=_(e,n),c=!r&&!i&&n?.scrollToPath!==e?n?.scrollToPath??null:null;if(l(r),d(i),p(i?n?.errorFields??[]:[]),a(r||i?``:e),s(c),t)window.location.href=o+(n?.scrollToPath?`#${encodeURIComponent(n.scrollToPath)}`:``);else{let e=document.getElementById(`val-shadow-root`)?.shadowRoot,t=e?.getElementById(`val-content-area`),r=t?.scrollTop,i=n?.scrollToPath;if(i&&e){let t=10,n=()=>{let r=mw(e,i);r?gw(e,r):t>0&&(t--,setTimeout(n,100))};setTimeout(n,100)}else t?.scrollTo(0,0);r!==void 0&&g.current.push(r),n?.replace?window.history.replaceState(null,``,o):window.history.pushState(null,``,o)}},[t,_]),y=(0,b.useCallback)((e,n)=>{if(t)return;let r=new URL(window.location.href);e==null?r.searchParams.delete(`session`):r.searchParams.set(`session`,e);let i=r.pathname+r.search+r.hash;n?.replace?window.history.replaceState(null,``,i):window.history.pushState(null,``,i),h(e)},[t]);return(0,Y.jsx)(dw.Provider,{value:{hardLink:!!t,currentSourcePath:i,focusedSourcePath:o,navigate:v,hrefOf:_,ready:n,isCompareView:c,isErrorsView:u,errorFields:f,sessionParam:m,setSessionParam:y},children:e})}function vw(){let{navigate:e,hrefOf:t,currentSourcePath:n,focusedSourcePath:r,ready:i,isCompareView:a,isErrorsView:o,errorFields:s}=(0,b.useContext)(dw);return{navigate:e,hrefOf:t,currentSourcePath:n,focusedSourcePath:r,ready:i,isCompareView:a,isErrorsView:o,errorFields:s}}function _le(){let{sessionParam:e,setSessionParam:t}=(0,b.useContext)(dw);return{sessionParam:e,setSessionParam:t}}function vle(){var e=[...arguments];return(0,b.useMemo)(()=>t=>{e.forEach(e=>e(t))},e)}var yw=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function bw(e){let t=Object.prototype.toString.call(e);return t===`[object Window]`||t===`[object global]`}function xw(e){return`nodeType`in e}function Sw(e){return e?bw(e)?e:xw(e)?e.ownerDocument?.defaultView??window:window:window}function Cw(e){let{Document:t}=Sw(e);return e instanceof t}function ww(e){return!bw(e)&&e instanceof Sw(e).HTMLElement}function Tw(e){return e instanceof Sw(e).SVGElement}function Ew(e){return e?bw(e)?e.document:xw(e)?Cw(e)?e:ww(e)||Tw(e)?e.ownerDocument:document:document:document}var Dw=yw?b.useLayoutEffect:b.useEffect;function Ow(e){let t=(0,b.useRef)(e);return Dw(()=>{t.current=e}),(0,b.useCallback)(function(){var e=[...arguments];return t.current==null?void 0:t.current(...e)},[])}function yle(){let e=(0,b.useRef)(null);return[(0,b.useCallback)((t,n)=>{e.current=setInterval(t,n)},[]),(0,b.useCallback)(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[])]}function kw(e,t){t===void 0&&(t=[e]);let n=(0,b.useRef)(e);return Dw(()=>{n.current!==e&&(n.current=e)},t),n}function Aw(e,t){let n=(0,b.useRef)();return(0,b.useMemo)(()=>{let t=e(n.current);return n.current=t,t},[...t])}function jw(e){let t=Ow(e),n=(0,b.useRef)(null);return[n,(0,b.useCallback)(e=>{e!==n.current&&t?.(e,n.current),n.current=e},[])]}function Mw(e){let t=(0,b.useRef)();return(0,b.useEffect)(()=>{t.current=e},[e]),t.current}var Nw={};function Pw(e,t){return(0,b.useMemo)(()=>{if(t)return t;let n=Nw[e]==null?0:Nw[e]+1;return Nw[e]=n,e+`-`+n},[e,t])}function Fw(e){return function(t){return[...arguments].slice(1).reduce((t,n)=>{let r=Object.entries(n);for(let[n,i]of r){let r=t[n];r!=null&&(t[n]=r+e*i)}return t},{...t})}}var Iw=Fw(1),Lw=Fw(-1);function ble(e){return`clientX`in e&&`clientY`in e}function Rw(e){if(!e)return!1;let{KeyboardEvent:t}=Sw(e.target);return t&&e instanceof t}function xle(e){if(!e)return!1;let{TouchEvent:t}=Sw(e.target);return t&&e instanceof t}function zw(e){if(xle(e)){if(e.touches&&e.touches.length){let{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}if(e.changedTouches&&e.changedTouches.length){let{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return ble(e)?{x:e.clientX,y:e.clientY}:null}var Bw=Object.freeze({Translate:{toString(e){if(!e)return;let{x:t,y:n}=e;return`translate3d(`+(t?Math.round(t):0)+`px, `+(n?Math.round(n):0)+`px, 0)`}},Scale:{toString(e){if(!e)return;let{scaleX:t,scaleY:n}=e;return`scaleX(`+t+`) scaleY(`+n+`)`}},Transform:{toString(e){if(e)return[Bw.Translate.toString(e),Bw.Scale.toString(e)].join(` `)}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+` `+n+`ms `+r}}}),Vw=`a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]`;function Sle(e){return e.matches(Vw)?e:e.querySelector(Vw)}var Cle={display:`none`};function wle(e){let{id:t,value:n}=e;return b.createElement(`div`,{id:t,style:Cle},n)}function Tle(e){let{id:t,announcement:n,ariaLiveType:r=`assertive`}=e;return b.createElement(`div`,{id:t,style:{position:`fixed`,top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0 0 0 0)`,clipPath:`inset(100%)`,whiteSpace:`nowrap`},role:`status`,"aria-live":r,"aria-atomic":!0},n)}function Ele(){let[e,t]=(0,b.useState)(``);return{announce:(0,b.useCallback)(e=>{e!=null&&t(e)},[]),announcement:e}}var Hw=(0,b.createContext)(null);function Dle(e){let t=(0,b.useContext)(Hw);(0,b.useEffect)(()=>{if(!t)throw Error(`useDndMonitor must be used within a children of <DndContext>`);return t(e)},[e,t])}function Ole(){let[e]=(0,b.useState)(()=>new Set),t=(0,b.useCallback)(t=>(e.add(t),()=>e.delete(t)),[e]);return[(0,b.useCallback)(t=>{let{type:n,event:r}=t;e.forEach(e=>e[n]?.call(e,r))},[e]),t]}var kle={draggable:`
134
134
  To pick up a draggable item, press the space bar.