tempo-sdk 0.0.38 → 0.0.42

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.
@@ -2743,6 +2743,11 @@ function captureProjectionLayerProps(fiber, element, sourceAnnotations = "fiber"
2743
2743
  if (value === false || value === "false") props[flatKey] = false;
2744
2744
  };
2745
2745
  putString("data-tempo-filepath", "tempoFilepath");
2746
+ const locked = read("data-tempo-locked", "tempoLocked");
2747
+ if (locked === true || locked === "true" || locked === "")
2748
+ props["data-tempo-locked"] = true;
2749
+ else if (locked === false || locked === "false")
2750
+ props["data-tempo-locked"] = false;
2746
2751
  putFiniteNumber("data-tempo-position", "tempoPosition");
2747
2752
  putFiniteNumber("data-tempo-modifiedts", "tempoModifiedts");
2748
2753
  putString("data-tempo-source-version", "tempoSourceVersion");
@@ -2923,6 +2928,9 @@ function layerIdForTarget(root, target, identity) {
2923
2928
  }
2924
2929
  function captureProjectionDomLayerProps(element) {
2925
2930
  const props = {};
2931
+ const locked = element.getAttribute("data-tempo-locked");
2932
+ if (locked === "true" || locked === "") props["data-tempo-locked"] = true;
2933
+ else if (locked === "false") props["data-tempo-locked"] = false;
2926
2934
  const className = element.getAttribute("class");
2927
2935
  if (className) props.className = className;
2928
2936
  const style = parseInlineStyle2(element.getAttribute("style"));
@@ -3185,15 +3193,16 @@ function normalizeTempoDataSet(props) {
3185
3193
  // ../../modules/iframe-projection/combined/projection-svelte-metadata.ts
3186
3194
  var TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE = "data-tempo-svelte-source-registry";
3187
3195
  function validateSvelteRuntimeMetadata(root) {
3188
- if (!root.querySelector(
3189
- `template[${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}]`
3190
- )) {
3196
+ if (!root.querySelector(`template[${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}]`)) {
3191
3197
  return {
3192
3198
  kind: "unavailable",
3193
3199
  message: "Svelte Canvas layers require a supported Svelte 5 development build with Tempo's Svelte preprocessor enabled. No source registry was found in the rendered root; confirm apps[0].uiFramework is set to svelte and the app is not serving a production/minified build."
3194
3200
  };
3195
3201
  }
3196
- const renderedElements = [root, ...Array.from(root.querySelectorAll("*"))].filter(
3202
+ const renderedElements = [
3203
+ root,
3204
+ ...Array.from(root.querySelectorAll("*"))
3205
+ ].filter(
3197
3206
  (element) => !element.hasAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE)
3198
3207
  );
3199
3208
  const authoredHosts = renderedElements.filter(
@@ -3311,6 +3320,7 @@ function parseSourceTargetRecord(value, kind) {
3311
3320
  position: value.position,
3312
3321
  ...typeof value.className === "string" ? { className: value.className } : {},
3313
3322
  ...typeof value.style === "string" ? { style: value.style } : {},
3323
+ ...typeof value.locked === "boolean" ? { locked: value.locked } : {},
3314
3324
  supportsClassName: value.supportsClassName,
3315
3325
  supportsStyle: value.supportsStyle
3316
3326
  };
@@ -3540,15 +3550,11 @@ function createProjectionSvelteLayerSerializer() {
3540
3550
  };
3541
3551
  });
3542
3552
  const metadata = targets.metadata.flatMap((target) => {
3543
- if (target === root || !root.contains(target) || !sourceHost(target) || coalesced.some(
3544
- (region) => region === root || region.contains(target)
3545
- )) {
3553
+ if (target === root || !root.contains(target) || !sourceHost(target) || coalesced.some((region) => region === root || region.contains(target))) {
3546
3554
  return [];
3547
3555
  }
3548
3556
  const targetFiberId = session.hostId(target);
3549
- return [
3550
- { targetFiberId, props: session.captureHostProps(target) }
3551
- ];
3557
+ return [{ targetFiberId, props: session.captureHostProps(target) }];
3552
3558
  });
3553
3559
  if (regionTrees.length === 0 && metadata.length === 0) return void 0;
3554
3560
  const patchObservedFiles = session.observedFiles();
@@ -3659,6 +3665,7 @@ function serializeComponentNode(resolved, children, id) {
3659
3665
  const props = {
3660
3666
  ...component.className ? { className: component.className } : {},
3661
3667
  ...component.style ? { style: parseInlineStyle3(component.style) } : {},
3668
+ ...component.locked !== void 0 ? { "data-tempo-locked": component.locked } : {},
3662
3669
  "data-tempo-filepath": source.filepath,
3663
3670
  "data-tempo-position": component.position,
3664
3671
  "data-tempo-modifiedts": source.modifiedTs,
@@ -6587,6 +6594,1000 @@ function initCombinedSourceInterface(targetOrigin, serialize, hideFiberProp) {
6587
6594
  };
6588
6595
  }
6589
6596
 
6597
+ // ../../modules/iframe-projection/canvas-frames/demand.ts
6598
+ var DEFAULT_CANVAS_FRAME_MAX_IN_FLIGHT = 2;
6599
+ var DEFAULT_CANVAS_ACTIVITY_WINDOW_MS = 2e3;
6600
+ var DISABLED_CANVAS_FRAME_DEMAND = Object.freeze({
6601
+ enabled: false,
6602
+ width: 0,
6603
+ height: 0,
6604
+ maxFps: 0
6605
+ });
6606
+
6607
+ // ../../modules/iframe-projection/canvas-frames/demand-planner.ts
6608
+ var LOW_FPS_AREA = 96 * 96;
6609
+
6610
+ // ../../modules/iframe-projection/canvas-frames/draw-tracker.ts
6611
+ var WeakReferenceCtor = globalThis.WeakRef;
6612
+ var INNER = /* @__PURE__ */ Symbol.for("iframe-projection.canvas-frames.draw-tracker.inner");
6613
+ var METHODS_2D = [
6614
+ "clearRect",
6615
+ "fillRect",
6616
+ "strokeRect",
6617
+ "fill",
6618
+ "stroke",
6619
+ "fillText",
6620
+ "strokeText",
6621
+ "drawImage",
6622
+ "putImageData",
6623
+ "reset",
6624
+ "drawFocusIfNeeded"
6625
+ ];
6626
+ var METHODS_GL = [
6627
+ "clear",
6628
+ "drawArrays",
6629
+ "drawElements",
6630
+ "drawArraysInstanced",
6631
+ "drawElementsInstanced",
6632
+ "drawRangeElements",
6633
+ "blitFramebuffer",
6634
+ "clearBufferfv",
6635
+ "clearBufferiv",
6636
+ "clearBufferuiv",
6637
+ "clearBufferfi"
6638
+ ];
6639
+ var GL_EXTENSION_DRAW_METHOD = /^(multiDraw|drawArrays|drawElements)/;
6640
+ var GPU_QUEUE_WRITE_METHODS = [
6641
+ "submit",
6642
+ "writeTexture",
6643
+ "copyExternalImageToTexture"
6644
+ ];
6645
+ function prototypeOf(scope, constructorName) {
6646
+ const ctor = scope[constructorName];
6647
+ if (typeof ctor !== "function") return null;
6648
+ const prototype = ctor.prototype;
6649
+ return typeof prototype === "object" && prototype !== null ? prototype : null;
6650
+ }
6651
+ function canvasOf(context) {
6652
+ const canvas = context?.canvas;
6653
+ return typeof canvas === "object" && canvas !== null ? canvas : null;
6654
+ }
6655
+ function unlink(current, wrapper) {
6656
+ if (current === wrapper) return wrapper[INNER];
6657
+ let outer = current;
6658
+ while (typeof outer === "function" && outer[INNER] !== wrapper) {
6659
+ outer = outer[INNER];
6660
+ }
6661
+ if (typeof outer === "function") outer[INNER] = wrapper[INNER];
6662
+ return current;
6663
+ }
6664
+ function installDrawTracker(scope = globalThis) {
6665
+ const states = /* @__PURE__ */ new WeakMap();
6666
+ const untracked = /* @__PURE__ */ new WeakSet();
6667
+ const restores = [];
6668
+ const wrapped = /* @__PURE__ */ new WeakMap();
6669
+ let patchedCount = 0;
6670
+ const stateOf = (canvas) => {
6671
+ let state = states.get(canvas);
6672
+ if (!state) {
6673
+ state = { revision: 0, dirty: false, listeners: null };
6674
+ states.set(canvas, state);
6675
+ }
6676
+ return state;
6677
+ };
6678
+ const notify = (state) => {
6679
+ if (!state.listeners) return;
6680
+ for (const listener of state.listeners) listener();
6681
+ };
6682
+ const mark = (canvas) => {
6683
+ if (!canvas) return;
6684
+ const state = stateOf(canvas);
6685
+ if (state.dirty) return;
6686
+ state.dirty = true;
6687
+ state.revision += 1;
6688
+ notify(state);
6689
+ };
6690
+ const alreadyWrapped = (owner, name) => {
6691
+ const names = wrapped.get(owner) ?? /* @__PURE__ */ new Set();
6692
+ if (names.has(name)) return true;
6693
+ names.add(name);
6694
+ wrapped.set(owner, names);
6695
+ return false;
6696
+ };
6697
+ const wrap = (owner, name, key, after) => {
6698
+ if (!owner || alreadyWrapped(owner, name)) return;
6699
+ const descriptor = Object.getOwnPropertyDescriptor(owner, name);
6700
+ const original = descriptor?.[key];
6701
+ if (typeof original !== "function") return;
6702
+ const wrapper = function(...args) {
6703
+ const result = Reflect.apply(
6704
+ wrapper[INNER] ?? original,
6705
+ this,
6706
+ args
6707
+ );
6708
+ after(this, args, result);
6709
+ return result;
6710
+ };
6711
+ wrapper[INNER] = original;
6712
+ Object.defineProperty(owner, name, { ...descriptor, [key]: wrapper });
6713
+ patchedCount += 1;
6714
+ restores.push(() => {
6715
+ const current = Object.getOwnPropertyDescriptor(owner, name)?.[key];
6716
+ const head = unlink(current, wrapper);
6717
+ if (head !== current) {
6718
+ Object.defineProperty(owner, name, { ...descriptor, [key]: head });
6719
+ }
6720
+ });
6721
+ };
6722
+ const markContextCanvas = (context) => mark(canvasOf(context));
6723
+ const markSelf = (self) => mark(self);
6724
+ for (const type of [
6725
+ "CanvasRenderingContext2D",
6726
+ "OffscreenCanvasRenderingContext2D"
6727
+ ]) {
6728
+ const prototype = prototypeOf(scope, type);
6729
+ for (const name of METHODS_2D) {
6730
+ wrap(prototype, name, "value", markContextCanvas);
6731
+ }
6732
+ }
6733
+ wrap(
6734
+ prototypeOf(scope, "ImageBitmapRenderingContext"),
6735
+ "transferFromImageBitmap",
6736
+ "value",
6737
+ markContextCanvas
6738
+ );
6739
+ const extensionCanvas = /* @__PURE__ */ new WeakMap();
6740
+ const markExtensionCanvas = (extension) => {
6741
+ if (typeof extension !== "object" || extension === null) return;
6742
+ mark(extensionCanvas.get(extension) ?? null);
6743
+ };
6744
+ for (const type of ["WebGLRenderingContext", "WebGL2RenderingContext"]) {
6745
+ const prototype = prototypeOf(scope, type);
6746
+ for (const name of METHODS_GL) {
6747
+ wrap(prototype, name, "value", markContextCanvas);
6748
+ }
6749
+ wrap(prototype, "getExtension", "value", (context, _args, extension) => {
6750
+ if (typeof extension !== "object" || extension === null) return;
6751
+ const canvas = canvasOf(context);
6752
+ if (canvas) extensionCanvas.set(extension, canvas);
6753
+ for (const owner of [extension, Object.getPrototypeOf(extension)]) {
6754
+ if (!owner) continue;
6755
+ for (const name of Object.getOwnPropertyNames(owner)) {
6756
+ if (GL_EXTENSION_DRAW_METHOD.test(name)) {
6757
+ wrap(owner, name, "value", markExtensionCanvas);
6758
+ }
6759
+ }
6760
+ }
6761
+ });
6762
+ }
6763
+ const gpuContexts = /* @__PURE__ */ new WeakMap();
6764
+ for (const type of ["HTMLCanvasElement", "OffscreenCanvas"]) {
6765
+ const prototype = prototypeOf(scope, type);
6766
+ wrap(prototype, "width", "set", markSelf);
6767
+ wrap(prototype, "height", "set", markSelf);
6768
+ wrap(prototype, "getContext", "value", (canvas, args, context) => {
6769
+ if (args[0] !== "webgpu" || typeof context !== "object" || !context) {
6770
+ return;
6771
+ }
6772
+ if (gpuContexts.has(context)) return;
6773
+ gpuContexts.set(context, {
6774
+ canvas,
6775
+ queue: null,
6776
+ reference: null
6777
+ });
6778
+ });
6779
+ }
6780
+ wrap(
6781
+ prototypeOf(scope, "HTMLCanvasElement"),
6782
+ "transferControlToOffscreen",
6783
+ "value",
6784
+ (canvas) => {
6785
+ untracked.add(canvas);
6786
+ const state = stateOf(canvas);
6787
+ if (state.dirty) notify(state);
6788
+ else mark(canvas);
6789
+ }
6790
+ );
6791
+ const observer = typeof scope.MutationObserver === "function" && scope.document ? new scope.MutationObserver((records) => {
6792
+ for (const record of records) {
6793
+ const target = record.target;
6794
+ if (target.localName === "canvas") mark(target);
6795
+ }
6796
+ }) : null;
6797
+ observer?.observe(scope.document, {
6798
+ subtree: true,
6799
+ attributes: true,
6800
+ attributeFilter: ["width", "height"]
6801
+ });
6802
+ const queueCanvases = /* @__PURE__ */ new WeakMap();
6803
+ const detachFromQueue = (state) => {
6804
+ if (state.queue && state.reference) {
6805
+ queueCanvases.get(state.queue)?.delete(state.reference);
6806
+ }
6807
+ state.queue = null;
6808
+ state.reference = null;
6809
+ };
6810
+ const gpuContextPrototype = prototypeOf(scope, "GPUCanvasContext");
6811
+ wrap(gpuContextPrototype, "configure", "value", (context, args) => {
6812
+ const state = gpuContexts.get(context);
6813
+ if (!state) return;
6814
+ detachFromQueue(state);
6815
+ const queue = args[0]?.device?.queue;
6816
+ if (queue) {
6817
+ const canvases = queueCanvases.get(queue) ?? /* @__PURE__ */ new Set();
6818
+ queueCanvases.set(queue, canvases);
6819
+ state.queue = queue;
6820
+ state.reference = new WeakReferenceCtor(state.canvas);
6821
+ canvases.add(state.reference);
6822
+ }
6823
+ mark(state.canvas);
6824
+ });
6825
+ wrap(gpuContextPrototype, "unconfigure", "value", (context) => {
6826
+ const state = gpuContexts.get(context);
6827
+ if (!state) return;
6828
+ detachFromQueue(state);
6829
+ mark(state.canvas);
6830
+ });
6831
+ const markQueueCanvases = (queue) => {
6832
+ const canvases = queueCanvases.get(queue);
6833
+ if (!canvases) return;
6834
+ for (const reference of canvases) {
6835
+ const canvas = reference.deref();
6836
+ if (canvas) mark(canvas);
6837
+ else canvases.delete(reference);
6838
+ }
6839
+ };
6840
+ for (const name of GPU_QUEUE_WRITE_METHODS) {
6841
+ wrap(prototypeOf(scope, "GPUQueue"), name, "value", markQueueCanvases);
6842
+ }
6843
+ return {
6844
+ patchedCount,
6845
+ revision: (canvas) => states.get(canvas)?.revision ?? 0,
6846
+ subscribe(canvas, listener) {
6847
+ const state = stateOf(canvas);
6848
+ state.listeners ?? (state.listeners = /* @__PURE__ */ new Set());
6849
+ state.listeners.add(listener);
6850
+ return () => {
6851
+ state.listeners?.delete(listener);
6852
+ };
6853
+ },
6854
+ captureStarted(canvas) {
6855
+ const state = stateOf(canvas);
6856
+ state.dirty = false;
6857
+ return state.revision;
6858
+ },
6859
+ isTracked: (canvas) => !untracked.has(canvas),
6860
+ dispose() {
6861
+ observer?.disconnect();
6862
+ for (const restore of restores) restore();
6863
+ restores.length = 0;
6864
+ }
6865
+ };
6866
+ }
6867
+
6868
+ // ../../modules/iframe-projection/canvas-frames/port-envelope.ts
6869
+ function definePortEnvelope(type) {
6870
+ const is = (value) => typeof value === "object" && value !== null && value.type === type;
6871
+ return {
6872
+ type,
6873
+ is,
6874
+ accept(event, trustedSource) {
6875
+ if (!is(event.data)) return null;
6876
+ const port = event.ports?.[0] ?? null;
6877
+ if (event.source !== trustedSource || !port) {
6878
+ port?.close();
6879
+ return null;
6880
+ }
6881
+ const fields = {
6882
+ ...event.data
6883
+ };
6884
+ delete fields.type;
6885
+ return { fields, port };
6886
+ },
6887
+ post(target, fields, port) {
6888
+ target.postMessage({ type, ...fields }, "*", [port]);
6889
+ }
6890
+ };
6891
+ }
6892
+ var CANVAS_FRAME_LANE_WINDOW_PORT = definePortEnvelope(
6893
+ "canvas-frames:window-port"
6894
+ );
6895
+
6896
+ // ../../modules/iframe-projection/canvas-frames/canvas-registry.ts
6897
+ function isCanvas(node) {
6898
+ return node.nodeType === 1 && node.localName === "canvas";
6899
+ }
6900
+ function collectCanvases(scope, into) {
6901
+ if (scope.nodeType !== 1) return;
6902
+ if (isCanvas(scope)) into.push(scope);
6903
+ for (const canvas of scope.querySelectorAll("canvas")) {
6904
+ into.push(canvas);
6905
+ }
6906
+ }
6907
+ function watchCanvasElements(root, callbacks) {
6908
+ const canvases = /* @__PURE__ */ new Set();
6909
+ let stopped = false;
6910
+ const add = (canvas) => {
6911
+ if (canvases.has(canvas) || !root.contains(canvas)) return;
6912
+ canvases.add(canvas);
6913
+ callbacks.onAdded(canvas);
6914
+ };
6915
+ const remove = (canvas) => {
6916
+ if (!canvases.delete(canvas)) return;
6917
+ callbacks.onRemoved(canvas);
6918
+ };
6919
+ const handleMutations = (records) => {
6920
+ if (stopped) return;
6921
+ const removedCandidates = [];
6922
+ const addedCandidates = [];
6923
+ for (const record of records) {
6924
+ for (const node of record.removedNodes) {
6925
+ collectCanvases(node, removedCandidates);
6926
+ }
6927
+ for (const node of record.addedNodes) {
6928
+ collectCanvases(node, addedCandidates);
6929
+ }
6930
+ }
6931
+ for (const canvas of removedCandidates) {
6932
+ if (!root.contains(canvas)) remove(canvas);
6933
+ }
6934
+ for (const canvas of addedCandidates) add(canvas);
6935
+ };
6936
+ const observer = new MutationObserver(handleMutations);
6937
+ observer.observe(root, { childList: true, subtree: true });
6938
+ const initial = [];
6939
+ collectCanvases(root, initial);
6940
+ for (const canvas of initial) add(canvas);
6941
+ return () => {
6942
+ if (stopped) return;
6943
+ stopped = true;
6944
+ observer.disconnect();
6945
+ };
6946
+ }
6947
+
6948
+ // ../../modules/iframe-projection/canvas-frames/direct-sampler.ts
6949
+ function resizeOptionsFor(source, size) {
6950
+ const width = Math.min(size.width, source.width);
6951
+ const height = Math.min(size.height, source.height);
6952
+ if (source.width === width && source.height === height) return {};
6953
+ return { resizeWidth: width, resizeHeight: height, resizeQuality: "low" };
6954
+ }
6955
+ var sampleCanvasDirect = (canvas, size) => {
6956
+ const scope = canvas.ownerDocument.defaultView ?? globalThis;
6957
+ return scope.createImageBitmap(canvas, resizeOptionsFor(canvas, size));
6958
+ };
6959
+ function classifyCanvasSampleError(error) {
6960
+ const name = error?.name;
6961
+ return name === "SecurityError" ? "tainted" : "unreadable";
6962
+ }
6963
+
6964
+ // ../../modules/iframe-projection/canvas-frames/capture-stream-sampler.ts
6965
+ var watchCanvasPaints = (canvas, callbacks) => {
6966
+ const scope = canvas.ownerDocument.defaultView ?? globalThis;
6967
+ const Processor = scope.MediaStreamTrackProcessor;
6968
+ if (typeof Processor !== "function" || typeof scope.createImageBitmap !== "function") {
6969
+ return null;
6970
+ }
6971
+ let stopped = false;
6972
+ let held = null;
6973
+ let stream = null;
6974
+ let reader = null;
6975
+ const run = async () => {
6976
+ if (stopped) return;
6977
+ let track;
6978
+ try {
6979
+ stream = canvas.captureStream();
6980
+ track = stream.getVideoTracks()[0];
6981
+ if (!track) {
6982
+ callbacks.onEnded("unreadable");
6983
+ return;
6984
+ }
6985
+ reader = new Processor({ track }).readable.getReader();
6986
+ while (!stopped) {
6987
+ const result = await reader.read();
6988
+ if (result.done) {
6989
+ if (!stopped) callbacks.onEnded("unreadable");
6990
+ return;
6991
+ }
6992
+ if (stopped) {
6993
+ result.value.close();
6994
+ return;
6995
+ }
6996
+ held?.close();
6997
+ held = result.value;
6998
+ callbacks.onPaint();
6999
+ }
7000
+ } catch (error) {
7001
+ if (!stopped) callbacks.onEnded(classifyCanvasSampleError(error));
7002
+ } finally {
7003
+ track?.stop();
7004
+ }
7005
+ };
7006
+ void Promise.resolve().then(run);
7007
+ return {
7008
+ async read(size) {
7009
+ const frame = held;
7010
+ held = null;
7011
+ if (!frame) return null;
7012
+ try {
7013
+ const source = {
7014
+ width: frame.displayWidth,
7015
+ height: frame.displayHeight
7016
+ };
7017
+ return await scope.createImageBitmap(
7018
+ frame,
7019
+ resizeOptionsFor(source, size)
7020
+ );
7021
+ } finally {
7022
+ frame.close();
7023
+ }
7024
+ },
7025
+ stop() {
7026
+ if (stopped) return;
7027
+ stopped = true;
7028
+ held?.close();
7029
+ held = null;
7030
+ void reader?.cancel().catch(() => {
7031
+ });
7032
+ for (const track of stream?.getTracks() ?? []) track.stop();
7033
+ }
7034
+ };
7035
+ };
7036
+
7037
+ // ../../modules/iframe-projection/canvas-frames/source.ts
7038
+ function createDefaultScheduler(view = globalThis) {
7039
+ const Channel = view.MessageChannel ?? MessageChannel;
7040
+ const channel = new Channel();
7041
+ const queued = [];
7042
+ channel.port1.onmessage = () => queued.shift()?.();
7043
+ return {
7044
+ now: () => performance.now(),
7045
+ setTimeout: (callback, ms) => view.setTimeout(callback, ms),
7046
+ clearTimeout: (handle) => view.clearTimeout(handle),
7047
+ post(callback) {
7048
+ queued.push(callback);
7049
+ channel.port2.postMessage(null);
7050
+ },
7051
+ close() {
7052
+ queued.length = 0;
7053
+ channel.port1.close();
7054
+ channel.port2.close();
7055
+ }
7056
+ };
7057
+ }
7058
+ var PAINT_RESTART_DELAY_MS = 1e3;
7059
+ function watchCanvasFrames(root, emitter, options = {}) {
7060
+ const own = options.scheduler ? null : createDefaultScheduler(
7061
+ root.ownerDocument.defaultView ?? globalThis
7062
+ );
7063
+ const scheduler = options.scheduler ?? own;
7064
+ const tracker = options.tracker ?? null;
7065
+ const sampleCanvas = options.sampleCanvas ?? sampleCanvasDirect;
7066
+ const watchPaints = options.watchPaints ?? watchCanvasPaints;
7067
+ const maxInFlight = options.maxInFlight ?? DEFAULT_CANVAS_FRAME_MAX_IN_FLIGHT;
7068
+ const activityWindowMs = options.activityWindowMs ?? DEFAULT_CANVAS_ACTIVITY_WINDOW_MS;
7069
+ const watched = /* @__PURE__ */ new Map();
7070
+ let demand = {};
7071
+ let stopped = false;
7072
+ const trackerOf = (entry) => tracker?.isTracked(entry.canvas) ? tracker : null;
7073
+ const revisionOf = (entry) => trackerOf(entry)?.revision(entry.canvas) ?? entry.paintRevision;
7074
+ const isServed = (entry) => entry.demand.enabled && !entry.removed && !entry.terminal && !entry.paintsExhausted;
7075
+ const isRunnable = (entry) => isServed(entry) && !entry.pending && entry.outstanding.size < maxInFlight && revisionOf(entry) !== entry.sampledRevision;
7076
+ let active = false;
7077
+ let lastDirtyAt = Number.NEGATIVE_INFINITY;
7078
+ let activityTimer = null;
7079
+ const rearmBlockedCanvases = () => {
7080
+ let drawnSinceRearm = false;
7081
+ for (const entry of watched.values()) {
7082
+ if (!isServed(entry)) continue;
7083
+ const seenBy = trackerOf(entry);
7084
+ if (!seenBy) continue;
7085
+ const revision = seenBy.revision(entry.canvas);
7086
+ if (revision === entry.sampledRevision) continue;
7087
+ if (revision !== entry.armedRevision) drawnSinceRearm = true;
7088
+ entry.armedRevision = revision;
7089
+ seenBy.captureStarted(entry.canvas);
7090
+ }
7091
+ return drawnSinceRearm;
7092
+ };
7093
+ const armActivityExpiry = (ms) => {
7094
+ activityTimer = scheduler.setTimeout(() => {
7095
+ activityTimer = null;
7096
+ const remaining = lastDirtyAt + activityWindowMs - scheduler.now();
7097
+ if (remaining > 0) {
7098
+ armActivityExpiry(remaining);
7099
+ return;
7100
+ }
7101
+ if (rearmBlockedCanvases()) {
7102
+ armActivityExpiry(activityWindowMs);
7103
+ return;
7104
+ }
7105
+ active = false;
7106
+ emitter.activity(false);
7107
+ }, ms);
7108
+ };
7109
+ const touchActivity = () => {
7110
+ lastDirtyAt = scheduler.now();
7111
+ if (!active) {
7112
+ active = true;
7113
+ emitter.activity(true);
7114
+ }
7115
+ if (activityTimer === null) armActivityExpiry(activityWindowMs);
7116
+ };
7117
+ const reportUnavailable = (entry, reason) => {
7118
+ if (reason !== "unreadable") entry.terminal = true;
7119
+ if (entry.unavailableReported) return;
7120
+ entry.unavailableReported = true;
7121
+ emitter.removed(entry.targetId, reason);
7122
+ };
7123
+ const stopPaints = (entry) => {
7124
+ entry.paints?.stop();
7125
+ entry.paints = null;
7126
+ if (entry.paintRestartTimer !== null) {
7127
+ scheduler.clearTimeout(entry.paintRestartTimer);
7128
+ entry.paintRestartTimer = null;
7129
+ }
7130
+ };
7131
+ const onPaintsEnded = (entry, reason) => {
7132
+ stopPaints(entry);
7133
+ if (entry.removed || stopped) return;
7134
+ reportUnavailable(entry, reason);
7135
+ if (entry.terminal) return;
7136
+ if (entry.paintRestarts > 0) {
7137
+ entry.paintsExhausted = true;
7138
+ return;
7139
+ }
7140
+ entry.paintRestarts += 1;
7141
+ entry.paintRestartTimer = scheduler.setTimeout(() => {
7142
+ entry.paintRestartTimer = null;
7143
+ syncPaints(entry);
7144
+ if (entry.paints) {
7145
+ entry.sampledRevision = -1;
7146
+ wake(entry);
7147
+ }
7148
+ }, PAINT_RESTART_DELAY_MS);
7149
+ };
7150
+ const startPaints = (entry) => {
7151
+ const watcher = watchPaints(entry.canvas, {
7152
+ onPaint: () => {
7153
+ if (entry.removed || stopped) return;
7154
+ entry.paintRevision += 1;
7155
+ onDirty(entry);
7156
+ },
7157
+ onEnded: (reason) => onPaintsEnded(entry, reason)
7158
+ });
7159
+ if (!watcher) {
7160
+ reportUnavailable(entry, "unsupported");
7161
+ return;
7162
+ }
7163
+ entry.paints = watcher;
7164
+ };
7165
+ const syncPaints = (entry) => {
7166
+ const wantsPaints = isServed(entry) && trackerOf(entry) === null;
7167
+ if (wantsPaints && !entry.paints) startPaints(entry);
7168
+ else if (!wantsPaints && entry.paints) stopPaints(entry);
7169
+ };
7170
+ let readPosted = false;
7171
+ let dueTimer = null;
7172
+ let dueTimerAt = Number.POSITIVE_INFINITY;
7173
+ const clearDueTimer = () => {
7174
+ if (dueTimer !== null) scheduler.clearTimeout(dueTimer);
7175
+ dueTimer = null;
7176
+ dueTimerAt = Number.POSITIVE_INFINITY;
7177
+ };
7178
+ const armDueTimer = (at, now) => {
7179
+ if (at === Number.POSITIVE_INFINITY) {
7180
+ clearDueTimer();
7181
+ return;
7182
+ }
7183
+ if (dueTimer !== null && dueTimerAt <= at) return;
7184
+ clearDueTimer();
7185
+ dueTimerAt = at;
7186
+ dueTimer = scheduler.setTimeout(() => {
7187
+ dueTimer = null;
7188
+ dueTimerAt = Number.POSITIVE_INFINITY;
7189
+ readDue();
7190
+ }, at - now);
7191
+ };
7192
+ const postRead = () => {
7193
+ if (readPosted) return;
7194
+ readPosted = true;
7195
+ scheduler.post(readDue);
7196
+ };
7197
+ const wake = (entry) => {
7198
+ if (stopped || !isRunnable(entry)) return;
7199
+ const now = scheduler.now();
7200
+ if (now >= entry.nextDueAt) postRead();
7201
+ else armDueTimer(entry.nextDueAt, now);
7202
+ };
7203
+ const schedule = () => {
7204
+ if (stopped) return;
7205
+ const now = scheduler.now();
7206
+ let earliest = Number.POSITIVE_INFINITY;
7207
+ let anyDue = false;
7208
+ for (const entry of watched.values()) {
7209
+ if (!isRunnable(entry)) continue;
7210
+ if (now >= entry.nextDueAt) anyDue = true;
7211
+ else earliest = Math.min(earliest, entry.nextDueAt);
7212
+ }
7213
+ if (anyDue) postRead();
7214
+ armDueTimer(earliest, now);
7215
+ };
7216
+ const readDue = () => {
7217
+ readPosted = false;
7218
+ if (stopped) return;
7219
+ const now = scheduler.now();
7220
+ for (const entry of watched.values()) {
7221
+ if (isRunnable(entry) && now >= entry.nextDueAt) beginRead(entry, now);
7222
+ }
7223
+ schedule();
7224
+ };
7225
+ const onDirty = (entry) => {
7226
+ if (!isServed(entry)) return;
7227
+ touchActivity();
7228
+ wake(entry);
7229
+ };
7230
+ const readEntry = async (entry, size) => {
7231
+ try {
7232
+ const paint = await entry.paints?.read(size);
7233
+ if (paint) return paint;
7234
+ } catch {
7235
+ return null;
7236
+ }
7237
+ return sampleCanvas(entry.canvas, size);
7238
+ };
7239
+ const beginRead = (entry, now) => {
7240
+ const interval = entry.demand.maxFps > 0 ? 1e3 / entry.demand.maxFps : 0;
7241
+ const dueAgain = entry.nextDueAt + interval;
7242
+ entry.nextDueAt = now < dueAgain + interval ? dueAgain : now + interval;
7243
+ entry.sampledRevision = trackerOf(entry)?.captureStarted(entry.canvas) ?? entry.paintRevision;
7244
+ const sourceWidth = entry.canvas.width;
7245
+ const sourceHeight = entry.canvas.height;
7246
+ const demandGeneration = entry.demandGeneration;
7247
+ if (sourceWidth <= 0 || sourceHeight <= 0) {
7248
+ emitter.removed(entry.targetId);
7249
+ return;
7250
+ }
7251
+ entry.pending = true;
7252
+ void readEntry(entry, {
7253
+ width: entry.demand.width,
7254
+ height: entry.demand.height
7255
+ }).then(
7256
+ (bitmap) => {
7257
+ entry.pending = false;
7258
+ if (bitmap) {
7259
+ if (demandGeneration !== entry.demandGeneration) {
7260
+ bitmap.close();
7261
+ } else {
7262
+ entry.unavailableReported = false;
7263
+ deliver(entry, bitmap, sourceWidth, sourceHeight);
7264
+ }
7265
+ }
7266
+ schedule();
7267
+ },
7268
+ (error) => {
7269
+ entry.pending = false;
7270
+ if (demandGeneration === entry.demandGeneration && !entry.removed && !stopped) {
7271
+ reportUnavailable(entry, classifyCanvasSampleError(error));
7272
+ }
7273
+ schedule();
7274
+ }
7275
+ );
7276
+ };
7277
+ const deliver = (entry, bitmap, sourceWidth, sourceHeight) => {
7278
+ if (stopped || !isServed(entry)) {
7279
+ bitmap.close();
7280
+ return;
7281
+ }
7282
+ entry.nextFrameId += 1;
7283
+ const frameId = entry.nextFrameId;
7284
+ entry.outstanding.add(frameId);
7285
+ const delivered = emitter.frame({
7286
+ targetId: entry.targetId,
7287
+ frameId,
7288
+ bitmap,
7289
+ sourceWidth,
7290
+ sourceHeight
7291
+ });
7292
+ if (!delivered) {
7293
+ bitmap.close();
7294
+ entry.outstanding.delete(frameId);
7295
+ }
7296
+ };
7297
+ const applyDemand = (entry, next) => {
7298
+ const previous = entry.demand;
7299
+ entry.demand = next;
7300
+ if (previous.enabled !== next.enabled) entry.demandGeneration += 1;
7301
+ const sizeChanged = previous.width !== next.width || previous.height !== next.height;
7302
+ if (next.enabled && (!previous.enabled || sizeChanged)) {
7303
+ entry.sampledRevision = -1;
7304
+ }
7305
+ if (next.enabled && !previous.enabled) {
7306
+ entry.paintRestarts = 0;
7307
+ entry.paintsExhausted = false;
7308
+ }
7309
+ syncPaints(entry);
7310
+ };
7311
+ const track = (canvas) => {
7312
+ const targetId = ensureProjectionDomId(canvas);
7313
+ if (!targetId) return;
7314
+ const entry = {
7315
+ canvas,
7316
+ targetId,
7317
+ demand: DISABLED_CANVAS_FRAME_DEMAND,
7318
+ sampledRevision: -1,
7319
+ pending: false,
7320
+ demandGeneration: 0,
7321
+ nextDueAt: 0,
7322
+ nextFrameId: 0,
7323
+ outstanding: /* @__PURE__ */ new Set(),
7324
+ tracked: tracker?.isTracked(canvas) ?? false,
7325
+ paints: null,
7326
+ paintRevision: 0,
7327
+ paintRestarts: 0,
7328
+ paintRestartTimer: null,
7329
+ paintsExhausted: false,
7330
+ unsubscribe: null,
7331
+ terminal: false,
7332
+ unavailableReported: false,
7333
+ removed: false,
7334
+ armedRevision: -1
7335
+ };
7336
+ watched.set(canvas, entry);
7337
+ entry.unsubscribe = tracker?.subscribe(canvas, () => {
7338
+ if (entry.tracked && trackerOf(entry) === null) {
7339
+ entry.tracked = false;
7340
+ entry.sampledRevision = -1;
7341
+ }
7342
+ syncPaints(entry);
7343
+ onDirty(entry);
7344
+ }) ?? null;
7345
+ applyDemand(entry, demand[targetId] ?? DISABLED_CANVAS_FRAME_DEMAND);
7346
+ wake(entry);
7347
+ };
7348
+ const untrack = (canvas, notify) => {
7349
+ const entry = watched.get(canvas);
7350
+ if (!entry) return;
7351
+ entry.removed = true;
7352
+ watched.delete(canvas);
7353
+ entry.unsubscribe?.();
7354
+ entry.unsubscribe = null;
7355
+ stopPaints(entry);
7356
+ if (notify) emitter.removed(entry.targetId);
7357
+ };
7358
+ const stopRegistry = watchCanvasElements(root, {
7359
+ onAdded: (canvas) => {
7360
+ if (!stopped) track(canvas);
7361
+ },
7362
+ onRemoved: (canvas) => untrack(canvas, true)
7363
+ });
7364
+ return {
7365
+ ack(targetId, frameId) {
7366
+ for (const entry of watched.values()) {
7367
+ if (entry.targetId !== targetId) continue;
7368
+ if (entry.outstanding.delete(frameId)) wake(entry);
7369
+ return;
7370
+ }
7371
+ },
7372
+ updateDemand(entries) {
7373
+ if (stopped) return;
7374
+ demand = entries;
7375
+ for (const entry of watched.values()) {
7376
+ applyDemand(
7377
+ entry,
7378
+ entries[entry.targetId] ?? DISABLED_CANVAS_FRAME_DEMAND
7379
+ );
7380
+ }
7381
+ schedule();
7382
+ },
7383
+ stop(stopOptions = {}) {
7384
+ if (stopped) return;
7385
+ stopped = true;
7386
+ stopRegistry();
7387
+ for (const entry of [...watched.values()]) {
7388
+ untrack(entry.canvas, stopOptions.notifyRemovals ?? false);
7389
+ }
7390
+ clearDueTimer();
7391
+ if (activityTimer !== null) scheduler.clearTimeout(activityTimer);
7392
+ activityTimer = null;
7393
+ if (active) {
7394
+ active = false;
7395
+ emitter.activity(false);
7396
+ }
7397
+ own?.close();
7398
+ }
7399
+ };
7400
+ }
7401
+
7402
+ // ../../modules/iframe-projection/canvas-frames/port-protocol.ts
7403
+ function isRecord3(value) {
7404
+ return typeof value === "object" && value !== null;
7405
+ }
7406
+ function isLaneCommand(value) {
7407
+ return isRecord3(value) && typeof value.kind === "string" && value.kind.startsWith("canvas-frames:");
7408
+ }
7409
+ var DEFAULT_ROOT_POLL_MS = 250;
7410
+ function serveCanvasFramesOverPort(port, options) {
7411
+ const { resolveRoot, rootPollMs, ...watchOptions } = options;
7412
+ const own = options.scheduler ? null : createDefaultScheduler();
7413
+ const scheduler = options.scheduler ?? own;
7414
+ const pollMs = rootPollMs ?? DEFAULT_ROOT_POLL_MS;
7415
+ let disposed = false;
7416
+ let rootId = null;
7417
+ let selector;
7418
+ let demand = {};
7419
+ let root = null;
7420
+ let watcher = null;
7421
+ let pollTimer = null;
7422
+ const send = (event, transfer) => {
7423
+ if (disposed) return false;
7424
+ try {
7425
+ port.postMessage(event, transfer);
7426
+ return true;
7427
+ } catch {
7428
+ return false;
7429
+ }
7430
+ };
7431
+ const startWatcher = (current) => {
7432
+ const started = watchCanvasFrames(
7433
+ current,
7434
+ {
7435
+ frame: ({ targetId, frameId, bitmap, sourceWidth, sourceHeight }) => send(
7436
+ {
7437
+ kind: "canvas-frames:frame",
7438
+ targetId,
7439
+ frameId,
7440
+ sourceWidth,
7441
+ sourceHeight,
7442
+ bitmap
7443
+ },
7444
+ [bitmap]
7445
+ ),
7446
+ removed: (targetId, reason) => void send({ kind: "canvas-frames:removed", targetId, reason }),
7447
+ activity: (active) => void send({ kind: "canvas-frames:activity", active })
7448
+ },
7449
+ { ...watchOptions, scheduler }
7450
+ );
7451
+ watcher = started;
7452
+ root = current;
7453
+ started.updateDemand(demand);
7454
+ };
7455
+ const stopLane = () => {
7456
+ watcher?.stop();
7457
+ watcher = null;
7458
+ root = null;
7459
+ rootId = null;
7460
+ if (pollTimer !== null) scheduler.clearTimeout(pollTimer);
7461
+ pollTimer = null;
7462
+ };
7463
+ const ensureRoot = () => {
7464
+ if (rootId === null || disposed) return;
7465
+ pollTimer = null;
7466
+ try {
7467
+ if (root && !root.isConnected) {
7468
+ watcher?.stop({ notifyRemovals: true });
7469
+ watcher = null;
7470
+ root = null;
7471
+ }
7472
+ if (!root) {
7473
+ const resolved = resolveRoot(rootId, selector);
7474
+ if (resolved) startWatcher(resolved);
7475
+ }
7476
+ } finally {
7477
+ pollTimer = scheduler.setTimeout(ensureRoot, pollMs);
7478
+ }
7479
+ };
7480
+ const handle = (command) => {
7481
+ switch (command.kind) {
7482
+ case "canvas-frames:start": {
7483
+ stopLane();
7484
+ rootId = command.rootId;
7485
+ selector = command.selector;
7486
+ demand = {};
7487
+ ensureRoot();
7488
+ return;
7489
+ }
7490
+ case "canvas-frames:demand": {
7491
+ if (rootId === null) return;
7492
+ demand = command.entries;
7493
+ watcher?.updateDemand(command.entries);
7494
+ return;
7495
+ }
7496
+ case "canvas-frames:ack":
7497
+ watcher?.ack(command.targetId, command.frameId);
7498
+ return;
7499
+ }
7500
+ };
7501
+ port.onmessage = (event) => {
7502
+ if (disposed) return;
7503
+ const command = event.data;
7504
+ if (!isLaneCommand(command)) return;
7505
+ try {
7506
+ handle(command);
7507
+ } catch (error) {
7508
+ console.warn("[canvas-frames] lane command failed", error);
7509
+ }
7510
+ };
7511
+ port.start?.();
7512
+ return () => {
7513
+ if (disposed) return;
7514
+ disposed = true;
7515
+ stopLane();
7516
+ own?.close();
7517
+ port.onmessage = null;
7518
+ try {
7519
+ port.close();
7520
+ } catch {
7521
+ }
7522
+ };
7523
+ }
7524
+ function serveCanvasFrameLanes(subscribePorts, options) {
7525
+ const lanes = /* @__PURE__ */ new Set();
7526
+ const unsubscribe = subscribePorts((port) => {
7527
+ const dispose = serveCanvasFramesOverPort(port, options);
7528
+ const disposeOnce = () => {
7529
+ if (!lanes.delete(disposeOnce)) return;
7530
+ dispose();
7531
+ };
7532
+ lanes.add(disposeOnce);
7533
+ port.addEventListener?.("close", disposeOnce, { once: true });
7534
+ });
7535
+ return () => {
7536
+ unsubscribe();
7537
+ for (const dispose of [...lanes]) dispose();
7538
+ };
7539
+ }
7540
+
7541
+ // ../../modules/iframe-projection/canvas-frames/preserve-drawing-buffer.ts
7542
+ var WEBGL_CONTEXT_IDS = /* @__PURE__ */ new Set(["webgl", "webgl2", "experimental-webgl"]);
7543
+ function installPreserveDrawingBuffer(scope = globalThis) {
7544
+ const prototype = scope.HTMLCanvasElement?.prototype;
7545
+ if (!prototype) return () => {
7546
+ };
7547
+ const original = prototype.getContext;
7548
+ if (typeof original !== "function") return () => {
7549
+ };
7550
+ const callOriginal = original;
7551
+ const patched = function(contextId, attributes, ...rest) {
7552
+ const forced = WEBGL_CONTEXT_IDS.has(contextId) ? {
7553
+ ...typeof attributes === "object" && attributes !== null ? attributes : {},
7554
+ preserveDrawingBuffer: true
7555
+ } : attributes;
7556
+ return callOriginal.call(this, contextId, forced, ...rest);
7557
+ };
7558
+ prototype.getContext = patched;
7559
+ return () => {
7560
+ if (prototype.getContext === patched) prototype.getContext = original;
7561
+ };
7562
+ }
7563
+
7564
+ // canvas/interact-canvas-frames.ts
7565
+ function installTempoInteractCanvasFrameLane() {
7566
+ const restoreDrawingBuffer = installPreserveDrawingBuffer(globalThis);
7567
+ const tracker = installDrawTracker(globalThis);
7568
+ const disposeLanes = serveCanvasFrameLanes(
7569
+ (deliver) => {
7570
+ const onMessage = (event) => {
7571
+ const hit = CANVAS_FRAME_LANE_WINDOW_PORT.accept(event, window.parent);
7572
+ if (hit) deliver(hit.port);
7573
+ };
7574
+ window.addEventListener("message", onMessage);
7575
+ return () => window.removeEventListener("message", onMessage);
7576
+ },
7577
+ {
7578
+ tracker,
7579
+ // The interact producer's projection root is the document body unless
7580
+ // the renderer named a capture selector, so the rootId is never used.
7581
+ resolveRoot: (_rootId, selector) => selector ? document.querySelector(selector) : document.body
7582
+ }
7583
+ );
7584
+ return () => {
7585
+ disposeLanes();
7586
+ tracker.dispose();
7587
+ restoreDrawingBuffer();
7588
+ };
7589
+ }
7590
+
6590
7591
  // canvas/interact-projection.ts
6591
7592
  var PENDING_ROOTS_KEY = "__tempoPendingFiberRoots";
6592
7593
  function installTempoInteractProjectionSource() {
@@ -6602,10 +7603,15 @@ function installTempoInteractProjectionSource() {
6602
7603
  pendingRoots.clear();
6603
7604
  delete hook[PENDING_ROOTS_KEY];
6604
7605
  }
6605
- return startCombinedSourceInterface();
7606
+ const disposeCanvasFrames = installTempoInteractCanvasFrameLane();
7607
+ const disposeProjection = startCombinedSourceInterface();
7608
+ return () => {
7609
+ disposeProjection();
7610
+ disposeCanvasFrames();
7611
+ };
6606
7612
  }
6607
7613
 
6608
7614
  export {
6609
7615
  installTempoInteractProjectionSource
6610
7616
  };
6611
- //# sourceMappingURL=chunk-FAO5QIJG.js.map
7617
+ //# sourceMappingURL=chunk-U52RN7MP.js.map