@hyperframes/core 0.9.34 → 0.9.35

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.
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The editing channel between a preview frame and its parent: a MessagePort the
3
+ * runtime hands the parent once, carrying typed requests and replies. The
4
+ * runtime side is `editingAgent.ts`; `createEditingPortClient` is the parent
5
+ * side. Both import their wire types from here, so they cannot drift apart.
6
+ *
7
+ * Playback transport (play, pause, seek, rate, mute, play range) stays on the
8
+ * control protocol in `bridge.ts`. This channel carries the reads a parent
9
+ * otherwise takes straight off the frame's window, which an opaque-origin
10
+ * preview does not allow.
11
+ */
12
+ import type { RuntimeTimelineMessage } from "./types.js";
13
+ export declare const EDITING_PROTOCOL_VERSION: 1;
14
+ /** Parent to frame, on the window: asks the runtime for the port. */
15
+ export declare const EDITING_CONNECT = "editing-connect";
16
+ /** Frame to parent, on the window: carries the port in its transfer list. */
17
+ export declare const EDITING_PORT = "editing-port";
18
+ export declare const EDITING_REQUEST_KINDS: readonly ["hello", "runtime-snapshot", "wait-for-seek", "set-loop-start"];
19
+ export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number];
20
+ export interface EditingRuntimeSnapshot {
21
+ /** The runtime has installed its player API. */
22
+ playerReady: boolean;
23
+ /** Why the runtime failed to start, when it did. */
24
+ startupError: string | null;
25
+ /** The clip manifest the runtime last posted as its `timeline` message. */
26
+ clipManifest: RuntimeTimelineMessage | null;
27
+ /** `[childId, parentId]` for each nested clip in the runtime's clip tree. */
28
+ clipParents: Array<[string, string]>;
29
+ }
30
+ type NoParams = Record<string, never>;
31
+ export interface EditingRequests {
32
+ hello: {
33
+ params: NoParams;
34
+ result: {
35
+ version: typeof EDITING_PROTOCOL_VERSION;
36
+ kinds: string[];
37
+ };
38
+ };
39
+ "runtime-snapshot": {
40
+ params: NoParams;
41
+ result: EditingRuntimeSnapshot;
42
+ };
43
+ /** `waited` is false when the runtime has no seek-completion hook. */
44
+ "wait-for-seek": {
45
+ params: NoParams;
46
+ result: {
47
+ waited: boolean;
48
+ };
49
+ };
50
+ /** Where a looping playback wraps to; null stops looping from a custom start. */
51
+ "set-loop-start": {
52
+ params: {
53
+ seconds: number | null;
54
+ };
55
+ result: {
56
+ applied: boolean;
57
+ };
58
+ };
59
+ }
60
+ export type EditingParams<K extends EditingRequestKind> = EditingRequests[K]["params"];
61
+ export type EditingResult<K extends EditingRequestKind> = EditingRequests[K]["result"];
62
+ export type EditingErrorCode = "malformed" | "unsupported-version" | "unknown-kind" | "invalid-params" | "failed" | "timeout" | "disposed";
63
+ export type EditingReply = {
64
+ v: typeof EDITING_PROTOCOL_VERSION;
65
+ id: number;
66
+ ok: true;
67
+ result: unknown;
68
+ } | {
69
+ v: typeof EDITING_PROTOCOL_VERSION;
70
+ id: number | null;
71
+ ok: false;
72
+ error: {
73
+ code: EditingErrorCode;
74
+ message: string;
75
+ };
76
+ };
77
+ export type ParsedEditingRequest = {
78
+ ok: true;
79
+ id: number;
80
+ kind: EditingRequestKind;
81
+ params: EditingParams<EditingRequestKind>;
82
+ } | {
83
+ ok: false;
84
+ id: number | null;
85
+ code: EditingErrorCode;
86
+ message: string;
87
+ };
88
+ export declare function isPlainRecord(value: unknown): value is Record<string, unknown>;
89
+ /** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */
90
+ export declare function parseEditingRequest(data: unknown): ParsedEditingRequest;
91
+ export declare class EditingPortError extends Error {
92
+ readonly code: EditingErrorCode;
93
+ constructor(code: EditingErrorCode, message: string);
94
+ }
95
+ export interface EditingPortClient {
96
+ /** Settles when the frame's runtime has handed over its port. */
97
+ readonly ready: Promise<void>;
98
+ request<K extends EditingRequestKind>(kind: K, params: EditingParams<K>, options?: {
99
+ timeoutMs?: number;
100
+ }): Promise<EditingResult<K>>;
101
+ /** Rejects every pending request with `disposed` and closes the port. */
102
+ dispose(): void;
103
+ }
104
+ /**
105
+ * The parent's end of the editing channel for one preview frame load. Asks for
106
+ * the port at once and again on the runtime's `ready`, and takes the first port
107
+ * that frame sends. Replies are data from the frame, so callers validate results.
108
+ */
109
+ export declare function createEditingPortClient(options: {
110
+ iframe: HTMLIFrameElement;
111
+ timeoutMs?: number;
112
+ host?: Window;
113
+ }): EditingPortClient;
114
+ export {};
@@ -0,0 +1,176 @@
1
+ import { wallClearTimeout, wallSetTimeout } from "./wallClock.js";
2
+ export const EDITING_PROTOCOL_VERSION = 1;
3
+ /** Parent to frame, on the window: asks the runtime for the port. */
4
+ export const EDITING_CONNECT = "editing-connect";
5
+ /** Frame to parent, on the window: carries the port in its transfer list. */
6
+ export const EDITING_PORT = "editing-port";
7
+ export const EDITING_REQUEST_KINDS = [
8
+ "hello",
9
+ "runtime-snapshot",
10
+ "wait-for-seek",
11
+ "set-loop-start",
12
+ ];
13
+ export function isPlainRecord(value) {
14
+ return Object.prototype.toString.call(value) === "[object Object]";
15
+ }
16
+ const noParams = (params) => params === undefined || (isPlainRecord(params) && Object.keys(params).length === 0) ? {} : null;
17
+ const PARAM_PARSERS = {
18
+ hello: noParams,
19
+ "runtime-snapshot": noParams,
20
+ "wait-for-seek": noParams,
21
+ "set-loop-start": (params) => {
22
+ if (!isPlainRecord(params) || Object.keys(params).join() !== "seconds")
23
+ return null;
24
+ const { seconds } = params;
25
+ if (seconds === null)
26
+ return { seconds };
27
+ return typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0
28
+ ? { seconds }
29
+ : null;
30
+ },
31
+ };
32
+ /** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */
33
+ export function parseEditingRequest(data) {
34
+ if (!isPlainRecord(data) || !Number.isSafeInteger(data.id) || data.id < 0) {
35
+ return { ok: false, id: null, code: "malformed", message: "request needs a numeric id" };
36
+ }
37
+ const id = data.id;
38
+ if (data.v !== EDITING_PROTOCOL_VERSION) {
39
+ return { ok: false, id, code: "unsupported-version", message: "unsupported version" };
40
+ }
41
+ const kind = EDITING_REQUEST_KINDS.find((known) => known === data.kind);
42
+ if (!kind)
43
+ return { ok: false, id, code: "unknown-kind", message: "unknown request kind" };
44
+ const params = PARAM_PARSERS[kind](data.params);
45
+ if (!params)
46
+ return { ok: false, id, code: "invalid-params", message: `invalid params for ${kind}` };
47
+ return { ok: true, id, kind, params };
48
+ }
49
+ export class EditingPortError extends Error {
50
+ code;
51
+ constructor(code, message) {
52
+ super(message);
53
+ this.code = code;
54
+ this.name = "EditingPortError";
55
+ }
56
+ }
57
+ /** A reply's result or typed error. Anything off-shape is `malformed`, never a throw. */
58
+ function replyOutcome(data) {
59
+ if (data.v !== EDITING_PROTOCOL_VERSION) {
60
+ return { error: new EditingPortError("unsupported-version", "reply version") };
61
+ }
62
+ if (data.ok === true && "result" in data)
63
+ return { result: data.result };
64
+ const error = isPlainRecord(data.error) ? data.error : null;
65
+ if (data.ok !== false || typeof error?.code !== "string") {
66
+ return { error: new EditingPortError("malformed", "malformed reply") };
67
+ }
68
+ const message = typeof error.message === "string" ? error.message : error.code;
69
+ return { error: new EditingPortError(error.code, message) };
70
+ }
71
+ /** The port this frame handed over, "ready" when its runtime came up, else null. */
72
+ function readHandoff(event, frame) {
73
+ const data = event.data;
74
+ if (!frame || event.source !== frame || !isPlainRecord(data) || data.source !== "hf-preview") {
75
+ return null;
76
+ }
77
+ if (data.type === "ready")
78
+ return "ready";
79
+ return data.type === EDITING_PORT && data.v === EDITING_PROTOCOL_VERSION
80
+ ? onlyPort(event.ports)
81
+ : null;
82
+ }
83
+ const onlyPort = (ports) => ports.length === 1 ? (ports[0] ?? null) : null;
84
+ /**
85
+ * The parent's end of the editing channel for one preview frame load. Asks for
86
+ * the port at once and again on the runtime's `ready`, and takes the first port
87
+ * that frame sends. Replies are data from the frame, so callers validate results.
88
+ */
89
+ export function createEditingPortClient(options) {
90
+ const { iframe, timeoutMs = 5_000, host = window } = options;
91
+ const pending = new Map();
92
+ let port = null;
93
+ let disposed = false;
94
+ let lastId = 0;
95
+ let resolveReady;
96
+ let rejectReady;
97
+ const ready = new Promise((resolve, reject) => {
98
+ resolveReady = resolve;
99
+ rejectReady = reject;
100
+ });
101
+ void ready.catch(() => { });
102
+ const settle = (id, outcome) => {
103
+ const entry = pending.get(id);
104
+ if (!entry)
105
+ return;
106
+ pending.delete(id);
107
+ wallClearTimeout(entry.timer);
108
+ if ("error" in outcome)
109
+ entry.reject(outcome.error);
110
+ else
111
+ entry.resolve(outcome.result);
112
+ };
113
+ const onReply = (event) => {
114
+ const data = event.data;
115
+ if (isPlainRecord(data) && typeof data.id === "number")
116
+ settle(data.id, replyOutcome(data));
117
+ };
118
+ const connect = () => {
119
+ try {
120
+ iframe.contentWindow?.postMessage({ source: "hf-parent", type: EDITING_CONNECT, v: EDITING_PROTOCOL_VERSION }, "*");
121
+ }
122
+ catch {
123
+ // The frame is mid-navigation; its runtime's `ready` asks again.
124
+ }
125
+ };
126
+ const onWindowMessage = (event) => {
127
+ const handoff = readHandoff(event, iframe.contentWindow);
128
+ if (handoff === "ready")
129
+ return connect();
130
+ if (!handoff)
131
+ return;
132
+ port = handoff;
133
+ host.removeEventListener("message", onWindowMessage);
134
+ port.onmessage = onReply;
135
+ resolveReady();
136
+ };
137
+ host.addEventListener("message", onWindowMessage);
138
+ connect();
139
+ return {
140
+ ready,
141
+ request(kind, params, requestOptions) {
142
+ if (disposed)
143
+ return Promise.reject(new EditingPortError("disposed", "client disposed"));
144
+ const id = ++lastId;
145
+ const limit = requestOptions?.timeoutMs ?? timeoutMs;
146
+ const result = new Promise((resolve, reject) => {
147
+ const timer = wallSetTimeout(() => settle(id, { error: new EditingPortError("timeout", `${kind} timed out`) }), limit);
148
+ pending.set(id, { resolve, reject, timer });
149
+ });
150
+ const send = () => {
151
+ if (!pending.has(id))
152
+ return;
153
+ try {
154
+ port?.postMessage({ v: EDITING_PROTOCOL_VERSION, id, kind, params });
155
+ }
156
+ catch (err) {
157
+ settle(id, { error: new EditingPortError("failed", String(err)) });
158
+ }
159
+ };
160
+ // A ready that rejects was disposed, which has already rejected this request.
161
+ ready.then(send, () => { });
162
+ return result;
163
+ },
164
+ dispose() {
165
+ if (disposed)
166
+ return;
167
+ disposed = true;
168
+ host.removeEventListener("message", onWindowMessage);
169
+ port?.close();
170
+ rejectReady(new EditingPortError("disposed", "client disposed"));
171
+ for (const id of [...pending.keys()]) {
172
+ settle(id, { error: new EditingPortError("disposed", "client disposed") });
173
+ }
174
+ },
175
+ };
176
+ }
@@ -32,6 +32,13 @@ export declare function isSafePath(base: string, resolved: string): boolean;
32
32
  * let the symlink-escape slip past several call sites historically.
33
33
  */
34
34
  export declare function resolveWithinProject(base: string, relativePath: string): string | null;
35
+ /** Segments as Windows opens them: any case, no trailing dots or spaces, no `:stream` suffix. */
36
+ export declare function projectPathSegments(relPath: string): string[];
37
+ export declare function isVcsOrSecretPath(relPath: string): boolean;
38
+ /** Studio's private files, for a project-relative path with `/` separators: git, env, and the app's records. */
39
+ export declare function isStudioPrivatePath(relPath: string): boolean;
40
+ /** Whether `isPrivate` holds for a file under `projectDir`, spelled as given or with its links resolved. */
41
+ export declare function isPrivateFileUnder(projectDir: string, filePath: string, isPrivate: (relPath: string) => boolean): boolean;
35
42
  /** The project folder is gone, renamed or deleted while open; a write must not bring it back. */
36
43
  export declare class ProjectRootMissingError extends Error {
37
44
  readonly root: string;
package/dist/safePath.js CHANGED
@@ -102,6 +102,51 @@ export function resolveWithinProject(base, relativePath) {
102
102
  const resolved = resolve(base, relativePath);
103
103
  return isSafePath(base, resolved) ? resolved : null;
104
104
  }
105
+ /** Segments as Windows opens them: any case, no trailing dots or spaces, no `:stream` suffix. */
106
+ export function projectPathSegments(relPath) {
107
+ return relPath
108
+ .toLowerCase()
109
+ .split(/[\\/]/)
110
+ .map((segment) => withoutTrailingDotsOrSpaces(segment.split(":", 1)[0] ?? ""));
111
+ }
112
+ function withoutTrailingDotsOrSpaces(segment) {
113
+ let end = segment.length;
114
+ while (end > 0 && (segment[end - 1] === "." || segment[end - 1] === " "))
115
+ end--;
116
+ return segment.slice(0, end);
117
+ }
118
+ // Git metadata and env files hold commands other tools run and secrets: nothing serves or inlines them.
119
+ export function isVcsOrSecretPath(relPath) {
120
+ return projectPathSegments(relPath).some((segment) => segment === ".git" || segment.startsWith(".env"));
121
+ }
122
+ // `.hyperframes/` holds the desktop app's and the CLI's own records (a hand-off, chat history, read marks): Studio
123
+ // reaches none of it, the folder itself included, but its own files and the app's request pictures.
124
+ const STUDIO_FILES = new Set([
125
+ ".hyperframes/studio-motion.json",
126
+ ".hyperframes/studio-manual-edits.json",
127
+ ]);
128
+ const STUDIO_FOLDERS = [".hyperframes/prepared-assets", ".hyperframes/requests"];
129
+ /** Studio's private files, for a project-relative path with `/` separators: git, env, and the app's records. */
130
+ export function isStudioPrivatePath(relPath) {
131
+ const path = relPath.toLowerCase();
132
+ if (isVcsOrSecretPath(path))
133
+ return true;
134
+ return ((path === ".hyperframes" || path.startsWith(".hyperframes/")) &&
135
+ !STUDIO_FILES.has(path) &&
136
+ !STUDIO_FOLDERS.some((folder) => path === folder || path.startsWith(`${folder}/`)));
137
+ }
138
+ /** Whether `isPrivate` holds for a file under `projectDir`, spelled as given or with its links resolved. */
139
+ export function isPrivateFileUnder(projectDir, filePath, isPrivate) {
140
+ const rel = (from, to) => relative(from, to).split(sep).join("/");
141
+ if (isPrivate(rel(resolve(projectDir), resolve(filePath))))
142
+ return true;
143
+ try {
144
+ return isPrivate(rel(realpath(resolve(projectDir)), realpath(filePath)));
145
+ }
146
+ catch {
147
+ return false;
148
+ }
149
+ }
105
150
  /** The project folder is gone, renamed or deleted while open; a write must not bring it back. */
106
151
  export class ProjectRootMissingError extends Error {
107
152
  root;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/core",
3
- "version": "0.9.34",
3
+ "version": "0.9.35",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -289,6 +289,10 @@
289
289
  "import": "./dist/runtime/protocol.js",
290
290
  "types": "./dist/runtime/protocol.d.ts"
291
291
  },
292
+ "./runtime/editing-port": {
293
+ "import": "./dist/runtime/editingPort.js",
294
+ "types": "./dist/runtime/editingPort.d.ts"
295
+ },
292
296
  "./runtime/clip-window": {
293
297
  "import": "./dist/runtime/clipWindow.js",
294
298
  "types": "./dist/runtime/clipWindow.d.ts"
@@ -437,9 +441,9 @@
437
441
  "linkedom": "^0.18.12",
438
442
  "postcss": "^8.5.8",
439
443
  "wawoff2": "^2.0.1",
440
- "@hyperframes/lint": "0.9.34",
441
- "@hyperframes/studio-server": "0.9.34",
442
- "@hyperframes/parsers": "0.9.34"
444
+ "@hyperframes/lint": "0.9.35",
445
+ "@hyperframes/studio-server": "0.9.35",
446
+ "@hyperframes/parsers": "0.9.35"
443
447
  },
444
448
  "devDependencies": {
445
449
  "@fontsource/archivo-black": "^5.2.8",