conformtools 0.6.4 → 0.6.6

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/README.md +3 -3
  2. package/dist/account-HDXVTS5T.js +3 -0
  3. package/dist/avid-panel/MANIFEST.json +11 -0
  4. package/dist/avid-panel/avid-manifest.json +46 -0
  5. package/dist/avid-panel/icon.svg +4 -0
  6. package/dist/avid-panel/icons/conformtools.svg +4 -0
  7. package/dist/avid-panel/index.html +26 -0
  8. package/dist/avid-panel/panel.css +12 -0
  9. package/dist/avid-panel/panel.js +7 -0
  10. package/dist/bridge-D5KPIUSY.js +3 -0
  11. package/dist/browser/timeline_core_bg.wasm +0 -0
  12. package/dist/chunk-3OCQA33E.js +3 -0
  13. package/dist/chunk-3XD6NC4G.js +10 -0
  14. package/dist/chunk-5JBUCVRI.js +20 -0
  15. package/dist/chunk-5RSNFPED.js +8 -0
  16. package/dist/{chunk-BW2NQ54J.js → chunk-5SUGU2YR.js} +1 -1
  17. package/dist/{chunk-HKP4P6JN.js → chunk-6ML26TIK.js} +1 -1
  18. package/dist/chunk-7MC7M2Y5.js +3 -0
  19. package/dist/chunk-AS7IXHYM.js +19 -0
  20. package/dist/chunk-BL6L5ZBP.js +39 -0
  21. package/dist/chunk-C5IX63YF.js +3 -0
  22. package/dist/chunk-EJGVNQ3E.js +8 -0
  23. package/dist/{chunk-EPZ6NWE4.js → chunk-HGDO3OED.js} +1 -1
  24. package/dist/chunk-JV7TZDKJ.js +3 -0
  25. package/dist/chunk-LFJLRLEP.js +3 -0
  26. package/dist/chunk-NFJHWZJX.js +3 -0
  27. package/dist/{chunk-WT6NIJCB.js → chunk-NQHQKEP5.js} +1 -1
  28. package/dist/chunk-NU3X7P4N.js +3 -0
  29. package/dist/chunk-OJWIBQK4.js +376 -0
  30. package/dist/chunk-OVUCL3YY.js +5 -0
  31. package/dist/chunk-PFISREY4.js +3 -0
  32. package/dist/chunk-PFZVET7S.js +3 -0
  33. package/dist/chunk-PLRB2YXJ.js +3 -0
  34. package/dist/chunk-RFIPLBQ4.js +5 -0
  35. package/dist/chunk-SZD4C5MB.js +6 -0
  36. package/dist/chunk-TXQR2HI2.js +4 -0
  37. package/dist/chunk-UKKRZ574.js +7 -0
  38. package/dist/{chunk-EO5NIBOV.js → chunk-VS3MKKJ5.js} +1 -1
  39. package/dist/{chunk-42QQI3WX.js → chunk-X53BNWNV.js} +1 -1
  40. package/dist/{chunk-QTPCU2TF.js → chunk-XNR7M4VX.js} +1 -1
  41. package/dist/{claude-setup-BM3AAUKR.js → claude-setup-IIWUB4CE.js} +1 -1
  42. package/dist/cli.js +8 -8
  43. package/dist/conformtools-analyze +0 -0
  44. package/dist/conformtools-decode +0 -0
  45. package/dist/{cr3-wasm-WKWMEK3V.js → cr3-wasm-L2LFY3LM.js} +1 -1
  46. package/dist/{dng-wasm-Z5OVO4UI.js → dng-wasm-U6NC3MDK.js} +1 -1
  47. package/dist/{dpx-wasm-QNYXAOAJ.js → dpx-wasm-RMKEUKED.js} +1 -1
  48. package/dist/engine-P6H5P6HP.js +5 -0
  49. package/dist/{exr-wasm-BHSBJLQH.js → exr-wasm-LBAOMOZD.js} +1 -1
  50. package/dist/flame/hook/conformtools_flame/__init__.py +10 -0
  51. package/dist/flame/hook/conformtools_flame/building.py +191 -0
  52. package/dist/flame/hook/conformtools_flame/hook.py +177 -0
  53. package/dist/flame/hook/conformtools_flame/render.py +622 -0
  54. package/dist/flame/hook/conformtools_flame/util.py +33 -0
  55. package/dist/flame/hook/conformtools_flame/verbs.py +1037 -0
  56. package/dist/flame/hook/conformtools_flame_hook.py +42 -0
  57. package/dist/fonts/gfx/BarlowCondensed-Bold.ttf +0 -0
  58. package/dist/fonts/gfx/BarlowCondensed-Regular.ttf +0 -0
  59. package/dist/fonts/gfx/InstrumentSerif-Regular.ttf +0 -0
  60. package/dist/fonts/gfx/Inter-Bold.ttf +0 -0
  61. package/dist/fonts/gfx/Inter-Regular.ttf +0 -0
  62. package/dist/fonts/gfx/JetBrainsMono-Bold.ttf +0 -0
  63. package/dist/fonts/gfx/JetBrainsMono-Regular.ttf +0 -0
  64. package/dist/fonts/gfx/OFL.txt +100 -0
  65. package/dist/framing-SRCJKAYO.js +3 -0
  66. package/dist/gfx-worker.js +3 -0
  67. package/dist/h264-3ESGVT6G.js +3 -0
  68. package/dist/{h264-mxf-MWS7DDV7.js → h264-mxf-NPFS7NGH.js} +1 -1
  69. package/dist/host-relink-D6CB2VOQ.js +10 -0
  70. package/dist/hosts-W4AD2MYH.js +3 -0
  71. package/dist/http.js +3 -2
  72. package/dist/i2o-transfer +0 -0
  73. package/dist/inspect-7ASUPU73.js +68 -0
  74. package/dist/isobmff-SIOE67WL.js +3 -0
  75. package/dist/mcp.js +7 -8
  76. package/dist/media-7AUNRKHF.js +3 -0
  77. package/dist/media_core-Q2PIEV7D.js +9 -0
  78. package/dist/{media_core_bg-FGAR5KA5.js → media_core_bg-FDL7GJZP.js} +1 -1
  79. package/dist/mxf-74TTDICM.js +3 -0
  80. package/dist/nuke/panel/python/Startup/conformtools_nuke_startup.py +44 -0
  81. package/dist/nuke/panel/python/conformtools_nuke/__init__.py +10 -0
  82. package/dist/nuke/panel/python/conformtools_nuke/panel.py +217 -0
  83. package/dist/nuke/panel/python/conformtools_nuke/verbs.py +837 -0
  84. package/dist/{ops-73NR3X6R.js → ops-FSOOBXMV.js} +1 -1
  85. package/dist/peer-kit/ctpeer/__init__.py +21 -0
  86. package/dist/peer-kit/ctpeer/client.py +247 -0
  87. package/dist/peer-kit/ctpeer/neutral.py +178 -0
  88. package/dist/peer-kit/ctpeer/pairing.py +139 -0
  89. package/dist/peer-kit/ctpeer/protocol.py +209 -0
  90. package/dist/peer-kit/ctpeer/websocket.py +289 -0
  91. package/dist/premiere-uxp/index.js +5 -5
  92. package/dist/premiere-uxp/lib/clipmeta.js +6 -6
  93. package/dist/premiere-uxp/lib/ctx.js +30 -24
  94. package/dist/premiere-uxp/lib/edit.js +516 -0
  95. package/dist/premiere-uxp/lib/markers.js +5 -5
  96. package/dist/premiere-uxp/lib/pairing.js +14 -5
  97. package/dist/premiere-uxp/lib/premiere.js +10 -1
  98. package/dist/premiere-uxp/lib/probe.js +102 -0
  99. package/dist/premiere-uxp/lib/render.js +15 -8
  100. package/dist/premiere-uxp/lib/session.js +1 -1
  101. package/dist/premiere-uxp/lib/sizing.js +30 -17
  102. package/dist/premiere-uxp/lib/time.js +7 -1
  103. package/dist/premiere-uxp/lib/timeline.js +2 -2
  104. package/dist/premiere-uxp/lib/verbs.js +3 -2
  105. package/dist/premiere-uxp/lib/write.js +3 -3
  106. package/dist/premiere-uxp/manifest.json +1 -1
  107. package/dist/probe-F7WQHMIA.js +3 -0
  108. package/dist/r3d-YTLOMC7C.js +3 -0
  109. package/dist/{r3d-VUOYU2KQ.js → r3d-ZDJ3WURS.js} +1 -1
  110. package/dist/resolve-bridge.py +1262 -13
  111. package/dist/{still-4G25EYN5.js → still-ZG2RUQAL.js} +1 -1
  112. package/dist/store-ZHXLQCGN.js +3 -0
  113. package/dist/{tiff-wasm-QJPCR7JT.js → tiff-wasm-D2FJ3L56.js} +1 -1
  114. package/dist/timeline-6DYFDVEH.js +3 -0
  115. package/dist/timeline_core-IOENXK4Z.js +3 -0
  116. package/dist/wasm/media_core_bg.wasm +0 -0
  117. package/dist/wasm-threads/media_core_bg.wasm +0 -0
  118. package/dist/wav-OWMUGQMM.js +3 -0
  119. package/package.json +6 -4
  120. package/dist/chunk-6FVGUJ6L.js +0 -3
  121. package/dist/chunk-6TM32YIJ.js +0 -7
  122. package/dist/chunk-BUEIRRNY.js +0 -3
  123. package/dist/chunk-CL26XMDO.js +0 -3
  124. package/dist/chunk-DRHOPOC7.js +0 -3
  125. package/dist/chunk-GXEVALBL.js +0 -3
  126. package/dist/chunk-JB7PR2TQ.js +0 -3
  127. package/dist/chunk-QDWB7QU7.js +0 -3
  128. package/dist/chunk-QTKRMXL5.js +0 -363
  129. package/dist/chunk-SP5RGDAM.js +0 -3
  130. package/dist/chunk-TEZP6VEQ.js +0 -3
  131. package/dist/chunk-Y2BEEOPB.js +0 -3
  132. package/dist/h264-LIZVHN2W.js +0 -3
  133. package/dist/inspect-DZF537QL.js +0 -46
  134. package/dist/isobmff-HM3UPWPZ.js +0 -3
  135. package/dist/media_core-R5PPN3AY.js +0 -9
  136. package/dist/mxf-K465SWBN.js +0 -3
  137. package/dist/onnxruntime-web-stub-PKJ2NZBF.js +0 -3
  138. package/dist/r3d-RR3FUM6H.js +0 -3
  139. package/dist/sscd-embed-DHFTEIOC.js +0 -3
  140. package/dist/sscd-sweep-OYS4XAID.js +0 -3
  141. package/dist/timeline_core-VK2ZWPCO.js +0 -3
  142. package/dist/wav-63QF6SCT.js +0 -3
  143. /package/dist/{arriraw-3GKCR6K2.js → arriraw-YIJ3BYNN.js} +0 -0
  144. /package/dist/{chunk-WHY3DVXS.js → chunk-D6YDLKSA.js} +0 -0
  145. /package/dist/{media_core_bg-YK63OUDM.js → media_core_bg-XRBVKQZH.js} +0 -0
  146. /package/dist/{prores-L4JZZWGH.js → prores-RIG37OIH.js} +0 -0
  147. /package/dist/{timeline_core_bg-2TYWZ35G.js → timeline_core_bg-JW42YM3G.js} +0 -0
  148. /package/dist/{udf_bg-A4WEMSAX.js → udf_bg-B37GKRIH.js} +0 -0
@@ -0,0 +1,209 @@
1
+ """Protocol 1, peer side: the handle table and the verb dispatcher.
2
+
3
+ The app sends `{"type":"request","id":N,"method":"<capability>.<verb>",
4
+ "params":{...}}`; the peer answers `{"type":"response","id":N,"ok":true,
5
+ "result":...}` or `{"ok":false,"error":{"code","message"}}`. The dispatcher
6
+ here is the ONLY thing that turns a request into a call, and it can only call
7
+ a function the host plugin put in its verb table under that exact method name,
8
+ for a capability the plugin announced. Nothing a request carries is evaluated,
9
+ imported, opened as a path to run, or used to pick an attribute by name.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import inspect
15
+ import itertools
16
+ import threading
17
+ from typing import Any, Callable, Dict, Iterable, List, Optional
18
+
19
+ PROTOCOL_VERSION = 1
20
+ H = "$h"
21
+
22
+
23
+ class PeerError(Exception):
24
+ """A refusal the app should see with its own code (`no_timeline`,
25
+ `bad_handle`, `read_only`, ...)."""
26
+
27
+ def __init__(self, code: str, message: str = ""):
28
+ super().__init__(message or code)
29
+ self.code = code or "peer_error"
30
+ self.message = message or code
31
+
32
+
33
+ class Handles:
34
+ """Host objects behind ids this peer mints: `{"$h": "seq:3"}`. The app
35
+ only ever hands an id back. Ids are stable for the life of the peer, so a
36
+ tool can reuse one across calls. `key` says when two Python wrappers are
37
+ the same host object (Flame and Hiero hand out fresh wrappers per access),
38
+ defaulting to the object itself when it is hashable, else its id()."""
39
+
40
+ def __init__(self) -> None:
41
+ self._by_id: Dict[str, Any] = {}
42
+ self._by_key: Dict[Any, str] = {}
43
+ self._n = itertools.count(1)
44
+ self._lock = threading.Lock()
45
+
46
+ def wrap(self, kind: str, obj: Any, key: Any = None) -> Optional[Dict[str, str]]:
47
+ if obj is None:
48
+ return None
49
+ if key is None:
50
+ try:
51
+ hash(obj)
52
+ key = ("obj", obj)
53
+ except TypeError:
54
+ key = ("id", id(obj))
55
+ key = (kind, key)
56
+ with self._lock:
57
+ hid = self._by_key.get(key)
58
+ if hid is None:
59
+ hid = f"{kind}:{next(self._n)}"
60
+ self._by_key[key] = hid
61
+ self._by_id[hid] = obj # the latest wrapper for that object
62
+ return {H: hid}
63
+
64
+ def get(self, handle: Any, *kinds: str) -> Any:
65
+ hid = handle.get(H) if isinstance(handle, dict) else None
66
+ if not isinstance(hid, str) or not hid:
67
+ raise PeerError("bad_handle", "not a handle")
68
+ kind = hid.split(":", 1)[0]
69
+ if kinds and kind not in kinds:
70
+ raise PeerError("bad_handle", f"expected a {' or '.join(kinds)}, got {hid}")
71
+ with self._lock:
72
+ if hid not in self._by_id:
73
+ raise PeerError("bad_handle", f"unknown handle {hid}")
74
+ return self._by_id[hid]
75
+
76
+ @staticmethod
77
+ def kind_of(handle: Any) -> str:
78
+ hid = handle.get(H) if isinstance(handle, dict) else None
79
+ return hid.split(":", 1)[0] if isinstance(hid, str) else ""
80
+
81
+ @staticmethod
82
+ def id_of(handle: Any) -> str:
83
+ return str(handle.get(H) or "") if isinstance(handle, dict) else ""
84
+
85
+ def clear(self) -> None:
86
+ with self._lock:
87
+ self._by_id.clear()
88
+ self._by_key.clear()
89
+
90
+ def __len__(self) -> int:
91
+ return len(self._by_id)
92
+
93
+
94
+ #: The attribute `off_main` sets (read through bound methods too).
95
+ OFF_MAIN_ATTR = "ctpeer_off_main"
96
+
97
+
98
+ def off_main(fn: Callable[..., Any]) -> Callable[..., Any]:
99
+ """Mark a verb that must NOT wait for the host's main thread: it touches
100
+ no host API (a job table, the file system) and has to answer while the
101
+ main thread is busy - Flame's foreground export holds it for the whole
102
+ render, and a status poll queued behind it would time out. The
103
+ Dispatcher runs a marked verb directly on its worker thread."""
104
+ setattr(fn, OFF_MAIN_ATTR, True)
105
+ return fn
106
+
107
+
108
+ def _accepted_params(fn: Callable[..., Any]) -> Optional[frozenset]:
109
+ """The keyword names `fn` takes, or None when it takes **kwargs."""
110
+ try:
111
+ sig = inspect.signature(fn)
112
+ except (TypeError, ValueError):
113
+ return None
114
+ names = set()
115
+ for p in sig.parameters.values():
116
+ if p.kind == p.VAR_KEYWORD:
117
+ return None
118
+ if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY):
119
+ names.add(p.name)
120
+ return frozenset(names)
121
+
122
+
123
+ class Dispatcher:
124
+ """`handle(message) -> response`. Never raises."""
125
+
126
+ def __init__(self, verbs: Dict[str, Callable[..., Any]], capabilities: Iterable[str],
127
+ run_on_main: Optional[Callable[[Callable[[], Any]], Any]] = None,
128
+ log: Optional[Callable[[str], None]] = None):
129
+ self.verbs = dict(verbs)
130
+ self.capabilities = list(capabilities)
131
+ self.run_on_main = run_on_main or (lambda fn: fn())
132
+ self.log = log or (lambda line: None)
133
+ self._accepts = {m: _accepted_params(fn) for m, fn in self.verbs.items()}
134
+ self.calls: List[str] = []
135
+
136
+ def handle(self, message: Any) -> Dict[str, Any]:
137
+ rid = message.get("id") if isinstance(message, dict) else None
138
+ if not isinstance(message, dict) or message.get("type") != "request":
139
+ return _error(rid, "bad_request", "not a request")
140
+ method = message.get("method")
141
+ if not isinstance(method, str):
142
+ return _error(rid, "bad_request", "method is not a string")
143
+ params = message.get("params") or {}
144
+ if not isinstance(params, dict):
145
+ return _error(rid, "bad_request", "params is not an object")
146
+ capability = method.split(".", 1)[0]
147
+ if capability not in self.capabilities:
148
+ return _error(rid, "capability_missing", f"{capability} is not supported")
149
+ fn = self.verbs.get(method)
150
+ if fn is None:
151
+ return _error(rid, "unknown_method", method)
152
+ accepts = self._accepts.get(method)
153
+ # A param this verb does not take is dropped (an app newer than the
154
+ # plugin may add an optional one), never passed through by name.
155
+ kwargs = {str(k): v for k, v in params.items() if accepts is None or str(k) in accepts}
156
+ self.calls.append(method)
157
+ try:
158
+ if getattr(fn, OFF_MAIN_ATTR, False):
159
+ result = fn(**kwargs) # touches no host API (see `off_main`)
160
+ else:
161
+ result = self.run_on_main(lambda: fn(**kwargs))
162
+ except PeerError as e:
163
+ return _error(rid, e.code, e.message)
164
+ except TypeError as e:
165
+ self.log(f"{method}: {e}")
166
+ return _error(rid, "bad_params", str(e))
167
+ except Exception as e: # a plugin answers with an error, it does not die
168
+ self.log(f"{method}: {type(e).__name__}: {e}")
169
+ return _error(rid, getattr(e, "code", None) or "peer_error", str(e) or type(e).__name__)
170
+ return {"type": "response", "id": rid, "ok": True, "result": result}
171
+
172
+
173
+ def _error(rid: Any, code: str, message: str) -> Dict[str, Any]:
174
+ return {"type": "response", "id": rid, "ok": False, "error": {"code": str(code), "message": str(message)}}
175
+
176
+
177
+ def hello(token: str, host: Dict[str, Any], capabilities: Iterable[str], optional_verbs: Iterable[str] = ()) -> Dict[str, Any]:
178
+ return {"type": "hello", "protocol": PROTOCOL_VERSION, "token": token, "host": dict(host),
179
+ "capabilities": list(capabilities), "optional_verbs": list(optional_verbs)}
180
+
181
+
182
+ def idle_marshaller(schedule: Callable[[Callable[[], None]], Any], timeout: float = 25.0) -> Callable[[Callable[[], Any]], Any]:
183
+ """A `run_on_main` built from a host's "run this on the main thread later"
184
+ (Flame: `flame.schedule_idle_event`; Qt: a single-shot timer). The calling
185
+ thread waits for the result; an exception is re-raised here. When called
186
+ ON the main thread it runs inline (waiting would deadlock)."""
187
+
188
+ def run_on_main(fn: Callable[[], Any]) -> Any:
189
+ if threading.current_thread() is threading.main_thread():
190
+ return fn()
191
+ done = threading.Event()
192
+ box: Dict[str, Any] = {}
193
+
194
+ def task() -> None:
195
+ try:
196
+ box["result"] = fn()
197
+ except BaseException as e: # carried back to the waiting thread
198
+ box["error"] = e
199
+ finally:
200
+ done.set()
201
+
202
+ schedule(task)
203
+ if not done.wait(timeout):
204
+ raise PeerError("main_thread_busy", f"the host's main thread did not run the call within {timeout:g} s")
205
+ if "error" in box:
206
+ raise box["error"]
207
+ return box.get("result")
208
+
209
+ return run_on_main
@@ -0,0 +1,289 @@
1
+ """A small RFC 6455 WebSocket CLIENT on the standard library only.
2
+
3
+ Flame and Nuke ship their own Pythons (3.9 - 3.13) and we may not install a
4
+ package into either, so this is the whole transport: a TCP socket to the app's
5
+ loopback bridge, the HTTP upgrade, and text frames. Only what the host bridge
6
+ uses is here - no TLS (loopback only; `connect` refuses anything that is not
7
+ `ws://127.0.0.1` or `ws://localhost`), no extensions, no binary messages.
8
+
9
+ * Client frames are MASKED (RFC 6455 5.3) with a fresh key from `os.urandom`.
10
+ * Server frames must NOT be masked; a masked one is a protocol error.
11
+ * Fragmented messages are reassembled; control frames may interleave.
12
+ * A ping is answered with a pong carrying the same payload.
13
+ * `max_message` caps a reassembled message (the bridge's own cap is 8 MiB).
14
+ * A close frame is answered once and ends the conversation.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import hashlib
21
+ import os
22
+ import socket
23
+ import struct
24
+ import threading
25
+ from typing import Optional, Tuple
26
+ from urllib.parse import urlparse
27
+
28
+ GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
29
+ MAX_MESSAGE_BYTES = 8 * 1024 * 1024
30
+
31
+ OP_CONT, OP_TEXT, OP_BINARY, OP_CLOSE, OP_PING, OP_PONG = 0x0, 0x1, 0x2, 0x8, 0x9, 0xA
32
+ LOOPBACK_HOSTS = ("127.0.0.1", "localhost")
33
+
34
+
35
+ class WebSocketError(Exception):
36
+ """The connection failed or the peer broke the protocol."""
37
+
38
+
39
+ class ConnectionClosed(WebSocketError):
40
+ def __init__(self, code: int = 1000, reason: str = ""):
41
+ super().__init__(f"closed ({code}) {reason}".strip())
42
+ self.code = code
43
+ self.reason = reason
44
+
45
+
46
+ def parse_loopback_url(url: str) -> Tuple[str, int, str]:
47
+ """`ws://127.0.0.1:48127/host-bridge` -> (host, port, path). Anything that
48
+ is not plain ws:// on loopback is refused: this client never leaves the
49
+ machine."""
50
+ u = urlparse(str(url or ""))
51
+ if u.scheme != "ws":
52
+ raise WebSocketError(f"not a ws:// url: {url!r}")
53
+ host = (u.hostname or "").lower()
54
+ if host not in LOOPBACK_HOSTS:
55
+ raise WebSocketError(f"refusing a non-loopback host: {host!r}")
56
+ if not u.port:
57
+ raise WebSocketError("the url has no port")
58
+ return host, int(u.port), u.path or "/"
59
+
60
+
61
+ def accept_key(key: str) -> str:
62
+ return base64.b64encode(hashlib.sha1((key + GUID).encode("ascii")).digest()).decode("ascii")
63
+
64
+
65
+ def mask(payload: bytes, key: bytes) -> bytes:
66
+ if not payload:
67
+ return b""
68
+ # XOR in one go: int arithmetic is much faster than a per-byte loop on 8 MiB.
69
+ n = len(payload)
70
+ k = (key * (n // 4 + 1))[:n]
71
+ return (int.from_bytes(payload, "big") ^ int.from_bytes(k, "big")).to_bytes(n, "big")
72
+
73
+
74
+ def encode_frame(opcode: int, payload: bytes, masked: bool = True, fin: bool = True, key: Optional[bytes] = None) -> bytes:
75
+ head = bytearray([(0x80 if fin else 0) | (opcode & 0x0F)])
76
+ n = len(payload)
77
+ mbit = 0x80 if masked else 0
78
+ if n < 126:
79
+ head.append(mbit | n)
80
+ elif n < 1 << 16:
81
+ head.append(mbit | 126)
82
+ head += struct.pack("!H", n)
83
+ else:
84
+ head.append(mbit | 127)
85
+ head += struct.pack("!Q", n)
86
+ if masked:
87
+ key = key or os.urandom(4)
88
+ return bytes(head) + key + mask(payload, key)
89
+ return bytes(head) + payload
90
+
91
+
92
+ class WebSocket:
93
+ """One client connection. `recv()` returns the next TEXT message (str) or
94
+ raises `ConnectionClosed`; `send_text` is thread-safe."""
95
+
96
+ def __init__(self, sock: socket.socket, max_message: int = MAX_MESSAGE_BYTES):
97
+ self.sock = sock
98
+ self.max_message = int(max_message)
99
+ self._send_lock = threading.Lock()
100
+ self._buf = b""
101
+ self.closed = False
102
+
103
+ # -- connecting ------------------------------------------------------
104
+ @classmethod
105
+ def connect(cls, url: str, timeout: float = 5.0, max_message: int = MAX_MESSAGE_BYTES) -> "WebSocket":
106
+ host, port, path = parse_loopback_url(url)
107
+ try:
108
+ sock = socket.create_connection((host, port), timeout=timeout)
109
+ except OSError as e:
110
+ raise WebSocketError(f"cannot reach {host}:{port}: {e}") from e
111
+ try:
112
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
113
+ key = base64.b64encode(os.urandom(16)).decode("ascii")
114
+ # No Origin header: the bridge refuses browser origins, and a native
115
+ # client has none (host_bridge.rs `origin_allowed`).
116
+ request = (
117
+ f"GET {path} HTTP/1.1\r\n"
118
+ f"Host: {host}:{port}\r\n"
119
+ "Upgrade: websocket\r\n"
120
+ "Connection: Upgrade\r\n"
121
+ f"Sec-WebSocket-Key: {key}\r\n"
122
+ "Sec-WebSocket-Version: 13\r\n\r\n"
123
+ )
124
+ sock.sendall(request.encode("ascii"))
125
+ ws = cls(sock, max_message)
126
+ head = ws._read_http_head()
127
+ status, headers = _parse_http_head(head)
128
+ if status != 101:
129
+ raise WebSocketError(f"upgrade refused: HTTP {status}")
130
+ if headers.get("upgrade", "").lower() != "websocket" or "upgrade" not in headers.get("connection", "").lower():
131
+ raise WebSocketError("the server did not switch to websocket")
132
+ if headers.get("sec-websocket-accept", "") != accept_key(key):
133
+ raise WebSocketError("bad Sec-WebSocket-Accept")
134
+ sock.settimeout(None)
135
+ return ws
136
+ except BaseException:
137
+ try:
138
+ sock.close()
139
+ except OSError:
140
+ pass
141
+ raise
142
+
143
+ def _read_http_head(self) -> bytes:
144
+ while b"\r\n\r\n" not in self._buf:
145
+ if len(self._buf) > 16384:
146
+ raise WebSocketError("HTTP head too large")
147
+ chunk = self.sock.recv(4096)
148
+ if not chunk:
149
+ raise WebSocketError("connection closed during the upgrade")
150
+ self._buf += chunk
151
+ head, _, rest = self._buf.partition(b"\r\n\r\n")
152
+ self._buf = rest
153
+ return head
154
+
155
+ # -- low level -------------------------------------------------------
156
+ def _read_exact(self, n: int) -> bytes:
157
+ while len(self._buf) < n:
158
+ try:
159
+ chunk = self.sock.recv(max(65536, n - len(self._buf)))
160
+ except OSError as e:
161
+ raise ConnectionClosed(1006, str(e)) from e
162
+ if not chunk:
163
+ raise ConnectionClosed(1006, "connection lost")
164
+ self._buf += chunk
165
+ out, self._buf = self._buf[:n], self._buf[n:]
166
+ return out
167
+
168
+ def _read_frame(self) -> Tuple[bool, int, bytes]:
169
+ b1, b2 = self._read_exact(2)
170
+ fin = bool(b1 & 0x80)
171
+ if b1 & 0x70:
172
+ raise WebSocketError("reserved bits set (no extension was negotiated)")
173
+ opcode = b1 & 0x0F
174
+ masked = bool(b2 & 0x80)
175
+ n = b2 & 0x7F
176
+ if n == 126:
177
+ (n,) = struct.unpack("!H", self._read_exact(2))
178
+ elif n == 127:
179
+ (n,) = struct.unpack("!Q", self._read_exact(8))
180
+ if masked:
181
+ raise WebSocketError("a server frame must not be masked")
182
+ if opcode >= 0x8 and (n > 125 or not fin):
183
+ raise WebSocketError("bad control frame")
184
+ if n > self.max_message:
185
+ raise WebSocketError(f"frame of {n} bytes exceeds the {self.max_message} byte cap")
186
+ return fin, opcode, self._read_exact(n)
187
+
188
+ def _send_frame(self, opcode: int, payload: bytes) -> None:
189
+ data = encode_frame(opcode, payload, masked=True)
190
+ with self._send_lock:
191
+ if self.closed and opcode != OP_CLOSE:
192
+ raise ConnectionClosed(1006, "already closed")
193
+ try:
194
+ self.sock.sendall(data)
195
+ except OSError as e:
196
+ raise ConnectionClosed(1006, str(e)) from e
197
+
198
+ # -- public ----------------------------------------------------------
199
+ def send_text(self, text: str) -> None:
200
+ payload = text.encode("utf-8")
201
+ if len(payload) > self.max_message:
202
+ raise WebSocketError(f"message of {len(payload)} bytes exceeds the {self.max_message} byte cap")
203
+ self._send_frame(OP_TEXT, payload)
204
+
205
+ def ping(self, payload: bytes = b"") -> None:
206
+ self._send_frame(OP_PING, payload[:125])
207
+
208
+ def recv(self) -> str:
209
+ """The next complete text message. Pings are answered, pongs ignored,
210
+ a close is acknowledged and raised as `ConnectionClosed`."""
211
+ parts = []
212
+ size = 0
213
+ opcode0 = None
214
+ while True:
215
+ fin, opcode, payload = self._read_frame()
216
+ if opcode == OP_PING:
217
+ self._send_frame(OP_PONG, payload)
218
+ continue
219
+ if opcode == OP_PONG:
220
+ continue
221
+ if opcode == OP_CLOSE:
222
+ code = struct.unpack("!H", payload[:2])[0] if len(payload) >= 2 else 1005
223
+ reason = payload[2:].decode("utf-8", "replace")
224
+ self._close_reply(payload[:2] if len(payload) >= 2 else b"")
225
+ raise ConnectionClosed(code, reason)
226
+ if opcode == OP_CONT:
227
+ if opcode0 is None:
228
+ raise WebSocketError("continuation without a first frame")
229
+ elif opcode in (OP_TEXT, OP_BINARY):
230
+ if opcode0 is not None:
231
+ raise WebSocketError("new message inside a fragmented one")
232
+ opcode0 = opcode
233
+ else:
234
+ raise WebSocketError(f"unknown opcode {opcode}")
235
+ size += len(payload)
236
+ if size > self.max_message:
237
+ raise WebSocketError(f"message exceeds the {self.max_message} byte cap")
238
+ parts.append(payload)
239
+ if fin:
240
+ if opcode0 == OP_BINARY:
241
+ raise WebSocketError("binary messages are not part of the protocol")
242
+ try:
243
+ return b"".join(parts).decode("utf-8")
244
+ except UnicodeDecodeError as e:
245
+ raise WebSocketError("text frame is not UTF-8") from e
246
+
247
+ def _close_reply(self, code: bytes) -> None:
248
+ if self.closed:
249
+ return
250
+ try:
251
+ self._send_frame(OP_CLOSE, code)
252
+ except WebSocketError:
253
+ pass
254
+ self.closed = True
255
+ self._shutdown()
256
+
257
+ def close(self, code: int = 1000, reason: str = "") -> None:
258
+ if self.closed:
259
+ return
260
+ try:
261
+ self._send_frame(OP_CLOSE, struct.pack("!H", code) + reason.encode("utf-8")[:120])
262
+ except WebSocketError:
263
+ pass
264
+ self.closed = True
265
+ self._shutdown()
266
+
267
+ def _shutdown(self) -> None:
268
+ try:
269
+ self.sock.shutdown(socket.SHUT_RDWR)
270
+ except OSError:
271
+ pass
272
+ try:
273
+ self.sock.close()
274
+ except OSError:
275
+ pass
276
+
277
+
278
+ def _parse_http_head(head: bytes):
279
+ lines = head.decode("latin-1").split("\r\n")
280
+ try:
281
+ status = int(lines[0].split(" ", 2)[1])
282
+ except (IndexError, ValueError) as e:
283
+ raise WebSocketError(f"bad HTTP status line: {lines[0]!r}") from e
284
+ headers = {}
285
+ for line in lines[1:]:
286
+ k, sep, v = line.partition(":")
287
+ if sep:
288
+ headers[k.strip().lower()] = v.strip()
289
+ return status, headers
@@ -23,12 +23,12 @@ const os = (() => { try { return require("os"); } catch (_) { return null; } })(
23
23
  const home = os && os.homedir ? os.homedir() : "";
24
24
  const platform = P.platform();
25
25
 
26
- async function readFileAt(path) {
26
+ async function entryAt(path) {
27
27
  if (!lfs) throw new Error("no file system access");
28
- const url = platform === "win32" ? `file:///${path.replace(/\\/g, "/")}` : `file://${path}`;
29
- const entry = await lfs.getEntryWithUrl(url);
30
- return entry.read();
28
+ return lfs.getEntryWithUrl(platform === "win32" ? `file:///${path.replace(/\\/g, "/")}` : `file://${path}`);
31
29
  }
30
+ const readFileAt = async (path) => (await entryAt(path)).read();
31
+ const mtimeAt = async (path) => +new Date((await (await entryAt(path)).getMetadata()).dateModified);
32
32
 
33
33
  async function pickedFolderRead() {
34
34
  const token = localStorage.getItem("conformtools.pairingFolder");
@@ -40,7 +40,7 @@ async function pickedFolderRead() {
40
40
 
41
41
  const readPairing = makeReader({
42
42
  candidates: () => (home ? dataDirs(home, platform) : []),
43
- readFileAt, pickedFolderRead, storage: localStorage,
43
+ readFileAt, mtimeAt, pickedFolderRead, storage: localStorage,
44
44
  });
45
45
 
46
46
  const client = new BridgeClient({
@@ -122,12 +122,12 @@ const verbs = {
122
122
  const project = await activeProject();
123
123
  if (!project) throw new PeerError("no_project", "No project open");
124
124
  if (key === "Clip Name") {
125
- const n = await transact(project, "Rename clip", async (add) => { add(await P.callAny(item, ["createSetNameAction"], String(value))); });
125
+ const n = await transact(project, "Rename clip", async (add) => { add(() => P.callAnySync(item, ["createSetNameAction"], String(value))); });
126
126
  return n > 0;
127
127
  }
128
128
  if (key === "Clip Color") {
129
129
  const c = asClip(item);
130
- const n = await transact(project, "Clip label", async (add) => { add(await P.callAny(c, ["createSetColorLabelAction"], Number(value))); });
130
+ const n = await transact(project, "Clip label", async (add) => { add(() => P.callAnySync(c, ["createSetColorLabelAction"], Number(value))); });
131
131
  return n > 0;
132
132
  }
133
133
  if (READONLY.has(key)) return false;
@@ -137,7 +137,7 @@ const verbs = {
137
137
  const xml = await xmpOf(item);
138
138
  if (!xml) return false;
139
139
  const next = xmpSet(xml, field, value);
140
- const n = await transact(project, `Set ${key}`, async (add) => { add(await ppro.Metadata.createSetXMPMetadataAction(item, next)); });
140
+ const n = await transact(project, `Set ${key}`, async (add) => { add(() => ppro.Metadata.createSetXMPMetadataAction(item, next)); });
141
141
  return n > 0;
142
142
  },
143
143
  /** Several writes as ONE transaction = one undo step in Premiere. Only
@@ -154,11 +154,11 @@ const verbs = {
154
154
  const { clip, key, value } = list[i] || {};
155
155
  try {
156
156
  const item = g(clip);
157
- if (key === "Clip Name") { add(await P.callAny(item, ["createSetNameAction"], String(value))); results[i] = true; }
157
+ if (key === "Clip Name") { add(() => P.callAnySync(item, ["createSetNameAction"], String(value))); results[i] = true; }
158
158
  else if (key === "Clip Color") { add(await P.callAny(asClip(item), ["createSetColorLabelAction"], Number(value))); results[i] = true; }
159
159
  else if (!READONLY.has(key) && XMP_FIELDS[key]) {
160
160
  const xml = xmpSet(await xmpOf(item), XMP_FIELDS[key], String(value));
161
- add(await P.callAny(ppro.Metadata, ["createSetXMPMetadataAction"], item, xml)); results[i] = true;
161
+ add(() => P.callAnySync(ppro.Metadata, ["createSetXMPMetadataAction"], item, xml)); results[i] = true;
162
162
  }
163
163
  } catch (_) { results[i] = false; }
164
164
  }
@@ -167,4 +167,4 @@ const verbs = {
167
167
  },
168
168
  };
169
169
 
170
- module.exports = { verbs, XMP_FIELDS, xmpGet, xmpSet, clipProps, h };
170
+ module.exports = { verbs, XMP_FIELDS, xmpGet, xmpSet, clipProps, h, isFolderItem: isFolder };
@@ -8,39 +8,45 @@ const P = require("./premiere");
8
8
 
9
9
  const handles = new Handles();
10
10
 
11
- /** Run `build()` to collect actions, then commit them as one undo step.
11
+ /** Run `build(add)` to collect the batch, then commit it as ONE transaction = one undo step.
12
12
  *
13
- * MEASURED on Premiere Pro 26.2.2: `project.lockedAccess(fn)` takes a
14
- * SYNCHRONOUS callback - an async one returns at its first `await`, the lock
15
- * is released, and the work runs later outside it (the first live pass saw
16
- * every write report "0 actions" while the renames still landed). So the
17
- * callback here never awaits: when `build` and the `create*Action` calls are
18
- * synchronous, creation and commit both happen under the lock (the 26.3
19
- * contract); when they are not, creation finishes outside and only the
20
- * commit is taken under the lock, which 26.2 accepts. */
13
+ * `add(x, onError?)` takes an action or, better, a THUNK that makes one. MEASURED 26.5.2 (2026-10-19): every
14
+ * clip action (createSetNameAction, createSetDisabledAction, createSetEndAction, a param's createSetValueAction)
15
+ * must be MADE inside project.lockedAccess(), whose callback is synchronous ("Requires locked access" /
16
+ * "The script object is no longer valid" when made outside and committed later); marker actions are not checked.
17
+ * So: `build` does every async read first, the thunks make the actions synchronously under the lock, and the
18
+ * same callback commits them. A thunk that throws fails only its own op (`onError`), never the batch.
19
+ * MEASURED 26.2.2: factories may return promises there; those are resolved outside and committed under the lock. */
21
20
  const isThenable = (x) => !!x && typeof x.then === "function";
22
21
 
23
22
  async function transact(project, label, build) {
24
- const actions = [];
25
- const add = (a) => { if (a) actions.push(a); };
26
- const commit = () => {
23
+ const items = [];
24
+ const add = (a, onError) => { if (a) items.push({ a, onError }); };
25
+ const built = build(add);
26
+ if (isThenable(built)) await built;
27
+ const make = () => {
28
+ const out = [];
29
+ for (const { a, onError } of items) {
30
+ try { const x = typeof a === "function" ? a() : a; if (x) out.push(x); }
31
+ catch (e) { if (onError) onError(e); else throw e; }
32
+ }
33
+ return out;
34
+ };
35
+ const commit = (actions) => {
27
36
  if (!actions.length) return 0;
28
37
  project.executeTransaction((compound) => { for (const a of actions) compound.addAction(a); }, label);
29
38
  return actions.length;
30
39
  };
31
- const locked = P.has(project, "lockedAccess");
32
- let built = null;
33
- let n = null;
34
- const start = () => {
35
- built = build(add);
36
- if (!isThenable(built) && !actions.some(isThenable)) n = commit();
37
- };
38
- if (locked) project.lockedAccess(start); else start();
40
+ if (!P.has(project, "lockedAccess")) return commit(await Promise.all(make()));
41
+ let n = null, err = null, pending = null;
42
+ project.lockedAccess(() => {
43
+ try { const acts = make(); if (acts.some(isThenable)) pending = acts; else n = commit(acts); } catch (e) { err = e; }
44
+ });
45
+ if (err) throw err;
39
46
  if (n !== null) return n;
40
- // The builder (or an action factory) is asynchronous: finish it here.
41
- if (isThenable(built)) await built;
42
- for (let i = 0; i < actions.length; i++) if (isThenable(actions[i])) actions[i] = await actions[i];
43
- if (locked) project.lockedAccess(() => { n = commit(); }); else n = commit();
47
+ const acts = await Promise.all(pending);
48
+ project.lockedAccess(() => { try { n = commit(acts); } catch (e) { err = e; } });
49
+ if (err) throw err;
44
50
  return n;
45
51
  }
46
52