@tldraw/state 5.8.0-canary.cd7308d44f85 → 5.8.0-next.e3fedfd98025

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.
@@ -92,8 +92,6 @@ export declare interface AtomOptions<Value, Diff> {
92
92
  isEqual?(a: any, b: any): boolean;
93
93
  }
94
94
 
95
- /* Excluded from this release type: beforeTransactionCommit */
96
-
97
95
  /* Excluded from this release type: Child */
98
96
 
99
97
  /**
@@ -452,8 +450,6 @@ export declare const EMPTY_ARRAY: [];
452
450
  */
453
451
  export declare function getComputedInstance<Obj extends object, Prop extends keyof Obj>(obj: Obj, propertyName: Prop): Computed<Obj[Prop] extends () => infer Value ? Value : Obj[Prop]>;
454
452
 
455
- /* Excluded from this release type: getValueBeforeTransaction */
456
-
457
453
  /**
458
454
  * Returns true if the given value is an {@link Atom}.
459
455
  *
@@ -550,8 +546,6 @@ export declare function isUninitialized(value: any): value is UNINITIALIZED;
550
546
  */
551
547
  export declare function localStorageAtom<Value, Diff = unknown>(name: string, initialValue: Value, options?: AtomOptions<Value, Diff>): [Atom<Value, Diff>, () => void];
552
548
 
553
- /* Excluded from this release type: onTransactionAbort */
554
-
555
549
  /**
556
550
  * Starts a new effect scheduler, scheduling the effect immediately.
557
551
  *
package/dist-cjs/index.js CHANGED
@@ -24,16 +24,13 @@ __export(index_exports, {
24
24
  RESET_VALUE: () => import_types.RESET_VALUE,
25
25
  UNINITIALIZED: () => import_Computed.UNINITIALIZED,
26
26
  atom: () => import_Atom.atom,
27
- beforeTransactionCommit: () => import_transactions.beforeTransactionCommit,
28
27
  computed: () => import_Computed.computed,
29
28
  deferAsyncEffects: () => import_transactions.deferAsyncEffects,
30
29
  getComputedInstance: () => import_Computed.getComputedInstance,
31
- getValueBeforeTransaction: () => import_transactions.getValueBeforeTransaction,
32
30
  isAtom: () => import_Atom.isAtom,
33
31
  isSignal: () => import_isSignal.isSignal,
34
32
  isUninitialized: () => import_Computed.isUninitialized,
35
33
  localStorageAtom: () => import_localStorageAtom.localStorageAtom,
36
- onTransactionAbort: () => import_transactions.onTransactionAbort,
37
34
  react: () => import_EffectScheduler.react,
38
35
  reactor: () => import_EffectScheduler.reactor,
39
36
  transact: () => import_transactions.transact,
@@ -64,7 +61,7 @@ if (actualApiVersion !== currentApiVersion) {
64
61
  }
65
62
  (0, import_utils.registerTldrawLibraryVersion)(
66
63
  "@tldraw/state",
67
- "5.8.0-canary.cd7308d44f85",
64
+ "5.8.0-next.e3fedfd98025",
68
65
  "cjs"
69
66
  );
70
67
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["import { registerTldrawLibraryVersion } from '@tldraw/utils'\nimport { singleton } from './lib/helpers'\n\nexport { ArraySet } from './lib/ArraySet'\nexport { atom, isAtom } from './lib/Atom'\nexport type { Atom, AtomOptions } from './lib/Atom'\nexport { unsafe__withoutCapture, whyAmIRunning } from './lib/capture'\nexport {\n\tcomputed,\n\tgetComputedInstance,\n\tisUninitialized,\n\tUNINITIALIZED,\n\twithDiff,\n} from './lib/Computed'\nexport type { Computed, ComputedOptions, WithDiff } from './lib/Computed'\nexport { EffectScheduler, react, reactor } from './lib/EffectScheduler'\nexport type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'\nexport { EMPTY_ARRAY } from './lib/helpers'\nexport { isSignal } from './lib/isSignal'\nexport { localStorageAtom } from './lib/localStorageAtom'\nexport {\n\tbeforeTransactionCommit,\n\tdeferAsyncEffects,\n\tgetValueBeforeTransaction,\n\tonTransactionAbort,\n\ttransact,\n\ttransaction,\n} from './lib/transactions'\nexport { RESET_VALUE } from './lib/types'\nexport type { Child, ComputeDiff, Signal } from './lib/types'\n\n// This should be incremented any time an API change is made. i.e. for additions or removals.\n// Bugfixes need not increment this.\nconst currentApiVersion = 1\n\nconst actualApiVersion = singleton('apiVersion', () => currentApiVersion)\n\nif (actualApiVersion !== currentApiVersion) {\n\tthrow new Error(\n\t\t`You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.`\n\t)\n}\n\nregisterTldrawLibraryVersion(\n\t(globalThis as any).TLDRAW_LIBRARY_NAME,\n\t(globalThis as any).TLDRAW_LIBRARY_VERSION,\n\t(globalThis as any).TLDRAW_LIBRARY_MODULES\n)\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA6C;AAC7C,qBAA0B;AAE1B,sBAAyB;AACzB,kBAA6B;AAE7B,qBAAsD;AACtD,sBAMO;AAEP,6BAAgD;AAEhD,IAAAA,kBAA4B;AAC5B,sBAAyB;AACzB,8BAAiC;AACjC,0BAOO;AACP,mBAA4B;AAK5B,MAAM,oBAAoB;AAE1B,MAAM,uBAAmB,0BAAU,cAAc,MAAM,iBAAiB;AAExE,IAAI,qBAAqB,mBAAmB;AAC3C,QAAM,IAAI;AAAA,IACT;AAAA,EACD;AACD;AAAA,IAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AACF;",
4
+ "sourcesContent": ["import { registerTldrawLibraryVersion } from '@tldraw/utils'\nimport { singleton } from './lib/helpers'\n\nexport { ArraySet } from './lib/ArraySet'\nexport { atom, isAtom } from './lib/Atom'\nexport type { Atom, AtomOptions } from './lib/Atom'\nexport { unsafe__withoutCapture, whyAmIRunning } from './lib/capture'\nexport {\n\tcomputed,\n\tgetComputedInstance,\n\tisUninitialized,\n\tUNINITIALIZED,\n\twithDiff,\n} from './lib/Computed'\nexport type { Computed, ComputedOptions, WithDiff } from './lib/Computed'\nexport { EffectScheduler, react, reactor } from './lib/EffectScheduler'\nexport type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'\nexport { EMPTY_ARRAY } from './lib/helpers'\nexport { isSignal } from './lib/isSignal'\nexport { localStorageAtom } from './lib/localStorageAtom'\nexport { deferAsyncEffects, transact, transaction } from './lib/transactions'\nexport { RESET_VALUE } from './lib/types'\nexport type { Child, ComputeDiff, Signal } from './lib/types'\n\n// This should be incremented any time an API change is made. i.e. for additions or removals.\n// Bugfixes need not increment this.\nconst currentApiVersion = 1\n\nconst actualApiVersion = singleton('apiVersion', () => currentApiVersion)\n\nif (actualApiVersion !== currentApiVersion) {\n\tthrow new Error(\n\t\t`You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.`\n\t)\n}\n\nregisterTldrawLibraryVersion(\n\t(globalThis as any).TLDRAW_LIBRARY_NAME,\n\t(globalThis as any).TLDRAW_LIBRARY_VERSION,\n\t(globalThis as any).TLDRAW_LIBRARY_MODULES\n)\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA6C;AAC7C,qBAA0B;AAE1B,sBAAyB;AACzB,kBAA6B;AAE7B,qBAAsD;AACtD,sBAMO;AAEP,6BAAgD;AAEhD,IAAAA,kBAA4B;AAC5B,sBAAyB;AACzB,8BAAiC;AACjC,0BAAyD;AACzD,mBAA4B;AAK5B,MAAM,oBAAoB;AAE1B,MAAM,uBAAmB,0BAAU,cAAc,MAAM,iBAAiB;AAExE,IAAI,qBAAqB,mBAAmB;AAC3C,QAAM,IAAI;AAAA,IACT;AAAA,EACD;AACD;AAAA,IAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AACF;",
6
6
  "names": ["import_helpers"]
7
7
  }
@@ -20,12 +20,9 @@ var transactions_exports = {};
20
20
  __export(transactions_exports, {
21
21
  advanceGlobalEpoch: () => advanceGlobalEpoch,
22
22
  atomDidChange: () => atomDidChange,
23
- beforeTransactionCommit: () => beforeTransactionCommit,
24
23
  deferAsyncEffects: () => deferAsyncEffects,
25
24
  getGlobalEpoch: () => getGlobalEpoch,
26
25
  getIsInTransaction: () => getIsInTransaction,
27
- getValueBeforeTransaction: () => getValueBeforeTransaction,
28
- onTransactionAbort: () => onTransactionAbort,
29
26
  transact: () => transact,
30
27
  transaction: () => transaction
31
28
  });
@@ -41,18 +38,11 @@ class Transaction {
41
38
  isSync;
42
39
  asyncProcessCount = 0;
43
40
  initialAtomValues = /* @__PURE__ */ new Map();
44
- // See `onTransactionAbort`. Oldest first.
45
- abortCallbacks = null;
46
- // See `beforeTransactionCommit`. Oldest first.
47
- commitCallbacks = null;
48
41
  commit() {
49
42
  if (this.parent === null) {
50
43
  flushChanges(this.initialAtomValues.keys());
51
44
  return;
52
45
  }
53
- const parent = this.parent;
54
- parent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks);
55
- parent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks);
56
46
  const parentValues = this.parent.initialAtomValues;
57
47
  if (parentValues.size === 0) {
58
48
  this.parent.initialAtomValues = this.initialAtomValues;
@@ -64,31 +54,6 @@ class Transaction {
64
54
  }
65
55
  });
66
56
  }
67
- /**
68
- * Run the callbacks registered with `beforeTransactionCommit`, including any that they
69
- * register. Only a root transaction has a commit of its own to prepare for: a nested one hands
70
- * its callbacks to its parent. Returns true if a callback asked for a rollback.
71
- */
72
- prepare() {
73
- if (this.parent !== null) return false;
74
- let rollback = false;
75
- const requestRollback = () => {
76
- rollback = true;
77
- };
78
- let passes = 0;
79
- while (this.commitCallbacks) {
80
- if (passes++ > 100) {
81
- throw new Error("Commit callback depth limit exceeded");
82
- }
83
- const callbacks = this.commitCallbacks;
84
- this.commitCallbacks = null;
85
- for (let i = 0; i < callbacks.length; i++) {
86
- callbacks[i](requestRollback);
87
- if (rollback) return true;
88
- }
89
- }
90
- return false;
91
- }
92
57
  /**
93
58
  * Abort the transaction. Restores every atom changed in this transaction to its initial
94
59
  * value, then commits. Must be called while this is still `inst.currentTransaction`, so that
@@ -102,35 +67,9 @@ class Transaction {
102
67
  atom.set(value);
103
68
  atom.historyBuffer?.clear();
104
69
  });
105
- const callbacks = this.abortCallbacks;
106
- this.abortCallbacks = null;
107
- this.commitCallbacks = null;
108
- let failure = null;
109
- if (callbacks) {
110
- for (let i = callbacks.length - 1; i >= 0; i--) {
111
- try {
112
- callbacks[i]();
113
- } catch (error) {
114
- failure ??= { error };
115
- }
116
- }
117
- }
118
70
  this.commit();
119
- if (failure) throw failure.error;
120
71
  }
121
72
  }
122
- function abortAfterError(txn) {
123
- try {
124
- txn.abort();
125
- } catch {
126
- }
127
- }
128
- function concatCallbacks(parent, child) {
129
- if (!child) return parent;
130
- if (!parent) return child;
131
- for (let i = 0; i < child.length; i++) parent.push(child[i]);
132
- return parent;
133
- }
134
73
  const inst = (0, import_helpers.singleton)("transactions", () => ({
135
74
  // The current epoch (global to all atoms).
136
75
  globalEpoch: import_constants.GLOBAL_START_EPOCH + 1,
@@ -195,26 +134,6 @@ function flushChanges(atoms) {
195
134
  traverseReactors = void 0;
196
135
  }
197
136
  }
198
- function onTransactionAbort(undo) {
199
- const txn = inst.currentTransaction;
200
- if (!txn) return;
201
- if (txn.abortCallbacks) txn.abortCallbacks.push(undo);
202
- else txn.abortCallbacks = [undo];
203
- }
204
- function beforeTransactionCommit(fn) {
205
- const txn = inst.currentTransaction;
206
- if (!txn) return;
207
- if (txn.commitCallbacks) txn.commitCallbacks.push(fn);
208
- else txn.commitCallbacks = [fn];
209
- }
210
- function getValueBeforeTransaction(atom) {
211
- let value = atom.__unsafe__getWithoutCapture();
212
- for (let txn = inst.currentTransaction; txn; txn = txn.parent) {
213
- const initialValues = txn.initialAtomValues;
214
- if (initialValues.has(atom)) value = initialValues.get(atom);
215
- }
216
- return value;
217
- }
218
137
  function atomDidChange(atom, previousValue) {
219
138
  if (inst.currentTransaction) {
220
139
  if (!inst.currentTransaction.initialAtomValues.has(atom)) {
@@ -240,20 +159,12 @@ function transaction(fn) {
240
159
  try {
241
160
  result = fn(() => rollback = true);
242
161
  } catch (e) {
243
- abortAfterError(txn);
162
+ txn.abort();
244
163
  throw e;
245
164
  }
246
165
  if (inst.currentTransaction !== txn) {
247
166
  throw new Error("Transaction boundaries overlap");
248
167
  }
249
- if (!rollback) {
250
- try {
251
- if (txn.prepare()) rollback = true;
252
- } catch (e) {
253
- abortAfterError(txn);
254
- throw e;
255
- }
256
- }
257
168
  if (rollback) {
258
169
  txn.abort();
259
170
  } else {
@@ -296,21 +207,13 @@ async function deferAsyncEffects(fn) {
296
207
  }
297
208
  }
298
209
  try {
299
- let rollback = false;
300
- if (typeof error === "undefined") {
301
- try {
302
- rollback = txn.prepare();
303
- } catch (e) {
304
- error = e ?? null;
305
- }
306
- }
307
210
  if (typeof error !== "undefined") {
308
- abortAfterError(txn);
211
+ txn.abort();
309
212
  throw error;
213
+ } else {
214
+ txn.commit();
215
+ return result;
310
216
  }
311
- if (rollback) txn.abort();
312
- else txn.commit();
313
- return result;
314
217
  } finally {
315
218
  inst.currentTransaction = null;
316
219
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/transactions.ts"],
4
- "sourcesContent": ["import { _Atom, Atom } from './Atom'\nimport { GLOBAL_START_EPOCH } from './constants'\nimport { singleton } from './helpers'\nimport { Child, Signal } from './types'\n\ninterface Reactor {\n\tmaybeScheduleEffect(): void\n\tlastTraversedEpoch: number\n}\n\nclass Transaction {\n\tasyncProcessCount = 0\n\tconstructor(\n\t\tpublic readonly parent: Transaction | null,\n\t\tpublic readonly isSync: boolean\n\t) {}\n\n\tinitialAtomValues = new Map<_Atom, any>()\n\n\t// See `onTransactionAbort`. Oldest first.\n\tabortCallbacks: (() => void)[] | null = null\n\n\t// See `beforeTransactionCommit`. Oldest first.\n\tcommitCallbacks: CommitCallback[] | null = null\n\n\tcommit() {\n\t\tif (this.parent === null) {\n\t\t\t// For root transactions, flush changed atoms\n\t\t\tflushChanges(this.initialAtomValues.keys())\n\t\t\treturn\n\t\t}\n\t\t// For transactions with parents, add the transaction's initial values to the parent's, so\n\t\t// an outer rollback can still undo them (T7). This must come before any \"are we reacting?\" special case: a nested\n\t\t// transaction committed by an effect during the reaction phase used to skip this fold and\n\t\t// its changes survived the outer rollback.\n\t\t// A parent that has recorded nothing yet adopts the map outright: this transaction is\n\t\t// finished with it, and the common nested case is a single inner transaction doing all\n\t\t// the writes.\n\t\tconst parent = this.parent!\n\t\tparent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks)\n\t\tparent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks)\n\t\tconst parentValues = this.parent!.initialAtomValues\n\t\tif (parentValues.size === 0) {\n\t\t\tthis.parent!.initialAtomValues = this.initialAtomValues\n\t\t\treturn\n\t\t}\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tif (!parentValues.has(atom)) {\n\t\t\t\tparentValues.set(atom, value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Run the callbacks registered with `beforeTransactionCommit`, including any that they\n\t * register. Only a root transaction has a commit of its own to prepare for: a nested one hands\n\t * its callbacks to its parent. Returns true if a callback asked for a rollback.\n\t */\n\tprepare(): boolean {\n\t\tif (this.parent !== null) return false\n\t\tlet rollback = false\n\t\tconst requestRollback = () => {\n\t\t\trollback = true\n\t\t}\n\t\tlet passes = 0\n\t\twhile (this.commitCallbacks) {\n\t\t\tif (passes++ > 100) {\n\t\t\t\tthrow new Error('Commit callback depth limit exceeded')\n\t\t\t}\n\t\t\tconst callbacks = this.commitCallbacks\n\t\t\tthis.commitCallbacks = null\n\t\t\tfor (let i = 0; i < callbacks.length; i++) {\n\t\t\t\tcallbacks[i](requestRollback)\n\t\t\t\tif (rollback) return true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t/**\n\t * Abort the transaction. Restores every atom changed in this transaction to its initial\n\t * value, then commits. Must be called while this is still `inst.currentTransaction`, so that\n\t * the restoring sets are recorded against it instead of each flushing effects on their own.\n\t *\n\t * @public\n\t */\n\tabort() {\n\t\tinst.globalEpoch++\n\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tatom.set(value)\n\t\t\tatom.historyBuffer?.clear()\n\t\t})\n\n\t\t// Taken off before `commit`, which would otherwise hand them to the parent.\n\t\tconst callbacks = this.abortCallbacks\n\t\tthis.abortCallbacks = null\n\t\tthis.commitCallbacks = null\n\t\tlet failure: { error: unknown } | null = null\n\t\tif (callbacks) {\n\t\t\tfor (let i = callbacks.length - 1; i >= 0; i--) {\n\t\t\t\t// A throw must not skip the older callbacks: each one left out keeps its state wrong for good.\n\t\t\t\ttry {\n\t\t\t\t\tcallbacks[i]()\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailure ??= { error }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.commit()\n\t\tif (failure) throw failure.error\n\t}\n}\n\ntype CommitCallback = (rollback: () => void) => void\n\n// For an abort caused by `error`: a throw from an abort callback must not replace it.\nfunction abortAfterError(txn: Transaction) {\n\ttry {\n\t\ttxn.abort()\n\t} catch {\n\t\t// `error` is the one to report\n\t}\n}\n\nfunction concatCallbacks<T>(parent: T[] | null, child: T[] | null): T[] | null {\n\tif (!child) return parent\n\tif (!parent) return child\n\tfor (let i = 0; i < child.length; i++) parent.push(child[i])\n\treturn parent\n}\n\nconst inst = singleton('transactions', () => ({\n\t// The current epoch (global to all atoms).\n\tglobalEpoch: GLOBAL_START_EPOCH + 1,\n\t// Whether any transaction is reacting.\n\tglobalIsReacting: false,\n\tcurrentTransaction: null as Transaction | null,\n\n\tcleanupReactors: null as null | Set<Reactor>,\n}))\n\n/**\n * Gets the current global epoch, which is incremented every time any atom changes.\n * This is used to track changes across the entire reactive system.\n *\n * @returns The current global epoch number\n * @public\n */\nexport function getGlobalEpoch() {\n\treturn inst.globalEpoch\n}\n\n/**\n * Whether a transaction (sync or async) is currently open. While one is, atom changes are\n * recorded but their children are not traversed until it commits.\n *\n * @internal\n */\nexport function getIsInTransaction() {\n\treturn inst.currentTransaction !== null\n}\n\n// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a\n// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user\n// code, so nothing can re-enter and swap it mid-walk.\nlet traverseReactors: Set<Reactor>\n\nfunction traverseChild(child: Child) {\n\tif (child.lastTraversedEpoch === inst.globalEpoch) {\n\t\treturn\n\t}\n\n\tchild.lastTraversedEpoch = inst.globalEpoch\n\n\tif ('__isEffectScheduler' in child) {\n\t\ttraverseReactors.add(child as unknown as Reactor)\n\t} else {\n\t\t;(child as any as Signal<any>).children.visit(traverseChild)\n\t}\n}\n\n/**\n * Collect all of the reactors that need to run for an atom and run them. During the reaction\n * phase the affected effects are instead queued for the cleanup pass, so a change made by an\n * effect never interrupts the pass that is running (P4).\n *\n * @param atoms - The atoms to flush changes for.\n */\nfunction flushChanges(atoms: Iterable<_Atom>) {\n\tif (inst.globalIsReacting) {\n\t\tfor (const atom of atoms) {\n\t\t\ttraverseAtomForCleanup(atom)\n\t\t}\n\t\treturn\n\t}\n\n\tconst outerTxn = inst.currentTransaction\n\ttry {\n\t\t// clear the transaction stack. Transactions started by effects must be roots: the committing\n\t\t// transaction (if any) has already handed its changes to this flush.\n\t\tinst.currentTransaction = null\n\t\tinst.globalIsReacting = true\n\n\t\tconst reactors = new Set<Reactor>()\n\t\ttraverseReactors = reactors\n\t\tfor (const atom of atoms) {\n\t\t\tatom.children.visit(traverseChild)\n\t\t}\n\n\t\t// Run each reactor.\n\t\tfor (const r of reactors) {\n\t\t\tr.maybeScheduleEffect()\n\t\t}\n\n\t\tlet updateDepth = 0\n\t\twhile (inst.cleanupReactors?.size) {\n\t\t\tif (updateDepth++ > 1000) {\n\t\t\t\tthrow new Error('Reaction update depth limit exceeded')\n\t\t\t}\n\t\t\tconst reactors = inst.cleanupReactors\n\t\t\tinst.cleanupReactors = null\n\t\t\tfor (const r of reactors) {\n\t\t\t\tr.maybeScheduleEffect()\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tinst.cleanupReactors = null\n\t\tinst.globalIsReacting = false\n\t\tinst.currentTransaction = outerTxn\n\t\ttraverseReactors = undefined! // free memory\n\t}\n}\n\n/**\n * Registers `undo` to run if the current transaction, or a transaction around it, rolls back. For\n * state kept outside atoms, which a rollback would otherwise leave as it is. Callbacks run newest\n * first, after the atoms are restored and before effects are flushed. They must not throw, and\n * must not change atoms or register callbacks: the transaction is already ending. Outside\n * a transaction nothing can roll back, so this does nothing.\n *\n * @internal\n */\nexport function onTransactionAbort(undo: () => void) {\n\tconst txn = inst.currentTransaction\n\tif (!txn) return\n\tif (txn.abortCallbacks) txn.abortCallbacks.push(undo)\n\telse txn.abortCallbacks = [undo]\n}\n\n/**\n * Registers `fn` to run when the outermost transaction is about to commit: every change is made,\n * no effect has run, and nothing outside the transaction has seen it. For checks on a transaction\n * as a whole. `fn` may change atoms and register further callbacks, which run before the same\n * commit. Calling `rollback` aborts the transaction and skips the callbacks that are left, and a\n * throw aborts it and propagates. Callbacks from a transaction that aborts never run. Outside a\n * transaction this does nothing.\n *\n * @internal\n */\nexport function beforeTransactionCommit(fn: (rollback: () => void) => void) {\n\tconst txn = inst.currentTransaction\n\tif (!txn) return\n\tif (txn.commitCallbacks) txn.commitCallbacks.push(fn)\n\telse txn.commitCallbacks = [fn]\n}\n\n/**\n * The value `atom` had before the outermost open transaction changed it, which is the value it\n * goes back to if that transaction rolls back. The atom's current value when no open transaction\n * has changed it.\n *\n * @internal\n */\nexport function getValueBeforeTransaction<T>(atom: Atom<T>): T {\n\tlet value = atom.__unsafe__getWithoutCapture()\n\tfor (let txn = inst.currentTransaction; txn; txn = txn.parent) {\n\t\tconst initialValues = txn.initialAtomValues\n\t\tif (initialValues.has(atom as any)) value = initialValues.get(atom as any)\n\t}\n\treturn value\n}\n\n/** @internal */\nexport function atomDidChange(atom: _Atom, previousValue: any) {\n\tif (inst.currentTransaction) {\n\t\t// If we are in a transaction, then all we have to do is preserve\n\t\t// the value of the atom at the start of the transaction in case\n\t\t// we need to roll back. Children are not traversed until the\n\t\t// transaction commits, which is why `Computed` must not trust its\n\t\t// traversal-based cache shortcut while a transaction is open.\n\t\tif (!inst.currentTransaction.initialAtomValues.has(atom)) {\n\t\t\tinst.currentTransaction.initialAtomValues.set(atom, previousValue)\n\t\t}\n\t} else {\n\t\t// If there is no transaction, flush the changes immediately.\n\t\tflushChanges([atom])\n\t}\n}\n\nfunction traverseAtomForCleanup(atom: _Atom) {\n\ttraverseReactors = inst.cleanupReactors ??= new Set()\n\tatom.children.visit(traverseChild)\n}\n\n/** @internal */\nexport function advanceGlobalEpoch() {\n\tinst.globalEpoch++\n}\n\n/**\n * Batches state updates, deferring side effects until after the transaction completes.\n * Unlike {@link transact}, this function always creates a new transaction, allowing for nested transactions.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * })\n *\n * // Logs \"Hello, Jane Smith!\"\n * ```\n *\n * If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * throw new Error('oops')\n * })\n *\n * // firstName.get() === 'John'\n * // Logs \"Hello, John Doe!\" again: effects whose parents were changed and restored still run,\n * // and observe the restored values.\n * ```\n *\n * A `rollback` callback is passed into the function.\n * Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction((rollback) => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * rollback()\n * })\n *\n * // firstName.get() === 'John'\n * // lastName.get() === 'Doe'\n * // Logs \"Hello, John Doe!\" again, as above.\n * ```\n *\n * @param fn - The function to run in a transaction, called with a function to roll back the change.\n * @returns The return value of the function\n * @public\n */\nexport function transaction<T>(fn: (rollback: () => void) => T) {\n\tconst txn = new Transaction(inst.currentTransaction, true)\n\n\tinst.currentTransaction = txn\n\n\ttry {\n\t\tlet result = undefined as T | undefined\n\t\tlet rollback = false\n\n\t\ttry {\n\t\t\tresult = fn(() => (rollback = true))\n\t\t} catch (e) {\n\t\t\tabortAfterError(txn)\n\t\t\tthrow e\n\t\t}\n\n\t\tif (inst.currentTransaction !== txn) {\n\t\t\tthrow new Error('Transaction boundaries overlap')\n\t\t}\n\n\t\tif (!rollback) {\n\t\t\ttry {\n\t\t\t\t// Never assign: a callback can call `fn`'s own `rollback`, which `prepare` can't see.\n\t\t\t\tif (txn.prepare()) rollback = true\n\t\t\t} catch (e) {\n\t\t\t\tabortAfterError(txn)\n\t\t\t\tthrow e\n\t\t\t}\n\t\t}\n\n\t\tif (rollback) {\n\t\t\ttxn.abort()\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t}\n\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = txn.parent\n\t}\n}\n\n/**\n * Like {@link transaction}, but does not create a new transaction if there is already one in progress.\n * This is the preferred way to batch state updates when you don't need the rollback functionality.\n *\n * @example\n * ```ts\n * const count = atom('count', 0)\n * const doubled = atom('doubled', 0)\n *\n * react('update doubled', () => {\n * console.log(`Count: ${count.get()}, Doubled: ${doubled.get()}`)\n * })\n *\n * // This batches both updates into a single reaction\n * transact(() => {\n * count.set(5)\n * doubled.set(count.get() * 2)\n * })\n * // Logs: \"Count: 5, Doubled: 10\"\n * ```\n *\n * @param fn - The function to run in a transaction\n * @returns The return value of the function\n * @public\n */\nexport function transact<T>(fn: () => T): T {\n\tif (inst.currentTransaction) {\n\t\treturn fn()\n\t}\n\treturn transaction(fn)\n}\n\n/**\n * Defers the execution of asynchronous effects until they can be properly handled.\n * This function creates an asynchronous transaction context that batches state updates\n * across async operations while preventing conflicts with synchronous transactions.\n *\n * @example\n * ```ts\n * const data = atom('data', null)\n * const loading = atom('loading', false)\n *\n * await deferAsyncEffects(async () => {\n * loading.set(true)\n * const result = await fetch('/api/data')\n * const json = await result.json()\n * data.set(json)\n * loading.set(false)\n * })\n * ```\n *\n * @param fn - The async function to execute within the deferred context\n * @returns A promise that resolves to the return value of the function\n * @throws Will throw if called during a synchronous transaction\n * @internal\n */\nexport async function deferAsyncEffects<T>(fn: () => Promise<T>) {\n\t// Can't kick off async transactions during a sync transaction because\n\t// the async transaction won't finish until after the sync transaction\n\t// is done.\n\tif (inst.currentTransaction?.isSync) {\n\t\tthrow new Error('deferAsyncEffects cannot be called during a sync transaction')\n\t}\n\n\t// Can't kick off async transactions during a reaction phase at the moment,\n\t// because the transaction stack is cleared after the reaction phase.\n\t// So wait until the path ahead is clear\n\twhile (inst.globalIsReacting) {\n\t\tawait new Promise((r) => queueMicrotask(() => r(null)))\n\t}\n\n\tconst txn = inst.currentTransaction ?? new Transaction(null, false)\n\n\t// don't think this can happen, but just in case\n\tif (txn.isSync) throw new Error('deferAsyncEffects cannot be called during a sync transaction')\n\n\tinst.currentTransaction = txn\n\ttxn.asyncProcessCount++\n\n\tlet result = undefined as T | undefined\n\n\t// `undefined` means \"did not throw\"; a thrown `undefined` is stored as `null` so it still counts.\n\tlet error = undefined as any\n\ttry {\n\t\t// Run the function.\n\t\tresult = await fn()\n\t} catch (e) {\n\t\t// Abort the transaction if the function throws.\n\t\terror = e ?? null\n\t}\n\n\tif (--txn.asyncProcessCount > 0) {\n\t\t// Other processes still share this transaction; it settles when the last one finishes.\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tthrow error\n\t\t} else {\n\t\t\treturn result\n\t\t}\n\t}\n\n\t// Settle while this is still the current transaction (see `Transaction.abort`): clearing it\n\t// first made every restoring set inside `abort()` flush effects on its own, so effects\n\t// observed half-restored state.\n\ttry {\n\t\tlet rollback = false\n\t\tif (typeof error === 'undefined') {\n\t\t\ttry {\n\t\t\t\trollback = txn.prepare()\n\t\t\t} catch (e) {\n\t\t\t\terror = e ?? null\n\t\t\t}\n\t\t}\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tabortAfterError(txn)\n\t\t\tthrow error\n\t\t}\n\t\tif (rollback) txn.abort()\n\t\telse txn.commit()\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = null\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAAmC;AACnC,qBAA0B;AAQ1B,MAAM,YAAY;AAAA,EAEjB,YACiB,QACA,QACf;AAFe;AACA;AAAA,EACd;AAAA,EAFc;AAAA,EACA;AAAA,EAHjB,oBAAoB;AAAA,EAMpB,oBAAoB,oBAAI,IAAgB;AAAA;AAAA,EAGxC,iBAAwC;AAAA;AAAA,EAGxC,kBAA2C;AAAA,EAE3C,SAAS;AACR,QAAI,KAAK,WAAW,MAAM;AAEzB,mBAAa,KAAK,kBAAkB,KAAK,CAAC;AAC1C;AAAA,IACD;AAQA,UAAM,SAAS,KAAK;AACpB,WAAO,iBAAiB,gBAAgB,OAAO,gBAAgB,KAAK,cAAc;AAClF,WAAO,kBAAkB,gBAAgB,OAAO,iBAAiB,KAA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AS,MAAM,GAAG;AAAA,EACnB,SAAS,GAAG;AAEX,YAAQ,KAAK;AAAA,EACd;AAEA,MAAI,EAAE,IAAI,oBAAoB,GAAG;AAEhC,QAAI,OAAO,UAAU,aAAa;AAEjC,YAAM;AAAA,IACP,OAAO;AACN,aAAO;AAAA,IACR;AAAA,EACD;AAKA,MAAI;AACH,QAAI,WAAW;AACf,QAAI,OAAO,UAAU,aAAa;AACjC,UAAI;AACH,mBAAW,IAAI,QAAQ;AAAA,MACxB,SAAS,GAAG;AACX,gBAAQ,KAAK;AAAA,MACd;AAAA,IACD;AACA,QAAI,OAAO,UAAU,aAAa;AAEjC,sBAAgB,GAAG;AACnB,YAAM;AAAA,IACP;AACA,QAAI,SAAU,KAAI,MAAM;AAAA,QACnB,KAAI,OAAO;AAChB,WAAO;AAAA,EACR,UAAE;AACD,SAAK,qBAAqB;AAAA,EAC3B;AACD;",
4
+ "sourcesContent": ["import { _Atom } from './Atom'\nimport { GLOBAL_START_EPOCH } from './constants'\nimport { singleton } from './helpers'\nimport { Child, Signal } from './types'\n\ninterface Reactor {\n\tmaybeScheduleEffect(): void\n\tlastTraversedEpoch: number\n}\n\nclass Transaction {\n\tasyncProcessCount = 0\n\tconstructor(\n\t\tpublic readonly parent: Transaction | null,\n\t\tpublic readonly isSync: boolean\n\t) {}\n\n\tinitialAtomValues = new Map<_Atom, any>()\n\n\tcommit() {\n\t\tif (this.parent === null) {\n\t\t\t// For root transactions, flush changed atoms\n\t\t\tflushChanges(this.initialAtomValues.keys())\n\t\t\treturn\n\t\t}\n\t\t// For transactions with parents, add the transaction's initial values to the parent's, so\n\t\t// an outer rollback can still undo them (T7). This must come before any \"are we reacting?\" special case: a nested\n\t\t// transaction committed by an effect during the reaction phase used to skip this fold and\n\t\t// its changes survived the outer rollback.\n\t\t// A parent that has recorded nothing yet adopts the map outright: this transaction is\n\t\t// finished with it, and the common nested case is a single inner transaction doing all\n\t\t// the writes.\n\t\tconst parentValues = this.parent!.initialAtomValues\n\t\tif (parentValues.size === 0) {\n\t\t\tthis.parent!.initialAtomValues = this.initialAtomValues\n\t\t\treturn\n\t\t}\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tif (!parentValues.has(atom)) {\n\t\t\t\tparentValues.set(atom, value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Abort the transaction. Restores every atom changed in this transaction to its initial\n\t * value, then commits. Must be called while this is still `inst.currentTransaction`, so that\n\t * the restoring sets are recorded against it instead of each flushing effects on their own.\n\t *\n\t * @public\n\t */\n\tabort() {\n\t\tinst.globalEpoch++\n\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tatom.set(value)\n\t\t\tatom.historyBuffer?.clear()\n\t\t})\n\n\t\tthis.commit()\n\t}\n}\n\nconst inst = singleton('transactions', () => ({\n\t// The current epoch (global to all atoms).\n\tglobalEpoch: GLOBAL_START_EPOCH + 1,\n\t// Whether any transaction is reacting.\n\tglobalIsReacting: false,\n\tcurrentTransaction: null as Transaction | null,\n\n\tcleanupReactors: null as null | Set<Reactor>,\n}))\n\n/**\n * Gets the current global epoch, which is incremented every time any atom changes.\n * This is used to track changes across the entire reactive system.\n *\n * @returns The current global epoch number\n * @public\n */\nexport function getGlobalEpoch() {\n\treturn inst.globalEpoch\n}\n\n/**\n * Whether a transaction (sync or async) is currently open. While one is, atom changes are\n * recorded but their children are not traversed until it commits.\n *\n * @internal\n */\nexport function getIsInTransaction() {\n\treturn inst.currentTransaction !== null\n}\n\n// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a\n// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user\n// code, so nothing can re-enter and swap it mid-walk.\nlet traverseReactors: Set<Reactor>\n\nfunction traverseChild(child: Child) {\n\tif (child.lastTraversedEpoch === inst.globalEpoch) {\n\t\treturn\n\t}\n\n\tchild.lastTraversedEpoch = inst.globalEpoch\n\n\tif ('__isEffectScheduler' in child) {\n\t\ttraverseReactors.add(child as unknown as Reactor)\n\t} else {\n\t\t;(child as any as Signal<any>).children.visit(traverseChild)\n\t}\n}\n\n/**\n * Collect all of the reactors that need to run for an atom and run them. During the reaction\n * phase the affected effects are instead queued for the cleanup pass, so a change made by an\n * effect never interrupts the pass that is running (P4).\n *\n * @param atoms - The atoms to flush changes for.\n */\nfunction flushChanges(atoms: Iterable<_Atom>) {\n\tif (inst.globalIsReacting) {\n\t\tfor (const atom of atoms) {\n\t\t\ttraverseAtomForCleanup(atom)\n\t\t}\n\t\treturn\n\t}\n\n\tconst outerTxn = inst.currentTransaction\n\ttry {\n\t\t// clear the transaction stack. Transactions started by effects must be roots: the committing\n\t\t// transaction (if any) has already handed its changes to this flush.\n\t\tinst.currentTransaction = null\n\t\tinst.globalIsReacting = true\n\n\t\tconst reactors = new Set<Reactor>()\n\t\ttraverseReactors = reactors\n\t\tfor (const atom of atoms) {\n\t\t\tatom.children.visit(traverseChild)\n\t\t}\n\n\t\t// Run each reactor.\n\t\tfor (const r of reactors) {\n\t\t\tr.maybeScheduleEffect()\n\t\t}\n\n\t\tlet updateDepth = 0\n\t\twhile (inst.cleanupReactors?.size) {\n\t\t\tif (updateDepth++ > 1000) {\n\t\t\t\tthrow new Error('Reaction update depth limit exceeded')\n\t\t\t}\n\t\t\tconst reactors = inst.cleanupReactors\n\t\t\tinst.cleanupReactors = null\n\t\t\tfor (const r of reactors) {\n\t\t\t\tr.maybeScheduleEffect()\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tinst.cleanupReactors = null\n\t\tinst.globalIsReacting = false\n\t\tinst.currentTransaction = outerTxn\n\t\ttraverseReactors = undefined! // free memory\n\t}\n}\n\n/** @internal */\nexport function atomDidChange(atom: _Atom, previousValue: any) {\n\tif (inst.currentTransaction) {\n\t\t// If we are in a transaction, then all we have to do is preserve\n\t\t// the value of the atom at the start of the transaction in case\n\t\t// we need to roll back. Children are not traversed until the\n\t\t// transaction commits, which is why `Computed` must not trust its\n\t\t// traversal-based cache shortcut while a transaction is open.\n\t\tif (!inst.currentTransaction.initialAtomValues.has(atom)) {\n\t\t\tinst.currentTransaction.initialAtomValues.set(atom, previousValue)\n\t\t}\n\t} else {\n\t\t// If there is no transaction, flush the changes immediately.\n\t\tflushChanges([atom])\n\t}\n}\n\nfunction traverseAtomForCleanup(atom: _Atom) {\n\ttraverseReactors = inst.cleanupReactors ??= new Set()\n\tatom.children.visit(traverseChild)\n}\n\n/** @internal */\nexport function advanceGlobalEpoch() {\n\tinst.globalEpoch++\n}\n\n/**\n * Batches state updates, deferring side effects until after the transaction completes.\n * Unlike {@link transact}, this function always creates a new transaction, allowing for nested transactions.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * })\n *\n * // Logs \"Hello, Jane Smith!\"\n * ```\n *\n * If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * throw new Error('oops')\n * })\n *\n * // firstName.get() === 'John'\n * // Logs \"Hello, John Doe!\" again: effects whose parents were changed and restored still run,\n * // and observe the restored values.\n * ```\n *\n * A `rollback` callback is passed into the function.\n * Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction((rollback) => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * rollback()\n * })\n *\n * // firstName.get() === 'John'\n * // lastName.get() === 'Doe'\n * // Logs \"Hello, John Doe!\" again, as above.\n * ```\n *\n * @param fn - The function to run in a transaction, called with a function to roll back the change.\n * @returns The return value of the function\n * @public\n */\nexport function transaction<T>(fn: (rollback: () => void) => T) {\n\tconst txn = new Transaction(inst.currentTransaction, true)\n\n\tinst.currentTransaction = txn\n\n\ttry {\n\t\tlet result = undefined as T | undefined\n\t\tlet rollback = false\n\n\t\ttry {\n\t\t\tresult = fn(() => (rollback = true))\n\t\t} catch (e) {\n\t\t\ttxn.abort()\n\t\t\tthrow e\n\t\t}\n\n\t\tif (inst.currentTransaction !== txn) {\n\t\t\tthrow new Error('Transaction boundaries overlap')\n\t\t}\n\n\t\tif (rollback) {\n\t\t\ttxn.abort()\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t}\n\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = txn.parent\n\t}\n}\n\n/**\n * Like {@link transaction}, but does not create a new transaction if there is already one in progress.\n * This is the preferred way to batch state updates when you don't need the rollback functionality.\n *\n * @example\n * ```ts\n * const count = atom('count', 0)\n * const doubled = atom('doubled', 0)\n *\n * react('update doubled', () => {\n * console.log(`Count: ${count.get()}, Doubled: ${doubled.get()}`)\n * })\n *\n * // This batches both updates into a single reaction\n * transact(() => {\n * count.set(5)\n * doubled.set(count.get() * 2)\n * })\n * // Logs: \"Count: 5, Doubled: 10\"\n * ```\n *\n * @param fn - The function to run in a transaction\n * @returns The return value of the function\n * @public\n */\nexport function transact<T>(fn: () => T): T {\n\tif (inst.currentTransaction) {\n\t\treturn fn()\n\t}\n\treturn transaction(fn)\n}\n\n/**\n * Defers the execution of asynchronous effects until they can be properly handled.\n * This function creates an asynchronous transaction context that batches state updates\n * across async operations while preventing conflicts with synchronous transactions.\n *\n * @example\n * ```ts\n * const data = atom('data', null)\n * const loading = atom('loading', false)\n *\n * await deferAsyncEffects(async () => {\n * loading.set(true)\n * const result = await fetch('/api/data')\n * const json = await result.json()\n * data.set(json)\n * loading.set(false)\n * })\n * ```\n *\n * @param fn - The async function to execute within the deferred context\n * @returns A promise that resolves to the return value of the function\n * @throws Will throw if called during a synchronous transaction\n * @internal\n */\nexport async function deferAsyncEffects<T>(fn: () => Promise<T>) {\n\t// Can't kick off async transactions during a sync transaction because\n\t// the async transaction won't finish until after the sync transaction\n\t// is done.\n\tif (inst.currentTransaction?.isSync) {\n\t\tthrow new Error('deferAsyncEffects cannot be called during a sync transaction')\n\t}\n\n\t// Can't kick off async transactions during a reaction phase at the moment,\n\t// because the transaction stack is cleared after the reaction phase.\n\t// So wait until the path ahead is clear\n\twhile (inst.globalIsReacting) {\n\t\tawait new Promise((r) => queueMicrotask(() => r(null)))\n\t}\n\n\tconst txn = inst.currentTransaction ?? new Transaction(null, false)\n\n\t// don't think this can happen, but just in case\n\tif (txn.isSync) throw new Error('deferAsyncEffects cannot be called during a sync transaction')\n\n\tinst.currentTransaction = txn\n\ttxn.asyncProcessCount++\n\n\tlet result = undefined as T | undefined\n\n\t// `undefined` means \"did not throw\"; a thrown `undefined` is stored as `null` so it still counts.\n\tlet error = undefined as any\n\ttry {\n\t\t// Run the function.\n\t\tresult = await fn()\n\t} catch (e) {\n\t\t// Abort the transaction if the function throws.\n\t\terror = e ?? null\n\t}\n\n\tif (--txn.asyncProcessCount > 0) {\n\t\t// Other processes still share this transaction; it settles when the last one finishes.\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tthrow error\n\t\t} else {\n\t\t\treturn result\n\t\t}\n\t}\n\n\t// Settle while this is still the current transaction (see `Transaction.abort`): clearing it\n\t// first made every restoring set inside `abort()` flush effects on its own, so effects\n\t// observed half-restored state.\n\ttry {\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction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AK;AAAA,EACd;AAEA,MAAI,EAAE,IAAI,oBAAoB,GAAG;AAEhC,QAAI,OAAO,UAAU,aAAa;AAEjC,YAAM;AAAA,IACP,OAAO;AACN,aAAO;AAAA,IACR;AAAA,EACD;AAKA,MAAI;AACH,QAAI,OAAO,UAAU,aAAa;AAEjC,UAAI,MAAM;AACV,YAAM;AAAA,IACP,OAAO;AACN,UAAI,OAAO;AACX,aAAO;AAAA,IACR;AAAA,EACD,UAAE;AACD,SAAK,qBAAqB;AAAA,EAC3B;AACD;",
6
6
  "names": ["reactors"]
7
7
  }
@@ -92,8 +92,6 @@ export declare interface AtomOptions<Value, Diff> {
92
92
  isEqual?(a: any, b: any): boolean;
93
93
  }
94
94
 
95
- /* Excluded from this release type: beforeTransactionCommit */
96
-
97
95
  /* Excluded from this release type: Child */
98
96
 
99
97
  /**
@@ -452,8 +450,6 @@ export declare const EMPTY_ARRAY: [];
452
450
  */
453
451
  export declare function getComputedInstance<Obj extends object, Prop extends keyof Obj>(obj: Obj, propertyName: Prop): Computed<Obj[Prop] extends () => infer Value ? Value : Obj[Prop]>;
454
452
 
455
- /* Excluded from this release type: getValueBeforeTransaction */
456
-
457
453
  /**
458
454
  * Returns true if the given value is an {@link Atom}.
459
455
  *
@@ -550,8 +546,6 @@ export declare function isUninitialized(value: any): value is UNINITIALIZED;
550
546
  */
551
547
  export declare function localStorageAtom<Value, Diff = unknown>(name: string, initialValue: Value, options?: AtomOptions<Value, Diff>): [Atom<Value, Diff>, () => void];
552
548
 
553
- /* Excluded from this release type: onTransactionAbort */
554
-
555
549
  /**
556
550
  * Starts a new effect scheduler, scheduling the effect immediately.
557
551
  *
@@ -14,14 +14,7 @@ import { EffectScheduler, react, reactor } from "./lib/EffectScheduler.mjs";
14
14
  import { EMPTY_ARRAY } from "./lib/helpers.mjs";
15
15
  import { isSignal } from "./lib/isSignal.mjs";
16
16
  import { localStorageAtom } from "./lib/localStorageAtom.mjs";
17
- import {
18
- beforeTransactionCommit,
19
- deferAsyncEffects,
20
- getValueBeforeTransaction,
21
- onTransactionAbort,
22
- transact,
23
- transaction
24
- } from "./lib/transactions.mjs";
17
+ import { deferAsyncEffects, transact, transaction } from "./lib/transactions.mjs";
25
18
  import { RESET_VALUE } from "./lib/types.mjs";
26
19
  const currentApiVersion = 1;
27
20
  const actualApiVersion = singleton("apiVersion", () => currentApiVersion);
@@ -32,7 +25,7 @@ if (actualApiVersion !== currentApiVersion) {
32
25
  }
33
26
  registerTldrawLibraryVersion(
34
27
  "@tldraw/state",
35
- "5.8.0-canary.cd7308d44f85",
28
+ "5.8.0-next.e3fedfd98025",
36
29
  "esm"
37
30
  );
38
31
  export {
@@ -42,16 +35,13 @@ export {
42
35
  RESET_VALUE,
43
36
  UNINITIALIZED,
44
37
  atom,
45
- beforeTransactionCommit,
46
38
  computed,
47
39
  deferAsyncEffects,
48
40
  getComputedInstance,
49
- getValueBeforeTransaction,
50
41
  isAtom,
51
42
  isSignal,
52
43
  isUninitialized,
53
44
  localStorageAtom,
54
- onTransactionAbort,
55
45
  react,
56
46
  reactor,
57
47
  transact,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["import { registerTldrawLibraryVersion } from '@tldraw/utils'\nimport { singleton } from './lib/helpers'\n\nexport { ArraySet } from './lib/ArraySet'\nexport { atom, isAtom } from './lib/Atom'\nexport type { Atom, AtomOptions } from './lib/Atom'\nexport { unsafe__withoutCapture, whyAmIRunning } from './lib/capture'\nexport {\n\tcomputed,\n\tgetComputedInstance,\n\tisUninitialized,\n\tUNINITIALIZED,\n\twithDiff,\n} from './lib/Computed'\nexport type { Computed, ComputedOptions, WithDiff } from './lib/Computed'\nexport { EffectScheduler, react, reactor } from './lib/EffectScheduler'\nexport type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'\nexport { EMPTY_ARRAY } from './lib/helpers'\nexport { isSignal } from './lib/isSignal'\nexport { localStorageAtom } from './lib/localStorageAtom'\nexport {\n\tbeforeTransactionCommit,\n\tdeferAsyncEffects,\n\tgetValueBeforeTransaction,\n\tonTransactionAbort,\n\ttransact,\n\ttransaction,\n} from './lib/transactions'\nexport { RESET_VALUE } from './lib/types'\nexport type { Child, ComputeDiff, Signal } from './lib/types'\n\n// This should be incremented any time an API change is made. i.e. for additions or removals.\n// Bugfixes need not increment this.\nconst currentApiVersion = 1\n\nconst actualApiVersion = singleton('apiVersion', () => currentApiVersion)\n\nif (actualApiVersion !== currentApiVersion) {\n\tthrow new Error(\n\t\t`You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.`\n\t)\n}\n\nregisterTldrawLibraryVersion(\n\t(globalThis as any).TLDRAW_LIBRARY_NAME,\n\t(globalThis as any).TLDRAW_LIBRARY_VERSION,\n\t(globalThis as any).TLDRAW_LIBRARY_MODULES\n)\n"],
5
- "mappings": "AAAA,SAAS,oCAAoC;AAC7C,SAAS,iBAAiB;AAE1B,SAAS,gBAAgB;AACzB,SAAS,MAAM,cAAc;AAE7B,SAAS,wBAAwB,qBAAqB;AACtD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAEP,SAAS,iBAAiB,OAAO,eAAe;AAEhD,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,wBAAwB;AACjC;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,mBAAmB;AAK5B,MAAM,oBAAoB;AAE1B,MAAM,mBAAmB,UAAU,cAAc,MAAM,iBAAiB;AAExE,IAAI,qBAAqB,mBAAmB;AAC3C,QAAM,IAAI;AAAA,IACT;AAAA,EACD;AACD;AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AACF;",
4
+ "sourcesContent": ["import { registerTldrawLibraryVersion } from '@tldraw/utils'\nimport { singleton } from './lib/helpers'\n\nexport { ArraySet } from './lib/ArraySet'\nexport { atom, isAtom } from './lib/Atom'\nexport type { Atom, AtomOptions } from './lib/Atom'\nexport { unsafe__withoutCapture, whyAmIRunning } from './lib/capture'\nexport {\n\tcomputed,\n\tgetComputedInstance,\n\tisUninitialized,\n\tUNINITIALIZED,\n\twithDiff,\n} from './lib/Computed'\nexport type { Computed, ComputedOptions, WithDiff } from './lib/Computed'\nexport { EffectScheduler, react, reactor } from './lib/EffectScheduler'\nexport type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'\nexport { EMPTY_ARRAY } from './lib/helpers'\nexport { isSignal } from './lib/isSignal'\nexport { localStorageAtom } from './lib/localStorageAtom'\nexport { deferAsyncEffects, transact, transaction } from './lib/transactions'\nexport { RESET_VALUE } from './lib/types'\nexport type { Child, ComputeDiff, Signal } from './lib/types'\n\n// This should be incremented any time an API change is made. i.e. for additions or removals.\n// Bugfixes need not increment this.\nconst currentApiVersion = 1\n\nconst actualApiVersion = singleton('apiVersion', () => currentApiVersion)\n\nif (actualApiVersion !== currentApiVersion) {\n\tthrow new Error(\n\t\t`You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.`\n\t)\n}\n\nregisterTldrawLibraryVersion(\n\t(globalThis as any).TLDRAW_LIBRARY_NAME,\n\t(globalThis as any).TLDRAW_LIBRARY_VERSION,\n\t(globalThis as any).TLDRAW_LIBRARY_MODULES\n)\n"],
5
+ "mappings": "AAAA,SAAS,oCAAoC;AAC7C,SAAS,iBAAiB;AAE1B,SAAS,gBAAgB;AACzB,SAAS,MAAM,cAAc;AAE7B,SAAS,wBAAwB,qBAAqB;AACtD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAEP,SAAS,iBAAiB,OAAO,eAAe;AAEhD,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,wBAAwB;AACjC,SAAS,mBAAmB,UAAU,mBAAmB;AACzD,SAAS,mBAAmB;AAK5B,MAAM,oBAAoB;AAE1B,MAAM,mBAAmB,UAAU,cAAc,MAAM,iBAAiB;AAExE,IAAI,qBAAqB,mBAAmB;AAC3C,QAAM,IAAI;AAAA,IACT;AAAA,EACD;AACD;AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AACF;",
6
6
  "names": []
7
7
  }
@@ -9,18 +9,11 @@ class Transaction {
9
9
  isSync;
10
10
  asyncProcessCount = 0;
11
11
  initialAtomValues = /* @__PURE__ */ new Map();
12
- // See `onTransactionAbort`. Oldest first.
13
- abortCallbacks = null;
14
- // See `beforeTransactionCommit`. Oldest first.
15
- commitCallbacks = null;
16
12
  commit() {
17
13
  if (this.parent === null) {
18
14
  flushChanges(this.initialAtomValues.keys());
19
15
  return;
20
16
  }
21
- const parent = this.parent;
22
- parent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks);
23
- parent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks);
24
17
  const parentValues = this.parent.initialAtomValues;
25
18
  if (parentValues.size === 0) {
26
19
  this.parent.initialAtomValues = this.initialAtomValues;
@@ -32,31 +25,6 @@ class Transaction {
32
25
  }
33
26
  });
34
27
  }
35
- /**
36
- * Run the callbacks registered with `beforeTransactionCommit`, including any that they
37
- * register. Only a root transaction has a commit of its own to prepare for: a nested one hands
38
- * its callbacks to its parent. Returns true if a callback asked for a rollback.
39
- */
40
- prepare() {
41
- if (this.parent !== null) return false;
42
- let rollback = false;
43
- const requestRollback = () => {
44
- rollback = true;
45
- };
46
- let passes = 0;
47
- while (this.commitCallbacks) {
48
- if (passes++ > 100) {
49
- throw new Error("Commit callback depth limit exceeded");
50
- }
51
- const callbacks = this.commitCallbacks;
52
- this.commitCallbacks = null;
53
- for (let i = 0; i < callbacks.length; i++) {
54
- callbacks[i](requestRollback);
55
- if (rollback) return true;
56
- }
57
- }
58
- return false;
59
- }
60
28
  /**
61
29
  * Abort the transaction. Restores every atom changed in this transaction to its initial
62
30
  * value, then commits. Must be called while this is still `inst.currentTransaction`, so that
@@ -70,35 +38,9 @@ class Transaction {
70
38
  atom.set(value);
71
39
  atom.historyBuffer?.clear();
72
40
  });
73
- const callbacks = this.abortCallbacks;
74
- this.abortCallbacks = null;
75
- this.commitCallbacks = null;
76
- let failure = null;
77
- if (callbacks) {
78
- for (let i = callbacks.length - 1; i >= 0; i--) {
79
- try {
80
- callbacks[i]();
81
- } catch (error) {
82
- failure ??= { error };
83
- }
84
- }
85
- }
86
41
  this.commit();
87
- if (failure) throw failure.error;
88
42
  }
89
43
  }
90
- function abortAfterError(txn) {
91
- try {
92
- txn.abort();
93
- } catch {
94
- }
95
- }
96
- function concatCallbacks(parent, child) {
97
- if (!child) return parent;
98
- if (!parent) return child;
99
- for (let i = 0; i < child.length; i++) parent.push(child[i]);
100
- return parent;
101
- }
102
44
  const inst = singleton("transactions", () => ({
103
45
  // The current epoch (global to all atoms).
104
46
  globalEpoch: GLOBAL_START_EPOCH + 1,
@@ -163,26 +105,6 @@ function flushChanges(atoms) {
163
105
  traverseReactors = void 0;
164
106
  }
165
107
  }
166
- function onTransactionAbort(undo) {
167
- const txn = inst.currentTransaction;
168
- if (!txn) return;
169
- if (txn.abortCallbacks) txn.abortCallbacks.push(undo);
170
- else txn.abortCallbacks = [undo];
171
- }
172
- function beforeTransactionCommit(fn) {
173
- const txn = inst.currentTransaction;
174
- if (!txn) return;
175
- if (txn.commitCallbacks) txn.commitCallbacks.push(fn);
176
- else txn.commitCallbacks = [fn];
177
- }
178
- function getValueBeforeTransaction(atom) {
179
- let value = atom.__unsafe__getWithoutCapture();
180
- for (let txn = inst.currentTransaction; txn; txn = txn.parent) {
181
- const initialValues = txn.initialAtomValues;
182
- if (initialValues.has(atom)) value = initialValues.get(atom);
183
- }
184
- return value;
185
- }
186
108
  function atomDidChange(atom, previousValue) {
187
109
  if (inst.currentTransaction) {
188
110
  if (!inst.currentTransaction.initialAtomValues.has(atom)) {
@@ -208,20 +130,12 @@ function transaction(fn) {
208
130
  try {
209
131
  result = fn(() => rollback = true);
210
132
  } catch (e) {
211
- abortAfterError(txn);
133
+ txn.abort();
212
134
  throw e;
213
135
  }
214
136
  if (inst.currentTransaction !== txn) {
215
137
  throw new Error("Transaction boundaries overlap");
216
138
  }
217
- if (!rollback) {
218
- try {
219
- if (txn.prepare()) rollback = true;
220
- } catch (e) {
221
- abortAfterError(txn);
222
- throw e;
223
- }
224
- }
225
139
  if (rollback) {
226
140
  txn.abort();
227
141
  } else {
@@ -264,21 +178,13 @@ async function deferAsyncEffects(fn) {
264
178
  }
265
179
  }
266
180
  try {
267
- let rollback = false;
268
- if (typeof error === "undefined") {
269
- try {
270
- rollback = txn.prepare();
271
- } catch (e) {
272
- error = e ?? null;
273
- }
274
- }
275
181
  if (typeof error !== "undefined") {
276
- abortAfterError(txn);
182
+ txn.abort();
277
183
  throw error;
184
+ } else {
185
+ txn.commit();
186
+ return result;
278
187
  }
279
- if (rollback) txn.abort();
280
- else txn.commit();
281
- return result;
282
188
  } finally {
283
189
  inst.currentTransaction = null;
284
190
  }
@@ -286,12 +192,9 @@ async function deferAsyncEffects(fn) {
286
192
  export {
287
193
  advanceGlobalEpoch,
288
194
  atomDidChange,
289
- beforeTransactionCommit,
290
195
  deferAsyncEffects,
291
196
  getGlobalEpoch,
292
197
  getIsInTransaction,
293
- getValueBeforeTransaction,
294
- onTransactionAbort,
295
198
  transact,
296
199
  transaction
297
200
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/transactions.ts"],
4
- "sourcesContent": ["import { _Atom, Atom } from './Atom'\nimport { GLOBAL_START_EPOCH } from './constants'\nimport { singleton } from './helpers'\nimport { Child, Signal } from './types'\n\ninterface Reactor {\n\tmaybeScheduleEffect(): void\n\tlastTraversedEpoch: number\n}\n\nclass Transaction {\n\tasyncProcessCount = 0\n\tconstructor(\n\t\tpublic readonly parent: Transaction | null,\n\t\tpublic readonly isSync: boolean\n\t) {}\n\n\tinitialAtomValues = new Map<_Atom, any>()\n\n\t// See `onTransactionAbort`. Oldest first.\n\tabortCallbacks: (() => void)[] | null = null\n\n\t// See `beforeTransactionCommit`. Oldest first.\n\tcommitCallbacks: CommitCallback[] | null = null\n\n\tcommit() {\n\t\tif (this.parent === null) {\n\t\t\t// For root transactions, flush changed atoms\n\t\t\tflushChanges(this.initialAtomValues.keys())\n\t\t\treturn\n\t\t}\n\t\t// For transactions with parents, add the transaction's initial values to the parent's, so\n\t\t// an outer rollback can still undo them (T7). This must come before any \"are we reacting?\" special case: a nested\n\t\t// transaction committed by an effect during the reaction phase used to skip this fold and\n\t\t// its changes survived the outer rollback.\n\t\t// A parent that has recorded nothing yet adopts the map outright: this transaction is\n\t\t// finished with it, and the common nested case is a single inner transaction doing all\n\t\t// the writes.\n\t\tconst parent = this.parent!\n\t\tparent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks)\n\t\tparent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks)\n\t\tconst parentValues = this.parent!.initialAtomValues\n\t\tif (parentValues.size === 0) {\n\t\t\tthis.parent!.initialAtomValues = this.initialAtomValues\n\t\t\treturn\n\t\t}\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tif (!parentValues.has(atom)) {\n\t\t\t\tparentValues.set(atom, value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Run the callbacks registered with `beforeTransactionCommit`, including any that they\n\t * register. Only a root transaction has a commit of its own to prepare for: a nested one hands\n\t * its callbacks to its parent. Returns true if a callback asked for a rollback.\n\t */\n\tprepare(): boolean {\n\t\tif (this.parent !== null) return false\n\t\tlet rollback = false\n\t\tconst requestRollback = () => {\n\t\t\trollback = true\n\t\t}\n\t\tlet passes = 0\n\t\twhile (this.commitCallbacks) {\n\t\t\tif (passes++ > 100) {\n\t\t\t\tthrow new Error('Commit callback depth limit exceeded')\n\t\t\t}\n\t\t\tconst callbacks = this.commitCallbacks\n\t\t\tthis.commitCallbacks = null\n\t\t\tfor (let i = 0; i < callbacks.length; i++) {\n\t\t\t\tcallbacks[i](requestRollback)\n\t\t\t\tif (rollback) return true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t/**\n\t * Abort the transaction. Restores every atom changed in this transaction to its initial\n\t * value, then commits. Must be called while this is still `inst.currentTransaction`, so that\n\t * the restoring sets are recorded against it instead of each flushing effects on their own.\n\t *\n\t * @public\n\t */\n\tabort() {\n\t\tinst.globalEpoch++\n\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tatom.set(value)\n\t\t\tatom.historyBuffer?.clear()\n\t\t})\n\n\t\t// Taken off before `commit`, which would otherwise hand them to the parent.\n\t\tconst callbacks = this.abortCallbacks\n\t\tthis.abortCallbacks = null\n\t\tthis.commitCallbacks = null\n\t\tlet failure: { error: unknown } | null = null\n\t\tif (callbacks) {\n\t\t\tfor (let i = callbacks.length - 1; i >= 0; i--) {\n\t\t\t\t// A throw must not skip the older callbacks: each one left out keeps its state wrong for good.\n\t\t\t\ttry {\n\t\t\t\t\tcallbacks[i]()\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailure ??= { error }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.commit()\n\t\tif (failure) throw failure.error\n\t}\n}\n\ntype CommitCallback = (rollback: () => void) => void\n\n// For an abort caused by `error`: a throw from an abort callback must not replace it.\nfunction abortAfterError(txn: Transaction) {\n\ttry {\n\t\ttxn.abort()\n\t} catch {\n\t\t// `error` is the one to report\n\t}\n}\n\nfunction concatCallbacks<T>(parent: T[] | null, child: T[] | null): T[] | null {\n\tif (!child) return parent\n\tif (!parent) return child\n\tfor (let i = 0; i < child.length; i++) parent.push(child[i])\n\treturn parent\n}\n\nconst inst = singleton('transactions', () => ({\n\t// The current epoch (global to all atoms).\n\tglobalEpoch: GLOBAL_START_EPOCH + 1,\n\t// Whether any transaction is reacting.\n\tglobalIsReacting: false,\n\tcurrentTransaction: null as Transaction | null,\n\n\tcleanupReactors: null as null | Set<Reactor>,\n}))\n\n/**\n * Gets the current global epoch, which is incremented every time any atom changes.\n * This is used to track changes across the entire reactive system.\n *\n * @returns The current global epoch number\n * @public\n */\nexport function getGlobalEpoch() {\n\treturn inst.globalEpoch\n}\n\n/**\n * Whether a transaction (sync or async) is currently open. While one is, atom changes are\n * recorded but their children are not traversed until it commits.\n *\n * @internal\n */\nexport function getIsInTransaction() {\n\treturn inst.currentTransaction !== null\n}\n\n// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a\n// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user\n// code, so nothing can re-enter and swap it mid-walk.\nlet traverseReactors: Set<Reactor>\n\nfunction traverseChild(child: Child) {\n\tif (child.lastTraversedEpoch === inst.globalEpoch) {\n\t\treturn\n\t}\n\n\tchild.lastTraversedEpoch = inst.globalEpoch\n\n\tif ('__isEffectScheduler' in child) {\n\t\ttraverseReactors.add(child as unknown as Reactor)\n\t} else {\n\t\t;(child as any as Signal<any>).children.visit(traverseChild)\n\t}\n}\n\n/**\n * Collect all of the reactors that need to run for an atom and run them. During the reaction\n * phase the affected effects are instead queued for the cleanup pass, so a change made by an\n * effect never interrupts the pass that is running (P4).\n *\n * @param atoms - The atoms to flush changes for.\n */\nfunction flushChanges(atoms: Iterable<_Atom>) {\n\tif (inst.globalIsReacting) {\n\t\tfor (const atom of atoms) {\n\t\t\ttraverseAtomForCleanup(atom)\n\t\t}\n\t\treturn\n\t}\n\n\tconst outerTxn = inst.currentTransaction\n\ttry {\n\t\t// clear the transaction stack. Transactions started by effects must be roots: the committing\n\t\t// transaction (if any) has already handed its changes to this flush.\n\t\tinst.currentTransaction = null\n\t\tinst.globalIsReacting = true\n\n\t\tconst reactors = new Set<Reactor>()\n\t\ttraverseReactors = reactors\n\t\tfor (const atom of atoms) {\n\t\t\tatom.children.visit(traverseChild)\n\t\t}\n\n\t\t// Run each reactor.\n\t\tfor (const r of reactors) {\n\t\t\tr.maybeScheduleEffect()\n\t\t}\n\n\t\tlet updateDepth = 0\n\t\twhile (inst.cleanupReactors?.size) {\n\t\t\tif (updateDepth++ > 1000) {\n\t\t\t\tthrow new Error('Reaction update depth limit exceeded')\n\t\t\t}\n\t\t\tconst reactors = inst.cleanupReactors\n\t\t\tinst.cleanupReactors = null\n\t\t\tfor (const r of reactors) {\n\t\t\t\tr.maybeScheduleEffect()\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tinst.cleanupReactors = null\n\t\tinst.globalIsReacting = false\n\t\tinst.currentTransaction = outerTxn\n\t\ttraverseReactors = undefined! // free memory\n\t}\n}\n\n/**\n * Registers `undo` to run if the current transaction, or a transaction around it, rolls back. For\n * state kept outside atoms, which a rollback would otherwise leave as it is. Callbacks run newest\n * first, after the atoms are restored and before effects are flushed. They must not throw, and\n * must not change atoms or register callbacks: the transaction is already ending. Outside\n * a transaction nothing can roll back, so this does nothing.\n *\n * @internal\n */\nexport function onTransactionAbort(undo: () => void) {\n\tconst txn = inst.currentTransaction\n\tif (!txn) return\n\tif (txn.abortCallbacks) txn.abortCallbacks.push(undo)\n\telse txn.abortCallbacks = [undo]\n}\n\n/**\n * Registers `fn` to run when the outermost transaction is about to commit: every change is made,\n * no effect has run, and nothing outside the transaction has seen it. For checks on a transaction\n * as a whole. `fn` may change atoms and register further callbacks, which run before the same\n * commit. Calling `rollback` aborts the transaction and skips the callbacks that are left, and a\n * throw aborts it and propagates. Callbacks from a transaction that aborts never run. Outside a\n * transaction this does nothing.\n *\n * @internal\n */\nexport function beforeTransactionCommit(fn: (rollback: () => void) => void) {\n\tconst txn = inst.currentTransaction\n\tif (!txn) return\n\tif (txn.commitCallbacks) txn.commitCallbacks.push(fn)\n\telse txn.commitCallbacks = [fn]\n}\n\n/**\n * The value `atom` had before the outermost open transaction changed it, which is the value it\n * goes back to if that transaction rolls back. The atom's current value when no open transaction\n * has changed it.\n *\n * @internal\n */\nexport function getValueBeforeTransaction<T>(atom: Atom<T>): T {\n\tlet value = atom.__unsafe__getWithoutCapture()\n\tfor (let txn = inst.currentTransaction; txn; txn = txn.parent) {\n\t\tconst initialValues = txn.initialAtomValues\n\t\tif (initialValues.has(atom as any)) value = initialValues.get(atom as any)\n\t}\n\treturn value\n}\n\n/** @internal */\nexport function atomDidChange(atom: _Atom, previousValue: any) {\n\tif (inst.currentTransaction) {\n\t\t// If we are in a transaction, then all we have to do is preserve\n\t\t// the value of the atom at the start of the transaction in case\n\t\t// we need to roll back. Children are not traversed until the\n\t\t// transaction commits, which is why `Computed` must not trust its\n\t\t// traversal-based cache shortcut while a transaction is open.\n\t\tif (!inst.currentTransaction.initialAtomValues.has(atom)) {\n\t\t\tinst.currentTransaction.initialAtomValues.set(atom, previousValue)\n\t\t}\n\t} else {\n\t\t// If there is no transaction, flush the changes immediately.\n\t\tflushChanges([atom])\n\t}\n}\n\nfunction traverseAtomForCleanup(atom: _Atom) {\n\ttraverseReactors = inst.cleanupReactors ??= new Set()\n\tatom.children.visit(traverseChild)\n}\n\n/** @internal */\nexport function advanceGlobalEpoch() {\n\tinst.globalEpoch++\n}\n\n/**\n * Batches state updates, deferring side effects until after the transaction completes.\n * Unlike {@link transact}, this function always creates a new transaction, allowing for nested transactions.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * })\n *\n * // Logs \"Hello, Jane Smith!\"\n * ```\n *\n * If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * throw new Error('oops')\n * })\n *\n * // firstName.get() === 'John'\n * // Logs \"Hello, John Doe!\" again: effects whose parents were changed and restored still run,\n * // and observe the restored values.\n * ```\n *\n * A `rollback` callback is passed into the function.\n * Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction((rollback) => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * rollback()\n * })\n *\n * // firstName.get() === 'John'\n * // lastName.get() === 'Doe'\n * // Logs \"Hello, John Doe!\" again, as above.\n * ```\n *\n * @param fn - The function to run in a transaction, called with a function to roll back the change.\n * @returns The return value of the function\n * @public\n */\nexport function transaction<T>(fn: (rollback: () => void) => T) {\n\tconst txn = new Transaction(inst.currentTransaction, true)\n\n\tinst.currentTransaction = txn\n\n\ttry {\n\t\tlet result = undefined as T | undefined\n\t\tlet rollback = false\n\n\t\ttry {\n\t\t\tresult = fn(() => (rollback = true))\n\t\t} catch (e) {\n\t\t\tabortAfterError(txn)\n\t\t\tthrow e\n\t\t}\n\n\t\tif (inst.currentTransaction !== txn) {\n\t\t\tthrow new Error('Transaction boundaries overlap')\n\t\t}\n\n\t\tif (!rollback) {\n\t\t\ttry {\n\t\t\t\t// Never assign: a callback can call `fn`'s own `rollback`, which `prepare` can't see.\n\t\t\t\tif (txn.prepare()) rollback = true\n\t\t\t} catch (e) {\n\t\t\t\tabortAfterError(txn)\n\t\t\t\tthrow e\n\t\t\t}\n\t\t}\n\n\t\tif (rollback) {\n\t\t\ttxn.abort()\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t}\n\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = txn.parent\n\t}\n}\n\n/**\n * Like {@link transaction}, but does not create a new transaction if there is already one in progress.\n * This is the preferred way to batch state updates when you don't need the rollback functionality.\n *\n * @example\n * ```ts\n * const count = atom('count', 0)\n * const doubled = atom('doubled', 0)\n *\n * react('update doubled', () => {\n * console.log(`Count: ${count.get()}, Doubled: ${doubled.get()}`)\n * })\n *\n * // This batches both updates into a single reaction\n * transact(() => {\n * count.set(5)\n * doubled.set(count.get() * 2)\n * })\n * // Logs: \"Count: 5, Doubled: 10\"\n * ```\n *\n * @param fn - The function to run in a transaction\n * @returns The return value of the function\n * @public\n */\nexport function transact<T>(fn: () => T): T {\n\tif (inst.currentTransaction) {\n\t\treturn fn()\n\t}\n\treturn transaction(fn)\n}\n\n/**\n * Defers the execution of asynchronous effects until they can be properly handled.\n * This function creates an asynchronous transaction context that batches state updates\n * across async operations while preventing conflicts with synchronous transactions.\n *\n * @example\n * ```ts\n * const data = atom('data', null)\n * const loading = atom('loading', false)\n *\n * await deferAsyncEffects(async () => {\n * loading.set(true)\n * const result = await fetch('/api/data')\n * const json = await result.json()\n * data.set(json)\n * loading.set(false)\n * })\n * ```\n *\n * @param fn - The async function to execute within the deferred context\n * @returns A promise that resolves to the return value of the function\n * @throws Will throw if called during a synchronous transaction\n * @internal\n */\nexport async function deferAsyncEffects<T>(fn: () => Promise<T>) {\n\t// Can't kick off async transactions during a sync transaction because\n\t// the async transaction won't finish until after the sync transaction\n\t// is done.\n\tif (inst.currentTransaction?.isSync) {\n\t\tthrow new Error('deferAsyncEffects cannot be called during a sync transaction')\n\t}\n\n\t// Can't kick off async transactions during a reaction phase at the moment,\n\t// because the transaction stack is cleared after the reaction phase.\n\t// So wait until the path ahead is clear\n\twhile (inst.globalIsReacting) {\n\t\tawait new Promise((r) => queueMicrotask(() => r(null)))\n\t}\n\n\tconst txn = inst.currentTransaction ?? new Transaction(null, false)\n\n\t// don't think this can happen, but just in case\n\tif (txn.isSync) throw new Error('deferAsyncEffects cannot be called during a sync transaction')\n\n\tinst.currentTransaction = txn\n\ttxn.asyncProcessCount++\n\n\tlet result = undefined as T | undefined\n\n\t// `undefined` means \"did not throw\"; a thrown `undefined` is stored as `null` so it still counts.\n\tlet error = undefined as any\n\ttry {\n\t\t// Run the function.\n\t\tresult = await fn()\n\t} catch (e) {\n\t\t// Abort the transaction if the function throws.\n\t\terror = e ?? null\n\t}\n\n\tif (--txn.asyncProcessCount > 0) {\n\t\t// Other processes still share this transaction; it settles when the last one finishes.\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tthrow error\n\t\t} else {\n\t\t\treturn result\n\t\t}\n\t}\n\n\t// Settle while this is still the current transaction (see `Transaction.abort`): clearing it\n\t// first made every restoring set inside `abort()` flush effects on its own, so effects\n\t// observed half-restored state.\n\ttry {\n\t\tlet rollback = false\n\t\tif (typeof error === 'undefined') {\n\t\t\ttry {\n\t\t\t\trollback = txn.prepare()\n\t\t\t} catch (e) {\n\t\t\t\terror = e ?? null\n\t\t\t}\n\t\t}\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tabortAfterError(txn)\n\t\t\tthrow error\n\t\t}\n\t\tif (rollback) txn.abort()\n\t\telse txn.commit()\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = null\n\t}\n}\n"],
5
- "mappings": "AACA,SAAS,0BAA0B;AACnC,SAAS,iBAAiB;AAQ1B,MAAM,YAAY;AAAA,EAEjB,YACiB,QACA,QACf;AAFe;AACA;AAAA,EACd;AAAA,EAFc;AAAA,EACA;AAAA,EAHjB,oBAAoB;AAAA,EAMpB,oBAAoB,oBAAI,IAAgB;AAAA;AAAA,EAGxC,iBAAwC;AAAA;AAAA,EAGxC,kBAA2C;AAAA,EAE3C,SAAS;AACR,QAAI,KAAK,WAAW,MAAM;AAEzB,mBAAa,KAAK,kBAAkB,KAAK,CAAC;AAC1C;AAAA,IACD;AAQA,UAAM,SAAS,KAAK;AACpB,WAAO,iBAAiB,gBAAgB,OAAO,gBAAgB,KAAK,cAAc;AAClF,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AAGb,MAAI,QAAQ;AACZ,MAAI;AAEH,aAAS,MAAM,GAAG;AAAA,EACnB,SAAS,GAAG;AAEX,YAAQ,KAAK;AAAA,EACd;AAEA,MAAI,EAAE,IAAI,oBAAoB,GAAG;AAEhC,QAAI,OAAO,UAAU,aAAa;AAEjC,YAAM;AAAA,IACP,OAAO;AACN,aAAO;AAAA,IACR;AAAA,EACD;AAKA,MAAI;AACH,QAAI,WAAW;AACf,QAAI,OAAO,UAAU,aAAa;AACjC,UAAI;AACH,mBAAW,IAAI,QAAQ;AAAA,MACxB,SAAS,GAAG;AACX,gBAAQ,KAAK;AAAA,MACd;AAAA,IACD;AACA,QAAI,OAAO,UAAU,aAAa;AAEjC,sBAAgB,GAAG;AACnB,YAAM;AAAA,IACP;AACA,QAAI,SAAU,KAAI,MAAM;AAAA,QACnB,KAAI,OAAO;AAChB,WAAO;AAAA,EACR,UAAE;AACD,SAAK,qBAAqB;AAAA,EAC3B;AACD;",
4
+ "sourcesContent": ["import { _Atom } from './Atom'\nimport { GLOBAL_START_EPOCH } from './constants'\nimport { singleton } from './helpers'\nimport { Child, Signal } from './types'\n\ninterface Reactor {\n\tmaybeScheduleEffect(): void\n\tlastTraversedEpoch: number\n}\n\nclass Transaction {\n\tasyncProcessCount = 0\n\tconstructor(\n\t\tpublic readonly parent: Transaction | null,\n\t\tpublic readonly isSync: boolean\n\t) {}\n\n\tinitialAtomValues = new Map<_Atom, any>()\n\n\tcommit() {\n\t\tif (this.parent === null) {\n\t\t\t// For root transactions, flush changed atoms\n\t\t\tflushChanges(this.initialAtomValues.keys())\n\t\t\treturn\n\t\t}\n\t\t// For transactions with parents, add the transaction's initial values to the parent's, so\n\t\t// an outer rollback can still undo them (T7). This must come before any \"are we reacting?\" special case: a nested\n\t\t// transaction committed by an effect during the reaction phase used to skip this fold and\n\t\t// its changes survived the outer rollback.\n\t\t// A parent that has recorded nothing yet adopts the map outright: this transaction is\n\t\t// finished with it, and the common nested case is a single inner transaction doing all\n\t\t// the writes.\n\t\tconst parentValues = this.parent!.initialAtomValues\n\t\tif (parentValues.size === 0) {\n\t\t\tthis.parent!.initialAtomValues = this.initialAtomValues\n\t\t\treturn\n\t\t}\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tif (!parentValues.has(atom)) {\n\t\t\t\tparentValues.set(atom, value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Abort the transaction. Restores every atom changed in this transaction to its initial\n\t * value, then commits. Must be called while this is still `inst.currentTransaction`, so that\n\t * the restoring sets are recorded against it instead of each flushing effects on their own.\n\t *\n\t * @public\n\t */\n\tabort() {\n\t\tinst.globalEpoch++\n\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tatom.set(value)\n\t\t\tatom.historyBuffer?.clear()\n\t\t})\n\n\t\tthis.commit()\n\t}\n}\n\nconst inst = singleton('transactions', () => ({\n\t// The current epoch (global to all atoms).\n\tglobalEpoch: GLOBAL_START_EPOCH + 1,\n\t// Whether any transaction is reacting.\n\tglobalIsReacting: false,\n\tcurrentTransaction: null as Transaction | null,\n\n\tcleanupReactors: null as null | Set<Reactor>,\n}))\n\n/**\n * Gets the current global epoch, which is incremented every time any atom changes.\n * This is used to track changes across the entire reactive system.\n *\n * @returns The current global epoch number\n * @public\n */\nexport function getGlobalEpoch() {\n\treturn inst.globalEpoch\n}\n\n/**\n * Whether a transaction (sync or async) is currently open. While one is, atom changes are\n * recorded but their children are not traversed until it commits.\n *\n * @internal\n */\nexport function getIsInTransaction() {\n\treturn inst.currentTransaction !== null\n}\n\n// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a\n// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user\n// code, so nothing can re-enter and swap it mid-walk.\nlet traverseReactors: Set<Reactor>\n\nfunction traverseChild(child: Child) {\n\tif (child.lastTraversedEpoch === inst.globalEpoch) {\n\t\treturn\n\t}\n\n\tchild.lastTraversedEpoch = inst.globalEpoch\n\n\tif ('__isEffectScheduler' in child) {\n\t\ttraverseReactors.add(child as unknown as Reactor)\n\t} else {\n\t\t;(child as any as Signal<any>).children.visit(traverseChild)\n\t}\n}\n\n/**\n * Collect all of the reactors that need to run for an atom and run them. During the reaction\n * phase the affected effects are instead queued for the cleanup pass, so a change made by an\n * effect never interrupts the pass that is running (P4).\n *\n * @param atoms - The atoms to flush changes for.\n */\nfunction flushChanges(atoms: Iterable<_Atom>) {\n\tif (inst.globalIsReacting) {\n\t\tfor (const atom of atoms) {\n\t\t\ttraverseAtomForCleanup(atom)\n\t\t}\n\t\treturn\n\t}\n\n\tconst outerTxn = inst.currentTransaction\n\ttry {\n\t\t// clear the transaction stack. Transactions started by effects must be roots: the committing\n\t\t// transaction (if any) has already handed its changes to this flush.\n\t\tinst.currentTransaction = null\n\t\tinst.globalIsReacting = true\n\n\t\tconst reactors = new Set<Reactor>()\n\t\ttraverseReactors = reactors\n\t\tfor (const atom of atoms) {\n\t\t\tatom.children.visit(traverseChild)\n\t\t}\n\n\t\t// Run each reactor.\n\t\tfor (const r of reactors) {\n\t\t\tr.maybeScheduleEffect()\n\t\t}\n\n\t\tlet updateDepth = 0\n\t\twhile (inst.cleanupReactors?.size) {\n\t\t\tif (updateDepth++ > 1000) {\n\t\t\t\tthrow new Error('Reaction update depth limit exceeded')\n\t\t\t}\n\t\t\tconst reactors = inst.cleanupReactors\n\t\t\tinst.cleanupReactors = null\n\t\t\tfor (const r of reactors) {\n\t\t\t\tr.maybeScheduleEffect()\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tinst.cleanupReactors = null\n\t\tinst.globalIsReacting = false\n\t\tinst.currentTransaction = outerTxn\n\t\ttraverseReactors = undefined! // free memory\n\t}\n}\n\n/** @internal */\nexport function atomDidChange(atom: _Atom, previousValue: any) {\n\tif (inst.currentTransaction) {\n\t\t// If we are in a transaction, then all we have to do is preserve\n\t\t// the value of the atom at the start of the transaction in case\n\t\t// we need to roll back. Children are not traversed until the\n\t\t// transaction commits, which is why `Computed` must not trust its\n\t\t// traversal-based cache shortcut while a transaction is open.\n\t\tif (!inst.currentTransaction.initialAtomValues.has(atom)) {\n\t\t\tinst.currentTransaction.initialAtomValues.set(atom, previousValue)\n\t\t}\n\t} else {\n\t\t// If there is no transaction, flush the changes immediately.\n\t\tflushChanges([atom])\n\t}\n}\n\nfunction traverseAtomForCleanup(atom: _Atom) {\n\ttraverseReactors = inst.cleanupReactors ??= new Set()\n\tatom.children.visit(traverseChild)\n}\n\n/** @internal */\nexport function advanceGlobalEpoch() {\n\tinst.globalEpoch++\n}\n\n/**\n * Batches state updates, deferring side effects until after the transaction completes.\n * Unlike {@link transact}, this function always creates a new transaction, allowing for nested transactions.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * })\n *\n * // Logs \"Hello, Jane Smith!\"\n * ```\n *\n * If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * throw new Error('oops')\n * })\n *\n * // firstName.get() === 'John'\n * // Logs \"Hello, John Doe!\" again: effects whose parents were changed and restored still run,\n * // and observe the restored values.\n * ```\n *\n * A `rollback` callback is passed into the function.\n * Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction((rollback) => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * rollback()\n * })\n *\n * // firstName.get() === 'John'\n * // lastName.get() === 'Doe'\n * // Logs \"Hello, John Doe!\" again, as above.\n * ```\n *\n * @param fn - The function to run in a transaction, called with a function to roll back the change.\n * @returns The return value of the function\n * @public\n */\nexport function transaction<T>(fn: (rollback: () => void) => T) {\n\tconst txn = new Transaction(inst.currentTransaction, true)\n\n\tinst.currentTransaction = txn\n\n\ttry {\n\t\tlet result = undefined as T | undefined\n\t\tlet rollback = false\n\n\t\ttry {\n\t\t\tresult = fn(() => (rollback = true))\n\t\t} catch (e) {\n\t\t\ttxn.abort()\n\t\t\tthrow e\n\t\t}\n\n\t\tif (inst.currentTransaction !== txn) {\n\t\t\tthrow new Error('Transaction boundaries overlap')\n\t\t}\n\n\t\tif (rollback) {\n\t\t\ttxn.abort()\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t}\n\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = txn.parent\n\t}\n}\n\n/**\n * Like {@link transaction}, but does not create a new transaction if there is already one in progress.\n * This is the preferred way to batch state updates when you don't need the rollback functionality.\n *\n * @example\n * ```ts\n * const count = atom('count', 0)\n * const doubled = atom('doubled', 0)\n *\n * react('update doubled', () => {\n * console.log(`Count: ${count.get()}, Doubled: ${doubled.get()}`)\n * })\n *\n * // This batches both updates into a single reaction\n * transact(() => {\n * count.set(5)\n * doubled.set(count.get() * 2)\n * })\n * // Logs: \"Count: 5, Doubled: 10\"\n * ```\n *\n * @param fn - The function to run in a transaction\n * @returns The return value of the function\n * @public\n */\nexport function transact<T>(fn: () => T): T {\n\tif (inst.currentTransaction) {\n\t\treturn fn()\n\t}\n\treturn transaction(fn)\n}\n\n/**\n * Defers the execution of asynchronous effects until they can be properly handled.\n * This function creates an asynchronous transaction context that batches state updates\n * across async operations while preventing conflicts with synchronous transactions.\n *\n * @example\n * ```ts\n * const data = atom('data', null)\n * const loading = atom('loading', false)\n *\n * await deferAsyncEffects(async () => {\n * loading.set(true)\n * const result = await fetch('/api/data')\n * const json = await result.json()\n * data.set(json)\n * loading.set(false)\n * })\n * ```\n *\n * @param fn - The async function to execute within the deferred context\n * @returns A promise that resolves to the return value of the function\n * @throws Will throw if called during a synchronous transaction\n * @internal\n */\nexport async function deferAsyncEffects<T>(fn: () => Promise<T>) {\n\t// Can't kick off async transactions during a sync transaction because\n\t// the async transaction won't finish until after the sync transaction\n\t// is done.\n\tif (inst.currentTransaction?.isSync) {\n\t\tthrow new Error('deferAsyncEffects cannot be called during a sync transaction')\n\t}\n\n\t// Can't kick off async transactions during a reaction phase at the moment,\n\t// because the transaction stack is cleared after the reaction phase.\n\t// So wait until the path ahead is clear\n\twhile (inst.globalIsReacting) {\n\t\tawait new Promise((r) => queueMicrotask(() => r(null)))\n\t}\n\n\tconst txn = inst.currentTransaction ?? new Transaction(null, false)\n\n\t// don't think this can happen, but just in case\n\tif (txn.isSync) throw new Error('deferAsyncEffects cannot be called during a sync transaction')\n\n\tinst.currentTransaction = txn\n\ttxn.asyncProcessCount++\n\n\tlet result = undefined as T | undefined\n\n\t// `undefined` means \"did not throw\"; a thrown `undefined` is stored as `null` so it still counts.\n\tlet error = undefined as any\n\ttry {\n\t\t// Run the function.\n\t\tresult = await fn()\n\t} catch (e) {\n\t\t// Abort the transaction if the function throws.\n\t\terror = e ?? null\n\t}\n\n\tif (--txn.asyncProcessCount > 0) {\n\t\t// Other processes still share this transaction; it settles when the last one finishes.\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tthrow error\n\t\t} else {\n\t\t\treturn result\n\t\t}\n\t}\n\n\t// Settle while this is still the current transaction (see `Transaction.abort`): clearing it\n\t// first made every restoring set inside `abort()` flush effects on its own, so effects\n\t// observed half-restored state.\n\ttry {\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\ttxn.abort()\n\t\t\tthrow error\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t\treturn result\n\t\t}\n\t} finally {\n\t\tinst.currentTransaction = null\n\t}\n}\n"],
5
+ "mappings": "AACA,SAAS,0BAA0B;AACnC,SAAS,iBAAiB;AAQ1B,MAAM,YAAY;AAAA,EAEjB,YACiB,QACA,QACf;AAFe;AACA;AAAA,EACd;AAAA,EAFc;AAAA,EACA;AAAA,EAHjB,oBAAoB;AAAA,EAMpB,oBAAoB,oBAAI,IAAgB;AAAA,EAExC,SAAS;AACR,QAAI,KAAK,WAAW,MAAM;AAEzB,mBAAa,KAAK,kBAAkB,KAAK,CAAC;AAC1C;AAAA,IACD;AAQA,UAAM,eAAe,KAAK,OAAQ;AAClC,QAAI,aAAa,SAAS,GAAG;AAC5B,WAAK,OAAQ,oBAAoB,KAAK;AACtC;AAAA,IACD;AACA,SAAK,kBAAkB,QAAQ,CAAC,OAAO,SAAS;AAC/C,UAAI,CAAC,aAAa,IAAI,IAAI,GAAG;AAC5B,qBAAa,IAAI,MAAM,KAAK;AAAA,MAC7B;AAAA,IACD,CAAC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,QAAQ;AACP,SAAK;AAEL,SAAK,kBAAkB,QAAQ,CAAC,OAAO,SAAS;AAC/C,WAAK,IAAI,KAAK;AACd,WAAK,eAAe,MAAM;AAAA,IAC3B,CAAC;AAED,SAAK,OAAO;AAAA,EACb;AACD;AAEA,MAAM,OAAO,UAAU,gBAAgB,OAAO;AAAA;AAAA,EAE7C,aAAa,qBAAqB;AAAA;AAAA,EAElC,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EAEpB,iBAAiB;AAClB,EAAE;AASK,SAAS,iBAAiB;AAChC,SAAO,KAAK;AACb;AAQO,SAAS,qBAAqB;AACpC,SAAO,KAAK,uBAAuB;AACpC;AAKA,IAAI;AA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,oBAAoB,GAAG;AAEhC,QAAI,OAAO,UAAU,aAAa;AAEjC,YAAM;AAAA,IACP,OAAO;AACN,aAAO;AAAA,IACR;AAAA,EACD;AAKA,MAAI;AACH,QAAI,OAAO,UAAU,aAAa;AAEjC,UAAI,MAAM;AACV,YAAM;AAAA,IACP,OAAO;AACN,UAAI,OAAO;AACX,aAAO;AAAA,IACR;AAAA,EACD,UAAE;AACD,SAAK,qBAAqB;AAAA,EAC3B;AACD;",
6
6
  "names": ["reactors"]
7
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tldraw/state",
3
3
  "description": "tldraw infinite canvas SDK (state).",
4
- "version": "5.8.0-canary.cd7308d44f85",
4
+ "version": "5.8.0-next.e3fedfd98025",
5
5
  "author": {
6
6
  "name": "tldraw Inc.",
7
7
  "email": "hello@tldraw.com"
@@ -44,7 +44,7 @@
44
44
  "vitest": "^5.0.0"
45
45
  },
46
46
  "dependencies": {
47
- "@tldraw/utils": "5.8.0-canary.cd7308d44f85"
47
+ "@tldraw/utils": "5.8.0-next.e3fedfd98025"
48
48
  },
49
49
  "typedoc": {
50
50
  "readmeFile": "none",
package/src/index.ts CHANGED
@@ -18,14 +18,7 @@ export type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'
18
18
  export { EMPTY_ARRAY } from './lib/helpers'
19
19
  export { isSignal } from './lib/isSignal'
20
20
  export { localStorageAtom } from './lib/localStorageAtom'
21
- export {
22
- beforeTransactionCommit,
23
- deferAsyncEffects,
24
- getValueBeforeTransaction,
25
- onTransactionAbort,
26
- transact,
27
- transaction,
28
- } from './lib/transactions'
21
+ export { deferAsyncEffects, transact, transaction } from './lib/transactions'
29
22
  export { RESET_VALUE } from './lib/types'
30
23
  export type { Child, ComputeDiff, Signal } from './lib/types'
31
24
 
@@ -3,7 +3,7 @@ import { vi } from 'vitest'
3
3
  import { atom } from '../Atom'
4
4
  import { computed } from '../Computed'
5
5
  import { react } from '../EffectScheduler'
6
- import { beforeTransactionCommit, deferAsyncEffects, transact, transaction } from '../transactions'
6
+ import { deferAsyncEffects, transact, transaction } from '../transactions'
7
7
 
8
8
  // Tests for SPEC.md §12 (async transactions: deferAsyncEffects).
9
9
  // Rule IDs like [AT3] in test names refer to that document.
@@ -253,23 +253,3 @@ describe('deferAsyncEffects (AT)', () => {
253
253
  await expect(deferAsyncEffects(async () => 'value')).resolves.toBe('value')
254
254
  })
255
255
  })
256
-
257
- describe('beforeTransactionCommit in an async transaction (T12)', () => {
258
- it('runs when the async transaction settles, and can roll it back', async () => {
259
- const a = atom('', 0)
260
- const seen: number[] = []
261
-
262
- await deferAsyncEffects(async () => {
263
- a.set(1)
264
- beforeTransactionCommit((rollback) => {
265
- seen.push(a.get())
266
- rollback()
267
- })
268
- await sleep(1)
269
- a.set(2)
270
- })
271
-
272
- expect(seen).toEqual([2])
273
- expect(a.get()).toBe(0)
274
- })
275
- })
@@ -1,13 +1,7 @@
1
1
  import { atom } from '../Atom'
2
2
  import { computed } from '../Computed'
3
3
  import { react } from '../EffectScheduler'
4
- import {
5
- beforeTransactionCommit,
6
- getGlobalEpoch,
7
- onTransactionAbort,
8
- transact,
9
- transaction,
10
- } from '../transactions'
4
+ import { getGlobalEpoch, transact, transaction } from '../transactions'
11
5
 
12
6
  // Tests for SPEC.md §11 (transactions), plus rule EP6.
13
7
  // Rule IDs like [T4] in test names refer to that document.
@@ -269,128 +263,3 @@ describe('transact (T)', () => {
269
263
  expect.assertions(3)
270
264
  })
271
265
  })
272
-
273
- describe('beforeTransactionCommit (T12)', () => {
274
- it('runs once when the outermost transaction is about to commit, before effects', () => {
275
- const a = atom('', 0)
276
- const seenByEffect: number[] = []
277
- react('', () => void seenByEffect.push(a.get()))
278
- const log: string[] = []
279
-
280
- transaction(() => {
281
- transaction(() => {
282
- a.set(1)
283
- beforeTransactionCommit(() => log.push(`commit ${a.get()}, effect saw ${seenByEffect}`))
284
- })
285
- log.push('inner committed')
286
- a.set(2)
287
- })
288
-
289
- expect(log).toEqual(['inner committed', 'commit 2, effect saw 0'])
290
- expect(seenByEffect).toEqual([0, 2])
291
- })
292
-
293
- it('does not run callbacks from a transaction that aborts', () => {
294
- const ran = vi.fn()
295
- transaction(() => {
296
- transaction((rollback) => {
297
- beforeTransactionCommit(ran)
298
- rollback()
299
- })
300
- })
301
- expect(() =>
302
- transaction(() => {
303
- beforeTransactionCommit(ran)
304
- throw new Error('boom')
305
- })
306
- ).toThrow('boom')
307
- expect(ran).not.toHaveBeenCalled()
308
- })
309
-
310
- it('runs callbacks registered by a callback, and commits what callbacks change', () => {
311
- const a = atom('', 0)
312
- transaction(() => {
313
- beforeTransactionCommit(() => {
314
- a.set(1)
315
- beforeTransactionCommit(() => a.set(a.get() + 1))
316
- })
317
- })
318
- expect(a.get()).toBe(2)
319
- })
320
-
321
- it.each([
322
- ['rollback', (rollback: () => void) => rollback(), undefined],
323
- [
324
- 'a throw',
325
- () => {
326
- throw new Error('boom')
327
- },
328
- 'boom',
329
- ],
330
- ])('aborts the whole transaction on %s', (_name, refuse, error) => {
331
- const a = atom('', 0)
332
- const aborted = vi.fn()
333
- const later = vi.fn()
334
- const run = () =>
335
- transaction(() => {
336
- a.set(1)
337
- onTransactionAbort(aborted)
338
- beforeTransactionCommit(refuse)
339
- beforeTransactionCommit(later)
340
- return 'result'
341
- })
342
-
343
- if (error) expect(run).toThrow(error)
344
- else expect(run()).toBe('result')
345
-
346
- expect(a.get()).toBe(0)
347
- expect(aborted).toHaveBeenCalledTimes(1)
348
- expect(later).not.toHaveBeenCalled()
349
- })
350
-
351
- it("aborts when a callback calls the transaction's own rollback", () => {
352
- const a = atom('', 0)
353
- const later = vi.fn()
354
- transaction((rollback) => {
355
- a.set(1)
356
- beforeTransactionCommit(() => rollback())
357
- beforeTransactionCommit(later)
358
- })
359
- expect(a.get()).toBe(0)
360
- expect(later).toHaveBeenCalledTimes(1)
361
- })
362
-
363
- it('runs every abort callback when one throws, then rethrows the first error', () => {
364
- const a = atom('', 0)
365
- const older = vi.fn()
366
- expect(() =>
367
- transaction((rollback) => {
368
- a.set(1)
369
- onTransactionAbort(older)
370
- onTransactionAbort(() => {
371
- throw new Error('second')
372
- })
373
- onTransactionAbort(() => {
374
- throw new Error('first')
375
- })
376
- rollback()
377
- })
378
- ).toThrow('first')
379
- expect(a.get()).toBe(0)
380
- expect(older).toHaveBeenCalledTimes(1)
381
- })
382
-
383
- it('keeps the original error when an abort callback also throws', () => {
384
- const older = vi.fn()
385
- expect(() =>
386
- transaction(() => {
387
- onTransactionAbort(older)
388
- onTransactionAbort(() => {
389
- throw new Error('callback')
390
- })
391
- throw new Error('original')
392
- })
393
- ).toThrow('original')
394
- expect(older).toHaveBeenCalledTimes(1)
395
- })
396
- })
@@ -1,4 +1,4 @@
1
- import { _Atom, Atom } from './Atom'
1
+ import { _Atom } from './Atom'
2
2
  import { GLOBAL_START_EPOCH } from './constants'
3
3
  import { singleton } from './helpers'
4
4
  import { Child, Signal } from './types'
@@ -17,12 +17,6 @@ class Transaction {
17
17
 
18
18
  initialAtomValues = new Map<_Atom, any>()
19
19
 
20
- // See `onTransactionAbort`. Oldest first.
21
- abortCallbacks: (() => void)[] | null = null
22
-
23
- // See `beforeTransactionCommit`. Oldest first.
24
- commitCallbacks: CommitCallback[] | null = null
25
-
26
20
  commit() {
27
21
  if (this.parent === null) {
28
22
  // For root transactions, flush changed atoms
@@ -36,9 +30,6 @@ class Transaction {
36
30
  // A parent that has recorded nothing yet adopts the map outright: this transaction is
37
31
  // finished with it, and the common nested case is a single inner transaction doing all
38
32
  // the writes.
39
- const parent = this.parent!
40
- parent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks)
41
- parent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks)
42
33
  const parentValues = this.parent!.initialAtomValues
43
34
  if (parentValues.size === 0) {
44
35
  this.parent!.initialAtomValues = this.initialAtomValues
@@ -51,32 +42,6 @@ class Transaction {
51
42
  })
52
43
  }
53
44
 
54
- /**
55
- * Run the callbacks registered with `beforeTransactionCommit`, including any that they
56
- * register. Only a root transaction has a commit of its own to prepare for: a nested one hands
57
- * its callbacks to its parent. Returns true if a callback asked for a rollback.
58
- */
59
- prepare(): boolean {
60
- if (this.parent !== null) return false
61
- let rollback = false
62
- const requestRollback = () => {
63
- rollback = true
64
- }
65
- let passes = 0
66
- while (this.commitCallbacks) {
67
- if (passes++ > 100) {
68
- throw new Error('Commit callback depth limit exceeded')
69
- }
70
- const callbacks = this.commitCallbacks
71
- this.commitCallbacks = null
72
- for (let i = 0; i < callbacks.length; i++) {
73
- callbacks[i](requestRollback)
74
- if (rollback) return true
75
- }
76
- }
77
- return false
78
- }
79
-
80
45
  /**
81
46
  * Abort the transaction. Restores every atom changed in this transaction to its initial
82
47
  * value, then commits. Must be called while this is still `inst.currentTransaction`, so that
@@ -92,44 +57,10 @@ class Transaction {
92
57
  atom.historyBuffer?.clear()
93
58
  })
94
59
 
95
- // Taken off before `commit`, which would otherwise hand them to the parent.
96
- const callbacks = this.abortCallbacks
97
- this.abortCallbacks = null
98
- this.commitCallbacks = null
99
- let failure: { error: unknown } | null = null
100
- if (callbacks) {
101
- for (let i = callbacks.length - 1; i >= 0; i--) {
102
- // A throw must not skip the older callbacks: each one left out keeps its state wrong for good.
103
- try {
104
- callbacks[i]()
105
- } catch (error) {
106
- failure ??= { error }
107
- }
108
- }
109
- }
110
60
  this.commit()
111
- if (failure) throw failure.error
112
61
  }
113
62
  }
114
63
 
115
- type CommitCallback = (rollback: () => void) => void
116
-
117
- // For an abort caused by `error`: a throw from an abort callback must not replace it.
118
- function abortAfterError(txn: Transaction) {
119
- try {
120
- txn.abort()
121
- } catch {
122
- // `error` is the one to report
123
- }
124
- }
125
-
126
- function concatCallbacks<T>(parent: T[] | null, child: T[] | null): T[] | null {
127
- if (!child) return parent
128
- if (!parent) return child
129
- for (let i = 0; i < child.length; i++) parent.push(child[i])
130
- return parent
131
- }
132
-
133
64
  const inst = singleton('transactions', () => ({
134
65
  // The current epoch (global to all atoms).
135
66
  globalEpoch: GLOBAL_START_EPOCH + 1,
@@ -232,55 +163,6 @@ function flushChanges(atoms: Iterable<_Atom>) {
232
163
  }
233
164
  }
234
165
 
235
- /**
236
- * Registers `undo` to run if the current transaction, or a transaction around it, rolls back. For
237
- * state kept outside atoms, which a rollback would otherwise leave as it is. Callbacks run newest
238
- * first, after the atoms are restored and before effects are flushed. They must not throw, and
239
- * must not change atoms or register callbacks: the transaction is already ending. Outside
240
- * a transaction nothing can roll back, so this does nothing.
241
- *
242
- * @internal
243
- */
244
- export function onTransactionAbort(undo: () => void) {
245
- const txn = inst.currentTransaction
246
- if (!txn) return
247
- if (txn.abortCallbacks) txn.abortCallbacks.push(undo)
248
- else txn.abortCallbacks = [undo]
249
- }
250
-
251
- /**
252
- * Registers `fn` to run when the outermost transaction is about to commit: every change is made,
253
- * no effect has run, and nothing outside the transaction has seen it. For checks on a transaction
254
- * as a whole. `fn` may change atoms and register further callbacks, which run before the same
255
- * commit. Calling `rollback` aborts the transaction and skips the callbacks that are left, and a
256
- * throw aborts it and propagates. Callbacks from a transaction that aborts never run. Outside a
257
- * transaction this does nothing.
258
- *
259
- * @internal
260
- */
261
- export function beforeTransactionCommit(fn: (rollback: () => void) => void) {
262
- const txn = inst.currentTransaction
263
- if (!txn) return
264
- if (txn.commitCallbacks) txn.commitCallbacks.push(fn)
265
- else txn.commitCallbacks = [fn]
266
- }
267
-
268
- /**
269
- * The value `atom` had before the outermost open transaction changed it, which is the value it
270
- * goes back to if that transaction rolls back. The atom's current value when no open transaction
271
- * has changed it.
272
- *
273
- * @internal
274
- */
275
- export function getValueBeforeTransaction<T>(atom: Atom<T>): T {
276
- let value = atom.__unsafe__getWithoutCapture()
277
- for (let txn = inst.currentTransaction; txn; txn = txn.parent) {
278
- const initialValues = txn.initialAtomValues
279
- if (initialValues.has(atom as any)) value = initialValues.get(atom as any)
280
- }
281
- return value
282
- }
283
-
284
166
  /** @internal */
285
167
  export function atomDidChange(atom: _Atom, previousValue: any) {
286
168
  if (inst.currentTransaction) {
@@ -395,7 +277,7 @@ export function transaction<T>(fn: (rollback: () => void) => T) {
395
277
  try {
396
278
  result = fn(() => (rollback = true))
397
279
  } catch (e) {
398
- abortAfterError(txn)
280
+ txn.abort()
399
281
  throw e
400
282
  }
401
283
 
@@ -403,16 +285,6 @@ export function transaction<T>(fn: (rollback: () => void) => T) {
403
285
  throw new Error('Transaction boundaries overlap')
404
286
  }
405
287
 
406
- if (!rollback) {
407
- try {
408
- // Never assign: a callback can call `fn`'s own `rollback`, which `prepare` can't see.
409
- if (txn.prepare()) rollback = true
410
- } catch (e) {
411
- abortAfterError(txn)
412
- throw e
413
- }
414
- }
415
-
416
288
  if (rollback) {
417
289
  txn.abort()
418
290
  } else {
@@ -530,22 +402,14 @@ export async function deferAsyncEffects<T>(fn: () => Promise<T>) {
530
402
  // first made every restoring set inside `abort()` flush effects on its own, so effects
531
403
  // observed half-restored state.
532
404
  try {
533
- let rollback = false
534
- if (typeof error === 'undefined') {
535
- try {
536
- rollback = txn.prepare()
537
- } catch (e) {
538
- error = e ?? null
539
- }
540
- }
541
405
  if (typeof error !== 'undefined') {
542
406
  // If the rollback was triggered, abort the transaction.
543
- abortAfterError(txn)
407
+ txn.abort()
544
408
  throw error
409
+ } else {
410
+ txn.commit()
411
+ return result
545
412
  }
546
- if (rollback) txn.abort()
547
- else txn.commit()
548
- return result
549
413
  } finally {
550
414
  inst.currentTransaction = null
551
415
  }