@yuneta/gobj-ui 7.27.27 → 7.27.29

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.
@@ -0,0 +1,315 @@
1
+ /***********************************************************************
2
+ * c_yui_update_watch.wiring.test.js
3
+ *
4
+ * C_YUI_UPDATE_WATCH driven through its FSM on a document double,
5
+ * with the server played by a fake fetch: the bar appears for
6
+ * another build and not for the same one, the ✕ hides it for THAT
7
+ * build only, a rollback takes it away, a check too soon or
8
+ * offline asks nothing, a failure is said once, and the reload
9
+ * asks the host first.
10
+ *
11
+ * Copyright (c) 2026, ArtGins.
12
+ * All Rights Reserved.
13
+ ***********************************************************************/
14
+ import {describe, test, expect, beforeAll, beforeEach, afterEach} from "vitest";
15
+ import {install_dom_double, fake_event} from "../test/dom_double.js";
16
+
17
+ install_dom_double();
18
+
19
+ const {
20
+ gclass_create, SDATA_END,
21
+ gobj_start_up, gobj_create_yuno, gobj_create_service, gobj_start, gobj_stop,
22
+ gobj_destroy, gobj_is_running, gobj_send_event, gobj_current_state,
23
+ set_log_callback, register_c_timer,
24
+ } = await import("@yuneta/gobj-js");
25
+ const {register_c_yui_update_watch} = await import("./c_yui_update_watch.js");
26
+
27
+ const RUNNING = "aaaaaaaaaaaaaaaa";
28
+
29
+ const logged = [];
30
+ const heard = [];
31
+ let yuno = null;
32
+ let host = null;
33
+ let watch = null;
34
+ let seq = 0;
35
+
36
+ /* The server: what the next fetches answer, and what was asked. */
37
+ const server = {
38
+ stamp: RUNNING,
39
+ version: "1.0.0",
40
+ fail: null, /* null | "network" | number (HTTP status) | "no-stamp" */
41
+ asked: 0,
42
+ };
43
+
44
+ function page(stamp, version)
45
+ {
46
+ return `<!doctype html><html><head><title>x</title>` +
47
+ `<meta name="yuneta-build" content="${stamp}" data-version="${version}">` +
48
+ `</head><body></body></html>`;
49
+ }
50
+
51
+ function fake_fetch(url, opts)
52
+ {
53
+ server.asked++;
54
+ expect(opts.cache).toBe("no-store");
55
+ if(server.fail === "network") {
56
+ return Promise.reject(new TypeError("Failed to fetch"));
57
+ }
58
+ if(typeof server.fail === "number") {
59
+ return Promise.resolve({ok: false, status: server.fail, text: () => Promise.resolve("")});
60
+ }
61
+ const body = server.fail === "no-stamp"
62
+ ? "<html><head><title>Hotel wifi</title></head></html>"
63
+ : page(server.stamp, server.version);
64
+ return Promise.resolve({ok: true, status: 200, text: () => Promise.resolve(body)});
65
+ }
66
+
67
+ async function settle()
68
+ {
69
+ for(let i = 0; i < 5; i++) {
70
+ await new Promise((resolve) => setTimeout(resolve, 0));
71
+ }
72
+ }
73
+
74
+ function bar()
75
+ {
76
+ return document.body.querySelector(".UPDATE_BAR");
77
+ }
78
+
79
+ function make_watch(kw)
80
+ {
81
+ watch = gobj_create_service(`update_watch_${++seq}`, "C_YUI_UPDATE_WATCH",
82
+ {subscriber: host, period_ms: 0, ...(kw || {})}, yuno);
83
+ gobj_start(watch);
84
+ return watch;
85
+ }
86
+
87
+ beforeAll(async () => {
88
+ const i18next = (await import("i18next")).default;
89
+ await i18next.init({lng: "en", resources: {}});
90
+
91
+ const $meta = document.createElement("meta");
92
+ $meta.setAttribute("name", "yuneta-build");
93
+ $meta.setAttribute("content", RUNNING);
94
+ $meta.setAttribute("data-version", "1.0.0");
95
+ document.head.appendChild($meta);
96
+
97
+ globalThis.fetch = fake_fetch;
98
+
99
+ gobj_start_up(null, null, null, null, null, null, null);
100
+ set_log_callback((level, msg) => {
101
+ logged.push({level: String(level), msg: String(msg)});
102
+ });
103
+ register_c_timer();
104
+ register_c_yui_update_watch();
105
+ gclass_create("C_TEST_UPD_YUNO", [], [["ST_IDLE", []]], {}, 0, [SDATA_END()], {}, 0, 0, 0, 0);
106
+ gclass_create(
107
+ "C_TEST_UPD_HOST",
108
+ [["EV_NEW_BUILD", 0], ["EV_BUILD_CURRENT", 0]],
109
+ [["ST_IDLE", [
110
+ ["EV_NEW_BUILD", (gobj, event, kw) => {
111
+ heard.push({event, kw});
112
+ return 0;
113
+ }, null],
114
+ ["EV_BUILD_CURRENT", (gobj, event, kw) => {
115
+ heard.push({event, kw});
116
+ return 0;
117
+ }, null]
118
+ ]]],
119
+ {}, 0, [SDATA_END()], {}, 0, 0, 0, 0
120
+ );
121
+ yuno = gobj_create_yuno("update_watch_yuno", "C_TEST_UPD_YUNO", {});
122
+ gobj_start(yuno);
123
+ host = gobj_create_service("update_watch_host", "C_TEST_UPD_HOST", {}, yuno);
124
+ gobj_start(host);
125
+ });
126
+
127
+ beforeEach(() => {
128
+ logged.length = 0;
129
+ heard.length = 0;
130
+ server.stamp = RUNNING;
131
+ server.version = "1.0.0";
132
+ server.fail = null;
133
+ server.asked = 0;
134
+ });
135
+
136
+ afterEach(() => {
137
+ if(watch) {
138
+ if(gobj_is_running(watch)) {
139
+ gobj_stop(watch);
140
+ }
141
+ gobj_destroy(watch);
142
+ watch = null;
143
+ }
144
+ expect(bar()).toBe(null);
145
+ expect(logged.filter((l) => l.level === "error")).toEqual([]);
146
+ });
147
+
148
+ describe("C_YUI_UPDATE_WATCH", () => {
149
+ test("the same build deployed: asked at start, no bar", async () => {
150
+ make_watch();
151
+ await settle();
152
+ expect(server.asked).toBe(1);
153
+ expect(gobj_current_state(watch)).toBe("ST_CURRENT");
154
+ expect(bar()).toBe(null);
155
+ expect(heard).toEqual([]);
156
+ });
157
+
158
+ test("another build: the bar, its version, EV_NEW_BUILD", async () => {
159
+ server.stamp = "bbbbbbbbbbbbbbbb";
160
+ server.version = "1.0.1";
161
+ make_watch();
162
+ await settle();
163
+ expect(gobj_current_state(watch)).toBe("ST_STALE");
164
+ const $bar = bar();
165
+ expect($bar).not.toBe(null);
166
+ expect($bar.querySelector(".UPDATE_VERSION").textContent).toBe("1.0.1");
167
+ const $reload = $bar.querySelector(".UPDATE_RELOAD");
168
+ expect($reload.getAttribute("title")).toBe("reload");
169
+ expect($reload.getAttribute("aria-label")).toBe("reload");
170
+ expect($reload.getAttribute("data-i18n-aria-label")).toBe("reload");
171
+ const $x = $bar.querySelector(".UPDATE_DISMISS");
172
+ expect($x.getAttribute("aria-label")).toBe("close");
173
+ expect(heard).toEqual([{event: "EV_NEW_BUILD", kw: {
174
+ running: RUNNING, deployed: "bbbbbbbbbbbbbbbb", version: "1.0.1"
175
+ }}]);
176
+ });
177
+
178
+ test("the ✕ hides it for that build; a later build shows it again", async () => {
179
+ server.stamp = "bbbbbbbbbbbbbbbb";
180
+ make_watch();
181
+ await settle();
182
+ gobj_send_event(watch, "EV_DISMISS", {}, watch);
183
+ expect(bar()).toBe(null);
184
+
185
+ gobj_send_event(watch, "EV_CHECK_BUILD", {force: true}, watch);
186
+ await settle();
187
+ expect(bar()).toBe(null);
188
+
189
+ server.stamp = "cccccccccccccccc";
190
+ server.version = "1.0.2";
191
+ gobj_send_event(watch, "EV_CHECK_BUILD", {force: true}, watch);
192
+ await settle();
193
+ expect(bar().querySelector(".UPDATE_VERSION").textContent).toBe("1.0.2");
194
+ expect(heard.map((h) => h.kw.deployed)).toEqual(["bbbbbbbbbbbbbbbb", "cccccccccccccccc"]);
195
+ });
196
+
197
+ test("a rollback to the running build takes the bar away", async () => {
198
+ server.stamp = "bbbbbbbbbbbbbbbb";
199
+ make_watch();
200
+ await settle();
201
+ expect(bar()).not.toBe(null);
202
+
203
+ server.stamp = RUNNING;
204
+ gobj_send_event(watch, "EV_CHECK_BUILD", {force: true}, watch);
205
+ await settle();
206
+ expect(gobj_current_state(watch)).toBe("ST_CURRENT");
207
+ expect(bar()).toBe(null);
208
+ expect(heard[1]).toEqual({event: "EV_BUILD_CURRENT", kw: {running: RUNNING}});
209
+ });
210
+
211
+ test("the focus asks, but not twice within min_interval_ms", async () => {
212
+ make_watch({min_interval_ms: 60000});
213
+ await settle();
214
+ expect(server.asked).toBe(1);
215
+ window.dispatchEvent(fake_event("focus"));
216
+ document.dispatchEvent(fake_event("visibilitychange"));
217
+ await settle();
218
+ expect(server.asked).toBe(1);
219
+
220
+ window.dispatchEvent(fake_event("vite:preloadError"));
221
+ await settle();
222
+ expect(server.asked).toBe(2);
223
+ });
224
+
225
+ test("with min_interval_ms 0, the focus asks", async () => {
226
+ make_watch({min_interval_ms: 0});
227
+ await settle();
228
+ window.dispatchEvent(fake_event("focus"));
229
+ await settle();
230
+ expect(server.asked).toBe(2);
231
+ });
232
+
233
+ test("period_ms asks on its own, for a screen that never gets the focus", async () => {
234
+ make_watch({min_interval_ms: 0, period_ms: 20});
235
+ await settle();
236
+ expect(server.asked).toBe(1);
237
+ await new Promise((resolve) => setTimeout(resolve, 70));
238
+ await settle();
239
+ expect(server.asked).toBeGreaterThanOrEqual(3);
240
+ });
241
+
242
+ test("stopped, the page events ask nothing", async () => {
243
+ make_watch({min_interval_ms: 0});
244
+ await settle();
245
+ gobj_stop(watch);
246
+ window.dispatchEvent(fake_event("focus"));
247
+ window.dispatchEvent(fake_event("online"));
248
+ await settle();
249
+ expect(server.asked).toBe(1);
250
+ });
251
+
252
+ test("a failure is said once, and its end once", async () => {
253
+ server.fail = 503;
254
+ make_watch();
255
+ await settle();
256
+ gobj_send_event(watch, "EV_CHECK_BUILD", {force: true}, watch);
257
+ await settle();
258
+ const warnings = logged.filter((l) => l.level === "warning");
259
+ expect(warnings.length).toBe(1);
260
+ expect(warnings[0].msg).toContain("HTTP 503");
261
+
262
+ server.fail = null;
263
+ gobj_send_event(watch, "EV_CHECK_BUILD", {force: true}, watch);
264
+ await settle();
265
+ expect(logged.filter((l) => l.msg.includes("can be read again")).length).toBe(1);
266
+ });
267
+
268
+ test("a network failure is info, a page with no stamp a warning, neither a new build", async () => {
269
+ server.fail = "network";
270
+ make_watch();
271
+ await settle();
272
+ expect(logged.filter((l) => l.level === "warning")).toEqual([]);
273
+ expect(logged.some((l) => l.level === "info" && l.msg.includes("Failed to fetch"))).toBe(true);
274
+ gobj_stop(watch);
275
+ gobj_destroy(watch);
276
+
277
+ logged.length = 0;
278
+ server.fail = "no-stamp";
279
+ make_watch();
280
+ await settle();
281
+ expect(gobj_current_state(watch)).toBe("ST_CURRENT");
282
+ expect(bar()).toBe(null);
283
+ expect(logged.filter((l) => l.level === "warning").length).toBe(1);
284
+ });
285
+
286
+ test("the reload asks the host first, and a veto keeps the page", async () => {
287
+ let reloads = 0;
288
+ window.location.reload = () => {
289
+ reloads++;
290
+ };
291
+ let answer = false;
292
+ server.stamp = "bbbbbbbbbbbbbbbb";
293
+ make_watch({before_reload: () => Promise.resolve(answer)});
294
+ await settle();
295
+
296
+ gobj_send_event(watch, "EV_RELOAD", {}, watch);
297
+ await settle();
298
+ expect(reloads).toBe(0);
299
+
300
+ answer = true;
301
+ bar().querySelector(".UPDATE_RELOAD").dispatchEvent(fake_event("click"));
302
+ await settle();
303
+ expect(reloads).toBe(1);
304
+ });
305
+
306
+ test("in ST_CURRENT a reload is not an event of the state", async () => {
307
+ make_watch();
308
+ await settle();
309
+ const ret = gobj_send_event(watch, "EV_RELOAD", {}, watch);
310
+ expect(ret).toBe(-1);
311
+ const errors = logged.filter((l) => l.level === "error");
312
+ expect(errors.length).toBeGreaterThan(0);
313
+ logged.length = 0;
314
+ });
315
+ });
@@ -169,6 +169,12 @@ describe("C_YUI_GCLASS: the gclass' trace levels, set from the viewer", () => {
169
169
  expect(problems()).toEqual([]);
170
170
  });
171
171
 
172
+ test("the zone says the gclass' traces survive a restart", () => {
173
+ const view = open({traces: {info: INFO, pending: false}});
174
+ expect(gobj_read_attr(view, "$container").querySelector(".GCLASS_TRACES_NOTE").getAttribute("data-i18n"))
175
+ .toBe("the traces of a gclass survive a restart");
176
+ });
177
+
172
178
  test("remove the traces of the gclass turns off its own, not the yuno's", () => {
173
179
  const view = open({traces: {info: INFO, pending: false}});
174
180
  gobj_read_attr(view, "$container").querySelector(".GCLASS_TRACES_CLEAR").click();
@@ -253,6 +253,20 @@ describe("C_YUI_GOBJ_TREE_JS, source remote", () => {
253
253
  expect(problems()).toEqual([]);
254
254
  });
255
255
 
256
+ test("a card says whether its gobj's traces survive a restart: a service's do", async () => {
257
+ const view = await mount("remote", host);
258
+ await open_tcp_card(view);
259
+ gobj_send_event(view, "EV_TRACE_INFO", TCP_INFO, host);
260
+ const note = () => view.priv.$popover.querySelector(".GOBJ_TREE_TRACES_NOTE").getAttribute("data-i18n");
261
+ expect(note()).toBe("the traces of a gobj that is not a service end with the yuno");
262
+
263
+ const tree = JSON.parse(JSON.stringify(TREE));
264
+ tree["C_YUNO^gate"].children["C_TCP^tcp1"].service = true;
265
+ gobj_send_event(view, "EV_LOAD_TREE", {tree: tree}, host);
266
+ expect(note()).toBe("the traces of a service survive a restart");
267
+ expect(problems()).toEqual([]);
268
+ });
269
+
256
270
  test("a level the whole yuno traces is locked in a card, said as the yuno's", async () => {
257
271
  const view = await mount("remote", host);
258
272
  await open_tcp_card(view);
@@ -104,6 +104,14 @@ export function yui_shell_popup_layer(shell)
104
104
  return (priv && priv.layers && priv.layers.popup) || null;
105
105
  }
106
106
 
107
+ /* Public: the toasts' layer (z 120), above the dialogs, for a notice
108
+ * that is not a toast and stays until it is answered (the bar of
109
+ * C_YUI_UPDATE_WATCH). Null when there is no shell. */
110
+ export function yui_shell_notification_layer(shell)
111
+ {
112
+ return notification_layer(shell) || null;
113
+ }
114
+
107
115
 
108
116
  /***************************************************************
109
117
  * i18n bridge:
@@ -4,7 +4,8 @@
4
4
  * The html transform of vite-plugin-yuneta-html.js: the policy is
5
5
  * ALWAYS emitted (connect-src 'self' alone without csp_connect_src,
6
6
  * and without a config.json at all), and the text of config.json is
7
- * escaped where it lands in markup.
7
+ * escaped where it lands in markup. And the build stamp written
8
+ * into the emitted index.html: the same bundle, the same stamp.
8
9
  *
9
10
  * Copyright (c) 2026, ArtGins.
10
11
  * All Rights Reserved.
@@ -14,6 +15,7 @@ import fs from "fs";
14
15
  import os from "os";
15
16
  import path from "path";
16
17
  import {yunetaHtmlPlugin} from "../vite-plugin-yuneta-html.js";
18
+ import {parse_build} from "./yui_build_stamp.js";
17
19
 
18
20
  const HTML = "<head><title></title>\n<!-- METADATA_PLACEHOLDER -->\n<!-- CSP_PLACEHOLDER --></head>";
19
21
 
@@ -92,3 +94,34 @@ describe("vite-plugin-yuneta-html", () => {
92
94
  expect(html).not.toContain('wss://a"onload');
93
95
  });
94
96
  });
97
+
98
+ function stamped(names)
99
+ {
100
+ const bundle = {"index.html": {source: "<html><head><title>x</title></head><body></body></html>"}};
101
+ for(const name of names) {
102
+ bundle[name] = {source: ""};
103
+ }
104
+ yunetaHtmlPlugin({}).generateBundle.handler({}, bundle);
105
+ return parse_build(String(bundle["index.html"].source));
106
+ }
107
+
108
+ describe("vite-plugin-yuneta-html: the build stamp", () => {
109
+ test("the emitted page carries the stamp and the app's version", () => {
110
+ const build = stamped(["assets/index-AAAA.js", "assets/index-BBBB.css"]);
111
+ expect(build.stamp).toMatch(/^[0-9a-f]{16}$/);
112
+ const pkg = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), "package.json"), "utf-8"));
113
+ expect(build.version).toBe(pkg.version);
114
+ });
115
+
116
+ test("the same files give the same stamp, in any order; the maps do not count", () => {
117
+ const a = stamped(["assets/a-1.js", "assets/b-2.css"]);
118
+ const b = stamped(["assets/b-2.css", "assets/a-1.js", "assets/a-1.js.map"]);
119
+ expect(b.stamp).toBe(a.stamp);
120
+ });
121
+
122
+ test("one changed chunk gives another stamp", () => {
123
+ const a = stamped(["assets/a-1.js", "assets/lazy-1.js"]);
124
+ const b = stamped(["assets/a-1.js", "assets/lazy-2.js"]);
125
+ expect(b.stamp).not.toBe(a.stamp);
126
+ });
127
+ });
@@ -0,0 +1,125 @@
1
+ /***********************************************************************
2
+ * yui_build_stamp.js
3
+ *
4
+ * Which build is this page, and which build does the server
5
+ * hand out now.
6
+ *
7
+ * The build writes its own identity into index.html as
8
+ *
9
+ * <meta name="yuneta-build" content="<stamp>" data-version="<version>">
10
+ *
11
+ * (vite-plugin-yuneta-html.js, at build time only). The stamp is
12
+ * a hash of the NAMES of every file of the bundle, and those
13
+ * names carry the hash of their content: the same code built
14
+ * twice gives the same stamp, and any change of a chunk, of a
15
+ * lazy chunk or of a stylesheet gives another. A build date
16
+ * would announce a "new version" after every rebuild of
17
+ * unchanged code, and the deploy round rebuilds every app after
18
+ * each publication of this library.
19
+ *
20
+ * The page that runs reads its stamp from its own DOM, where the
21
+ * meta is never touched again; the deployed one is read from the
22
+ * text of the same document fetched again. Pure functions: the
23
+ * gclass that compares them is C_YUI_UPDATE_WATCH.
24
+ *
25
+ * Copyright (c) 2026, ArtGins.
26
+ * All Rights Reserved.
27
+ ***********************************************************************/
28
+
29
+ const BUILD_META_NAME = "yuneta-build";
30
+
31
+ /************************************************************
32
+ * The build of the page that runs: {stamp, version}, or
33
+ * null when its document carries no stamp (`vite dev`, or
34
+ * an app built without the plugin).
35
+ ************************************************************/
36
+ function running_build(doc)
37
+ {
38
+ if(!doc || typeof doc.querySelector !== "function") {
39
+ return null;
40
+ }
41
+ let $meta = doc.querySelector(`meta[name="${BUILD_META_NAME}"]`);
42
+ if(!$meta) {
43
+ return null;
44
+ }
45
+ let stamp = $meta.getAttribute("content") || "";
46
+ if(!stamp) {
47
+ return null;
48
+ }
49
+ return {
50
+ stamp: stamp,
51
+ version: $meta.getAttribute("data-version") || ""
52
+ };
53
+ }
54
+
55
+ /************************************************************
56
+ * The build named by the text of an index.html: {stamp,
57
+ * version}, or null when the text carries no stamp -- an
58
+ * error page, a captive portal, or a build older than the
59
+ * stamp. Null is NOT "another build": a hotel wifi that
60
+ * answers 200 with its own login page must not tell the
61
+ * reader to reload into it.
62
+ ************************************************************/
63
+ function parse_build(html)
64
+ {
65
+ if(typeof html !== "string" || !html) {
66
+ return null;
67
+ }
68
+ let metas = html.match(/<meta\b[^>]*>/gi) || [];
69
+ for(let tag of metas) {
70
+ if(read_html_attr(tag, "name") !== BUILD_META_NAME) {
71
+ continue;
72
+ }
73
+ let stamp = read_html_attr(tag, "content");
74
+ if(!stamp) {
75
+ return null;
76
+ }
77
+ return {
78
+ stamp: stamp,
79
+ version: read_html_attr(tag, "data-version")
80
+ };
81
+ }
82
+ return null;
83
+ }
84
+
85
+ /************************************************************
86
+ * The value of one attribute of one tag's text, quoted
87
+ * with " or ' (the plugin writes ", a minifier may not).
88
+ * The entities the plugin escapes are read back.
89
+ ************************************************************/
90
+ function read_html_attr(tag, name)
91
+ {
92
+ let re = new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i");
93
+ let m = tag.match(re);
94
+ if(!m) {
95
+ return "";
96
+ }
97
+ let value = (m[2] !== undefined) ? m[2] : m[3];
98
+ return value
99
+ .replace(/&quot;/g, "\"")
100
+ .replace(/&lt;/g, "<")
101
+ .replace(/&gt;/g, ">")
102
+ .replace(/&amp;/g, "&");
103
+ }
104
+
105
+ /************************************************************
106
+ * The url to ask for the deployed document: the page's own,
107
+ * without its hash. Every route of these apps is a hash, so
108
+ * this is the deploy root, whatever path the app is served
109
+ * under.
110
+ ************************************************************/
111
+ function build_page_url(loc)
112
+ {
113
+ if(!loc) {
114
+ return "";
115
+ }
116
+ return `${loc.origin || ""}${loc.pathname || "/"}${loc.search || ""}`;
117
+ }
118
+
119
+
120
+ export {
121
+ BUILD_META_NAME,
122
+ running_build,
123
+ parse_build,
124
+ build_page_url,
125
+ };
@@ -0,0 +1,56 @@
1
+ /***********************************************************************
2
+ * yui_build_stamp.test.js
3
+ *
4
+ * The build stamp read back: from the DOM of the page that runs,
5
+ * from the text of the page the server hands out, and NOT from a
6
+ * page that carries none (an error page, a captive portal).
7
+ *
8
+ * Copyright (c) 2026, ArtGins.
9
+ * All Rights Reserved.
10
+ ***********************************************************************/
11
+ import {describe, test, expect} from "vitest";
12
+ import {running_build, parse_build, build_page_url} from "./yui_build_stamp.js";
13
+
14
+ describe("yui_build_stamp", () => {
15
+ test("parse_build reads the stamp and the version", () => {
16
+ const html = '<head><meta charset="utf-8">\n' +
17
+ '<meta name="yuneta-build" content="0123456789abcdef" data-version="2.0.41">\n</head>';
18
+ expect(parse_build(html)).toEqual({stamp: "0123456789abcdef", version: "2.0.41"});
19
+ });
20
+
21
+ test("parse_build takes single quotes and any attribute order", () => {
22
+ const html = "<meta data-version='1.0.0' content='abc' name='yuneta-build'>";
23
+ expect(parse_build(html)).toEqual({stamp: "abc", version: "1.0.0"});
24
+ });
25
+
26
+ test("a page with no stamp is no build, not another build", () => {
27
+ expect(parse_build("<html><head><title>Hotel wifi</title></head></html>")).toBe(null);
28
+ expect(parse_build('<meta name="yuneta-build" content="">')).toBe(null);
29
+ expect(parse_build("")).toBe(null);
30
+ expect(parse_build(null)).toBe(null);
31
+ });
32
+
33
+ test("another meta is not mistaken for the stamp", () => {
34
+ const html = '<meta name="description" content="x"><meta name="yuneta-build" content="s1" data-version="v">';
35
+ expect(parse_build(html)).toEqual({stamp: "s1", version: "v"});
36
+ });
37
+
38
+ test("running_build reads the meta of a document", () => {
39
+ const attrs = {content: "s2", "data-version": "3.1.4"};
40
+ const doc = {
41
+ querySelector: (sel) => sel === 'meta[name="yuneta-build"]'
42
+ ? {getAttribute: (k) => attrs[k] || null}
43
+ : null
44
+ };
45
+ expect(running_build(doc)).toEqual({stamp: "s2", version: "3.1.4"});
46
+ expect(running_build({querySelector: () => null})).toBe(null);
47
+ expect(running_build(null)).toBe(null);
48
+ });
49
+
50
+ test("build_page_url is the page without its hash", () => {
51
+ expect(build_page_url({origin: "https://a.b", pathname: "/", search: "", hash: "#/x/y"}))
52
+ .toBe("https://a.b/");
53
+ expect(build_page_url({origin: "https://a.b", pathname: "/sub/", search: "?q=1"}))
54
+ .toBe("https://a.b/sub/?q=1");
55
+ });
56
+ });
@@ -9,9 +9,21 @@
9
9
  * (always emitted: connect-src 'self' alone when the
10
10
  * list is missing, with a warning; an entry that is
11
11
  * not one CSP source -- a `;`, `,` or space -- is refused)
12
+ * - at build time only, the build stamp read by
13
+ * C_YUI_UPDATE_WATCH (src/yui_build_stamp.js):
14
+ * <meta name="yuneta-build" content="<stamp>" data-version="<version>">
15
+ * <stamp> is a hash of the names of every file of the
16
+ * bundle -- names that carry the hash of their content --
17
+ * so the same code built twice has the same stamp;
18
+ * <version> is the app's package.json version
12
19
  *
13
- * Usage in vite.config.js (vendored copy):
14
- * import { yunetaHtmlPlugin } from "./src/gobj-ui/vite-plugin-yuneta-html.js";
20
+ * The title, the metadata and the policy are written before
21
+ * Vite's own transforms ("pre"); the stamp needs the finished
22
+ * bundle, so it is written into the emitted index.html in
23
+ * generateBundle, after every other plugin ("post").
24
+ *
25
+ * Usage in vite.config.js:
26
+ * import { yunetaHtmlPlugin } from "@yuneta/gobj-ui/vite-plugin-yuneta-html.js";
15
27
  * plugins: [ yunetaHtmlPlugin({ defaultTitle: "My App" }) ]
16
28
  *
17
29
  * Copyright (c) 2025-2026, ArtGins.
@@ -19,6 +31,7 @@
19
31
  ***********************************************************************/
20
32
  import fs from "fs";
21
33
  import path from "path";
34
+ import {createHash} from "crypto";
22
35
 
23
36
  /* config.json is build input, but its text lands inside markup. */
24
37
  function escape_html(value) {
@@ -157,6 +170,51 @@ export function yunetaHtmlPlugin(options = {}) {
157
170
  .replace("<!-- METADATA_PLACEHOLDER -->", metadataHtml)
158
171
  .replace("<!-- CSP_PLACEHOLDER -->", cspHtml);
159
172
  }
173
+ },
174
+
175
+ /*------------------------------------------*
176
+ * Build stamp (see the header)
177
+ *
178
+ * The names of the bundle's files are known
179
+ * only once it is complete. A source map is
180
+ * left out: with `sourcemap: "hidden"` its
181
+ * name only repeats its chunk's.
182
+ *------------------------------------------*/
183
+ generateBundle: {
184
+ order: "post",
185
+ handler(output_options, bundle) {
186
+ const names = Object.keys(bundle)
187
+ .filter(name => !name.endsWith(".map") && !name.endsWith(".html"))
188
+ .sort();
189
+ const pages = Object.keys(bundle).filter(name => name.endsWith(".html"));
190
+ if (names.length === 0 || pages.length === 0) {
191
+ console.error("❌ yuneta-build-stamp: no bundle or no page, no build stamp written");
192
+ return;
193
+ }
194
+ const stamp = createHash("sha256")
195
+ .update(names.join("\n"))
196
+ .digest("hex")
197
+ .slice(0, 16);
198
+
199
+ let version = "";
200
+ const pkgPath = path.resolve(process.cwd(), "package.json");
201
+ if (fs.existsSync(pkgPath)) {
202
+ version = JSON.parse(fs.readFileSync(pkgPath, "utf-8")).version || "";
203
+ }
204
+ const meta = `<meta name="yuneta-build" content="${stamp}" ` +
205
+ `data-version="${escape_html(version)}">`;
206
+
207
+ for (const name of pages) {
208
+ const page = bundle[name];
209
+ const html = String(page.source);
210
+ if (!html.includes("</head>")) {
211
+ console.error(`❌ yuneta-build-stamp: ${name} has no </head>, no build stamp written`);
212
+ continue;
213
+ }
214
+ page.source = html.replace("</head>", ` ${meta}\n </head>`);
215
+ }
216
+ }
160
217
  }
161
218
  };
162
219
  }
220
+