paseo-plugin-genui 0.1.0 → 0.1.2

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.
@@ -1,4 +1,5 @@
1
1
  import { Icon as PaseoIcon, Modal } from "@getpaseo/plugin/client/react-native";
2
+ import { ImageLightbox } from "./image-lightbox";
2
3
  import { ExternalLink } from "@getpaseo/plugin/client/ui";
3
4
  import React, { useContext, useEffect, useState } from "react";
4
5
  import { Image as RNImage, Pressable, StyleSheet, Text as RNText, View } from "react-native";
@@ -174,13 +175,17 @@ export function LoadedImageView({
174
175
  src,
175
176
  alt,
176
177
  height = 200,
178
+ zoomable = true,
177
179
  }: {
178
180
  src: string;
179
181
  alt?: string | null;
180
182
  height?: number;
183
+ /** Tapping opens the image full size; off where the image sits inside another tap target. */
184
+ zoomable?: boolean;
181
185
  }) {
182
186
  const { theme, loadImage } = useUiRuntime();
183
187
  const [state, setState] = useState<ImageUrl | null>(null);
188
+ const [zoomed, setZoomed] = useState(false);
184
189
 
185
190
  useEffect(() => {
186
191
  if (!loadImage || !src) return;
@@ -227,22 +232,33 @@ export function LoadedImageView({
227
232
  );
228
233
  }
229
234
 
235
+ const picture = (frameHeight: number) => (
236
+ <RNImage
237
+ source={{ uri: state.url }}
238
+ accessibilityLabel={alt ?? src}
239
+ resizeMode="contain"
240
+ style={{
241
+ width: "100%",
242
+ height: frameHeight,
243
+ borderRadius: 8,
244
+ backgroundColor: theme.colors.surface2,
245
+ }}
246
+ />
247
+ );
248
+
230
249
  return (
231
250
  <View style={{ gap: 4 }}>
232
- <RNImage
233
- source={{ uri: state.url }}
234
- accessibilityLabel={alt ?? src}
235
- resizeMode="contain"
236
- style={{
237
- width: "100%",
238
- height,
239
- borderRadius: 8,
240
- backgroundColor: theme.colors.surface2,
241
- }}
242
- />
251
+ {zoomable ? (
252
+ <Pressable accessibilityRole="imagebutton" accessibilityLabel={`View ${alt ?? src} full size`} onPress={() => setZoomed(true)}>
253
+ {picture(height)}
254
+ </Pressable>
255
+ ) : (
256
+ picture(height)
257
+ )}
243
258
  {alt ? (
244
259
  <RNText style={{ color: theme.colors.foregroundMuted, fontSize: 11.5 }}>{alt}</RNText>
245
260
  ) : null}
261
+ {zoomed ? <ImageLightbox uri={state.url} title={alt ?? src} onClose={() => setZoomed(false)} /> : null}
246
262
  </View>
247
263
  );
248
264
  }
@@ -0,0 +1,110 @@
1
+ import React, { useEffect, useState } from "react";
2
+ import {
3
+ Image,
4
+ Modal,
5
+ Platform,
6
+ Pressable,
7
+ ScrollView,
8
+ StyleSheet,
9
+ Text,
10
+ useWindowDimensions,
11
+ View,
12
+ } from "react-native";
13
+
14
+ /**
15
+ * A fullscreen image viewer, like the one Paseo uses for chat images. The plugin
16
+ * SDK exposes no call to open the host's, so this is built on React Native's Modal,
17
+ * which covers the whole window. Click the image to switch between fit and actual size.
18
+ */
19
+ export function ImageLightbox({
20
+ uri,
21
+ title,
22
+ onClose,
23
+ }: {
24
+ uri: string;
25
+ title: string;
26
+ onClose(): void;
27
+ }) {
28
+ const viewport = useWindowDimensions();
29
+ const [natural, setNatural] = useState<{ width: number; height: number } | null>(null);
30
+ const [actual, setActual] = useState(false);
31
+
32
+ useEffect(() => {
33
+ let live = true;
34
+ Image.getSize(
35
+ uri,
36
+ (width, height) => {
37
+ if (live) setNatural({ width, height });
38
+ },
39
+ () => undefined,
40
+ );
41
+ return () => {
42
+ live = false;
43
+ };
44
+ }, [uri]);
45
+
46
+ const stageWidth = viewport.width;
47
+ const stageHeight = Math.max(200, viewport.height - 96);
48
+ const fit = natural === null ? 1 : Math.min(stageWidth / natural.width, stageHeight / natural.height, 1);
49
+ const scale = actual ? 1 : fit;
50
+ const shown = natural === null ? null : { width: natural.width * scale, height: natural.height * scale };
51
+ const zoomable = natural !== null && fit < 1;
52
+
53
+ return (
54
+ <Modal transparent animationType="fade" visible onRequestClose={onClose} statusBarTranslucent>
55
+ <View style={styles.backdrop}>
56
+ <View style={styles.header}>
57
+ <Text numberOfLines={1} style={styles.title}>
58
+ {title}
59
+ {natural !== null ? ` ${natural.width} × ${natural.height}` : ""}
60
+ </Text>
61
+ {natural !== null ? <Text style={styles.percent}>{Math.round(scale * 100)}%</Text> : null}
62
+ <Pressable accessibilityRole="button" accessibilityLabel="Close" hitSlop={12} onPress={onClose} style={styles.close}>
63
+ <Text style={styles.closeText}>✕</Text>
64
+ </Pressable>
65
+ </View>
66
+ <ScrollView
67
+ style={styles.stage}
68
+ contentContainerStyle={{ minHeight: stageHeight, minWidth: stageWidth, alignItems: "center", justifyContent: "center" }}
69
+ horizontal={actual}
70
+ maximumZoomScale={4}
71
+ centerContent
72
+ >
73
+ <ScrollView
74
+ contentContainerStyle={{ minHeight: stageHeight, justifyContent: "center", alignItems: "center" }}
75
+ scrollEnabled={actual}
76
+ >
77
+ <Pressable
78
+ accessibilityRole="imagebutton"
79
+ accessibilityLabel={zoomable ? (actual ? "Fit to window" : "Show actual size") : title}
80
+ onPress={() => {
81
+ if (zoomable) setActual((value) => !value);
82
+ }}
83
+ >
84
+ {shown !== null ? (
85
+ <Image source={{ uri }} resizeMode="contain" style={shown} />
86
+ ) : (
87
+ <Text style={styles.percent}>Loading…</Text>
88
+ )}
89
+ </Pressable>
90
+ </ScrollView>
91
+ </ScrollView>
92
+ <Text style={styles.hint}>
93
+ {zoomable ? (actual ? "Click to fit" : "Click to zoom") : ""}
94
+ {Platform.OS === "web" ? `${zoomable ? " · " : ""}Esc to close` : ""}
95
+ </Text>
96
+ </View>
97
+ </Modal>
98
+ );
99
+ }
100
+
101
+ const styles = StyleSheet.create({
102
+ backdrop: { flex: 1, backgroundColor: "rgba(0,0,0,0.94)" },
103
+ header: { flexDirection: "row", alignItems: "center", gap: 12, paddingHorizontal: 16, paddingTop: 16, paddingBottom: 8 },
104
+ title: { flex: 1, color: "#f4f4f5", fontSize: 13, fontWeight: "600" },
105
+ percent: { color: "#a1a1aa", fontSize: 12 },
106
+ close: { padding: 6 },
107
+ closeText: { color: "#f4f4f5", fontSize: 16 },
108
+ stage: { flex: 1 },
109
+ hint: { color: "#a1a1aa", fontSize: 12, textAlign: "center", paddingVertical: 8 },
110
+ });
@@ -678,7 +678,7 @@ export function OptionCards({ props }: { props: Props }) {
678
678
  gap: 6,
679
679
  }}
680
680
  >
681
- {opt.image ? <LoadedImageView src={opt.image} alt={opt.title} height={100} /> : null}
681
+ {opt.image ? <LoadedImageView src={opt.image} alt={opt.title} height={100} zoomable={false} /> : null}
682
682
  <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
683
683
  {iconName ? <Icon name={iconName} size={15} color={theme.colors.accent} /> : null}
684
684
  <Text style={{ color: theme.colors.foreground, fontSize: 13, fontWeight: "600", flex: 1 }}>
@@ -116,7 +116,7 @@ export function Gallery({ props }: { props: Props }) {
116
116
  {item.query ? (
117
117
  <ImageSearch props={{ query: item.query, alt: item.caption ?? item.query }} />
118
118
  ) : item.src ? (
119
- <LoadedImageView src={item.src} alt={item.caption} height={150} />
119
+ <LoadedImageView src={item.src} alt={item.caption} height={150} zoomable={false} />
120
120
  ) : null}
121
121
  {item.caption ? (
122
122
  <Text style={{ color: theme.colors.foregroundMuted, fontSize: 11.5 }}>
@@ -139,7 +139,7 @@ export function Gallery({ props }: { props: Props }) {
139
139
  {selected.query ? (
140
140
  <ImageSearch props={{ query: selected.query, alt: selected.caption ?? selected.query }} />
141
141
  ) : selected.src ? (
142
- <LoadedImageView src={selected.src} alt={selected.caption} height={360} />
142
+ <LoadedImageView src={selected.src} alt={selected.caption} height={360} zoomable={false} />
143
143
  ) : null}
144
144
  </Modal.Content>
145
145
  </Modal>
@@ -18,7 +18,7 @@ import { useAudioLoader, useImageLoader, useLoadedData, useTextLoader, type File
18
18
  import { MarkdownText } from "./markdown";
19
19
  import { RenderNodes } from "./render";
20
20
  import { UiRuntimeContext, type UiRuntime } from "./runtime";
21
- import { canRenderWebIframe, mountSandboxedAppIframe, readStorage, writeStorage } from "./web";
21
+ import { canRenderWebIframe, mountSandboxedAppIframe, openWorkspaceFile, readStorage, writeStorage } from "./web";
22
22
 
23
23
  function readStoredValues(storageKey: string): Record<string, Value> {
24
24
  const raw = readStorage(storageKey);
@@ -506,7 +506,7 @@ export function TimelineBlockItem({
506
506
  stateKey={stateKey}
507
507
  scope={{ agentId }}
508
508
  send={send}
509
- openFile={null}
509
+ openFile={layout.platform === "web" ? openWorkspaceFile : null}
510
510
  playAudio={playAudio}
511
511
  theme={theme}
512
512
  compact={layout.compact}
@@ -1,6 +1,7 @@
1
- import React, { Component, type ComponentType, type ReactNode } from "react";
1
+ import React, { Component, type ComponentClass, type ComponentType, type ReactNode } from "react";
2
2
  import { StyleSheet, Text, View } from "react-native";
3
3
  import type { ComponentName } from "../shared/core/catalog";
4
+ import { defineClass } from "../shared/core/define-class";
4
5
  import type { UiNode } from "../shared/core/types";
5
6
  import { text, type Props } from "../shared/logic/values";
6
7
  import { useUiRuntime } from "./runtime";
@@ -126,24 +127,41 @@ interface BoundaryProps {
126
127
  children: ReactNode;
127
128
  }
128
129
 
129
- export class NodeBoundary extends Component<BoundaryProps, { error: string | null }> {
130
- override state: { error: string | null } = { error: null };
130
+ interface BoundaryState {
131
+ error: string | null;
132
+ }
131
133
 
132
- static getDerivedStateFromError(cause: unknown): { error: string } {
133
- return { error: cause instanceof Error ? cause.message : String(cause) };
134
- }
134
+ /**
135
+ * An error boundary needs `getDerivedStateFromError`, which only a React class
136
+ * component can have. Hermes has no `class` syntax, so this is built on
137
+ * `Component`'s prototype instead (see shared/core/define-class.ts).
138
+ */
139
+ const NodeBoundaryBase = defineClass(
140
+ function (this: Component<BoundaryProps, BoundaryState>, props: BoundaryProps): void {
141
+ // React's Component is a plain function underneath; it sets props, context and updater.
142
+ (Component as unknown as (this: unknown, props: BoundaryProps) => void).call(this, props);
143
+ this.state = { error: null };
144
+ },
145
+ {
146
+ componentDidUpdate(previous: BoundaryProps): void {
147
+ if (this.state.error !== null && previous.node !== this.props.node) {
148
+ this.setState({ error: null });
149
+ }
150
+ },
135
151
 
136
- override componentDidUpdate(previous: BoundaryProps): void {
137
- if (this.state.error !== null && previous.node !== this.props.node) {
138
- this.setState({ error: null });
139
- }
140
- }
152
+ render(): ReactNode {
153
+ return this.state.error === null ? (
154
+ this.props.children
155
+ ) : (
156
+ <ErrorLine message={this.state.error} />
157
+ );
158
+ },
159
+ },
160
+ Component,
161
+ );
141
162
 
142
- override render(): ReactNode {
143
- return this.state.error === null ? (
144
- this.props.children
145
- ) : (
146
- <ErrorLine message={this.state.error} />
147
- );
148
- }
149
- }
163
+ export const NodeBoundary = Object.assign(NodeBoundaryBase, {
164
+ getDerivedStateFromError(cause: unknown): BoundaryState {
165
+ return { error: cause instanceof Error ? cause.message : String(cause) };
166
+ },
167
+ }) as unknown as ComponentClass<BoundaryProps, BoundaryState>;
package/client/web.ts CHANGED
@@ -41,7 +41,11 @@ interface WebGlobal {
41
41
  readonly window?: {
42
42
  addEventListener(type: "message", listener: (event: WebMessageEvent) => void): void;
43
43
  removeEventListener(type: "message", listener: (event: WebMessageEvent) => void): void;
44
+ readonly location?: { readonly pathname: string };
45
+ readonly history?: { pushState(state: null, unused: string, url: string): void };
46
+ dispatchEvent?(event: unknown): boolean;
44
47
  };
48
+ readonly PopStateEvent?: new (type: "popstate") => unknown;
45
49
  }
46
50
 
47
51
  const memoryStore = new Map<string, string>();
@@ -184,3 +188,21 @@ export function mountSandboxedAppIframe(
184
188
  iframe.remove();
185
189
  };
186
190
  }
191
+
192
+ /**
193
+ * Opens an absolute file path in a file tab of the workspace on screen, the way the
194
+ * host does for file links in chat. The plugin SDK has no call for it, so this goes
195
+ * through the host's `?open=file:<base64url path>` route. Web and desktop only.
196
+ */
197
+ export function openWorkspaceFile(path: string): boolean {
198
+ const web = getWeb();
199
+ const win = web?.window;
200
+ if (!win?.location || !win.history || !win.dispatchEvent || !web?.PopStateEvent) return false;
201
+ if (!path.startsWith("/")) return false;
202
+ const match = /^\/h\/[^/]+\/workspace\/[^/]+/.exec(win.location.pathname);
203
+ if (match === null) return false;
204
+ const token = btoa(unescape(encodeURIComponent(path))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
205
+ win.history.pushState(null, "", `${match[0]}?open=${encodeURIComponent(`file:${token}`)}`);
206
+ win.dispatchEvent(new web.PopStateEvent("popstate"));
207
+ return true;
208
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-plugin-genui",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Paseo plugin: agents answer with charts, diagrams, maps, plans and forms rendered inline in the chat.",
5
5
  "keywords": [
6
6
  "paseo",
@@ -1,5 +1,5 @@
1
- import { existsSync, readFileSync, readdirSync } from "node:fs";
2
- import { mkdir, readdir, readFile, stat } from "node:fs/promises";
1
+ import { constants, existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { mkdir, open, readdir, readFile, realpath } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -47,9 +47,15 @@ type FileContent =
47
47
 
48
48
  type FileReader = (requested: string, maxBytes: number) => Promise<FileContent>;
49
49
 
50
+ const AGENT_REFUSAL = "only files in this agent's workspace, its thread storage or /tmp can be loaded";
51
+ const GALLERY_REFUSAL = "gallery specs can only load files in gallery/";
52
+
50
53
  function contains(root: string, target: string): boolean {
51
- const relative = path.relative(path.resolve(root), path.resolve(target));
52
- return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
54
+ const resolvedRoot = path.resolve(root);
55
+ const resolvedTarget = path.resolve(target);
56
+ if (resolvedRoot === resolvedTarget) return false;
57
+ const relative = path.relative(resolvedRoot, resolvedTarget);
58
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
53
59
  }
54
60
 
55
61
  export function agentStorageDir(agentId: string): string {
@@ -79,9 +85,58 @@ export async function resolveAgentCwd(paseo: PaseoApi, agentId: string): Promise
79
85
  }
80
86
  }
81
87
 
82
- async function readLocalFile(target: string, requested: string, maxBytes: number): Promise<FileContent> {
88
+ interface Attempt {
89
+ readonly root: string;
90
+ readonly target: string;
91
+ }
92
+
93
+ type AttemptOutcome =
94
+ | { ok: true; content: string; encoding: "utf8" | "base64" }
95
+ | { ok: false; error: string; outsideRoot?: boolean };
96
+
97
+ /**
98
+ * Resolves both `root` and `target` with `realpath` before checking containment,
99
+ * rejects any symlink or intermediate directory link that escapes `realRoot`,
100
+ * and reads from the validated canonical path with `O_NOFOLLOW`.
101
+ */
102
+ async function readConfinedFile(
103
+ root: string,
104
+ target: string,
105
+ requested: string,
106
+ maxBytes: number,
107
+ refusalError: string,
108
+ ): Promise<AttemptOutcome> {
109
+ if (!contains(root, target)) {
110
+ return { ok: false, error: refusalError, outsideRoot: true };
111
+ }
112
+
113
+ let realRoot: string;
114
+ try {
115
+ realRoot = await realpath(root);
116
+ } catch {
117
+ return { ok: false, error: refusalError };
118
+ }
119
+
120
+ let realTarget: string;
121
+ try {
122
+ realTarget = await realpath(target);
123
+ } catch (cause) {
124
+ const code = typeof cause === "object" && cause !== null && "code" in cause ? cause.code : null;
125
+ if (code === "ENOENT" || code === "ENOTDIR") {
126
+ return { ok: false, error: "file not found" };
127
+ }
128
+ return { ok: false, error: cause instanceof Error ? cause.message : String(cause) };
129
+ }
130
+
131
+ if (!contains(realRoot, realTarget)) {
132
+ return { ok: false, error: refusalError, outsideRoot: true };
133
+ }
134
+
135
+ const openFlags = constants.O_RDONLY | (typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0);
136
+ let handle;
83
137
  try {
84
- const info = await stat(target);
138
+ handle = await open(realTarget, openFlags);
139
+ const info = await handle.stat();
85
140
  if (!info.isFile()) return { ok: false, error: "not a regular file" };
86
141
  if (info.size > maxBytes) {
87
142
  return { ok: false, error: `${info.size} bytes is over the ${maxBytes}-byte limit` };
@@ -90,7 +145,7 @@ async function readLocalFile(target: string, requested: string, maxBytes: number
90
145
  const binary =
91
146
  (Object.hasOwn(IMAGE_TYPES, extension) && extension !== "svg") ||
92
147
  Object.hasOwn(AUDIO_TYPES, extension);
93
- const content = await readFile(target);
148
+ const content = await handle.readFile();
94
149
  return binary
95
150
  ? { ok: true, content: content.toString("base64"), encoding: "base64" }
96
151
  : { ok: true, content: content.toString("utf8"), encoding: "utf8" };
@@ -100,9 +155,20 @@ async function readLocalFile(target: string, requested: string, maxBytes: number
100
155
  ok: false,
101
156
  error: code === "ENOENT" ? "file not found" : cause instanceof Error ? cause.message : String(cause),
102
157
  };
158
+ } finally {
159
+ await handle?.close().catch(() => undefined);
103
160
  }
104
161
  }
105
162
 
163
+ function tempAttempts(target: string): Attempt[] {
164
+ if (contains("/private/tmp", target)) return [{ root: "/private/tmp", target }];
165
+ if (!contains("/tmp", target)) return [];
166
+ return [
167
+ { root: "/private/tmp", target: path.join("/private", target) },
168
+ { root: "/tmp", target },
169
+ ];
170
+ }
171
+
106
172
  async function readAgentFile(
107
173
  paseo: PaseoApi,
108
174
  agentId: string,
@@ -113,50 +179,37 @@ async function readAgentFile(
113
179
  await mkdir(storageRoot, { recursive: true }).catch(() => undefined);
114
180
  const workspaceCwd = await resolveAgentCwd(paseo, agentId);
115
181
 
116
- const candidates: string[] = [];
182
+ const inside = (root: string | null, target: string): Attempt[] =>
183
+ root !== null && contains(root, target) ? [{ root, target }] : [];
184
+
185
+ let attempts: Attempt[];
117
186
  if (requested.startsWith(BB_STORAGE_PREFIX)) {
118
187
  const rel = requested.slice(BB_STORAGE_PREFIX.length);
119
- const target = path.resolve(storageRoot, rel);
120
- if (contains(storageRoot, target)) candidates.push(target);
121
- const galleryTarget = path.resolve(galleryDir(), rel);
122
- if (contains(galleryDir(), galleryTarget)) candidates.push(galleryTarget);
188
+ attempts = inside(storageRoot, path.resolve(storageRoot, rel));
123
189
  } else if (requested.startsWith(PASEO_STORAGE_PREFIX)) {
124
190
  const rel = requested.slice(PASEO_STORAGE_PREFIX.length);
125
- const target = path.resolve(storageRoot, rel);
126
- if (contains(storageRoot, target)) candidates.push(target);
191
+ attempts = inside(storageRoot, path.resolve(storageRoot, rel));
127
192
  } else if (path.isAbsolute(requested)) {
128
193
  const target = path.resolve(requested);
129
- if (
130
- contains(storageRoot, target) ||
131
- (workspaceCwd !== null && contains(workspaceCwd, target)) ||
132
- contains("/tmp", target) ||
133
- contains("/private/tmp", target)
134
- ) {
135
- candidates.push(target);
136
- }
194
+ attempts = [...inside(storageRoot, target), ...inside(workspaceCwd, target)].slice(0, 1);
195
+ if (attempts.length === 0) attempts = tempAttempts(target);
137
196
  } else {
138
- if (workspaceCwd !== null) {
139
- const target = path.resolve(workspaceCwd, requested);
140
- if (contains(workspaceCwd, target)) candidates.push(target);
141
- }
142
- const storageTarget = path.resolve(storageRoot, requested);
143
- if (contains(storageRoot, storageTarget)) candidates.push(storageTarget);
144
- const galleryTarget = path.resolve(galleryDir(), requested);
145
- if (contains(galleryDir(), galleryTarget)) candidates.push(galleryTarget);
197
+ attempts = [
198
+ ...inside(workspaceCwd, workspaceCwd !== null ? path.resolve(workspaceCwd, requested) : ""),
199
+ ...inside(storageRoot, path.resolve(storageRoot, requested)),
200
+ ];
146
201
  }
147
202
 
148
- if (candidates.length === 0) {
149
- return {
150
- ok: false,
151
- error: "only files in this agent's workspace, its thread storage or /tmp can be loaded",
152
- };
203
+ if (attempts.length === 0) {
204
+ return { ok: false, error: AGENT_REFUSAL };
153
205
  }
154
206
 
155
207
  let firstFailure: FileContent | undefined;
156
- for (const candidate of candidates) {
157
- const result = await readLocalFile(candidate, requested, maxBytes);
208
+ for (const attempt of attempts) {
209
+ const result = await readConfinedFile(attempt.root, attempt.target, requested, maxBytes, AGENT_REFUSAL);
158
210
  if (result.ok) return result;
159
- firstFailure ??= result;
211
+ if (result.outsideRoot) return { ok: false, error: AGENT_REFUSAL };
212
+ firstFailure ??= { ok: false, error: result.error };
160
213
  }
161
214
  return firstFailure!;
162
215
  }
@@ -341,9 +394,10 @@ async function readGalleryFile(requested: string, maxBytes: number): Promise<Fil
341
394
  : requested;
342
395
  const target = path.resolve(root, clean);
343
396
  if (path.isAbsolute(clean) || !contains(root, target)) {
344
- return { ok: false, error: "gallery specs can only load files in gallery/" };
397
+ return { ok: false, error: GALLERY_REFUSAL };
345
398
  }
346
- return readLocalFile(target, clean, maxBytes);
399
+ const result = await readConfinedFile(root, target, clean, maxBytes, GALLERY_REFUSAL);
400
+ return result.ok ? result : { ok: false, error: result.error };
347
401
  }
348
402
 
349
403
  export function loadGalleryFile(requested: string, { raw = false }: { raw?: boolean } = {}): Promise<LoadedData> {
@@ -6,6 +6,7 @@ import { LIMITS } from "./catalog";
6
6
  import type { Pos } from "./diagnostics";
7
7
  import { JUnitError, readJUnit } from "./junit";
8
8
  import type { Value } from "./types";
9
+ import { defineClass } from "./define-class";
9
10
 
10
11
  export type LoadedData = { readonly ok: true; readonly value: Value } | { readonly ok: false; readonly error: string };
11
12
 
@@ -211,7 +212,14 @@ export function parseDataFile(path: string, text: string): LoadedData {
211
212
  }
212
213
 
213
214
  /** A malformed-input reason, already phrased for the user. */
214
- class DataError extends Error {}
215
+ const DataError = defineClass(
216
+ function (this: Error, message: string): void {
217
+ this.message = message;
218
+ },
219
+ undefined,
220
+ Error,
221
+ );
222
+ type DataError = InstanceType<typeof DataError>;
215
223
 
216
224
  function parseJsonLines(text: string): unknown[] {
217
225
  const values: unknown[] = [];
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Builds a constructor from a function and a prototype of methods, without `class` syntax.
3
+ *
4
+ * Plugin client bundles run in Hermes on mobile, which has no `class` syntax
5
+ * (`class X {}` is a syntax error there, and a lazily compiled one evaluates to
6
+ * `undefined`, so `new X()` fails with "Cannot read property 'prototype' of
7
+ * undefined"). Paseo compiles plugin bundles for es2020, so they keep `class`.
8
+ * Everything under shared/ and client/ that is `new`ed goes through this.
9
+ *
10
+ * `init` assigns the instance fields. `methods` become non-enumerable prototype
11
+ * members, as class methods are. `parent` links the prototype chain.
12
+ */
13
+ export function defineClass<Args extends unknown[], Instance extends object, Methods extends object = {}>(
14
+ init: (this: Instance, ...args: Args) => void,
15
+ methods?: Methods & ThisType<Instance & Methods>,
16
+ parent?: abstract new (...args: never[]) => object,
17
+ ): new (...args: Args) => Instance & Methods {
18
+ function Constructor(this: Instance, ...args: Args): void {
19
+ init.apply(this, args);
20
+ }
21
+ const prototype = Object.create(
22
+ parent === undefined ? Object.prototype : (parent as unknown as { readonly prototype: object }).prototype,
23
+ ) as object;
24
+ Object.defineProperty(prototype, "constructor", { value: Constructor, writable: true, configurable: true });
25
+ if (methods !== undefined) {
26
+ for (const name of Object.keys(methods)) {
27
+ Object.defineProperty(prototype, name, {
28
+ value: (methods as Record<string, unknown>)[name],
29
+ writable: true,
30
+ configurable: true,
31
+ });
32
+ }
33
+ }
34
+ Constructor.prototype = prototype;
35
+ return Constructor as unknown as new (...args: Args) => Instance & Methods;
36
+ }
@@ -1,4 +1,5 @@
1
1
  import type { Diagnostic } from "./types";
2
+ import { defineClass } from "./define-class";
2
3
 
3
4
  /** A 1-based source position. Tokens and AST nodes carry one. */
4
5
  export interface Pos {
@@ -8,17 +9,27 @@ export interface Pos {
8
9
 
9
10
  const MAX_DIAGNOSTICS = 20;
10
11
 
11
- /** Collects up to 20 diagnostics, dropping exact duplicates. */
12
- export class DiagnosticList {
13
- readonly items: Diagnostic[] = [];
14
- hasErrors = false;
15
- private readonly seen = new Set<string>();
16
-
17
- report(pos: Pos, message: string, severity: Diagnostic["severity"] = "error"): void {
18
- if (severity === "error") this.hasErrors = true;
19
- const id = `${pos.line}:${pos.column}:${message}`;
20
- if (this.items.length >= MAX_DIAGNOSTICS || this.seen.has(id)) return;
21
- this.seen.add(id);
22
- this.items.push({ severity, line: pos.line, column: pos.column, message });
23
- }
12
+ interface DiagnosticListFields {
13
+ items: Diagnostic[];
14
+ hasErrors: boolean;
15
+ seen: Set<string>;
24
16
  }
17
+
18
+ /** Collects up to 20 diagnostics, dropping exact duplicates. */
19
+ export const DiagnosticList = defineClass(
20
+ function (this: DiagnosticListFields): void {
21
+ this.items = [];
22
+ this.hasErrors = false;
23
+ this.seen = new Set<string>();
24
+ },
25
+ {
26
+ report(pos: Pos, message: string, severity: Diagnostic["severity"] = "error"): void {
27
+ if (severity === "error") this.hasErrors = true;
28
+ const id = `${pos.line}:${pos.column}:${message}`;
29
+ if (this.items.length >= MAX_DIAGNOSTICS || this.seen.has(id)) return;
30
+ this.seen.add(id);
31
+ this.items.push({ severity, line: pos.line, column: pos.column, message });
32
+ },
33
+ },
34
+ );
35
+ export type DiagnosticList = InstanceType<typeof DiagnosticList>;