Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

preview.ts

397 lines12.7 KB

1import { Schema } from "effect";
2import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
3import { BROWSER_PROFILE_MAX_COUNT, BrowserProfile, BrowserProfileId } from "./browserProfile.ts";
4​
5export const PREVIEW_URL_MAX_LENGTH = 2_048;
6export const CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS = 32;
7​
8const Url = TrimmedNonEmptyString.check(Schema.isMaxLength(PREVIEW_URL_MAX_LENGTH));
9​
10export const ConfiguredLocalServerUrls = Schema.Array(Url).check(
11 Schema.isMaxLength(CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS),
12);
13const Title = Schema.String.check(Schema.isMaxLength(512));
14​
15export const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
16export type PreviewTabId = typeof PreviewTabId.Type;
17​
18export const PREVIEW_VIEWPORT_MIN_DIMENSION = 240;
19export const PREVIEW_VIEWPORT_MAX_DIMENSION = 3840;
20export const PREVIEW_VIEWPORT_MAX_AREA = 3840 * 2160;
21​
22const PreviewViewportDimension = Schema.Int.check(
23 Schema.isBetween({
24 minimum: PREVIEW_VIEWPORT_MIN_DIMENSION,
25 maximum: PREVIEW_VIEWPORT_MAX_DIMENSION,
26 }),
27);
28​
29const viewportAreaFilter = Schema.makeFilter(
30 ({ width, height }: { readonly width: number; readonly height: number }) =>
31 width * height <= PREVIEW_VIEWPORT_MAX_AREA ||
32 `Viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`,
33);
34​
35export const PreviewViewportSize = Schema.Struct({
36 width: PreviewViewportDimension,
37 height: PreviewViewportDimension,
38}).check(viewportAreaFilter);
39export type PreviewViewportSize = typeof PreviewViewportSize.Type;
40​
41/**
42 * The page's measured viewport can be smaller than the minimum selectable
43 * fixed size while fill mode follows a narrow panel. Keep measurement
44 * validation separate from the stricter user-selectable size constraints.
45 */
46export const PreviewRenderedViewportSize = Schema.Struct({
47 width: Schema.Int.check(Schema.isGreaterThan(0)),
48 height: Schema.Int.check(Schema.isGreaterThan(0)),
49});
50export type PreviewRenderedViewportSize = typeof PreviewRenderedViewportSize.Type;
51​
52export const PREVIEW_VIEWPORT_PRESET_IDS = [
53 "iphone-se",
54 "iphone-xr",
55 "iphone-12-pro",
56 "iphone-14-pro-max",
57 "pixel-7",
58 "samsung-galaxy-s8-plus",
59 "samsung-galaxy-s20-ultra",
60 "ipad-mini",
61 "ipad-air",
62 "ipad-pro",
63 "surface-pro-7",
64 "surface-duo",
65 "galaxy-z-fold-5",
66 "asus-zenbook-fold",
67 "samsung-galaxy-a51-71",
68 "nest-hub",
69 "nest-hub-max",
70] as const;
71​
72export const PreviewViewportPresetId = Schema.Literals(PREVIEW_VIEWPORT_PRESET_IDS);
73export type PreviewViewportPresetId = typeof PreviewViewportPresetId.Type;
74​
75const LEGACY_PREVIEW_VIEWPORT_PRESET_IDS = [
76 "desktop-1920x1080",
77 "desktop-1440x900",
78 "laptop-1366x768",
79 "laptop-1280x800",
80 "ipad-pro-11",
81 "iphone-15-pro",
82 "pixel-8",
83 "galaxy-s24",
84] as const;
85​
86const StoredPreviewViewportPresetId = Schema.Literals([
87 ...PREVIEW_VIEWPORT_PRESET_IDS,
88 ...LEGACY_PREVIEW_VIEWPORT_PRESET_IDS,
89]);
90​
91export const PreviewViewportSetting = Schema.Union([
92 Schema.TaggedStruct("fill", {}),
93 Schema.TaggedStruct("freeform", {
94 ...PreviewViewportSize.fields,
95 }).check(viewportAreaFilter),
96 Schema.TaggedStruct("preset", {
97 ...PreviewViewportSize.fields,
98 presetId: StoredPreviewViewportPresetId,
99 }).check(viewportAreaFilter),
100]);
101export type PreviewViewportSetting = typeof PreviewViewportSetting.Type;
102​
103export const FILL_PREVIEW_VIEWPORT = {
104 _tag: "fill",
105} as const satisfies PreviewViewportSetting;
106​
107/**
108 * Zoom is applied by the desktop main process to the Chromium guest, but the ladder lives here so
109 * the settings UI can offer exactly the steps the zoom controls step through.
110 */
111export const PREVIEW_ZOOM_LEVELS = [
112 0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0,
113] as const;
114​
115export const PreviewZoomFactor = Schema.Literals(PREVIEW_ZOOM_LEVELS);
116export type PreviewZoomFactor = typeof PreviewZoomFactor.Type;
117​
118export const DEFAULT_PREVIEW_ZOOM_FACTOR: PreviewZoomFactor = 1.0;
119​
120export const PreviewAppearancePreference = Schema.Literals(["system", "light", "dark"]);
121export type PreviewAppearancePreference = typeof PreviewAppearancePreference.Type;
122​
123export const DEFAULT_PREVIEW_APPEARANCE: PreviewAppearancePreference = "system";
124​
125const PreviewFileDownload = Schema.Struct({ id: Schema.String, fileName: Schema.String });
126​
127export const PreviewNavStatus = Schema.Union([
128 Schema.TaggedStruct("Idle", {}),
129 Schema.TaggedStruct("Loading", {
130 url: Url,
131 title: Title,
132 }),
133 Schema.TaggedStruct("Success", {
134 url: Url,
135 title: Title,
136 }),
137 Schema.TaggedStruct("LoadFailed", {
138 url: Url,
139 title: Title,
140 code: Schema.Int,
141 description: Schema.String,
142 download: Schema.optional(PreviewFileDownload),
143 }),
144]);
145export type PreviewNavStatus = typeof PreviewNavStatus.Type;
146​
147export const PreviewRuntime = Schema.Literals(["desktop", "server"]);
148export type PreviewRuntime = typeof PreviewRuntime.Type;
149​
150/**
151 * Host setup the server's browser is missing, sent as JSON in the reason when
152 * the preview stream closes with code 4503. Close reasons are capped at 123
153 * bytes, which this fits.
154 */
155export const PreviewStreamHostSetup = Schema.Struct({
156 need: Schema.Literals(["sandbox", "libraries"]),
157 command: Schema.String,
158});
159export type PreviewStreamHostSetup = typeof PreviewStreamHostSetup.Type;
160export const PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE = 4503;
161​
162export const PreviewSessionSnapshot = Schema.Struct({
163 threadId: TrimmedNonEmptyString,
164 tabId: PreviewTabId,
165 navStatus: PreviewNavStatus,
166 canGoBack: Schema.Boolean,
167 canGoForward: Schema.Boolean,
168 viewport: Schema.optional(PreviewViewportSetting),
169 colorScheme: Schema.optional(PreviewAppearancePreference),
170 zoomFactor: Schema.optional(PreviewZoomFactor),
171 /**
172 * Browser profile the tab's Chromium partition is derived from. Fixed at
173 * open: Electron only honours a `<webview>`'s partition before attach, so
174 * switching would require tearing the guest down and losing page state.
175 */
176 profileId: Schema.optional(BrowserProfileId),
177 runtime: Schema.optional(PreviewRuntime),
178 automationOwner: Schema.optional(Schema.String),
179 reveal: Schema.optional(Schema.Boolean),
180 revealRequest: Schema.optional(Schema.Struct({ id: Schema.String, force: Schema.Boolean })),
181 updatedAt: Schema.String,
182});
183export type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;
184​
185export const PreviewOpenInput = Schema.Struct({
186 threadId: ThreadId,
187 url: Schema.optional(Url),
188 viewport: Schema.optional(PreviewViewportSetting),
189 profileId: Schema.optional(BrowserProfileId),
190 runtime: Schema.optional(PreviewRuntime),
191 reveal: Schema.optional(Schema.Boolean),
192});
193export type PreviewOpenInput = typeof PreviewOpenInput.Type;
194​
195export const PreviewNavigateInput = Schema.Struct({
196 threadId: ThreadId,
197 tabId: PreviewTabId,
198 url: Url,
199 resolvedTitle: Schema.optional(Title),
200});
201export type PreviewNavigateInput = typeof PreviewNavigateInput.Type;
202​
203export const PreviewReportStatusInput = Schema.Struct({
204 threadId: ThreadId,
205 tabId: PreviewTabId,
206 navStatus: PreviewNavStatus,
207 canGoBack: Schema.Boolean,
208 canGoForward: Schema.Boolean,
209});
210export type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;
211​
212export const PreviewRefreshInput = Schema.Struct({
213 threadId: ThreadId,
214 tabId: PreviewTabId,
215});
216export type PreviewRefreshInput = typeof PreviewRefreshInput.Type;
217​
218export const PreviewResizeInput = Schema.Struct({
219 threadId: ThreadId,
220 tabId: PreviewTabId,
221 viewport: PreviewViewportSetting,
222});
223export type PreviewResizeInput = typeof PreviewResizeInput.Type;
224​
225/**
226 * Unlike page input, these need no control of the tab.
227 */
228export const PreviewAdjustInput = Schema.Struct({
229 threadId: ThreadId,
230 tabId: PreviewTabId,
231 colorScheme: Schema.optional(PreviewAppearancePreference),
232 zoomFactor: Schema.optional(PreviewZoomFactor),
233 hardReload: Schema.optional(Schema.Boolean),
234 clear: Schema.optional(Schema.Literals(["cookies", "cache"])),
235});
236export type PreviewAdjustInput = typeof PreviewAdjustInput.Type;
237​
238export const PreviewCloseInput = Schema.Struct({
239 threadId: ThreadId,
240 tabId: Schema.optional(PreviewTabId),
241});
242export type PreviewCloseInput = typeof PreviewCloseInput.Type;
243​
244export const PreviewReportProfilesInput = Schema.Struct({
245 profiles: Schema.Array(BrowserProfile).check(Schema.isMaxLength(BROWSER_PROFILE_MAX_COUNT)),
246 defaultProfileId: BrowserProfileId,
247});
248export type PreviewReportProfilesInput = typeof PreviewReportProfilesInput.Type;
249​
250export const PreviewClearProfileInput = Schema.Struct({
251 profileId: BrowserProfileId,
252});
253export type PreviewClearProfileInput = typeof PreviewClearProfileInput.Type;
254​
255export const PreviewListInput = Schema.Struct({
256 threadId: ThreadId,
257});
258export type PreviewListInput = typeof PreviewListInput.Type;
259​
260export const PreviewListResult = Schema.Struct({
261 sessions: Schema.Array(PreviewSessionSnapshot),
262 /** Identifies the current server process so revision resets are safe. */
263 serverEpoch: TrimmedNonEmptyString,
264 revision: NonNegativeInt,
265});
266export type PreviewListResult = typeof PreviewListResult.Type;
267​
268const PreviewEventBaseSchema = Schema.Struct({
269 threadId: TrimmedNonEmptyString,
270 tabId: PreviewTabId,
271 createdAt: Schema.String,
272 serverEpoch: TrimmedNonEmptyString,
273 /** Monotonic server state revision shared with PreviewListResult. */
274 revision: PositiveInt,
275});
276​
277const PreviewOpenedEvent = Schema.Struct({
278 ...PreviewEventBaseSchema.fields,
279 type: Schema.Literal("opened"),
280 snapshot: PreviewSessionSnapshot,
281});
282​
283const PreviewNavigatedEvent = Schema.Struct({
284 ...PreviewEventBaseSchema.fields,
285 type: Schema.Literal("navigated"),
286 snapshot: PreviewSessionSnapshot,
287});
288​
289const PreviewResizedEvent = Schema.Struct({
290 ...PreviewEventBaseSchema.fields,
291 type: Schema.Literal("resized"),
292 snapshot: PreviewSessionSnapshot,
293 request: Schema.optional(
294 Schema.Struct({
295 hardReload: Schema.optional(Schema.Boolean),
296 clear: Schema.optional(Schema.Literals(["cookies", "cache"])),
297 }),
298 ),
299});
300​
301const PreviewFailedEvent = Schema.Struct({
302 ...PreviewEventBaseSchema.fields,
303 type: Schema.Literal("failed"),
304 url: Url,
305 title: Title,
306 code: Schema.Int,
307 description: Schema.String,
308 download: Schema.optional(PreviewFileDownload),
309});
310​
311const PreviewClosedEvent = Schema.Struct({
312 ...PreviewEventBaseSchema.fields,
313 type: Schema.Literal("closed"),
314});
315​
316export const PreviewEvent = Schema.Union([
317 PreviewOpenedEvent,
318 PreviewNavigatedEvent,
319 PreviewResizedEvent,
320 PreviewFailedEvent,
321 PreviewClosedEvent,
322]);
323export type PreviewEvent = typeof PreviewEvent.Type;
324​
325export const DiscoveredLocalServer = Schema.Struct({
326 host: TrimmedNonEmptyString,
327 port: Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536)),
328 url: Url,
329 processName: Schema.NullOr(TrimmedNonEmptyString),
330 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
331 terminal: Schema.NullOr(
332 Schema.Struct({
333 threadId: ThreadId,
334 terminalId: TrimmedNonEmptyString,
335 }),
336 ),
337});
338export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
339​
340export const DiscoveredLocalServerList = Schema.Struct({
341 servers: Schema.Array(DiscoveredLocalServer),
342 scannedAt: Schema.String,
343 configuredUrlProbing: Schema.optional(Schema.Literal(true)),
344});
345export type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;
346​
347export class PreviewSessionLookupError extends Schema.TaggedError<PreviewSessionLookupError>()(
348 "PreviewSessionLookupError",
349 {
350 threadId: Schema.String,
351 tabId: Schema.String,
352 },
353) {
354 override get message() {
355 return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;
356 }
358​
359export class PreviewInvalidUrlError extends Schema.TaggedError<PreviewInvalidUrlError>()(
360 "PreviewInvalidUrlError",
361 {
362 inputLength: Schema.Number,
363 reason: Schema.Literals(["empty", "parse", "unsupported-protocol", "unexpected"]),
364 protocol: Schema.optional(Schema.String),
365 cause: Schema.Defect(),
366 },
367) {
368 override get message() {
369 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
370 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
371 }
373​
374export class PreviewControlRequiredError extends Schema.TaggedError<PreviewControlRequiredError>()(
375 "PreviewControlRequiredError",
376 { tabId: Schema.String },
377) {
378 override get message() {
379 return "Take control of the server browser and use its viewer controls.";
380 }
382​
383export class PreviewClearProfileError extends Schema.TaggedError<PreviewClearProfileError>()(
384 "PreviewClearProfileError",
385 { profileId: Schema.String, cause: Schema.Defect() },
386) {
387 override get message() {
388 return "The environment could not delete this browser profile's data.";
389 }
391​
392export const PreviewError = Schema.Union([
393 PreviewSessionLookupError,
394 PreviewInvalidUrlError,
395 PreviewControlRequiredError,
396]);
397export type PreviewError = typeof PreviewError.Type;