@inkeep/open-knowledge 0.29.0-beta.2 → 0.29.0-beta.3

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.
Files changed (73) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/cli.mjs +6 -6
  4. package/dist/constants-iJEQPyMf.mjs +2 -0
  5. package/dist/{dist-B2S_dh_W.mjs → dist-BC-5uOuA.mjs} +1 -1
  6. package/dist/{dist-uq1hO0l5.mjs → dist-DU6kAT_L.mjs} +4 -4
  7. package/dist/{gh-detect-CkD5P0-7.mjs → gh-detect-C8cgnhPS.mjs} +2 -2
  8. package/dist/index.mjs +1 -1
  9. package/dist/{init-Ctx2NP2_.mjs → init-BB94DLRV.mjs} +4 -4
  10. package/dist/init-DmRFXjVl.mjs +1 -0
  11. package/dist/{loader-_BJcNCg3.mjs → loader-C8BAnl-B.mjs} +2 -2
  12. package/dist/loader-CEde1zp9.mjs +1 -0
  13. package/dist/{open-browser-Bs3YoMQ3.mjs → open-browser-Csh_BnzS.mjs} +2 -2
  14. package/dist/{preview-CX35q4j-.mjs → preview-B3hDDzfT.mjs} +2 -2
  15. package/dist/preview-C6Q_b6ow.mjs +1 -0
  16. package/dist/public/assets/{ActivityModeContent-iGsUwFZM.js → ActivityModeContent-2tp1Q_zI.js} +1 -1
  17. package/dist/public/assets/{CodeMirrorPropInput-CI_BdrFO.js → CodeMirrorPropInput-Cl2krBi1.js} +1 -1
  18. package/dist/public/assets/{DocumentContext-H8ueoY2i.js → DocumentContext-BMXtV-Ln.js} +1 -1
  19. package/dist/public/assets/{EnableSyncConfirmDialog-Bfx-F020.js → EnableSyncConfirmDialog-8psqtAAY.js} +1 -1
  20. package/dist/public/assets/{GraphPanel-DY7seH_k.js → GraphPanel-SzbCW7lv.js} +1 -1
  21. package/dist/public/assets/{ManagedArtifactProperties-BacfB11y.js → ManagedArtifactProperties-YzNV7lSB.js} +1 -1
  22. package/dist/public/assets/{McpConsentDialogBody-BGQg0BNB.js → McpConsentDialogBody-DL5wtFki.js} +1 -1
  23. package/dist/public/assets/{MermaidDocEditor-Dfh6FYTu.js → MermaidDocEditor-CpXnSnNc.js} +1 -1
  24. package/dist/public/assets/{PropertyPanel-CdSjB-1i.js → PropertyPanel-BjgqBOzt.js} +1 -1
  25. package/dist/public/assets/{SettingsDialogBody-DqSaum3o.js → SettingsDialogBody-okqOz3JG.js} +1 -1
  26. package/dist/public/assets/{ShareBranchSwitchDialog-DCB8oBto.js → ShareBranchSwitchDialog-CHK_z72s.js} +1 -1
  27. package/dist/public/assets/{ShareReceiveDialog-Dd0J6bu0.js → ShareReceiveDialog-B7LADZTY.js} +1 -1
  28. package/dist/public/assets/{ShareReceiveMissDialog-F7-OypGp.js → ShareReceiveMissDialog-DjXRStpL.js} +1 -1
  29. package/dist/public/assets/{SkillEditorActions-CS0pOij-.js → SkillEditorActions-BY6-FtCh.js} +1 -1
  30. package/dist/public/assets/{SourceEditor-CM6j_h7v.js → SourceEditor-CKhJOjEN.js} +1 -1
  31. package/dist/public/assets/{TerminalPanel-C1NoS4P8.js → TerminalPanel-DcsneHQ6.js} +1 -1
  32. package/dist/public/assets/{agent-presence-Df3xVodm.js → agent-presence-CDhPSQ1V.js} +1 -1
  33. package/dist/public/assets/{auth-state-cache-CYLTInpD.js → auth-state-cache-Sf96j0tb.js} +1 -1
  34. package/dist/public/assets/{config-provider-C8aBdDar.js → config-provider-ChqdK0oC.js} +1 -1
  35. package/dist/public/assets/{dist-D5fPTJjV.js → dist-CZpHX_li.js} +1 -1
  36. package/dist/public/assets/{dist-D74hAxnw.js → dist-D9rK70V6.js} +1 -1
  37. package/dist/public/assets/{doc-hash-I00EhzUZ.js → doc-hash-DpRfN6nP.js} +1 -1
  38. package/dist/public/assets/{documents-events-BvkJvzEE.js → documents-events-BBnySus9.js} +1 -1
  39. package/dist/public/assets/{file-tree-adapter-DvAE1kkw.js → file-tree-adapter-Czoj_1kM.js} +1 -1
  40. package/dist/public/assets/{index-Dot-SWIQ.js → index-cgyL6Dw7.js} +7 -7
  41. package/dist/public/assets/{keyboard-shortcuts-CYQR8WL_.js → keyboard-shortcuts-Bh19wFn8.js} +1 -1
  42. package/dist/public/assets/{navigation-targets-u2AFSpqT.js → navigation-targets-dSNCMciZ.js} +1 -1
  43. package/dist/public/assets/{open-managed-artifact-tab-BX3OwOLJ.js → open-managed-artifact-tab-Cp8GwMMz.js} +1 -1
  44. package/dist/public/assets/{pending-receive-nav-store-CEbpuzlN.js → pending-receive-nav-store-81v0u2oK.js} +1 -1
  45. package/dist/public/assets/{prop-types-B0pfL-iG.js → prop-types-CjhSDm4-.js} +1 -1
  46. package/dist/public/assets/{receive-store-Dt6o4uQU.js → receive-store-BV3siC5s.js} +1 -1
  47. package/dist/public/assets/{selection-context-Lsc6HP-h.js → selection-context-BEXgwMs6.js} +1 -1
  48. package/dist/public/assets/{skill-actions--keDj-1t.js → skill-actions-CU2OFW3l.js} +1 -1
  49. package/dist/public/assets/{skills-api-C4PwgAoY.js → skills-api-Bp3kco7L.js} +1 -1
  50. package/dist/public/assets/{src-ibmWGcks.js → src-BYue3aqY.js} +1 -1
  51. package/dist/public/assets/{target-navigation-intent-B9aNmptJ.js → target-navigation-intent-hg3FepK0.js} +1 -1
  52. package/dist/public/assets/{typing-burst-detector-uC8uK0Mq.js → typing-burst-detector-DsAscwX2.js} +1 -1
  53. package/dist/public/assets/{workspace-paths-BTMolBhv.js → workspace-paths-YQ-7XBlO.js} +1 -1
  54. package/dist/public/index.html +25 -25
  55. package/dist/{repair-launch-json-B22PVEUL.mjs → repair-launch-json-0_w3Th4l.mjs} +2 -2
  56. package/dist/{repair-mcp-configs-BY_IWOhJ.mjs → repair-mcp-configs-B5jS3LgK.mjs} +2 -2
  57. package/dist/repair-skills-B0B7a5IA.mjs +1 -0
  58. package/dist/{repair-skills-BHDFQ7QJ.mjs → repair-skills-C_l1phOf.mjs} +2 -2
  59. package/dist/server-lock-GuuouVft-DSQyMetL.mjs +1 -0
  60. package/dist/{server-lock-iLcBw_q0-rwg8rOgA.mjs → server-lock-iLcBw_q0-CdaRzkXM.mjs} +2 -2
  61. package/dist/{src-Bv4nWkUq.mjs → src-DigXo6He.mjs} +2 -2
  62. package/dist/{start-DAGRv3oL.mjs → start-Bz36N1Vk.mjs} +2 -2
  63. package/dist/start-szYTsrPy.mjs +1 -0
  64. package/dist/write-project-skill-BnCIY7g1.mjs +36 -0
  65. package/package.json +1 -1
  66. package/dist/constants-BDeiyoTG.mjs +0 -2
  67. package/dist/init-Da-7KOcl.mjs +0 -1
  68. package/dist/loader-CAY4VO1u.mjs +0 -1
  69. package/dist/preview-BDrPrn0_.mjs +0 -1
  70. package/dist/repair-skills-BoioTwtW.mjs +0 -1
  71. package/dist/server-lock-GuuouVft-C8t6Ffyt.mjs +0 -1
  72. package/dist/start-ChBqLjxS.mjs +0 -1
  73. package/dist/write-project-skill-CIXZymGf.mjs +0 -36
@@ -301,7 +301,7 @@ Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#pl
301
301
  `,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
302
302
  Please provide a chat model before proceeding with creating an answer session.
303
303
  Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy
304
- `,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:`The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.`,PLUGIN_COMPONENT_CONFLICT:`The component "%s" is already defined. The plugin "%s" is trying to redefine it.`};function pH(e,...t){let n=Error(WV(fH[e]??`Unsupported Orama Error code: ${e}`,...t));return n.code=e,`captureStackTrace`in Error.prototype&&Error.captureStackTrace(n),n}function mH(e){return{raw:Number(e),formatted:JV(e)}}function hH(e){if(e.id){if(typeof e.id!=`string`)throw pH(`DOCUMENT_ID_MUST_BE_STRING`,typeof e.id);return e.id}return XV()}function gH(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];if(t!==void 0&&!(r===`geopoint`&&typeof t==`object`&&typeof t.lon==`number`&&typeof t.lat==`number`)&&!(r===`enum`&&(typeof t==`string`||typeof t==`number`))){if(r===`enum[]`&&Array.isArray(t)){let e=t.length;for(let r=0;r<e;r++)if(typeof t[r]!=`string`&&typeof t[r]!=`number`)return n+`.`+r;continue}if(bH(r)){let e=CH(r);if(!Array.isArray(t)||t.length!==e)throw pH(`INVALID_INPUT_VECTOR`,n,e,t.length);continue}if(xH(r)){if(!Array.isArray(t))return n;let e=SH(r),i=t.length;for(let r=0;r<i;r++)if(typeof t[r]!==e)return n+`.`+r;continue}if(typeof r==`object`){if(!t||typeof t!=`object`)return n;let e=gH(t,r);if(e)return n+`.`+e;continue}if(typeof t!==r)return n}}}const _H={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},vH={"string[]":`string`,"number[]":`number`,"boolean[]":`boolean`,"enum[]":`enum`};function yH(e){return e===`geopoint`}function bH(e){return typeof e==`string`&&/^vector\[\d+\]$/.test(e)}function xH(e){return typeof e==`string`&&_H[e]}function SH(e){return vH[e]}function CH(e){let t=Number(e.slice(7,-1));switch(!0){case isNaN(t):throw pH(`INVALID_VECTOR_VALUE`,e);case t<=0:throw pH(`INVALID_VECTOR_SIZE`,e);default:return t}}function wH(){return{idToInternalId:new Map,internalIdToId:[],save:TH,load:EH}}function TH(e){return{internalIdToId:e.internalIdToId}}function EH(e,t){let{internalIdToId:n}=t;e.internalDocumentIDStore.idToInternalId.clear(),e.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let t=0;t<r;t++){let r=n[t];e.internalDocumentIDStore.idToInternalId.set(r,t+1),e.internalDocumentIDStore.internalIdToId.push(r)}}function DH(e,t){if(typeof t==`string`){let n=e.idToInternalId.get(t);if(n)return n;let r=e.idToInternalId.size+1;return e.idToInternalId.set(t,r),e.internalIdToId.push(t),r}return t>e.internalIdToId.length?DH(e,t.toString()):t}function OH(e,t){if(e.internalIdToId.length<t)throw Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function kH(e,t){return{sharedInternalDocumentStore:t,docs:{},count:0}}function AH(e,t){let n=DH(e.sharedInternalDocumentStore,t);return e.docs[n]}function jH(e,t){let n=t.length,r=Array.from({length:n});for(let i=0;i<n;i++){let n=DH(e.sharedInternalDocumentStore,t[i]);r[i]=e.docs[n]}return r}function MH(e){return e.docs}function NH(e,t,n,r){return e.docs[n]===void 0?(e.docs[n]=r,e.count++,!0):!1}function PH(e,t){let n=DH(e.sharedInternalDocumentStore,t);return e.docs[n]===void 0?!1:(delete e.docs[n],e.count--,!0)}function FH(e){return e.count}function IH(e,t){let n=t;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:e}}function LH(e){return{docs:e.docs,count:e.count}}function RH(){return{create:kH,get:AH,getMultiple:jH,getAll:MH,store:NH,remove:PH,count:FH,load:IH,save:LH}}const zH=[`beforeInsert`,`afterInsert`,`beforeRemove`,`afterRemove`,`beforeUpdate`,`afterUpdate`,`beforeUpsert`,`afterUpsert`,`beforeSearch`,`afterSearch`,`beforeInsertMultiple`,`afterInsertMultiple`,`beforeRemoveMultiple`,`afterRemoveMultiple`,`beforeUpdateMultiple`,`afterUpdateMultiple`,`beforeUpsertMultiple`,`afterUpsertMultiple`,`beforeLoad`,`afterLoad`,`afterCreate`];function BH(e,t){let n=[],r=e.plugins?.length;if(!r)return n;for(let i=0;i<r;i++)try{let r=e.plugins[i];typeof r[t]==`function`&&n.push(r[t])}catch(e){throw console.error(`Caught error in getAllPluginsByHook:`,e),pH(`PLUGIN_CRASHED`)}return n}const VH=[`tokenizer`,`index`,`documentsStore`,`sorter`,`pinning`],HH=[`validateSchema`,`getDocumentIndexId`,`getDocumentProperties`,`formatElapsedTime`];function UH(e,t,n,r){if(e.some(aH))return(async()=>{for(let i of e)await i(t,n,r)})();for(let i of e)i(t,n,r)}function WH(e,t,n){if(e.some(aH))return(async()=>{for(let r of e)await r(t,n)})();for(let r of e)r(t,n)}function GH(e,t,n,r,i){if(e.some(aH))return(async()=>{for(let a of e)await a(t,n,r,i)})();for(let a of e)a(t,n,r,i)}function KH(e,t,n,r){if(e.some(aH))return(async()=>{for(let i of e)await i(t,n,r)})();for(let i of e)i(t,n,r)}function qH(e,t){if(e.some(aH))return(async()=>{for(let n of e)await n(t)})();for(let n of e)n(t)}var JH=class e{k;v;l=null;r=null;h=1;constructor(e,t){this.k=e,this.v=new Set(t)}updateHeight(){this.h=Math.max(e.getHeight(this.l),e.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return e.getHeight(this.l)-e.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(t){let n=new e(t.k,t.v);return n.l=t.l?e.fromJSON(t.l):null,n.r=t.r?e.fromJSON(t.r):null,n.h=t.h,n}},YH=class e{root=null;insertCount=0;constructor(e,t){e!==void 0&&t!==void 0&&(this.root=new JH(e,t))}insert(e,t,n=1e3){this.root=this.insertNode(this.root,e,t,n)}insertMultiple(e,t,n=1e3){for(let r of t)this.insert(e,r,n)}rebalance(){this.root&&=this.rebalanceNode(this.root)}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(t){let n=new e;return n.root=t.root?JH.fromJSON(t.root):null,n.insertCount=t.insertCount||0,n}insertNode(e,t,n,r){if(e===null)return new JH(t,[n]);let i=[],a=e,o=null;for(;a!==null;)if(i.push({parent:o,node:a}),t<a.k)if(a.l===null){a.l=new JH(t,[n]),i.push({parent:a,node:a.l});break}else o=a,a=a.l;else if(t>a.k)if(a.r===null){a.r=new JH(t,[n]),i.push({parent:a,node:a.r});break}else o=a,a=a.r;else return a.v.add(n),e;let s=!1;this.insertCount++%r===0&&(s=!0);for(let t=i.length-1;t>=0;t--){let{parent:n,node:r}=i[t];if(r.updateHeight(),s){let t=this.rebalanceNode(r);n?n.l===r?n.l=t:n.r===r&&(n.r=t):e=t}}return e}rebalanceNode(e){let t=e.getBalanceFactor();if(t>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(t<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let t=this.findNodeByKey(e);return t?t.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,t=[],n=this.root;for(;n||t.length>0;){for(;n;)t.push(n),n=n.l;n=t.pop(),e++,n=n.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let t=e.pop(),n=t.getBalanceFactor();if(Math.abs(n)>1)return!1;t.l&&e.push(t.l),t.r&&e.push(t.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,t){let n=this.findNodeByKey(e);n&&(n.v.size===1?this.root=this.removeNode(this.root,e):n.v=new Set([...n.v.values()].filter(e=>e!==t)))}findNodeByKey(e){let t=this.root;for(;t;)if(e<t.k)t=t.l;else if(e>t.k)t=t.r;else return t;return null}removeNode(e,t){if(e===null)return null;let n=[],r=e;for(;r!==null&&r.k!==t;)n.push(r),r=t<r.k?r.l:r.r;if(r===null)return e;if(r.l===null||r.r===null){let t=r.l?r.l:r.r;if(n.length===0)e=t;else{let e=n[n.length-1];e.l===r?e.l=t:e.r=t}}else{let e=r,t=r.r;for(;t.l!==null;)e=t,t=t.l;r.k=t.k,r.v=t.v,e.l===t?e.l=t.r:e.r=t.r,r=e}n.push(r);for(let t=n.length-1;t>=0;t--){let r=n[t];r.updateHeight();let i=this.rebalanceNode(r);if(t>0){let e=n[t-1];e.l===r?e.l=i:e.r===r&&(e.r=i)}else e=i}return e}rangeSearch(e,t){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.l;if(i=r.pop(),i.k>=e&&i.k<=t)for(let e of i.v)n.add(e);if(i.k>t)break;i=i.r}return n}greaterThan(e,t=!1){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.r;if(i=r.pop(),t&&i.k>=e||!t&&i.k>e)for(let e of i.v)n.add(e);else if(i.k<=e)break;i=i.l}return n}lessThan(e,t=!1){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.l;if(i=r.pop(),t&&i.k<=e||!t&&i.k<e)for(let e of i.v)n.add(e);else if(i.k>e)break;i=i.r}return n}},XH=class e{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,t){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(t):this.numberToDocumentId.set(e,new Set([t]))}find(e){let t=this.numberToDocumentId.get(e);return t?Array.from(t):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,t){let n=this.numberToDocumentId.get(t);n&&(n.delete(e),n.size===0&&this.numberToDocumentId.delete(t))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let t of this.numberToDocumentId.values())e+=t.size;return e}filter(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let n=t[0];switch(n){case`eq`:{let t=e[n],r=this.numberToDocumentId.get(t);return r?Array.from(r):[]}case`in`:{let t=e[n],r=new Set;for(let e of t){let t=this.numberToDocumentId.get(e);if(t)for(let e of t)r.add(e)}return Array.from(r)}case`nin`:{let t=new Set(e[n]),r=new Set;for(let[e,n]of this.numberToDocumentId.entries())if(!t.has(e))for(let e of n)r.add(e);return Array.from(r)}default:throw Error(`Invalid operation`)}}filterArr(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let n=t[0];switch(n){case`containsAll`:{let t=e[n].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let r=t.reduce((e,t)=>new Set([...e].filter(e=>t.has(e))));return Array.from(r)}case`containsAny`:{let t=e[n].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let r=t.reduce((e,t)=>new Set([...e,...t]));return Array.from(r)}default:throw Error(`Invalid operation`)}}static fromJSON(t){if(!t.numberToDocumentId)throw Error(`Invalid Flat Tree JSON`);let n=new e;for(let[e,r]of t.numberToDocumentId)n.numberToDocumentId.set(e,new Set(r));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,t])=>[e,Array.from(t)])}}};function ZH(e,t,n){if(n<0)return-1;if(e===t)return 0;let r=e.length,i=t.length;if(r===0)return i<=n?i:-1;if(i===0)return r<=n?r:-1;let a=Math.abs(r-i);if(e.startsWith(t))return a<=n?a:-1;if(t.startsWith(e))return 0;if(a>n)return-1;let o=[];for(let e=0;e<=r;e++){o[e]=[e];for(let t=1;t<=i;t++)o[e][t]=e===0?t:0}for(let a=1;a<=r;a++){let r=1/0;for(let n=1;n<=i;n++)e[a-1]===t[n-1]?o[a][n]=o[a-1][n-1]:o[a][n]=Math.min(o[a-1][n]+1,o[a][n-1]+1,o[a-1][n-1]+1),r=Math.min(r,o[a][n]);if(r>n)return-1}return o[r][i]<=n?o[r][i]:-1}function QH(e,t,n){let r=ZH(e,t,n);return{distance:r,isBounded:r>=0}}var $H=class e{k;s;c=new Map;d=new Set;e;w=``;constructor(e,t,n){this.k=e,this.s=t,this.e=n}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,t,n,r){let i=[this];for(;i.length>0;){let a=i.pop();if(a.e){let{w:i,d:o}=a;if(n&&i!==t)continue;if(ZV(e,i)!==null)if(r)if(Math.abs(t.length-i.length)<=r&&QH(t,i,r).isBounded)e[i]=[];else continue;else e[i]=[];if(ZV(e,i)!=null&&o.size>0){let t=e[i];for(let e of o)t.includes(e)||t.push(e)}}a.c.size>0&&i.push(...a.c.values())}return e}insert(t,n){let r=this,i=0,a=t.length;for(;i<a;){let o=t[i],s=r.c.get(o);if(s){let o=s.s,c=o.length,l=0;for(;l<c&&i+l<a&&o[l]===t[i+l];)l++;if(l===c){if(r=s,i+=l,i===a){s.e||=!0,s.addDocument(n);return}continue}let u=o.slice(0,l),d=o.slice(l),f=t.slice(i+l),p=new e(u[0],u,!1);if(r.c.set(u[0],p),p.updateParent(r),s.s=d,s.k=d[0],p.c.set(d[0],s),s.updateParent(p),f){let t=new e(f[0],f,!0);t.addDocument(n),p.c.set(f[0],t),t.updateParent(p)}else p.e=!0,p.addDocument(n);return}else{let a=new e(o,t.slice(i),!0);a.addDocument(n),r.c.set(o,a),a.updateParent(r);return}}r.e||=!0,r.addDocument(n)}_findLevenshtein(e,t,n,r,i){let a=[{node:this,index:t,tolerance:n}];for(;a.length>0;){let{node:t,index:n,tolerance:o}=a.pop();if(t.w.startsWith(e)){t.findAllWords(i,e,!1,0);continue}if(o<0)continue;if(t.e){let{w:n,d:a}=t;if(n&&(QH(e,n,r).isBounded&&(i[n]=[]),ZV(i,n)!==void 0&&a.size>0)){let e=new Set(i[n]);for(let t of a)e.add(t);i[n]=Array.from(e)}}if(n>=e.length)continue;let s=e[n];if(t.c.has(s)){let e=t.c.get(s);a.push({node:e,index:n+1,tolerance:o})}a.push({node:t,index:n+1,tolerance:o-1});for(let[e,r]of t.c)a.push({node:r,index:n,tolerance:o-1}),e!==s&&a.push({node:r,index:n+1,tolerance:o-1})}}find(e){let{term:t,exact:n,tolerance:r}=e;if(r&&!n){let e={};return this._findLevenshtein(t,0,r,r,e),e}else{let e=this,i=0,a=t.length;for(;i<a;){let o=t[i],s=e.c.get(o);if(s){let o=s.s,c=o.length,l=0;for(;l<c&&i+l<a&&o[l]===t[i+l];)l++;if(l===c)e=s,i+=l;else if(i+l===a)if(l===a-i){if(n)return{};{let e={};return s.findAllWords(e,t,n,r),e}}else return{};else return{}}else return{}}let o={};return e.findAllWords(o,t,n,r),o}}contains(e){let t=this,n=0,r=e.length;for(;n<r;){let i=e[n],a=t.c.get(i);if(a){let i=a.s,o=i.length,s=0;for(;s<o&&n+s<r&&i[s]===e[n+s];)s++;if(s<o)return!1;n+=o,t=a}else return!1}return!0}removeWord(e){if(!e)return!1;let t=this,n=e.length,r=[];for(let i=0;i<n;i++){let n=e[i];if(t.c.has(n)){let e=t.c.get(n);r.push({parent:t,character:n}),i+=e.s.length-1,t=e}else return!1}for(t.d.clear(),t.e=!1;r.length>0&&t.c.size===0&&!t.e&&t.d.size===0;){let{parent:e,character:n}=r.pop();e.c.delete(n),t=e}return!0}removeDocumentByWord(e,t,n=!0){if(!e)return!0;let r=this,i=e.length;for(let a=0;a<i;a++){let i=e[a];if(r.c.has(i)){let o=r.c.get(i);a+=o.s.length-1,r=o,n&&r.w!==e||r.removeDocument(t)}else return!1}return!0}static getCommonPrefix(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e.charCodeAt(r)===t.charCodeAt(r);)r++;return e.slice(0,r)}toJSON(){return{w:this.w,s:this.s,e:this.e,k:this.k,d:Array.from(this.d),c:Array.from(this.c?.entries())?.map(([e,t])=>[e,t.toJSON()])}}static fromJSON(t){let n=new e(t.k,t.s,t.e);return n.w=t.w,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([t,n])=>[t,e.fromJSON(n)])||[]),n}},eU=class e extends $H{constructor(){super(``,``,!1)}static fromJSON(t){let n=new e;return n.w=t.w,n.s=t.s,n.e=t.e,n.k=t.k,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([e,t])=>[e,$H.fromJSON(t)])||[]),n}toJSON(){return super.toJSON()}},tU=class e{point;docIDs;left;right;parent;constructor(e,t){this.point=e,this.docIDs=new Set(t),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(t,n=null){let r=new e(t.point,t.docIDs);return r.parent=n,t.left&&(r.left=e.fromJSON(t.left,r)),t.right&&(r.right=e.fromJSON(t.right,r)),r}},nU=class e{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,t){let n=this.getPointKey(e),r=this.nodeMap.get(n);if(r){t.forEach(e=>r.docIDs.add(e));return}let i=new tU(e,t);if(this.nodeMap.set(n,i),this.root==null){this.root=i;return}let a=this.root,o=0;for(;;){if(o%2==0)if(e.lon<a.point.lon){if(a.left==null){a.left=i,i.parent=a;return}a=a.left}else{if(a.right==null){a.right=i,i.parent=a;return}a=a.right}else if(e.lat<a.point.lat){if(a.left==null){a.left=i,i.parent=a;return}a=a.left}else{if(a.right==null){a.right=i,i.parent=a;return}a=a.right}o++}}contains(e){let t=this.getPointKey(e);return this.nodeMap.has(t)}getDocIDsByCoordinates(e){let t=this.getPointKey(e),n=this.nodeMap.get(t);return n?Array.from(n.docIDs):null}removeDocByID(e,t){let n=this.getPointKey(e),r=this.nodeMap.get(n);r&&(r.docIDs.delete(t),r.docIDs.size===0&&(this.nodeMap.delete(n),this.deleteNode(r)))}deleteNode(e){let t=e.parent,n=e.left?e.left:e.right;n&&(n.parent=t),t?t.left===e?t.left=n:t.right===e&&(t.right=n):(this.root=n,this.root&&(this.root.parent=null))}searchByRadius(t,n,r=!0,i=`asc`,a=!1){let o=a?e.vincentyDistance:e.haversineDistance,s=[{node:this.root,depth:0}],c=[];for(;s.length>0;){let{node:e,depth:i}=s.pop();if(e==null)continue;let a=o(t,e.point);(r?a<=n:a>n)&&c.push({point:e.point,docIDs:Array.from(e.docIDs)}),e.left!=null&&s.push({node:e.left,depth:i+1}),e.right!=null&&s.push({node:e.right,depth:i+1})}return i&&c.sort((e,n)=>{let r=o(t,e.point),a=o(t,n.point);return i.toLowerCase()===`asc`?r-a:a-r}),c}searchByPolygon(t,n=!0,r=null,i=!1){let a=[{node:this.root,depth:0}],o=[];for(;a.length>0;){let{node:r,depth:i}=a.pop();if(r==null)continue;r.left!=null&&a.push({node:r.left,depth:i+1}),r.right!=null&&a.push({node:r.right,depth:i+1});let s=e.isPointInPolygon(t,r.point);(s&&n||!s&&!n)&&o.push({point:r.point,docIDs:Array.from(r.docIDs)})}let s=e.calculatePolygonCentroid(t);if(r){let t=i?e.vincentyDistance:e.haversineDistance;o.sort((e,n)=>{let i=t(s,e.point),a=t(s,n.point);return r.toLowerCase()===`asc`?i-a:a-i})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(t){let n=new e;return t.root&&(n.root=tU.fromJSON(t.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let t=this.getPointKey(e.point);this.nodeMap.set(t,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let t=0,n=0,r=0,i=e.length;for(let a=0,o=i-1;a<i;o=a++){let i=e[a].lon,s=e[a].lat,c=e[o].lon,l=e[o].lat,u=i*l-c*s;t+=u,n+=(i+c)*u,r+=(s+l)*u}t/=2;let a=6*t;return n/=a,r/=a,{lon:n,lat:r}}static isPointInPolygon(e,t){let n=!1,r=t.lon,i=t.lat,a=e.length;for(let t=0,o=a-1;t<a;o=t++){let a=e[t].lon,s=e[t].lat,c=e[o].lon,l=e[o].lat;s>i!=l>i&&r<(c-a)*(i-s)/(l-s)+a&&(n=!n)}return n}static haversineDistance(e,t){let n=Math.PI/180,r=e.lat*n,i=t.lat*n,a=(t.lat-e.lat)*n,o=(t.lon-e.lon)*n,s=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(i)*Math.sin(o/2)*Math.sin(o/2);return 6371e3*(2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s)))}static vincentyDistance(e,t){let n=6378137,r=1/298.257223563,i=(1-r)*n,a=Math.PI/180,o=e.lat*a,s=t.lat*a,c=(t.lon-e.lon)*a,l=Math.atan((1-r)*Math.tan(o)),u=Math.atan((1-r)*Math.tan(s)),d=Math.sin(l),f=Math.cos(l),p=Math.sin(u),m=Math.cos(u),h=c,g,_=1e3,v,y,b,x,S,C;do{let e=Math.sin(h),t=Math.cos(h);if(v=Math.sqrt(m*e*(m*e)+(f*p-d*m*t)*(f*p-d*m*t)),v===0)return 0;y=d*p+f*m*t,b=Math.atan2(v,y),x=f*m*e/v,S=1-x*x,C=y-2*d*p/S,isNaN(C)&&(C=0);let n=r/16*S*(4+r*(4-3*S));g=h,h=c+(1-n)*r*x*(b+n*v*(C+n*y*(-1+2*C*C)))}while(Math.abs(h-g)>1e-12&&--_>0);if(_===0)return NaN;let w=S*(n*n-i*i)/(i*i),T=1+w/16384*(4096+w*(-768+w*(320-175*w))),E=w/1024*(256+w*(-128+w*(74-47*w))),ee=E*v*(C+E/4*(y*(-1+2*C*C)-E/6*C*(-3+4*v*v)*(-3+4*C*C)));return i*T*(b-ee)}},rU=class e{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,t){t?this.true.add(e):this.false.add(e)}delete(e,t){t?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(t){let n=new e;return n.true=new Set(t.true),n.false=new Set(t.false),n}};function iU(e,t,n,r,i,{k:a,b:o,d:s}){return Math.log(1+(n-t+.5)/(t+.5))*(s+e*(a+1))/(e+a*(1-o+o*r/i))}var aU=class e{size;vectors=new Map;constructor(e){this.size=e}add(e,t){t instanceof Float32Array||(t=new Float32Array(t));let n=oU(t,this.size);this.vectors.set(e,[n,t])}remove(e){this.vectors.delete(e)}find(e,t,n){return e instanceof Float32Array||(e=new Float32Array(e)),sU(e,n,this.vectors,this.size,t)}toJSON(){let e=[];for(let[t,[n,r]]of this.vectors)e.push([t,[n,Array.from(r)]]);return{size:this.size,vectors:e}}static fromJSON(t){let n=t,r=new e(n.size);for(let[e,[t,i]]of n.vectors)r.vectors.set(e,[t,new Float32Array(i)]);return r}};function oU(e,t){let n=0;for(let r=0;r<t;r++)n+=e[r]*e[r];return Math.sqrt(n)}function sU(e,t,n,r,i){let a=oU(e,r),o=[],s=t||n.keys();for(let t of s){let s=n.get(t);if(!s)continue;let c=s[0],l=s[1],u=0;for(let t=0;t<r;t++)u+=e[t]*l[t];let d=u/(a*c);d>=i&&o.push([t,d])}return o}function cU(e,t,n,r,i){let a=DH(e.sharedInternalDocumentStore,n);e.avgFieldLength[t]=((e.avgFieldLength[t]??0)*(i-1)+r.length)/i,e.fieldLengths[t][a]=r.length,e.frequencies[t][a]={}}function lU(e,t,n,r,i){let a=0;for(let e of r)e===i&&a++;let o=DH(e.sharedInternalDocumentStore,n),s=a/r.length;e.frequencies[t][o][i]=s,i in e.tokenOccurrences[t]||(e.tokenOccurrences[t][i]=0),e.tokenOccurrences[t][i]=(e.tokenOccurrences[t][i]??0)+1}function uU(e,t,n,r){let i=DH(e.sharedInternalDocumentStore,n);r>1?e.avgFieldLength[t]=(e.avgFieldLength[t]*r-e.fieldLengths[t][i])/(r-1):e.avgFieldLength[t]=void 0,e.fieldLengths[t][i]=void 0,e.frequencies[t][i]=void 0}function dU(e,t,n){e.tokenOccurrences[t][n]--}function fU(e,t,n,r,i=``){r||={sharedInternalDocumentStore:t,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}};for(let[a,o]of Object.entries(n)){let n=`${i}${i?`.`:``}${a}`;if(typeof o==`object`&&!Array.isArray(o)){fU(e,t,o,r,n);continue}if(bH(o))r.searchableProperties.push(n),r.searchablePropertiesWithTypes[n]=o,r.vectorIndexes[n]={type:`Vector`,node:new aU(CH(o)),isArray:!1};else{let e=/\[/.test(o);switch(o){case`boolean`:case`boolean[]`:r.indexes[n]={type:`Bool`,node:new rU,isArray:e};break;case`number`:case`number[]`:r.indexes[n]={type:`AVL`,node:new YH(0,[]),isArray:e};break;case`string`:case`string[]`:r.indexes[n]={type:`Radix`,node:new eU,isArray:e},r.avgFieldLength[n]=0,r.frequencies[n]={},r.tokenOccurrences[n]={},r.fieldLengths[n]={};break;case`enum`:case`enum[]`:r.indexes[n]={type:`Flat`,node:new XH,isArray:e};break;case`geopoint`:r.indexes[n]={type:`BKD`,node:new nU,isArray:e};break;default:throw pH(`INVALID_SCHEMA_TYPE`,Array.isArray(o)?`array`:o,n)}r.searchableProperties.push(n),r.searchablePropertiesWithTypes[n]=o}}return r}function pU(e,t,n,r,i,a,o,s){return c=>{let{type:l,node:u}=t.indexes[n];switch(l){case`Bool`:u[c?`true`:`false`].add(r);break;case`AVL`:{let e=s?.avlRebalanceThreshold??1;u.insert(c,r,e);break}case`Radix`:{let s=a.tokenize(c,i,n,!1);e.insertDocumentScoreParameters(t,n,r,s,o);for(let i of s)e.insertTokenScoreParameters(t,n,r,s,i),u.insert(i,r);break}case`Flat`:u.insert(c,r);break;case`BKD`:u.insert(c,[r]);break}}}function mU(e,t,n,r,i,a,o,s,c,l,u){if(bH(o))return hU(t,n,a,r,i);let d=pU(e,t,n,i,s,c,l,u);if(!xH(o))return d(a);let f=a,p=f.length;for(let e=0;e<p;e++)d(f[e])}function hU(e,t,n,r,i){e.vectorIndexes[t].node.add(i,n)}function gU(e,t,n,r,i,a,o,s,c,l){if(bH(o))return t.vectorIndexes[n].node.remove(i),!0;let{type:u,node:d}=t.indexes[n];switch(u){case`AVL`:return d.removeDocument(a,i),!0;case`Bool`:return d[a?`true`:`false`].delete(i),!0;case`Radix`:{let o=c.tokenize(a,s,n);e.removeDocumentScoreParameters(t,n,r,l);for(let r of o)e.removeTokenScoreParameters(t,n,r),d.removeDocumentByWord(r,i);return!0}case`Flat`:return d.removeDocument(i,a),!0;case`BKD`:return d.removeDocByID(a,i),!1}}function _U(e,t,n,r,i,a,o,s,c,l){if(!xH(o))return gU(e,t,n,r,i,a,o,s,c,l);let u=SH(o),d=a,f=d.length;for(let a=0;a<f;a++)gU(e,t,n,r,i,d[a],u,s,c,l);return!0}function vU(e,t,n,r,i,a,o,s,c,l){let u=Array.from(r),d=e.avgFieldLength[t],f=e.fieldLengths[t],p=e.tokenOccurrences[t],m=e.frequencies[t],h=typeof p[n]==`number`?p[n]??0:0,g=u.length;for(let e=0;e<g;e++){let r=u[e];if(c&&!c.has(r))continue;l.has(r)||l.set(r,new Map);let p=l.get(r);p.set(t,(p.get(t)||0)+1);let g=iU(m?.[r]?.[n]??0,h,i,f[r],d,a);o.has(r)?o.set(r,o.get(r)+g*s):o.set(r,g*s)}}function yU(e,t,n,r,i,a,o,s,c,l,u,d=0){let f=n.tokenize(t,r),p=f.length||1,m=new Map,h=new Map,g=new Map;for(let n of i){if(!(n in e.indexes))continue;let r=e.indexes[n],{type:i}=r;if(i!==`Radix`)throw pH(`WRONG_SEARCH_PROPERTY_TYPE`,n);let d=s[n]??1;if(d<=0)throw pH(`INVALID_BOOST_VALUE`,d);f.length===0&&!t&&f.push(``);let p=f.length;for(let t=0;t<p;t++){let i=f[t],s=r.node.find({term:i,exact:a,tolerance:o}),p=Object.keys(s);p.length>0&&h.set(i,!0);let _=p.length;for(let t=0;t<_;t++){let r=p[t],i=s[r];vU(e,n,r,i,l,c,g,d,u,m)}}}let _=Array.from(g.entries()).map(([e,t])=>[e,t]).sort((e,t)=>t[1]-e[1]);if(_.length===0)return[];if(d===1)return _;if(d===0){if(p===1)return _;for(let e of f)if(!h.get(e))return[];return _.filter(([e])=>{let t=m.get(e);return t?Array.from(t.values()).some(e=>e===p):!1})}let v=_.filter(([e])=>{let t=m.get(e);return t?Array.from(t.values()).some(e=>e===p):!1});if(v.length>0){let e=_.filter(([e])=>!v.some(([t])=>t===e)),t=Math.ceil(e.length*d);return[...v,...e.slice(0,t)]}return _}function bU(e,t,n,r){if(`and`in n&&n.and&&Array.isArray(n.and)){let i=n.and;return i.length===0?new Set:sH(...i.map(n=>bU(e,t,n,r)))}if(`or`in n&&n.or&&Array.isArray(n.or)){let i=n.or;return i.length===0?new Set:i.map(n=>bU(e,t,n,r)).reduce((e,t)=>lH(e,t),new Set)}if(`not`in n&&n.not){let i=n.not,a=new Set,o=e.sharedInternalDocumentStore;for(let e=1;e<=o.internalIdToId.length;e++)a.add(e);return uH(a,bU(e,t,i,r))}let i=Object.keys(n),a=i.reduce((e,t)=>({[t]:new Set,...e}),{});for(let o of i){let i=n[o];if(e.indexes[o]===void 0)throw pH(`UNKNOWN_FILTER_PROPERTY`,o);let{node:s,type:c,isArray:l}=e.indexes[o];if(c===`Bool`){let e=s,t=i?e.true:e.false;a[o]=lH(a[o],t);continue}if(c===`BKD`){let e;if(`radius`in i)e=`radius`;else if(`polygon`in i)e=`polygon`;else throw Error(`Invalid operation ${i}`);if(e===`radius`){let{value:t,coordinates:n,unit:r=`m`,inside:c=!0,highPrecision:l=!1}=i[e],u=rH(t,r),d=s.searchByRadius(n,u,c,void 0,l);a[o]=EU(a[o],d)}else{let{coordinates:t,inside:n=!0,highPrecision:r=!1}=i[e],c=s.searchByPolygon(t,n,void 0,r);a[o]=EU(a[o],c)}continue}if(c===`Radix`&&(typeof i==`string`||Array.isArray(i))){for(let e of[i].flat()){let n=t.tokenize(e,r,o);for(let e of n){let t=s.find({term:e,exact:!0});a[o]=AU(a[o],t)}}continue}let u=Object.keys(i);if(u.length>1)throw pH(`INVALID_FILTER_OPERATION`,u.length);if(c===`Flat`){let e=new Set(l?s.filterArr(i):s.filter(i));a[o]=lH(a[o],e);continue}if(c===`AVL`){let e=u[0],t=i[e],n;switch(e){case`gt`:n=s.greaterThan(t,!1);break;case`gte`:n=s.greaterThan(t,!0);break;case`lt`:n=s.lessThan(t,!1);break;case`lte`:n=s.lessThan(t,!0);break;case`eq`:n=s.find(t)??new Set;break;case`between`:{let[e,r]=t;n=s.rangeSearch(e,r);break}default:throw pH(`INVALID_FILTER_OPERATION`,e)}a[o]=lH(a[o],n)}}return sH(...Object.values(a))}function xU(e){return e.searchableProperties}function SU(e){return e.searchablePropertiesWithTypes}function CU(e,t){let{indexes:n,vectorIndexes:r,searchableProperties:i,searchablePropertiesWithTypes:a,frequencies:o,tokenOccurrences:s,avgFieldLength:c,fieldLengths:l}=t,u={},d={};for(let e of Object.keys(n)){let{node:t,type:r,isArray:i}=n[e];switch(r){case`Radix`:u[e]={type:`Radix`,node:eU.fromJSON(t),isArray:i};break;case`Flat`:u[e]={type:`Flat`,node:XH.fromJSON(t),isArray:i};break;case`AVL`:u[e]={type:`AVL`,node:YH.fromJSON(t),isArray:i};break;case`BKD`:u[e]={type:`BKD`,node:nU.fromJSON(t),isArray:i};break;case`Bool`:u[e]={type:`Bool`,node:rU.fromJSON(t),isArray:i};break;default:u[e]=n[e]}}for(let e of Object.keys(r))d[e]={type:`Vector`,isArray:!1,node:aU.fromJSON(r[e])};return{sharedInternalDocumentStore:e,indexes:u,vectorIndexes:d,searchableProperties:i,searchablePropertiesWithTypes:a,frequencies:o,tokenOccurrences:s,avgFieldLength:c,fieldLengths:l}}function wU(e){let{indexes:t,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:i,frequencies:a,tokenOccurrences:o,avgFieldLength:s,fieldLengths:c}=e,l={};for(let e of Object.keys(n))l[e]=n[e].node.toJSON();let u={};for(let e of Object.keys(t)){let{type:n,node:r,isArray:i}=t[e];n===`Flat`||n===`Radix`||n===`AVL`||n===`BKD`||n===`Bool`?u[e]={type:n,node:r.toJSON(),isArray:i}:(u[e]=t[e],u[e].node=u[e].node.toJSON())}return{indexes:u,vectorIndexes:l,searchableProperties:r,searchablePropertiesWithTypes:i,frequencies:a,tokenOccurrences:o,avgFieldLength:s,fieldLengths:c}}function TU(){return{create:fU,insert:mU,remove:_U,insertDocumentScoreParameters:cU,insertTokenScoreParameters:lU,removeDocumentScoreParameters:uU,removeTokenScoreParameters:dU,calculateResultScores:vU,search:yU,searchByWhereClause:bU,getSearchableProperties:xU,getSearchablePropertiesWithTypes:SU,load:CU,save:wU}}function EU(e,t){e||=new Set;let n=t.length;for(let r=0;r<n;r++){let n=t[r].docIDs,i=n.length;for(let t=0;t<i;t++)e.add(n[t])}return e}function DU(e,t,n=!1){let r=n?nU.vincentyDistance:nU.haversineDistance,i=[],a=[];for(let{point:n}of e)a.push(r(t,n));let o=Math.max(...a),s=0;for(let{docIDs:t}of e){let e=o-a[s]+1;for(let n of t)i.push([n,e]);s++}return i.sort((e,t)=>t[1]-e[1]),i}function OU(e,t){let n=Object.keys(e);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],i=e[r];if(t.indexes[r]===void 0)return{isGeoOnly:!1};let{type:a}=t.indexes[r];return a===`BKD`&&i&&(`radius`in i||`polygon`in i)?{isGeoOnly:!0,geoProperty:r,geoOperation:i}:{isGeoOnly:!1}}function kU(e,t){let n=e,r=OU(t,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:i}=n.indexes[r.geoProperty],a=r.geoOperation,o=i,s;if(`radius`in a){let{value:e,coordinates:t,unit:n=`m`,inside:r=!0,highPrecision:i=!1}=a.radius,c=t,l=rH(e,n);return s=o.searchByRadius(c,l,r,`asc`,i),DU(s,c,i)}else if(`polygon`in a){let{coordinates:e,inside:t=!0,highPrecision:n=!1}=a.polygon;s=o.searchByPolygon(e,t,`asc`,n);let r=nU.calculatePolygonCentroid(e);return DU(s,r,n)}return null}function AU(e,t){e||=new Set;let n=Object.keys(t),r=n.length;for(let i=0;i<r;i++){let r=t[n[i]],a=r.length;for(let t=0;t<a;t++)e.add(r[t])}return e}function jU(e,t,n,r,i){let a={language:e.tokenizer.language,sharedInternalDocumentStore:t,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,s]of Object.entries(n)){let n=`${i}${i?`.`:``}${o}`;if(!r.includes(n)){if(typeof s==`object`&&!Array.isArray(s)){let i=jU(e,t,s,r,n);UV(a.sortableProperties,i.sortableProperties),a.sorts={...a.sorts,...i.sorts},a.sortablePropertiesWithTypes={...a.sortablePropertiesWithTypes,...i.sortablePropertiesWithTypes};continue}if(!bH(s))switch(s){case`boolean`:case`number`:case`string`:a.sortableProperties.push(n),a.sortablePropertiesWithTypes[n]=s,a.sorts[n]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:s};break;case`geopoint`:case`enum`:continue;case`enum[]`:case`boolean[]`:case`number[]`:case`string[]`:continue;default:throw pH(`INVALID_SORT_SCHEMA_TYPE`,Array.isArray(s)?`array`:s,n)}}}return a}function MU(e,t,n,r){return r?.enabled===!1?{disabled:!0}:jU(e,t,n,(r||{}).unsortableProperties||[],``)}function NU(e,t,n,r){if(!e.enabled)return;e.isSorted=!1;let i=DH(e.sharedInternalDocumentStore,n),a=e.sorts[t];a.orderedDocsToRemove.has(i)&&BU(e,t),a.docs.set(i,a.orderedDocs.length),a.orderedDocs.push([i,r])}function PU(e){if(e.isSorted||!e.enabled)return;let t=Object.keys(e.sorts);for(let n of t)RU(e,n);e.isSorted=!0}function FU(e,t,n){return t[1].localeCompare(n[1],IV(e))}function IU(e,t){return e[1]-t[1]}function LU(e,t){return t[1]?-1:1}function RU(e,t){let n=e.sorts[t],r;switch(n.type){case`string`:r=FU.bind(null,e.language);break;case`number`:r=IU.bind(null);break;case`boolean`:r=LU.bind(null);break}n.orderedDocs.sort(r);let i=n.orderedDocs.length;for(let e=0;e<i;e++){let t=n.orderedDocs[e][0];n.docs.set(t,e)}}function zU(e){let t=Object.keys(e.sorts);for(let n of t)BU(e,n)}function BU(e,t){let n=e.sorts[t];n.orderedDocsToRemove.size&&(n.orderedDocs=n.orderedDocs.filter(e=>!n.orderedDocsToRemove.has(e[0])),n.orderedDocsToRemove.clear())}function VU(e,t,n){if(!e.enabled)return;let r=e.sorts[t],i=DH(e.sharedInternalDocumentStore,n);r.docs.get(i)&&(r.docs.delete(i),r.orderedDocsToRemove.set(i,!0))}function HU(e,t,n){if(!e.enabled)throw pH(`SORT_DISABLED`);let r=n.property,i=n.order===`DESC`,a=e.sorts[r];if(!a)throw pH(`UNABLE_TO_SORT_ON_UNKNOWN_FIELD`,r,e.sortableProperties.join(`, `));return BU(e,r),PU(e),t.sort((t,n)=>{let r=a.docs.get(DH(e.sharedInternalDocumentStore,t[0])),o=a.docs.get(DH(e.sharedInternalDocumentStore,n[0])),s=r!==void 0,c=o!==void 0;return!s&&!c?0:s?c?i?o-r:r-o:-1:1}),t}function UU(e){return e.enabled?e.sortableProperties:[]}function WU(e){return e.enabled?e.sortablePropertiesWithTypes:{}}function GU(e,t){let n=t;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((e,t)=>{let{docs:r,orderedDocs:i,type:a}=n.sorts[t];return e[t]={docs:new Map(Object.entries(r).map(([e,t])=>[+e,t])),orderedDocsToRemove:new Map,orderedDocs:i,type:a},e},{});return{sharedInternalDocumentStore:e,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function KU(e){if(!e.enabled)return{enabled:!1};zU(e),PU(e);let t=Object.keys(e.sorts).reduce((t,n)=>{let{docs:r,orderedDocs:i,type:a}=e.sorts[n];return t[n]={docs:Object.fromEntries(r.entries()),orderedDocs:i,type:a},t},{});return{language:e.language,sortableProperties:e.sortableProperties,sortablePropertiesWithTypes:e.sortablePropertiesWithTypes,sorts:t,enabled:e.enabled,isSorted:e.isSorted}}function qU(){return{create:MU,insert:NU,remove:VU,save:KU,load:GU,sortBy:HU,getSortableProperties:UU,getSortablePropertiesWithTypes:WU}}const JU=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function YU(e){return e<192||e>383?e:JU[e-192]||e}function XU(e){let t=[];for(let n=0;n<e.length;n++)t[n]=YU(e.charCodeAt(n));return String.fromCharCode(...t)}const ZU={ational:`ate`,tional:`tion`,enci:`ence`,anci:`ance`,izer:`ize`,bli:`ble`,alli:`al`,entli:`ent`,eli:`e`,ousli:`ous`,ization:`ize`,ation:`ate`,ator:`ate`,alism:`al`,iveness:`ive`,fulness:`ful`,ousness:`ous`,aliti:`al`,iviti:`ive`,biliti:`ble`,logi:`log`},QU={icate:`ic`,ative:``,alize:`al`,iciti:`ic`,ical:`ic`,ful:``,ness:``},$U=`[aeiouy]`,eW=`[^aeiou][^aeiouy]*`;$U+``;const tW=`^(`+eW+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*`;``+eW;const nW=`^(`+eW+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*[aeiouy][aeiou]*[^aeiou][^aeiouy]*`,rW=`^(`+eW+`)?[aeiouy]`;function iW(e){let t,n,r,i,a,o;if(e.length<3)return e;let s=e.substring(0,1);if(s==`y`&&(e=s.toUpperCase()+e.substring(1)),r=/^(.+?)(ss|i)es$/,i=/^(.+?)([^s])s$/,r.test(e)?e=e.replace(r,`$1$2`):i.test(e)&&(e=e.replace(i,`$1$2`)),r=/^(.+?)eed$/,i=/^(.+?)(ed|ing)$/,r.test(e)){let t=r.exec(e);r=new RegExp(tW),r.test(t[1])&&(r=/.$/,e=e.replace(r,``))}else i.test(e)&&(t=i.exec(e)[1],i=new RegExp(rW),i.test(t)&&(e=t,i=/(at|bl|iz)$/,a=RegExp(`([^aeiouylsz])\\1$`),o=RegExp(`^`+eW+$U+`[^aeiouwxy]$`),i.test(e)?e+=`e`:a.test(e)?(r=/.$/,e=e.replace(r,``)):o.test(e)&&(e+=`e`)));if(r=/^(.+?)y$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(rW),t&&r.test(t)&&(e=t+`i`)),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(e)){let i=r.exec(e);t=i?.[1],n=i?.[2],r=new RegExp(tW),t&&r.test(t)&&(e=t+ZU[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(e)){let i=r.exec(e);t=i?.[1],n=i?.[2],r=new RegExp(tW),t&&r.test(t)&&(e=t+QU[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,i=/^(.+?)(s|t)(ion)$/,r.test(e))t=r.exec(e)?.[1],r=new RegExp(nW),t&&r.test(t)&&(e=t);else if(i.test(e)){let n=i.exec(e);t=n?.[1]??``+n?.[2]??``,i=new RegExp(nW),i.test(t)&&(e=t)}return r=/^(.+?)e$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(nW),i=RegExp(`^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*([aeiouy][aeiou]*)?$`),a=RegExp(`^`+eW+$U+`[^aeiouwxy]$`),t&&(r.test(t)||i.test(t)&&!a.test(t))&&(e=t)),r=/ll$/,i=new RegExp(nW),r.test(e)&&i.test(e)&&(r=/.$/,e=e.replace(r,``)),s==`y`&&(e=s.toLowerCase()+e.substring(1)),e}function aW(e,t,n=!0){let r=`${this.language}:${e}:${t}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(t)?(n&&this.normalizationCache.set(r,``),``):(this.stemmer&&!this.stemmerSkipProperties.has(e)&&(t=this.stemmer(t)),t=XU(t),n&&this.normalizationCache.set(r,t),t)}function oW(e){for(;e[e.length-1]===``;)e.pop();for(;e[0]===``;)e.shift();return e}function sW(e,t,n,r=!0){if(t&&t!==this.language)throw pH(`LANGUAGE_NOT_SUPPORTED`,t);if(typeof e!=`string`)return[e];let i=this.normalizeToken.bind(this,n??``),a;if(n&&this.tokenizeSkipProperties.has(n))a=[i(e,r)];else{let t=PV[this.language];a=e.toLowerCase().split(t).map(e=>i(e,r)).filter(Boolean)}let o=oW(a);return this.allowDuplicates?o:Array.from(new Set(o))}function cW(e={}){if(!e.language)e.language=`english`;else if(!FV.includes(e.language))throw pH(`LANGUAGE_NOT_SUPPORTED`,e.language);let t;if(e.stemming||e.stemmer&&!(`stemming`in e))if(e.stemmer){if(typeof e.stemmer!=`function`)throw pH(`INVALID_STEMMER_FUNCTION_TYPE`);t=e.stemmer}else if(e.language===`english`)t=iW;else throw pH(`MISSING_STEMMER`,e.language);let n;if(e.stopWords!==!1){if(n=[],Array.isArray(e.stopWords))n=e.stopWords;else if(typeof e.stopWords==`function`)n=e.stopWords(n);else if(e.stopWords)throw pH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);if(!Array.isArray(n))throw pH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);for(let e of n)if(typeof e!=`string`)throw pH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`)}let r={tokenize:sW,language:e.language,stemmer:t,stemmerSkipProperties:new Set(e.stemmerSkipProperties?[e.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(e.tokenizeSkipProperties?[e.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!e.allowDuplicates,normalizeToken:aW,normalizationCache:new Map};return r.tokenize=sW.bind(r),r.normalizeToken=aW,r}function lW(e){return{sharedInternalDocumentStore:e,rules:new Map}}function uW(e,t){if(e.rules.has(t.id))throw Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${t.id}" already exists. Use updateRule to modify it.`);e.rules.set(t.id,t)}function dW(e,t){if(!e.rules.has(t.id))throw Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${t.id}" because it does not exist. Use addRule to create it.`);e.rules.set(t.id,t)}function fW(e,t){return e.rules.delete(t)}function pW(e,t){return e.rules.get(t)}function mW(e){return Array.from(e.rules.values())}function hW(e,t){let n=e.toLowerCase().trim(),r=t.pattern.toLowerCase().trim();switch(t.anchoring){case`is`:return n===r;case`starts_with`:return n.startsWith(r);case`contains`:return n.includes(r);default:return!1}}function gW(e,t){return e?t.conditions.every(t=>hW(e,t)):!1}function _W(e,t){if(!t)return[];let n=[];for(let r of e.rules.values())gW(t,r)&&n.push(r);return n}function vW(e,t){return{sharedInternalDocumentStore:e,rules:new Map(t?.rules??[])}}function yW(e){return{rules:Array.from(e.rules.entries())}}function bW(){return{create:lW,addRule:uW,updateRule:dW,removeRule:fW,getRule:pW,getAllRules:mW,getMatchingRules:_W,load:vW,save:yW}}function xW(e){let t={formatElapsedTime:mH,getDocumentIndexId:hH,getDocumentProperties:eH,validateSchema:gH};for(let n of HH){let r=n;if(e[r]){if(typeof e[r]!=`function`)throw pH(`COMPONENT_MUST_BE_FUNCTION`,r)}else e[r]=t[r]}for(let t of Object.keys(e))if(!VH.includes(t)&&!HH.includes(t))throw pH(`UNSUPPORTED_COMPONENT`,t)}function SW({schema:e,sort:t,language:n,components:r,id:i,plugins:a}){r||={};for(let t of a??[]){if(!(`getComponents`in t)||typeof t.getComponents!=`function`)continue;let n=t.getComponents(e),i=Object.keys(n);for(let e of i)if(r[e])throw pH(`PLUGIN_COMPONENT_CONFLICT`,e,t.name);r={...r,...n}}i||=XV();let o=r.tokenizer,s=r.index,c=r.documentsStore,l=r.sorter,u=r.pinning;if(o=o?o.tokenize?o:cW(o):cW({language:n??`english`}),r.tokenizer&&n)throw pH(`NO_LANGUAGE_WITH_CUSTOM_TOKENIZER`);let d=wH();s||=TU(),l||=qU(),c||=RH(),u||=bW(),xW(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:m,formatElapsedTime:h}=r,g={data:{},caches:{},schema:e,tokenizer:o,index:s,sorter:l,documentsStore:c,pinning:u,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:m,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:h,id:i,plugins:a,version:CW()};g.data={index:g.index.create(g,d,e),docs:g.documentsStore.create(g,d),sorting:g.sorter.create(g,d,e,t),pinning:g.pinning.create(d)};for(let e of zH)g[e]=(g[e]??[]).concat(BH(g,e));let _=g.afterCreate;return _&&qH(_,g),g}function CW(){return`{{VERSION}}`}function wW(e){return e.documentsStore.count(e.data.docs)}function TW(e,t,n,r,i){let a=e.validateSchema(t,e.schema);if(a)throw pH(`SCHEMA_VALIDATION_FAILURE`,a);return aH(e.beforeInsert)||aH(e.afterInsert)||aH(e.index.beforeInsert)||aH(e.index.insert)||aH(e.index.afterInsert)?OW(e,t,n,r,i):kW(e,t,n,r,i)}const EW=new Set([`enum`,`enum[]`]),DW=new Set([`string`,`number`]);async function OW(e,t,n,r,i){let{index:a,docs:o}=e.data,s=e.getDocumentIndexId(t);if(typeof s!=`string`)throw pH(`DOCUMENT_ID_MUST_BE_STRING`,typeof s);let c=DH(e.internalDocumentIDStore,s);if(r||await UH(e.beforeInsert,e,s,t),!e.documentsStore.store(o,s,c,t))throw pH(`DOCUMENT_ALREADY_EXISTS`,s);let l=e.documentsStore.count(o),u=e.index.getSearchableProperties(a),d=e.index.getSearchablePropertiesWithTypes(a),f=e.getDocumentProperties(t,u);for(let[e,t]of Object.entries(f)){if(t===void 0)continue;let n=typeof t,r=d[e];AW(n,r,e,t)}return await jW(e,s,u,f,l,n,t,i),r||await UH(e.afterInsert,e,s,t),s}function kW(e,t,n,r,i){let{index:a,docs:o}=e.data,s=e.getDocumentIndexId(t);if(typeof s!=`string`)throw pH(`DOCUMENT_ID_MUST_BE_STRING`,typeof s);let c=DH(e.internalDocumentIDStore,s);if(r||UH(e.beforeInsert,e,s,t),!e.documentsStore.store(o,s,c,t))throw pH(`DOCUMENT_ALREADY_EXISTS`,s);let l=e.documentsStore.count(o),u=e.index.getSearchableProperties(a),d=e.index.getSearchablePropertiesWithTypes(a),f=e.getDocumentProperties(t,u);for(let[e,t]of Object.entries(f)){if(t===void 0)continue;let n=typeof t,r=d[e];AW(n,r,e,t)}return MW(e,s,u,f,l,n,t,i),r||UH(e.afterInsert,e,s,t),s}function AW(e,t,n,r){if(!(yH(t)&&typeof r==`object`&&typeof r.lon==`number`&&typeof r.lat==`number`)&&!(bH(t)&&Array.isArray(r))&&!(xH(t)&&Array.isArray(r))&&!(EW.has(t)&&DW.has(e))&&e!==t)throw pH(`INVALID_DOCUMENT_PROPERTY`,n,t,e)}async function jW(e,t,n,r,i,a,o,s){for(let o of n){let n=r[o];if(n===void 0)continue;let c=e.index.getSearchablePropertiesWithTypes(e.data.index)[o];await e.index.beforeInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i);let l=e.internalDocumentIDStore.idToInternalId.get(t);await e.index.insert(e.index,e.data.index,o,t,l,n,c,a,e.tokenizer,i,s),await e.index.afterInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i)}let c=e.sorter.getSortableProperties(e.data.sorting),l=e.getDocumentProperties(o,c);for(let n of c){let r=l[n];if(r===void 0)continue;let i=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[n];e.sorter.insert(e.data.sorting,n,t,r,i,a)}}function MW(e,t,n,r,i,a,o,s){for(let o of n){let n=r[o];if(n===void 0)continue;let c=e.index.getSearchablePropertiesWithTypes(e.data.index)[o],l=DH(e.internalDocumentIDStore,t);e.index.beforeInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i),e.index.insert(e.index,e.data.index,o,t,l,n,c,a,e.tokenizer,i,s),e.index.afterInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i)}let c=e.sorter.getSortableProperties(e.data.sorting),l=e.getDocumentProperties(o,c);for(let n of c){let r=l[n];if(r===void 0)continue;let i=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[n];e.sorter.insert(e.data.sorting,n,t,r,i,a)}}function NW(e,t,n,r,i,a){return aH(e.afterInsertMultiple)||aH(e.beforeInsertMultiple)||aH(e.index.beforeInsert)||aH(e.index.insert)||aH(e.index.afterInsert)?PW(e,t,n,r,i,a):FW(e,t,n,r,i,a)}async function PW(e,t,n=1e3,r,i,a=0){let o=[],s=async a=>{let s=Math.min(a+n,t.length),c=t.slice(a,s);for(let t of c){let n=await TW(e,t,r,i,{avlRebalanceThreshold:c.length});o.push(n)}return s};return await(async()=>{let e=0;for(;e<t.length;){let t=Date.now();if(e=await s(e),a>0){let e=a-(Date.now()-t);e>0&&dH(e)}}})(),i||await WH(e.afterInsertMultiple,e,t),o}function FW(e,t,n=1e3,r,i,a=0){let o=[],s=0;function c(){let a=t.slice(s*n,(s+1)*n);if(a.length===0)return!1;for(let t of a){let n=TW(e,t,r,i,{avlRebalanceThreshold:a.length});o.push(n)}return s++,!0}function l(){let e=Date.now();for(;c();)if(a>0){let t=Date.now()-e;if(t>=a){let e=a-t%a;e>0&&dH(e)}}}return l(),i||WH(e.afterInsertMultiple,e,t),o}function IW(e,t){return e[1]-t[1]}function LW(e,t){return t[1]-e[1]}function RW(e=`desc`){return e.toLowerCase()===`asc`?IW:LW}function zW(e,t,n){let r={},i=t.map(([e])=>e),a=e.documentsStore.getMultiple(e.data.docs,i),o=Object.keys(n),s=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e of o){let t;if(s[e]===`number`){let{ranges:r}=n[e],i=r.length,a=Array.from({length:i});for(let e=0;e<i;e++){let t=r[e];a[e]=[`${t.from}-${t.to}`,0]}t=Object.fromEntries(a)}r[e]={count:0,values:t??{}}}let c=a.length;for(let e=0;e<c;e++){let t=a[e];for(let e of o){let i=e.includes(`.`)?tH(t,e):t[e],a=s[e],o=r[e].values;switch(a){case`number`:{let t=n[e].ranges;BW(t,o)(i);break}case`number[]`:{let t=new Set,r=n[e].ranges,a=BW(r,o,t);for(let e of i)a(e);break}case`boolean`:case`enum`:case`string`:VW(o,a)(i);break;case`boolean[]`:case`enum[]`:case`string[]`:{let e=VW(o,a===`boolean[]`?`boolean`:`string`,new Set);for(let t of i)e(t);break}default:throw pH(`FACET_NOT_SUPPORTED`,a)}}}for(let e of o){let t=r[e];if(t.count=Object.keys(t.values).length,s[e]===`string`){let r=n[e],i=RW(r.sort);t.values=Object.fromEntries(Object.entries(t.values).sort(i).slice(r.offset??0,r.limit??10))}}return r}function BW(e,t,n){return r=>{for(let i of e){let e=`${i.from}-${i.to}`;n?.has(e)||r>=i.from&&r<=i.to&&(t[e]===void 0?t[e]=1:(t[e]++,n?.add(e)))}}}function VW(e,t,n){let r=t===`boolean`?`false`:``;return t=>{let i=t?.toString()??r;n?.has(i)||(e[i]=(e[i]??0)+1,n?.add(i))}}const HW={reducer:(e,t,n,r)=>(t[r]=n,t),getInitialValue:e=>Array.from({length:e})},UW=[`string`,`number`,`boolean`];function WW(e,t,n){let r=n.properties,i=r.length,a=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e=0;e<i;e++){let t=r[e];if(a[t]===void 0)throw pH(`UNKNOWN_GROUP_BY_PROPERTY`,t);if(!UW.includes(a[t]))throw pH(`INVALID_GROUP_BY_PROPERTY`,t,UW.join(`, `),a[t])}let o=t.map(([t])=>OH(e.internalDocumentIDStore,t)),s=e.documentsStore.getMultiple(e.data.docs,o),c=s.length,l=n.maxResult||2**53-1,u=[],d={};for(let e=0;e<i;e++){let t=r[e],n={property:t,perValue:{}},i=new Set;for(let e=0;e<c;e++){let r=s[e],a=tH(r,t);if(a===void 0)continue;let o=typeof a==`boolean`?``+a:a,c=n.perValue[o]??{indexes:[],count:0};c.count>=l||(c.indexes.push(e),c.count++,n.perValue[o]=c,i.add(a))}u.push(Array.from(i)),d[t]=n}let f=GW(u),p=f.length,m=[];for(let e=0;e<p;e++){let t=f[e],n=t.length,i={values:[],indexes:[]},a=[];for(let e=0;e<n;e++){let n=t[e],o=r[e];a.push(d[o].perValue[typeof n==`boolean`?``+n:n].indexes),i.values.push(n)}i.indexes=$V(a).sort((e,t)=>e-t),i.indexes.length!==0&&m.push(i)}let h=m.length,g=Array.from({length:h});for(let e=0;e<h;e++){let r=m[e],i=n.reduce||HW,a=r.indexes.map(e=>({id:o[e],score:t[e][1],document:s[e]})),c=i.reducer.bind(null,r.values),l=i.getInitialValue(r.indexes.length),u=a.reduce(c,l);g[e]={values:r.values,result:u}}return g}function GW(e,t=0){if(t+1===e.length)return e[t].map(e=>[e]);let n=e[t],r=GW(e,t+1),i=[];for(let e of n)for(let t of r){let n=[e];UV(n,t),i.push(n)}return i}function KW(e,t,n,r){let i=_W(t,r);if(i.length===0)return n;let a=i.flatMap(e=>e.consequence.promote);a.sort((e,t)=>e.position-t.position);let o=new Set,s=new Map,c=new Set;for(let t of a){let n=DH(e.internalDocumentIDStore,t.doc_id);if(n!==void 0){if(s.has(n)){let e=s.get(n);t.position<e&&s.set(n,t.position);continue}c.has(t.position)||(o.add(n),s.set(n,t.position),c.add(t.position))}}if(s.size===0)return n;let l=n.filter(([e])=>!o.has(e)),u=[];for(let[t,r]of s.entries())n.find(([e])=>e===t)?u.push([t,1e6-r]):e.documentsStore.get(e.data.docs,t)&&u.push([t,0]);u.sort((e,t)=>(s.get(e[0])??1/0)-(s.get(t[0])??1/0));let d=[],f=new Map;for(let e of u){let t=s.get(e[0]);f.set(t,e)}let p=0,m=0;for(;m<l.length+u.length;)if(f.has(m))d.push(f.get(m)),m++;else if(p<l.length)d.push(l[p]),p++,m++;else break;for(let[e,t]of f.entries())e>=d.length&&d.push(t);return d}function qW(e,t,n){let{term:r,properties:i}=t,a=e.data.index,o=e.caches.propertiesToSearch;if(!o){let t=e.index.getSearchablePropertiesWithTypes(a);o=e.index.getSearchableProperties(a),o=o.filter(e=>t[e].startsWith(`string`)),e.caches.propertiesToSearch=o}if(i&&i!==`*`){for(let e of i)if(!o.includes(e))throw pH(`UNKNOWN_INDEX`,e,o.join(`, `));o=o.filter(e=>i.includes(e))}let s=Object.keys(t.where??{}).length>0,c;s&&(c=e.index.searchByWhereClause(a,e.tokenizer,t.where,n));let l,u=t.threshold!==void 0&&t.threshold!==null?t.threshold:1;if(r||i){let i=wW(e);if(l=e.index.search(a,r||``,e.tokenizer,n,o,t.exact||!1,t.tolerance||0,t.boost||{},QW(t.relevance),i,c,u),t.exact&&r){let t=r.trim().split(/\s+/);l=l.filter(([n])=>{let r=e.documentsStore.get(e.data.docs,n);if(!r)return!1;for(let e of o){let n=YW(r,e);if(typeof n==`string`&&t.every(e=>RegExp(`\\b${JW(e)}\\b`).test(n)))return!0}return!1})}}else l=s?kU(a,t.where)||(c?Array.from(c):[]).map(e=>[+e,0]):Object.keys(e.documentsStore.getAll(e.data.docs)).map(e=>[+e,0]);return l}function JW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function YW(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r&&typeof r==`object`&&e in r)r=r[e];else return;return r}function XW(e,t,n){let r=YV();function i(){let i=Object.keys(e.data.index.vectorIndexes),a=t.facets&&Object.keys(t.facets).length>0,{limit:o=10,offset:s=0,distinctOn:c,includeVectors:l=!1}=t,u=t.preflight===!0,d=qW(e,t,n);if(t.sortBy)if(typeof t.sortBy==`function`){let n=d.map(([e])=>e),r=e.documentsStore.getMultiple(e.data.docs,n).map((e,t)=>[d[t][0],d[t][1],e]);r.sort(t.sortBy),d=r.map(([e,t])=>[e,t])}else d=e.sorter.sortBy(e.data.sorting,d,t.sortBy).map(([t,n])=>[DH(e.internalDocumentIDStore,t),n]);else d=d.sort(QV);d=KW(e,e.data.pinning,d,t.term);let f;u||(f=c?uG(e,d,s,o,c):dG(e,d,s,o));let p={elapsed:{formatted:``,raw:0},hits:[],count:d.length};return f!==void 0&&(p.hits=f.filter(Boolean),l||iH(p,i)),a&&(p.facets=zW(e,d,t.facets)),t.groupBy&&(p.groups=WW(e,d,t.groupBy)),p.elapsed=e.formatElapsedTime(YV()-r),p}async function a(){e.beforeSearch&&await KH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await GH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}const ZW={k:1.2,b:.75,d:.5};function QW(e){let t=e??{};return t.k=t.k??ZW.k,t.b=t.b??ZW.b,t.d=t.d??ZW.d,t}function $W(e,t,n){let r=t.vector;if(r&&(!(`value`in r)||!(`property`in r)))throw pH(`INVALID_VECTOR_INPUT`,Object.keys(r).join(`, `));let i=e.data.index.vectorIndexes[r.property];if(!i)throw pH(`UNKNOWN_VECTOR_PROPERTY`,r.property);let a=i.node.size;if(r?.value.length!==a)throw r?.property===void 0||r?.value.length===void 0?pH(`INVALID_INPUT_VECTOR`,`undefined`,a,`undefined`):pH(`INVALID_INPUT_VECTOR`,r.property,a,r.value.length);let o=e.data.index,s;return Object.keys(t.where??{}).length>0&&(s=e.index.searchByWhereClause(o,e.tokenizer,t.where,n)),i.node.find(r.value,t.similarity??.8,s)}function eG(e,t,n=`english`){let r=YV();function i(){let i=$W(e,t,n).sort(QV);i=KW(e,e.data.pinning,i,void 0);let a=[];t.facets&&Object.keys(t.facets).length>0&&(a=zW(e,i,t.facets));let o=t.vector.property,s=t.includeVectors??!1,c=t.limit??10,l=t.offset??0,u=Array.from({length:c});for(let t=0;t<c;t++){let n=i[t+l];if(!n)break;let r=e.data.docs.docs[n[0]];r&&(s||(r[o]=null),u[t]={id:OH(e.internalDocumentIDStore,n[0]),score:n[1],document:r})}let d=[];t.groupBy&&(d=WW(e,i,t.groupBy));let f=YV()-r;return{count:i.length,hits:u.filter(Boolean),elapsed:{raw:Number(f),formatted:JV(f)},...a?{facets:a}:{},...d?{groups:d}:{}}}async function a(){e.beforeSearch&&await KH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await GH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}function tG(e,t,n){let r=iG(qW(e,t,n)),i=$W(e,t,n),a=t.hybridWeights;return sG(r,i,t.term??``,a)}function nG(e,t,n){let r=YV();function i(){let i=tG(e,t,n);i=KW(e,e.data.pinning,i,t.term);let a;t.facets&&Object.keys(t.facets).length>0&&(a=zW(e,i,t.facets));let o;t.groupBy&&(o=WW(e,i,t.groupBy));let s=t.offset??0,c=t.limit??10,l=dG(e,i,s,c).filter(Boolean),u=YV(),d={count:i.length,elapsed:{raw:Number(u-r),formatted:JV(u-r)},hits:l,...a?{facets:a}:{},...o?{groups:o}:{}};return(t.includeVectors??!1)||iH(d,Object.keys(e.data.index.vectorIndexes)),d}async function a(){e.beforeSearch&&await KH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await GH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}function rG(e){return e[1]}function iG(e){let t=Math.max.apply(Math,e.map(rG));return e.map(([e,n])=>[e,n/t])}function aG(e,t){return e/t}function oG(e,t){return(n,r)=>n*e+r*t}function sG(e,t,n,r){let i=Math.max.apply(Math,e.map(rG)),a=Math.max.apply(Math,t.map(rG)),{text:o,vector:s}=r&&r.text&&r.vector?r:cG(n),c=new Map,l=e.length,u=oG(o,s);for(let t=0;t<l;t++){let[n,r]=e[t],a=u(aG(r,i),0);c.set(n,a)}let d=t.length;for(let e=0;e<d;e++){let[n,r]=t[e],i=aG(r,a),o=c.get(n)??0;c.set(n,o+u(0,i))}return[...c].sort((e,t)=>t[1]-e[1])}function cG(e){return{text:.5,vector:.5}}function lG(e,t,n){let r=t.mode??`fulltext`;if(r===`fulltext`)return XW(e,t,n);if(r===`vector`)return eG(e,t);if(r===`hybrid`)return nG(e,t);throw pH(`INVALID_SEARCH_MODE`,r)}function uG(e,t,n,r,i){let a=e.data.docs,o=new Map,s=[],c=new Set,l=t.length,u=0;for(let d=0;d<l;d++){let l=t[d];if(l===void 0)continue;let[f,p]=l;if(c.has(f))continue;let m=e.documentsStore.get(a,f),h=tH(m,i);if(!(h===void 0||o.has(h))&&(o.set(h,!0),u++,!(u<=n)&&(s.push({id:OH(e.internalDocumentIDStore,f),score:p,document:m}),c.add(f),u>=n+r)))break}return s}function dG(e,t,n,r){let i=e.data.docs,a=Array.from({length:r}),o=new Set;for(let s=n;s<r+n;s++){let n=t[s];if(n===void 0)break;let[r,c]=n;if(!o.has(r)){let t=e.documentsStore.get(i,r);a[s]={id:OH(e.internalDocumentIDStore,r),score:c,document:t},o.add(r)}}return a}var fG=n(OV(),1);const pG=1,mG={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`};function hG({kind:e,runtimeVersion:t}){return{[mG.protocol]:`1`,[mG.runtime]:t,[mG.kind]:e}}const gG=`__system__`,_G=1,vG=`__config__/project`,yG=`__user__/config.yml`,bG=`__local__/project`,xG=`__config__/okignore`,SG=Object.freeze([vG,bG,yG,xG]),CG=`__skill__/`,wG=`__template__/`,TG=[`project`,`global`];function EG(e){return e.startsWith(`__skill__/`)||e.startsWith(`__template__/`)}const DG=`.ok/skills`;function OG(e){return`${DG}/${e}/SKILL`}const kG=[`references`,`scripts`];function AG(e,t){let n=/^(\.ok\/skills\/[^/]+)\/SKILL$/.exec(t);if(!n)return null;let r=n[1],i=e.trim().replace(/\.mdx?$/i,``).split(`/`).filter(e=>e!==``&&e!==`.`),[a]=i;return!a||!kG.includes(a)||i.includes(`..`)||i.length<2?null:`${r}/${i.join(`/`)}`}const jG=/^\.ok\/skills\/([^/]+)\/(SKILL|references\/.+)$/;function MG(e){let t=jG.exec(e);if(!t)return null;let n=t[1],r=t[2];return r===`SKILL`?{name:n,kind:`skill`,rel:null}:{name:n,kind:`reference`,rel:r.slice(11)}}const NG=/^__skill__\/global\/([^/]+)(?:\/(references\/.+))?$/;function PG(e){let t=NG.exec(e);if(!t)return null;let n=t[1],r=t[2];return r===void 0?{name:n,kind:`skill`,rel:null}:{name:n,kind:`reference`,rel:r.slice(11)}}function FG(e,t){return e===`project`?OG(t):`${CG}${e}/${t}`}function IG(e){if(e===``)return``;try{return e.split(`/`).map(e=>decodeURIComponent(e)).join(`/`)}catch{return e}}function LG(e){if(e.startsWith(`__skill__/`)){let t=e.slice(10),n=t.indexOf(`/`);if(n<0)return null;let r=t.slice(0,n);if(r!==`global`&&r!==`project`)return null;let i=t.slice(n+1);return i?{kind:`skill`,scope:r,name:IG(i)}:null}if(e.startsWith(`__template__/`)){let t=e.slice(13);if(!t)return null;let n=t.lastIndexOf(`/`),r=n<0?t:t.slice(n+1);return r?{kind:`template`,folder:IG(n<0?``:t.slice(0,n)),name:IG(r)}:null}return null}const RG=/^(?:(.+)\/)?\.ok\/templates\/([^/]+?)(?:\.mdx?)?$/;function zG(e){let t=RG.exec(e);if(t){let e=(t[1]??``).replace(/^\/+|\/+$/g,``);return`${wG}${e?`${e}/`:``}${t[2]}`}return null}const BG=[`.mdx`,`.md`],VG=`epoch`,HG=512*1024,UG=[`claude`,`claude-desktop`,`cursor`,`codex`,`opencode`,`openclaw`,`pi`,`antigravity`],WG={claude:`Claude`,"claude-desktop":`Claude Desktop`,cursor:`Cursor`,codex:`Codex`,opencode:`OpenCode`,openclaw:`OpenClaw`,pi:`Pi`,antigravity:`Antigravity`},GG={claude:`.claude/skills`,"claude-desktop":null,cursor:`.cursor/skills`,codex:`.codex/skills`,opencode:`.opencode/skills`,openclaw:null,pi:`.pi/skills`,antigravity:null},KG=UG.filter(e=>GG[e]!==null),qG=KG.filter(e=>e!==`pi`).map(e=>({hostDir:(GG[e]??``).split(`/`)[0],editorId:e})),JG={claude:`.mcp.json`,"claude-desktop":null,cursor:`.cursor/mcp.json`,codex:`.codex/config.toml`,opencode:`opencode.json`,openclaw:null,pi:`.pi/extensions/open-knowledge.ts`,antigravity:null},YG={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},XG=`Ov23liqlSd0V1MwR6rhI`,ZG=[`incoming`,`outgoing`,`both`];function QG(e){return ZG.includes(e)}const $G=`open-knowledge`,eK=[{id:`chart`,title:`Chart`,description:`A bar chart whose series colors track the OK chart palette.`,html:`<div style="font-family:system-ui,sans-serif;padding:20px;color:var(--foreground)">
304
+ `,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:`The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.`,PLUGIN_COMPONENT_CONFLICT:`The component "%s" is already defined. The plugin "%s" is trying to redefine it.`};function pH(e,...t){let n=Error(WV(fH[e]??`Unsupported Orama Error code: ${e}`,...t));return n.code=e,`captureStackTrace`in Error.prototype&&Error.captureStackTrace(n),n}function mH(e){return{raw:Number(e),formatted:JV(e)}}function hH(e){if(e.id){if(typeof e.id!=`string`)throw pH(`DOCUMENT_ID_MUST_BE_STRING`,typeof e.id);return e.id}return XV()}function gH(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];if(t!==void 0&&!(r===`geopoint`&&typeof t==`object`&&typeof t.lon==`number`&&typeof t.lat==`number`)&&!(r===`enum`&&(typeof t==`string`||typeof t==`number`))){if(r===`enum[]`&&Array.isArray(t)){let e=t.length;for(let r=0;r<e;r++)if(typeof t[r]!=`string`&&typeof t[r]!=`number`)return n+`.`+r;continue}if(bH(r)){let e=CH(r);if(!Array.isArray(t)||t.length!==e)throw pH(`INVALID_INPUT_VECTOR`,n,e,t.length);continue}if(xH(r)){if(!Array.isArray(t))return n;let e=SH(r),i=t.length;for(let r=0;r<i;r++)if(typeof t[r]!==e)return n+`.`+r;continue}if(typeof r==`object`){if(!t||typeof t!=`object`)return n;let e=gH(t,r);if(e)return n+`.`+e;continue}if(typeof t!==r)return n}}}const _H={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},vH={"string[]":`string`,"number[]":`number`,"boolean[]":`boolean`,"enum[]":`enum`};function yH(e){return e===`geopoint`}function bH(e){return typeof e==`string`&&/^vector\[\d+\]$/.test(e)}function xH(e){return typeof e==`string`&&_H[e]}function SH(e){return vH[e]}function CH(e){let t=Number(e.slice(7,-1));switch(!0){case isNaN(t):throw pH(`INVALID_VECTOR_VALUE`,e);case t<=0:throw pH(`INVALID_VECTOR_SIZE`,e);default:return t}}function wH(){return{idToInternalId:new Map,internalIdToId:[],save:TH,load:EH}}function TH(e){return{internalIdToId:e.internalIdToId}}function EH(e,t){let{internalIdToId:n}=t;e.internalDocumentIDStore.idToInternalId.clear(),e.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let t=0;t<r;t++){let r=n[t];e.internalDocumentIDStore.idToInternalId.set(r,t+1),e.internalDocumentIDStore.internalIdToId.push(r)}}function DH(e,t){if(typeof t==`string`){let n=e.idToInternalId.get(t);if(n)return n;let r=e.idToInternalId.size+1;return e.idToInternalId.set(t,r),e.internalIdToId.push(t),r}return t>e.internalIdToId.length?DH(e,t.toString()):t}function OH(e,t){if(e.internalIdToId.length<t)throw Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function kH(e,t){return{sharedInternalDocumentStore:t,docs:{},count:0}}function AH(e,t){let n=DH(e.sharedInternalDocumentStore,t);return e.docs[n]}function jH(e,t){let n=t.length,r=Array.from({length:n});for(let i=0;i<n;i++){let n=DH(e.sharedInternalDocumentStore,t[i]);r[i]=e.docs[n]}return r}function MH(e){return e.docs}function NH(e,t,n,r){return e.docs[n]===void 0?(e.docs[n]=r,e.count++,!0):!1}function PH(e,t){let n=DH(e.sharedInternalDocumentStore,t);return e.docs[n]===void 0?!1:(delete e.docs[n],e.count--,!0)}function FH(e){return e.count}function IH(e,t){let n=t;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:e}}function LH(e){return{docs:e.docs,count:e.count}}function RH(){return{create:kH,get:AH,getMultiple:jH,getAll:MH,store:NH,remove:PH,count:FH,load:IH,save:LH}}const zH=[`beforeInsert`,`afterInsert`,`beforeRemove`,`afterRemove`,`beforeUpdate`,`afterUpdate`,`beforeUpsert`,`afterUpsert`,`beforeSearch`,`afterSearch`,`beforeInsertMultiple`,`afterInsertMultiple`,`beforeRemoveMultiple`,`afterRemoveMultiple`,`beforeUpdateMultiple`,`afterUpdateMultiple`,`beforeUpsertMultiple`,`afterUpsertMultiple`,`beforeLoad`,`afterLoad`,`afterCreate`];function BH(e,t){let n=[],r=e.plugins?.length;if(!r)return n;for(let i=0;i<r;i++)try{let r=e.plugins[i];typeof r[t]==`function`&&n.push(r[t])}catch(e){throw console.error(`Caught error in getAllPluginsByHook:`,e),pH(`PLUGIN_CRASHED`)}return n}const VH=[`tokenizer`,`index`,`documentsStore`,`sorter`,`pinning`],HH=[`validateSchema`,`getDocumentIndexId`,`getDocumentProperties`,`formatElapsedTime`];function UH(e,t,n,r){if(e.some(aH))return(async()=>{for(let i of e)await i(t,n,r)})();for(let i of e)i(t,n,r)}function WH(e,t,n){if(e.some(aH))return(async()=>{for(let r of e)await r(t,n)})();for(let r of e)r(t,n)}function GH(e,t,n,r,i){if(e.some(aH))return(async()=>{for(let a of e)await a(t,n,r,i)})();for(let a of e)a(t,n,r,i)}function KH(e,t,n,r){if(e.some(aH))return(async()=>{for(let i of e)await i(t,n,r)})();for(let i of e)i(t,n,r)}function qH(e,t){if(e.some(aH))return(async()=>{for(let n of e)await n(t)})();for(let n of e)n(t)}var JH=class e{k;v;l=null;r=null;h=1;constructor(e,t){this.k=e,this.v=new Set(t)}updateHeight(){this.h=Math.max(e.getHeight(this.l),e.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return e.getHeight(this.l)-e.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(t){let n=new e(t.k,t.v);return n.l=t.l?e.fromJSON(t.l):null,n.r=t.r?e.fromJSON(t.r):null,n.h=t.h,n}},YH=class e{root=null;insertCount=0;constructor(e,t){e!==void 0&&t!==void 0&&(this.root=new JH(e,t))}insert(e,t,n=1e3){this.root=this.insertNode(this.root,e,t,n)}insertMultiple(e,t,n=1e3){for(let r of t)this.insert(e,r,n)}rebalance(){this.root&&=this.rebalanceNode(this.root)}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(t){let n=new e;return n.root=t.root?JH.fromJSON(t.root):null,n.insertCount=t.insertCount||0,n}insertNode(e,t,n,r){if(e===null)return new JH(t,[n]);let i=[],a=e,o=null;for(;a!==null;)if(i.push({parent:o,node:a}),t<a.k)if(a.l===null){a.l=new JH(t,[n]),i.push({parent:a,node:a.l});break}else o=a,a=a.l;else if(t>a.k)if(a.r===null){a.r=new JH(t,[n]),i.push({parent:a,node:a.r});break}else o=a,a=a.r;else return a.v.add(n),e;let s=!1;this.insertCount++%r===0&&(s=!0);for(let t=i.length-1;t>=0;t--){let{parent:n,node:r}=i[t];if(r.updateHeight(),s){let t=this.rebalanceNode(r);n?n.l===r?n.l=t:n.r===r&&(n.r=t):e=t}}return e}rebalanceNode(e){let t=e.getBalanceFactor();if(t>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(t<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let t=this.findNodeByKey(e);return t?t.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,t=[],n=this.root;for(;n||t.length>0;){for(;n;)t.push(n),n=n.l;n=t.pop(),e++,n=n.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let t=e.pop(),n=t.getBalanceFactor();if(Math.abs(n)>1)return!1;t.l&&e.push(t.l),t.r&&e.push(t.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,t){let n=this.findNodeByKey(e);n&&(n.v.size===1?this.root=this.removeNode(this.root,e):n.v=new Set([...n.v.values()].filter(e=>e!==t)))}findNodeByKey(e){let t=this.root;for(;t;)if(e<t.k)t=t.l;else if(e>t.k)t=t.r;else return t;return null}removeNode(e,t){if(e===null)return null;let n=[],r=e;for(;r!==null&&r.k!==t;)n.push(r),r=t<r.k?r.l:r.r;if(r===null)return e;if(r.l===null||r.r===null){let t=r.l?r.l:r.r;if(n.length===0)e=t;else{let e=n[n.length-1];e.l===r?e.l=t:e.r=t}}else{let e=r,t=r.r;for(;t.l!==null;)e=t,t=t.l;r.k=t.k,r.v=t.v,e.l===t?e.l=t.r:e.r=t.r,r=e}n.push(r);for(let t=n.length-1;t>=0;t--){let r=n[t];r.updateHeight();let i=this.rebalanceNode(r);if(t>0){let e=n[t-1];e.l===r?e.l=i:e.r===r&&(e.r=i)}else e=i}return e}rangeSearch(e,t){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.l;if(i=r.pop(),i.k>=e&&i.k<=t)for(let e of i.v)n.add(e);if(i.k>t)break;i=i.r}return n}greaterThan(e,t=!1){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.r;if(i=r.pop(),t&&i.k>=e||!t&&i.k>e)for(let e of i.v)n.add(e);else if(i.k<=e)break;i=i.l}return n}lessThan(e,t=!1){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.l;if(i=r.pop(),t&&i.k<=e||!t&&i.k<e)for(let e of i.v)n.add(e);else if(i.k>e)break;i=i.r}return n}},XH=class e{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,t){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(t):this.numberToDocumentId.set(e,new Set([t]))}find(e){let t=this.numberToDocumentId.get(e);return t?Array.from(t):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,t){let n=this.numberToDocumentId.get(t);n&&(n.delete(e),n.size===0&&this.numberToDocumentId.delete(t))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let t of this.numberToDocumentId.values())e+=t.size;return e}filter(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let n=t[0];switch(n){case`eq`:{let t=e[n],r=this.numberToDocumentId.get(t);return r?Array.from(r):[]}case`in`:{let t=e[n],r=new Set;for(let e of t){let t=this.numberToDocumentId.get(e);if(t)for(let e of t)r.add(e)}return Array.from(r)}case`nin`:{let t=new Set(e[n]),r=new Set;for(let[e,n]of this.numberToDocumentId.entries())if(!t.has(e))for(let e of n)r.add(e);return Array.from(r)}default:throw Error(`Invalid operation`)}}filterArr(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let n=t[0];switch(n){case`containsAll`:{let t=e[n].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let r=t.reduce((e,t)=>new Set([...e].filter(e=>t.has(e))));return Array.from(r)}case`containsAny`:{let t=e[n].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let r=t.reduce((e,t)=>new Set([...e,...t]));return Array.from(r)}default:throw Error(`Invalid operation`)}}static fromJSON(t){if(!t.numberToDocumentId)throw Error(`Invalid Flat Tree JSON`);let n=new e;for(let[e,r]of t.numberToDocumentId)n.numberToDocumentId.set(e,new Set(r));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,t])=>[e,Array.from(t)])}}};function ZH(e,t,n){if(n<0)return-1;if(e===t)return 0;let r=e.length,i=t.length;if(r===0)return i<=n?i:-1;if(i===0)return r<=n?r:-1;let a=Math.abs(r-i);if(e.startsWith(t))return a<=n?a:-1;if(t.startsWith(e))return 0;if(a>n)return-1;let o=[];for(let e=0;e<=r;e++){o[e]=[e];for(let t=1;t<=i;t++)o[e][t]=e===0?t:0}for(let a=1;a<=r;a++){let r=1/0;for(let n=1;n<=i;n++)e[a-1]===t[n-1]?o[a][n]=o[a-1][n-1]:o[a][n]=Math.min(o[a-1][n]+1,o[a][n-1]+1,o[a-1][n-1]+1),r=Math.min(r,o[a][n]);if(r>n)return-1}return o[r][i]<=n?o[r][i]:-1}function QH(e,t,n){let r=ZH(e,t,n);return{distance:r,isBounded:r>=0}}var $H=class e{k;s;c=new Map;d=new Set;e;w=``;constructor(e,t,n){this.k=e,this.s=t,this.e=n}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,t,n,r){let i=[this];for(;i.length>0;){let a=i.pop();if(a.e){let{w:i,d:o}=a;if(n&&i!==t)continue;if(ZV(e,i)!==null)if(r)if(Math.abs(t.length-i.length)<=r&&QH(t,i,r).isBounded)e[i]=[];else continue;else e[i]=[];if(ZV(e,i)!=null&&o.size>0){let t=e[i];for(let e of o)t.includes(e)||t.push(e)}}a.c.size>0&&i.push(...a.c.values())}return e}insert(t,n){let r=this,i=0,a=t.length;for(;i<a;){let o=t[i],s=r.c.get(o);if(s){let o=s.s,c=o.length,l=0;for(;l<c&&i+l<a&&o[l]===t[i+l];)l++;if(l===c){if(r=s,i+=l,i===a){s.e||=!0,s.addDocument(n);return}continue}let u=o.slice(0,l),d=o.slice(l),f=t.slice(i+l),p=new e(u[0],u,!1);if(r.c.set(u[0],p),p.updateParent(r),s.s=d,s.k=d[0],p.c.set(d[0],s),s.updateParent(p),f){let t=new e(f[0],f,!0);t.addDocument(n),p.c.set(f[0],t),t.updateParent(p)}else p.e=!0,p.addDocument(n);return}else{let a=new e(o,t.slice(i),!0);a.addDocument(n),r.c.set(o,a),a.updateParent(r);return}}r.e||=!0,r.addDocument(n)}_findLevenshtein(e,t,n,r,i){let a=[{node:this,index:t,tolerance:n}];for(;a.length>0;){let{node:t,index:n,tolerance:o}=a.pop();if(t.w.startsWith(e)){t.findAllWords(i,e,!1,0);continue}if(o<0)continue;if(t.e){let{w:n,d:a}=t;if(n&&(QH(e,n,r).isBounded&&(i[n]=[]),ZV(i,n)!==void 0&&a.size>0)){let e=new Set(i[n]);for(let t of a)e.add(t);i[n]=Array.from(e)}}if(n>=e.length)continue;let s=e[n];if(t.c.has(s)){let e=t.c.get(s);a.push({node:e,index:n+1,tolerance:o})}a.push({node:t,index:n+1,tolerance:o-1});for(let[e,r]of t.c)a.push({node:r,index:n,tolerance:o-1}),e!==s&&a.push({node:r,index:n+1,tolerance:o-1})}}find(e){let{term:t,exact:n,tolerance:r}=e;if(r&&!n){let e={};return this._findLevenshtein(t,0,r,r,e),e}else{let e=this,i=0,a=t.length;for(;i<a;){let o=t[i],s=e.c.get(o);if(s){let o=s.s,c=o.length,l=0;for(;l<c&&i+l<a&&o[l]===t[i+l];)l++;if(l===c)e=s,i+=l;else if(i+l===a)if(l===a-i){if(n)return{};{let e={};return s.findAllWords(e,t,n,r),e}}else return{};else return{}}else return{}}let o={};return e.findAllWords(o,t,n,r),o}}contains(e){let t=this,n=0,r=e.length;for(;n<r;){let i=e[n],a=t.c.get(i);if(a){let i=a.s,o=i.length,s=0;for(;s<o&&n+s<r&&i[s]===e[n+s];)s++;if(s<o)return!1;n+=o,t=a}else return!1}return!0}removeWord(e){if(!e)return!1;let t=this,n=e.length,r=[];for(let i=0;i<n;i++){let n=e[i];if(t.c.has(n)){let e=t.c.get(n);r.push({parent:t,character:n}),i+=e.s.length-1,t=e}else return!1}for(t.d.clear(),t.e=!1;r.length>0&&t.c.size===0&&!t.e&&t.d.size===0;){let{parent:e,character:n}=r.pop();e.c.delete(n),t=e}return!0}removeDocumentByWord(e,t,n=!0){if(!e)return!0;let r=this,i=e.length;for(let a=0;a<i;a++){let i=e[a];if(r.c.has(i)){let o=r.c.get(i);a+=o.s.length-1,r=o,n&&r.w!==e||r.removeDocument(t)}else return!1}return!0}static getCommonPrefix(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e.charCodeAt(r)===t.charCodeAt(r);)r++;return e.slice(0,r)}toJSON(){return{w:this.w,s:this.s,e:this.e,k:this.k,d:Array.from(this.d),c:Array.from(this.c?.entries())?.map(([e,t])=>[e,t.toJSON()])}}static fromJSON(t){let n=new e(t.k,t.s,t.e);return n.w=t.w,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([t,n])=>[t,e.fromJSON(n)])||[]),n}},eU=class e extends $H{constructor(){super(``,``,!1)}static fromJSON(t){let n=new e;return n.w=t.w,n.s=t.s,n.e=t.e,n.k=t.k,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([e,t])=>[e,$H.fromJSON(t)])||[]),n}toJSON(){return super.toJSON()}},tU=class e{point;docIDs;left;right;parent;constructor(e,t){this.point=e,this.docIDs=new Set(t),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(t,n=null){let r=new e(t.point,t.docIDs);return r.parent=n,t.left&&(r.left=e.fromJSON(t.left,r)),t.right&&(r.right=e.fromJSON(t.right,r)),r}},nU=class e{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,t){let n=this.getPointKey(e),r=this.nodeMap.get(n);if(r){t.forEach(e=>r.docIDs.add(e));return}let i=new tU(e,t);if(this.nodeMap.set(n,i),this.root==null){this.root=i;return}let a=this.root,o=0;for(;;){if(o%2==0)if(e.lon<a.point.lon){if(a.left==null){a.left=i,i.parent=a;return}a=a.left}else{if(a.right==null){a.right=i,i.parent=a;return}a=a.right}else if(e.lat<a.point.lat){if(a.left==null){a.left=i,i.parent=a;return}a=a.left}else{if(a.right==null){a.right=i,i.parent=a;return}a=a.right}o++}}contains(e){let t=this.getPointKey(e);return this.nodeMap.has(t)}getDocIDsByCoordinates(e){let t=this.getPointKey(e),n=this.nodeMap.get(t);return n?Array.from(n.docIDs):null}removeDocByID(e,t){let n=this.getPointKey(e),r=this.nodeMap.get(n);r&&(r.docIDs.delete(t),r.docIDs.size===0&&(this.nodeMap.delete(n),this.deleteNode(r)))}deleteNode(e){let t=e.parent,n=e.left?e.left:e.right;n&&(n.parent=t),t?t.left===e?t.left=n:t.right===e&&(t.right=n):(this.root=n,this.root&&(this.root.parent=null))}searchByRadius(t,n,r=!0,i=`asc`,a=!1){let o=a?e.vincentyDistance:e.haversineDistance,s=[{node:this.root,depth:0}],c=[];for(;s.length>0;){let{node:e,depth:i}=s.pop();if(e==null)continue;let a=o(t,e.point);(r?a<=n:a>n)&&c.push({point:e.point,docIDs:Array.from(e.docIDs)}),e.left!=null&&s.push({node:e.left,depth:i+1}),e.right!=null&&s.push({node:e.right,depth:i+1})}return i&&c.sort((e,n)=>{let r=o(t,e.point),a=o(t,n.point);return i.toLowerCase()===`asc`?r-a:a-r}),c}searchByPolygon(t,n=!0,r=null,i=!1){let a=[{node:this.root,depth:0}],o=[];for(;a.length>0;){let{node:r,depth:i}=a.pop();if(r==null)continue;r.left!=null&&a.push({node:r.left,depth:i+1}),r.right!=null&&a.push({node:r.right,depth:i+1});let s=e.isPointInPolygon(t,r.point);(s&&n||!s&&!n)&&o.push({point:r.point,docIDs:Array.from(r.docIDs)})}let s=e.calculatePolygonCentroid(t);if(r){let t=i?e.vincentyDistance:e.haversineDistance;o.sort((e,n)=>{let i=t(s,e.point),a=t(s,n.point);return r.toLowerCase()===`asc`?i-a:a-i})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(t){let n=new e;return t.root&&(n.root=tU.fromJSON(t.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let t=this.getPointKey(e.point);this.nodeMap.set(t,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let t=0,n=0,r=0,i=e.length;for(let a=0,o=i-1;a<i;o=a++){let i=e[a].lon,s=e[a].lat,c=e[o].lon,l=e[o].lat,u=i*l-c*s;t+=u,n+=(i+c)*u,r+=(s+l)*u}t/=2;let a=6*t;return n/=a,r/=a,{lon:n,lat:r}}static isPointInPolygon(e,t){let n=!1,r=t.lon,i=t.lat,a=e.length;for(let t=0,o=a-1;t<a;o=t++){let a=e[t].lon,s=e[t].lat,c=e[o].lon,l=e[o].lat;s>i!=l>i&&r<(c-a)*(i-s)/(l-s)+a&&(n=!n)}return n}static haversineDistance(e,t){let n=Math.PI/180,r=e.lat*n,i=t.lat*n,a=(t.lat-e.lat)*n,o=(t.lon-e.lon)*n,s=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(i)*Math.sin(o/2)*Math.sin(o/2);return 6371e3*(2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s)))}static vincentyDistance(e,t){let n=6378137,r=1/298.257223563,i=(1-r)*n,a=Math.PI/180,o=e.lat*a,s=t.lat*a,c=(t.lon-e.lon)*a,l=Math.atan((1-r)*Math.tan(o)),u=Math.atan((1-r)*Math.tan(s)),d=Math.sin(l),f=Math.cos(l),p=Math.sin(u),m=Math.cos(u),h=c,g,_=1e3,v,y,b,x,S,C;do{let e=Math.sin(h),t=Math.cos(h);if(v=Math.sqrt(m*e*(m*e)+(f*p-d*m*t)*(f*p-d*m*t)),v===0)return 0;y=d*p+f*m*t,b=Math.atan2(v,y),x=f*m*e/v,S=1-x*x,C=y-2*d*p/S,isNaN(C)&&(C=0);let n=r/16*S*(4+r*(4-3*S));g=h,h=c+(1-n)*r*x*(b+n*v*(C+n*y*(-1+2*C*C)))}while(Math.abs(h-g)>1e-12&&--_>0);if(_===0)return NaN;let w=S*(n*n-i*i)/(i*i),T=1+w/16384*(4096+w*(-768+w*(320-175*w))),E=w/1024*(256+w*(-128+w*(74-47*w))),ee=E*v*(C+E/4*(y*(-1+2*C*C)-E/6*C*(-3+4*v*v)*(-3+4*C*C)));return i*T*(b-ee)}},rU=class e{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,t){t?this.true.add(e):this.false.add(e)}delete(e,t){t?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(t){let n=new e;return n.true=new Set(t.true),n.false=new Set(t.false),n}};function iU(e,t,n,r,i,{k:a,b:o,d:s}){return Math.log(1+(n-t+.5)/(t+.5))*(s+e*(a+1))/(e+a*(1-o+o*r/i))}var aU=class e{size;vectors=new Map;constructor(e){this.size=e}add(e,t){t instanceof Float32Array||(t=new Float32Array(t));let n=oU(t,this.size);this.vectors.set(e,[n,t])}remove(e){this.vectors.delete(e)}find(e,t,n){return e instanceof Float32Array||(e=new Float32Array(e)),sU(e,n,this.vectors,this.size,t)}toJSON(){let e=[];for(let[t,[n,r]]of this.vectors)e.push([t,[n,Array.from(r)]]);return{size:this.size,vectors:e}}static fromJSON(t){let n=t,r=new e(n.size);for(let[e,[t,i]]of n.vectors)r.vectors.set(e,[t,new Float32Array(i)]);return r}};function oU(e,t){let n=0;for(let r=0;r<t;r++)n+=e[r]*e[r];return Math.sqrt(n)}function sU(e,t,n,r,i){let a=oU(e,r),o=[],s=t||n.keys();for(let t of s){let s=n.get(t);if(!s)continue;let c=s[0],l=s[1],u=0;for(let t=0;t<r;t++)u+=e[t]*l[t];let d=u/(a*c);d>=i&&o.push([t,d])}return o}function cU(e,t,n,r,i){let a=DH(e.sharedInternalDocumentStore,n);e.avgFieldLength[t]=((e.avgFieldLength[t]??0)*(i-1)+r.length)/i,e.fieldLengths[t][a]=r.length,e.frequencies[t][a]={}}function lU(e,t,n,r,i){let a=0;for(let e of r)e===i&&a++;let o=DH(e.sharedInternalDocumentStore,n),s=a/r.length;e.frequencies[t][o][i]=s,i in e.tokenOccurrences[t]||(e.tokenOccurrences[t][i]=0),e.tokenOccurrences[t][i]=(e.tokenOccurrences[t][i]??0)+1}function uU(e,t,n,r){let i=DH(e.sharedInternalDocumentStore,n);r>1?e.avgFieldLength[t]=(e.avgFieldLength[t]*r-e.fieldLengths[t][i])/(r-1):e.avgFieldLength[t]=void 0,e.fieldLengths[t][i]=void 0,e.frequencies[t][i]=void 0}function dU(e,t,n){e.tokenOccurrences[t][n]--}function fU(e,t,n,r,i=``){r||={sharedInternalDocumentStore:t,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}};for(let[a,o]of Object.entries(n)){let n=`${i}${i?`.`:``}${a}`;if(typeof o==`object`&&!Array.isArray(o)){fU(e,t,o,r,n);continue}if(bH(o))r.searchableProperties.push(n),r.searchablePropertiesWithTypes[n]=o,r.vectorIndexes[n]={type:`Vector`,node:new aU(CH(o)),isArray:!1};else{let e=/\[/.test(o);switch(o){case`boolean`:case`boolean[]`:r.indexes[n]={type:`Bool`,node:new rU,isArray:e};break;case`number`:case`number[]`:r.indexes[n]={type:`AVL`,node:new YH(0,[]),isArray:e};break;case`string`:case`string[]`:r.indexes[n]={type:`Radix`,node:new eU,isArray:e},r.avgFieldLength[n]=0,r.frequencies[n]={},r.tokenOccurrences[n]={},r.fieldLengths[n]={};break;case`enum`:case`enum[]`:r.indexes[n]={type:`Flat`,node:new XH,isArray:e};break;case`geopoint`:r.indexes[n]={type:`BKD`,node:new nU,isArray:e};break;default:throw pH(`INVALID_SCHEMA_TYPE`,Array.isArray(o)?`array`:o,n)}r.searchableProperties.push(n),r.searchablePropertiesWithTypes[n]=o}}return r}function pU(e,t,n,r,i,a,o,s){return c=>{let{type:l,node:u}=t.indexes[n];switch(l){case`Bool`:u[c?`true`:`false`].add(r);break;case`AVL`:{let e=s?.avlRebalanceThreshold??1;u.insert(c,r,e);break}case`Radix`:{let s=a.tokenize(c,i,n,!1);e.insertDocumentScoreParameters(t,n,r,s,o);for(let i of s)e.insertTokenScoreParameters(t,n,r,s,i),u.insert(i,r);break}case`Flat`:u.insert(c,r);break;case`BKD`:u.insert(c,[r]);break}}}function mU(e,t,n,r,i,a,o,s,c,l,u){if(bH(o))return hU(t,n,a,r,i);let d=pU(e,t,n,i,s,c,l,u);if(!xH(o))return d(a);let f=a,p=f.length;for(let e=0;e<p;e++)d(f[e])}function hU(e,t,n,r,i){e.vectorIndexes[t].node.add(i,n)}function gU(e,t,n,r,i,a,o,s,c,l){if(bH(o))return t.vectorIndexes[n].node.remove(i),!0;let{type:u,node:d}=t.indexes[n];switch(u){case`AVL`:return d.removeDocument(a,i),!0;case`Bool`:return d[a?`true`:`false`].delete(i),!0;case`Radix`:{let o=c.tokenize(a,s,n);e.removeDocumentScoreParameters(t,n,r,l);for(let r of o)e.removeTokenScoreParameters(t,n,r),d.removeDocumentByWord(r,i);return!0}case`Flat`:return d.removeDocument(i,a),!0;case`BKD`:return d.removeDocByID(a,i),!1}}function _U(e,t,n,r,i,a,o,s,c,l){if(!xH(o))return gU(e,t,n,r,i,a,o,s,c,l);let u=SH(o),d=a,f=d.length;for(let a=0;a<f;a++)gU(e,t,n,r,i,d[a],u,s,c,l);return!0}function vU(e,t,n,r,i,a,o,s,c,l){let u=Array.from(r),d=e.avgFieldLength[t],f=e.fieldLengths[t],p=e.tokenOccurrences[t],m=e.frequencies[t],h=typeof p[n]==`number`?p[n]??0:0,g=u.length;for(let e=0;e<g;e++){let r=u[e];if(c&&!c.has(r))continue;l.has(r)||l.set(r,new Map);let p=l.get(r);p.set(t,(p.get(t)||0)+1);let g=iU(m?.[r]?.[n]??0,h,i,f[r],d,a);o.has(r)?o.set(r,o.get(r)+g*s):o.set(r,g*s)}}function yU(e,t,n,r,i,a,o,s,c,l,u,d=0){let f=n.tokenize(t,r),p=f.length||1,m=new Map,h=new Map,g=new Map;for(let n of i){if(!(n in e.indexes))continue;let r=e.indexes[n],{type:i}=r;if(i!==`Radix`)throw pH(`WRONG_SEARCH_PROPERTY_TYPE`,n);let d=s[n]??1;if(d<=0)throw pH(`INVALID_BOOST_VALUE`,d);f.length===0&&!t&&f.push(``);let p=f.length;for(let t=0;t<p;t++){let i=f[t],s=r.node.find({term:i,exact:a,tolerance:o}),p=Object.keys(s);p.length>0&&h.set(i,!0);let _=p.length;for(let t=0;t<_;t++){let r=p[t],i=s[r];vU(e,n,r,i,l,c,g,d,u,m)}}}let _=Array.from(g.entries()).map(([e,t])=>[e,t]).sort((e,t)=>t[1]-e[1]);if(_.length===0)return[];if(d===1)return _;if(d===0){if(p===1)return _;for(let e of f)if(!h.get(e))return[];return _.filter(([e])=>{let t=m.get(e);return t?Array.from(t.values()).some(e=>e===p):!1})}let v=_.filter(([e])=>{let t=m.get(e);return t?Array.from(t.values()).some(e=>e===p):!1});if(v.length>0){let e=_.filter(([e])=>!v.some(([t])=>t===e)),t=Math.ceil(e.length*d);return[...v,...e.slice(0,t)]}return _}function bU(e,t,n,r){if(`and`in n&&n.and&&Array.isArray(n.and)){let i=n.and;return i.length===0?new Set:sH(...i.map(n=>bU(e,t,n,r)))}if(`or`in n&&n.or&&Array.isArray(n.or)){let i=n.or;return i.length===0?new Set:i.map(n=>bU(e,t,n,r)).reduce((e,t)=>lH(e,t),new Set)}if(`not`in n&&n.not){let i=n.not,a=new Set,o=e.sharedInternalDocumentStore;for(let e=1;e<=o.internalIdToId.length;e++)a.add(e);return uH(a,bU(e,t,i,r))}let i=Object.keys(n),a=i.reduce((e,t)=>({[t]:new Set,...e}),{});for(let o of i){let i=n[o];if(e.indexes[o]===void 0)throw pH(`UNKNOWN_FILTER_PROPERTY`,o);let{node:s,type:c,isArray:l}=e.indexes[o];if(c===`Bool`){let e=s,t=i?e.true:e.false;a[o]=lH(a[o],t);continue}if(c===`BKD`){let e;if(`radius`in i)e=`radius`;else if(`polygon`in i)e=`polygon`;else throw Error(`Invalid operation ${i}`);if(e===`radius`){let{value:t,coordinates:n,unit:r=`m`,inside:c=!0,highPrecision:l=!1}=i[e],u=rH(t,r),d=s.searchByRadius(n,u,c,void 0,l);a[o]=EU(a[o],d)}else{let{coordinates:t,inside:n=!0,highPrecision:r=!1}=i[e],c=s.searchByPolygon(t,n,void 0,r);a[o]=EU(a[o],c)}continue}if(c===`Radix`&&(typeof i==`string`||Array.isArray(i))){for(let e of[i].flat()){let n=t.tokenize(e,r,o);for(let e of n){let t=s.find({term:e,exact:!0});a[o]=AU(a[o],t)}}continue}let u=Object.keys(i);if(u.length>1)throw pH(`INVALID_FILTER_OPERATION`,u.length);if(c===`Flat`){let e=new Set(l?s.filterArr(i):s.filter(i));a[o]=lH(a[o],e);continue}if(c===`AVL`){let e=u[0],t=i[e],n;switch(e){case`gt`:n=s.greaterThan(t,!1);break;case`gte`:n=s.greaterThan(t,!0);break;case`lt`:n=s.lessThan(t,!1);break;case`lte`:n=s.lessThan(t,!0);break;case`eq`:n=s.find(t)??new Set;break;case`between`:{let[e,r]=t;n=s.rangeSearch(e,r);break}default:throw pH(`INVALID_FILTER_OPERATION`,e)}a[o]=lH(a[o],n)}}return sH(...Object.values(a))}function xU(e){return e.searchableProperties}function SU(e){return e.searchablePropertiesWithTypes}function CU(e,t){let{indexes:n,vectorIndexes:r,searchableProperties:i,searchablePropertiesWithTypes:a,frequencies:o,tokenOccurrences:s,avgFieldLength:c,fieldLengths:l}=t,u={},d={};for(let e of Object.keys(n)){let{node:t,type:r,isArray:i}=n[e];switch(r){case`Radix`:u[e]={type:`Radix`,node:eU.fromJSON(t),isArray:i};break;case`Flat`:u[e]={type:`Flat`,node:XH.fromJSON(t),isArray:i};break;case`AVL`:u[e]={type:`AVL`,node:YH.fromJSON(t),isArray:i};break;case`BKD`:u[e]={type:`BKD`,node:nU.fromJSON(t),isArray:i};break;case`Bool`:u[e]={type:`Bool`,node:rU.fromJSON(t),isArray:i};break;default:u[e]=n[e]}}for(let e of Object.keys(r))d[e]={type:`Vector`,isArray:!1,node:aU.fromJSON(r[e])};return{sharedInternalDocumentStore:e,indexes:u,vectorIndexes:d,searchableProperties:i,searchablePropertiesWithTypes:a,frequencies:o,tokenOccurrences:s,avgFieldLength:c,fieldLengths:l}}function wU(e){let{indexes:t,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:i,frequencies:a,tokenOccurrences:o,avgFieldLength:s,fieldLengths:c}=e,l={};for(let e of Object.keys(n))l[e]=n[e].node.toJSON();let u={};for(let e of Object.keys(t)){let{type:n,node:r,isArray:i}=t[e];n===`Flat`||n===`Radix`||n===`AVL`||n===`BKD`||n===`Bool`?u[e]={type:n,node:r.toJSON(),isArray:i}:(u[e]=t[e],u[e].node=u[e].node.toJSON())}return{indexes:u,vectorIndexes:l,searchableProperties:r,searchablePropertiesWithTypes:i,frequencies:a,tokenOccurrences:o,avgFieldLength:s,fieldLengths:c}}function TU(){return{create:fU,insert:mU,remove:_U,insertDocumentScoreParameters:cU,insertTokenScoreParameters:lU,removeDocumentScoreParameters:uU,removeTokenScoreParameters:dU,calculateResultScores:vU,search:yU,searchByWhereClause:bU,getSearchableProperties:xU,getSearchablePropertiesWithTypes:SU,load:CU,save:wU}}function EU(e,t){e||=new Set;let n=t.length;for(let r=0;r<n;r++){let n=t[r].docIDs,i=n.length;for(let t=0;t<i;t++)e.add(n[t])}return e}function DU(e,t,n=!1){let r=n?nU.vincentyDistance:nU.haversineDistance,i=[],a=[];for(let{point:n}of e)a.push(r(t,n));let o=Math.max(...a),s=0;for(let{docIDs:t}of e){let e=o-a[s]+1;for(let n of t)i.push([n,e]);s++}return i.sort((e,t)=>t[1]-e[1]),i}function OU(e,t){let n=Object.keys(e);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],i=e[r];if(t.indexes[r]===void 0)return{isGeoOnly:!1};let{type:a}=t.indexes[r];return a===`BKD`&&i&&(`radius`in i||`polygon`in i)?{isGeoOnly:!0,geoProperty:r,geoOperation:i}:{isGeoOnly:!1}}function kU(e,t){let n=e,r=OU(t,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:i}=n.indexes[r.geoProperty],a=r.geoOperation,o=i,s;if(`radius`in a){let{value:e,coordinates:t,unit:n=`m`,inside:r=!0,highPrecision:i=!1}=a.radius,c=t,l=rH(e,n);return s=o.searchByRadius(c,l,r,`asc`,i),DU(s,c,i)}else if(`polygon`in a){let{coordinates:e,inside:t=!0,highPrecision:n=!1}=a.polygon;s=o.searchByPolygon(e,t,`asc`,n);let r=nU.calculatePolygonCentroid(e);return DU(s,r,n)}return null}function AU(e,t){e||=new Set;let n=Object.keys(t),r=n.length;for(let i=0;i<r;i++){let r=t[n[i]],a=r.length;for(let t=0;t<a;t++)e.add(r[t])}return e}function jU(e,t,n,r,i){let a={language:e.tokenizer.language,sharedInternalDocumentStore:t,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,s]of Object.entries(n)){let n=`${i}${i?`.`:``}${o}`;if(!r.includes(n)){if(typeof s==`object`&&!Array.isArray(s)){let i=jU(e,t,s,r,n);UV(a.sortableProperties,i.sortableProperties),a.sorts={...a.sorts,...i.sorts},a.sortablePropertiesWithTypes={...a.sortablePropertiesWithTypes,...i.sortablePropertiesWithTypes};continue}if(!bH(s))switch(s){case`boolean`:case`number`:case`string`:a.sortableProperties.push(n),a.sortablePropertiesWithTypes[n]=s,a.sorts[n]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:s};break;case`geopoint`:case`enum`:continue;case`enum[]`:case`boolean[]`:case`number[]`:case`string[]`:continue;default:throw pH(`INVALID_SORT_SCHEMA_TYPE`,Array.isArray(s)?`array`:s,n)}}}return a}function MU(e,t,n,r){return r?.enabled===!1?{disabled:!0}:jU(e,t,n,(r||{}).unsortableProperties||[],``)}function NU(e,t,n,r){if(!e.enabled)return;e.isSorted=!1;let i=DH(e.sharedInternalDocumentStore,n),a=e.sorts[t];a.orderedDocsToRemove.has(i)&&BU(e,t),a.docs.set(i,a.orderedDocs.length),a.orderedDocs.push([i,r])}function PU(e){if(e.isSorted||!e.enabled)return;let t=Object.keys(e.sorts);for(let n of t)RU(e,n);e.isSorted=!0}function FU(e,t,n){return t[1].localeCompare(n[1],IV(e))}function IU(e,t){return e[1]-t[1]}function LU(e,t){return t[1]?-1:1}function RU(e,t){let n=e.sorts[t],r;switch(n.type){case`string`:r=FU.bind(null,e.language);break;case`number`:r=IU.bind(null);break;case`boolean`:r=LU.bind(null);break}n.orderedDocs.sort(r);let i=n.orderedDocs.length;for(let e=0;e<i;e++){let t=n.orderedDocs[e][0];n.docs.set(t,e)}}function zU(e){let t=Object.keys(e.sorts);for(let n of t)BU(e,n)}function BU(e,t){let n=e.sorts[t];n.orderedDocsToRemove.size&&(n.orderedDocs=n.orderedDocs.filter(e=>!n.orderedDocsToRemove.has(e[0])),n.orderedDocsToRemove.clear())}function VU(e,t,n){if(!e.enabled)return;let r=e.sorts[t],i=DH(e.sharedInternalDocumentStore,n);r.docs.get(i)&&(r.docs.delete(i),r.orderedDocsToRemove.set(i,!0))}function HU(e,t,n){if(!e.enabled)throw pH(`SORT_DISABLED`);let r=n.property,i=n.order===`DESC`,a=e.sorts[r];if(!a)throw pH(`UNABLE_TO_SORT_ON_UNKNOWN_FIELD`,r,e.sortableProperties.join(`, `));return BU(e,r),PU(e),t.sort((t,n)=>{let r=a.docs.get(DH(e.sharedInternalDocumentStore,t[0])),o=a.docs.get(DH(e.sharedInternalDocumentStore,n[0])),s=r!==void 0,c=o!==void 0;return!s&&!c?0:s?c?i?o-r:r-o:-1:1}),t}function UU(e){return e.enabled?e.sortableProperties:[]}function WU(e){return e.enabled?e.sortablePropertiesWithTypes:{}}function GU(e,t){let n=t;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((e,t)=>{let{docs:r,orderedDocs:i,type:a}=n.sorts[t];return e[t]={docs:new Map(Object.entries(r).map(([e,t])=>[+e,t])),orderedDocsToRemove:new Map,orderedDocs:i,type:a},e},{});return{sharedInternalDocumentStore:e,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function KU(e){if(!e.enabled)return{enabled:!1};zU(e),PU(e);let t=Object.keys(e.sorts).reduce((t,n)=>{let{docs:r,orderedDocs:i,type:a}=e.sorts[n];return t[n]={docs:Object.fromEntries(r.entries()),orderedDocs:i,type:a},t},{});return{language:e.language,sortableProperties:e.sortableProperties,sortablePropertiesWithTypes:e.sortablePropertiesWithTypes,sorts:t,enabled:e.enabled,isSorted:e.isSorted}}function qU(){return{create:MU,insert:NU,remove:VU,save:KU,load:GU,sortBy:HU,getSortableProperties:UU,getSortablePropertiesWithTypes:WU}}const JU=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function YU(e){return e<192||e>383?e:JU[e-192]||e}function XU(e){let t=[];for(let n=0;n<e.length;n++)t[n]=YU(e.charCodeAt(n));return String.fromCharCode(...t)}const ZU={ational:`ate`,tional:`tion`,enci:`ence`,anci:`ance`,izer:`ize`,bli:`ble`,alli:`al`,entli:`ent`,eli:`e`,ousli:`ous`,ization:`ize`,ation:`ate`,ator:`ate`,alism:`al`,iveness:`ive`,fulness:`ful`,ousness:`ous`,aliti:`al`,iviti:`ive`,biliti:`ble`,logi:`log`},QU={icate:`ic`,ative:``,alize:`al`,iciti:`ic`,ical:`ic`,ful:``,ness:``},$U=`[aeiouy]`,eW=`[^aeiou][^aeiouy]*`;$U+``;const tW=`^(`+eW+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*`;``+eW;const nW=`^(`+eW+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*[aeiouy][aeiou]*[^aeiou][^aeiouy]*`,rW=`^(`+eW+`)?[aeiouy]`;function iW(e){let t,n,r,i,a,o;if(e.length<3)return e;let s=e.substring(0,1);if(s==`y`&&(e=s.toUpperCase()+e.substring(1)),r=/^(.+?)(ss|i)es$/,i=/^(.+?)([^s])s$/,r.test(e)?e=e.replace(r,`$1$2`):i.test(e)&&(e=e.replace(i,`$1$2`)),r=/^(.+?)eed$/,i=/^(.+?)(ed|ing)$/,r.test(e)){let t=r.exec(e);r=new RegExp(tW),r.test(t[1])&&(r=/.$/,e=e.replace(r,``))}else i.test(e)&&(t=i.exec(e)[1],i=new RegExp(rW),i.test(t)&&(e=t,i=/(at|bl|iz)$/,a=RegExp(`([^aeiouylsz])\\1$`),o=RegExp(`^`+eW+$U+`[^aeiouwxy]$`),i.test(e)?e+=`e`:a.test(e)?(r=/.$/,e=e.replace(r,``)):o.test(e)&&(e+=`e`)));if(r=/^(.+?)y$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(rW),t&&r.test(t)&&(e=t+`i`)),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(e)){let i=r.exec(e);t=i?.[1],n=i?.[2],r=new RegExp(tW),t&&r.test(t)&&(e=t+ZU[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(e)){let i=r.exec(e);t=i?.[1],n=i?.[2],r=new RegExp(tW),t&&r.test(t)&&(e=t+QU[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,i=/^(.+?)(s|t)(ion)$/,r.test(e))t=r.exec(e)?.[1],r=new RegExp(nW),t&&r.test(t)&&(e=t);else if(i.test(e)){let n=i.exec(e);t=n?.[1]??``+n?.[2]??``,i=new RegExp(nW),i.test(t)&&(e=t)}return r=/^(.+?)e$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(nW),i=RegExp(`^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*([aeiouy][aeiou]*)?$`),a=RegExp(`^`+eW+$U+`[^aeiouwxy]$`),t&&(r.test(t)||i.test(t)&&!a.test(t))&&(e=t)),r=/ll$/,i=new RegExp(nW),r.test(e)&&i.test(e)&&(r=/.$/,e=e.replace(r,``)),s==`y`&&(e=s.toLowerCase()+e.substring(1)),e}function aW(e,t,n=!0){let r=`${this.language}:${e}:${t}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(t)?(n&&this.normalizationCache.set(r,``),``):(this.stemmer&&!this.stemmerSkipProperties.has(e)&&(t=this.stemmer(t)),t=XU(t),n&&this.normalizationCache.set(r,t),t)}function oW(e){for(;e[e.length-1]===``;)e.pop();for(;e[0]===``;)e.shift();return e}function sW(e,t,n,r=!0){if(t&&t!==this.language)throw pH(`LANGUAGE_NOT_SUPPORTED`,t);if(typeof e!=`string`)return[e];let i=this.normalizeToken.bind(this,n??``),a;if(n&&this.tokenizeSkipProperties.has(n))a=[i(e,r)];else{let t=PV[this.language];a=e.toLowerCase().split(t).map(e=>i(e,r)).filter(Boolean)}let o=oW(a);return this.allowDuplicates?o:Array.from(new Set(o))}function cW(e={}){if(!e.language)e.language=`english`;else if(!FV.includes(e.language))throw pH(`LANGUAGE_NOT_SUPPORTED`,e.language);let t;if(e.stemming||e.stemmer&&!(`stemming`in e))if(e.stemmer){if(typeof e.stemmer!=`function`)throw pH(`INVALID_STEMMER_FUNCTION_TYPE`);t=e.stemmer}else if(e.language===`english`)t=iW;else throw pH(`MISSING_STEMMER`,e.language);let n;if(e.stopWords!==!1){if(n=[],Array.isArray(e.stopWords))n=e.stopWords;else if(typeof e.stopWords==`function`)n=e.stopWords(n);else if(e.stopWords)throw pH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);if(!Array.isArray(n))throw pH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);for(let e of n)if(typeof e!=`string`)throw pH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`)}let r={tokenize:sW,language:e.language,stemmer:t,stemmerSkipProperties:new Set(e.stemmerSkipProperties?[e.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(e.tokenizeSkipProperties?[e.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!e.allowDuplicates,normalizeToken:aW,normalizationCache:new Map};return r.tokenize=sW.bind(r),r.normalizeToken=aW,r}function lW(e){return{sharedInternalDocumentStore:e,rules:new Map}}function uW(e,t){if(e.rules.has(t.id))throw Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${t.id}" already exists. Use updateRule to modify it.`);e.rules.set(t.id,t)}function dW(e,t){if(!e.rules.has(t.id))throw Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${t.id}" because it does not exist. Use addRule to create it.`);e.rules.set(t.id,t)}function fW(e,t){return e.rules.delete(t)}function pW(e,t){return e.rules.get(t)}function mW(e){return Array.from(e.rules.values())}function hW(e,t){let n=e.toLowerCase().trim(),r=t.pattern.toLowerCase().trim();switch(t.anchoring){case`is`:return n===r;case`starts_with`:return n.startsWith(r);case`contains`:return n.includes(r);default:return!1}}function gW(e,t){return e?t.conditions.every(t=>hW(e,t)):!1}function _W(e,t){if(!t)return[];let n=[];for(let r of e.rules.values())gW(t,r)&&n.push(r);return n}function vW(e,t){return{sharedInternalDocumentStore:e,rules:new Map(t?.rules??[])}}function yW(e){return{rules:Array.from(e.rules.entries())}}function bW(){return{create:lW,addRule:uW,updateRule:dW,removeRule:fW,getRule:pW,getAllRules:mW,getMatchingRules:_W,load:vW,save:yW}}function xW(e){let t={formatElapsedTime:mH,getDocumentIndexId:hH,getDocumentProperties:eH,validateSchema:gH};for(let n of HH){let r=n;if(e[r]){if(typeof e[r]!=`function`)throw pH(`COMPONENT_MUST_BE_FUNCTION`,r)}else e[r]=t[r]}for(let t of Object.keys(e))if(!VH.includes(t)&&!HH.includes(t))throw pH(`UNSUPPORTED_COMPONENT`,t)}function SW({schema:e,sort:t,language:n,components:r,id:i,plugins:a}){r||={};for(let t of a??[]){if(!(`getComponents`in t)||typeof t.getComponents!=`function`)continue;let n=t.getComponents(e),i=Object.keys(n);for(let e of i)if(r[e])throw pH(`PLUGIN_COMPONENT_CONFLICT`,e,t.name);r={...r,...n}}i||=XV();let o=r.tokenizer,s=r.index,c=r.documentsStore,l=r.sorter,u=r.pinning;if(o=o?o.tokenize?o:cW(o):cW({language:n??`english`}),r.tokenizer&&n)throw pH(`NO_LANGUAGE_WITH_CUSTOM_TOKENIZER`);let d=wH();s||=TU(),l||=qU(),c||=RH(),u||=bW(),xW(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:m,formatElapsedTime:h}=r,g={data:{},caches:{},schema:e,tokenizer:o,index:s,sorter:l,documentsStore:c,pinning:u,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:m,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:h,id:i,plugins:a,version:CW()};g.data={index:g.index.create(g,d,e),docs:g.documentsStore.create(g,d),sorting:g.sorter.create(g,d,e,t),pinning:g.pinning.create(d)};for(let e of zH)g[e]=(g[e]??[]).concat(BH(g,e));let _=g.afterCreate;return _&&qH(_,g),g}function CW(){return`{{VERSION}}`}function wW(e){return e.documentsStore.count(e.data.docs)}function TW(e,t,n,r,i){let a=e.validateSchema(t,e.schema);if(a)throw pH(`SCHEMA_VALIDATION_FAILURE`,a);return aH(e.beforeInsert)||aH(e.afterInsert)||aH(e.index.beforeInsert)||aH(e.index.insert)||aH(e.index.afterInsert)?OW(e,t,n,r,i):kW(e,t,n,r,i)}const EW=new Set([`enum`,`enum[]`]),DW=new Set([`string`,`number`]);async function OW(e,t,n,r,i){let{index:a,docs:o}=e.data,s=e.getDocumentIndexId(t);if(typeof s!=`string`)throw pH(`DOCUMENT_ID_MUST_BE_STRING`,typeof s);let c=DH(e.internalDocumentIDStore,s);if(r||await UH(e.beforeInsert,e,s,t),!e.documentsStore.store(o,s,c,t))throw pH(`DOCUMENT_ALREADY_EXISTS`,s);let l=e.documentsStore.count(o),u=e.index.getSearchableProperties(a),d=e.index.getSearchablePropertiesWithTypes(a),f=e.getDocumentProperties(t,u);for(let[e,t]of Object.entries(f)){if(t===void 0)continue;let n=typeof t,r=d[e];AW(n,r,e,t)}return await jW(e,s,u,f,l,n,t,i),r||await UH(e.afterInsert,e,s,t),s}function kW(e,t,n,r,i){let{index:a,docs:o}=e.data,s=e.getDocumentIndexId(t);if(typeof s!=`string`)throw pH(`DOCUMENT_ID_MUST_BE_STRING`,typeof s);let c=DH(e.internalDocumentIDStore,s);if(r||UH(e.beforeInsert,e,s,t),!e.documentsStore.store(o,s,c,t))throw pH(`DOCUMENT_ALREADY_EXISTS`,s);let l=e.documentsStore.count(o),u=e.index.getSearchableProperties(a),d=e.index.getSearchablePropertiesWithTypes(a),f=e.getDocumentProperties(t,u);for(let[e,t]of Object.entries(f)){if(t===void 0)continue;let n=typeof t,r=d[e];AW(n,r,e,t)}return MW(e,s,u,f,l,n,t,i),r||UH(e.afterInsert,e,s,t),s}function AW(e,t,n,r){if(!(yH(t)&&typeof r==`object`&&typeof r.lon==`number`&&typeof r.lat==`number`)&&!(bH(t)&&Array.isArray(r))&&!(xH(t)&&Array.isArray(r))&&!(EW.has(t)&&DW.has(e))&&e!==t)throw pH(`INVALID_DOCUMENT_PROPERTY`,n,t,e)}async function jW(e,t,n,r,i,a,o,s){for(let o of n){let n=r[o];if(n===void 0)continue;let c=e.index.getSearchablePropertiesWithTypes(e.data.index)[o];await e.index.beforeInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i);let l=e.internalDocumentIDStore.idToInternalId.get(t);await e.index.insert(e.index,e.data.index,o,t,l,n,c,a,e.tokenizer,i,s),await e.index.afterInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i)}let c=e.sorter.getSortableProperties(e.data.sorting),l=e.getDocumentProperties(o,c);for(let n of c){let r=l[n];if(r===void 0)continue;let i=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[n];e.sorter.insert(e.data.sorting,n,t,r,i,a)}}function MW(e,t,n,r,i,a,o,s){for(let o of n){let n=r[o];if(n===void 0)continue;let c=e.index.getSearchablePropertiesWithTypes(e.data.index)[o],l=DH(e.internalDocumentIDStore,t);e.index.beforeInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i),e.index.insert(e.index,e.data.index,o,t,l,n,c,a,e.tokenizer,i,s),e.index.afterInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i)}let c=e.sorter.getSortableProperties(e.data.sorting),l=e.getDocumentProperties(o,c);for(let n of c){let r=l[n];if(r===void 0)continue;let i=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[n];e.sorter.insert(e.data.sorting,n,t,r,i,a)}}function NW(e,t,n,r,i,a){return aH(e.afterInsertMultiple)||aH(e.beforeInsertMultiple)||aH(e.index.beforeInsert)||aH(e.index.insert)||aH(e.index.afterInsert)?PW(e,t,n,r,i,a):FW(e,t,n,r,i,a)}async function PW(e,t,n=1e3,r,i,a=0){let o=[],s=async a=>{let s=Math.min(a+n,t.length),c=t.slice(a,s);for(let t of c){let n=await TW(e,t,r,i,{avlRebalanceThreshold:c.length});o.push(n)}return s};return await(async()=>{let e=0;for(;e<t.length;){let t=Date.now();if(e=await s(e),a>0){let e=a-(Date.now()-t);e>0&&dH(e)}}})(),i||await WH(e.afterInsertMultiple,e,t),o}function FW(e,t,n=1e3,r,i,a=0){let o=[],s=0;function c(){let a=t.slice(s*n,(s+1)*n);if(a.length===0)return!1;for(let t of a){let n=TW(e,t,r,i,{avlRebalanceThreshold:a.length});o.push(n)}return s++,!0}function l(){let e=Date.now();for(;c();)if(a>0){let t=Date.now()-e;if(t>=a){let e=a-t%a;e>0&&dH(e)}}}return l(),i||WH(e.afterInsertMultiple,e,t),o}function IW(e,t){return e[1]-t[1]}function LW(e,t){return t[1]-e[1]}function RW(e=`desc`){return e.toLowerCase()===`asc`?IW:LW}function zW(e,t,n){let r={},i=t.map(([e])=>e),a=e.documentsStore.getMultiple(e.data.docs,i),o=Object.keys(n),s=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e of o){let t;if(s[e]===`number`){let{ranges:r}=n[e],i=r.length,a=Array.from({length:i});for(let e=0;e<i;e++){let t=r[e];a[e]=[`${t.from}-${t.to}`,0]}t=Object.fromEntries(a)}r[e]={count:0,values:t??{}}}let c=a.length;for(let e=0;e<c;e++){let t=a[e];for(let e of o){let i=e.includes(`.`)?tH(t,e):t[e],a=s[e],o=r[e].values;switch(a){case`number`:{let t=n[e].ranges;BW(t,o)(i);break}case`number[]`:{let t=new Set,r=n[e].ranges,a=BW(r,o,t);for(let e of i)a(e);break}case`boolean`:case`enum`:case`string`:VW(o,a)(i);break;case`boolean[]`:case`enum[]`:case`string[]`:{let e=VW(o,a===`boolean[]`?`boolean`:`string`,new Set);for(let t of i)e(t);break}default:throw pH(`FACET_NOT_SUPPORTED`,a)}}}for(let e of o){let t=r[e];if(t.count=Object.keys(t.values).length,s[e]===`string`){let r=n[e],i=RW(r.sort);t.values=Object.fromEntries(Object.entries(t.values).sort(i).slice(r.offset??0,r.limit??10))}}return r}function BW(e,t,n){return r=>{for(let i of e){let e=`${i.from}-${i.to}`;n?.has(e)||r>=i.from&&r<=i.to&&(t[e]===void 0?t[e]=1:(t[e]++,n?.add(e)))}}}function VW(e,t,n){let r=t===`boolean`?`false`:``;return t=>{let i=t?.toString()??r;n?.has(i)||(e[i]=(e[i]??0)+1,n?.add(i))}}const HW={reducer:(e,t,n,r)=>(t[r]=n,t),getInitialValue:e=>Array.from({length:e})},UW=[`string`,`number`,`boolean`];function WW(e,t,n){let r=n.properties,i=r.length,a=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e=0;e<i;e++){let t=r[e];if(a[t]===void 0)throw pH(`UNKNOWN_GROUP_BY_PROPERTY`,t);if(!UW.includes(a[t]))throw pH(`INVALID_GROUP_BY_PROPERTY`,t,UW.join(`, `),a[t])}let o=t.map(([t])=>OH(e.internalDocumentIDStore,t)),s=e.documentsStore.getMultiple(e.data.docs,o),c=s.length,l=n.maxResult||2**53-1,u=[],d={};for(let e=0;e<i;e++){let t=r[e],n={property:t,perValue:{}},i=new Set;for(let e=0;e<c;e++){let r=s[e],a=tH(r,t);if(a===void 0)continue;let o=typeof a==`boolean`?``+a:a,c=n.perValue[o]??{indexes:[],count:0};c.count>=l||(c.indexes.push(e),c.count++,n.perValue[o]=c,i.add(a))}u.push(Array.from(i)),d[t]=n}let f=GW(u),p=f.length,m=[];for(let e=0;e<p;e++){let t=f[e],n=t.length,i={values:[],indexes:[]},a=[];for(let e=0;e<n;e++){let n=t[e],o=r[e];a.push(d[o].perValue[typeof n==`boolean`?``+n:n].indexes),i.values.push(n)}i.indexes=$V(a).sort((e,t)=>e-t),i.indexes.length!==0&&m.push(i)}let h=m.length,g=Array.from({length:h});for(let e=0;e<h;e++){let r=m[e],i=n.reduce||HW,a=r.indexes.map(e=>({id:o[e],score:t[e][1],document:s[e]})),c=i.reducer.bind(null,r.values),l=i.getInitialValue(r.indexes.length),u=a.reduce(c,l);g[e]={values:r.values,result:u}}return g}function GW(e,t=0){if(t+1===e.length)return e[t].map(e=>[e]);let n=e[t],r=GW(e,t+1),i=[];for(let e of n)for(let t of r){let n=[e];UV(n,t),i.push(n)}return i}function KW(e,t,n,r){let i=_W(t,r);if(i.length===0)return n;let a=i.flatMap(e=>e.consequence.promote);a.sort((e,t)=>e.position-t.position);let o=new Set,s=new Map,c=new Set;for(let t of a){let n=DH(e.internalDocumentIDStore,t.doc_id);if(n!==void 0){if(s.has(n)){let e=s.get(n);t.position<e&&s.set(n,t.position);continue}c.has(t.position)||(o.add(n),s.set(n,t.position),c.add(t.position))}}if(s.size===0)return n;let l=n.filter(([e])=>!o.has(e)),u=[];for(let[t,r]of s.entries())n.find(([e])=>e===t)?u.push([t,1e6-r]):e.documentsStore.get(e.data.docs,t)&&u.push([t,0]);u.sort((e,t)=>(s.get(e[0])??1/0)-(s.get(t[0])??1/0));let d=[],f=new Map;for(let e of u){let t=s.get(e[0]);f.set(t,e)}let p=0,m=0;for(;m<l.length+u.length;)if(f.has(m))d.push(f.get(m)),m++;else if(p<l.length)d.push(l[p]),p++,m++;else break;for(let[e,t]of f.entries())e>=d.length&&d.push(t);return d}function qW(e,t,n){let{term:r,properties:i}=t,a=e.data.index,o=e.caches.propertiesToSearch;if(!o){let t=e.index.getSearchablePropertiesWithTypes(a);o=e.index.getSearchableProperties(a),o=o.filter(e=>t[e].startsWith(`string`)),e.caches.propertiesToSearch=o}if(i&&i!==`*`){for(let e of i)if(!o.includes(e))throw pH(`UNKNOWN_INDEX`,e,o.join(`, `));o=o.filter(e=>i.includes(e))}let s=Object.keys(t.where??{}).length>0,c;s&&(c=e.index.searchByWhereClause(a,e.tokenizer,t.where,n));let l,u=t.threshold!==void 0&&t.threshold!==null?t.threshold:1;if(r||i){let i=wW(e);if(l=e.index.search(a,r||``,e.tokenizer,n,o,t.exact||!1,t.tolerance||0,t.boost||{},QW(t.relevance),i,c,u),t.exact&&r){let t=r.trim().split(/\s+/);l=l.filter(([n])=>{let r=e.documentsStore.get(e.data.docs,n);if(!r)return!1;for(let e of o){let n=YW(r,e);if(typeof n==`string`&&t.every(e=>RegExp(`\\b${JW(e)}\\b`).test(n)))return!0}return!1})}}else l=s?kU(a,t.where)||(c?Array.from(c):[]).map(e=>[+e,0]):Object.keys(e.documentsStore.getAll(e.data.docs)).map(e=>[+e,0]);return l}function JW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function YW(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r&&typeof r==`object`&&e in r)r=r[e];else return;return r}function XW(e,t,n){let r=YV();function i(){let i=Object.keys(e.data.index.vectorIndexes),a=t.facets&&Object.keys(t.facets).length>0,{limit:o=10,offset:s=0,distinctOn:c,includeVectors:l=!1}=t,u=t.preflight===!0,d=qW(e,t,n);if(t.sortBy)if(typeof t.sortBy==`function`){let n=d.map(([e])=>e),r=e.documentsStore.getMultiple(e.data.docs,n).map((e,t)=>[d[t][0],d[t][1],e]);r.sort(t.sortBy),d=r.map(([e,t])=>[e,t])}else d=e.sorter.sortBy(e.data.sorting,d,t.sortBy).map(([t,n])=>[DH(e.internalDocumentIDStore,t),n]);else d=d.sort(QV);d=KW(e,e.data.pinning,d,t.term);let f;u||(f=c?uG(e,d,s,o,c):dG(e,d,s,o));let p={elapsed:{formatted:``,raw:0},hits:[],count:d.length};return f!==void 0&&(p.hits=f.filter(Boolean),l||iH(p,i)),a&&(p.facets=zW(e,d,t.facets)),t.groupBy&&(p.groups=WW(e,d,t.groupBy)),p.elapsed=e.formatElapsedTime(YV()-r),p}async function a(){e.beforeSearch&&await KH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await GH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}const ZW={k:1.2,b:.75,d:.5};function QW(e){let t=e??{};return t.k=t.k??ZW.k,t.b=t.b??ZW.b,t.d=t.d??ZW.d,t}function $W(e,t,n){let r=t.vector;if(r&&(!(`value`in r)||!(`property`in r)))throw pH(`INVALID_VECTOR_INPUT`,Object.keys(r).join(`, `));let i=e.data.index.vectorIndexes[r.property];if(!i)throw pH(`UNKNOWN_VECTOR_PROPERTY`,r.property);let a=i.node.size;if(r?.value.length!==a)throw r?.property===void 0||r?.value.length===void 0?pH(`INVALID_INPUT_VECTOR`,`undefined`,a,`undefined`):pH(`INVALID_INPUT_VECTOR`,r.property,a,r.value.length);let o=e.data.index,s;return Object.keys(t.where??{}).length>0&&(s=e.index.searchByWhereClause(o,e.tokenizer,t.where,n)),i.node.find(r.value,t.similarity??.8,s)}function eG(e,t,n=`english`){let r=YV();function i(){let i=$W(e,t,n).sort(QV);i=KW(e,e.data.pinning,i,void 0);let a=[];t.facets&&Object.keys(t.facets).length>0&&(a=zW(e,i,t.facets));let o=t.vector.property,s=t.includeVectors??!1,c=t.limit??10,l=t.offset??0,u=Array.from({length:c});for(let t=0;t<c;t++){let n=i[t+l];if(!n)break;let r=e.data.docs.docs[n[0]];r&&(s||(r[o]=null),u[t]={id:OH(e.internalDocumentIDStore,n[0]),score:n[1],document:r})}let d=[];t.groupBy&&(d=WW(e,i,t.groupBy));let f=YV()-r;return{count:i.length,hits:u.filter(Boolean),elapsed:{raw:Number(f),formatted:JV(f)},...a?{facets:a}:{},...d?{groups:d}:{}}}async function a(){e.beforeSearch&&await KH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await GH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}function tG(e,t,n){let r=iG(qW(e,t,n)),i=$W(e,t,n),a=t.hybridWeights;return sG(r,i,t.term??``,a)}function nG(e,t,n){let r=YV();function i(){let i=tG(e,t,n);i=KW(e,e.data.pinning,i,t.term);let a;t.facets&&Object.keys(t.facets).length>0&&(a=zW(e,i,t.facets));let o;t.groupBy&&(o=WW(e,i,t.groupBy));let s=t.offset??0,c=t.limit??10,l=dG(e,i,s,c).filter(Boolean),u=YV(),d={count:i.length,elapsed:{raw:Number(u-r),formatted:JV(u-r)},hits:l,...a?{facets:a}:{},...o?{groups:o}:{}};return(t.includeVectors??!1)||iH(d,Object.keys(e.data.index.vectorIndexes)),d}async function a(){e.beforeSearch&&await KH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await GH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}function rG(e){return e[1]}function iG(e){let t=Math.max.apply(Math,e.map(rG));return e.map(([e,n])=>[e,n/t])}function aG(e,t){return e/t}function oG(e,t){return(n,r)=>n*e+r*t}function sG(e,t,n,r){let i=Math.max.apply(Math,e.map(rG)),a=Math.max.apply(Math,t.map(rG)),{text:o,vector:s}=r&&r.text&&r.vector?r:cG(n),c=new Map,l=e.length,u=oG(o,s);for(let t=0;t<l;t++){let[n,r]=e[t],a=u(aG(r,i),0);c.set(n,a)}let d=t.length;for(let e=0;e<d;e++){let[n,r]=t[e],i=aG(r,a),o=c.get(n)??0;c.set(n,o+u(0,i))}return[...c].sort((e,t)=>t[1]-e[1])}function cG(e){return{text:.5,vector:.5}}function lG(e,t,n){let r=t.mode??`fulltext`;if(r===`fulltext`)return XW(e,t,n);if(r===`vector`)return eG(e,t);if(r===`hybrid`)return nG(e,t);throw pH(`INVALID_SEARCH_MODE`,r)}function uG(e,t,n,r,i){let a=e.data.docs,o=new Map,s=[],c=new Set,l=t.length,u=0;for(let d=0;d<l;d++){let l=t[d];if(l===void 0)continue;let[f,p]=l;if(c.has(f))continue;let m=e.documentsStore.get(a,f),h=tH(m,i);if(!(h===void 0||o.has(h))&&(o.set(h,!0),u++,!(u<=n)&&(s.push({id:OH(e.internalDocumentIDStore,f),score:p,document:m}),c.add(f),u>=n+r)))break}return s}function dG(e,t,n,r){let i=e.data.docs,a=Array.from({length:r}),o=new Set;for(let s=n;s<r+n;s++){let n=t[s];if(n===void 0)break;let[r,c]=n;if(!o.has(r)){let t=e.documentsStore.get(i,r);a[s]={id:OH(e.internalDocumentIDStore,r),score:c,document:t},o.add(r)}}return a}var fG=n(OV(),1);const pG=1,mG={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`};function hG({kind:e,runtimeVersion:t}){return{[mG.protocol]:`1`,[mG.runtime]:t,[mG.kind]:e}}const gG=`__system__`,_G=1,vG=`__config__/project`,yG=`__user__/config.yml`,bG=`__local__/project`,xG=`__config__/okignore`,SG=Object.freeze([vG,bG,yG,xG]),CG=`__skill__/`,wG=`__template__/`,TG=[`project`,`global`];function EG(e){return e.startsWith(`__skill__/`)||e.startsWith(`__template__/`)}const DG=`.ok/skills`;function OG(e){return`${DG}/${e}/SKILL`}const kG=[`references`,`scripts`];function AG(e,t){let n=/^(\.ok\/skills\/[^/]+)\/SKILL$/.exec(t);if(!n)return null;let r=n[1],i=e.trim().replace(/\.mdx?$/i,``).split(`/`).filter(e=>e!==``&&e!==`.`),[a]=i;return!a||!kG.includes(a)||i.includes(`..`)||i.length<2?null:`${r}/${i.join(`/`)}`}const jG=/^\.ok\/skills\/([^/]+)\/(SKILL|references\/.+)$/;function MG(e){let t=jG.exec(e);if(!t)return null;let n=t[1],r=t[2];return r===`SKILL`?{name:n,kind:`skill`,rel:null}:{name:n,kind:`reference`,rel:r.slice(11)}}const NG=/^__skill__\/global\/([^/]+)(?:\/(references\/.+))?$/;function PG(e){let t=NG.exec(e);if(!t)return null;let n=t[1],r=t[2];return r===void 0?{name:n,kind:`skill`,rel:null}:{name:n,kind:`reference`,rel:r.slice(11)}}function FG(e,t){return e===`project`?OG(t):`${CG}${e}/${t}`}function IG(e){if(e===``)return``;try{return e.split(`/`).map(e=>decodeURIComponent(e)).join(`/`)}catch{return e}}function LG(e){if(e.startsWith(`__skill__/`)){let t=e.slice(10),n=t.indexOf(`/`);if(n<0)return null;let r=t.slice(0,n);if(r!==`global`&&r!==`project`)return null;let i=t.slice(n+1);return i?{kind:`skill`,scope:r,name:IG(i)}:null}if(e.startsWith(`__template__/`)){let t=e.slice(13);if(!t)return null;let n=t.lastIndexOf(`/`),r=n<0?t:t.slice(n+1);return r?{kind:`template`,folder:IG(n<0?``:t.slice(0,n)),name:IG(r)}:null}return null}const RG=/^(?:(.+)\/)?\.ok\/templates\/([^/]+?)(?:\.mdx?)?$/;function zG(e){let t=RG.exec(e);if(t){let e=(t[1]??``).replace(/^\/+|\/+$/g,``);return`${wG}${e?`${e}/`:``}${t[2]}`}return null}const BG=[`.mdx`,`.md`],VG=`epoch`,HG=512*1024,UG=[`claude`,`claude-desktop`,`cursor`,`codex`,`opencode`,`openclaw`,`pi`,`antigravity`,`lm-studio`],WG={claude:`Claude`,"claude-desktop":`Claude Desktop`,cursor:`Cursor`,codex:`Codex`,opencode:`OpenCode`,openclaw:`OpenClaw`,pi:`Pi`,antigravity:`Antigravity`,"lm-studio":`LM Studio`},GG={claude:`.claude/skills`,"claude-desktop":null,cursor:`.cursor/skills`,codex:`.codex/skills`,opencode:`.opencode/skills`,openclaw:null,pi:`.pi/skills`,antigravity:null,"lm-studio":null},KG=UG.filter(e=>GG[e]!==null),qG=KG.filter(e=>e!==`pi`).map(e=>({hostDir:(GG[e]??``).split(`/`)[0],editorId:e})),JG={claude:`.mcp.json`,"claude-desktop":null,cursor:`.cursor/mcp.json`,codex:`.codex/config.toml`,opencode:`opencode.json`,openclaw:null,pi:`.pi/extensions/open-knowledge.ts`,antigravity:null,"lm-studio":null},YG={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},XG=`Ov23liqlSd0V1MwR6rhI`,ZG=[`incoming`,`outgoing`,`both`];function QG(e){return ZG.includes(e)}const $G=`open-knowledge`,eK=[{id:`chart`,title:`Chart`,description:`A bar chart whose series colors track the OK chart palette.`,html:`<div style="font-family:system-ui,sans-serif;padding:20px;color:var(--foreground)">
305
305
  <h3 style="margin:0 0 14px;font-size:15px;font-weight:600">Revenue by region</h3>
306
306
  <div id="bars" style="display:flex;align-items:flex-end;gap:14px;height:170px"></div>
307
307
  <script>
@@ -450,4 +450,4 @@ $2`).split(`
450
450
  `);if(!(t[0]??``).startsWith(`template:`))return null;let n=[t[0]??``],r=1;for(;r<t.length;){let e=t[r]??``;if(/^[ \t]/.test(e)){n.push(e),r++;continue}if(e.trim()===``){let i=r+1;for(;i<t.length&&(t[i]??``).trim()===``;)i++;if(i<t.length&&/^[ \t]/.test(t[i]??``)){n.push(e),r++;continue}}break}let i=B6(n.join(`
451
451
  `))[z6];return{identity:typeof i==`object`&&i&&!Array.isArray(i)?i:{},docFrontmatterText:t.slice(r).join(`
452
452
  `).replace(/\n+$/,``)}}function W6(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,{frontmatter:n,body:r}=dK(t);if(n===``)return{identity:{},starterContent:t};let i=pK(n),a=U6(i);if(a)return{identity:a.identity,starterContent:V6(a.docFrontmatterText,r)};let{frontmatter:o}=dK(r);if(o!==``)return{identity:B6(i),starterContent:r};let s=B6(i);return typeof s.title==`string`?{identity:s,starterContent:r}:{identity:{},starterContent:V6(i,r)}}function G6(e,t){let{docFrontmatterText:n,markdown:r}=H6(t),i={};for(let[t,n]of Object.entries(e))n!==void 0&&(i[t]=n);let a=(0,Fc.stringify)({[z6]:i});return`---\n${n.trim()===``?a:`${a}${n}\n`}---\n${r}`}function K6(e){return W6(e).starterContent}function q6(){let e=!1,t=``,n=0;return r=>{let i=J6(r);return e?(i&&i.char===t&&i.len>=n&&!i.hasInfo&&(e=!1,t=``,n=0),!0):i?(e=!0,t=i.char,n=i.len,!0):!1}}function J6(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const Y6=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],X6={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function Z6(e,t=Y6){let n=0;for(let t of e)n=(n<<5)-n+t.charCodeAt(0)|0;return t[Math.abs(n)%t.length]}const Q6={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function $6(e){return e?Q6[e]||(e.startsWith(`local-agent-mode-`)?`claude`:`bot`):`bot`}const e8={claude:`Claude`,cursor:`Cursor`,windsurf:`Windsurf`,openai:`Codex`,github:`Copilot`,cline:`Cline`};function t8(e){let t=e?.trim();return t?e8[$6(t)]??t:`Agent`}function n8(e,t){let n=e.trim();if(!n||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(n)||n.startsWith(`//`)||n.startsWith(`#`))return null;let r=n.indexOf(`#`),i=r>=0?n.slice(0,r):n,a=r>=0?n.slice(r+1):null,o=(i.split(`?`)[0]??``).trim();if(!o)return null;let s=(o.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(s){let e=(s[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let c=o.toLowerCase(),l=c.endsWith(`.mdx`)?o.slice(0,-4):c.endsWith(`.md`)?o.slice(0,-3):o,u=l.startsWith(`/`),d=u?l.slice(1):l,f=u?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of d.split(`/`))if(e===`..`){if(f.length===0)return null;f.pop()}else e!==`.`&&e!==``&&f.push(e);return f.length===0?null:{docName:f.join(`/`),anchor:a||null}}const r8=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function i8(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function a8(e){let t=e.trim();return r8.test(t)||t.startsWith(`//`)}function o8(e,t){let n=e.trim();if(!n)return null;if(n.startsWith(`#`)){let e=n.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}if(a8(n))return{kind:`external`,url:n};let r=n8(n,t);if(r)return{kind:`doc`,docName:r.docName,anchor:r.anchor};let i=i8(n);return i&&i!==`md`&&i!==`mdx`?{kind:`asset`,url:n,ext:i}:null}function s8(e,t){let n=e.trim();if(!n)return null;if(a8(n))return{kind:`external`,url:t?`${n}#${t}`:n};let r=i8(n);return r&&r!==`md`&&r!==`mdx`?{kind:`asset`,url:n,ext:r}:{kind:`doc`,docName:n,anchor:t?.trim()||null}}function c8(e,t){let n=e.trim();if(!n||r8.test(n)||n.startsWith(`//`)||n.startsWith(`#`))return null;let r=n.indexOf(`#`),i=((r>=0?n.slice(0,r):n).split(`?`)[0]??``).trim();if(!i)return null;let a=i.startsWith(`/`),o=a?i.slice(1):i,s=a?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of o.split(`/`))if(e===`..`){if(s.length===0)return null;s.pop()}else e!==`.`&&e!==``&&s.push(e);return s.length===0?null:s.join(`/`)}function l8(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function u8(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function d8(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function f8(e){return e.split(`/`).filter(e=>e!==``)}function p8(e,t){let n=d8(t);return e===``||n===e?!0:n.startsWith(`${e}/`)}function m8(e,t){let n=d8(t);if(e===n)return 0;let r=e===``?n:n.slice(e.length+1);return r===``?0:f8(r).length}function h8(e,t){let n=f8(e),r=f8(t),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;return n.length-i+(r.length-i)}function g8(){let e=new Map;function t(t){let n=l8(t);if(n===``)return;let r=u8(n);if(r===``)return;let i=r.toLowerCase(),a=e.get(i);if(!a){e.set(i,[n]);return}a.includes(n)||a.push(n)}function n(t){let n=l8(t),r=u8(n).toLowerCase(),i=e.get(r);if(!i)return;let a=i.indexOf(n);a!==-1&&(i.splice(a,1),i.length===0&&e.delete(r))}function r(e,r){n(e),t(r)}function i(t,n){let r=t.toLowerCase(),i=e.get(r);if(!i||i.length===0)return null;if(i.length===1)return i[0];let a=d8(l8(n)),o=[],s=[];for(let e of i)p8(a,e)?o.push(e):s.push(e);return o.length>0?(e=>{let t=e[0],n=m8(a,t);for(let r=1;r<e.length;r++){let i=e[r],o=m8(a,i);(o<n||o===n&&i<t)&&(t=i,n=o)}return t})(o):(e=>{let t=e[0],n=h8(a,d8(t));for(let r=1;r<e.length;r++){let i=e[r],o=h8(a,d8(i));(o<n||o===n&&i<t)&&(t=i,n=o)}return t})(s)}function a(){let t=new Map;for(let[n,r]of e)t.set(n,[...r]);return t}function o(){e.clear()}return{add:t,remove:n,rename:r,resolveEmbed:i,clear:o,snapshot:a,size:()=>e.size}}function _8(e){if(!e)return[];let t=e.split(`/`),n=[],r=``;for(let e of t)r=r?`${r}/${e}`:e,n.push(r);return n}function v8(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let n=new Set,r=`${t}/`;for(let i of e)(i===t||i.startsWith(r))&&n.add(i);return n}function y8(e){try{return process.kill(e,0),!0}catch(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`)}}function b8(e){return!(typeof e!=`number`||!Number.isInteger(e)||e<2||e>2147483647)}const x8=/^[A-Za-z0-9-]{8,64}$/;let S8=null;function C8(e){return l(e??m(),`.ok`,`machine-id`)}function w8(e){if(e===void 0&&S8!==null)return S8;let t=C8(e),n=null;try{let e=b(t,`utf-8`).trim();x8.test(e)&&(n=e)}catch{}if(n===null){n=w();try{v(c(t),{recursive:!0}),S(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){console.warn(`[machine-id] Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(S8=n),n}function T8(){try{let e=u(c(f(import.meta.url)),`..`,`package.json`),t=JSON.parse(b(e,`utf-8`));if(typeof t.version==`string`&&t.version.length>0)return t.version}catch{}return`0.0.0-unknown`}const E8=T8(),D8=1;var O8=class extends Error{existing;lockPath;lockName;constructor(e,t,n){super(`OpenKnowledge ${n} already running on port ${e.port} (pid ${e.pid}, started ${e.startedAt}). Stop it first or use a different directory. Lock: ${t}`),this.name=`ProcessLockCollisionError`,this.existing=e,this.lockPath=t,this.lockName=n}};function k8(e,t){return u(e,`${t}.lock`)}const A8=new Map;function j8(e){A8.set(e,(A8.get(e)??0)+1)}function M8(e){let t=A8.get(e);return t===void 0||t<=1?(A8.delete(e),!0):(A8.set(e,t-1),!1)}function N8(e){return typeof e.machineId==`string`?e.machineId===w8():e.hostname===h()}const P8=new Set;let F8=!1;function I8(e){P8.add(e),!F8&&(F8=!0,process.on(`exit`,()=>{for(let e of P8)try{let t=JSON.parse(b(e,`utf-8`));if(t?.pid!==process.pid||typeof t.machineId==`string`&&t.machineId!==w8()||t.machineId===void 0&&typeof t.hostname==`string`&&t.hostname!==h())continue;x(e)}catch{}}))}function L8(e,t){try{let n=JSON.parse(b(e,`utf-8`));return n&&typeof n==`object`&&b8(n.pid)?n:(console.warn(`${t} Corrupt lock file at ${e} — replacing`),null)}catch{return console.warn(`${t} Corrupt lock file at ${e} — replacing`),null}}function R8(e){let{lockName:t,lockDir:n,metadata:r}=e,i=`[${t}-lock]`;v(n,{recursive:!0});let a=k8(n,t),o={pid:process.pid,hostname:h(),port:r.port,startedAt:new Date().toISOString(),worktreeRoot:r.worktreeRoot,machineId:w8(),...r.kind!==void 0&&{kind:r.kind},...r.parentPid!==void 0&&{parentPid:r.parentPid},...r.capabilities!==void 0&&{capabilities:r.capabilities},protocolVersion:r.protocolVersion??1,runtimeVersion:r.runtimeVersion??E8},s=JSON.stringify(o,null,2);for(let e=0;e<3;e++){if(!_(a))try{let e=y(a,`wx`,384);try{C(e,s)}finally{g(e)}return j8(a),I8(a),z8({lockName:t,lockDir:n,lockPath:a})}catch(e){if(e.code!==`EEXIST`)throw e}let e=L8(a,i);if(e){if(N8(e)&&e.pid===process.pid)return S(a,s,{encoding:`utf-8`,mode:384}),j8(a),I8(a),z8({lockName:t,lockDir:n,lockPath:a});if(y8(e.pid))throw new O8(e,a,t);console.warn(`${i} Stale lock detected (pid=${e.pid}, host=${e.hostname}) — replacing`)}try{x(a)}catch{}}throw Error(`${i} Failed to acquire ${a} after 3 attempts (concurrent acquire contention).`)}function z8(e){let{lockName:t,lockDir:n,lockPath:r}=e;return{lockPath:r,release:()=>G8({lockName:t,lockDir:n}),updatePort:e=>B8({lockName:t,lockDir:n,port:e})}}function B8(e){let{lockName:t,lockDir:n,port:r}=e,i=`[${t}-lock]`,a=k8(n,t);if(!_(a)){console.warn(`${i} Lock file missing at ${a} during port update — skipping`);return}let o;try{let e=JSON.parse(b(a,`utf-8`));if(!e||typeof e!=`object`||!b8(e.pid)){console.warn(`${i} Corrupt lock at ${a} during port update — skipping`);return}o=e}catch{console.warn(`${i} Unreadable lock at ${a} during port update — skipping`);return}if(o.pid===process.pid&&N8(o)){o.port=r;try{S(a,JSON.stringify(o,null,2),{encoding:`utf-8`,mode:384})}catch(e){console.warn(`${i} Failed to update port in ${a}: ${e instanceof Error?e.message:String(e)}`)}}}function V8(e){let{lockName:t,lockDir:n}=e,r=`[${t}-lock]`,i=k8(n,t);if((A8.get(i)??0)>1)return;let a;try{let e=JSON.parse(b(i,`utf-8`));if(!e||typeof e!=`object`||!b8(e.pid)){console.warn(`${r} Corrupt lock at ${i} during draining mark — skipping`);return}a=e}catch(e){e.code!==`ENOENT`&&console.warn(`${r} Unreadable lock at ${i} during draining mark — skipping: ${e instanceof Error?e.message:String(e)}`);return}if(a.pid===process.pid&&N8(a)&&a.draining!==!0){a.draining=!0;try{S(i,JSON.stringify(a,null,2),{encoding:`utf-8`,mode:384})}catch(e){console.warn(`${r} Failed to mark ${i} draining: ${e instanceof Error?e.message:String(e)}`)}}}function H8(e){let{lockName:t,lockDir:n}=e,r=k8(n,t);if(!_(r))return null;let i;try{let e=JSON.parse(b(r,`utf-8`));if(!e||typeof e!=`object`||!b8(e.pid))return null;i=e}catch{return null}if(!N8(i))return null;if(!y8(i.pid)){try{x(r)}catch{}return null}return i}function U8(e){let{lockName:t,lockDir:n}=e,r=k8(n,t);if(!_(r))return{status:`absent`};let i;try{i=JSON.parse(b(r,`utf-8`))}catch{return{status:`incompatible`,reason:`corrupt`,raw:void 0}}if(!i||typeof i!=`object`)return{status:`incompatible`,reason:`corrupt`,raw:i};let a=i;if(!b8(a.pid)||typeof a.hostname!=`string`||typeof a.port!=`number`||typeof a.startedAt!=`string`||typeof a.worktreeRoot!=`string`)return{status:`incompatible`,reason:`corrupt`,raw:i};let o={pid:a.pid,hostname:a.hostname,port:a.port,startedAt:a.startedAt,worktreeRoot:a.worktreeRoot,machineId:typeof a.machineId==`string`?a.machineId:void 0,draining:a.draining===!0?!0:void 0,protocolVersion:typeof a.protocolVersion==`number`?a.protocolVersion:void 0,runtimeVersion:typeof a.runtimeVersion==`string`?a.runtimeVersion:void 0};if(!N8(o))return{status:`stale`,lock:o};if(!y8(o.pid)){try{x(r)}catch{}return{status:`stale`,lock:o}}return o.protocolVersion===void 0||o.runtimeVersion===void 0?{status:`incompatible`,reason:`missing-fields`,raw:i}:{status:`live`,lock:o}}async function W8(e){let{lockName:t,lockDir:n}=e,r=e.timeoutMs??1e4,i=e.pollIntervalMs??100,a=e.readLock??(()=>H8({lockName:t,lockDir:n})),o=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=a();if(s===null||s.draining!==!0)return`no-drain`;let c=Date.now()+r;for(;Date.now()<c;){await o(i);let e=a();if(e===null)return`released`;if(e.draining!==!0)return`no-drain`}return`timeout`}function G8(e){let{lockName:t,lockDir:n,deferUnlinkToExit:r=!1}=e,i=`[${t}-lock]`,a=k8(n,t);if(M8(a)){if(r){V8({lockName:t,lockDir:n});return}if(_(a))try{let e=JSON.parse(b(a,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`||e.pid!==process.pid||!N8(e))return;x(a),P8.delete(a)}catch(e){console.warn(`${i} Failed to release ${a}: ${e instanceof Error?e.message:String(e)}`)}}}var K8=class extends O8{constructor(e,t){super(e,t,`server`),this.name=`ServerLockCollisionError`}};function q8(e,t){try{return R8({lockName:`server`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof O8&&e.lockName===`server`?new K8(e.existing,e.lockPath):e}}function J8(e,t){B8({lockName:`server`,lockDir:e,port:t})}function Y8(e){return H8({lockName:`server`,lockDir:e})}function X8(e,t){G8({lockName:`server`,lockDir:e,...t})}function Z8(e){V8({lockName:`server`,lockDir:e})}function Q8(e,t){return W8({lockName:`server`,lockDir:e,...t})}export{mG as $,fl as $a,f2 as $i,z2 as $n,YG as $r,n0 as $t,a1 as A,lu as Aa,g$ as Ai,N6 as An,Uo as Ao,X0 as Ar,_2 as At,g1 as B,Kc as Ba,Gq as Bi,n2 as Bn,cn as Bo,w2 as Br,H3 as Bt,m1 as C,M$ as Ca,t8 as Ci,K1 as Cn,Pc as Co,L2 as Cr,A0 as Ct,b1 as D,gb as Da,T6 as Di,O2 as Dn,Ks as Do,lJ as Dr,z1 as Dt,o1 as E,P4 as Ea,R6 as Ei,DG as En,$s as Eo,x0 as Er,GG as Et,j1 as F,Cl as Fa,$6 as Fi,B1 as Fn,br as Fo,Y0 as Fr,e1 as Ft,v4 as G,nu as Ga,zG as Gi,Cq as Gn,ht as Go,C2 as Gr,VG as Gt,b4 as H,pl as Ha,QG as Hi,e2 as Hn,Dt as Ho,T2 as Hr,c2 as Ht,A1 as I,wl as Ia,K6 as Ii,V1 as In,un as Io,z6 as Ir,qG as It,p4 as J,jl as Ja,A4 as Ji,Aq as Jn,p0 as Jr,t0 as Jt,h4 as K,Yc as Ka,Z4 as Ki,Eq as Kn,mt as Ko,x2 as Kr,I1 as Kt,qq as L,Sl as La,Rq as Li,n4 as Ln,fn as Lo,j2 as Lr,U1 as Lt,i1 as M,ou as Ma,P$ as Mi,L3 as Mn,Ka as Mo,Q0 as Mr,N1 as Mt,v1 as N,Dl as Na,IY as Ni,BG as Nn,qa as No,q0 as Nr,S1 as Nt,s1 as O,op as Oa,_8 as Oi,A6 as On,xs as Oo,Z1 as Or,w0 as Ot,nJ as P,Zc as Pa,cq as Pi,gG as Pn,si as Po,J0 as Pr,C1 as Pt,_G as Q,ql as Qa,MG as Qi,Qq as Qn,B0 as Qr,r0 as Qt,G4 as R,xl as Ra,r1 as Ri,o4 as Rn,mn as Ro,h2 as Rr,W1 as Rt,UG as S,W4 as Sa,F4 as Si,I0 as Sn,dc as So,X2 as Sr,k0 as St,d0 as T,hq as Ta,K3 as Ti,H0 as Tn,A as To,P2 as Tr,JG as Tt,y4 as U,cu as Ua,O3 as Ui,a4 as Un,k as Uo,E2 as Ur,b0 as Ut,g4 as V,Xc as Va,EG as Vi,a2 as Vn,zt as Vo,b2 as Vr,o2 as Vt,_4 as W,su as Wa,Iq as Wi,eJ as Wn,O as Wo,S2 as Wr,G3 as Wt,d4 as X,au as Xa,q3 as Xi,Fq as Xn,f0 as Xr,a0 as Xt,f4 as Y,Rl as Ya,PG as Yi,Nq as Yn,m0 as Yr,i0 as Yt,l4 as Z,Xl as Za,LG as Zi,Zq as Zn,z0 as Zr,cJ as Zt,X8 as _,mq as _a,WZ as _i,N0 as _n,rc as _o,Z2 as _r,X1 as _t,R8 as a,OG as aa,U4 as ai,$G as an,Il as ao,q2 as ar,Jq as at,Q8 as b,dK as ba,k3 as bi,aJ as bn,j as bo,d2 as br,O1 as bt,y8 as c,X$ as ca,o8 as ci,_0 as cn,Ls as co,B2 as cr,T1 as ct,V8 as d,n8 as da,Z6 as di,q1 as dn,Hs as do,I2 as dr,T0 as dt,W6 as ea,sJ as ei,Q1 as en,El as eo,K2 as er,SG as et,Z8 as f,AG as fa,kJ as fi,S3 as fn,Ws as fo,e4 as fr,E0 as ft,G8 as g,fq as ga,q6 as gi,pG as gn,tc as go,u2 as gr,HG as gt,Y8 as h,P3 as ha,g8 as hi,KG as hn,jc as ho,I6 as hr,I3 as ht,K8 as i,Y4 as ia,T4 as ii,TG as in,zl as io,N2 as ir,yG as it,y1 as j,qc as ja,B$ as ji,l2 as jn,ma as jo,Z0 as jr,v2 as jt,x1 as k,L as ka,V3 as ki,j6 as kn,Go as ko,$0 as kr,g2 as kt,b8 as l,c8 as la,s8 as li,g0 as ln,uc as lo,V2 as lr,D0 as lt,U8 as m,j4 as ma,A2 as mi,nK as mn,M as mo,D2 as mr,rK as mt,E8 as n,tK as na,G1 as ni,CG as nn,ml as no,U2 as nr,vG as nt,q8 as o,R4 as oa,iJ as oi,_$ as on,kl as oo,c4 as or,Xq as ot,H8 as p,S6 as pa,G6 as pi,eK as pn,N as po,t4 as pr,XG as pt,u4 as q,Jc as qa,b3 as qi,jq as qn,h0 as qr,o0 as qt,D8 as r,Y$ as ra,E4 as ri,wG as rn,Tl as ro,W2 as rr,bG as rt,w8 as s,J4 as sa,Wq as si,y0 as sn,Al as so,J2 as sr,w1 as st,O8 as t,fK as ta,oJ as ti,e0 as tn,eu as to,G2 as tr,xG as tt,k8 as u,L6 as ua,hG as ui,ZG as un,F as uo,F2 as ur,O0 as ut,B8 as v,FG as va,r6 as vi,j0 as vn,I as vo,Q2 as vr,L0 as vt,u0 as w,pK as wa,F3 as wi,V0 as wn,ac as wo,R2 as wr,WG as wt,X6 as x,v8 as xa,x3 as xi,F0 as xn,P as xo,Y2 as xr,D1 as xt,J8 as y,q4 as ya,t6 as yi,tJ as yn,Zs as yo,$2 as yr,R0 as yt,e3 as z,bl as za,_q as zi,t2 as zn,gn as zo,p2 as zr,J1 as zt};
453
- //# sourceMappingURL=server-lock-iLcBw_q0-rwg8rOgA.mjs.map
453
+ //# sourceMappingURL=server-lock-iLcBw_q0-CdaRzkXM.mjs.map
@@ -1,7 +1,7 @@
1
- import{s as e}from"./chunk-C94x7I9S.mjs";import{c as t,l as n,s as r,u as i}from"./server-lock-iLcBw_q0-rwg8rOgA.mjs";import{Mr as a,Nr as o,Tn as s,ga as c,ii as l,pn as u,xn as d}from"./dist-uq1hO0l5.mjs";import{t as f}from"./esm-CsQUg9js.mjs";import"./gh-detect-CkD5P0-7.mjs";import{C as ee,D as p,M as m,N as h,S as te,d as g,j as _,k as v,w as y}from"./init-Ctx2NP2_.mjs";import{_ as ne,d as re,i as ie,v as ae}from"./write-project-skill-CIXZymGf.mjs";import"./loader-_BJcNCg3.mjs";import{c as oe}from"./colors-8SzMRIVy.mjs";import"./preview-CX35q4j-.mjs";import{dirname as se,isAbsolute as b,join as x,relative as S,resolve as C}from"node:path";import{hostname as w}from"node:os";import{existsSync as T,lstatSync as E,readFileSync as D,readlinkSync as ce,rmSync as le,statSync as ue}from"node:fs";import{readFile as O,realpath as k}from"node:fs/promises";function A(e,a,o={}){let s=i(e,a);if(!T(s))return{status:`missing`,lockPath:s};let c;try{c=JSON.parse(D(s,`utf-8`))}catch{return{status:`corrupt`,lockPath:s}}if(!c||typeof c!=`object`||!n(c.pid))return{status:`corrupt`,lockPath:s};let l=c;if(!(o.isAlive??t)(l.pid))return{status:`dead-pid`,lockPath:s,lock:l};if(typeof l.machineId==`string`)return l.machineId===(o.machineId??r())?{status:`alive`,lockPath:s,lock:l}:{status:`foreign-host`,lockPath:s,lock:l};let u=o.host??w();return l.hostname===u?{status:`alive`,lockPath:s,lock:l}:{status:`foreign-host`,lockPath:s,lock:l}}function j(e){return e.replace(/:\d+$/,``)}function M(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function N(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`).filter(e=>e.length>0);if(n.length<5||n[2]!==`blob`)return null;let r,i,a,o;try{r=decodeURIComponent(n[0]),i=decodeURIComponent(n[1]),a=decodeURIComponent(n[3]),o=n.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!r||!i||!a||o.length===0||o.some(e=>e.length===0)?null:{owner:r,repo:i,branch:a,path:o.join(`/`)}}function P(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`);if(n.length<5||n[0]!==``||n[3]!==`tree`)return null;let r=n.slice(5);r.length===1&&r[0]===``&&r.pop();let i,a,o,s;try{i=decodeURIComponent(n[1]),a=decodeURIComponent(n[2]),o=decodeURIComponent(n[4]),s=r.map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.some(e=>e.length===0)?null:{owner:i,repo:a,branch:o,path:s.join(`/`)}}function F(e){let t=N(e);if(t)return{kind:`doc`,...t};let n=P(e);return n?{kind:`folder`,...n}:null}const I=`# >>> open-knowledge cli >>>`,L=`# <<< open-knowledge cli <<<`,R=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function z(e){return x(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}const B={existsSync:e=>T(e),readFileSync:(e,t)=>D(e,t),lstatSync:e=>E(e),readlinkSync:e=>ce(e)};function V(e,t=B){let n=z(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function H(e){let t=e.replace(R,``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function U(e,t,n=B){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}function de(e){return ne(e)||ae(e)||v(e)}function fe(e,t,n,r){let i=g(e,t,n,r);if(i.kind===`absent`||i.kind===`no-entry`)return{kind:`not-present`};if(i.kind===`decline`)return{kind:`declined`,reason:i.reason};if(!de(i.entry))return{kind:`left-foreign`};let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=e.serverName(t);return e.format===`file`?(le(a,{force:!0}),{kind:`removed`}):e.format===`toml`?me(a,o):pe(a,e.topLevelKey,e.serverMapSubKey,o)}function pe(e,t,n,r){let i;try{i=D(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(i,`utf-8`)>10485760)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=h(i,ee(t,n,r));return o?(c(e,a,{mode:_(e)}),{kind:`removed`}):{kind:`not-present`}}function me(e,t){let n=p();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=D(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=m(a),s=a.trim()===``||a.endsWith(`
1
+ import{s as e}from"./chunk-C94x7I9S.mjs";import{c as t,l as n,s as r,u as i}from"./server-lock-iLcBw_q0-CdaRzkXM.mjs";import{Mr as a,Nr as o,Tn as s,ga as c,ii as l,pn as u,xn as d}from"./dist-DU6kAT_L.mjs";import{t as f}from"./esm-CsQUg9js.mjs";import"./gh-detect-C8cgnhPS.mjs";import{C as ee,D as p,M as m,N as h,S as te,d as g,j as _,k as v,w as y}from"./init-BB94DLRV.mjs";import{_ as ne,d as re,i as ie,v as ae}from"./write-project-skill-BnCIY7g1.mjs";import"./loader-C8BAnl-B.mjs";import{c as oe}from"./colors-8SzMRIVy.mjs";import"./preview-B3hDDzfT.mjs";import{dirname as se,isAbsolute as b,join as x,relative as S,resolve as C}from"node:path";import{hostname as w}from"node:os";import{existsSync as T,lstatSync as E,readFileSync as D,readlinkSync as ce,rmSync as le,statSync as ue}from"node:fs";import{readFile as O,realpath as k}from"node:fs/promises";function A(e,a,o={}){let s=i(e,a);if(!T(s))return{status:`missing`,lockPath:s};let c;try{c=JSON.parse(D(s,`utf-8`))}catch{return{status:`corrupt`,lockPath:s}}if(!c||typeof c!=`object`||!n(c.pid))return{status:`corrupt`,lockPath:s};let l=c;if(!(o.isAlive??t)(l.pid))return{status:`dead-pid`,lockPath:s,lock:l};if(typeof l.machineId==`string`)return l.machineId===(o.machineId??r())?{status:`alive`,lockPath:s,lock:l}:{status:`foreign-host`,lockPath:s,lock:l};let u=o.host??w();return l.hostname===u?{status:`alive`,lockPath:s,lock:l}:{status:`foreign-host`,lockPath:s,lock:l}}function j(e){return e.replace(/:\d+$/,``)}function M(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function N(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`).filter(e=>e.length>0);if(n.length<5||n[2]!==`blob`)return null;let r,i,a,o;try{r=decodeURIComponent(n[0]),i=decodeURIComponent(n[1]),a=decodeURIComponent(n[3]),o=n.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!r||!i||!a||o.length===0||o.some(e=>e.length===0)?null:{owner:r,repo:i,branch:a,path:o.join(`/`)}}function P(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`);if(n.length<5||n[0]!==``||n[3]!==`tree`)return null;let r=n.slice(5);r.length===1&&r[0]===``&&r.pop();let i,a,o,s;try{i=decodeURIComponent(n[1]),a=decodeURIComponent(n[2]),o=decodeURIComponent(n[4]),s=r.map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.some(e=>e.length===0)?null:{owner:i,repo:a,branch:o,path:s.join(`/`)}}function F(e){let t=N(e);if(t)return{kind:`doc`,...t};let n=P(e);return n?{kind:`folder`,...n}:null}const I=`# >>> open-knowledge cli >>>`,L=`# <<< open-knowledge cli <<<`,R=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function z(e){return x(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}const B={existsSync:e=>T(e),readFileSync:(e,t)=>D(e,t),lstatSync:e=>E(e),readlinkSync:e=>ce(e)};function V(e,t=B){let n=z(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function H(e){let t=e.replace(R,``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function U(e,t,n=B){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}function de(e){return ne(e)||ae(e)||v(e)}function fe(e,t,n,r){let i=g(e,t,n,r);if(i.kind===`absent`||i.kind===`no-entry`)return{kind:`not-present`};if(i.kind===`decline`)return{kind:`declined`,reason:i.reason};if(!de(i.entry))return{kind:`left-foreign`};let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=e.serverName(t);return e.format===`file`?(le(a,{force:!0}),{kind:`removed`}):e.format===`toml`?me(a,o):pe(a,e.topLevelKey,e.serverMapSubKey,o)}function pe(e,t,n,r){let i;try{i=D(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(i,`utf-8`)>10485760)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=h(i,ee(t,n,r));return o?(c(e,a,{mode:_(e)}),{kind:`removed`}):{kind:`not-present`}}function me(e,t){let n=p();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=D(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=m(a),s=a.trim()===``||a.endsWith(`
2
2
  `),l;try{l=n.removeEntry(a,t)}catch{return{kind:`declined`,reason:`unparseable`}}if(!l.existed)return{kind:`not-present`};let u=l.text;s?u.endsWith(`
3
3
  `)||(u=`${u}\n`):u=u.replace(/\n+$/,``),o&&(u=u.replace(/\r\n/g,`
4
4
  `).replace(/\n/g,`\r
5
5
  `));let d=`${i?``:``}${u}`;return d!==r&&c(e,d,{mode:_(e)}),{kind:`removed`}}const he=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`deinit`]);function ge(e,t,n=s){if(e!==void 0&&!he.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let W=null;function _e(e){W=e}function G(){return W??process.cwd()}var K=e(oe(),1);function ve(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function ye(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function be(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:d(r),command:r,isDesktop:ve(r)}}function xe(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function q(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&xe(e)?`ui-orphan`:`stale`}const Se=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Ce(e){switch(e){case`running`:return K.default.green(e);case`desktop`:return K.default.blue(e);case`foreign`:return K.default.cyan(e);case`ui-orphan`:return K.default.magenta(e);case`stale`:return K.default.yellow(e)}}function J(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function we(e){return`${J(e.server.usage)} | ${J(e.ui?.usage??null)}`}function Te(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ee(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=q(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Te(e),we(e),t,String(n),ye(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Ce(q(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=K.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
6
6
  `)}async function Y(e={}){let t=e.discover??u,n=e.inspect??A,r=e.log??(e=>console.log(e)),i=e.resolveCommand??a,s=e.resolveUsage??o,c=await t(),l=[];for(let e of c){let t=n(e,`server`),r=n(e,`ui`),a=be(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:s(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:s(r.lock.pid));a!=null&&l.push(a)}if(e.json){let e=l.map(e=>({...e,displayStatus:q(e)}));r(JSON.stringify(e,null,2));return}r(Ee(e.all?l:l.filter(e=>Se.has(q(e)))))}function De(){return new f(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await Y({all:t.all===!0||e===`all`,json:t.json===!0})})}function Oe(e,n,r={}){let i=r.isAlive??t,a=[];for(let[t,r]of[[`server`,e],[`ui`,n]])(r.status===`alive`||r.status===`foreign-host`&&i(r.lock.pid))&&a.push({name:t,pid:r.lock.pid,port:r.lock.port});return{targets:a}}function X(e){let t=e.inspect??(t=>A(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Oe(t(`server`),t(`ui`),{isAlive:e.isAlive});if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Z(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function ke(e,n=t){let r=await u(),i=null;for(let t of r){let r=A(t,`server`),a=A(t,`ui`);if(Z(r,n)&&r.lock.port===e||Z(a,n)&&a.lock.port===e)return t;i===null&&(Z(r,n)&&r.lock.pid===e||Z(a,n)&&a.lock.pid===e)&&(i=t)}return i}function Q(e){let t=X({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function Ae(e){return new f(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async n=>{let r=n.length===0?void 0:n.join(` `);if(r===void 0){e();let t=X({lockDir:l(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await Y({});return}if(r===`all`){let e=await u();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let n=0;for(let r of e){let e=A(r,`server`),i=A(r,`ui`);!Z(e,t)&&!Z(i,t)||(Q(r),n++)}n===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(r)){let e=Number.parseInt(r,10),t=await ke(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}Q(t);return}Q(l(C(G(),r)))})}function je(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}async function Me(e,t){let n,r;try{n=await k(C(e)),r=await k(C(se(e)))}catch{return{kind:`not-git`}}if(!$(n,r))return{kind:`symlink-escape`};let i=x(n,`.git`),a;try{a=ue(i)}catch{return{kind:`not-git`}}let o;if(a.isDirectory()){let e;try{e=await k(i)}catch{return{kind:`not-git`}}if(!$(e,n))return{kind:`symlink-escape`};o=e}else if(a.isFile()){let e;try{e=await O(i,`utf-8`)}catch{return{kind:`not-git`}}let t=/^gitdir:\s*(.+)$/m.exec(e.trim());if(!t)return{kind:`not-git`};let r=t[1].trim(),a=b(r)?r:C(n,r);try{o=await k(a)}catch{return{kind:`not-git`}}}else return{kind:`not-git`};let s=x(await Ne(o),`config`),c;try{c=await O(s,`utf-8`)}catch{return{kind:`not-git`}}let l=Fe(c);if(l===null)return{kind:`no-origin`};let u=M(l);if(u===null||u.hostname!==`github.com`)return{kind:`non-github`};let d=u.owner.toLowerCase()===t.owner.toLowerCase(),f=u.name.toLowerCase()===t.repo.toLowerCase();return!d||!f?{kind:`wrong-repo`,actualOwner:u.owner,actualRepo:u.name}:{kind:`ok`,gitRemoteUrl:`https://github.com/${u.owner}/${u.name}.git`}}async function Ne(e){let t;try{t=(await O(x(e,`commondir`),`utf-8`)).trim()}catch{return e}if(t.length===0)return e;let n=b(t)?t:C(e,t);try{return await k(n)}catch{return n}}function $(e,t){if(e===t)return!0;let n=S(t,e);return n.length>0&&!n.startsWith(`..`)&&!b(n)}function Pe(e){let t=e.indexOf(`#`),n=e.indexOf(`;`),r=-1;return t>=0&&n>=0?r=Math.min(t,n):t>=0?r=t:n>=0&&(r=n),(r===-1?e:e.slice(0,r)).trim()}function Fe(e){let t=!1;for(let n of e.split(/\r?\n/)){let e=Pe(n);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let r=/^url\s*=\s*(.+)$/.exec(e);if(r)return Ie(r[1])}return null}function Ie(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}const Le=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=y(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let n=ie(e,t);return{integration:`project-skill`,editorId:e.id,action:n.action,...n.path?{path:n.path}:{},...n.error?{error:n.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function Re(e,t,n={},r=Le){let i=[];for(let a of t){let t=re[a];for(let a of r)i.push(a.write(t,e,n))}return i}function ze(e,t,n={}){return{integrations:Re(e,t,n),claudeLaunchJson:t.includes(`claude`)?te(e,n):void 0}}export{N as _,Ae as a,M as b,ge as c,R as d,L as f,H as g,V as h,X as i,fe as l,z as m,Me as n,De as o,U as p,je as r,_e as s,ze as t,I as u,F as v,A as x,P as y};
7
- //# sourceMappingURL=src-Bv4nWkUq.mjs.map
7
+ //# sourceMappingURL=src-DigXo6He.mjs.map
@@ -1,3 +1,3 @@
1
- import{Mn as e,ht as t}from"./server-lock-iLcBw_q0-rwg8rOgA.mjs";import{cr as n,jr as r,xr as i}from"./dist-uq1hO0l5.mjs";import{n as a,t as o}from"./esm-CsQUg9js.mjs";import{i as s,t as c}from"./gh-detect-CkD5P0-7.mjs";import{n as l}from"./constants-BDeiyoTG.mjs";import{spawn as u}from"node:child_process";import{basename as d,dirname as f,join as p}from"node:path";import{homedir as m}from"node:os";import{closeSync as h,existsSync as g,mkdirSync as _,openSync as v,statSync as y}from"node:fs";import{rm as b}from"node:fs/promises";import{setTimeout as x}from"node:timers/promises";const S=`OpenKnowledge.app`,C=`/Applications/${S}`;function w(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return y(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function T(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(E(e,C))return C;let t=p(e.homeDir??m(),`Applications`,S);return E(e,t)?t:null}function E(e,t){try{let n=p(t,`Contents`,`MacOS`,`OpenKnowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function D(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=T(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function O(e){(e.log??(e=>console.error(e)))("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function k(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${C}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${C} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${C} but launch dispatch did not fire (caller bug).`}}function A(e){return p(f(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const j=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function M(e){if(e.platform!==`darwin`||!j.test(e.execPath))return null;let t=A(e.execPath);return e.exists(t)?t:null}function N(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??g,a=r[1];return a?{command:M({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function P(e,t){return e.host??t.HOST??`127.0.0.1`}function F(e){let t=d(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var I=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function L(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function R(t){g(t.lockDir)||_(t.lockDir,{recursive:!0});let n=v(p(t.lockDir,e),`w`),r=t.spawn??u,{PORT:i,...a}=process.env,o=N();try{let e=r(o.command,[...o.prefixArgs,...t.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,n],windowsHide:!0,cwd:t.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return e.unref(),e}finally{try{h(n)}catch{}}}function z(e,t,n){return e??(n===void 0?t:void 0)}function B(e,t){return e!==void 0&&t!==null&&t.port>0&&t.draining!==!0}function V(e,t,n){return e??(t!=null&&!n?1:0)}async function H(e){let t=e.spawn??u,n=N(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,windowsHide:!0,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=V(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function U(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const W=t;function G(e,t,n=e=>b(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}}}}function K(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:i?1:0,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(i?1:0)}}}function q(e){let t=e.sigtermGraceMs??W,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>x(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function J(e){let{config:t,cwd:a,host:o}=e,l=e.skipAutoInit??!1,u=e.skipUiAutoSpawn??!1,d=e.idleThresholdMs??18e5,{existsSync:f,mkdirSync:p}=await import(`node:fs`),{basename:m,dirname:h}=await import(`node:path`),{bootServer:g,getLogger:_,isProcessAlive:v,readUiLock:y,resolveContentDir:b,resolveLockDir:S,waitForServerLockDrain:C}=await import(`./dist-B2S_dh_W.mjs`),w=e.log??_(`start`),T=e.singleFile!==void 0,E=e.projectDir??a,D=T?r(e.singleFile).canonicalFilePath:void 0,O=D?h(D):void 0,k=D?m(D):void 0;if(!T){if(!l&&!n(a))throw new I(a);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&w.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-BY_IWOhJ.mjs`)).repairMcpConfigs)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-B22PVEUL.mjs`)).repairLaunchJson)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-BoioTwtW.mjs`)).repairSkills)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let A=O??b(t,a);!T&&!f(A)&&(p(A,{recursive:!0}),w.info({contentDir:A},`Created content directory`));let j=null,M=async({lockDir:t})=>{if(j=L({uiLock:y(t),isAlive:v}),j.action===`spawn`&&!u)try{let n=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];R({lockDir:t,cwd:a,spawn:e.spawn,args:n}),w.info({reason:j.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else j.action===`skip`&&w.info({port:j.port,pid:j.pid},`UI already running at port ${j.port}`)},N=e.reactShellDistDir===void 0,P=s(),F=i();{let e=S(T?E:a),t=Date.now(),n=await C(e);n!==`no-drain`&&w.info({event:`start-waited-for-draining-predecessor`,outcome:n,waitedMs:Date.now()-t,drainLockDir:e},n===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}let z=await g({config:t,contentDir:A,projectDir:T?E:a,contentRoot:T?void 0:t.content.dir,port:e.port,host:o,quiet:!1,detectGh:c,tokenStore:P,embeddingsKeyStore:F,...T?{ephemeral:!0,singleDocRelPath:k,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:N,idleShutdownMs:d,skipAutoInit:!0,...N?{spawnUiSiblingFn:M}:{},idleShutdownHandler:t=>{let n=q({readUiLock:()=>y(z.lockDir),isAlive:v,killPid:(e,t)=>{process.kill(e,t)},destroy:t,log:w});return K(T?G(n,E):n,{log:w,exit:e.idleExit})},log:w,...e.serveContentAssets?{serveContentAssets:!0}:{},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});j||={action:`skip`,reason:`alive`,pid:0,port:0};let B=j,V=null;if(B.action===`skip`)V=B.port>0?B.port:null;else if(!u){let t=e.uiBindTimeoutMs??3e3;V=await U({readUiLock:()=>y(z.lockDir),now:Date.now,sleep:e=>x(e),timeoutMs:t,pollIntervalMs:50}),V===null&&w.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:z.httpServer,destroy:z.destroy,lockDir:z.lockDir,contentDir:A,port:z.port,ready:z.ready,degraded:z.degraded,uiSpawnDecision:j,resolvedUiPort:V}}function ee(e){if(e===`browser`||e===`app`)return e;throw new a(`--mode must be 'browser' or 'app'`)}function te(e){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<1||t>65535)throw new a(`--ui-port must be a port number between 1 and 65535`);return t}function Y(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function X(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Z(e,t){let n=Y(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner-BxCFCyu8.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-CmkIIbww.mjs`),c=process.cwd(),u=e;process.title=F(c);let d=P(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=z(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./dist-B2S_dh_W.mjs`);if(B(m,e(t(c)))){await H({cwd:c,uiPort:m});return}}let g;try{g=await J({config:u,cwd:c,host:d,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets?{serveContentAssets:!0}:{},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof I&&(console.error(o(e.message)),process.exit(1));let t=await import(`./dist-B2S_dh_W.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&Q(e,t)){await H({cwd:c,uiPort:m});return}let n=$(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=X(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${d}:${g.port}`,b=d===`0.0.0.0`||d===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${d}:${x}`:y;console.log(r({name:`open-knowledge`,version:l,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-Bs3YoMQ3.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function Q(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function $(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=p(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function ne(e){return new o(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,te).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ee).option(`--serve-content-assets`,`Serve content assets from this server`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
1
+ import{Mn as e,ht as t}from"./server-lock-iLcBw_q0-CdaRzkXM.mjs";import{cr as n,jr as r,xr as i}from"./dist-DU6kAT_L.mjs";import{n as a,t as o}from"./esm-CsQUg9js.mjs";import{i as s,t as c}from"./gh-detect-C8cgnhPS.mjs";import{n as l}from"./constants-iJEQPyMf.mjs";import{spawn as u}from"node:child_process";import{basename as d,dirname as f,join as p}from"node:path";import{homedir as m}from"node:os";import{closeSync as h,existsSync as g,mkdirSync as _,openSync as v,statSync as y}from"node:fs";import{rm as b}from"node:fs/promises";import{setTimeout as x}from"node:timers/promises";const S=`OpenKnowledge.app`,C=`/Applications/${S}`;function w(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return y(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function T(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(E(e,C))return C;let t=p(e.homeDir??m(),`Applications`,S);return E(e,t)?t:null}function E(e,t){try{let n=p(t,`Contents`,`MacOS`,`OpenKnowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function D(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=T(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function O(e){(e.log??(e=>console.error(e)))("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function k(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${C}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${C} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${C} but launch dispatch did not fire (caller bug).`}}function A(e){return p(f(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const j=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function M(e){if(e.platform!==`darwin`||!j.test(e.execPath))return null;let t=A(e.execPath);return e.exists(t)?t:null}function N(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??g,a=r[1];return a?{command:M({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function P(e,t){return e.host??t.HOST??`127.0.0.1`}function F(e){let t=d(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var I=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function L(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function R(t){g(t.lockDir)||_(t.lockDir,{recursive:!0});let n=v(p(t.lockDir,e),`w`),r=t.spawn??u,{PORT:i,...a}=process.env,o=N();try{let e=r(o.command,[...o.prefixArgs,...t.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,n],windowsHide:!0,cwd:t.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return e.unref(),e}finally{try{h(n)}catch{}}}function z(e,t,n){return e??(n===void 0?t:void 0)}function B(e,t){return e!==void 0&&t!==null&&t.port>0&&t.draining!==!0}function V(e,t,n){return e??(t!=null&&!n?1:0)}async function H(e){let t=e.spawn??u,n=N(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,windowsHide:!0,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=V(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function U(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const W=t;function G(e,t,n=e=>b(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}}}}function K(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:i?1:0,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(i?1:0)}}}function q(e){let t=e.sigtermGraceMs??W,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>x(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function J(e){let{config:t,cwd:a,host:o}=e,l=e.skipAutoInit??!1,u=e.skipUiAutoSpawn??!1,d=e.idleThresholdMs??18e5,{existsSync:f,mkdirSync:p}=await import(`node:fs`),{basename:m,dirname:h}=await import(`node:path`),{bootServer:g,getLogger:_,isProcessAlive:v,readUiLock:y,resolveContentDir:b,resolveLockDir:S,waitForServerLockDrain:C}=await import(`./dist-BC-5uOuA.mjs`),w=e.log??_(`start`),T=e.singleFile!==void 0,E=e.projectDir??a,D=T?r(e.singleFile).canonicalFilePath:void 0,O=D?h(D):void 0,k=D?m(D):void 0;if(!T){if(!l&&!n(a))throw new I(a);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&w.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-B5jS3LgK.mjs`)).repairMcpConfigs)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-0_w3Th4l.mjs`)).repairLaunchJson)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-B0B7a5IA.mjs`)).repairSkills)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let A=O??b(t,a);!T&&!f(A)&&(p(A,{recursive:!0}),w.info({contentDir:A},`Created content directory`));let j=null,M=async({lockDir:t})=>{if(j=L({uiLock:y(t),isAlive:v}),j.action===`spawn`&&!u)try{let n=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];R({lockDir:t,cwd:a,spawn:e.spawn,args:n}),w.info({reason:j.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else j.action===`skip`&&w.info({port:j.port,pid:j.pid},`UI already running at port ${j.port}`)},N=e.reactShellDistDir===void 0,P=s(),F=i();{let e=S(T?E:a),t=Date.now(),n=await C(e);n!==`no-drain`&&w.info({event:`start-waited-for-draining-predecessor`,outcome:n,waitedMs:Date.now()-t,drainLockDir:e},n===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}let z=await g({config:t,contentDir:A,projectDir:T?E:a,contentRoot:T?void 0:t.content.dir,port:e.port,host:o,quiet:!1,detectGh:c,tokenStore:P,embeddingsKeyStore:F,...T?{ephemeral:!0,singleDocRelPath:k,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:N,idleShutdownMs:d,skipAutoInit:!0,...N?{spawnUiSiblingFn:M}:{},idleShutdownHandler:t=>{let n=q({readUiLock:()=>y(z.lockDir),isAlive:v,killPid:(e,t)=>{process.kill(e,t)},destroy:t,log:w});return K(T?G(n,E):n,{log:w,exit:e.idleExit})},log:w,...e.serveContentAssets?{serveContentAssets:!0}:{},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});j||={action:`skip`,reason:`alive`,pid:0,port:0};let B=j,V=null;if(B.action===`skip`)V=B.port>0?B.port:null;else if(!u){let t=e.uiBindTimeoutMs??3e3;V=await U({readUiLock:()=>y(z.lockDir),now:Date.now,sleep:e=>x(e),timeoutMs:t,pollIntervalMs:50}),V===null&&w.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:z.httpServer,destroy:z.destroy,lockDir:z.lockDir,contentDir:A,port:z.port,ready:z.ready,degraded:z.degraded,uiSpawnDecision:j,resolvedUiPort:V}}function ee(e){if(e===`browser`||e===`app`)return e;throw new a(`--mode must be 'browser' or 'app'`)}function te(e){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<1||t>65535)throw new a(`--ui-port must be a port number between 1 and 65535`);return t}function Y(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function X(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Z(e,t){let n=Y(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner-BxCFCyu8.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-CmkIIbww.mjs`),c=process.cwd(),u=e;process.title=F(c);let d=P(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=z(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./dist-BC-5uOuA.mjs`);if(B(m,e(t(c)))){await H({cwd:c,uiPort:m});return}}let g;try{g=await J({config:u,cwd:c,host:d,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets?{serveContentAssets:!0}:{},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof I&&(console.error(o(e.message)),process.exit(1));let t=await import(`./dist-BC-5uOuA.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&Q(e,t)){await H({cwd:c,uiPort:m});return}let n=$(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=X(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${d}:${g.port}`,b=d===`0.0.0.0`||d===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${d}:${x}`:y;console.log(r({name:`open-knowledge`,version:l,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-Csh_BnzS.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function Q(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function $(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=p(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function ne(e){return new o(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,te).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ee).option(`--serve-content-assets`,`Serve content assets from this server`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
2
2
  `),process.exit(2));let e=[];if(t.port!==void 0&&e.push(`--port`),t.uiPort!==void 0&&e.push(`--ui-port`),t.host!==void 0&&e.push(`--host`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=D(w());if(n.available){O({spawn:u});return}console.error(k(n.reason)),process.exit(1)}await Z(n,t)})}export{D as C,w as S,ne as _,V as a,K as b,F as c,z as d,P as f,R as g,B as h,q as i,X as l,Z as m,U as n,H as o,Y as p,J as r,L as s,I as t,Q as u,$ as v,O as w,N as x,G as y};
3
- //# sourceMappingURL=start-DAGRv3oL.mjs.map
3
+ //# sourceMappingURL=start-Bz36N1Vk.mjs.map
@@ -0,0 +1 @@
1
+ import{_ as e,f as t,r as n}from"./start-Bz36N1Vk.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};
@@ -0,0 +1,36 @@
1
+ import{It as e,S as t,an as n,wt as r}from"./server-lock-iLcBw_q0-CdaRzkXM.mjs";import{d as i,ei as a,ut as o}from"./dist-DU6kAT_L.mjs";import{basename as s,dirname as c,isAbsolute as ee,join as l,posix as u,relative as d,resolve as f,sep as p,win32 as m}from"node:path";import{homedir as h}from"node:os";import{cpSync as te,existsSync as g,lstatSync as _,mkdirSync as v,realpathSync as y,rmSync as b}from"node:fs";const x=t,S=r,C=e,w=`node`,T={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},ne=`# ok-mcp-v1`,E=`# ok-mcp-v1
2
+ USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
3
+ [ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" mcp
4
+ BUNDLE="/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
5
+ [ -f "$BUNDLE" ] && [ -x "$BUNDLE" ] && exec "$BUNDLE" mcp
6
+ command -v npx >/dev/null 2>&1 && exec npx -y @inkeep/open-knowledge@latest mcp
7
+ for d in "$HOME/.nvm/versions/node"/*/bin "$HOME/.fnm/node-versions"/*/installation/bin "$HOME/.asdf/installs/nodejs"/*/bin /opt/homebrew/bin /usr/local/bin "$HOME/.local/bin" "$HOME/.volta/bin"; do
8
+ [ -f "$d/npx" ] && [ -x "$d/npx" ] && exec "$d/npx" -y @inkeep/open-knowledge@latest mcp
9
+ done
10
+ echo "OpenKnowledge: install OK Desktop or Node.js 24+, then restart your editor" >&2
11
+ exit 127`,D=`# ok-mcp-win-v1`,O=`# ok-mcp-win-v1
12
+ if ($env:PATHEXT -notmatch 'CMD') { $env:PATHEXT = '.COM;.EXE;.BAT;.CMD;' + $env:PATHEXT }
13
+ if ($env:APPDATA) {
14
+ $shim = Join-Path $env:APPDATA 'npm\\ok.cmd'
15
+ if (Test-Path -LiteralPath $shim -PathType Leaf) { & $shim mcp; exit $LASTEXITCODE }
16
+ }
17
+ $ok = Get-Command ok.cmd -CommandType Application -ErrorAction SilentlyContinue
18
+ if ($ok) { & $ok.Source mcp; exit $LASTEXITCODE }
19
+ $npx = Get-Command npx.cmd -CommandType Application -ErrorAction SilentlyContinue
20
+ if ($npx) { & $npx.Source -y '@inkeep/open-knowledge@latest' mcp; exit $LASTEXITCODE }
21
+ $dirs = @()
22
+ if ($env:ProgramFiles) { $dirs += Join-Path $env:ProgramFiles 'nodejs' }
23
+ if ($env:NVM_SYMLINK) { $dirs += $env:NVM_SYMLINK }
24
+ if ($env:LOCALAPPDATA) {
25
+ $dirs += Join-Path $env:LOCALAPPDATA 'fnm\\aliases\\default'
26
+ $dirs += Join-Path $env:LOCALAPPDATA 'Volta\\bin'
27
+ $dirs += Join-Path $env:LOCALAPPDATA 'pnpm'
28
+ }
29
+ if ($env:USERPROFILE) { $dirs += Join-Path $env:USERPROFILE 'scoop\\shims' }
30
+ foreach ($d in $dirs) {
31
+ $probe = Join-Path $d 'npx.cmd'
32
+ if (Test-Path -LiteralPath $probe -PathType Leaf) { & $probe -y '@inkeep/open-knowledge@latest' mcp; exit $LASTEXITCODE }
33
+ }
34
+ [Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
35
+ exit 127`,k=`// ok-pi-bridge`,A=`${k}-v1`,j=`ok-pi-managed-extension`;function M(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command===`/bin/sh`){if(!Array.isArray(t.args)||t.args[0]!==`-l`||t.args[1]!==`-c`)return!1;let e=t.args[2];return typeof e==`string`&&e.includes(`# ok-mcp-v1`)}if(t.command===`powershell`){if(!Array.isArray(t.args)||t.args[0]!==`-NoProfile`||t.args[1]!==`-NonInteractive`||t.args[2]!==`-Command`)return!1;let e=t.args[3];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}if(t.type===`local`&&Array.isArray(t.command)){if(t.command[0]===`/bin/sh`){if(t.command[1]!==`-l`||t.command[2]!==`-c`)return!1;let e=t.command[3];return typeof e==`string`&&e.includes(`# ok-mcp-v1`)}if(t.command[0]===`powershell`){if(t.command[1]!==`-NoProfile`||t.command[2]!==`-NonInteractive`||t.command[3]!==`-Command`)return!1;let e=t.command[4];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}return!1}if(t.command===`ok-pi-managed-extension`){if(!Array.isArray(t.args))return!1;let e=t.args[0];return typeof e==`string`&&e.startsWith(A)}return!1}function N(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=f(e);if(s(t)===`cli.mjs`&&s(c(t))===`dist`)return t;let n=t.split(p),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return l(i.length===0?p:i.join(p),`packages`,`cli`,`dist`,`cli.mjs`)}function P(e={}){return e.mode===`dev`?{command:w,args:[N(),`mcp`],env:{...T}}:(e.platformName??process.platform)===`win32`?{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,O]}:{command:`/bin/sh`,args:[`-l`,`-c`,E]}}function re(e={}){return e.mode===`dev`?{type:`local`,enabled:!0,command:[w,N(),`mcp`],environment:{...T}}:(e.platformName??process.platform)===`win32`?{type:`local`,enabled:!0,command:[`powershell`,`-NoProfile`,`-NonInteractive`,`-Command`,O]}:{type:`local`,enabled:!0,command:[`/bin/sh`,`-l`,`-c`,E]}}function ie(e){if(typeof e!=`object`||!e)return!1;let t=e;return F(t,P({mode:`published`,platformName:`darwin`}))||F(t,P({mode:`published`,platformName:`win32`}))}function F(e,t){if(Object.keys(e).length!==Object.keys(t).length||e.command!==t.command)return!1;let n=t.args;return!Array.isArray(n)||!Array.isArray(e.args)||e.args.length!==n.length?!1:e.args.every((e,t)=>e===n[t])}function I(e){return e===`win32`?m:u}function ae(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env,i=I(t);return t===`darwin`?i.join(n,`Library`,`Application Support`):t===`win32`?r.APPDATA??i.join(n,`AppData`,`Roaming`):r.XDG_CONFIG_HOME??i.join(n,`.config`)}function L(e={}){let t=e.platformName??process.platform,n=e.home??h();return I(t).join(n,`.claude.json`)}function R(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env;if(t===`darwin`)return u.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??m.join(n,`AppData`,`Roaming`);return m.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function z(e={}){let t=e.platformName??process.platform,n=e.home??h();return I(t).join(n,`.cursor`,`mcp.json`)}function B(e={}){let t=e.platformName??process.platform,n=e.home??h();return(e.env??process.env).CODEX_HOME??I(t).join(n,`.codex`)}function V(e={}){return I(e.platformName??process.platform).join(B(e),`config.toml`)}function H(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env,i=I(t);if(t===`win32`){let e=r.APPDATA??i.join(n,`AppData`,`Roaming`);return i.join(e,`opencode`)}let a=r.XDG_CONFIG_HOME??i.join(n,`.config`);return i.join(a,`opencode`)}function U(e={}){return I(e.platformName??process.platform).join(H(e),`opencode.json`)}function W(e={}){let t=e.platformName??process.platform,n=e.home??h();return I(t).join(n,`.openclaw`,`openclaw.json`)}function G(e={}){let t=e.platformName??process.platform,n=e.home??h();return(e.env??process.env).PI_CODING_AGENT_DIR??I(t).join(n,`.pi`,`agent`)}function K(e={}){let t=e.platformName??process.platform,n=e.home??h();return I(t).join(n,`.gemini`,`config`,`mcp_config.json`)}function q(e,t){let n=I(t),r=n.join(e,`.lmstudio`,`mcp.json`),i=n.join(e,`.cache`,`lm-studio`,`mcp.json`);return t===`darwin`?[i,r]:[r,i]}function J(e={}){let t=e.platformName??process.platform,n=q(e.home??h(),t);return n.find(e=>g(e))||n.find(e=>g(c(e)))||n[0]}const Y={claude:{id:`claude`,label:S.claude,configPath:(e,t)=>L({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>P(t),scope:`global`,detectPath:(e,t)=>l(t??h(),`.claude`),projectConfigPath:e=>l(e,`.mcp.json`),projectSkillPath:e=>l(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:S[`claude-desktop`],configPath:(e,t)=>R({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>P(t),scope:`global`,detectPath:(e,t)=>c(R({home:t}))},cursor:{id:`cursor`,label:S.cursor,configPath:(e,t)=>z({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>P(t),scope:`global`,detectPath:(e,t)=>c(z({home:t})),projectConfigPath:e=>l(e,`.cursor`,`mcp.json`),projectSkillPath:e=>l(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:S.codex,configPath:(e,t)=>V({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>n,buildEntry:(e,t)=>P(t),scope:`global`,detectPath:(e,t)=>c(V({home:t})),projectConfigPath:e=>l(e,`.codex`,`config.toml`),projectSkillPath:e=>l(e,`.codex`,`skills`,`open-knowledge`,`SKILL.md`)},opencode:{id:`opencode`,label:S.opencode,configPath:(e,t)=>U({home:t}),format:`json`,topLevelKey:`mcp`,serverName:()=>n,buildEntry:(e,t)=>re(t),scope:`global`,detectPath:(e,t)=>c(U({home:t})),projectConfigPath:e=>l(e,`opencode.json`),projectSkillPath:e=>l(e,`.opencode`,`skills`,`open-knowledge`,`SKILL.md`)},openclaw:{id:`openclaw`,label:S.openclaw,configPath:(e,t)=>W({home:t}),format:`json`,topLevelKey:`mcp`,serverMapSubKey:`servers`,serverName:()=>n,buildEntry:(e,t)=>P(t),scope:`global`,detectPath:(e,t)=>l(t??h(),`.openclaw`),offerOnlyWhenDetected:!0},pi:{id:`pi`,label:S.pi,configPath:()=>{throw Error("Pi has no user-global MCP config; OK's integration is the project-scoped bridge extension at .pi/extensions/open-knowledge.ts (run `ok init` in the project).")},format:`file`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:()=>{throw Error(`Pi has no MCP entry shape; the managed bridge file is built by buildPiExtensionSource (integrations/pi-extension.ts).`)},scope:`project`,detectPath:(e,t)=>G({home:t}),projectConfigPath:e=>l(e,`.pi`,`extensions`,`open-knowledge.ts`),projectSkillPath:e=>l(e,`.pi`,`skills`,`open-knowledge`,`SKILL.md`)},antigravity:{id:`antigravity`,label:S.antigravity,configPath:(e,t)=>K({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>P(t),scope:`global`,detectPath:(e,t)=>l(t??h(),`.gemini`),offerOnlyWhenDetected:!0},"lm-studio":{id:`lm-studio`,label:S[`lm-studio`],configPath:(e,t)=>J({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>P(t),scope:`global`,detectPath:(e,t)=>c(J({home:t})),offerOnlyWhenDetected:!0}};function oe(e){let t=e.filter(e=>!Object.hasOwn(Y,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${x.join(`, `)}`);return e.map(e=>Y[e])}function X(e){let t=[];for(let n of o){let r=i[n];t.push({path:l(e,`.agents`,`skills`,r),bundleId:n,scope:`central`});for(let i of C)t.push({path:l(e,i.hostDir,`skills`,r),bundleId:n,scope:`host`,hostDir:i.hostDir})}return t}function se(e,t){let n=[];for(let r of X(e))if(r.bundleId===t)try{b(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}function Z(e,t){let n;try{n=_(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(n?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);$(e,t)}function Q(e,t){$(e,t)}function $(e,t){let n;try{n=y(t)}catch{n=f(t)}let r=c(e);for(;r.length>1&&r!==p;){let t;try{t=y(r)}catch(e){if(e.code===`ENOENT`){r=c(r);continue}throw e}let i=d(n,t);if(i===``||!i.startsWith(`..`)&&!ee(i))return;throw Error(`Refusing to write at ${e}: ancestor ${r} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function ce(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=a(`project`,{checkDesktop:!0}),i=c(n);Z(i,t);let o=g(n)?`overwritten`:`written`;return b(i,{recursive:!0,force:!0}),v(c(i),{recursive:!0}),te(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:o,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function le(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=c(n);return g(n)?(Q(r,t),b(r,{recursive:!0,force:!0}),{editorId:e.id,label:e.label,action:`removed`,path:n}):{editorId:e.id,label:e.label,action:`not-present`,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}export{M as _,se as a,N as b,ne as c,Y as d,C as f,P as g,j as h,ce as i,D as l,A as m,Q as n,X as o,k as p,le as r,x as s,Z as t,S as u,ie as v,oe as x,ae as y};
36
+ //# sourceMappingURL=write-project-skill-BnCIY7g1.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/open-knowledge",
3
- "version": "0.29.0-beta.2",
3
+ "version": "0.29.0-beta.3",
4
4
  "license": "GPL-3.0-or-later",
5
5
  "private": false,
6
6
  "type": "module",
@@ -1,2 +0,0 @@
1
- import"./server-lock-iLcBw_q0-rwg8rOgA.mjs";var e=`0.29.0-beta.2`;const t=`config.yml`,n=e;export{n,t};
2
- //# sourceMappingURL=constants-BDeiyoTG.mjs.map
@@ -1 +0,0 @@
1
- import{x as e}from"./init-Ctx2NP2_.mjs";export{e as runInit};
@@ -1 +0,0 @@
1
- import{n as e}from"./loader-_BJcNCg3.mjs";export{e as loadConfig};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./preview-CX35q4j-.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1 +0,0 @@
1
- import{t as e}from"./repair-skills-BHDFQ7QJ.mjs";export{e as repairSkills};
@@ -1 +0,0 @@
1
- import{_ as e,f as t,y as n}from"./server-lock-iLcBw_q0-rwg8rOgA.mjs";export{t as markServerLockDraining,e as releaseServerLock,n as updateServerLockPort};
@@ -1 +0,0 @@
1
- import{_ as e,f as t,r as n}from"./start-DAGRv3oL.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};