@egen-civitas/esm-embed-testing 0.1.0 → 0.3.0
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/CHANGELOG.md +28 -0
- package/README.md +4 -4
- package/bin/egen-embed-check.mjs +33 -0
- package/dist/check.d.ts +18 -0
- package/dist/check.d.ts.map +1 -0
- package/dist/check.js +319 -0
- package/dist/conformance.js +78 -85
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/server.d.ts +0 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +14 -11
- package/dist/test-host.d.ts +6 -10
- package/dist/test-host.d.ts.map +1 -1
- package/dist/test-host.js +24 -41
- package/package.json +9 -4
- package/src/check.ts +77 -0
- package/src/conformance.ts +28 -28
- package/src/index.ts +1 -0
- package/src/server.ts +8 -10
- package/src/test-host.ts +22 -26
package/src/check.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { CAPABILITIES, patternCovers, validateManifest, type EmbedManifest } from '@egen-civitas/esm-embed-protocol';
|
|
2
|
+
|
|
3
|
+
export interface CheckIssue {
|
|
4
|
+
level: 'error' | 'warn' | 'info';
|
|
5
|
+
message: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface CheckOptions {
|
|
9
|
+
/** Manifeste `egen-app.json` déjà lu. */
|
|
10
|
+
manifest: unknown;
|
|
11
|
+
/** Origine du Shell EGEN (ex. `https://egen.exemple.org`) : active le contrôle d'intégration en iframe. */
|
|
12
|
+
shellOrigin?: string;
|
|
13
|
+
/** Interroge réellement l'URL de l'app (en-têtes `frame-ancestors`, `X-Frame-Options`). */
|
|
14
|
+
probe?: boolean;
|
|
15
|
+
allowInsecureLocalhost?: boolean;
|
|
16
|
+
fetchImpl?: typeof fetch;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Vérificateur d'app embarquée (`egen-embed-check`) : manifeste, hygiène des capacités demandées, intégrabilité en iframe. */
|
|
20
|
+
export async function checkEmbedApp(o: CheckOptions): Promise<CheckIssue[]> {
|
|
21
|
+
const issues: CheckIssue[] = [];
|
|
22
|
+
const add = (level: CheckIssue['level'], message: string) => issues.push({ level, message });
|
|
23
|
+
|
|
24
|
+
const r = validateManifest(o.manifest, { allowInsecureLocalhost: o.allowInsecureLocalhost });
|
|
25
|
+
if (!r.ok) {
|
|
26
|
+
for (const e of r.errors) add('error', e);
|
|
27
|
+
return issues;
|
|
28
|
+
}
|
|
29
|
+
const m: EmbedManifest = r.manifest;
|
|
30
|
+
const caps = m.capabilities as Record<string, Record<string, unknown>>;
|
|
31
|
+
|
|
32
|
+
const needApproval = Object.keys(caps).filter((id) => !CAPABILITIES[id as keyof typeof CAPABILITIES].defaultGrant);
|
|
33
|
+
if (needApproval.length) add('info', `Capacités à faire approuver par l'opérateur (grants) : ${needApproval.join(', ')}`);
|
|
34
|
+
|
|
35
|
+
const pub = caps.events?.publish;
|
|
36
|
+
if (Array.isArray(pub)) {
|
|
37
|
+
const own = `app.${m.route}.*`;
|
|
38
|
+
for (const p of pub) {
|
|
39
|
+
if (p === '*' || /^\*/.test(String(p))) add('error', `events.publish : le motif « ${p} » n'est pas supporté (nommer le préfixe, ex. ${own})`);
|
|
40
|
+
else if (!patternCovers(own, String(p).replace(/\.\*$/, '.x'))) add('warn', `events.publish : « ${p} » sort de l'espace conseillé ${own}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const tools = caps['ai-tools']?.tools;
|
|
44
|
+
if (Array.isArray(tools) && tools.some((t) => !String(t).includes('.'))) add('warn', 'ai-tools.tools : préférer des noms d’outils préfixés (ex. studio.apply) pour éviter les collisions');
|
|
45
|
+
|
|
46
|
+
const slots = [...new Set((m.extensions ?? []).map((e) => e.slot))];
|
|
47
|
+
if (slots.length) add('info', `Contributions d'extension : l'opérateur doit approuver les slots (extensions.contribute) : ${slots.join(', ')}`);
|
|
48
|
+
for (const e of m.extensions ?? []) if (e.view) add('info', `Extension « ${e.name} » : la vue ${e.view} sera affichée dans une iframe du Core (frame-ancestors à autoriser pour le Shell, hauteur via navigation.resize)`);
|
|
49
|
+
const discover = caps.extensions?.discover;
|
|
50
|
+
if (Array.isArray(discover) && discover.some((s) => s === '*')) add('error', "extensions.discover : le motif « * » n'est pas supporté (nommer les slots)");
|
|
51
|
+
|
|
52
|
+
if (m.technology === 'nextjs' && m.navigation.mode === 'none') add('info', 'Next.js avec navigation « none » : l’URL du Core ne reflétera pas la page courante (partage de lien, F5)');
|
|
53
|
+
|
|
54
|
+
if (o.probe) {
|
|
55
|
+
const f = o.fetchImpl ?? fetch;
|
|
56
|
+
try {
|
|
57
|
+
const res = await f(m.url, { redirect: 'manual', signal: AbortSignal.timeout(10_000) });
|
|
58
|
+
if (res.status >= 400) add('warn', `L'URL de l'app répond HTTP ${res.status}`);
|
|
59
|
+
if (res.status >= 300 && res.status < 400) add('info', `L'URL de l'app redirige (HTTP ${res.status}) : vérifier que la cible reste dans la même origine`);
|
|
60
|
+
const xfo = res.headers.get('x-frame-options');
|
|
61
|
+
const csp = res.headers.get('content-security-policy') ?? '';
|
|
62
|
+
const fa = /frame-ancestors\s+([^;]*)/i.exec(csp)?.[1]?.trim();
|
|
63
|
+
if (xfo && /deny|sameorigin/i.test(xfo) && !fa) add('error', `X-Frame-Options: ${xfo} interdit l'intégration en iframe par le Shell (utiliser CSP frame-ancestors)`);
|
|
64
|
+
else if (fa !== undefined) {
|
|
65
|
+
const tokens = fa.split(/\s+/);
|
|
66
|
+
if (o.shellOrigin && !tokens.includes('*') && !tokens.includes(o.shellOrigin)) add('error', `CSP frame-ancestors (${fa}) n'autorise pas le Shell ${o.shellOrigin}`);
|
|
67
|
+
if (tokens.includes('*')) add('warn', 'CSP frame-ancestors « * » : n’importe quel site peut intégrer l’app (clickjacking) ; nommer l’origine du Shell');
|
|
68
|
+
if (tokens.includes("'none'")) add('error', "CSP frame-ancestors 'none' : intégration impossible");
|
|
69
|
+
} else add('warn', 'Aucune restriction frame-ancestors : l’app peut être intégrée par n’importe quel site (clickjacking) ; limiter à l’origine du Shell');
|
|
70
|
+
} catch (e) {
|
|
71
|
+
add('warn', `URL de l'app injoignable (${(e as Error).message})`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return issues;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export const hasErrors = (issues: CheckIssue[]) => issues.some((i) => i.level === 'error');
|
package/src/conformance.ts
CHANGED
|
@@ -20,7 +20,7 @@ export function defineConformance(connect: ConnectFn, t: ConformanceApi): void {
|
|
|
20
20
|
describe('conformité protocole v2 (client)', () => {
|
|
21
21
|
it('poignée de main : connecté en protocole 2', async () => {
|
|
22
22
|
const sim = createTestHost();
|
|
23
|
-
const c = await connect({ ...sim.connectOptions, capabilities: ['
|
|
23
|
+
const c = await connect({ ...sim.connectOptions, capabilities: ['tenant'] });
|
|
24
24
|
expect(c.connected).toBe(true);
|
|
25
25
|
expect(c.protocol).toBe(2);
|
|
26
26
|
c.close();
|
|
@@ -32,7 +32,7 @@ export function defineConformance(connect: ConnectFn, t: ConformanceApi): void {
|
|
|
32
32
|
const silent = { postMessage: () => undefined };
|
|
33
33
|
const c = await connect({ ...sim.connectOptions, host: silent as any, timeoutMs: 80 });
|
|
34
34
|
expect(c.connected).toBe(false);
|
|
35
|
-
await expect(c.
|
|
35
|
+
await expect(c.tenant.get()).rejects.toMatchObject({ code: 'DENIED' });
|
|
36
36
|
sim.destroy();
|
|
37
37
|
});
|
|
38
38
|
|
|
@@ -50,54 +50,54 @@ export function defineConformance(connect: ConnectFn, t: ConformanceApi): void {
|
|
|
50
50
|
sim.destroy();
|
|
51
51
|
});
|
|
52
52
|
|
|
53
|
-
it('
|
|
54
|
-
const sim = createTestHost(
|
|
55
|
-
const c = await connect({ ...sim.connectOptions, capabilities: ['session'] });
|
|
56
|
-
|
|
57
|
-
expect(
|
|
58
|
-
expect(
|
|
53
|
+
it('règle d’or : identité, droits, thème et api ne sont pas des capacités du SDK', async () => {
|
|
54
|
+
const sim = createTestHost();
|
|
55
|
+
const c = await connect({ ...sim.connectOptions, capabilities: ['tenant', 'session', 'theme', 'permissions', 'api'] as any });
|
|
56
|
+
expect(c.has('tenant')).toBe(true);
|
|
57
|
+
expect(c.denied.map((d) => d.id).sort()).toEqual(['api', 'permissions', 'session', 'theme']);
|
|
58
|
+
expect(c.denied.every((d) => d.reason === 'UNKNOWN')).toBe(true);
|
|
59
59
|
c.close();
|
|
60
60
|
sim.destroy();
|
|
61
61
|
});
|
|
62
62
|
|
|
63
63
|
it('moindre privilège : capacité non approuvée refusée à la négociation et localement', async () => {
|
|
64
64
|
const sim = createTestHost();
|
|
65
|
-
const c = await connect({ ...sim.connectOptions, capabilities: ['
|
|
66
|
-
expect(c.has('
|
|
67
|
-
expect(c.denied.map((d) => d.id).sort()).toEqual(['
|
|
68
|
-
await expect(c.
|
|
69
|
-
expect(sim.calls.some((x) => x.cap === '
|
|
65
|
+
const c = await connect({ ...sim.connectOptions, capabilities: ['tenant', 'events', 'notifications'] });
|
|
66
|
+
expect(c.has('events')).toBe(false);
|
|
67
|
+
expect(c.denied.map((d) => d.id).sort()).toEqual(['events', 'notifications']);
|
|
68
|
+
await expect(c.notifications.show({ kind: 'info', title: 'x' })).rejects.toMatchObject({ code: 'DENIED' });
|
|
69
|
+
expect(sim.calls.some((x) => x.cap === 'notifications')).toBe(false);
|
|
70
70
|
c.close();
|
|
71
71
|
sim.destroy();
|
|
72
72
|
});
|
|
73
73
|
|
|
74
|
-
it('changements poussés par l’hôte (
|
|
75
|
-
const sim = createTestHost({
|
|
76
|
-
const c = await connect({ ...sim.connectOptions, capabilities: ['
|
|
77
|
-
const
|
|
78
|
-
await c.
|
|
79
|
-
sim.emit.
|
|
74
|
+
it('changements poussés par l’hôte (langue)', async () => {
|
|
75
|
+
const sim = createTestHost({ locale: 'fr' });
|
|
76
|
+
const c = await connect({ ...sim.connectOptions, capabilities: ['locale'] });
|
|
77
|
+
const seen: unknown[] = [];
|
|
78
|
+
await c.locale.onChange((x) => seen.push(x));
|
|
79
|
+
sim.emit.locale('en');
|
|
80
80
|
await tick();
|
|
81
|
-
expect(
|
|
81
|
+
expect(seen).toEqual(['en']);
|
|
82
82
|
c.close();
|
|
83
83
|
sim.destroy();
|
|
84
84
|
});
|
|
85
85
|
|
|
86
|
-
it('
|
|
87
|
-
const
|
|
88
|
-
const sim = createTestHost({
|
|
89
|
-
const c = await connect({ ...sim.connectOptions, capabilities: ['
|
|
90
|
-
await c.
|
|
91
|
-
expect(
|
|
86
|
+
it('extensions : découverte limitée aux slots approuvés', async () => {
|
|
87
|
+
const list = [{ name: 'nav-x', moduleName: '@egen/esm-x-app', meta: { label: 'X' } }];
|
|
88
|
+
const sim = createTestHost({ extensions: { 'topbar-nav-slot': list }, manifestCapabilities: { extensions: { discover: ['topbar-nav-slot'] } }, approved: { extensions: { discover: ['topbar-nav-slot'] } } });
|
|
89
|
+
const c = await connect({ ...sim.connectOptions, capabilities: ['extensions'] });
|
|
90
|
+
await expect(c.extensions.list('topbar-nav-slot')).resolves.toEqual(list);
|
|
91
|
+
await expect(c.extensions.list('shell-rail-left-slot')).rejects.toMatchObject({ code: 'DENIED' });
|
|
92
92
|
c.close();
|
|
93
93
|
sim.destroy();
|
|
94
94
|
});
|
|
95
95
|
|
|
96
96
|
it('fermeture : appels suivants rejetés', async () => {
|
|
97
97
|
const sim = createTestHost();
|
|
98
|
-
const c = await connect({ ...sim.connectOptions, capabilities: ['
|
|
98
|
+
const c = await connect({ ...sim.connectOptions, capabilities: ['tenant'] });
|
|
99
99
|
c.close();
|
|
100
|
-
await expect(c.
|
|
100
|
+
await expect(c.tenant.get()).rejects.toMatchObject({ code: 'DENIED' });
|
|
101
101
|
sim.destroy();
|
|
102
102
|
});
|
|
103
103
|
});
|
package/src/index.ts
CHANGED
package/src/server.ts
CHANGED
|
@@ -14,7 +14,6 @@ export interface SimulatorOptions {
|
|
|
14
14
|
manifest?: unknown;
|
|
15
15
|
/** Approuver toutes les capacités demandées (défaut) ou seulement celles « par défaut » (`strict`). */
|
|
16
16
|
strict?: boolean;
|
|
17
|
-
session?: Record<string, unknown>;
|
|
18
17
|
}
|
|
19
18
|
|
|
20
19
|
export interface Simulator {
|
|
@@ -52,7 +51,7 @@ export async function startSimulator(o: SimulatorOptions): Promise<Simulator> {
|
|
|
52
51
|
moduleName: manifest?.name ?? '@acme/esm-sim-app',
|
|
53
52
|
manifestCapabilities: manifest?.capabilities,
|
|
54
53
|
approved: approvedFor(manifest, !!o.strict),
|
|
55
|
-
|
|
54
|
+
extensions: { 'topbar-nav-slot': [{ name: 'nav-demo', moduleName: '@egen/esm-demo-app', order: 1, meta: { label: 'Démo', route: 'demo' } }] },
|
|
56
55
|
};
|
|
57
56
|
const roots: Record<string, string> = { protocol: pkgDist('@egen-civitas/esm-embed-protocol'), host: pkgDist('@egen-civitas/esm-embed-host') };
|
|
58
57
|
|
|
@@ -99,7 +98,7 @@ h1{font-size:14px;margin:0 0 8px}h2{font-size:12px;margin:12px 0 4px;text-transf
|
|
|
99
98
|
<aside><h1>Simulateur de Shell EGEN</h1>
|
|
100
99
|
<div id="info"></div>
|
|
101
100
|
<h2>Pousser vers l'app</h2>
|
|
102
|
-
<button id="
|
|
101
|
+
<button id="locale">Langue fr/en</button><button id="event">Événement core.sim.ping</button><button id="ext">Changer les extensions de topbar-nav-slot</button>
|
|
103
102
|
<h2>Notifications</h2><div id="toasts"></div>
|
|
104
103
|
<h2>Journal des échanges</h2><pre id="log"></pre></aside>
|
|
105
104
|
<script type="module">
|
|
@@ -109,17 +108,17 @@ const cfg = await (await fetch('/api/config')).json();
|
|
|
109
108
|
const $ = (id) => document.getElementById(id);
|
|
110
109
|
const log = (...a) => { $('log').textContent = new Date().toLocaleTimeString() + ' ' + a.map((x) => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\\n' + $('log').textContent; };
|
|
111
110
|
const watch = (v) => { const s = new Set(); return { get: () => v, subscribe: (cb) => (s.add(cb), () => s.delete(cb)), set: (n) => { v = n; s.forEach((f) => f(n)); } }; };
|
|
112
|
-
const
|
|
113
|
-
const tenant = watch({ id: 'sim-tenant' }), conf = watch({});
|
|
111
|
+
const locale = watch('fr'), tenant = watch({ id: 'sim-tenant' }), conf = watch({});
|
|
114
112
|
const topics = new Map();
|
|
113
|
+
const extState = new Map(Object.entries(cfg.extensions)), extSubs = new Map();
|
|
115
114
|
const wrap = (cap, p) => Object.fromEntries(Object.entries(p).map(([k, f]) => [k, typeof f === 'function' ? (...a) => { log('←', cap + '.' + k, a); return f(...a); } : f]));
|
|
116
115
|
const providers = {
|
|
117
|
-
|
|
118
|
-
flags: wrap('flags', { isEnabled: () => true }),
|
|
116
|
+
locale: wrap('locale', locale), tenant: wrap('tenant', tenant), config: wrap('config', conf),
|
|
117
|
+
flags: wrap('flags', { isEnabled: () => true }),
|
|
118
|
+
extensions: { list: (slot) => { log('← extensions.list', slot); return extState.get(slot) || []; }, subscribe: (slot, cb) => { const s = extSubs.get(slot) || new Set(); s.add(cb); extSubs.set(slot, s); return () => s.delete(cb); } },
|
|
119
119
|
events: { publish: (t, p, c) => { log('← events.publish', t, p, 'de', c.moduleName); (topics.get(t) || []).forEach((f) => f(p)); }, subscribe: (t, cb) => { log('← events.subscribe', t); const l = topics.get(t) || []; l.push(cb); topics.set(t, l); return () => topics.set(t, (topics.get(t) || []).filter((f) => f !== cb)); } },
|
|
120
120
|
notifications: { show: (n) => { log('← notifications.show', n); const d = document.createElement('div'); d.className = 'toast'; d.textContent = '[' + n.kind + '] ' + n.title + (n.subtitle ? ' — ' + n.subtitle : ''); $('toasts').prepend(d); } },
|
|
121
121
|
dialogs: { confirm: (d) => { log('← dialogs.confirm', d); return confirm(d.title + '\\n\\n' + d.message); } },
|
|
122
|
-
api: { fetch: async (r) => { log('← api.fetch', r); return { status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ simulated: true, request: r }) }; } },
|
|
123
122
|
telemetry: { log: (...a) => log('← telemetry.log', a.slice(0, 3)), metric: (...a) => log('← telemetry.metric', a.slice(0, 3)) },
|
|
124
123
|
aiTools: { register: (m, t) => log('← ai-tools.register', t.map((x) => x.name)), unregister: (m, n) => log('← ai-tools.unregister', n) },
|
|
125
124
|
};
|
|
@@ -127,8 +126,7 @@ const grants = effectiveGrants(cfg.manifestCapabilities, cfg.approved);
|
|
|
127
126
|
$('info').innerHTML = '<b>App</b> ' + cfg.app + '<br><b>Module</b> ' + cfg.moduleName + '<br><b>hostOrigins à déclarer dans l’app</b> <code>' + location.origin + '</code><br><b>Capacités accordées</b> ' + Object.keys(grants).join(', ');
|
|
128
127
|
const host = createEmbedHost({ moduleName: cfg.moduleName, src: cfg.app, grants, providers, onConnect: (g, d) => log('✔ connecté', { accordées: g.map((x) => x.id), refusées: d }), onClose: (r) => log('✖ fermé', r) });
|
|
129
128
|
host.mount($('stage'));
|
|
130
|
-
$('theme').onclick = () => { const t = theme.get(); const dark = t.mode !== 'dark'; theme.set({ mode: dark ? 'dark' : 'light', tokens: { ...t.tokens, '--background': dark ? '#0b0b0f' : '#ffffff', '--foreground': dark ? '#f5f5f5' : '#111111' } }); };
|
|
131
129
|
$('locale').onclick = () => locale.set(locale.get() === 'fr' ? 'en' : 'fr');
|
|
132
|
-
$('session').onclick = () => { const s = session.get(); session.set({ ...s, user: { ...s.user, display: 'Autre ' + Math.floor(Math.random() * 100) } }); };
|
|
133
130
|
$('event').onclick = () => (topics.get('core.sim.ping') || []).forEach((f) => f({ at: Date.now() }));
|
|
131
|
+
$('ext').onclick = () => { const n = [{ name: 'nav-' + Math.floor(Math.random() * 100), moduleName: '@egen/esm-demo-app', meta: { label: 'Nouvelle extension' } }]; extState.set('topbar-nav-slot', n); (extSubs.get('topbar-nav-slot') || []).forEach((f) => f(n)); };
|
|
134
132
|
</script></body></html>`;
|
package/src/test-host.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { effectiveGrants, type ApprovedGrants, type CapabilityId, type GrantConfig } from '@egen-civitas/esm-embed-protocol';
|
|
2
2
|
import type { ConnectOptions } from '@egen-civitas/esm-embed-client';
|
|
3
|
-
import { createBus, HostConnection, type
|
|
3
|
+
import { createBus, HostConnection, type ExtensionInfo, type HostProviders } from '@egen-civitas/esm-embed-host';
|
|
4
4
|
|
|
5
5
|
export interface TestHostOptions {
|
|
6
6
|
moduleName?: string;
|
|
@@ -10,15 +10,12 @@ export interface TestHostOptions {
|
|
|
10
10
|
manifestCapabilities?: Partial<Record<CapabilityId, GrantConfig>>;
|
|
11
11
|
/** Plafond fixé par l'opérateur (défaut : rien d'approuvé hors capacités « par défaut »). */
|
|
12
12
|
approved?: ApprovedGrants;
|
|
13
|
-
session?: Record<string, unknown>;
|
|
14
13
|
tenant?: { id: string | null };
|
|
15
14
|
locale?: string;
|
|
16
|
-
theme?: ThemeState;
|
|
17
15
|
config?: Record<string, unknown>;
|
|
18
16
|
flags?: Record<string, boolean>;
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
api?: (req: ApiRequest) => ApiResponse | Promise<ApiResponse>;
|
|
17
|
+
/** Extensions attachées à chaque slot (`{ 'topbar-nav-slot': [...] }`). */
|
|
18
|
+
extensions?: Record<string, ExtensionInfo[]>;
|
|
22
19
|
confirm?: boolean | ((d: { title: string; message: string; danger?: boolean }) => boolean);
|
|
23
20
|
}
|
|
24
21
|
|
|
@@ -39,10 +36,9 @@ export interface TestHost {
|
|
|
39
36
|
tools: Map<string, { description: string }>;
|
|
40
37
|
/** Pousse un changement vers l'app (comme le ferait le Core). */
|
|
41
38
|
emit: {
|
|
42
|
-
session(v: Record<string, unknown>): void;
|
|
43
39
|
tenant(v: { id: string | null }): void;
|
|
44
40
|
locale(v: string): void;
|
|
45
|
-
|
|
41
|
+
extensions(slot: string, list: ExtensionInfo[]): void;
|
|
46
42
|
config(v: Record<string, unknown>): void;
|
|
47
43
|
event(topic: string, payload?: unknown): void;
|
|
48
44
|
goto(path: string): void;
|
|
@@ -71,8 +67,8 @@ function watchable<T>(initial: T) {
|
|
|
71
67
|
* relié à votre app par de fausses fenêtres et un vrai `MessageChannel`. Aucun navigateur, aucun Core.
|
|
72
68
|
*
|
|
73
69
|
* ```ts
|
|
74
|
-
* const sim = createTestHost({
|
|
75
|
-
* const egen = await connectToEgen({ ...sim.connectOptions, capabilities: ['
|
|
70
|
+
* const sim = createTestHost({ locale: 'fr', tenant: { id: 'acme' } });
|
|
71
|
+
* const egen = await connectToEgen({ ...sim.connectOptions, capabilities: ['locale', 'tenant'] });
|
|
76
72
|
* ```
|
|
77
73
|
*/
|
|
78
74
|
export function createTestHost(o: TestHostOptions = {}): TestHost {
|
|
@@ -85,10 +81,10 @@ export function createTestHost(o: TestHostOptions = {}): TestHost {
|
|
|
85
81
|
const toolInvokers = new Map<string, (name: string, args: Record<string, unknown>) => Promise<unknown>>();
|
|
86
82
|
const log = (cap: string, method: string, ...args: unknown[]) => void calls.push({ cap, method, args });
|
|
87
83
|
|
|
88
|
-
const session = watchable<Record<string, unknown> | undefined>(o.session ?? { authenticated: true });
|
|
89
84
|
const tenant = watchable(o.tenant ?? { id: null });
|
|
90
85
|
const locale = watchable(o.locale ?? 'fr');
|
|
91
|
-
const
|
|
86
|
+
const extList = new Map<string, ExtensionInfo[]>(Object.entries(o.extensions ?? {}));
|
|
87
|
+
const extSubs = new Map<string, Set<(l: ExtensionInfo[]) => void>>();
|
|
92
88
|
const config = watchable(o.config ?? {});
|
|
93
89
|
const flagSubs = new Set<() => void>();
|
|
94
90
|
const eventSubs = new Map<string, Set<(p: unknown) => void>>();
|
|
@@ -103,10 +99,8 @@ export function createTestHost(o: TestHostOptions = {}): TestHost {
|
|
|
103
99
|
});
|
|
104
100
|
|
|
105
101
|
const providers: HostProviders = {
|
|
106
|
-
session: wrapWatch('session', session),
|
|
107
102
|
tenant: wrapWatch('tenant', tenant),
|
|
108
103
|
locale: wrapWatch('locale', locale),
|
|
109
|
-
theme: wrapWatch('theme', theme),
|
|
110
104
|
config: wrapWatch('config', config),
|
|
111
105
|
flags: {
|
|
112
106
|
isEnabled: (n) => {
|
|
@@ -115,10 +109,16 @@ export function createTestHost(o: TestHostOptions = {}): TestHost {
|
|
|
115
109
|
},
|
|
116
110
|
subscribe: (cb) => (flagSubs.add(cb), () => void flagSubs.delete(cb)),
|
|
117
111
|
},
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
log('
|
|
121
|
-
return
|
|
112
|
+
extensions: {
|
|
113
|
+
list: (slot) => {
|
|
114
|
+
log('extensions', 'list', slot);
|
|
115
|
+
return extList.get(slot) ?? [];
|
|
116
|
+
},
|
|
117
|
+
subscribe: (slot, cb) => {
|
|
118
|
+
let set = extSubs.get(slot);
|
|
119
|
+
if (!set) extSubs.set(slot, (set = new Set()));
|
|
120
|
+
set.add(cb);
|
|
121
|
+
return () => void set!.delete(cb);
|
|
122
122
|
},
|
|
123
123
|
},
|
|
124
124
|
events: {
|
|
@@ -145,12 +145,6 @@ export function createTestHost(o: TestHostOptions = {}): TestHost {
|
|
|
145
145
|
return typeof o.confirm === 'function' ? o.confirm(d) : (o.confirm ?? true);
|
|
146
146
|
},
|
|
147
147
|
},
|
|
148
|
-
api: {
|
|
149
|
-
fetch: async (req) => {
|
|
150
|
-
log('api', 'fetch', req);
|
|
151
|
-
return o.api ? o.api(req) : { status: 200, headers: { 'content-type': 'application/json' }, body: '{}' };
|
|
152
|
-
},
|
|
153
|
-
},
|
|
154
148
|
telemetry: { log: (l, m, c) => log('telemetry', 'log', l, m, c), metric: (n, v, t) => log('telemetry', 'metric', n, v, t) },
|
|
155
149
|
aiTools: {
|
|
156
150
|
register: (_m, list, invoke) => {
|
|
@@ -204,10 +198,12 @@ export function createTestHost(o: TestHostOptions = {}): TestHost {
|
|
|
204
198
|
published,
|
|
205
199
|
tools,
|
|
206
200
|
emit: {
|
|
207
|
-
session: (v) => session.set(v),
|
|
208
201
|
tenant: (v) => tenant.set(v),
|
|
209
202
|
locale: (v) => locale.set(v),
|
|
210
|
-
|
|
203
|
+
extensions: (slot, list) => {
|
|
204
|
+
extList.set(slot, list);
|
|
205
|
+
extSubs.get(slot)?.forEach((cb) => cb(list));
|
|
206
|
+
},
|
|
211
207
|
config: (v) => config.set(v),
|
|
212
208
|
event: (topic, payload) => eventSubs.get(topic)?.forEach((cb) => cb(payload)),
|
|
213
209
|
goto: (path) => channel.emit('goto', { path, seq: Date.now() }),
|