@stacksjs/stx 0.2.533 → 0.2.535
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/{chunk-843y0pfg.js → chunk-0yveptr0.js} +2 -2
- package/dist/{chunk-01343ehq.js → chunk-1es2y1jz.js} +1 -1
- package/dist/{chunk-13zbt9py.js → chunk-22ztsen0.js} +1 -1
- package/dist/{chunk-7zgtdap7.js → chunk-2kf4z3e6.js} +1 -1
- package/dist/{chunk-9p6bt089.js → chunk-33vbh6g3.js} +1 -1
- package/dist/{chunk-qqr4rn9p.js → chunk-5zp9wt6m.js} +2 -2
- package/dist/{chunk-pz1mjgsp.js → chunk-672nmsmm.js} +1 -1
- package/dist/{chunk-nmy4x6dx.js → chunk-7g90r41h.js} +1 -1
- package/dist/{chunk-f3q84h7b.js → chunk-8bt1mxny.js} +1 -1
- package/dist/{chunk-d1jxmhph.js → chunk-9e1hftmd.js} +1 -1
- package/dist/{chunk-7v2j9bmc.js → chunk-bgvqcjrg.js} +1 -1
- package/dist/{chunk-8chxczpj.js → chunk-bk5g7qez.js} +1 -1
- package/dist/{chunk-wxy9re1a.js → chunk-c0prbbpe.js} +1 -1
- package/dist/{chunk-kcs7hyep.js → chunk-dr0394tm.js} +1 -1
- package/dist/{chunk-tgc645pa.js → chunk-e6mmvwy9.js} +5 -5
- package/dist/{chunk-bxsehntq.js → chunk-f1cc1z85.js} +1 -1
- package/dist/{chunk-9674w2gm.js → chunk-g9byv420.js} +1 -1
- package/dist/{chunk-4a7v51vh.js → chunk-gx3cs15y.js} +1 -1
- package/dist/{chunk-sqb6gkzf.js → chunk-h51g1ydb.js} +1 -1
- package/dist/{chunk-gsc5t942.js → chunk-hen8zqnp.js} +1 -1
- package/dist/{chunk-tr9bjtqx.js → chunk-hpkrscgk.js} +1 -1
- package/dist/{chunk-z9r3tqyr.js → chunk-jn9e5a4t.js} +1 -1
- package/dist/{chunk-90kzf313.js → chunk-jq3j35a6.js} +1 -1
- package/dist/{chunk-xwrbrg1q.js → chunk-jsa2apk6.js} +1 -1
- package/dist/{chunk-94rg5s6c.js → chunk-jskc4rr7.js} +1 -1
- package/dist/{chunk-jv3jj612.js → chunk-knxqe213.js} +1 -1
- package/dist/chunk-kvn3xsfq.js +2 -0
- package/dist/{chunk-k3v13vfr.js → chunk-mx3rh8zj.js} +1 -1
- package/dist/chunk-n9k24wmf.js +57 -0
- package/dist/{chunk-d871008z.js → chunk-nn66ek7z.js} +1 -1
- package/dist/{chunk-ngma9vzc.js → chunk-pd460250.js} +1 -1
- package/dist/{chunk-v4r8nzf3.js → chunk-pekfkzh7.js} +1 -1
- package/dist/{chunk-gnx0fzne.js → chunk-pwdvc964.js} +19 -19
- package/dist/{chunk-3zs8yxy0.js → chunk-qmd2kvb2.js} +1 -1
- package/dist/{chunk-kvp0at16.js → chunk-s9htq6ef.js} +1 -1
- package/dist/{chunk-2n4je46m.js → chunk-sh8ec2e0.js} +1 -1
- package/dist/chunk-sve2646p.js +2 -0
- package/dist/{chunk-5g498pdp.js → chunk-sye2bjyq.js} +1 -1
- package/dist/{chunk-6rcxtdh3.js → chunk-tr49ckr5.js} +1 -1
- package/dist/{chunk-qk3ptn6h.js → chunk-va61kyky.js} +1 -1
- package/dist/{chunk-93n6yv5x.js → chunk-ve6tn04z.js} +1 -1
- package/dist/{chunk-0e5nasyf.js → chunk-vmq2dd3k.js} +1 -1
- package/dist/{chunk-fqfqyn48.js → chunk-xq7f1yc2.js} +1 -1
- package/dist/chunk-xvjtj1kt.js +2 -0
- package/dist/{chunk-vfnerp7h.js → chunk-xy5sx2z1.js} +1 -1
- package/dist/{chunk-2h4f37kx.js → chunk-xz7dk3yc.js} +1 -1
- package/dist/{chunk-zeve89kw.js → chunk-y5acfh13.js} +1 -1
- package/dist/{chunk-4pxc3r1p.js → chunk-z0h3we7z.js} +2 -2
- package/dist/{chunk-jvqas8y2.js → chunk-zaj09h72.js} +1 -1
- package/dist/{chunk-wjt46tdp.js → chunk-zs5p8jcn.js} +1 -1
- package/dist/cli.js +8 -8
- package/dist/client/signals-loop-conditional-runtime.d.ts +1 -1
- package/dist/client/signals-loop-conditional-runtime.js +1 -1
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/native/bridge/protocol.d.ts +3 -1
- package/dist/native/compiler/browser.d.ts +10 -0
- package/dist/native/compiler/browser.js +31 -0
- package/dist/native/compiler/bundle.d.ts +3 -0
- package/dist/native/compiler/bundle.js +27 -10
- package/dist/native/compiler/html-to-ir.d.ts +2 -0
- package/dist/native/compiler/html-to-ir.js +8 -3
- package/dist/native/compiler/icons.d.ts +2 -0
- package/dist/native/compiler/icons.js +2 -0
- package/dist/native/compiler/render-screen.d.ts +1 -0
- package/dist/native/compiler/render-screen.js +2 -2
- package/dist/native/index.d.ts +1 -0
- package/dist/native/index.js +1 -0
- package/dist/native/runtime/browser-renderer.d.ts +16 -0
- package/dist/native/runtime/browser-renderer.js +510 -0
- package/dist/native/runtime/browser-screen.d.ts +26 -0
- package/dist/native/runtime/browser-screen.js +225 -0
- package/dist/native/runtime/craft-bridge.js +10 -6
- package/dist/native/runtime/jsc-globals.js +1 -1
- package/dist/native/runtime/native-host.js +9 -4
- package/dist/pwa.js +1 -1
- package/dist/signals-loop-conditional-runtime.d.ts +1 -1
- package/dist/ssg.js +2 -2
- package/dist/variable-extractor.js +5 -1
- package/package.json +5 -5
- package/dist/chunk-40hbpz2b.js +0 -45
- package/dist/chunk-5wx323bm.js +0 -2
- package/dist/chunk-epa1c4q4.js +0 -2
- package/dist/chunk-ydtnskdv.js +0 -2
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { BrowserScreenRenderer } from "./browser-renderer.js";
|
|
2
|
+
export function createBrowserScreenBridge(platform, options) {
|
|
3
|
+
const rootPath = new URL(options.appURL, location.href).pathname.replace(/\/$/, "") || "/", container = document.querySelector(options.container);
|
|
4
|
+
if (!container)
|
|
5
|
+
throw Error(`Screen container ${options.container} does not exist`);
|
|
6
|
+
let listener = null, disposed = !1;
|
|
7
|
+
const chromeRenderers = [];
|
|
8
|
+
let serial = 0;
|
|
9
|
+
const pending = new Map, send = (type, payload, correlationId) => {
|
|
10
|
+
if (!disposed)
|
|
11
|
+
listener?.(JSON.stringify({ id: `browser_${++serial}`, type, payload, correlationId, source: "native", timestamp: Date.now() }));
|
|
12
|
+
}, renderer = new BrowserScreenRenderer(container, { icons: options.icons, resolveMedia: platform.resolveMedia, event: (handlerId, nativeEvent) => send("EVENT", { handlerId, nativeEvent }) }), g = globalThis;
|
|
13
|
+
g.craft = platform.craft;
|
|
14
|
+
const matched = matchBrowserRoute(location.pathname, options.routes);
|
|
15
|
+
g.__stxNativeParams = { ...Object.fromEntries(new URLSearchParams(location.search)), ...matched?.params, ...options.params };
|
|
16
|
+
const nav = document.createElement("header"), content = document.createElement("div"), tabs = document.createElement("nav"), shell = document.createElement("div");
|
|
17
|
+
shell.setAttribute("data-stx-screen-shell", "");
|
|
18
|
+
shell.style.cssText = "display:flex;flex-direction:column;height:100dvh;max-width:512px;margin:auto;color:#1c1c1e;background:#f2f2f7;font:17px system-ui,-apple-system,sans-serif;overflow:hidden";
|
|
19
|
+
content.style.cssText = "display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden";
|
|
20
|
+
container.before(shell);
|
|
21
|
+
shell.append(nav, content, tabs);
|
|
22
|
+
content.append(container);
|
|
23
|
+
container.style.cssText = "display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden";
|
|
24
|
+
nav.style.cssText = "display:flex;align-items:center;gap:12px;min-height:52px;padding:env(safe-area-inset-top) 16px 0;flex-shrink:0";
|
|
25
|
+
tabs.style.cssText = "display:flex;justify-content:space-around;gap:4px;padding:8px 8px max(8px,env(safe-area-inset-bottom));flex-shrink:0;border-top:1px solid #8884";
|
|
26
|
+
tabs.setAttribute("aria-label", "Main navigation");
|
|
27
|
+
const theme = () => {
|
|
28
|
+
const dark = document.documentElement.classList.contains("dark");
|
|
29
|
+
shell.style.background = dark ? "#000000" : "#f2f2f7";
|
|
30
|
+
shell.style.color = dark ? "#ffffff" : "#1c1c1e";
|
|
31
|
+
bridge.colorScheme = dark ? "dark" : "light";
|
|
32
|
+
send("APPEARANCE", { colorScheme: bridge.colorScheme });
|
|
33
|
+
}, navigation = (settings) => {
|
|
34
|
+
const title = typeof settings.title === "string" ? settings.title : options.title ?? "";
|
|
35
|
+
if (title)
|
|
36
|
+
document.title = title;
|
|
37
|
+
if (typeof settings.tabBarHidden === "boolean") {
|
|
38
|
+
tabs.hidden = settings.tabBarHidden;
|
|
39
|
+
tabs.style.display = settings.tabBarHidden ? "none" : "flex";
|
|
40
|
+
}
|
|
41
|
+
nav.hidden = settings.hidden === !0;
|
|
42
|
+
nav.style.display = nav.hidden ? "none" : "flex";
|
|
43
|
+
const heading = document.createElement("h1");
|
|
44
|
+
heading.textContent = title;
|
|
45
|
+
heading.style.cssText = `font-size:${settings.largeTitle ? 28 : 20}px;font-weight:700;flex:1;margin:8px 0`;
|
|
46
|
+
for (const icon of chromeRenderers.splice((options.tabs ?? []).filter((tab) => tab.symbol).length))
|
|
47
|
+
icon.dispose();
|
|
48
|
+
nav.replaceChildren();
|
|
49
|
+
if (location.pathname.replace(/\/$/, "") !== rootPath && !(options.tabs ?? []).some((tab) => tab.id === location.pathname.replace(/\/$/, ""))) {
|
|
50
|
+
const back = document.createElement("button");
|
|
51
|
+
back.type = "button";
|
|
52
|
+
back.textContent = String(settings.backTitle || "Back");
|
|
53
|
+
back.setAttribute("aria-label", back.textContent);
|
|
54
|
+
back.style.cssText = "font:inherit;color:#007aff;border:0;background:none;min-width:44px;min-height:44px";
|
|
55
|
+
back.onclick = () => history.length > 1 ? history.back() : platform.navigate(rootPath);
|
|
56
|
+
nav.append(back);
|
|
57
|
+
}
|
|
58
|
+
nav.append(heading);
|
|
59
|
+
if (Array.isArray(settings.rightButtons))
|
|
60
|
+
for (const item of settings.rightButtons) {
|
|
61
|
+
const button = document.createElement("button");
|
|
62
|
+
button.type = "button";
|
|
63
|
+
button.style.cssText = "display:flex;align-items:center;justify-content:center;min-width:44px;min-height:44px;border:0;border-radius:50%;background:transparent;color:inherit;font:inherit;position:relative";
|
|
64
|
+
button.setAttribute("aria-label", String(item.accessibilityLabel ?? item.title ?? item.id));
|
|
65
|
+
if (item.image) {
|
|
66
|
+
const image = document.createElement("img");
|
|
67
|
+
image.src = String(item.image);
|
|
68
|
+
image.alt = "";
|
|
69
|
+
image.style.cssText = "width:32px;height:32px;border-radius:50%;object-fit:cover";
|
|
70
|
+
button.append(image);
|
|
71
|
+
} else if (item.title)
|
|
72
|
+
button.textContent = String(item.title);
|
|
73
|
+
else {
|
|
74
|
+
const holder = document.createElement("span");
|
|
75
|
+
button.append(holder);
|
|
76
|
+
const icon = new BrowserScreenRenderer(holder, { icons: options.icons, event() {} });
|
|
77
|
+
chromeRenderers.push(icon);
|
|
78
|
+
icon.render({ id: `nav_${item.id}`, type: "Icon", props: { symbol: item.symbol }, style: { width: 24, height: 24 }, events: {}, children: [] });
|
|
79
|
+
}
|
|
80
|
+
if (Number(item.badge) > 0) {
|
|
81
|
+
const badge = document.createElement("span");
|
|
82
|
+
badge.textContent = item.badgeStyle === "dot" ? "" : String(item.badge);
|
|
83
|
+
badge.style.cssText = "position:absolute;top:0;right:0;background:#ff3b30;color:white;border-radius:10px;padding:1px 4px;font-size:10px";
|
|
84
|
+
if (item.badgeStyle === "dot")
|
|
85
|
+
badge.style.cssText += ";width:8px;height:8px;padding:0";
|
|
86
|
+
button.append(badge);
|
|
87
|
+
}
|
|
88
|
+
button.onclick = () => send("NAV_BUTTON", { id: String(item.id) });
|
|
89
|
+
nav.append(button);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
for (const tab of options.tabs ?? []) {
|
|
93
|
+
const link = document.createElement("a");
|
|
94
|
+
link.href = tab.id;
|
|
95
|
+
link.style.cssText = "display:flex;flex:1;flex-direction:column;align-items:center;gap:3px;min-height:44px;text-decoration:none;color:inherit;font-size:11px";
|
|
96
|
+
const iconRoot = document.createElement("span");
|
|
97
|
+
link.append(iconRoot);
|
|
98
|
+
if (tab.symbol) {
|
|
99
|
+
const icon = new BrowserScreenRenderer(iconRoot, { icons: options.icons, event() {} });
|
|
100
|
+
chromeRenderers.push(icon);
|
|
101
|
+
icon.render({ id: `tab_${tab.id}`, type: "Icon", props: { symbol: tab.symbol }, style: { width: 23, height: 23 }, events: {}, children: [] });
|
|
102
|
+
}
|
|
103
|
+
const label = document.createElement("span");
|
|
104
|
+
label.textContent = tab.title;
|
|
105
|
+
link.append(label);
|
|
106
|
+
if (location.pathname.replace(/\/$/, "") === tab.id || tab.id !== rootPath && location.pathname.startsWith(`${tab.id}/`)) {
|
|
107
|
+
link.setAttribute("aria-current", "page");
|
|
108
|
+
link.style.color = "#007aff";
|
|
109
|
+
}
|
|
110
|
+
tabs.append(link);
|
|
111
|
+
}
|
|
112
|
+
tabs.hidden = !options.tabs?.length;
|
|
113
|
+
const navigateScreen = (screen, params, replace = !1) => {
|
|
114
|
+
const route = Object.entries(options.routes).find(([, name]) => name === screen)?.[0];
|
|
115
|
+
if (!route)
|
|
116
|
+
throw Error(`No browser route for screen ${screen}`);
|
|
117
|
+
const values = params && typeof params === "object" ? { ...params } : {}, path = route.replace(/:([a-z\d_]+)/gi, (_, key) => {
|
|
118
|
+
const value = values[key];
|
|
119
|
+
if (value == null)
|
|
120
|
+
throw Error(`Missing route parameter ${key}`);
|
|
121
|
+
delete values[key];
|
|
122
|
+
return encodeURIComponent(String(value));
|
|
123
|
+
}), query = new URLSearchParams(Object.entries(values).map(([key, value]) => [key, String(value)]));
|
|
124
|
+
platform.navigate(path + (query.size ? `?${query}` : ""), replace);
|
|
125
|
+
}, bridge = {
|
|
126
|
+
resolveFile: platform.resolveFile,
|
|
127
|
+
routeURL: location.pathname + location.search,
|
|
128
|
+
platform: "web",
|
|
129
|
+
capabilityProtocolVersion: 1,
|
|
130
|
+
capabilities: platform.capabilities,
|
|
131
|
+
appURL: new URL(options.appURL, location.href).href,
|
|
132
|
+
initialAppState: document.hidden ? "background" : "active",
|
|
133
|
+
colorScheme: document.documentElement.classList.contains("dark") ? "dark" : "light",
|
|
134
|
+
onMessage(callback) {
|
|
135
|
+
listener = callback;
|
|
136
|
+
},
|
|
137
|
+
postMessage(raw) {
|
|
138
|
+
if (disposed)
|
|
139
|
+
return;
|
|
140
|
+
const message = JSON.parse(raw), { type, payload } = message;
|
|
141
|
+
if (type === "RENDER")
|
|
142
|
+
try {
|
|
143
|
+
renderer.render(payload.document);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
container.textContent = "This screen could not render. Reload to try again.";
|
|
146
|
+
container.setAttribute("role", "alert");
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
else if (type === "MUTATE")
|
|
150
|
+
try {
|
|
151
|
+
renderer.mutate(payload);
|
|
152
|
+
send("MUTATION_ACK", { batchId: payload.batchId, revision: payload.revision, version: 1 });
|
|
153
|
+
} catch (error) {
|
|
154
|
+
send("MUTATION_ERROR", { batchId: payload.batchId, version: 1, code: error instanceof Error && error.message === "REVISION_MISMATCH" ? "REVISION_MISMATCH" : "INVALID_MUTATION", message: String(error) });
|
|
155
|
+
}
|
|
156
|
+
else if (type === "NAVIGATION_SET_OPTIONS")
|
|
157
|
+
navigation(payload);
|
|
158
|
+
else if (type === "NAVIGATE_OPEN")
|
|
159
|
+
platform.navigate(String(payload.path));
|
|
160
|
+
else if (type === "NAVIGATE_BACK")
|
|
161
|
+
history.length > 1 ? history.back() : platform.navigate(rootPath);
|
|
162
|
+
else if (type === "NAVIGATE_POP_TO_ROOT")
|
|
163
|
+
platform.navigate(options.tabs?.find((tab) => location.pathname.startsWith(tab.id) && tab.id !== rootPath)?.id ?? options.tabs?.[0]?.id ?? rootPath);
|
|
164
|
+
else if (type === "NAVIGATE" || type === "NAVIGATE_REPLACE")
|
|
165
|
+
navigateScreen(payload.screen, payload.params, type === "NAVIGATE_REPLACE");
|
|
166
|
+
else if (type === "API_CANCEL") {
|
|
167
|
+
pending.get(String(payload.requestId))?.abort();
|
|
168
|
+
pending.delete(String(payload.requestId));
|
|
169
|
+
} else if (type === "API_REQUEST") {
|
|
170
|
+
const controller = new AbortController;
|
|
171
|
+
pending.set(message.id, controller);
|
|
172
|
+
platform.call(String(payload.module), String(payload.method), Array.isArray(payload.args) ? payload.args : [], controller.signal).then((data) => send("API_RESPONSE", { data }, message.id), (error) => send("API_ERROR", { code: error && typeof error === "object" && "code" in error ? error.code : "BROWSER_ERROR", message: error instanceof Error ? error.message : String(error) }, message.id)).finally(() => pending.delete(message.id));
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
dispose() {
|
|
176
|
+
if (disposed)
|
|
177
|
+
return;
|
|
178
|
+
disposed = !0;
|
|
179
|
+
for (const controller of pending.values())
|
|
180
|
+
controller.abort();
|
|
181
|
+
pending.clear();
|
|
182
|
+
observer.disconnect();
|
|
183
|
+
media.removeEventListener("change", theme);
|
|
184
|
+
document.removeEventListener("visibilitychange", visibility);
|
|
185
|
+
stopEvents?.();
|
|
186
|
+
renderer.dispose();
|
|
187
|
+
for (const icon of chromeRenderers)
|
|
188
|
+
icon.dispose();
|
|
189
|
+
platform.dispose();
|
|
190
|
+
shell.before(container);
|
|
191
|
+
shell.remove();
|
|
192
|
+
listener = null;
|
|
193
|
+
}
|
|
194
|
+
}, visibility = () => send("APP_STATE", { state: document.hidden ? "background" : "active" });
|
|
195
|
+
document.addEventListener("visibilitychange", visibility);
|
|
196
|
+
const media = matchMedia("(prefers-color-scheme: dark)");
|
|
197
|
+
media.addEventListener("change", theme);
|
|
198
|
+
const observer = new MutationObserver(theme);
|
|
199
|
+
observer.observe(document.documentElement, { attributes: !0, attributeFilter: ["class"] });
|
|
200
|
+
const stopEvents = platform.emit?.(send);
|
|
201
|
+
navigation({ title: options.title });
|
|
202
|
+
theme();
|
|
203
|
+
return bridge;
|
|
204
|
+
}
|
|
205
|
+
export function matchBrowserRoute(path, routes) {
|
|
206
|
+
const pieces = path.replace(/\/$/, "").split("/");
|
|
207
|
+
return Object.entries(routes).flatMap(([route, screen]) => {
|
|
208
|
+
const segments = route.replace(/\/$/, "").split("/");
|
|
209
|
+
if (segments.length !== pieces.length)
|
|
210
|
+
return [];
|
|
211
|
+
const params = {};
|
|
212
|
+
for (let index = 0;index < segments.length; index++) {
|
|
213
|
+
const segment = segments[index];
|
|
214
|
+
if (segment.startsWith(":"))
|
|
215
|
+
try {
|
|
216
|
+
params[segment.slice(1)] = decodeURIComponent(pieces[index]);
|
|
217
|
+
} catch {
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
else if (segment !== pieces[index])
|
|
221
|
+
return [];
|
|
222
|
+
}
|
|
223
|
+
return [{ screen, params, score: segments.filter((segment) => !segment.startsWith(":")).length }];
|
|
224
|
+
}).sort((a, b) => b.score - a.score)[0] ?? null;
|
|
225
|
+
}
|
|
@@ -64,13 +64,13 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
|
|
|
64
64
|
let focused = !0;
|
|
65
65
|
const routeName = options.routeName || "main", routeNames = options.routeNames || [routeName];
|
|
66
66
|
craft.platform = nativeBridge.platform || "unknown";
|
|
67
|
-
const navigatorObject = target.navigator
|
|
67
|
+
const navigatorObject = target.navigator || (target.navigator = {});
|
|
68
68
|
if (typeof navigatorObject.userAgent !== "string")
|
|
69
69
|
navigatorObject.userAgent = platformUserAgent(craft.platform);
|
|
70
70
|
craft.capabilityProtocolVersion = Number(nativeBridge.capabilityProtocolVersion || 0);
|
|
71
71
|
craft.capabilities = capabilityFlags(capabilities);
|
|
72
72
|
const paramsHandlers = new Set;
|
|
73
|
-
craft.route = { name: routeName, params: target.__stxNativeParams || {} };
|
|
73
|
+
craft.route = { name: routeName, params: target.__stxNativeParams || {}, ...nativeBridge.routeURL ? { path: nativeBridge.routeURL } : {} };
|
|
74
74
|
Object.defineProperty(craft.route, "onParams", {
|
|
75
75
|
value: (callback) => {
|
|
76
76
|
if (typeof callback !== "function")
|
|
@@ -378,11 +378,15 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
|
|
|
378
378
|
};
|
|
379
379
|
if (capabilities.has("files")) {
|
|
380
380
|
craft.files = {
|
|
381
|
+
pickVideo: (options = {}) => ask("Files", "pickVideo", [{
|
|
382
|
+
source: options.source === "files" ? "files" : "library",
|
|
383
|
+
...typeof options.maxBytes === "number" ? { maxBytes: options.maxBytes } : {}
|
|
384
|
+
}]).then((file) => nativeBridge.resolveFile ? nativeBridge.resolveFile(file) : file ?? null),
|
|
381
385
|
pickImage: (options = {}) => ask("Files", "pickImage", [{
|
|
382
386
|
source: options.source === "camera" ? "camera" : "library",
|
|
383
387
|
...typeof options.maxPixels === "number" ? { maxPixels: options.maxPixels } : {},
|
|
384
388
|
...typeof options.quality === "number" ? { quality: options.quality } : {}
|
|
385
|
-
}]).then((file) => file ?? null),
|
|
389
|
+
}]).then((file) => nativeBridge.resolveFile ? nativeBridge.resolveFile(file) : file ?? null),
|
|
386
390
|
download: (url, options = {}) => {
|
|
387
391
|
if (typeof url !== "string" || !url)
|
|
388
392
|
return Promise.reject(TypeError("files.download needs a URL"));
|
|
@@ -391,7 +395,7 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
|
|
|
391
395
|
Object.keys(given).forEach((name) => {
|
|
392
396
|
headers[name] = String(given[name]);
|
|
393
397
|
});
|
|
394
|
-
return request("Files", "download", [url, { headers, ...typeof options.name === "string" ? { name: options.name } : {} }]);
|
|
398
|
+
return request("Files", "download", [url, { headers, ...typeof options.name === "string" ? { name: options.name } : {} }]).then((file) => nativeBridge.resolveFile ? nativeBridge.resolveFile(file) : file);
|
|
395
399
|
},
|
|
396
400
|
write: (name, data, options = {}) => {
|
|
397
401
|
if (typeof name !== "string" || !name.trim())
|
|
@@ -401,7 +405,7 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
|
|
|
401
405
|
return request("Files", "write", [name, data, {
|
|
402
406
|
encoding: options.encoding === "base64" ? "base64" : "utf8",
|
|
403
407
|
...typeof options.type === "string" ? { type: options.type } : {}
|
|
404
|
-
}]);
|
|
408
|
+
}]).then((file) => nativeBridge.resolveFile ? nativeBridge.resolveFile(file) : file);
|
|
405
409
|
},
|
|
406
410
|
remove: (file) => request("Files", "remove", [typeof file === "string" ? file : file?.path]).then(Boolean)
|
|
407
411
|
};
|
|
@@ -648,7 +652,7 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
|
|
|
648
652
|
return Promise.reject(abortError(signal.reason));
|
|
649
653
|
if (streaming && !form && /text\/event-stream/i.test(headers.accept || ""))
|
|
650
654
|
return streamingFetch(url, method, headers, body == null ? null : body, signal);
|
|
651
|
-
const answer = request("Network", "fetch", [{ url, method, headers, body: body == null ? null : body, ...form ? { form } : {} }]).then((data) => {
|
|
655
|
+
const answer = (form ? ask : request)("Network", "fetch", [{ url, method, headers, body: body == null ? null : body, ...form ? { form } : {} }]).then((data) => {
|
|
652
656
|
const responseBody = data?.body == null ? "" : String(data.body);
|
|
653
657
|
let bodyUsed = !1;
|
|
654
658
|
return response(data, { get bodyUsed() {
|
|
@@ -618,7 +618,7 @@ export function installJSCGlobals(target = globalThis) {
|
|
|
618
618
|
}, emptyList = [], documentElement = { setAttribute() {}, removeAttribute() {}, getAttribute() {
|
|
619
619
|
return null;
|
|
620
620
|
} }, head = { appendChild() {} };
|
|
621
|
-
target.window
|
|
621
|
+
target.window ??= target;
|
|
622
622
|
target.Node ??= { ELEMENT_NODE: 1, TEXT_NODE: 3, COMMENT_NODE: 8 };
|
|
623
623
|
target.Event ??= NativeEvent;
|
|
624
624
|
target.CustomEvent ??= NativeEvent;
|
|
@@ -199,9 +199,11 @@ export function createNativeHost(options) {
|
|
|
199
199
|
emit({ op: "updateNode", id, patch: { style: { ...patch, ...style } } });
|
|
200
200
|
const classes = compileClassStyles(record.classes);
|
|
201
201
|
if (record.type === "Icon" && classes.icon) {
|
|
202
|
-
|
|
202
|
+
const icon = resolveIconName(classes.icon);
|
|
203
|
+
record.props.symbol = icon.symbol;
|
|
204
|
+
record.props.iconify = icon.iconify;
|
|
203
205
|
if (record.materialized)
|
|
204
|
-
emit({ op: "updateNode", id, patch: { props: { symbol: record.props.symbol } } });
|
|
206
|
+
emit({ op: "updateNode", id, patch: { props: { symbol: record.props.symbol, iconify: icon.iconify } } });
|
|
205
207
|
}
|
|
206
208
|
if (classes.numberOfLines !== void 0) {
|
|
207
209
|
record.props.numberOfLines = classes.numberOfLines;
|
|
@@ -372,8 +374,11 @@ export function createNativeHost(options) {
|
|
|
372
374
|
}
|
|
373
375
|
const prop = nativePropName(name), record = recordOf(node);
|
|
374
376
|
record.props[prop] = value;
|
|
375
|
-
if (record.type === "Icon" && prop === "name")
|
|
376
|
-
|
|
377
|
+
if (record.type === "Icon" && prop === "name") {
|
|
378
|
+
const icon = resolveIconName(String(value ?? ""));
|
|
379
|
+
this.setAttribute(node, "iconify", icon.iconify ?? null);
|
|
380
|
+
this.setAttribute(node, "symbol", icon.symbol);
|
|
381
|
+
}
|
|
377
382
|
const patch = { [prop]: value };
|
|
378
383
|
if (SVG_NODE_TYPES.has(record.type)) {
|
|
379
384
|
if (prop === "strokeDasharray" && value != null && !Array.isArray(value))
|
package/dist/pwa.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{Bn,Ne,Ho,Xa}from"./chunk-m56m95gk.js";import{jn,Wr,qa,Ga,Ka}from"./chunk-6dtmants.js";import{Bo,Fo,zo,Va,Wa}from"./chunk-66s4nhp7.js";import{ie,ht,qr}from"./chunk-6abvk7vj.js";import{Zc,Qc,el,tl,mr,wu}from"./chunk-r6gxy92f.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
|
|
3
|
-
Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-
|
|
3
|
+
Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-g9byv420.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="UTF-8">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Loop-row conditional deferral for the generated client runtime. */
|
|
2
|
-
export declare const SIGNALS_LOOP_CONDITIONAL_RUNTIME = " // A :for row is a clone of its template, so a conditional element in the row\n // is built for every row whether or not its condition ever holds; :if then\n // parks the false ones. In WebKit a <video> or <audio> sets up a media player\n // as it is created: a message list with one media slot per attachment took\n // 1.8s to render instead of 18ms, and every row paid for elements it never\n // showed. Before any row is cloned, each eligible conditional element in the\n // row template is moved into a <template> carrying its condition. Template\n // content is inert, so a cloned row builds the element only when the\n // condition holds (bindIf clones template content on the first true).\n //\n // Left alone: an if/else chain (its branches must stay siblings), an element\n // that is also a loop, a component (its setup script is a sibling), and\n // anything holding a script.\n var IF_ATTRS = [':if', 'x-if', '@if'];\n var FOR_ATTRS = [':for', 'x-for', '@for'];\n function deferRowConditionals(root) {\n if (!root || !root.querySelectorAll || typeof document === 'undefined' || !document.createElement) return;\n // Inert HTML template content is a DOM allocation optimisation. Native\n // hosts already clone recorded descriptors and bind conditions through\n // their host operations; their document facade has no template content.\n if (!document.createElement('template').content) return;\n // A walk, not a selector: escaping ':' and '@' in an attribute selector\n // through this generated source is easy to get wrong, and wrong throws.\n var candidates = Array.prototype.slice.call(root.querySelectorAll('*'));\n for (var i = 0; i < candidates.length; i++) {\n var el = candidates[i];\n if (el.tagName === 'TEMPLATE' || !el.parentNode) continue;\n var attr = null;\n for (var a = 0; a < IF_ATTRS.length; a++) {\n if (el.hasAttribute(IF_ATTRS[a])) { attr = IF_ATTRS[a]; break; }\n }\n if (!attr) continue;\n var skip = false;\n for (var f = 0; f < FOR_ATTRS.length; f++) {\n if (el.hasAttribute(FOR_ATTRS[f])) skip = true;\n }\n if (skip || getElseAttrInfo(el)) continue;\n var next = el.nextElementSibling;\n if (next && (getElseAttrInfo(next) || next.tagName === 'SCRIPT')) continue;\n if (el.hasAttribute('data-stx-scope') || el.hasAttribute('x-data') || el.querySelector('script')) continue;\n var holder = document.createElement('template');\n holder.setAttribute(attr, el.getAttribute(attr));\n el.removeAttribute(attr);\n el.parentNode.insertBefore(holder, el);\n holder.content.appendChild(el);\n }\n }\n";
|
|
2
|
+
export declare const SIGNALS_LOOP_CONDITIONAL_RUNTIME = " // A :for row is a clone of its template, so a conditional element in the row\n // is built for every row whether or not its condition ever holds; :if then\n // parks the false ones. In WebKit a <video> or <audio> sets up a media player\n // as it is created: a message list with one media slot per attachment took\n // 1.8s to render instead of 18ms, and every row paid for elements it never\n // showed. Before any row is cloned, each eligible conditional element in the\n // row template is moved into a <template> carrying its condition. Template\n // content is inert, so a cloned row builds the element only when the\n // condition holds (bindIf clones template content on the first true).\n //\n // Left alone: an if/else chain (its branches must stay siblings), an element\n // that is also a loop, a component (its setup script is a sibling), and\n // anything holding a script.\n var IF_ATTRS = [':if', 'x-if', '@if'];\n var FOR_ATTRS = [':for', 'x-for', '@for'];\n function deferRowConditionals(root) {\n if (stxHost.isNative || !root || !root.querySelectorAll || typeof document === 'undefined' || !document.createElement) return;\n // Inert HTML template content is a DOM allocation optimisation. Native\n // hosts already clone recorded descriptors and bind conditions through\n // their host operations; their document facade has no template content.\n if (!document.createElement('template').content) return;\n // A walk, not a selector: escaping ':' and '@' in an attribute selector\n // through this generated source is easy to get wrong, and wrong throws.\n var candidates = Array.prototype.slice.call(root.querySelectorAll('*'));\n for (var i = 0; i < candidates.length; i++) {\n var el = candidates[i];\n if (el.tagName === 'TEMPLATE' || !el.parentNode) continue;\n var attr = null;\n for (var a = 0; a < IF_ATTRS.length; a++) {\n if (el.hasAttribute(IF_ATTRS[a])) { attr = IF_ATTRS[a]; break; }\n }\n if (!attr) continue;\n var skip = false;\n for (var f = 0; f < FOR_ATTRS.length; f++) {\n if (el.hasAttribute(FOR_ATTRS[f])) skip = true;\n }\n if (skip || getElseAttrInfo(el)) continue;\n var next = el.nextElementSibling;\n if (next && (getElseAttrInfo(next) || next.tagName === 'SCRIPT')) continue;\n if (el.hasAttribute('data-stx-scope') || el.hasAttribute('x-data') || el.querySelector('script')) continue;\n var holder = document.createElement('template');\n holder.setAttribute(attr, el.getAttribute(attr));\n el.removeAttribute(attr);\n el.parentNode.insertBefore(holder, el);\n holder.content.appendChild(el);\n }\n }\n";
|
package/dist/ssg.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-azb58ven.js";import"./chunk-vhfwnvmc.js";import"./chunk-bpr4bkde.js";import{nt,rt,st,ot,it,at}from"./chunk-2bvk0qyd.js";import"./chunk-d7zterbp.js";import"./chunk-6v1gwdbv.js";import{f,ze,N,K,n,o}from"./chunk-
|
|
2
|
+
import"./chunk-azb58ven.js";import"./chunk-vhfwnvmc.js";import"./chunk-bpr4bkde.js";import{nt,rt,st,ot,it,at}from"./chunk-2bvk0qyd.js";import"./chunk-d7zterbp.js";import"./chunk-6v1gwdbv.js";import{f,ze,N,K,n,o}from"./chunk-pwdvc964.js";import"./chunk-y18yvcjb.js";import{sr}from"./chunk-tkvp3rz0.js";import"./chunk-v9vvzdag.js";import"./chunk-1es2y1jz.js";import"./chunk-1xgs9gd5.js";import"./chunk-x607yxrc.js";import"./chunk-7g90r41h.js";import{ae,yt,bt}from"./chunk-nn66ek7z.js";import{No,Lo,jo}from"./chunk-wk85dz07.js";import{mt,Qt,en}from"./chunk-hpeg9erh.js";import"./chunk-bczcm7jk.js";import{a}from"./chunk-4cmqjmqr.js";import x from"fs";import g from"path";import{createHash as Dt}from"crypto";function Rt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var kt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function Ct(t){return Bun.hash(t).toString(16)}function ut(t,i={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,r=t.replace(kt,(e,l,w,y)=>{let h=y.trim();if(!h)return e;if(/\bdata-stx-src=/.test(w))return e;if(i.minify)h=Rt(h);let S=Ct(h);if(!s.has(S))s.set(S,h);let P=i.integrity?` data-stx-integrity="sha384-${Dt("sha384").update(h).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${l}" data-stx-src="/_stx/islands/${S}.js"${P}${w}></script>`}),c=Array.from(s,([e,l])=>({hash:e,code:l}));return{html:r,chunks:c}}var Et=new Set(["visible","idle"]);function dt(t){if(!t.includes("data-stx-src="))return t;let i=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,r;while((r=s.exec(t))!==null)i.set(r[1],r[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,l;while((l=e.exec(t))!==null)if(Et.has(i.get(l[1])||""))c.add(l[2]);let w=t.lastIndexOf("</head>");if(c.size===0||w===-1)return t;let y=Array.from(c).filter((h)=>!t.includes(`rel="prefetch" href="${h}"`)).map((h)=>`<link rel="prefetch" href="${h}" as="script">`).join("");if(!y)return t;return t.slice(0,w)+y+t.slice(w)}var It=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function q(t){let i=t.trim();if(!i)return null;let s=/^https?:\/\//i.test(i)?i:`https://${i}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function Bt(t){for(let i of It){let s=t[i];if(!s)continue;let r=q(s);if(r)return{url:r,source:"env",via:i}}return null}function gt(t){if(!t||typeof t!=="object")return null;let i=t,s=i.site?.url??i.url??i.app?.url;return typeof s==="string"?q(s):null}async function jt(t){let{existsSync:i}=await import("fs"),s=await import("path");for(let r of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=s.resolve(t,r);if(!i(c))continue;try{let e=await import(c),l=gt(e.default??e);if(l)return l}catch{}}return null}async function pt(t={}){let i=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let l=q(t.explicit);if(l)return{url:l,source:"option"}}let r=gt(t.stxConfig);if(r)return{url:r,source:"stx.config",via:"site.url"};let c=await jt(i);if(c)return{url:c,source:"site.config",via:"url"};let e=Bt(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function ht(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
|
|
3
3
|
`)}class ft{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,i=""){this.cacheDir=t,this.salt=i}async load(){if(this.loaded)return;let t=g.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let i=JSON.parse(await Bun.file(t).text());for(let[s,r]of Object.entries(i))this.cache.set(s,r)}catch{}this.loaded=!0}async save(){await x.promises.mkdir(this.cacheDir,{recursive:!0});let t=g.join(this.cacheDir,"build-cache.json"),i={};for(let[s,r]of this.cache)i[s]=r;await Bun.write(t,JSON.stringify(i))}getHash(t,i){let s=x.statSync(t),r=`${this.salt}|${t}:${s.mtimeMs}`;for(let e of i)if(x.existsSync(e)){let l=x.statSync(e);r+=`:${e}:${l.mtimeMs}`}let c=0;for(let e=0;e<r.length;e++){let l=r.charCodeAt(e);c=(c<<5)-c+l,c=c&c}return Math.abs(c).toString(36)}get(t,i){let s=this.cache.get(t);if(!s)return null;let r=this.getHash(i,s.dependencies??[]);if(s.hash!==r)return this.cache.delete(t),null;return s.html}set(t,i,s,r){let c=this.getHash(i,s);this.cache.set(t,{hash:c,html:r,generatedAt:Date.now(),dependencies:s})}}class wt{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let i=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return g.join(this.cacheDir,"isr",i)}async get(t){let i=this.getFilePath(t);if(!await Bun.file(i).exists())return null;try{return JSON.parse(await Bun.file(i).text())}catch{return null}}async set(t,i){let s=this.getFilePath(t);await x.promises.mkdir(g.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(i))}async invalidate(t){let i=this.getFilePath(t);if(await Bun.file(i).exists())await x.promises.unlink(i)}async invalidatePattern(t){let i=g.join(this.cacheDir,"isr");if(!x.existsSync(i))return;let s=await x.promises.readdir(i);for(let r of s){let c=r.replace(/_/g,"/").replace(".json","");if(t.test(c))await x.promises.unlink(g.join(i,r))}}async needsRevalidation(t){let i=await this.get(t);if(!i)return!0;return Date.now()>i.revalidateAfter}}async function Ft(t){try{let s=(await Bun.file(t).text()).match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return null;let r=s[1];if(!r.includes("getStaticPaths"))return null;let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticPaths\s*\([^)]*\)\s*\{([\s\S]*?)\n[\t ]*\}/);if(!c)return null;return await Function(`
|
|
4
4
|
return (async function getStaticPaths() {
|
|
5
5
|
${c[1]}
|
|
@@ -41,7 +41,7 @@ ${t.map((r)=>{let c=new URL(r.loc,i).href,e=` <url>
|
|
|
41
41
|
${s.join(`
|
|
42
42
|
`)}
|
|
43
43
|
</channel>
|
|
44
|
-
</rss>`}async function zt(t={}){let i=Date.now();bt();let s=await o(process.cwd()),r=s.build||{},c=await pt({explicit:t.domain||r.domain,stxConfig:s});if(c.source==="fallback"&&(t.sitemap??r.sitemap??!0))console.warn(ht());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||r.pagesDir||"pages",outputDir:t.outputDir||r.outputDir||"dist",baseUrl:t.baseUrl||r.baseUrl||"/",domain:c.url,revalidate:t.revalidate??r.revalidate??!1,sitemap:t.sitemap??r.sitemap??!0,sitemapExclude:t.sitemapExclude||r.sitemapExclude||[],robots:t.robots??r.robots??!0,rss:t.rss??r.rss??!1,concurrency:t.concurrency||r.concurrency||10,cache:t.cache??r.cache??!0,cacheDir:t.cacheDir||r.cacheDir||a(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??r.minify??!0,generate404:t.generate404??r.generate404??!0,publicDir:t.publicDir||r.publicDir||"public",trailingSlash:t.trailingSlash??r.trailingSlash??!1,cleanOutput:t.cleanOutput??r.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},l={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},w=new Set,y=0,h={},S={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&x.existsSync(e.outputDir))await x.promises.rm(e.outputDir,{recursive:!0});await x.promises.mkdir(e.outputDir,{recursive:!0});let D=e.cacheSalt;if(!D){let{resolveUserCssConfig:u,fingerprintConfig:m}=await import("./chunk-
|
|
44
|
+
</rss>`}async function zt(t={}){let i=Date.now();bt();let s=await o(process.cwd()),r=s.build||{},c=await pt({explicit:t.domain||r.domain,stxConfig:s});if(c.source==="fallback"&&(t.sitemap??r.sitemap??!0))console.warn(ht());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||r.pagesDir||"pages",outputDir:t.outputDir||r.outputDir||"dist",baseUrl:t.baseUrl||r.baseUrl||"/",domain:c.url,revalidate:t.revalidate??r.revalidate??!1,sitemap:t.sitemap??r.sitemap??!0,sitemapExclude:t.sitemapExclude||r.sitemapExclude||[],robots:t.robots??r.robots??!0,rss:t.rss??r.rss??!1,concurrency:t.concurrency||r.concurrency||10,cache:t.cache??r.cache??!0,cacheDir:t.cacheDir||r.cacheDir||a(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??r.minify??!0,generate404:t.generate404??r.generate404??!0,publicDir:t.publicDir||r.publicDir||"public",trailingSlash:t.trailingSlash??r.trailingSlash??!1,cleanOutput:t.cleanOutput??r.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},l={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},w=new Set,y=0,h={},S={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&x.existsSync(e.outputDir))await x.promises.rm(e.outputDir,{recursive:!0});await x.promises.mkdir(e.outputDir,{recursive:!0});let D=e.cacheSalt;if(!D){let{resolveUserCssConfig:u,fingerprintConfig:m}=await import("./chunk-jq3j35a6.js");try{D=m(await u(process.cwd()))}catch{}}let{prepareImageDelivery:p}=await import("./chunk-hen8zqnp.js"),b=await p(e.publicDir,e.outputDir);if(b.count>0)console.log(`Optimized ${b.count} image(s) for responsive delivery`),D=[D,b.fingerprint].filter(Boolean).join(":");let B=new ft(e.cacheDir,D);if(e.cache)await B.load();try{let{generateCss:u}=await import("./chunk-jq3j35a6.js");await u('<div class="bg-black"></div>')}catch{}nt();let xt=s?.routeMiddleware?.dir||"middleware";await st(process.cwd(),xt);let H=rt();if(H.length>0)console.log(`Loaded ${H.length} middleware: ${H.join(", ")}`);let vt=s?.routeMiddleware?.global||[];jo(s?.layoutsDir,a(process.cwd()));let V=N(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${V.length} routes`);let _=[];for(let u of V){let m=await Ot(u);for(let v of m)_.push({route:u,url:v.url,params:v.params,props:v.props,revalidate:v.revalidate??e.revalidate})}l.totalPages=_.length,console.log(`Generating ${l.totalPages} pages...`);let A=[],X=[];for(let u=0;u<_.length;u+=e.concurrency)X.push(_.slice(u,u+e.concurrency));for(let u of X)await Promise.all(u.map(async(m)=>{let{route:v,url:d,params:L,props:Pt,revalidate:Q}=m;try{await e.hooks.onPageStart?.(d);let j=await Bun.file(v.filePath).text(),F=Jt(j),$t=F?.middleware?Array.isArray(F.middleware)?F.middleware:[F.middleware]:[],tt=[...vt,...$t];if(tt.length>0){let C=ot(d,L,F||{}),O=it(C,null,void 0,{isServer:!0}),E=await at(tt,O);if(E.redirect){let R=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,U=Vt(String(R),d),T=Kt(d,e);await x.promises.mkdir(g.dirname(T),{recursive:!0}),await Bun.write(T,U),l.successCount++,l.pages.push({route:d,outputPath:T,size:Buffer.byteLength(U),cached:!1}),A.push({loc:d,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${d} \u2192 redirect to ${R}`);return}if(E.abort){let R=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${d} \u2014 middleware aborted: ${R}`);return}}let et=j.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(et)try{if(!await Function("route",`
|
|
45
45
|
const validate = ${et[1]};
|
|
46
46
|
return validate(route);
|
|
47
47
|
`)({params:L})){console.warn(`Validation failed for ${d}, skipping...`);return}}catch{}let k=null,ct=!1;if(e.cache){if(k=B.get(d,v.filePath),k)ct=!0,l.cachedCount++}if(!k){let C=await St(v,L,Pt,e,s);if(k=C.html,e.failOnIncludeError&&C.includeFailures.length>0)throw Error(`${C.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
|
|
@@ -673,7 +673,11 @@ export function convertToCommonJS(scriptContent, filePath) {
|
|
|
673
673
|
return path.resolve(templateDir, source);
|
|
674
674
|
if (source.startsWith("~/") || source.startsWith("@/"))
|
|
675
675
|
return path.resolve(projectRoot, source.slice(2));
|
|
676
|
-
|
|
676
|
+
try {
|
|
677
|
+
return Bun.resolveSync(source, templateDir);
|
|
678
|
+
} catch {
|
|
679
|
+
return source;
|
|
680
|
+
}
|
|
677
681
|
};
|
|
678
682
|
if (defaultImportMatch) {
|
|
679
683
|
const [, name, source] = defaultImportMatch, resolved = resolveSource(source);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/stx",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.535",
|
|
5
5
|
"description": "A performant UI Framework. Powered by Bun.",
|
|
6
6
|
"author": "Chris Breuer <chris@stacksjs.org>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -123,12 +123,12 @@
|
|
|
123
123
|
"dependencies": {
|
|
124
124
|
"@stacksjs/ts-css": "^0.3.11",
|
|
125
125
|
"@stacksjs/clapp": "^0.2.16",
|
|
126
|
-
"@stacksjs/desktop": "0.2.
|
|
127
|
-
"@stacksjs/sanitizer": "0.2.
|
|
126
|
+
"@stacksjs/desktop": "0.2.535",
|
|
127
|
+
"@stacksjs/sanitizer": "0.2.535",
|
|
128
128
|
"@stacksjs/ts-i18n": "^0.1.11",
|
|
129
|
-
"bun-plugin-stx": "0.2.
|
|
129
|
+
"bun-plugin-stx": "0.2.535",
|
|
130
130
|
"bunfig": "^0.15.19",
|
|
131
|
-
"stx-router": "0.2.
|
|
131
|
+
"stx-router": "0.2.535",
|
|
132
132
|
"ts-broadcasting": "^0.0.11",
|
|
133
133
|
"ts-images": "^0.2.22",
|
|
134
134
|
"ts-syntax-highlighter": "^0.2.1"
|