@jskit-ai/shell-web 0.2.0 → 0.2.2

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/locales/en.json CHANGED
@@ -34,12 +34,14 @@
34
34
  "appLabel": "App",
35
35
  "appModuleLabel": "App module",
36
36
  "appUnreachable": "The app could not reach the server or network. Check the connection and try again.",
37
+ "appUpdated": "{app} was updated. Reload to get the latest version.",
37
38
  "errorConfigLabel": "Error config",
38
39
  "moduleFailed": "A required app module could not load.",
39
40
  "placementConfigLabel": "Placement config",
40
41
  "placementTopologyLabel": "Placement topology",
41
42
  "refreshFailed": "Unable to refresh. Check the connection and try again.",
42
43
  "reloadFailed": "The app cannot reload because the app server is not reachable. Restart the server, then click Reload.",
44
+ "thisAppUpdated": "This app was updated. Reload to get the latest version.",
43
45
  "unreachable": "{label} could not reach the server or network. Check the connection and try again."
44
46
  }
45
47
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/shell-web",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -37,7 +37,7 @@
37
37
  "@vue/compiler-sfc": "3.5.44"
38
38
  },
39
39
  "peerDependencies": {
40
- "@jskit-ai/kernel": "0.2.0",
40
+ "@jskit-ai/kernel": "0.2.2",
41
41
  "pinia": "^4.0.3",
42
42
  "vue": "^3.5.44",
43
43
  "vue-router": "^5.3.1",
@@ -0,0 +1,86 @@
1
+ import { pageClientBuildId } from "@jskit-ai/kernel/shared/support/clientBuild";
2
+ import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
+ import { useJskitText } from "../i18n.js";
4
+
5
+ const { t } = useJskitText();
6
+
7
+ // The title the page loaded with (index.html's <title>) names the app; screens
8
+ // may change the tab title later.
9
+ function loadedAppName(documentObject = globalThis.document) {
10
+ return normalizeText(documentObject?.title);
11
+ }
12
+
13
+ // Offers a reload when the server serves a different client build from the one
14
+ // this page runs, as it does after an update. It never reloads by itself: the
15
+ // person may be in the middle of something. Reload returns to the same address.
16
+ function createShellClientUpdateRuntime({
17
+ errorRuntime,
18
+ reload,
19
+ pageBuildId = pageClientBuildId(),
20
+ appName = loadedAppName()
21
+ } = {}) {
22
+ let offer = null;
23
+ let stopWatching = null;
24
+
25
+ function withdraw() {
26
+ if (offer?.presentationId) {
27
+ errorRuntime.dismiss(offer.presentationId);
28
+ }
29
+ offer = null;
30
+ }
31
+
32
+ function offerReload(servedBuildId) {
33
+ const [messageKey, messageParams] = appName
34
+ ? ["jskit.shell.recovery.appUpdated", { app: appName }]
35
+ : ["jskit.shell.recovery.thisAppUpdated", {}];
36
+ const result = errorRuntime.report({
37
+ source: "shell-web.client-update",
38
+ message: t(messageKey, messageParams),
39
+ // The error host renders the sentence in the user's language from its code.
40
+ messageCode: messageKey.slice("jskit.".length),
41
+ messageParams,
42
+ intent: "app-recoverable",
43
+ severity: "info",
44
+ action: {
45
+ label: t("jskit.shell.actions.reload"),
46
+ handler() {
47
+ return reload();
48
+ }
49
+ }
50
+ });
51
+ offer = { buildId: servedBuildId, presentationId: normalizeText(result?.presentationId) };
52
+ }
53
+
54
+ // One offer per served build: a reconnection to the same build does not
55
+ // repeat it, even after the person closed it.
56
+ function check(servedBuildId = "") {
57
+ const served = normalizeText(servedBuildId);
58
+ if (!pageBuildId || !served || served === offer?.buildId) {
59
+ return;
60
+ }
61
+ withdraw();
62
+ if (served !== pageBuildId) {
63
+ offerReload(served);
64
+ }
65
+ }
66
+
67
+ // realtime is the optional client.realtime capability, which names the
68
+ // server's build on every connection.
69
+ function watch(realtime = null) {
70
+ dispose();
71
+ stopWatching = realtime ? realtime.onServedClientBuild(check) : null;
72
+ }
73
+
74
+ function dispose() {
75
+ stopWatching?.();
76
+ stopWatching = null;
77
+ }
78
+
79
+ return Object.freeze({
80
+ check,
81
+ dispose,
82
+ watch
83
+ });
84
+ }
85
+
86
+ export { createShellClientUpdateRuntime };
@@ -9,6 +9,7 @@ import {
9
9
  SHELL_ASYNC_MODULE_RECOVERY_RUNTIME_KEY
10
10
  } from "../asyncModuleRecovery/inject.js";
11
11
  import { createShellAsyncModuleRecoveryRuntime } from "../asyncModuleRecovery/runtime.js";
12
+ import { createShellClientUpdateRuntime } from "../clientUpdate/runtime.js";
12
13
  import {
13
14
  SHELL_REQUEST_RECOVERY_RUNTIME_KEY
14
15
  } from "../requestRecovery/inject.js";
@@ -259,6 +260,9 @@ const ShellWebClientProvider = defineProvider({
259
260
  surfaceRuntime: "client.surface",
260
261
  vueApp: "client.vue"
261
262
  },
263
+ optional: {
264
+ realtime: "client.realtime"
265
+ },
262
266
  provides: {
263
267
  shell: "client.shell"
264
268
  },
@@ -305,6 +309,10 @@ const ShellWebClientProvider = defineProvider({
305
309
  errorRuntime,
306
310
  logger
307
311
  });
312
+ const clientUpdateRuntime = createShellClientUpdateRuntime({
313
+ errorRuntime,
314
+ reload: () => asyncModuleRecoveryRuntime.reload()
315
+ });
308
316
  const bootstrapRuntime = createShellBootstrapRuntime({
309
317
  handlers: bootstrapHandlers,
310
318
  placementRuntime,
@@ -324,6 +332,7 @@ const ShellWebClientProvider = defineProvider({
324
332
  asyncModuleRecovery: asyncModuleRecoveryRuntime,
325
333
  bootstrap: bootstrapRuntime,
326
334
  bootstrapHandlers,
335
+ clientUpdate: clientUpdateRuntime,
327
336
  error: errorRuntime,
328
337
  errorPresentationStore,
329
338
  placement: placementRuntime,
@@ -332,11 +341,12 @@ const ShellWebClientProvider = defineProvider({
332
341
  })
333
342
  };
334
343
  },
335
- async boot({ loggerInput, pinia, router, surfaceRuntime, vueApp }, { outputs }) {
344
+ async boot({ loggerInput, pinia, realtime, router, surfaceRuntime, vueApp }, { outputs }) {
336
345
  const logger = createSharedProviderLogger(loggerInput);
337
346
  const {
338
347
  asyncModuleRecovery: asyncModuleRecoveryRuntime,
339
348
  bootstrap: bootstrapRuntime,
349
+ clientUpdate: clientUpdateRuntime,
340
350
  error: errorRuntime,
341
351
  errorPresentationStore,
342
352
  placement: placementRuntime,
@@ -370,6 +380,8 @@ const ShellWebClientProvider = defineProvider({
370
380
  const errorConfig = await loadAppErrorConfig(logger, errorRuntime, asyncModuleRecoveryRuntime);
371
381
  errorRuntime.configure(errorConfig);
372
382
  requestRecoveryRuntime.install();
383
+ // After the app's error configuration, so the offer follows its policy.
384
+ clientUpdateRuntime.watch(realtime);
373
385
 
374
386
  await bootstrapRuntime.initialize();
375
387
 
@@ -391,6 +403,7 @@ const ShellWebClientProvider = defineProvider({
391
403
  installRouterErrorBridge(router, errorRuntime, logger);
392
404
  },
393
405
  shutdown(_dependencies, { outputs }) {
406
+ outputs.shell.clientUpdate.dispose();
394
407
  outputs.shell.requestRecovery.dispose();
395
408
  outputs.shell.asyncModuleRecovery.dispose();
396
409
  }
@@ -0,0 +1,241 @@
1
+ import assert from "node:assert/strict";
2
+ import { once } from "node:events";
3
+ import { createServer } from "node:http";
4
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import test from "node:test";
8
+ import { createPinia } from "pinia";
9
+ import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
10
+ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
11
+ import { createSurfaceRuntime } from "@jskit-ai/kernel/shared/surface/runtime";
12
+ import { createClientComponentRegistry } from "../../kernel/client/componentRegistry.js";
13
+ import { RealtimeClientProvider } from "../../realtime/src/client/RealtimeClientProvider.js";
14
+ import { RealtimeProvider } from "../../realtime/src/server/RealtimeProvider.js";
15
+ import { ShellWebClientProvider } from "../src/client/providers/ShellWebClientProvider.js";
16
+
17
+ const CLIENT_APP_CONFIG_GLOBAL_KEY = "__JSKIT_CLIENT_APP_CONFIG__";
18
+ const PAGE_BUILD = "aaaaaaaaaaaaaaaa";
19
+ const NEW_BUILD = "bbbbbbbbbbbbbbbb";
20
+ const NEWER_BUILD = "cccccccccccccccc";
21
+ const logger = Object.freeze({ debug() {}, info() {}, warn() {}, error() {} });
22
+
23
+ const originalGlobals = new WeakMap();
24
+
25
+ // Each global is restored to its value from before the test, however often the test sets it.
26
+ function setGlobal(t, name, value) {
27
+ if (!originalGlobals.has(t)) {
28
+ const originals = new Map();
29
+ originalGlobals.set(t, originals);
30
+ t.after(() => {
31
+ for (const [key, original] of originals) {
32
+ if (original.had) globalThis[key] = original.value;
33
+ else delete globalThis[key];
34
+ }
35
+ });
36
+ }
37
+ const originals = originalGlobals.get(t);
38
+ if (!originals.has(name)) {
39
+ originals.set(name, { had: Object.hasOwn(globalThis, name), value: globalThis[name] });
40
+ }
41
+ globalThis[name] = value;
42
+ }
43
+
44
+ // The page as it loaded: its <title> and, when built, its build id.
45
+ function loadPage(t, { buildId = PAGE_BUILD, title = "Vibe Test" } = {}) {
46
+ setGlobal(t, "document", Object.assign(new EventTarget(), {
47
+ hidden: false,
48
+ title,
49
+ querySelector: (selector) => (selector === 'meta[name="jskit-client-build"]' && buildId
50
+ ? { getAttribute: (name) => (name === "content" ? buildId : null) }
51
+ : null)
52
+ }));
53
+ }
54
+
55
+ // The shape of client.realtime's served-build subscription, driven by the test.
56
+ function createRealtimeStandIn() {
57
+ const listeners = new Set();
58
+ let latest = "";
59
+ return {
60
+ connect(buildId) {
61
+ latest = buildId;
62
+ for (const listener of [...listeners]) listener(buildId);
63
+ },
64
+ listenerCount: () => listeners.size,
65
+ capability: {
66
+ onServedClientBuild(listener) {
67
+ listeners.add(listener);
68
+ if (latest) listener(latest);
69
+ return () => listeners.delete(listener);
70
+ }
71
+ }
72
+ };
73
+ }
74
+
75
+ // Starts the client with the shell (and any other providers), and returns the
76
+ // capabilities the probe names once they are set up.
77
+ async function startClient(t, { inputs = {}, providers = [], probe = { shell: "client.shell" } } = {}) {
78
+ setGlobal(t, "fetch", async () => ({ ok: true, status: 200, json: async () => ({}) }));
79
+ const captured = {};
80
+ const Probe = defineProvider({
81
+ id: "test.client-update.probe",
82
+ requires: probe,
83
+ setup(dependencies) {
84
+ Object.assign(captured, dependencies);
85
+ }
86
+ });
87
+ const runtime = createCapabilityRuntime({
88
+ profile: "test",
89
+ providers: [ShellWebClientProvider, ...providers, Probe],
90
+ inputs: {
91
+ "client.components": createClientComponentRegistry(),
92
+ "client.env": {},
93
+ "client.logger": logger,
94
+ "client.pinia": createPinia(),
95
+ "client.query": null,
96
+ "client.router": { currentRoute: { value: { path: "/" } }, onError: () => () => {} },
97
+ "client.surface": createSurfaceRuntime({
98
+ allMode: "all",
99
+ surfaces: { app: { id: "app", pagesRoot: "app", enabled: true } },
100
+ defaultSurfaceId: "app"
101
+ }),
102
+ "client.vue": { config: {}, provide() {}, use() { return this; } },
103
+ ...inputs
104
+ }
105
+ });
106
+ await runtime.start();
107
+ t.after(() => (runtime.diagnostics().lifecycleState === "started" ? runtime.shutdown() : null));
108
+ return { runtime, ...captured };
109
+ }
110
+
111
+ async function waitFor(predicate, label) {
112
+ const deadline = Date.now() + 8_000;
113
+ while (!predicate()) {
114
+ if (Date.now() > deadline) throw new Error(`Timed out waiting until ${label}.`);
115
+ await new Promise((resolve) => setTimeout(resolve, 20));
116
+ }
117
+ }
118
+
119
+ function banners(shell) {
120
+ return shell.errorPresentationStore.getState().channels.banner;
121
+ }
122
+
123
+ test("a page running an older build offers a reload once; the served build itself shows nothing", async (t) => {
124
+ loadPage(t);
125
+ const realtime = createRealtimeStandIn();
126
+ const { shell } = await startClient(t, { inputs: { "client.realtime": realtime.capability } });
127
+
128
+ realtime.connect(PAGE_BUILD);
129
+ assert.deepEqual(banners(shell), [], "the page already runs the build its server serves");
130
+
131
+ realtime.connect(NEW_BUILD);
132
+ assert.equal(banners(shell).length, 1);
133
+ const [offer] = banners(shell);
134
+ assert.equal(offer.message, "Vibe Test was updated. Reload to get the latest version.");
135
+ assert.equal(offer.messageCode, "shell.recovery.appUpdated");
136
+ assert.equal(offer.severity, "info");
137
+ assert.equal(offer.action.label, "Reload");
138
+
139
+ realtime.connect(NEW_BUILD);
140
+ assert.equal(banners(shell).length, 1, "a reconnection to the same build does not repeat the offer");
141
+
142
+ // Reload returns to the same address, and only when the person chooses it.
143
+ const reloads = [];
144
+ const checks = [];
145
+ setGlobal(t, "window", Object.assign(new EventTarget(), {
146
+ location: { href: "http://app.test/app/project?tab=chat", reload: () => reloads.push("reload") }
147
+ }));
148
+ setGlobal(t, "fetch", async (url, options) => {
149
+ checks.push({ url, cache: options.cache });
150
+ return { ok: true, status: 200 };
151
+ });
152
+ assert.deepEqual(reloads, [], "the page never reloads by itself");
153
+ assert.equal(await offer.action.handler(), true);
154
+ assert.deepEqual(checks, [{ url: "http://app.test/app/project?tab=chat", cache: "no-store" }]);
155
+ assert.deepEqual(reloads, ["reload"]);
156
+ });
157
+
158
+ test("a closed offer stays closed for its build, a newer build offers again, and the served page build withdraws it", async (t) => {
159
+ loadPage(t, { title: "" });
160
+ const realtime = createRealtimeStandIn();
161
+ const { shell } = await startClient(t, { inputs: { "client.realtime": realtime.capability } });
162
+
163
+ realtime.connect(NEW_BUILD);
164
+ assert.equal(banners(shell)[0].message, "This app was updated. Reload to get the latest version.");
165
+ shell.error.dismiss(banners(shell)[0].id);
166
+ realtime.connect(NEW_BUILD);
167
+ assert.deepEqual(banners(shell), [], "the person closed the offer for this build");
168
+
169
+ realtime.connect(NEWER_BUILD);
170
+ assert.equal(banners(shell).length, 1, "a newer update offers again");
171
+ realtime.connect(PAGE_BUILD);
172
+ assert.deepEqual(banners(shell), [], "a server back on the page's own build withdraws the offer");
173
+
174
+ assert.equal(realtime.listenerCount(), 1);
175
+ await shell.clientUpdate.dispose();
176
+ assert.equal(realtime.listenerCount(), 0);
177
+ });
178
+
179
+ test("a development page, which has no build id, never offers a reload", async (t) => {
180
+ loadPage(t, { buildId: "" });
181
+ const realtime = createRealtimeStandIn();
182
+ const { shell } = await startClient(t, { inputs: { "client.realtime": realtime.capability } });
183
+ realtime.connect(NEW_BUILD);
184
+ assert.deepEqual(banners(shell), []);
185
+ });
186
+
187
+ test("reconnecting to a restarted server that serves a new build offers a reload", async (t) => {
188
+ loadPage(t);
189
+ const appRoot = await mkdtemp(path.join(os.tmpdir(), "shell-client-update-"));
190
+ t.after(() => rm(appRoot, { recursive: true, force: true }));
191
+ async function serve(buildId) {
192
+ await mkdir(path.join(appRoot, "dist"), { recursive: true });
193
+ await writeFile(path.join(appRoot, "dist", "index.html"),
194
+ `<!doctype html><html><head><meta name="jskit-client-build" content="${buildId}"></head></html>`);
195
+ }
196
+ // One server process: its own HTTP server and realtime runtime.
197
+ async function startServer(port = 0) {
198
+ const http = createServer();
199
+ const runtime = createCapabilityRuntime({ providers: [EventProvider, RealtimeProvider], inputs: {
200
+ "runtime.app-root": appRoot, "runtime.config": {}, "runtime.env": {},
201
+ "runtime.fastify": { server: http }, "runtime.logger": logger
202
+ } });
203
+ await runtime.start();
204
+ http.listen(port, "127.0.0.1");
205
+ await once(http, "listening");
206
+ return {
207
+ port: http.address().port,
208
+ async stop() {
209
+ await runtime.shutdown();
210
+ http.closeAllConnections();
211
+ await new Promise((resolve) => http.close(resolve));
212
+ }
213
+ };
214
+ }
215
+
216
+ await serve(PAGE_BUILD);
217
+ let server = await startServer();
218
+ const { port } = server;
219
+ t.after(() => server?.stop());
220
+ setGlobal(t, CLIENT_APP_CONFIG_GLOBAL_KEY, Object.freeze({ realtimeClient: {
221
+ url: `http://127.0.0.1:${port}`,
222
+ options: { transports: ["websocket"], reconnectionDelay: 50, reconnectionDelayMax: 100, randomizationFactor: 0 }
223
+ } }));
224
+ const { runtime: client, realtime, shell } = await startClient(t, {
225
+ providers: [RealtimeClientProvider],
226
+ probe: { realtime: "client.realtime", shell: "client.shell" }
227
+ });
228
+ const served = [];
229
+ realtime.onServedClientBuild((buildId) => served.push(buildId));
230
+ await waitFor(() => served.length === 1, "the server names the build it serves");
231
+ assert.deepEqual(banners(shell), [], "connected to a server that serves this page's build");
232
+
233
+ await server.stop();
234
+ server = null;
235
+ await serve(NEW_BUILD);
236
+ server = await startServer(port);
237
+ await waitFor(() => banners(shell).length === 1, "the reconnection offers a reload");
238
+ assert.equal(banners(shell)[0].message, "Vibe Test was updated. Reload to get the latest version.");
239
+ assert.deepEqual(served, [PAGE_BUILD, NEW_BUILD]);
240
+ await client.shutdown();
241
+ });
@@ -127,6 +127,7 @@ test("shell capability owns placement, bootstrap, refresh, errors, and recovery
127
127
  "asyncModuleRecovery",
128
128
  "bootstrap",
129
129
  "bootstrapHandlers",
130
+ "clientUpdate",
130
131
  "error",
131
132
  "errorPresentationStore",
132
133
  "placement",