@abraca/orchestrator 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abracadabra-orchestrator.esm.js","names":["u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H"],"sources":["../../../node_modules/@noble/hashes/utils.js","../../../node_modules/@noble/hashes/_md.js","../../../node_modules/@noble/hashes/_u64.js","../../../node_modules/@noble/hashes/sha2.js","../src/crypto.ts","../src/utils.ts","../src/yjs-utils.ts","../src/actor-connection.ts","../src/timeline-runner.ts","../src/actions/connect.ts","../src/actions/navigate.ts","../src/actions/type.ts","../src/easing.ts","../src/actions/cursor.ts","../src/converters/markdownToYjs.ts","../src/actions/content.ts","../src/actions/awareness.ts","../src/actions/document.ts","../src/actions/chat.ts","../src/actions/flow.ts","../src/actions/index.ts","../src/orchestrator.ts","../src/define.ts","../src/index.ts"],"sourcesContent":["/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n }\n return value;\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1)\n throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1)\n throw new Error('\"blockLen\" must be >= 1');\n}\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async () => { };\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n//# sourceMappingURL=sha2.js.map","/**\n * Ed25519 key generation, persistence, and challenge signing for actor auth.\n * Copied from packages/mcp/src/crypto.ts\n */\nimport * as ed from '@noble/ed25519'\nimport { sha512 } from '@noble/hashes/sha2.js'\nimport { readFile, writeFile, mkdir } from 'node:fs/promises'\n\n// @noble/ed25519 v3 hash hook\ned.hashes.sha512 = sha512\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m))\nimport { existsSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\nfunction toBase64url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url')\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n return new Uint8Array(Buffer.from(b64, 'base64url'))\n}\n\nexport interface AgentKeypair {\n privateKey: Uint8Array\n publicKeyB64: string\n}\n\n/**\n * Load an existing Ed25519 keypair from disk, or generate and persist a new one.\n */\nexport async function loadOrCreateKeypair(keyPath: string): Promise<AgentKeypair> {\n if (existsSync(keyPath)) {\n const seed = await readFile(keyPath)\n if (seed.length !== 32) {\n throw new Error(`Invalid key file at ${keyPath}: expected 32 bytes, got ${seed.length}`)\n }\n const privateKey = new Uint8Array(seed)\n const publicKey = ed.getPublicKey(privateKey)\n return { privateKey, publicKeyB64: toBase64url(publicKey) }\n }\n\n const privateKey = ed.utils.randomSecretKey()\n const publicKey = ed.getPublicKey(privateKey)\n\n const dir = dirname(keyPath)\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true, mode: 0o700 })\n }\n await writeFile(keyPath, Buffer.from(privateKey), { mode: 0o600 })\n\n console.error(`[orchestrator] Generated new keypair at ${keyPath}`)\n return { privateKey, publicKeyB64: toBase64url(publicKey) }\n}\n\n/**\n * Generate a deterministic Ed25519 keypair from a seed string (e.g. actor name).\n * The same seed always produces the same keypair.\n */\nexport function deterministicKeypair(seed: string): AgentKeypair {\n const hash = sha512(new TextEncoder().encode(seed + ':orchestrator-salt'))\n const privateKey = hash.slice(0, 32)\n const publicKey = ed.getPublicKey(privateKey)\n return { privateKey, publicKeyB64: toBase64url(publicKey) }\n}\n\n/** Sign a base64url challenge with the agent's private key; returns base64url signature. */\nexport function signChallenge(challengeB64: string, privateKey: Uint8Array): string {\n const challenge = fromBase64url(challengeB64)\n const sig = ed.sign(challenge, privateKey)\n return toBase64url(sig)\n}\n","/**\n * Utility functions for the orchestrator.\n */\n\n/** Wait for a provider's `synced` event with a timeout. Resolves immediately if already synced. */\nexport function waitForSync(\n provider: { on(event: string, cb: () => void): void; off(event: string, cb: () => void): void; synced?: boolean },\n timeoutMs = 15000\n): Promise<void> {\n // If already synced, resolve immediately\n if (provider.synced) return Promise.resolve()\n\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n provider.off('synced', handler)\n reject(new Error(`Sync timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n\n function handler() {\n clearTimeout(timer)\n resolve()\n }\n\n provider.on('synced', handler)\n })\n}\n\n/** Sleep for a given number of milliseconds. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\n/** Wraps a promise with a timeout. */\nexport function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message?: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)),\n timeoutMs\n )\n promise.then(\n (val) => { clearTimeout(timer); resolve(val) },\n (err) => { clearTimeout(timer); reject(err) }\n )\n })\n}\n\n/** Log to stderr with [orchestrator] prefix. */\nexport function log(msg: string): void {\n console.error(`[orchestrator] ${msg}`)\n}\n","/**\n * Y.js document structure utilities for TipTap-compatible editing.\n *\n * TipTap documents have the structure:\n * XmlFragment('default') → [documentHeader, documentMeta, ...body paragraphs]\n *\n * All text position functions skip documentHeader and documentMeta —\n * character index 0 maps to the first character of the first body paragraph.\n */\nimport * as Y from 'yjs'\n\nconst SCHEMA_NODES = new Set(['documentHeader', 'documentMeta'])\n\n/** Check if an XmlElement is a TipTap schema node (not body content). */\nfunction isSchemaNode(el: Y.XmlElement): boolean {\n return SCHEMA_NODES.has(el.nodeName)\n}\n\n/**\n * Ensure the fragment has documentHeader and documentMeta nodes.\n * Creates them if missing. Idempotent — safe to call multiple times.\n */\nexport function ensureDocumentStructure(fragment: Y.XmlFragment): void {\n let hasHeader = false\n let hasMeta = false\n\n for (let i = 0; i < fragment.length; i++) {\n const child = fragment.get(i)\n if (child instanceof Y.XmlElement) {\n if (child.nodeName === 'documentHeader') hasHeader = true\n if (child.nodeName === 'documentMeta') hasMeta = true\n }\n }\n\n // Insert in reverse order so indices stay correct\n if (!hasMeta) {\n const meta = new Y.XmlElement('documentMeta')\n fragment.insert(hasHeader ? 1 : 0, [meta])\n }\n if (!hasHeader) {\n const header = new Y.XmlElement('documentHeader')\n fragment.insert(0, [header])\n }\n}\n\n/**\n * Find the index where body content starts (after documentHeader + documentMeta).\n */\nexport function bodyStartIndex(fragment: Y.XmlFragment): number {\n let idx = 0\n for (let i = 0; i < fragment.length; i++) {\n const child = fragment.get(i)\n if (child instanceof Y.XmlElement && isSchemaNode(child)) {\n idx = i + 1\n } else {\n break\n }\n }\n return idx\n}\n\n/**\n * Walk the XmlFragment body (skipping schema nodes) to find the XmlText node\n * and local offset for a given global character index.\n */\nexport function findTextPosition(\n fragment: Y.XmlFragment,\n globalIndex: number\n): { text: Y.XmlText; offset: number } | null {\n let consumed = 0\n for (let i = 0; i < fragment.length; i++) {\n const child = fragment.get(i)\n if (child instanceof Y.XmlElement) {\n if (isSchemaNode(child)) continue\n const result = findTextInElement(child, globalIndex - consumed)\n if (result) return result\n consumed += elementTextLength(child)\n }\n }\n return null\n}\n\nfunction findTextInElement(\n el: Y.XmlElement,\n remaining: number\n): { text: Y.XmlText; offset: number } | null {\n for (let i = 0; i < el.length; i++) {\n const child = el.get(i)\n if (child instanceof Y.XmlText) {\n if (remaining <= child.length) {\n return { text: child, offset: remaining }\n }\n remaining -= child.length\n } else if (child instanceof Y.XmlElement) {\n const result = findTextInElement(child, remaining)\n if (result) return result\n remaining -= elementTextLength(child)\n }\n }\n return null\n}\n\n/** Total text length of an XmlElement (recursive). */\nexport function elementTextLength(el: Y.XmlElement): number {\n let len = 0\n for (let i = 0; i < el.length; i++) {\n const child = el.get(i)\n if (child instanceof Y.XmlText) {\n len += child.length\n } else if (child instanceof Y.XmlElement) {\n len += elementTextLength(child)\n }\n }\n return len\n}\n\n/** Total text length of all body paragraphs (skips schema nodes). */\nexport function fragmentTextLength(fragment: Y.XmlFragment): number {\n let len = 0\n for (let i = 0; i < fragment.length; i++) {\n const child = fragment.get(i)\n if (child instanceof Y.XmlElement && !isSchemaNode(child)) {\n len += elementTextLength(child)\n }\n }\n return len\n}\n\n/**\n * Compute the global character index of a position within a known XmlText node.\n * Re-derives from current document state — safe under concurrent edits.\n * Only counts body content (skips schema nodes).\n */\nexport function globalIndexOf(\n fragment: Y.XmlFragment,\n targetText: Y.XmlText,\n localOffset: number\n): number {\n let index = 0\n for (let i = 0; i < fragment.length; i++) {\n const child = fragment.get(i)\n if (child instanceof Y.XmlElement) {\n if (isSchemaNode(child)) continue\n const result = globalIndexInElement(child, targetText, localOffset, index)\n if (result !== null) return result\n index += elementTextLength(child)\n }\n }\n return index + localOffset // fallback\n}\n\nfunction globalIndexInElement(\n el: Y.XmlElement,\n targetText: Y.XmlText,\n localOffset: number,\n base: number\n): number | null {\n for (let i = 0; i < el.length; i++) {\n const child = el.get(i)\n if (child instanceof Y.XmlText) {\n if (child === targetText) {\n return base + localOffset\n }\n base += child.length\n } else if (child instanceof Y.XmlElement) {\n const result = globalIndexInElement(child, targetText, localOffset, base)\n if (result !== null) return result\n base += elementTextLength(child)\n }\n }\n return null\n}\n\n/**\n * Get or create the last body paragraph's XmlText.\n * Skips documentHeader and documentMeta. Creates a new paragraph if none exist.\n */\nexport function getOrCreateLastParagraph(\n fragment: Y.XmlFragment\n): { text: Y.XmlText; globalOffset: number } {\n // Search backwards for the last body paragraph\n for (let i = fragment.length - 1; i >= 0; i--) {\n const child = fragment.get(i)\n if (child instanceof Y.XmlElement) {\n if (isSchemaNode(child)) continue\n if (child.nodeName === 'paragraph') {\n for (let j = child.length - 1; j >= 0; j--) {\n const grandchild = child.get(j)\n if (grandchild instanceof Y.XmlText) {\n return { text: grandchild, globalOffset: fragmentTextLength(fragment) }\n }\n }\n // Paragraph exists but has no XmlText — add one\n const xt = new Y.XmlText()\n child.insert(0, [xt])\n return { text: xt, globalOffset: fragmentTextLength(fragment) }\n }\n }\n }\n\n // No body paragraph found — create one after schema nodes\n const para = new Y.XmlElement('paragraph')\n const xt = new Y.XmlText()\n para.insert(0, [xt])\n fragment.push([para])\n return { text: xt, globalOffset: 0 }\n}\n\n/**\n * Insert a new paragraph after the one containing the given global character index.\n * Skips schema nodes when computing positions.\n */\nexport function insertParagraphAfter(\n fragment: Y.XmlFragment,\n afterGlobalIndex: number\n): Y.XmlText {\n let offset = 0\n let insertAt = fragment.length\n\n for (let i = 0; i < fragment.length; i++) {\n const child = fragment.get(i)\n if (child instanceof Y.XmlElement) {\n if (isSchemaNode(child)) continue\n const elLen = elementTextLength(child)\n if (offset + elLen >= afterGlobalIndex) {\n insertAt = i + 1\n break\n }\n offset += elLen\n }\n }\n\n const para = new Y.XmlElement('paragraph')\n const xt = new Y.XmlText()\n para.insert(0, [xt])\n fragment.insert(insertAt, [para])\n return xt\n}\n","/**\n * ActorConnection — manages a single actor's connection to the Abracadabra server.\n * One instance per actor. Handles auth, providers, child caching, awareness, and cursors.\n */\nimport * as Y from 'yjs'\nimport { AbracadabraProvider, AbracadabraClient } from '@abraca/dabra'\nimport type { ActorDef, ServerConfig } from './types.ts'\nimport { loadOrCreateKeypair, deterministicKeypair, signChallenge } from './crypto.ts'\nimport { waitForSync, sleep, log } from './utils.ts'\nimport { findTextPosition, fragmentTextLength } from './yjs-utils.ts'\n\ninterface CachedChild {\n provider: AbracadabraProvider\n lastAccessed: number\n}\n\nexport class ActorConnection {\n readonly actor: ActorDef\n readonly client: AbracadabraClient\n private _rootDocId: string | null = null\n private _rootDoc: Y.Doc | null = null\n private _rootProvider: AbracadabraProvider | null = null\n private _publicKey: string | null = null\n private _childCache = new Map<string, CachedChild>()\n\n constructor(actor: ActorDef, serverConfig: ServerConfig) {\n this.actor = actor\n // AbracadabraClient expects an HTTP(S) URL — normalize ws(s):// if provided\n const httpUrl = serverConfig.url\n .replace(/^wss:\\/\\//, 'https://')\n .replace(/^ws:\\/\\//, 'http://')\n this.client = new AbracadabraClient({ url: httpUrl })\n }\n\n get rootProvider(): AbracadabraProvider | null {\n return this._rootProvider\n }\n\n get rootDocId(): string | null {\n return this._rootDocId\n }\n\n /** Connect, authenticate, discover root doc, sync, and set awareness. */\n async connect(serverConfig: ServerConfig): Promise<void> {\n // Step 1: Get keypair (from file or deterministic from name)\n const keypair = this.actor.keyFile\n ? await loadOrCreateKeypair(this.actor.keyFile)\n : deterministicKeypair(this.actor.name)\n this._publicKey = keypair.publicKeyB64\n const signFn = (challenge: string) =>\n Promise.resolve(signChallenge(challenge, keypair.privateKey))\n\n // Step 2: Auth (auto-register on first run)\n try {\n await this.client.loginWithKey(keypair.publicKeyB64, signFn)\n } catch (err: any) {\n const status = err?.status ?? err?.response?.status\n if (status === 404 || status === 422) {\n log(`${this.actor.name}: registering new account...`)\n await this.client.registerWithKey({\n publicKey: keypair.publicKeyB64,\n username: this.actor.name.replace(/\\s+/g, '-').toLowerCase(),\n displayName: this.actor.name,\n deviceName: 'Orchestrator Actor',\n inviteCode: serverConfig.inviteCode,\n })\n await this.client.loginWithKey(keypair.publicKeyB64, signFn)\n } else {\n throw err\n }\n }\n log(`${this.actor.name}: authenticated (${keypair.publicKeyB64.slice(0, 12)}...)`)\n\n // Step 3: Pick an entry-point doc — first Space under the server root,\n // falling back to the first top-level doc of any kind.\n const roots = await this.client.listChildren()\n const firstSpace = roots.find((d) => d.kind === 'space')\n const rootDocId = (firstSpace ?? roots[0])?.id ?? null\n\n if (!rootDocId) {\n throw new Error(`${this.actor.name}: no root document found`)\n }\n this._rootDocId = rootDocId\n\n // Step 4: Connect provider\n const doc = new Y.Doc({ guid: rootDocId })\n const provider = new AbracadabraProvider({\n name: rootDocId,\n document: doc,\n client: this.client,\n disableOfflineStore: true,\n subdocLoading: 'lazy',\n })\n await waitForSync(provider)\n\n this._rootDoc = doc\n this._rootProvider = provider\n\n // Step 5: Set awareness — actors appear as humans (isAgent: false)\n provider.awareness.setLocalStateField('user', {\n name: this.actor.name,\n color: this.actor.color,\n publicKey: this._publicKey,\n isAgent: false,\n })\n provider.awareness.setLocalStateField('status', null)\n\n log(`${this.actor.name}: connected to space ${rootDocId}`)\n }\n\n /** Get or create a child provider for a document. Caches and sets awareness. */\n async getChildProvider(docId: string): Promise<AbracadabraProvider> {\n const cached = this._childCache.get(docId)\n if (cached) {\n cached.lastAccessed = Date.now()\n return cached.provider\n }\n\n if (!this._rootProvider) {\n throw new Error(`${this.actor.name}: not connected`)\n }\n\n const childProvider = await this._rootProvider.loadChild(docId)\n await waitForSync(childProvider)\n\n childProvider.awareness.setLocalStateField('user', {\n name: this.actor.name,\n color: this.actor.color,\n publicKey: this._publicKey,\n isAgent: false,\n })\n\n this._childCache.set(docId, {\n provider: childProvider,\n lastAccessed: Date.now(),\n })\n\n return childProvider\n }\n\n /**\n * Set cursor position in a document (collapsed — anchor = head).\n *\n * TipTap's yCursorPlugin reads awareness field 'cursor' as\n * { anchor: RelativePosJSON, head: RelativePosJSON }.\n * Positions must point into XmlText nodes (not the fragment) with assoc=-1.\n */\n setCursor(docId: string, index: number): void {\n const cached = this._childCache.get(docId)\n if (!cached) return\n\n const fragment = cached.provider.document.getXmlFragment('default')\n const relPos = this._charIndexToRelativePosition(fragment, index)\n if (!relPos) return\n\n const json = Y.relativePositionToJSON(relPos)\n cached.provider.awareness.setLocalStateField('cursor', {\n anchor: json,\n head: json,\n })\n }\n\n /** Set text selection range in a document (anchor != head). */\n setSelection(docId: string, anchor: number, head: number): void {\n const cached = this._childCache.get(docId)\n if (!cached) return\n\n const fragment = cached.provider.document.getXmlFragment('default')\n const anchorPos = this._charIndexToRelativePosition(fragment, anchor)\n const headPos = this._charIndexToRelativePosition(fragment, head)\n if (!anchorPos || !headPos) return\n\n cached.provider.awareness.setLocalStateField('cursor', {\n anchor: Y.relativePositionToJSON(anchorPos),\n head: Y.relativePositionToJSON(headPos),\n })\n }\n\n /**\n * Convert a character index (body text only, skipping schema nodes)\n * to a Y.js RelativePosition pointing into the correct XmlText node.\n * Uses assoc=-1 (associate-left) to match TipTap's cursor behavior.\n */\n private _charIndexToRelativePosition(\n fragment: Y.XmlFragment,\n charIndex: number\n ): Y.RelativePosition | null {\n const totalLen = fragmentTextLength(fragment)\n const clamped = Math.max(0, Math.min(charIndex, totalLen))\n\n if (clamped === 0) {\n // Position at start of fragment — use assoc=-1 on the fragment itself\n return Y.createRelativePositionFromTypeIndex(fragment, 0, -1)\n }\n\n const pos = findTextPosition(fragment, clamped)\n if (pos) {\n return Y.createRelativePositionFromTypeIndex(pos.text, pos.offset, -1)\n }\n\n // Fallback: end of fragment\n return Y.createRelativePositionFromTypeIndex(fragment, fragment.length, -1)\n }\n\n /** Set a field on root awareness. */\n setRootAwareness(field: string, value: unknown): void {\n this._rootProvider?.awareness.setLocalStateField(field, value)\n }\n\n /** Set a field on a child document's awareness. */\n setChildAwareness(docId: string, field: string, value: unknown): void {\n const cached = this._childCache.get(docId)\n cached?.provider.awareness.setLocalStateField(field, value)\n }\n\n /** Disconnect and clean up all providers. */\n async disconnect(): Promise<void> {\n // Clear awareness on children\n for (const [, cached] of this._childCache) {\n cached.provider.awareness.setLocalStateField('cursor', null)\n }\n\n // Clear root awareness\n if (this._rootProvider) {\n this._rootProvider.awareness.setLocalStateField('status', null)\n this._rootProvider.awareness.setLocalStateField('docId', null)\n }\n\n // Wait for awareness updates to propagate before destroying\n await sleep(150)\n\n for (const [, cached] of this._childCache) {\n cached.provider.destroy()\n }\n this._childCache.clear()\n\n if (this._rootProvider) {\n this._rootProvider.destroy()\n this._rootProvider = null\n }\n this._rootDoc = null\n this._rootDocId = null\n\n log(`${this.actor.name}: disconnected`)\n }\n}\n","/**\n * TimelineRunner — schedules and executes timed actions with drift correction.\n */\nimport type { TimelineEntry } from './types.ts'\nimport type { ActionExecutor } from './actions/index.ts'\nimport { sleep, log } from './utils.ts'\n\nexport type ErrorStrategy = 'log' | 'abort'\n\nexport interface TimelineRunnerOptions {\n /** How to handle action errors. 'log' continues, 'abort' stops. Default: 'log'. */\n onError?: ErrorStrategy\n}\n\nexport class TimelineRunner {\n private sceneStartTime = 0\n private options: TimelineRunnerOptions\n readonly errors: { entry: TimelineEntry; error: Error; elapsed: number }[] = []\n\n constructor(options?: TimelineRunnerOptions) {\n this.options = options ?? {}\n }\n\n /** Get elapsed ms since scene start. */\n get elapsed(): number {\n return Date.now() - this.sceneStartTime\n }\n\n /** Execute all timeline entries in order with proper timing. */\n async run(timeline: TimelineEntry[], execute: ActionExecutor): Promise<void> {\n const sorted = [...timeline].sort((a, b) => (a.at ?? 0) - (b.at ?? 0))\n const errorStrategy = this.options.onError ?? 'log'\n\n this.sceneStartTime = Date.now()\n const pending: Promise<void>[] = []\n\n for (let i = 0; i < sorted.length; i++) {\n const entry = sorted[i]!\n const targetTime = entry.at ?? 0\n const elapsed = Date.now() - this.sceneStartTime\n const delay = targetTime - elapsed\n\n if (delay > 0) {\n await sleep(delay)\n }\n\n // Log progress\n const ts = `${((Date.now() - this.sceneStartTime) / 1000).toFixed(1)}s`\n const actorLabel = entry.actor ?? '—'\n log(`[${ts}] ${actorLabel}: ${entry.action.type}`)\n\n const actionPromise = execute(entry).catch((err: Error) => {\n const errorInfo = {\n entry,\n error: err,\n elapsed: Date.now() - this.sceneStartTime,\n }\n this.errors.push(errorInfo)\n log(`Error in ${entry.action.type}${entry.actor ? ` for ${entry.actor}` : ''}: ${err.message}`)\n if (errorStrategy === 'abort') {\n throw err\n }\n })\n\n // Check if the next entry has the same timestamp — if so, run in parallel\n const nextEntry = sorted[i + 1]\n if (nextEntry && (nextEntry.at ?? 0) === targetTime) {\n pending.push(actionPromise)\n } else {\n pending.push(actionPromise)\n await Promise.all(pending)\n pending.length = 0\n }\n }\n\n if (pending.length) {\n await Promise.all(pending)\n }\n\n if (this.errors.length) {\n log(`Timeline finished with ${this.errors.length} error(s)`)\n }\n }\n}\n","/**\n * Connect / disconnect actions.\n */\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type { ServerConfig } from '../types.ts'\n\nexport async function executeConnect(\n actor: ActorConnection,\n serverConfig: ServerConfig\n): Promise<void> {\n await actor.connect(serverConfig)\n}\n\nexport async function executeDisconnect(actor: ActorConnection): Promise<void> {\n await actor.disconnect()\n}\n","/**\n * Navigate action — sets which document an actor is viewing.\n */\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type { NavigateAction } from '../types.ts'\n\nexport async function executeNavigate(\n actor: ActorConnection,\n action: NavigateAction\n): Promise<void> {\n // Set docId in root awareness (this is what the dashboard watches for presence)\n actor.setRootAwareness('docId', action.docId)\n // Pre-load the child provider so subsequent actions on this doc are fast\n await actor.getChildProvider(action.docId)\n}\n","/**\n * Typewriter action — character-by-character text insertion with live cursor.\n *\n * TipTap Y.js structure: XmlFragment('default') contains:\n * [documentHeader, documentMeta, ...body blocks]\n * Each paragraph is an XmlElement('paragraph') containing XmlText nodes.\n *\n * All character indices are relative to body content only (schema nodes skipped).\n *\n * TypeDelete action — backspace simulation, deletes characters one at a time.\n */\nimport * as Y from 'yjs'\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type { TypeAction, TypeDeleteAction } from '../types.ts'\nimport { sleep } from '../utils.ts'\nimport {\n ensureDocumentStructure,\n findTextPosition,\n fragmentTextLength,\n getOrCreateLastParagraph,\n insertParagraphAfter,\n globalIndexOf,\n} from '../yjs-utils.ts'\n\nexport async function executeType(\n actor: ActorConnection,\n action: TypeAction\n): Promise<void> {\n const speed = action.speed ?? 80\n const variance = action.variance ?? 30\n const provider = await actor.getChildProvider(action.docId)\n const doc = provider.document\n const fragment = doc.getXmlFragment('default')\n\n // Ensure TipTap schema nodes exist\n doc.transact(() => ensureDocumentStructure(fragment))\n\n // Determine starting position\n const startIndex = action.position ?? fragmentTextLength(fragment)\n\n // Find the XmlText node at the starting position\n let currentText: Y.XmlText\n let currentLocalOffset: number\n\n const pos = findTextPosition(fragment, startIndex)\n if (pos) {\n currentText = pos.text\n currentLocalOffset = pos.offset\n } else {\n const last = getOrCreateLastParagraph(fragment)\n currentText = last.text\n currentLocalOffset = currentText.length\n }\n\n for (const char of action.text) {\n const delay = Math.max(10, speed + (Math.random() * 2 - 1) * variance)\n await sleep(delay)\n\n if (char === '\\n') {\n // Re-derive global index from current node position (concurrent-safe)\n const globalIdx = globalIndexOf(fragment, currentText, currentLocalOffset)\n doc.transact(() => {\n currentText = insertParagraphAfter(fragment, globalIdx)\n currentLocalOffset = 0\n })\n } else {\n doc.transact(() => {\n currentText.insert(currentLocalOffset, char)\n })\n currentLocalOffset++\n }\n\n // Update cursor — re-derive global position for accuracy\n const cursorGlobal = globalIndexOf(fragment, currentText, currentLocalOffset)\n actor.setCursor(action.docId, cursorGlobal)\n }\n}\n\nexport async function executeTypeDelete(\n actor: ActorConnection,\n action: TypeDeleteAction\n): Promise<void> {\n const speed = action.speed ?? 60\n const variance = action.variance ?? 20\n const provider = await actor.getChildProvider(action.docId)\n const doc = provider.document\n const fragment = doc.getXmlFragment('default')\n\n // Find starting position\n const startIndex = action.position ?? fragmentTextLength(fragment)\n let remaining = action.count\n\n while (remaining > 0) {\n const delay = Math.max(10, speed + (Math.random() * 2 - 1) * variance)\n await sleep(delay)\n\n // Re-find position each iteration (concurrent-safe)\n const deleteAt = Math.max(0, startIndex - (action.count - remaining) - 1)\n const pos = findTextPosition(fragment, deleteAt)\n if (!pos || deleteAt < 0) break\n\n doc.transact(() => {\n if (pos.offset > 0) {\n pos.text.delete(pos.offset - 1, 1)\n }\n })\n\n remaining--\n\n // Update cursor\n actor.setCursor(action.docId, Math.max(0, deleteAt))\n }\n}\n","/**\n * Easing functions for animated actions (cursor movement, pointer, etc.)\n */\nimport type { EasingName, EasingFn } from './types.ts'\n\nexport const easings: Record<EasingName, EasingFn> = {\n linear: (t) => t,\n easeIn: (t) => t * t,\n easeOut: (t) => t * (2 - t),\n easeInOut: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,\n}\n\nexport function getEasing(name?: EasingName): EasingFn {\n return easings[name ?? 'easeInOut']\n}\n","/**\n * Cursor actions: moveCursor (animated), select.\n */\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type { MoveCursorAction, SelectAction } from '../types.ts'\nimport { sleep } from '../utils.ts'\nimport { getEasing } from '../easing.ts'\n\nexport async function executeMoveCursor(\n actor: ActorConnection,\n action: MoveCursorAction\n): Promise<void> {\n const easing = getEasing(action.easing)\n const steps = Math.max(1, Math.round(action.duration / 16))\n const stepDuration = action.duration / steps\n\n for (let i = 0; i <= steps; i++) {\n const t = easing(i / steps)\n const pos = Math.round(action.from + (action.to - action.from) * t)\n actor.setCursor(action.docId, pos)\n if (i < steps) await sleep(stepDuration)\n }\n}\n\nexport async function executeSelect(\n actor: ActorConnection,\n action: SelectAction\n): Promise<void> {\n actor.setSelection(action.docId, action.anchor, action.head)\n}\n","/**\n * Markdown → Y.js converter.\n * Ported from cou-sh/app/utils/markdownToYjs.ts with Vue dependency removed.\n */\nimport * as Y from 'yjs'\nimport type { PageMeta } from './types.ts'\n\n// ── Filename → readable label ────────────────────────────────────────────────\n\nexport function filenameToLabel(raw: string): string {\n const base = raw.replace(/\\.[^.]+$/, '')\n const spaced = base.replace(/([a-z])([A-Z])/g, '$1 $2')\n const clean = spaced.replace(/[-_.]+/g, ' ').replace(/\\s+/g, ' ').trim()\n return clean.charAt(0).toUpperCase() + clean.slice(1)\n}\n\n// ── YAML frontmatter parser ──────────────────────────────────────────────────\n\nexport interface FrontmatterResult {\n title?: string\n meta: Partial<PageMeta>\n body: string\n}\n\nfunction coerceScalar(raw: string): string | number | boolean {\n const trimmed = raw.trim()\n if (trimmed === 'true') return true\n if (trimmed === 'false') return false\n const num = Number(trimmed)\n if (!Number.isNaN(num) && trimmed !== '') return num\n if ((trimmed.startsWith('\"') && trimmed.endsWith('\"'))\n || (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))) {\n return trimmed.slice(1, -1)\n }\n return trimmed\n}\n\nfunction parseInlineArray(raw: string): string[] {\n return raw.slice(1, -1).split(',').map(s => s.trim()).filter(Boolean)\n}\n\nexport function parseFrontmatter(markdown: string): FrontmatterResult {\n const noResult: FrontmatterResult = { meta: {}, body: markdown }\n\n const match = markdown.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?/)\n if (!match) return noResult\n\n const yamlBlock = match[1]!\n const body = markdown.slice(match[0].length)\n\n const raw: Record<string, string | string[]> = {}\n const lines = yamlBlock.split('\\n')\n let i = 0\n while (i < lines.length) {\n const line = lines[i]!\n const blockSeqKey = line.match(/^(\\w[\\w-]*):\\s*$/)\n if (blockSeqKey && i + 1 < lines.length && /^\\s+-\\s/.test(lines[i + 1]!)) {\n const key = blockSeqKey[1]!\n const items: string[] = []\n i++\n while (i < lines.length && /^\\s+-\\s/.test(lines[i]!)) {\n items.push(lines[i]!.replace(/^\\s+-\\s/, '').trim())\n i++\n }\n raw[key] = items\n continue\n }\n const kvMatch = line.match(/^(\\w[\\w-]*):\\s*(.*)$/)\n if (kvMatch) {\n const key = kvMatch[1]!\n const val = kvMatch[2]!.trim()\n if (val.startsWith('[') && val.endsWith(']')) {\n raw[key] = parseInlineArray(val)\n } else {\n raw[key] = val\n }\n }\n i++\n }\n\n const meta: Partial<PageMeta> = {}\n\n const getStr = (keys: string[]): string | undefined => {\n for (const k of keys) {\n const v = raw[k]\n if (typeof v === 'string' && v) return v\n }\n }\n\n if (raw['tags']) meta.tags = Array.isArray(raw['tags']) ? raw['tags'] : [raw['tags'] as string]\n const color = getStr(['color'])\n if (color) meta.color = color\n const icon = getStr(['icon'])\n if (icon) meta.icon = icon\n const status = getStr(['status'])\n if (status) meta.status = status\n\n const priorityRaw = getStr(['priority'])\n if (priorityRaw !== undefined) {\n const map: Record<string, number> = { low: 1, medium: 2, high: 3, urgent: 4 }\n meta.priority = map[priorityRaw.toLowerCase()] ?? (Number(priorityRaw) || 0)\n }\n\n const checkedRaw = raw['checked'] ?? raw['done']\n if (checkedRaw !== undefined) meta.checked = checkedRaw === 'true' || checkedRaw === true\n\n const dateStart = getStr(['date', 'created'])\n if (dateStart) meta.dateStart = dateStart\n const dateEnd = getStr(['due'])\n if (dateEnd) meta.dateEnd = dateEnd\n\n const subtitle = getStr(['description', 'subtitle'])\n if (subtitle) meta.subtitle = subtitle\n const url = getStr(['url'])\n if (url) meta.url = url\n const email = getStr(['email'])\n if (email) meta.email = email\n const phone = getStr(['phone'])\n if (phone) meta.phone = phone\n\n const ratingRaw = getStr(['rating'])\n if (ratingRaw !== undefined) {\n const n = Number(ratingRaw)\n if (!Number.isNaN(n)) meta.rating = Math.min(5, Math.max(0, n))\n }\n\n // Datetime fields\n const datetimeStart = getStr(['datetimeStart'])\n if (datetimeStart) meta.datetimeStart = datetimeStart\n const datetimeEnd = getStr(['datetimeEnd'])\n if (datetimeEnd) meta.datetimeEnd = datetimeEnd\n const allDayRaw = raw['allDay']\n if (allDayRaw !== undefined) meta.allDay = allDayRaw === 'true' || allDayRaw === true\n\n // Geo fields\n const geoLatRaw = getStr(['geoLat'])\n if (geoLatRaw !== undefined) { const n = Number(geoLatRaw); if (!Number.isNaN(n)) meta.geoLat = n }\n const geoLngRaw = getStr(['geoLng'])\n if (geoLngRaw !== undefined) { const n = Number(geoLngRaw); if (!Number.isNaN(n)) meta.geoLng = n }\n const geoType = getStr(['geoType'])\n if (geoType && (geoType === 'marker' || geoType === 'line' || geoType === 'measure')) {\n meta.geoType = geoType\n }\n const geoDescription = getStr(['geoDescription'])\n if (geoDescription) meta.geoDescription = geoDescription\n\n // Numeric fields\n const numberRaw = getStr(['number'])\n if (numberRaw !== undefined) { const n = Number(numberRaw); if (!Number.isNaN(n)) meta.number = n }\n const unit = getStr(['unit'])\n if (unit) meta.unit = unit\n\n // Note\n const note = getStr(['note'])\n if (note) meta.note = note\n\n const title = typeof raw['title'] === 'string' ? raw['title'] : undefined\n\n return { title, meta, body }\n}\n\n// ── Inline token parsing ─────────────────────────────────────────────────────\n\ninterface InlineToken {\n text: string\n attrs?: Record<string, unknown>\n /** If set, emit an inline Y.XmlElement with this nodeName instead of text+marks. */\n node?: string\n /** Attributes for the inline node (when node is set). */\n nodeAttrs?: Record<string, string>\n}\n\nfunction parseInline(text: string): InlineToken[] {\n const stripped = text.replace(/\\{lang=\"[^\"]*\"\\}/g, '')\n .replace(/:(?!badge|icon|kbd)(\\w[\\w-]*)\\[([^\\]]*)\\](\\{[^}]*\\})?/g, '$2')\n .replace(/:(?!badge|icon|kbd)(\\w[\\w-]*)(\\{[^}]*\\})/g, '')\n\n const tokens: InlineToken[] = []\n const re = /:badge\\[([^\\]]*)\\](\\{[^}]*\\})?|:icon\\{([^}]*)\\}|:kbd\\{([^}]*)\\}|!?\\[\\[([^\\]|]+?)(?:\\|([^\\]]+?))?\\]\\]|~~(.+?)~~|\\*\\*(.+?)\\*\\*|\\*(.+?)\\*|_(.+?)_|`(.+?)`|\\[(.+?)\\]\\((.+?)\\)/g\n let lastIndex = 0\n let match: RegExpExecArray | null\n\n while ((match = re.exec(stripped)) !== null) {\n if (match.index > lastIndex) {\n tokens.push({ text: stripped.slice(lastIndex, match.index) })\n }\n if (match[1] !== undefined) {\n const badgeProps = parseMdcProps(match[2])\n tokens.push({ text: match[1] || 'Badge', attrs: { badge: { label: match[1] || 'Badge', color: badgeProps['color'] || 'neutral', variant: badgeProps['variant'] || 'subtle' } } })\n } else if (match[3] !== undefined) {\n const iconProps = parseMdcProps(`{${match[3]}}`)\n tokens.push({ text: '\\u200B', attrs: { proseIcon: { name: iconProps['name'] || 'i-lucide-star' } } })\n } else if (match[4] !== undefined) {\n const kbdProps = parseMdcProps(`{${match[4]}}`)\n tokens.push({ text: kbdProps['value'] || '', attrs: { kbd: { value: kbdProps['value'] || '' } } })\n } else if (match[5] !== undefined) {\n // Inline wikilink [[docId]] or [[docId|label]] → inline docLink node\n // (the label is derived from the tree at render time; legacy label is dropped)\n tokens.push({ text: '', node: 'docLink', nodeAttrs: { docId: match[5]! } })\n } else if (match[7] !== undefined) {\n tokens.push({ text: match[7], attrs: { strike: true } })\n } else if (match[8] !== undefined) {\n tokens.push({ text: match[8], attrs: { bold: true } })\n } else if (match[9] !== undefined) {\n tokens.push({ text: match[9], attrs: { italic: true } })\n } else if (match[10] !== undefined) {\n tokens.push({ text: match[10], attrs: { italic: true } })\n } else if (match[11] !== undefined) {\n tokens.push({ text: match[11], attrs: { code: true } })\n } else if (match[12] !== undefined && match[13] !== undefined) {\n tokens.push({ text: match[12], attrs: { link: { href: match[13] } } })\n }\n lastIndex = match.index + match[0].length\n }\n\n if (lastIndex < stripped.length) {\n tokens.push({ text: stripped.slice(lastIndex) })\n }\n return tokens.filter(t => t.node || t.text.length > 0)\n}\n\n// ── Block-level parser ───────────────────────────────────────────────────────\n\ninterface TaskItem {\n text: string\n checked: boolean\n}\n\ntype Block =\n | { type: 'heading'; level: number; text: string }\n | { type: 'paragraph'; text: string }\n | { type: 'bulletList'; items: string[] }\n | { type: 'orderedList'; items: string[] }\n | { type: 'taskList'; items: TaskItem[] }\n | { type: 'codeBlock'; lang: string; code: string }\n | { type: 'blockquote'; lines: string[] }\n | { type: 'table'; headerRow: string[]; dataRows: string[][] }\n | { type: 'hr' }\n | { type: 'callout'; calloutType: string; innerBlocks: Block[] }\n | { type: 'collapsible'; label: string; open: boolean; innerBlocks: Block[] }\n | { type: 'steps'; innerBlocks: Block[] }\n | { type: 'card'; title: string; icon: string; to: string; innerBlocks: Block[] }\n | { type: 'cardGroup'; cards: Block[] }\n | { type: 'codeCollapse'; codeBlocks: Block[] }\n | { type: 'codeGroup'; codeBlocks: Block[] }\n | { type: 'codePreview'; innerBlocks: Block[]; codeBlocks: Block[] }\n | { type: 'codeTree'; files: string }\n | { type: 'accordion'; items: { label: string; icon: string; innerBlocks: Block[] }[] }\n | { type: 'tabs'; items: { label: string; icon: string; innerBlocks: Block[] }[] }\n | { type: 'field'; name: string; fieldType: string; required: boolean; innerBlocks: Block[] }\n | { type: 'fieldGroup'; fields: Block[] }\n | { type: 'image'; src: string; alt: string; width?: string; height?: string }\n | { type: 'docEmbed'; docId: string; seamless?: boolean }\n | { type: 'svgEmbed'; svg: string; title: string }\n\nfunction parseTableRow(line: string): string[] {\n const parts = line.split('|')\n return parts.slice(1, parts.length - 1).map(c => c.trim())\n}\n\nfunction isTableSeparator(line: string): boolean {\n return /^\\|[\\s|:-]+\\|$/.test(line.trim())\n}\n\nfunction extractFencedCode(lines: string[]): Block[] {\n const result: Block[] = []\n let i = 0\n while (i < lines.length) {\n const line = lines[i]!\n const fenceMatch = line.match(/^(`{3,})(\\w*)/)\n if (fenceMatch) {\n const fence = fenceMatch[1]!\n const lang = fenceMatch[2] ?? ''\n const codeLines: string[] = []\n i++\n while (i < lines.length && !lines[i]!.startsWith(fence)) {\n codeLines.push(lines[i]!)\n i++\n }\n i++\n result.push({ type: 'codeBlock', lang, code: codeLines.join('\\n') })\n continue\n }\n i++\n }\n return result\n}\n\nfunction parseMdcProps(propsStr: string | undefined): Record<string, string> {\n if (!propsStr) return {}\n const result: Record<string, string> = {}\n const re = /(\\w[\\w-]*)=\"([^\"]*)\"/g\n let m: RegExpExecArray | null\n while ((m = re.exec(propsStr)) !== null) {\n result[m[1]!] = m[2]!\n }\n return result\n}\n\nfunction parseMdcChildren(innerLines: string[], slotPrefix: string): { label: string; icon: string; innerBlocks: Block[] }[] {\n const items: { label: string; icon: string; lines: string[] }[] = []\n let current: { label: string; icon: string; lines: string[] } | null = null\n const slotRe = new RegExp(`^#${slotPrefix}(\\\\{[^}]*\\\\})?\\\\s*$`)\n\n for (const line of innerLines) {\n const slotMatch = line.match(slotRe)\n if (slotMatch) {\n if (current) items.push(current)\n const props = parseMdcProps(slotMatch[1])\n current = { label: props['label'] || props['title'] || `Item ${items.length + 1}`, icon: props['icon'] || '', lines: [] }\n continue\n }\n if (current) {\n current.lines.push(line)\n } else {\n if (!items.length && !current) {\n current = { label: `Item 1`, icon: '', lines: [line] }\n }\n }\n }\n if (current) items.push(current)\n\n return items.map(item => ({\n label: item.label,\n icon: item.icon,\n innerBlocks: parseBlocks(item.lines.join('\\n')),\n }))\n}\n\nconst TASK_RE = /^[-*+]\\s+\\[([ xX])\\]\\s+(.*)/\n\nfunction parseBlocks(markdown: string): Block[] {\n const rawLines = markdown.split('\\n')\n let firstContentLine = 0\n while (firstContentLine < rawLines.length) {\n const l = rawLines[firstContentLine]!\n if (l.trim() === '' || /^import\\s/.test(l) || /^export\\s/.test(l)) {\n firstContentLine++\n } else {\n break\n }\n }\n const stripped = rawLines.slice(firstContentLine).join('\\n')\n\n const blocks: Block[] = []\n const lines = stripped.split('\\n')\n let i = 0\n\n while (i < lines.length) {\n const line = lines[i]!\n\n const fenceBlockMatch = line.match(/^(`{3,})(.*)$/)\n if (fenceBlockMatch) {\n const fence = fenceBlockMatch[1]!\n const lang = fenceBlockMatch[2]!.trim()\n .replace(/\\{[^}]*\\}$/, '')\n .replace(/\\s*\\[.*\\]$/, '')\n .trim()\n const codeLines: string[] = []\n i++\n while (i < lines.length && !lines[i]!.startsWith(fence)) {\n codeLines.push(lines[i]!)\n i++\n }\n i++\n if (lang === 'svg' || lang.startsWith('svg ')) {\n const svgTitle = lang === 'svg' ? '' : lang.slice(4).trim()\n blocks.push({ type: 'svgEmbed', svg: codeLines.join('\\n'), title: svgTitle })\n } else {\n blocks.push({ type: 'codeBlock', lang, code: codeLines.join('\\n') })\n }\n continue\n }\n\n const headingMatch = line.match(/^(#{1,6})\\s+(.*)/)\n if (headingMatch) {\n blocks.push({ type: 'heading', level: headingMatch[1]!.length, text: headingMatch[2]!.trim() })\n i++\n continue\n }\n\n if (/^[-*_]{3,}\\s*$/.test(line)) {\n blocks.push({ type: 'hr' })\n i++\n continue\n }\n\n const docEmbedMatch = line.match(/^!\\[\\[([^\\]|]+?)(?:\\|[^\\]]*?)?\\]\\](\\{[^}]*\\})?\\s*$/)\n if (docEmbedMatch) {\n const props = parseMdcProps(docEmbedMatch[2])\n const seamless = 'seamless' in props || props['seamless'] === 'true' || /\\{[^}]*\\bseamless\\b[^}]*\\}/.test(docEmbedMatch[2] ?? '')\n blocks.push({ type: 'docEmbed', docId: docEmbedMatch[1]!, seamless: seamless || undefined })\n i++\n continue\n }\n\n const imgMatch = line.match(/^!\\[([^\\]]*)\\]\\(([^)]+)\\)(\\{[^}]*\\})?\\s*$/)\n if (imgMatch) {\n const alt = imgMatch[1] ?? ''\n const src = imgMatch[2] ?? ''\n const attrs = parseMdcProps(imgMatch[3])\n blocks.push({ type: 'image', src, alt, width: attrs['width'], height: attrs['height'] })\n i++\n continue\n }\n\n if (line.startsWith('> ') || line === '>') {\n const bqLines: string[] = []\n while (i < lines.length && (lines[i]!.startsWith('> ') || lines[i] === '>')) {\n bqLines.push(lines[i]!.replace(/^>\\s?/, ''))\n i++\n }\n blocks.push({ type: 'blockquote', lines: bqLines })\n continue\n }\n\n if (/^\\s*\\|/.test(line)) {\n const tableLines: string[] = []\n while (i < lines.length && /^\\s*\\|/.test(lines[i]!)) {\n tableLines.push(lines[i]!)\n i++\n }\n if (tableLines.length >= 2 && isTableSeparator(tableLines[1]!)) {\n const headerRow = parseTableRow(tableLines[0]!)\n const dataRows = tableLines.slice(2)\n .filter(l => !isTableSeparator(l))\n .map(parseTableRow)\n blocks.push({ type: 'table', headerRow, dataRows })\n } else {\n for (const l of tableLines) blocks.push({ type: 'paragraph', text: l })\n }\n continue\n }\n\n const MDC_OPEN = /^\\s*(:{2,})(\\w[\\w-]*)(\\{[^}]*\\})?\\s*$/\n if (MDC_OPEN.test(line)) {\n const colons = line.match(/^\\s*(:+)/)?.[1]?.length ?? 2\n const componentName = line.match(/^\\s*:{2,}(\\w[\\w-]*)/)?.[1] ?? ''\n const innerLines: string[] = []\n i++\n while (i < lines.length) {\n const l = lines[i]!\n if (new RegExp(`^\\\\s*:{${colons}}\\\\s*$`).test(l)) { i++; break }\n const innerFence = l.match(/^(\\s*`{3,})/)\n if (innerFence) {\n const fenceStr = innerFence[1]!.trimStart()\n innerLines.push(l)\n i++\n while (i < lines.length && !lines[i]!.trimStart().startsWith(fenceStr)) {\n innerLines.push(lines[i]!)\n i++\n }\n if (i < lines.length) { innerLines.push(lines[i]!); i++ }\n continue\n }\n innerLines.push(l)\n i++\n }\n\n const nonBlank = innerLines.filter(l => l.trim().length > 0)\n if (nonBlank.length) {\n const minIndent = Math.min(...nonBlank.map(l => l.match(/^(\\s*)/)?.[1]?.length ?? 0))\n if (minIndent > 0) {\n for (let j = 0; j < innerLines.length; j++) {\n innerLines[j] = innerLines[j]!.slice(Math.min(minIndent, innerLines[j]!.length))\n }\n }\n }\n\n let contentStart = 0\n if (innerLines[0]?.trim() === '---') {\n const fmEnd = innerLines.findIndex((l, idx) => idx > 0 && l.trim() === '---')\n if (fmEnd !== -1) contentStart = fmEnd + 1\n }\n const contentLines = innerLines.slice(contentStart)\n\n const defaultSlotLines: string[] = []\n const codeSlotLines: string[] = []\n let currentSlot: 'default' | 'code' | 'other' = 'default'\n for (const l of contentLines) {\n if (/^#code\\s*$/.test(l)) { currentSlot = 'code'; continue }\n if (/^#\\w+/.test(l) && !/^#{2,}\\s/.test(l)) { currentSlot = 'other'; continue }\n if (currentSlot === 'default') defaultSlotLines.push(l)\n else if (currentSlot === 'code') codeSlotLines.push(l)\n }\n const innerBlocks = parseBlocks(defaultSlotLines.join('\\n'))\n\n const codeBlocks = extractFencedCode(codeSlotLines)\n\n const CALLOUT_NAMES = new Set(['tip', 'note', 'info', 'warning', 'caution', 'danger', 'callout', 'alert'])\n if (CALLOUT_NAMES.has(componentName.toLowerCase())) {\n blocks.push({ type: 'callout', calloutType: componentName.toLowerCase(), innerBlocks })\n } else {\n const mdcProps = parseMdcProps(line.match(MDC_OPEN)?.[3])\n const lc = componentName.toLowerCase()\n\n if (lc === 'collapsible') {\n blocks.push({ type: 'collapsible', label: mdcProps['label'] || 'Details', open: mdcProps['open'] === 'true', innerBlocks })\n } else if (lc === 'steps') {\n blocks.push({ type: 'steps', innerBlocks })\n } else if (lc === 'card') {\n blocks.push({ type: 'card', title: mdcProps['title'] || '', icon: mdcProps['icon'] || '', to: mdcProps['to'] || '', innerBlocks })\n } else if (lc === 'card-group') {\n const cards = innerBlocks.filter(b => b.type === 'card')\n if (cards.length) {\n blocks.push({ type: 'cardGroup', cards })\n } else {\n blocks.push(...innerBlocks)\n }\n } else if (lc === 'code-collapse') {\n blocks.push({ type: 'codeCollapse', codeBlocks: codeBlocks.length ? codeBlocks : innerBlocks.filter(b => b.type === 'codeBlock') })\n } else if (lc === 'code-group') {\n const allCode = [...innerBlocks.filter(b => b.type === 'codeBlock'), ...codeBlocks]\n blocks.push({ type: 'codeGroup', codeBlocks: allCode })\n } else if (lc === 'code-preview') {\n blocks.push({ type: 'codePreview', innerBlocks, codeBlocks })\n } else if (lc === 'code-tree') {\n blocks.push({ type: 'codeTree', files: mdcProps['files'] || '[]' })\n } else if (lc === 'accordion') {\n const items = parseMdcChildren(contentLines, 'item')\n if (items.length) {\n blocks.push({ type: 'accordion', items })\n } else {\n blocks.push({ type: 'accordion', items: [{ label: 'Item 1', icon: '', innerBlocks }] })\n }\n } else if (lc === 'tabs') {\n const items = parseMdcChildren(contentLines, 'tab')\n if (items.length) {\n blocks.push({ type: 'tabs', items })\n } else {\n blocks.push({ type: 'tabs', items: [{ label: 'Tab 1', icon: '', innerBlocks }] })\n }\n } else if (lc === 'field') {\n blocks.push({ type: 'field', name: mdcProps['name'] || '', fieldType: mdcProps['type'] || 'string', required: mdcProps['required'] === 'true', innerBlocks })\n } else if (lc === 'field-group') {\n const fields = innerBlocks.filter(b => b.type === 'field')\n if (fields.length) {\n blocks.push({ type: 'fieldGroup', fields })\n } else {\n blocks.push(...innerBlocks)\n }\n } else {\n blocks.push(...innerBlocks)\n blocks.push(...codeBlocks)\n }\n }\n continue\n }\n\n if (TASK_RE.test(line)) {\n const items: TaskItem[] = []\n while (i < lines.length && TASK_RE.test(lines[i]!)) {\n const m = lines[i]!.match(TASK_RE)!\n items.push({ checked: m[1]!.toLowerCase() === 'x', text: m[2]! })\n i++\n }\n blocks.push({ type: 'taskList', items })\n continue\n }\n\n if (/^[-*+]\\s+/.test(line)) {\n const items: string[] = []\n while (i < lines.length && /^[-*+]\\s+/.test(lines[i]!) && !TASK_RE.test(lines[i]!)) {\n items.push(lines[i]!.replace(/^[-*+]\\s+/, ''))\n i++\n }\n if (items.length) {\n blocks.push({ type: 'bulletList', items })\n continue\n }\n }\n\n if (/^\\d+\\.\\s+/.test(line)) {\n const items: string[] = []\n while (i < lines.length && /^\\d+\\.\\s+/.test(lines[i]!)) {\n items.push(lines[i]!.replace(/^\\d+\\.\\s+/, ''))\n i++\n }\n blocks.push({ type: 'orderedList', items })\n continue\n }\n\n if (line.trim() === '') {\n i++\n continue\n }\n\n const paraLines: string[] = []\n while (\n i < lines.length\n && lines[i]!.trim() !== ''\n && !/^(#{1,6}\\s|[-*+]\\s|\\d+\\.\\s|>|`{3,}|\\s*\\||[-*_]{3,}\\s*$|\\s*:{2,}\\w)/.test(lines[i]!)\n ) {\n paraLines.push(lines[i]!)\n i++\n }\n if (paraLines.length) {\n blocks.push({ type: 'paragraph', text: paraLines.join(' ') })\n }\n }\n\n return blocks\n}\n\n// ── Y.js content population ──────────────────────────────────────────────────\n\nfunction fillTextInto(el: Y.XmlElement, tokens: InlineToken[]): void {\n const filtered = tokens.filter(t => t.node || t.text.length > 0)\n if (!filtered.length) return\n\n const children: (Y.XmlText | Y.XmlElement)[] = filtered.map((tok) => {\n if (tok.node) {\n const xe = new Y.XmlElement(tok.node)\n if (tok.nodeAttrs) {\n for (const [k, v] of Object.entries(tok.nodeAttrs)) xe.setAttribute(k, v)\n }\n return xe\n }\n return new Y.XmlText()\n })\n el.insert(0, children)\n\n filtered.forEach((tok, i) => {\n if (tok.node) return\n const xt = children[i] as Y.XmlText\n if (tok.attrs) {\n xt.insert(0, tok.text, tok.attrs as Record<string, boolean | object>)\n } else {\n xt.insert(0, tok.text)\n }\n })\n}\n\nfunction blockElName(b: Block): string {\n switch (b.type) {\n case 'heading': return 'heading'\n case 'paragraph': return 'paragraph'\n case 'bulletList': return 'bulletList'\n case 'orderedList': return 'orderedList'\n case 'taskList': return 'taskList'\n case 'codeBlock': return 'codeBlock'\n case 'blockquote': return 'blockquote'\n case 'table': return 'table'\n case 'hr': return 'horizontalRule'\n case 'callout': return 'callout'\n case 'collapsible': return 'collapsible'\n case 'steps': return 'steps'\n case 'card': return 'card'\n case 'cardGroup': return 'cardGroup'\n case 'codeCollapse': return 'codeCollapse'\n case 'codeGroup': return 'codeGroup'\n case 'codePreview': return 'codePreview'\n case 'codeTree': return 'codeTree'\n case 'accordion': return 'accordion'\n case 'tabs': return 'tabs'\n case 'field': return 'field'\n case 'fieldGroup': return 'fieldGroup'\n case 'image': return 'image'\n case 'docEmbed': return 'docEmbed'\n case 'svgEmbed': return 'svgEmbed'\n }\n}\n\nfunction fillBlock(el: Y.XmlElement, block: Block): void {\n switch (block.type) {\n case 'heading': {\n el.setAttribute('level', block.level as any)\n fillTextInto(el, parseInline(block.text))\n break\n }\n case 'paragraph': {\n fillTextInto(el, parseInline(block.text))\n break\n }\n case 'bulletList':\n case 'orderedList': {\n const listItemEls = block.items.map(() => new Y.XmlElement('listItem'))\n el.insert(0, listItemEls)\n block.items.forEach((text, i) => {\n const paraEl = new Y.XmlElement('paragraph')\n listItemEls[i]!.insert(0, [paraEl])\n fillTextInto(paraEl, parseInline(text))\n })\n break\n }\n case 'taskList': {\n const taskItemEls = block.items.map(() => new Y.XmlElement('taskItem'))\n el.insert(0, taskItemEls)\n block.items.forEach((item, i) => {\n taskItemEls[i]!.setAttribute('checked', item.checked as any)\n const paraEl = new Y.XmlElement('paragraph')\n taskItemEls[i]!.insert(0, [paraEl])\n fillTextInto(paraEl, parseInline(item.text))\n })\n break\n }\n case 'codeBlock': {\n if (block.lang) el.setAttribute('language', block.lang)\n const xt = new Y.XmlText()\n el.insert(0, [xt])\n xt.insert(0, block.code)\n break\n }\n case 'blockquote': {\n const paraEls = block.lines.map(() => new Y.XmlElement('paragraph'))\n el.insert(0, paraEls)\n block.lines.forEach((line, i) => fillTextInto(paraEls[i]!, parseInline(line)))\n break\n }\n case 'table': {\n const headerRowEl = new Y.XmlElement('tableRow')\n const dataRowEls = block.dataRows.map(() => new Y.XmlElement('tableRow'))\n el.insert(0, [headerRowEl, ...dataRowEls])\n\n const headerCellEls = block.headerRow.map(() => new Y.XmlElement('tableHeader'))\n headerRowEl.insert(0, headerCellEls)\n block.headerRow.forEach((cellText, i) => {\n const paraEl = new Y.XmlElement('paragraph')\n headerCellEls[i]!.insert(0, [paraEl])\n fillTextInto(paraEl, parseInline(cellText))\n })\n\n block.dataRows.forEach((row, ri) => {\n const cellEls = row.map(() => new Y.XmlElement('tableCell'))\n dataRowEls[ri]!.insert(0, cellEls)\n row.forEach((cellText, ci) => {\n const paraEl = new Y.XmlElement('paragraph')\n cellEls[ci]!.insert(0, [paraEl])\n fillTextInto(paraEl, parseInline(cellText))\n })\n })\n break\n }\n case 'hr': break\n case 'callout': {\n el.setAttribute('type', block.calloutType)\n if (!block.innerBlocks.length) {\n const paraEl = new Y.XmlElement('paragraph')\n el.insert(0, [paraEl])\n break\n }\n const innerEls = block.innerBlocks.map(b => new Y.XmlElement(blockElName(b)))\n el.insert(0, innerEls)\n block.innerBlocks.forEach((b, i) => fillBlock(innerEls[i]!, b))\n break\n }\n case 'collapsible': {\n el.setAttribute('label', block.label)\n el.setAttribute('open', block.open as any)\n const inner = block.innerBlocks.length ? block.innerBlocks : [{ type: 'paragraph' as const, text: '' }]\n const innerEls = inner.map(b => new Y.XmlElement(blockElName(b)))\n el.insert(0, innerEls)\n inner.forEach((b, i) => fillBlock(innerEls[i]!, b))\n break\n }\n case 'steps': {\n const inner = block.innerBlocks.length ? block.innerBlocks : [{ type: 'paragraph' as const, text: '' }]\n const innerEls = inner.map(b => new Y.XmlElement(blockElName(b)))\n el.insert(0, innerEls)\n inner.forEach((b, i) => fillBlock(innerEls[i]!, b))\n break\n }\n case 'card': {\n if (block.title) el.setAttribute('title', block.title)\n if (block.icon) el.setAttribute('icon', block.icon)\n if (block.to) el.setAttribute('to', block.to)\n const inner = block.innerBlocks.length ? block.innerBlocks : [{ type: 'paragraph' as const, text: '' }]\n const innerEls = inner.map(b => new Y.XmlElement(blockElName(b)))\n el.insert(0, innerEls)\n inner.forEach((b, i) => fillBlock(innerEls[i]!, b))\n break\n }\n case 'cardGroup': {\n const cardEls = block.cards.map(b => new Y.XmlElement(blockElName(b)))\n el.insert(0, cardEls)\n block.cards.forEach((b, i) => fillBlock(cardEls[i]!, b))\n break\n }\n case 'codeCollapse': {\n const codes = block.codeBlocks.length ? block.codeBlocks : [{ type: 'codeBlock' as const, lang: '', code: '' }]\n const codeEl = new Y.XmlElement('codeBlock')\n el.insert(0, [codeEl])\n fillBlock(codeEl, codes[0]!)\n break\n }\n case 'codeGroup': {\n const codes = block.codeBlocks.length ? block.codeBlocks : [{ type: 'codeBlock' as const, lang: '', code: '' }]\n const codeEls = codes.map(() => new Y.XmlElement('codeBlock'))\n el.insert(0, codeEls)\n codes.forEach((b, i) => fillBlock(codeEls[i]!, b))\n break\n }\n case 'codePreview': {\n const all = [...block.innerBlocks, ...block.codeBlocks]\n const inner = all.length ? all : [{ type: 'paragraph' as const, text: '' }]\n const innerEls = inner.map(b => new Y.XmlElement(blockElName(b)))\n el.insert(0, innerEls)\n inner.forEach((b, i) => fillBlock(innerEls[i]!, b))\n break\n }\n case 'codeTree': {\n el.setAttribute('files', block.files)\n break\n }\n case 'accordion': {\n const itemEls = block.items.map(() => new Y.XmlElement('accordionItem'))\n el.insert(0, itemEls)\n block.items.forEach((item, i) => {\n itemEls[i]!.setAttribute('label', item.label)\n if (item.icon) itemEls[i]!.setAttribute('icon', item.icon)\n const inner = item.innerBlocks.length ? item.innerBlocks : [{ type: 'paragraph' as const, text: '' }]\n const childEls = inner.map(b => new Y.XmlElement(blockElName(b)))\n itemEls[i]!.insert(0, childEls)\n inner.forEach((b, ci) => fillBlock(childEls[ci]!, b))\n })\n break\n }\n case 'tabs': {\n const itemEls = block.items.map(() => new Y.XmlElement('tabsItem'))\n el.insert(0, itemEls)\n block.items.forEach((item, i) => {\n itemEls[i]!.setAttribute('label', item.label)\n if (item.icon) itemEls[i]!.setAttribute('icon', item.icon)\n const inner = item.innerBlocks.length ? item.innerBlocks : [{ type: 'paragraph' as const, text: '' }]\n const childEls = inner.map(b => new Y.XmlElement(blockElName(b)))\n itemEls[i]!.insert(0, childEls)\n inner.forEach((b, ci) => fillBlock(childEls[ci]!, b))\n })\n break\n }\n case 'field': {\n if (block.name) el.setAttribute('name', block.name)\n el.setAttribute('type', block.fieldType)\n el.setAttribute('required', block.required as any)\n const inner = block.innerBlocks.length ? block.innerBlocks : [{ type: 'paragraph' as const, text: '' }]\n const innerEls = inner.map(b => new Y.XmlElement(blockElName(b)))\n el.insert(0, innerEls)\n inner.forEach((b, i) => fillBlock(innerEls[i]!, b))\n break\n }\n case 'fieldGroup': {\n const fieldEls = block.fields.map(b => new Y.XmlElement(blockElName(b)))\n el.insert(0, fieldEls)\n block.fields.forEach((b, i) => fillBlock(fieldEls[i]!, b))\n break\n }\n case 'image': {\n el.setAttribute('src', block.src)\n if (block.alt) el.setAttribute('alt', block.alt)\n if (block.width) el.setAttribute('width', block.width)\n if (block.height) el.setAttribute('height', block.height)\n break\n }\n case 'docEmbed': {\n el.setAttribute('docId', block.docId)\n if (block.seamless) el.setAttribute('seamless', 'true')\n break\n }\n case 'svgEmbed': {\n el.setAttribute('svg', block.svg)\n if (block.title) el.setAttribute('title', block.title)\n break\n }\n }\n}\n\n// ── Public API ───────────────────────────────────────────────────────────────\n\nexport function populateYDocFromMarkdown(\n fragment: Y.XmlFragment,\n markdown: string,\n fallbackTitle = 'Untitled'\n): void {\n const ydoc = fragment.doc\n if (!ydoc) {\n console.warn('[markdownToYjs] fragment has no doc — skipping population')\n return\n }\n\n const blocks = parseBlocks(markdown)\n\n let title = fallbackTitle\n let contentBlocks = blocks\n const h1 = blocks.findIndex(b => b.type === 'heading' && b.level === 1)\n if (h1 !== -1) {\n title = (blocks[h1] as { type: 'heading'; level: number; text: string }).text\n contentBlocks = blocks.filter((_, i) => i !== h1)\n }\n if (!contentBlocks.length) contentBlocks = [{ type: 'paragraph', text: '' }]\n\n ydoc.transact(() => {\n const headerEl = new Y.XmlElement('documentHeader')\n const metaEl = new Y.XmlElement('documentMeta')\n const bodyEls: Y.XmlElement[] = contentBlocks.map((b) => {\n switch (b.type) {\n case 'heading': return new Y.XmlElement('heading')\n case 'paragraph': return new Y.XmlElement('paragraph')\n case 'bulletList': return new Y.XmlElement('bulletList')\n case 'orderedList': return new Y.XmlElement('orderedList')\n case 'taskList': return new Y.XmlElement('taskList')\n case 'codeBlock': return new Y.XmlElement('codeBlock')\n case 'blockquote': return new Y.XmlElement('blockquote')\n case 'table': return new Y.XmlElement('table')\n case 'hr': return new Y.XmlElement('horizontalRule')\n case 'callout': return new Y.XmlElement('callout')\n case 'collapsible': return new Y.XmlElement('collapsible')\n case 'steps': return new Y.XmlElement('steps')\n case 'card': return new Y.XmlElement('card')\n case 'cardGroup': return new Y.XmlElement('cardGroup')\n case 'codeCollapse': return new Y.XmlElement('codeCollapse')\n case 'codeGroup': return new Y.XmlElement('codeGroup')\n case 'codePreview': return new Y.XmlElement('codePreview')\n case 'codeTree': return new Y.XmlElement('codeTree')\n case 'accordion': return new Y.XmlElement('accordion')\n case 'tabs': return new Y.XmlElement('tabs')\n case 'field': return new Y.XmlElement('field')\n case 'fieldGroup': return new Y.XmlElement('fieldGroup')\n case 'image': return new Y.XmlElement('image')\n case 'docEmbed': return new Y.XmlElement('docEmbed')\n case 'svgEmbed': return new Y.XmlElement('svgEmbed')\n }\n })\n\n fragment.insert(0, [headerEl, metaEl, ...bodyEls])\n\n const headerXt = new Y.XmlText()\n headerEl.insert(0, [headerXt])\n headerXt.insert(0, title)\n\n contentBlocks.forEach((block, i) => fillBlock(bodyEls[i]!, block))\n })\n}\n","/**\n * Content actions: writeContent (markdown → Y.js), deleteContent.\n *\n * Preserves TipTap schema nodes (documentHeader, documentMeta) —\n * only body content is cleared/replaced.\n */\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type { WriteContentAction, DeleteContentAction } from '../types.ts'\nimport { populateYDocFromMarkdown } from '../converters/markdownToYjs.ts'\nimport { bodyStartIndex } from '../yjs-utils.ts'\n\nexport async function executeWriteContent(\n actor: ActorConnection,\n action: WriteContentAction\n): Promise<void> {\n const provider = await actor.getChildProvider(action.docId)\n const fragment = provider.document.getXmlFragment('default')\n\n // Clear entire fragment (schema nodes + body) — populateYDocFromMarkdown rebuilds them\n provider.document.transact(() => {\n while (fragment.length > 0) {\n fragment.delete(0, 1)\n }\n })\n\n // Populate from markdown (creates fresh documentHeader + documentMeta + body)\n populateYDocFromMarkdown(fragment, action.markdown)\n}\n\nexport async function executeDeleteContent(\n actor: ActorConnection,\n action: DeleteContentAction\n): Promise<void> {\n const provider = await actor.getChildProvider(action.docId)\n const fragment = provider.document.getXmlFragment('default')\n\n provider.document.transact(() => {\n // Offset from by the schema nodes to protect them\n const start = bodyStartIndex(fragment)\n const adjustedFrom = start + action.from\n const count = Math.min(action.length, fragment.length - adjustedFrom)\n if (count > 0) {\n fragment.delete(adjustedFrom, count)\n }\n })\n}\n","/**\n * Awareness actions: setStatus, setAwareness, clearAwareness, pointerMove, scrollTo,\n * kanbanHover, kanbanDrag.\n */\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type {\n SetStatusAction,\n SetAwarenessAction,\n ClearAwarenessAction,\n PointerMoveAction,\n ScrollToAction,\n KanbanHoverAction,\n KanbanDragAction,\n} from '../types.ts'\nimport { sleep } from '../utils.ts'\nimport { getEasing } from '../easing.ts'\n\nexport async function executeSetStatus(\n actor: ActorConnection,\n action: SetStatusAction\n): Promise<void> {\n actor.setRootAwareness('status', action.status)\n}\n\nexport async function executeSetAwareness(\n actor: ActorConnection,\n action: SetAwarenessAction\n): Promise<void> {\n if (action.docId) {\n // Ensure child provider is loaded\n await actor.getChildProvider(action.docId)\n for (const [key, value] of Object.entries(action.fields)) {\n actor.setChildAwareness(action.docId, key, value)\n }\n } else {\n for (const [key, value] of Object.entries(action.fields)) {\n actor.setRootAwareness(key, value)\n }\n }\n}\n\nexport async function executeClearAwareness(\n actor: ActorConnection,\n action: ClearAwarenessAction\n): Promise<void> {\n if (action.docId) {\n for (const field of action.fields) {\n actor.setChildAwareness(action.docId, field, null)\n }\n } else {\n for (const field of action.fields) {\n actor.setRootAwareness(field, null)\n }\n }\n}\n\nexport async function executePointerMove(\n actor: ActorConnection,\n action: PointerMoveAction\n): Promise<void> {\n const easing = getEasing(action.easing)\n const steps = Math.max(1, Math.round(action.duration / 16)) // ~60fps\n const stepDuration = action.duration / steps\n\n for (let i = 0; i <= steps; i++) {\n const t = easing(i / steps)\n const x = action.from.x + (action.to.x - action.from.x) * t\n const y = action.from.y + (action.to.y - action.from.y) * t\n actor.setChildAwareness(action.docId, 'pos', { x, y })\n if (i < steps) await sleep(stepDuration)\n }\n}\n\nexport async function executeScrollTo(\n actor: ActorConnection,\n action: ScrollToAction\n): Promise<void> {\n actor.setChildAwareness(action.docId, 'doc:scroll', action.position)\n}\n\nexport async function executeKanbanHover(\n actor: ActorConnection,\n action: KanbanHoverAction\n): Promise<void> {\n actor.setChildAwareness(action.docId, 'kanban:hovering', action.cardId)\n}\n\nexport async function executeKanbanDrag(\n actor: ActorConnection,\n action: KanbanDragAction\n): Promise<void> {\n // Set drag state\n actor.setChildAwareness(action.docId, 'kanban:dragging', {\n cardId: action.cardId,\n toColumnId: action.toColumnId,\n })\n // Hold for duration\n await sleep(action.duration)\n // Clear drag state\n actor.setChildAwareness(action.docId, 'kanban:dragging', null)\n}\n","/**\n * Document management actions: createDocument, moveDocument, setMeta.\n * These operate on the Y.js doc-tree map (same as the dashboard and MCP do).\n */\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type { CreateDocumentAction, MoveDocumentAction, SetMetaAction, RenameDocumentAction } from '../types.ts'\nimport { log } from '../utils.ts'\n\nexport async function executeCreateDocument(\n actor: ActorConnection,\n action: CreateDocumentAction,\n vars: Map<string, string>\n): Promise<void> {\n const rootProvider = actor.rootProvider\n if (!rootProvider) throw new Error(`${actor.actor.name}: not connected`)\n\n const treeMap = rootProvider.document.getMap('doc-tree')\n const id = crypto.randomUUID()\n const now = Date.now()\n\n // Normalize parentId: if it matches the root doc, use null (top-level)\n const normalizedParent = action.parentId === actor.rootDocId ? null : action.parentId\n\n rootProvider.document.transact(() => {\n treeMap.set(id, {\n label: action.label,\n parentId: normalizedParent,\n order: now,\n type: action.docType,\n meta: action.meta,\n createdAt: now,\n updatedAt: now,\n })\n })\n\n log(`${actor.actor.name}: created document \"${action.label}\" (${id})`)\n\n // Store the created ID for later reference in the script\n if (action.assignId) {\n vars.set(action.assignId, id)\n }\n}\n\nexport async function executeMoveDocument(\n actor: ActorConnection,\n action: MoveDocumentAction\n): Promise<void> {\n const rootProvider = actor.rootProvider\n if (!rootProvider) throw new Error(`${actor.actor.name}: not connected`)\n\n const treeMap = rootProvider.document.getMap('doc-tree')\n const entry = treeMap.get(action.docId) as Record<string, unknown> | undefined\n if (!entry) {\n log(`${actor.actor.name}: document ${action.docId} not found in tree`)\n return\n }\n\n // Normalize parentId\n const normalizedParent = action.newParentId === actor.rootDocId ? null : action.newParentId\n\n rootProvider.document.transact(() => {\n treeMap.set(action.docId, {\n ...entry,\n parentId: normalizedParent,\n order: action.order ?? Date.now(),\n updatedAt: Date.now(),\n })\n })\n\n log(`${actor.actor.name}: moved document ${action.docId} to ${action.newParentId}`)\n}\n\nexport async function executeSetMeta(\n actor: ActorConnection,\n action: SetMetaAction\n): Promise<void> {\n const rootProvider = actor.rootProvider\n if (!rootProvider) throw new Error(`${actor.actor.name}: not connected`)\n\n const treeMap = rootProvider.document.getMap('doc-tree')\n const entry = treeMap.get(action.docId) as Record<string, unknown> | undefined\n if (!entry) {\n log(`${actor.actor.name}: document ${action.docId} not found in tree`)\n return\n }\n\n rootProvider.document.transact(() => {\n const currentMeta = (entry.meta as Record<string, unknown>) ?? {}\n treeMap.set(action.docId, {\n ...entry,\n meta: { ...currentMeta, ...action.meta },\n updatedAt: Date.now(),\n })\n })\n}\n\nexport async function executeRenameDocument(\n actor: ActorConnection,\n action: RenameDocumentAction\n): Promise<void> {\n const rootProvider = actor.rootProvider\n if (!rootProvider) throw new Error(`${actor.actor.name}: not connected`)\n\n const treeMap = rootProvider.document.getMap('doc-tree')\n const entry = treeMap.get(action.docId) as Record<string, unknown> | undefined\n if (!entry) {\n log(`${actor.actor.name}: document ${action.docId} not found in tree`)\n return\n }\n\n rootProvider.document.transact(() => {\n treeMap.set(action.docId, {\n ...entry,\n label: action.label,\n updatedAt: Date.now(),\n })\n })\n\n log(`${actor.actor.name}: renamed ${action.docId} to \"${action.label}\"`)\n}\n","/**\n * Chat action — send a stateless message via the provider.\n *\n * Routes through the unified `messages:send` protocol. `action.channel` is\n * interpreted as a doc id (the channel/dm doc UUID); legacy `group:<docId>`\n * strings are accepted with the prefix stripped.\n */\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type { SendChatAction } from '../types.ts'\n\nexport async function executeSendChat(\n actor: ActorConnection,\n action: SendChatAction\n): Promise<void> {\n const rootProvider = actor.rootProvider\n if (!rootProvider) throw new Error(`${actor.actor.name}: not connected`)\n\n const channel_doc_id = action.channel.startsWith('group:')\n ? action.channel.slice(6)\n : action.channel\n\n const payload = JSON.stringify({\n type: 'messages:send',\n channel_doc_id,\n content: action.message,\n mentions: [],\n })\n\n rootProvider.sendStateless(payload)\n}\n","/**\n * Flow control actions: wait, parallel, sequence.\n */\nimport type { WaitAction, ParallelAction, SequenceAction, RepeatAction, TimelineEntry } from '../types.ts'\nimport { sleep } from '../utils.ts'\nimport type { ActionExecutor } from './index.ts'\n\nexport async function executeWait(action: WaitAction): Promise<void> {\n await sleep(action.duration)\n}\n\nexport async function executeParallel(\n action: ParallelAction,\n execute: ActionExecutor\n): Promise<void> {\n const promises = action.actions.map(async (entry) => {\n const delay = entry.at ?? 0\n if (delay > 0) await sleep(delay)\n await execute(entry)\n })\n await Promise.all(promises)\n}\n\nexport async function executeSequence(\n action: SequenceAction,\n execute: ActionExecutor\n): Promise<void> {\n for (const entry of action.actions) {\n const delay = entry.at ?? 0\n if (delay > 0) await sleep(delay)\n await execute(entry)\n }\n}\n\nexport async function executeRepeat(\n action: RepeatAction,\n execute: ActionExecutor\n): Promise<void> {\n for (let n = 0; n < action.times; n++) {\n for (const entry of action.actions) {\n const delay = entry.at ?? 0\n if (delay > 0) await sleep(delay)\n await execute(entry)\n }\n }\n}\n","/**\n * Action dispatcher — routes Action.type to the correct executor.\n */\nimport type { ActorConnection } from '../actor-connection.ts'\nimport type { Action, TimelineEntry, ServerConfig } from '../types.ts'\nimport { executeConnect, executeDisconnect } from './connect.ts'\nimport { executeNavigate } from './navigate.ts'\nimport { executeType, executeTypeDelete } from './type.ts'\nimport { executeMoveCursor, executeSelect } from './cursor.ts'\nimport { executeWriteContent, executeDeleteContent } from './content.ts'\nimport {\n executeSetStatus,\n executeSetAwareness,\n executeClearAwareness,\n executePointerMove,\n executeScrollTo,\n executeKanbanHover,\n executeKanbanDrag,\n} from './awareness.ts'\nimport { executeCreateDocument, executeMoveDocument, executeSetMeta, executeRenameDocument } from './document.ts'\nimport { executeSendChat } from './chat.ts'\nimport { executeWait, executeParallel, executeSequence, executeRepeat } from './flow.ts'\n\nexport type ActionExecutor = (entry: TimelineEntry) => Promise<void>\n\nexport interface ActionContext {\n actors: Map<string, ActorConnection>\n serverConfig: ServerConfig\n vars: Map<string, string>\n}\n\n/**\n * Resolve variable references in string values.\n * Replaces ${varName} with the value from vars map.\n */\nfunction resolveVars(value: string, vars: Map<string, string>): string {\n return value.replace(/\\$\\{(\\w+)\\}/g, (_, key) => vars.get(key) ?? `\\${${key}}`)\n}\n\nfunction resolveActionVars(action: Action, vars: Map<string, string>): Action {\n if (vars.size === 0) return action\n\n // Clone to avoid mutating the original scene definition\n const a = { ...action } as any\n\n // Resolve ID fields\n if (a.docId && typeof a.docId === 'string') a.docId = resolveVars(a.docId, vars)\n if (a.parentId && typeof a.parentId === 'string') a.parentId = resolveVars(a.parentId, vars)\n if (a.newParentId && typeof a.newParentId === 'string') a.newParentId = resolveVars(a.newParentId, vars)\n if (a.cardId && typeof a.cardId === 'string') a.cardId = resolveVars(a.cardId, vars)\n if (a.toColumnId && typeof a.toColumnId === 'string') a.toColumnId = resolveVars(a.toColumnId, vars)\n\n // Resolve content fields\n if (a.text && typeof a.text === 'string') a.text = resolveVars(a.text, vars)\n if (a.label && typeof a.label === 'string') a.label = resolveVars(a.label, vars)\n if (a.markdown && typeof a.markdown === 'string') a.markdown = resolveVars(a.markdown, vars)\n if (a.channel && typeof a.channel === 'string') a.channel = resolveVars(a.channel, vars)\n if (a.message && typeof a.message === 'string') a.message = resolveVars(a.message, vars)\n\n return a\n}\n\nexport function createExecutor(ctx: ActionContext): ActionExecutor {\n const execute: ActionExecutor = async (entry: TimelineEntry) => {\n const action = resolveActionVars(entry.action, ctx.vars)\n const actor = entry.actor ? ctx.actors.get(entry.actor) : undefined\n\n switch (action.type) {\n case 'connect': {\n if (!actor) throw new Error('connect requires an actor')\n await executeConnect(actor, ctx.serverConfig)\n break\n }\n case 'disconnect': {\n if (!actor) throw new Error('disconnect requires an actor')\n await executeDisconnect(actor)\n break\n }\n case 'navigate': {\n if (!actor) throw new Error('navigate requires an actor')\n await executeNavigate(actor, action)\n break\n }\n case 'type': {\n if (!actor) throw new Error('type requires an actor')\n await executeType(actor, action)\n break\n }\n case 'typeDelete': {\n if (!actor) throw new Error('typeDelete requires an actor')\n await executeTypeDelete(actor, action)\n break\n }\n case 'select': {\n if (!actor) throw new Error('select requires an actor')\n await executeSelect(actor, action)\n break\n }\n case 'moveCursor': {\n if (!actor) throw new Error('moveCursor requires an actor')\n await executeMoveCursor(actor, action)\n break\n }\n case 'setStatus': {\n if (!actor) throw new Error('setStatus requires an actor')\n await executeSetStatus(actor, action)\n break\n }\n case 'setAwareness': {\n if (!actor) throw new Error('setAwareness requires an actor')\n await executeSetAwareness(actor, action)\n break\n }\n case 'clearAwareness': {\n if (!actor) throw new Error('clearAwareness requires an actor')\n await executeClearAwareness(actor, action)\n break\n }\n case 'createDocument': {\n if (!actor) throw new Error('createDocument requires an actor')\n await executeCreateDocument(actor, action, ctx.vars)\n break\n }\n case 'moveDocument': {\n if (!actor) throw new Error('moveDocument requires an actor')\n await executeMoveDocument(actor, action)\n break\n }\n case 'renameDocument': {\n if (!actor) throw new Error('renameDocument requires an actor')\n await executeRenameDocument(actor, action)\n break\n }\n case 'writeContent': {\n if (!actor) throw new Error('writeContent requires an actor')\n await executeWriteContent(actor, action)\n break\n }\n case 'deleteContent': {\n if (!actor) throw new Error('deleteContent requires an actor')\n await executeDeleteContent(actor, action)\n break\n }\n case 'setMeta': {\n if (!actor) throw new Error('setMeta requires an actor')\n await executeSetMeta(actor, action)\n break\n }\n case 'pointerMove': {\n if (!actor) throw new Error('pointerMove requires an actor')\n await executePointerMove(actor, action)\n break\n }\n case 'scrollTo': {\n if (!actor) throw new Error('scrollTo requires an actor')\n await executeScrollTo(actor, action)\n break\n }\n case 'kanbanHover': {\n if (!actor) throw new Error('kanbanHover requires an actor')\n await executeKanbanHover(actor, action)\n break\n }\n case 'kanbanDrag': {\n if (!actor) throw new Error('kanbanDrag requires an actor')\n await executeKanbanDrag(actor, action)\n break\n }\n case 'sendChat': {\n if (!actor) throw new Error('sendChat requires an actor')\n await executeSendChat(actor, action)\n break\n }\n case 'wait': {\n await executeWait(action)\n break\n }\n case 'parallel': {\n await executeParallel(action, execute)\n break\n }\n case 'sequence': {\n await executeSequence(action, execute)\n break\n }\n case 'repeat': {\n await executeRepeat(action, execute)\n break\n }\n default: {\n throw new Error(`Unknown action type: ${(action as any).type}`)\n }\n }\n }\n\n return execute\n}\n","/**\n * Orchestrator — top-level class that loads a scene, manages actors, and runs the timeline.\n */\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Scene } from './types.ts'\nimport { ActorConnection } from './actor-connection.ts'\nimport { TimelineRunner, type ErrorStrategy } from './timeline-runner.ts'\nimport { createExecutor } from './actions/index.ts'\nimport { log } from './utils.ts'\n\nexport class Orchestrator {\n private scene: Scene | null = null\n private actors = new Map<string, ActorConnection>()\n private vars = new Map<string, string>()\n\n /** Load a scene from a TypeScript file. */\n async load(scriptPath: string): Promise<void> {\n const absPath = resolve(scriptPath)\n const fileUrl = pathToFileURL(absPath).href\n const mod = await import(fileUrl)\n const scene: Scene = mod.default ?? mod\n\n if (!scene.server?.url) {\n throw new Error('Scene must have server.url')\n }\n if (!scene.actors?.length) {\n throw new Error('Scene must have at least one actor')\n }\n if (!scene.timeline?.length) {\n throw new Error('Scene must have at least one timeline entry')\n }\n\n this.scene = scene\n log(`Loaded scene: ${scene.actors.length} actors, ${scene.timeline.length} timeline entries`)\n }\n\n /** Prepare actor connections (does not connect yet — that's a timeline action). */\n prepare(): void {\n if (!this.scene) throw new Error('No scene loaded')\n\n if (this.scene.vars) {\n for (const [k, v] of Object.entries(this.scene.vars)) {\n this.vars.set(k, v)\n }\n }\n\n for (const actorDef of this.scene.actors) {\n if (this.actors.has(actorDef.name)) {\n throw new Error(`Duplicate actor name: ${actorDef.name}`)\n }\n const conn = new ActorConnection(actorDef, this.scene.server)\n this.actors.set(actorDef.name, conn)\n }\n\n log(`Prepared ${this.actors.size} actors: ${[...this.actors.keys()].join(', ')}`)\n }\n\n /** Validate the scene without connecting. Logs the timeline structure. */\n dryRun(): void {\n if (!this.scene) throw new Error('No scene loaded')\n\n const actorNames = new Set(this.scene.actors.map(a => a.name))\n const errors: string[] = []\n\n for (let i = 0; i < this.scene.timeline.length; i++) {\n const entry = this.scene.timeline[i]!\n const prefix = `timeline[${i}]`\n\n if (entry.actor && !actorNames.has(entry.actor)) {\n errors.push(`${prefix}: unknown actor \"${entry.actor}\"`)\n }\n\n const needsActor = !['wait', 'parallel', 'sequence', 'repeat'].includes(entry.action.type)\n if (needsActor && !entry.actor) {\n errors.push(`${prefix}: ${entry.action.type} requires an actor`)\n }\n }\n\n if (errors.length) {\n log(`Dry run found ${errors.length} issue(s):`)\n for (const e of errors) log(` - ${e}`)\n } else {\n log('Dry run: no issues found')\n }\n\n // Print timeline summary\n const sorted = [...this.scene.timeline].sort((a, b) => (a.at ?? 0) - (b.at ?? 0))\n log('Timeline:')\n for (const entry of sorted) {\n const ts = `${((entry.at ?? 0) / 1000).toFixed(1)}s`\n const actorLabel = entry.actor ?? '—'\n log(` [${ts}] ${actorLabel}: ${entry.action.type}`)\n }\n\n if (this.scene.duration) {\n log(`Scene duration: ${(this.scene.duration / 1000).toFixed(1)}s`)\n }\n }\n\n /** Run the timeline. */\n async run(): Promise<void> {\n if (!this.scene) throw new Error('No scene loaded')\n\n // Run onStart hook\n if (this.scene.onStart) {\n log('Running onStart hook...')\n await this.scene.onStart()\n }\n\n const executor = createExecutor({\n actors: this.actors,\n serverConfig: this.scene.server,\n vars: this.vars,\n })\n\n const runner = new TimelineRunner()\n log('Starting timeline...')\n const startTime = Date.now()\n\n if (this.scene.duration) {\n // Race timeline against duration timeout\n const timelinePromise = runner.run(this.scene.timeline, executor)\n const timeoutPromise = new Promise<void>(resolve => {\n setTimeout(() => {\n log(`Scene duration reached (${this.scene!.duration}ms), stopping...`)\n resolve()\n }, this.scene.duration)\n })\n await Promise.race([timelinePromise, timeoutPromise])\n } else {\n await runner.run(this.scene.timeline, executor)\n }\n\n const elapsed = ((Date.now() - startTime) / 1000).toFixed(1)\n log(`Timeline complete in ${elapsed}s`)\n\n // Run onEnd hook\n if (this.scene.onEnd) {\n log('Running onEnd hook...')\n await this.scene.onEnd()\n }\n }\n\n /** Disconnect all actors gracefully. */\n async cleanup(): Promise<void> {\n const disconnects = [...this.actors.values()].map(a => a.disconnect().catch(() => {}))\n await Promise.all(disconnects)\n this.actors.clear()\n this.vars.clear()\n log('All actors disconnected')\n }\n}\n","/**\n * Script definition helpers — typed factory functions for building scenes.\n */\nimport type {\n Scene,\n ActorDef,\n ConnectAction,\n DisconnectAction,\n NavigateAction,\n TypeAction,\n TypeDeleteAction,\n SelectAction,\n MoveCursorAction,\n SetStatusAction,\n SetAwarenessAction,\n ClearAwarenessAction,\n CreateDocumentAction,\n MoveDocumentAction,\n RenameDocumentAction,\n WriteContentAction,\n DeleteContentAction,\n SetMetaAction,\n PointerMoveAction,\n ScrollToAction,\n KanbanHoverAction,\n KanbanDragAction,\n SendChatAction,\n WaitAction,\n ParallelAction,\n SequenceAction,\n RepeatAction,\n TimelineEntry,\n EasingName,\n} from './types.ts'\n\n/** Define a complete scene. */\nexport function defineScene(scene: Scene): Scene {\n return scene\n}\n\n/** Define an actor. */\nexport function actor(name: string, opts: Omit<ActorDef, 'name'>): ActorDef {\n return { name, ...opts }\n}\n\n/** Factory functions for all action types. */\nexport const actions = {\n connect(): ConnectAction {\n return { type: 'connect' }\n },\n\n disconnect(): DisconnectAction {\n return { type: 'disconnect' }\n },\n\n navigate(docId: string): NavigateAction {\n return { type: 'navigate', docId }\n },\n\n type(docId: string, text: string, opts?: { speed?: number; variance?: number; position?: number }): TypeAction {\n return { type: 'type', docId, text, ...opts }\n },\n\n typeDelete(docId: string, count: number, opts?: { speed?: number; variance?: number; position?: number }): TypeDeleteAction {\n return { type: 'typeDelete', docId, count, ...opts }\n },\n\n select(docId: string, anchor: number, head: number): SelectAction {\n return { type: 'select', docId, anchor, head }\n },\n\n moveCursor(docId: string, from: number, to: number, duration: number, easing?: EasingName): MoveCursorAction {\n return { type: 'moveCursor', docId, from, to, duration, easing }\n },\n\n setStatus(status: string | null): SetStatusAction {\n return { type: 'setStatus', status }\n },\n\n setAwareness(fields: Record<string, unknown>, docId?: string): SetAwarenessAction {\n return { type: 'setAwareness', docId, fields }\n },\n\n clearAwareness(fields: string[], docId?: string): ClearAwarenessAction {\n return { type: 'clearAwareness', docId, fields }\n },\n\n createDocument(parentId: string, label: string, opts?: { docType?: string; meta?: Record<string, unknown>; assignId?: string }): CreateDocumentAction {\n return { type: 'createDocument', parentId, label, ...opts }\n },\n\n moveDocument(docId: string, newParentId: string, order?: number): MoveDocumentAction {\n return { type: 'moveDocument', docId, newParentId, order }\n },\n\n renameDocument(docId: string, label: string): RenameDocumentAction {\n return { type: 'renameDocument', docId, label }\n },\n\n writeContent(docId: string, markdown: string): WriteContentAction {\n return { type: 'writeContent', docId, markdown }\n },\n\n deleteContent(docId: string, from: number, length: number): DeleteContentAction {\n return { type: 'deleteContent', docId, from, length }\n },\n\n setMeta(docId: string, meta: Record<string, unknown>): SetMetaAction {\n return { type: 'setMeta', docId, meta }\n },\n\n pointerMove(docId: string, from: { x: number; y: number }, to: { x: number; y: number }, duration: number, easing?: EasingName): PointerMoveAction {\n return { type: 'pointerMove', docId, from, to, duration, easing }\n },\n\n scrollTo(docId: string, position: number): ScrollToAction {\n return { type: 'scrollTo', docId, position }\n },\n\n kanbanHover(docId: string, cardId: string | null): KanbanHoverAction {\n return { type: 'kanbanHover', docId, cardId }\n },\n\n kanbanDrag(docId: string, cardId: string, toColumnId: string, duration: number): KanbanDragAction {\n return { type: 'kanbanDrag', docId, cardId, toColumnId, duration }\n },\n\n sendChat(channel: string, message: string): SendChatAction {\n return { type: 'sendChat', channel, message }\n },\n\n wait(duration: number): WaitAction {\n return { type: 'wait', duration }\n },\n\n parallel(entries: TimelineEntry[]): ParallelAction {\n return { type: 'parallel', actions: entries }\n },\n\n sequence(entries: TimelineEntry[]): SequenceAction {\n return { type: 'sequence', actions: entries }\n },\n\n repeat(times: number, entries: TimelineEntry[]): RepeatAction {\n return { type: 'repeat', times, actions: entries }\n },\n}\n","#!/usr/bin/env node\n/**\n * Abracadabra Orchestrator — CouShell commercial director.\n *\n * Usage (after pnpm build:packages):\n * node --experimental-transform-types \\\n * packages/orchestrator/dist/abracadabra-orchestrator.esm.js ./scripts/demo.ts\n *\n * Dry run:\n * node --experimental-transform-types \\\n * packages/orchestrator/dist/abracadabra-orchestrator.esm.js --dry-run ./scripts/demo.ts\n */\nimport { Orchestrator } from './orchestrator.ts'\n\n// Re-export public API for script files\nexport { defineScene, actor, actions } from './define.ts'\nexport { Orchestrator } from './orchestrator.ts'\nexport type {\n Scene,\n ActorDef,\n ServerConfig,\n Action,\n TimelineEntry,\n ConnectAction,\n DisconnectAction,\n NavigateAction,\n TypeAction,\n TypeDeleteAction,\n SelectAction,\n MoveCursorAction,\n SetStatusAction,\n SetAwarenessAction,\n ClearAwarenessAction,\n CreateDocumentAction,\n MoveDocumentAction,\n RenameDocumentAction,\n WriteContentAction,\n DeleteContentAction,\n SetMetaAction,\n PointerMoveAction,\n ScrollToAction,\n KanbanHoverAction,\n KanbanDragAction,\n SendChatAction,\n RepeatAction,\n WaitAction,\n ParallelAction,\n SequenceAction,\n EasingName,\n} from './types.ts'\n\nasync function main() {\n const args = process.argv.slice(2)\n const dryRun = args.includes('--dry-run')\n const scriptPath = args.find(a => !a.startsWith('--'))\n\n if (!scriptPath) {\n console.error('Usage: abracadabra-orchestrator [--dry-run] <script.ts>')\n console.error('')\n console.error(' The script file should export a Scene object (use defineScene()).')\n console.error('')\n console.error('Options:')\n console.error(' --dry-run Validate the scene without connecting to the server')\n console.error('')\n console.error('Example:')\n console.error(' node --conditions=source --experimental-transform-types \\\\')\n console.error(' packages/orchestrator/src/index.ts ./scripts/demo.ts')\n process.exit(1)\n }\n\n const orchestrator = new Orchestrator()\n\n try {\n await orchestrator.load(scriptPath)\n orchestrator.prepare()\n\n if (dryRun) {\n orchestrator.dryRun()\n } else {\n await orchestrator.run()\n }\n } catch (err: any) {\n console.error(`[orchestrator] Fatal: ${err.message}`)\n process.exit(1)\n } finally {\n if (!dryRun) {\n await orchestrator.cleanup()\n }\n }\n}\n\n// Only run CLI when executed directly (not imported as a library)\n// Check if argv[1] points to a file within this package's directory\nimport { fileURLToPath } from 'node:url'\nimport { dirname, resolve } from 'node:path'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nif (process.argv[1]) {\n const resolved = resolve(process.argv[1])\n if (resolved.startsWith(__dirname) || resolved.includes('abracadabra-orchestrator')) {\n main()\n }\n}\n"],"x_google_ignoreList":[0,1,2,3],"mappings":";;;;;;;;;;;;;;;;;;;;AAUA,SAAgB,QAAQ,GAAG;AAKvB,QAAQ,aAAa,cAChB,YAAY,OAAO,EAAE,IAClB,EAAE,YAAY,SAAS,gBACvB,uBAAuB,KACvB,EAAE,sBAAsB;;;;;;;;;;;;;;;;AAsCpC,SAAgB,OAAO,OAAO,QAAQ,QAAQ,IAAI;CAC9C,MAAM,QAAQ,QAAQ,MAAM;CAC5B,MAAM,MAAM,OAAO;CACnB,MAAM,WAAW,WAAW;AAC5B,KAAI,CAAC,SAAU,YAAY,QAAQ,QAAS;EACxC,MAAM,SAAS,SAAS,IAAI,MAAM;EAClC,MAAM,QAAQ,WAAW,cAAc,WAAW;EAClD,MAAM,MAAM,QAAQ,UAAU,QAAQ,QAAQ,OAAO;EACrD,MAAM,UAAU,SAAS,wBAAwB,QAAQ,WAAW;AACpE,MAAI,CAAC,MACD,OAAM,IAAI,UAAU,QAAQ;AAChC,QAAM,IAAI,WAAW,QAAQ;;AAEjC,QAAO;;;;;;;;;;;;;;;;AA2DX,SAAgB,QAAQ,UAAU,gBAAgB,MAAM;AACpD,KAAI,SAAS,UACT,OAAM,IAAI,MAAM,mCAAmC;AACvD,KAAI,iBAAiB,SAAS,SAC1B,OAAM,IAAI,MAAM,wCAAwC;;;;;;;;;;;;;;;;;;AAkBhE,SAAgB,QAAQ,KAAK,UAAU;AACnC,QAAO,KAAK,QAAW,sBAAsB;CAC7C,MAAM,MAAM,SAAS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