@ds-lang/monaco-editor 0.0.0-stage → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ <!-- SPDX-FileCopyrightText: 2026 Dan Finster and the Desert Sage Contributors -->
2
+ <!-- SPDX-License-Identifier: BSD-4-Clause OR AGPL-3.0-or-later -->
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ # ds-monaco-editor
5
+
6
+ `@ds-lang/monaco-editor`: the DS editor kit for [Monaco](https://microsoft.github.io/monaco-editor/): [Desert Sage (DS)](https://ds-lang.org) rulesets in the host page's own Monaco editor, with the DS compiler running in the browser for live diagnostics; completion, hover, signature help, go to definition, the outline (Ctrl-Shift-O), semantic highlighting, references (Shift-F12) and rename (F2) within the document from DS's language server for hosts that run Node; on a debugging session on the host's `ds dap` (`dsDebugger`), breakpoints in the glyph margin, the stop marked, stepping both ways (F5, Shift-F5, F10, Shift-F10, F11, Shift-F11, F6), and rule, fact, cache and exception breakpoints; and recordings of a run with their replay and inspect views, for the DS integrations to embed in their own pages.
7
+
8
+ It is `@ds-lang/codemirror-editor`'s counterpart, with the same options and the same core: everything no editor needs is `@ds-lang/editor-core`'s. Monaco itself is not bundled: a host passes its own to `createEditor`.
9
+
10
+ ## License
11
+
12
+ Copyright (c) 2026 Dan Finster and the Desert Sage Contributors.
13
+
14
+ Licensed under `BSD-4-Clause OR AGPL-3.0-or-later`, either at the licensee's choice; [LICENSE](LICENSE) holds both texts.
@@ -0,0 +1,77 @@
1
+ # Third-party notices
2
+
3
+ @ds-lang/monaco-editor's bundles in dist/ carry the packages below. Each is listed with its version, its licence, the bundles it is in, and the licence text it carries.
4
+
5
+ ## base64-js 1.5.1
6
+
7
+ Licence: MIT. In: ds-monaco-editor.js.
8
+
9
+ ~~~~
10
+ The MIT License (MIT)
11
+
12
+ Copyright (c) 2014 Jameson Little
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in
22
+ all copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30
+ THE SOFTWARE.
31
+ ~~~~
32
+
33
+ ## buffer 6.0.3
34
+
35
+ Licence: MIT. In: ds-monaco-editor.js.
36
+
37
+ ~~~~
38
+ The MIT License (MIT)
39
+
40
+ Copyright (c) Feross Aboukhadijeh, and other contributors.
41
+
42
+ Permission is hereby granted, free of charge, to any person obtaining a copy
43
+ of this software and associated documentation files (the "Software"), to deal
44
+ in the Software without restriction, including without limitation the rights
45
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
46
+ copies of the Software, and to permit persons to whom the Software is
47
+ furnished to do so, subject to the following conditions:
48
+
49
+ The above copyright notice and this permission notice shall be included in
50
+ all copies or substantial portions of the Software.
51
+
52
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
58
+ THE SOFTWARE.
59
+ ~~~~
60
+
61
+ ## ieee754 1.2.1
62
+
63
+ Licence: BSD-3-Clause. In: ds-monaco-editor.js.
64
+
65
+ ~~~~
66
+ Copyright 2008 Fair Oaks Labs, Inc.
67
+
68
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
69
+
70
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
71
+
72
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
73
+
74
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
75
+
76
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
77
+ ~~~~
@@ -0,0 +1,4 @@
1
+ var d="/ds-libraries",m=r=>r.endsWith(`
2
+ `)?r:`${r}
3
+ `;function f(r,{file:i="rules.ds",libraries:n={}}={}){let o={};for(let[s,e]of Object.entries(n)){if(!/^[A-Za-z0-9_.-]+\.ds$/.test(s))throw new Error(`a library is a .ds file name, not ${JSON.stringify(s)}`);o[`${d}/${s}`]=m(e)}let t=Object.keys(o).length?["-L",d]:[],a=s=>new TextEncoder().encode(m(s));return{async version(){let s=await r(["--version"],{});return(new TextDecoder().decode(s.stdout)||s.stderr).trim()},async diagnose(s){let e=await r(["check","-","--filename",i,"--diagnostics","json",...t],{stdin:a(s),files:o});if(e.status===0&&!e.stderr.trim())return{diagnostics:[]};try{let l=JSON.parse(e.stderr);return{diagnostics:l&&l.diagnostics||[]}}catch{return{diagnostics:[],failure:e.stderr.trim()||`dsc exited ${e.status}`}}},async compile(s){let e=await r(["compile","-","-o","-","--filename",i,...t],{stdin:a(s),files:o});return e.status===0?{ok:!0,bytes:e.stdout,log:e.stderr.trim()}:{ok:!1,status:e.status,log:e.stderr.trim()}}}}var c=null,u={async init({runner:r,dsc:i,wasm:n,file:o,libraries:t}){let{runDsc:a}=await import(r),s=await WebAssembly.compileStreaming(fetch(n));return c=f((e,l)=>a(i,e,{...l,wasmModule:s}),{file:o,libraries:t}),c.version()}};self.onmessage=async r=>{let{id:i,op:n,args:o}=r.data||{};try{let t;if(n==="init")t=await u.init(...o||[]);else if(c)if(Object.prototype.hasOwnProperty.call(c,n))t=await c[n](...o||[]);else throw new Error(`no such op: ${n}`);else throw new Error("the compiler is not initialised");let a=t&&t.bytes?[t.bytes.buffer]:[];self.postMessage({id:i,ok:!0,value:t},a)}catch(t){self.postMessage({id:i,ok:!1,error:String(t&&t.message||t)})}};
4
+ //# sourceMappingURL=compiler-worker.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../node_modules/@ds-lang/editor-core/src/compiler-core.mjs", "../node_modules/@ds-lang/editor-core/src/compiler-worker.mjs"],
4
+ "sourcesContent": ["// SPDX-FileCopyrightText: 2026 Dan Finster and the Desert Sage Contributors\n// SPDX-License-Identifier: BSD-4-Clause OR AGPL-3.0-or-later\n// What the editor asks of `dsc`, as operations over one function that runs it:\n// `runDsc` from `@ds-lang/ds`, on its WebAssembly build of dsc, in the\n// compiler worker (compiler-worker.mjs) and in Node. The host's libraries, given\n// as text, are written under LIBRARY_DIR, which is on the search path (`-L`).\n\nexport const LIBRARY_DIR = '/ds-libraries';\n\n/**\n * @typedef {(argv: string[], io: {stdin?: Uint8Array, files?: Record<string, string | Uint8Array>})\n * => Promise<{status: number, stdout: Uint8Array, stderr: string}>} RunDsc\n */\n\nconst withNewline = s => (s.endsWith('\\n') ? s : `${s}\\n`);\n\n/**\n * The editor's operations on dsc.\n *\n * @param {RunDsc} run runs dsc with an argv, standard input and files\n * @param {object} [options] the source's name and the host's libraries\n * @param {string} [options.file] what diagnostics call the source, rules.ds unless given\n * @param {Record<string, string>} [options.libraries] each library file's name and text, such as {'house.ds': '...'}\n */\nexport function compilerOps(run, { file = 'rules.ds', libraries = {} } = {}) {\n const files = {};\n for (const [name, text] of Object.entries(libraries)) {\n if (!/^[A-Za-z0-9_.-]+\\.ds$/.test(name)) {\n throw new Error(`a library is a .ds file name, not ${JSON.stringify(name)}`);\n }\n files[`${LIBRARY_DIR}/${name}`] = withNewline(text);\n }\n const search = Object.keys(files).length ? ['-L', LIBRARY_DIR] : [];\n const enc = s => new TextEncoder().encode(withNewline(s));\n\n return {\n /** @returns {Promise<string>} dsc's version line */\n async version() {\n const r = await run(['--version'], {});\n return (new TextDecoder().decode(r.stdout) || r.stderr).trim();\n },\n\n /**\n * The source's diagnostics as data (`dsc check --diagnostics json`):\n * code, severity, message, hint and a span. `failure` holds the\n * compiler's own words where it gives no diagnostic: usage (exit 2),\n * or its own failure (exit 3).\n *\n * @param {string} source the ruleset's text\n * @returns {Promise<{diagnostics: any[], failure?: string}>} the diagnostics\n */\n async diagnose(source) {\n const r = await run(['check', '-', '--filename', file, '--diagnostics', 'json', ...search], {\n stdin: enc(source),\n files,\n });\n if (r.status === 0 && !r.stderr.trim()) {\n return { diagnostics: [] };\n }\n try {\n const doc = JSON.parse(r.stderr);\n return { diagnostics: (doc && doc.diagnostics) || [] };\n } catch {\n return { diagnostics: [], failure: r.stderr.trim() || `dsc exited ${r.status}` };\n }\n },\n\n /**\n * A whole compilation: the .dsc, or the compiler's report as text.\n *\n * @param {string} source the ruleset's text\n * @returns {Promise<{ok: true, bytes: Uint8Array, log: string} | {ok: false, status: number, log: string}>} the result\n */\n async compile(source) {\n const r = await run(['compile', '-', '-o', '-', '--filename', file, ...search], {\n stdin: enc(source),\n files,\n });\n return r.status === 0\n ? { ok: true, bytes: r.stdout, log: r.stderr.trim() }\n : { ok: false, status: r.status, log: r.stderr.trim() };\n },\n };\n}\n", "// SPDX-FileCopyrightText: 2026 Dan Finster and the Desert Sage Contributors\n// SPDX-License-Identifier: BSD-4-Clause OR AGPL-3.0-or-later\n// The compiler's thread: dsc compiled to WebAssembly, off the main thread. The\n// module is compiled once and instantiated afresh for each run, as the Mercury\n// runtime keeps global state.\n//\n// The compiler is the host's own `@ds-lang/ds`'s. The first message names where\n// the host serves its files:\n//\n// {op: 'init', args: [{runner, dsc, wasm, file, libraries}]}\n// runner URL of @ds-lang/ds's lib/dsc-wasm.js\n// dsc URL of its build/ds_dsc/ds_dsc.mjs\n// wasm URL of its build/ds_dsc/dsc_cli.wasm\n// file the source's name in diagnostics\n// libraries {name.ds: text}, on the search path\n//\n// Then each message is {id, op, args}, answered {id, ok, value} or {id, ok:\n// false, error}: compiler-core.mjs's operations.\nimport { compilerOps } from './compiler-core.mjs';\n\nlet ops = null;\n\nconst handlers = {\n async init({ runner, dsc, wasm, file, libraries }) {\n const { runDsc } = await import(/* the host's own file */ runner);\n const wasmModule = await WebAssembly.compileStreaming(fetch(wasm));\n ops = compilerOps((argv, io) => runDsc(dsc, argv, { ...io, wasmModule }), { file, libraries });\n return ops.version();\n },\n};\n\nself.onmessage = async e => {\n const { id, op, args } = e.data || {};\n try {\n let value;\n if (op === 'init') {\n value = await handlers.init(...(args || []));\n } else if (!ops) {\n throw new Error('the compiler is not initialised');\n } else if (!Object.prototype.hasOwnProperty.call(ops, op)) {\n throw new Error(`no such op: ${op}`);\n } else {\n value = await ops[op](...(args || []));\n }\n // A .dsc's bytes move rather than copy.\n const transfer = value && value.bytes ? [value.bytes.buffer] : [];\n self.postMessage({ id, ok: true, value }, transfer);\n } catch (err) {\n self.postMessage({ id, ok: false, error: String((err && err.message) || err) });\n }\n};\n"],
5
+ "mappings": "AAOO,IAAMA,EAAc,gBAOrBC,EAAcC,GAAMA,EAAE,SAAS;AAAA,CAAI,EAAIA,EAAI,GAAGA,CAAC;AAAA,EAU9C,SAASC,EAAYC,EAAK,CAAE,KAAAC,EAAO,WAAY,UAAAC,EAAY,CAAC,CAAE,EAAI,CAAC,EAAG,CACzE,IAAMC,EAAQ,CAAC,EACf,OAAW,CAACC,EAAMC,CAAI,IAAK,OAAO,QAAQH,CAAS,EAAG,CAClD,GAAI,CAAC,wBAAwB,KAAKE,CAAI,EAClC,MAAM,IAAI,MAAM,qCAAqC,KAAK,UAAUA,CAAI,CAAC,EAAE,EAE/ED,EAAM,GAAGP,CAAW,IAAIQ,CAAI,EAAE,EAAIP,EAAYQ,CAAI,CACtD,CACA,IAAMC,EAAS,OAAO,KAAKH,CAAK,EAAE,OAAS,CAAC,KAAMP,CAAW,EAAI,CAAC,EAC5DW,EAAM,GAAK,IAAI,YAAY,EAAE,OAAOV,EAAY,CAAC,CAAC,EAExD,MAAO,CAEH,MAAM,SAAU,CACZ,IAAMW,EAAI,MAAMR,EAAI,CAAC,WAAW,EAAG,CAAC,CAAC,EACrC,OAAQ,IAAI,YAAY,EAAE,OAAOQ,EAAE,MAAM,GAAKA,EAAE,QAAQ,KAAK,CACjE,EAWA,MAAM,SAASC,EAAQ,CACnB,IAAMD,EAAI,MAAMR,EAAI,CAAC,QAAS,IAAK,aAAcC,EAAM,gBAAiB,OAAQ,GAAGK,CAAM,EAAG,CACxF,MAAOC,EAAIE,CAAM,EACjB,MAAAN,CACJ,CAAC,EACD,GAAIK,EAAE,SAAW,GAAK,CAACA,EAAE,OAAO,KAAK,EACjC,MAAO,CAAE,YAAa,CAAC,CAAE,EAE7B,GAAI,CACA,IAAME,EAAM,KAAK,MAAMF,EAAE,MAAM,EAC/B,MAAO,CAAE,YAAcE,GAAOA,EAAI,aAAgB,CAAC,CAAE,CACzD,MAAQ,CACJ,MAAO,CAAE,YAAa,CAAC,EAAG,QAASF,EAAE,OAAO,KAAK,GAAK,cAAcA,EAAE,MAAM,EAAG,CACnF,CACJ,EAQA,MAAM,QAAQC,EAAQ,CAClB,IAAMD,EAAI,MAAMR,EAAI,CAAC,UAAW,IAAK,KAAM,IAAK,aAAcC,EAAM,GAAGK,CAAM,EAAG,CAC5E,MAAOC,EAAIE,CAAM,EACjB,MAAAN,CACJ,CAAC,EACD,OAAOK,EAAE,SAAW,EACd,CAAE,GAAI,GAAM,MAAOA,EAAE,OAAQ,IAAKA,EAAE,OAAO,KAAK,CAAE,EAClD,CAAE,GAAI,GAAO,OAAQA,EAAE,OAAQ,IAAKA,EAAE,OAAO,KAAK,CAAE,CAC9D,CACJ,CACJ,CC/DA,IAAIG,EAAM,KAEJC,EAAW,CACb,MAAM,KAAK,CAAE,OAAAC,EAAQ,IAAAC,EAAK,KAAAC,EAAM,KAAAC,EAAM,UAAAC,CAAU,EAAG,CAC/C,GAAM,CAAE,OAAAC,CAAO,EAAI,MAAM,OAAiCL,GACpDM,EAAa,MAAM,YAAY,iBAAiB,MAAMJ,CAAI,CAAC,EACjE,OAAAJ,EAAMS,EAAY,CAACC,EAAMC,IAAOJ,EAAOJ,EAAKO,EAAM,CAAE,GAAGC,EAAI,WAAAH,CAAW,CAAC,EAAG,CAAE,KAAAH,EAAM,UAAAC,CAAU,CAAC,EACtFN,EAAI,QAAQ,CACvB,CACJ,EAEA,KAAK,UAAY,MAAMY,GAAK,CACxB,GAAM,CAAE,GAAAC,EAAI,GAAAC,EAAI,KAAAC,CAAK,EAAIH,EAAE,MAAQ,CAAC,EACpC,GAAI,CACA,IAAII,EACJ,GAAIF,IAAO,OACPE,EAAQ,MAAMf,EAAS,KAAK,GAAIc,GAAQ,CAAC,CAAE,UACnCf,EAEL,GAAK,OAAO,UAAU,eAAe,KAAKA,EAAKc,CAAE,EAGpDE,EAAQ,MAAMhB,EAAIc,CAAE,EAAE,GAAIC,GAAQ,CAAC,CAAE,MAFrC,OAAM,IAAI,MAAM,eAAeD,CAAE,EAAE,MAFnC,OAAM,IAAI,MAAM,iCAAiC,EAOrD,IAAMG,EAAWD,GAASA,EAAM,MAAQ,CAACA,EAAM,MAAM,MAAM,EAAI,CAAC,EAChE,KAAK,YAAY,CAAE,GAAAH,EAAI,GAAI,GAAM,MAAAG,CAAM,EAAGC,CAAQ,CACtD,OAASC,EAAK,CACV,KAAK,YAAY,CAAE,GAAAL,EAAI,GAAI,GAAO,MAAO,OAAQK,GAAOA,EAAI,SAAYA,CAAG,CAAE,CAAC,CAClF,CACJ",
6
+ "names": ["LIBRARY_DIR", "withNewline", "s", "compilerOps", "run", "file", "libraries", "files", "name", "text", "search", "enc", "r", "source", "doc", "ops", "handlers", "runner", "dsc", "wasm", "file", "libraries", "runDsc", "wasmModule", "compilerOps", "argv", "io", "e", "id", "op", "args", "value", "transfer", "err"]
7
+ }
@@ -0,0 +1,103 @@
1
+ var xr=Object.create;var $n=Object.defineProperty;var kr=Object.getOwnPropertyDescriptor;var vr=Object.getOwnPropertyNames;var Er=Object.getPrototypeOf,$r=Object.prototype.hasOwnProperty;var Ft=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ir=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of vr(e))!$r.call(n,s)&&s!==t&&$n(n,s,{get:()=>e[s],enumerable:!(r=kr(e,s))||r.enumerable});return n};var Br=(n,e,t)=>(t=n!=null?xr(Er(n)):{},Ir(e||!n||!n.__esModule?$n(t,"default",{value:n,enumerable:!0}):t,n));var Dn=Ft(ft=>{"use strict";ft.byteLength=Or;ft.toByteArray=Gr;ft.fromByteArray=zr;var Ie=[],we=[],Pr=typeof Uint8Array<"u"?Uint8Array:Array,Xt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(qe=0,Fn=Xt.length;qe<Fn;++qe)Ie[qe]=Xt[qe],we[Xt.charCodeAt(qe)]=qe;var qe,Fn;we[45]=62;we[95]=63;function Tn(n){var e=n.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=n.indexOf("=");t===-1&&(t=e);var r=t===e?0:4-t%4;return[t,r]}function Or(n){var e=Tn(n),t=e[0],r=e[1];return(t+r)*3/4-r}function jr(n,e,t){return(e+t)*3/4-t}function Gr(n){var e,t=Tn(n),r=t[0],s=t[1],i=new Pr(jr(n,r,s)),o=0,d=s>0?r-4:r,c;for(c=0;c<d;c+=4)e=we[n.charCodeAt(c)]<<18|we[n.charCodeAt(c+1)]<<12|we[n.charCodeAt(c+2)]<<6|we[n.charCodeAt(c+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=we[n.charCodeAt(c)]<<2|we[n.charCodeAt(c+1)]>>4,i[o++]=e&255),s===1&&(e=we[n.charCodeAt(c)]<<10|we[n.charCodeAt(c+1)]<<4|we[n.charCodeAt(c+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function qr(n){return Ie[n>>18&63]+Ie[n>>12&63]+Ie[n>>6&63]+Ie[n&63]}function Hr(n,e,t){for(var r,s=[],i=e;i<t;i+=3)r=(n[i]<<16&16711680)+(n[i+1]<<8&65280)+(n[i+2]&255),s.push(qr(r));return s.join("")}function zr(n){for(var e,t=n.length,r=t%3,s=[],i=16383,o=0,d=t-r;o<d;o+=i)s.push(Hr(n,o,o+i>d?d:o+i));return r===1?(e=n[t-1],s.push(Ie[e>>2]+Ie[e<<4&63]+"==")):r===2&&(e=(n[t-2]<<8)+n[t-1],s.push(Ie[e>>10]+Ie[e>>4&63]+Ie[e<<2&63]+"=")),s.join("")}});var Ln=Ft(Yt=>{Yt.read=function(n,e,t,r,s){var i,o,d=s*8-r-1,c=(1<<d)-1,l=c>>1,a=-7,u=t?s-1:0,m=t?-1:1,w=n[e+u];for(u+=m,i=w&(1<<-a)-1,w>>=-a,a+=d;a>0;i=i*256+n[e+u],u+=m,a-=8);for(o=i&(1<<-a)-1,i>>=-a,a+=r;a>0;o=o*256+n[e+u],u+=m,a-=8);if(i===0)i=1-l;else{if(i===c)return o?NaN:(w?-1:1)*(1/0);o=o+Math.pow(2,r),i=i-l}return(w?-1:1)*o*Math.pow(2,i-r)};Yt.write=function(n,e,t,r,s,i){var o,d,c,l=i*8-s-1,a=(1<<l)-1,u=a>>1,m=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,w=r?0:i-1,g=r?1:-1,_=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(d=isNaN(e)?1:0,o=a):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+u>=1?e+=m/c:e+=m*Math.pow(2,1-u),e*c>=2&&(o++,c/=2),o+u>=a?(d=0,o=a):o+u>=1?(d=(e*c-1)*Math.pow(2,s),o=o+u):(d=e*Math.pow(2,u-1)*Math.pow(2,s),o=0));s>=8;n[t+w]=d&255,w+=g,d/=256,s-=8);for(o=o<<s|d,l+=s;l>0;n[t+w]=o&255,w+=g,o/=256,l-=8);n[t+w-g]|=_*128}});var Zn=Ft(et=>{"use strict";var Jt=Dn(),Ze=Ln(),Mn=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;et.Buffer=h;et.SlowBuffer=Jr;et.INSPECT_MAX_BYTES=50;var pt=2147483647;et.kMaxLength=pt;h.TYPED_ARRAY_SUPPORT=Vr();!h.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Vr(){try{let n=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(n,e),n.foo()===42}catch{return!1}}Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.buffer}});Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.byteOffset}});function Se(n){if(n>pt)throw new RangeError('The value "'+n+'" is invalid for option "size"');let e=new Uint8Array(n);return Object.setPrototypeOf(e,h.prototype),e}function h(n,e,t){if(typeof n=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return tn(n)}return On(n,e,t)}h.poolSize=8192;function On(n,e,t){if(typeof n=="string")return Kr(n,e);if(ArrayBuffer.isView(n))return Xr(n);if(n==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n);if(Be(n,ArrayBuffer)||n&&Be(n.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Be(n,SharedArrayBuffer)||n&&Be(n.buffer,SharedArrayBuffer)))return Qt(n,e,t);if(typeof n=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let r=n.valueOf&&n.valueOf();if(r!=null&&r!==n)return h.from(r,e,t);let s=Yr(n);if(s)return s;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof n[Symbol.toPrimitive]=="function")return h.from(n[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n)}h.from=function(n,e,t){return On(n,e,t)};Object.setPrototypeOf(h.prototype,Uint8Array.prototype);Object.setPrototypeOf(h,Uint8Array);function jn(n){if(typeof n!="number")throw new TypeError('"size" argument must be of type number');if(n<0)throw new RangeError('The value "'+n+'" is invalid for option "size"')}function Wr(n,e,t){return jn(n),n<=0?Se(n):e!==void 0?typeof t=="string"?Se(n).fill(e,t):Se(n).fill(e):Se(n)}h.alloc=function(n,e,t){return Wr(n,e,t)};function tn(n){return jn(n),Se(n<0?0:nn(n)|0)}h.allocUnsafe=function(n){return tn(n)};h.allocUnsafeSlow=function(n){return tn(n)};function Kr(n,e){if((typeof e!="string"||e==="")&&(e="utf8"),!h.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=Gn(n,e)|0,r=Se(t),s=r.write(n,e);return s!==t&&(r=r.slice(0,s)),r}function Zt(n){let e=n.length<0?0:nn(n.length)|0,t=Se(e);for(let r=0;r<e;r+=1)t[r]=n[r]&255;return t}function Xr(n){if(Be(n,Uint8Array)){let e=new Uint8Array(n);return Qt(e.buffer,e.byteOffset,e.byteLength)}return Zt(n)}function Qt(n,e,t){if(e<0||n.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(n.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');let r;return e===void 0&&t===void 0?r=new Uint8Array(n):t===void 0?r=new Uint8Array(n,e):r=new Uint8Array(n,e,t),Object.setPrototypeOf(r,h.prototype),r}function Yr(n){if(h.isBuffer(n)){let e=nn(n.length)|0,t=Se(e);return t.length===0||n.copy(t,0,0,e),t}if(n.length!==void 0)return typeof n.length!="number"||sn(n.length)?Se(0):Zt(n);if(n.type==="Buffer"&&Array.isArray(n.data))return Zt(n.data)}function nn(n){if(n>=pt)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+pt.toString(16)+" bytes");return n|0}function Jr(n){return+n!=n&&(n=0),h.alloc(+n)}h.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==h.prototype};h.compare=function(e,t){if(Be(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),Be(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(e)||!h.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,s=t.length;for(let i=0,o=Math.min(r,s);i<o;++i)if(e[i]!==t[i]){r=e[i],s=t[i];break}return r<s?-1:s<r?1:0};h.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};h.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return h.alloc(0);let r;if(t===void 0)for(t=0,r=0;r<e.length;++r)t+=e[r].length;let s=h.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){let o=e[r];if(Be(o,Uint8Array))i+o.length>s.length?(h.isBuffer(o)||(o=h.from(o)),o.copy(s,i)):Uint8Array.prototype.set.call(s,o,i);else if(h.isBuffer(o))o.copy(s,i);else throw new TypeError('"list" argument must be an Array of Buffers');i+=o.length}return s};function Gn(n,e){if(h.isBuffer(n))return n.length;if(ArrayBuffer.isView(n)||Be(n,ArrayBuffer))return n.byteLength;if(typeof n!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof n);let t=n.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&t===0)return 0;let s=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return en(n).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return Jn(n).length;default:if(s)return r?-1:en(n).length;e=(""+e).toLowerCase(),s=!0}}h.byteLength=Gn;function Zr(n,e,t){let r=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(n||(n="utf8");;)switch(n){case"hex":return cs(this,e,t);case"utf8":case"utf-8":return Hn(this,e,t);case"ascii":return os(this,e,t);case"latin1":case"binary":return as(this,e,t);case"base64":return ss(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ls(this,e,t);default:if(r)throw new TypeError("Unknown encoding: "+n);n=(n+"").toLowerCase(),r=!0}}h.prototype._isBuffer=!0;function He(n,e,t){let r=n[e];n[e]=n[t],n[t]=r}h.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)He(this,t,t+1);return this};h.prototype.swap32=function(){let e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)He(this,t,t+3),He(this,t+1,t+2);return this};h.prototype.swap64=function(){let e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)He(this,t,t+7),He(this,t+1,t+6),He(this,t+2,t+5),He(this,t+3,t+4);return this};h.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?Hn(this,0,e):Zr.apply(this,arguments)};h.prototype.toLocaleString=h.prototype.toString;h.prototype.equals=function(e){if(!h.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:h.compare(this,e)===0};h.prototype.inspect=function(){let e="",t=et.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"};Mn&&(h.prototype[Mn]=h.prototype.inspect);h.prototype.compare=function(e,t,r,s,i){if(Be(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),!h.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),r===void 0&&(r=e?e.length:0),s===void 0&&(s=0),i===void 0&&(i=this.length),t<0||r>e.length||s<0||i>this.length)throw new RangeError("out of range index");if(s>=i&&t>=r)return 0;if(s>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,s>>>=0,i>>>=0,this===e)return 0;let o=i-s,d=r-t,c=Math.min(o,d),l=this.slice(s,i),a=e.slice(t,r);for(let u=0;u<c;++u)if(l[u]!==a[u]){o=l[u],d=a[u];break}return o<d?-1:d<o?1:0};function qn(n,e,t,r,s){if(n.length===0)return-1;if(typeof t=="string"?(r=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,sn(t)&&(t=s?0:n.length-1),t<0&&(t=n.length+t),t>=n.length){if(s)return-1;t=n.length-1}else if(t<0)if(s)t=0;else return-1;if(typeof e=="string"&&(e=h.from(e,r)),h.isBuffer(e))return e.length===0?-1:Rn(n,e,t,r,s);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?s?Uint8Array.prototype.indexOf.call(n,e,t):Uint8Array.prototype.lastIndexOf.call(n,e,t):Rn(n,[e],t,r,s);throw new TypeError("val must be string, number or Buffer")}function Rn(n,e,t,r,s){let i=1,o=n.length,d=e.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(n.length<2||e.length<2)return-1;i=2,o/=2,d/=2,t/=2}function c(a,u){return i===1?a[u]:a.readUInt16BE(u*i)}let l;if(s){let a=-1;for(l=t;l<o;l++)if(c(n,l)===c(e,a===-1?0:l-a)){if(a===-1&&(a=l),l-a+1===d)return a*i}else a!==-1&&(l-=l-a),a=-1}else for(t+d>o&&(t=o-d),l=t;l>=0;l--){let a=!0;for(let u=0;u<d;u++)if(c(n,l+u)!==c(e,u)){a=!1;break}if(a)return l}return-1}h.prototype.includes=function(e,t,r){return this.indexOf(e,t,r)!==-1};h.prototype.indexOf=function(e,t,r){return qn(this,e,t,r,!0)};h.prototype.lastIndexOf=function(e,t,r){return qn(this,e,t,r,!1)};function Qr(n,e,t,r){t=Number(t)||0;let s=n.length-t;r?(r=Number(r),r>s&&(r=s)):r=s;let i=e.length;r>i/2&&(r=i/2);let o;for(o=0;o<r;++o){let d=parseInt(e.substr(o*2,2),16);if(sn(d))return o;n[t+o]=d}return o}function es(n,e,t,r){return ht(en(e,n.length-t),n,t,r)}function ts(n,e,t,r){return ht(ps(e),n,t,r)}function ns(n,e,t,r){return ht(Jn(e),n,t,r)}function rs(n,e,t,r){return ht(hs(e,n.length-t),n,t,r)}h.prototype.write=function(e,t,r,s){if(t===void 0)s="utf8",r=this.length,t=0;else if(r===void 0&&typeof t=="string")s=t,r=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(r)?(r=r>>>0,s===void 0&&(s="utf8")):(s=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let i=this.length-t;if((r===void 0||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");let o=!1;for(;;)switch(s){case"hex":return Qr(this,e,t,r);case"utf8":case"utf-8":return es(this,e,t,r);case"ascii":case"latin1":case"binary":return ts(this,e,t,r);case"base64":return ns(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return rs(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),o=!0}};h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ss(n,e,t){return e===0&&t===n.length?Jt.fromByteArray(n):Jt.fromByteArray(n.slice(e,t))}function Hn(n,e,t){t=Math.min(n.length,t);let r=[],s=e;for(;s<t;){let i=n[s],o=null,d=i>239?4:i>223?3:i>191?2:1;if(s+d<=t){let c,l,a,u;switch(d){case 1:i<128&&(o=i);break;case 2:c=n[s+1],(c&192)===128&&(u=(i&31)<<6|c&63,u>127&&(o=u));break;case 3:c=n[s+1],l=n[s+2],(c&192)===128&&(l&192)===128&&(u=(i&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:c=n[s+1],l=n[s+2],a=n[s+3],(c&192)===128&&(l&192)===128&&(a&192)===128&&(u=(i&15)<<18|(c&63)<<12|(l&63)<<6|a&63,u>65535&&u<1114112&&(o=u))}}o===null?(o=65533,d=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),s+=d}return is(r)}var Un=4096;function is(n){let e=n.length;if(e<=Un)return String.fromCharCode.apply(String,n);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,n.slice(r,r+=Un));return t}function os(n,e,t){let r="";t=Math.min(n.length,t);for(let s=e;s<t;++s)r+=String.fromCharCode(n[s]&127);return r}function as(n,e,t){let r="";t=Math.min(n.length,t);for(let s=e;s<t;++s)r+=String.fromCharCode(n[s]);return r}function cs(n,e,t){let r=n.length;(!e||e<0)&&(e=0),(!t||t<0||t>r)&&(t=r);let s="";for(let i=e;i<t;++i)s+=ms[n[i]];return s}function ls(n,e,t){let r=n.slice(e,t),s="";for(let i=0;i<r.length-1;i+=2)s+=String.fromCharCode(r[i]+r[i+1]*256);return s}h.prototype.slice=function(e,t){let r=this.length;e=~~e,t=t===void 0?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t<e&&(t=e);let s=this.subarray(e,t);return Object.setPrototypeOf(s,h.prototype),s};function J(n,e,t){if(n%1!==0||n<0)throw new RangeError("offset is not uint");if(n+e>t)throw new RangeError("Trying to access beyond buffer length")}h.prototype.readUintLE=h.prototype.readUIntLE=function(e,t,r){e=e>>>0,t=t>>>0,r||J(e,t,this.length);let s=this[e],i=1,o=0;for(;++o<t&&(i*=256);)s+=this[e+o]*i;return s};h.prototype.readUintBE=h.prototype.readUIntBE=function(e,t,r){e=e>>>0,t=t>>>0,r||J(e,t,this.length);let s=this[e+--t],i=1;for(;t>0&&(i*=256);)s+=this[e+--t]*i;return s};h.prototype.readUint8=h.prototype.readUInt8=function(e,t){return e=e>>>0,t||J(e,1,this.length),this[e]};h.prototype.readUint16LE=h.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||J(e,2,this.length),this[e]|this[e+1]<<8};h.prototype.readUint16BE=h.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||J(e,2,this.length),this[e]<<8|this[e+1]};h.prototype.readUint32LE=h.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||J(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};h.prototype.readUint32BE=h.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||J(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};h.prototype.readBigUInt64LE=Le(function(e){e=e>>>0,Qe(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&at(e,this.length-8);let s=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+r*2**24;return BigInt(s)+(BigInt(i)<<BigInt(32))});h.prototype.readBigUInt64BE=Le(function(e){e=e>>>0,Qe(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&at(e,this.length-8);let s=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r;return(BigInt(s)<<BigInt(32))+BigInt(i)});h.prototype.readIntLE=function(e,t,r){e=e>>>0,t=t>>>0,r||J(e,t,this.length);let s=this[e],i=1,o=0;for(;++o<t&&(i*=256);)s+=this[e+o]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s};h.prototype.readIntBE=function(e,t,r){e=e>>>0,t=t>>>0,r||J(e,t,this.length);let s=t,i=1,o=this[e+--s];for(;s>0&&(i*=256);)o+=this[e+--s]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o};h.prototype.readInt8=function(e,t){return e=e>>>0,t||J(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};h.prototype.readInt16LE=function(e,t){e=e>>>0,t||J(e,2,this.length);let r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};h.prototype.readInt16BE=function(e,t){e=e>>>0,t||J(e,2,this.length);let r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};h.prototype.readInt32LE=function(e,t){return e=e>>>0,t||J(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};h.prototype.readInt32BE=function(e,t){return e=e>>>0,t||J(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};h.prototype.readBigInt64LE=Le(function(e){e=e>>>0,Qe(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&at(e,this.length-8);let s=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(r<<24);return(BigInt(s)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)});h.prototype.readBigInt64BE=Le(function(e){e=e>>>0,Qe(e,"offset");let t=this[e],r=this[e+7];(t===void 0||r===void 0)&&at(e,this.length-8);let s=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(s)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r)});h.prototype.readFloatLE=function(e,t){return e=e>>>0,t||J(e,4,this.length),Ze.read(this,e,!0,23,4)};h.prototype.readFloatBE=function(e,t){return e=e>>>0,t||J(e,4,this.length),Ze.read(this,e,!1,23,4)};h.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||J(e,8,this.length),Ze.read(this,e,!0,52,8)};h.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||J(e,8,this.length),Ze.read(this,e,!1,52,8)};function ce(n,e,t,r,s,i){if(!h.isBuffer(n))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>s||e<i)throw new RangeError('"value" argument is out of bounds');if(t+r>n.length)throw new RangeError("Index out of range")}h.prototype.writeUintLE=h.prototype.writeUIntLE=function(e,t,r,s){if(e=+e,t=t>>>0,r=r>>>0,!s){let d=Math.pow(2,8*r)-1;ce(this,e,t,r,d,0)}let i=1,o=0;for(this[t]=e&255;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r};h.prototype.writeUintBE=h.prototype.writeUIntBE=function(e,t,r,s){if(e=+e,t=t>>>0,r=r>>>0,!s){let d=Math.pow(2,8*r)-1;ce(this,e,t,r,d,0)}let i=r-1,o=1;for(this[t+i]=e&255;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r};h.prototype.writeUint8=h.prototype.writeUInt8=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,1,255,0),this[t]=e&255,t+1};h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function zn(n,e,t,r,s){Yn(e,r,s,n,t,7);let i=Number(e&BigInt(4294967295));n[t++]=i,i=i>>8,n[t++]=i,i=i>>8,n[t++]=i,i=i>>8,n[t++]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return n[t++]=o,o=o>>8,n[t++]=o,o=o>>8,n[t++]=o,o=o>>8,n[t++]=o,t}function Vn(n,e,t,r,s){Yn(e,r,s,n,t,7);let i=Number(e&BigInt(4294967295));n[t+7]=i,i=i>>8,n[t+6]=i,i=i>>8,n[t+5]=i,i=i>>8,n[t+4]=i;let o=Number(e>>BigInt(32)&BigInt(4294967295));return n[t+3]=o,o=o>>8,n[t+2]=o,o=o>>8,n[t+1]=o,o=o>>8,n[t]=o,t+8}h.prototype.writeBigUInt64LE=Le(function(e,t=0){return zn(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});h.prototype.writeBigUInt64BE=Le(function(e,t=0){return Vn(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))});h.prototype.writeIntLE=function(e,t,r,s){if(e=+e,t=t>>>0,!s){let c=Math.pow(2,8*r-1);ce(this,e,t,r,c-1,-c)}let i=0,o=1,d=0;for(this[t]=e&255;++i<r&&(o*=256);)e<0&&d===0&&this[t+i-1]!==0&&(d=1),this[t+i]=(e/o>>0)-d&255;return t+r};h.prototype.writeIntBE=function(e,t,r,s){if(e=+e,t=t>>>0,!s){let c=Math.pow(2,8*r-1);ce(this,e,t,r,c-1,-c)}let i=r-1,o=1,d=0;for(this[t+i]=e&255;--i>=0&&(o*=256);)e<0&&d===0&&this[t+i+1]!==0&&(d=1),this[t+i]=(e/o>>0)-d&255;return t+r};h.prototype.writeInt8=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};h.prototype.writeInt16LE=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeInt16BE=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeInt32LE=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};h.prototype.writeInt32BE=function(e,t,r){return e=+e,t=t>>>0,r||ce(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};h.prototype.writeBigInt64LE=Le(function(e,t=0){return zn(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});h.prototype.writeBigInt64BE=Le(function(e,t=0){return Vn(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Wn(n,e,t,r,s,i){if(t+r>n.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function Kn(n,e,t,r,s){return e=+e,t=t>>>0,s||Wn(n,e,t,4,34028234663852886e22,-34028234663852886e22),Ze.write(n,e,t,r,23,4),t+4}h.prototype.writeFloatLE=function(e,t,r){return Kn(this,e,t,!0,r)};h.prototype.writeFloatBE=function(e,t,r){return Kn(this,e,t,!1,r)};function Xn(n,e,t,r,s){return e=+e,t=t>>>0,s||Wn(n,e,t,8,17976931348623157e292,-17976931348623157e292),Ze.write(n,e,t,r,52,8),t+8}h.prototype.writeDoubleLE=function(e,t,r){return Xn(this,e,t,!0,r)};h.prototype.writeDoubleBE=function(e,t,r){return Xn(this,e,t,!1,r)};h.prototype.copy=function(e,t,r,s){if(!h.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),!s&&s!==0&&(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s<r&&(s=r),s===r||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t<s-r&&(s=e.length-t+r);let i=s-r;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,r,s):Uint8Array.prototype.set.call(e,this.subarray(r,s),t),i};h.prototype.fill=function(e,t,r,s){if(typeof e=="string"){if(typeof t=="string"?(s=t,t=0,r=this.length):typeof r=="string"&&(s=r,r=this.length),s!==void 0&&typeof s!="string")throw new TypeError("encoding must be a string");if(typeof s=="string"&&!h.isEncoding(s))throw new TypeError("Unknown encoding: "+s);if(e.length===1){let o=e.charCodeAt(0);(s==="utf8"&&o<128||s==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;t=t>>>0,r=r===void 0?this.length:r>>>0,e||(e=0);let i;if(typeof e=="number")for(i=t;i<r;++i)this[i]=e;else{let o=h.isBuffer(e)?e:h.from(e,s),d=o.length;if(d===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%d]}return this};var Je={};function rn(n,e,t){Je[n]=class extends t{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${n}]`,this.stack,delete this.name}get code(){return n}set code(s){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:s,writable:!0})}toString(){return`${this.name} [${n}]: ${this.message}`}}}rn("ERR_BUFFER_OUT_OF_BOUNDS",function(n){return n?`${n} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);rn("ERR_INVALID_ARG_TYPE",function(n,e){return`The "${n}" argument must be of type number. Received type ${typeof e}`},TypeError);rn("ERR_OUT_OF_RANGE",function(n,e,t){let r=`The value of "${n}" is out of range.`,s=t;return Number.isInteger(t)&&Math.abs(t)>2**32?s=Pn(String(t)):typeof t=="bigint"&&(s=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(s=Pn(s)),s+="n"),r+=` It must be ${e}. Received ${s}`,r},RangeError);function Pn(n){let e="",t=n.length,r=n[0]==="-"?1:0;for(;t>=r+4;t-=3)e=`_${n.slice(t-3,t)}${e}`;return`${n.slice(0,t)}${e}`}function ds(n,e,t){Qe(e,"offset"),(n[e]===void 0||n[e+t]===void 0)&&at(e,n.length-(t+1))}function Yn(n,e,t,r,s,i){if(n>t||n<e){let o=typeof e=="bigint"?"n":"",d;throw i>3?e===0||e===BigInt(0)?d=`>= 0${o} and < 2${o} ** ${(i+1)*8}${o}`:d=`>= -(2${o} ** ${(i+1)*8-1}${o}) and < 2 ** ${(i+1)*8-1}${o}`:d=`>= ${e}${o} and <= ${t}${o}`,new Je.ERR_OUT_OF_RANGE("value",d,n)}ds(r,s,i)}function Qe(n,e){if(typeof n!="number")throw new Je.ERR_INVALID_ARG_TYPE(e,"number",n)}function at(n,e,t){throw Math.floor(n)!==n?(Qe(n,t),new Je.ERR_OUT_OF_RANGE(t||"offset","an integer",n)):e<0?new Je.ERR_BUFFER_OUT_OF_BOUNDS:new Je.ERR_OUT_OF_RANGE(t||"offset",`>= ${t?1:0} and <= ${e}`,n)}var us=/[^+/0-9A-Za-z-_]/g;function fs(n){if(n=n.split("=")[0],n=n.trim().replace(us,""),n.length<2)return"";for(;n.length%4!==0;)n=n+"=";return n}function en(n,e){e=e||1/0;let t,r=n.length,s=null,i=[];for(let o=0;o<r;++o){if(t=n.charCodeAt(o),t>55295&&t<57344){if(!s){if(t>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(o+1===r){(e-=3)>-1&&i.push(239,191,189);continue}s=t;continue}if(t<56320){(e-=3)>-1&&i.push(239,191,189),s=t;continue}t=(s-55296<<10|t-56320)+65536}else s&&(e-=3)>-1&&i.push(239,191,189);if(s=null,t<128){if((e-=1)<0)break;i.push(t)}else if(t<2048){if((e-=2)<0)break;i.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;i.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;i.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return i}function ps(n){let e=[];for(let t=0;t<n.length;++t)e.push(n.charCodeAt(t)&255);return e}function hs(n,e){let t,r,s,i=[];for(let o=0;o<n.length&&!((e-=2)<0);++o)t=n.charCodeAt(o),r=t>>8,s=t%256,i.push(s),i.push(r);return i}function Jn(n){return Jt.toByteArray(fs(n))}function ht(n,e,t,r){let s;for(s=0;s<r&&!(s+t>=e.length||s>=n.length);++s)e[s+t]=n[s];return s}function Be(n,e){return n instanceof e||n!=null&&n.constructor!=null&&n.constructor.name!=null&&n.constructor.name===e.name}function sn(n){return n!==n}var ms=(function(){let n="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let r=t*16;for(let s=0;s<16;++s)e[r+s]=n[t]+n[s]}return e})();function Le(n){return typeof BigInt>"u"?gs:n}function gs(){throw new Error("BigInt not supported")}});function Ar({worker:n,runner:e,dsc:t,wasm:r,file:s="rules.ds",libraries:i={}}){let o=new Worker(n,{type:"module"}),d=new Map,c=1,l=null;o.onmessage=({data:m})=>{let w=d.get(m.id);w&&(d.delete(m.id),m.ok?w.resolve(m.value):w.reject(new Error(m.error)))},o.onerror=m=>{l=new Error(`the compiler worker failed: ${m.message||m}`);for(let w of d.values())w.reject(l);d.clear()};let a=(m,...w)=>l?Promise.reject(l):new Promise((g,_)=>{let A=c++;d.set(A,{resolve:g,reject:_}),o.postMessage({id:A,op:m,args:w})}),u=a("init",{runner:e,dsc:t,wasm:r,file:s,libraries:i});return{ready:u,diagnose:m=>u.then(()=>a("diagnose",m)),compile:m=>u.then(()=>a("compile",m)),terminate:()=>o.terminate()}}function Tt(n,e){let t=(n.diagnostics||[]).map(r=>{let s=r.span||{},i=!s.file||s.file===e;return{start:i&&s.start||null,end:i&&(s.end||s.start)||null,severity:r.severity==="warning"?"warning":"error",message:(r.hint?`${r.message}
2
+
3
+ hint: ${r.hint}`:r.message)+(i?"":` (in ${s.file})`),code:r.code||null}});return n.failure&&t.push({start:null,end:null,severity:"error",message:`the compiler failed to analyse this file: ${n.failure}`,code:null}),t}var Nr=0,Cr=(()=>{let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")})();function Dt(n,{uri:e,editor:t="ds-editor"}={}){let r={uri:e||`untitled:${t}/${Cr}/${++Nr}.ds`,opened:!1,text:null,version:0,sent:-1,generation:null},s=Promise.resolve(),i=(c,l)=>{let a=s.then(()=>o(c,l));return s=a.catch(()=>null),a};async function o(c,l){c!==r.text&&(r.text=c,r.version++);let a=r.version,u=[];if(r.opened?r.sent!==a&&u.push({method:"textDocument/didChange",params:{textDocument:{uri:r.uri,version:a},contentChanges:[{text:c}]}}):u.push({method:"textDocument/didOpen",params:{textDocument:{uri:r.uri,languageId:"ds",version:a,text:c}}}),l?u.push(l):u.length&&u.push({method:"textDocument/didSave",params:{textDocument:{uri:r.uri}}}),!u.length)return null;let m=null;try{m=await n(u)}catch{m=null}return!m||!Array.isArray(m.results)||r.opened&&m.generation!==r.generation?(r.opened=!1,null):(r.opened=!0,r.sent=a,r.generation=m.generation,l&&m.results[m.results.length-1]||null)}let d=(c,l,a)=>i(c,{method:l,params:{textDocument:{uri:r.uri},...a},request:!0});return{uri:r.uri,get opened(){return r.opened},ask:(c,l,a)=>d(c,l,a).then(u=>u&&u.result!==void 0?u.result:null),request:d,sync:c=>i(c,null),close(){let c=s.then(()=>r.opened?(r.opened=!1,n([{method:"textDocument/didClose",params:{textDocument:{uri:r.uri}}}]).catch(()=>null)):null);return s=c.catch(()=>null),c}}}function _r({worker:n,dsc:e,wasm:t,libraries:r={},timeoutMs:s=3e4,Worker:i=globalThis.Worker}){let o=null,d=null,c=0,l=1,a=new Map;function u(A){for(let V of a.values())clearTimeout(V.timer),V.reject(new Error(A));a.clear(),o&&o.terminate(),o=null,d=null}let m=A=>o.postMessage(JSON.stringify({jsonrpc:"2.0",...A}));function w(A,V){return new Promise((S,R)=>{let T=l++,U=setTimeout(()=>{a.delete(T),R(new Error(`ds lsp did not answer ${A} within ${s} ms`))},s);a.set(T,{resolve:S,reject:R,timer:U}),m({id:T,method:A,params:V})})}function g(){c++;let A=new i(n,{type:"module"});return o=A,new Promise((S,R)=>{A.onmessage=({data:T})=>{let U;try{U=typeof T=="string"?JSON.parse(T):T}catch{return}if(!U||typeof U!="object")return;if(U["ds-editor-core/ready"]){S();return}if(U["ds-editor-core/failed"]){R(new Error(`ds lsp did not start: ${U["ds-editor-core/failed"]}`));return}let W=U.id!==void 0&&U.method===void 0?a.get(U.id):void 0;W&&(a.delete(U.id),clearTimeout(W.timer),W.resolve(U))},A.onerror=T=>{let U=`the lsp worker failed: ${T&&T.message||T}`;o===A&&u(U),R(new Error(U))},A.postMessage({op:"ds-editor-core/init",dsc:String(e),wasm:String(t),libraries:r})}).then(()=>w("initialize",{processId:null,rootUri:null,capabilities:{}})).then(S=>{if(S.error)throw new Error(`ds lsp refused initialize: ${S.error.message}`);m({method:"initialized",params:{}})}).catch(S=>{throw o===A&&u(S.message),S})}async function _(A){if(!d){let S=g();d=S,S.catch(()=>{d===S&&(d=null)})}await d;let V=[];for(let S of A){if(!S.request){m({method:S.method,params:S.params});continue}let R=await w(S.method,S.params);V.push(R.error?{error:R.error.message}:{result:R.result===void 0?null:R.result})}return{generation:c,results:V}}return{exchange:_,lsp:A=>_(A).catch(()=>null),stop(){o&&u("stopped")}}}var In="ds-editor-core/catchUp";function Sr(n,{generation:e=null}={}){let t={generation:e,ended:null,stopped:null,threads:new Set,breakpoints:new Map,output:[],terminated:!1},r=new Set,s=(l,a)=>{for(let u of r)try{u(l,a)}catch{}},i=l=>{let a=l.body||{};switch(l.event){case"stopped":t.stopped=a;break;case"thread":a.reason==="started"?t.threads.add(a.threadId):a.reason==="exited"&&t.threads.delete(a.threadId);break;case"breakpoint":a.breakpoint&&a.breakpoint.id!==void 0&&(a.reason==="removed"?t.breakpoints.delete(a.breakpoint.id):t.breakpoints.set(a.breakpoint.id,a.breakpoint));break;case"output":t.output.push({category:a.category||"console",output:String(a.output||"")}),t.output.length>500&&t.output.splice(0,t.output.length-500);break;case"terminated":t.terminated=!0,t.ended="the session ended";break;default:break}s("event",l)},o=Promise.resolve();async function d(l,a){if(t.ended)return{success:!1,message:t.ended};let u=null;try{u=await n(a===void 0?{command:l}:{command:l,arguments:a})}catch{u=null}if(!u||!u.response)return{success:!1,message:"the host did not answer"};if(t.generation===null)t.generation=u.generation;else if(u.generation!==t.generation)return t.ended="ds dap started again: this session has ended",s("answer",{command:l,response:{success:!1,message:t.ended}}),{success:!1,message:t.ended};for(let w of u.events||[])i(w);if(/^(setBreakpoints|setFunctionBreakpoints|ds\/setFactBreakpoints|ds\/setCacheBreakpoints)$/.test(l)&&u.response.success&&u.response.body&&Array.isArray(u.response.body.breakpoints)){for(let[w,g]of t.breakpoints)g.kind===l&&t.breakpoints.delete(w);for(let w of u.response.body.breakpoints)w&&w.id!==void 0&&t.breakpoints.set(w.id,{...w,kind:l})}return l==="disconnect"&&u.response.success&&(t.ended="the session was closed"),s("answer",{command:l,response:u.response}),u.response}let c=(l,a)=>{let u=o.then(()=>d(l,a));return o=u.catch(()=>null),u};return{request:c,get state(){return t},listen(l){return r.add(l),()=>r.delete(l)},setLineBreakpoints:l=>c("setBreakpoints",{source:{path:"rules.ds"},breakpoints:l}).then(a=>a.success&&a.body?a.body.breakpoints:[]),async stepInTargets(){let l=t.stopped;if(!l||t.ended||l.threadId===void 0)return[];let a=await c("stackTrace",{threadId:l.threadId,levels:1}),u=a.success&&a.body.stackFrames.length?a.body.stackFrames[0]:null;if(!u)return[];let m=await c("stepInTargets",{frameId:u.id});return m.success&&m.body?m.body.targets:[]},stepInto:l=>c("stepIn",{threadId:t.stopped?t.stopped.threadId:1,targetId:l}),catchUp:()=>c(In),close:()=>c("disconnect")}}var Bn=Object.freeze(["textDocument/didOpen","textDocument/didChange","textDocument/didSave","textDocument/didClose","textDocument/completion","textDocument/hover","textDocument/signatureHelp","textDocument/definition","textDocument/documentSymbol","textDocument/semanticTokens/full","textDocument/references","textDocument/rename"]);var st=Object.freeze({tokenTypes:Object.freeze(["namespace","type","struct","interface","function","variable","property","keyword","operator","string","number","comment"]),tokenModifiers:Object.freeze(["declaration","readonly","defaultLibrary","action","clause","constant"])});function Fr(n,e=st){let t=n&&n.data||[],r=[],s=0,i=0;for(let o=0;o+4<t.length;o+=5){let[d,c,l,a,u]=t.slice(o,o+5);s+=d,i=d===0?i+c:c;let m=e.tokenModifiers.filter((w,g)=>u&1<<g);r.push({line:s,character:i,length:l,type:e.tokenTypes[a]||"unknown",modifiers:m})}return r}function Lt(n,e){let t=Array.isArray(n)?n:[],r=s=>({name:s.name,detail:s.detail||"",kind:s.kind,range:s.range,selectionRange:s.selectionRange||s.range,children:(s.children||[]).map(r)});return t.filter(s=>s&&(s.range||s.location&&s.location.uri===e)).map(s=>s.range?r(s):{name:s.name,detail:s.containerName||"",kind:s.kind,range:s.location.range,selectionRange:s.location.range,children:[]})}function Mt(n,e){return(Array.isArray(n)?n:n?[n]:[]).map(r=>r&&r.targetUri?{uri:r.targetUri,range:r.targetSelectionRange||r.targetRange}:r).filter(r=>r&&r.uri===e&&r.range).map(r=>r.range)}function Rt(n,e){if(!n)return{error:"nothing to rename here"};let t=new Map;for(let[s,i]of Object.entries(n.changes||{}))t.set(s,[...t.get(s)||[],...i]);for(let s of n.documentChanges||[]){if(!s||!s.textDocument)return{error:"the rename creates, renames or deletes a file"};let i=s.textDocument.uri;t.set(i,[...t.get(i)||[],...s.edits||[]])}let r=[...t.keys()].filter(s=>s!==e&&t.get(s).length);return r.length?{error:`the rename also edits ${r.join(", ")}, outside this document`}:{edits:t.get(e)||[]}}var lt=new Set(["clock","assert","retract","external","pump"]),An=n=>n instanceof Uint8Array?[...n].map(e=>e.toString(16).padStart(2,"0")).join(""):"",Nn=n=>n&&typeof n=="object"?n.name||n.number:n;function Tr(n){for(let[e,t]of Object.entries(n||{}))if(e.endsWith("_value"))return t;return null}function Ut(n,e){let t=n.readAtoms(e,{incremental:!0}),r=new Map,s=null,i=[],o=(d,c)=>{let l=r.get(d);if(!l)return{slots:null,problem:`schema ${d} was not announced`};try{let{slots:a,refs:u}=n.decodeAnnouncedFactBodyHandles(l,c);for(let[m,w]of Object.entries(u||{}))a[m]=w===null?null:{factId:w};return{slots:a}}catch(a){return{slots:null,problem:String(a&&a.message||a)}}};for(let d of t.atoms){let c=d.body||{},l={seq:c.seq??null,clockNs:c.clock_ns??null,offset:d.offset};switch(d.message){case"StreamHeader":s={dsVersion:c.ds_version||null,dscHash:An(c.dsc_hash),dialectHash:An(c.dialect_def_sha256),sessionId:c.session_id||null,tierId:c.tier_id||null,capabilities:(c.capabilities||[]).map(Nn)};break;case"SchemaDef":r.set(c.schema_name,[]);break;case"Slot":r.has(c.schema_name)&&r.get(c.schema_name).push({name:c.slot_name,kind:c.kind&&typeof c.kind=="object"?c.kind.number:c.kind,nullable:!!c.nullable,schemaRef:c.schema_ref||null});break;case"ClockAdvance":i.push({kind:"clock",...l,wallNs:c.has_wall?c.wall_ns:null});break;case"FactAssert":case"FactEmit":i.push({kind:d.message==="FactAssert"?"assert":"emit",...l,factId:c.fact_id,schema:c.schema_name,...o(c.schema_name,c.fact),rule:c.rule_name||null,ttlNs:c.ttl_ns??null});break;case"FactRetract":i.push({kind:"retract",...l,factId:c.fact_id});break;case"FactWithdraw":i.push({kind:"withdraw",...l,factId:c.fact_id,cause:Nn(c.cause)});break;case"RuleFireAnnotation":i.push({kind:c.end?"fire-end":"fire",...l,rule:c.rule_name,timetag:c.timetag});break;case"CallIssued":i.push({kind:"call",...l,service:c.service,correlation:c.correlation,rule:c.rule_name,timetag:c.timetag,args:Object.fromEntries((c.args||[]).map(a=>[a.name,Tr(a)]))});break;case"FactPublish":i.push({kind:"publish",...l,schema:c.schema_name,rule:c.rule_name,timetag:c.timetag});break;case"PumpBoundary":i.push({kind:"pump",...l});break;case"ExternalAssert":i.push({kind:"external",...l,factIds:c.fact_ids||[],body:{offset:d.bodyOffset,length:d.bodyLength}});break;case"ComputationError":case"TypeError":case"BoundsError":case"EngineError":i.push({kind:"fault",...l,fault:d.message,rule:c.rule_name||null,detail:c});break;default:i.push({kind:"other",...l,message:d.message,field:d.field})}}return{header:s,schemas:r,events:i,end:t.end,error:t.error,incomplete:t.incomplete}}function Xe(n,e){let{events:t}=n;for(let r=Math.max(0,e);r<t.length;r++)if(lt.has(t[r].kind))return{events:r,bytes:t[r].offset};if(!n.incomplete&&!n.error)return{events:t.length,bytes:n.end};for(let r=t.length-1;r>=0;r--)if(lt.has(t[r].kind))return{events:r,bytes:t[r].offset};return{events:0,bytes:t.length?t[0].offset:n.end}}function Pt(n,e=n.events.length){let t=new Map;for(let r of n.events.slice(0,e))if(r.kind==="assert"||r.kind==="emit")t.set(r.factId,{schema:r.schema,slots:r.slots,since:r.seq,rule:r.rule});else if(r.kind==="external")for(let s of r.factIds)t.set(s,{schema:null,slots:null,since:r.seq,rule:null});else(r.kind==="retract"||r.kind==="withdraw")&&t.delete(r.factId);return t}function Ot(n,e,t){let[r,s]=e<=t?[e,t]:[t,e],i=new Map,o=[],d=[];return n.events.slice(0,s).forEach((c,l)=>{let a=l>=r;if(c.kind==="assert"||c.kind==="emit")i.set(c.factId,{schema:c.schema,slots:c.slots}),a&&o.push({index:l,factId:c.factId,schema:c.schema,slots:c.slots,clockNs:c.clockNs,rule:c.rule});else if(c.kind==="external")for(let u of c.factIds)i.set(u,{schema:null,slots:null}),a&&o.push({index:l,factId:u,schema:null,slots:null,clockNs:c.clockNs,rule:null});else if((c.kind==="retract"||c.kind==="withdraw")&&a){let u=i.get(c.factId)||{schema:null,slots:null};d.push({index:l,factId:c.factId,schema:u.schema,slots:u.slots,clockNs:c.clockNs,rule:null})}}),{from:r,to:s,asserted:o,retracted:d}}function dt(n){let e=[],t=null;return n.events.forEach((r,s)=>{if(lt.has(r.kind)&&t&&(t.end=s,t=null),r.kind==="pump"){t={index:s,end:n.events.length,seq:r.seq,clockNs:r.clockNs,fires:[],calls:[],emits:[],withdrawals:[],publishes:[],faults:[]},e.push(t);return}lt.has(r.kind)||t&&(r.kind==="fire"?t.fires.push(r.rule):r.kind==="call"?t.calls.push(r):r.kind==="emit"?t.emits.push(r):r.kind==="withdraw"?t.withdrawals.push(r):r.kind==="publish"?t.publishes.push(r):r.kind==="fault"&&t.faults.push(r))}),e}function jt(n,e,t,r,s){let i=Xe(r,s),o=new n.Engine;try{o.clock.mode="mock",o.loadDsc(e);let d=o.replayStream(t.subarray(0,i.bytes));return{engine:o,cut:i,counts:d}}catch(d){throw o.close(),d}}function ut(n,e=""){let t=n.reteNetwork({ruleFilter:e||null,includeOccupancy:!0});return{nodes:t.nodes.map(r=>({id:r.id,kind:r.kind,label:r.label,filter:r.filter,occupancy:r.occupancy,negative:r.isNegative})),edges:t.edges.map(r=>({from:r.fromId,to:r.toId}))}}function Gt(n){return[...n.facts()].map(e=>e.read()).sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0).map(e=>({id:e.id,schema:e.schema,slots:e.slots}))}function qt(n,e=""){return n.refractedActivations(e||null).map(t=>({rule:t.ruleName,reason:t.reason,detail:t.detail,factIds:t.factIds}))}function Ht(n,e){return{match:n.reteMatchTrace(e).map(t=>({node:t.nodeId,kind:t.nodeKind,result:t.result,detail:t.detail})),justifiers:n.justifiers(e).map(t=>({timetag:t.timetag,rule:t.ruleName}))}}var it=class{constructor(e,t,r,s){this.api=e,this.dsc=t,this.bytes=r,this.recording=s,this.current=null}at(e){let t=Xe(this.recording,e);if(this.current&&this.current.cut.events===t.events)return this.current;this.close();let{engine:r}=jt(this.api,this.dsc,this.bytes,this.recording,e);return this.current={engine:r,cut:t},this.current}close(){this.current&&(this.current.engine.close(),this.current=null)}};function Dr(n,e,t,r,s,{ruleFilter:i=""}={}){let{engine:o,cut:d}=jt(n,e,t,r,s);try{return{cut:d,network:ut(o,i),factCount:Number(o.factCount)}}finally{o.close()}}function zt(n,e,t,r){let s=[],i=new Map,o=null,d=0,c=new n.Engine;try{c.clock.mode="mock",c.loadDsc(e);for(let[a,u]of c.schemas)i.set(a,BigInt(u.ttlNs??0n));c.setCallCallback(()=>{}),c.addEventListener("timer_armed",a=>{s.push({at:d,rule:a.ruleName,kind:a.timerKind,windowNs:a.windowNs,fireAtNs:a.fireAtNs})});let l=new Map;for(;d<r.events.length;d++){let a=r.events[d];switch(a.kind){case"clock":a.clockNs!==null&&BigInt(a.clockNs)>c.clock.now&&c.clock.set(BigInt(a.clockNs)),a.wallNs!==null&&a.wallNs!==void 0&&c.clock.setWall(BigInt(a.wallNs));break;case"assert":if(!a.slots)throw new Error(a.problem||"an assert whose slots were not decoded");l.set(a.factId,c.assert(a.schema,a.slots).id);break;case"external":{let u=c.applyExternalAssert(t.subarray(a.body.offset,a.body.offset+a.body.length));u.recordedIds.forEach((m,w)=>l.set(m,u.factIds[w]));break}case"retract":{let u=c.factById(l.get(a.factId)??a.factId);u!==null&&c.retract(u);break}case"pump":c.pump();break;default:break}}}catch(l){o={at:d,message:String(l&&l.message||l)}}finally{c.close()}return{timers:s,ttls:i,error:o}}function Vt(n,e,t){let r=null,s=new Map;for(let o of n.events.slice(0,t))o.clockNs!==null&&o.clockNs!==void 0&&(r===null||BigInt(o.clockNs)>r)&&(r=BigInt(o.clockNs)),o.kind==="assert"||o.kind==="emit"?s.set(o.factId,{schema:o.schema,ttlNs:o.ttlNs===null?null:BigInt(o.ttlNs),sinceNs:r}):(o.kind==="retract"||o.kind==="withdraw")&&s.delete(o.factId);let i=[];for(let o of e.timers){let d=BigInt(o.fireAtNs);o.at<t&&(r===null||d>r)&&i.push({kind:o.kind,rule:o.rule,factId:null,schema:null,endsNs:d,remainingNs:r===null?null:d-r})}for(let[o,d]of s){let c=d.ttlNs!==null&&d.ttlNs>0n?d.ttlNs:e.ttls.get(d.schema)??0n;if(c>0n&&d.sinceNs!==null){let l=d.sinceNs+c;i.push({kind:"ttl",rule:null,factId:o,schema:d.schema,endsNs:l,remainingNs:r===null?null:l-r})}}return i.sort((o,d)=>o.endsNs<d.endsNs?-1:o.endsNs>d.endsNs?1:0),{nowNs:r,timers:i}}function Cn(n){return n==null?"null":typeof n=="string"?JSON.stringify(n):typeof n=="bigint"||typeof n=="number"||typeof n=="boolean"?String(n):n instanceof Uint8Array?`<${n.length} bytes>`:typeof n=="object"&&"factId"in n&&Object.keys(n).length===1?`#${n.factId}`:JSON.stringify(n,(e,t)=>typeof t=="bigint"?String(t):t)}function me(n){return Object.entries(n||{}).map(([e,t])=>`${e}: ${Cn(t)}`).join(", ")}function Ce(n,e){let t=n||"fact";return e?`${t}(${me(e)})`:t}function De(n,e=null){if(n==null)return"";let t=e==null?BigInt(n):BigInt(n)-BigInt(e),r=t<0n?"-":e==null?"":"+",i=(t<0n?-t:t)/1000000n;return`${r}${i/1000n}.${String(i%1000n).padStart(3,"0")} s`}function Ye(n){let e=n.events.find(t=>t.clockNs!==null&&t.clockNs!==void 0);return e?e.clockNs:null}var Wt=n=>n?` by ${n}`:"";function ot(n,e=null){switch(n.kind){case"clock":return`clock to ${De(n.clockNs,e)}`;case"assert":return`assert #${n.factId} ${Ce(n.schema,n.slots)}${n.problem?` (${n.problem})`:""}`;case"emit":return`emit #${n.factId} ${Ce(n.schema,n.slots)}${Wt(n.rule)}${n.problem?` (${n.problem})`:""}`;case"retract":return`retract #${n.factId}`;case"withdraw":return`withdraw #${n.factId}${n.cause?`, ${n.cause}`:""}`;case"fire":return`rule ${n.rule} fires`;case"fire-end":return`rule ${n.rule} done`;case"call":return`call ${n.service}(${me(n.args)})${n.correlation?` as ${JSON.stringify(n.correlation)}`:""}${Wt(n.rule)}`;case"publish":return`publish ${n.schema}${Wt(n.rule)}`;case"pump":return"pump";case"external":return`external delivery ${n.factIds.map(t=>`#${t}`).join(", ")}`;case"fault":return`${n.fault}${n.rule?` in ${n.rule}`:""}`;default:return n.message||`atom ${n.field}`}}var Lr="http://www.w3.org/2000/svg";function _e(n,e={},t=null){let r=document.createElementNS(Lr,n);for(let[s,i]of Object.entries(e))r.setAttribute(s,String(i));return t&&t.appendChild(r),r}var Mr=n=>n.length>38?n.slice(0,37)+"\u2026":n;function Kt(n){return n.kind==="beta"?n.negative?"beta (not)":"beta":n.kind}function Sn(n){return n.kind==="beta"&&n.negative?"not":n.label||n.kind}function Rr(n){let e=[Sn(n)];return n.filter&&n.filter!==n.label&&e.push(Mr(n.filter)),n.occupancy!==null&&n.occupancy!==void 0&&e.push(`occupancy ${n.occupancy}`),e}function Ur(n){let e=n.nodes.map((a,u)=>({...a,order:u,preds:[],succs:[]})),t=new Map(e.map(a=>[a.id,a])),r=n.edges.filter(a=>t.has(a.from)&&t.has(a.to));for(let a of r)t.get(a.from).succs.push(a.to),t.get(a.to).preds.push(a.from);let s=new Set,i=a=>a.layer!==void 0?a.layer:s.has(a.id)?0:(s.add(a.id),a.layer=a.preds.length?1+Math.max(...a.preds.map(u=>i(t.get(u)))):0,s.delete(a.id),a.layer);e.forEach(i);let o=[];for(let a of e)(o[a.layer]||=[]).push(a);o.forEach((a,u)=>{if(u>0){let m=w=>w.preds.length?w.preds.reduce((g,_)=>g+t.get(_).slot,0)/w.preds.length:1/0;a.sort((w,g)=>m(w)-m(g)||w.order-g.order)}a.forEach((m,w)=>{m.slot=w})});for(let a of e)a.text=Rr(a),a.w=Math.max(56,Math.max(...a.text.map(u=>u.length))*7.3+20),a.h=a.text.length*16+12;let d=o.map(a=>a.reduce((u,m)=>u+m.w,0)+22*(a.length-1)),c=Math.max(0,...d)+24,l=12;return o.forEach((a,u)=>{let m=12+(c-24-d[u])/2,w=Math.max(...a.map(g=>g.h));for(let g of a)g.x=m,g.y=l+(w-g.h)/2,m+=g.w+22;l+=w+46}),{nodes:e,edges:r,byId:t,width:c,height:l-46+12}}function _n(n,e,t){let r=new Set,s=[e];for(;s.length;)for(let i of n.get(s.pop())[t])r.has(i)||(r.add(i),s.push(i));return r}var Ge=class{constructor(e,t){this.svg=e,this.detail=t,this.picked=null,this.g=null,e.addEventListener("click",r=>{r.target===e&&this.pick(null)})}render(e){let t=this.svg;t.textContent="",this.g=Ur(e||{nodes:[],edges:[]});let{nodes:r,edges:s,byId:i,width:o,height:d}=this.g;if(!r.length){t.setAttribute("width",0),t.setAttribute("height",0),this.pick(null);return}t.setAttribute("width",o),t.setAttribute("height",d),t.setAttribute("viewBox",`0 0 ${o} ${d}`);let c=_e("marker",{id:"pg-net-arrow",viewBox:"0 0 8 8",refX:7,refY:4,markerWidth:7,markerHeight:7,orient:"auto-start-reverse"},_e("defs",{},t));_e("path",{d:"M0,0 L8,4 L0,8 z"},c);let l=_e("g",{},t);this.edgeEls=s.map(a=>{let u=i.get(a.from),m=i.get(a.to),w=u.x+u.w/2,g=u.y+u.h,_=m.x+m.w/2,A=m.y,V=Math.max(46/2,(A-g)/2),S=_e("path",{class:"e","marker-end":"url(#pg-net-arrow)",d:`M${w},${g} C${w},${g+V} ${_},${A-V} ${_},${A}`},l);return{e:a,p:S}}),this.nodeEls=new Map;for(let a of r){let u=["n",a.kind,a.negative?"negative":""].filter(Boolean).join(" "),m=_e("g",{class:u,tabindex:0,role:"button","aria-pressed":"false","aria-label":`${Kt(a)} ${Sn(a)}${a.filter?": "+a.filter:""}`},t);_e("title",{},m).textContent=`${Kt(a)} ${a.id}${a.filter?`
4
+ `+a.filter:""}`,_e("rect",{x:a.x,y:a.y,width:a.w,height:a.h,rx:a.kind==="terminal"?a.h/2:a.kind==="alpha"?6:1},m),a.text.forEach((w,g)=>{let _=_e("text",{x:a.x+a.w/2,y:a.y+6+16*g+12,"text-anchor":"middle",class:g===0?"head":"sub"},m);_.textContent=w}),m.addEventListener("click",()=>this.pick(a.id===this.picked?null:a.id)),m.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),this.pick(a.id===this.picked?null:a.id))}),this.nodeEls.set(a.id,m)}this.pick(i.has(this.picked)?this.picked:null)}pick(e){this.picked=e;let t=this.g;if(!t||!this.nodeEls)return;this.svg.classList.toggle("picked",e!==null);let r=e===null?new Set:_n(t.byId,e,"preds"),s=e===null?new Set:_n(t.byId,e,"succs");for(let[i,o]of this.nodeEls)o.classList.toggle("sel",i===e),o.classList.toggle("on",i===e||r.has(i)||s.has(i)),o.setAttribute("aria-pressed",String(i===e));for(let{e:i,p:o}of this.edgeEls){let d=r.has(i.from)&&(r.has(i.to)||i.to===e),c=(i.from===e||s.has(i.from))&&s.has(i.to);o.classList.toggle("on",d||c)}this.describe(e,r,s)}describe(e,t,r){let s=this.detail;if(s.textContent="",e===null){s.hidden=!0;return}s.hidden=!1;let i=this.g.byId.get(e),o=[...r].map(l=>this.g.byId.get(l)).filter(l=>l.kind==="terminal").map(l=>l.label),d=[...t].map(l=>this.g.byId.get(l)).filter(l=>l.kind==="alpha").map(l=>l.label),c=[["node",i.id],["kind",Kt(i)],["label",i.label||"\u2014"],["test",i.filter||"none"],["occupancy",i.occupancy===null||i.occupancy===void 0?"not reported":String(i.occupancy)]];i.kind!=="alpha"&&c.push(["fed by",[...new Set(d)].join(", ")||"\u2014"]),i.kind!=="terminal"&&c.push(["feeds rules",[...new Set(o)].join(", ")||"\u2014"]);for(let[l,a]of c){let u=document.createElement("dt");u.textContent=l;let m=document.createElement("dd");m.textContent=a,s.append(u,m)}}};var Qn=Br(Zn(),1);async function ys({module:n,glue:e,runtime:t,wasmBinary:r}){return typeof globalThis.Buffer!="function"&&(globalThis.Buffer=Qn.Buffer),(typeof n=="string"||n instanceof URL?await import(String(n)):n).open(r===void 0?{glue:e,runtime:t}:{glue:e,runtime:t,wasmBinary:r})}var ws=new Set(["clock","assert","retract","external","pump"]),D=(n,e)=>`var(--ds-view-${n}, ${e})`,ze="font-family: var(--ds-code-font, monospace); font-size: var(--ds-code-size, 0.85rem);",Me=D("border","#d0d7de"),bs=`
5
+ .ds-inspector { display: grid; grid-template-columns: minmax(18rem, 1fr) minmax(18rem, 1.3fr); gap: 0.75rem 1.25rem; color: ${D("text","inherit")}; }
6
+ .ds-inspector > .ds-head { grid-column: 1 / -1; margin: 0; color: ${D("soft","#57606a")}; }
7
+ .ds-inspector > .ds-head.bad { color: ${D("bad","#cf222e")}; }
8
+ .ds-inspector > section.ds-timeline-part { grid-row: span 6; }
9
+ .ds-inspector .ds-mark { font: inherit; margin: 0 0 0.35rem; }
10
+ .ds-inspector h4 { font-size: 1em; margin: 0.75rem 0 0.25rem; }
11
+ .ds-inspector h3 { font-size: 1em; margin: 0 0 0.35rem; }
12
+ .ds-inspector .ds-note { margin: 0.35rem 0 0; color: ${D("soft","#57606a")}; font-size: 0.9em; }
13
+ .ds-inspector .ds-note.bad { color: ${D("bad","#cf222e")}; }
14
+ .ds-timeline, .ds-pumps { list-style: none; margin: 0; padding: 0; overflow: auto; border: 1px solid ${Me}; ${ze} }
15
+ .ds-timeline { max-height: 36rem; }
16
+ .ds-pumps { max-height: 14rem; }
17
+ .ds-timeline:focus-visible, .ds-pumps:focus-visible { outline: 2px solid ${D("link","#0969da")}; }
18
+ .ds-timeline li { display: grid; grid-template-columns: 3em 6.5em 1fr; gap: 0.5em; padding: 0.1rem 0.4rem; cursor: pointer; }
19
+ .ds-timeline li.input { border-top: 1px solid ${Me}; }
20
+ .ds-timeline li.input:first-child { border-top: none; }
21
+ .ds-timeline li .n, .ds-timeline li .t { color: ${D("soft","#57606a")}; text-align: right; }
22
+ .ds-timeline li .what { overflow-wrap: anywhere; }
23
+ .ds-timeline li.fault .what { color: ${D("bad","#cf222e")}; }
24
+ .ds-timeline li.sel, .ds-pumps li.sel { background: ${D("pick","#ddf4ff")}; }
25
+ .ds-pumps li { padding: 0.2rem 0.4rem; cursor: pointer; border-top: 1px solid ${Me}; }
26
+ .ds-pumps li:first-child { border-top: none; }
27
+ .ds-pumps li .t { color: ${D("soft","#57606a")}; }
28
+ .ds-pumps li .faults { color: ${D("bad","#cf222e")}; }
29
+ .ds-memory, .ds-table { border-collapse: collapse; width: 100%; ${ze} }
30
+ .ds-memory caption { text-align: left; caption-side: bottom; padding-top: 0.35rem; color: ${D("soft","#57606a")}; font-family: inherit; }
31
+ .ds-memory th, .ds-memory td, .ds-table th, .ds-table td { text-align: left; vertical-align: top; padding: 0.1rem 0.5rem; border-bottom: 1px solid ${Me}; }
32
+ .ds-memory td.slots, .ds-table td { overflow-wrap: anywhere; }
33
+ .ds-memory tbody tr[data-fact] { cursor: pointer; }
34
+ .ds-memory tbody tr.sel { background: ${D("pick","#ddf4ff")}; }
35
+ .ds-memory tbody tr[data-fact]:focus-visible { outline: 2px solid ${D("link","#0969da")}; }
36
+ .ds-net-wrap { overflow: auto; border: 1px solid ${Me}; }
37
+ .ds-net { display: block; font-family: var(--ds-code-font, monospace); font-size: 12px; }
38
+ .ds-net .n { cursor: pointer; outline: none; }
39
+ .ds-net .n rect { fill: ${D("surface","#ffffff")}; stroke: ${Me}; stroke-width: 1.5; }
40
+ .ds-net .n.terminal rect { stroke: ${D("link","#0969da")}; }
41
+ .ds-net .n.negative rect { stroke-dasharray: 4 3; }
42
+ .ds-net .n text { fill: ${D("text","#1f2328")}; }
43
+ .ds-net .n text.head { font-weight: 600; }
44
+ .ds-net .n text.sub { fill: ${D("soft","#57606a")}; }
45
+ .ds-net .n:hover rect, .ds-net .n:focus-visible rect { stroke: ${D("link","#0969da")}; stroke-width: 2.5; }
46
+ .ds-net .n.sel rect { stroke: ${D("link","#0969da")}; stroke-width: 3; }
47
+ .ds-net .e { fill: none; stroke: ${D("soft","#57606a")}; stroke-width: 1.2; }
48
+ .ds-net .e.on { stroke: ${D("link","#0969da")}; stroke-width: 2; }
49
+ .ds-net marker path { fill: ${D("soft","#57606a")}; }
50
+ .ds-net.picked .n:not(.on), .ds-net.picked .e:not(.on) { opacity: 0.25; }
51
+ .ds-net-detail { display: grid; grid-template-columns: max-content 1fr; gap: 0.1rem 0.75rem; margin: 0.5rem 0 0; }
52
+ .ds-net-detail dt { color: ${D("soft","#57606a")}; }
53
+ .ds-net-detail dd { margin: 0; ${ze} }
54
+ .ds-vars { list-style: none; margin: 0; padding: 0 0 0 1.1em; ${ze} }
55
+ .ds-scopes, .ds-watches, .ds-console .ds-vars { padding-left: 0; }
56
+ .ds-var-row { display: flex; gap: 0.25em; align-items: baseline; }
57
+ .ds-twisty { flex: none; width: 1em; padding: 0; border: none; background: none; font: inherit; color: ${D("soft","#57606a")}; cursor: pointer; text-align: center; }
58
+ span.ds-twisty { cursor: default; }
59
+ .ds-var-name { color: ${D("link","#0969da")}; }
60
+ .ds-scope > .ds-var-row .ds-var-name { color: inherit; font-weight: 600; }
61
+ .ds-var-value { overflow-wrap: anywhere; }
62
+ .ds-var.bad, .ds-out.bad, .ds-watch .bad .ds-var-value { color: ${D("bad","#cf222e")}; }
63
+ .ds-more button, .ds-unwatch { font: inherit; }
64
+ .ds-watch { display: flex; gap: 0.25em; align-items: baseline; }
65
+ .ds-watch > .ds-vars { flex: 1; }
66
+ .ds-unwatch { padding: 0 0.3em; }
67
+ .ds-stack, .ds-frames { list-style: none; margin: 0; padding: 0; ${ze} }
68
+ .ds-frames { padding-left: 1.1em; }
69
+ .ds-thread-name { color: ${D("soft","#57606a")}; }
70
+ .ds-frame { cursor: pointer; padding: 0 0.3em; }
71
+ .ds-frame.sel { background: ${D("pick","#ddf4ff")}; }
72
+ .ds-frame:focus-visible { outline: 2px solid ${D("link","#0969da")}; }
73
+ .ds-console { list-style: none; margin: 0.5rem 0 0.25rem; padding: 0.2rem 0.4rem; max-height: 14rem; overflow: auto; border: 1px solid ${Me}; ${ze} }
74
+ .ds-console .ds-in { color: ${D("soft","#57606a")}; }
75
+ .ds-console-input, .ds-watch-add { display: flex; gap: 0.35em; margin: 0 0 0.35rem; }
76
+ .ds-console-input input, .ds-watch-add input { flex: 1; font: inherit; }
77
+ .ds-event-kinds { display: flex; flex-wrap: wrap; gap: 0 0.75em; align-items: baseline; }
78
+ .ds-event-kinds button { font: inherit; }
79
+ .ds-events { list-style: none; margin: 0.35rem 0 0; padding: 0.2rem 0.4rem; max-height: 14rem; overflow: auto; border: 1px solid ${Me}; ${ze} }
80
+ .ds-events:empty { display: none; }
81
+ .ds-event { display: grid; grid-template-columns: 6.5em 1fr; gap: 0.5em; }
82
+ .ds-event .t { color: ${D("soft","#57606a")}; text-align: right; }
83
+ .ds-event .what { overflow-wrap: anywhere; }
84
+ .ds-inspector > .ds-live { grid-column: 1 / -1; display: flex; gap: 0.75em; align-items: baseline; }
85
+ .ds-live button { font: inherit; }
86
+ `;function kt(n=document){if(!n.getElementById("ds-kit-views")){let e=n.createElement("style");e.id="ds-kit-views",e.textContent=bs,n.head.appendChild(e)}}function p(n,e={},t=null,r=null){let s=(t?t.ownerDocument:document).createElement(n);for(let[i,o]of Object.entries(e))s.setAttribute(i,String(o));return r!==null&&(s.textContent=r),t&&t.appendChild(s),s}function nr(n,e,t){let r=t-1;switch(n){case"ArrowDown":return Math.min(r,e+1);case"ArrowUp":return Math.max(0,e-1);case"PageDown":return Math.min(r,e+10);case"PageUp":return Math.max(0,e-10);case"Home":return 0;case"End":return r;default:return null}}var gt=class{constructor(e,{onPick:t=()=>{}}={}){this.list=p("ol",{class:"ds-timeline",role:"listbox",tabindex:0,"aria-label":"events"},e),this.onPick=t,this.items=[],this.picked=-1,this.list.addEventListener("click",r=>{let s=r.target instanceof Element?r.target.closest("li[data-index]"):null;s&&this.choose(Number(s.getAttribute("data-index")))}),this.list.addEventListener("keydown",r=>{let s=nr(r.key,Math.max(0,this.picked),this.items.length);s!==null&&this.items.length&&(r.preventDefault(),this.choose(s))})}render(e){this.list.textContent="";let t=Ye(e);this.items=e.events.map((r,s)=>{let i=["ev",r.kind,ws.has(r.kind)?"input":""].filter(Boolean).join(" "),o=p("li",{class:i,role:"option","aria-selected":"false","data-index":s},this.list);return p("span",{class:"n"},o,String(s+1)),p("span",{class:"t",title:r.clockNs===null?"":`${r.clockNs} ns`},o,De(r.clockNs,t)),p("span",{class:"what"},o,ot(r,t)),o}),this.picked=-1}pick(e){this.items[this.picked]&&(this.items[this.picked].classList.remove("sel"),this.items[this.picked].setAttribute("aria-selected","false")),this.picked=e;let t=this.items[e];t&&(t.classList.add("sel"),t.setAttribute("aria-selected","true"),t.scrollIntoView({block:"nearest"}))}choose(e){this.pick(e),this.onPick(e)}},yt=class{constructor(e,{onFact:t=()=>{}}={}){this.table=p("table",{class:"ds-memory"},e),this.caption=p("caption",{},this.table);let r=p("tr",{},p("thead",{},this.table));for(let s of["fact","schema","slots","since","by"])p("th",{scope:"col"},r,s);this.body=p("tbody",{},this.table),this.onFact=t,this.rows=new Map}render(e,t=""){if(this.caption.textContent=t,this.body.textContent="",this.rows=new Map,!e.size){p("td",{colspan:5},p("tr",{class:"empty"},this.body),"no facts");return}for(let[r,s]of e){let i=p("tr",{tabindex:0,"data-fact":r,"aria-label":`fact #${r}`},this.body);p("td",{},i,`#${r}`),p("td",{},i,s.schema||"(external)"),p("td",{class:"slots"},i,s.slots?me(s.slots):""),p("td",{},i,s.since===null?"":`seq ${s.since}`),p("td",{},i,s.rule||"host"),i.addEventListener("click",()=>this.onFact(r)),i.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),this.onFact(r))}),this.rows.set(r,i)}}mark(e){for(let[t,r]of this.rows)r.classList.toggle("sel",t===e)}},wt=class{constructor(e,{onPick:t=()=>{}}={}){this.list=p("ol",{class:"ds-pumps",role:"listbox",tabindex:0,"aria-label":"pumps"},e),this.onPick=t,this.pumps=[],this.items=[],this.picked=-1,this.list.addEventListener("click",r=>{let s=r.target instanceof Element?r.target.closest("li[data-pump]"):null;s&&this.choose(Number(s.getAttribute("data-pump")))}),this.list.addEventListener("keydown",r=>{let s=nr(r.key,Math.max(0,this.picked),this.items.length);s!==null&&this.items.length&&(r.preventDefault(),this.choose(s))})}render(e,t=dt(e)){this.list.textContent="",this.pumps=t;let r=Ye(e);this.items=t.map((s,i)=>{let o=p("li",{role:"option","aria-selected":"false","data-pump":i,"data-index":s.index},this.list);p("span",{class:"t"},o,`pump ${i+1} at ${De(s.clockNs,r)}`);let d=[];s.fires.length&&d.push(["fires",`fires ${s.fires.join(", ")}`]);for(let c of s.emits)d.push(["emits",`emits #${c.factId} ${Ce(c.schema,c.slots)}`]);for(let c of s.calls)d.push(["calls",`calls ${c.service}(${me(c.args)})`]);s.withdrawals.length&&d.push(["withdraws",`withdraws ${s.withdrawals.map(c=>`#${c.factId}`).join(", ")}`]),s.publishes.length&&d.push(["publishes",`publishes ${s.publishes.map(c=>c.schema).join(", ")}`]),s.faults.length&&d.push(["faults",`faults: ${s.faults.map(c=>ot(c)).join("; ")}`]),d.length||d.push(["quiet","no rule fired"]);for(let[c,l]of d)p("div",{class:c},o,l);return o}),this.picked=-1}show(e){let t=this.pumps.findIndex(r=>r.index<=e&&e<r.end);this.items[this.picked]&&(this.items[this.picked].classList.remove("sel"),this.items[this.picked].setAttribute("aria-selected","false")),this.picked=t,this.items[t]&&(this.items[t].classList.add("sel"),this.items[t].setAttribute("aria-selected","true"),this.items[t].scrollIntoView({block:"nearest"}))}choose(e){let t=this.pumps[e];t&&this.onPick(t.end-1)}},bt=class{constructor(e){this.body=ne(e,["kind","for","ends","remaining"])}render(e,t=null){z(this.body,e.map(r=>[r.kind,r.kind==="ttl"?`#${r.factId} ${r.schema}`:r.rule||"",De(r.endsNs,t),r.remainingNs===null?"":De(r.remainingNs)]))}},xt=class{constructor(e){p("h4",{},e,"In"),this.in=ne(e,["event","fact","by"]),p("h4",{},e,"Out"),this.out=ne(e,["event","fact"])}render(e){let t=r=>`#${r.factId} ${Ce(r.schema,r.slots)}`;z(this.in,e?e.asserted.map(r=>[String(r.index+1),t(r),r.rule||"host"]):[]),z(this.out,e?e.retracted.map(r=>[String(r.index+1),t(r)]):[])}},xs=n=>n?n.slice(0,12):"none";function ks(n,e){let t=n.header,s=[t?`DS ${t.dsVersion||"?"}`:"no stream header",t?`program ${xs(t.dscHash)}`:null,`${n.events.length} events`,`${e.length} pumps`].filter(Boolean).join(" \xB7 ");return n.incomplete&&(s+=" \xB7 cut short, read as far as it goes"),n.error&&(s+=` \xB7 unreadable from byte ${n.error.offset}: ${n.error.detail}`),s}function ne(n,e){let t=p("table",{class:"ds-table"},n),r=p("tr",{},p("thead",{},t));for(let s of e)p("th",{scope:"col"},r,s);return p("tbody",{},t)}function z(n,e){n.textContent="";for(let t of e){let r=p("tr",{},n);for(let s of t)p("td",{},r,s)}}var mt="This needs the program the recording was made with.",er=n=>n.events===0?"before the first event":`after event ${n.events}`,tr=n=>String(n&&n.message||n);function vs({parent:n,api:e,bytes:t,dsc:r=null,onPick:s=()=>{}}){kt(n.ownerDocument);let i=Ut(e,t),o=dt(i),d=p("div",{class:"ds-inspector"},n);p("p",{class:i.error?"ds-head bad":"ds-head"},d,ks(i,o));let c=(v,N)=>{let G=p("section",{class:v},d);return p("h3",{},G,N),G},l=(v,N="")=>p("p",{class:"ds-note"},v,N),a=(v,N,G=!1)=>{v.className=G?"ds-note bad":"ds-note",v.textContent=N},u=new gt(c("ds-timeline-part","Timeline"),{onPick:v=>be(v)}),m=c("ds-memory-part","Working memory"),w=new yt(m,{onFact:v=>j(v)}),g=p("div",{class:"ds-why",hidden:""},m),_=p("h4",{},g),A=l(g),V=l(g),S=ne(g,["node","kind","result","why"]),R=l(g),T=ne(g,["timetag","rule"]),U=new wt(c("ds-pumps-part","Pumps"),{onPick:v=>be(v)}),W=c("ds-network-part","Network"),q=W.ownerDocument.createElementNS("http://www.w3.org/2000/svg","svg");q.setAttribute("class","ds-net"),q.setAttribute("role","group"),q.setAttribute("aria-label","Rete network"),p("div",{class:"ds-net-wrap"},W).appendChild(q);let re=p("dl",{class:"ds-net-detail",hidden:""},W),Y=l(W),le=new Ge(q,re),Z=c("ds-refract-part","Refracted"),se=l(Z),ve=ne(Z,["rule","reason","over facts","detail"]),ge=c("ds-timers-part","Timers"),ie=l(ge),de=new bt(ge),ye=c("ds-changes-part","Changes"),X=p("button",{type:"button",class:"ds-mark"},ye,"Mark this point"),Q=l(ye),Ee=new xt(ye);u.render(i),U.render(i,o);let $e=Ye(i),oe=r?new it(e,r,t,i):null,K=r?zt(e,r,t,i):null,ue=null,M=null,b=-1,B=null,O=v=>{if(!oe){le.render(null),a(Y,mt),a(se,mt),z(ve,[]);return}let N=Xe(i,v);if(!M||M.cut.events!==N.events){try{let{engine:f}=oe.at(v);M={cut:N,engine:f,network:ut(f),refracted:qt(f),ids:new Set(Gt(f).map(y=>y.id))}}catch(f){oe.close(),M={cut:N,error:tr(f)}}le.render(M.error?null:M.network),z(ve,M.error?[]:M.refracted.map(f=>[f.rule,f.reason,f.factIds.map(y=>`#${y}`).join(" "),f.detail||""]))}if(M.error){a(Y,`The replay stopped: ${M.error}`,!0),a(se,`The replay stopped: ${M.error}`,!0);return}let G=er(N);a(Y,N.events===v?`The network ${G}, replayed.`:`The network ${G}, replayed: a replay stops before an input, once a pump's rules have run.`),a(se,M.refracted.length?`${G}: ${M.refracted.length} activation(s) have fired and do not fire again for the same facts.`:`${G}: no activation is refracted.`)};function j(v){if(B=v,w.mark(v),g.hidden=!1,_.textContent=`Fact #${v}`,z(S,[]),z(T,[]),a(V,""),a(R,""),!M||M.error){a(A,M?`The replay stopped: ${M.error}`:mt,!!M);return}let N=er(M.cut);if(!M.ids.has(v)){a(A,`Fact #${v} has left working memory ${N}, where the replay stops.`);return}let G;try{G=Ht(M.engine,v)}catch(f){a(A,`The engine could not answer: ${tr(f)}`,!0);return}a(A,`The engine's answers ${N}.`),a(V,G.match.length?`${G.match.length} alpha node(s) saw this fact.`:"No alpha node tests this fact's schema."),z(S,G.match.map(f=>[f.node,f.kind,f.result,f.detail||""])),a(R,G.justifiers.length?`${G.justifiers.length} activation(s) hold this fact.`:"No rule holds it: it was asserted, not derived logically."),z(T,G.justifiers.map(f=>[String(f.timetag),f.rule]))}let P=v=>v===0?"before the first event":`after event ${v}`,ae=v=>{if(!K){de.render([]),a(ie,mt);return}let N=Vt(i,K,v);de.render(N.timers,$e);let G=`${P(v)}${N.nowNs===null?"":`, at ${De(N.nowNs,$e)}`}`,f=N.timers.length?`${G}: ${N.timers.length} timer(s) run. Pending after timers are not listed: the engine does not report them.`:`${G}: no cooldown or TTL runs.`;K.error&&K.error.at<v&&(f+=` The re-run stopped at event ${K.error.at+1} (${K.error.message}): no timer armed after it is shown.`),a(ie,f,!!(K.error&&K.error.at<v))},ee=v=>{if(ue===null){Ee.render(null),a(Q,"Mark a point, then pick another: what entered and left working memory between them.");return}let N=Ot(i,ue,v);Ee.render(N),a(Q,`From ${P(N.from)} to ${P(N.to)}: ${N.asserted.length} in, ${N.retracted.length} out.`)};function Ne(v=b+1){ue=Math.max(0,Math.min(i.events.length,v)),X.textContent=`Marked ${P(ue)}: mark again`,ee(b+1)}X.addEventListener("click",()=>Ne());function be(v){if(v<0||v>=i.events.length)return;b=v,u.pick(v),U.show(v);let N=Pt(i,v+1);w.render(N,`after event ${v+1}: ${ot(i.events[v],Ye(i))}`),O(v+1),ae(v+1),ee(v+1),B!==null&&N.has(B)?j(B):(B=null,g.hidden=!0),s(v)}return i.events.length?be(i.events.length-1):(w.render(new Map,"no events"),O(0),ae(0),ee(0)),{element:d,recording:i,pick:be,picked:()=>b,why:j,mark:Ne,close:()=>{oe&&oe.close(),M=null}}}var on=100,Es=3,rr=20,$s=/[\p{XID_Start}_]\p{XID_Continue}*(?:\.[\p{XID_Start}_]\p{XID_Continue}*)*/gu;function an(n,e){for(let t of n.matchAll($s)){let r=t.index??0,s=e-r;if(s<0||s>=t[0].length)continue;if(t[0][s]===".")return null;let i=t[0].indexOf(".",s),o=i===-1?t[0].length:i,d=t[0].lastIndexOf(".",s)+1;return{expression:t[0].slice(0,o),from:r+d,to:r+o}}return null}async function sr(n){let e=n.state;if(!e.stopped||e.ended)return null;let t=await n.request("threads");if(!t.success||!t.body.threads.length)return null;let r=t.body.threads.find(i=>i.id===e.stopped.threadId)||t.body.threads[0],s=await n.request("stackTrace",{threadId:r.id,levels:1});return s.success&&s.body.stackFrames.length?s.body.stackFrames[0]:null}async function vt(n,e,{frameId:t=null,context:r="repl"}={}){let s=e.trim(),i=await n.request("evaluate",{expression:s,context:r,...t===null?{}:{frameId:t}});return i.success?{result:i.body.result,variablesReference:i.body.variablesReference||0}:{error:i.message||"ds dap refused"}}async function ir(n,e,t,r,s){let i=await n.request("variables",{variablesReference:e,start:0,count:rr});if(!i.success){s.push(`${r}(${i.message||"ds dap refused"})`);return}for(let o of i.body.variables)s.push(`${r}${o.name}: ${o.value}`),o.variablesReference&&t>1&&await ir(n,o.variablesReference,t-1,`${r} `,s);i.body.variables.length===rr&&s.push(`${r}\u2026`)}async function cn(n,e){let t=await sr(n);if(!t)return null;let r=await vt(n,e,{frameId:t.id,context:"hover"});if("error"in r)return null;let s=[`${e} = ${r.result}`];return r.variablesReference&&await ir(n,r.variablesReference,Es," ",s),s.join(`
87
+ `)}function tt(n,e,t,r){let s=p("li",{class:"ds-var","data-name":t.name},n),i=p("div",{class:"ds-var-row"},s),o=t.variablesReference||0,d=o?p("button",{type:"button",class:"ds-twisty","aria-expanded":"false","aria-label":`${t.name}: show its parts`},i,"\u25B8"):p("span",{class:"ds-twisty"},i,"");if(t.name!==""&&p("span",{class:"ds-var-name"},i,t.name),t.name!==""&&t.value!==""&&p("span",{class:"ds-var-sep"},i,": "),t.value!==""&&p("span",{class:"ds-var-value"},i,t.value),!o)return s;let c=null,l=async a=>{d.setAttribute("aria-expanded",String(a)),d.textContent=a?"\u25BE":"\u25B8",a?r.open.add(r.path):r.open.delete(r.path),a&&!c?(c=p("ul",{class:"ds-vars"},s),await or(c,e,o,0,r)):c&&(c.hidden=!a)};return d.addEventListener("click",()=>l(d.getAttribute("aria-expanded")!=="true")),s.dsOpen=l,r.open.has(r.path)&&(s.dsOpening=l(!0)),s}async function or(n,e,t,r,s){let i=await e.request("variables",{variablesReference:t,start:r,count:on});if(!i.success){p("li",{class:"ds-var bad"},n,i.message||"ds dap refused");return}let o=[];for(let d of i.body.variables){let c=tt(n,e,d,{path:`${s.path}/${d.name}`,open:s.open});c.dsOpening&&o.push(c.dsOpening)}if(i.body.variables.length===on){let d=p("li",{class:"ds-var ds-more"},n);p("button",{type:"button"},d,"More\u2026").addEventListener("click",async()=>{d.remove(),await or(n,e,t,r+on,s)})}await Promise.all(o)}function ln({parent:n,session:e,before:t=null,consoleParent:r=null,watches:s=[]}){let i=n.ownerDocument,o=(b,B,O,j=null)=>{let P=i.createElement("section");return P.className=B,b.insertBefore(P,j),p("h3",{},P,O),P},d=b=>p("p",{class:"ds-note"},b),c=(b,B,O=!1)=>{b.className=O?"ds-note bad":"ds-note",b.textContent=B},l=o(n,"ds-stack-part","Call stack",t),a=d(l),u=p("ol",{class:"ds-stack"},l),m=o(n,"ds-variables-part","Variables",t),w=d(m),g=p("ul",{class:"ds-vars ds-scopes"},m),_=o(n,"ds-watch-part","Watch",t),A=p("form",{class:"ds-watch-add"},_),V=p("input",{name:"expression",placeholder:"expression to watch",size:24,"aria-label":"expression to watch"},A);p("button",{type:"submit"},A,"Watch");let S=p("ul",{class:"ds-vars ds-watches"},_),R=o(r||n,"ds-console-part","Console",r?null:t),T=p("ol",{class:"ds-console","aria-label":"console","aria-live":"polite"},R),U=p("form",{class:"ds-console-input"},R),W=p("input",{name:"expression",placeholder:"DS expression at the picked frame",size:36,"aria-label":"console expression"},U);p("button",{type:"submit"},U,"Evaluate");let q=null,re=new Set(["Bindings"]),Y=[...s],le=[],Z=0,se=!1;async function ve(){if(g.textContent="",q===null)return;let b=await e.request("scopes",{frameId:q});if(!b.success){c(w,b.message||"ds dap refused",!0);return}c(w,b.body.scopes.some(O=>O.name==="Bindings")?"The picked frame's scopes.":"The engine binds nothing here: pick a firing to read its bindings.");let B=[];for(let O of b.body.scopes){let j=tt(g,e,{name:O.name,value:"",variablesReference:O.variablesReference},{path:O.name,open:re});j.classList.add("ds-scope"),j.dsOpening&&B.push(j.dsOpening)}await Promise.all(B)}async function ge(){S.textContent="";for(let b of Y){let B=p("li",{class:"ds-watch","data-expression":b},S);p("button",{type:"button",class:"ds-unwatch","aria-label":`stop watching ${b}`},B,"\xD7").addEventListener("click",()=>oe(b));let j=p("ul",{class:"ds-vars"},B);if(q===null&&!e.state.stopped){tt(j,e,{name:b,value:"not stopped"},{path:`watch:${b}`,open:re});continue}let P=await vt(e,b,{frameId:q,context:"watch"});if("error"in P)tt(j,e,{name:b,value:P.error},{path:`watch:${b}`,open:re}).classList.add("bad");else{let ae=tt(j,e,{name:b,value:P.result,variablesReference:P.variablesReference},{path:`watch:${b}`,open:re});ae.dsOpening&&await ae.dsOpening}}}async function ie(){u.textContent="";let b=e.state;if(b.ended){c(a,b.ended,!0),q=null;return}if(!b.stopped){c(a,"Not stopped yet."),q=null;return}let B=await e.request("threads");if(!B.success){c(a,B.message||"ds dap refused",!0),q=null;return}let O=b.stopped.threadId,j=null,P=null,ae=!1;for(let ee of B.body.threads){let Ne=p("li",{class:"ds-thread","data-thread":ee.id},u);p("span",{class:"ds-thread-name"},Ne,ee.name);let be=p("ol",{class:"ds-frames"},Ne),v=await e.request("stackTrace",{threadId:ee.id});for(let N of v.success?v.body.stackFrames:[]){let G=p("li",{class:"ds-frame","data-frame":N.id,tabindex:0},be,`${N.name}${N.line?`, line ${N.line}`:""}`),f=()=>Ee(N.id);G.addEventListener("click",f),G.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),f())}),N.id===q&&(ae=!0),P===null&&(P=N.id),j===null&&ee.id===O&&(j=N.id)}}ae||(q=j??P),c(a,`${B.body.threads.length} firing(s) at this stop.`),de()}function de(){for(let b of u.querySelectorAll(".ds-frame"))b.classList.toggle("sel",Number(b.getAttribute("data-frame"))===q)}let ye=Promise.resolve(),X=b=>(ye=ye.then(b,b),ye),Q=(b=!1)=>X(async()=>{se||(b&&(q=null),await ie(),await ve(),await ge())}),Ee=b=>X(async()=>{q=b,de(),await ve(),await ge()}),$e=b=>{let B=b.trim();return B&&!Y.includes(B)&&Y.push(B),X(ge)},oe=b=>{let B=Y.indexOf(b);return B!==-1&&Y.splice(B,1),X(ge)};async function K(b){let B=b.trim();if(!B)return null;le.push(B),Z=0,p("li",{class:"ds-in"},T,`\u203A ${B}`);let O=await vt(e,B,{frameId:q,context:"repl"}),j=p("li",{class:"ds-out"},T),P=p("ul",{class:"ds-vars"},j);return"error"in O?(j.classList.add("bad"),p("li",{class:"ds-var"},P,O.error)):tt(P,e,{name:"",value:O.result,variablesReference:O.variablesReference},{path:`console:${le.length}`,open:new Set}),T.scrollTop=T.scrollHeight,O}A.addEventListener("submit",b=>{b.preventDefault();let B=V.value;V.value="",$e(B)}),U.addEventListener("submit",b=>{b.preventDefault();let B=W.value;W.value="",K(B)}),W.addEventListener("keydown",b=>{(b.key==="ArrowUp"||b.key==="ArrowDown")&&le.length&&(b.preventDefault(),Z=Math.max(0,Math.min(le.length,Z+(b.key==="ArrowUp"?1:-1))),W.value=Z?le[le.length-Z]:"")});let ue=!1,M=e.listen((b,B)=>{b==="event"&&(B.event==="stopped"||B.event==="terminated")&&(ue=!0),b==="answer"&&ue&&(ue=!1,Q(!0))});return c(a,"Not stopped yet."),{refresh:Q,select:Ee,frame:()=>q,evaluate:K,watch:$e,unwatch:oe,watches:()=>[...Y],close(){se=!0,M()}}}var Fe=n=>n==null?"":`${(Number(n)/1e9).toFixed(3)} s`,dn=[["factAsserted","asserted"],["factRetracted","retracted"],["logicalFactFlipped","logical flips"],["callMade","calls"],["callAnswered","answers"]],Is=new Set(dn.map(([n])=>`ds/${n}`)),Bs=500,ar=n=>n?n.kind==="rule"?`rule ${n.rule_name} (${n.firing})`:n.kind.replace(/_/g," "):"";function cr(n,e){switch(n){case"factAsserted":return`+ ${e.fact_id} ${Ce(e.schema,e.slots||{})}, by ${ar(e.asserter)}`;case"factRetracted":return`\u2212 ${e.fact_id} ${e.schema}, by ${ar(e.retractor)}`;case"logicalFactFlipped":return`${e.fact_id} ${e.schema} ${e.direction==="assert"?"holds":"no longer holds"} (${e.justifier_count} justifier(s))`;case"callMade":return`call ${e.service} ${e.corr} ${me(e.kwargs||{})}, from ${e.firing}`;case"callAnswered":return`answer ${e.service} ${e.corr}: ${"error"in e?`error ${JSON.stringify(e.error)}`:me(e.response||{})}`;default:return JSON.stringify(e)}}function Ve(n,e,t){return p("label",{class:"ds-field"},n,`${e} `).appendChild(t),t}function As({parent:n,session:e,live:t=!1}){let r=n.ownerDocument;kt(r);let s=p("div",{class:"ds-inspector ds-debug"},n),i=p("p",{class:"ds-head"},s,"Not stopped yet."),o=null;if(t){let x=p("div",{class:"ds-live"},s),$=p("button",{type:"button",class:"ds-catch-up"},x,"Catch up with the live engine");o=p("span",{class:"ds-note"},x,"The recording so far, from the engine's start."),$.addEventListener("click",async()=>{$.disabled=!0;let C=await e.catchUp();$.disabled=!1,o.className=C.success?"ds-note":"ds-note bad",o.textContent=C.success?`Caught up: ${C.body.event_count} events, to ${Fe(C.body.duration_ns)}. The replay starts over, the breakpoints kept.`:C.message||"ds dap refused"})}let d=(x,$)=>{let C=p("section",{class:x},s);return p("h3",{},C,$),C},c=x=>p("p",{class:"ds-note"},x),l=(x,$,C=!1)=>{x.className=C?"ds-note bad":"ds-note",x.textContent=$},a=d("ds-firing-part","Firing"),u=c(a),m=ne(a,["pattern","binding","fact","slots","join"]),w=d("ds-memory-part","Working memory"),g=c(w),_=ne(w,["fact","schema","slots","logical","ttl left"]),A=p("div",{class:"ds-why",hidden:""},w),V=p("h4",{},A),S=c(A),R=c(A),T=ne(A,["firing","rule","at"]),U=c(A),W=ne(A,["node","kind","result","why"]),q=p("button",{type:"button",class:"ds-retract"},A,"Retract (what if)"),re=d("ds-network-part","Network"),Y=r.createElementNS("http://www.w3.org/2000/svg","svg");Y.setAttribute("class","ds-net"),Y.setAttribute("role","group"),Y.setAttribute("aria-label","Rete network"),p("div",{class:"ds-net-wrap"},re).appendChild(Y);let le=p("dl",{class:"ds-net-detail",hidden:""},re),Z=c(re),se=new Ge(Y,le),ve=d("ds-refract-part","Refracted"),ge=c(ve),ie=ne(ve,["rule","reason","detail","bindings"]),de=d("ds-timers-part","Timers"),ye=c(de),X=ne(de,["kind","for","ends","remaining"]),Q=d("ds-changes-part","Changes"),Ee=p("button",{type:"button",class:"ds-mark"},Q,"Mark this stop"),$e=c(Q);p("h4",{},Q,"In");let oe=ne(Q,["fact","schema","slots"]);p("h4",{},Q,"Out");let K=ne(Q,["fact","schema","slots"]),ue=d("ds-timelines-part","Timelines"),M=c(ue),b=p("ul",{class:"ds-timelines"},ue),B=d("ds-whatif-part","What if"),O=c(B),j=p("form",{class:"ds-assert"},B),P=Ve(j,"Assert",p("input",{name:"schema",placeholder:"schema",size:12})),ae=Ve(j,"slots",p("input",{name:"slots",placeholder:'{"slot": "value"}',size:28}));p("button",{type:"submit"},j,"Assert");let ee=p("form",{class:"ds-answer"},B),Ne=Ve(ee,"Answer call",p("input",{name:"corr",placeholder:"corr",size:12})),be=Ve(ee,"response",p("input",{name:"response",placeholder:'{"slot": "value"}',size:28}));p("button",{type:"submit"},ee,"Answer");let v=p("form",{class:"ds-mock"},B),N=Ve(v,"Mock service",p("input",{name:"service",placeholder:"service",size:12})),G=Ve(v,"response",p("input",{name:"response",placeholder:'{"slot": "value"}',size:28})),f=Ve(v,"times",p("input",{name:"times",type:"number",min:0,value:1,size:3}));p("button",{type:"submit"},v,"Install");let y=p("ul",{class:"ds-mocks"},B),I=d("ds-events-part","Events"),k=c(I),F=p("div",{class:"ds-event-kinds"},I),Ue=new Map;for(let[x,$]of dn){let C=p("label",{class:"ds-field"},F),L=p("input",{type:"checkbox",name:x},C);C.append(` ${$} `),Ue.set(x,L),L.addEventListener("change",()=>kn())}p("button",{type:"button",class:"ds-events-clear"},F,"Clear").addEventListener("click",()=>{Ke.textContent=""});let Ke=p("ol",{class:"ds-events","aria-label":"events"},I),gn=d("ds-output-part","Output"),yn=p("ol",{class:"ds-output"},gn),wn=ln({parent:s,session:e,before:a,consoleParent:gn}),Pe=new Map,nt=null,Oe=null,Et=new Map,bn=!1,$t=0,fe=(x,$)=>e.request(x,$),xe=x=>x.message||"ds dap refused",It=()=>{if(!nt){l($e,"Mark a stop, then step: what entered and left working memory between them."),z(oe,[]),z(K,[]);return}let x=L=>[L.fact_id,L.schema,me(L.slots)],$=[...Pe.values()].filter(L=>!nt.facts.has(L.fact_id)),C=[...nt.facts.values()].filter(L=>!Pe.has(L.fact_id));z(oe,$.map(x)),z(K,C.map(x)),l($e,`From the stop marked (${nt.where}) to this one: ${$.length} in, ${C.length} out.`)},yr=()=>{let x=e.state.stopped;return x?x.reason:"no stop"};async function Bt(x){Oe=x,A.hidden=!1;let $=Pe.get(x);V.textContent=$?`Fact ${x} ${Ce($.schema,$.slots)}`:`Fact ${x}`;for(let H of _.querySelectorAll("tr"))H.classList.toggle("sel",H.getAttribute("data-fact")===x);let[C,L,pe]=await Promise.all([fe("ds/getFactLineage",{fact_id:x}),fe("ds/getJustifiers",{fact_id:x}),fe("ds/getMatchTrace",{fact_id:x})]);if(C.success){let H=C.body.asserter,te=C.body.retractor,Te=ke=>ke.kind==="rule"?`rule ${ke.rule_name} (${ke.firing})`:ke.kind;l(S,`Asserted by ${Te(H)} at ${Fe(H.clock_ns)}${te?`; retracted by ${Te(te)} at ${Fe(te.clock_ns)}`:"; still in working memory"}.`)}else l(S,xe(C),!0);if(L.success){let H=L.body.justifiers;l(R,H.length?`${H.length} activation(s) hold this fact.`:"No rule holds it: it was asserted, not derived logically."),z(T,H.map(te=>[te.firing,te.display_name||te.rule_name,Fe(te.clock_ns)]))}else l(R,xe(L),!0),z(T,[]);pe.success?(l(U,`${pe.body.path.length} alpha node(s) saw this fact.`),z(W,pe.body.path.map(H=>[H.node_id,H.node_kind,H.result,H.detail||""]))):(l(U,xe(pe),!0),z(W,[]))}let At=Promise.resolve(),Nt=()=>(At=At.then(xn,xn),At);async function xn(){if(bn)return;let x=e.state;if(x.ended){i.className="ds-head bad",i.textContent=x.ended;return}let $=await fe("threads"),C=$.success&&$.body.threads.length?$.body.threads.find(E=>E.id===(x.stopped&&x.stopped.threadId))||$.body.threads[0]:null,L=null;if(C){let E=await fe("stackTrace",{threadId:C.id,levels:1});L=E.success&&E.body.stackFrames.length?E.body.stackFrames[0]:null}let pe=x.stopped;i.className="ds-head",i.textContent=pe?`Stopped: ${pe.reason}${pe.description?`, ${pe.description}`:""}${C?`, in ${C.name}`:""}${L&&L.line?` at line ${L.line} (${L.name})`:""}.`:"Not stopped yet.";let H=C?await fe("ds/getActivationPath",{threadId:C.id}):null;H&&H.success?(l(u,`${H.body.display_name}: the facts each pattern matched.`),z(m,H.body.steps.map(E=>[String(E.pattern_index+1),E.binding||"",E.fact_id||"",E.slots?me(E.slots):"",E.join_result]))):(l(u,H?xe(H):"No firing at this stop.",!!H),z(m,[]));let[te,Te,ke,St,ct]=await Promise.all([fe("ds/getWorkingMemory",{}),fe("ds/getTimerAgenda",{}),fe("ds/getReteNetwork",{include_occupancy:!0}),fe("ds/getRefractedActivations",{rule_name:""}),fe("ds/timelines")]);if(Pe=new Map,_.textContent="",te.success){for(let E of te.body.facts){Pe.set(E.fact_id,E);let he=p("tr",{tabindex:0,"data-fact":E.fact_id},_);for(let rt of[E.fact_id,E.schema,me(E.slots),E.logical?"yes":"no",Fe(E.ttl_remaining_ns)])p("td",{},he,rt);let En=()=>Bt(E.fact_id);he.addEventListener("click",En),he.addEventListener("keydown",rt=>{(rt.key==="Enter"||rt.key===" ")&&(rt.preventDefault(),En())})}l(g,`${te.body.total} fact(s) at this stop.`)}else l(g,xe(te),!0);if(Te.success?(l(ye,Te.body.timers.length?`${Te.body.timers.length} timer(s) run. Pending after timers are not listed.`:"No cooldown or TTL runs."),z(X,Te.body.timers.map(E=>[E.kind,E.kind==="ttl"?E.fact_id:E.rule_name,Fe(E.ends_at_ns),Fe(E.remaining_ns)]))):(l(ye,xe(Te),!0),z(X,[])),ke.success?(se.render({nodes:ke.body.nodes.map(E=>({id:E.id,kind:E.kind,label:E.label,filter:E.filter||"",occupancy:E.occupancy??E.pending_activations??null,negative:!1})),edges:ke.body.edges.map(E=>({from:E.from,to:E.to}))}),l(Z,ke.body.truncated?`The first nodes of ${ke.body.node_count}.`:"The network at this stop.")):(se.render(null),l(Z,xe(ke),!0)),St.success){let E=St.body.refracted;l(ge,E.length?`${E.length} activation(s) have fired and do not fire again for the same facts.`:"No activation is refracted."),z(ie,E.map(he=>[he.display_name||he.rule_name,he.reason,he.detail||"",me(he.bindings||{})]))}else l(ge,xe(St),!0),z(ie,[]);if(b.textContent="",ct.success){for(let E of ct.body.timelines){let he=p("li",{"data-timeline":E.timeline,class:E.current?"sel":""},b);p("span",{},he,E.timeline==="%0"?"%0, the run":`${E.timeline}, from ${E.from} at ${Fe(E.at_ns)}: ${E.change||""}`),E.current||(p("button",{type:"button",class:"ds-switch"},he,"Follow").addEventListener("click",()=>je("ds/switchTimeline",{timeline:E.timeline})),E.timeline!=="%0"&&p("button",{type:"button",class:"ds-drop"},he,"Drop").addEventListener("click",()=>je("ds/dropTimeline",{timeline:E.timeline})))}l(M,ct.body.timelines.length>1?"The run and its forks.":'The run alone: a change in "What if" opens a fork.')}else l(M,xe(ct),!0);yn.textContent="";for(let E of x.output.slice(-50))p("li",{class:E.category},yn,E.output.replace(/\n$/,""));It(),Oe&&Pe.has(Oe)?await Bt(Oe):(Oe=null,A.hidden=!0)}async function je(x,$){let C=$t,L=await fe(x,$);l(O,L.success?L.body&&L.body.message||`${x} done.`:xe(L),!L.success),L.success&&x==="ds/installMock"&&L.body&&L.body.mock_id&&Et.set(L.body.mock_id,`${$.service||$.corr}: ${JSON.stringify($.response)}`),L.success&&x==="ds/removeMock"&&Et.delete($.mock_id),y.textContent="";for(let[pe,H]of Et){let te=p("li",{"data-mock":pe},y,`${pe} ${H} `);p("button",{type:"button"},te,"Remove").addEventListener("click",()=>je("ds/removeMock",{mock_id:pe}))}return $t===C&&await Nt(),L}let Ct=(x,$)=>{try{return JSON.parse(x.value||"{}")}catch{return l(O,`${$}: ${x.value} is not JSON.`,!0),null}};j.addEventListener("submit",x=>{x.preventDefault();let $=Ct(ae,"Slots");$&&je("ds/assertFact",{schema:P.value,slots:$})}),ee.addEventListener("submit",x=>{x.preventDefault();let $=Ct(be,"Response");$&&je("ds/answerCall",{corr:Ne.value,response:$})}),v.addEventListener("submit",x=>{x.preventDefault();let $=Ct(G,"Response");$&&je("ds/installMock",{service:N.value,response:$,times:Number(f.value)})}),q.addEventListener("click",()=>{Oe&&je("ds/retractFact",{fact_id:Oe})}),Ee.addEventListener("click",()=>vn());async function kn(){let x=[...Ue].filter(([,C])=>C.checked).map(([C])=>C),$=await fe("ds/streamEvents",{kinds:x});return l(k,$.success?x.length?"Each goes out while the session moves forward.":"No events chosen.":xe($),!$.success),$}function wr(x){let $=x.event.slice(3),C=p("li",{class:`ds-event ${$}`,"data-kind":$},Ke);for(p("span",{class:"t"},C,Fe(x.body&&x.body.clock_ns)),p("span",{class:"what"},C,cr($,x.body||{}));Ke.childElementCount>Bs;)Ke.firstElementChild.remove();C.scrollIntoView?.({block:"nearest"})}function vn(){nt={facts:new Map(Pe),where:yr()},Ee.textContent="Marked: mark again",It()}let _t=!1,br=e.listen((x,$)=>{x==="event"&&Is.has($.event)&&wr($),x==="event"&&($.event==="stopped"||$.event==="terminated")&&(_t=!0,$t++),x==="answer"&&_t&&(_t=!1,Nt())});return It(),l(k,"Choose the events to log: they go out while the session moves forward."),{element:s,refresh:Nt,why:Bt,mark:vn,variables:wn,events(x){for(let[$,C]of Ue)C.checked=x.includes($);return kn()},close(){bn=!0,br(),wn.close()}}}var Ae="ds",Ns=/\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?_?[a-zA-Zµ°ΩÅ][\wµ°ΩÅ]*/,Cs=/\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?/,lr={unicode:!0,keywords:["activated","activation","after","alias","all_time","ambient","as","at","base","by","cache_deleted","cached","called","capacity","cooldown","count","default","dimension","emitted","empty","error","explicit","field","filter_fields","for","formula","from_base","fx_pair","gap","has","hold","hydrates","hydration","implicit","initial","inputs","inverting","key","kwarg","latest","let","literal","logged","logical","max_limit","max_window","mutable","never","no","none","on","over","persist","produces","published","record_event","recorded","required","response","responses","retained","retracted","sample","sampled","scalar","scope","skip","sliding","storage","then","timeout","to","to_base","tolerance","ttl","tumbling","type","until","via","where","within","wm","zero","cache","cache_delete","call","emit","log","publish","withdraw","const","from","import","opaque","rule","schema","series","service","test","unit","use","and","contains","in","is","not","or","overlaps","nocooldown","retain"],typeKeywords:["Bool","Bytes","ComputationError","Date","Duration","Float","Int","Interval","Json","Schema","String","Time","TypeError"],constants:["false","inf","nan","NaN","null","true"],builtins:["abs","len","monotonic_ns","now","round","dwell","active_fraction","bool_and","bool_or","count_distinct","count_of","direction","first","integral","last","max","mean","median","min","onset_rate","pstdev","pvariance","rate","stdev","sum","variance"],tokenizer:{root:[[/#.*$/,"comment"],[/"""/,"string","@longString"],[/"/,"string","@string"],[/(~)(\s*)(\/(?:\\.|[^/\\\n])*\/)/,["operator","white","regexp"]],[Ns,"number.unit"],[Cs,"number"],[/->/,"keyword"],[/[\p{XID_Start}_]\p{XID_Continue}*/u,{cases:{"@keywords":"keyword","@typeKeywords":"type","@constants":"constant","@builtins":"predefined","~[\\p{Lu}\\p{Lt}].*":"type.identifier","@default":"identifier"}}]],string:[[/\{[^}]*\}/,"variable"],[/\\./,"string.escape"],[/"/,"string","@pop"],[/[^"\\{]+/,"string"]],longString:[[/"""/,"string","@pop"],[/[^"]+/,"string"],[/"/,"string"]]}},dr={comments:{lineComment:"#"},brackets:[["(",")"],["[","]"],["{","}"]],autoClosingPairs:[{open:"(",close:")"},{open:"[",close:"]"},{open:"{",close:"}"},{open:'"',close:'"'}]};function un(n){return n.languages.getLanguages().some(e=>e.id==="ds")||(n.languages.register({id:"ds",extensions:[".ds"],aliases:["DS","Desert Sage"]}),n.languages.setLanguageConfiguration("ds",dr),n.languages.setMonarchTokensProvider("ds",lr)),"ds"}var pn="ds";function fn(n,e){let t=Math.max(1,Math.min((e&&e.line)|0||1,n.getLineCount())),r=n.getLineContent(t),s=Array.from(r).slice(0,Math.max(0,((e&&e.column)|0)-1));return{lineNumber:t,column:s.join("").length+1}}function hn(n,e,t,r){return Tt(e,t).map(s=>{let i=fn(n,s.start||{line:1,column:1}),o=s.start?fn(n,s.end):i;if(o.lineNumber<i.lineNumber||o.lineNumber===i.lineNumber&&o.column<=i.column){let c=n.getLineContent(i.lineNumber).length+1;o={lineNumber:i.lineNumber,column:Math.min(i.column+1,c)},o.column===i.column&&i.column>1&&(i.column-=1)}let d={severity:s.severity==="warning"?r.Warning:r.Error,message:s.message,startLineNumber:i.lineNumber,startColumn:i.column,endLineNumber:o.lineNumber,endColumn:o.column};return s.code&&(d.code=s.code,d.source="dsc"),d})}function pr(n,e={}){return Dt(n,{editor:"ds-monaco-editor",...e})}var ur=new WeakMap,Re=n=>({line:n.lineNumber-1,character:n.column-1}),We=n=>({startLineNumber:n.start.line+1,startColumn:n.start.character+1,endLineNumber:n.end.line+1,endColumn:n.end.character+1}),fr=n=>n==null?void 0:typeof n=="string"?n:{value:n.value};function _s(n){let e=new Map,t=n.languages.CompletionItemKind,r={3:t.Function,5:t.Field,6:t.Variable,7:t.Class,9:t.Module,14:t.Keyword,21:t.Constant,22:t.Struct,24:t.Operator},s=(c,l,a)=>{let u=e.get(c.uri.toString());return u?u.ask(c.getValue(),l,a):Promise.resolve(null)};n.languages.registerCompletionItemProvider("ds",{triggerCharacters:[".",":"],async provideCompletionItems(c,l){let a=await s(c,"textDocument/completion",{position:Re(l)}),u=a&&(Array.isArray(a)?a:a.items)||[],m=c.getWordUntilPosition(l),w={startLineNumber:l.lineNumber,endLineNumber:l.lineNumber,startColumn:m.startColumn,endColumn:m.endColumn};return{suggestions:u.map(g=>({label:g.label,kind:r[g.kind]!==void 0?r[g.kind]:t.Text,detail:g.detail,documentation:fr(g.documentation),insertText:g.insertText||g.label,insertTextRules:g.insertTextFormat===2?n.languages.CompletionItemInsertTextRule.InsertAsSnippet:void 0,range:w}))}}}),n.languages.registerHoverProvider("ds",{async provideHover(c,l){let a=await s(c,"textDocument/hover",{position:Re(l)});if(!a||!a.contents)return null;let u=typeof a.contents=="string"?a.contents:a.contents.value;return u?{contents:[{value:u}],range:a.range?We(a.range):void 0}:null}}),n.languages.registerSignatureHelpProvider("ds",{signatureHelpTriggerCharacters:["(",","],async provideSignatureHelp(c,l){let a=await s(c,"textDocument/signatureHelp",{position:Re(l)});return!a||!a.signatures||!a.signatures.length?null:{value:{signatures:a.signatures.map(u=>({label:u.label,documentation:fr(u.documentation),parameters:(u.parameters||[]).map(m=>({label:m.label}))})),activeSignature:a.activeSignature||0,activeParameter:a.activeParameter||0},dispose(){}}}}),n.languages.registerDefinitionProvider("ds",{async provideDefinition(c,l){let a=e.get(c.uri.toString()),u=await s(c,"textDocument/definition",{position:Re(l)});return(Array.isArray(u)?u:u?[u]:[]).filter(w=>a&&w.uri===a.uri).map(w=>({uri:c.uri,range:We(w.range)}))}});let i=c=>({name:c.name,detail:c.detail,kind:Math.max(0,c.kind-1),tags:[],range:We(c.range),selectionRange:We(c.selectionRange),children:c.children.map(i)});n.languages.registerDocumentSymbolProvider("ds",{displayName:"ds lsp",async provideDocumentSymbols(c){let l=e.get(c.uri.toString()),a=await s(c,"textDocument/documentSymbol",{});return l?Lt(a,l.uri).map(i):[]}});let o={tokenTypes:[...st.tokenTypes],tokenModifiers:[...st.tokenModifiers]};n.languages.registerDocumentSemanticTokensProvider("ds",{getLegend:()=>o,async provideDocumentSemanticTokens(c){let l=await s(c,"textDocument/semanticTokens/full",{});return l&&Array.isArray(l.data)?{data:new Uint32Array(l.data)}:null},releaseDocumentSemanticTokens(){}}),n.languages.registerReferenceProvider("ds",{async provideReferences(c,l){let a=e.get(c.uri.toString()),u=await s(c,"textDocument/references",{position:Re(l),context:{includeDeclaration:!0}});return a?Mt(u,a.uri).map(m=>({uri:c.uri,range:We(m)})):[]}});let d=async(c,l,a)=>{let u=e.get(c.uri.toString());if(!u)return{error:"no language server"};let m=await u.request(c.getValue(),"textDocument/rename",{position:Re(l),newName:a});return!m||m.error?{error:m?m.error:"the language server did not answer"}:Rt(m.result,u.uri)};return n.languages.registerRenameProvider("ds",{async resolveRenameLocation(c,l){let a=c.getWordAtPosition(l);if(!a)return{range:We({start:Re(l),end:Re(l)}),text:"",rejectReason:"no name here"};let u={startLineNumber:l.lineNumber,startColumn:a.startColumn,endLineNumber:l.lineNumber,endColumn:a.endColumn},m=await d(c,l,a.word);return m.error?{range:u,text:a.word,rejectReason:`${a.word} is not renamed: ${m.error}`}:{range:u,text:a.word}},async provideRenameEdits(c,l,a){let u=await d(c,l,a);return u.error?{edits:[],rejectReason:u.error}:{edits:u.edits.map(m=>({resource:c.uri,versionId:void 0,textEdit:{range:We(m.range),text:m.newText}}))}}}),e}function mn(n,e,t,r={}){let s=ur.get(n);s||(s=_s(n),ur.set(n,s));let i=e.uri.toString(),o=pr(t,r);return s.set(i,o),{doc:o,dispose(){s.get(i)===o&&s.delete(i),o.close()}}}function hr(n,e,t,{file:r="rules.ds",delay:s=500,onClean:i}={}){let o=null,d=0,c=!1,l=async()=>{let u=++d,m=e.getValue(),w;try{w=hn(e,await t.diagnose(m),r,n.MarkerSeverity)}catch{return}c||u!==d||e.isDisposed()||(n.editor.setModelMarkers(e,pn,w),i&&!w.some(g=>g.severity===n.MarkerSeverity.Error)&&i(m))},a=e.onDidChangeContent(()=>{clearTimeout(o),o=setTimeout(l,s)});return o=setTimeout(l,0),{check:l,dispose(){c=!0,clearTimeout(o),a.dispose()}}}function Ss({monaco:n,parent:e,doc:t="",compiler:r,lsp:s,file:i="rules.ds",onChange:o,options:d={}}){let c=un(n),l=n.editor.createModel(t,c),a=n.editor.create(e,{model:l,automaticLayout:!0,minimap:{enabled:!1},tabSize:4,insertSpaces:!0,"semanticHighlighting.enabled":!0,...d}),u=[],m=s?mn(n,l,s):null;if(m&&u.push(m),r){let g=m?_=>m.doc.sync(_):void 0;u.push(hr(n,l,r,{file:i,onClean:g}))}o&&u.push(l.onDidChangeContent(()=>o(l.getValue())));let w=a.dispose.bind(a);return a.dispose=()=>{for(let g of u)g.dispose();w(),l.dispose()},a}var Fs=`
88
+ .ds-bp::before { content: '\u25CF'; color: var(--ds-code-bad, #cf222e); }
89
+ .ds-bp.unverified::before { color: var(--ds-code-soft, #8c959f); }
90
+ .ds-bp.logpoint::before { content: '\u25C6'; }
91
+ .ds-bp.conditional { font-weight: 700; }
92
+ .ds-stop { background: var(--ds-code-stop, rgba(255, 213, 0, 0.35)); }
93
+ .ds-debug-panel { padding: 4px 8px; font-family: var(--ds-code-font, monospace); max-height: 16em; overflow: auto; border-top: 1px solid var(--ds-view-border, #d0d7de); }
94
+ .ds-debug-panel button, .ds-debug-panel input, .ds-debug-panel select { font: inherit; }
95
+ .ds-debug-panel button { margin-right: 4px; }
96
+ .ds-debug-panel .ds-row { margin: 2px 0; }
97
+ .ds-debug-panel .ds-stopline { font-weight: 600; }
98
+ .ds-debug-panel .bad { color: var(--ds-code-bad, #cf222e); }
99
+ .ds-debug-panel ul, .ds-debug-panel ol { margin: 2px 0; padding-left: 1.5em; }
100
+ `;function Ts(n){if(!n.getElementById("ds-monaco-debug")){let e=n.createElement("style");e.id="ds-monaco-debug",e.textContent=Fs,n.head.appendChild(e)}}var mr=[["F5","continue","Continue"],["Shift+F5","reverseContinue","Reverse"],["F10","next","Step"],["Shift+F10","stepBack","Back"],["F11","stepIn","In"],["Shift+F11","stepOut","Out"],["F6","pause","Pause"],["Ctrl+Shift+F5","restart","Restart"]],gr=[["unanswered_call","Unanswered call"],["fault","Fault"],["engine_error","Engine error"]];function Ds(n,e,t,{panelParent:r}={}){let s=e.getContainerDomNode().ownerDocument;Ts(s),e.updateOptions({glyphMargin:!0});let i=e.getModel(),o=[],d=[],c=e.createDecorationsCollection([]),l=f=>{let y=i.getDecorationRange(f.id);return y?y.startLineNumber:null};function a(){d=i.deltaDecorations(d,o.map(f=>({range:new n.Range(f.line,1,f.line,1),options:{stickiness:n.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,glyphMarginClassName:`ds-bp${f.verified===!1?" unverified":""}${f.logMessage?" logpoint":""}${f.condition||f.hitCondition||f.logMessage?" conditional":""}`,glyphMarginHoverMessage:{value:f.verified===!1?f.message||"not verified":[f.condition&&`when ${f.condition}`,f.hitCondition&&`hit ${f.hitCondition}`,f.logMessage&&`log ${f.logMessage}`].filter(Boolean).join("; ")||"breakpoint"}}}))),o=o.map((f,y)=>({...f,id:d[y]}))}async function u(){o=o.map(y=>({...y,line:l(y)||y.line}));let f=await t.setLineBreakpoints(o.map(y=>({line:y.line,...y.condition?{condition:y.condition}:{},...y.hitCondition?{hitCondition:y.hitCondition}:{},...y.logMessage?{logMessage:y.logMessage}:{}})));return o=o.map((y,I)=>f[I]?{...y,dapId:f[I].id,verified:!!f[I].verified,message:f[I].message}:y),a(),f}async function m(f,y=null){o=o.map(k=>({...k,line:l(k)||k.line}));let I=o.find(k=>k.line===f);y?o=[...o.filter(k=>k.line!==f),{line:f,...y}]:o=I?o.filter(k=>k.line!==f):[...o,{line:f}],o.sort((k,F)=>k.line-F.line),a(),await u()}let w=f=>t.request(f),g=(f,y={},I=null,k=null)=>{let F=s.createElement(f);for(let[Ue,Ke]of Object.entries(y))F.setAttribute(Ue,String(Ke));return k!==null&&(F.textContent=k),I&&I.append(F),F},_=g("div",{class:"ds-debug-panel","aria-label":"debugger"});r?r.append(_):e.getContainerDomNode().after(_);let A=g("div",{class:"ds-stopline"},_,"Not stopped yet."),V=g("div",{class:"ds-debugnote"},_),S=(f,y=!1)=>{V.textContent=f,V.className=y?"ds-debugnote bad":"ds-debugnote"},R=(f,y)=>(f.success||S(`${y}: ${f.message||"refused"}`,!0),f),T=g("form",{class:"ds-row ds-bpedit",hidden:""},_),U=g("span",{},T),W=g("input",{name:"condition",placeholder:"when (DS expression)",size:22},T),q=g("input",{name:"hitCondition",placeholder:"hit (5, >= 3)",size:8},T),re=g("input",{name:"logMessage",placeholder:"log message (level={r.level})",size:22},T);g("button",{type:"submit"},T,"Set");let Y=null,le=f=>{let y=o.find(I=>I.line===f)||{};Y=f,U.textContent=`Line ${f}: `,W.value=y.condition||"",q.value=y.hitCondition||"",re.value=y.logMessage||"",T.hidden=!1,W.focus()};T.addEventListener("submit",async f=>{f.preventDefault();let y=Y;T.hidden=!0,await m(y,{...W.value?{condition:W.value}:{},...q.value?{hitCondition:q.value}:{},...re.value?{logMessage:re.value}:{}})}),T.addEventListener("keydown",f=>{f.key==="Escape"&&(f.preventDefault(),T.hidden=!0,e.focus())});let Z=g("div",{class:"ds-row ds-controls"},_);for(let[f,y,I]of mr)g("button",{type:"button","data-command":y,title:f},Z,I).addEventListener("click",async()=>{R(await w(y),I)});let se=g("select",{"aria-label":"step granularity"},Z);for(let f of["action","rule","pump","input"])g("option",{value:f},se,f);se.addEventListener("change",async()=>{let f=R(await t.request("ds/stepGranularity",{granularity:se.value}),"Granularity");f.success&&f.body&&(se.value=f.body.granularity)});let ve=g("button",{type:"button",class:"ds-goto"},Z,"Go to\u2026"),ge=g("button",{type:"button",class:"ds-into",title:"step in to a firing the action caused"},Z,"Into\u2026"),ie=g("ul",{class:"ds-targets"},_);ge.addEventListener("click",async()=>{ie.textContent="";let f=await t.stepInTargets();if(!f.length){S("The action here caused no firing.");return}for(let y of f)g("li",{"data-step-target":y.id},ie,y.label).addEventListener("click",async()=>{ie.textContent="",R(await t.stepInto(y.id),"Into")})}),ve.addEventListener("click",async()=>{ie.textContent="";let f=e.getPosition().lineNumber,y=R(await t.request("gotoTargets",{source:{path:"rules.ds"},line:f}),"Go to");if(y.success){y.body.targets.length||S(`No recorded instant of line ${f}.`);for(let I of y.body.targets)g("li",{"data-target":I.id},ie,I.label).addEventListener("click",async()=>{ie.textContent="",R(await t.request("goto",{threadId:t.state.stopped&&t.state.stopped.threadId||1,targetId:I.id}),"Go to")})}});let de=g("form",{class:"ds-row ds-functions"},_);g("span",{},de,"Rules ");let ye=g("input",{name:"functions",placeholder:"rule, rule",size:24},de);g("button",{type:"submit"},de,"Break on"),de.addEventListener("submit",async f=>{f.preventDefault();let y=ye.value.split(",").map(k=>k.trim()).filter(Boolean),I=R(await t.request("setFunctionBreakpoints",{breakpoints:y.map(k=>({name:k}))}),"Rule breakpoints");if(I.success){let k=I.body.breakpoints.filter(F=>!F.verified);S(k.length?k.map(F=>F.message).join("; "):`Breaking on ${y.length} rule(s).`,!!k.length)}});let X=g("form",{class:"ds-row ds-facts"},_);g("span",{},X,"Facts ");let Q=g("input",{name:"schema",placeholder:"schema",size:10},X),Ee=g("input",{type:"checkbox",name:"assert",checked:""},X);g("span",{},X,"assert ");let $e=g("input",{type:"checkbox",name:"retract"},X);g("span",{},X,"retract ");let oe=g("input",{name:"where",placeholder:"where (optional)",size:18},X);g("button",{type:"submit"},X,"Break on"),X.addEventListener("submit",async f=>{f.preventDefault();let y=[Ee.checked&&"assert",$e.checked&&"retract"].filter(Boolean),I={schema:Q.value,on:y,...oe.value?{where:oe.value}:{}},k=R(await t.request("ds/setFactBreakpoints",{breakpoints:Q.value?[I]:[]}),"Fact breakpoint");if(k.success){let[F]=k.body.breakpoints;S(F?F.verified?`Breaking on ${I.schema} ${y.join(" and ")}.`:F.message:"No fact breakpoint.",!!(F&&!F.verified))}});let K=g("form",{class:"ds-row ds-cache"},_);g("span",{},K,"Cache ");let ue=g("input",{name:"key",placeholder:"key (empty: any)",size:14},K),M={};for(let f of["get","set","delete"])M[f]=g("input",{type:"checkbox",name:f,...f==="get"?{}:{checked:""}},K),g("span",{},K,`${f} `);g("button",{type:"submit"},K,"Break on"),K.addEventListener("submit",async f=>{f.preventDefault();let y=Object.keys(M).filter(k=>M[k].checked),I=R(await t.request("ds/setCacheBreakpoints",{breakpoints:[{key:ue.value,on:y}]}),"Cache breakpoint");if(I.success){let[k]=I.body.breakpoints;S(k&&!k.verified?k.message:`Breaking on cache ${y.join(", ")}.`,!!(k&&!k.verified))}});let b=g("div",{class:"ds-row ds-exceptions"},_);g("span",{},b,"Stop on ");for(let[f,y]of gr){let I=g("input",{type:"checkbox",name:f,...f==="engine_error"?{checked:""}:{}},b);g("span",{},b,`${y} `),I.addEventListener("change",async()=>{let k=gr.map(([F])=>F).filter(F=>b.querySelector(`input[name="${F}"]`).checked);R(await t.request("setExceptionBreakpoints",{filters:k}),"Exception breakpoints")})}let B=g("ol",{class:"ds-output","aria-label":"output"},_);async function O(){let f=t.state.stopped,y=null,I="";if(f&&f.threadId!==void 0){let k=await t.request("stackTrace",{threadId:f.threadId,levels:1}),F=k.success&&k.body.stackFrames.length?k.body.stackFrames[0]:null;F&&F.line&&(y=F.line,I=` at line ${F.line} (${F.name})`)}c.set(y?[{range:new n.Range(y,1,y,1),options:{isWholeLine:!0,className:"ds-stop"}}]:[]),y&&(e.setPosition({lineNumber:y,column:1}),e.revealLineInCenterIfOutsideViewport(y)),A.textContent=t.state.ended?t.state.ended:f?`Stopped: ${f.reason}${f.description?`, ${f.description}`:""}${I}.`:"Not stopped yet.",B.textContent="";for(let k of t.state.output.slice(-20))g("li",{class:k.category},B,k.output.replace(/\n$/,""))}let j=e.onMouseDown(f=>{if(f.target.type!==n.editor.MouseTargetType.GUTTER_GLYPH_MARGIN||!f.target.position)return;let y=f.target.position.lineNumber;f.event.altKey||f.event.shiftKey?le(y):m(y)}),P=n.KeyCode,ae=n.KeyMod,ee={F5:P.F5,F6:P.F6,F10:P.F10,F11:P.F11},Ne={Shift:ae.Shift,Ctrl:ae.CtrlCmd};for(let[f,y]of mr){let I=f.split("+"),k=ee[I.pop()];e.addCommand(I.reduce((F,Ue)=>F|Ne[Ue],0)|k,()=>{w(y)})}async function be(f,y){let I=t.state;if(!I.stopped||I.ended)return null;let k=an(i.getLineContent(f),y-1);if(!k)return null;let F=await cn(t,k.expression);return F===null?null:{line:f,from:k.from+1,to:k.to+1,text:F}}let v=n.languages.registerHoverProvider(i.getLanguageId(),{async provideHover(f,y){if(f!==i)return null;let I=await be(y.lineNumber,y.column);return I?{range:new n.Range(I.line,I.from,I.line,I.to),contents:[{value:`\`\`\`
101
+ ${I.text}
102
+ \`\`\``}]}:null}}),N=!1,G=t.listen((f,y)=>{if(f==="event"&&y.event==="breakpoint"&&y.body&&y.body.breakpoint){let I=y.body.breakpoint;o.some(k=>k.dapId===I.id)&&(o=y.body.reason==="removed"?o.filter(k=>k.dapId!==I.id):o.map(k=>k.dapId===I.id?{...k,line:l(k)||k.line,verified:!!I.verified,message:I.message}:k),a())}f==="event"&&(y.event==="stopped"||y.event==="terminated"||y.event==="output")&&(N=!0),f==="answer"&&N&&(N=!1,O())});return{toggle:m,sync:u,step:w,refresh:O,hoverAt:be,breakpoints:()=>o.map(f=>({...f,line:l(f)||f.line})),dispose(){G(),v.dispose(),j.dispose(),d=i.deltaDecorations(d,[]),c.clear(),_.remove()}}}export{In as CATCH_UP,xt as ChangesView,Ae as DS_LANGUAGE_ID,dn as EVENT_KINDS,Bn as LSP_METHODS,pn as MARKER_OWNER,yt as MemoryView,Ge as NetworkView,wt as PumpsView,it as Replayer,st as SEMANTIC_LEGEND,gt as TimelineView,bt as TimersView,kt as addViewStyle,Ot as changesBetween,As as createDebugInspector,ln as createDebugVariables,Ss as createEditor,vs as createInspector,Xe as cutAt,cr as dapEventText,Sr as dapSession,Lt as documentSymbols,Ds as dsDebugger,Tt as dsDiagnostics,dr as dsLanguageConfiguration,hr as dsLinter,mn as dsLsp,lr as dsMonarch,jt as engineAt,vt as evaluateAt,ot as eventText,an as expressionAt,Ce as factText,Gt as factsOf,cn as hoverText,Mt as localRanges,Rt as localRename,pr as lspDocument,Pt as memoryAt,Dr as networkAt,ys as openDs,fn as positionOf,dt as pumpsOf,Ut as readRecording,qt as refractedOf,un as registerDsLanguage,zt as rerun,ut as reteOf,De as secondsText,Fr as semanticTokens,me as slotsText,_r as startBrowserLsp,Ar as startCompiler,Ye as startOf,Vt as timersAt,hn as toMonacoMarkers,sr as topFrame,Cn as valueText,Ht as whyOf};
103
+ //# sourceMappingURL=ds-monaco-editor.js.map