@fragment-dev/cli 2026.10.30-3 → 2026.10.30-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +35 -0
  2. package/bin/dev.js +1 -1
  3. package/bin/run.js +3 -1
  4. package/dist/{chunk-5GFLO7UI.js → chunk-4CPAGLCS.js} +3 -3
  5. package/dist/chunk-4E5LH6UM.js +46 -0
  6. package/dist/{chunk-RBPPQTJQ.js → chunk-6CHMI6QB.js} +1144 -102
  7. package/dist/{chunk-5IXOOVRA.js → chunk-AXYDDQ64.js} +1 -1
  8. package/dist/{chunk-C7BZFVCG.js → chunk-C3IGD3FR.js} +1 -1
  9. package/dist/{chunk-IC5FEPA7.js → chunk-ERS7TGXY.js} +4 -4
  10. package/dist/{chunk-MU3PFOFX.js → chunk-EXTVHTGU.js} +6 -36
  11. package/dist/{chunk-XDLQLWN4.js → chunk-FTALVA4K.js} +10 -6
  12. package/dist/{chunk-BJCQGSYO.js → chunk-GKWT6QEB.js} +3 -3
  13. package/dist/{chunk-2B4YYDGV.js → chunk-HOYPQHWF.js} +4 -4
  14. package/dist/{chunk-CBQOKKM3.js → chunk-JSWKMWBO.js} +5 -5
  15. package/dist/{chunk-XGFUT3M2.js → chunk-N2SKO3MO.js} +2 -2
  16. package/dist/chunk-NSEYKDYC.js +398 -0
  17. package/dist/chunk-OCE3DJ2V.js +76 -0
  18. package/dist/chunk-POIPF2YW.js +609 -0
  19. package/dist/chunk-PW3XYURG.js +4917 -0
  20. package/dist/{chunk-L3PXI35O.js → chunk-WRHRJO7G.js} +6 -3
  21. package/dist/{chunk-75AAIPKL.js → chunk-WSFEOM2D.js} +0 -205
  22. package/dist/chunk-XKVEOJUH.js +85 -0
  23. package/dist/commands/gen-graphql.js +7 -6
  24. package/dist/commands/print-schema.js +9 -7
  25. package/dist/commands/simulate-scenario.js +31 -0
  26. package/dist/commands/verify-schema.js +8 -7
  27. package/dist/commands.js +21 -15
  28. package/dist/graphql.js +4 -3
  29. package/dist/index.js +21 -15
  30. package/dist/utils/formatAccountHierarchy.js +11 -0
  31. package/dist/utils/formatBalance.js +11 -0
  32. package/dist/utils/formatChartOfAccounts.js +7 -5
  33. package/dist/utils/formatEntries.js +6 -5
  34. package/dist/utils/formatScenarioAccountBalances.js +18 -0
  35. package/dist/utils/formatScenarioBalances.js +19 -0
  36. package/dist/utils/formatValidationErrors.js +3 -2
  37. package/dist/utils/schemaBackCompat.js +7 -6
  38. package/dist/utils/schemaValidation.js +6 -5
  39. package/oclif.manifest.json +43 -1
  40. package/package.json +7 -2
@@ -0,0 +1,4917 @@
1
+ import {
2
+ computeStructuralPath,
3
+ enhanceCoA,
4
+ enhanceLedgerEntry,
5
+ enhanceSchema,
6
+ formatScenarioAccountBalances,
7
+ generateSimulatingEntry,
8
+ lil_id_default,
9
+ makeLineKey
10
+ } from "./chunk-POIPF2YW.js";
11
+ import {
12
+ formatBalance,
13
+ getBalancePrecision
14
+ } from "./chunk-OCE3DJ2V.js";
15
+ import {
16
+ formatAccountReference
17
+ } from "./chunk-T3RKAA7V.js";
18
+ import {
19
+ ChartOfAccounts,
20
+ Schema,
21
+ assertBalancedLines,
22
+ evaluateExpression,
23
+ findPaymentAccountPath,
24
+ getStructuralPathToAccount,
25
+ isTotalBalanceSchema,
26
+ serializeCurrency,
27
+ transformAndValidateCoA,
28
+ transformAndValidateEntries,
29
+ transformAndValidatePayments,
30
+ uniqBy_default,
31
+ validateEntry,
32
+ validateGroup,
33
+ validateLedgerConsistencySettings,
34
+ validatePaymentEntry,
35
+ z as z2
36
+ } from "./chunk-6CHMI6QB.js";
37
+ import {
38
+ BaseSchema,
39
+ PaymentAccountingEventKey,
40
+ SystemLineParameterName,
41
+ fillParams,
42
+ getSchemaObjectParameters
43
+ } from "./chunk-WRHRJO7G.js";
44
+ import {
45
+ InternalError,
46
+ assert_default
47
+ } from "./chunk-WSFEOM2D.js";
48
+ import {
49
+ getStructuralPath
50
+ } from "./chunk-2QGAXOCF.js";
51
+ import {
52
+ CurrencyCodeSchema
53
+ } from "./chunk-NSEYKDYC.js";
54
+ import {
55
+ ParameterizedString,
56
+ SafeStringSchema,
57
+ safe
58
+ } from "./chunk-MI5NFPWE.js";
59
+ import {
60
+ z
61
+ } from "./chunk-3SE5DFKP.js";
62
+ import {
63
+ init_cjs_shims
64
+ } from "./chunk-7GH3YGSC.js";
65
+
66
+ // src/utils/formatScenarioBalances.ts
67
+ init_cjs_shims();
68
+
69
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/simulateScene.ts
70
+ init_cjs_shims();
71
+
72
+ // ../../libs/liveblocks-commands/src/utils/sceneEventResolution.ts
73
+ init_cjs_shims();
74
+
75
+ // ../../libs/liveblocks-commands/src/commands/entries/entryUtils.ts
76
+ init_cjs_shims();
77
+
78
+ // ../../libs/liveblocks-commands/src/commands/paymentTypes/paymentTypeErrors.ts
79
+ init_cjs_shims();
80
+
81
+ // ../../libs/liveblocks-commands/src/commands/entries/entryUtils.ts
82
+ var makePaymentEntryId = (paymentTypeId, paymentTypeVersionId, event) => ({
83
+ flavor: "payment",
84
+ paymentTypeId,
85
+ paymentTypeVersionId,
86
+ event
87
+ });
88
+ var getEntryIdKey = (entryId) => entryId.flavor === "ledger" ? `${entryId.entryTypeId}:${entryId.entryTypeVersionId ?? ""}` : `${entryId.paymentTypeId}:${entryId.paymentTypeVersionId}:${entryId.event}`;
89
+ var getLatestVersionID = (entryType) => {
90
+ let highestVersionIndex = 0;
91
+ let highestVersionId;
92
+ Array.from(entryType.typeVersionToVersionId.entries()).forEach(
93
+ ([versionIndex, versionId]) => {
94
+ const versionIndexInt = parseInt(versionIndex, 10);
95
+ if (versionIndexInt > highestVersionIndex) {
96
+ highestVersionIndex = versionIndexInt;
97
+ highestVersionId = versionId;
98
+ }
99
+ }
100
+ );
101
+ return highestVersionId;
102
+ };
103
+
104
+ // ../../libs/liveblocks-commands/src/utils/entrySelectors.ts
105
+ init_cjs_shims();
106
+
107
+ // ../../libs/liveblocks-commands/src/utils/entryValidation.ts
108
+ init_cjs_shims();
109
+ var buildAndValidateChartOfAccounts = (chartOfAccounts) => {
110
+ const defaultCurrencyCode = chartOfAccounts.defaultCurrency.code;
111
+ const defaultCurrencyCustomId = chartOfAccounts.defaultCurrency.customCurrencyId;
112
+ const defaultCurrency = defaultCurrencyCode ? {
113
+ code: defaultCurrencyCode,
114
+ ...defaultCurrencyCustomId && {
115
+ customCurrencyId: defaultCurrencyCustomId
116
+ }
117
+ } : void 0;
118
+ const accountsMap = new Map(
119
+ Array.from(chartOfAccounts.accounts.entries()).map(
120
+ ([id, account]) => [
121
+ id,
122
+ {
123
+ key: account.key,
124
+ type: account.type,
125
+ name: account.name,
126
+ template: account.template,
127
+ currency: account.currencyMode === "multi" ? void 0 : account.currency,
128
+ currencyMode: account.currencyMode,
129
+ consistencyConfig: {
130
+ lines: account.consistencyConfig?.lines,
131
+ ownBalanceUpdates: account.consistencyConfig?.ownBalanceUpdates,
132
+ totalBalanceUpdates: account.consistencyConfig?.totalBalanceUpdates,
133
+ groups: account.consistencyConfig?.groups ? Array.from(account.consistencyConfig.groups.entries()).map(([, group]) => ({
134
+ key: safe`${group.key}`,
135
+ ownBalanceUpdates: group.ownBalanceUpdates
136
+ })) : []
137
+ },
138
+ linkedAccount: account.linkedAccount,
139
+ children: [],
140
+ status: account.status,
141
+ clearing: account.clearing,
142
+ payment: account.payment
143
+ }
144
+ ]
145
+ )
146
+ );
147
+ const accounts = [];
148
+ const processedAccountIds = /* @__PURE__ */ new Set();
149
+ chartOfAccounts.accountsOrder.forEach((accountId) => {
150
+ if (processedAccountIds.has(accountId))
151
+ return;
152
+ const account = accountsMap.get(accountId);
153
+ const liveAccount = chartOfAccounts.accounts.get(accountId);
154
+ if (!account || !liveAccount)
155
+ return;
156
+ processedAccountIds.add(accountId);
157
+ if (liveAccount.parentId) {
158
+ const parent = accountsMap.get(liveAccount.parentId);
159
+ if (parent) {
160
+ if (liveAccount.parentId === accountId)
161
+ return;
162
+ parent.children.push(account);
163
+ }
164
+ } else {
165
+ accounts.push(account);
166
+ }
167
+ });
168
+ const { defaultCurrencyMode, defaultConsistencyConfig } = chartOfAccounts;
169
+ const coa = {
170
+ defaultCurrencyMode,
171
+ defaultCurrency,
172
+ defaultConsistencyConfig: {
173
+ lines: defaultConsistencyConfig.lines,
174
+ ownBalanceUpdates: defaultConsistencyConfig.ownBalanceUpdates,
175
+ totalBalanceUpdates: defaultConsistencyConfig.totalBalanceUpdates,
176
+ groups: Array.from(defaultConsistencyConfig.groups.entries()).map(([, group]) => ({
177
+ key: safe`${group.key}`,
178
+ ownBalanceUpdates: group.ownBalanceUpdates
179
+ }))
180
+ },
181
+ accounts
182
+ };
183
+ const { filledIn } = transformAndValidateCoA({ coa });
184
+ return filledIn;
185
+ };
186
+ var buildAccountPathToAccountMap = (chartOfAccounts) => {
187
+ if (!chartOfAccounts)
188
+ return { accountPathToAccount: /* @__PURE__ */ new Map() };
189
+ const filledIn = buildAndValidateChartOfAccounts(chartOfAccounts);
190
+ return {
191
+ accountPathToAccount: getStructuralPathToAccount(filledIn),
192
+ defaultConsistencyConfig: filledIn.defaultConsistencyConfig
193
+ };
194
+ };
195
+ var convertStaticParametersToRecord = (staticParameters) => staticParameters?.length ? Object.fromEntries(
196
+ Array.from(staticParameters).map((param) => [param.key, param.value])
197
+ ) : void 0;
198
+ var getEntryTypeVersion = (entryType, entryVersionId) => parseInt(
199
+ Array.from(entryType.typeVersionToVersionId).find(
200
+ ([, versionId]) => versionId === entryVersionId
201
+ )?.[0] ?? "1",
202
+ 10
203
+ );
204
+ var validateLiveEntryTypeVersion = ({
205
+ entryType,
206
+ entryVersion,
207
+ accountPathToAccount,
208
+ defaultConsistencyConfig
209
+ }) => {
210
+ const conditions = entryVersion.conditions ? entryVersion.conditions.map((condition) => ({
211
+ account: condition.account ? { path: condition.account.path } : { path: "" },
212
+ currency: condition.currency,
213
+ precondition: condition.precondition,
214
+ postcondition: condition.postcondition,
215
+ repeated: condition.repeated ? { key: SafeStringSchema.parse(condition.repeated.key) } : void 0
216
+ })) : [];
217
+ const orderedLines = Array.from(entryVersion.linesOrder.values()).map((lineId) => entryVersion.lines.get(lineId)).filter((line) => line !== void 0);
218
+ const entryLines = orderedLines.map((line) => ({
219
+ account: line.account ? { path: line.account.path } : { path: "" },
220
+ key: line.key,
221
+ amount: line.amount ?? "",
222
+ currency: line.currency,
223
+ description: line.description,
224
+ tx: line.tx,
225
+ repeated: line.repeated ? { key: SafeStringSchema.parse(line.repeated.key) } : void 0,
226
+ tags: line.tags?.map((tag) => ({
227
+ key: tag.key,
228
+ value: tag.value
229
+ })) ?? []
230
+ }));
231
+ const groups = entryVersion.groups?.map((group) => ({
232
+ key: group.key,
233
+ value: group.value
234
+ })) ?? [];
235
+ const tags = entryVersion.tags?.map((tag) => ({
236
+ key: tag.key,
237
+ value: tag.value
238
+ })) ?? [];
239
+ const parameters = convertStaticParametersToRecord(
240
+ entryVersion.staticParameters
241
+ );
242
+ const errors = validateEntry(
243
+ {
244
+ type: entryType.type,
245
+ lines: entryLines,
246
+ conditions,
247
+ description: entryVersion.description,
248
+ tags,
249
+ groups,
250
+ parameters,
251
+ status: entryVersion.status,
252
+ typeVersion: getEntryTypeVersion(entryType, entryVersion.id),
253
+ postLinesAs: entryVersion.postLinesAs
254
+ },
255
+ accountPathToAccount,
256
+ defaultConsistencyConfig
257
+ );
258
+ const hasRepeatedLineWithEmptyKey = orderedLines.some(
259
+ (line) => line.repeated && !line.repeated.key
260
+ );
261
+ const hasRepeatedConditionWithEmptyKey = entryVersion.conditions?.some(
262
+ (condition) => condition.repeated && !condition.repeated.key
263
+ ) ?? false;
264
+ if (hasRepeatedLineWithEmptyKey || hasRepeatedConditionWithEmptyKey) {
265
+ errors.push({
266
+ message: "Repeated key is required when repeated lines or conditions exist",
267
+ path: ["repeated", "key"]
268
+ });
269
+ }
270
+ return errors;
271
+ };
272
+
273
+ // ../../libs/liveblocks-commands/src/utils/entrySelectors.ts
274
+ var getPaymentEntryFromVersion = (paymentTypeVersion, event) => {
275
+ const paymentEntry = paymentTypeVersion.accounting[event];
276
+ if (!paymentEntry)
277
+ return null;
278
+ return { ...paymentEntry, status: "active", postLinesAs: "raw_lines" };
279
+ };
280
+ var getPaymentEntryFromRoot = (root, entryId) => {
281
+ const paymentType = root.schema.paymentTypes?.types.get(
282
+ entryId.paymentTypeId
283
+ );
284
+ if (!paymentType)
285
+ return null;
286
+ const paymentTypeVersion = paymentType.versions.get(
287
+ entryId.paymentTypeVersionId
288
+ );
289
+ if (!paymentTypeVersion)
290
+ return null;
291
+ return getPaymentEntryFromVersion(paymentTypeVersion, entryId.event);
292
+ };
293
+ var getEntryTypeFromRoot = (root, entryId) => {
294
+ if (entryId.flavor === "ledger") {
295
+ return root.schema.ledgerEntries.types.get(entryId.entryTypeId) ?? null;
296
+ }
297
+ const paymentType = root.schema.paymentTypes?.types.get(
298
+ entryId.paymentTypeId
299
+ );
300
+ if (!paymentType)
301
+ return null;
302
+ const paymentEntry = getPaymentEntryFromRoot(root, entryId);
303
+ if (!paymentEntry)
304
+ return null;
305
+ const versionIndex = Array.from(paymentType.typeVersionToVersionId.entries()).find(
306
+ ([, versionId]) => versionId === entryId.paymentTypeVersionId
307
+ )?.[0] ?? "1";
308
+ return {
309
+ id: entryId.paymentTypeId,
310
+ type: `${paymentType.type}.${versionIndex}.${entryId.event}`,
311
+ versions: /* @__PURE__ */ new Map([[paymentEntry.id, paymentEntry]]),
312
+ // Always keyed '1': the synthetic type wraps a single embedded entry, so
313
+ // the entry is the first version regardless of the payment type's own
314
+ // version index (which only feeds the derived type string above).
315
+ typeVersionToVersionId: /* @__PURE__ */ new Map([["1", paymentEntry.id]])
316
+ };
317
+ };
318
+ var getLedgerEntryVersion = (ledgerEntries, entryId) => {
319
+ const entryType = ledgerEntries.types.get(entryId.entryTypeId);
320
+ if (!entryType)
321
+ return null;
322
+ const entryVersionId = entryId.entryTypeVersionId ?? getLatestVersionID(entryType);
323
+ if (!entryVersionId)
324
+ return null;
325
+ let entryVersion = entryType.versions.get(entryVersionId);
326
+ if (!entryVersion) {
327
+ const mappedVersionId = entryType.typeVersionToVersionId.get(entryVersionId);
328
+ if (mappedVersionId) {
329
+ entryVersion = entryType.versions.get(mappedVersionId);
330
+ }
331
+ }
332
+ if (!entryVersion)
333
+ return null;
334
+ return entryVersion;
335
+ };
336
+ var getEntryVersionFromRoot = (root, entryId) => entryId.flavor === "payment" ? getPaymentEntryFromRoot(root, entryId) : getLedgerEntryVersion(root.schema.ledgerEntries, entryId);
337
+ var transformEntryVersion = ({
338
+ entryVersion,
339
+ entryType,
340
+ errors,
341
+ accountPathToAccount
342
+ }) => {
343
+ const lines = Array.from(entryVersion.linesOrder.values()).map((lineId) => entryVersion.lines.get(lineId)).filter((line) => line !== void 0);
344
+ const linesWithTypes = lines.map((line) => ({
345
+ ...line,
346
+ type: line.account?.path ? accountPathToAccount.get(getStructuralPath(line.account.path))?.type : void 0
347
+ }));
348
+ return {
349
+ value: {
350
+ entryId: entryType.id,
351
+ versionId: entryVersion.id,
352
+ type: entryType.type,
353
+ typeVersion: getEntryTypeVersion(entryType, entryVersion.id),
354
+ description: entryVersion.description,
355
+ parameters: entryVersion.staticParameters?.map((param) => ({
356
+ id: param.id,
357
+ key: param.key,
358
+ value: param.value
359
+ })),
360
+ groups: entryVersion.groups?.map((group) => ({
361
+ id: group.id,
362
+ key: group.key,
363
+ value: group.value
364
+ })),
365
+ tags: entryVersion.tags?.map((tag) => ({
366
+ id: tag.id,
367
+ key: tag.key,
368
+ value: tag.value
369
+ })),
370
+ conditions: entryVersion.conditions?.map((condition) => ({
371
+ id: condition.id,
372
+ account: condition.account ? {
373
+ id: condition.account.accountId,
374
+ path: condition.account.path
375
+ } : void 0,
376
+ currency: condition.currency,
377
+ precondition: condition.precondition,
378
+ postcondition: condition.postcondition,
379
+ repeated: condition.repeated
380
+ })),
381
+ lines: linesWithTypes,
382
+ status: entryVersion.status,
383
+ postLinesAs: entryVersion.postLinesAs
384
+ },
385
+ errors
386
+ };
387
+ };
388
+ var validateAndTransformEntryVersion = ({
389
+ entryType,
390
+ entryVersion,
391
+ accountPathToAccount,
392
+ defaultConsistencyConfig
393
+ }) => {
394
+ const errors = validateLiveEntryTypeVersion({
395
+ entryType,
396
+ entryVersion,
397
+ accountPathToAccount,
398
+ defaultConsistencyConfig
399
+ });
400
+ return transformEntryVersion({
401
+ entryVersion,
402
+ entryType,
403
+ errors,
404
+ accountPathToAccount
405
+ });
406
+ };
407
+
408
+ // ../../libs/liveblocks-commands/src/utils/paymentTypeValidation.ts
409
+ init_cjs_shims();
410
+ var convertLiveLine = (line) => ({
411
+ key: line.key,
412
+ account: line.account ? { path: line.account.path } : void 0,
413
+ amount: line.amount ?? "",
414
+ currency: line.currency ? {
415
+ code: line.currency.code,
416
+ customCurrencyId: line.currency.customCurrencyId
417
+ } : void 0,
418
+ description: line.description,
419
+ system: line.system
420
+ });
421
+ var convertLiveEntry = (entry) => ({
422
+ description: entry.description,
423
+ lines: Array.from(entry.linesOrder.values()).map((lineId) => entry.lines.get(lineId)).filter((line) => line !== void 0).map(convertLiveLine)
424
+ });
425
+ var validateLivePaymentEntry = ({
426
+ entryVersion,
427
+ event,
428
+ entryIdentity,
429
+ accountPathToAccount
430
+ }) => validatePaymentEntry({
431
+ entry: convertLiveEntry(entryVersion),
432
+ event,
433
+ entryIdentity,
434
+ accountPathToAccount,
435
+ paymentAccountPath: findPaymentAccountPath(accountPathToAccount)
436
+ });
437
+
438
+ // ../../libs/liveblocks-commands/src/utils/scenarioPayments.ts
439
+ init_cjs_shims();
440
+
441
+ // ../../libs/payment-commands/utils/amount.ts
442
+ init_cjs_shims();
443
+
444
+ // ../../libs/types/payment.ts
445
+ init_cjs_shims();
446
+ var MIN_PAYMENT_AMOUNT_CENTS = 100n;
447
+ var MAX_PAYMENT_AMOUNT_CENTS = 10000000n;
448
+ var formatUsd = (cents) => `$${(cents / 100n).toLocaleString("en-US")}.${(cents % 100n).toString().padStart(2, "0")}`;
449
+ var PAYMENT_AMOUNT_RANGE_MESSAGE = `Amount must be between ${formatUsd(
450
+ MIN_PAYMENT_AMOUNT_CENTS
451
+ )} and ${formatUsd(MAX_PAYMENT_AMOUNT_CENTS)}`;
452
+ var PaymentMode = /* @__PURE__ */ ((PaymentMode2) => {
453
+ PaymentMode2["sandbox"] = "sandbox";
454
+ PaymentMode2["glassbox"] = "glassbox";
455
+ PaymentMode2["production"] = "production";
456
+ return PaymentMode2;
457
+ })(PaymentMode || {});
458
+ var PaymentModeSchema = z.nativeEnum(PaymentMode);
459
+ var ApiPaymentMode = /* @__PURE__ */ ((ApiPaymentMode2) => {
460
+ ApiPaymentMode2["sandbox"] = "sandbox";
461
+ ApiPaymentMode2["production"] = "production";
462
+ return ApiPaymentMode2;
463
+ })(ApiPaymentMode || {});
464
+ var ApiPaymentModeSchema = z.nativeEnum(ApiPaymentMode);
465
+ var PaymentPersistenceEvent = {
466
+ /** The Payment was created. */
467
+ created: "created",
468
+ /** The payer went through checkout; posted when the Payment enters `processing`. */
469
+ checkout: "checkout",
470
+ /** The Customer retried the Payment on a saved payment method; posted when the Payment enters `processing`. */
471
+ retry: "retry",
472
+ /** The card network captured the payment; it is guaranteed to settle. */
473
+ card_captured: "card_captured",
474
+ /** Whop declined an attempt, or refused to create a payment for it. */
475
+ card_declined: "card_declined",
476
+ /** The payer abandoned or failed an attempt's 3DS challenge. */
477
+ card_3ds_canceled: "card_3ds_canceled",
478
+ /** The payment was settled. */
479
+ settled: "settled",
480
+ /** A Fragment Payment refund record was created. */
481
+ refund_initiated: "refund_initiated",
482
+ /** A Fragment Payment refund cleared its in-transit account. */
483
+ refund_settled: "refund_settled",
484
+ /** Whop declined a Fragment Payment refund. */
485
+ refund_failed: "refund_failed"
486
+ };
487
+ var PaymentPersistenceEventSchema = z.nativeEnum(
488
+ PaymentPersistenceEvent
489
+ );
490
+ var InternalPaymentAttemptStatus = {
491
+ /** Payment attempt not yet sent to Whop. */
492
+ created: "created",
493
+ /** Payment attempt has been sent to Whop and is being processed. */
494
+ processing: "processing",
495
+ /** Payment attempt has been accepted. */
496
+ accepted: "accepted",
497
+ /** Payment attempt has been declined. */
498
+ declined: "declined",
499
+ /** Whop refused to create a payment for the attempt. */
500
+ rejected: "rejected",
501
+ /** The payer abandoned or failed the attempt's 3DS challenge. */
502
+ canceled: "canceled",
503
+ /** Payment attempt needs action from the payer. No stored shape yet. */
504
+ needs_action: "needs_action"
505
+ };
506
+ var EXTERNAL_PAYMENT_ATTEMPT_STATUSES = {
507
+ [InternalPaymentAttemptStatus.created]: "processing" /* processing */,
508
+ [InternalPaymentAttemptStatus.processing]: "processing" /* processing */,
509
+ [InternalPaymentAttemptStatus.needs_action]: "processing" /* processing */,
510
+ [InternalPaymentAttemptStatus.accepted]: "succeeded" /* succeeded */,
511
+ [InternalPaymentAttemptStatus.declined]: "failed" /* failed */,
512
+ [InternalPaymentAttemptStatus.rejected]: "failed" /* failed */,
513
+ [InternalPaymentAttemptStatus.canceled]: "failed" /* failed */
514
+ };
515
+ var paymentCurrencyCodes = [
516
+ "USD"
517
+ ];
518
+ var PaymentCurrencyCodeSchema = z.enum(paymentCurrencyCodes);
519
+ var ExternalAccountMatchInput = z.object({
520
+ id: ParameterizedString.optional(),
521
+ /** The External systems's ID of the account */
522
+ externalId: ParameterizedString.optional(),
523
+ /** The Fragment ID of the link */
524
+ linkId: ParameterizedString.optional()
525
+ });
526
+
527
+ // ../../libs/payment-commands/utils/amount.ts
528
+ var MAX_AMOUNT_CENTS = 2n ** 46n * 100n;
529
+ var DEFAULT_FRAGMENT_FEE_SCHEDULE = {
530
+ ["card_payin" /* card_payin */]: {
531
+ rateBps: 290n,
532
+ fixedCents: 30n
533
+ }
534
+ };
535
+ var BPS_DENOMINATOR = 10000n;
536
+ var calculateFragmentFeeCents = ({
537
+ settledCents,
538
+ schedule
539
+ }) => {
540
+ assert_default(settledCents >= 0n, InternalError, {
541
+ info: { settledCents },
542
+ message: `Expected a non-negative settled amount, got ${settledCents}`
543
+ });
544
+ return schedule.fixedCents + (settledCents * schedule.rateBps + BPS_DENOMINATOR / 2n) / BPS_DENOMINATOR;
545
+ };
546
+ var IntegerAmountSchema = z.string().regex(/^-?\d+$/).transform(BigInt);
547
+
548
+ // ../../libs/shared-utils/parameterization.ts
549
+ init_cjs_shims();
550
+
551
+ // ../../libs/liveblocks-commands/src/utils/scenarioPayments.ts
552
+ var SCENARIO_FRAGMENT_FEE_PERCENT = Number(DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */].rateBps) / 100;
553
+ var SCENARIO_FRAGMENT_FEE_FIXED_CENTS = Number(
554
+ DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */].fixedCents
555
+ );
556
+ var evaluatePaymentAmount = (expression, parameters) => {
557
+ const filled = fillParams(expression, parameters, {
558
+ allowMissing: true,
559
+ allowMissingInChildren: true
560
+ }).trim();
561
+ try {
562
+ return { kind: "amount", amount: evaluateExpression(filled) };
563
+ } catch {
564
+ return { kind: "unevaluated", expression };
565
+ }
566
+ };
567
+ var computeScenarioFee = (amount) => {
568
+ const fee = calculateFragmentFeeCents({
569
+ settledCents: amount < 0n ? -amount : amount,
570
+ schedule: DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */]
571
+ });
572
+ return amount < 0n ? -fee : fee;
573
+ };
574
+
575
+ // ../../libs/liveblocks-commands/src/utils/sceneEventResolution.ts
576
+ var PAYMENT_GONE_FROM_SCENARIO_REASON = "This payment is no longer in the scenario. Remove this row.";
577
+ var PAYMENT_GONE_FROM_SCHEMA_REASON = "This payment is no longer in the schema. Remove this row.";
578
+ var SETTLED_BEFORE_APPROVAL_REASON = "This payment settles before it is approved \u2014 move the settled row after its approved row.";
579
+ var SETTLED_WITHOUT_APPROVAL_REASON = "This payment settles without being approved \u2014 its approved row is missing. Delete the settled row and re-add the payment.";
580
+ var makeUnevaluatedAmountReason = (expression) => `Payment amount '${expression}' did not evaluate to a whole number. Check the parameters it references.`;
581
+ var getLedgerSceneEventEntryId = (event) => ({
582
+ flavor: "ledger",
583
+ entryTypeId: event.entry.entryTypeId ?? "",
584
+ entryTypeVersionId: event.entry.entryTypeVersionId ?? ""
585
+ });
586
+ var getPaymentVersionContext = (paymentTypes, payment) => {
587
+ const paymentType = paymentTypes?.types.get(payment.paymentTypeId);
588
+ const version = paymentType?.versions.get(payment.paymentTypeVersionId);
589
+ if (!paymentType || !version)
590
+ return null;
591
+ return {
592
+ paymentType: paymentType.type,
593
+ amountExpression: version.payment.amount,
594
+ lifecycleEvents: Object.values(PaymentAccountingEventKey).filter(
595
+ (event) => getPaymentEntryFromVersion(version, event) !== null
596
+ )
597
+ };
598
+ };
599
+ var withSystemParameters = (parameters, amountExpression, event) => {
600
+ const evaluated = evaluatePaymentAmount(amountExpression, parameters);
601
+ if (evaluated.kind !== "amount")
602
+ return null;
603
+ const amount = evaluated.amount.toString();
604
+ const systemParameters = z2(event).with(PaymentAccountingEventKey.initiated, () => ({})).with(PaymentAccountingEventKey.settled, () => ({
605
+ [SystemLineParameterName.payment_settlement_line]: amount,
606
+ [SystemLineParameterName.payment_fee_line]: computeScenarioFee(
607
+ evaluated.amount
608
+ ).toString()
609
+ })).with(
610
+ PaymentAccountingEventKey.refund_initiated,
611
+ PaymentAccountingEventKey.refund_failed,
612
+ () => ({
613
+ [SystemLineParameterName.payment_refund_line]: amount
614
+ })
615
+ ).exhaustive();
616
+ return { ...parameters, ...systemParameters };
617
+ };
618
+ var getPaymentLifecycleFailure = ({
619
+ lifecycleEvents,
620
+ eventIndexByEvent
621
+ }) => {
622
+ const lifecycleSteps = lifecycleEvents.slice(1).map((event2, position) => {
623
+ const previousEvent2 = lifecycleEvents[position];
624
+ return {
625
+ event: event2,
626
+ previousEvent: previousEvent2,
627
+ eventRowIndex: eventIndexByEvent.get(event2),
628
+ previousEventRowIndex: eventIndexByEvent.get(previousEvent2)
629
+ };
630
+ });
631
+ const invalidStep = lifecycleSteps.find(
632
+ ({ eventRowIndex, previousEventRowIndex: previousEventRowIndex2 }) => eventRowIndex !== void 0 && (previousEventRowIndex2 === void 0 || previousEventRowIndex2 > eventRowIndex)
633
+ );
634
+ if (!invalidStep)
635
+ return void 0;
636
+ const { event, previousEvent, previousEventRowIndex } = invalidStep;
637
+ if (event === PaymentAccountingEventKey.settled && previousEvent === PaymentAccountingEventKey.initiated) {
638
+ return previousEventRowIndex === void 0 ? SETTLED_WITHOUT_APPROVAL_REASON : SETTLED_BEFORE_APPROVAL_REASON;
639
+ }
640
+ return previousEventRowIndex === void 0 ? `This ${event} row has no preceding ${previousEvent} row. Delete the ${event} row and re-add the payment.` : `This ${event} row occurs before its ${previousEvent} row. Move the ${event} row after its ${previousEvent} row.`;
641
+ };
642
+ var findInvalidPaymentEvents = (orderedEvents, lifecycleEventsByPaymentId) => {
643
+ const eventIndexesByPaymentId = /* @__PURE__ */ new Map();
644
+ orderedEvents.forEach((event, index) => {
645
+ if (event.eventType !== "payment-entry")
646
+ return;
647
+ const eventIndexByEvent = eventIndexesByPaymentId.get(event.entry.paymentId) ?? /* @__PURE__ */ new Map();
648
+ eventIndexByEvent.set(event.entry.event, index);
649
+ eventIndexesByPaymentId.set(event.entry.paymentId, eventIndexByEvent);
650
+ });
651
+ const invalidReasonsById = /* @__PURE__ */ new Map();
652
+ eventIndexesByPaymentId.forEach((eventIndexByEvent, paymentId) => {
653
+ const lifecycleEvents = lifecycleEventsByPaymentId.get(paymentId);
654
+ if (!lifecycleEvents)
655
+ return;
656
+ const failure = getPaymentLifecycleFailure({
657
+ lifecycleEvents,
658
+ eventIndexByEvent
659
+ });
660
+ if (failure === void 0)
661
+ return;
662
+ orderedEvents.forEach((event) => {
663
+ if (event.eventType === "payment-entry" && event.entry.paymentId === paymentId) {
664
+ invalidReasonsById.set(event.id, failure);
665
+ }
666
+ });
667
+ });
668
+ return invalidReasonsById;
669
+ };
670
+ var resolvePaymentEvent = ({
671
+ event,
672
+ payments,
673
+ paymentTypes,
674
+ invalidPaymentReasonsById
675
+ }) => {
676
+ const payment = payments.get(event.entry.paymentId);
677
+ if (!payment) {
678
+ return {
679
+ id: event.id,
680
+ entryId: null,
681
+ idKey: null,
682
+ parameters: {},
683
+ repeatedParameters: {},
684
+ failure: {
685
+ errorKind: "entry_invalid",
686
+ reasons: [PAYMENT_GONE_FROM_SCENARIO_REASON]
687
+ }
688
+ };
689
+ }
690
+ const entryId = makePaymentEntryId(
691
+ payment.paymentTypeId,
692
+ payment.paymentTypeVersionId,
693
+ event.entry.event
694
+ );
695
+ const context = getPaymentVersionContext(paymentTypes, payment);
696
+ const instanceParameters = payment.parameters;
697
+ const base = {
698
+ id: event.id,
699
+ entryId,
700
+ idKey: getEntryIdKey(entryId),
701
+ payment: {
702
+ paymentType: context?.paymentType ?? "unknown",
703
+ event: event.entry.event,
704
+ ik: payment.ik
705
+ },
706
+ parameters: instanceParameters,
707
+ repeatedParameters: {}
708
+ };
709
+ const fail = (errorKind, reason) => ({
710
+ ...base,
711
+ failure: { errorKind, reasons: [reason] }
712
+ });
713
+ if (!context)
714
+ return fail("entry_invalid", PAYMENT_GONE_FROM_SCHEMA_REASON);
715
+ const invalidPaymentReason = invalidPaymentReasonsById.get(event.id);
716
+ if (invalidPaymentReason !== void 0) {
717
+ return fail("entry_invalid", invalidPaymentReason);
718
+ }
719
+ const parameters = withSystemParameters(
720
+ instanceParameters,
721
+ context.amountExpression,
722
+ event.entry.event
723
+ );
724
+ if (parameters === null) {
725
+ return fail(
726
+ "parameter_error",
727
+ makeUnevaluatedAmountReason(context.amountExpression)
728
+ );
729
+ }
730
+ return { ...base, parameters };
731
+ };
732
+ var resolveSceneEvents = ({
733
+ events,
734
+ eventsOrder,
735
+ payments,
736
+ paymentTypes
737
+ }) => {
738
+ const eventsById = new Map(events.map((event) => [event.id, event]));
739
+ const orderedEvents = eventsOrder.map((eventId) => eventsById.get(eventId)).filter((event) => event !== void 0);
740
+ const lifecycleEventsByPaymentId = /* @__PURE__ */ new Map();
741
+ payments.forEach((payment, paymentId) => {
742
+ const context = getPaymentVersionContext(paymentTypes, payment);
743
+ if (context) {
744
+ lifecycleEventsByPaymentId.set(paymentId, context.lifecycleEvents);
745
+ }
746
+ });
747
+ const invalidPaymentReasonsById = findInvalidPaymentEvents(
748
+ orderedEvents,
749
+ lifecycleEventsByPaymentId
750
+ );
751
+ return orderedEvents.map(
752
+ (event) => z2(event).with({ eventType: "entry" }, (ledgerEvent) => {
753
+ const entryId = getLedgerSceneEventEntryId(ledgerEvent);
754
+ return {
755
+ id: ledgerEvent.id,
756
+ entryId,
757
+ idKey: getEntryIdKey(entryId),
758
+ parameters: ledgerEvent.entry.parameters,
759
+ repeatedParameters: ledgerEvent.entry.repeatedParameters ?? {}
760
+ };
761
+ }).with(
762
+ { eventType: "payment-entry" },
763
+ (paymentEvent) => resolvePaymentEvent({
764
+ event: paymentEvent,
765
+ payments,
766
+ paymentTypes,
767
+ invalidPaymentReasonsById
768
+ })
769
+ ).exhaustive()
770
+ );
771
+ };
772
+ var buildSceneEntriesByKey = ({
773
+ resolvedEvents,
774
+ root,
775
+ accountPathToAccount,
776
+ defaultConsistencyConfig
777
+ }) => {
778
+ const entriesByKey = /* @__PURE__ */ new Map();
779
+ resolvedEvents.forEach(({ entryId, idKey }) => {
780
+ if (!entryId || !idKey || entriesByKey.has(idKey))
781
+ return;
782
+ const entryType = getEntryTypeFromRoot(root, entryId);
783
+ if (!entryType)
784
+ return;
785
+ const entryVersion = getEntryVersionFromRoot(root, entryId);
786
+ if (!entryVersion)
787
+ return;
788
+ if (entryId.flavor === "ledger") {
789
+ entriesByKey.set(
790
+ idKey,
791
+ validateAndTransformEntryVersion({
792
+ entryType,
793
+ entryVersion,
794
+ accountPathToAccount,
795
+ defaultConsistencyConfig
796
+ })
797
+ );
798
+ return;
799
+ }
800
+ entriesByKey.set(
801
+ idKey,
802
+ transformEntryVersion({
803
+ entryType,
804
+ entryVersion,
805
+ accountPathToAccount,
806
+ errors: validateLivePaymentEntry({
807
+ entryVersion,
808
+ event: entryId.event,
809
+ entryIdentity: entryType.type,
810
+ accountPathToAccount
811
+ })
812
+ })
813
+ );
814
+ });
815
+ return entriesByKey;
816
+ };
817
+
818
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Entries/EntryValidationUtils.ts
819
+ init_cjs_shims();
820
+ var buildAccountIdToAccountRecord = (chartOfAccounts) => {
821
+ if (!chartOfAccounts)
822
+ return {};
823
+ const accountsMap = new Map(
824
+ Array.from(chartOfAccounts.accounts.entries())
825
+ );
826
+ const accountIds = {};
827
+ chartOfAccounts.accounts.forEach((account, accountId) => {
828
+ const structuralPath = computeStructuralPath(
829
+ accountId,
830
+ accountsMap,
831
+ account.parentId
832
+ );
833
+ accountIds[structuralPath] = accountId;
834
+ });
835
+ const filledIn = buildAndValidateChartOfAccounts(chartOfAccounts);
836
+ const enhancedCoA = enhanceCoA(filledIn, { accountIds });
837
+ return enhancedCoA.accountIdToAccount;
838
+ };
839
+
840
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/ScenarioValidationUtils.ts
841
+ init_cjs_shims();
842
+
843
+ // ../../fragment-compositions/visualizer/src/libs/FragmentBackendMock.ts
844
+ init_cjs_shims();
845
+ import assert from "assert";
846
+
847
+ // ../../libs/schema-validation/utils/transformers/schema.ts
848
+ init_cjs_shims();
849
+ var transformAndValidateSchema = (schema) => {
850
+ const errors = [];
851
+ const schemaKeyResult = SafeStringSchema.safeParse(schema.key);
852
+ if (!schemaKeyResult.success || schemaKeyResult.data.includes("{{") || schemaKeyResult.data.includes("}}")) {
853
+ errors.push({
854
+ message: `Invalid key. Keys cannot contain '{{' or '}}' and must be non-empty`,
855
+ path: ["key"]
856
+ });
857
+ }
858
+ const res = transformAndValidateCoA({
859
+ coa: schema.chartOfAccounts
860
+ });
861
+ const { errors: coaErrors } = res;
862
+ const validatedChartOfAccounts = res.filledIn;
863
+ errors.push(
864
+ ...coaErrors.map((e) => ({ ...e, path: ["chartOfAccounts", ...e.path] }))
865
+ );
866
+ const { filledIn: ledgerEntries, errors: entryErrors } = transformAndValidateEntries({
867
+ ledgerEntries: schema.ledgerEntries ?? { types: [] },
868
+ validatedCoA: validatedChartOfAccounts
869
+ });
870
+ errors.push(
871
+ ...entryErrors.map((e) => ({ ...e, path: ["ledgerEntries", ...e.path] }))
872
+ );
873
+ const { errors: paymentErrors } = transformAndValidatePayments({
874
+ payments: schema.payments ?? { types: [] },
875
+ validatedCoA: validatedChartOfAccounts
876
+ });
877
+ errors.push(
878
+ ...paymentErrors.map((e) => ({ ...e, path: ["payments", ...e.path] }))
879
+ );
880
+ const consistencyErrors = schema.consistencyConfig ? validateLedgerConsistencySettings(schema.consistencyConfig) : { errors: [] };
881
+ errors.push(...consistencyErrors.errors);
882
+ const groups = schema.groups ?? [];
883
+ if (groups.length > 0) {
884
+ groups.forEach((group, index) => {
885
+ const groupErrors = validateGroup(
886
+ group,
887
+ validatedChartOfAccounts,
888
+ ledgerEntries,
889
+ index
890
+ );
891
+ errors.push(...groupErrors);
892
+ });
893
+ }
894
+ return {
895
+ errors,
896
+ validatedSchema: {
897
+ name: schema.name,
898
+ key: schema.key,
899
+ consistencyConfig: schema.consistencyConfig?.entries ? {
900
+ entries: schema.consistencyConfig.entries
901
+ } : {
902
+ entries: "eventual"
903
+ },
904
+ ledgerEntries,
905
+ chartOfAccounts: validatedChartOfAccounts,
906
+ scenes: schema.scenes,
907
+ groups,
908
+ payments: schema.payments
909
+ }
910
+ };
911
+ };
912
+
913
+ // ../../libs/shared-utils/accounting/currency.ts
914
+ init_cjs_shims();
915
+
916
+ // ../../libs/shared-utils/accounting/doubleEntry.ts
917
+ init_cjs_shims();
918
+
919
+ // ../../fragment-compositions/visualizer/src/libs/FragmentBackendMock.ts
920
+ var formatSchemaValidationError = (error3) => {
921
+ const path = error3.path.length > 0 ? ` (Path: ${error3.path.join("/")})` : "";
922
+ const code = error3.code ? ` [${error3.code}]` : "";
923
+ return `${error3.message}${code}${path}`;
924
+ };
925
+ var getBaseEntryParameters = (entry, accountIdToAccount) => {
926
+ const allParams = new Set(
927
+ [
928
+ ...getSchemaObjectParameters(entry, false),
929
+ ...entry.lines.flatMap(
930
+ ({ account }) => account?.id ? getSchemaObjectParameters(accountIdToAccount[account.id], false) : []
931
+ )
932
+ ].filter((param) => !entry.parameters[param])
933
+ );
934
+ return [...allParams];
935
+ };
936
+ var validateEntryConditions = ({
937
+ filledEntry,
938
+ sceneEvents,
939
+ entryIndex
940
+ }) => {
941
+ filledEntry.conditions.forEach((condition) => {
942
+ const { path } = condition.account;
943
+ const { currency } = condition;
944
+ assert(
945
+ currency.code !== "MULTI",
946
+ `Invalid Condition. Condition in Entry ${filledEntry.type} on multi-currency Ledger Account ${path} must have a currency set`
947
+ );
948
+ const matchesPath = {
949
+ ownBalance: (linePath) => linePath === path,
950
+ totalBalance: (linePath) => linePath === path || linePath.startsWith(`${path}/`)
951
+ };
952
+ const sumLines = (lines, scope) => lines.filter(
953
+ (line) => matchesPath[scope](line.account.path) && line.currency.code === currency.code && line.currency.customCurrencyId === currency.customCurrencyId
954
+ ).reduce(
955
+ (sum, line) => sum + BigInt(evaluateExpression(line.amount)),
956
+ 0n
957
+ );
958
+ const sumPriorLines = (scope) => sceneEvents.slice(0, entryIndex).reduce(
959
+ (sum, { entry: balanceEntry }) => sum + (balanceEntry.isValid ? sumLines(balanceEntry.lines, scope) : 0n),
960
+ 0n
961
+ );
962
+ const checkBoundary = (kind, scope, amount, bounds) => {
963
+ if (!bounds)
964
+ return;
965
+ const label = kind === "precondition" ? "Precondition" : "Postcondition";
966
+ const when = kind === "precondition" ? "before posting this entry" : "after posting this entry";
967
+ const checks = [
968
+ ["=", bounds.eq, (a, b) => a === b],
969
+ [">=", bounds.gte, (a, b) => a >= b],
970
+ ["<=", bounds.lte, (a, b) => a <= b]
971
+ ];
972
+ checks.forEach(([op, rhs, cmp]) => {
973
+ if (rhs === void 0)
974
+ return;
975
+ assert(
976
+ cmp(amount, BigInt(evaluateExpression(rhs))),
977
+ `${label} not satisfied. Ledger Account ${path} must have ${scope} ${op} ${rhs} ${when}. Got: ${amount}`
978
+ );
979
+ });
980
+ };
981
+ const preOwn = sumPriorLines("ownBalance");
982
+ const preTotal = sumPriorLines("totalBalance");
983
+ checkBoundary(
984
+ "precondition",
985
+ "ownBalance",
986
+ preOwn,
987
+ condition.precondition?.ownBalance
988
+ );
989
+ checkBoundary(
990
+ "precondition",
991
+ "totalBalance",
992
+ preTotal,
993
+ condition.precondition?.totalBalance
994
+ );
995
+ const postOwn = preOwn + sumLines(filledEntry.lines, "ownBalance");
996
+ const postTotal = preTotal + sumLines(filledEntry.lines, "totalBalance");
997
+ checkBoundary(
998
+ "postcondition",
999
+ "ownBalance",
1000
+ postOwn,
1001
+ condition.postcondition?.ownBalance
1002
+ );
1003
+ checkBoundary(
1004
+ "postcondition",
1005
+ "totalBalance",
1006
+ postTotal,
1007
+ condition.postcondition?.totalBalance
1008
+ );
1009
+ });
1010
+ };
1011
+ var validateEntry2 = ({
1012
+ accountIdToAccount,
1013
+ baseEntry,
1014
+ errors,
1015
+ entry,
1016
+ parameterValues
1017
+ }) => {
1018
+ try {
1019
+ if (baseEntry) {
1020
+ if (errors.length > 0) {
1021
+ return {
1022
+ errorKind: "entry_invalid",
1023
+ reasons: errors.map(formatSchemaValidationError)
1024
+ };
1025
+ }
1026
+ const parameters = getBaseEntryParameters(baseEntry, accountIdToAccount);
1027
+ const missingParams = parameters.filter(
1028
+ (param) => !parameterValues[param]
1029
+ );
1030
+ if (missingParams.length) {
1031
+ throw new Error("All parameters must be filled in");
1032
+ }
1033
+ }
1034
+ const lineValues = {};
1035
+ entry.lines.forEach((line) => {
1036
+ line.amountParameters.forEach((param) => {
1037
+ assert(
1038
+ !Number.isNaN(parseInt(parameterValues[param], 10)),
1039
+ `Parameter ${param} must have numeric value`
1040
+ );
1041
+ });
1042
+ });
1043
+ const filledEntry = fillParams(entry, {
1044
+ ...parameterValues,
1045
+ ...entry.parameters
1046
+ });
1047
+ filledEntry.lines.forEach((line, lineNumber) => {
1048
+ const key = makeLineKey(line, lineNumber);
1049
+ const amount = line.amount && evaluateExpression(line.amount);
1050
+ lineValues[key] = {
1051
+ amount: Number(amount)
1052
+ };
1053
+ });
1054
+ assert(
1055
+ filledEntry.lines.every(
1056
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1057
+ (line, lineNumber) => lineValues[makeLineKey(line, lineNumber)]
1058
+ ),
1059
+ "All amounts must be populated"
1060
+ );
1061
+ const accountsForBalancedPayload = {};
1062
+ const linesForBalancedPayload = filledEntry.lines.map(
1063
+ (line, lineNumber) => {
1064
+ const lineKey = makeLineKey(line, lineNumber);
1065
+ const fetchedAccount = accountIdToAccount[line.account.id];
1066
+ const accountType = fetchedAccount.type;
1067
+ if (accountType === void 0) {
1068
+ throw new Error(
1069
+ `Could not determine account type for path ${fetchedAccount.structuralPath}`
1070
+ );
1071
+ }
1072
+ const account = {
1073
+ currency: CurrencyCodeSchema.parse(line.currency.code),
1074
+ customCurrencyId: line.currency.customCurrencyId,
1075
+ type: accountType
1076
+ };
1077
+ const accountKey = `${fetchedAccount.structuralPath}:${serializeCurrency(account)}`;
1078
+ accountsForBalancedPayload[accountKey] = account;
1079
+ return {
1080
+ currency: line.currency.code,
1081
+ customCurrencyId: line.currency.customCurrencyId,
1082
+ amount: BigInt(lineValues[lineKey].amount),
1083
+ account: {
1084
+ id: accountKey
1085
+ }
1086
+ };
1087
+ }
1088
+ );
1089
+ assertBalancedLines({
1090
+ // @ts-expect-error TODO: make visualizer support parameterized currencies after https://github.com/fragment-dev/workspaces/pull/3076/files is merged
1091
+ lines: linesForBalancedPayload,
1092
+ ledgerAccounts: accountsForBalancedPayload
1093
+ });
1094
+ return { lineValues, filledEntry };
1095
+ } catch (err) {
1096
+ if (err instanceof Error) {
1097
+ return { errorKind: "parameter_error", reasons: [err.message] };
1098
+ }
1099
+ throw err;
1100
+ }
1101
+ };
1102
+ var generatePostedEntry = ({
1103
+ accountIdToAccount,
1104
+ baseEntry,
1105
+ errors,
1106
+ entry,
1107
+ postedEntryId,
1108
+ parameterValues
1109
+ }) => {
1110
+ const entryId = postedEntryId || lil_id_default();
1111
+ const validation = validateEntry2({
1112
+ accountIdToAccount,
1113
+ baseEntry,
1114
+ errors,
1115
+ entry,
1116
+ parameterValues
1117
+ });
1118
+ if ("reasons" in validation) {
1119
+ return {
1120
+ isValid: false,
1121
+ errorKind: validation.errorKind,
1122
+ reasons: validation.reasons,
1123
+ id: entryId,
1124
+ type: entry.type,
1125
+ typeVersion: entry.typeVersion,
1126
+ baseEntryId: entry.id,
1127
+ parameters: parameterValues
1128
+ };
1129
+ }
1130
+ const { filledEntry, lineValues } = validation;
1131
+ return {
1132
+ id: entryId,
1133
+ typeVersion: filledEntry.typeVersion,
1134
+ ik: lil_id_default(),
1135
+ type: filledEntry.type,
1136
+ parameters: parameterValues,
1137
+ conditions: filledEntry.conditions,
1138
+ lines: filledEntry.lines.map(
1139
+ (line, lineNumber) => ({
1140
+ ...line,
1141
+ amount: String(lineValues[makeLineKey(line, lineNumber)].amount)
1142
+ })
1143
+ ),
1144
+ tags: filledEntry.tags,
1145
+ groups: filledEntry.groups,
1146
+ baseEntryId: entry.id,
1147
+ isValid: true,
1148
+ status: filledEntry.status ?? "active"
1149
+ };
1150
+ };
1151
+
1152
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Entries/useEntryUtils.ts
1153
+ init_cjs_shims();
1154
+ var convertEntryResponseToEnhancedSchemaLedgerEntry = (entry, accountIdToAccount) => {
1155
+ const baseEntry = {
1156
+ type: entry.value.type,
1157
+ typeVersion: entry.value.typeVersion,
1158
+ description: entry.value.description,
1159
+ postLinesAs: entry.value.postLinesAs,
1160
+ status: entry.value.status,
1161
+ parameters: convertStaticParametersToRecord(entry.value.parameters) ?? {},
1162
+ groups: entry.value.groups?.map((group) => ({
1163
+ key: safe`${group.key}`,
1164
+ value: group.value
1165
+ })) ?? [],
1166
+ tags: entry.value.tags?.map((tag) => ({
1167
+ key: tag.key,
1168
+ value: tag.value
1169
+ })) ?? [],
1170
+ lines: entry.value.lines?.map((line) => ({
1171
+ key: line.key,
1172
+ account: line.account ? {
1173
+ id: line.account.accountId ?? "",
1174
+ path: line.account.path
1175
+ } : void 0,
1176
+ amount: line.amount,
1177
+ currency: line.currency,
1178
+ description: line.description,
1179
+ tx: line.tx,
1180
+ repeated: line.repeated ? { key: safe`${line.repeated.key}` } : void 0
1181
+ })) ?? [],
1182
+ conditions: entry.value.conditions?.map((condition) => ({
1183
+ account: condition.account ? {
1184
+ id: condition.account.accountId ?? "",
1185
+ path: condition.account.path
1186
+ } : void 0,
1187
+ currency: condition.currency,
1188
+ precondition: condition.precondition,
1189
+ postcondition: condition.postcondition,
1190
+ repeated: condition.repeated ? { key: safe`${condition.repeated.key}` } : void 0
1191
+ })) ?? []
1192
+ };
1193
+ return enhanceLedgerEntry(
1194
+ baseEntry,
1195
+ accountIdToAccount,
1196
+ safe`${entry.value.typeVersion && entry.value.typeVersion > 1 ? entry.value.versionId : entry.value.entryId}`
1197
+ );
1198
+ };
1199
+
1200
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/ScenarioValidationUtils.ts
1201
+ var transformLiveblocksSceneEvents = (resolvedEvents, entriesByKey, accountIdToAccount) => {
1202
+ const accountMap = new Map(Object.entries(accountIdToAccount));
1203
+ const postedEntries = [];
1204
+ resolvedEvents.forEach((event, entryIndex) => {
1205
+ const { entryId, idKey, payment: paymentInfo } = event;
1206
+ const baseEntryResponse = idKey === null ? void 0 : entriesByKey.get(idKey);
1207
+ const baseEntryId = (entryId && (entryId.flavor === "payment" ? entryId.paymentTypeId : entryId.entryTypeId)) ?? "";
1208
+ const repeatedParams = event.repeatedParameters;
1209
+ const staticParams = event.parameters;
1210
+ const pushSceneEvent = (entry, lineAccountTypes2) => {
1211
+ postedEntries.push(
1212
+ paymentInfo ? {
1213
+ id: event.id,
1214
+ eventType: "payment-entry",
1215
+ entry,
1216
+ payment: paymentInfo,
1217
+ entryId,
1218
+ lineAccountTypes: lineAccountTypes2
1219
+ } : {
1220
+ id: event.id,
1221
+ eventType: "entry",
1222
+ entry,
1223
+ entryId,
1224
+ lineAccountTypes: lineAccountTypes2
1225
+ }
1226
+ );
1227
+ };
1228
+ const pushInvalidSceneEvent = (errorKind, reasons) => {
1229
+ pushSceneEvent(
1230
+ {
1231
+ id: event.id,
1232
+ parameters: { ...staticParams, ...repeatedParams },
1233
+ baseEntryId,
1234
+ type: paymentInfo?.paymentType ?? "unknown",
1235
+ isValid: false,
1236
+ errorKind,
1237
+ reasons
1238
+ },
1239
+ []
1240
+ );
1241
+ };
1242
+ if (event.failure) {
1243
+ pushInvalidSceneEvent(event.failure.errorKind, event.failure.reasons);
1244
+ return;
1245
+ }
1246
+ if (!baseEntryResponse) {
1247
+ pushInvalidSceneEvent("entry_invalid", [
1248
+ entryId?.flavor === "payment" ? PAYMENT_GONE_FROM_SCHEMA_REASON : "Entry not found"
1249
+ ]);
1250
+ return;
1251
+ }
1252
+ const lineAccountTypes = (baseEntryResponse.value.lines ?? []).map((line) => {
1253
+ if (!line.account?.accountId) {
1254
+ return void 0;
1255
+ }
1256
+ const account = accountMap.get(line.account.accountId);
1257
+ if (!account) {
1258
+ return void 0;
1259
+ }
1260
+ return account.type;
1261
+ }).filter((type) => type !== void 0);
1262
+ const enhancedEntry = convertEntryResponseToEnhancedSchemaLedgerEntry(
1263
+ baseEntryResponse,
1264
+ accountIdToAccount
1265
+ );
1266
+ const simulatingEntryErrors = [];
1267
+ const simulatingEntry = generateSimulatingEntry({
1268
+ entry: enhancedEntry,
1269
+ accountIdToAccount,
1270
+ onError: (error3) => {
1271
+ if (error3 instanceof Error) {
1272
+ simulatingEntryErrors.push(error3.message);
1273
+ }
1274
+ }
1275
+ });
1276
+ if (!simulatingEntry) {
1277
+ pushSceneEvent(
1278
+ {
1279
+ id: event.id,
1280
+ parameters: { ...staticParams, ...repeatedParams },
1281
+ baseEntryId,
1282
+ type: "unknown",
1283
+ isValid: false,
1284
+ errorKind: "parameter_error",
1285
+ reasons: [
1286
+ "Failed to fill parameters on Entry. Reasons: ",
1287
+ simulatingEntryErrors.join(", ")
1288
+ ]
1289
+ },
1290
+ []
1291
+ );
1292
+ return;
1293
+ }
1294
+ const mergedRepeatedParams = { ...staticParams, ...repeatedParams };
1295
+ const preFilledEntry = {
1296
+ ...simulatingEntry,
1297
+ lines: simulatingEntry.lines.map(
1298
+ (line) => fillParams(line, line.repeated ? mergedRepeatedParams : staticParams, {
1299
+ allowMissing: true,
1300
+ allowMissingInChildren: true
1301
+ })
1302
+ ),
1303
+ conditions: simulatingEntry.conditions.map(
1304
+ (condition) => fillParams(
1305
+ condition,
1306
+ condition.repeated ? mergedRepeatedParams : staticParams,
1307
+ { allowMissing: true, allowMissingInChildren: true }
1308
+ )
1309
+ )
1310
+ };
1311
+ const postedEntry = generatePostedEntry({
1312
+ accountIdToAccount,
1313
+ baseEntry: enhancedEntry,
1314
+ errors: baseEntryResponse.errors,
1315
+ entry: preFilledEntry,
1316
+ postedEntryId: event.id,
1317
+ parameterValues: { ...staticParams, ...repeatedParams }
1318
+ });
1319
+ if (postedEntry.isValid) {
1320
+ const lineAccounts = postedEntry.lines.map((line) => ({
1321
+ acc: accountMap.get(line.account.id),
1322
+ currency: line.currency
1323
+ })).filter(
1324
+ (la) => la.acc !== void 0
1325
+ );
1326
+ if (lineAccounts.length !== postedEntry.lines.length) {
1327
+ pushSceneEvent(
1328
+ {
1329
+ ...postedEntry,
1330
+ isValid: false,
1331
+ errorKind: "entry_invalid",
1332
+ reasons: ["Could not find account for some lines"]
1333
+ },
1334
+ []
1335
+ );
1336
+ return;
1337
+ }
1338
+ const resolveAccountType = (acc) => acc.type;
1339
+ const lineAccountWithMissingType = lineAccounts.find(
1340
+ ({ acc }) => resolveAccountType(acc) === void 0
1341
+ );
1342
+ if (lineAccountWithMissingType) {
1343
+ pushSceneEvent(
1344
+ {
1345
+ ...postedEntry,
1346
+ isValid: false,
1347
+ errorKind: "entry_invalid",
1348
+ reasons: [
1349
+ `Could not determine account type for path ${lineAccountWithMissingType.acc.structuralPath}`
1350
+ ]
1351
+ },
1352
+ []
1353
+ );
1354
+ return;
1355
+ }
1356
+ const conditionWithMissingType = postedEntry.conditions.map(
1357
+ (condition) => condition.account.id ? accountMap.get(condition.account.id) : void 0
1358
+ ).find(
1359
+ (account) => account && resolveAccountType(account) === void 0
1360
+ );
1361
+ if (conditionWithMissingType) {
1362
+ pushSceneEvent(
1363
+ {
1364
+ ...postedEntry,
1365
+ isValid: false,
1366
+ errorKind: "entry_invalid",
1367
+ reasons: [
1368
+ `Could not determine account type for path ${conditionWithMissingType.structuralPath}`
1369
+ ]
1370
+ },
1371
+ []
1372
+ );
1373
+ return;
1374
+ }
1375
+ try {
1376
+ validateEntryConditions({
1377
+ filledEntry: postedEntry,
1378
+ sceneEvents: postedEntries,
1379
+ entryIndex
1380
+ });
1381
+ } catch (err) {
1382
+ if (err instanceof Error) {
1383
+ pushSceneEvent(
1384
+ {
1385
+ ...postedEntry,
1386
+ isValid: false,
1387
+ errorKind: "parameter_error",
1388
+ reasons: [`Error in entry condition: ${err.message}`]
1389
+ },
1390
+ []
1391
+ );
1392
+ }
1393
+ return;
1394
+ }
1395
+ }
1396
+ pushSceneEvent(postedEntry, lineAccountTypes);
1397
+ });
1398
+ return postedEntries;
1399
+ };
1400
+
1401
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/simulateScene.ts
1402
+ var NO_SCENE_PAYMENTS = /* @__PURE__ */ new Map();
1403
+ var simulateScene = ({
1404
+ root,
1405
+ sceneId
1406
+ }) => {
1407
+ const scene = root.schema.scenes.get(sceneId);
1408
+ if (!scene)
1409
+ return null;
1410
+ const { chartOfAccounts } = root.schema;
1411
+ const accountIdToAccount = buildAccountIdToAccountRecord(chartOfAccounts);
1412
+ const { accountPathToAccount, defaultConsistencyConfig } = buildAccountPathToAccountMap(chartOfAccounts);
1413
+ const resolvedEvents = resolveSceneEvents({
1414
+ events: Array.from(scene.events.values()),
1415
+ eventsOrder: Array.from(scene.eventsOrder.values()),
1416
+ payments: scene.payments ?? NO_SCENE_PAYMENTS,
1417
+ paymentTypes: root.schema.paymentTypes
1418
+ });
1419
+ const entriesByKey = buildSceneEntriesByKey({
1420
+ resolvedEvents,
1421
+ root,
1422
+ accountPathToAccount,
1423
+ defaultConsistencyConfig
1424
+ });
1425
+ const events = transformLiveblocksSceneEvents(
1426
+ resolvedEvents,
1427
+ entriesByKey,
1428
+ accountIdToAccount
1429
+ );
1430
+ return {
1431
+ id: scene.id,
1432
+ name: scene.name ?? "",
1433
+ events
1434
+ };
1435
+ };
1436
+
1437
+ // ../../fragment-compositions/visualizer/src/utils/liveblocksUtils.ts
1438
+ init_cjs_shims();
1439
+ import assert3 from "assert";
1440
+
1441
+ // ../../node_modules/@liveblocks/client/dist/index.js
1442
+ init_cjs_shims();
1443
+
1444
+ // ../../node_modules/@liveblocks/core/dist/index.js
1445
+ init_cjs_shims();
1446
+ var __defProp = Object.defineProperty;
1447
+ var __export = (target, all) => {
1448
+ for (var name in all)
1449
+ __defProp(target, name, { get: all[name], enumerable: true });
1450
+ };
1451
+ var PKG_NAME = "@liveblocks/core";
1452
+ var PKG_VERSION = "3.7.1";
1453
+ var PKG_FORMAT = "esm";
1454
+ var g = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
1455
+ var crossLinkedDocs = "https://liveblocks.io/docs/errors/cross-linked";
1456
+ var dupesDocs = "https://liveblocks.io/docs/errors/dupes";
1457
+ var SPACE = " ";
1458
+ function error(msg) {
1459
+ if (process.env.NODE_ENV === "production") {
1460
+ console.error(msg);
1461
+ } else {
1462
+ throw new Error(msg);
1463
+ }
1464
+ }
1465
+ function detectDupes(pkgName, pkgVersion, pkgFormat) {
1466
+ const pkgId = Symbol.for(pkgName);
1467
+ const pkgBuildInfo = pkgFormat ? `${pkgVersion || "dev"} (${pkgFormat})` : pkgVersion || "dev";
1468
+ if (!g[pkgId]) {
1469
+ g[pkgId] = pkgBuildInfo;
1470
+ } else if (g[pkgId] === pkgBuildInfo) {
1471
+ } else {
1472
+ const msg = [
1473
+ `Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See ${dupesDocs + SPACE}`,
1474
+ "",
1475
+ "Conflicts:",
1476
+ `- ${pkgName} ${g[pkgId]} (already loaded)`,
1477
+ `- ${pkgName} ${pkgBuildInfo} (trying to load this now)`
1478
+ ].join("\n");
1479
+ error(msg);
1480
+ }
1481
+ if (pkgVersion && PKG_VERSION && pkgVersion !== PKG_VERSION) {
1482
+ error(
1483
+ [
1484
+ `Cross-linked versions of Liveblocks found, which will cause issues! See ${crossLinkedDocs + SPACE}`,
1485
+ "",
1486
+ "Conflicts:",
1487
+ `- ${PKG_NAME} is at ${PKG_VERSION}`,
1488
+ `- ${pkgName} is at ${pkgVersion}`,
1489
+ "",
1490
+ "Always upgrade all Liveblocks packages to the same version number."
1491
+ ].join("\n")
1492
+ );
1493
+ }
1494
+ }
1495
+ function makeEventSource() {
1496
+ const _observers = /* @__PURE__ */ new Set();
1497
+ function subscribe(callback) {
1498
+ _observers.add(callback);
1499
+ return () => _observers.delete(callback);
1500
+ }
1501
+ function subscribeOnce(callback) {
1502
+ const unsub = subscribe((event) => {
1503
+ unsub();
1504
+ return callback(event);
1505
+ });
1506
+ return unsub;
1507
+ }
1508
+ async function waitUntil(predicate) {
1509
+ let unsub;
1510
+ return new Promise((res) => {
1511
+ unsub = subscribe((event) => {
1512
+ if (predicate === void 0 || predicate(event)) {
1513
+ res(event);
1514
+ }
1515
+ });
1516
+ }).finally(() => unsub?.());
1517
+ }
1518
+ function notify(event) {
1519
+ let called = false;
1520
+ for (const callback of _observers) {
1521
+ callback(event);
1522
+ called = true;
1523
+ }
1524
+ return called;
1525
+ }
1526
+ function count() {
1527
+ return _observers.size;
1528
+ }
1529
+ return {
1530
+ // Private/internal control over event emission
1531
+ notify,
1532
+ subscribe,
1533
+ subscribeOnce,
1534
+ count,
1535
+ waitUntil,
1536
+ dispose() {
1537
+ _observers.clear();
1538
+ },
1539
+ // Publicly exposable subscription API
1540
+ observable: {
1541
+ subscribe,
1542
+ subscribeOnce,
1543
+ waitUntil
1544
+ }
1545
+ };
1546
+ }
1547
+ var freeze = process.env.NODE_ENV === "production" ? (
1548
+ /* istanbul ignore next */
1549
+ (x) => x
1550
+ ) : Object.freeze;
1551
+ function raise(msg) {
1552
+ throw new Error(msg);
1553
+ }
1554
+ function deepClone(value) {
1555
+ return JSON.parse(JSON.stringify(value));
1556
+ }
1557
+ function compactObject(obj) {
1558
+ const newObj = { ...obj };
1559
+ Object.keys(obj).forEach((k) => {
1560
+ const key = k;
1561
+ if (newObj[key] === void 0) {
1562
+ delete newObj[key];
1563
+ }
1564
+ });
1565
+ return newObj;
1566
+ }
1567
+ var kSinks = Symbol("kSinks");
1568
+ var kTrigger = Symbol("kTrigger");
1569
+ var signalsToTrigger = null;
1570
+ var trackedReads = null;
1571
+ function enqueueTrigger(signal) {
1572
+ if (!signalsToTrigger)
1573
+ raise("Expected to be in an active batch");
1574
+ signalsToTrigger.add(signal);
1575
+ }
1576
+ var AbstractSignal = class {
1577
+ /** @internal */
1578
+ equals;
1579
+ #eventSource;
1580
+ /** @internal */
1581
+ [kSinks];
1582
+ constructor(equals) {
1583
+ this.equals = equals ?? Object.is;
1584
+ this.#eventSource = makeEventSource();
1585
+ this[kSinks] = /* @__PURE__ */ new Set();
1586
+ this.get = this.get.bind(this);
1587
+ this.subscribe = this.subscribe.bind(this);
1588
+ this.subscribeOnce = this.subscribeOnce.bind(this);
1589
+ }
1590
+ dispose() {
1591
+ this.#eventSource.dispose();
1592
+ this.#eventSource = "(disposed)";
1593
+ this.equals = "(disposed)";
1594
+ }
1595
+ get hasWatchers() {
1596
+ if (this.#eventSource.count() > 0)
1597
+ return true;
1598
+ for (const sink of this[kSinks]) {
1599
+ if (sink.hasWatchers) {
1600
+ return true;
1601
+ }
1602
+ }
1603
+ return false;
1604
+ }
1605
+ [kTrigger]() {
1606
+ this.#eventSource.notify();
1607
+ for (const sink of this[kSinks]) {
1608
+ enqueueTrigger(sink);
1609
+ }
1610
+ }
1611
+ subscribe(callback) {
1612
+ if (this.#eventSource.count() === 0) {
1613
+ this.get();
1614
+ }
1615
+ return this.#eventSource.subscribe(callback);
1616
+ }
1617
+ subscribeOnce(callback) {
1618
+ const unsub = this.subscribe(() => {
1619
+ unsub();
1620
+ return callback();
1621
+ });
1622
+ return unsub;
1623
+ }
1624
+ waitUntil() {
1625
+ throw new Error("waitUntil not supported on Signals");
1626
+ }
1627
+ markSinksDirty() {
1628
+ for (const sink of this[kSinks]) {
1629
+ sink.markDirty();
1630
+ }
1631
+ }
1632
+ addSink(sink) {
1633
+ this[kSinks].add(sink);
1634
+ }
1635
+ removeSink(sink) {
1636
+ this[kSinks].delete(sink);
1637
+ }
1638
+ asReadonly() {
1639
+ return this;
1640
+ }
1641
+ };
1642
+ var INITIAL = Symbol();
1643
+ var DerivedSignal = class _DerivedSignal extends AbstractSignal {
1644
+ #prevValue;
1645
+ #dirty;
1646
+ // When true, the value in #value may not be up-to-date and needs re-checking
1647
+ #sources;
1648
+ #deps;
1649
+ #transform;
1650
+ // prettier-ignore
1651
+ static from(...args) {
1652
+ const last = args.pop();
1653
+ if (typeof last !== "function")
1654
+ raise("Invalid .from() call, last argument expected to be a function");
1655
+ if (typeof args[args.length - 1] === "function") {
1656
+ const equals = last;
1657
+ const transform = args.pop();
1658
+ return new _DerivedSignal(args, transform, equals);
1659
+ } else {
1660
+ const transform = last;
1661
+ return new _DerivedSignal(args, transform);
1662
+ }
1663
+ }
1664
+ constructor(deps, transform, equals) {
1665
+ super(equals);
1666
+ this.#dirty = true;
1667
+ this.#prevValue = INITIAL;
1668
+ this.#deps = deps;
1669
+ this.#sources = /* @__PURE__ */ new Set();
1670
+ this.#transform = transform;
1671
+ }
1672
+ dispose() {
1673
+ for (const src of this.#sources) {
1674
+ src.removeSink(this);
1675
+ }
1676
+ this.#prevValue = "(disposed)";
1677
+ this.#sources = "(disposed)";
1678
+ this.#deps = "(disposed)";
1679
+ this.#transform = "(disposed)";
1680
+ }
1681
+ get isDirty() {
1682
+ return this.#dirty;
1683
+ }
1684
+ #recompute() {
1685
+ const oldTrackedReads = trackedReads;
1686
+ let derived;
1687
+ trackedReads = /* @__PURE__ */ new Set();
1688
+ try {
1689
+ derived = this.#transform(...this.#deps.map((p) => p.get()));
1690
+ } finally {
1691
+ const oldSources = this.#sources;
1692
+ this.#sources = /* @__PURE__ */ new Set();
1693
+ for (const sig of trackedReads) {
1694
+ this.#sources.add(sig);
1695
+ oldSources.delete(sig);
1696
+ }
1697
+ for (const oldSource of oldSources) {
1698
+ oldSource.removeSink(this);
1699
+ }
1700
+ for (const newSource of this.#sources) {
1701
+ newSource.addSink(this);
1702
+ }
1703
+ trackedReads = oldTrackedReads;
1704
+ }
1705
+ this.#dirty = false;
1706
+ if (!this.equals(this.#prevValue, derived)) {
1707
+ this.#prevValue = derived;
1708
+ return true;
1709
+ }
1710
+ return false;
1711
+ }
1712
+ markDirty() {
1713
+ if (!this.#dirty) {
1714
+ this.#dirty = true;
1715
+ this.markSinksDirty();
1716
+ }
1717
+ }
1718
+ get() {
1719
+ if (this.#dirty) {
1720
+ this.#recompute();
1721
+ }
1722
+ trackedReads?.add(this);
1723
+ return this.#prevValue;
1724
+ }
1725
+ /**
1726
+ * Called by the Signal system if one or more of the dependent signals have
1727
+ * changed. In the case of a DerivedSignal, we'll only want to re-evaluate
1728
+ * the actual value if it's being watched, or any of their sinks are being
1729
+ * watched actively.
1730
+ */
1731
+ [kTrigger]() {
1732
+ if (!this.hasWatchers) {
1733
+ return;
1734
+ }
1735
+ const updated = this.#recompute();
1736
+ if (updated) {
1737
+ super[kTrigger]();
1738
+ }
1739
+ }
1740
+ };
1741
+ function assertNever(_value, errmsg) {
1742
+ throw new Error(errmsg);
1743
+ }
1744
+ function assert2(condition, errmsg) {
1745
+ if (process.env.NODE_ENV !== "production") {
1746
+ if (!condition) {
1747
+ const err = new Error(errmsg);
1748
+ err.name = "Assertion failure";
1749
+ throw err;
1750
+ }
1751
+ }
1752
+ }
1753
+ function nn(value, errmsg = "Expected value to be non-nullable") {
1754
+ assert2(value !== null && value !== void 0, errmsg);
1755
+ return value;
1756
+ }
1757
+ var fancy_console_exports = {};
1758
+ __export(fancy_console_exports, {
1759
+ error: () => error2,
1760
+ errorWithTitle: () => errorWithTitle,
1761
+ warn: () => warn,
1762
+ warnWithTitle: () => warnWithTitle
1763
+ });
1764
+ var badge = "background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;";
1765
+ var bold = "font-weight:600";
1766
+ function wrap(method) {
1767
+ return typeof window === "undefined" || process.env.NODE_ENV === "test" ? console[method] : (
1768
+ /* istanbul ignore next */
1769
+ (message, ...args) => console[method]("%cLiveblocks", badge, message, ...args)
1770
+ );
1771
+ }
1772
+ var warn = wrap("warn");
1773
+ var error2 = wrap("error");
1774
+ function wrapWithTitle(method) {
1775
+ return typeof window === "undefined" || process.env.NODE_ENV === "test" ? console[method] : (
1776
+ /* istanbul ignore next */
1777
+ (title, message, ...args) => console[method](
1778
+ `%cLiveblocks%c ${title}`,
1779
+ badge,
1780
+ bold,
1781
+ message,
1782
+ ...args
1783
+ )
1784
+ );
1785
+ }
1786
+ var warnWithTitle = wrapWithTitle("warn");
1787
+ var errorWithTitle = wrapWithTitle("error");
1788
+ var nanoid = (t = 21) => crypto.getRandomValues(new Uint8Array(t)).reduce(
1789
+ (t2, e) => t2 += (e &= 63) < 36 ? e.toString(36) : e < 62 ? (e - 26).toString(36).toUpperCase() : e < 63 ? "_" : "-",
1790
+ ""
1791
+ );
1792
+ var BACKOFF_DELAYS = [250, 500, 1e3, 2e3, 4e3, 8e3, 1e4];
1793
+ var RESET_DELAY = BACKOFF_DELAYS[0] - 1;
1794
+ function log(level, message) {
1795
+ const logger = level === 2 ? error2 : level === 1 ? warn : (
1796
+ /* black hole */
1797
+ () => {
1798
+ }
1799
+ );
1800
+ return () => {
1801
+ logger(message);
1802
+ };
1803
+ }
1804
+ var logPermanentClose = log(
1805
+ 1,
1806
+ "Connection to WebSocket closed permanently. Won't retry."
1807
+ );
1808
+ var kInternal = Symbol();
1809
+ var EMPTY_OBJECT = Object.freeze({});
1810
+ var NULL_KEYWORD_CHARS = Array.from(new Set("null"));
1811
+ var TRUE_KEYWORD_CHARS = Array.from(new Set("true"));
1812
+ var FALSE_KEYWORD_CHARS = Array.from(new Set("false"));
1813
+ var ALL_KEYWORD_CHARS = Array.from(new Set("nulltruefalse"));
1814
+ var kWILDCARD = Symbol("*");
1815
+ var eventSource = makeEventSource();
1816
+ if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
1817
+ window.addEventListener("message", (event) => {
1818
+ if (event.source === window && event.data?.source === "liveblocks-devtools-panel") {
1819
+ eventSource.notify(event.data);
1820
+ } else {
1821
+ }
1822
+ });
1823
+ }
1824
+ var onMessageFromPanel = eventSource.observable;
1825
+ var loadedAt = Date.now();
1826
+ var kPlain = Symbol("notification-settings-plain");
1827
+ var MIN_CODE = 32;
1828
+ var MAX_CODE = 126;
1829
+ var NUM_DIGITS = MAX_CODE - MIN_CODE + 1;
1830
+ var ZERO = nthDigit(0);
1831
+ var ONE = nthDigit(1);
1832
+ var ZERO_NINE = ZERO + nthDigit(-1);
1833
+ function nthDigit(n) {
1834
+ const code = MIN_CODE + (n < 0 ? NUM_DIGITS + n : n);
1835
+ if (code < MIN_CODE || code > MAX_CODE) {
1836
+ throw new Error(`Invalid n value: ${n}`);
1837
+ }
1838
+ return String.fromCharCode(code);
1839
+ }
1840
+ function makePosition(x, y) {
1841
+ if (x !== void 0 && y !== void 0) {
1842
+ return between(x, y);
1843
+ } else if (x !== void 0) {
1844
+ return after(x);
1845
+ } else if (y !== void 0) {
1846
+ return before(y);
1847
+ } else {
1848
+ return ONE;
1849
+ }
1850
+ }
1851
+ function before(pos) {
1852
+ const lastIndex = pos.length - 1;
1853
+ for (let i = 0; i <= lastIndex; i++) {
1854
+ const code = pos.charCodeAt(i);
1855
+ if (code <= MIN_CODE) {
1856
+ continue;
1857
+ }
1858
+ if (i === lastIndex) {
1859
+ if (code === MIN_CODE + 1) {
1860
+ return pos.substring(0, i) + ZERO_NINE;
1861
+ } else {
1862
+ return pos.substring(0, i) + String.fromCharCode(code - 1);
1863
+ }
1864
+ } else {
1865
+ return pos.substring(0, i + 1);
1866
+ }
1867
+ }
1868
+ return ONE;
1869
+ }
1870
+ function after(pos) {
1871
+ for (let i = 0; i <= pos.length - 1; i++) {
1872
+ const code = pos.charCodeAt(i);
1873
+ if (code >= MAX_CODE) {
1874
+ continue;
1875
+ }
1876
+ return pos.substring(0, i) + String.fromCharCode(code + 1);
1877
+ }
1878
+ return pos + ONE;
1879
+ }
1880
+ function between(lo, hi) {
1881
+ if (lo < hi) {
1882
+ return _between(lo, hi);
1883
+ } else if (lo > hi) {
1884
+ return _between(hi, lo);
1885
+ } else {
1886
+ throw new Error("Cannot compute value between two equal positions");
1887
+ }
1888
+ }
1889
+ function _between(lo, hi) {
1890
+ let index = 0;
1891
+ const loLen = lo.length;
1892
+ const hiLen = hi.length;
1893
+ while (true) {
1894
+ const loCode = index < loLen ? lo.charCodeAt(index) : MIN_CODE;
1895
+ const hiCode = index < hiLen ? hi.charCodeAt(index) : MAX_CODE;
1896
+ if (loCode === hiCode) {
1897
+ index++;
1898
+ continue;
1899
+ }
1900
+ if (hiCode - loCode === 1) {
1901
+ const size = index + 1;
1902
+ let prefix = lo.substring(0, size);
1903
+ if (prefix.length < size) {
1904
+ prefix += ZERO.repeat(size - prefix.length);
1905
+ }
1906
+ const suffix = lo.substring(size);
1907
+ const nines = "";
1908
+ return prefix + _between(suffix, nines);
1909
+ } else {
1910
+ return takeN(lo, index) + String.fromCharCode(hiCode + loCode >> 1);
1911
+ }
1912
+ }
1913
+ }
1914
+ function takeN(pos, n) {
1915
+ return n < pos.length ? pos.substring(0, n) : pos + ZERO.repeat(n - pos.length);
1916
+ }
1917
+ var MIN_NON_ZERO_CODE = MIN_CODE + 1;
1918
+ function isPos(str) {
1919
+ if (str === "") {
1920
+ return false;
1921
+ }
1922
+ const lastIdx = str.length - 1;
1923
+ const last = str.charCodeAt(lastIdx);
1924
+ if (last < MIN_NON_ZERO_CODE || last > MAX_CODE) {
1925
+ return false;
1926
+ }
1927
+ for (let i = 0; i < lastIdx; i++) {
1928
+ const code = str.charCodeAt(i);
1929
+ if (code < MIN_CODE || code > MAX_CODE) {
1930
+ return false;
1931
+ }
1932
+ }
1933
+ return true;
1934
+ }
1935
+ function convertToPos(str) {
1936
+ const codes2 = [];
1937
+ for (let i = 0; i < str.length; i++) {
1938
+ const code = str.charCodeAt(i);
1939
+ codes2.push(code < MIN_CODE ? MIN_CODE : code > MAX_CODE ? MAX_CODE : code);
1940
+ }
1941
+ while (codes2.length > 0 && codes2[codes2.length - 1] === MIN_CODE) {
1942
+ codes2.length--;
1943
+ }
1944
+ return codes2.length > 0 ? String.fromCharCode(...codes2) : (
1945
+ // Edge case: the str was a 0-only string, which is invalid. Default back to .1
1946
+ ONE
1947
+ );
1948
+ }
1949
+ function asPos(str) {
1950
+ return isPos(str) ? str : convertToPos(str);
1951
+ }
1952
+ function crdtAsLiveNode(value) {
1953
+ return value;
1954
+ }
1955
+ function HasParent(node, key, pos = asPos(key)) {
1956
+ return Object.freeze({ type: "HasParent", node, key, pos });
1957
+ }
1958
+ var NoParent = Object.freeze({ type: "NoParent" });
1959
+ function Orphaned(oldKey, oldPos = asPos(oldKey)) {
1960
+ return Object.freeze({ type: "Orphaned", oldKey, oldPos });
1961
+ }
1962
+ var AbstractCrdt = class {
1963
+ // ^^^^^^^^^^^^ TODO: Make this an interface
1964
+ #pool;
1965
+ #id;
1966
+ #parent = NoParent;
1967
+ /** @internal */
1968
+ _getParentKeyOrThrow() {
1969
+ switch (this.parent.type) {
1970
+ case "HasParent":
1971
+ return this.parent.key;
1972
+ case "NoParent":
1973
+ throw new Error("Parent key is missing");
1974
+ case "Orphaned":
1975
+ return this.parent.oldKey;
1976
+ default:
1977
+ return assertNever(this.parent, "Unknown state");
1978
+ }
1979
+ }
1980
+ /** @internal */
1981
+ get _parentPos() {
1982
+ switch (this.parent.type) {
1983
+ case "HasParent":
1984
+ return this.parent.pos;
1985
+ case "NoParent":
1986
+ throw new Error("Parent key is missing");
1987
+ case "Orphaned":
1988
+ return this.parent.oldPos;
1989
+ default:
1990
+ return assertNever(this.parent, "Unknown state");
1991
+ }
1992
+ }
1993
+ /** @internal */
1994
+ get _pool() {
1995
+ return this.#pool;
1996
+ }
1997
+ get roomId() {
1998
+ return this.#pool ? this.#pool.roomId : null;
1999
+ }
2000
+ /** @internal */
2001
+ get _id() {
2002
+ return this.#id;
2003
+ }
2004
+ /** @internal */
2005
+ get parent() {
2006
+ return this.#parent;
2007
+ }
2008
+ /** @internal */
2009
+ get _parentKey() {
2010
+ switch (this.parent.type) {
2011
+ case "HasParent":
2012
+ return this.parent.key;
2013
+ case "NoParent":
2014
+ return null;
2015
+ case "Orphaned":
2016
+ return this.parent.oldKey;
2017
+ default:
2018
+ return assertNever(this.parent, "Unknown state");
2019
+ }
2020
+ }
2021
+ /** @internal */
2022
+ _apply(op, _isLocal) {
2023
+ switch (op.type) {
2024
+ case 5: {
2025
+ if (this.parent.type === "HasParent") {
2026
+ return this.parent.node._detachChild(crdtAsLiveNode(this));
2027
+ }
2028
+ return { modified: false };
2029
+ }
2030
+ }
2031
+ return { modified: false };
2032
+ }
2033
+ /** @internal */
2034
+ _setParentLink(newParentNode, newParentKey) {
2035
+ switch (this.parent.type) {
2036
+ case "HasParent":
2037
+ if (this.parent.node !== newParentNode) {
2038
+ throw new Error("Cannot set parent: node already has a parent");
2039
+ } else {
2040
+ this.#parent = HasParent(newParentNode, newParentKey);
2041
+ return;
2042
+ }
2043
+ case "Orphaned":
2044
+ case "NoParent": {
2045
+ this.#parent = HasParent(newParentNode, newParentKey);
2046
+ return;
2047
+ }
2048
+ default:
2049
+ return assertNever(this.parent, "Unknown state");
2050
+ }
2051
+ }
2052
+ /** @internal */
2053
+ _attach(id, pool) {
2054
+ if (this.#id || this.#pool) {
2055
+ throw new Error("Cannot attach node: already attached");
2056
+ }
2057
+ pool.addNode(id, crdtAsLiveNode(this));
2058
+ this.#id = id;
2059
+ this.#pool = pool;
2060
+ }
2061
+ /** @internal */
2062
+ _detach() {
2063
+ if (this.#pool && this.#id) {
2064
+ this.#pool.deleteNode(this.#id);
2065
+ }
2066
+ switch (this.parent.type) {
2067
+ case "HasParent": {
2068
+ this.#parent = Orphaned(this.parent.key, this.parent.pos);
2069
+ break;
2070
+ }
2071
+ case "NoParent": {
2072
+ this.#parent = NoParent;
2073
+ break;
2074
+ }
2075
+ case "Orphaned": {
2076
+ break;
2077
+ }
2078
+ default:
2079
+ assertNever(this.parent, "Unknown state");
2080
+ }
2081
+ this.#pool = void 0;
2082
+ }
2083
+ /** This caches the result of the last .toImmutable() call for this Live node. */
2084
+ #cachedImmutable;
2085
+ #cachedTreeNodeKey;
2086
+ /** This caches the result of the last .toTreeNode() call for this Live node. */
2087
+ #cachedTreeNode;
2088
+ /**
2089
+ * @internal
2090
+ *
2091
+ * Clear the Immutable cache, so that the next call to `.toImmutable()` will
2092
+ * recompute the equivalent Immutable value again. Call this after every
2093
+ * mutation to the Live node.
2094
+ */
2095
+ invalidate() {
2096
+ if (this.#cachedImmutable !== void 0 || this.#cachedTreeNode !== void 0) {
2097
+ this.#cachedImmutable = void 0;
2098
+ this.#cachedTreeNode = void 0;
2099
+ if (this.parent.type === "HasParent") {
2100
+ this.parent.node.invalidate();
2101
+ }
2102
+ }
2103
+ }
2104
+ /**
2105
+ * @internal
2106
+ *
2107
+ * Return an snapshot of this Live tree for use in DevTools.
2108
+ */
2109
+ toTreeNode(key) {
2110
+ if (this.#cachedTreeNode === void 0 || this.#cachedTreeNodeKey !== key) {
2111
+ this.#cachedTreeNodeKey = key;
2112
+ this.#cachedTreeNode = this._toTreeNode(key);
2113
+ }
2114
+ return this.#cachedTreeNode;
2115
+ }
2116
+ /**
2117
+ * Return an immutable snapshot of this Live node and its children.
2118
+ */
2119
+ toImmutable() {
2120
+ if (this.#cachedImmutable === void 0) {
2121
+ this.#cachedImmutable = this._toImmutable();
2122
+ }
2123
+ return this.#cachedImmutable;
2124
+ }
2125
+ };
2126
+ function isRootCrdt(crdt) {
2127
+ return crdt.type === 0 && !isChildCrdt(crdt);
2128
+ }
2129
+ function isChildCrdt(crdt) {
2130
+ return crdt.parentId !== void 0 && crdt.parentKey !== void 0;
2131
+ }
2132
+ var LiveRegister = class _LiveRegister extends AbstractCrdt {
2133
+ #data;
2134
+ constructor(data) {
2135
+ super();
2136
+ this.#data = data;
2137
+ }
2138
+ get data() {
2139
+ return this.#data;
2140
+ }
2141
+ /** @internal */
2142
+ static _deserialize([id, item], _parentToChildren, pool) {
2143
+ const register = new _LiveRegister(item.data);
2144
+ register._attach(id, pool);
2145
+ return register;
2146
+ }
2147
+ /** @internal */
2148
+ _toOps(parentId, parentKey, pool) {
2149
+ if (this._id === void 0) {
2150
+ throw new Error(
2151
+ "Cannot serialize register if parentId or parentKey is undefined"
2152
+ );
2153
+ }
2154
+ return [
2155
+ {
2156
+ type: 8,
2157
+ opId: pool?.generateOpId(),
2158
+ id: this._id,
2159
+ parentId,
2160
+ parentKey,
2161
+ data: this.data
2162
+ }
2163
+ ];
2164
+ }
2165
+ /** @internal */
2166
+ _serialize() {
2167
+ if (this.parent.type !== "HasParent") {
2168
+ throw new Error("Cannot serialize LiveRegister if parent is missing");
2169
+ }
2170
+ return {
2171
+ type: 3,
2172
+ parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
2173
+ parentKey: this.parent.key,
2174
+ data: this.data
2175
+ };
2176
+ }
2177
+ /** @internal */
2178
+ _attachChild(_op) {
2179
+ throw new Error("Method not implemented.");
2180
+ }
2181
+ /** @internal */
2182
+ _detachChild(_crdt) {
2183
+ throw new Error("Method not implemented.");
2184
+ }
2185
+ /** @internal */
2186
+ _apply(op, isLocal) {
2187
+ return super._apply(op, isLocal);
2188
+ }
2189
+ /** @internal */
2190
+ _toTreeNode(key) {
2191
+ return {
2192
+ type: "Json",
2193
+ id: this._id ?? nanoid(),
2194
+ key,
2195
+ payload: this.#data
2196
+ };
2197
+ }
2198
+ /** @internal */
2199
+ _toImmutable() {
2200
+ return this.#data;
2201
+ }
2202
+ clone() {
2203
+ return deepClone(this.data);
2204
+ }
2205
+ };
2206
+ function compareNodePosition(itemA, itemB) {
2207
+ const posA = itemA._parentPos;
2208
+ const posB = itemB._parentPos;
2209
+ return posA === posB ? 0 : posA < posB ? -1 : 1;
2210
+ }
2211
+ var LiveList = class _LiveList extends AbstractCrdt {
2212
+ // TODO: Naive array at first, find a better data structure. Maybe an Order statistics tree?
2213
+ #items;
2214
+ #implicitlyDeletedItems;
2215
+ #unacknowledgedSets;
2216
+ constructor(items) {
2217
+ super();
2218
+ this.#items = [];
2219
+ this.#implicitlyDeletedItems = /* @__PURE__ */ new WeakSet();
2220
+ this.#unacknowledgedSets = /* @__PURE__ */ new Map();
2221
+ let position = void 0;
2222
+ for (const item of items) {
2223
+ const newPosition = makePosition(position);
2224
+ const node = lsonToLiveNode(item);
2225
+ node._setParentLink(this, newPosition);
2226
+ this.#items.push(node);
2227
+ position = newPosition;
2228
+ }
2229
+ }
2230
+ /** @internal */
2231
+ static _deserialize([id], parentToChildren, pool) {
2232
+ const list = new _LiveList([]);
2233
+ list._attach(id, pool);
2234
+ const children = parentToChildren.get(id);
2235
+ if (children === void 0) {
2236
+ return list;
2237
+ }
2238
+ for (const [id2, crdt] of children) {
2239
+ const child = deserialize([id2, crdt], parentToChildren, pool);
2240
+ child._setParentLink(list, crdt.parentKey);
2241
+ list._insertAndSort(child);
2242
+ }
2243
+ return list;
2244
+ }
2245
+ /**
2246
+ * @internal
2247
+ * This function assumes that the resulting ops will be sent to the server if they have an 'opId'
2248
+ * so we mutate _unacknowledgedSets to avoid potential flickering
2249
+ * https://github.com/liveblocks/liveblocks/pull/1177
2250
+ *
2251
+ * This is quite unintuitive and should disappear as soon as
2252
+ * we introduce an explicit LiveList.Set operation
2253
+ */
2254
+ _toOps(parentId, parentKey, pool) {
2255
+ if (this._id === void 0) {
2256
+ throw new Error("Cannot serialize item is not attached");
2257
+ }
2258
+ const ops = [];
2259
+ const op = {
2260
+ id: this._id,
2261
+ opId: pool?.generateOpId(),
2262
+ type: 2,
2263
+ parentId,
2264
+ parentKey
2265
+ };
2266
+ ops.push(op);
2267
+ for (const item of this.#items) {
2268
+ const parentKey2 = item._getParentKeyOrThrow();
2269
+ const childOps = HACK_addIntentAndDeletedIdToOperation(
2270
+ item._toOps(this._id, parentKey2, pool),
2271
+ void 0
2272
+ );
2273
+ const childOpId = childOps[0].opId;
2274
+ if (childOpId !== void 0) {
2275
+ this.#unacknowledgedSets.set(parentKey2, childOpId);
2276
+ }
2277
+ ops.push(...childOps);
2278
+ }
2279
+ return ops;
2280
+ }
2281
+ /**
2282
+ * @internal
2283
+ *
2284
+ * Adds a new item into the sorted list, in the correct position.
2285
+ */
2286
+ _insertAndSort(item) {
2287
+ this.#items.push(item);
2288
+ this._sortItems();
2289
+ }
2290
+ /** @internal */
2291
+ _sortItems() {
2292
+ this.#items.sort(compareNodePosition);
2293
+ this.invalidate();
2294
+ }
2295
+ /** @internal */
2296
+ _indexOfPosition(position) {
2297
+ return this.#items.findIndex(
2298
+ (item) => item._getParentKeyOrThrow() === position
2299
+ );
2300
+ }
2301
+ /** @internal */
2302
+ _attach(id, pool) {
2303
+ super._attach(id, pool);
2304
+ for (const item of this.#items) {
2305
+ item._attach(pool.generateId(), pool);
2306
+ }
2307
+ }
2308
+ /** @internal */
2309
+ _detach() {
2310
+ super._detach();
2311
+ for (const item of this.#items) {
2312
+ item._detach();
2313
+ }
2314
+ }
2315
+ #applySetRemote(op) {
2316
+ if (this._pool === void 0) {
2317
+ throw new Error("Can't attach child if managed pool is not present");
2318
+ }
2319
+ const { id, parentKey: key } = op;
2320
+ const child = creationOpToLiveNode(op);
2321
+ child._attach(id, this._pool);
2322
+ child._setParentLink(this, key);
2323
+ const deletedId = op.deletedId;
2324
+ const indexOfItemWithSamePosition = this._indexOfPosition(key);
2325
+ if (indexOfItemWithSamePosition !== -1) {
2326
+ const itemWithSamePosition = this.#items[indexOfItemWithSamePosition];
2327
+ if (itemWithSamePosition._id === deletedId) {
2328
+ itemWithSamePosition._detach();
2329
+ this.#items[indexOfItemWithSamePosition] = child;
2330
+ return {
2331
+ modified: makeUpdate(this, [
2332
+ setDelta(indexOfItemWithSamePosition, child)
2333
+ ]),
2334
+ reverse: []
2335
+ };
2336
+ } else {
2337
+ this.#implicitlyDeletedItems.add(itemWithSamePosition);
2338
+ this.#items[indexOfItemWithSamePosition] = child;
2339
+ const delta = [
2340
+ setDelta(indexOfItemWithSamePosition, child)
2341
+ ];
2342
+ const deleteDelta2 = this.#detachItemAssociatedToSetOperation(
2343
+ op.deletedId
2344
+ );
2345
+ if (deleteDelta2) {
2346
+ delta.push(deleteDelta2);
2347
+ }
2348
+ return {
2349
+ modified: makeUpdate(this, delta),
2350
+ reverse: []
2351
+ };
2352
+ }
2353
+ } else {
2354
+ const updates = [];
2355
+ const deleteDelta2 = this.#detachItemAssociatedToSetOperation(
2356
+ op.deletedId
2357
+ );
2358
+ if (deleteDelta2) {
2359
+ updates.push(deleteDelta2);
2360
+ }
2361
+ this._insertAndSort(child);
2362
+ updates.push(insertDelta(this._indexOfPosition(key), child));
2363
+ return {
2364
+ reverse: [],
2365
+ modified: makeUpdate(this, updates)
2366
+ };
2367
+ }
2368
+ }
2369
+ #applySetAck(op) {
2370
+ if (this._pool === void 0) {
2371
+ throw new Error("Can't attach child if managed pool is not present");
2372
+ }
2373
+ const delta = [];
2374
+ const deletedDelta = this.#detachItemAssociatedToSetOperation(op.deletedId);
2375
+ if (deletedDelta) {
2376
+ delta.push(deletedDelta);
2377
+ }
2378
+ const unacknowledgedOpId = this.#unacknowledgedSets.get(op.parentKey);
2379
+ if (unacknowledgedOpId !== void 0) {
2380
+ if (unacknowledgedOpId !== op.opId) {
2381
+ return delta.length === 0 ? { modified: false } : { modified: makeUpdate(this, delta), reverse: [] };
2382
+ } else {
2383
+ this.#unacknowledgedSets.delete(op.parentKey);
2384
+ }
2385
+ }
2386
+ const indexOfItemWithSamePosition = this._indexOfPosition(op.parentKey);
2387
+ const existingItem = this.#items.find((item) => item._id === op.id);
2388
+ if (existingItem !== void 0) {
2389
+ if (existingItem._parentKey === op.parentKey) {
2390
+ return {
2391
+ modified: delta.length > 0 ? makeUpdate(this, delta) : false,
2392
+ reverse: []
2393
+ };
2394
+ }
2395
+ if (indexOfItemWithSamePosition !== -1) {
2396
+ this.#implicitlyDeletedItems.add(
2397
+ this.#items[indexOfItemWithSamePosition]
2398
+ );
2399
+ const [prevNode] = this.#items.splice(indexOfItemWithSamePosition, 1);
2400
+ delta.push(deleteDelta(indexOfItemWithSamePosition, prevNode));
2401
+ }
2402
+ const prevIndex = this.#items.indexOf(existingItem);
2403
+ existingItem._setParentLink(this, op.parentKey);
2404
+ this._sortItems();
2405
+ const newIndex = this.#items.indexOf(existingItem);
2406
+ if (newIndex !== prevIndex) {
2407
+ delta.push(moveDelta(prevIndex, newIndex, existingItem));
2408
+ }
2409
+ return {
2410
+ modified: delta.length > 0 ? makeUpdate(this, delta) : false,
2411
+ reverse: []
2412
+ };
2413
+ } else {
2414
+ const orphan = this._pool.getNode(op.id);
2415
+ if (orphan && this.#implicitlyDeletedItems.has(orphan)) {
2416
+ orphan._setParentLink(this, op.parentKey);
2417
+ this.#implicitlyDeletedItems.delete(orphan);
2418
+ this._insertAndSort(orphan);
2419
+ const recreatedItemIndex = this.#items.indexOf(orphan);
2420
+ return {
2421
+ modified: makeUpdate(this, [
2422
+ // If there is an item at this position, update is a set, else it's an insert
2423
+ indexOfItemWithSamePosition === -1 ? insertDelta(recreatedItemIndex, orphan) : setDelta(recreatedItemIndex, orphan),
2424
+ ...delta
2425
+ ]),
2426
+ reverse: []
2427
+ };
2428
+ } else {
2429
+ if (indexOfItemWithSamePosition !== -1) {
2430
+ this.#items.splice(indexOfItemWithSamePosition, 1);
2431
+ }
2432
+ const { newItem, newIndex } = this.#createAttachItemAndSort(
2433
+ op,
2434
+ op.parentKey
2435
+ );
2436
+ return {
2437
+ modified: makeUpdate(this, [
2438
+ // If there is an item at this position, update is a set, else it's an insert
2439
+ indexOfItemWithSamePosition === -1 ? insertDelta(newIndex, newItem) : setDelta(newIndex, newItem),
2440
+ ...delta
2441
+ ]),
2442
+ reverse: []
2443
+ };
2444
+ }
2445
+ }
2446
+ }
2447
+ /**
2448
+ * Returns the update delta of the deletion or null
2449
+ */
2450
+ #detachItemAssociatedToSetOperation(deletedId) {
2451
+ if (deletedId === void 0 || this._pool === void 0) {
2452
+ return null;
2453
+ }
2454
+ const deletedItem = this._pool.getNode(deletedId);
2455
+ if (deletedItem === void 0) {
2456
+ return null;
2457
+ }
2458
+ const result = this._detachChild(deletedItem);
2459
+ if (result.modified === false) {
2460
+ return null;
2461
+ }
2462
+ return result.modified.updates[0];
2463
+ }
2464
+ #applyRemoteInsert(op) {
2465
+ if (this._pool === void 0) {
2466
+ throw new Error("Can't attach child if managed pool is not present");
2467
+ }
2468
+ const key = asPos(op.parentKey);
2469
+ const existingItemIndex = this._indexOfPosition(key);
2470
+ if (existingItemIndex !== -1) {
2471
+ this.#shiftItemPosition(existingItemIndex, key);
2472
+ }
2473
+ const { newItem, newIndex } = this.#createAttachItemAndSort(op, key);
2474
+ return {
2475
+ modified: makeUpdate(this, [insertDelta(newIndex, newItem)]),
2476
+ reverse: []
2477
+ };
2478
+ }
2479
+ #applyInsertAck(op) {
2480
+ const existingItem = this.#items.find((item) => item._id === op.id);
2481
+ const key = asPos(op.parentKey);
2482
+ const itemIndexAtPosition = this._indexOfPosition(key);
2483
+ if (existingItem) {
2484
+ if (existingItem._parentKey === key) {
2485
+ return {
2486
+ modified: false
2487
+ };
2488
+ } else {
2489
+ const oldPositionIndex = this.#items.indexOf(existingItem);
2490
+ if (itemIndexAtPosition !== -1) {
2491
+ this.#shiftItemPosition(itemIndexAtPosition, key);
2492
+ }
2493
+ existingItem._setParentLink(this, key);
2494
+ this._sortItems();
2495
+ const newIndex = this._indexOfPosition(key);
2496
+ if (newIndex === oldPositionIndex) {
2497
+ return { modified: false };
2498
+ }
2499
+ return {
2500
+ modified: makeUpdate(this, [
2501
+ moveDelta(oldPositionIndex, newIndex, existingItem)
2502
+ ]),
2503
+ reverse: []
2504
+ };
2505
+ }
2506
+ } else {
2507
+ const orphan = nn(this._pool).getNode(op.id);
2508
+ if (orphan && this.#implicitlyDeletedItems.has(orphan)) {
2509
+ orphan._setParentLink(this, key);
2510
+ this.#implicitlyDeletedItems.delete(orphan);
2511
+ this._insertAndSort(orphan);
2512
+ const newIndex = this._indexOfPosition(key);
2513
+ return {
2514
+ modified: makeUpdate(this, [insertDelta(newIndex, orphan)]),
2515
+ reverse: []
2516
+ };
2517
+ } else {
2518
+ if (itemIndexAtPosition !== -1) {
2519
+ this.#shiftItemPosition(itemIndexAtPosition, key);
2520
+ }
2521
+ const { newItem, newIndex } = this.#createAttachItemAndSort(op, key);
2522
+ return {
2523
+ modified: makeUpdate(this, [insertDelta(newIndex, newItem)]),
2524
+ reverse: []
2525
+ };
2526
+ }
2527
+ }
2528
+ }
2529
+ #applyInsertUndoRedo(op) {
2530
+ const { id, parentKey: key } = op;
2531
+ const child = creationOpToLiveNode(op);
2532
+ if (this._pool?.getNode(id) !== void 0) {
2533
+ return { modified: false };
2534
+ }
2535
+ child._attach(id, nn(this._pool));
2536
+ child._setParentLink(this, key);
2537
+ const existingItemIndex = this._indexOfPosition(key);
2538
+ let newKey = key;
2539
+ if (existingItemIndex !== -1) {
2540
+ const before2 = this.#items[existingItemIndex]?._parentPos;
2541
+ const after2 = this.#items[existingItemIndex + 1]?._parentPos;
2542
+ newKey = makePosition(before2, after2);
2543
+ child._setParentLink(this, newKey);
2544
+ }
2545
+ this._insertAndSort(child);
2546
+ const newIndex = this._indexOfPosition(newKey);
2547
+ return {
2548
+ modified: makeUpdate(this, [insertDelta(newIndex, child)]),
2549
+ reverse: [{ type: 5, id }]
2550
+ };
2551
+ }
2552
+ #applySetUndoRedo(op) {
2553
+ const { id, parentKey: key } = op;
2554
+ const child = creationOpToLiveNode(op);
2555
+ if (this._pool?.getNode(id) !== void 0) {
2556
+ return { modified: false };
2557
+ }
2558
+ this.#unacknowledgedSets.set(key, nn(op.opId));
2559
+ const indexOfItemWithSameKey = this._indexOfPosition(key);
2560
+ child._attach(id, nn(this._pool));
2561
+ child._setParentLink(this, key);
2562
+ const newKey = key;
2563
+ if (indexOfItemWithSameKey !== -1) {
2564
+ const existingItem = this.#items[indexOfItemWithSameKey];
2565
+ existingItem._detach();
2566
+ this.#items[indexOfItemWithSameKey] = child;
2567
+ const reverse = HACK_addIntentAndDeletedIdToOperation(
2568
+ existingItem._toOps(nn(this._id), key, this._pool),
2569
+ op.id
2570
+ );
2571
+ const delta = [setDelta(indexOfItemWithSameKey, child)];
2572
+ const deletedDelta = this.#detachItemAssociatedToSetOperation(
2573
+ op.deletedId
2574
+ );
2575
+ if (deletedDelta) {
2576
+ delta.push(deletedDelta);
2577
+ }
2578
+ return {
2579
+ modified: makeUpdate(this, delta),
2580
+ reverse
2581
+ };
2582
+ } else {
2583
+ this._insertAndSort(child);
2584
+ this.#detachItemAssociatedToSetOperation(op.deletedId);
2585
+ const newIndex = this._indexOfPosition(newKey);
2586
+ return {
2587
+ reverse: [{ type: 5, id }],
2588
+ modified: makeUpdate(this, [insertDelta(newIndex, child)])
2589
+ };
2590
+ }
2591
+ }
2592
+ /** @internal */
2593
+ _attachChild(op, source) {
2594
+ if (this._pool === void 0) {
2595
+ throw new Error("Can't attach child if managed pool is not present");
2596
+ }
2597
+ let result;
2598
+ if (op.intent === "set") {
2599
+ if (source === 1) {
2600
+ result = this.#applySetRemote(op);
2601
+ } else if (source === 2) {
2602
+ result = this.#applySetAck(op);
2603
+ } else {
2604
+ result = this.#applySetUndoRedo(op);
2605
+ }
2606
+ } else {
2607
+ if (source === 1) {
2608
+ result = this.#applyRemoteInsert(op);
2609
+ } else if (source === 2) {
2610
+ result = this.#applyInsertAck(op);
2611
+ } else {
2612
+ result = this.#applyInsertUndoRedo(op);
2613
+ }
2614
+ }
2615
+ if (result.modified !== false) {
2616
+ this.invalidate();
2617
+ }
2618
+ return result;
2619
+ }
2620
+ /** @internal */
2621
+ _detachChild(child) {
2622
+ if (child) {
2623
+ const parentKey = nn(child._parentKey);
2624
+ const reverse = child._toOps(nn(this._id), parentKey, this._pool);
2625
+ const indexToDelete = this.#items.indexOf(child);
2626
+ if (indexToDelete === -1) {
2627
+ return {
2628
+ modified: false
2629
+ };
2630
+ }
2631
+ const [previousNode] = this.#items.splice(indexToDelete, 1);
2632
+ this.invalidate();
2633
+ child._detach();
2634
+ return {
2635
+ modified: makeUpdate(this, [deleteDelta(indexToDelete, previousNode)]),
2636
+ reverse
2637
+ };
2638
+ }
2639
+ return { modified: false };
2640
+ }
2641
+ #applySetChildKeyRemote(newKey, child) {
2642
+ if (this.#implicitlyDeletedItems.has(child)) {
2643
+ this.#implicitlyDeletedItems.delete(child);
2644
+ child._setParentLink(this, newKey);
2645
+ this._insertAndSort(child);
2646
+ const newIndex = this.#items.indexOf(child);
2647
+ return {
2648
+ modified: makeUpdate(this, [insertDelta(newIndex, child)]),
2649
+ reverse: []
2650
+ };
2651
+ }
2652
+ const previousKey = child._parentKey;
2653
+ if (newKey === previousKey) {
2654
+ return {
2655
+ modified: false
2656
+ };
2657
+ }
2658
+ const existingItemIndex = this._indexOfPosition(newKey);
2659
+ if (existingItemIndex === -1) {
2660
+ const previousIndex = this.#items.indexOf(child);
2661
+ child._setParentLink(this, newKey);
2662
+ this._sortItems();
2663
+ const newIndex = this.#items.indexOf(child);
2664
+ if (newIndex === previousIndex) {
2665
+ return {
2666
+ modified: false
2667
+ };
2668
+ }
2669
+ return {
2670
+ modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
2671
+ reverse: []
2672
+ };
2673
+ } else {
2674
+ this.#items[existingItemIndex]._setParentLink(
2675
+ this,
2676
+ makePosition(newKey, this.#items[existingItemIndex + 1]?._parentPos)
2677
+ );
2678
+ const previousIndex = this.#items.indexOf(child);
2679
+ child._setParentLink(this, newKey);
2680
+ this._sortItems();
2681
+ const newIndex = this.#items.indexOf(child);
2682
+ if (newIndex === previousIndex) {
2683
+ return {
2684
+ modified: false
2685
+ };
2686
+ }
2687
+ return {
2688
+ modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
2689
+ reverse: []
2690
+ };
2691
+ }
2692
+ }
2693
+ #applySetChildKeyAck(newKey, child) {
2694
+ const previousKey = nn(child._parentKey);
2695
+ if (this.#implicitlyDeletedItems.has(child)) {
2696
+ const existingItemIndex = this._indexOfPosition(newKey);
2697
+ this.#implicitlyDeletedItems.delete(child);
2698
+ if (existingItemIndex !== -1) {
2699
+ this.#items[existingItemIndex]._setParentLink(
2700
+ this,
2701
+ makePosition(newKey, this.#items[existingItemIndex + 1]?._parentPos)
2702
+ );
2703
+ }
2704
+ child._setParentLink(this, newKey);
2705
+ this._insertAndSort(child);
2706
+ return {
2707
+ modified: false
2708
+ };
2709
+ } else {
2710
+ if (newKey === previousKey) {
2711
+ return {
2712
+ modified: false
2713
+ };
2714
+ }
2715
+ const previousIndex = this.#items.indexOf(child);
2716
+ const existingItemIndex = this._indexOfPosition(newKey);
2717
+ if (existingItemIndex !== -1) {
2718
+ this.#items[existingItemIndex]._setParentLink(
2719
+ this,
2720
+ makePosition(newKey, this.#items[existingItemIndex + 1]?._parentPos)
2721
+ );
2722
+ }
2723
+ child._setParentLink(this, newKey);
2724
+ this._sortItems();
2725
+ const newIndex = this.#items.indexOf(child);
2726
+ if (previousIndex === newIndex) {
2727
+ return {
2728
+ modified: false
2729
+ };
2730
+ } else {
2731
+ return {
2732
+ modified: makeUpdate(this, [
2733
+ moveDelta(previousIndex, newIndex, child)
2734
+ ]),
2735
+ reverse: []
2736
+ };
2737
+ }
2738
+ }
2739
+ }
2740
+ #applySetChildKeyUndoRedo(newKey, child) {
2741
+ const previousKey = nn(child._parentKey);
2742
+ const previousIndex = this.#items.indexOf(child);
2743
+ const existingItemIndex = this._indexOfPosition(newKey);
2744
+ let actualNewKey = newKey;
2745
+ if (existingItemIndex !== -1) {
2746
+ actualNewKey = makePosition(
2747
+ newKey,
2748
+ this.#items[existingItemIndex + 1]?._parentPos
2749
+ );
2750
+ }
2751
+ child._setParentLink(this, actualNewKey);
2752
+ this._sortItems();
2753
+ const newIndex = this.#items.indexOf(child);
2754
+ if (previousIndex === newIndex) {
2755
+ return {
2756
+ modified: false
2757
+ };
2758
+ }
2759
+ return {
2760
+ modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
2761
+ reverse: [
2762
+ {
2763
+ type: 1,
2764
+ id: nn(child._id),
2765
+ parentKey: previousKey
2766
+ }
2767
+ ]
2768
+ };
2769
+ }
2770
+ /** @internal */
2771
+ _setChildKey(newKey, child, source) {
2772
+ if (source === 1) {
2773
+ return this.#applySetChildKeyRemote(newKey, child);
2774
+ } else if (source === 2) {
2775
+ return this.#applySetChildKeyAck(newKey, child);
2776
+ } else {
2777
+ return this.#applySetChildKeyUndoRedo(newKey, child);
2778
+ }
2779
+ }
2780
+ /** @internal */
2781
+ _apply(op, isLocal) {
2782
+ return super._apply(op, isLocal);
2783
+ }
2784
+ /** @internal */
2785
+ _serialize() {
2786
+ if (this.parent.type !== "HasParent") {
2787
+ throw new Error("Cannot serialize LiveList if parent is missing");
2788
+ }
2789
+ return {
2790
+ type: 1,
2791
+ parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
2792
+ parentKey: this.parent.key
2793
+ };
2794
+ }
2795
+ /**
2796
+ * Returns the number of elements.
2797
+ */
2798
+ get length() {
2799
+ return this.#items.length;
2800
+ }
2801
+ /**
2802
+ * Adds one element to the end of the LiveList.
2803
+ * @param element The element to add to the end of the LiveList.
2804
+ */
2805
+ push(element) {
2806
+ this._pool?.assertStorageIsWritable();
2807
+ return this.insert(element, this.length);
2808
+ }
2809
+ /**
2810
+ * Inserts one element at a specified index.
2811
+ * @param element The element to insert.
2812
+ * @param index The index at which you want to insert the element.
2813
+ */
2814
+ insert(element, index) {
2815
+ this._pool?.assertStorageIsWritable();
2816
+ if (index < 0 || index > this.#items.length) {
2817
+ throw new Error(
2818
+ `Cannot insert list item at index "${index}". index should be between 0 and ${this.#items.length}`
2819
+ );
2820
+ }
2821
+ const before2 = this.#items[index - 1] ? this.#items[index - 1]._parentPos : void 0;
2822
+ const after2 = this.#items[index] ? this.#items[index]._parentPos : void 0;
2823
+ const position = makePosition(before2, after2);
2824
+ const value = lsonToLiveNode(element);
2825
+ value._setParentLink(this, position);
2826
+ this._insertAndSort(value);
2827
+ if (this._pool && this._id) {
2828
+ const id = this._pool.generateId();
2829
+ value._attach(id, this._pool);
2830
+ this._pool.dispatch(
2831
+ value._toOps(this._id, position, this._pool),
2832
+ [{ type: 5, id }],
2833
+ /* @__PURE__ */ new Map([
2834
+ [this._id, makeUpdate(this, [insertDelta(index, value)])]
2835
+ ])
2836
+ );
2837
+ }
2838
+ }
2839
+ /**
2840
+ * Move one element from one index to another.
2841
+ * @param index The index of the element to move
2842
+ * @param targetIndex The index where the element should be after moving.
2843
+ */
2844
+ move(index, targetIndex) {
2845
+ this._pool?.assertStorageIsWritable();
2846
+ if (targetIndex < 0) {
2847
+ throw new Error("targetIndex cannot be less than 0");
2848
+ }
2849
+ if (targetIndex >= this.#items.length) {
2850
+ throw new Error(
2851
+ "targetIndex cannot be greater or equal than the list length"
2852
+ );
2853
+ }
2854
+ if (index < 0) {
2855
+ throw new Error("index cannot be less than 0");
2856
+ }
2857
+ if (index >= this.#items.length) {
2858
+ throw new Error("index cannot be greater or equal than the list length");
2859
+ }
2860
+ let beforePosition = null;
2861
+ let afterPosition = null;
2862
+ if (index < targetIndex) {
2863
+ afterPosition = targetIndex === this.#items.length - 1 ? void 0 : this.#items[targetIndex + 1]._parentPos;
2864
+ beforePosition = this.#items[targetIndex]._parentPos;
2865
+ } else {
2866
+ afterPosition = this.#items[targetIndex]._parentPos;
2867
+ beforePosition = targetIndex === 0 ? void 0 : this.#items[targetIndex - 1]._parentPos;
2868
+ }
2869
+ const position = makePosition(beforePosition, afterPosition);
2870
+ const item = this.#items[index];
2871
+ const previousPosition = item._getParentKeyOrThrow();
2872
+ item._setParentLink(this, position);
2873
+ this._sortItems();
2874
+ if (this._pool && this._id) {
2875
+ const storageUpdates = /* @__PURE__ */ new Map([
2876
+ [this._id, makeUpdate(this, [moveDelta(index, targetIndex, item)])]
2877
+ ]);
2878
+ this._pool.dispatch(
2879
+ [
2880
+ {
2881
+ type: 1,
2882
+ id: nn(item._id),
2883
+ opId: this._pool.generateOpId(),
2884
+ parentKey: position
2885
+ }
2886
+ ],
2887
+ [
2888
+ {
2889
+ type: 1,
2890
+ id: nn(item._id),
2891
+ parentKey: previousPosition
2892
+ }
2893
+ ],
2894
+ storageUpdates
2895
+ );
2896
+ }
2897
+ }
2898
+ /**
2899
+ * Deletes an element at the specified index
2900
+ * @param index The index of the element to delete
2901
+ */
2902
+ delete(index) {
2903
+ this._pool?.assertStorageIsWritable();
2904
+ if (index < 0 || index >= this.#items.length) {
2905
+ throw new Error(
2906
+ `Cannot delete list item at index "${index}". index should be between 0 and ${this.#items.length - 1}`
2907
+ );
2908
+ }
2909
+ const item = this.#items[index];
2910
+ item._detach();
2911
+ const [prev] = this.#items.splice(index, 1);
2912
+ this.invalidate();
2913
+ if (this._pool) {
2914
+ const childRecordId = item._id;
2915
+ if (childRecordId) {
2916
+ const storageUpdates = /* @__PURE__ */ new Map();
2917
+ storageUpdates.set(
2918
+ nn(this._id),
2919
+ makeUpdate(this, [deleteDelta(index, prev)])
2920
+ );
2921
+ this._pool.dispatch(
2922
+ [
2923
+ {
2924
+ id: childRecordId,
2925
+ opId: this._pool.generateOpId(),
2926
+ type: 5
2927
+ /* DELETE_CRDT */
2928
+ }
2929
+ ],
2930
+ item._toOps(nn(this._id), item._getParentKeyOrThrow()),
2931
+ storageUpdates
2932
+ );
2933
+ }
2934
+ }
2935
+ }
2936
+ clear() {
2937
+ this._pool?.assertStorageIsWritable();
2938
+ if (this._pool) {
2939
+ const ops = [];
2940
+ const reverseOps = [];
2941
+ const updateDelta = [];
2942
+ for (const item of this.#items) {
2943
+ item._detach();
2944
+ const childId = item._id;
2945
+ if (childId) {
2946
+ ops.push({
2947
+ type: 5,
2948
+ id: childId,
2949
+ opId: this._pool.generateOpId()
2950
+ });
2951
+ reverseOps.push(
2952
+ ...item._toOps(nn(this._id), item._getParentKeyOrThrow())
2953
+ );
2954
+ updateDelta.push(deleteDelta(0, item));
2955
+ }
2956
+ }
2957
+ this.#items = [];
2958
+ this.invalidate();
2959
+ const storageUpdates = /* @__PURE__ */ new Map();
2960
+ storageUpdates.set(nn(this._id), makeUpdate(this, updateDelta));
2961
+ this._pool.dispatch(ops, reverseOps, storageUpdates);
2962
+ } else {
2963
+ for (const item of this.#items) {
2964
+ item._detach();
2965
+ }
2966
+ this.#items = [];
2967
+ this.invalidate();
2968
+ }
2969
+ }
2970
+ set(index, item) {
2971
+ this._pool?.assertStorageIsWritable();
2972
+ if (index < 0 || index >= this.#items.length) {
2973
+ throw new Error(
2974
+ `Cannot set list item at index "${index}". index should be between 0 and ${this.#items.length - 1}`
2975
+ );
2976
+ }
2977
+ const existingItem = this.#items[index];
2978
+ const position = existingItem._getParentKeyOrThrow();
2979
+ const existingId = existingItem._id;
2980
+ existingItem._detach();
2981
+ const value = lsonToLiveNode(item);
2982
+ value._setParentLink(this, position);
2983
+ this.#items[index] = value;
2984
+ this.invalidate();
2985
+ if (this._pool && this._id) {
2986
+ const id = this._pool.generateId();
2987
+ value._attach(id, this._pool);
2988
+ const storageUpdates = /* @__PURE__ */ new Map();
2989
+ storageUpdates.set(this._id, makeUpdate(this, [setDelta(index, value)]));
2990
+ const ops = HACK_addIntentAndDeletedIdToOperation(
2991
+ value._toOps(this._id, position, this._pool),
2992
+ existingId
2993
+ );
2994
+ this.#unacknowledgedSets.set(position, nn(ops[0].opId));
2995
+ const reverseOps = HACK_addIntentAndDeletedIdToOperation(
2996
+ existingItem._toOps(this._id, position, void 0),
2997
+ id
2998
+ );
2999
+ this._pool.dispatch(ops, reverseOps, storageUpdates);
3000
+ }
3001
+ }
3002
+ /**
3003
+ * Returns an Array of all the elements in the LiveList.
3004
+ */
3005
+ toArray() {
3006
+ return this.#items.map(
3007
+ (entry) => liveNodeToLson(entry)
3008
+ // ^^^^^^^^
3009
+ // FIXME! This isn't safe.
3010
+ );
3011
+ }
3012
+ /**
3013
+ * Tests whether all elements pass the test implemented by the provided function.
3014
+ * @param predicate Function to test for each element, taking two arguments (the element and its index).
3015
+ * @returns true if the predicate function returns a truthy value for every element. Otherwise, false.
3016
+ */
3017
+ every(predicate) {
3018
+ return this.toArray().every(predicate);
3019
+ }
3020
+ /**
3021
+ * Creates an array with all elements that pass the test implemented by the provided function.
3022
+ * @param predicate Function to test each element of the LiveList. Return a value that coerces to true to keep the element, or to false otherwise.
3023
+ * @returns An array with the elements that pass the test.
3024
+ */
3025
+ filter(predicate) {
3026
+ return this.toArray().filter(predicate);
3027
+ }
3028
+ /**
3029
+ * Returns the first element that satisfies the provided testing function.
3030
+ * @param predicate Function to execute on each value.
3031
+ * @returns The value of the first element in the LiveList that satisfies the provided testing function. Otherwise, undefined is returned.
3032
+ */
3033
+ find(predicate) {
3034
+ return this.toArray().find(predicate);
3035
+ }
3036
+ /**
3037
+ * Returns the index of the first element in the LiveList that satisfies the provided testing function.
3038
+ * @param predicate Function to execute on each value until the function returns true, indicating that the satisfying element was found.
3039
+ * @returns The index of the first element in the LiveList that passes the test. Otherwise, -1.
3040
+ */
3041
+ findIndex(predicate) {
3042
+ return this.toArray().findIndex(predicate);
3043
+ }
3044
+ /**
3045
+ * Executes a provided function once for each element.
3046
+ * @param callbackfn Function to execute on each element.
3047
+ */
3048
+ forEach(callbackfn) {
3049
+ return this.toArray().forEach(callbackfn);
3050
+ }
3051
+ /**
3052
+ * Get the element at the specified index.
3053
+ * @param index The index on the element to get.
3054
+ * @returns The element at the specified index or undefined.
3055
+ */
3056
+ get(index) {
3057
+ if (index < 0 || index >= this.#items.length) {
3058
+ return void 0;
3059
+ }
3060
+ return liveNodeToLson(this.#items[index]);
3061
+ }
3062
+ /**
3063
+ * Returns the first index at which a given element can be found in the LiveList, or -1 if it is not present.
3064
+ * @param searchElement Element to locate.
3065
+ * @param fromIndex The index to start the search at.
3066
+ * @returns The first index of the element in the LiveList; -1 if not found.
3067
+ */
3068
+ indexOf(searchElement, fromIndex) {
3069
+ return this.toArray().indexOf(searchElement, fromIndex);
3070
+ }
3071
+ /**
3072
+ * Returns the last index at which a given element can be found in the LiveList, or -1 if it is not present. The LiveLsit is searched backwards, starting at fromIndex.
3073
+ * @param searchElement Element to locate.
3074
+ * @param fromIndex The index at which to start searching backwards.
3075
+ * @returns
3076
+ */
3077
+ lastIndexOf(searchElement, fromIndex) {
3078
+ return this.toArray().lastIndexOf(searchElement, fromIndex);
3079
+ }
3080
+ /**
3081
+ * Creates an array populated with the results of calling a provided function on every element.
3082
+ * @param callback Function that is called for every element.
3083
+ * @returns An array with each element being the result of the callback function.
3084
+ */
3085
+ map(callback) {
3086
+ return this.#items.map(
3087
+ (entry, i) => callback(
3088
+ liveNodeToLson(entry),
3089
+ // ^^^^^^^^
3090
+ // FIXME! This isn't safe.
3091
+ i
3092
+ )
3093
+ );
3094
+ }
3095
+ /**
3096
+ * Tests whether at least one element in the LiveList passes the test implemented by the provided function.
3097
+ * @param predicate Function to test for each element.
3098
+ * @returns true if the callback function returns a truthy value for at least one element. Otherwise, false.
3099
+ */
3100
+ some(predicate) {
3101
+ return this.toArray().some(predicate);
3102
+ }
3103
+ [Symbol.iterator]() {
3104
+ return new LiveListIterator(this.#items);
3105
+ }
3106
+ #createAttachItemAndSort(op, key) {
3107
+ const newItem = creationOpToLiveNode(op);
3108
+ newItem._attach(op.id, nn(this._pool));
3109
+ newItem._setParentLink(this, key);
3110
+ this._insertAndSort(newItem);
3111
+ const newIndex = this._indexOfPosition(key);
3112
+ return { newItem, newIndex };
3113
+ }
3114
+ #shiftItemPosition(index, key) {
3115
+ const shiftedPosition = makePosition(
3116
+ key,
3117
+ this.#items.length > index + 1 ? this.#items[index + 1]?._parentPos : void 0
3118
+ );
3119
+ this.#items[index]._setParentLink(this, shiftedPosition);
3120
+ }
3121
+ /** @internal */
3122
+ _toTreeNode(key) {
3123
+ return {
3124
+ type: "LiveList",
3125
+ id: this._id ?? nanoid(),
3126
+ key,
3127
+ payload: this.#items.map(
3128
+ (item, index) => item.toTreeNode(index.toString())
3129
+ )
3130
+ };
3131
+ }
3132
+ toImmutable() {
3133
+ return super.toImmutable();
3134
+ }
3135
+ /** @internal */
3136
+ _toImmutable() {
3137
+ const result = this.#items.map((node) => node.toImmutable());
3138
+ return process.env.NODE_ENV === "production" ? result : Object.freeze(result);
3139
+ }
3140
+ clone() {
3141
+ return new _LiveList(this.#items.map((item) => item.clone()));
3142
+ }
3143
+ };
3144
+ var LiveListIterator = class {
3145
+ #innerIterator;
3146
+ constructor(items) {
3147
+ this.#innerIterator = items[Symbol.iterator]();
3148
+ }
3149
+ [Symbol.iterator]() {
3150
+ return this;
3151
+ }
3152
+ next() {
3153
+ const result = this.#innerIterator.next();
3154
+ if (result.done) {
3155
+ return {
3156
+ done: true,
3157
+ value: void 0
3158
+ };
3159
+ }
3160
+ const value = liveNodeToLson(result.value);
3161
+ return { value };
3162
+ }
3163
+ };
3164
+ function makeUpdate(liveList, deltaUpdates) {
3165
+ return {
3166
+ node: liveList,
3167
+ type: "LiveList",
3168
+ updates: deltaUpdates
3169
+ };
3170
+ }
3171
+ function setDelta(index, item) {
3172
+ return {
3173
+ index,
3174
+ type: "set",
3175
+ item: item instanceof LiveRegister ? item.data : item
3176
+ };
3177
+ }
3178
+ function deleteDelta(index, deletedNode) {
3179
+ return {
3180
+ type: "delete",
3181
+ index,
3182
+ deletedItem: deletedNode instanceof LiveRegister ? deletedNode.data : deletedNode
3183
+ };
3184
+ }
3185
+ function insertDelta(index, item) {
3186
+ return {
3187
+ index,
3188
+ type: "insert",
3189
+ item: item instanceof LiveRegister ? item.data : item
3190
+ };
3191
+ }
3192
+ function moveDelta(previousIndex, index, item) {
3193
+ return {
3194
+ type: "move",
3195
+ index,
3196
+ item: item instanceof LiveRegister ? item.data : item,
3197
+ previousIndex
3198
+ };
3199
+ }
3200
+ function HACK_addIntentAndDeletedIdToOperation(ops, deletedId) {
3201
+ return ops.map((op, index) => {
3202
+ if (index === 0) {
3203
+ const firstOp = op;
3204
+ return {
3205
+ ...firstOp,
3206
+ intent: "set",
3207
+ deletedId
3208
+ };
3209
+ } else {
3210
+ return op;
3211
+ }
3212
+ });
3213
+ }
3214
+ var LiveMap = class _LiveMap extends AbstractCrdt {
3215
+ #map;
3216
+ #unacknowledgedSet;
3217
+ constructor(entries2) {
3218
+ super();
3219
+ this.#unacknowledgedSet = /* @__PURE__ */ new Map();
3220
+ if (entries2) {
3221
+ const mappedEntries = [];
3222
+ for (const [key, value] of entries2) {
3223
+ const node = lsonToLiveNode(value);
3224
+ node._setParentLink(this, key);
3225
+ mappedEntries.push([key, node]);
3226
+ }
3227
+ this.#map = new Map(mappedEntries);
3228
+ } else {
3229
+ this.#map = /* @__PURE__ */ new Map();
3230
+ }
3231
+ }
3232
+ /** @internal */
3233
+ _toOps(parentId, parentKey, pool) {
3234
+ if (this._id === void 0) {
3235
+ throw new Error("Cannot serialize item is not attached");
3236
+ }
3237
+ const ops = [];
3238
+ const op = {
3239
+ id: this._id,
3240
+ opId: pool?.generateOpId(),
3241
+ type: 7,
3242
+ parentId,
3243
+ parentKey
3244
+ };
3245
+ ops.push(op);
3246
+ for (const [key, value] of this.#map) {
3247
+ ops.push(...value._toOps(this._id, key, pool));
3248
+ }
3249
+ return ops;
3250
+ }
3251
+ /** @internal */
3252
+ static _deserialize([id, _item], parentToChildren, pool) {
3253
+ const map = new _LiveMap();
3254
+ map._attach(id, pool);
3255
+ const children = parentToChildren.get(id);
3256
+ if (children === void 0) {
3257
+ return map;
3258
+ }
3259
+ for (const [id2, crdt] of children) {
3260
+ const child = deserialize([id2, crdt], parentToChildren, pool);
3261
+ child._setParentLink(map, crdt.parentKey);
3262
+ map.#map.set(crdt.parentKey, child);
3263
+ map.invalidate();
3264
+ }
3265
+ return map;
3266
+ }
3267
+ /** @internal */
3268
+ _attach(id, pool) {
3269
+ super._attach(id, pool);
3270
+ for (const [_key, value] of this.#map) {
3271
+ if (isLiveNode(value)) {
3272
+ value._attach(pool.generateId(), pool);
3273
+ }
3274
+ }
3275
+ }
3276
+ /** @internal */
3277
+ _attachChild(op, source) {
3278
+ if (this._pool === void 0) {
3279
+ throw new Error("Can't attach child if managed pool is not present");
3280
+ }
3281
+ const { id, parentKey, opId } = op;
3282
+ const key = parentKey;
3283
+ const child = creationOpToLiveNode(op);
3284
+ if (this._pool.getNode(id) !== void 0) {
3285
+ return { modified: false };
3286
+ }
3287
+ if (source === 2) {
3288
+ const lastUpdateOpId = this.#unacknowledgedSet.get(key);
3289
+ if (lastUpdateOpId === opId) {
3290
+ this.#unacknowledgedSet.delete(key);
3291
+ return { modified: false };
3292
+ } else if (lastUpdateOpId !== void 0) {
3293
+ return { modified: false };
3294
+ }
3295
+ } else if (source === 1) {
3296
+ this.#unacknowledgedSet.delete(key);
3297
+ }
3298
+ const previousValue = this.#map.get(key);
3299
+ let reverse;
3300
+ if (previousValue) {
3301
+ const thisId = nn(this._id);
3302
+ reverse = previousValue._toOps(thisId, key);
3303
+ previousValue._detach();
3304
+ } else {
3305
+ reverse = [{ type: 5, id }];
3306
+ }
3307
+ child._setParentLink(this, key);
3308
+ child._attach(id, this._pool);
3309
+ this.#map.set(key, child);
3310
+ this.invalidate();
3311
+ return {
3312
+ modified: {
3313
+ node: this,
3314
+ type: "LiveMap",
3315
+ updates: { [key]: { type: "update" } }
3316
+ },
3317
+ reverse
3318
+ };
3319
+ }
3320
+ /** @internal */
3321
+ _detach() {
3322
+ super._detach();
3323
+ for (const item of this.#map.values()) {
3324
+ item._detach();
3325
+ }
3326
+ }
3327
+ /** @internal */
3328
+ _detachChild(child) {
3329
+ const id = nn(this._id);
3330
+ const parentKey = nn(child._parentKey);
3331
+ const reverse = child._toOps(id, parentKey, this._pool);
3332
+ for (const [key, value] of this.#map) {
3333
+ if (value === child) {
3334
+ this.#map.delete(key);
3335
+ this.invalidate();
3336
+ }
3337
+ }
3338
+ child._detach();
3339
+ const storageUpdate = {
3340
+ node: this,
3341
+ type: "LiveMap",
3342
+ updates: { [parentKey]: { type: "delete" } }
3343
+ };
3344
+ return { modified: storageUpdate, reverse };
3345
+ }
3346
+ /** @internal */
3347
+ _serialize() {
3348
+ if (this.parent.type !== "HasParent") {
3349
+ throw new Error("Cannot serialize LiveMap if parent is missing");
3350
+ }
3351
+ return {
3352
+ type: 2,
3353
+ parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
3354
+ parentKey: this.parent.key
3355
+ };
3356
+ }
3357
+ /**
3358
+ * Returns a specified element from the LiveMap.
3359
+ * @param key The key of the element to return.
3360
+ * @returns The element associated with the specified key, or undefined if the key can't be found in the LiveMap.
3361
+ */
3362
+ get(key) {
3363
+ const value = this.#map.get(key);
3364
+ if (value === void 0) {
3365
+ return void 0;
3366
+ }
3367
+ return liveNodeToLson(value);
3368
+ }
3369
+ /**
3370
+ * Adds or updates an element with a specified key and a value.
3371
+ * @param key The key of the element to add. Should be a string.
3372
+ * @param value The value of the element to add. Should be serializable to JSON.
3373
+ */
3374
+ set(key, value) {
3375
+ this._pool?.assertStorageIsWritable();
3376
+ const oldValue = this.#map.get(key);
3377
+ if (oldValue) {
3378
+ oldValue._detach();
3379
+ }
3380
+ const item = lsonToLiveNode(value);
3381
+ item._setParentLink(this, key);
3382
+ this.#map.set(key, item);
3383
+ this.invalidate();
3384
+ if (this._pool && this._id) {
3385
+ const id = this._pool.generateId();
3386
+ item._attach(id, this._pool);
3387
+ const storageUpdates = /* @__PURE__ */ new Map();
3388
+ storageUpdates.set(this._id, {
3389
+ node: this,
3390
+ type: "LiveMap",
3391
+ updates: { [key]: { type: "update" } }
3392
+ });
3393
+ const ops = item._toOps(this._id, key, this._pool);
3394
+ this.#unacknowledgedSet.set(key, nn(ops[0].opId));
3395
+ this._pool.dispatch(
3396
+ item._toOps(this._id, key, this._pool),
3397
+ oldValue ? oldValue._toOps(this._id, key) : [{ type: 5, id }],
3398
+ storageUpdates
3399
+ );
3400
+ }
3401
+ }
3402
+ /**
3403
+ * Returns the number of elements in the LiveMap.
3404
+ */
3405
+ get size() {
3406
+ return this.#map.size;
3407
+ }
3408
+ /**
3409
+ * Returns a boolean indicating whether an element with the specified key exists or not.
3410
+ * @param key The key of the element to test for presence.
3411
+ */
3412
+ has(key) {
3413
+ return this.#map.has(key);
3414
+ }
3415
+ /**
3416
+ * Removes the specified element by key.
3417
+ * @param key The key of the element to remove.
3418
+ * @returns true if an element existed and has been removed, or false if the element does not exist.
3419
+ */
3420
+ delete(key) {
3421
+ this._pool?.assertStorageIsWritable();
3422
+ const item = this.#map.get(key);
3423
+ if (item === void 0) {
3424
+ return false;
3425
+ }
3426
+ item._detach();
3427
+ this.#map.delete(key);
3428
+ this.invalidate();
3429
+ if (this._pool && item._id) {
3430
+ const thisId = nn(this._id);
3431
+ const storageUpdates = /* @__PURE__ */ new Map();
3432
+ storageUpdates.set(thisId, {
3433
+ node: this,
3434
+ type: "LiveMap",
3435
+ updates: { [key]: { type: "delete" } }
3436
+ });
3437
+ this._pool.dispatch(
3438
+ [
3439
+ {
3440
+ type: 5,
3441
+ id: item._id,
3442
+ opId: this._pool.generateOpId()
3443
+ }
3444
+ ],
3445
+ item._toOps(thisId, key),
3446
+ storageUpdates
3447
+ );
3448
+ }
3449
+ return true;
3450
+ }
3451
+ /**
3452
+ * Returns a new Iterator object that contains the [key, value] pairs for each element.
3453
+ */
3454
+ entries() {
3455
+ const innerIterator = this.#map.entries();
3456
+ return {
3457
+ [Symbol.iterator]() {
3458
+ return this;
3459
+ },
3460
+ next() {
3461
+ const iteratorValue = innerIterator.next();
3462
+ if (iteratorValue.done) {
3463
+ return {
3464
+ done: true,
3465
+ value: void 0
3466
+ };
3467
+ }
3468
+ const entry = iteratorValue.value;
3469
+ const key = entry[0];
3470
+ const value = liveNodeToLson(iteratorValue.value[1]);
3471
+ return {
3472
+ value: [key, value]
3473
+ };
3474
+ }
3475
+ };
3476
+ }
3477
+ /**
3478
+ * Same function object as the initial value of the entries method.
3479
+ */
3480
+ [Symbol.iterator]() {
3481
+ return this.entries();
3482
+ }
3483
+ /**
3484
+ * Returns a new Iterator object that contains the keys for each element.
3485
+ */
3486
+ keys() {
3487
+ return this.#map.keys();
3488
+ }
3489
+ /**
3490
+ * Returns a new Iterator object that contains the values for each element.
3491
+ */
3492
+ values() {
3493
+ const innerIterator = this.#map.values();
3494
+ return {
3495
+ [Symbol.iterator]() {
3496
+ return this;
3497
+ },
3498
+ next() {
3499
+ const iteratorValue = innerIterator.next();
3500
+ if (iteratorValue.done) {
3501
+ return {
3502
+ done: true,
3503
+ value: void 0
3504
+ };
3505
+ }
3506
+ const value = liveNodeToLson(iteratorValue.value);
3507
+ return { value };
3508
+ }
3509
+ };
3510
+ }
3511
+ /**
3512
+ * Executes a provided function once per each key/value pair in the Map object, in insertion order.
3513
+ * @param callback Function to execute for each entry in the map.
3514
+ */
3515
+ forEach(callback) {
3516
+ for (const entry of this) {
3517
+ callback(entry[1], entry[0], this);
3518
+ }
3519
+ }
3520
+ /** @internal */
3521
+ _toTreeNode(key) {
3522
+ return {
3523
+ type: "LiveMap",
3524
+ id: this._id ?? nanoid(),
3525
+ key,
3526
+ payload: Array.from(this.#map.entries()).map(
3527
+ ([key2, val]) => val.toTreeNode(key2)
3528
+ )
3529
+ };
3530
+ }
3531
+ toImmutable() {
3532
+ return super.toImmutable();
3533
+ }
3534
+ /** @internal */
3535
+ _toImmutable() {
3536
+ const result = /* @__PURE__ */ new Map();
3537
+ for (const [key, value] of this.#map) {
3538
+ result.set(key, value.toImmutable());
3539
+ }
3540
+ return freeze(result);
3541
+ }
3542
+ clone() {
3543
+ return new _LiveMap(
3544
+ Array.from(this.#map).map(([key, node]) => [key, node.clone()])
3545
+ );
3546
+ }
3547
+ };
3548
+ var MAX_LIVE_OBJECT_SIZE = 128 * 1024;
3549
+ var LiveObject = class _LiveObject extends AbstractCrdt {
3550
+ #map;
3551
+ #propToLastUpdate;
3552
+ /**
3553
+ * Enable or disable detection of too large LiveObjects.
3554
+ * When enabled, throws an error if LiveObject static data exceeds 128KB, which
3555
+ * is the maximum value the server will be able to accept.
3556
+ * By default, this behavior is disabled to avoid the runtime performance
3557
+ * overhead on every LiveObject.set() or LiveObject.update() call.
3558
+ *
3559
+ * @experimental
3560
+ */
3561
+ static detectLargeObjects = false;
3562
+ static #buildRootAndParentToChildren(items) {
3563
+ const parentToChildren = /* @__PURE__ */ new Map();
3564
+ let root = null;
3565
+ for (const [id, crdt] of items) {
3566
+ if (isRootCrdt(crdt)) {
3567
+ root = [id, crdt];
3568
+ } else {
3569
+ const tuple = [id, crdt];
3570
+ const children = parentToChildren.get(crdt.parentId);
3571
+ if (children !== void 0) {
3572
+ children.push(tuple);
3573
+ } else {
3574
+ parentToChildren.set(crdt.parentId, [tuple]);
3575
+ }
3576
+ }
3577
+ }
3578
+ if (root === null) {
3579
+ throw new Error("Root can't be null");
3580
+ }
3581
+ return [root, parentToChildren];
3582
+ }
3583
+ /** @private Do not use this API directly */
3584
+ static _fromItems(items, pool) {
3585
+ const [root, parentToChildren] = _LiveObject.#buildRootAndParentToChildren(items);
3586
+ return _LiveObject._deserialize(
3587
+ root,
3588
+ parentToChildren,
3589
+ pool
3590
+ );
3591
+ }
3592
+ constructor(obj = {}) {
3593
+ super();
3594
+ this.#propToLastUpdate = /* @__PURE__ */ new Map();
3595
+ const o = compactObject(obj);
3596
+ for (const key of Object.keys(o)) {
3597
+ const value = o[key];
3598
+ if (isLiveNode(value)) {
3599
+ value._setParentLink(this, key);
3600
+ }
3601
+ }
3602
+ this.#map = new Map(Object.entries(o));
3603
+ }
3604
+ /** @internal */
3605
+ _toOps(parentId, parentKey, pool) {
3606
+ if (this._id === void 0) {
3607
+ throw new Error("Cannot serialize item is not attached");
3608
+ }
3609
+ const opId = pool?.generateOpId();
3610
+ const ops = [];
3611
+ const op = {
3612
+ type: 4,
3613
+ id: this._id,
3614
+ opId,
3615
+ parentId,
3616
+ parentKey,
3617
+ data: {}
3618
+ };
3619
+ ops.push(op);
3620
+ for (const [key, value] of this.#map) {
3621
+ if (isLiveNode(value)) {
3622
+ ops.push(...value._toOps(this._id, key, pool));
3623
+ } else {
3624
+ op.data[key] = value;
3625
+ }
3626
+ }
3627
+ return ops;
3628
+ }
3629
+ /** @internal */
3630
+ static _deserialize([id, item], parentToChildren, pool) {
3631
+ const liveObj = new _LiveObject(item.data);
3632
+ liveObj._attach(id, pool);
3633
+ return this._deserializeChildren(liveObj, parentToChildren, pool);
3634
+ }
3635
+ /** @internal */
3636
+ static _deserializeChildren(liveObj, parentToChildren, pool) {
3637
+ const children = parentToChildren.get(nn(liveObj._id));
3638
+ if (children === void 0) {
3639
+ return liveObj;
3640
+ }
3641
+ for (const [id, crdt] of children) {
3642
+ const child = deserializeToLson([id, crdt], parentToChildren, pool);
3643
+ if (isLiveStructure(child)) {
3644
+ child._setParentLink(liveObj, crdt.parentKey);
3645
+ }
3646
+ liveObj.#map.set(crdt.parentKey, child);
3647
+ liveObj.invalidate();
3648
+ }
3649
+ return liveObj;
3650
+ }
3651
+ /** @internal */
3652
+ _attach(id, pool) {
3653
+ super._attach(id, pool);
3654
+ for (const [_key, value] of this.#map) {
3655
+ if (isLiveNode(value)) {
3656
+ value._attach(pool.generateId(), pool);
3657
+ }
3658
+ }
3659
+ }
3660
+ /** @internal */
3661
+ _attachChild(op, source) {
3662
+ if (this._pool === void 0) {
3663
+ throw new Error("Can't attach child if managed pool is not present");
3664
+ }
3665
+ const { id, opId, parentKey: key } = op;
3666
+ const child = creationOpToLson(op);
3667
+ if (this._pool.getNode(id) !== void 0) {
3668
+ if (this.#propToLastUpdate.get(key) === opId) {
3669
+ this.#propToLastUpdate.delete(key);
3670
+ }
3671
+ return { modified: false };
3672
+ }
3673
+ if (source === 0) {
3674
+ this.#propToLastUpdate.set(key, nn(opId));
3675
+ } else if (this.#propToLastUpdate.get(key) === void 0) {
3676
+ } else if (this.#propToLastUpdate.get(key) === opId) {
3677
+ this.#propToLastUpdate.delete(key);
3678
+ return { modified: false };
3679
+ } else {
3680
+ return { modified: false };
3681
+ }
3682
+ const thisId = nn(this._id);
3683
+ const previousValue = this.#map.get(key);
3684
+ let reverse;
3685
+ if (isLiveNode(previousValue)) {
3686
+ reverse = previousValue._toOps(thisId, key);
3687
+ previousValue._detach();
3688
+ } else if (previousValue === void 0) {
3689
+ reverse = [{ type: 6, id: thisId, key }];
3690
+ } else {
3691
+ reverse = [
3692
+ {
3693
+ type: 3,
3694
+ id: thisId,
3695
+ data: { [key]: previousValue }
3696
+ }
3697
+ ];
3698
+ }
3699
+ this.#map.set(key, child);
3700
+ this.invalidate();
3701
+ if (isLiveStructure(child)) {
3702
+ child._setParentLink(this, key);
3703
+ child._attach(id, this._pool);
3704
+ }
3705
+ return {
3706
+ reverse,
3707
+ modified: {
3708
+ node: this,
3709
+ type: "LiveObject",
3710
+ updates: { [key]: { type: "update" } }
3711
+ }
3712
+ };
3713
+ }
3714
+ /** @internal */
3715
+ _detachChild(child) {
3716
+ if (child) {
3717
+ const id = nn(this._id);
3718
+ const parentKey = nn(child._parentKey);
3719
+ const reverse = child._toOps(id, parentKey, this._pool);
3720
+ for (const [key, value] of this.#map) {
3721
+ if (value === child) {
3722
+ this.#map.delete(key);
3723
+ this.invalidate();
3724
+ }
3725
+ }
3726
+ child._detach();
3727
+ const storageUpdate = {
3728
+ node: this,
3729
+ type: "LiveObject",
3730
+ updates: {
3731
+ [parentKey]: { type: "delete" }
3732
+ }
3733
+ };
3734
+ return { modified: storageUpdate, reverse };
3735
+ }
3736
+ return { modified: false };
3737
+ }
3738
+ /** @internal */
3739
+ _detach() {
3740
+ super._detach();
3741
+ for (const value of this.#map.values()) {
3742
+ if (isLiveNode(value)) {
3743
+ value._detach();
3744
+ }
3745
+ }
3746
+ }
3747
+ /** @internal */
3748
+ _apply(op, isLocal) {
3749
+ if (op.type === 3) {
3750
+ return this.#applyUpdate(op, isLocal);
3751
+ } else if (op.type === 6) {
3752
+ return this.#applyDeleteObjectKey(op, isLocal);
3753
+ }
3754
+ return super._apply(op, isLocal);
3755
+ }
3756
+ /** @internal */
3757
+ _serialize() {
3758
+ const data = {};
3759
+ for (const [key, value] of this.#map) {
3760
+ if (!isLiveNode(value)) {
3761
+ data[key] = value;
3762
+ }
3763
+ }
3764
+ if (this.parent.type === "HasParent" && this.parent.node._id) {
3765
+ return {
3766
+ type: 0,
3767
+ parentId: this.parent.node._id,
3768
+ parentKey: this.parent.key,
3769
+ data
3770
+ };
3771
+ } else {
3772
+ return {
3773
+ type: 0,
3774
+ data
3775
+ };
3776
+ }
3777
+ }
3778
+ #applyUpdate(op, isLocal) {
3779
+ let isModified = false;
3780
+ const id = nn(this._id);
3781
+ const reverse = [];
3782
+ const reverseUpdate = {
3783
+ type: 3,
3784
+ id,
3785
+ data: {}
3786
+ };
3787
+ for (const key in op.data) {
3788
+ const oldValue = this.#map.get(key);
3789
+ if (isLiveNode(oldValue)) {
3790
+ reverse.push(...oldValue._toOps(id, key));
3791
+ oldValue._detach();
3792
+ } else if (oldValue !== void 0) {
3793
+ reverseUpdate.data[key] = oldValue;
3794
+ } else if (oldValue === void 0) {
3795
+ reverse.push({ type: 6, id, key });
3796
+ }
3797
+ }
3798
+ const updateDelta = {};
3799
+ for (const key in op.data) {
3800
+ const value = op.data[key];
3801
+ if (value === void 0) {
3802
+ continue;
3803
+ }
3804
+ if (isLocal) {
3805
+ this.#propToLastUpdate.set(key, nn(op.opId));
3806
+ } else if (this.#propToLastUpdate.get(key) === void 0) {
3807
+ isModified = true;
3808
+ } else if (this.#propToLastUpdate.get(key) === op.opId) {
3809
+ this.#propToLastUpdate.delete(key);
3810
+ continue;
3811
+ } else {
3812
+ continue;
3813
+ }
3814
+ const oldValue = this.#map.get(key);
3815
+ if (isLiveNode(oldValue)) {
3816
+ oldValue._detach();
3817
+ }
3818
+ isModified = true;
3819
+ updateDelta[key] = { type: "update" };
3820
+ this.#map.set(key, value);
3821
+ this.invalidate();
3822
+ }
3823
+ if (Object.keys(reverseUpdate.data).length !== 0) {
3824
+ reverse.unshift(reverseUpdate);
3825
+ }
3826
+ return isModified ? {
3827
+ modified: {
3828
+ node: this,
3829
+ type: "LiveObject",
3830
+ updates: updateDelta
3831
+ },
3832
+ reverse
3833
+ } : { modified: false };
3834
+ }
3835
+ #applyDeleteObjectKey(op, isLocal) {
3836
+ const key = op.key;
3837
+ if (this.#map.has(key) === false) {
3838
+ return { modified: false };
3839
+ }
3840
+ if (!isLocal && this.#propToLastUpdate.get(key) !== void 0) {
3841
+ return { modified: false };
3842
+ }
3843
+ const oldValue = this.#map.get(key);
3844
+ const id = nn(this._id);
3845
+ let reverse = [];
3846
+ if (isLiveNode(oldValue)) {
3847
+ reverse = oldValue._toOps(id, op.key);
3848
+ oldValue._detach();
3849
+ } else if (oldValue !== void 0) {
3850
+ reverse = [
3851
+ {
3852
+ type: 3,
3853
+ id,
3854
+ data: { [key]: oldValue }
3855
+ }
3856
+ ];
3857
+ }
3858
+ this.#map.delete(key);
3859
+ this.invalidate();
3860
+ return {
3861
+ modified: {
3862
+ node: this,
3863
+ type: "LiveObject",
3864
+ updates: { [op.key]: { type: "delete" } }
3865
+ },
3866
+ reverse
3867
+ };
3868
+ }
3869
+ /**
3870
+ * Transform the LiveObject into a javascript object
3871
+ */
3872
+ toObject() {
3873
+ return Object.fromEntries(this.#map);
3874
+ }
3875
+ /**
3876
+ * Adds or updates a property with a specified key and a value.
3877
+ * @param key The key of the property to add
3878
+ * @param value The value of the property to add
3879
+ */
3880
+ set(key, value) {
3881
+ this._pool?.assertStorageIsWritable();
3882
+ this.update({ [key]: value });
3883
+ }
3884
+ /**
3885
+ * Returns a specified property from the LiveObject.
3886
+ * @param key The key of the property to get
3887
+ */
3888
+ get(key) {
3889
+ return this.#map.get(key);
3890
+ }
3891
+ /**
3892
+ * Deletes a key from the LiveObject
3893
+ * @param key The key of the property to delete
3894
+ */
3895
+ delete(key) {
3896
+ this._pool?.assertStorageIsWritable();
3897
+ const keyAsString = key;
3898
+ const oldValue = this.#map.get(keyAsString);
3899
+ if (oldValue === void 0) {
3900
+ return;
3901
+ }
3902
+ if (this._pool === void 0 || this._id === void 0) {
3903
+ if (isLiveNode(oldValue)) {
3904
+ oldValue._detach();
3905
+ }
3906
+ this.#map.delete(keyAsString);
3907
+ this.invalidate();
3908
+ return;
3909
+ }
3910
+ let reverse;
3911
+ if (isLiveNode(oldValue)) {
3912
+ oldValue._detach();
3913
+ reverse = oldValue._toOps(this._id, keyAsString);
3914
+ } else {
3915
+ reverse = [
3916
+ {
3917
+ type: 3,
3918
+ data: { [keyAsString]: oldValue },
3919
+ id: this._id
3920
+ }
3921
+ ];
3922
+ }
3923
+ this.#map.delete(keyAsString);
3924
+ this.invalidate();
3925
+ const storageUpdates = /* @__PURE__ */ new Map();
3926
+ storageUpdates.set(this._id, {
3927
+ node: this,
3928
+ type: "LiveObject",
3929
+ updates: { [key]: { type: "delete" } }
3930
+ });
3931
+ this._pool.dispatch(
3932
+ [
3933
+ {
3934
+ type: 6,
3935
+ key: keyAsString,
3936
+ id: this._id,
3937
+ opId: this._pool.generateOpId()
3938
+ }
3939
+ ],
3940
+ reverse,
3941
+ storageUpdates
3942
+ );
3943
+ }
3944
+ /**
3945
+ * Adds or updates multiple properties at once with an object.
3946
+ * @param patch The object used to overrides properties
3947
+ */
3948
+ update(patch) {
3949
+ this._pool?.assertStorageIsWritable();
3950
+ if (_LiveObject.detectLargeObjects) {
3951
+ const data = {};
3952
+ for (const [key, value] of this.#map) {
3953
+ if (!isLiveNode(value)) {
3954
+ data[key] = value;
3955
+ }
3956
+ }
3957
+ for (const key of Object.keys(patch)) {
3958
+ const value = patch[key];
3959
+ if (value === void 0)
3960
+ continue;
3961
+ if (!isLiveNode(value)) {
3962
+ data[key] = value;
3963
+ }
3964
+ }
3965
+ const jsonString = JSON.stringify(data);
3966
+ const upperBoundSize = jsonString.length * 4;
3967
+ if (upperBoundSize > MAX_LIVE_OBJECT_SIZE) {
3968
+ const preciseSize = new TextEncoder().encode(jsonString).length;
3969
+ if (preciseSize > MAX_LIVE_OBJECT_SIZE) {
3970
+ throw new Error(
3971
+ `LiveObject size exceeded limit: ${preciseSize} bytes > ${MAX_LIVE_OBJECT_SIZE} bytes. See https://liveblocks.io/docs/platform/limits#Liveblocks-Storage-limits`
3972
+ );
3973
+ }
3974
+ }
3975
+ }
3976
+ if (this._pool === void 0 || this._id === void 0) {
3977
+ for (const key in patch) {
3978
+ const newValue = patch[key];
3979
+ if (newValue === void 0) {
3980
+ continue;
3981
+ }
3982
+ const oldValue = this.#map.get(key);
3983
+ if (isLiveNode(oldValue)) {
3984
+ oldValue._detach();
3985
+ }
3986
+ if (isLiveNode(newValue)) {
3987
+ newValue._setParentLink(this, key);
3988
+ }
3989
+ this.#map.set(key, newValue);
3990
+ this.invalidate();
3991
+ }
3992
+ return;
3993
+ }
3994
+ const ops = [];
3995
+ const reverseOps = [];
3996
+ const opId = this._pool.generateOpId();
3997
+ const updatedProps = {};
3998
+ const reverseUpdateOp = {
3999
+ id: this._id,
4000
+ type: 3,
4001
+ data: {}
4002
+ };
4003
+ const updateDelta = {};
4004
+ for (const key in patch) {
4005
+ const newValue = patch[key];
4006
+ if (newValue === void 0) {
4007
+ continue;
4008
+ }
4009
+ const oldValue = this.#map.get(key);
4010
+ if (isLiveNode(oldValue)) {
4011
+ reverseOps.push(...oldValue._toOps(this._id, key));
4012
+ oldValue._detach();
4013
+ } else if (oldValue === void 0) {
4014
+ reverseOps.push({ type: 6, id: this._id, key });
4015
+ } else {
4016
+ reverseUpdateOp.data[key] = oldValue;
4017
+ }
4018
+ if (isLiveNode(newValue)) {
4019
+ newValue._setParentLink(this, key);
4020
+ newValue._attach(this._pool.generateId(), this._pool);
4021
+ const newAttachChildOps = newValue._toOps(this._id, key, this._pool);
4022
+ const createCrdtOp = newAttachChildOps.find(
4023
+ (op) => op.parentId === this._id
4024
+ );
4025
+ if (createCrdtOp) {
4026
+ this.#propToLastUpdate.set(key, nn(createCrdtOp.opId));
4027
+ }
4028
+ ops.push(...newAttachChildOps);
4029
+ } else {
4030
+ updatedProps[key] = newValue;
4031
+ this.#propToLastUpdate.set(key, opId);
4032
+ }
4033
+ this.#map.set(key, newValue);
4034
+ this.invalidate();
4035
+ updateDelta[key] = { type: "update" };
4036
+ }
4037
+ if (Object.keys(reverseUpdateOp.data).length !== 0) {
4038
+ reverseOps.unshift(reverseUpdateOp);
4039
+ }
4040
+ if (Object.keys(updatedProps).length !== 0) {
4041
+ ops.unshift({
4042
+ opId,
4043
+ id: this._id,
4044
+ type: 3,
4045
+ data: updatedProps
4046
+ });
4047
+ }
4048
+ const storageUpdates = /* @__PURE__ */ new Map();
4049
+ storageUpdates.set(this._id, {
4050
+ node: this,
4051
+ type: "LiveObject",
4052
+ updates: updateDelta
4053
+ });
4054
+ this._pool.dispatch(ops, reverseOps, storageUpdates);
4055
+ }
4056
+ toImmutable() {
4057
+ return super.toImmutable();
4058
+ }
4059
+ /** @internal */
4060
+ toTreeNode(key) {
4061
+ return super.toTreeNode(key);
4062
+ }
4063
+ /** @internal */
4064
+ _toTreeNode(key) {
4065
+ const nodeId = this._id ?? nanoid();
4066
+ return {
4067
+ type: "LiveObject",
4068
+ id: nodeId,
4069
+ key,
4070
+ payload: Array.from(this.#map.entries()).map(
4071
+ ([key2, value]) => isLiveNode(value) ? value.toTreeNode(key2) : { type: "Json", id: `${nodeId}:${key2}`, key: key2, payload: value }
4072
+ )
4073
+ };
4074
+ }
4075
+ /** @internal */
4076
+ _toImmutable() {
4077
+ const result = {};
4078
+ for (const [key, val] of this.#map) {
4079
+ result[key] = isLiveStructure(val) ? val.toImmutable() : val;
4080
+ }
4081
+ return process.env.NODE_ENV === "production" ? result : Object.freeze(result);
4082
+ }
4083
+ clone() {
4084
+ return new _LiveObject(
4085
+ Object.fromEntries(
4086
+ Array.from(this.#map).map(([key, value]) => [
4087
+ key,
4088
+ isLiveStructure(value) ? value.clone() : deepClone(value)
4089
+ ])
4090
+ )
4091
+ );
4092
+ }
4093
+ };
4094
+ function creationOpToLiveNode(op) {
4095
+ return lsonToLiveNode(creationOpToLson(op));
4096
+ }
4097
+ function creationOpToLson(op) {
4098
+ switch (op.type) {
4099
+ case 8:
4100
+ return op.data;
4101
+ case 4:
4102
+ return new LiveObject(op.data);
4103
+ case 7:
4104
+ return new LiveMap();
4105
+ case 2:
4106
+ return new LiveList([]);
4107
+ default:
4108
+ return assertNever(op, "Unknown creation Op");
4109
+ }
4110
+ }
4111
+ function deserialize([id, crdt], parentToChildren, pool) {
4112
+ switch (crdt.type) {
4113
+ case 0: {
4114
+ return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4115
+ }
4116
+ case 1: {
4117
+ return LiveList._deserialize([id, crdt], parentToChildren, pool);
4118
+ }
4119
+ case 2: {
4120
+ return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4121
+ }
4122
+ case 3: {
4123
+ return LiveRegister._deserialize([id, crdt], parentToChildren, pool);
4124
+ }
4125
+ default: {
4126
+ throw new Error("Unexpected CRDT type");
4127
+ }
4128
+ }
4129
+ }
4130
+ function deserializeToLson([id, crdt], parentToChildren, pool) {
4131
+ switch (crdt.type) {
4132
+ case 0: {
4133
+ return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4134
+ }
4135
+ case 1: {
4136
+ return LiveList._deserialize([id, crdt], parentToChildren, pool);
4137
+ }
4138
+ case 2: {
4139
+ return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4140
+ }
4141
+ case 3: {
4142
+ return crdt.data;
4143
+ }
4144
+ default: {
4145
+ throw new Error("Unexpected CRDT type");
4146
+ }
4147
+ }
4148
+ }
4149
+ function isLiveStructure(value) {
4150
+ return isLiveList(value) || isLiveMap(value) || isLiveObject(value);
4151
+ }
4152
+ function isLiveNode(value) {
4153
+ return isLiveStructure(value) || isLiveRegister(value);
4154
+ }
4155
+ function isLiveList(value) {
4156
+ return value instanceof LiveList;
4157
+ }
4158
+ function isLiveMap(value) {
4159
+ return value instanceof LiveMap;
4160
+ }
4161
+ function isLiveObject(value) {
4162
+ return value instanceof LiveObject;
4163
+ }
4164
+ function isLiveRegister(value) {
4165
+ return value instanceof LiveRegister;
4166
+ }
4167
+ function liveNodeToLson(obj) {
4168
+ if (obj instanceof LiveRegister) {
4169
+ return obj.data;
4170
+ } else if (obj instanceof LiveList || obj instanceof LiveMap || obj instanceof LiveObject) {
4171
+ return obj;
4172
+ } else {
4173
+ return assertNever(obj, "Unknown AbstractCrdt");
4174
+ }
4175
+ }
4176
+ function lsonToLiveNode(value) {
4177
+ if (value instanceof LiveObject || value instanceof LiveMap || value instanceof LiveList) {
4178
+ return value;
4179
+ } else {
4180
+ return new LiveRegister(value);
4181
+ }
4182
+ }
4183
+ var MAX_SOCKET_MESSAGE_SIZE = 1024 * 1024 - 512;
4184
+ var htmlEscapables = {
4185
+ "&": "&amp;",
4186
+ "<": "&lt;",
4187
+ ">": "&gt;",
4188
+ '"': "&quot;",
4189
+ "'": "&#39;"
4190
+ };
4191
+ var htmlEscapablesRegex = new RegExp(
4192
+ Object.keys(htmlEscapables).map((entity) => `\\${entity}`).join("|"),
4193
+ "g"
4194
+ );
4195
+ var markdownEscapables = {
4196
+ _: "\\_",
4197
+ "*": "\\*",
4198
+ "#": "\\#",
4199
+ "`": "\\`",
4200
+ "~": "\\~",
4201
+ "!": "\\!",
4202
+ "|": "\\|",
4203
+ "(": "\\(",
4204
+ ")": "\\)",
4205
+ "{": "\\{",
4206
+ "}": "\\}",
4207
+ "[": "\\[",
4208
+ "]": "\\]"
4209
+ };
4210
+ var markdownEscapablesRegex = new RegExp(
4211
+ Object.keys(markdownEscapables).map((entity) => `\\${entity}`).join("|"),
4212
+ "g"
4213
+ );
4214
+ detectDupes(PKG_NAME, PKG_VERSION, PKG_FORMAT);
4215
+
4216
+ // ../../node_modules/@liveblocks/client/dist/index.js
4217
+ var PKG_NAME2 = "@liveblocks/client";
4218
+ var PKG_VERSION2 = "3.7.1";
4219
+ var PKG_FORMAT2 = "esm";
4220
+ detectDupes(PKG_NAME2, PKG_VERSION2, PKG_FORMAT2);
4221
+
4222
+ // ../../libs/liveblocks-commands/src/utils/liveObjectOf.ts
4223
+ init_cjs_shims();
4224
+ var liveObjectOf = (fields) => {
4225
+ return new LiveObject(fields);
4226
+ };
4227
+
4228
+ // ../../libs/liveblocks-commands/src/utils/schemaConverters.ts
4229
+ init_cjs_shims();
4230
+
4231
+ // ../../fragment-compositions/visualizer/src/utils/liveblocksUtils.ts
4232
+ var toLiveCurrency = (currency) => liveObjectOf({
4233
+ code: currency.code,
4234
+ customCurrencyId: currency.customCurrencyId
4235
+ });
4236
+ var toLiveGroupConsistencyMap = (groups) => new LiveMap(
4237
+ groups.map((group) => [
4238
+ group.key,
4239
+ liveObjectOf({
4240
+ key: group.key,
4241
+ ownBalanceUpdates: group.ownBalanceUpdates
4242
+ })
4243
+ ])
4244
+ );
4245
+ var toLiveAccountConsistencyConfig = (config) => liveObjectOf({
4246
+ lines: config.lines,
4247
+ ownBalanceUpdates: config.ownBalanceUpdates,
4248
+ totalBalanceUpdates: config.totalBalanceUpdates,
4249
+ groups: toLiveGroupConsistencyMap(config.groups)
4250
+ });
4251
+ var toLiveDefaultConsistencyConfig = (config) => {
4252
+ const lines = config.lines ?? "eventual";
4253
+ const groups = toLiveGroupConsistencyMap(config.groups ?? []);
4254
+ return liveObjectOf({
4255
+ lines,
4256
+ // A schema uses either own or total balance updates, never both.
4257
+ ...isTotalBalanceSchema(config) ? {
4258
+ ownBalanceUpdates: void 0,
4259
+ totalBalanceUpdates: config.totalBalanceUpdates
4260
+ } : {
4261
+ ownBalanceUpdates: config.ownBalanceUpdates ?? "eventual",
4262
+ totalBalanceUpdates: void 0
4263
+ },
4264
+ groups
4265
+ });
4266
+ };
4267
+ var toLiveAccount = (account, parentId) => liveObjectOf({
4268
+ id: account.id,
4269
+ key: account.key,
4270
+ type: account.type,
4271
+ name: account.name,
4272
+ template: account.template,
4273
+ currency: account.currency ? toLiveCurrency(account.currency) : void 0,
4274
+ currencyMode: account.currencyMode,
4275
+ consistencyConfig: toLiveAccountConsistencyConfig(
4276
+ account.consistencyConfig
4277
+ ),
4278
+ linkedAccount: account.linkedAccount ? liveObjectOf({
4279
+ linkType: account.linkedAccount.linkType,
4280
+ id: account.linkedAccount.id,
4281
+ externalId: account.linkedAccount.externalId,
4282
+ linkId: account.linkedAccount.linkId,
4283
+ linkIk: account.linkedAccount.linkIk
4284
+ }) : void 0,
4285
+ parentId,
4286
+ status: account.status,
4287
+ clearing: account.clearing,
4288
+ payment: account.payment ? liveObjectOf({
4289
+ enabled: account.payment.enabled
4290
+ }) : void 0
4291
+ });
4292
+ var toLiveAccountRef = (ref, accountId) => liveObjectOf({ accountId, path: ref.path });
4293
+ var toLiveRepeated = (repeated) => liveObjectOf({ key: repeated.key });
4294
+ var toLiveTag = (tag) => liveObjectOf({
4295
+ id: tag.id,
4296
+ key: tag.key,
4297
+ value: tag.value
4298
+ });
4299
+ var toLiveBalanceBounds = (bounds) => liveObjectOf({
4300
+ eq: bounds.eq,
4301
+ lte: bounds.lte,
4302
+ gte: bounds.gte
4303
+ });
4304
+ var toLiveBalanceCondition = (condition) => condition?.ownBalance || condition?.totalBalance ? liveObjectOf({
4305
+ ownBalance: condition.ownBalance ? toLiveBalanceBounds(condition.ownBalance) : void 0,
4306
+ totalBalance: condition.totalBalance ? toLiveBalanceBounds(condition.totalBalance) : void 0
4307
+ }) : void 0;
4308
+ var toLiveEntryCondition = (condition) => liveObjectOf({
4309
+ id: condition.id,
4310
+ account: condition.account ? toLiveAccountRef(condition.account, condition.account.id) : void 0,
4311
+ currency: condition.currency ? toLiveCurrency(condition.currency) : void 0,
4312
+ precondition: toLiveBalanceCondition(condition.precondition),
4313
+ postcondition: toLiveBalanceCondition(condition.postcondition),
4314
+ repeated: condition.repeated ? toLiveRepeated(condition.repeated) : void 0
4315
+ });
4316
+ var toLiveLine = (line) => liveObjectOf({
4317
+ id: line.id,
4318
+ key: line.key,
4319
+ account: line.account ? toLiveAccountRef(line.account, line.account.id) : void 0,
4320
+ amount: line.amount,
4321
+ currency: line.currency ? toLiveCurrency(line.currency) : void 0,
4322
+ description: line.description,
4323
+ tx: line.tx ? liveObjectOf({
4324
+ id: line.tx.id,
4325
+ externalId: line.tx.externalId
4326
+ }) : void 0,
4327
+ repeated: line.repeated ? toLiveRepeated(line.repeated) : void 0,
4328
+ tags: line.tags?.length ? new LiveList(line.tags.map((tag) => toLiveTag(tag))) : void 0,
4329
+ system: void 0
4330
+ });
4331
+ var toLiveVersion = (entry) => {
4332
+ const lines = entry.lines.map((line) => toLiveLine(line));
4333
+ const staticParameters = Object.entries(entry.parameters ?? {}).map(
4334
+ ([key, value]) => liveObjectOf({
4335
+ id: lil_id_default(),
4336
+ key,
4337
+ value
4338
+ })
4339
+ );
4340
+ return liveObjectOf({
4341
+ id: entry.id,
4342
+ description: entry.description,
4343
+ staticParameters: staticParameters.length ? new LiveList(staticParameters) : void 0,
4344
+ groups: entry.groups.length ? new LiveList(
4345
+ entry.groups.map(
4346
+ (group) => liveObjectOf({
4347
+ id: group.id,
4348
+ key: group.key,
4349
+ value: group.value
4350
+ })
4351
+ )
4352
+ ) : void 0,
4353
+ tags: entry.tags.length ? new LiveList(entry.tags.map((tag) => toLiveTag(tag))) : void 0,
4354
+ conditions: entry.conditions.length ? new LiveList(
4355
+ entry.conditions.map((condition) => toLiveEntryCondition(condition))
4356
+ ) : void 0,
4357
+ lines: new LiveMap(
4358
+ lines.map((line) => [line.get("id"), line])
4359
+ ),
4360
+ linesOrder: new LiveList(lines.map((line) => line.get("id"))),
4361
+ status: entry.status,
4362
+ postLinesAs: entry.postLinesAs
4363
+ });
4364
+ };
4365
+ var toLivePaymentLine = (line, accountIdByStructuralPath) => liveObjectOf({
4366
+ id: lil_id_default(),
4367
+ key: line.key,
4368
+ account: toLiveAccountRef(
4369
+ line.account,
4370
+ accountIdByStructuralPath.get(getStructuralPath(line.account.path))
4371
+ ),
4372
+ amount: line.amount,
4373
+ currency: line.currency ? toLiveCurrency(line.currency) : void 0,
4374
+ description: line.description,
4375
+ tx: void 0,
4376
+ repeated: void 0,
4377
+ tags: void 0,
4378
+ system: line.system
4379
+ });
4380
+ var toLivePaymentEntry = (entry, accountIdByStructuralPath) => {
4381
+ const lines = entry.lines.map(
4382
+ (line) => toLivePaymentLine(line, accountIdByStructuralPath)
4383
+ );
4384
+ return liveObjectOf({
4385
+ id: lil_id_default(),
4386
+ description: entry.description,
4387
+ lines: new LiveMap(
4388
+ lines.map((line) => [line.get("id"), line])
4389
+ ),
4390
+ linesOrder: new LiveList(lines.map((line) => line.get("id")))
4391
+ });
4392
+ };
4393
+ var toLivePaymentAccounting = (accounting, accountIdByStructuralPath) => {
4394
+ const toOptionalEntry = (entry) => entry && toLivePaymentEntry(entry, accountIdByStructuralPath);
4395
+ return liveObjectOf({
4396
+ settled: toLivePaymentEntry(accounting.settled, accountIdByStructuralPath),
4397
+ initiated: toOptionalEntry(accounting.initiated),
4398
+ refund_initiated: toOptionalEntry(accounting.refund_initiated),
4399
+ refund_failed: toOptionalEntry(accounting.refund_failed)
4400
+ });
4401
+ };
4402
+ var toLivePaymentTypeVersion = (paymentType, versionId, accountIdByStructuralPath) => liveObjectOf({
4403
+ id: versionId,
4404
+ payment: liveObjectOf({
4405
+ amount: paymentType.payment.amount,
4406
+ direction: paymentType.payment.direction
4407
+ }),
4408
+ status: paymentType.status,
4409
+ accounting: toLivePaymentAccounting(
4410
+ paymentType.accounting,
4411
+ accountIdByStructuralPath
4412
+ )
4413
+ });
4414
+ var toLiveSceneEvent = ({
4415
+ event,
4416
+ entryTypeId,
4417
+ entryTypeVersionId
4418
+ }) => liveObjectOf({
4419
+ id: event.id,
4420
+ eventType: event.eventType,
4421
+ entry: liveObjectOf({
4422
+ entryTypeId,
4423
+ entryTypeVersionId,
4424
+ parameters: event.entry.parameters,
4425
+ repeatedParameters: void 0
4426
+ })
4427
+ });
4428
+ var toLiveScenePayment = ({
4429
+ payment,
4430
+ paymentId,
4431
+ paymentTypeId,
4432
+ paymentTypeVersionId
4433
+ }) => liveObjectOf({
4434
+ id: paymentId,
4435
+ paymentTypeId,
4436
+ paymentTypeVersionId,
4437
+ ik: payment.ik,
4438
+ parameters: payment.parameters
4439
+ });
4440
+ var toLiveScenePaymentEvent = (event, paymentId) => liveObjectOf({
4441
+ id: event.id,
4442
+ eventType: "payment-entry",
4443
+ entry: liveObjectOf({
4444
+ paymentId,
4445
+ event: event.payment.event
4446
+ })
4447
+ });
4448
+ var preprocessLedgerAccount = (account) => ({
4449
+ ...account,
4450
+ status: account.status ?? "active",
4451
+ // Clear currency if currencyMode is multi
4452
+ currency: account.currencyMode === "multi" ? void 0 : account.currency,
4453
+ children: account.children.map(preprocessLedgerAccount),
4454
+ consistencyConfig: {
4455
+ ...account.consistencyConfig,
4456
+ groups: uniqBy_default(account.consistencyConfig.groups, "key")
4457
+ }
4458
+ });
4459
+ var preprocessSchemaDraftForLiveblocks = (schema) => {
4460
+ let processedDefaultCurrency = schema.chartOfAccounts.defaultCurrency;
4461
+ if (processedDefaultCurrency && processedDefaultCurrency.customCurrencyId === "") {
4462
+ const { customCurrencyId, ...rest } = processedDefaultCurrency;
4463
+ processedDefaultCurrency = rest;
4464
+ }
4465
+ const processedLedgerEntryTypes = schema.ledgerEntries.types.map((type) => ({
4466
+ ...type,
4467
+ // Missing status should default to 'active'
4468
+ status: type.status ?? "active",
4469
+ // Ensure typeVersion is always set
4470
+ typeVersion: type.typeVersion ?? 1
4471
+ }));
4472
+ const dedupedEntries = processedLedgerEntryTypes.filter(
4473
+ (obj, index, self) => index === self.findIndex(
4474
+ (o) => o.type === obj.type && o.typeVersion === obj.typeVersion
4475
+ )
4476
+ );
4477
+ const contiguousTypeVersions = [...dedupedEntries];
4478
+ const addedTypeVersions = [];
4479
+ for (const entry of dedupedEntries) {
4480
+ const missingVersions = [];
4481
+ for (let version = 1; version < entry.typeVersion; version++) {
4482
+ const exists = dedupedEntries.find(
4483
+ (e) => e.type === entry.type && e.typeVersion === version
4484
+ );
4485
+ const alreadyAdded = addedTypeVersions.find(
4486
+ (e) => e.type === entry.type && e.typeVersion === version
4487
+ );
4488
+ if (!exists && !alreadyAdded) {
4489
+ missingVersions.push({
4490
+ ...entry,
4491
+ id: lil_id_default(),
4492
+ typeVersion: version
4493
+ });
4494
+ addedTypeVersions.push({ type: entry.type, typeVersion: version });
4495
+ }
4496
+ }
4497
+ if (missingVersions.length > 0) {
4498
+ const entryIndex = contiguousTypeVersions.findIndex(
4499
+ (e) => e.type === entry.type && e.typeVersion === entry.typeVersion
4500
+ );
4501
+ contiguousTypeVersions.splice(entryIndex, 0, ...missingVersions);
4502
+ }
4503
+ }
4504
+ const processedLedgerEntries = {
4505
+ ...schema.ledgerEntries,
4506
+ types: contiguousTypeVersions
4507
+ };
4508
+ const versionsByPaymentType = /* @__PURE__ */ new Map();
4509
+ (schema.payments?.types ?? []).forEach((paymentType) => {
4510
+ const versions = versionsByPaymentType.get(paymentType.type) ?? /* @__PURE__ */ new Set();
4511
+ versions.add(paymentType.typeVersion);
4512
+ versionsByPaymentType.set(paymentType.type, versions);
4513
+ });
4514
+ const processedScenes = schema.scenes.map(
4515
+ ({ payments: declaredPayments, ...scene }) => {
4516
+ const payments = (declaredPayments ?? []).flatMap(
4517
+ (payment) => {
4518
+ const typeVersion = payment.typeVersion ?? 1;
4519
+ return versionsByPaymentType.get(payment.type)?.has(typeVersion) ? [{ ...payment, typeVersion }] : [];
4520
+ }
4521
+ );
4522
+ const declaredIks = new Set(payments.map((payment) => payment.ik));
4523
+ const events = scene.events.flatMap(
4524
+ (event) => z2(event).with(
4525
+ { eventType: "payment" },
4526
+ (paymentEvent) => declaredIks.has(paymentEvent.payment.ik) ? [paymentEvent] : []
4527
+ ).with({ eventType: "entry" }, (ledgerEvent) => {
4528
+ const typeVersion = ledgerEvent.entry.typeVersion ?? 1;
4529
+ const entryExists = ledgerEvent.entry.type !== "" && processedLedgerEntries.types.some(
4530
+ (type) => type.type === ledgerEvent.entry.type && // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
4531
+ (type.typeVersion ?? 1) === typeVersion
4532
+ );
4533
+ return entryExists ? [
4534
+ {
4535
+ ...ledgerEvent,
4536
+ entry: { ...ledgerEvent.entry, typeVersion }
4537
+ }
4538
+ ] : [];
4539
+ }).exhaustive()
4540
+ );
4541
+ return {
4542
+ ...scene,
4543
+ events,
4544
+ // Omitted like the deployable scene, never `payments: undefined`.
4545
+ ...payments.length > 0 && { payments }
4546
+ };
4547
+ }
4548
+ );
4549
+ return {
4550
+ ...schema,
4551
+ chartOfAccounts: {
4552
+ ...schema.chartOfAccounts,
4553
+ defaultCurrency: processedDefaultCurrency,
4554
+ accounts: schema.chartOfAccounts.accounts.map(preprocessLedgerAccount)
4555
+ },
4556
+ ledgerEntries: processedLedgerEntries,
4557
+ scenes: processedScenes
4558
+ };
4559
+ };
4560
+ var convertToLiveblocksFormat = (schema) => {
4561
+ const accountsMap = new LiveMap();
4562
+ const accountsOrder = new LiveList([]);
4563
+ const accountIdByStructuralPath = /* @__PURE__ */ new Map();
4564
+ const addAccountToMap = (account, parentId) => {
4565
+ accountsMap.set(account.id, toLiveAccount(account, parentId));
4566
+ accountsOrder.push(account.id);
4567
+ accountIdByStructuralPath.set(account.structuralPath, account.id);
4568
+ account.children.forEach((child) => {
4569
+ addAccountToMap(child, account.id);
4570
+ });
4571
+ };
4572
+ schema.chartOfAccounts.accounts.forEach((account) => {
4573
+ addAccountToMap(account, void 0);
4574
+ });
4575
+ const entryTypeLookupByType = /* @__PURE__ */ new Map();
4576
+ const paymentTypeLookupByType = /* @__PURE__ */ new Map();
4577
+ const entryTypeMap = /* @__PURE__ */ new Map();
4578
+ schema.ledgerEntries.types.forEach((entry) => {
4579
+ const version = {
4580
+ id: entry.id,
4581
+ typeVersion: entry.typeVersion,
4582
+ live: toLiveVersion(entry)
4583
+ };
4584
+ const existing = entryTypeMap.get(entry.type);
4585
+ if (existing) {
4586
+ existing.versions.push(version);
4587
+ } else {
4588
+ entryTypeMap.set(entry.type, { type: entry.type, versions: [version] });
4589
+ }
4590
+ });
4591
+ const entryTypesMap = new LiveMap();
4592
+ const typeOrder = new LiveList([]);
4593
+ entryTypeMap.forEach((typeData) => {
4594
+ const versionsMap = new LiveMap(
4595
+ typeData.versions.map((version) => [version.id, version.live])
4596
+ );
4597
+ const versionIdByTypeVersion = new Map(
4598
+ typeData.versions.map((version) => [
4599
+ version.typeVersion.toString(),
4600
+ version.id
4601
+ ])
4602
+ );
4603
+ const entryId = versionIdByTypeVersion.get("1") || lil_id_default();
4604
+ entryTypeLookupByType.set(typeData.type, {
4605
+ id: entryId,
4606
+ versionIdByTypeVersion
4607
+ });
4608
+ typeOrder.push(entryId);
4609
+ entryTypesMap.set(
4610
+ entryId,
4611
+ liveObjectOf({
4612
+ id: entryId,
4613
+ type: typeData.type,
4614
+ versions: versionsMap,
4615
+ typeVersionToVersionId: new LiveMap([...versionIdByTypeVersion])
4616
+ })
4617
+ );
4618
+ });
4619
+ const paymentTypesMap = new LiveMap();
4620
+ const paymentTypeOrder = new LiveList([]);
4621
+ const paymentTypesByType = /* @__PURE__ */ new Map();
4622
+ (schema.payments?.types ?? []).forEach((paymentType) => {
4623
+ paymentTypesByType.set(paymentType.type, [
4624
+ ...paymentTypesByType.get(paymentType.type) ?? [],
4625
+ paymentType
4626
+ ]);
4627
+ });
4628
+ paymentTypesByType.forEach((versions, type) => {
4629
+ const versionsMap = new LiveMap();
4630
+ const versionIdByTypeVersion = /* @__PURE__ */ new Map();
4631
+ versions.forEach((paymentType) => {
4632
+ const versionId = lil_id_default();
4633
+ versionsMap.set(
4634
+ versionId,
4635
+ toLivePaymentTypeVersion(
4636
+ paymentType,
4637
+ versionId,
4638
+ accountIdByStructuralPath
4639
+ )
4640
+ );
4641
+ versionIdByTypeVersion.set(String(paymentType.typeVersion), versionId);
4642
+ });
4643
+ const paymentTypeId = lil_id_default();
4644
+ paymentTypeLookupByType.set(type, {
4645
+ id: paymentTypeId,
4646
+ versionIdByTypeVersion
4647
+ });
4648
+ paymentTypesMap.set(
4649
+ paymentTypeId,
4650
+ liveObjectOf({
4651
+ id: paymentTypeId,
4652
+ type,
4653
+ versions: versionsMap,
4654
+ typeVersionToVersionId: new LiveMap([...versionIdByTypeVersion])
4655
+ })
4656
+ );
4657
+ paymentTypeOrder.push(paymentTypeId);
4658
+ });
4659
+ const scenes = new LiveMap();
4660
+ const sceneOrder = new LiveList([]);
4661
+ schema.scenes.forEach((scene) => {
4662
+ const eventsMap = new LiveMap();
4663
+ const eventsOrder = new LiveList([]);
4664
+ const paymentsMap = new LiveMap();
4665
+ const paymentIdByIk = /* @__PURE__ */ new Map();
4666
+ (scene.payments ?? []).forEach((payment) => {
4667
+ const paymentType = paymentTypeLookupByType.get(payment.type);
4668
+ assert3(paymentType, `Payment type ${payment.type} not found`);
4669
+ const paymentTypeVersionId = paymentType.versionIdByTypeVersion.get(
4670
+ String(payment.typeVersion)
4671
+ );
4672
+ assert3(
4673
+ paymentTypeVersionId,
4674
+ `Payment type version ${payment.typeVersion} not found for payment ${payment.type}`
4675
+ );
4676
+ const paymentId = lil_id_default();
4677
+ paymentsMap.set(
4678
+ paymentId,
4679
+ toLiveScenePayment({
4680
+ payment,
4681
+ paymentId,
4682
+ paymentTypeId: paymentType.id,
4683
+ paymentTypeVersionId
4684
+ })
4685
+ );
4686
+ paymentIdByIk.set(payment.ik, paymentId);
4687
+ });
4688
+ scene.events.forEach((event) => {
4689
+ const liveEvent = z2(event).with({ eventType: "payment" }, (paymentEvent) => {
4690
+ const paymentId = paymentIdByIk.get(paymentEvent.payment.ik);
4691
+ assert3(
4692
+ paymentId,
4693
+ `Scene payment ${paymentEvent.payment.ik} not found`
4694
+ );
4695
+ return toLiveScenePaymentEvent(paymentEvent, paymentId);
4696
+ }).with({ eventType: "entry" }, (ledgerEvent) => {
4697
+ const entryType = entryTypeLookupByType.get(ledgerEvent.entry.type);
4698
+ assert3(entryType, `Entry type ${ledgerEvent.entry.type} not found`);
4699
+ const entryTypeVersionId = entryType.versionIdByTypeVersion.get(
4700
+ String(ledgerEvent.entry.typeVersion)
4701
+ );
4702
+ assert3(
4703
+ entryTypeVersionId,
4704
+ `Entry type version ${ledgerEvent.entry.typeVersion} not found for event ${ledgerEvent.entry.type}`
4705
+ );
4706
+ return toLiveSceneEvent({
4707
+ event: ledgerEvent,
4708
+ entryTypeId: entryType.id,
4709
+ entryTypeVersionId
4710
+ });
4711
+ }).exhaustive();
4712
+ eventsMap.set(event.id, liveEvent);
4713
+ eventsOrder.push(event.id);
4714
+ });
4715
+ scenes.set(
4716
+ scene.id,
4717
+ liveObjectOf({
4718
+ id: scene.id,
4719
+ name: scene.name,
4720
+ events: eventsMap,
4721
+ eventsOrder,
4722
+ // Written even when empty; only scenes stored before payments lack it.
4723
+ payments: paymentsMap
4724
+ })
4725
+ );
4726
+ sceneOrder.push(scene.id);
4727
+ });
4728
+ const { defaultCurrency, defaultConsistencyConfig } = schema.chartOfAccounts;
4729
+ return {
4730
+ name: schema.name,
4731
+ consistencyConfig: liveObjectOf({
4732
+ entries: schema.consistencyConfig.entries
4733
+ }),
4734
+ chartOfAccounts: liveObjectOf({
4735
+ defaultCurrencyMode: schema.chartOfAccounts.defaultCurrencyMode,
4736
+ defaultCurrency: toLiveCurrency({
4737
+ code: defaultCurrency?.code || "",
4738
+ customCurrencyId: defaultCurrency?.customCurrencyId || ""
4739
+ }),
4740
+ defaultConsistencyConfig: toLiveDefaultConsistencyConfig(
4741
+ defaultConsistencyConfig
4742
+ ),
4743
+ accounts: accountsMap,
4744
+ accountsOrder
4745
+ }),
4746
+ ledgerEntries: liveObjectOf({
4747
+ types: entryTypesMap,
4748
+ typeOrder
4749
+ }),
4750
+ // Absent rather than empty for a schema without payments, like rooms
4751
+ // created before payment types.
4752
+ ...schema.payments && {
4753
+ paymentTypes: liveObjectOf({
4754
+ types: paymentTypesMap,
4755
+ typeOrder: paymentTypeOrder
4756
+ })
4757
+ },
4758
+ scenes,
4759
+ sceneOrder
4760
+ };
4761
+ };
4762
+ var convertEnhancedSchemaToImmutableRoot = (schema) => {
4763
+ const draft = convertToLiveblocksFormat(
4764
+ preprocessSchemaDraftForLiveblocks(schema)
4765
+ );
4766
+ const liveSchema = new LiveObject(draft);
4767
+ return new LiveObject({
4768
+ schema: liveSchema
4769
+ }).toImmutable();
4770
+ };
4771
+
4772
+ // src/utils/formatScenarioBalances.ts
4773
+ var parseScenarioAmount = (amount, step) => {
4774
+ const numericAmount = Number(amount);
4775
+ if (!Number.isSafeInteger(numericAmount)) {
4776
+ throw new Error(
4777
+ `Scenario step ${step} exceeds the supported integer amount range.`
4778
+ );
4779
+ }
4780
+ return BigInt(numericAmount);
4781
+ };
4782
+ var formatScenarioBalances = ({
4783
+ schema: schemaInput,
4784
+ scenarioName,
4785
+ step
4786
+ }) => {
4787
+ if (!Number.isSafeInteger(step) || step < 1) {
4788
+ throw new Error(
4789
+ "Step must be an integer starting at 1. Step 0 is not allowed."
4790
+ );
4791
+ }
4792
+ const schema = BaseSchema.parse(schemaInput);
4793
+ const matches = (schema.scenes ?? []).filter(
4794
+ (scene2) => scene2.name === scenarioName
4795
+ );
4796
+ if (matches.length !== 1) {
4797
+ throw new Error(
4798
+ matches.length === 0 ? `Scenario "${scenarioName}" was not found.` : `Scenario "${scenarioName}" is ambiguous. Use a unique scenario name.`
4799
+ );
4800
+ }
4801
+ const scenario = matches[0];
4802
+ if (scenario.events.length === 0) {
4803
+ throw new Error(`Scenario "${scenarioName}" has no steps to simulate.`);
4804
+ }
4805
+ if (step > scenario.events.length) {
4806
+ throw new Error(
4807
+ `Scenario "${scenarioName}" has ${scenario.events.length} steps. Choose a step from 1 to ${scenario.events.length}.`
4808
+ );
4809
+ }
4810
+ const normalizedSchema = BaseSchema.parse({
4811
+ ...schema,
4812
+ payments: Schema.parse(schema).payments
4813
+ });
4814
+ const { validatedSchema } = transformAndValidateSchema(normalizedSchema);
4815
+ const root = convertEnhancedSchemaToImmutableRoot(
4816
+ enhanceSchema(validatedSchema)
4817
+ );
4818
+ const scene = [...root.schema.scenes.values()].find(
4819
+ (candidate) => candidate.name === scenarioName
4820
+ );
4821
+ if (!scene)
4822
+ throw new Error(`Scenario "${scenarioName}" could not be loaded.`);
4823
+ if (scene.eventsOrder.length !== scenario.events.length) {
4824
+ throw new Error(
4825
+ `Scenario "${scenarioName}" contains unresolved entry or payment references. Fix the schema before simulating.`
4826
+ );
4827
+ }
4828
+ const simulation = simulateScene({ root, sceneId: scene.id });
4829
+ if (!simulation)
4830
+ throw new Error(`Scenario "${scenarioName}" could not be simulated.`);
4831
+ const events = simulation.events.slice(0, step);
4832
+ const lines = events.flatMap((event, index) => {
4833
+ if (!event.entry.isValid) {
4834
+ throw new Error(
4835
+ `Scenario step ${index + 1} failed: ${event.entry.reasons.join("; ")}`
4836
+ );
4837
+ }
4838
+ return event.entry.lines.map((line) => {
4839
+ const amount = parseScenarioAmount(line.amount, index + 1);
4840
+ return {
4841
+ accountPath: line.accountPath,
4842
+ currency: line.currency.code,
4843
+ customCurrencyId: line.currency.customCurrencyId,
4844
+ amount
4845
+ };
4846
+ });
4847
+ });
4848
+ const balances = /* @__PURE__ */ new Map();
4849
+ lines.forEach((line) => {
4850
+ const key = JSON.stringify([
4851
+ line.accountPath,
4852
+ line.currency,
4853
+ line.customCurrencyId
4854
+ ]);
4855
+ const amount = (balances.get(key)?.amount ?? 0n) + line.amount;
4856
+ balances.set(key, { ...line, amount });
4857
+ });
4858
+ const { accounts, accountPathToAccount } = ChartOfAccounts.parse(
4859
+ schema.chartOfAccounts
4860
+ );
4861
+ const entryRows = scenario.events.map((event, index) => {
4862
+ const name = event.eventType === "entry" ? event.entry.type : `${scenario.payments?.find(
4863
+ (payment) => payment.ik === event.payment.ik
4864
+ )?.type ?? event.payment.ik} (${event.payment.event})`;
4865
+ const heading = `${index + 1 === step ? "\u27A1\uFE0F " : " "}${index + 1}. ${name}`;
4866
+ if (index + 1 > step)
4867
+ return heading;
4868
+ const simulatedEntry = simulation.events[index].entry;
4869
+ if (!simulatedEntry.isValid)
4870
+ return heading;
4871
+ return [
4872
+ heading,
4873
+ ...simulatedEntry.lines.map(
4874
+ (line) => ` ${formatAccountReference({
4875
+ path: line.accountPath,
4876
+ accounts: accountPathToAccount
4877
+ })} [${formatBalance({
4878
+ amount: parseScenarioAmount(line.amount, index + 1),
4879
+ currency: line.currency.customCurrencyId ?? line.currency.code,
4880
+ precision: getBalancePrecision(line.currency.code)
4881
+ })}]`
4882
+ )
4883
+ ].join("\n");
4884
+ });
4885
+ return [
4886
+ "## Scenario Entries",
4887
+ "",
4888
+ entryRows.join("\n\n"),
4889
+ "",
4890
+ "---",
4891
+ "",
4892
+ "## Account Balances",
4893
+ "",
4894
+ formatScenarioAccountBalances({
4895
+ accounts,
4896
+ usedAccounts: simulation.events.flatMap(
4897
+ (event) => event.entry.isValid ? event.entry.lines.map((line) => ({
4898
+ accountPath: line.accountPath,
4899
+ currency: line.currency.customCurrencyId ?? line.currency.code,
4900
+ precision: getBalancePrecision(line.currency.code),
4901
+ currencyCode: line.currency.code
4902
+ })) : []
4903
+ ),
4904
+ balances: [...balances.values()].map((balance) => ({
4905
+ accountPath: balance.accountPath,
4906
+ amount: balance.amount,
4907
+ currency: balance.customCurrencyId ?? balance.currency,
4908
+ precision: getBalancePrecision(balance.currency),
4909
+ currencyCode: balance.currency
4910
+ }))
4911
+ })
4912
+ ].join("\n");
4913
+ };
4914
+
4915
+ export {
4916
+ formatScenarioBalances
4917
+ };