@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.
- package/dist/runtime/chunks/chunk-9EZydhXt.js +1 -0
- package/dist/runtime/chunks/chunk-BQPllGmY.js +1 -0
- package/dist/runtime/chunks/chunk-CTgT5UYL.js +1 -0
- package/dist/runtime/chunks/chunk-ChRkfjHR.js +1 -0
- package/dist/runtime/chunks/chunk-Cmbb89rp.js +1 -0
- package/dist/runtime/chunks/chunk-CqpY4RsZ.js +1 -0
- package/dist/runtime/chunks/chunk-D7Jd5Dpn.js +1 -0
- package/dist/runtime/chunks/chunk-DNUkGPCL.js +1 -0
- package/dist/runtime/chunks/chunk-DebScgYV.js +1 -0
- package/dist/runtime/chunks/chunk-DgPYxg7o.js +1 -0
- package/dist/runtime/chunks/chunk-DhgH0pN2.js +1 -0
- package/dist/runtime/chunks/chunk-FEL6LDrJ.js +1 -0
- package/dist/runtime/chunks/chunk-RPo0Hd8r.js +1 -0
- package/dist/runtime/chunks/chunk-Xd_2KAhC.js +1 -0
- package/dist/runtime/chunks/chunk-akOtSLvV.js +1 -0
- package/dist/runtime/chunks/chunk-cUxFvg6m.js +1 -0
- package/dist/runtime/css/pano-fallback-icons.css +9 -0
- package/dist/runtime/css/pano-tokens.css +225 -0
- package/dist/runtime/host/components-panel.js +1 -0
- package/dist/runtime/host/components-theme.js +1 -0
- package/dist/runtime/host/controllers.js +1 -0
- package/dist/runtime/host/index.js +1 -0
- package/dist/runtime/host/internal.js +1 -0
- package/dist/runtime/host/svelte.js +1 -0
- package/dist/runtime/host/toasts.js +1 -0
- package/dist/runtime/host/utils-api.js +1 -0
- package/dist/runtime/host/utils-auth.js +1 -0
- package/dist/runtime/host/utils-component.js +1 -0
- package/dist/runtime/host/utils-language.js +1 -0
- package/dist/runtime/host/utils-route.js +1 -0
- package/dist/runtime/host/utils-text.js +1 -0
- package/dist/runtime/host/utils-tooltip.js +1 -0
- package/dist/runtime/host/variables.js +1 -0
- package/dist/runtime/host/views.js +1 -0
- package/dist/runtime/loader.js +1 -0
- package/dist/runtime/runtime.json +104 -0
- package/dist/runtime/svelte/animate.js +1 -0
- package/dist/runtime/svelte/attachments.js +1 -0
- package/dist/runtime/svelte/easing.js +1 -0
- package/dist/runtime/svelte/events.js +1 -0
- package/dist/runtime/svelte/index.js +1 -0
- package/dist/runtime/svelte/internal-client.js +1 -0
- package/dist/runtime/svelte/internal-disclose-version.js +1 -0
- package/dist/runtime/svelte/internal-flags-async.js +1 -0
- package/dist/runtime/svelte/internal-flags-legacy.js +1 -0
- package/dist/runtime/svelte/internal-flags-tracing.js +1 -0
- package/dist/runtime/svelte/internal.js +1 -0
- package/dist/runtime/svelte/legacy.js +1 -0
- package/dist/runtime/svelte/motion.js +1 -0
- package/dist/runtime/svelte/reactivity-window.js +1 -0
- package/dist/runtime/svelte/reactivity.js +1 -0
- package/dist/runtime/svelte/store.js +1 -0
- package/dist/runtime/svelte/transition.js +1 -0
- package/dist/runtime/svelte-i18n.js +1 -0
- package/dist/runtime/webfonts/fa-brands-400.ttf +0 -0
- package/dist/runtime/webfonts/fa-brands-400.woff2 +0 -0
- package/dist/runtime/webfonts/fa-regular-400.ttf +0 -0
- package/dist/runtime/webfonts/fa-regular-400.woff2 +0 -0
- package/dist/runtime/webfonts/fa-solid-900.ttf +0 -0
- package/dist/runtime/webfonts/fa-solid-900.woff2 +0 -0
- package/dist/runtime/webfonts/fa-v4compatibility.ttf +0 -0
- package/dist/runtime/webfonts/fa-v4compatibility.woff2 +0 -0
- package/dist/widget-runtime.zip +0 -0
- package/package.json +59 -4
- package/scripts/build-zip.js +35 -0
- package/scripts/install-local.js +57 -0
- package/scripts/loader.js +169 -0
- package/scripts/runtime-map.js +52 -0
- package/scripts/zip.js +128 -0
- package/src/__tests__/components.test.js +77 -0
- package/src/__tests__/controllers.test.js +188 -0
- package/src/__tests__/define.test.js +276 -0
- package/src/__tests__/env.js +111 -0
- package/src/__tests__/fixtures/Goal.svelte +5 -0
- package/src/__tests__/modules.test.js +251 -0
- package/src/__tests__/parity.test.js +123 -0
- package/src/api.js +144 -0
- package/src/auth.js +2 -0
- package/src/component.js +4 -0
- package/src/components/Date.svelte +38 -0
- package/src/components/NoContent.svelte +13 -0
- package/src/components/PageActions.svelte +22 -0
- package/src/components/PageTitle.svelte +32 -0
- package/src/components/Pagination.svelte +49 -0
- package/src/components/PlayerHead.svelte +39 -0
- package/src/components/Toast.svelte +16 -0
- package/src/components/empty.js +3 -0
- package/src/components/index.js +14 -0
- package/src/components/panel.js +19 -0
- package/src/config.js +100 -0
- package/src/context.js +47 -0
- package/src/controllers.js +313 -0
- package/src/define.js +352 -0
- package/src/index.js +38 -0
- package/src/internal.js +2 -0
- package/src/language.js +181 -0
- package/src/plugin.js +20 -0
- package/src/route.js +4 -0
- package/src/runtime.js +49 -0
- package/src/session.js +72 -0
- package/src/svelte-runtime.js +3 -0
- package/src/svelte.js +72 -0
- package/src/text.js +2 -0
- package/src/toasts.js +75 -0
- package/src/tooltip.js +4 -0
- package/src/variables.js +29 -0
- package/src/views.js +17 -0
- package/README.md +0 -3
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Test environment for the widget host (not shipped): a happy-dom window on globalThis, the browser build of
|
|
2
|
+
// Svelte under Bun (the default condition resolves the server build, where mount() throws) and a .svelte loader.
|
|
3
|
+
import { mock } from 'bun:test';
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { Window } from 'happy-dom';
|
|
9
|
+
|
|
10
|
+
const require = createRequire(import.meta.url);
|
|
11
|
+
const svelteDir = dirname(require.resolve('svelte/package.json'));
|
|
12
|
+
const svelteExports = JSON.parse(readFileSync(join(svelteDir, 'package.json'), 'utf8')).exports;
|
|
13
|
+
const { compile } = require('svelte/compiler');
|
|
14
|
+
|
|
15
|
+
function pick(entry) {
|
|
16
|
+
if (typeof entry === 'string') return entry;
|
|
17
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
18
|
+
for (const key of ['browser', 'import', 'default']) {
|
|
19
|
+
if (key in entry) {
|
|
20
|
+
const found = pick(entry[key]);
|
|
21
|
+
if (found) return found;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Absolute file of a `svelte` / `svelte/x` specifier under the `browser` condition, or null. */
|
|
28
|
+
export function resolveSvelteBrowser(specifier) {
|
|
29
|
+
const key = specifier === 'svelte' ? '.' : `./${specifier.slice('svelte/'.length)}`;
|
|
30
|
+
if (key === './compiler') return null;
|
|
31
|
+
const file = pick(svelteExports[key]);
|
|
32
|
+
return file ? join(svelteDir, file) : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let pluginInstalled = false;
|
|
36
|
+
/** @type {Map<string, PropertyDescriptor | undefined>} */
|
|
37
|
+
let saved = new Map();
|
|
38
|
+
let window = null;
|
|
39
|
+
|
|
40
|
+
const NAMES = [
|
|
41
|
+
'window', 'self', 'document', 'HTMLElement', 'Element', 'Node', 'Text', 'Comment', 'DocumentFragment', 'ShadowRoot',
|
|
42
|
+
'CustomEvent', 'Event', 'MouseEvent', 'KeyboardEvent', 'MutationObserver', 'customElements', 'HTMLTemplateElement',
|
|
43
|
+
'HTMLInputElement', 'HTMLButtonElement', 'HTMLAnchorElement', 'HTMLLinkElement', 'getComputedStyle', 'location',
|
|
44
|
+
'navigator', 'localStorage', 'sessionStorage', 'requestAnimationFrame', 'cancelAnimationFrame', 'DOMParser',
|
|
45
|
+
'SVGElement', 'HTMLSelectElement', 'HTMLTextAreaElement', 'HTMLImageElement', 'HTMLFormElement', 'NodeFilter',
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
function installPlugin() {
|
|
49
|
+
if (pluginInstalled) return;
|
|
50
|
+
pluginInstalled = true;
|
|
51
|
+
|
|
52
|
+
Bun.plugin({
|
|
53
|
+
name: 'widget-host-test-svelte',
|
|
54
|
+
setup(build) {
|
|
55
|
+
build.onLoad({ filter: /\.svelte$/ }, (args) => {
|
|
56
|
+
const source = readFileSync(args.path, 'utf8');
|
|
57
|
+
const { js, warnings } = compile(source, { generate: 'client', filename: args.path, dev: false });
|
|
58
|
+
for (const w of warnings) console.warn(`[svelte] ${args.path}: ${w.code} ${w.message}`);
|
|
59
|
+
return { contents: js.code, loader: 'js' };
|
|
60
|
+
});
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Under Bun the default `svelte` is the server build (mount() throws) and a Bun plugin cannot redirect a bare package name.
|
|
66
|
+
// So `svelte/reactivity` is replaced with `mock.module`, and `../svelte-runtime.js` (mount, unmount, onMount) with the browser build.
|
|
67
|
+
// `uninstallBrowserEnv` puts `svelte/reactivity` back (the runtime file is only used by this package).
|
|
68
|
+
const RUNTIME_FILE = fileURLToPath(new URL('../svelte-runtime.js', import.meta.url));
|
|
69
|
+
/** @type {Record<string, any>} */
|
|
70
|
+
let originals = {};
|
|
71
|
+
|
|
72
|
+
/** A fresh happy-dom window on globalThis and the browser build of Svelte. Call `uninstallBrowserEnv()` in `afterAll`. */
|
|
73
|
+
export async function installBrowserEnv() {
|
|
74
|
+
installPlugin();
|
|
75
|
+
if (window) return window;
|
|
76
|
+
|
|
77
|
+
originals = { reactivity: { ...(await import('svelte/reactivity')) } };
|
|
78
|
+
const reactivity = await import(resolveSvelteBrowser('svelte/reactivity'));
|
|
79
|
+
const core = await import(resolveSvelteBrowser('svelte'));
|
|
80
|
+
mock.module('svelte/reactivity', () => ({ ...reactivity }));
|
|
81
|
+
mock.module(RUNTIME_FILE, () => ({ mount: core.mount, unmount: core.unmount, onMount: core.onMount }));
|
|
82
|
+
|
|
83
|
+
window = new Window({ url: 'https://site.test/page', settings: { disableErrorCapturing: true } });
|
|
84
|
+
saved = new Map();
|
|
85
|
+
|
|
86
|
+
for (const name of NAMES) {
|
|
87
|
+
saved.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
|
88
|
+
const value = name === 'window' || name === 'self' ? window : window[name];
|
|
89
|
+
Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return window;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function uninstallBrowserEnv() {
|
|
96
|
+
if (!window) return;
|
|
97
|
+
mock.module('svelte/reactivity', () => ({ ...originals.reactivity }));
|
|
98
|
+
for (const [name, descriptor] of saved) {
|
|
99
|
+
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
|
|
100
|
+
else delete globalThis[name];
|
|
101
|
+
}
|
|
102
|
+
saved = new Map();
|
|
103
|
+
window.happyDOM?.abort?.();
|
|
104
|
+
window = null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Flush microtasks and a macrotask: Svelte batches effects. */
|
|
108
|
+
export const settle = async (ms = 0) => {
|
|
109
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
110
|
+
await Promise.resolve();
|
|
111
|
+
};
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// W1: the host modules that talk to the page: api, svelte, toasts, language, session, the controller host.
|
|
2
|
+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
|
3
|
+
import { installBrowserEnv, settle, uninstallBrowserEnv } from './env.js';
|
|
4
|
+
|
|
5
|
+
let m = {};
|
|
6
|
+
|
|
7
|
+
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
8
|
+
|
|
9
|
+
/** @param {(url:string, init:any) => Response|Promise<Response>} handler */
|
|
10
|
+
function serve(handler) {
|
|
11
|
+
const calls = [];
|
|
12
|
+
m.config.configure({
|
|
13
|
+
apiBase: 'https://pano.test',
|
|
14
|
+
siteUrl: 'https://site.test',
|
|
15
|
+
urls: { 'market.order': '/shop/o/{id}', 'auth.login': '/login' },
|
|
16
|
+
fetch: async (url, init) => {
|
|
17
|
+
calls.push({ url: String(url), init });
|
|
18
|
+
return handler(String(url), init);
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
return calls;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
beforeAll(async () => {
|
|
25
|
+
await installBrowserEnv();
|
|
26
|
+
m.config = await import('../config.js');
|
|
27
|
+
m.api = await import('../api.js');
|
|
28
|
+
m.svelte = await import('../svelte.js');
|
|
29
|
+
m.toasts = await import('../toasts.js');
|
|
30
|
+
m.language = await import('../language.js');
|
|
31
|
+
m.session = await import('../session.js');
|
|
32
|
+
m.controllers = await import('../controllers.js');
|
|
33
|
+
m.runtime = await import('../runtime.js');
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
afterAll(() => uninstallBrowserEnv());
|
|
37
|
+
|
|
38
|
+
beforeEach(() => {
|
|
39
|
+
m.session.resetSession();
|
|
40
|
+
m.language.resetLanguage();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
afterEach(() => {
|
|
44
|
+
document.body.replaceChildren();
|
|
45
|
+
m.config.resetConfig();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe('config', () => {
|
|
49
|
+
test('csrf is off for a relative apiBase only', () => {
|
|
50
|
+
expect(m.config.configure({ apiBase: 'https://pano.test' }).csrf).toBe('auto');
|
|
51
|
+
expect(m.config.configure({ apiBase: '/pano' }).csrf).toBe('off');
|
|
52
|
+
expect(m.config.configure({ apiBase: '' }).csrf).toBe('auto');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('resolveUrl fills the URL map and prefixes the site', () => {
|
|
56
|
+
serve(() => json(200, {}));
|
|
57
|
+
expect(m.config.resolveUrl('market.order', { id: 7 })).toBe('https://site.test/shop/o/7');
|
|
58
|
+
expect(m.config.resolveUrl('/shop')).toBe('https://site.test/shop');
|
|
59
|
+
expect(m.config.resolveUrl('https://elsewhere.test/x')).toBe('https://elsewhere.test/x');
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe('ApiUtil', () => {
|
|
64
|
+
test('success: the parsed body; paths relative to /api/v1', async () => {
|
|
65
|
+
const calls = serve(() => json(200, { items: [1], page: { current: 1 } }));
|
|
66
|
+
const body = await m.api.ApiUtil.get({ path: '/posts?page=1' });
|
|
67
|
+
expect(body).toEqual({ items: [1], page: { current: 1 } });
|
|
68
|
+
expect(calls[0].url).toBe('https://pano.test/api/v1/posts?page=1');
|
|
69
|
+
expect(calls[0].init.credentials).toBe('include');
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('a path with the prefix means the same', async () => {
|
|
73
|
+
const calls = serve(() => json(200, {}));
|
|
74
|
+
await m.api.ApiUtil.get({ path: '/api/v1/posts' });
|
|
75
|
+
await m.api.ApiUtil.get({ path: '/api/posts' });
|
|
76
|
+
expect(calls.map((c) => c.url)).toEqual(['https://pano.test/api/v1/posts', 'https://pano.test/api/v1/posts']);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('the envelope of a failed answer comes back unchanged; no body is {}', async () => {
|
|
80
|
+
serve((url) => (url.endsWith('/nothing') ? new Response(null, { status: 204 }) : json(404, { error: { code: 'NOT_FOUND', message: 'no' } })));
|
|
81
|
+
expect(await m.api.ApiUtil.get({ path: '/x' })).toEqual({ error: { code: 'NOT_FOUND', message: 'no' } });
|
|
82
|
+
expect(await m.api.ApiUtil.delete({ path: '/nothing' })).toEqual({});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('network failure: { error: { code: NETWORK_ERROR } }', async () => {
|
|
86
|
+
m.config.configure({ apiBase: 'https://pano.test', fetch: async () => { throw new TypeError('offline'); } });
|
|
87
|
+
expect(await m.api.ApiUtil.get({ path: '/x' })).toEqual({ error: { code: 'NETWORK_ERROR' } });
|
|
88
|
+
expect(m.api.networkErrorBody).toEqual({ error: { code: m.api.NETWORK_ERROR } });
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test('post sends JSON and a token, a handler maps the body', async () => {
|
|
92
|
+
const calls = serve(() => json(200, { id: 3 }));
|
|
93
|
+
const out = await m.api.ApiUtil.post({ path: '/things', body: { a: 1 }, token: 'jwt', handler: (b) => b.id });
|
|
94
|
+
expect(out).toBe(3);
|
|
95
|
+
expect(calls[calls.length - 1].init.method).toBe('POST');
|
|
96
|
+
expect(calls[calls.length - 1].init.body).toBe('{"a":1}');
|
|
97
|
+
expect(calls[calls.length - 1].init.headers.Authorization).toBe('Bearer jwt');
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test('buildQueryParams drops empty values', () => {
|
|
101
|
+
expect(m.api.buildQueryParams({ a: 1, b: '', c: 'x y' })).toBe('?a=1&c=x%20y');
|
|
102
|
+
expect(m.api.buildQueryParams({})).toBe('');
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe('svelte module', () => {
|
|
107
|
+
test('goto raises a cancelable pano:navigate; cancelled does not navigate', async () => {
|
|
108
|
+
serve(() => json(200, {}));
|
|
109
|
+
const navigated = [];
|
|
110
|
+
m.config.configure({ navigate: (url) => navigated.push(url) });
|
|
111
|
+
|
|
112
|
+
const seen = [];
|
|
113
|
+
const listener = (e) => {
|
|
114
|
+
seen.push(e.detail.url);
|
|
115
|
+
if (e.detail.url.includes('blocked')) e.preventDefault();
|
|
116
|
+
};
|
|
117
|
+
document.addEventListener('pano:navigate', listener);
|
|
118
|
+
|
|
119
|
+
await m.svelte.goto('/shop');
|
|
120
|
+
await m.svelte.goto('/blocked');
|
|
121
|
+
await m.svelte.goto('market.order');
|
|
122
|
+
|
|
123
|
+
expect(seen).toEqual(['https://site.test/shop', 'https://site.test/blocked', 'https://site.test/shop/o/{id}']);
|
|
124
|
+
expect(navigated).toEqual(['https://site.test/shop', 'https://site.test/shop/o/{id}']);
|
|
125
|
+
document.removeEventListener('pano:navigate', listener);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('error() throws a WidgetError, base follows configure, page and navigating are readable', async () => {
|
|
129
|
+
serve(() => json(200, {}));
|
|
130
|
+
expect(() => m.svelte.error(404, 'missing')).toThrow('missing');
|
|
131
|
+
try {
|
|
132
|
+
m.svelte.error(418, 'tea');
|
|
133
|
+
} catch (e) {
|
|
134
|
+
expect(e.status).toBe(418);
|
|
135
|
+
expect(e.code).toBe('HTTP_418');
|
|
136
|
+
}
|
|
137
|
+
expect(m.svelte.browser).toBe(true);
|
|
138
|
+
expect(m.svelte.base).toBe('https://site.test');
|
|
139
|
+
|
|
140
|
+
const { get } = await import('svelte/store');
|
|
141
|
+
expect(get(m.svelte.page).url.href).toBe('https://site.test/page');
|
|
142
|
+
expect(get(m.svelte.page).params).toEqual({});
|
|
143
|
+
expect(get(m.svelte.navigating)).toBeNull();
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
describe('toasts', () => {
|
|
148
|
+
test('pano:toast is cancelable; uncancelled it shows in one shared <pano-toasts>', async () => {
|
|
149
|
+
serve(() => json(200, {}));
|
|
150
|
+
const events = [];
|
|
151
|
+
const listener = (e) => events.push(e.detail);
|
|
152
|
+
document.addEventListener('pano:toast', listener);
|
|
153
|
+
|
|
154
|
+
await m.toasts.showToast('Saved', {}, undefined, { variant: 'success' });
|
|
155
|
+
await m.toasts.showToast('Again');
|
|
156
|
+
|
|
157
|
+
expect(events.map((d) => d.variant)).toEqual(['success', null]);
|
|
158
|
+
expect(document.querySelectorAll('pano-toasts')).toHaveLength(1);
|
|
159
|
+
const items = document.querySelector('pano-toasts').shadowRoot.querySelectorAll('.toast');
|
|
160
|
+
expect(items).toHaveLength(2);
|
|
161
|
+
expect(items[0].textContent).toBe('Saved');
|
|
162
|
+
|
|
163
|
+
const cancel = (e) => e.preventDefault();
|
|
164
|
+
document.addEventListener('pano:toast', cancel);
|
|
165
|
+
await m.toasts.showToast('Hidden');
|
|
166
|
+
expect(document.querySelector('pano-toasts').shadowRoot.querySelectorAll('.toast')).toHaveLength(2);
|
|
167
|
+
|
|
168
|
+
document.removeEventListener('pano:toast', cancel);
|
|
169
|
+
document.removeEventListener('pano:toast', listener);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test('limitTitle', () => {
|
|
173
|
+
expect(m.toasts.limitTitle('x'.repeat(40))).toBe(`${'x'.repeat(32)}...`);
|
|
174
|
+
expect(m.toasts.limitTitle('short')).toBe('short');
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
describe('language', () => {
|
|
179
|
+
test('text from the core THEME endpoint and the plugin endpoint, each fetched once', async () => {
|
|
180
|
+
const calls = serve((url) => {
|
|
181
|
+
if (url.endsWith('/api/v1/locales')) return json(200, { items: [{ code: 'en-US' }, { code: 'tr-TR' }] });
|
|
182
|
+
if (url.endsWith('/locales/tr-TR/translations/types/THEME')) return json(200, { components: { 'no-content': { text: 'Icerik yok' } } });
|
|
183
|
+
if (url.endsWith('/locales/en-US/translations/types/THEME')) return json(200, { components: { 'no-content': { text: 'No content' } } });
|
|
184
|
+
if (url.endsWith('/plugins/pano-plugin-market/_/translations/tr-TR')) return json(200, { locale: 'tr-TR', translations: { goal: { title: 'Hedef' } } });
|
|
185
|
+
return json(404, { error: { code: 'NOT_FOUND' } });
|
|
186
|
+
});
|
|
187
|
+
m.config.configure({ locale: 'tr-TR' });
|
|
188
|
+
|
|
189
|
+
await m.language.ensureLanguage();
|
|
190
|
+
await m.language.ensureLanguage();
|
|
191
|
+
await m.language.loadPluginTranslations('pano-plugin-market', 'tr-TR');
|
|
192
|
+
await m.language.loadPluginTranslations('pano-plugin-market', 'tr-TR');
|
|
193
|
+
|
|
194
|
+
const { get } = await import('svelte/store');
|
|
195
|
+
expect(get(m.language.currentLanguage).code).toBe('tr-TR');
|
|
196
|
+
expect(get(m.language._)('components.no-content.text')).toBe('Icerik yok');
|
|
197
|
+
expect(get(m.language._)('plugins.pano-plugin-market.goal.title')).toBe('Hedef');
|
|
198
|
+
|
|
199
|
+
expect(calls.filter((c) => c.url.endsWith('/locales/tr-TR/translations/types/THEME'))).toHaveLength(1);
|
|
200
|
+
expect(calls.filter((c) => c.url.includes('/_/translations/'))).toHaveLength(1);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
test('init works when the API is down: the key is shown', async () => {
|
|
204
|
+
serve(() => json(500, { error: { code: 'INTERNAL' } }));
|
|
205
|
+
await m.language.ensureLanguage();
|
|
206
|
+
expect(m.language.translate('missing.key', 'Fallback')).toBe('Fallback');
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
describe('session probe', () => {
|
|
211
|
+
test('logged in: the user and token; anonymous and failure: a guest, never an error; once per page', async () => {
|
|
212
|
+
const calls = serve(() => json(200, { username: 'steve', panelAccess: false, csrfToken: 'tok' }));
|
|
213
|
+
const changes = [];
|
|
214
|
+
m.session.onSession((s) => changes.push(s.user?.username ?? null));
|
|
215
|
+
|
|
216
|
+
await m.session.ensureSession();
|
|
217
|
+
await m.session.ensureSession();
|
|
218
|
+
expect(calls.filter((c) => c.url.endsWith('/auth/credentials'))).toHaveLength(1);
|
|
219
|
+
expect(m.session.getSession()).toEqual({ user: { username: 'steve', panelAccess: false }, csrfToken: 'tok' });
|
|
220
|
+
expect(changes).toEqual(['steve']);
|
|
221
|
+
|
|
222
|
+
m.session.resetSession();
|
|
223
|
+
serve(() => json(401, { error: { code: 'NOT_LOGGED_IN' } }));
|
|
224
|
+
expect((await m.session.ensureSession()).user).toBeNull();
|
|
225
|
+
|
|
226
|
+
m.session.resetSession();
|
|
227
|
+
m.config.configure({ fetch: async () => { throw new Error('down'); } });
|
|
228
|
+
expect((await m.session.ensureSession()).user).toBeNull();
|
|
229
|
+
});
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
describe('controller host', () => {
|
|
233
|
+
test('request goes to the page client in the body shape; session, locale, toast, navigate, storage, urls', async () => {
|
|
234
|
+
const calls = serve((url) => json(200, { ok: url }));
|
|
235
|
+
m.config.configure({ locale: 'tr-TR', navigate: (u) => calls.push({ navigated: u }) });
|
|
236
|
+
const host = m.controllers.createWidgetHost();
|
|
237
|
+
|
|
238
|
+
expect(host.baseUrl).toBe('https://pano.test');
|
|
239
|
+
expect(await host.request({ method: 'GET', path: '/widgets', query: { a: 1 } })).toEqual({ ok: 'https://pano.test/api/v1/widgets?a=1' });
|
|
240
|
+
expect(host.session()).toEqual({ user: null, csrfToken: null });
|
|
241
|
+
expect(host.locale()).toBe('tr-TR');
|
|
242
|
+
expect(host.feature('x')).toBe(false);
|
|
243
|
+
expect(host.loginUrl('/cart')).toBe('https://site.test/login?redirect=%2Fcart');
|
|
244
|
+
expect(host.registerUrl()).toBe('https://site.test/register');
|
|
245
|
+
expect(host.storage('local')).not.toBeNull();
|
|
246
|
+
|
|
247
|
+
host.navigate('/shop');
|
|
248
|
+
await settle(5);
|
|
249
|
+
expect(calls.some((c) => c.navigated === 'https://site.test/shop')).toBe(true);
|
|
250
|
+
});
|
|
251
|
+
});
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// W1: every name an SDK facade exports exists in the widget host (doc 06 section 3.2), for every facade under packages/sdk/src.
|
|
2
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { installBrowserEnv, uninstallBrowserEnv } from './env.js';
|
|
7
|
+
|
|
8
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const hostSrc = resolve(here, '..');
|
|
10
|
+
const sdkDir = resolve(here, '../../../sdk');
|
|
11
|
+
const sdkPackage = JSON.parse(readFileSync(join(sdkDir, 'package.json'), 'utf8'));
|
|
12
|
+
|
|
13
|
+
// exports that are not facades: build output, the engine's core files, package.json
|
|
14
|
+
const NOT_FACADES = (key) => key === './package.json' || key.startsWith('./build/') || key.startsWith('./core/');
|
|
15
|
+
|
|
16
|
+
/** A value that answers every property read and call: stands in for the theme's context while a facade module evaluates. */
|
|
17
|
+
const deep = () => new Proxy(function () {}, { get: (_t, key) => (key === 'then' ? undefined : deep()), apply: () => deep() });
|
|
18
|
+
|
|
19
|
+
const facades = Object.entries(sdkPackage.exports)
|
|
20
|
+
.filter(([key]) => !NOT_FACADES(key))
|
|
21
|
+
.map(([key, value]) => ({
|
|
22
|
+
key,
|
|
23
|
+
specifier: key === '.' ? '@panomc/sdk' : `@panomc/sdk/${key.slice(2)}`,
|
|
24
|
+
file: join(sdkDir, (typeof value === 'string' ? value : (value.default ?? value.svelte)).replace(/^\.\//, '')),
|
|
25
|
+
}));
|
|
26
|
+
|
|
27
|
+
let host;
|
|
28
|
+
let SPECIFIER_MODULES;
|
|
29
|
+
|
|
30
|
+
beforeAll(async () => {
|
|
31
|
+
await installBrowserEnv();
|
|
32
|
+
globalThis.__PANO_CONTEXT__ = { context: deep(), listeners: [] };
|
|
33
|
+
host = await import('../index.js');
|
|
34
|
+
SPECIFIER_MODULES = host.SPECIFIER_MODULES;
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
afterAll(() => {
|
|
38
|
+
delete globalThis.__PANO_CONTEXT__;
|
|
39
|
+
uninstallBrowserEnv();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
describe('export parity with the SDK facades', () => {
|
|
43
|
+
test('the SDK still has the facades this test knows', () => {
|
|
44
|
+
const specifiers = facades.map((f) => f.specifier);
|
|
45
|
+
for (const must of ['@panomc/sdk', '@panomc/sdk/svelte', '@panomc/sdk/views', '@panomc/sdk/controllers', '@panomc/sdk/toasts']) {
|
|
46
|
+
expect(specifiers).toContain(must);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('every SDK facade has a host module, and no host module is for a facade that is gone', () => {
|
|
51
|
+
expect(Object.keys(SPECIFIER_MODULES).sort()).toEqual(facades.map((f) => f.specifier).sort());
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
for (const facade of facades) {
|
|
55
|
+
test(`${facade.specifier} -> every export is present`, async () => {
|
|
56
|
+
const sdk = await import(facade.file);
|
|
57
|
+
const module = await import(join(hostSrc, SPECIFIER_MODULES[facade.specifier]));
|
|
58
|
+
|
|
59
|
+
expect(Object.keys(sdk).length).toBeGreaterThan(0);
|
|
60
|
+
const missing = Object.keys(sdk).filter((name) => !(name in module));
|
|
61
|
+
expect(missing).toEqual([]);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
test('the names of the work order are really there', async () => {
|
|
66
|
+
const names = {
|
|
67
|
+
'svelte.js': ['browser', 'base', 'page', 'goto', 'redirect', 'error', 'invalidate', 'invalidateAll', 'navigating'],
|
|
68
|
+
'language.js': ['_', 'currentLanguage', 'changeLanguage', 'languageLoading', 'Languages', 'init', 'getAcceptedLanguage', 'loadLanguage', 'getLanguageByLocale'],
|
|
69
|
+
'toasts.js': ['showToast', 'limitTitle'],
|
|
70
|
+
'api.js': ['ApiUtil', 'NETWORK_ERROR', 'networkErrorBody', 'buildQueryParams', 'createPluginApi'],
|
|
71
|
+
'controllers.js': ['plugin', 'useController', 'reactive'],
|
|
72
|
+
'views.js': ['createViewProxy'],
|
|
73
|
+
'index.js': ['viewComponent', 'getPanoContext', 'PanoPlugin', 'defineWidget'],
|
|
74
|
+
};
|
|
75
|
+
for (const [file, list] of Object.entries(names)) {
|
|
76
|
+
const module = await import(join(hostSrc, file));
|
|
77
|
+
for (const name of list) expect(name in module).toBe(true);
|
|
78
|
+
}
|
|
79
|
+
const components = await import(join(hostSrc, 'components/index.js'));
|
|
80
|
+
for (const name of ['PlayerHead', 'NoContent', 'Date', 'Toast', 'PageTitle', 'PageActions', 'Pagination', 'PluginBlock', 'PluginSlot']) {
|
|
81
|
+
expect(typeof components[name]).toBe('function');
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('createPluginApi has the contract of @panomc/sdk/utils/api', async () => {
|
|
86
|
+
const { createPluginApi } = await import(join(hostSrc, 'api.js'));
|
|
87
|
+
|
|
88
|
+
expect(() => createPluginApi('market/x')).toThrow(/full plugin id/);
|
|
89
|
+
expect(() => createPluginApi(undefined)).toThrow(/full plugin id/);
|
|
90
|
+
|
|
91
|
+
const api = createPluginApi('pano-plugin-market');
|
|
92
|
+
for (const scope of [api, api.panel]) {
|
|
93
|
+
for (const method of ['get', 'post', 'put', 'delete', 'customRequest']) expect(typeof scope[method]).toBe('function');
|
|
94
|
+
}
|
|
95
|
+
expect(await api.get({ path: '/api/v1/x' }).catch((e) => e.message)).toMatch(/must not start with \/api/);
|
|
96
|
+
expect(await api.panel.get({}).catch((e) => e.message)).toMatch(/must be a string/);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('createPluginApi calls the unversioned plugin namespace (decision 81)', async () => {
|
|
100
|
+
const { createPluginApi } = await import(join(hostSrc, 'api.js'));
|
|
101
|
+
const { configure, resetConfig } = await import(join(hostSrc, 'config.js'));
|
|
102
|
+
const calls = [];
|
|
103
|
+
configure({
|
|
104
|
+
apiBase: 'https://pano.test',
|
|
105
|
+
csrf: 'off',
|
|
106
|
+
fetch: async (url, init) => {
|
|
107
|
+
calls.push([init?.method ?? 'GET', String(url)]);
|
|
108
|
+
return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
try {
|
|
112
|
+
const api = createPluginApi('pano-plugin-market');
|
|
113
|
+
await api.get({ path: '/store/products' });
|
|
114
|
+
await api.panel.get({ path: '/products' });
|
|
115
|
+
} finally {
|
|
116
|
+
resetConfig();
|
|
117
|
+
}
|
|
118
|
+
expect(calls).toEqual([
|
|
119
|
+
['GET', 'https://pano.test/api/plugins/pano-plugin-market/store/products'],
|
|
120
|
+
['GET', 'https://pano.test/api/plugins/pano-plugin-market/panel/products'],
|
|
121
|
+
]);
|
|
122
|
+
});
|
|
123
|
+
});
|
package/src/api.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// `@panomc/sdk/utils/api` outside a theme (doc 06 section 3.2): `ApiUtil` over the page's `@panomc/client`.
|
|
2
|
+
// Paths are relative to `/api/v1`. The return value is the body shape of doc 04 section 9: the parsed body of a 2xx answer
|
|
3
|
+
// (`{}` when it has none), `{ error: { code, ... } }` for any other answer, `{ error: { code: 'NETWORK_ERROR' } }` when nothing arrived.
|
|
4
|
+
import { getClient, getConfig, pageFetch } from './config.js';
|
|
5
|
+
|
|
6
|
+
export const NETWORK_ERROR = 'NETWORK_ERROR';
|
|
7
|
+
export const networkErrorBody = Object.freeze({ error: Object.freeze({ code: NETWORK_ERROR }) });
|
|
8
|
+
|
|
9
|
+
/** Query string from an object; empty values are left out (same rule as the theme). */
|
|
10
|
+
export function buildQueryParams(params) {
|
|
11
|
+
const query = Object.keys(params ?? {})
|
|
12
|
+
.filter((key) => params[key])
|
|
13
|
+
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
|
14
|
+
.join('&');
|
|
15
|
+
return query === '' ? '' : `?${query}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* `/posts`, `posts`, `/api/v1/posts` and `/api/posts` all mean `/api/v1/posts`. A plugin's own path
|
|
20
|
+
* (`/api/plugins/<id>/...`, unversioned, decision 81) is kept as it is.
|
|
21
|
+
*/
|
|
22
|
+
function v1Path(path) {
|
|
23
|
+
const text = String(path ?? '');
|
|
24
|
+
if (/^\/api\/plugins\/[^/?#]+\/(?!_(?:[/?#]|$))[^?#]/.test(text)) return text;
|
|
25
|
+
if (/^\/plugins\/[^/?#]+\/(?!_(?:[/?#]|$))[^?#]/.test(text)) return `/api${text}`;
|
|
26
|
+
const rest = String(path ?? '').replace(/^\/?api(\/v1)?(?=\/|$)/, '');
|
|
27
|
+
return `/api/v1${rest.startsWith('/') || rest === '' ? '' : '/'}${rest}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The call behind `ApiUtil` and the controller host's `request`.
|
|
32
|
+
* @param {{ method?: string, path: string, query?: Record<string, any>, body?: any, headers?: Record<string,string>, blob?: boolean, signal?: AbortSignal }} r
|
|
33
|
+
*/
|
|
34
|
+
export async function hostRequest(r) {
|
|
35
|
+
const method = String(r?.method ?? 'GET').toUpperCase();
|
|
36
|
+
const path = v1Path(r?.path);
|
|
37
|
+
|
|
38
|
+
if (r?.blob && method === 'GET') {
|
|
39
|
+
try {
|
|
40
|
+
const url = `${getConfig().apiBase}${path}${buildQueryParams(r.query ?? {})}`;
|
|
41
|
+
const response = await pageFetch(url, { method, credentials: 'include', headers: r.headers, signal: r.signal });
|
|
42
|
+
if (response.ok) return await response.blob();
|
|
43
|
+
return { error: { code: 'UNKNOWN_ERROR', details: { status: response.status } } };
|
|
44
|
+
} catch {
|
|
45
|
+
return { error: { code: NETWORK_ERROR } };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const result = await getClient().request(
|
|
50
|
+
{ method, path },
|
|
51
|
+
{ query: r?.query, body: r?.body, headers: r?.headers, signal: r?.signal },
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
if (result.ok) return result.data === undefined || result.data === null ? {} : result.data;
|
|
55
|
+
if (result.error?.code === NETWORK_ERROR) return { error: { code: NETWORK_ERROR } };
|
|
56
|
+
return { error: result.error };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function finish(body, handler) {
|
|
60
|
+
return handler ? handler(body) : body;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function headersOf({ headers, token, csrfToken }) {
|
|
64
|
+
const out = { ...(headers ?? {}) };
|
|
65
|
+
if (token) out.Authorization = `Bearer ${token}`;
|
|
66
|
+
if (csrfToken) out['X-CSRF-Token'] = csrfToken;
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const ApiUtil = {
|
|
71
|
+
interceptors: {},
|
|
72
|
+
|
|
73
|
+
get({ path, query, headers, csrfToken, token, blob, handler }) {
|
|
74
|
+
return this.customRequest({ path, data: { method: 'GET', query, headers }, csrfToken, token, blob, handler });
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
post({ path, body, headers, csrfToken, token, blob, handler }) {
|
|
78
|
+
return this.customRequest({ path, data: { method: 'POST', body, headers }, csrfToken, token, blob, handler });
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
put({ path, body, headers, csrfToken, token, blob, handler }) {
|
|
82
|
+
return this.customRequest({ path, data: { method: 'PUT', body, headers }, csrfToken, token, blob, handler });
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
delete({ path, headers, csrfToken, token, blob, handler }) {
|
|
86
|
+
return this.customRequest({ path, data: { method: 'DELETE', headers }, csrfToken, token, blob, handler });
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
/** `request` (a SvelteKit load event) is accepted and ignored: a widget has none. */
|
|
90
|
+
async customRequest({ path, data = {}, csrfToken, token, blob, handler }) {
|
|
91
|
+
const body = await hostRequest({
|
|
92
|
+
method: data.method ?? 'GET',
|
|
93
|
+
path,
|
|
94
|
+
query: data.query,
|
|
95
|
+
body: data.body,
|
|
96
|
+
headers: headersOf({ headers: data.headers, token, csrfToken }),
|
|
97
|
+
blob,
|
|
98
|
+
});
|
|
99
|
+
return finish(body, handler);
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const PLUGIN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Plugin-scoped client with the contract of `createPluginApi` in `@panomc/sdk/utils/api` (doc 04 section 9):
|
|
107
|
+
* `createPluginApi('pano-plugin-market').get({ path: '/store/products' })` calls
|
|
108
|
+
* `/api/plugins/pano-plugin-market/store/products`, `.panel.get(...)` the `/api/plugins/<id>/panel/...` twin.
|
|
109
|
+
* Every method takes the options of the matching `ApiUtil` method. A path that starts with `/api` throws outside
|
|
110
|
+
* production, as it does in a theme.
|
|
111
|
+
*
|
|
112
|
+
* @param {string} pluginId the full plugin id (`pano-plugin-market`), never the short namespace
|
|
113
|
+
*/
|
|
114
|
+
export function createPluginApi(pluginId) {
|
|
115
|
+
if (typeof pluginId !== 'string' || !PLUGIN_ID_PATTERN.test(pluginId)) {
|
|
116
|
+
throw new Error(`[pano] createPluginApi needs the full plugin id, got ${JSON.stringify(pluginId)}`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const scoped = (prefix) => {
|
|
120
|
+
const wrap = (method) => async (options = {}) => {
|
|
121
|
+
if (typeof options.path !== 'string') throw new TypeError('[pano] api path must be a string');
|
|
122
|
+
|
|
123
|
+
const path = options.path.startsWith('/') ? options.path : `/${options.path}`;
|
|
124
|
+
|
|
125
|
+
if (!import.meta.env?.PROD && /^\/api(?:[/?#]|$)/.test(path)) {
|
|
126
|
+
throw new Error(`[pano] path must not start with /api: write '${path.replace(/^\/api/, '') || '/'}'`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return ApiUtil[method]({ ...options, path: `${prefix}${path}` });
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
get: wrap('get'),
|
|
134
|
+
post: wrap('post'),
|
|
135
|
+
put: wrap('put'),
|
|
136
|
+
delete: wrap('delete'),
|
|
137
|
+
customRequest: wrap('customRequest'),
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
return { ...scoped(`/api/plugins/${pluginId}`), panel: scoped(`/api/plugins/${pluginId}/panel`) };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export default ApiUtil;
|
package/src/auth.js
ADDED
package/src/component.js
ADDED