| 101 | }> | null; |
| 102 | |
| 103 | export function createEventLoop<S>(options: CreateEventLoopOptions<S>): AppEventLoop { |
| 104 | let pendingShiftTextPair: PendingShiftTextPair = null; |
| 105 | function commitUpdates(): void { |
| 106 | const drained = options.updates.drain(); |
| 107 | if (drained.length === 0) return; |
| 108 | |
| 109 | const commitToken = perfMarkStart("commit"); |
| 110 | options.setInCommit(true); |
| 111 | try { |
| 112 | let next = options.getCommittedState() as S; |
| 113 | for (const update of drained) { |
| 114 | if (typeof update === "function") { |
| 115 | next = (update as (prev: Readonly<S>) => S)(next); |
| 116 | } else { |
| 117 | next = update; |
| 118 | } |
| 119 | } |
| 120 | if (next !== options.getCommittedState()) { |
| 121 | options.setCommittedState(next); |
| 122 | options.markDirty(DIRTY_VIEW, false); |
| 123 | } |
| 124 | } catch (error: unknown) { |
| 125 | options.fatalNowOrEnqueue( |
| 126 | "ZRUI_USER_CODE_THROW", |
| 127 | `state updater threw: ${describeThrown(error)}`, |
| 128 | ); |
| 129 | } finally { |
| 130 | options.setInCommit(false); |
| 131 | perfMarkEnd("commit", commitToken); |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | function releaseOnce( |
| 136 | batch: BackendEventBatch, |
| 137 | releasedBatches: Set<BackendEventBatch>, |
| 138 | ): () => void { |
| 139 | let released = false; |
| 140 | return () => { |
| 141 | if (released) return; |
| 142 | released = true; |
| 143 | releasedBatches.add(batch); |
| 144 | try { |
| 145 | batch.release(); |
| 146 | } catch { |
| 147 | // ignore |
| 148 | } |
| 149 | }; |
| 150 | } |
| 151 | |
| 152 | function processEventBatch( |
| 153 | batch: BackendEventBatch, |
| 154 | releasedBatches: Set<BackendEventBatch>, |
| 155 | ): void { |
| 156 | const release = releaseOnce(batch, releasedBatches); |
| 157 | |
| 158 | const parseToken = perfMarkStart("event_parse"); |
| 159 | const parsed = parseEventBatchV1(batch.bytes, { |
| 160 | maxTotalSize: options.config.maxEventBytes, |