@abraca/orchestrator 2.33.0 → 2.35.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.
@@ -2,671 +2,10 @@
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import * as Y from "yjs";
5
- import { AbracadabraClient, AbracadabraProvider } from "@abraca/dabra";
6
- import * as ed from "@noble/ed25519";
7
- import { mkdir, readFile, writeFile } from "node:fs/promises";
8
- import { existsSync } from "node:fs";
5
+ import { AbracadabraClient, deterministicKeypair, loadOrCreateKeyFile, loginOrRegisterWithKey, openSyncedProvider, pickEntrySpace, waitForSync } from "@abraca/dabra";
6
+ import { populateYDocFromMarkdown } from "@abraca/convert";
9
7
 
10
- //#region node_modules/@noble/hashes/utils.js
11
- /**
12
- * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
13
- * @param a - value to test
14
- * @returns `true` when the value is a Uint8Array-compatible view.
15
- * @example
16
- * Check whether a value is a Uint8Array-compatible view.
17
- * ```ts
18
- * isBytes(new Uint8Array([1, 2, 3]));
19
- * ```
20
- */
21
- function isBytes(a) {
22
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
23
- }
24
- /**
25
- * Asserts something is Uint8Array.
26
- * @param value - value to validate
27
- * @param length - optional exact length constraint
28
- * @param title - label included in thrown errors
29
- * @returns The validated byte array.
30
- * @throws On wrong argument types. {@link TypeError}
31
- * @throws On wrong argument ranges or values. {@link RangeError}
32
- * @example
33
- * Validate that a value is a byte array.
34
- * ```ts
35
- * abytes(new Uint8Array([1, 2, 3]));
36
- * ```
37
- */
38
- function abytes(value, length, title = "") {
39
- const bytes = isBytes(value);
40
- const len = value?.length;
41
- const needsLen = length !== void 0;
42
- if (!bytes || needsLen && len !== length) {
43
- const prefix = title && `"${title}" `;
44
- const ofLen = needsLen ? ` of length ${length}` : "";
45
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
46
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
47
- if (!bytes) throw new TypeError(message);
48
- throw new RangeError(message);
49
- }
50
- return value;
51
- }
52
- /**
53
- * Asserts a hash instance has not been destroyed or finished.
54
- * @param instance - hash instance to validate
55
- * @param checkFinished - whether to reject finalized instances
56
- * @throws If the hash instance has already been destroyed or finalized. {@link Error}
57
- * @example
58
- * Validate that a hash instance is still usable.
59
- * ```ts
60
- * import { aexists } from '@noble/hashes/utils.js';
61
- * import { sha256 } from '@noble/hashes/sha2.js';
62
- * const hash = sha256.create();
63
- * aexists(hash);
64
- * ```
65
- */
66
- function aexists(instance, checkFinished = true) {
67
- if (instance.destroyed) throw new Error("Hash instance has been destroyed");
68
- if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
69
- }
70
- /**
71
- * Asserts output is a sufficiently-sized byte array.
72
- * @param out - destination buffer
73
- * @param instance - hash instance providing output length
74
- * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
75
- * @throws On wrong argument types. {@link TypeError}
76
- * @throws On wrong argument ranges or values. {@link RangeError}
77
- * @example
78
- * Validate a caller-provided digest buffer.
79
- * ```ts
80
- * import { aoutput } from '@noble/hashes/utils.js';
81
- * import { sha256 } from '@noble/hashes/sha2.js';
82
- * const hash = sha256.create();
83
- * aoutput(new Uint8Array(hash.outputLen), hash);
84
- * ```
85
- */
86
- function aoutput(out, instance) {
87
- abytes(out, void 0, "digestInto() output");
88
- const min = instance.outputLen;
89
- if (out.length < min) throw new RangeError("\"digestInto() output\" expected to be of length >=" + min);
90
- }
91
- /**
92
- * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
93
- * @param arrays - arrays to overwrite with zeros
94
- * @example
95
- * Zeroize sensitive buffers in place.
96
- * ```ts
97
- * clean(new Uint8Array([1, 2, 3]));
98
- * ```
99
- */
100
- function clean(...arrays) {
101
- for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
102
- }
103
- /**
104
- * Creates a DataView for byte-level manipulation.
105
- * @param arr - source typed array
106
- * @returns DataView over the same buffer region.
107
- * @example
108
- * Create a DataView over an existing buffer.
109
- * ```ts
110
- * createView(new Uint8Array(4));
111
- * ```
112
- */
113
- function createView(arr) {
114
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
115
- }
116
- /** Whether the current platform is little-endian. */
117
- const isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
118
- const hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
119
- /**
120
- * Creates a callable hash function from a stateful class constructor.
121
- * @param hashCons - hash constructor or factory
122
- * @param info - optional metadata such as DER OID
123
- * @returns Frozen callable hash wrapper with `.create()`.
124
- * Wrapper construction eagerly calls `hashCons(undefined)` once to read
125
- * `outputLen` / `blockLen`, so constructor side effects happen at module
126
- * init time.
127
- * @example
128
- * Wrap a stateful hash constructor into a callable helper.
129
- * ```ts
130
- * import { createHasher } from '@noble/hashes/utils.js';
131
- * import { sha256 } from '@noble/hashes/sha2.js';
132
- * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
133
- * wrapped(new Uint8Array([1]));
134
- * ```
135
- */
136
- function createHasher(hashCons, info = {}) {
137
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
138
- const tmp = hashCons(void 0);
139
- hashC.outputLen = tmp.outputLen;
140
- hashC.blockLen = tmp.blockLen;
141
- hashC.canXOF = tmp.canXOF;
142
- hashC.create = (opts) => hashCons(opts);
143
- Object.assign(hashC, info);
144
- return Object.freeze(hashC);
145
- }
146
- /**
147
- * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
148
- * @param suffix - final OID byte for the selected hash.
149
- * The helper accepts any byte even though only the documented NIST hash
150
- * suffixes are meaningful downstream.
151
- * @returns Object containing the DER-encoded OID.
152
- * @example
153
- * Build OID metadata for a NIST hash.
154
- * ```ts
155
- * oidNist(0x01);
156
- * ```
157
- */
158
- const oidNist = (suffix) => ({ oid: Uint8Array.from([
159
- 6,
160
- 9,
161
- 96,
162
- 134,
163
- 72,
164
- 1,
165
- 101,
166
- 3,
167
- 4,
168
- 2,
169
- suffix
170
- ]) });
171
-
172
- //#endregion
173
- //#region node_modules/@noble/hashes/_md.js
174
- /**
175
- * Internal Merkle-Damgard hash utils.
176
- * @module
177
- */
178
- /**
179
- * Merkle-Damgard hash construction base class.
180
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
181
- * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
182
- * strings with partial-byte tails.
183
- * @param blockLen - internal block size in bytes
184
- * @param outputLen - digest size in bytes
185
- * @param padOffset - trailing length field size in bytes
186
- * @param isLE - whether length and state words are encoded in little-endian
187
- * @example
188
- * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
189
- * ```ts
190
- * import { _SHA1 } from '@noble/hashes/legacy.js';
191
- * const hash = new _SHA1();
192
- * hash.update(new Uint8Array([97, 98, 99]));
193
- * hash.digest();
194
- * ```
195
- */
196
- var HashMD = class {
197
- blockLen;
198
- outputLen;
199
- canXOF = false;
200
- padOffset;
201
- isLE;
202
- buffer;
203
- view;
204
- finished = false;
205
- length = 0;
206
- pos = 0;
207
- destroyed = false;
208
- constructor(blockLen, outputLen, padOffset, isLE) {
209
- this.blockLen = blockLen;
210
- this.outputLen = outputLen;
211
- this.padOffset = padOffset;
212
- this.isLE = isLE;
213
- this.buffer = new Uint8Array(blockLen);
214
- this.view = createView(this.buffer);
215
- }
216
- update(data) {
217
- aexists(this);
218
- abytes(data);
219
- const { view, buffer, blockLen } = this;
220
- const len = data.length;
221
- for (let pos = 0; pos < len;) {
222
- const take = Math.min(blockLen - this.pos, len - pos);
223
- if (take === blockLen) {
224
- const dataView = createView(data);
225
- for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
226
- continue;
227
- }
228
- buffer.set(data.subarray(pos, pos + take), this.pos);
229
- this.pos += take;
230
- pos += take;
231
- if (this.pos === blockLen) {
232
- this.process(view, 0);
233
- this.pos = 0;
234
- }
235
- }
236
- this.length += data.length;
237
- this.roundClean();
238
- return this;
239
- }
240
- digestInto(out) {
241
- aexists(this);
242
- aoutput(out, this);
243
- this.finished = true;
244
- const { buffer, view, blockLen, isLE } = this;
245
- let { pos } = this;
246
- buffer[pos++] = 128;
247
- clean(this.buffer.subarray(pos));
248
- if (this.padOffset > blockLen - pos) {
249
- this.process(view, 0);
250
- pos = 0;
251
- }
252
- for (let i = pos; i < blockLen; i++) buffer[i] = 0;
253
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
254
- this.process(view, 0);
255
- const oview = createView(out);
256
- const len = this.outputLen;
257
- if (len % 4) throw new Error("_sha2: outputLen must be aligned to 32bit");
258
- const outLen = len / 4;
259
- const state = this.get();
260
- if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
261
- for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
262
- }
263
- digest() {
264
- const { buffer, outputLen } = this;
265
- this.digestInto(buffer);
266
- const res = buffer.slice(0, outputLen);
267
- this.destroy();
268
- return res;
269
- }
270
- _cloneInto(to) {
271
- to ||= new this.constructor();
272
- to.set(...this.get());
273
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
274
- to.destroyed = destroyed;
275
- to.finished = finished;
276
- to.length = length;
277
- to.pos = pos;
278
- if (length % blockLen) to.buffer.set(buffer);
279
- return to;
280
- }
281
- clone() {
282
- return this._cloneInto();
283
- }
284
- };
285
- /** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
286
- * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
287
- * eight prime numbers. Exported as a shared table; callers must treat it as read-only because
288
- * constructors copy halves from it by index. */
289
- const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
290
- 1779033703,
291
- 4089235720,
292
- 3144134277,
293
- 2227873595,
294
- 1013904242,
295
- 4271175723,
296
- 2773480762,
297
- 1595750129,
298
- 1359893119,
299
- 2917565137,
300
- 2600822924,
301
- 725511199,
302
- 528734635,
303
- 4215389547,
304
- 1541459225,
305
- 327033209
306
- ]);
307
-
308
- //#endregion
309
- //#region node_modules/@noble/hashes/_u64.js
310
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
311
- const _32n = /* @__PURE__ */ BigInt(32);
312
- function fromBig(n, le = false) {
313
- if (le) return {
314
- h: Number(n & U32_MASK64),
315
- l: Number(n >> _32n & U32_MASK64)
316
- };
317
- return {
318
- h: Number(n >> _32n & U32_MASK64) | 0,
319
- l: Number(n & U32_MASK64) | 0
320
- };
321
- }
322
- function split(lst, le = false) {
323
- const len = lst.length;
324
- let Ah = new Uint32Array(len);
325
- let Al = new Uint32Array(len);
326
- for (let i = 0; i < len; i++) {
327
- const { h, l } = fromBig(lst[i], le);
328
- [Ah[i], Al[i]] = [h, l];
329
- }
330
- return [Ah, Al];
331
- }
332
- const shrSH = (h, _l, s) => h >>> s;
333
- const shrSL = (h, l, s) => h << 32 - s | l >>> s;
334
- const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
335
- const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
336
- const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
337
- const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
338
- function add(Ah, Al, Bh, Bl) {
339
- const l = (Al >>> 0) + (Bl >>> 0);
340
- return {
341
- h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
342
- l: l | 0
343
- };
344
- }
345
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
346
- const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
347
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
348
- const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
349
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
350
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
351
-
352
- //#endregion
353
- //#region node_modules/@noble/hashes/sha2.js
354
- /**
355
- * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
356
- * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
357
- * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
358
- * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
359
- * @module
360
- */
361
- const K512 = split([
362
- "0x428a2f98d728ae22",
363
- "0x7137449123ef65cd",
364
- "0xb5c0fbcfec4d3b2f",
365
- "0xe9b5dba58189dbbc",
366
- "0x3956c25bf348b538",
367
- "0x59f111f1b605d019",
368
- "0x923f82a4af194f9b",
369
- "0xab1c5ed5da6d8118",
370
- "0xd807aa98a3030242",
371
- "0x12835b0145706fbe",
372
- "0x243185be4ee4b28c",
373
- "0x550c7dc3d5ffb4e2",
374
- "0x72be5d74f27b896f",
375
- "0x80deb1fe3b1696b1",
376
- "0x9bdc06a725c71235",
377
- "0xc19bf174cf692694",
378
- "0xe49b69c19ef14ad2",
379
- "0xefbe4786384f25e3",
380
- "0x0fc19dc68b8cd5b5",
381
- "0x240ca1cc77ac9c65",
382
- "0x2de92c6f592b0275",
383
- "0x4a7484aa6ea6e483",
384
- "0x5cb0a9dcbd41fbd4",
385
- "0x76f988da831153b5",
386
- "0x983e5152ee66dfab",
387
- "0xa831c66d2db43210",
388
- "0xb00327c898fb213f",
389
- "0xbf597fc7beef0ee4",
390
- "0xc6e00bf33da88fc2",
391
- "0xd5a79147930aa725",
392
- "0x06ca6351e003826f",
393
- "0x142929670a0e6e70",
394
- "0x27b70a8546d22ffc",
395
- "0x2e1b21385c26c926",
396
- "0x4d2c6dfc5ac42aed",
397
- "0x53380d139d95b3df",
398
- "0x650a73548baf63de",
399
- "0x766a0abb3c77b2a8",
400
- "0x81c2c92e47edaee6",
401
- "0x92722c851482353b",
402
- "0xa2bfe8a14cf10364",
403
- "0xa81a664bbc423001",
404
- "0xc24b8b70d0f89791",
405
- "0xc76c51a30654be30",
406
- "0xd192e819d6ef5218",
407
- "0xd69906245565a910",
408
- "0xf40e35855771202a",
409
- "0x106aa07032bbd1b8",
410
- "0x19a4c116b8d2d0c8",
411
- "0x1e376c085141ab53",
412
- "0x2748774cdf8eeb99",
413
- "0x34b0bcb5e19b48a8",
414
- "0x391c0cb3c5c95a63",
415
- "0x4ed8aa4ae3418acb",
416
- "0x5b9cca4f7763e373",
417
- "0x682e6ff3d6b2b8a3",
418
- "0x748f82ee5defb2fc",
419
- "0x78a5636f43172f60",
420
- "0x84c87814a1f0ab72",
421
- "0x8cc702081a6439ec",
422
- "0x90befffa23631e28",
423
- "0xa4506cebde82bde9",
424
- "0xbef9a3f7b2c67915",
425
- "0xc67178f2e372532b",
426
- "0xca273eceea26619c",
427
- "0xd186b8c721c0c207",
428
- "0xeada7dd6cde0eb1e",
429
- "0xf57d4f7fee6ed178",
430
- "0x06f067aa72176fba",
431
- "0x0a637dc5a2c898a6",
432
- "0x113f9804bef90dae",
433
- "0x1b710b35131c471b",
434
- "0x28db77f523047d84",
435
- "0x32caab7b40c72493",
436
- "0x3c9ebe0a15c9bebc",
437
- "0x431d67c49c100d4c",
438
- "0x4cc5d4becb3e42b6",
439
- "0x597f299cfc657e2a",
440
- "0x5fcb6fab3ad6faec",
441
- "0x6c44198c4a475817"
442
- ].map((n) => BigInt(n)));
443
- const SHA512_Kh = K512[0];
444
- const SHA512_Kl = K512[1];
445
- const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
446
- const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
447
- /** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */
448
- var SHA2_64B = class extends HashMD {
449
- constructor(outputLen) {
450
- super(128, outputLen, 16, false);
451
- }
452
- get() {
453
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
454
- return [
455
- Ah,
456
- Al,
457
- Bh,
458
- Bl,
459
- Ch,
460
- Cl,
461
- Dh,
462
- Dl,
463
- Eh,
464
- El,
465
- Fh,
466
- Fl,
467
- Gh,
468
- Gl,
469
- Hh,
470
- Hl
471
- ];
472
- }
473
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
474
- this.Ah = Ah | 0;
475
- this.Al = Al | 0;
476
- this.Bh = Bh | 0;
477
- this.Bl = Bl | 0;
478
- this.Ch = Ch | 0;
479
- this.Cl = Cl | 0;
480
- this.Dh = Dh | 0;
481
- this.Dl = Dl | 0;
482
- this.Eh = Eh | 0;
483
- this.El = El | 0;
484
- this.Fh = Fh | 0;
485
- this.Fl = Fl | 0;
486
- this.Gh = Gh | 0;
487
- this.Gl = Gl | 0;
488
- this.Hh = Hh | 0;
489
- this.Hl = Hl | 0;
490
- }
491
- process(view, offset) {
492
- for (let i = 0; i < 16; i++, offset += 4) {
493
- SHA512_W_H[i] = view.getUint32(offset);
494
- SHA512_W_L[i] = view.getUint32(offset += 4);
495
- }
496
- for (let i = 16; i < 80; i++) {
497
- const W15h = SHA512_W_H[i - 15] | 0;
498
- const W15l = SHA512_W_L[i - 15] | 0;
499
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
500
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
501
- const W2h = SHA512_W_H[i - 2] | 0;
502
- const W2l = SHA512_W_L[i - 2] | 0;
503
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
504
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
505
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
506
- SHA512_W_H[i] = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]) | 0;
507
- SHA512_W_L[i] = SUMl | 0;
508
- }
509
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
510
- for (let i = 0; i < 80; i++) {
511
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
512
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
513
- const CHIh = Eh & Fh ^ ~Eh & Gh;
514
- const CHIl = El & Fl ^ ~El & Gl;
515
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
516
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
517
- const T1l = T1ll | 0;
518
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
519
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
520
- const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
521
- const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
522
- Hh = Gh | 0;
523
- Hl = Gl | 0;
524
- Gh = Fh | 0;
525
- Gl = Fl | 0;
526
- Fh = Eh | 0;
527
- Fl = El | 0;
528
- ({h: Eh, l: El} = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
529
- Dh = Ch | 0;
530
- Dl = Cl | 0;
531
- Ch = Bh | 0;
532
- Cl = Bl | 0;
533
- Bh = Ah | 0;
534
- Bl = Al | 0;
535
- const All = add3L(T1l, sigma0l, MAJl);
536
- Ah = add3H(All, T1h, sigma0h, MAJh);
537
- Al = All | 0;
538
- }
539
- ({h: Ah, l: Al} = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
540
- ({h: Bh, l: Bl} = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
541
- ({h: Ch, l: Cl} = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
542
- ({h: Dh, l: Dl} = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
543
- ({h: Eh, l: El} = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
544
- ({h: Fh, l: Fl} = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
545
- ({h: Gh, l: Gl} = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
546
- ({h: Hh, l: Hl} = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
547
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
548
- }
549
- roundClean() {
550
- clean(SHA512_W_H, SHA512_W_L);
551
- }
552
- destroy() {
553
- this.destroyed = true;
554
- clean(this.buffer);
555
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
556
- }
557
- };
558
- /** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */
559
- var _SHA512 = class extends SHA2_64B {
560
- Ah = SHA512_IV[0] | 0;
561
- Al = SHA512_IV[1] | 0;
562
- Bh = SHA512_IV[2] | 0;
563
- Bl = SHA512_IV[3] | 0;
564
- Ch = SHA512_IV[4] | 0;
565
- Cl = SHA512_IV[5] | 0;
566
- Dh = SHA512_IV[6] | 0;
567
- Dl = SHA512_IV[7] | 0;
568
- Eh = SHA512_IV[8] | 0;
569
- El = SHA512_IV[9] | 0;
570
- Fh = SHA512_IV[10] | 0;
571
- Fl = SHA512_IV[11] | 0;
572
- Gh = SHA512_IV[12] | 0;
573
- Gl = SHA512_IV[13] | 0;
574
- Hh = SHA512_IV[14] | 0;
575
- Hl = SHA512_IV[15] | 0;
576
- constructor() {
577
- super(64);
578
- }
579
- };
580
- /**
581
- * SHA2-512 hash function from RFC 4634.
582
- * @param msg - message bytes to hash
583
- * @returns Digest bytes.
584
- * @example
585
- * Hash a message with SHA2-512.
586
- * ```ts
587
- * sha512(new Uint8Array([97, 98, 99]));
588
- * ```
589
- */
590
- const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), /* @__PURE__ */ oidNist(3));
591
-
592
- //#endregion
593
- //#region packages/orchestrator/src/crypto.ts
594
- /**
595
- * Ed25519 key generation, persistence, and challenge signing for actor auth.
596
- * Copied from packages/mcp/src/crypto.ts
597
- */
598
- ed.hashes.sha512 = sha512;
599
- ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
600
- function toBase64url(bytes) {
601
- return Buffer.from(bytes).toString("base64url");
602
- }
603
- function fromBase64url(b64) {
604
- return new Uint8Array(Buffer.from(b64, "base64url"));
605
- }
606
- /**
607
- * Load an existing Ed25519 keypair from disk, or generate and persist a new one.
608
- */
609
- async function loadOrCreateKeypair(keyPath) {
610
- if (existsSync(keyPath)) {
611
- const seed = await readFile(keyPath);
612
- if (seed.length !== 32) throw new Error(`Invalid key file at ${keyPath}: expected 32 bytes, got ${seed.length}`);
613
- const privateKey = new Uint8Array(seed);
614
- return {
615
- privateKey,
616
- publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
617
- };
618
- }
619
- const privateKey = ed.utils.randomSecretKey();
620
- const publicKey = ed.getPublicKey(privateKey);
621
- const dir = dirname(keyPath);
622
- if (!existsSync(dir)) await mkdir(dir, {
623
- recursive: true,
624
- mode: 448
625
- });
626
- await writeFile(keyPath, Buffer.from(privateKey), { mode: 384 });
627
- console.error(`[orchestrator] Generated new keypair at ${keyPath}`);
628
- return {
629
- privateKey,
630
- publicKeyB64: toBase64url(publicKey)
631
- };
632
- }
633
- /**
634
- * Generate a deterministic Ed25519 keypair from a seed string (e.g. actor name).
635
- * The same seed always produces the same keypair.
636
- */
637
- function deterministicKeypair(seed) {
638
- const privateKey = sha512(new TextEncoder().encode(seed + ":orchestrator-salt")).slice(0, 32);
639
- return {
640
- privateKey,
641
- publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
642
- };
643
- }
644
- /** Sign a base64url challenge with the agent's private key; returns base64url signature. */
645
- function signChallenge(challengeB64, privateKey) {
646
- const challenge = fromBase64url(challengeB64);
647
- return toBase64url(ed.sign(challenge, privateKey));
648
- }
649
-
650
- //#endregion
651
8
  //#region packages/orchestrator/src/utils.ts
652
- /**
653
- * Utility functions for the orchestrator.
654
- */
655
- /** Wait for a provider's `synced` event with a timeout. Resolves immediately if already synced. */
656
- function waitForSync(provider, timeoutMs = 15e3) {
657
- if (provider.synced) return Promise.resolve();
658
- return new Promise((resolve, reject) => {
659
- const timer = setTimeout(() => {
660
- provider.off("synced", handler);
661
- reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
662
- }, timeoutMs);
663
- function handler() {
664
- clearTimeout(timer);
665
- resolve();
666
- }
667
- provider.on("synced", handler);
668
- });
669
- }
670
9
  /** Sleep for a given number of milliseconds. */
671
10
  function sleep(ms) {
672
11
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -897,39 +236,23 @@ var ActorConnection = class {
897
236
  }
898
237
  /** Connect, authenticate, discover root doc, sync, and set awareness. */
899
238
  async connect(serverConfig) {
900
- const keypair = this.actor.keyFile ? await loadOrCreateKeypair(this.actor.keyFile) : deterministicKeypair(this.actor.name);
239
+ const keypair = this.actor.keyFile ? await loadOrCreateKeyFile(this.actor.keyFile) : deterministicKeypair(this.actor.name);
901
240
  this._publicKey = keypair.publicKeyB64;
902
- const signFn = (challenge) => Promise.resolve(signChallenge(challenge, keypair.privateKey));
903
- try {
904
- await this.client.loginWithKey(keypair.publicKeyB64, signFn);
905
- } catch (err) {
906
- const status = err?.status ?? err?.response?.status;
907
- if (status === 404 || status === 422) {
908
- log(`${this.actor.name}: registering new account...`);
909
- await this.client.registerWithKey({
910
- publicKey: keypair.publicKeyB64,
911
- username: this.actor.name.replace(/\s+/g, "-").toLowerCase(),
912
- displayName: this.actor.name,
913
- deviceName: "Orchestrator Actor",
914
- inviteCode: serverConfig.inviteCode
915
- });
916
- await this.client.loginWithKey(keypair.publicKeyB64, signFn);
917
- } else throw err;
918
- }
241
+ await loginOrRegisterWithKey(this.client, keypair, {
242
+ displayName: this.actor.name,
243
+ deviceName: "Orchestrator Actor",
244
+ inviteCode: serverConfig.inviteCode,
245
+ onRegister: () => log(`${this.actor.name}: registering new account...`)
246
+ });
919
247
  log(`${this.actor.name}: authenticated (${keypair.publicKeyB64.slice(0, 12)}...)`);
920
- const roots = await this.client.listChildren();
921
- const rootDocId = (roots.find((d) => d.kind === "space") ?? roots[0])?.id ?? null;
248
+ const { entry } = pickEntrySpace(await this.client.listChildren());
249
+ const rootDocId = entry?.id ?? null;
922
250
  if (!rootDocId) throw new Error(`${this.actor.name}: no root document found`);
923
251
  this._rootDocId = rootDocId;
924
- const doc = new Y.Doc({ guid: rootDocId });
925
- const provider = new AbracadabraProvider({
926
- name: rootDocId,
927
- document: doc,
252
+ const { doc, provider } = await openSyncedProvider({
928
253
  client: this.client,
929
- disableOfflineStore: true,
930
- subdocLoading: "lazy"
254
+ docId: rootDocId
931
255
  });
932
- await waitForSync(provider);
933
256
  this._rootDoc = doc;
934
257
  this._rootProvider = provider;
935
258
  provider.awareness.setLocalStateField("user", {
@@ -1185,819 +508,6 @@ async function executeSelect(actor, action) {
1185
508
  actor.setSelection(action.docId, action.anchor, action.head);
1186
509
  }
1187
510
 
1188
- //#endregion
1189
- //#region packages/orchestrator/src/converters/markdownToYjs.ts
1190
- /**
1191
- * Markdown → Y.js converter.
1192
- * Ported from cou-sh/app/utils/markdownToYjs.ts with Vue dependency removed.
1193
- */
1194
- function parseInline(text) {
1195
- const stripped = text.replace(/\{lang="[^"]*"\}/g, "").replace(/:(?!badge|icon|kbd)(\w[\w-]*)\[([^\]]*)\](\{[^}]*\})?/g, "$2").replace(/:(?!badge|icon|kbd)(\w[\w-]*)(\{[^}]*\})/g, "");
1196
- const tokens = [];
1197
- const re = /:badge\[([^\]]*)\](\{[^}]*\})?|:icon\{([^}]*)\}|:kbd\{([^}]*)\}|!?\[\[([^\]|]+?)(?:\|([^\]]+?))?\]\]|~~(.+?)~~|\*\*(.+?)\*\*|\*(.+?)\*|_(.+?)_|`(.+?)`|\[(.+?)\]\((.+?)\)/g;
1198
- let lastIndex = 0;
1199
- let match;
1200
- while ((match = re.exec(stripped)) !== null) {
1201
- if (match.index > lastIndex) tokens.push({ text: stripped.slice(lastIndex, match.index) });
1202
- if (match[1] !== void 0) {
1203
- const badgeProps = parseMdcProps(match[2]);
1204
- tokens.push({
1205
- text: match[1] || "Badge",
1206
- attrs: { badge: {
1207
- label: match[1] || "Badge",
1208
- color: badgeProps["color"] || "neutral",
1209
- variant: badgeProps["variant"] || "subtle"
1210
- } }
1211
- });
1212
- } else if (match[3] !== void 0) {
1213
- const iconProps = parseMdcProps(`{${match[3]}}`);
1214
- tokens.push({
1215
- text: "​",
1216
- attrs: { proseIcon: { name: iconProps["name"] || "i-lucide-star" } }
1217
- });
1218
- } else if (match[4] !== void 0) {
1219
- const kbdProps = parseMdcProps(`{${match[4]}}`);
1220
- tokens.push({
1221
- text: kbdProps["value"] || "",
1222
- attrs: { kbd: { value: kbdProps["value"] || "" } }
1223
- });
1224
- } else if (match[5] !== void 0) tokens.push({
1225
- text: "",
1226
- node: "docLink",
1227
- nodeAttrs: { docId: match[5] }
1228
- });
1229
- else if (match[7] !== void 0) tokens.push({
1230
- text: match[7],
1231
- attrs: { strike: true }
1232
- });
1233
- else if (match[8] !== void 0) tokens.push({
1234
- text: match[8],
1235
- attrs: { bold: true }
1236
- });
1237
- else if (match[9] !== void 0) tokens.push({
1238
- text: match[9],
1239
- attrs: { italic: true }
1240
- });
1241
- else if (match[10] !== void 0) tokens.push({
1242
- text: match[10],
1243
- attrs: { italic: true }
1244
- });
1245
- else if (match[11] !== void 0) tokens.push({
1246
- text: match[11],
1247
- attrs: { code: true }
1248
- });
1249
- else if (match[12] !== void 0 && match[13] !== void 0) tokens.push({
1250
- text: match[12],
1251
- attrs: { link: { href: match[13] } }
1252
- });
1253
- lastIndex = match.index + match[0].length;
1254
- }
1255
- if (lastIndex < stripped.length) tokens.push({ text: stripped.slice(lastIndex) });
1256
- return tokens.filter((t) => t.node || t.text.length > 0);
1257
- }
1258
- function parseTableRow(line) {
1259
- const parts = line.split("|");
1260
- return parts.slice(1, parts.length - 1).map((c) => c.trim());
1261
- }
1262
- function isTableSeparator(line) {
1263
- return /^\|[\s|:-]+\|$/.test(line.trim());
1264
- }
1265
- function extractFencedCode(lines) {
1266
- const result = [];
1267
- let i = 0;
1268
- while (i < lines.length) {
1269
- const fenceMatch = lines[i].match(/^(`{3,})(\w*)/);
1270
- if (fenceMatch) {
1271
- const fence = fenceMatch[1];
1272
- const lang = fenceMatch[2] ?? "";
1273
- const codeLines = [];
1274
- i++;
1275
- while (i < lines.length && !lines[i].startsWith(fence)) {
1276
- codeLines.push(lines[i]);
1277
- i++;
1278
- }
1279
- i++;
1280
- result.push({
1281
- type: "codeBlock",
1282
- lang,
1283
- code: codeLines.join("\n")
1284
- });
1285
- continue;
1286
- }
1287
- i++;
1288
- }
1289
- return result;
1290
- }
1291
- function parseMdcProps(propsStr) {
1292
- if (!propsStr) return {};
1293
- const result = {};
1294
- const re = /(\w[\w-]*)="([^"]*)"/g;
1295
- let m;
1296
- while ((m = re.exec(propsStr)) !== null) result[m[1]] = m[2];
1297
- return result;
1298
- }
1299
- function parseMdcChildren(innerLines, slotPrefix) {
1300
- const items = [];
1301
- let current = null;
1302
- const slotRe = new RegExp(`^#${slotPrefix}(\\{[^}]*\\})?\\s*$`);
1303
- for (const line of innerLines) {
1304
- const slotMatch = line.match(slotRe);
1305
- if (slotMatch) {
1306
- if (current) items.push(current);
1307
- const props = parseMdcProps(slotMatch[1]);
1308
- current = {
1309
- label: props["label"] || props["title"] || `Item ${items.length + 1}`,
1310
- icon: props["icon"] || "",
1311
- lines: []
1312
- };
1313
- continue;
1314
- }
1315
- if (current) current.lines.push(line);
1316
- else if (!items.length && !current) current = {
1317
- label: `Item 1`,
1318
- icon: "",
1319
- lines: [line]
1320
- };
1321
- }
1322
- if (current) items.push(current);
1323
- return items.map((item) => ({
1324
- label: item.label,
1325
- icon: item.icon,
1326
- innerBlocks: parseBlocks(item.lines.join("\n"))
1327
- }));
1328
- }
1329
- const TASK_RE = /^[-*+]\s+\[([ xX])\]\s+(.*)/;
1330
- function parseBlocks(markdown) {
1331
- const rawLines = markdown.split("\n");
1332
- let firstContentLine = 0;
1333
- while (firstContentLine < rawLines.length) {
1334
- const l = rawLines[firstContentLine];
1335
- if (l.trim() === "" || /^import\s/.test(l) || /^export\s/.test(l)) firstContentLine++;
1336
- else break;
1337
- }
1338
- const stripped = rawLines.slice(firstContentLine).join("\n");
1339
- const blocks = [];
1340
- const lines = stripped.split("\n");
1341
- let i = 0;
1342
- while (i < lines.length) {
1343
- const line = lines[i];
1344
- const fenceBlockMatch = line.match(/^(`{3,})(.*)$/);
1345
- if (fenceBlockMatch) {
1346
- const fence = fenceBlockMatch[1];
1347
- const lang = fenceBlockMatch[2].trim().replace(/\{[^}]*\}$/, "").replace(/\s*\[.*\]$/, "").trim();
1348
- const codeLines = [];
1349
- i++;
1350
- while (i < lines.length && !lines[i].startsWith(fence)) {
1351
- codeLines.push(lines[i]);
1352
- i++;
1353
- }
1354
- i++;
1355
- if (lang === "svg" || lang.startsWith("svg ")) {
1356
- const svgTitle = lang === "svg" ? "" : lang.slice(4).trim();
1357
- blocks.push({
1358
- type: "svgEmbed",
1359
- svg: codeLines.join("\n"),
1360
- title: svgTitle
1361
- });
1362
- } else blocks.push({
1363
- type: "codeBlock",
1364
- lang,
1365
- code: codeLines.join("\n")
1366
- });
1367
- continue;
1368
- }
1369
- const headingMatch = line.match(/^(#{1,6})\s+(.*)/);
1370
- if (headingMatch) {
1371
- blocks.push({
1372
- type: "heading",
1373
- level: headingMatch[1].length,
1374
- text: headingMatch[2].trim()
1375
- });
1376
- i++;
1377
- continue;
1378
- }
1379
- if (/^[-*_]{3,}\s*$/.test(line)) {
1380
- blocks.push({ type: "hr" });
1381
- i++;
1382
- continue;
1383
- }
1384
- const docEmbedMatch = line.match(/^!\[\[([^\]|]+?)(?:\|[^\]]*?)?\]\](\{[^}]*\})?\s*$/);
1385
- if (docEmbedMatch) {
1386
- const props = parseMdcProps(docEmbedMatch[2]);
1387
- const seamless = "seamless" in props || props["seamless"] === "true" || /\{[^}]*\bseamless\b[^}]*\}/.test(docEmbedMatch[2] ?? "");
1388
- blocks.push({
1389
- type: "docEmbed",
1390
- docId: docEmbedMatch[1],
1391
- seamless: seamless || void 0
1392
- });
1393
- i++;
1394
- continue;
1395
- }
1396
- const imgMatch = line.match(/^!\[([^\]]*)\]\(([^)]+)\)(\{[^}]*\})?\s*$/);
1397
- if (imgMatch) {
1398
- const alt = imgMatch[1] ?? "";
1399
- const src = imgMatch[2] ?? "";
1400
- const attrs = parseMdcProps(imgMatch[3]);
1401
- blocks.push({
1402
- type: "image",
1403
- src,
1404
- alt,
1405
- width: attrs["width"],
1406
- height: attrs["height"]
1407
- });
1408
- i++;
1409
- continue;
1410
- }
1411
- if (line.startsWith("> ") || line === ">") {
1412
- const bqLines = [];
1413
- while (i < lines.length && (lines[i].startsWith("> ") || lines[i] === ">")) {
1414
- bqLines.push(lines[i].replace(/^>\s?/, ""));
1415
- i++;
1416
- }
1417
- blocks.push({
1418
- type: "blockquote",
1419
- lines: bqLines
1420
- });
1421
- continue;
1422
- }
1423
- if (/^\s*\|/.test(line)) {
1424
- const tableLines = [];
1425
- while (i < lines.length && /^\s*\|/.test(lines[i])) {
1426
- tableLines.push(lines[i]);
1427
- i++;
1428
- }
1429
- if (tableLines.length >= 2 && isTableSeparator(tableLines[1])) {
1430
- const headerRow = parseTableRow(tableLines[0]);
1431
- const dataRows = tableLines.slice(2).filter((l) => !isTableSeparator(l)).map(parseTableRow);
1432
- blocks.push({
1433
- type: "table",
1434
- headerRow,
1435
- dataRows
1436
- });
1437
- } else for (const l of tableLines) blocks.push({
1438
- type: "paragraph",
1439
- text: l
1440
- });
1441
- continue;
1442
- }
1443
- const MDC_OPEN = /^\s*(:{2,})(\w[\w-]*)(\{[^}]*\})?\s*$/;
1444
- if (MDC_OPEN.test(line)) {
1445
- const colons = line.match(/^\s*(:+)/)?.[1]?.length ?? 2;
1446
- const componentName = line.match(/^\s*:{2,}(\w[\w-]*)/)?.[1] ?? "";
1447
- const innerLines = [];
1448
- i++;
1449
- while (i < lines.length) {
1450
- const l = lines[i];
1451
- if (new RegExp(`^\\s*:{${colons}}\\s*$`).test(l)) {
1452
- i++;
1453
- break;
1454
- }
1455
- const innerFence = l.match(/^(\s*`{3,})/);
1456
- if (innerFence) {
1457
- const fenceStr = innerFence[1].trimStart();
1458
- innerLines.push(l);
1459
- i++;
1460
- while (i < lines.length && !lines[i].trimStart().startsWith(fenceStr)) {
1461
- innerLines.push(lines[i]);
1462
- i++;
1463
- }
1464
- if (i < lines.length) {
1465
- innerLines.push(lines[i]);
1466
- i++;
1467
- }
1468
- continue;
1469
- }
1470
- innerLines.push(l);
1471
- i++;
1472
- }
1473
- const nonBlank = innerLines.filter((l) => l.trim().length > 0);
1474
- if (nonBlank.length) {
1475
- const minIndent = Math.min(...nonBlank.map((l) => l.match(/^(\s*)/)?.[1]?.length ?? 0));
1476
- if (minIndent > 0) for (let j = 0; j < innerLines.length; j++) innerLines[j] = innerLines[j].slice(Math.min(minIndent, innerLines[j].length));
1477
- }
1478
- let contentStart = 0;
1479
- if (innerLines[0]?.trim() === "---") {
1480
- const fmEnd = innerLines.findIndex((l, idx) => idx > 0 && l.trim() === "---");
1481
- if (fmEnd !== -1) contentStart = fmEnd + 1;
1482
- }
1483
- const contentLines = innerLines.slice(contentStart);
1484
- const defaultSlotLines = [];
1485
- const codeSlotLines = [];
1486
- let currentSlot = "default";
1487
- for (const l of contentLines) {
1488
- if (/^#code\s*$/.test(l)) {
1489
- currentSlot = "code";
1490
- continue;
1491
- }
1492
- if (/^#\w+/.test(l) && !/^#{2,}\s/.test(l)) {
1493
- currentSlot = "other";
1494
- continue;
1495
- }
1496
- if (currentSlot === "default") defaultSlotLines.push(l);
1497
- else if (currentSlot === "code") codeSlotLines.push(l);
1498
- }
1499
- const innerBlocks = parseBlocks(defaultSlotLines.join("\n"));
1500
- const codeBlocks = extractFencedCode(codeSlotLines);
1501
- if (new Set([
1502
- "tip",
1503
- "note",
1504
- "info",
1505
- "warning",
1506
- "caution",
1507
- "danger",
1508
- "callout",
1509
- "alert"
1510
- ]).has(componentName.toLowerCase())) blocks.push({
1511
- type: "callout",
1512
- calloutType: componentName.toLowerCase(),
1513
- innerBlocks
1514
- });
1515
- else {
1516
- const mdcProps = parseMdcProps(line.match(MDC_OPEN)?.[3]);
1517
- const lc = componentName.toLowerCase();
1518
- if (lc === "collapsible") blocks.push({
1519
- type: "collapsible",
1520
- label: mdcProps["label"] || "Details",
1521
- open: mdcProps["open"] === "true",
1522
- innerBlocks
1523
- });
1524
- else if (lc === "steps") blocks.push({
1525
- type: "steps",
1526
- innerBlocks
1527
- });
1528
- else if (lc === "card") blocks.push({
1529
- type: "card",
1530
- title: mdcProps["title"] || "",
1531
- icon: mdcProps["icon"] || "",
1532
- to: mdcProps["to"] || "",
1533
- innerBlocks
1534
- });
1535
- else if (lc === "card-group") {
1536
- const cards = innerBlocks.filter((b) => b.type === "card");
1537
- if (cards.length) blocks.push({
1538
- type: "cardGroup",
1539
- cards
1540
- });
1541
- else blocks.push(...innerBlocks);
1542
- } else if (lc === "code-collapse") blocks.push({
1543
- type: "codeCollapse",
1544
- codeBlocks: codeBlocks.length ? codeBlocks : innerBlocks.filter((b) => b.type === "codeBlock")
1545
- });
1546
- else if (lc === "code-group") {
1547
- const allCode = [...innerBlocks.filter((b) => b.type === "codeBlock"), ...codeBlocks];
1548
- blocks.push({
1549
- type: "codeGroup",
1550
- codeBlocks: allCode
1551
- });
1552
- } else if (lc === "code-preview") blocks.push({
1553
- type: "codePreview",
1554
- innerBlocks,
1555
- codeBlocks
1556
- });
1557
- else if (lc === "code-tree") blocks.push({
1558
- type: "codeTree",
1559
- files: mdcProps["files"] || "[]"
1560
- });
1561
- else if (lc === "accordion") {
1562
- const items = parseMdcChildren(contentLines, "item");
1563
- if (items.length) blocks.push({
1564
- type: "accordion",
1565
- items
1566
- });
1567
- else blocks.push({
1568
- type: "accordion",
1569
- items: [{
1570
- label: "Item 1",
1571
- icon: "",
1572
- innerBlocks
1573
- }]
1574
- });
1575
- } else if (lc === "tabs") {
1576
- const items = parseMdcChildren(contentLines, "tab");
1577
- if (items.length) blocks.push({
1578
- type: "tabs",
1579
- items
1580
- });
1581
- else blocks.push({
1582
- type: "tabs",
1583
- items: [{
1584
- label: "Tab 1",
1585
- icon: "",
1586
- innerBlocks
1587
- }]
1588
- });
1589
- } else if (lc === "field") blocks.push({
1590
- type: "field",
1591
- name: mdcProps["name"] || "",
1592
- fieldType: mdcProps["type"] || "string",
1593
- required: mdcProps["required"] === "true",
1594
- innerBlocks
1595
- });
1596
- else if (lc === "field-group") {
1597
- const fields = innerBlocks.filter((b) => b.type === "field");
1598
- if (fields.length) blocks.push({
1599
- type: "fieldGroup",
1600
- fields
1601
- });
1602
- else blocks.push(...innerBlocks);
1603
- } else {
1604
- blocks.push(...innerBlocks);
1605
- blocks.push(...codeBlocks);
1606
- }
1607
- }
1608
- continue;
1609
- }
1610
- if (TASK_RE.test(line)) {
1611
- const items = [];
1612
- while (i < lines.length && TASK_RE.test(lines[i])) {
1613
- const m = lines[i].match(TASK_RE);
1614
- items.push({
1615
- checked: m[1].toLowerCase() === "x",
1616
- text: m[2]
1617
- });
1618
- i++;
1619
- }
1620
- blocks.push({
1621
- type: "taskList",
1622
- items
1623
- });
1624
- continue;
1625
- }
1626
- if (/^[-*+]\s+/.test(line)) {
1627
- const items = [];
1628
- while (i < lines.length && /^[-*+]\s+/.test(lines[i]) && !TASK_RE.test(lines[i])) {
1629
- items.push(lines[i].replace(/^[-*+]\s+/, ""));
1630
- i++;
1631
- }
1632
- if (items.length) {
1633
- blocks.push({
1634
- type: "bulletList",
1635
- items
1636
- });
1637
- continue;
1638
- }
1639
- }
1640
- if (/^\d+\.\s+/.test(line)) {
1641
- const items = [];
1642
- while (i < lines.length && /^\d+\.\s+/.test(lines[i])) {
1643
- items.push(lines[i].replace(/^\d+\.\s+/, ""));
1644
- i++;
1645
- }
1646
- blocks.push({
1647
- type: "orderedList",
1648
- items
1649
- });
1650
- continue;
1651
- }
1652
- if (line.trim() === "") {
1653
- i++;
1654
- continue;
1655
- }
1656
- const paraLines = [];
1657
- while (i < lines.length && lines[i].trim() !== "" && !/^(#{1,6}\s|[-*+]\s|\d+\.\s|>|`{3,}|\s*\||[-*_]{3,}\s*$|\s*:{2,}\w)/.test(lines[i])) {
1658
- paraLines.push(lines[i]);
1659
- i++;
1660
- }
1661
- if (paraLines.length) blocks.push({
1662
- type: "paragraph",
1663
- text: paraLines.join(" ")
1664
- });
1665
- }
1666
- return blocks;
1667
- }
1668
- function fillTextInto(el, tokens) {
1669
- const filtered = tokens.filter((t) => t.node || t.text.length > 0);
1670
- if (!filtered.length) return;
1671
- const children = filtered.map((tok) => {
1672
- if (tok.node) {
1673
- const xe = new Y.XmlElement(tok.node);
1674
- if (tok.nodeAttrs) for (const [k, v] of Object.entries(tok.nodeAttrs)) xe.setAttribute(k, v);
1675
- return xe;
1676
- }
1677
- return new Y.XmlText();
1678
- });
1679
- el.insert(0, children);
1680
- filtered.forEach((tok, i) => {
1681
- if (tok.node) return;
1682
- const xt = children[i];
1683
- if (tok.attrs) xt.insert(0, tok.text, tok.attrs);
1684
- else xt.insert(0, tok.text);
1685
- });
1686
- }
1687
- function blockElName(b) {
1688
- switch (b.type) {
1689
- case "heading": return "heading";
1690
- case "paragraph": return "paragraph";
1691
- case "bulletList": return "bulletList";
1692
- case "orderedList": return "orderedList";
1693
- case "taskList": return "taskList";
1694
- case "codeBlock": return "codeBlock";
1695
- case "blockquote": return "blockquote";
1696
- case "table": return "table";
1697
- case "hr": return "horizontalRule";
1698
- case "callout": return "callout";
1699
- case "collapsible": return "collapsible";
1700
- case "steps": return "steps";
1701
- case "card": return "card";
1702
- case "cardGroup": return "cardGroup";
1703
- case "codeCollapse": return "codeCollapse";
1704
- case "codeGroup": return "codeGroup";
1705
- case "codePreview": return "codePreview";
1706
- case "codeTree": return "codeTree";
1707
- case "accordion": return "accordion";
1708
- case "tabs": return "tabs";
1709
- case "field": return "field";
1710
- case "fieldGroup": return "fieldGroup";
1711
- case "image": return "image";
1712
- case "docEmbed": return "docEmbed";
1713
- case "svgEmbed": return "svgEmbed";
1714
- }
1715
- }
1716
- function fillBlock(el, block) {
1717
- switch (block.type) {
1718
- case "heading":
1719
- el.setAttribute("level", block.level);
1720
- fillTextInto(el, parseInline(block.text));
1721
- break;
1722
- case "paragraph":
1723
- fillTextInto(el, parseInline(block.text));
1724
- break;
1725
- case "bulletList":
1726
- case "orderedList": {
1727
- const listItemEls = block.items.map(() => new Y.XmlElement("listItem"));
1728
- el.insert(0, listItemEls);
1729
- block.items.forEach((text, i) => {
1730
- const paraEl = new Y.XmlElement("paragraph");
1731
- listItemEls[i].insert(0, [paraEl]);
1732
- fillTextInto(paraEl, parseInline(text));
1733
- });
1734
- break;
1735
- }
1736
- case "taskList": {
1737
- const taskItemEls = block.items.map(() => new Y.XmlElement("taskItem"));
1738
- el.insert(0, taskItemEls);
1739
- block.items.forEach((item, i) => {
1740
- taskItemEls[i].setAttribute("checked", item.checked);
1741
- const paraEl = new Y.XmlElement("paragraph");
1742
- taskItemEls[i].insert(0, [paraEl]);
1743
- fillTextInto(paraEl, parseInline(item.text));
1744
- });
1745
- break;
1746
- }
1747
- case "codeBlock": {
1748
- if (block.lang) el.setAttribute("language", block.lang);
1749
- const xt = new Y.XmlText();
1750
- el.insert(0, [xt]);
1751
- xt.insert(0, block.code);
1752
- break;
1753
- }
1754
- case "blockquote": {
1755
- const paraEls = block.lines.map(() => new Y.XmlElement("paragraph"));
1756
- el.insert(0, paraEls);
1757
- block.lines.forEach((line, i) => fillTextInto(paraEls[i], parseInline(line)));
1758
- break;
1759
- }
1760
- case "table": {
1761
- const headerRowEl = new Y.XmlElement("tableRow");
1762
- const dataRowEls = block.dataRows.map(() => new Y.XmlElement("tableRow"));
1763
- el.insert(0, [headerRowEl, ...dataRowEls]);
1764
- const headerCellEls = block.headerRow.map(() => new Y.XmlElement("tableHeader"));
1765
- headerRowEl.insert(0, headerCellEls);
1766
- block.headerRow.forEach((cellText, i) => {
1767
- const paraEl = new Y.XmlElement("paragraph");
1768
- headerCellEls[i].insert(0, [paraEl]);
1769
- fillTextInto(paraEl, parseInline(cellText));
1770
- });
1771
- block.dataRows.forEach((row, ri) => {
1772
- const cellEls = row.map(() => new Y.XmlElement("tableCell"));
1773
- dataRowEls[ri].insert(0, cellEls);
1774
- row.forEach((cellText, ci) => {
1775
- const paraEl = new Y.XmlElement("paragraph");
1776
- cellEls[ci].insert(0, [paraEl]);
1777
- fillTextInto(paraEl, parseInline(cellText));
1778
- });
1779
- });
1780
- break;
1781
- }
1782
- case "hr": break;
1783
- case "callout": {
1784
- el.setAttribute("type", block.calloutType);
1785
- if (!block.innerBlocks.length) {
1786
- const paraEl = new Y.XmlElement("paragraph");
1787
- el.insert(0, [paraEl]);
1788
- break;
1789
- }
1790
- const innerEls = block.innerBlocks.map((b) => new Y.XmlElement(blockElName(b)));
1791
- el.insert(0, innerEls);
1792
- block.innerBlocks.forEach((b, i) => fillBlock(innerEls[i], b));
1793
- break;
1794
- }
1795
- case "collapsible": {
1796
- el.setAttribute("label", block.label);
1797
- el.setAttribute("open", block.open);
1798
- const inner = block.innerBlocks.length ? block.innerBlocks : [{
1799
- type: "paragraph",
1800
- text: ""
1801
- }];
1802
- const innerEls = inner.map((b) => new Y.XmlElement(blockElName(b)));
1803
- el.insert(0, innerEls);
1804
- inner.forEach((b, i) => fillBlock(innerEls[i], b));
1805
- break;
1806
- }
1807
- case "steps": {
1808
- const inner = block.innerBlocks.length ? block.innerBlocks : [{
1809
- type: "paragraph",
1810
- text: ""
1811
- }];
1812
- const innerEls = inner.map((b) => new Y.XmlElement(blockElName(b)));
1813
- el.insert(0, innerEls);
1814
- inner.forEach((b, i) => fillBlock(innerEls[i], b));
1815
- break;
1816
- }
1817
- case "card": {
1818
- if (block.title) el.setAttribute("title", block.title);
1819
- if (block.icon) el.setAttribute("icon", block.icon);
1820
- if (block.to) el.setAttribute("to", block.to);
1821
- const inner = block.innerBlocks.length ? block.innerBlocks : [{
1822
- type: "paragraph",
1823
- text: ""
1824
- }];
1825
- const innerEls = inner.map((b) => new Y.XmlElement(blockElName(b)));
1826
- el.insert(0, innerEls);
1827
- inner.forEach((b, i) => fillBlock(innerEls[i], b));
1828
- break;
1829
- }
1830
- case "cardGroup": {
1831
- const cardEls = block.cards.map((b) => new Y.XmlElement(blockElName(b)));
1832
- el.insert(0, cardEls);
1833
- block.cards.forEach((b, i) => fillBlock(cardEls[i], b));
1834
- break;
1835
- }
1836
- case "codeCollapse": {
1837
- const codes = block.codeBlocks.length ? block.codeBlocks : [{
1838
- type: "codeBlock",
1839
- lang: "",
1840
- code: ""
1841
- }];
1842
- const codeEl = new Y.XmlElement("codeBlock");
1843
- el.insert(0, [codeEl]);
1844
- fillBlock(codeEl, codes[0]);
1845
- break;
1846
- }
1847
- case "codeGroup": {
1848
- const codes = block.codeBlocks.length ? block.codeBlocks : [{
1849
- type: "codeBlock",
1850
- lang: "",
1851
- code: ""
1852
- }];
1853
- const codeEls = codes.map(() => new Y.XmlElement("codeBlock"));
1854
- el.insert(0, codeEls);
1855
- codes.forEach((b, i) => fillBlock(codeEls[i], b));
1856
- break;
1857
- }
1858
- case "codePreview": {
1859
- const all = [...block.innerBlocks, ...block.codeBlocks];
1860
- const inner = all.length ? all : [{
1861
- type: "paragraph",
1862
- text: ""
1863
- }];
1864
- const innerEls = inner.map((b) => new Y.XmlElement(blockElName(b)));
1865
- el.insert(0, innerEls);
1866
- inner.forEach((b, i) => fillBlock(innerEls[i], b));
1867
- break;
1868
- }
1869
- case "codeTree":
1870
- el.setAttribute("files", block.files);
1871
- break;
1872
- case "accordion": {
1873
- const itemEls = block.items.map(() => new Y.XmlElement("accordionItem"));
1874
- el.insert(0, itemEls);
1875
- block.items.forEach((item, i) => {
1876
- itemEls[i].setAttribute("label", item.label);
1877
- if (item.icon) itemEls[i].setAttribute("icon", item.icon);
1878
- const inner = item.innerBlocks.length ? item.innerBlocks : [{
1879
- type: "paragraph",
1880
- text: ""
1881
- }];
1882
- const childEls = inner.map((b) => new Y.XmlElement(blockElName(b)));
1883
- itemEls[i].insert(0, childEls);
1884
- inner.forEach((b, ci) => fillBlock(childEls[ci], b));
1885
- });
1886
- break;
1887
- }
1888
- case "tabs": {
1889
- const itemEls = block.items.map(() => new Y.XmlElement("tabsItem"));
1890
- el.insert(0, itemEls);
1891
- block.items.forEach((item, i) => {
1892
- itemEls[i].setAttribute("label", item.label);
1893
- if (item.icon) itemEls[i].setAttribute("icon", item.icon);
1894
- const inner = item.innerBlocks.length ? item.innerBlocks : [{
1895
- type: "paragraph",
1896
- text: ""
1897
- }];
1898
- const childEls = inner.map((b) => new Y.XmlElement(blockElName(b)));
1899
- itemEls[i].insert(0, childEls);
1900
- inner.forEach((b, ci) => fillBlock(childEls[ci], b));
1901
- });
1902
- break;
1903
- }
1904
- case "field": {
1905
- if (block.name) el.setAttribute("name", block.name);
1906
- el.setAttribute("type", block.fieldType);
1907
- el.setAttribute("required", block.required);
1908
- const inner = block.innerBlocks.length ? block.innerBlocks : [{
1909
- type: "paragraph",
1910
- text: ""
1911
- }];
1912
- const innerEls = inner.map((b) => new Y.XmlElement(blockElName(b)));
1913
- el.insert(0, innerEls);
1914
- inner.forEach((b, i) => fillBlock(innerEls[i], b));
1915
- break;
1916
- }
1917
- case "fieldGroup": {
1918
- const fieldEls = block.fields.map((b) => new Y.XmlElement(blockElName(b)));
1919
- el.insert(0, fieldEls);
1920
- block.fields.forEach((b, i) => fillBlock(fieldEls[i], b));
1921
- break;
1922
- }
1923
- case "image":
1924
- el.setAttribute("src", block.src);
1925
- if (block.alt) el.setAttribute("alt", block.alt);
1926
- if (block.width) el.setAttribute("width", block.width);
1927
- if (block.height) el.setAttribute("height", block.height);
1928
- break;
1929
- case "docEmbed":
1930
- el.setAttribute("docId", block.docId);
1931
- if (block.seamless) el.setAttribute("seamless", "true");
1932
- break;
1933
- case "svgEmbed":
1934
- el.setAttribute("svg", block.svg);
1935
- if (block.title) el.setAttribute("title", block.title);
1936
- break;
1937
- }
1938
- }
1939
- function populateYDocFromMarkdown(fragment, markdown, fallbackTitle = "Untitled") {
1940
- const ydoc = fragment.doc;
1941
- if (!ydoc) {
1942
- console.warn("[markdownToYjs] fragment has no doc — skipping population");
1943
- return;
1944
- }
1945
- const blocks = parseBlocks(markdown);
1946
- let title = fallbackTitle;
1947
- let contentBlocks = blocks;
1948
- const h1 = blocks.findIndex((b) => b.type === "heading" && b.level === 1);
1949
- if (h1 !== -1) {
1950
- title = blocks[h1].text;
1951
- contentBlocks = blocks.filter((_, i) => i !== h1);
1952
- }
1953
- if (!contentBlocks.length) contentBlocks = [{
1954
- type: "paragraph",
1955
- text: ""
1956
- }];
1957
- ydoc.transact(() => {
1958
- const headerEl = new Y.XmlElement("documentHeader");
1959
- const metaEl = new Y.XmlElement("documentMeta");
1960
- const bodyEls = contentBlocks.map((b) => {
1961
- switch (b.type) {
1962
- case "heading": return new Y.XmlElement("heading");
1963
- case "paragraph": return new Y.XmlElement("paragraph");
1964
- case "bulletList": return new Y.XmlElement("bulletList");
1965
- case "orderedList": return new Y.XmlElement("orderedList");
1966
- case "taskList": return new Y.XmlElement("taskList");
1967
- case "codeBlock": return new Y.XmlElement("codeBlock");
1968
- case "blockquote": return new Y.XmlElement("blockquote");
1969
- case "table": return new Y.XmlElement("table");
1970
- case "hr": return new Y.XmlElement("horizontalRule");
1971
- case "callout": return new Y.XmlElement("callout");
1972
- case "collapsible": return new Y.XmlElement("collapsible");
1973
- case "steps": return new Y.XmlElement("steps");
1974
- case "card": return new Y.XmlElement("card");
1975
- case "cardGroup": return new Y.XmlElement("cardGroup");
1976
- case "codeCollapse": return new Y.XmlElement("codeCollapse");
1977
- case "codeGroup": return new Y.XmlElement("codeGroup");
1978
- case "codePreview": return new Y.XmlElement("codePreview");
1979
- case "codeTree": return new Y.XmlElement("codeTree");
1980
- case "accordion": return new Y.XmlElement("accordion");
1981
- case "tabs": return new Y.XmlElement("tabs");
1982
- case "field": return new Y.XmlElement("field");
1983
- case "fieldGroup": return new Y.XmlElement("fieldGroup");
1984
- case "image": return new Y.XmlElement("image");
1985
- case "docEmbed": return new Y.XmlElement("docEmbed");
1986
- case "svgEmbed": return new Y.XmlElement("svgEmbed");
1987
- }
1988
- });
1989
- fragment.insert(0, [
1990
- headerEl,
1991
- metaEl,
1992
- ...bodyEls
1993
- ]);
1994
- const headerXt = new Y.XmlText();
1995
- headerEl.insert(0, [headerXt]);
1996
- headerXt.insert(0, title);
1997
- contentBlocks.forEach((block, i) => fillBlock(bodyEls[i], block));
1998
- });
1999
- }
2000
-
2001
511
  //#endregion
2002
512
  //#region packages/orchestrator/src/actions/content.ts
2003
513
  async function executeWriteContent(actor, action) {