@stream-mdx/react 0.4.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +385 -4
  2. package/README.md +141 -16
  3. package/dist/blocks-renderer-DAOBFBfi.d.ts +29 -0
  4. package/dist/blocks-renderer-DQEL1kJW.d.cts +29 -0
  5. package/dist/components/bottom-stick-scroll-area.cjs +268 -0
  6. package/dist/components/bottom-stick-scroll-area.d.cts +36 -0
  7. package/dist/components/bottom-stick-scroll-area.d.ts +36 -0
  8. package/dist/components/bottom-stick-scroll-area.mjs +249 -0
  9. package/dist/components/diff-renderer.cjs +86 -0
  10. package/dist/components/diff-renderer.d.cts +11 -0
  11. package/dist/components/diff-renderer.d.ts +11 -0
  12. package/dist/components/diff-renderer.mjs +66 -0
  13. package/dist/components/index.cjs +2879 -1295
  14. package/dist/components/index.d.cts +9 -2
  15. package/dist/components/index.d.ts +9 -2
  16. package/dist/components/index.mjs +2842 -1277
  17. package/dist/components/katex-math.cjs +220 -0
  18. package/dist/components/katex-math.d.cts +10 -0
  19. package/dist/components/katex-math.d.ts +10 -0
  20. package/dist/components/katex-math.mjs +188 -0
  21. package/dist/contexts/math-tracker.cjs +240 -521
  22. package/dist/contexts/math-tracker.mjs +235 -513
  23. package/dist/index-Cmne1yUK.d.cts +723 -0
  24. package/dist/index-D7dyyu3q.d.ts +723 -0
  25. package/dist/index.cjs +13180 -5640
  26. package/dist/index.d.cts +72 -40
  27. package/dist/index.d.ts +72 -40
  28. package/dist/index.mjs +12587 -5038
  29. package/dist/math/display-wrapper.cjs +7 -15
  30. package/dist/math/display-wrapper.d.cts +2 -2
  31. package/dist/math/display-wrapper.d.ts +2 -2
  32. package/dist/math/display-wrapper.mjs +2 -6
  33. package/dist/node-views-Bpc6Gkgl.d.cts +13 -0
  34. package/dist/node-views-DpnYdaAS.d.ts +13 -0
  35. package/dist/renderer/hooks.cjs +35 -20
  36. package/dist/renderer/hooks.d.cts +22 -1
  37. package/dist/renderer/hooks.d.ts +22 -1
  38. package/dist/renderer/hooks.mjs +27 -12
  39. package/dist/renderer/patch-batching.cjs +7 -8
  40. package/dist/renderer/patch-batching.d.cts +1 -1
  41. package/dist/renderer/patch-batching.d.ts +1 -1
  42. package/dist/renderer/patch-batching.mjs +2 -1
  43. package/dist/renderer/patch-coalescing.cjs +5 -8
  44. package/dist/renderer/patch-commit-scheduler.cjs +160 -326
  45. package/dist/renderer/patch-commit-scheduler.d.cts +28 -4
  46. package/dist/renderer/patch-commit-scheduler.d.ts +28 -4
  47. package/dist/renderer/patch-commit-scheduler.mjs +157 -318
  48. package/dist/renderer/store.cjs +3847 -1099
  49. package/dist/renderer/store.d.cts +111 -3
  50. package/dist/renderer/store.d.ts +111 -3
  51. package/dist/renderer/store.mjs +3847 -1085
  52. package/dist/renderer/virtualized-code.cjs +415 -71
  53. package/dist/renderer/virtualized-code.d.cts +24 -23
  54. package/dist/renderer/virtualized-code.d.ts +24 -23
  55. package/dist/renderer/virtualized-code.mjs +409 -62
  56. package/dist/renderer.cjs +10939 -3974
  57. package/dist/renderer.d.cts +100 -29
  58. package/dist/renderer.d.ts +100 -29
  59. package/dist/renderer.mjs +10711 -3697
  60. package/dist/server-regions-CPLHGli0.d.cts +32 -0
  61. package/dist/server-regions-mUhyoKi7.d.ts +32 -0
  62. package/dist/server.cjs +10286 -3365
  63. package/dist/server.d.cts +17 -247
  64. package/dist/server.d.ts +17 -247
  65. package/dist/server.mjs +10565 -3619
  66. package/dist/{streaming-markdown-DOc2uLiP.d.ts → streaming-markdown-yELbJxyH.d.ts} +51 -55
  67. package/dist/{streaming-markdown-D-JcByd9.d.cts → streaming-markdown-zVwFuaJG.d.cts} +51 -55
  68. package/dist/streaming-markdown.cjs +11828 -4879
  69. package/dist/streaming-markdown.d.cts +9 -2
  70. package/dist/streaming-markdown.d.ts +9 -2
  71. package/dist/streaming-markdown.mjs +11820 -4821
  72. package/dist/trusted-mdx/index.cjs +833 -0
  73. package/dist/trusted-mdx/index.d.cts +11 -0
  74. package/dist/trusted-mdx/index.d.ts +11 -0
  75. package/dist/trusted-mdx/index.mjs +807 -0
  76. package/dist/trusted-mdx/native-children-slot.cjs +45 -0
  77. package/dist/trusted-mdx/native-children-slot.d.cts +11 -0
  78. package/dist/trusted-mdx/native-children-slot.d.ts +11 -0
  79. package/dist/trusted-mdx/native-children-slot.mjs +24 -0
  80. package/dist/trusted-mdx/server.cjs +752 -0
  81. package/dist/trusted-mdx/server.d.cts +24 -0
  82. package/dist/trusted-mdx/server.d.ts +24 -0
  83. package/dist/trusted-mdx/server.mjs +724 -0
  84. package/dist/trusted-mdx-contract-ElKpkDI5.d.cts +113 -0
  85. package/dist/trusted-mdx-contract-ElKpkDI5.d.ts +113 -0
  86. package/dist/utils/inline-html.cjs +246 -147
  87. package/dist/utils/inline-html.d.cts +39 -6
  88. package/dist/utils/inline-html.d.ts +39 -6
  89. package/dist/utils/inline-html.mjs +237 -134
  90. package/package.json +52 -18
  91. package/shadcn/README.md +28 -0
  92. package/shadcn/bottom-stick-scroll-area.tsx +358 -0
  93. package/dist/index-D2MYusAM.d.cts +0 -248
  94. package/dist/index-D2MYusAM.d.ts +0 -248
  95. package/dist/mdx-client.cjs +0 -408
  96. package/dist/mdx-client.d.cts +0 -113
  97. package/dist/mdx-client.d.ts +0 -113
  98. package/dist/mdx-client.mjs +0 -369
  99. package/dist/mdx-coordinator.cjs +0 -563
  100. package/dist/mdx-coordinator.d.cts +0 -21
  101. package/dist/mdx-coordinator.d.ts +0 -21
  102. package/dist/mdx-coordinator.mjs +0 -529
  103. package/dist/renderer/node-views.cjs +0 -1642
  104. package/dist/renderer/node-views.d.cts +0 -12
  105. package/dist/renderer/node-views.d.ts +0 -12
  106. package/dist/renderer/node-views.mjs +0 -1616
@@ -6,17 +6,14 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
7
  var __export = (target, all) => {
8
8
  for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
9
+ __defProp(target, name, { get: all[name], enumerable: !0 });
10
+ }, __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from == "object" || typeof from == "function")
13
12
  for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
13
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
14
  return to;
18
15
  };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
20
17
 
21
18
  // src/renderer/patch-commit-scheduler.ts
22
19
  var patch_commit_scheduler_exports = {};
@@ -24,232 +21,172 @@ __export(patch_commit_scheduler_exports, {
24
21
  PatchCommitScheduler: () => PatchCommitScheduler
25
22
  });
26
23
  module.exports = __toCommonJS(patch_commit_scheduler_exports);
24
+ var import_patch_batching = require("@stream-mdx/core/perf/patch-batching");
27
25
 
28
26
  // src/renderer/patch-coalescing.ts
29
27
  var import_core = require("@stream-mdx/core");
30
28
 
31
29
  // src/renderer/patch-commit-scheduler.ts
32
- var DEFAULT_TIMEOUT_MS = 16;
33
- var COALESCING_DURATION_SAMPLE_LIMIT = 60;
34
- var COALESCING_DURATION_ACTIVATE_MS = 6;
35
- var COALESCING_DURATION_DEACTIVATE_MS = 4;
36
- var RETAIN_TOUCHED_IN_HISTORY = typeof process !== "undefined" && process.env ? process.env.NODE_ENV !== "production" : true;
37
- var EMPTY_TOUCHED_SET = /* @__PURE__ */ new Set();
30
+ var DEFAULT_TIMEOUT_MS = 16, COALESCING_DURATION_SAMPLE_LIMIT = 60, COALESCING_DURATION_ACTIVATE_MS = 6, COALESCING_DURATION_DEACTIVATE_MS = 4, RETAIN_TOUCHED_IN_HISTORY = typeof process < "u" && process.env ? process.env.NODE_ENV !== "production" : !0, EMPTY_TOUCHED_SET = /* @__PURE__ */ new Set();
31
+ function semanticEnvelopeKeyForPatch(patch) {
32
+ if ((0, import_patch_batching.getPatchKind)(patch) !== "semantic") return;
33
+ let meta = patch.op === "setHTML" ? patch.patchMeta : patch.meta, streamSeq = meta?.streamSeq, parseEpoch = meta?.parseEpoch, tx = meta?.tx;
34
+ if (!(typeof streamSeq != "number" || !Number.isFinite(streamSeq) || streamSeq < 0 || typeof parseEpoch != "number" || !Number.isFinite(parseEpoch) || parseEpoch < 0 || typeof tx != "number" || !Number.isFinite(tx) || tx < 0))
35
+ return `${streamSeq}/${parseEpoch}/${tx}`;
36
+ }
37
+ function shouldSkipCoalescing(patches) {
38
+ if (patches.length <= 1) return !0;
39
+ let firstEnvelopeKey, hasEnvelopeKey = !1, hasMultipleEnvelopes = !1, hasUnsequencedSemantic = !1, hasEnrichment = !1, observePatch = (patch) => {
40
+ if ((0, import_patch_batching.getPatchKind)(patch) === "enrichment") {
41
+ hasEnrichment = !0;
42
+ return;
43
+ }
44
+ let key = semanticEnvelopeKeyForPatch(patch);
45
+ if (key === void 0) {
46
+ hasUnsequencedSemantic = !0;
47
+ return;
48
+ }
49
+ hasEnvelopeKey && firstEnvelopeKey !== key && (hasMultipleEnvelopes = !0), hasEnvelopeKey || (firstEnvelopeKey = key, hasEnvelopeKey = !0);
50
+ };
51
+ for (let patch of patches)
52
+ if (patch.op === "setPropsBatch")
53
+ for (let entry of patch.entries ?? [])
54
+ !entry || !entry.at || observePatch({
55
+ op: "setProps",
56
+ at: entry.at,
57
+ props: entry.props,
58
+ meta: { ...patch.meta ?? {}, ...entry.meta ?? {} }
59
+ });
60
+ else
61
+ observePatch(patch);
62
+ return hasEnvelopeKey && (hasMultipleEnvelopes || hasUnsequencedSemantic || hasEnrichment);
63
+ }
38
64
  function getDefaultNow() {
39
- if (typeof performance !== "undefined" && typeof performance.now === "function") {
40
- return () => performance.now();
41
- }
42
- return () => Date.now();
65
+ return typeof performance < "u" && typeof performance.now == "function" ? () => performance.now() : () => Date.now();
43
66
  }
44
67
  function getDefaultRaf() {
45
- if (typeof globalThis !== "undefined") {
46
- const candidate = globalThis.requestAnimationFrame;
47
- if (typeof candidate === "function") {
68
+ if (typeof globalThis < "u") {
69
+ let candidate = globalThis.requestAnimationFrame;
70
+ if (typeof candidate == "function")
48
71
  return candidate.bind(globalThis);
49
- }
50
72
  }
51
73
  return null;
52
74
  }
53
75
  function getDefaultCancelRaf() {
54
- if (typeof globalThis !== "undefined") {
55
- const candidate = globalThis.cancelAnimationFrame;
56
- if (typeof candidate === "function") {
76
+ if (typeof globalThis < "u") {
77
+ let candidate = globalThis.cancelAnimationFrame;
78
+ if (typeof candidate == "function")
57
79
  return candidate.bind(globalThis);
58
- }
59
80
  }
60
81
  return null;
61
82
  }
62
83
  var PatchCommitScheduler = class {
63
84
  constructor(params) {
64
- this.highQueue = [];
65
- this.lowQueue = [];
66
- this.scheduled = false;
67
- this.flushing = false;
85
+ this.semanticQueue = [];
86
+ this.enrichmentHighQueue = [];
87
+ this.enrichmentLowQueue = [];
88
+ this.scheduled = !1;
89
+ this.flushing = !1;
68
90
  this.scheduledHandle = null;
69
- this.scheduledViaRaf = false;
91
+ this.scheduledViaRaf = !1;
70
92
  this.sequence = 0;
71
93
  this.idleResolvers = [];
72
- this.paused = false;
94
+ this.paused = !1;
73
95
  this.history = [];
74
96
  this.scheduleToken = 0;
75
97
  this.coalescingDurationSamples = [];
76
- this.adaptiveBudgetActive = false;
77
- this.store = params.store;
78
- this.onFlush = params.onFlush;
79
- this.frameBudgetMs = Math.max(1, params.options?.frameBudgetMs ?? 10);
80
- this.maxBatchesPerFlush = params.options?.maxBatchesPerFlush ?? 12;
81
- this.now = params.options?.now ?? getDefaultNow();
82
- this.raf = params.options?.raf ?? getDefaultRaf();
83
- this.cancelRaf = params.options?.cancelRaf ?? getDefaultCancelRaf();
84
- this.timeoutMs = Math.max(1, params.options?.timeoutMs ?? DEFAULT_TIMEOUT_MS);
85
- this.lowPriorityFrameBudgetMs = Math.max(
98
+ this.adaptiveBudgetActive = !1;
99
+ this.flushCount = 0;
100
+ this.store = params.store, this.onFlush = params.onFlush, this.isGenerationCurrent = params.isGenerationCurrent, this.frameBudgetMs = Math.max(1, params.options?.frameBudgetMs ?? 4), this.maxBatchesPerFlush = params.options?.maxBatchesPerFlush ?? 12, this.now = params.options?.now ?? getDefaultNow(), this.raf = params.options?.raf ?? getDefaultRaf(), this.cancelRaf = params.options?.cancelRaf ?? getDefaultCancelRaf(), this.timeoutMs = Math.max(1, params.options?.timeoutMs ?? DEFAULT_TIMEOUT_MS), this.lowPriorityFrameBudgetMs = Math.max(
86
101
  1,
87
102
  params.options?.lowPriorityFrameBudgetMs ?? Math.max(2, Math.floor(this.frameBudgetMs * 0.6))
88
- );
89
- this.maxLowPriorityBatchesPerFlush = params.options?.maxLowPriorityBatchesPerFlush ?? 2;
90
- this.urgentQueueThreshold = Math.max(1, params.options?.urgentQueueThreshold ?? 4);
91
- this.historyLimit = Math.max(1, params.options?.historyLimit ?? 200);
92
- const requestedBatch = params.options?.batch;
93
- if (requestedBatch === "microtask") {
94
- this.batchStrategy = "microtask";
95
- } else if (requestedBatch === "timeout") {
96
- this.batchStrategy = "timeout";
97
- } else if (requestedBatch === "rAF") {
98
- this.batchStrategy = this.raf ? "rAF" : "timeout";
99
- } else {
100
- this.batchStrategy = "microtask";
101
- }
102
- if (this.batchStrategy === "microtask" && typeof queueMicrotask !== "function") {
103
- this.batchStrategy = this.raf ? "rAF" : "timeout";
104
- }
103
+ ), this.maxLowPriorityBatchesPerFlush = params.options?.maxLowPriorityBatchesPerFlush ?? 2, this.urgentQueueThreshold = Math.max(1, params.options?.urgentQueueThreshold ?? 4), this.historyLimit = Math.max(1, params.options?.historyLimit ?? 200), this.startupMicrotaskFlushes = Math.max(0, Math.floor(params.options?.startupMicrotaskFlushes ?? 0)), this.adaptiveBudgeting = params.options?.adaptiveBudgeting ?? !0;
104
+ let requestedBatch = params.options?.batch;
105
+ requestedBatch === "microtask" ? this.batchStrategy = "microtask" : requestedBatch === "timeout" ? this.batchStrategy = "timeout" : requestedBatch === "rAF" ? this.batchStrategy = this.raf ? "rAF" : "timeout" : this.batchStrategy = this.raf ? "rAF" : "timeout", this.batchStrategy === "microtask" && typeof queueMicrotask != "function" && (this.batchStrategy = this.raf ? "rAF" : "timeout");
105
106
  }
106
107
  enqueue(input) {
107
- if (!input || !input.patches || input.patches.length === 0) {
108
+ if (!input || !input.patches || input.patches.length === 0)
108
109
  return;
109
- }
110
- if (!this.paused && !this.flushing && this.getPendingCount() >= this.urgentQueueThreshold) {
111
- this.runFlush(this.frameBudgetMs, false);
112
- }
113
- const batch = {
110
+ this.batchStrategy !== "rAF" && !this.paused && !this.flushing && this.getPendingCount() >= this.urgentQueueThreshold && this.runFlush(this.frameBudgetMs, !1);
111
+ let explicitKind = input.meta?.kind, hasExplicitKind = explicitKind === "semantic" || explicitKind === "enrichment", hasSemanticPatch = !1, hasNonInputSourcePatch = !1;
112
+ for (let patch of input.patches)
113
+ patch.op !== "appendInputSource" && (hasNonInputSourcePatch = !0), !hasExplicitKind && !hasSemanticPatch && (0, import_patch_batching.getPatchKind)(patch) === "semantic" && (hasSemanticPatch = !0);
114
+ let batch = {
114
115
  seq: ++this.sequence,
115
116
  patches: input.patches,
116
117
  meta: input.meta ?? {},
117
118
  receivedAt: input.meta?.receivedAt ?? this.now(),
119
+ kind: explicitKind === "semantic" || explicitKind === "enrichment" ? explicitKind : hasSemanticPatch ? "semantic" : "enrichment",
120
+ hasNonInputSourcePatch,
118
121
  priority: input.meta?.priority === "low" ? "low" : "high"
119
122
  };
120
- if (batch.priority === "low") {
121
- this.lowQueue.push(batch);
122
- } else {
123
- this.highQueue.push(batch);
124
- }
125
- if (!this.paused) {
126
- this.schedule();
127
- }
123
+ batch.kind === "semantic" ? (batch.priority = "high", this.semanticQueue.push(batch)) : batch.priority === "low" ? this.enrichmentLowQueue.push(batch) : this.enrichmentHighQueue.push(batch), this.paused || this.schedule();
128
124
  }
129
125
  flushAll() {
130
- if (this.highQueue.length === 0 && this.lowQueue.length === 0 && !this.flushing) {
126
+ if (this.semanticQueue.length === 0 && this.enrichmentHighQueue.length === 0 && this.enrichmentLowQueue.length === 0 && !this.flushing)
131
127
  return null;
132
- }
133
128
  this.cancelScheduled();
134
- const result = this.runFlush(Number.POSITIVE_INFINITY, true);
135
- this.maybeResolveIdle();
136
- return result;
129
+ let result = this.runFlush(Number.POSITIVE_INFINITY, !0);
130
+ return this.maybeResolveIdle(), result;
137
131
  }
138
132
  clear() {
139
- this.cancelScheduled();
140
- this.highQueue = [];
141
- this.lowQueue = [];
142
- this.flushing = false;
143
- this.coalescingDurationSamples = [];
144
- this.adaptiveBudgetActive = false;
145
- this.adaptiveHighBatchCap = void 0;
146
- this.adaptiveLowBatchCap = void 0;
147
- this.maybeResolveIdle();
133
+ this.cancelScheduled(), this.semanticQueue = [], this.enrichmentHighQueue = [], this.enrichmentLowQueue = [], this.flushing = !1, this.flushCount = 0, this.coalescingDurationSamples = [], this.adaptiveBudgetActive = !1, this.adaptiveHighBatchCap = void 0, this.adaptiveLowBatchCap = void 0, this.maybeResolveIdle();
148
134
  }
149
135
  getPendingCount() {
150
- return this.highQueue.length + this.lowQueue.length;
136
+ return this.semanticQueue.length + this.enrichmentHighQueue.length + this.enrichmentLowQueue.length;
151
137
  }
152
138
  isIdle() {
153
- return !this.flushing && !this.scheduled && this.highQueue.length === 0 && this.lowQueue.length === 0;
139
+ return !this.flushing && !this.scheduled && this.semanticQueue.length === 0 && this.enrichmentHighQueue.length === 0 && this.enrichmentLowQueue.length === 0;
154
140
  }
155
141
  awaitIdle() {
156
- if (this.isIdle()) {
157
- return Promise.resolve();
158
- }
159
- return new Promise((resolve) => {
142
+ return this.isIdle() ? Promise.resolve() : new Promise((resolve) => {
160
143
  this.idleResolvers.push(resolve);
161
144
  });
162
145
  }
163
146
  schedule() {
164
- if (this.paused) {
165
- return;
166
- }
167
- if (this.scheduled || this.flushing) {
147
+ if (this.paused || this.scheduled || this.flushing)
168
148
  return;
169
- }
170
- const token = ++this.scheduleToken;
171
- this.scheduled = true;
172
- const execute = () => {
149
+ let token = ++this.scheduleToken;
150
+ this.scheduled = !0;
151
+ let execute = () => {
173
152
  if (token !== this.scheduleToken) {
174
- this.scheduled = false;
175
- this.scheduledHandle = null;
176
- this.scheduledViaRaf = false;
177
- this.maybeResolveIdle();
153
+ this.scheduled = !1, this.scheduledHandle = null, this.scheduledViaRaf = !1, this.maybeResolveIdle();
178
154
  return;
179
155
  }
180
156
  if (this.paused) {
181
- this.scheduled = false;
182
- this.scheduledHandle = null;
183
- this.scheduledViaRaf = false;
184
- this.maybeResolveIdle();
157
+ this.scheduled = !1, this.scheduledHandle = null, this.scheduledViaRaf = !1, this.maybeResolveIdle();
185
158
  return;
186
159
  }
187
- this.scheduled = false;
188
- this.scheduledHandle = null;
189
- this.scheduledViaRaf = false;
190
- this.runFlush(this.frameBudgetMs, false);
191
- this.maybeResolveIdle();
192
- };
193
- if (this.batchStrategy === "microtask" && typeof queueMicrotask === "function") {
194
- this.scheduledViaRaf = false;
195
- this.scheduledHandle = token;
196
- queueMicrotask(execute);
197
- } else if (this.batchStrategy === "rAF" && this.raf) {
198
- this.scheduledViaRaf = true;
199
- this.scheduledHandle = this.raf(() => execute());
200
- } else {
201
- this.scheduledViaRaf = false;
202
- this.scheduledHandle = setTimeout(() => execute(), this.timeoutMs);
203
- }
160
+ this.scheduled = !1, this.scheduledHandle = null, this.scheduledViaRaf = !1, this.runFlush(this.frameBudgetMs, !1), this.maybeResolveIdle();
161
+ }, useStartupMicrotask = this.batchStrategy !== "microtask" && this.startupMicrotaskFlushes > 0 && this.flushCount < this.startupMicrotaskFlushes && typeof queueMicrotask == "function";
162
+ (this.batchStrategy === "microtask" || useStartupMicrotask) && typeof queueMicrotask == "function" ? (this.scheduledViaRaf = !1, this.scheduledHandle = token, queueMicrotask(execute)) : this.batchStrategy === "rAF" && this.raf ? (this.scheduledViaRaf = !0, this.scheduledHandle = this.raf(() => execute())) : (this.scheduledViaRaf = !1, this.scheduledHandle = setTimeout(() => execute(), this.timeoutMs));
204
163
  }
205
164
  cancelScheduled() {
206
- if (!this.scheduled) return;
207
- this.scheduleToken++;
208
- if (this.scheduledHandle !== null) {
209
- if (this.scheduledViaRaf && this.cancelRaf) {
210
- this.cancelRaf(this.scheduledHandle);
211
- } else {
212
- clearTimeout(this.scheduledHandle);
213
- }
214
- }
215
- this.scheduled = false;
216
- this.scheduledHandle = null;
217
- this.scheduledViaRaf = false;
165
+ this.scheduled && (this.scheduleToken++, this.scheduledHandle !== null && (this.scheduledViaRaf && this.cancelRaf ? this.cancelRaf(this.scheduledHandle) : clearTimeout(this.scheduledHandle)), this.scheduled = !1, this.scheduledHandle = null, this.scheduledViaRaf = !1);
218
166
  }
219
167
  runFlush(budgetMs, manual) {
220
- if (this.paused && !manual) {
221
- return null;
222
- }
223
- if (this.highQueue.length === 0 && this.lowQueue.length === 0) {
168
+ if (this.paused && !manual || this.semanticQueue.length === 0 && this.enrichmentHighQueue.length === 0 && this.enrichmentLowQueue.length === 0)
224
169
  return null;
225
- }
226
- this.flushing = true;
227
- const startedAt = this.now();
228
- const initialQueueSize = this.highQueue.length + this.lowQueue.length;
229
- const batches = [];
230
- let totalInputPatches = 0;
231
- let totalAppliedPatches = 0;
232
- let elapsed = 0;
233
- const processQueue = (queue, maxBatches, budgetLimit) => {
234
- const effectiveBudget = manual ? Number.POSITIVE_INFINITY : Math.max(0, budgetLimit ?? budgetMs);
235
- const startingBatchCount = batches.length;
236
- let consumed = 0;
237
- while (consumed < queue.length) {
238
- const next = queue[consumed];
170
+ this.flushing = !0;
171
+ let startedAt = this.now(), elapsed = 0, initialSemanticQueueSize = this.semanticQueue.length, initialEnrichmentQueueSize = this.enrichmentHighQueue.length + this.enrichmentLowQueue.length, initialQueueSize = initialSemanticQueueSize + initialEnrichmentQueueSize, batches = [], totalInputPatches = 0, totalAppliedPatches = 0, hasNonInputSourcePatch = !1, processQueue = (queue, maxBatches, budgetLimit) => {
172
+ let effectiveBudget = manual ? Number.POSITIVE_INFINITY : Math.max(0, budgetLimit ?? budgetMs), startingBatchCount = batches.length, consumed = 0;
173
+ for (; consumed < queue.length; ) {
174
+ let next = queue[consumed];
239
175
  if (!next) break;
240
- consumed += 1;
241
- const applyStart = this.now();
242
- const queueDelayMs = Math.max(0, applyStart - next.receivedAt);
243
- const { patches: coalesced, metrics: coalescingMetrics } = (0, import_core.coalescePatchesWithMetrics)(next.patches, import_core.DEFAULT_COALESCE_CONFIG);
244
- const touched = this.store.applyPatches(coalesced, {
245
- coalesced: true,
176
+ if (consumed += 1, next.meta.generation !== void 0 && this.isGenerationCurrent && !this.isGenerationCurrent(next.meta.generation)) continue;
177
+ hasNonInputSourcePatch || (hasNonInputSourcePatch = next.hasNonInputSourcePatch);
178
+ let applyStart = this.now(), queueDelayMs = Math.max(0, applyStart - next.receivedAt), coalesced, coalescingMetrics;
179
+ if (shouldSkipCoalescing(next.patches))
180
+ coalesced = next.patches;
181
+ else {
182
+ let result = (0, import_core.coalescePatchesWithMetrics)(next.patches, import_core.DEFAULT_COALESCE_CONFIG);
183
+ coalesced = result.patches, coalescingMetrics = result.metrics;
184
+ }
185
+ let touched = this.store.applyPatches(coalesced, {
186
+ coalesced: !0,
246
187
  metrics: coalescingMetrics
247
- });
248
- const durationMs = this.now() - applyStart;
249
- this.recordCoalescingDuration(coalescingMetrics?.durationMs);
250
- totalInputPatches += next.patches.length;
251
- totalAppliedPatches += coalesced.length;
252
- batches.push({
188
+ }), durationMs = this.now() - applyStart;
189
+ if (this.recordCoalescingDuration(coalescingMetrics?.durationMs), totalInputPatches += next.patches.length, totalAppliedPatches += coalesced.length, batches.push({
253
190
  tx: next.meta.tx,
254
191
  metrics: next.meta.metrics,
255
192
  patchCount: next.patches.length,
@@ -260,43 +197,30 @@ var PatchCommitScheduler = class {
260
197
  receivedAt: next.receivedAt,
261
198
  appliedAt: applyStart,
262
199
  priority: next.priority,
200
+ kind: next.kind,
263
201
  coalescing: coalescingMetrics
264
- });
265
- if (maxBatches && batches.length - startingBatchCount >= maxBatches) {
202
+ }), maxBatches && batches.length - startingBatchCount >= maxBatches || !manual && (elapsed = this.now() - startedAt, elapsed >= effectiveBudget))
266
203
  break;
267
- }
268
- if (!manual) {
269
- elapsed = this.now() - startedAt;
270
- if (elapsed >= effectiveBudget) {
271
- break;
272
- }
273
- }
274
- }
275
- if (consumed > 0) {
276
- queue.splice(0, consumed);
277
204
  }
205
+ consumed > 0 && queue.splice(0, consumed);
278
206
  };
279
- const initialHighQueueSize = this.highQueue.length;
280
- const configuredHighLimit = manual || !this.maxBatchesPerFlush ? void 0 : initialHighQueueSize > this.maxBatchesPerFlush ? void 0 : this.maxBatchesPerFlush;
281
- const highBatchLimit = this.adaptiveHighBatchCap ?? configuredHighLimit;
282
- processQueue(this.highQueue, highBatchLimit, budgetMs);
283
- if (manual) {
284
- processQueue(this.lowQueue, void 0, Number.POSITIVE_INFINITY);
285
- } else if (this.lowQueue.length > 0) {
286
- elapsed = this.now() - startedAt;
287
- const budgetForLow = Math.max(0, this.lowPriorityFrameBudgetMs - elapsed);
288
- if (budgetForLow > 0) {
289
- const initialLowQueueSize = this.lowQueue.length;
290
- const configuredLowLimit = manual || !this.maxLowPriorityBatchesPerFlush ? void 0 : initialLowQueueSize > this.maxLowPriorityBatchesPerFlush ? void 0 : this.maxLowPriorityBatchesPerFlush;
291
- const lowBatchLimit = this.adaptiveLowBatchCap ?? configuredLowLimit;
292
- processQueue(this.lowQueue, lowBatchLimit, budgetForLow);
207
+ if (processQueue(this.semanticQueue, void 0, budgetMs), this.semanticQueue.length === 0) {
208
+ let initialHighQueueSize = this.enrichmentHighQueue.length, configuredHighLimit = manual || !this.maxBatchesPerFlush || initialHighQueueSize > this.maxBatchesPerFlush ? void 0 : this.maxBatchesPerFlush, highBatchLimit = this.adaptiveBudgeting ? this.adaptiveHighBatchCap ?? configuredHighLimit : configuredHighLimit;
209
+ if (processQueue(this.enrichmentHighQueue, highBatchLimit, budgetMs), manual)
210
+ processQueue(this.enrichmentLowQueue, void 0, Number.POSITIVE_INFINITY);
211
+ else if (this.enrichmentLowQueue.length > 0) {
212
+ elapsed = this.now() - startedAt;
213
+ let budgetForLow = Math.max(0, this.lowPriorityFrameBudgetMs - elapsed), processedHigherPriorityWork = batches.length > 0;
214
+ if (budgetForLow > 0 || !processedHigherPriorityWork) {
215
+ let initialLowQueueSize = this.enrichmentLowQueue.length, configuredLowLimit = this.maxLowPriorityBatchesPerFlush ? initialLowQueueSize > this.maxLowPriorityBatchesPerFlush ? void 0 : this.maxLowPriorityBatchesPerFlush : void 0, lowBatchLimit = this.adaptiveBudgeting ? this.adaptiveLowBatchCap ?? configuredLowLimit : configuredLowLimit;
216
+ processQueue(this.enrichmentLowQueue, lowBatchLimit, budgetForLow);
217
+ }
293
218
  }
294
219
  }
295
- this.flushing = false;
296
- const completedAt = this.now();
297
- const totalDurationMs = completedAt - startedAt;
298
- const remaining = this.highQueue.length + this.lowQueue.length;
220
+ this.flushing = !1;
221
+ let completedAt = this.now(), totalDurationMs = completedAt - startedAt, remainingSemantic = this.semanticQueue.length, remainingEnrichment = this.enrichmentHighQueue.length + this.enrichmentLowQueue.length, remaining = remainingSemantic + remainingEnrichment;
299
222
  if (batches.length > 0) {
223
+ this.flushCount += 1;
300
224
  try {
301
225
  this.onFlush({
302
226
  batches,
@@ -304,54 +228,48 @@ var PatchCommitScheduler = class {
304
228
  totalAppliedPatches,
305
229
  totalDurationMs,
306
230
  remainingQueueSize: remaining,
231
+ remainingSemanticQueueSize: remainingSemantic,
232
+ remainingEnrichmentQueueSize: remainingEnrichment,
307
233
  queueDepthBefore: initialQueueSize,
234
+ semanticQueueDepthBefore: initialSemanticQueueSize,
235
+ enrichmentQueueDepthBefore: initialEnrichmentQueueSize,
308
236
  flushStartedAt: startedAt,
309
237
  flushCompletedAt: completedAt
310
- });
238
+ }, hasNonInputSourcePatch);
311
239
  } catch (error) {
312
240
  console.error("[patch-scheduler] onFlush callback failed", error);
313
241
  }
314
242
  }
315
- if (remaining > 0 && !this.paused) {
316
- this.schedule();
317
- }
318
- const coalescingStats = this.computeCoalescingDurationStats();
319
- this.updateAdaptiveBudget(coalescingStats.p95);
320
- const adaptiveState = this.snapshotAdaptiveBudget(coalescingStats.p95 ?? null);
321
- const flushResult = batches.length > 0 ? {
243
+ remaining > 0 && !this.paused && this.schedule();
244
+ let coalescingStats = this.adaptiveBudgeting ? this.computeCoalescingDurationStats() : { sampleCount: this.coalescingDurationSamples.length, p95: null };
245
+ this.adaptiveBudgeting && this.updateAdaptiveBudget(coalescingStats.p95);
246
+ let adaptiveState = this.adaptiveBudgeting ? this.snapshotAdaptiveBudget(coalescingStats.p95 ?? null) : void 0, flushResult = batches.length > 0 ? {
322
247
  batches,
323
248
  totalPatches: totalInputPatches,
324
249
  totalAppliedPatches,
325
250
  totalDurationMs,
326
251
  remainingQueueSize: remaining,
252
+ remainingSemanticQueueSize: remainingSemantic,
253
+ remainingEnrichmentQueueSize: remainingEnrichment,
327
254
  queueDepthBefore: initialQueueSize,
255
+ semanticQueueDepthBefore: initialSemanticQueueSize,
256
+ enrichmentQueueDepthBefore: initialEnrichmentQueueSize,
328
257
  flushStartedAt: startedAt,
329
258
  flushCompletedAt: completedAt,
330
259
  coalescingDurationP95: coalescingStats.p95 ?? void 0,
331
260
  coalescingDurationSampleCount: coalescingStats.sampleCount,
332
- adaptiveBudgetActive: adaptiveState.active,
261
+ adaptiveBudgetActive: adaptiveState?.active,
333
262
  adaptiveBudgetState: adaptiveState
334
263
  } : null;
335
- if (flushResult) {
336
- this.recordHistory(flushResult);
337
- }
338
- return flushResult;
264
+ return flushResult && this.recordHistory(flushResult), flushResult;
339
265
  }
340
266
  recordCoalescingDuration(value) {
341
- if (typeof value !== "number" || !Number.isFinite(value)) {
342
- return;
343
- }
344
- this.coalescingDurationSamples.push(value);
345
- if (this.coalescingDurationSamples.length > COALESCING_DURATION_SAMPLE_LIMIT) {
346
- this.coalescingDurationSamples.splice(0, this.coalescingDurationSamples.length - COALESCING_DURATION_SAMPLE_LIMIT);
347
- }
267
+ typeof value != "number" || !Number.isFinite(value) || (this.coalescingDurationSamples.push(value), this.coalescingDurationSamples.length > COALESCING_DURATION_SAMPLE_LIMIT && this.coalescingDurationSamples.splice(0, this.coalescingDurationSamples.length - COALESCING_DURATION_SAMPLE_LIMIT));
348
268
  }
349
269
  computeCoalescingDurationStats() {
350
- if (this.coalescingDurationSamples.length === 0) {
270
+ if (this.coalescingDurationSamples.length === 0)
351
271
  return { sampleCount: 0, p95: null };
352
- }
353
- const sorted = [...this.coalescingDurationSamples].sort((a, b) => a - b);
354
- const index = Math.min(sorted.length - 1, Math.max(0, Math.floor(0.95 * (sorted.length - 1))));
272
+ let sorted = [...this.coalescingDurationSamples].sort((a, b) => a - b), index = Math.min(sorted.length - 1, Math.max(0, Math.floor(0.95 * (sorted.length - 1))));
355
273
  return { sampleCount: this.coalescingDurationSamples.length, p95: sorted[index] ?? null };
356
274
  }
357
275
  snapshotAdaptiveBudget(latestP95) {
@@ -361,50 +279,32 @@ var PatchCommitScheduler = class {
361
279
  lowBatchCap: this.adaptiveLowBatchCap,
362
280
  activateThresholdMs: COALESCING_DURATION_ACTIVATE_MS,
363
281
  deactivateThresholdMs: COALESCING_DURATION_DEACTIVATE_MS,
364
- lastObservedP95: typeof latestP95 === "number" ? latestP95 : null
282
+ lastObservedP95: typeof latestP95 == "number" ? latestP95 : null
365
283
  };
366
284
  }
367
285
  updateAdaptiveBudget(p95) {
368
- if (p95 !== null && p95 > COALESCING_DURATION_ACTIVATE_MS) {
369
- if (!this.adaptiveBudgetActive) {
370
- this.adaptiveBudgetActive = true;
371
- this.adaptiveHighBatchCap = this.computeAdaptiveCap(this.maxBatchesPerFlush, 2);
372
- this.adaptiveLowBatchCap = this.computeAdaptiveCap(this.maxLowPriorityBatchesPerFlush, 1);
373
- }
374
- } else if (this.adaptiveBudgetActive && (p95 === null || p95 < COALESCING_DURATION_DEACTIVATE_MS)) {
375
- this.adaptiveBudgetActive = false;
376
- this.adaptiveHighBatchCap = void 0;
377
- this.adaptiveLowBatchCap = void 0;
378
- }
286
+ this.adaptiveBudgeting && (p95 !== null && p95 > COALESCING_DURATION_ACTIVATE_MS ? this.adaptiveBudgetActive || (this.adaptiveBudgetActive = !0, this.adaptiveHighBatchCap = this.computeAdaptiveCap(this.maxBatchesPerFlush, 2), this.adaptiveLowBatchCap = this.computeAdaptiveCap(this.maxLowPriorityBatchesPerFlush, 1)) : this.adaptiveBudgetActive && (p95 === null || p95 < COALESCING_DURATION_DEACTIVATE_MS) && (this.adaptiveBudgetActive = !1, this.adaptiveHighBatchCap = void 0, this.adaptiveLowBatchCap = void 0));
379
287
  }
380
288
  computeAdaptiveCap(configured, fallback = 1) {
381
- if (configured === void 0 || configured <= 0) {
382
- return Math.max(1, fallback);
383
- }
384
- return Math.max(1, Math.floor(configured / 2));
289
+ return configured === void 0 || configured <= 0 ? Math.max(1, fallback) : Math.max(1, Math.floor(configured / 2));
385
290
  }
386
291
  maybeResolveIdle() {
387
- if (!this.isIdle()) {
292
+ if (!this.isIdle() || this.idleResolvers.length === 0)
388
293
  return;
389
- }
390
- if (this.idleResolvers.length === 0) {
391
- return;
392
- }
393
- const pending = this.idleResolvers.slice();
294
+ let pending = this.idleResolvers.slice();
394
295
  this.idleResolvers = [];
395
- for (const resolve of pending) {
296
+ for (let resolve of pending)
396
297
  try {
397
298
  resolve();
398
299
  } catch (error) {
399
300
  console.error("[patch-scheduler] idle resolver failed", error);
400
301
  }
401
- }
402
302
  }
403
303
  recordHistory(result) {
404
- if (RETAIN_TOUCHED_IN_HISTORY) {
304
+ if (RETAIN_TOUCHED_IN_HISTORY)
405
305
  this.history.push(result);
406
- } else {
407
- const trimmed = {
306
+ else {
307
+ let trimmed = {
408
308
  ...result,
409
309
  batches: result.batches.map((batch) => ({
410
310
  ...batch,
@@ -413,100 +313,34 @@ var PatchCommitScheduler = class {
413
313
  };
414
314
  this.history.push(trimmed);
415
315
  }
416
- if (this.history.length > this.historyLimit) {
417
- this.history.splice(0, this.history.length - this.historyLimit);
418
- }
316
+ this.history.length > this.historyLimit && this.history.splice(0, this.history.length - this.historyLimit);
419
317
  }
420
318
  pause() {
421
- if (this.paused) {
422
- return;
423
- }
424
- this.paused = true;
425
- this.cancelScheduled();
319
+ this.paused || (this.paused = !0, this.cancelScheduled());
426
320
  }
427
321
  resume() {
428
- if (!this.paused) {
429
- return;
430
- }
431
- this.paused = false;
432
- if (this.getPendingCount() > 0) {
433
- this.schedule();
434
- }
322
+ this.paused && (this.paused = !1, this.getPendingCount() > 0 && this.schedule());
435
323
  }
436
324
  isPaused() {
437
325
  return this.paused;
438
326
  }
439
327
  restart() {
440
- this.cancelScheduled();
441
- this.highQueue = [];
442
- this.lowQueue = [];
443
- this.flushing = false;
444
- this.sequence = 0;
445
- this.history = [];
446
- this.scheduleToken++;
447
- this.paused = false;
448
- this.coalescingDurationSamples = [];
449
- this.adaptiveBudgetActive = false;
450
- this.adaptiveHighBatchCap = void 0;
451
- this.adaptiveLowBatchCap = void 0;
452
- this.maybeResolveIdle();
328
+ this.cancelScheduled(), this.semanticQueue = [], this.enrichmentHighQueue = [], this.enrichmentLowQueue = [], this.flushing = !1, this.sequence = 0, this.history = [], this.flushCount = 0, this.scheduleToken++, this.paused = !1, this.coalescingDurationSamples = [], this.adaptiveBudgetActive = !1, this.adaptiveHighBatchCap = void 0, this.adaptiveLowBatchCap = void 0, this.maybeResolveIdle();
453
329
  }
454
330
  getHistory(limit) {
455
- if (limit === void 0 || limit >= this.history.length) {
456
- return [...this.history];
457
- }
458
- return this.history.slice(this.history.length - limit);
331
+ return limit === void 0 || limit >= this.history.length ? [...this.history] : this.history.slice(this.history.length - limit);
459
332
  }
460
333
  setHistoryLimit(limit) {
461
- this.historyLimit = Math.max(1, limit);
462
- if (this.history.length > this.historyLimit) {
463
- this.history.splice(0, this.history.length - this.historyLimit);
464
- }
334
+ this.historyLimit = Math.max(1, limit), this.history.length > this.historyLimit && this.history.splice(0, this.history.length - this.historyLimit);
465
335
  }
466
336
  updateOptions(options) {
467
337
  if (!options) return;
468
- let shouldReschedule = false;
469
- if (typeof options.frameBudgetMs !== "undefined") {
470
- this.frameBudgetMs = Math.max(1, options.frameBudgetMs);
471
- shouldReschedule = true;
472
- }
473
- if (typeof options.maxBatchesPerFlush !== "undefined") {
474
- this.maxBatchesPerFlush = options.maxBatchesPerFlush;
475
- shouldReschedule = true;
476
- }
477
- if (typeof options.lowPriorityFrameBudgetMs !== "undefined") {
478
- this.lowPriorityFrameBudgetMs = Math.max(1, options.lowPriorityFrameBudgetMs);
479
- shouldReschedule = true;
480
- }
481
- if (typeof options.maxLowPriorityBatchesPerFlush !== "undefined") {
482
- this.maxLowPriorityBatchesPerFlush = options.maxLowPriorityBatchesPerFlush;
483
- shouldReschedule = true;
484
- }
485
- if (typeof options.urgentQueueThreshold !== "undefined") {
486
- this.urgentQueueThreshold = Math.max(1, options.urgentQueueThreshold);
487
- shouldReschedule = true;
488
- }
489
- if (typeof options.historyLimit !== "undefined") {
490
- this.setHistoryLimit(options.historyLimit);
491
- }
492
- if (typeof options.batch !== "undefined") {
493
- const requestedBatch = options.batch;
494
- if (requestedBatch === "microtask") {
495
- this.batchStrategy = "microtask";
496
- } else if (requestedBatch === "timeout") {
497
- this.batchStrategy = "timeout";
498
- } else if (requestedBatch === "rAF") {
499
- this.batchStrategy = this.raf ? "rAF" : "timeout";
500
- }
501
- if (this.batchStrategy === "microtask" && typeof queueMicrotask !== "function") {
502
- this.batchStrategy = this.raf ? "rAF" : "timeout";
503
- }
504
- shouldReschedule = true;
505
- }
506
- if (shouldReschedule && !this.paused && !this.flushing && this.getPendingCount() > 0) {
507
- this.cancelScheduled();
508
- this.schedule();
338
+ let shouldReschedule = !1;
339
+ if (typeof options.frameBudgetMs < "u" && (this.frameBudgetMs = Math.max(1, options.frameBudgetMs), shouldReschedule = !0), typeof options.maxBatchesPerFlush < "u" && (this.maxBatchesPerFlush = options.maxBatchesPerFlush, shouldReschedule = !0), typeof options.lowPriorityFrameBudgetMs < "u" && (this.lowPriorityFrameBudgetMs = Math.max(1, options.lowPriorityFrameBudgetMs), shouldReschedule = !0), typeof options.maxLowPriorityBatchesPerFlush < "u" && (this.maxLowPriorityBatchesPerFlush = options.maxLowPriorityBatchesPerFlush, shouldReschedule = !0), typeof options.urgentQueueThreshold < "u" && (this.urgentQueueThreshold = Math.max(1, options.urgentQueueThreshold), shouldReschedule = !0), typeof options.historyLimit < "u" && this.setHistoryLimit(options.historyLimit), typeof options.startupMicrotaskFlushes < "u" && (this.startupMicrotaskFlushes = Math.max(0, Math.floor(options.startupMicrotaskFlushes))), typeof options.adaptiveBudgeting < "u" && (this.adaptiveBudgeting = options.adaptiveBudgeting), typeof options.batch < "u") {
340
+ let requestedBatch = options.batch;
341
+ requestedBatch === "microtask" ? this.batchStrategy = "microtask" : requestedBatch === "timeout" ? this.batchStrategy = "timeout" : requestedBatch === "rAF" && (this.batchStrategy = this.raf ? "rAF" : "timeout"), this.batchStrategy === "microtask" && typeof queueMicrotask != "function" && (this.batchStrategy = this.raf ? "rAF" : "timeout"), shouldReschedule = !0;
509
342
  }
343
+ shouldReschedule && !this.paused && !this.flushing && this.getPendingCount() > 0 && (this.cancelScheduled(), this.schedule());
510
344
  }
511
345
  clearHistory() {
512
346
  this.history = [];