@three-flatland/devtools 0.1.0-alpha.3

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 (148) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +82 -0
  3. package/dist/buffers-modal.cjs +491 -0
  4. package/dist/buffers-modal.cjs.map +1 -0
  5. package/dist/buffers-modal.d.cts +62 -0
  6. package/dist/buffers-modal.d.ts +62 -0
  7. package/dist/buffers-modal.js +467 -0
  8. package/dist/buffers-modal.js.map +1 -0
  9. package/dist/buffers-view.cjs +269 -0
  10. package/dist/buffers-view.cjs.map +1 -0
  11. package/dist/buffers-view.d.cts +39 -0
  12. package/dist/buffers-view.d.ts +39 -0
  13. package/dist/buffers-view.js +245 -0
  14. package/dist/buffers-view.js.map +1 -0
  15. package/dist/create-pane.cjs +203 -0
  16. package/dist/create-pane.cjs.map +1 -0
  17. package/dist/create-pane.d.cts +66 -0
  18. package/dist/create-pane.d.ts +66 -0
  19. package/dist/create-pane.js +178 -0
  20. package/dist/create-pane.js.map +1 -0
  21. package/dist/dashboard/app.tsx +42 -0
  22. package/dist/dashboard/client.ts +21 -0
  23. package/dist/dashboard/export.ts +84 -0
  24. package/dist/dashboard/hooks.ts +75 -0
  25. package/dist/dashboard/index.html +1149 -0
  26. package/dist/dashboard/index.tsx +18 -0
  27. package/dist/dashboard/panels/batches.tsx +282 -0
  28. package/dist/dashboard/panels/buffers.tsx +425 -0
  29. package/dist/dashboard/panels/env.tsx +85 -0
  30. package/dist/dashboard/panels/header-stats.tsx +30 -0
  31. package/dist/dashboard/panels/producer-select.tsx +81 -0
  32. package/dist/dashboard/panels/protocol-log.tsx +743 -0
  33. package/dist/dashboard/panels/registry.tsx +642 -0
  34. package/dist/dashboard/panels/stats.tsx +431 -0
  35. package/dist/dashboard/protocol-store.ts +312 -0
  36. package/dist/dashboard/tsconfig.json +19 -0
  37. package/dist/dashboard/vendor/hooks.module.js +1 -0
  38. package/dist/dashboard/vendor/jsx-runtime.js +22 -0
  39. package/dist/dashboard/vendor/preact.module.js +12 -0
  40. package/dist/devtools-client.cjs +870 -0
  41. package/dist/devtools-client.cjs.map +1 -0
  42. package/dist/devtools-client.d.cts +362 -0
  43. package/dist/devtools-client.d.ts +362 -0
  44. package/dist/devtools-client.js +852 -0
  45. package/dist/devtools-client.js.map +1 -0
  46. package/dist/index.cjs +42 -0
  47. package/dist/index.cjs.map +1 -0
  48. package/dist/index.d.cts +8 -0
  49. package/dist/index.d.ts +8 -0
  50. package/dist/index.js +13 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/perf-trace.cjs +103 -0
  53. package/dist/perf-trace.cjs.map +1 -0
  54. package/dist/perf-trace.d.cts +27 -0
  55. package/dist/perf-trace.d.ts +27 -0
  56. package/dist/perf-trace.js +79 -0
  57. package/dist/perf-trace.js.map +1 -0
  58. package/dist/plugins.cjs +44 -0
  59. package/dist/plugins.cjs.map +1 -0
  60. package/dist/plugins.d.cts +7 -0
  61. package/dist/plugins.d.ts +7 -0
  62. package/dist/plugins.js +9 -0
  63. package/dist/plugins.js.map +1 -0
  64. package/dist/provider-switcher.cjs +95 -0
  65. package/dist/provider-switcher.cjs.map +1 -0
  66. package/dist/provider-switcher.d.cts +18 -0
  67. package/dist/provider-switcher.d.ts +18 -0
  68. package/dist/provider-switcher.js +71 -0
  69. package/dist/provider-switcher.js.map +1 -0
  70. package/dist/react/devtools-provider.cjs +59 -0
  71. package/dist/react/devtools-provider.cjs.map +1 -0
  72. package/dist/react/devtools-provider.d.cts +39 -0
  73. package/dist/react/devtools-provider.d.ts +39 -0
  74. package/dist/react/devtools-provider.js +38 -0
  75. package/dist/react/devtools-provider.js.map +1 -0
  76. package/dist/react/use-fps-graph.cjs +49 -0
  77. package/dist/react/use-fps-graph.cjs.map +1 -0
  78. package/dist/react/use-fps-graph.d.cts +15 -0
  79. package/dist/react/use-fps-graph.d.ts +15 -0
  80. package/dist/react/use-fps-graph.js +25 -0
  81. package/dist/react/use-fps-graph.js.map +1 -0
  82. package/dist/react/use-pane-button.cjs +58 -0
  83. package/dist/react/use-pane-button.cjs.map +1 -0
  84. package/dist/react/use-pane-button.d.cts +10 -0
  85. package/dist/react/use-pane-button.d.ts +10 -0
  86. package/dist/react/use-pane-button.js +34 -0
  87. package/dist/react/use-pane-button.js.map +1 -0
  88. package/dist/react/use-pane-folder.cjs +48 -0
  89. package/dist/react/use-pane-folder.cjs.map +1 -0
  90. package/dist/react/use-pane-folder.d.cts +15 -0
  91. package/dist/react/use-pane-folder.d.ts +15 -0
  92. package/dist/react/use-pane-folder.js +24 -0
  93. package/dist/react/use-pane-folder.js.map +1 -0
  94. package/dist/react/use-pane-input.cjs +70 -0
  95. package/dist/react/use-pane-input.cjs.map +1 -0
  96. package/dist/react/use-pane-input.d.cts +44 -0
  97. package/dist/react/use-pane-input.d.ts +44 -0
  98. package/dist/react/use-pane-input.js +46 -0
  99. package/dist/react/use-pane-input.js.map +1 -0
  100. package/dist/react/use-pane-radio-grid.cjs +78 -0
  101. package/dist/react/use-pane-radio-grid.cjs.map +1 -0
  102. package/dist/react/use-pane-radio-grid.d.cts +35 -0
  103. package/dist/react/use-pane-radio-grid.d.ts +35 -0
  104. package/dist/react/use-pane-radio-grid.js +54 -0
  105. package/dist/react/use-pane-radio-grid.js.map +1 -0
  106. package/dist/react/use-pane.cjs +45 -0
  107. package/dist/react/use-pane.cjs.map +1 -0
  108. package/dist/react/use-pane.d.cts +40 -0
  109. package/dist/react/use-pane.d.ts +40 -0
  110. package/dist/react/use-pane.js +21 -0
  111. package/dist/react/use-pane.js.map +1 -0
  112. package/dist/react.cjs +50 -0
  113. package/dist/react.cjs.map +1 -0
  114. package/dist/react.d.cts +12 -0
  115. package/dist/react.d.ts +12 -0
  116. package/dist/react.js +19 -0
  117. package/dist/react.js.map +1 -0
  118. package/dist/registry-view.cjs +371 -0
  119. package/dist/registry-view.cjs.map +1 -0
  120. package/dist/registry-view.d.cts +24 -0
  121. package/dist/registry-view.d.ts +24 -0
  122. package/dist/registry-view.js +347 -0
  123. package/dist/registry-view.js.map +1 -0
  124. package/dist/stats-graph.cjs +297 -0
  125. package/dist/stats-graph.cjs.map +1 -0
  126. package/dist/stats-graph.d.cts +40 -0
  127. package/dist/stats-graph.d.ts +40 -0
  128. package/dist/stats-graph.js +273 -0
  129. package/dist/stats-graph.js.map +1 -0
  130. package/dist/stats-row.cjs +153 -0
  131. package/dist/stats-row.cjs.map +1 -0
  132. package/dist/stats-row.d.cts +24 -0
  133. package/dist/stats-row.d.ts +24 -0
  134. package/dist/stats-row.js +129 -0
  135. package/dist/stats-row.js.map +1 -0
  136. package/dist/theme.cjs +260 -0
  137. package/dist/theme.cjs.map +1 -0
  138. package/dist/theme.d.cts +10 -0
  139. package/dist/theme.d.ts +10 -0
  140. package/dist/theme.js +235 -0
  141. package/dist/theme.js.map +1 -0
  142. package/dist/vite-plugin.cjs +113 -0
  143. package/dist/vite-plugin.cjs.map +1 -0
  144. package/dist/vite-plugin.d.cts +9 -0
  145. package/dist/vite-plugin.d.ts +9 -0
  146. package/dist/vite-plugin.js +88 -0
  147. package/dist/vite-plugin.js.map +1 -0
  148. package/package.json +124 -0
@@ -0,0 +1,852 @@
1
+ import {
2
+ ACK_INTERVAL_MS,
3
+ DEBUG_PROTOCOL_VERSION,
4
+ DISCOVERY_CHANNEL,
5
+ SERVER_LIVENESS_MS,
6
+ providerChannelName
7
+ } from "three-flatland/debug-protocol";
8
+ import { tracePerf } from "./perf-trace.js";
9
+ const QUERY_RETRY_MIN_MS = 500;
10
+ const QUERY_RETRY_MAX_MS = 5e3;
11
+ const QUERY_MAX_RETRIES = 10;
12
+ const CLIENT_SERIES_SIZE = 1024;
13
+ const EMPTY_SAMPLE = new Float32Array(0);
14
+ class DevtoolsClient {
15
+ id;
16
+ state;
17
+ /** Shared discovery bus — carries query/announce/gone only. */
18
+ _discoveryBus;
19
+ /** Per-provider data bus. Opened when we subscribe; closed on switch / gone. */
20
+ _dataBus = null;
21
+ /** Bound handler for the current `_dataBus`. Tracked so we can detach on close. */
22
+ _dataHandler = null;
23
+ _features;
24
+ /**
25
+ * Registry entry filter. `null` = all entries; `string[]` = only
26
+ * these. Starts empty-array so providers don't drain (sometimes
27
+ * expensive) registry payloads until the pane actually needs them.
28
+ */
29
+ _registrySelection = [];
30
+ /**
31
+ * Buffer subscription. Map of entry-name → { mode, thumbSize? }.
32
+ * Empty map = metadata-only (consumer is connected to the `buffers`
33
+ * feature but isn't actually watching anything — provider skips all
34
+ * readbacks). `null` is not a distinct state; represented by `{}`.
35
+ */
36
+ _buffersSelection = {};
37
+ _listeners = /* @__PURE__ */ new Set();
38
+ _chunkListeners = /* @__PURE__ */ new Set();
39
+ _rawMessageListeners = /* @__PURE__ */ new Set();
40
+ _ackTimer = null;
41
+ _livenessTimer = null;
42
+ _queryRetryTimer = null;
43
+ _lastServerAt = 0;
44
+ _subscribed = false;
45
+ _disposed = false;
46
+ /** Known providers by id — updated live via `provider:announce` + `provider:gone`. */
47
+ _providers = /* @__PURE__ */ new Map();
48
+ constructor(options) {
49
+ this.id = generateUuid();
50
+ this._features = [...options.features];
51
+ if (options.onChange) this._listeners.add(options.onChange);
52
+ this._discoveryBus = new BroadcastChannel(options.discoveryChannelName ?? DISCOVERY_CHANNEL);
53
+ const mkSeries = () => ({
54
+ data: new Float32Array(CLIENT_SERIES_SIZE),
55
+ write: 0,
56
+ length: 0
57
+ });
58
+ this.state = {
59
+ series: {
60
+ fps: mkSeries(),
61
+ cpuMs: mkSeries(),
62
+ gpuMs: mkSeries(),
63
+ heapUsedMB: mkSeries(),
64
+ drawCalls: mkSeries(),
65
+ triangles: mkSeries(),
66
+ primitives: mkSeries(),
67
+ geometries: mkSeries(),
68
+ textures: mkSeries()
69
+ },
70
+ registry: /* @__PURE__ */ new Map(),
71
+ buffers: /* @__PURE__ */ new Map(),
72
+ batches: { frame: 0, passes: [], batches: [] },
73
+ providers: [],
74
+ selectedProviderId: null,
75
+ serverAlive: false,
76
+ serverLagMs: 0
77
+ };
78
+ this._discoveryBus.addEventListener("message", (ev) => {
79
+ this._onDiscoveryMessage(ev.data);
80
+ });
81
+ }
82
+ /**
83
+ * Begin discovery + subscription. Sends a `provider:query`, waits
84
+ * `DISCOVERY_WINDOW_MS` for `provider:announce` responses, then picks
85
+ * the best provider (user > system) and subscribes to it.
86
+ *
87
+ * Idempotent — calling again while already started is a no-op.
88
+ */
89
+ start() {
90
+ if (this._disposed || this._subscribed) return;
91
+ this._subscribed = true;
92
+ this._sendQuery();
93
+ let retries = 0;
94
+ let nextDelay = QUERY_RETRY_MIN_MS;
95
+ const tick = () => {
96
+ if (this._disposed || this.state.selectedProviderId !== null) {
97
+ this._queryRetryTimer = null;
98
+ return;
99
+ }
100
+ if (retries >= QUERY_MAX_RETRIES) {
101
+ this._queryRetryTimer = null;
102
+ return;
103
+ }
104
+ retries++;
105
+ this._sendQuery();
106
+ nextDelay = Math.min(nextDelay * 2, QUERY_RETRY_MAX_MS);
107
+ this._queryRetryTimer = setTimeout(tick, nextDelay);
108
+ };
109
+ this._queryRetryTimer = setTimeout(tick, nextDelay);
110
+ this._livenessTimer = setInterval(() => this._checkLiveness(), 1e3);
111
+ }
112
+ _sendQuery() {
113
+ this._postDiscovery({
114
+ type: "provider:query",
115
+ payload: { requesterId: this.id }
116
+ });
117
+ }
118
+ /**
119
+ * Update the feature set. Re-posts `subscribe` on the current
120
+ * provider's data channel.
121
+ */
122
+ setFeatures(features) {
123
+ if (sameSet(this._features, features)) return;
124
+ this._features = [...features];
125
+ this._resubscribe();
126
+ }
127
+ /**
128
+ * Update the registry entry filter. Pass `null` for "every entry",
129
+ * `[]` to stop all registry traffic, or a list of names to narrow.
130
+ * Re-posts `subscribe` if the filter actually changed.
131
+ */
132
+ /**
133
+ * Narrow which registry entries the provider should ship samples
134
+ * for. `null` = all entries; `[]` = none; `[name, …]` = only these.
135
+ * Metadata still flows regardless — only sample bytes are gated.
136
+ */
137
+ setRegistry(names) {
138
+ if (sameFilter(this._registrySelection, names)) return;
139
+ this._registrySelection = names === null ? null : [...names];
140
+ this._resubscribe();
141
+ }
142
+ /**
143
+ * Update the buffer subscription. Map of entry-name → (mode, thumbSize?).
144
+ * - Empty map / missing names → metadata-only (provider sends no pixels,
145
+ * runs no readbacks). This is the idle state when no preview or
146
+ * modal is visible.
147
+ * - `{ name: { mode: 'thumbnail', thumbSize: 256 } }` → small
148
+ * downsampled preview. Use when a thumbnail card is visible.
149
+ * - `{ name: { mode: 'stream' } }` → full-size VP9 video stream.
150
+ * Use when the fullscreen modal is open.
151
+ *
152
+ * Mode changes (incl. unsubscribing) take effect on the next
153
+ * provider flush; the producer will drop old readbacks immediately.
154
+ */
155
+ setBuffers(subscription) {
156
+ if (sameBufferSubscription(this._buffersSelection, subscription)) return;
157
+ this._buffersSelection = { ...subscription };
158
+ this._resubscribe();
159
+ }
160
+ _resubscribe() {
161
+ if (this._subscribed && this._dataBus !== null) {
162
+ const hasBuffers = Object.keys(this._buffersSelection).length > 0;
163
+ this._postData({
164
+ type: "subscribe",
165
+ payload: {
166
+ id: this.id,
167
+ features: this._features,
168
+ registry: this._registrySelection ?? void 0,
169
+ buffers: hasBuffers ? this._buffersSelection : void 0
170
+ }
171
+ });
172
+ }
173
+ }
174
+ /**
175
+ * Manually switch to a different provider. No-op if unknown or if
176
+ * already selected. Closes the old data channel and opens the new one.
177
+ */
178
+ selectProvider(providerId) {
179
+ if (!this._providers.has(providerId)) return;
180
+ if (this.state.selectedProviderId === providerId) return;
181
+ this._leaveDataChannel();
182
+ this.state.selectedProviderId = providerId;
183
+ this._resetAccumulatedState();
184
+ this._joinDataChannel(providerId);
185
+ this._postData({
186
+ type: "subscribe",
187
+ payload: {
188
+ id: this.id,
189
+ features: this._features,
190
+ registry: this._registrySelection ?? void 0,
191
+ buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
192
+ }
193
+ });
194
+ this._fire();
195
+ }
196
+ dispose() {
197
+ if (this._disposed) return;
198
+ this._disposed = true;
199
+ this._leaveDataChannel();
200
+ this._subscribed = false;
201
+ if (this._ackTimer !== null) {
202
+ clearInterval(this._ackTimer);
203
+ this._ackTimer = null;
204
+ }
205
+ if (this._livenessTimer !== null) {
206
+ clearInterval(this._livenessTimer);
207
+ this._livenessTimer = null;
208
+ }
209
+ if (this._queryRetryTimer !== null) {
210
+ clearTimeout(this._queryRetryTimer);
211
+ this._queryRetryTimer = null;
212
+ }
213
+ try {
214
+ this._discoveryBus.close();
215
+ } catch {
216
+ }
217
+ }
218
+ /**
219
+ * Open a fresh per-provider data channel and start listening on it.
220
+ * Caller is responsible for posting the initial `subscribe`.
221
+ */
222
+ _joinDataChannel(providerId) {
223
+ this._dataBus = new BroadcastChannel(providerChannelName(providerId));
224
+ this._dataHandler = (ev) => {
225
+ this._onDataMessage(ev.data);
226
+ };
227
+ this._dataBus.addEventListener("message", this._dataHandler);
228
+ }
229
+ /**
230
+ * Send `unsubscribe` (if we have someone to tell) and close the data
231
+ * channel. Idempotent — safe to call when there's no active channel.
232
+ */
233
+ _leaveDataChannel() {
234
+ if (this._dataBus !== null) {
235
+ if (this._subscribed) {
236
+ try {
237
+ this._postData({ type: "unsubscribe", payload: { id: this.id } });
238
+ } catch {
239
+ }
240
+ }
241
+ if (this._dataHandler !== null) {
242
+ try {
243
+ this._dataBus.removeEventListener("message", this._dataHandler);
244
+ } catch {
245
+ }
246
+ }
247
+ try {
248
+ this._dataBus.close();
249
+ } catch {
250
+ }
251
+ this._dataBus = null;
252
+ this._dataHandler = null;
253
+ }
254
+ }
255
+ // ── Internal ──────────────────────────────────────────────────────────
256
+ /**
257
+ * Handler for the shared discovery bus. Only discovery messages land
258
+ * here by protocol; anything else is ignored.
259
+ */
260
+ _onDiscoveryMessage(msg) {
261
+ if (!msg || typeof msg !== "object" || !("type" in msg)) return;
262
+ tracePerf(msg);
263
+ switch (msg.type) {
264
+ case "provider:announce": {
265
+ const id = msg.payload.identity.id;
266
+ this._providers.set(id, msg.payload.identity);
267
+ this.state.providers = Array.from(this._providers.values());
268
+ this._fire();
269
+ if (this.state.selectedProviderId === null) this._pickProviderAndSubscribe();
270
+ break;
271
+ }
272
+ case "provider:gone": {
273
+ const id = msg.payload.id;
274
+ if (!this._providers.has(id)) return;
275
+ this._providers.delete(id);
276
+ this.state.providers = Array.from(this._providers.values());
277
+ if (this.state.selectedProviderId === id) {
278
+ this._leaveDataChannel();
279
+ this.state.selectedProviderId = null;
280
+ this._resetAccumulatedState();
281
+ this._pickProviderAndSubscribe();
282
+ }
283
+ this._fire();
284
+ break;
285
+ }
286
+ default:
287
+ break;
288
+ }
289
+ }
290
+ /**
291
+ * Handler for the per-provider data channel. Everything here is
292
+ * already implicitly addressed to us (we opened the channel with the
293
+ * provider's id), so no per-message filtering is required beyond
294
+ * matching our consumer `id` on `subscribe:ack`.
295
+ */
296
+ _onDataMessage(msg) {
297
+ if (!msg || typeof msg !== "object" || !("type" in msg)) return;
298
+ tracePerf(msg);
299
+ if (this._rawMessageListeners.size > 0) {
300
+ for (const cb of this._rawMessageListeners) {
301
+ try {
302
+ cb(msg, "in");
303
+ } catch {
304
+ }
305
+ }
306
+ }
307
+ switch (msg.type) {
308
+ case "subscribe:ack": {
309
+ if (msg.payload.id !== this.id) return;
310
+ this._markServerAlive();
311
+ this._applyEnv(msg.payload.env);
312
+ if (this._ackTimer === null) {
313
+ this._ackTimer = setInterval(() => this._sendAck(), ACK_INTERVAL_MS);
314
+ }
315
+ this._fire();
316
+ break;
317
+ }
318
+ case "data": {
319
+ this._markServerAlive();
320
+ this.state.frame = msg.payload.frame;
321
+ const features = msg.payload.features;
322
+ if (features.stats !== void 0) this._applyStats(features.stats);
323
+ if (features.env !== void 0) this._applyEnv(features.env);
324
+ if (features.registry !== void 0) this._applyRegistry(features.registry);
325
+ if (features.buffers !== void 0) this._applyBuffers(features.buffers);
326
+ if (features.batches !== void 0) this._applyBatches(features.batches);
327
+ this._fire();
328
+ break;
329
+ }
330
+ case "buffer:chunk": {
331
+ this._markServerAlive();
332
+ const payload = msg.payload;
333
+ for (const cb of this._chunkListeners) {
334
+ try {
335
+ cb(payload);
336
+ } catch {
337
+ }
338
+ }
339
+ break;
340
+ }
341
+ case "buffer:raw": {
342
+ this._markServerAlive();
343
+ const payload = msg.payload;
344
+ let snap = this.state.buffers.get(payload.name);
345
+ if (snap !== void 0) {
346
+ snap.pixels = new Uint8Array(payload.data);
347
+ snap.width = payload.width;
348
+ snap.height = payload.height;
349
+ snap.version++;
350
+ } else {
351
+ snap = {
352
+ name: payload.name,
353
+ width: payload.width,
354
+ height: payload.height,
355
+ srcWidth: payload.width,
356
+ srcHeight: payload.height,
357
+ pixelType: "rgba8",
358
+ display: "colors",
359
+ version: 0,
360
+ pixels: new Uint8Array(payload.data)
361
+ };
362
+ this.state.buffers.set(payload.name, snap);
363
+ }
364
+ this._fire();
365
+ break;
366
+ }
367
+ case "ping": {
368
+ this._markServerAlive();
369
+ break;
370
+ }
371
+ default:
372
+ break;
373
+ }
374
+ }
375
+ _markServerAlive() {
376
+ this._lastServerAt = Date.now();
377
+ if (!this.state.serverAlive) {
378
+ this.state.serverAlive = true;
379
+ this._fire();
380
+ }
381
+ }
382
+ /**
383
+ * Pick the best provider from the currently-known set and subscribe
384
+ * to it. Preference: `user` over `system`; first-announced as
385
+ * tiebreak. No-op if zero providers are known (we'll stay waiting;
386
+ * any future `provider:announce` that arrives doesn't auto-trigger
387
+ * this — call it again or restart discovery).
388
+ */
389
+ _pickProviderAndSubscribe() {
390
+ if (this.state.selectedProviderId !== null) return;
391
+ const providers = Array.from(this._providers.values());
392
+ if (providers.length === 0) return;
393
+ const user = providers.find((p) => p.kind === "user");
394
+ const chosen = user ?? providers[0];
395
+ this.state.selectedProviderId = chosen.id;
396
+ this._joinDataChannel(chosen.id);
397
+ this._postData({
398
+ type: "subscribe",
399
+ payload: {
400
+ id: this.id,
401
+ features: this._features,
402
+ registry: this._registrySelection ?? void 0,
403
+ buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
404
+ }
405
+ });
406
+ this._fire();
407
+ }
408
+ /** Clear all feature-derived state so the next data packet can start fresh. */
409
+ _resetAccumulatedState() {
410
+ this.state.frame = void 0;
411
+ this._applyStats(null);
412
+ this._applyEnv(null);
413
+ this.state.registry.clear();
414
+ this.state.buffers.clear();
415
+ this._applyBatches(null);
416
+ }
417
+ /**
418
+ * Apply a stats batch. Null = reset (feature cleared / provider gone).
419
+ * Otherwise: decode each typed array onto the matching Float32 ring
420
+ * and update the scalar with the batch mean (natural smoothing for
421
+ * the text label).
422
+ */
423
+ _applyStats(batch) {
424
+ if (batch === null) {
425
+ this.state.drawCalls = void 0;
426
+ this.state.triangles = void 0;
427
+ this.state.primitives = void 0;
428
+ this.state.geometries = void 0;
429
+ this.state.textures = void 0;
430
+ this.state.cpuMs = void 0;
431
+ this.state.fps = void 0;
432
+ this.state.gpuMs = void 0;
433
+ this.state.heapUsedMB = void 0;
434
+ this.state.heapLimitMB = void 0;
435
+ const s2 = this.state.series;
436
+ s2.fps.write = 0;
437
+ s2.fps.length = 0;
438
+ s2.cpuMs.write = 0;
439
+ s2.cpuMs.length = 0;
440
+ s2.gpuMs.write = 0;
441
+ s2.gpuMs.length = 0;
442
+ s2.heapUsedMB.write = 0;
443
+ s2.heapUsedMB.length = 0;
444
+ s2.drawCalls.write = 0;
445
+ s2.drawCalls.length = 0;
446
+ s2.triangles.write = 0;
447
+ s2.triangles.length = 0;
448
+ s2.primitives.write = 0;
449
+ s2.primitives.length = 0;
450
+ s2.geometries.write = 0;
451
+ s2.geometries.length = 0;
452
+ s2.textures.write = 0;
453
+ s2.textures.length = 0;
454
+ return;
455
+ }
456
+ const count = batch.count;
457
+ if (count <= 0) return;
458
+ const s = this.state.series;
459
+ if (batch.fps) this.state.fps = this._ingestI16(s.fps, batch.fps, count, 0.1);
460
+ if (batch.cpuMs) this.state.cpuMs = this._ingestU16(s.cpuMs, batch.cpuMs, count, 0.01);
461
+ if (batch.gpuMs) this.state.gpuMs = this._ingestU16(s.gpuMs, batch.gpuMs, count, 0.01);
462
+ if (batch.heapUsedMB) this.state.heapUsedMB = this._ingestU16(s.heapUsedMB, batch.heapUsedMB, count, 1);
463
+ if (batch.drawCalls) this.state.drawCalls = this._ingestU32(s.drawCalls, batch.drawCalls, count);
464
+ if (batch.triangles) this.state.triangles = this._ingestU32(s.triangles, batch.triangles, count);
465
+ if (batch.primitives) this.state.primitives = this._ingestU32(s.primitives, batch.primitives, count);
466
+ if (batch.geometries) this.state.geometries = this._ingestU32(s.geometries, batch.geometries, count);
467
+ if (batch.textures) this.state.textures = this._ingestU32(s.textures, batch.textures, count);
468
+ if (batch.heapLimitMB !== void 0) this.state.heapLimitMB = batch.heapLimitMB;
469
+ }
470
+ /**
471
+ * Append `count` samples from a scaled integer view to a Float32 ring;
472
+ * return the batch mean (scaled). Zero-alloc past the ring itself.
473
+ */
474
+ _ingestI16(ring, src, count, scale) {
475
+ const size = ring.data.length;
476
+ let sum = 0;
477
+ let w = ring.write;
478
+ for (let i = 0; i < count; i++) {
479
+ const v = src[i] * scale;
480
+ ring.data[w] = v;
481
+ sum += v;
482
+ w = (w + 1) % size;
483
+ }
484
+ ring.write = w;
485
+ ring.length = Math.min(size, ring.length + count);
486
+ return sum / count;
487
+ }
488
+ _ingestU16(ring, src, count, scale) {
489
+ const size = ring.data.length;
490
+ let sum = 0;
491
+ let w = ring.write;
492
+ for (let i = 0; i < count; i++) {
493
+ const v = src[i] * scale;
494
+ ring.data[w] = v;
495
+ sum += v;
496
+ w = (w + 1) % size;
497
+ }
498
+ ring.write = w;
499
+ ring.length = Math.min(size, ring.length + count);
500
+ return sum / count;
501
+ }
502
+ _ingestU32(ring, src, count) {
503
+ const size = ring.data.length;
504
+ let sum = 0;
505
+ let w = ring.write;
506
+ for (let i = 0; i < count; i++) {
507
+ const v = src[i];
508
+ ring.data[w] = v;
509
+ sum += v;
510
+ w = (w + 1) % size;
511
+ }
512
+ ring.write = w;
513
+ ring.length = Math.min(size, ring.length + count);
514
+ return sum / count;
515
+ }
516
+ /**
517
+ * Apply a batches feature payload — replaces the snapshot wholesale.
518
+ * The wire arrays are scratch pools on the producer; we truncate by
519
+ * the provided counts and copy fields into persistent snapshot
520
+ * objects the UI can hold across subsequent frames.
521
+ *
522
+ * The client-side snapshot arrays grow monotonically to the high
523
+ * watermark and entries are overwritten in place — same alloc
524
+ * discipline as the producer.
525
+ */
526
+ _applyBatches(delta) {
527
+ if (delta === null) {
528
+ this.state.batches.frame = 0;
529
+ this.state.batches.passes.length = 0;
530
+ this.state.batches.batches.length = 0;
531
+ return;
532
+ }
533
+ this.state.batches.frame = delta.frame;
534
+ const passesIn = delta.passes;
535
+ const passCount = delta.passCount | 0;
536
+ const passesOut = this.state.batches.passes;
537
+ if (passesIn !== void 0) {
538
+ for (let i = 0; i < passCount; i++) {
539
+ const src = passesIn[i];
540
+ if (src === void 0) continue;
541
+ let dst = passesOut[i];
542
+ if (dst === void 0) {
543
+ dst = { label: "", calls: 0, triangles: 0, cpuMs: 0, depth: 0, parent: -1 };
544
+ passesOut[i] = dst;
545
+ }
546
+ dst.label = src.label;
547
+ dst.calls = src.calls;
548
+ dst.triangles = src.triangles;
549
+ dst.cpuMs = src.cpuMs;
550
+ dst.depth = src.depth;
551
+ dst.parent = src.parent;
552
+ }
553
+ }
554
+ if (passesOut.length > passCount) passesOut.length = passCount;
555
+ const batchesIn = delta.batches;
556
+ const batchCount = delta.batchCount | 0;
557
+ const batchesOut = this.state.batches.batches;
558
+ if (batchesIn !== void 0) {
559
+ for (let i = 0; i < batchCount; i++) {
560
+ const src = batchesIn[i];
561
+ if (src === void 0) continue;
562
+ let dst = batchesOut[i];
563
+ if (dst === void 0) {
564
+ dst = {
565
+ runKey: 0,
566
+ materialId: 0,
567
+ layer: 0,
568
+ materialName: "",
569
+ spriteCount: 0,
570
+ batchIdx: 0,
571
+ kind: "sprite",
572
+ label: ""
573
+ };
574
+ batchesOut[i] = dst;
575
+ }
576
+ dst.runKey = src.runKey;
577
+ dst.materialId = src.materialId;
578
+ dst.layer = src.layer;
579
+ dst.materialName = src.materialName;
580
+ dst.spriteCount = src.spriteCount;
581
+ dst.batchIdx = src.batchIdx;
582
+ dst.kind = src.kind ?? "sprite";
583
+ dst.label = src.label ?? "";
584
+ }
585
+ }
586
+ if (batchesOut.length > batchCount) batchesOut.length = batchCount;
587
+ }
588
+ /**
589
+ * Apply a registry delta. `entries[name] === null` → remove;
590
+ * `entries[name]` present → upsert a snapshot keyed by `name`.
591
+ * A `null` batch (feature cleared) drops every entry.
592
+ */
593
+ _applyRegistry(delta) {
594
+ if (delta === null) {
595
+ this.state.registry.clear();
596
+ return;
597
+ }
598
+ if (!delta.entries) return;
599
+ const entries = delta.entries;
600
+ for (const name in entries) {
601
+ const d = entries[name];
602
+ if (d === void 0) continue;
603
+ if (d === null) {
604
+ this.state.registry.delete(name);
605
+ continue;
606
+ }
607
+ let snap = this.state.registry.get(name);
608
+ const sample = d.sample ?? snap?.sample ?? EMPTY_SAMPLE;
609
+ if (snap === void 0) {
610
+ snap = {
611
+ name,
612
+ kind: d.kind,
613
+ version: d.version,
614
+ count: d.count,
615
+ sample,
616
+ label: d.label
617
+ };
618
+ this.state.registry.set(name, snap);
619
+ } else {
620
+ snap.kind = d.kind;
621
+ snap.version = d.version;
622
+ snap.count = d.count;
623
+ snap.sample = sample;
624
+ snap.label = d.label;
625
+ }
626
+ }
627
+ }
628
+ /**
629
+ * Apply a buffers delta. Metadata (width/height/version/pixelType)
630
+ * ships regardless of the client's selection; `pixels` only arrives
631
+ * when this entry is in the current selection. Retain the previous
632
+ * `pixels` when the delta is metadata-only so the UI keeps showing
633
+ * the last thumbnail while browsing.
634
+ */
635
+ _applyBuffers(delta) {
636
+ if (delta === null) {
637
+ this.state.buffers.clear();
638
+ return;
639
+ }
640
+ if (!delta.entries) return;
641
+ const entries = delta.entries;
642
+ for (const name in entries) {
643
+ const d = entries[name];
644
+ if (d === void 0) continue;
645
+ if (d === null) {
646
+ this.state.buffers.delete(name);
647
+ continue;
648
+ }
649
+ let snap = this.state.buffers.get(name);
650
+ const pixels = d.pixels ?? snap?.pixels ?? null;
651
+ const isFloat = d.pixelType === "rgba16f" || d.pixelType === "rgba32f";
652
+ const display = d.display ?? (isFloat ? "normalize" : "colors");
653
+ const srcW = d.srcWidth ?? d.width;
654
+ const srcH = d.srcHeight ?? d.height;
655
+ if (snap === void 0) {
656
+ snap = {
657
+ name,
658
+ width: d.width,
659
+ height: d.height,
660
+ srcWidth: srcW,
661
+ srcHeight: srcH,
662
+ pixelType: d.pixelType,
663
+ display,
664
+ version: d.version,
665
+ pixels,
666
+ label: d.label
667
+ };
668
+ this.state.buffers.set(name, snap);
669
+ } else {
670
+ snap.width = d.width;
671
+ snap.height = d.height;
672
+ snap.srcWidth = srcW;
673
+ snap.srcHeight = srcH;
674
+ snap.pixelType = d.pixelType;
675
+ snap.display = display;
676
+ snap.version = d.version;
677
+ snap.pixels = pixels;
678
+ snap.label = d.label;
679
+ }
680
+ }
681
+ }
682
+ _applyEnv(delta) {
683
+ if (delta === null) {
684
+ this.state.threeFlatlandVersion = void 0;
685
+ this.state.threeRevision = void 0;
686
+ this.state.backendName = void 0;
687
+ this.state.backendTrackTimestamp = void 0;
688
+ this.state.backendDisjoint = void 0;
689
+ this.state.gpuModeEnabled = void 0;
690
+ this.state.canvasWidth = void 0;
691
+ this.state.canvasHeight = void 0;
692
+ this.state.canvasPixelRatio = void 0;
693
+ return;
694
+ }
695
+ if ("threeFlatlandVersion" in delta) this.state.threeFlatlandVersion = delta.threeFlatlandVersion ?? void 0;
696
+ if ("threeRevision" in delta) this.state.threeRevision = delta.threeRevision ?? void 0;
697
+ if (delta.backend !== void 0) {
698
+ const b = delta.backend;
699
+ if (b === null) {
700
+ this.state.backendName = void 0;
701
+ this.state.backendTrackTimestamp = void 0;
702
+ this.state.backendDisjoint = void 0;
703
+ this.state.gpuModeEnabled = void 0;
704
+ } else {
705
+ if ("name" in b) this.state.backendName = b.name ?? void 0;
706
+ if ("trackTimestamp" in b) this.state.backendTrackTimestamp = b.trackTimestamp ?? void 0;
707
+ if ("disjoint" in b) this.state.backendDisjoint = b.disjoint ?? void 0;
708
+ if ("gpuModeEnabled" in b) this.state.gpuModeEnabled = b.gpuModeEnabled ?? void 0;
709
+ }
710
+ }
711
+ if (delta.canvas !== void 0) {
712
+ const c = delta.canvas;
713
+ if (c === null) {
714
+ this.state.canvasWidth = void 0;
715
+ this.state.canvasHeight = void 0;
716
+ this.state.canvasPixelRatio = void 0;
717
+ } else {
718
+ if ("width" in c) this.state.canvasWidth = c.width ?? void 0;
719
+ if ("height" in c) this.state.canvasHeight = c.height ?? void 0;
720
+ if ("pixelRatio" in c) this.state.canvasPixelRatio = c.pixelRatio ?? void 0;
721
+ }
722
+ }
723
+ }
724
+ _checkLiveness() {
725
+ const now = Date.now();
726
+ const lag = this._lastServerAt === 0 ? now : now - this._lastServerAt;
727
+ this.state.serverLagMs = lag;
728
+ if (this._lastServerAt !== 0 && lag > SERVER_LIVENESS_MS) {
729
+ if (this.state.serverAlive) {
730
+ this.state.serverAlive = false;
731
+ }
732
+ if (this._dataBus !== null) {
733
+ this._postData({
734
+ type: "subscribe",
735
+ payload: {
736
+ id: this.id,
737
+ features: this._features,
738
+ registry: this._registrySelection ?? void 0,
739
+ buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
740
+ }
741
+ });
742
+ }
743
+ }
744
+ this._fire();
745
+ }
746
+ _sendAck() {
747
+ if (this._disposed || this._dataBus === null) return;
748
+ this._postData({ type: "ack", payload: { id: this.id } });
749
+ }
750
+ _postDiscovery(body) {
751
+ const msg = { v: DEBUG_PROTOCOL_VERSION, ts: Date.now(), ...body };
752
+ this._fireRawMessage(msg, "out");
753
+ try {
754
+ this._discoveryBus.postMessage(msg);
755
+ } catch {
756
+ }
757
+ }
758
+ _postData(body) {
759
+ if (this._dataBus === null) return;
760
+ const msg = { v: DEBUG_PROTOCOL_VERSION, ts: Date.now(), ...body };
761
+ this._fireRawMessage(msg, "out");
762
+ try {
763
+ this._dataBus.postMessage(msg);
764
+ } catch {
765
+ }
766
+ }
767
+ _fireRawMessage(msg, direction) {
768
+ if (this._rawMessageListeners.size === 0) return;
769
+ for (const cb of this._rawMessageListeners) {
770
+ try {
771
+ cb(msg, direction);
772
+ } catch {
773
+ }
774
+ }
775
+ }
776
+ /** Subscribe to state-change events. Returns an unsubscribe function. */
777
+ addListener(cb) {
778
+ this._listeners.add(cb);
779
+ return () => {
780
+ this._listeners.delete(cb);
781
+ };
782
+ }
783
+ /** Explicit remove — equivalent to calling the unsubscribe returned from `addListener`. */
784
+ removeListener(cb) {
785
+ this._listeners.delete(cb);
786
+ }
787
+ /** Subscribe to incoming WebCodecs buffer chunks. Returns an unsubscribe function. */
788
+ addChunkListener(cb) {
789
+ this._chunkListeners.add(cb);
790
+ return () => {
791
+ this._chunkListeners.delete(cb);
792
+ };
793
+ }
794
+ /**
795
+ * Subscribe to every bus message — both inbound (from providers) and
796
+ * outbound (our own `subscribe`/`ack`/etc.). Used by the dashboard's
797
+ * protocol-log panel. Listeners fire on the hot path so keep them
798
+ * cheap — filter and format lazily.
799
+ */
800
+ addRawMessageListener(cb) {
801
+ this._rawMessageListeners.add(cb);
802
+ return () => {
803
+ this._rawMessageListeners.delete(cb);
804
+ };
805
+ }
806
+ _fire() {
807
+ for (const cb of this._listeners) {
808
+ try {
809
+ cb(this.state);
810
+ } catch {
811
+ }
812
+ }
813
+ }
814
+ }
815
+ function sameSet(a, b) {
816
+ if (a.length !== b.length) return false;
817
+ for (const v of a) if (!b.includes(v)) return false;
818
+ return true;
819
+ }
820
+ function sameFilter(a, b) {
821
+ if (a === b) return true;
822
+ if (a === null || b === null) return false;
823
+ return sameSet(a, b);
824
+ }
825
+ function sameBufferSubscription(a, b) {
826
+ const ak = Object.keys(a);
827
+ const bk = Object.keys(b);
828
+ if (ak.length !== bk.length) return false;
829
+ for (const k of ak) {
830
+ const av = a[k];
831
+ const bv = b[k];
832
+ if (av === void 0 || bv === void 0) return false;
833
+ if (av.mode !== bv.mode) return false;
834
+ if ((av.thumbSize ?? 256) !== (bv.thumbSize ?? 256)) return false;
835
+ }
836
+ return true;
837
+ }
838
+ function generateUuid() {
839
+ const c = typeof crypto !== "undefined" ? crypto : void 0;
840
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
841
+ const bytes = new Uint8Array(16);
842
+ if (c && typeof c.getRandomValues === "function") c.getRandomValues(bytes);
843
+ else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
844
+ bytes[6] = bytes[6] & 15 | 64;
845
+ bytes[8] = bytes[8] & 63 | 128;
846
+ const h = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
847
+ return `${h.slice(0, 4).join("")}-${h.slice(4, 6).join("")}-${h.slice(6, 8).join("")}-${h.slice(8, 10).join("")}-${h.slice(10).join("")}`;
848
+ }
849
+ export {
850
+ DevtoolsClient
851
+ };
852
+ //# sourceMappingURL=devtools-client.js.map