@octane-xplat/build 0.0.0-stage → 0.20.0

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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/add-worker.js +66 -0
  4. package/dist/build-worker.js +276 -0
  5. package/dist/compatibility-check.js +153 -0
  6. package/dist/compatibility-data/compatibility.js +106 -0
  7. package/dist/compatibility-data/compatibility.json +305 -0
  8. package/dist/compatibility.js +229 -0
  9. package/dist/css-layers.js +63 -0
  10. package/dist/css-platform.js +230 -0
  11. package/dist/css-platform.types.d.ts +11 -0
  12. package/dist/dev-inspector.web.js +125 -0
  13. package/dist/dev-log-client.web.js +79 -0
  14. package/dist/dev-log-server.js +13 -0
  15. package/dist/doctor-checks.js +317 -0
  16. package/dist/doctor-tool.js +27 -0
  17. package/dist/env.js +3 -0
  18. package/dist/fmt-plan.js +149 -0
  19. package/dist/fonts-worker.js +31 -0
  20. package/dist/fonts.js +614 -0
  21. package/dist/inline-stylesheets.js +37 -0
  22. package/dist/linux/config.js +43 -0
  23. package/dist/linux/host/bridge-selftest.linux.js +255 -0
  24. package/dist/linux/host/gjs-host.js +1412 -0
  25. package/dist/linux/package.js +176 -0
  26. package/dist/linux-gtk/vite.d.ts +23 -0
  27. package/dist/linux-gtk/vite.js +194 -0
  28. package/dist/macos/config.js +141 -0
  29. package/dist/macos/doctor-checks.js +58 -0
  30. package/dist/macos/executables.js +39 -0
  31. package/dist/macos/jsc-host/runtime.js +134 -0
  32. package/dist/macos/native.js +287 -0
  33. package/dist/macos/runtime-package.js +30 -0
  34. package/dist/macos/tab-item.js +62 -0
  35. package/dist/macos/vite.d.ts +21 -0
  36. package/dist/macos/vite.js +111 -0
  37. package/dist/markdown.js +11 -0
  38. package/dist/mason-engine.js +20 -0
  39. package/dist/mcp/contracts/actions.js +133 -0
  40. package/dist/mcp/dev-bridge.js +363 -0
  41. package/dist/mcp/dev-socket.js +161 -0
  42. package/dist/mcp/dev-stack.js +134 -0
  43. package/dist/mcp/inspection/dom.web.js +46 -0
  44. package/dist/native-regex.js +123 -0
  45. package/dist/package-manager.js +106 -0
  46. package/dist/package-root.js +48 -0
  47. package/dist/patches.js +356 -0
  48. package/dist/route-config.js +53 -0
  49. package/dist/route-data.js +42 -0
  50. package/dist/route-generator.js +514 -0
  51. package/dist/route-path.js +29 -0
  52. package/dist/route-source.js +67 -0
  53. package/dist/targets.js +38 -0
  54. package/dist/tsconfig-envs.js +287 -0
  55. package/dist/tsrx-leaf.js +57 -0
  56. package/dist/typecheck-globals/macos.d.ts +21 -0
  57. package/dist/typecheck-globals/native.d.ts +26 -0
  58. package/dist/ui/src/markdown/markdown-ast.js +33 -0
  59. package/dist/ui/src/markdown/markdown-character-references.js +79 -0
  60. package/dist/ui/src/markdown/markdown-parse.js +1930 -0
  61. package/dist/ui/src/markdown/markdown-plugins.js +564 -0
  62. package/dist/ui/src/markdown/markdown-url.js +17 -0
  63. package/dist/updates-worker.js +34 -0
  64. package/dist/upgrade-worker.js +63 -0
  65. package/dist/vite.d.ts +85 -0
  66. package/dist/vite.js +628 -0
  67. package/dist/workshop-worker.js +181 -0
  68. package/package.json +72 -5
@@ -0,0 +1,1412 @@
1
+ #!/usr/bin/env gjs
2
+ // gjs-host — the real Linux host. Same wire contract as WKHost.swift:
3
+ // webview → host: webkit.messageHandlers.xplat.postMessage(JSON string)
4
+ // host → webview: __xplatBridge.resolve/reject/emit via evaluate_javascript
5
+ //
6
+ // Deps (Debian trixie): gjs libgtk-4-1 libadwaita-1-0 libwebkitgtk-6.0-4
7
+ // gir1.2-webkit-6.0 gir1.2-adw-1 libsecret-1-0 gir1.2-secret-1 dbus xvfb
8
+ // gnome-keyring notification-daemon
9
+ // Run: xvfb-run -a dbus-run-session -- gjs gjs-host.js [--self-test] [--bundle DIR] [url]
10
+
11
+ imports.gi.versions.Gtk = '4.0'
12
+ imports.gi.versions.WebKit = '6.0'
13
+ imports.gi.versions.Adw = '1'
14
+ imports.gi.versions.Secret = '1'
15
+
16
+ const { Adw, Gtk, WebKit, Gio, GLib, Gdk, Secret } = imports.gi
17
+
18
+ const selfTest = ARGV.includes('--self-test')
19
+ const hostDir = GLib.path_get_dirname(imports.system.programPath)
20
+ let appSettings = {
21
+ applicationId: 'org.octane.xplat',
22
+ productName: 'Octane xplat',
23
+ scheme: 'xplat',
24
+ }
25
+
26
+ const settingsFile = GLib.build_filenamev([hostDir, '..', 'app.json'])
27
+
28
+ if (GLib.file_test(settingsFile, GLib.FileTest.EXISTS)) {
29
+ const [, bytes] = GLib.file_get_contents(settingsFile)
30
+
31
+ appSettings = JSON.parse(imports.byteArray.toString(bytes))
32
+ }
33
+
34
+ appSettings.applicationId = GLib.getenv('XPLAT_PROBE_APP_ID') || appSettings.applicationId
35
+
36
+ const contentPrefix = `${appSettings.scheme}://localhost`
37
+ let selfTestExit = 1
38
+
39
+ // Bundle resolution: --bundle flag > $XPLAT_BUNDLE_DIR > ./bundle (packaged
40
+ // app dir) > ../dist (repo layout — host/ sits next to apps/linux/dist).
41
+ const bundleFlag = ARGV.findIndex((a) => a === '--bundle')
42
+ const bundleDir = [
43
+ bundleFlag >= 0 ? ARGV[bundleFlag + 1] : null,
44
+ GLib.getenv('XPLAT_BUNDLE_DIR'),
45
+ GLib.build_filenamev([hostDir, '..', 'bundle']),
46
+ 'bundle',
47
+ '../dist',
48
+ ]
49
+ .filter(Boolean)
50
+ .map((d) => (GLib.path_is_absolute(d) ? d : GLib.build_filenamev([GLib.get_current_dir(), d])))
51
+ .find((d) => GLib.file_test(GLib.build_filenamev([d, 'index.html']), GLib.FileTest.EXISTS))
52
+
53
+ // Positional args: URIs only (flags and their values are ours). They're
54
+ // handed to GApplication, which delivers them via the 'open' signal (a
55
+ // second invocation of a running app forwards through D-Bus — that's the
56
+ // real deep-link delivery path). xplat://localhost/* URIs are content loads;
57
+ // anything else is a deep link.
58
+ const positionals = ARGV.filter(
59
+ (a, i) => !a.startsWith('--') && (bundleFlag < 0 || i !== bundleFlag + 1),
60
+ )
61
+
62
+ const url =
63
+ positionals.find((u) => u.startsWith(contentPrefix)) ??
64
+ positionals.find((u) => /^https?:\/\//.test(u)) ??
65
+ (bundleDir ? `${contentPrefix}/` : 'http://localhost:5201')
66
+
67
+ const contentOrigin = url.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+/i)?.[0] ?? url
68
+
69
+ // --- xplat:// scheme: serve the built bundle so the app never needs http ---
70
+ const MIMES = {
71
+ '.html': 'text/html',
72
+ '.js': 'text/javascript',
73
+ '.ts': 'text/javascript',
74
+ '.css': 'text/css',
75
+ '.json': 'application/json',
76
+ '.svg': 'image/svg+xml',
77
+ '.png': 'image/png',
78
+ '.jpg': 'image/jpeg',
79
+ '.jpeg': 'image/jpeg',
80
+ '.gif': 'image/gif',
81
+ '.webp': 'image/webp',
82
+ '.ico': 'image/x-icon',
83
+ '.woff': 'font/woff',
84
+ '.woff2': 'font/woff2',
85
+ '.ttf': 'font/ttf',
86
+ '.wasm': 'application/wasm',
87
+ '.map': 'application/json',
88
+ '.txt': 'text/plain',
89
+ '.mp4': 'video/mp4',
90
+ '.m4v': 'video/mp4',
91
+ '.webm': 'video/webm',
92
+ '.mov': 'video/quicktime',
93
+ '.m4a': 'audio/mp4',
94
+ '.ogg': 'audio/ogg',
95
+ }
96
+
97
+ function serveBundle(webContext) {
98
+ if (!bundleDir) {
99
+ return
100
+ }
101
+
102
+ webContext.register_uri_scheme(appSettings.scheme, (request) => {
103
+ // Host-managed movies play back same-origin without a bridge
104
+ // round-trip; unlike app routes, this prefix never falls back to
105
+ // index.html — a missing movie is a real miss.
106
+ if (request.get_path().startsWith('/-/media/')) {
107
+ const file = GLib.build_filenamev([mediaDir(), GLib.path_get_basename(request.get_path())])
108
+
109
+ try {
110
+ const f = Gio.File.new_for_path(file)
111
+ const info = f.query_info('standard::size', Gio.FileQueryInfoFlags.NONE, null)
112
+ const ext = file.slice(file.lastIndexOf('.')).toLowerCase()
113
+
114
+ request.finish(f.read(null), info.get_size(), MIMES[ext] ?? 'video/mp4')
115
+ } catch (e) {
116
+ request.finish_error(
117
+ new GLib.Error(Gio.IOErrorEnum.quark(), Gio.IOErrorEnum.NOT_FOUND, e.message),
118
+ )
119
+ }
120
+
121
+ return
122
+ }
123
+
124
+ // SPA fallback: unknown paths serve index.html; '..' never escapes.
125
+ let path = request.get_path().replace(/\/+$/, '') || '/index.html'
126
+ let file = GLib.build_filenamev([bundleDir, '.' + GLib.canonicalize_filename(path, '/')])
127
+
128
+ if (!GLib.file_test(file, GLib.FileTest.EXISTS) || GLib.file_test(file, GLib.FileTest.IS_DIR)) {
129
+ file = GLib.build_filenamev([bundleDir, 'index.html'])
130
+ }
131
+
132
+ try {
133
+ const f = Gio.File.new_for_path(file)
134
+ const info = f.query_info('standard::size', Gio.FileQueryInfoFlags.NONE, null)
135
+ const ext = file.slice(file.lastIndexOf('.')).toLowerCase()
136
+
137
+ request.finish(f.read(null), info.get_size(), MIMES[ext] ?? 'application/octet-stream')
138
+ } catch (e) {
139
+ print(`[host] scheme serve failed for ${path}: ${e.message}`)
140
+ request.finish_error(
141
+ new GLib.Error(Gio.IOErrorEnum.quark(), Gio.IOErrorEnum.NOT_FOUND, e.message),
142
+ )
143
+ }
144
+ })
145
+
146
+ // Secure + CORS so secure-context APIs (navigator.clipboard, crypto.subtle)
147
+ // and module/font fetches behave on the custom scheme.
148
+ const sm = webContext.get_security_manager()
149
+
150
+ sm.register_uri_scheme_as_secure(appSettings.scheme)
151
+ sm.register_uri_scheme_as_cors_enabled(appSettings.scheme)
152
+ print(`[host] serving bundle ${bundleDir} at ${contentPrefix}/`)
153
+ }
154
+
155
+ // HANDLES_OPEN routes URI argv through the 'open' signal — and, more
156
+ // importantly, forwards second-invocation URIs to the running primary
157
+ // instance over D-Bus. That's the real installed deep-link path.
158
+ const app = new Adw.Application({
159
+ application_id: appSettings.applicationId,
160
+ flags: Gio.ApplicationFlags.HANDLES_OPEN,
161
+ })
162
+
163
+ let win = null
164
+ let webView = null // main window's view — global events default here
165
+ let loadedOnce = false
166
+ let pendingInitialUrl = null
167
+ const linkQueue = []
168
+ const initialUrls = new Map()
169
+ let colorScheme = 'light'
170
+ let secretSchema = null
171
+ // wid → { win, wv, opener } — secondary windows opened via windows.open.
172
+ const windows = new Map()
173
+
174
+ try {
175
+ secretSchema = new Secret.Schema(appSettings.applicationId, Secret.SchemaFlags.NONE, {
176
+ key: Secret.SchemaAttributeType.STRING,
177
+ })
178
+ } catch (e) {
179
+ print(`[host] Secret.Schema unavailable: ${e.message}`)
180
+ }
181
+
182
+ // --- appearance: org.freedesktop.appearance via portal.Settings ---
183
+ // Read(ss)→(v) where v wraps uint32 (0 none, 1 dark, 2 light). No portal
184
+ // backend → the call fails → libadwaita's own system tracking is the
185
+ // fallback, else light.
186
+ function detectColorScheme() {
187
+ try {
188
+ const reply = Gio.bus_get_sync(Gio.BusType.SESSION, null).call_sync(
189
+ 'org.freedesktop.portal.Desktop',
190
+ '/org/freedesktop/portal/desktop',
191
+ 'org.freedesktop.portal.Settings',
192
+ 'Read',
193
+ new GLib.Variant('(ss)', ['org.freedesktop.appearance', 'color-scheme']),
194
+ new GLib.VariantType('(v)'),
195
+ Gio.DBusCallFlags.NONE,
196
+ 2000,
197
+ null,
198
+ )
199
+
200
+ return reply.get_child_value(0).get_variant().get_uint32() === 1 ? 'dark' : 'light'
201
+ } catch {
202
+ return Adw.StyleManager.get_default().get_dark() ? 'dark' : 'light'
203
+ }
204
+ }
205
+
206
+ function emitTo(wv, service, event, payload) {
207
+ const name =
208
+ (service === 'deepLinks' || service === 'deep-links') && event === 'open'
209
+ ? 'app.deep-link'
210
+ : `${service}.${event}`
211
+
212
+ const packet = JSON.stringify({ type: 'event', name, payload: payload ?? null })
213
+
214
+ wv.evaluate_javascript(
215
+ `window.__xplatHostTransport?.receive(${JSON.stringify(packet)});` +
216
+ `window.__xplatBridge?.emit('${service}', '${event}', ${JSON.stringify(payload ?? null)})`,
217
+ -1,
218
+ null,
219
+ null,
220
+ null,
221
+ null,
222
+ )
223
+ }
224
+
225
+ // Global events (appearance) go to every window's webview; app-targeted
226
+ // events (deep links) go to the main view.
227
+ function emitAll(service, event, payload) {
228
+ if (webView) {
229
+ emitTo(webView, service, event, payload)
230
+ }
231
+
232
+ for (const entry of windows.values()) {
233
+ emitTo(entry.wv, service, event, payload)
234
+ }
235
+ }
236
+
237
+ function subscribeAppearance() {
238
+ try {
239
+ Gio.bus_get_sync(Gio.BusType.SESSION, null).signal_subscribe(
240
+ 'org.freedesktop.portal.Desktop',
241
+ 'org.freedesktop.portal.Settings',
242
+ 'SettingChanged',
243
+ '/org/freedesktop/portal/desktop',
244
+ 'org.freedesktop.appearance',
245
+ Gio.DBusSignalFlags.MATCH_ARG0_NAMESPACE,
246
+ (_c, _s, _p, _i, _m, params) => {
247
+ const [_ns, key, val] = params.deepUnpack()
248
+
249
+ if (key === 'color-scheme') {
250
+ colorScheme = val.get_uint32() === 1 ? 'dark' : 'light'
251
+ emitAll('appearance', 'change', colorScheme)
252
+ }
253
+ },
254
+ )
255
+ } catch (e) {
256
+ print(`[host] appearance subscribe unavailable: ${e.message}`)
257
+ }
258
+ }
259
+
260
+ // Canonical framework service table — packages/platform/src/host-services.ts is
261
+ // the type source; this JS host is covered by bridge conformance checks.
262
+ // wv is the sender's webview: replies must land on the window that asked.
263
+ const keepAwakeCookies = new Map()
264
+ function releaseKeepAwake(wv) {
265
+ for (const cookie of keepAwakeCookies.get(wv)?.values() ?? []) {
266
+ app.uninhibit(cookie)
267
+ }
268
+
269
+ keepAwakeCookies.delete(wv)
270
+ }
271
+
272
+ const hostCapabilities = {
273
+ keepAwake: typeof app.inhibit === 'function' ? ['activate', 'deactivate'] : [],
274
+ app: ['getInfo', 'getState', 'getWindowSize', 'consumeInitialUrl'],
275
+ notifications: ['ensure', 'notify'],
276
+ clipboard: ['read', 'write'],
277
+ secureStorage: ['get', 'set', 'remove'],
278
+ appearance: ['get'],
279
+ files: ['readText', 'pick', 'writeText'],
280
+ windows: ['open', 'close', 'setTitle'],
281
+ system: ['openUrl', 'openPath'],
282
+ storage: ['get', 'set', 'remove'],
283
+ camera: [
284
+ 'permissionStatus',
285
+ 'requestPermission',
286
+ 'movieDirectory',
287
+ 'reserveMoviePath',
288
+ 'writeMovieFile',
289
+ 'movieFileInfo',
290
+ 'readMovieFile',
291
+ 'deleteMovieFile',
292
+ ],
293
+ }
294
+
295
+ const appInfo = () => ({
296
+ supported: true,
297
+ version: appSettings.version ?? null,
298
+ build: appSettings.build ?? appSettings.version ?? null,
299
+ bundleId: appSettings.applicationId,
300
+ })
301
+
302
+ const windowSizeFor = (targetWindow) => {
303
+ let width = 0
304
+ let height = 0
305
+
306
+ try {
307
+ width = targetWindow?.get_width?.() ?? 0
308
+ height = targetWindow?.get_height?.() ?? 0
309
+ } catch {}
310
+
311
+ if (!width || !height) {
312
+ try {
313
+ const [defaultWidth, defaultHeight] = targetWindow?.get_default_size?.() ?? [0, 0]
314
+
315
+ width ||= defaultWidth
316
+ height ||= defaultHeight
317
+ } catch {}
318
+ }
319
+
320
+ return {
321
+ width,
322
+ height,
323
+ orientation: width >= height ? 'landscape' : 'portrait',
324
+ }
325
+ }
326
+
327
+ const appStateFor = (targetWindow) =>
328
+ targetWindow?.is_active === true || targetWindow?.isActive === true ? 'active' : 'inactive'
329
+
330
+ const storagePath = () =>
331
+ GLib.build_filenamev([GLib.get_user_config_dir(), appSettings.applicationId, 'storage.json'])
332
+
333
+ // --- media capture: permission store + app-private movie files ---
334
+ // getUserMedia surfaces through the webview's permission-request signal as a
335
+ // WebKitUserMediaPermissionRequest — the host is the deciding authority on an
336
+ // unsandboxed Linux install (no OS-level camera gate outside Flatpak portals).
337
+ // Decisions persist per capture kind so checkPermission can answer without
338
+ // prompting. XPLAT_MEDIA_POLICY=allow|deny overrides the interactive prompt
339
+ // for harnesses; XPLAT_CAMERA_MOCK=1 swaps real devices for WebKit's mock
340
+ // capture devices (deterministic source on camera-less hosts).
341
+ const mediaDir = () =>
342
+ GLib.build_filenamev([GLib.get_user_data_dir(), appSettings.applicationId, 'media'])
343
+
344
+ const mediaPermissionsPath = () =>
345
+ GLib.build_filenamev([
346
+ GLib.get_user_config_dir(),
347
+ appSettings.applicationId,
348
+ 'media-permissions.json',
349
+ ])
350
+
351
+ const readMediaGrants = () => {
352
+ try {
353
+ const [ok, bytes] = GLib.file_get_contents(mediaPermissionsPath())
354
+
355
+ return ok ? JSON.parse(imports.byteArray.toString(bytes)) : {}
356
+ } catch {
357
+ return {}
358
+ }
359
+ }
360
+
361
+ const writeMediaGrants = (grants) => {
362
+ const file = mediaPermissionsPath()
363
+
364
+ GLib.mkdir_with_parents(GLib.path_get_dirname(file), 0o700)
365
+ GLib.file_set_contents(file, JSON.stringify(grants))
366
+ }
367
+
368
+ const mediaPolicy = () => {
369
+ const value = GLib.getenv('XPLAT_MEDIA_POLICY')
370
+
371
+ return value === 'allow' || value === 'deny' ? value : 'prompt'
372
+ }
373
+
374
+ // Status vocabulary matches the desktop camera contract — 'restricted' marks
375
+ // a policy refusal the user cannot override in this process (XPLAT_MEDIA_POLICY=deny).
376
+ const mediaPermissionStatus = (kind) => {
377
+ const policy = mediaPolicy()
378
+
379
+ if (policy === 'deny') {
380
+ return 'restricted'
381
+ }
382
+
383
+ if (policy === 'allow') {
384
+ return 'granted'
385
+ }
386
+
387
+ const value = readMediaGrants()[kind]
388
+
389
+ return value === 'granted' || value === 'denied' ? value : 'notDetermined'
390
+ }
391
+
392
+ // Explicit app action: answer from the persisted grant when one exists,
393
+ // otherwise follow the env policy or raise the interactive GTK dialog and
394
+ // remember the choice. Replies asynchronously — the bridge tolerates a late
395
+ // reply.
396
+ const mediaRequestPermission = (kind, wv, done) => {
397
+ const status = mediaPermissionStatus(kind)
398
+
399
+ if (status !== 'notDetermined') {
400
+ done(status)
401
+ return
402
+ }
403
+
404
+ const policy = mediaPolicy()
405
+
406
+ if (policy === 'deny') {
407
+ done('restricted')
408
+ return
409
+ }
410
+
411
+ if (policy === 'allow') {
412
+ done('granted')
413
+ return
414
+ }
415
+
416
+ const dialog = new Gtk.AlertDialog({
417
+ message: `Allow ${kind} access?`,
418
+ detail: `${appSettings.productName} is requesting access to your ${kind}. The decision is remembered for this app.`,
419
+ buttons: ['Deny', 'Allow'],
420
+ cancel_button: 0,
421
+ default_button: 1,
422
+ })
423
+
424
+ dialog.choose(winFor(wv) ?? win, null, (d, res) => {
425
+ let allowed = false
426
+
427
+ try {
428
+ allowed = d.choose_finish(res) === 1
429
+ } catch {}
430
+
431
+ const next = readMediaGrants()
432
+
433
+ next[kind] = allowed ? 'granted' : 'denied'
434
+ writeMediaGrants(next)
435
+ done(next[kind])
436
+ })
437
+ }
438
+
439
+ // App-private data root — mirrors the macOS host's Application Support root.
440
+ const appPrivateRoot = () =>
441
+ GLib.build_filenamev([GLib.get_user_data_dir(), appSettings.applicationId])
442
+
443
+ const uriToPath = (uri) => {
444
+ const value = String(uri)
445
+
446
+ if (value.startsWith('/')) {
447
+ return value
448
+ }
449
+
450
+ const path = Gio.File.new_for_uri(value).get_path()
451
+
452
+ return path || null
453
+ }
454
+
455
+ const pathInsidePrivateRoot = (uri) => {
456
+ const path = uriToPath(uri)
457
+
458
+ if (!path) {
459
+ return null
460
+ }
461
+
462
+ const root = `${appPrivateRoot()}/`
463
+
464
+ return path === appPrivateRoot() || path.startsWith(root) ? path : null
465
+ }
466
+
467
+ const movieDirectory = () => {
468
+ const dir = mediaDir()
469
+
470
+ GLib.mkdir_with_parents(dir, 0o700)
471
+ return Gio.File.new_for_path(dir).get_uri()
472
+ }
473
+
474
+ const reserveMoviePath = (options) => {
475
+ // The app-private root always exists on demand so a destination directly
476
+ // under it validates; deeper parents must already exist.
477
+ GLib.mkdir_with_parents(appPrivateRoot(), 0o700)
478
+
479
+ if (options.fileUrl) {
480
+ const target = pathInsidePrivateRoot(String(options.fileUrl))
481
+
482
+ if (!target) {
483
+ return null
484
+ }
485
+
486
+ const file = Gio.File.new_for_path(target)
487
+ const parent = file.get_parent()
488
+
489
+ if (file.query_exists(null) || !parent || !parent.query_exists(null)) {
490
+ return null
491
+ }
492
+
493
+ return { fileUrl: file.get_uri() }
494
+ }
495
+
496
+ const suffix = String(options.container ?? '').toLowerCase()
497
+ const ext = ['mp4', 'mov', 'webm'].includes(suffix) ? suffix : 'mp4'
498
+ const name = `clip-${Date.now()}-${GLib.uuid_string_random().slice(0, 8)}.${ext}`
499
+
500
+ movieDirectory()
501
+
502
+ const file = Gio.File.new_for_path(mediaDir())
503
+
504
+ return { fileUrl: file.get_child(name).get_uri() }
505
+ }
506
+
507
+ const writeMovieFile = (options) => {
508
+ const target = pathInsidePrivateRoot(String(options.fileUrl ?? ''))
509
+
510
+ if (!target) {
511
+ return null
512
+ }
513
+
514
+ const bytes = GLib.base64_decode(String(options.base64 ?? ''))
515
+ const file = Gio.File.new_for_path(target)
516
+ const parent = file.get_parent()
517
+
518
+ if (!parent || file.query_exists(null)) {
519
+ return null
520
+ }
521
+
522
+ try {
523
+ const free = parent
524
+ .query_filesystem_info(Gio.FILE_ATTRIBUTE_FILESYSTEM_FREE, null)
525
+ .get_attribute_uint64(Gio.FILE_ATTRIBUTE_FILESYSTEM_FREE)
526
+
527
+ if (free < bytes.length + 1_048_576) {
528
+ return null
529
+ }
530
+ } catch {
531
+ return null
532
+ }
533
+
534
+ // Write-then-move keeps partial files out of the output name;
535
+ // FileCopyFlags.NONE makes the move refuse an existing target.
536
+ const tmpPath = `${target}.tmp-${GLib.uuid_string_random().slice(0, 8)}`
537
+
538
+ GLib.file_set_contents(tmpPath, bytes)
539
+ try {
540
+ Gio.File.new_for_path(tmpPath).move(file, Gio.FileCopyFlags.NONE, null, null)
541
+ } catch {
542
+ Gio.File.new_for_path(tmpPath).delete(null)
543
+ return null
544
+ }
545
+
546
+ return { name: GLib.path_get_basename(target), uri: file.get_uri() }
547
+ }
548
+
549
+ const movieFileInfo = (uri) => {
550
+ const target = pathInsidePrivateRoot(uri)
551
+
552
+ if (!target) {
553
+ return null
554
+ }
555
+
556
+ const file = Gio.File.new_for_path(target)
557
+
558
+ if (!file.query_exists(null)) {
559
+ return { exists: false }
560
+ }
561
+
562
+ const info = file.query_info('standard::size', Gio.FileQueryInfoFlags.NONE, null)
563
+
564
+ return { exists: true, fileUrl: file.get_uri(), size: info.get_size() }
565
+ }
566
+
567
+ const readMovieFile = (uri) => {
568
+ const target = pathInsidePrivateRoot(uri)
569
+
570
+ if (!target) {
571
+ return null
572
+ }
573
+
574
+ const [ok, bytes] = GLib.file_get_contents(target)
575
+
576
+ return ok ? GLib.base64_encode(bytes) : null
577
+ }
578
+
579
+ const deleteMovieFile = (uri) => {
580
+ const target = pathInsidePrivateRoot(uri)
581
+
582
+ if (!target) {
583
+ return false
584
+ }
585
+
586
+ const file = Gio.File.new_for_path(target)
587
+
588
+ if (!file.query_exists(null)) {
589
+ return true
590
+ }
591
+
592
+ try {
593
+ return file.delete(null)
594
+ } catch {
595
+ return false
596
+ }
597
+ }
598
+
599
+ function decideUserMedia(wv, request) {
600
+ const required = []
601
+
602
+ if (WebKit.user_media_permission_is_for_video_device(request)) {
603
+ required.push('camera')
604
+ }
605
+
606
+ if (WebKit.user_media_permission_is_for_audio_device(request)) {
607
+ required.push('microphone')
608
+ }
609
+
610
+ const grants = readMediaGrants()
611
+
612
+ // An explicit denial is a durable user decision — deny without reprompting.
613
+ if (required.some((kind) => grants[kind] === 'denied')) {
614
+ request.deny()
615
+ return true
616
+ }
617
+
618
+ const missing = required.filter((kind) => grants[kind] !== 'granted')
619
+
620
+ if (!missing.length) {
621
+ request.allow()
622
+ return true
623
+ }
624
+
625
+ const policy = mediaPolicy()
626
+
627
+ if (policy === 'deny') {
628
+ request.deny()
629
+ return true
630
+ }
631
+
632
+ if (policy === 'allow') {
633
+ // Test-seam decisions stay in memory — persisted grants belong to
634
+ // interactive choices.
635
+ request.allow()
636
+ return true
637
+ }
638
+
639
+ const names = missing.join(' and ')
640
+ const dialog = new Gtk.AlertDialog({
641
+ message: `Allow ${names} access?`,
642
+ detail: `${appSettings.productName} is requesting access to your ${names}. The decision is remembered for this app.`,
643
+ buttons: ['Deny', 'Allow'],
644
+ cancel_button: 0,
645
+ default_button: 1,
646
+ })
647
+
648
+ dialog.choose(winFor(wv) ?? win, null, (d, res) => {
649
+ let allowed = false
650
+
651
+ try {
652
+ allowed = d.choose_finish(res) === 1
653
+ } catch {}
654
+
655
+ const next = readMediaGrants()
656
+
657
+ for (const kind of missing) {
658
+ next[kind] = allowed ? 'granted' : 'denied'
659
+ }
660
+
661
+ writeMediaGrants(next)
662
+ if (allowed) {
663
+ request.allow()
664
+ } else {
665
+ request.deny()
666
+ }
667
+ })
668
+
669
+ return true
670
+ }
671
+
672
+ const readStorage = () => {
673
+ try {
674
+ const [ok, bytes] = GLib.file_get_contents(storagePath())
675
+
676
+ return ok ? JSON.parse(imports.byteArray.toString(bytes)) : {}
677
+ } catch {
678
+ return {}
679
+ }
680
+ }
681
+
682
+ const writeStorage = (values) => {
683
+ const file = storagePath()
684
+
685
+ GLib.mkdir_with_parents(GLib.path_get_dirname(file), 0o700)
686
+ GLib.file_set_contents(file, JSON.stringify(values))
687
+ }
688
+
689
+ function receiveProtocol(wv, packet) {
690
+ const message = JSON.stringify(packet)
691
+
692
+ wv.evaluate_javascript(
693
+ `window.__xplatHostTransport?.receive(${JSON.stringify(message)})`,
694
+ -1,
695
+ null,
696
+ null,
697
+ null,
698
+ null,
699
+ )
700
+ }
701
+
702
+ function dispatch(wv, id, service, method, args, protocol = false) {
703
+ const evalJS = (js) => wv.evaluate_javascript(js, -1, null, null, null, null)
704
+ const reply = (value) =>
705
+ protocol
706
+ ? receiveProtocol(wv, { type: 'reply', id, ok: true, value: value ?? null })
707
+ : evalJS(`window.__xplatBridge?.resolve(${id}, ${JSON.stringify(value ?? null)})`)
708
+
709
+ const fail = (message) =>
710
+ protocol
711
+ ? receiveProtocol(wv, { type: 'reply', id, ok: false, error: String(message) })
712
+ : evalJS(`window.__xplatBridge?.reject(${id}, ${JSON.stringify(message)})`)
713
+
714
+ if (!Array.isArray(hostCapabilities[service]) || !hostCapabilities[service].includes(method)) {
715
+ fail(`host has no ${service}.${method}`)
716
+ return
717
+ }
718
+
719
+ try {
720
+ if (service === 'keepAwake') {
721
+ const tag = String(args[0])
722
+ let cookies = keepAwakeCookies.get(wv)
723
+
724
+ if (!cookies) {
725
+ cookies = new Map()
726
+ keepAwakeCookies.set(wv, cookies)
727
+ }
728
+
729
+ if (method === 'activate') {
730
+ if (!cookies.has(tag)) {
731
+ const cookie = app.inhibit(wv.get_root(), Gtk.ApplicationInhibitFlags.IDLE, tag)
732
+
733
+ if (!cookie) {
734
+ reply(false)
735
+ return
736
+ }
737
+
738
+ cookies.set(tag, cookie)
739
+ }
740
+ } else {
741
+ const cookie = cookies.get(tag)
742
+
743
+ if (cookie) {
744
+ app.uninhibit(cookie)
745
+ }
746
+
747
+ cookies.delete(tag)
748
+ }
749
+
750
+ reply(true)
751
+ return
752
+ }
753
+
754
+ if (service === 'notifications') {
755
+ // org.freedesktop.Notifications directly — GApplication.send_notification
756
+ // needs an org.gtk.Notifications server (GNOME Shell); the freedesktop
757
+ // Notify call is the cross-DE path (notification-daemon, dunst, …).
758
+ const bus = Gio.bus_get_sync(Gio.BusType.SESSION, null)
759
+
760
+ if (method === 'ensure') {
761
+ try {
762
+ bus.call_sync(
763
+ 'org.freedesktop.Notifications',
764
+ '/org/freedesktop/Notifications',
765
+ 'org.freedesktop.Notifications',
766
+ 'GetCapabilities',
767
+ null,
768
+ new GLib.VariantType('(as)'),
769
+ Gio.DBusCallFlags.NONE,
770
+ 2000,
771
+ null,
772
+ )
773
+
774
+ reply('granted')
775
+ } catch {
776
+ reply('unsupported')
777
+ }
778
+ } else if (method === 'notify') {
779
+ bus.call_sync(
780
+ 'org.freedesktop.Notifications',
781
+ '/org/freedesktop/Notifications',
782
+ 'org.freedesktop.Notifications',
783
+ 'Notify',
784
+ new GLib.Variant('(susssasa{sv}i)', [
785
+ appSettings.productName,
786
+ 0,
787
+ '',
788
+ String(args[0] ?? ''),
789
+ String(args[1] ?? ''),
790
+ [],
791
+ {},
792
+ -1,
793
+ ]),
794
+ new GLib.VariantType('(u)'),
795
+ Gio.DBusCallFlags.NONE,
796
+ -1,
797
+ null,
798
+ )
799
+
800
+ reply(true)
801
+ }
802
+
803
+ return
804
+ }
805
+
806
+ if (service === 'clipboard') {
807
+ const cb = wv.get_display().get_clipboard()
808
+
809
+ if (method === 'write') {
810
+ // GTK4 has no Gdk.Clipboard.set_text — writes go through a
811
+ // ContentProvider.
812
+ cb.set_content(Gdk.ContentProvider.new_for_value(String(args[0] ?? '')))
813
+
814
+ reply(true)
815
+ } else if (method === 'read') {
816
+ cb.read_text_async(null, (_c, res) => {
817
+ try {
818
+ reply(cb.read_text_finish(res))
819
+ } catch {
820
+ reply(null)
821
+ }
822
+ })
823
+ }
824
+
825
+ return
826
+ }
827
+
828
+ if (service === 'app') {
829
+ if (method === 'getInfo') {
830
+ reply(appInfo())
831
+ } else if (method === 'getState') {
832
+ reply(appStateFor(winFor(wv)))
833
+ } else if (method === 'getWindowSize') {
834
+ reply(windowSizeFor(winFor(wv)))
835
+ } else if (method === 'consumeInitialUrl') {
836
+ reply(initialUrls.get(wv) ?? null)
837
+ initialUrls.delete(wv)
838
+ }
839
+
840
+ return
841
+ }
842
+
843
+ if (service === 'storage') {
844
+ if (selfTest) {
845
+ globalThis.__xplatSelftestStorage ??= new Map()
846
+
847
+ const values = globalThis.__xplatSelftestStorage
848
+
849
+ if (method === 'get') {
850
+ reply(values.get(String(args[0])) ?? null)
851
+ } else if (method === 'set') {
852
+ values.set(String(args[0]), String(args[1] ?? ''))
853
+ reply(null)
854
+ } else if (method === 'remove') {
855
+ values.delete(String(args[0]))
856
+ reply(null)
857
+ }
858
+
859
+ return
860
+ }
861
+
862
+ const key = String(args[0])
863
+ const values = readStorage()
864
+
865
+ if (method === 'get') {
866
+ reply(Object.prototype.hasOwnProperty.call(values, key) ? String(values[key]) : null)
867
+ } else if (method === 'set') {
868
+ values[key] = String(args[1] ?? '')
869
+ writeStorage(values)
870
+ reply(null)
871
+ } else if (method === 'remove') {
872
+ delete values[key]
873
+ writeStorage(values)
874
+ reply(null)
875
+ }
876
+
877
+ return
878
+ }
879
+
880
+ if (service === 'secureStorage') {
881
+ if (!secretSchema) {
882
+ fail('Secret.Schema unavailable')
883
+ return
884
+ }
885
+
886
+ const attrs = { key: String(args[0] ?? '') }
887
+ // Real apps persist to the user's unlocked keyring. Self-tests use
888
+ // an in-memory collection so probes never persist test secrets.
889
+ const collection = selfTest ? Secret.COLLECTION_SESSION : Secret.COLLECTION_DEFAULT
890
+
891
+ const finish = (operation) => (_source, result) => {
892
+ try {
893
+ reply(operation(result))
894
+ } catch (error) {
895
+ fail(error.message ?? String(error))
896
+ }
897
+ }
898
+
899
+ if (method === 'get') {
900
+ Secret.password_lookup(secretSchema, attrs, null, finish(Secret.password_lookup_finish))
901
+ } else if (method === 'set') {
902
+ Secret.password_store(
903
+ secretSchema,
904
+ attrs,
905
+ collection,
906
+ `${appSettings.productName} secret`,
907
+ String(args[1] ?? ''),
908
+ null,
909
+ finish(Secret.password_store_finish),
910
+ )
911
+ } else if (method === 'remove') {
912
+ Secret.password_clear(secretSchema, attrs, null, finish(Secret.password_clear_finish))
913
+ }
914
+
915
+ return
916
+ }
917
+
918
+ if (service === 'appearance' && method === 'get') {
919
+ reply(colorScheme)
920
+ return
921
+ }
922
+
923
+ if (service === 'camera') {
924
+ // Shared desktop contract — packages/camera/src/host-movie.web.ts on
925
+ // the page side, XplatWebViewHost.swift on macOS. All movie paths are
926
+ // confined to the app-private data root; nothing overwrites.
927
+ const options = args[0] ?? {}
928
+
929
+ if (method === 'permissionStatus') {
930
+ reply({ status: mediaPermissionStatus(String(options.kind)) })
931
+ return
932
+ }
933
+
934
+ if (method === 'requestPermission') {
935
+ mediaRequestPermission(String(options.kind), wv, (status) => reply({ status }))
936
+ return
937
+ }
938
+
939
+ if (method === 'movieDirectory') {
940
+ reply({ fileUrl: movieDirectory() })
941
+ return
942
+ }
943
+
944
+ if (method === 'reserveMoviePath') {
945
+ reply({ reservation: reserveMoviePath(options) })
946
+ return
947
+ }
948
+
949
+ if (method === 'writeMovieFile') {
950
+ reply({ file: writeMovieFile(options) })
951
+ return
952
+ }
953
+
954
+ if (method === 'movieFileInfo') {
955
+ reply({ info: movieFileInfo(String(options.fileUrl ?? '')) })
956
+ return
957
+ }
958
+
959
+ if (method === 'readMovieFile') {
960
+ reply({ base64: readMovieFile(String(options.fileUrl ?? '')) })
961
+ return
962
+ }
963
+
964
+ if (method === 'deleteMovieFile') {
965
+ reply({ removed: deleteMovieFile(String(options.fileUrl ?? '')) })
966
+ return
967
+ }
968
+ }
969
+
970
+ if (service === 'files') {
971
+ if (method === 'readText') {
972
+ const [ok, bytes] = Gio.File.new_for_uri(String(args[0])).load_contents(null)
973
+
974
+ reply(ok ? imports.byteArray.toString(bytes) : null)
975
+ return
976
+ }
977
+
978
+ // pick/writeText open a Gtk.FileDialog — unsandboxed host, so the
979
+ // native dialog beats portal.FileChooser here. Portal is the
980
+ // sandboxed upgrade path. The dialog parents on the sender's window.
981
+ const parent = winFor(wv) ?? win
982
+ const dialog = new Gtk.FileDialog()
983
+ const finish = (d, res) => {
984
+ try {
985
+ const f = method === 'pick' ? d.open_finish(res) : d.save_finish(res)
986
+
987
+ if (!f) {
988
+ reply(null)
989
+ return
990
+ }
991
+
992
+ if (method === 'writeText') {
993
+ f.replace_contents(
994
+ new TextEncoder().encode(String(args[1] ?? '')),
995
+ null,
996
+ false,
997
+ Gio.FileCreateFlags.NONE,
998
+ null,
999
+ )
1000
+ }
1001
+
1002
+ reply({ name: f.get_basename(), uri: f.get_uri() })
1003
+ } catch {
1004
+ reply(null)
1005
+ }
1006
+ }
1007
+
1008
+ if (method === 'pick') {
1009
+ const options = args[1] && typeof args[1] === 'object' ? args[1] : {}
1010
+
1011
+ if (options.startingFolder) {
1012
+ dialog.set_initial_folder(Gio.File.new_for_path(String(options.startingFolder)))
1013
+ }
1014
+
1015
+ dialog.open(parent, null, finish)
1016
+ } else if (method === 'writeText') {
1017
+ dialog.set_initial_name(String(args[0] ?? 'untitled.txt'))
1018
+ dialog.save(parent, null, finish)
1019
+ }
1020
+
1021
+ return
1022
+ }
1023
+
1024
+ if (service === 'windows') {
1025
+ if (method === 'open') {
1026
+ const opts = args[0] ?? {}
1027
+ const wid = String(opts.id ?? `w${windows.size + 1}`)
1028
+
1029
+ openSecondaryWindow(wv, wid, opts)
1030
+ reply(wid)
1031
+ } else if (method === 'close') {
1032
+ const entry = windows.get(String(args[0]))
1033
+
1034
+ entry?.win.close()
1035
+ reply(!!entry)
1036
+ } else if (method === 'setTitle') {
1037
+ const entry = windows.get(String(args[0]))
1038
+
1039
+ entry?.win.set_title(String(args[1] ?? ''))
1040
+ reply(!!entry)
1041
+ }
1042
+
1043
+ return
1044
+ }
1045
+
1046
+ if (service === 'system' && method === 'openUrl') {
1047
+ reply(Gio.AppInfo.launch_default_for_uri(String(args[0]), null))
1048
+ return
1049
+ }
1050
+
1051
+ if (service === 'system' && method === 'openPath') {
1052
+ const target = Gio.File.new_for_path(String(args[0]))
1053
+
1054
+ reply(Gio.AppInfo.launch_default_for_uri(target.get_uri(), null))
1055
+ return
1056
+ }
1057
+
1058
+ fail(`host has no ${service}.${method}`)
1059
+ } catch (e) {
1060
+ fail(e.message ?? String(e))
1061
+ }
1062
+ }
1063
+
1064
+ function readSelftest() {
1065
+ const custom = GLib.getenv('XPLAT_SELFTEST_SCRIPT')
1066
+
1067
+ if (custom) {
1068
+ try {
1069
+ const [, bytes] = GLib.file_get_contents(custom)
1070
+
1071
+ return imports.byteArray.toString(bytes)
1072
+ } catch {
1073
+ return null
1074
+ }
1075
+ }
1076
+
1077
+ for (const dir of [hostDir, '.', bundleDir ?? '']) {
1078
+ try {
1079
+ const [ok, bytes] = GLib.file_get_contents(
1080
+ GLib.build_filenamev([dir, 'bridge-selftest.linux.js']),
1081
+ )
1082
+
1083
+ if (ok) {
1084
+ return imports.byteArray.toString(bytes)
1085
+ }
1086
+ } catch {}
1087
+ }
1088
+
1089
+ return null
1090
+ }
1091
+
1092
+ // Every webview gets its own UCM — per-window message wiring and its own
1093
+ // document-start injection (initial url / color scheme / window data).
1094
+ function wireWebView(wv, extraInjected = '', hostWindow = win, consumeInitial = true) {
1095
+ const ucm = wv.get_user_content_manager()
1096
+
1097
+ ucm.register_script_message_handler('xplat', null)
1098
+ ucm.register_script_message_handler('xplatLog', null)
1099
+ // Detailed signals separate the two handlers — WebKitGTK 6.0 delivers a
1100
+ // bare JSCValue (WebKitJavascriptResult is gone); the client posts a JSON
1101
+ // string, so to_string() → JSON.parse.
1102
+ ucm.connect('script-message-received::xplat', (_ucm, value) => {
1103
+ const req = JSON.parse(value.to_string())
1104
+
1105
+ if (req.type === 'capabilities') {
1106
+ receiveProtocol(wv, {
1107
+ type: 'reply',
1108
+ id: req.id,
1109
+ ok: true,
1110
+ value: hostCapabilities,
1111
+ })
1112
+
1113
+ return
1114
+ }
1115
+
1116
+ dispatch(wv, req.id, req.service, req.method, req.args ?? [], req.type === 'call')
1117
+ })
1118
+
1119
+ ucm.connect('script-message-received::xplatLog', (_ucm, value) => {
1120
+ const message = value.to_string()
1121
+
1122
+ print(`[webview] ${message}`)
1123
+ if (selfTest && message.startsWith('SELFTEST_RESULT ')) {
1124
+ const result = JSON.parse(message.slice('SELFTEST_RESULT '.length))
1125
+
1126
+ selfTestExit = result.failed.length === 0 ? 0 : 1
1127
+ app.quit()
1128
+ }
1129
+ })
1130
+
1131
+ // getUserMedia needs the media-stream feature; the mock capture flag is a
1132
+ // deterministic device source for camera-less hosts and harnesses — real
1133
+ // devices remain the default for packaged apps.
1134
+ const wvSettings = wv.get_settings()
1135
+
1136
+ wvSettings.set_enable_media_stream(true)
1137
+ if (GLib.getenv('XPLAT_CAMERA_MOCK') === '1') {
1138
+ wvSettings.set_enable_mock_capture_devices(true)
1139
+ }
1140
+
1141
+ wv.connect('permission-request', (_w, request) => {
1142
+ if (request instanceof WebKit.UserMediaPermissionRequest) {
1143
+ return decideUserMedia(wv, request)
1144
+ }
1145
+
1146
+ if (request instanceof WebKit.DeviceInfoPermissionRequest) {
1147
+ const grants = readMediaGrants()
1148
+
1149
+ if (grants.camera === 'granted' || grants.microphone === 'granted') {
1150
+ request.allow()
1151
+ } else {
1152
+ request.deny()
1153
+ }
1154
+
1155
+ return true
1156
+ }
1157
+
1158
+ return false
1159
+ })
1160
+
1161
+ const initialUrl = consumeInitial ? (linkQueue.shift() ?? pendingInitialUrl) : null
1162
+
1163
+ if (consumeInitial) {
1164
+ pendingInitialUrl = null
1165
+ }
1166
+
1167
+ if (initialUrl) {
1168
+ initialUrls.set(wv, initialUrl)
1169
+ }
1170
+
1171
+ const snapshot = JSON.stringify({
1172
+ appInfo: appInfo(),
1173
+ appState: appStateFor(hostWindow),
1174
+ windowSize: windowSizeFor(hostWindow),
1175
+ initialUrl,
1176
+ colorScheme,
1177
+ })
1178
+
1179
+ const transportScript = `(() => {
1180
+ const listeners = new Set();
1181
+ Object.defineProperty(window, '__xplatHostTransport', {
1182
+ value: {
1183
+ receive(message) { for (const listener of listeners) listener(message); },
1184
+ listen(listener) {
1185
+ listeners.add(listener);
1186
+ return () => listeners.delete(listener);
1187
+ }
1188
+ },
1189
+ configurable: false
1190
+ });
1191
+ })();`
1192
+
1193
+ ucm.add_script(
1194
+ WebKit.UserScript.new(
1195
+ transportScript +
1196
+ `window.__xplatHostSnapshot = ${snapshot};` +
1197
+ 'window.__xplatInitialUrl = window.__xplatHostSnapshot.initialUrl;' +
1198
+ 'window.__xplatColorScheme = window.__xplatHostSnapshot.colorScheme;' +
1199
+ (extraInjected ?? ''),
1200
+ WebKit.UserContentInjectedFrames.TOP_FRAME,
1201
+ WebKit.UserScriptInjectionTime.START,
1202
+ null,
1203
+ null,
1204
+ ),
1205
+ )
1206
+ }
1207
+
1208
+ function winFor(wv) {
1209
+ if (wv === webView) {
1210
+ return win
1211
+ }
1212
+
1213
+ for (const entry of windows.values()) {
1214
+ if (entry.wv === wv) {
1215
+ return entry.win
1216
+ }
1217
+ }
1218
+
1219
+ return null
1220
+ }
1221
+
1222
+ // openWindow → Adw window + own WebKitWebView + own Octane root. kinds:
1223
+ // 'regular' = independent window; 'dialog' = transient modal on the opener
1224
+ // (GTK has no sheets — modal-transient is the OS-level equivalent). options.url
1225
+ // resolves against the content origin; options.data is injected as
1226
+ // window.__xplatWindowData — the app-installed content resolver reads it.
1227
+ function openSecondaryWindow(opener, wid, opts) {
1228
+ const w = new Adw.ApplicationWindow({
1229
+ application: app,
1230
+ title: String(opts.title ?? 'xplat'),
1231
+ })
1232
+
1233
+ const size = opts.size ?? { width: 640, height: 480 }
1234
+
1235
+ w.set_default_size(Number(size.width) || 640, Number(size.height) || 480)
1236
+
1237
+ const wv = new WebKit.WebView()
1238
+
1239
+ wireWebView(
1240
+ wv,
1241
+ `window.__xplatWindowId = ${JSON.stringify(wid)};` +
1242
+ `window.__xplatWindowData = ${JSON.stringify(opts.data ?? null)};`,
1243
+ w,
1244
+ false,
1245
+ )
1246
+
1247
+ if (opts.kind === 'dialog') {
1248
+ const parent = winFor(opener) ?? win
1249
+
1250
+ w.set_transient_for(parent)
1251
+ w.set_modal(true)
1252
+ }
1253
+
1254
+ const u = String(opts.url ?? '/')
1255
+ const target = /^[a-z]+:/i.test(u) ? u : contentOrigin + (u.startsWith('/') ? u : '/' + u)
1256
+
1257
+ w.set_content(wv)
1258
+ windows.set(wid, { win: w, wv, opener })
1259
+
1260
+ w.connect('close-request', () => {
1261
+ releaseKeepAwake(wv)
1262
+ windows.delete(wid)
1263
+ if (opener) {
1264
+ emitTo(opener, 'windows', 'closed', wid)
1265
+ }
1266
+
1267
+ return false
1268
+ })
1269
+
1270
+ wv.load_uri(target)
1271
+ w.present()
1272
+ print(`[host] window ${wid} → ${target}`)
1273
+ }
1274
+
1275
+ function ensureWindow() {
1276
+ if (win) {
1277
+ return
1278
+ }
1279
+
1280
+ colorScheme = detectColorScheme()
1281
+ subscribeAppearance()
1282
+
1283
+ win = new Adw.ApplicationWindow({ application: app, title: appSettings.productName })
1284
+ win.set_default_size(1024, 768)
1285
+
1286
+ webView = new WebKit.WebView()
1287
+ win.connect('close-request', () => {
1288
+ releaseKeepAwake(webView)
1289
+ return false
1290
+ })
1291
+
1292
+ if (selfTest || GLib.getenv('XPLAT_LOG_CONSOLE') === '1') {
1293
+ webView.get_settings().set_enable_write_console_messages_to_stdout(true)
1294
+ }
1295
+
1296
+ serveBundle(webView.get_context())
1297
+ wireWebView(webView, '', win, true)
1298
+
1299
+ if (selfTest) {
1300
+ const js = readSelftest()
1301
+
1302
+ if (!js) {
1303
+ printerr('[host] missing bridge-selftest.linux.js')
1304
+ imports.system.exit(1)
1305
+ }
1306
+
1307
+ GLib.timeout_add(GLib.PRIORITY_DEFAULT, 90000, () => {
1308
+ printerr('[host] self-test timed out')
1309
+ app.quit()
1310
+ return GLib.SOURCE_REMOVE
1311
+ })
1312
+
1313
+ let tried = 0
1314
+
1315
+ const runWhenReady = () => {
1316
+ webView.evaluate_javascript(
1317
+ "typeof __xplatBridge === 'object'",
1318
+ -1,
1319
+ null,
1320
+ null,
1321
+ null,
1322
+ (_wv, res) => {
1323
+ let ready = false
1324
+
1325
+ try {
1326
+ ready = webView.evaluate_javascript_finish(res)?.to_boolean() ?? false
1327
+ } catch {}
1328
+
1329
+ if (ready) {
1330
+ webView.evaluate_javascript(js ?? '0', -1, null, null, null, null)
1331
+ GLib.timeout_add(GLib.PRIORITY_DEFAULT, 1500, () => {
1332
+ emitTo(webView, 'deep-links', 'open', 'xplat://self-test/deep-link')
1333
+ return GLib.SOURCE_REMOVE
1334
+ })
1335
+ } else if (++tried < 100) {
1336
+ GLib.timeout_add(GLib.PRIORITY_DEFAULT, 100, () => {
1337
+ runWhenReady()
1338
+ return GLib.SOURCE_REMOVE
1339
+ })
1340
+ }
1341
+ },
1342
+ )
1343
+ }
1344
+
1345
+ webView.connect('load-changed', (_wv, ev) => {
1346
+ if (ev === WebKit.LoadEvent.FINISHED) {
1347
+ runWhenReady()
1348
+ }
1349
+ })
1350
+ }
1351
+
1352
+ webView.connect('load-changed', (_wv, ev) => {
1353
+ if (ev !== WebKit.LoadEvent.FINISHED) {
1354
+ return
1355
+ }
1356
+
1357
+ loadedOnce = true
1358
+ // The cold-start link was consumed via __xplatInitialUrl injection —
1359
+ // emit any that arrived alongside it.
1360
+ while (linkQueue.length) {
1361
+ emitTo(webView, 'deep-links', 'open', linkQueue.shift())
1362
+ }
1363
+ })
1364
+
1365
+ win.set_content(webView)
1366
+ webView.load_uri(url)
1367
+ win.present()
1368
+
1369
+ win.connect('notify::is-active', () => {
1370
+ emitAll('app.state', 'change', appStateFor(win))
1371
+ })
1372
+
1373
+ win.connect('notify::default-width', () => {
1374
+ emitAll('window', 'resize', windowSizeFor(win))
1375
+ })
1376
+
1377
+ win.connect('notify::default-height', () => {
1378
+ emitAll('window', 'resize', windowSizeFor(win))
1379
+ })
1380
+
1381
+ emitTo(webView, 'host', 'ready', { url })
1382
+ }
1383
+
1384
+ // 'open' fires instead of 'activate' when argv carries URIs — and again on a
1385
+ // running instance for each new launch. xplat://localhost/* selects content;
1386
+ // anything else is a deep link: the first is consumed via document-start
1387
+ // injection, the rest emit once the bundle is up.
1388
+ app.connect('activate', ensureWindow)
1389
+ app.connect('open', (_a, files) => {
1390
+ for (const f of files) {
1391
+ const u = f.get_uri()
1392
+
1393
+ print(`[host] open ${u}`)
1394
+
1395
+ if (u.startsWith(contentPrefix)) {
1396
+ continue
1397
+ }
1398
+
1399
+ pendingInitialUrl ??= u
1400
+ if (loadedOnce) {
1401
+ emitTo(webView, 'deep-links', 'open', u)
1402
+ } else {
1403
+ linkQueue.push(u)
1404
+ }
1405
+ }
1406
+
1407
+ ensureWindow()
1408
+ })
1409
+
1410
+ const exitCode = app.run(['gjs-host', ...positionals])
1411
+
1412
+ imports.system.exit(selfTest ? selfTestExit : exitCode)