qmlbox 0.0.0-stage → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,596 @@
1
+ // src/loaders.ts
2
+ import { unzipSync } from "fflate";
3
+ var encoder = new TextEncoder();
4
+ var githubApi = "https://api.github.com";
5
+ var maxZipBytes = 128 * 1024 * 1024;
6
+ var maxZipFiles = 4096;
7
+ function normalizePath(path) {
8
+ const relativePath = path.replaceAll("\\", "/");
9
+ const parts = relativePath.split("/");
10
+ if (relativePath.startsWith("/") || /^[A-Za-z]:/.test(relativePath) || parts.includes("..") || /[\u0000-\u001f\u007f]/.test(path)) {
11
+ throw new Error(`Invalid relative theme path: ${path}`);
12
+ }
13
+ const normalized = parts.filter((part) => part && part !== ".").join("/");
14
+ if (!normalized) throw new Error("A theme file needs a relative path.");
15
+ return normalized;
16
+ }
17
+ function insertFile(files, path, bytes) {
18
+ if (Object.hasOwn(files, path)) throw new Error(`Duplicate theme file: ${path}`);
19
+ files[path] = bytes;
20
+ }
21
+ function newFileMap() {
22
+ return /* @__PURE__ */ Object.create(null);
23
+ }
24
+ function fromCodeString(source) {
25
+ const files = newFileMap();
26
+ files["Main.qml"] = encoder.encode(source);
27
+ return files;
28
+ }
29
+ async function fromSingleFile(file) {
30
+ const name = normalizePath(file.name);
31
+ if (!/\.qml$/i.test(name)) throw new Error("Select a .qml file.");
32
+ const files = newFileMap();
33
+ files[name] = new Uint8Array(await file.arrayBuffer());
34
+ return files;
35
+ }
36
+ async function fromFolderInput(input) {
37
+ const uploads = Array.from(input, (file) => ({
38
+ file,
39
+ path: normalizePath(file.webkitRelativePath || file.name)
40
+ }));
41
+ if (!uploads.length) throw new Error("The selected folder contains no files.");
42
+ const root = uploads[0].path.split("/")[0] + "/";
43
+ const stripRoot = uploads.every(({ path }) => path.startsWith(root));
44
+ const files = newFileMap();
45
+ for (const { file, path } of uploads) {
46
+ insertFile(files, stripRoot ? path.slice(root.length) : path, new Uint8Array(await file.arrayBuffer()));
47
+ }
48
+ return files;
49
+ }
50
+ async function fromZipFile(file) {
51
+ if (file.size > maxZipBytes) throw new Error("The ZIP exceeds 128 MiB.");
52
+ let expandedBytes = 0;
53
+ let fileCount = 0;
54
+ const paths = /* @__PURE__ */ new Set();
55
+ const archive = unzipSync(new Uint8Array(await file.arrayBuffer()), {
56
+ filter({ name, originalSize }) {
57
+ if (name.endsWith("/") || name.endsWith("\\")) return false;
58
+ const path = normalizePath(name);
59
+ if (path === "__proto__" || paths.has(path)) throw new Error(`Invalid or duplicate ZIP entry: ${path}`);
60
+ paths.add(path);
61
+ expandedBytes += originalSize;
62
+ fileCount += 1;
63
+ if (expandedBytes > maxZipBytes || fileCount > maxZipFiles) {
64
+ throw new Error("The ZIP exceeds 128 MiB unpacked or contains more than 4096 files.");
65
+ }
66
+ return true;
67
+ }
68
+ });
69
+ const entries = Object.entries(archive).map(([path, bytes]) => [normalizePath(path), bytes]);
70
+ if (!entries.length) throw new Error("The ZIP contains no files.");
71
+ let prefix = "";
72
+ for (const part of entries[0][0].split("/").slice(0, -1)) {
73
+ const candidate = `${prefix}${part}/`;
74
+ if (!entries.every(([path]) => path.startsWith(candidate))) break;
75
+ prefix = candidate;
76
+ }
77
+ const files = newFileMap();
78
+ for (const [path, bytes] of entries) insertFile(files, path.slice(prefix.length), bytes);
79
+ return files;
80
+ }
81
+ var GitHubRequestError = class extends Error {
82
+ constructor(status, message) {
83
+ super(message);
84
+ this.status = status;
85
+ }
86
+ status;
87
+ };
88
+ async function fromGitHubRepo(url, options = {}) {
89
+ const repoUrl = new URL(url);
90
+ const [owner, repoName, view, ...treePath] = repoUrl.pathname.split("/").filter(Boolean).map(decodeURIComponent);
91
+ const repo = repoName?.replace(/\.git$/, "");
92
+ if (repoUrl.protocol !== "https:" || repoUrl.host !== "github.com" || !owner || !repo || !/^[\w.-]+$/.test(owner) || !/^[\w.-]+$/.test(repo) || view !== void 0 && (view !== "tree" || !treePath.length)) {
93
+ throw new Error("Enter a GitHub repository URL or a URL pointing to a folder in that repository.");
94
+ }
95
+ const repoEndpoint = `${githubApi}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
96
+ const headers = new Headers({ Accept: "application/vnd.github+json" });
97
+ const controller = new AbortController();
98
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
99
+ if (options.token) headers.set("Authorization", `Bearer ${options.token}`);
100
+ async function request(path, raw = false) {
101
+ const requestHeaders = new Headers(headers);
102
+ if (raw) requestHeaders.set("Accept", "application/vnd.github.raw+json");
103
+ const response = await fetch(repoEndpoint + path, {
104
+ headers: requestHeaders,
105
+ signal
106
+ });
107
+ if (!response.ok) {
108
+ const limited = response.status === 429 || response.headers.get("x-ratelimit-remaining") === "0";
109
+ const message = limited ? "The GitHub API rate limit was reached." : `GitHub returned HTTP ${response.status} for ${owner}/${repo}${path}.`;
110
+ throw new GitHubRequestError(response.status, message);
111
+ }
112
+ return response;
113
+ }
114
+ async function readTree(ref2, recursive) {
115
+ const path = `/git/trees/${encodeURIComponent(ref2)}${recursive ? "?recursive=1" : ""}`;
116
+ return (await request(path)).json();
117
+ }
118
+ let ref = options.ref;
119
+ let directory2 = options.subdirectory ?? "";
120
+ let result;
121
+ if (!ref && treePath.length) {
122
+ for (let length = treePath.length; length > 0; length--) {
123
+ const candidate = treePath.slice(0, length).join("/");
124
+ try {
125
+ result = await readTree(candidate, true);
126
+ ref = candidate;
127
+ directory2 = options.subdirectory ?? treePath.slice(length).join("/");
128
+ break;
129
+ } catch (error) {
130
+ if (!(error instanceof GitHubRequestError) || error.status !== 404 || length === 1) throw error;
131
+ }
132
+ }
133
+ } else if (!ref) {
134
+ const info = await (await request("")).json();
135
+ ref = info.default_branch;
136
+ } else if (options.subdirectory === void 0 && treePath.length) {
137
+ const urlPath = treePath.join("/");
138
+ if (urlPath.startsWith(ref + "/")) directory2 = urlPath.slice(ref.length + 1);
139
+ }
140
+ if (!ref) throw new Error("The GitHub repository has no branch to load.");
141
+ const folder = directory2 ? normalizePath(directory2.replace(/\/+$/, "")) : "";
142
+ const prefix = folder ? `${folder}/` : "";
143
+ result ??= await readTree(ref, true);
144
+ async function readSubtrees(treeRef) {
145
+ const files2 = [];
146
+ const pending = [{ ref: treeRef, prefix: "" }];
147
+ while (pending.length) {
148
+ const subtree = pending.pop();
149
+ const listing = await readTree(subtree.ref, false);
150
+ if (listing.truncated) throw new Error("GitHub truncated a non-recursive tree listing.");
151
+ for (const item of listing.tree) {
152
+ const path = subtree.prefix + item.path;
153
+ if (item.type === "tree") pending.push({ ref: item.sha, prefix: `${path}/` });
154
+ else files2.push({ ...item, path });
155
+ }
156
+ }
157
+ return files2;
158
+ }
159
+ let entries;
160
+ if (!result.truncated) {
161
+ entries = result.tree.filter((item) => item.path.startsWith(prefix)).map((item) => ({ ...item, path: item.path.slice(prefix.length) }));
162
+ } else {
163
+ let subtree = ref;
164
+ for (const part of folder ? folder.split("/") : []) {
165
+ const listing = await readTree(subtree, false);
166
+ const match = listing.tree.find((item) => item.type === "tree" && item.path === part);
167
+ if (!match) throw new Error(`The folder "${folder}" does not exist in the repository.`);
168
+ subtree = match.sha;
169
+ }
170
+ entries = await readSubtrees(subtree);
171
+ }
172
+ const blobs = entries.filter((item) => item.type === "blob" && item.mode !== "120000");
173
+ if (!blobs.length) throw new Error(`GitHub returned no regular files${folder ? ` in "${folder}"` : ""}.`);
174
+ const files = newFileMap();
175
+ const downloads = /* @__PURE__ */ new Map();
176
+ let next = 0;
177
+ async function downloadFiles() {
178
+ while (!signal.aborted && next < blobs.length) {
179
+ const { path, sha } = blobs[next++];
180
+ let download = downloads.get(sha);
181
+ if (!download) {
182
+ download = request(`/git/blobs/${encodeURIComponent(sha)}`, true).then((response) => response.arrayBuffer()).then((buffer) => new Uint8Array(buffer));
183
+ downloads.set(sha, download);
184
+ }
185
+ insertFile(files, normalizePath(path), await download);
186
+ }
187
+ signal.throwIfAborted();
188
+ }
189
+ try {
190
+ await Promise.all(Array.from({ length: Math.min(6, blobs.length) }, downloadFiles));
191
+ } catch (error) {
192
+ controller.abort(error);
193
+ throw error;
194
+ }
195
+ return files;
196
+ }
197
+
198
+ // src/sddmParser.ts
199
+ var decoder = new TextDecoder();
200
+ function parseIni(source) {
201
+ const sections = /* @__PURE__ */ Object.create(null);
202
+ let section = sections[""] = /* @__PURE__ */ Object.create(null);
203
+ for (const rawLine of source.replace(/^\uFEFF/, "").split(/\r\n?|\n/)) {
204
+ const line = rawLine.trim();
205
+ if (!line || line.startsWith("#") || line.startsWith(";")) continue;
206
+ const header = /^\[([^\]]+)\]\s*(?:[;#].*)?$/.exec(line);
207
+ if (header) {
208
+ const name = header[1].trim();
209
+ section = sections[name] ??= /* @__PURE__ */ Object.create(null);
210
+ continue;
211
+ }
212
+ const delimiter = line.indexOf("=");
213
+ if (delimiter < 1) continue;
214
+ const key = line.slice(0, delimiter).trim();
215
+ const value = line.slice(delimiter + 1).trim();
216
+ const quoted = /^(["'])(.*)\1\s*(?:[;#].*)?$/.exec(value);
217
+ section[key] = quoted ? quoted[2].replace(/\\([nrt\\'"])/g, (_, character) => ({ n: "\n", r: "\r", t: " " })[character] ?? character) : value;
218
+ }
219
+ return sections;
220
+ }
221
+ function parseThemeConfig(source) {
222
+ const ini = parseIni(source);
223
+ const config = Object.assign(/* @__PURE__ */ Object.create(null), ini[""]);
224
+ for (const [group, values] of Object.entries(ini)) {
225
+ if (!group) continue;
226
+ if (group.toLowerCase() === "general") Object.assign(config, values);
227
+ else for (const [key, value] of Object.entries(values)) config[`${group}/${key}`] = value;
228
+ }
229
+ return config;
230
+ }
231
+ function parseMetadata(source) {
232
+ const sections = parseIni(source);
233
+ const properties = Object.assign(
234
+ /* @__PURE__ */ Object.create(null),
235
+ sections[""],
236
+ ...Object.entries(sections).filter(([group]) => group.toLowerCase() === "sddmgreetertheme").map(([, values]) => values)
237
+ );
238
+ const keys = Object.fromEntries(
239
+ Object.entries(properties).map(([key, value]) => [key.toLowerCase(), value])
240
+ );
241
+ return { mainScript: keys["mainscript"], configFile: keys["configfile"] };
242
+ }
243
+ function readText(files, path) {
244
+ const file = files[path];
245
+ return typeof file === "string" ? file : file ? decoder.decode(file) : "";
246
+ }
247
+ function directory(path) {
248
+ return path.slice(0, path.lastIndexOf("/") + 1);
249
+ }
250
+ function resolveTheme(files, entryFile) {
251
+ const paths = Object.keys(files);
252
+ const qmlFiles = paths.filter((path) => /\.qml$/i.test(path));
253
+ const metadataPaths = paths.filter((path) => path.split("/").at(-1) === "metadata.desktop");
254
+ let metadataPath;
255
+ let entry = entryFile === void 0 ? void 0 : normalizePath(entryFile);
256
+ if (entry !== void 0) {
257
+ metadataPath = metadataPaths.filter((path) => entry.startsWith(directory(path))).sort((a, b) => b.length - a.length)[0];
258
+ } else if (Object.hasOwn(files, "metadata.desktop")) {
259
+ metadataPath = "metadata.desktop";
260
+ } else if (Object.hasOwn(files, "Main.qml") || Object.hasOwn(files, "main.qml")) {
261
+ entry = Object.hasOwn(files, "Main.qml") ? "Main.qml" : "main.qml";
262
+ } else if (metadataPaths.length === 1) {
263
+ metadataPath = metadataPaths[0];
264
+ } else if (metadataPaths.length > 1) {
265
+ throw new Error("This input contains several themes. Select one theme folder or specify the entry file.");
266
+ }
267
+ const metadata = metadataPath ? parseMetadata(readText(files, metadataPath)) : {};
268
+ const metadataRoot = metadataPath ? directory(metadataPath) : "";
269
+ if (!entry && metadata.mainScript) entry = metadataRoot + normalizePath(metadata.mainScript);
270
+ if (!entry) {
271
+ const candidates = qmlFiles.filter((path) => path.startsWith(metadataRoot));
272
+ const mainFiles = candidates.filter((path) => path.split("/").at(-1)?.toLowerCase() === "main.qml");
273
+ entry = mainFiles.find((path) => directory(path) === metadataRoot) ?? (mainFiles.length === 1 ? mainFiles[0] : void 0) ?? (candidates.length === 1 ? candidates[0] : void 0);
274
+ }
275
+ if (!entry) throw new Error("Could not select a QML entry file. Include Main.qml or specify the entry file.");
276
+ if (!Object.hasOwn(files, entry) || !/\.qml$/i.test(entry)) {
277
+ throw new Error(`QML entry file "${entry}" was not found.`);
278
+ }
279
+ const root = metadataPath ? metadataRoot : directory(entry);
280
+ const configPath = root + normalizePath(metadata.configFile || "theme.conf");
281
+ const config = Object.assign(
282
+ parseThemeConfig(readText(files, configPath)),
283
+ parseThemeConfig(readText(files, `${configPath}.user`))
284
+ );
285
+ return { entryFile: entry, root, config };
286
+ }
287
+
288
+ // src/wasmLoader.ts
289
+ function loadScript(doc, url, signal) {
290
+ signal.throwIfAborted();
291
+ const script = doc.createElement("script");
292
+ script.src = url;
293
+ return new Promise((resolve, reject) => {
294
+ function finish(error) {
295
+ script.onload = null;
296
+ script.onerror = null;
297
+ signal.removeEventListener("abort", abort);
298
+ if (error === void 0) resolve();
299
+ else {
300
+ script.remove();
301
+ reject(error);
302
+ }
303
+ }
304
+ function abort() {
305
+ finish(signal.reason);
306
+ }
307
+ script.onload = () => finish();
308
+ script.onerror = () => finish(new Error(`Could not load Qt runtime script ${url}.`));
309
+ signal.addEventListener("abort", abort, { once: true });
310
+ doc.head.append(script);
311
+ });
312
+ }
313
+ async function compileWasm(url, signal, progress) {
314
+ const response = await fetch(url, { signal });
315
+ if (!response.ok) throw new Error(`Could not download ${url} (HTTP ${response.status}).`);
316
+ if (!response.body) throw new Error(`The WebAssembly response for ${url} was empty.`);
317
+ const expected = Number(response.headers.get("content-length"));
318
+ let received = 0;
319
+ let lastPercent = 0;
320
+ const counted = response.body.pipeThrough(new TransformStream({
321
+ transform(chunk, controller) {
322
+ received += chunk.length;
323
+ if (expected > 0) {
324
+ const percent = Math.min(90, Math.floor(received / expected * 90));
325
+ if (percent > lastPercent) {
326
+ lastPercent = percent;
327
+ progress(percent);
328
+ }
329
+ }
330
+ controller.enqueue(chunk);
331
+ }
332
+ }));
333
+ const wasm = await WebAssembly.compileStreaming(new Response(counted, {
334
+ headers: { "Content-Type": "application/wasm" }
335
+ }));
336
+ if (lastPercent < 90) progress(90);
337
+ return wasm;
338
+ }
339
+ function untilAborted(promise, signal) {
340
+ return new Promise((resolve, reject) => {
341
+ const abort = () => reject(signal.reason);
342
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
343
+ if (signal.aborted) abort();
344
+ else signal.addEventListener("abort", abort, { once: true });
345
+ });
346
+ }
347
+ async function loadWasmRuntime(frame, baseUrl, maxPixelRatio, signal, progress, onError) {
348
+ const doc = frame.contentDocument;
349
+ const win = frame.contentWindow;
350
+ const parentWindow = frame.ownerDocument.defaultView;
351
+ if (!doc || !win || !parentWindow) throw new Error("Could not open the Qt viewer frame.");
352
+ Object.defineProperty(win, "devicePixelRatio", {
353
+ configurable: true,
354
+ get: () => Math.min(parentWindow.devicePixelRatio || 1, maxPixelRatio)
355
+ });
356
+ const viewport = doc.createElement("meta");
357
+ viewport.name = "viewport";
358
+ viewport.content = "width=device-width, initial-scale=1";
359
+ doc.head.append(viewport);
360
+ const screen = doc.createElement("div");
361
+ Object.assign(doc.body.style, { margin: "0", overflow: "hidden", background: "#161b22" });
362
+ Object.assign(screen.style, { width: "100vw", height: "100vh", overflow: "hidden" });
363
+ doc.body.append(screen);
364
+ const base = new URL(baseUrl, frame.ownerDocument.baseURI);
365
+ if (!base.pathname.endsWith("/")) base.pathname += "/";
366
+ const locate = (name) => new URL(name, base).href;
367
+ progress(0);
368
+ const [wasm] = await Promise.all([
369
+ compileWasm(locate("qml_engine.wasm"), signal, progress),
370
+ loadScript(doc, locate("qtloader.js"), signal),
371
+ loadScript(doc, locate("qml_engine.js"), signal)
372
+ ]);
373
+ signal.throwIfAborted();
374
+ const entryFunction = win.qml_engine_entry ?? win.createQtAppInstance;
375
+ if (typeof win.qtLoad !== "function" || typeof entryFunction !== "function") {
376
+ throw new Error(
377
+ `The Qt scripts did not expose the expected WebAssembly entry points (qtLoad=${typeof win.qtLoad}, qml_engine_entry=${typeof win.qml_engine_entry}, createQtAppInstance=${typeof win.createQtAppInstance}).`
378
+ );
379
+ }
380
+ progress(95);
381
+ signal.throwIfAborted();
382
+ const runtime = await untilAborted(win.qtLoad({
383
+ locateFile: locate,
384
+ qmlViewerWarning: (message) => queueMicrotask(() => {
385
+ if (!signal.aborted) onError(message);
386
+ }),
387
+ qt: {
388
+ // Emscripten val::isArray() checks `instanceof global("Array")` in the iframe's realm.
389
+ containerElements: win.Array.of(screen),
390
+ entryFunction,
391
+ module: win.Promise.resolve(wasm),
392
+ onExit: ({ crashed, code, text }) => {
393
+ if (!signal.aborted && (crashed || code)) onError(text || `The Qt runtime exited (${code ?? "unknown error"}).`);
394
+ }
395
+ }
396
+ }), signal);
397
+ if (!runtime.FS || typeof runtime.loadMainQml !== "function" || typeof runtime.updateSddmConfig !== "function" || typeof runtime.clearWorkspace !== "function" || typeof runtime.setRenderingEnabled !== "function" || typeof runtime.shutdown !== "function") {
398
+ throw new Error("The Qt runtime is missing the qml-web-viewer exports.");
399
+ }
400
+ return runtime;
401
+ }
402
+
403
+ // src/index.ts
404
+ var workspace = "/workspace";
405
+ var defaults = {
406
+ hostName: "qml-preview",
407
+ canPowerOff: true,
408
+ canReboot: true,
409
+ canSuspend: true,
410
+ canHibernate: false,
411
+ canHybridSleep: false,
412
+ canSwitchUser: false,
413
+ loginSucceeds: false,
414
+ users: [{ name: "demo", realName: "Demo User", homeDir: "/home/demo", uid: 1e3 }],
415
+ sessions: [
416
+ { name: "Wayland", file: "wayland.desktop", type: "wayland" },
417
+ { name: "X11", file: "x11.desktop", type: "x11" }
418
+ ]
419
+ };
420
+ function messageOf(error) {
421
+ return error instanceof Error ? error.message : String(error);
422
+ }
423
+ function prepareFiles(files) {
424
+ const normalized = /* @__PURE__ */ Object.create(null);
425
+ const directories = /* @__PURE__ */ new Set();
426
+ for (const [name, data] of Object.entries(files)) {
427
+ const path = normalizePath(name);
428
+ if (Object.hasOwn(normalized, path)) throw new Error(`Duplicate theme file: ${path}`);
429
+ normalized[path] = data;
430
+ for (let slash = path.indexOf("/"); slash >= 0; slash = path.indexOf("/", slash + 1)) {
431
+ directories.add(path.slice(0, slash));
432
+ }
433
+ }
434
+ for (const directory2 of directories) {
435
+ if (Object.hasOwn(normalized, directory2)) throw new Error(`A theme path is both a file and a directory: ${directory2}`);
436
+ }
437
+ return { files: normalized, directories };
438
+ }
439
+ var QmlViewer = class {
440
+ constructor(options) {
441
+ this.options = options;
442
+ this.document = options.container.ownerDocument;
443
+ this.sddmConfig = options.sddmConfig;
444
+ this.maxPixelRatio = options.maxPixelRatio ?? 2;
445
+ if (!Number.isFinite(this.maxPixelRatio) || this.maxPixelRatio <= 0) {
446
+ throw new RangeError("maxPixelRatio must be a positive finite number.");
447
+ }
448
+ }
449
+ options;
450
+ maxPixelRatio;
451
+ document;
452
+ frame;
453
+ runtime;
454
+ initializing;
455
+ controller;
456
+ observer;
457
+ sddmConfig;
458
+ themeConfig;
459
+ generation = 0;
460
+ destroyed = false;
461
+ inViewport = true;
462
+ init() {
463
+ if (this.destroyed) return Promise.reject(new Error("This QmlViewer has been destroyed."));
464
+ return this.initializing ??= this.start();
465
+ }
466
+ async start() {
467
+ await Promise.resolve();
468
+ if (this.destroyed) throw new Error("This QmlViewer has been destroyed.");
469
+ const { container, wasmBaseUrl = "./wasm/" } = this.options;
470
+ const controller = this.controller = new AbortController();
471
+ const frame = this.frame = this.document.createElement("iframe");
472
+ frame.title = "Interactive QML preview";
473
+ Object.assign(frame.style, { display: "block", width: "100%", height: "100%", border: "0" });
474
+ try {
475
+ container.append(frame);
476
+ this.document.addEventListener("visibilitychange", this.syncVisibility);
477
+ const Observer = this.document.defaultView?.IntersectionObserver;
478
+ if (Observer) {
479
+ this.observer = new Observer(([entry]) => {
480
+ if (entry) this.inViewport = entry.isIntersecting && entry.intersectionRatio > 0;
481
+ this.syncVisibility();
482
+ });
483
+ this.observer.observe(frame);
484
+ }
485
+ const runtime = await loadWasmRuntime(
486
+ frame,
487
+ wasmBaseUrl,
488
+ this.maxPixelRatio,
489
+ controller.signal,
490
+ (percent) => this.options.onProgress?.(percent),
491
+ this.reportError
492
+ );
493
+ if (controller.signal.aborted) {
494
+ runtime.shutdown();
495
+ controller.signal.throwIfAborted();
496
+ }
497
+ this.runtime = runtime;
498
+ runtime.FS.mkdirTree(workspace);
499
+ runtime.updateSddmConfig(this.mockJson());
500
+ this.syncVisibility();
501
+ this.options.onProgress?.(100);
502
+ } catch (error) {
503
+ this.stop();
504
+ if (!this.destroyed) this.reportError(messageOf(error));
505
+ throw error;
506
+ }
507
+ }
508
+ async renderThemeFiles(input, entryFile) {
509
+ let prepared;
510
+ let theme;
511
+ try {
512
+ prepared = prepareFiles(input);
513
+ theme = resolveTheme(prepared.files, entryFile);
514
+ } catch (error2) {
515
+ this.reportError(messageOf(error2));
516
+ throw error2;
517
+ }
518
+ await this.init();
519
+ const runtime = this.runtime;
520
+ if (!runtime) throw new Error("This QmlViewer has been destroyed.");
521
+ const root = `${workspace}/theme-${++this.generation}`;
522
+ try {
523
+ const config = this.mockJson(theme.config);
524
+ if (!runtime.clearWorkspace()) throw new Error("Could not clear the Qt workspace.");
525
+ runtime.FS.mkdirTree(root);
526
+ for (const dir of prepared.directories) runtime.FS.mkdirTree(`${root}/${dir}`);
527
+ for (const [path, data] of Object.entries(prepared.files)) runtime.FS.writeFile(`${root}/${path}`, data);
528
+ runtime.updateSddmConfig(config);
529
+ this.themeConfig = theme.config;
530
+ } catch (error2) {
531
+ runtime.clearWorkspace();
532
+ this.reportError(messageOf(error2));
533
+ throw error2;
534
+ }
535
+ const importDirectory = theme.root ? `${root}/${theme.root.slice(0, -1)}` : root;
536
+ const error = runtime.loadMainQml(`${root}/${theme.entryFile}`, importDirectory);
537
+ if (error) throw new Error(error);
538
+ }
539
+ renderCode(qmlSource) {
540
+ return this.renderThemeFiles(fromCodeString(qmlSource), "Main.qml");
541
+ }
542
+ /** Update the mock environment used by the current and subsequent previews. */
543
+ setSddmConfig(config) {
544
+ if (this.destroyed) throw new Error("This QmlViewer has been destroyed.");
545
+ this.sddmConfig = config;
546
+ this.runtime?.updateSddmConfig(this.mockJson(this.themeConfig));
547
+ }
548
+ destroy() {
549
+ if (this.destroyed) return;
550
+ this.destroyed = true;
551
+ this.stop();
552
+ }
553
+ mockJson(themeConfig) {
554
+ const mock = { ...defaults, ...this.sddmConfig };
555
+ return JSON.stringify({ ...mock, config: { ...themeConfig, ...mock.config } });
556
+ }
557
+ syncVisibility = () => {
558
+ this.runtime?.setRenderingEnabled(this.inViewport && this.document.visibilityState !== "hidden");
559
+ };
560
+ reportError = (message) => {
561
+ if (this.destroyed) return;
562
+ try {
563
+ this.options.onError?.(message);
564
+ } catch (error) {
565
+ console.error("QmlViewer onError callback failed", error);
566
+ }
567
+ };
568
+ stop() {
569
+ this.controller?.abort();
570
+ this.observer?.disconnect();
571
+ this.document.removeEventListener("visibilitychange", this.syncVisibility);
572
+ try {
573
+ this.runtime?.shutdown();
574
+ } catch (error) {
575
+ this.reportError(messageOf(error));
576
+ } finally {
577
+ this.frame?.remove();
578
+ this.frame = void 0;
579
+ this.runtime = void 0;
580
+ this.initializing = void 0;
581
+ this.controller = void 0;
582
+ this.observer = void 0;
583
+ this.inViewport = true;
584
+ }
585
+ }
586
+ };
587
+ export {
588
+ QmlViewer,
589
+ fromCodeString,
590
+ fromFolderInput,
591
+ fromGitHubRepo,
592
+ fromSingleFile,
593
+ fromZipFile,
594
+ parseIni,
595
+ parseThemeConfig
596
+ };
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "qmlbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Render interactive Qt Quick QML and SDDM themes in a browser with Qt for WebAssembly",
5
+ "license": "GPL-3.0-only",
6
+ "keywords": [
7
+ "qml",
8
+ "qt",
9
+ "qt-quick",
10
+ "webassembly",
11
+ "wasm",
12
+ "sddm"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/OminduD/qml-web-viewer.git"
17
+ },
18
+ "homepage": "https://github.com/OminduD/qml-web-viewer#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/OminduD/qml-web-viewer/issues"
21
+ },
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "main": "./dist/index.cjs",
25
+ "module": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "import": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "require": {
34
+ "types": "./dist/index.d.cts",
35
+ "default": "./dist/index.cjs"
36
+ }
37
+ },
38
+ "./wasm/*": "./wasm/*"
39
+ },
40
+ "files": [
41
+ "dist",
42
+ "wasm"
43
+ ],
44
+ "scripts": {
45
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
46
+ "typecheck": "tsc --noEmit",
47
+ "dev": "vite --open /example/",
48
+ "prepack": "npm run build && node scripts/check-wasm.mjs",
49
+ "test:browser": "node scripts/smoke-browser.mjs"
50
+ },
51
+ "dependencies": {
52
+ "fflate": "0.8.3"
53
+ },
54
+ "devDependencies": {
55
+ "playwright": "1.65.1",
56
+ "tsup": "8.5.1",
57
+ "typescript": "5.9.3",
58
+ "vite": "6.4.6"
59
+ }
60
+ }