@panomc/widget-host 0.0.0-stage → 1.0.0-dev.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/runtime/chunks/chunk-9EZydhXt.js +1 -0
  2. package/dist/runtime/chunks/chunk-BQPllGmY.js +1 -0
  3. package/dist/runtime/chunks/chunk-CTgT5UYL.js +1 -0
  4. package/dist/runtime/chunks/chunk-ChRkfjHR.js +1 -0
  5. package/dist/runtime/chunks/chunk-Cmbb89rp.js +1 -0
  6. package/dist/runtime/chunks/chunk-CqpY4RsZ.js +1 -0
  7. package/dist/runtime/chunks/chunk-D7Jd5Dpn.js +1 -0
  8. package/dist/runtime/chunks/chunk-DNUkGPCL.js +1 -0
  9. package/dist/runtime/chunks/chunk-DebScgYV.js +1 -0
  10. package/dist/runtime/chunks/chunk-DgPYxg7o.js +1 -0
  11. package/dist/runtime/chunks/chunk-DhgH0pN2.js +1 -0
  12. package/dist/runtime/chunks/chunk-FEL6LDrJ.js +1 -0
  13. package/dist/runtime/chunks/chunk-RPo0Hd8r.js +1 -0
  14. package/dist/runtime/chunks/chunk-Xd_2KAhC.js +1 -0
  15. package/dist/runtime/chunks/chunk-akOtSLvV.js +1 -0
  16. package/dist/runtime/chunks/chunk-cUxFvg6m.js +1 -0
  17. package/dist/runtime/css/pano-fallback-icons.css +9 -0
  18. package/dist/runtime/css/pano-tokens.css +225 -0
  19. package/dist/runtime/host/components-panel.js +1 -0
  20. package/dist/runtime/host/components-theme.js +1 -0
  21. package/dist/runtime/host/controllers.js +1 -0
  22. package/dist/runtime/host/index.js +1 -0
  23. package/dist/runtime/host/internal.js +1 -0
  24. package/dist/runtime/host/svelte.js +1 -0
  25. package/dist/runtime/host/toasts.js +1 -0
  26. package/dist/runtime/host/utils-api.js +1 -0
  27. package/dist/runtime/host/utils-auth.js +1 -0
  28. package/dist/runtime/host/utils-component.js +1 -0
  29. package/dist/runtime/host/utils-language.js +1 -0
  30. package/dist/runtime/host/utils-route.js +1 -0
  31. package/dist/runtime/host/utils-text.js +1 -0
  32. package/dist/runtime/host/utils-tooltip.js +1 -0
  33. package/dist/runtime/host/variables.js +1 -0
  34. package/dist/runtime/host/views.js +1 -0
  35. package/dist/runtime/loader.js +1 -0
  36. package/dist/runtime/runtime.json +104 -0
  37. package/dist/runtime/svelte/animate.js +1 -0
  38. package/dist/runtime/svelte/attachments.js +1 -0
  39. package/dist/runtime/svelte/easing.js +1 -0
  40. package/dist/runtime/svelte/events.js +1 -0
  41. package/dist/runtime/svelte/index.js +1 -0
  42. package/dist/runtime/svelte/internal-client.js +1 -0
  43. package/dist/runtime/svelte/internal-disclose-version.js +1 -0
  44. package/dist/runtime/svelte/internal-flags-async.js +1 -0
  45. package/dist/runtime/svelte/internal-flags-legacy.js +1 -0
  46. package/dist/runtime/svelte/internal-flags-tracing.js +1 -0
  47. package/dist/runtime/svelte/internal.js +1 -0
  48. package/dist/runtime/svelte/legacy.js +1 -0
  49. package/dist/runtime/svelte/motion.js +1 -0
  50. package/dist/runtime/svelte/reactivity-window.js +1 -0
  51. package/dist/runtime/svelte/reactivity.js +1 -0
  52. package/dist/runtime/svelte/store.js +1 -0
  53. package/dist/runtime/svelte/transition.js +1 -0
  54. package/dist/runtime/svelte-i18n.js +1 -0
  55. package/dist/runtime/webfonts/fa-brands-400.ttf +0 -0
  56. package/dist/runtime/webfonts/fa-brands-400.woff2 +0 -0
  57. package/dist/runtime/webfonts/fa-regular-400.ttf +0 -0
  58. package/dist/runtime/webfonts/fa-regular-400.woff2 +0 -0
  59. package/dist/runtime/webfonts/fa-solid-900.ttf +0 -0
  60. package/dist/runtime/webfonts/fa-solid-900.woff2 +0 -0
  61. package/dist/runtime/webfonts/fa-v4compatibility.ttf +0 -0
  62. package/dist/runtime/webfonts/fa-v4compatibility.woff2 +0 -0
  63. package/dist/widget-runtime.zip +0 -0
  64. package/package.json +59 -4
  65. package/scripts/build-zip.js +35 -0
  66. package/scripts/install-local.js +57 -0
  67. package/scripts/loader.js +169 -0
  68. package/scripts/runtime-map.js +52 -0
  69. package/scripts/zip.js +128 -0
  70. package/src/__tests__/components.test.js +77 -0
  71. package/src/__tests__/controllers.test.js +188 -0
  72. package/src/__tests__/define.test.js +276 -0
  73. package/src/__tests__/env.js +111 -0
  74. package/src/__tests__/fixtures/Goal.svelte +5 -0
  75. package/src/__tests__/modules.test.js +251 -0
  76. package/src/__tests__/parity.test.js +123 -0
  77. package/src/api.js +144 -0
  78. package/src/auth.js +2 -0
  79. package/src/component.js +4 -0
  80. package/src/components/Date.svelte +38 -0
  81. package/src/components/NoContent.svelte +13 -0
  82. package/src/components/PageActions.svelte +22 -0
  83. package/src/components/PageTitle.svelte +32 -0
  84. package/src/components/Pagination.svelte +49 -0
  85. package/src/components/PlayerHead.svelte +39 -0
  86. package/src/components/Toast.svelte +16 -0
  87. package/src/components/empty.js +3 -0
  88. package/src/components/index.js +14 -0
  89. package/src/components/panel.js +19 -0
  90. package/src/config.js +100 -0
  91. package/src/context.js +47 -0
  92. package/src/controllers.js +313 -0
  93. package/src/define.js +352 -0
  94. package/src/index.js +38 -0
  95. package/src/internal.js +2 -0
  96. package/src/language.js +181 -0
  97. package/src/plugin.js +20 -0
  98. package/src/route.js +4 -0
  99. package/src/runtime.js +49 -0
  100. package/src/session.js +72 -0
  101. package/src/svelte-runtime.js +3 -0
  102. package/src/svelte.js +72 -0
  103. package/src/text.js +2 -0
  104. package/src/toasts.js +75 -0
  105. package/src/tooltip.js +4 -0
  106. package/src/variables.js +29 -0
  107. package/src/views.js +17 -0
  108. package/README.md +0 -3
package/scripts/zip.js ADDED
@@ -0,0 +1,128 @@
1
+ // A minimal, deterministic zip writer and reader (no dependency): the runtime zip has a few hundred files, all deflate or stored.
2
+ // Entries are written sorted, with a fixed timestamp, so two builds of the same files give the same bytes.
3
+ import { deflateRawSync, inflateRawSync } from 'node:zlib';
4
+
5
+ const TABLE = (() => {
6
+ const table = new Uint32Array(256);
7
+ for (let n = 0; n < 256; n++) {
8
+ let c = n;
9
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
10
+ table[n] = c >>> 0;
11
+ }
12
+ return table;
13
+ })();
14
+
15
+ /** @param {Uint8Array} buf */
16
+ export function crc32(buf) {
17
+ let c = 0xffffffff;
18
+ for (let i = 0; i < buf.length; i++) c = TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
19
+ return (c ^ 0xffffffff) >>> 0;
20
+ }
21
+
22
+ // 2020-01-01 00:00:00 in DOS format
23
+ const DOS_TIME = 0;
24
+ const DOS_DATE = ((2020 - 1980) << 9) | (1 << 5) | 1;
25
+
26
+ /**
27
+ * @param {Array<{ name: string, data: Uint8Array }>} entries names use `/`
28
+ * @returns {Buffer}
29
+ */
30
+ export function writeZip(entries) {
31
+ const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
32
+ const parts = [];
33
+ const central = [];
34
+ let offset = 0;
35
+
36
+ for (const { name, data } of sorted) {
37
+ const raw = Buffer.from(data);
38
+ const packed = deflateRawSync(raw, { level: 9 });
39
+ const store = packed.length >= raw.length;
40
+ const body = store ? raw : packed;
41
+ const nameBytes = Buffer.from(name, 'utf8');
42
+ const crc = crc32(raw);
43
+
44
+ const local = Buffer.alloc(30);
45
+ local.writeUInt32LE(0x04034b50, 0);
46
+ local.writeUInt16LE(20, 4);
47
+ local.writeUInt16LE(0x0800, 6); // utf-8 names
48
+ local.writeUInt16LE(store ? 0 : 8, 8);
49
+ local.writeUInt16LE(DOS_TIME, 10);
50
+ local.writeUInt16LE(DOS_DATE, 12);
51
+ local.writeUInt32LE(crc, 14);
52
+ local.writeUInt32LE(body.length, 18);
53
+ local.writeUInt32LE(raw.length, 22);
54
+ local.writeUInt16LE(nameBytes.length, 26);
55
+ parts.push(local, nameBytes, body);
56
+
57
+ const entry = Buffer.alloc(46);
58
+ entry.writeUInt32LE(0x02014b50, 0);
59
+ entry.writeUInt16LE(20, 4);
60
+ entry.writeUInt16LE(20, 6);
61
+ entry.writeUInt16LE(0x0800, 8);
62
+ entry.writeUInt16LE(store ? 0 : 8, 10);
63
+ entry.writeUInt16LE(DOS_TIME, 12);
64
+ entry.writeUInt16LE(DOS_DATE, 14);
65
+ entry.writeUInt32LE(crc, 16);
66
+ entry.writeUInt32LE(body.length, 20);
67
+ entry.writeUInt32LE(raw.length, 24);
68
+ entry.writeUInt16LE(nameBytes.length, 28);
69
+ entry.writeUInt32LE(0o100644 * 65536, 38); // unix mode in the external attributes
70
+ entry.writeUInt32LE(offset, 42);
71
+ central.push(entry, nameBytes);
72
+
73
+ offset += local.length + nameBytes.length + body.length;
74
+ }
75
+
76
+ const centralBuf = Buffer.concat(central);
77
+ const end = Buffer.alloc(22);
78
+ end.writeUInt32LE(0x06054b50, 0);
79
+ end.writeUInt16LE(sorted.length, 8);
80
+ end.writeUInt16LE(sorted.length, 10);
81
+ end.writeUInt32LE(centralBuf.length, 12);
82
+ end.writeUInt32LE(offset, 16);
83
+ return Buffer.concat([...parts, centralBuf, end]);
84
+ }
85
+
86
+ /**
87
+ * @param {Uint8Array} bytes
88
+ * @returns {Array<{ name: string, data: Buffer }>} directories are skipped
89
+ */
90
+ export function readZip(bytes) {
91
+ const buf = Buffer.from(bytes);
92
+ let eocd = -1;
93
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) {
94
+ if (buf.readUInt32LE(i) === 0x06054b50) {
95
+ eocd = i;
96
+ break;
97
+ }
98
+ }
99
+ if (eocd < 0) throw new Error('not a zip file (no end of central directory)');
100
+
101
+ const count = buf.readUInt16LE(eocd + 10);
102
+ let pos = buf.readUInt32LE(eocd + 16);
103
+ const out = [];
104
+
105
+ for (let n = 0; n < count; n++) {
106
+ if (buf.readUInt32LE(pos) !== 0x02014b50) throw new Error('corrupt zip (central directory)');
107
+ const method = buf.readUInt16LE(pos + 10);
108
+ const crc = buf.readUInt32LE(pos + 16);
109
+ const size = buf.readUInt32LE(pos + 20);
110
+ const nameLen = buf.readUInt16LE(pos + 28);
111
+ const extraLen = buf.readUInt16LE(pos + 30);
112
+ const commentLen = buf.readUInt16LE(pos + 32);
113
+ const localAt = buf.readUInt32LE(pos + 42);
114
+ const name = buf.toString('utf8', pos + 46, pos + 46 + nameLen);
115
+ pos += 46 + nameLen + extraLen + commentLen;
116
+ if (name.endsWith('/')) continue;
117
+
118
+ const localNameLen = buf.readUInt16LE(localAt + 26);
119
+ const localExtraLen = buf.readUInt16LE(localAt + 28);
120
+ const start = localAt + 30 + localNameLen + localExtraLen;
121
+ const body = buf.subarray(start, start + size);
122
+ const data = method === 0 ? Buffer.from(body) : method === 8 ? inflateRawSync(body) : null;
123
+ if (!data) throw new Error(`${name}: unsupported compression method ${method}`);
124
+ if (crc32(data) !== crc) throw new Error(`${name}: checksum mismatch`);
125
+ out.push({ name, data });
126
+ }
127
+ return out;
128
+ }
@@ -0,0 +1,77 @@
1
+ // W1: the Svelte copies of the theme components render without $lib / $app.
2
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
3
+ import { installBrowserEnv, settle, uninstallBrowserEnv } from './env.js';
4
+
5
+ let c, mount, unmount, configure;
6
+
7
+ beforeAll(async () => {
8
+ await installBrowserEnv();
9
+ c = await import('../components/index.js');
10
+ ({ mount, unmount } = await import('../svelte-runtime.js'));
11
+ ({ configure } = await import('../config.js'));
12
+ configure({ apiBase: 'https://pano.test', locale: 'en-US' });
13
+ });
14
+
15
+ afterAll(() => uninstallBrowserEnv());
16
+
17
+ function render(Component, props = {}) {
18
+ const target = document.createElement('div');
19
+ document.body.append(target);
20
+ const instance = mount(Component, { target, props });
21
+ return { target, destroy: () => unmount(instance) };
22
+ }
23
+
24
+ describe('components', () => {
25
+ test('NoContent shows the text and the icon class', () => {
26
+ const { target, destroy } = render(c.NoContent, { text: 'Nothing here', icon: 'fa-solid fa-ghost' });
27
+ expect(target.querySelector('p').textContent).toBe('Nothing here');
28
+ expect(target.querySelector('span').className).toBe('fa-solid fa-ghost');
29
+ destroy();
30
+ });
31
+
32
+ test('Pagination renders the pages and marks the current one', async () => {
33
+ const { target, destroy } = render(c.Pagination, { page: 2, totalPage: 3 });
34
+ expect(target.querySelectorAll('li.page-item')).toHaveLength(5);
35
+ expect(target.querySelector('li.active').textContent.trim()).toBe('2');
36
+ destroy();
37
+ });
38
+
39
+ test('Toast maps the variant to a class', () => {
40
+ const { target, destroy } = render(c.Toast, { id: 4, variant: 'danger' });
41
+ const el = target.querySelector('#appToast4');
42
+ expect(el.className).toContain('text-danger');
43
+ destroy();
44
+ });
45
+
46
+ test('PageTitle: a string title, subtitle', () => {
47
+ const { target, destroy } = render(c.PageTitle, { title: 'Hello', subtitle: 'World' });
48
+ expect(target.querySelector('h1').textContent.trim()).toBe('Hello');
49
+ expect(target.querySelector('p').textContent.trim()).toBe('World');
50
+ destroy();
51
+ });
52
+
53
+ test('PageActions renders only the sides it was given', () => {
54
+ const { target, destroy } = render(c.PageActions, { leftClasses: 'x' });
55
+ expect(target.querySelectorAll('.row > div')).toHaveLength(1);
56
+ destroy();
57
+ });
58
+
59
+ test('Date formats an epoch string; PlayerHead points at the site picture', async () => {
60
+ const date = render(c.Date, { time: String(Date.UTC(2026, 0, 15, 12)) });
61
+ expect(date.target.querySelector('span').textContent.trim()).toContain('2026');
62
+ date.destroy();
63
+
64
+ const head = render(c.PlayerHead, { username: 'Steve', lastActivityTime: Date.now(), banned: false });
65
+ await settle(5);
66
+ expect(head.target.querySelector('img').getAttribute('src')).toBe('https://pano.test/api/profile/picture/Steve');
67
+ head.destroy();
68
+ });
69
+
70
+ test('PluginBlock and PluginSlot render nothing', () => {
71
+ for (const C of [c.PluginBlock, c.PluginSlot]) {
72
+ const { target, destroy } = render(C, { id: 'market:NavCart' });
73
+ expect(target.innerHTML.trim()).toBe('');
74
+ destroy();
75
+ }
76
+ });
77
+ });
@@ -0,0 +1,188 @@
1
+ // W1: the controller host memoises load(name, params) while in flight and for 5 s (doc 06 section 3.1).
2
+ import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
3
+ import { installBrowserEnv, uninstallBrowserEnv } from './env.js';
4
+
5
+ let createLoadMemo, LOAD_MEMO_MS, plugin, clearLoadMemo, registry, loadPluginControllers, reactive;
6
+
7
+ beforeAll(async () => {
8
+ await installBrowserEnv();
9
+ ({ createLoadMemo, LOAD_MEMO_MS, plugin, clearLoadMemo, registry, loadPluginControllers, reactive } = await import('../controllers.js'));
10
+ });
11
+
12
+ afterAll(() => uninstallBrowserEnv());
13
+
14
+ afterEach(() => {
15
+ clearLoadMemo();
16
+ registry.reset();
17
+ });
18
+
19
+ const deferred = () => {
20
+ let resolve, reject;
21
+ const promise = new Promise((res, rej) => ((resolve = res), (reject = rej)));
22
+ return { promise, resolve, reject };
23
+ };
24
+
25
+ describe('createLoadMemo', () => {
26
+ test('the window is 5 seconds', () => {
27
+ expect(LOAD_MEMO_MS).toBe(5000);
28
+ });
29
+
30
+ test('callers in flight share one call', async () => {
31
+ const memo = createLoadMemo();
32
+ const d = deferred();
33
+ let calls = 0;
34
+ const produce = () => (calls++, d.promise);
35
+
36
+ const results = [memo.run('market/widgets', {}, produce), memo.run('market/widgets', {}, produce), memo.run('market/widgets', undefined, produce), memo.run('market/widgets', {}, produce)];
37
+ expect(calls).toBe(1);
38
+
39
+ d.resolve({ goal: 1 });
40
+ expect(await Promise.all(results)).toEqual([{ goal: 1 }, { goal: 1 }, { goal: 1 }, { goal: 1 }]);
41
+ });
42
+
43
+ test('the answer is kept for 5 s after it arrived, then asked again', async () => {
44
+ let time = 1000;
45
+ const memo = createLoadMemo({ now: () => time });
46
+ let calls = 0;
47
+ const produce = async () => ({ n: ++calls });
48
+
49
+ expect(await memo.run('a/b', {}, produce)).toEqual({ n: 1 });
50
+ await Promise.resolve();
51
+
52
+ time += 4999;
53
+ expect(await memo.run('a/b', {}, produce)).toEqual({ n: 1 });
54
+ expect(calls).toBe(1);
55
+
56
+ time += 1;
57
+ expect(await memo.run('a/b', {}, produce)).toEqual({ n: 2 });
58
+ expect(calls).toBe(2);
59
+ });
60
+
61
+ test('the 5 s run from the answer, not from the call', async () => {
62
+ let time = 0;
63
+ const memo = createLoadMemo({ now: () => time });
64
+ const d = deferred();
65
+ let calls = 0;
66
+ const produce = () => (calls++, d.promise);
67
+
68
+ const first = memo.run('a/b', {}, produce);
69
+ time = 20000; // a slow request
70
+ d.resolve({ ok: true });
71
+ await first;
72
+ await Promise.resolve();
73
+
74
+ time = 24000;
75
+ await memo.run('a/b', {}, produce);
76
+ expect(calls).toBe(1);
77
+ });
78
+
79
+ test('params and names are separate keys; key order does not matter', async () => {
80
+ const memo = createLoadMemo();
81
+ let calls = 0;
82
+ const produce = async () => ++calls;
83
+
84
+ await memo.run('a/b', { x: 1, y: 2 }, produce);
85
+ await memo.run('a/b', { y: 2, x: 1 }, produce);
86
+ expect(calls).toBe(1);
87
+
88
+ await memo.run('a/b', { x: 2, y: 2 }, produce);
89
+ await memo.run('a/c', { x: 1, y: 2 }, produce);
90
+ expect(calls).toBe(3);
91
+ });
92
+
93
+ test('a failure is not kept', async () => {
94
+ const memo = createLoadMemo();
95
+ let calls = 0;
96
+ const produce = async () => {
97
+ calls++;
98
+ if (calls === 1) throw new Error('down');
99
+ return { ok: true };
100
+ };
101
+
102
+ await expect(memo.run('a/b', {}, produce)).rejects.toThrow('down');
103
+ await Promise.resolve();
104
+ expect(await memo.run('a/b', {}, produce)).toEqual({ ok: true });
105
+ expect(calls).toBe(2);
106
+ });
107
+
108
+ test('null (controller not available yet) is not kept', async () => {
109
+ const memo = createLoadMemo();
110
+ let calls = 0;
111
+ const produce = async () => (++calls === 1 ? null : { ok: true });
112
+
113
+ expect(await memo.run('a/b', {}, produce)).toBeNull();
114
+ await Promise.resolve();
115
+ expect(await memo.run('a/b', {}, produce)).toEqual({ ok: true });
116
+ });
117
+ });
118
+
119
+ describe('plugin(ns).load', () => {
120
+ test('four widgets of one plugin make one request', async () => {
121
+ let requests = 0;
122
+ const definition = {
123
+ name: 'widgets',
124
+ version: 1,
125
+ load: async ({ params }) => {
126
+ requests++;
127
+ await new Promise((r) => setTimeout(r, 5));
128
+ return { goal: 10, params };
129
+ },
130
+ create: () => ({ get: () => ({}), subscribe: (run) => (run({}), () => {}), actions: {}, destroy() {} }),
131
+ };
132
+ registry.register('pano-plugin-demo', 'demo', [definition]);
133
+
134
+ const results = await Promise.all(['goal', 'buyers', 'top', 'stats'].map(() => plugin('demo').load('widgets')));
135
+ expect(requests).toBe(1);
136
+ expect(results.every((r) => r.goal === 10)).toBe(true);
137
+
138
+ // a different params object is another request; clearing (invalidate) forgets
139
+ await plugin('demo').load('widgets', { params: { page: 2 } });
140
+ expect(requests).toBe(2);
141
+ clearLoadMemo();
142
+ await plugin('demo').load('widgets');
143
+ expect(requests).toBe(3);
144
+ });
145
+
146
+ test('an unknown controller resolves null and is not remembered', async () => {
147
+ expect(await plugin('missing').load('nothing')).toBeNull();
148
+ });
149
+ });
150
+
151
+ describe('loadPluginControllers', () => {
152
+ test('registers the definitions of a plugin once, with the widget host', async () => {
153
+ let created = 0;
154
+ const module = {
155
+ controllers: {
156
+ cart: {
157
+ name: 'cart',
158
+ version: 1,
159
+ create: (host) => {
160
+ created++;
161
+ return { get: () => ({ guest: host.session().user === null, base: host.baseUrl }), subscribe: (run) => (run({}), () => {}), actions: {}, destroy() {} };
162
+ },
163
+ },
164
+ },
165
+ };
166
+
167
+ expect(await loadPluginControllers({ pluginId: 'pano-plugin-shop', ns: 'shop', module })).toBe(true);
168
+ expect(await loadPluginControllers({ pluginId: 'pano-plugin-shop', ns: 'shop', module: {} })).toBe(true); // once per plugin
169
+
170
+ const cart = plugin('shop').use('cart');
171
+ expect(cart.state.guest).toBe(true);
172
+ expect(created).toBe(1);
173
+ expect(plugin('shop').installed).toBe(true);
174
+ });
175
+
176
+ test('a plugin without controllers resolves false', async () => {
177
+ expect(await loadPluginControllers({ pluginId: 'pano-plugin-none', ns: 'none', module: {} })).toBe(false);
178
+ });
179
+ });
180
+
181
+ describe('reactive', () => {
182
+ test('exposes state and actions of a controller', () => {
183
+ const controller = { get: () => ({ n: 1 }), subscribe: (run) => (run({ n: 1 }), () => {}), actions: { add() {} } };
184
+ const wrapped = reactive(controller);
185
+ expect(wrapped.state).toEqual({ n: 1 });
186
+ expect(wrapped.actions).toBe(controller.actions);
187
+ });
188
+ });
@@ -0,0 +1,276 @@
1
+ // W1: defineWidget life cycle with the real browser build of Svelte on happy-dom.
2
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
3
+ import { installBrowserEnv, settle, uninstallBrowserEnv } from './env.js';
4
+
5
+ let defineWidget, configure, resetConfig, resetSession, activeWidgets, Goal, invalidateAll;
6
+
7
+ /** a fake Pano: `credentials` answers per `session`, everything else 404 */
8
+ function fakePano({ user = null } = {}) {
9
+ const calls = [];
10
+ const fetch = async (url, init) => {
11
+ calls.push(String(url));
12
+ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
13
+ if (String(url).endsWith('/api/v1/auth/credentials')) {
14
+ return user ? json(200, { ...user, csrfToken: 'tok' }) : json(401, { error: { code: 'NOT_LOGGED_IN' } });
15
+ }
16
+ return json(404, { error: { code: 'NOT_FOUND' } });
17
+ };
18
+ return { fetch, calls };
19
+ }
20
+
21
+ let counter = 0;
22
+ const nextTag = () => `pano-test-w${++counter}`;
23
+ const mountEl = (tag, attrs = {}) => {
24
+ const el = document.createElement(tag);
25
+ for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
26
+ document.body.append(el);
27
+ return el;
28
+ };
29
+ const body = (el) => (el.shadowRoot ?? el).querySelector('.pano-fb');
30
+
31
+ beforeAll(async () => {
32
+ await installBrowserEnv();
33
+ ({ defineWidget } = await import('../define.js'));
34
+ ({ configure, resetConfig } = await import('../config.js'));
35
+ ({ resetSession } = await import('../session.js'));
36
+ ({ activeWidgets } = await import('../runtime.js'));
37
+ ({ invalidateAll } = await import('../svelte.js'));
38
+ Goal = (await import('./fixtures/Goal.svelte')).default;
39
+ });
40
+
41
+ afterAll(() => uninstallBrowserEnv());
42
+
43
+ beforeEach(() => {
44
+ resetSession();
45
+ configure({ apiBase: 'https://pano.test', siteUrl: 'https://site.test', urls: { 'auth.login': '/login' }, fetch: fakePano().fetch });
46
+ });
47
+
48
+ afterEach(() => {
49
+ document.body.replaceChildren();
50
+ document.head.replaceChildren();
51
+ resetConfig();
52
+ });
53
+
54
+ describe('defineWidget', () => {
55
+ test('connected: shadow root with the sheets and div.pano-fb, load, mount, pano:ready', async () => {
56
+ const tag = nextTag();
57
+ const loadCalls = [];
58
+ defineWidget(
59
+ tag,
60
+ {
61
+ component: Goal,
62
+ attrs: ['label', { name: 'count', type: 'number' }],
63
+ load: async (event, props) => {
64
+ loadCalls.push({ event, props });
65
+ return { data: { value: 5 } };
66
+ },
67
+ },
68
+ { ns: 'test', styles: { fallback: 'https://pano.test/api/v1/plugins/pano-plugin-test/_/ui/fallback.css', hash: 'abc', icons: 'https://pano.test/icons.css' } },
69
+ );
70
+
71
+ const events = [];
72
+ document.addEventListener('pano:ready', (e) => events.push(e));
73
+
74
+ const el = mountEl(tag, { label: 'goal-x' });
75
+ expect(el.dataset.panoState).toBe('loading');
76
+ await settle(20);
77
+
78
+ const root = el.shadowRoot;
79
+ expect(root.mode ?? 'open').toBe('open');
80
+ const hrefs = [...root.querySelectorAll('link[rel="stylesheet"]')].map((l) => l.getAttribute('href'));
81
+ expect(hrefs).toEqual(['https://pano.test/api/v1/plugins/pano-plugin-test/_/ui/fallback.css?v=abc', 'https://pano.test/icons.css']);
82
+
83
+ const fb = root.querySelector('div.pano-fb');
84
+ expect(fb.getAttribute('data-pano-fb')).toBe('test');
85
+ expect(fb.querySelector('.goal').textContent).toBe('goal-x:5:0');
86
+
87
+ // the load contract of doc 06 section 3.1
88
+ expect(loadCalls).toHaveLength(1);
89
+ expect(loadCalls[0].event.widget).toBe(true);
90
+ expect(loadCalls[0].event.params).toEqual({ label: 'goal-x' });
91
+ expect(loadCalls[0].event.url).toBeInstanceOf(URL);
92
+ expect(typeof loadCalls[0].event.fetch).toBe('function');
93
+ expect(loadCalls[0].props).toEqual({ label: 'goal-x' });
94
+
95
+ expect(el.dataset.panoState).toBe('ready');
96
+ expect(events).toHaveLength(1);
97
+ expect(events[0].bubbles).toBe(true);
98
+ expect(events[0].composed).toBe(true);
99
+ expect(activeWidgets()).toContain(el);
100
+ });
101
+
102
+ test('attribute change updates the props of the mounted component; properties too', async () => {
103
+ const tag = nextTag();
104
+ let loads = 0;
105
+ defineWidget(tag, { component: Goal, attrs: ['label', { name: 'count', type: 'number' }], load: async () => (loads++, { data: { value: 1 } }) });
106
+
107
+ const el = mountEl(tag, { count: '2' });
108
+ await settle(20);
109
+ expect(body(el).querySelector('.goal').textContent).toBe('goal:1:2');
110
+
111
+ el.setAttribute('count', '7');
112
+ await settle(10);
113
+ expect(body(el).querySelector('.goal').textContent).toBe('goal:1:7');
114
+
115
+ el.label = 'renamed';
116
+ await settle(10);
117
+ expect(body(el).querySelector('.goal').textContent).toBe('renamed:1:7');
118
+
119
+ el.props = { data: { value: 42 } };
120
+ await settle(10);
121
+ expect(body(el).querySelector('.goal').textContent).toBe('renamed:42:7');
122
+ expect(loads).toBe(1);
123
+ });
124
+
125
+ test('disconnected unmounts the component; reconnecting mounts again', async () => {
126
+ const tag = nextTag();
127
+ defineWidget(tag, { component: Goal, load: async () => ({ data: { value: 3 } }) });
128
+
129
+ const el = mountEl(tag);
130
+ await settle(20);
131
+ expect(body(el).querySelector('.goal')).not.toBeNull();
132
+
133
+ el.remove();
134
+ expect(body(el).childElementCount).toBe(0);
135
+ expect(activeWidgets()).not.toContain(el);
136
+
137
+ document.body.append(el);
138
+ await settle(20);
139
+ expect(body(el).querySelector('.goal').textContent).toBe('goal:3:0');
140
+ });
141
+
142
+ test('a load that finishes after disconnect mounts nothing', async () => {
143
+ const tag = nextTag();
144
+ let release;
145
+ defineWidget(tag, { component: Goal, load: () => new Promise((r) => (release = r)) });
146
+
147
+ const el = mountEl(tag);
148
+ await settle(20);
149
+ el.remove();
150
+ release({ data: { value: 1 } });
151
+ await settle(10);
152
+ expect(body(el).childElementCount).toBe(0);
153
+ });
154
+
155
+ test('load error: inline message, retry button, pano:error { code }, retry loads again', async () => {
156
+ const tag = nextTag();
157
+ let fail = true;
158
+ defineWidget(tag, {
159
+ component: Goal,
160
+ load: async () => {
161
+ if (fail) throw Object.assign(new Error('nope'), { code: 'BOOM' });
162
+ return { data: { value: 9 } };
163
+ },
164
+ });
165
+
166
+ const errors = [];
167
+ document.addEventListener('pano:error', (e) => errors.push(e.detail));
168
+
169
+ const el = mountEl(tag);
170
+ await settle(20);
171
+ expect(el.dataset.panoState).toBe('error');
172
+ expect(errors).toEqual([{ code: 'BOOM' }]);
173
+ const retry = body(el).querySelector('[data-pano-retry]');
174
+ expect(retry).not.toBeNull();
175
+
176
+ fail = false;
177
+ retry.click();
178
+ await settle(20);
179
+ expect(el.dataset.panoState).toBe('ready');
180
+ expect(body(el).querySelector('.goal').textContent).toBe('goal:9:0');
181
+ });
182
+
183
+ test('inactive plugin: empty, no error event', async () => {
184
+ const errors = [];
185
+ const onError = (e) => errors.push(e.detail);
186
+ document.addEventListener('pano:error', onError);
187
+
188
+ const a = nextTag();
189
+ defineWidget(a, { component: Goal, load: async () => ({}) }, { active: false });
190
+ const b = nextTag();
191
+ defineWidget(b, {
192
+ component: Goal,
193
+ load: async () => {
194
+ throw Object.assign(new Error('gone'), { code: 'PLUGIN_INACTIVE' });
195
+ },
196
+ });
197
+
198
+ const first = mountEl(a);
199
+ const second = mountEl(b);
200
+ await settle(20);
201
+
202
+ for (const el of [first, second]) {
203
+ expect(el.dataset.panoState).toBe('inactive');
204
+ expect(body(el).childElementCount).toBe(0);
205
+ }
206
+ expect(errors).toEqual([]);
207
+ document.removeEventListener('pano:error', onError);
208
+ });
209
+
210
+ test("session 'required' and anonymous: sign-in link to the URL map; logged in: mounts", async () => {
211
+ const tag = nextTag();
212
+ let loads = 0;
213
+ defineWidget(tag, { component: Goal, session: 'required', load: async () => (loads++, { data: { value: 1 } }) });
214
+
215
+ const el = mountEl(tag);
216
+ await settle(30);
217
+ expect(el.dataset.panoState).toBe('signin');
218
+ const a = body(el).querySelector('a');
219
+ expect(a.getAttribute('href')).toBe('https://site.test/login');
220
+ expect(loads).toBe(0);
221
+
222
+ resetSession();
223
+ configure({ fetch: fakePano({ user: { username: 'steve' } }).fetch });
224
+ await el.reload();
225
+ await settle(20);
226
+ expect(el.dataset.panoState).toBe('ready');
227
+ expect(loads).toBe(1);
228
+ });
229
+
230
+ test("session 'none' never probes the session", async () => {
231
+ const tag = nextTag();
232
+ const pano = fakePano();
233
+ configure({ fetch: pano.fetch });
234
+ defineWidget(tag, { component: Goal, load: async () => ({ data: { value: 1 } }) });
235
+
236
+ mountEl(tag);
237
+ await settle(20);
238
+ expect(pano.calls.some((u) => u.endsWith('/auth/credentials'))).toBe(false);
239
+ });
240
+
241
+ test('no-shadow renders in the light DOM and links the sheets in head once', async () => {
242
+ const tag = nextTag();
243
+ defineWidget(tag, { component: Goal, load: async () => ({ data: { value: 6 } }) }, { ns: 'test', styles: { fallback: 'https://pano.test/fb.css', hash: 'h' } });
244
+
245
+ const one = mountEl(tag, { 'no-shadow': '' });
246
+ const two = mountEl(tag, { 'no-shadow': '' });
247
+ await settle(20);
248
+
249
+ expect(one.shadowRoot).toBeNull();
250
+ expect(one.querySelector('div.pano-fb .goal').textContent).toBe('goal:6:0');
251
+ expect(two.querySelector('div.pano-fb .goal')).not.toBeNull();
252
+ const links = [...document.head.querySelectorAll('link[rel="stylesheet"]')];
253
+ expect(links.map((l) => l.getAttribute('href'))).toEqual(['https://pano.test/fb.css?v=h']);
254
+ });
255
+
256
+ test('invalidateAll re-runs the load of the mounted widgets', async () => {
257
+ const tag = nextTag();
258
+ let loads = 0;
259
+ defineWidget(tag, { component: Goal, load: async () => ({ data: { value: ++loads } }) });
260
+
261
+ const el = mountEl(tag);
262
+ await settle(20);
263
+ expect(body(el).querySelector('.goal').textContent).toBe('goal:1:0');
264
+
265
+ await invalidateAll();
266
+ await settle(10);
267
+ expect(loads).toBe(2);
268
+ expect(body(el).querySelector('.goal').textContent).toBe('goal:2:0');
269
+ });
270
+
271
+ test('an existing registration is kept', () => {
272
+ const tag = nextTag();
273
+ const first = defineWidget(tag, { component: Goal });
274
+ expect(defineWidget(tag, { component: Goal })).toBe(first);
275
+ });
276
+ });