@egen-civitas/esm-embed-host 0.0.0-stage → 0.2.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 +25 -0
- package/README.md +31 -2
- package/dist/bus.d.ts +8 -0
- package/dist/bus.d.ts.map +1 -0
- package/dist/bus.js +64 -0
- package/dist/connection.d.ts +40 -0
- package/dist/connection.d.ts.map +1 -0
- package/dist/connection.js +366 -0
- package/dist/host.d.ts +45 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +587 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/navigation.d.ts +51 -0
- package/dist/navigation.d.ts.map +1 -0
- package/dist/navigation.js +153 -0
- package/dist/providers.d.ts +101 -0
- package/dist/providers.d.ts.map +1 -0
- package/dist/providers.js +301 -0
- package/dist/table.d.ts +36 -0
- package/dist/table.d.ts.map +1 -0
- package/dist/table.js +676 -0
- package/package.json +71 -3
- package/src/__tests__/harness.ts +42 -0
- package/src/bus.ts +28 -0
- package/src/connection.ts +132 -0
- package/src/host.ts +231 -0
- package/src/index.ts +6 -0
- package/src/navigation.ts +163 -0
- package/src/providers.ts +127 -0
- package/src/table.ts +203 -0
package/package.json
CHANGED
|
@@ -1,6 +1,74 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@egen-civitas/esm-embed-host",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"license": "MPL-2.0",
|
|
5
|
+
"description": "Hôte (côté Shell/Core) des applications embarquées : iframe sécurisée, poignée de main v2, grants, fournisseurs de capacités, navigation partagée, compatibilité du pont 1.1.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"src",
|
|
11
|
+
"!src/**/*.test.*"
|
|
12
|
+
],
|
|
13
|
+
"module": "dist/index.js",
|
|
14
|
+
"types": "dist/index.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./package.json": {
|
|
21
|
+
"default": "./package.json"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"source": true,
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "cross-env TZ=UTC vitest run --passWithNoTests",
|
|
27
|
+
"test:watch": "cross-env TZ=UTC vitest watch --passWithNoTests",
|
|
28
|
+
"build": "rimraf dist && concurrently \"swc --strip-leading-paths src -d dist --ignore \\\"**/*.test.*\\\" --ignore \\\"**/__tests__/**\\\"\" \"tsc --project tsconfig.build.json\"",
|
|
29
|
+
"build:development": "rimraf dist && concurrently \"swc --strip-leading-paths src -d dist --ignore \\\"**/*.test.*\\\" --ignore \\\"**/__tests__/**\\\"\" \"tsc --project tsconfig.build.json\"",
|
|
30
|
+
"typescript": "tsc --project tsconfig.build.json",
|
|
31
|
+
"lint": "eslint src --ext ts,tsx"
|
|
32
|
+
},
|
|
33
|
+
"keywords": [
|
|
34
|
+
"egen",
|
|
35
|
+
"microfrontends",
|
|
36
|
+
"embed",
|
|
37
|
+
"iframe",
|
|
38
|
+
"host"
|
|
39
|
+
],
|
|
40
|
+
"directories": {
|
|
41
|
+
"lib": "dist",
|
|
42
|
+
"src": "src"
|
|
43
|
+
},
|
|
44
|
+
"browserslist": [
|
|
45
|
+
"extends browserslist-config-egen"
|
|
46
|
+
],
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/amourgit/Frontend-esm-framework.git",
|
|
50
|
+
"directory": "packages/framework/esm-embed-host"
|
|
51
|
+
},
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/amourgit/Frontend-esm-framework/issues"
|
|
54
|
+
},
|
|
55
|
+
"homepage": "https://github.com/amourgit/Frontend-esm-framework#readme",
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@egen-civitas/esm-embed-client": "^0.1.1",
|
|
61
|
+
"@swc/cli": "0.8.1",
|
|
62
|
+
"@swc/core": "1.15.21",
|
|
63
|
+
"@types/node": "^20",
|
|
64
|
+
"concurrently": "^9.2.1",
|
|
65
|
+
"cross-env": "^10.1.0",
|
|
66
|
+
"happy-dom": "^20.6.0",
|
|
67
|
+
"rimraf": "^6.1.3",
|
|
68
|
+
"typescript": "^5.8.3",
|
|
69
|
+
"vitest": "^4.1.2"
|
|
70
|
+
},
|
|
71
|
+
"dependencies": {
|
|
72
|
+
"@egen-civitas/esm-embed-protocol": "^0.2.0"
|
|
73
|
+
}
|
|
6
74
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { connectToEgen, type EgenClient } from '@egen-civitas/esm-embed-client';
|
|
2
|
+
import { createBus, HostConnection, type ConnectionOptions, type HostControls, type HostProviders } from '../index.js';
|
|
3
|
+
import { effectiveGrants, type ApprovedGrants, type EffectiveGrants } from '@egen-civitas/esm-embed-protocol';
|
|
4
|
+
|
|
5
|
+
export const ORIGIN = 'https://shell.exemple.org';
|
|
6
|
+
export const MODULE = '@acme/esm-demo-app';
|
|
7
|
+
|
|
8
|
+
/** Banc d'essai : un vrai `HostConnection` face au vrai client SDK, reliés par des fenêtres simulées et un vrai MessageChannel. */
|
|
9
|
+
export async function harness(opts: { providers?: HostProviders; approved?: ApprovedGrants; requested?: Parameters<typeof connectToEgen>[0]['capabilities']; controls?: Partial<HostControls>; grants?: EffectiveGrants; limits?: ConnectionOptions['limits'] } = {}) {
|
|
10
|
+
const appWindow = new EventTarget();
|
|
11
|
+
const hostWindow: any = {
|
|
12
|
+
postMessage: (message: unknown, targetOrigin: string) => {
|
|
13
|
+
// app → hôte : livré à la connexion comme le ferait le Shell après filtrage source/origine
|
|
14
|
+
queueMicrotask(() => conn.handle(message));
|
|
15
|
+
sentByApp.push({ message, targetOrigin });
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
const sentByApp: Array<{ message: any; targetOrigin: string }> = [];
|
|
19
|
+
const channel = createBus();
|
|
20
|
+
const controls: HostControls = { channel, ...opts.controls };
|
|
21
|
+
const conn: HostConnection = new HostConnection({
|
|
22
|
+
moduleName: MODULE,
|
|
23
|
+
grants: opts.grants ?? effectiveGrants(undefined, opts.approved ?? {}),
|
|
24
|
+
providers: opts.providers ?? {},
|
|
25
|
+
controls,
|
|
26
|
+
limits: { pingIntervalMs: 0, ...opts.limits },
|
|
27
|
+
post: (message, transfer) => {
|
|
28
|
+
const ev: any = new Event('message');
|
|
29
|
+
ev.data = message;
|
|
30
|
+
ev.origin = ORIGIN;
|
|
31
|
+
ev.source = hostWindow;
|
|
32
|
+
ev.ports = transfer ?? [];
|
|
33
|
+
queueMicrotask(() => appWindow.dispatchEvent(ev));
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
const client: EgenClient = await new Promise<EgenClient>((resolve) => {
|
|
37
|
+
connectToEgen({ moduleName: MODULE, hostOrigins: [ORIGIN], window: appWindow as any, host: hostWindow, capabilities: opts.requested, timeoutMs: 400 }).then(resolve);
|
|
38
|
+
});
|
|
39
|
+
return { client, conn, channel, sentByApp, close: () => (client.close(), conn.destroy()) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const tick = (ms = 20) => new Promise((r) => setTimeout(r, ms));
|
package/src/bus.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Unsub } from './providers.js';
|
|
2
|
+
|
|
3
|
+
/** Bus interne hôte → app (navigation.goto, lifecycle.visibility/focus). */
|
|
4
|
+
export interface Bus {
|
|
5
|
+
on(name: string, cb: (v: unknown) => void): Unsub;
|
|
6
|
+
emit(name: string, value?: unknown): void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function createBus(): Bus {
|
|
10
|
+
const map = new Map<string, Set<(v: unknown) => void>>();
|
|
11
|
+
return {
|
|
12
|
+
on(name, cb) {
|
|
13
|
+
let set = map.get(name);
|
|
14
|
+
if (!set) map.set(name, (set = new Set()));
|
|
15
|
+
set.add(cb);
|
|
16
|
+
return () => set!.delete(cb);
|
|
17
|
+
},
|
|
18
|
+
emit(name, value) {
|
|
19
|
+
for (const cb of [...(map.get(name) ?? [])]) {
|
|
20
|
+
try {
|
|
21
|
+
cb(value);
|
|
22
|
+
} catch {
|
|
23
|
+
/* un abonné fautif ne doit pas bloquer les autres */
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import {
|
|
2
|
+
EGEN_EMBED_PROTOCOL,
|
|
3
|
+
RpcEndpoint,
|
|
4
|
+
createNonce,
|
|
5
|
+
negotiateCapabilities,
|
|
6
|
+
negotiateProtocol,
|
|
7
|
+
parseConnect,
|
|
8
|
+
parseEnvelope,
|
|
9
|
+
validateCall,
|
|
10
|
+
wrapHandshake,
|
|
11
|
+
type CapabilityDenied,
|
|
12
|
+
type CapabilityGranted,
|
|
13
|
+
type EffectiveGrants,
|
|
14
|
+
type Limits,
|
|
15
|
+
} from '@egen-civitas/esm-embed-protocol';
|
|
16
|
+
import type { HostProviders } from './providers.js';
|
|
17
|
+
import { availableCapabilities, createCapabilityTable, type HostControls } from './table.js';
|
|
18
|
+
|
|
19
|
+
export type ConnectionState = 'idle' | 'hello' | 'connected' | 'closed';
|
|
20
|
+
|
|
21
|
+
export interface ConnectionOptions {
|
|
22
|
+
moduleName: string;
|
|
23
|
+
grants: EffectiveGrants;
|
|
24
|
+
providers: HostProviders;
|
|
25
|
+
controls: HostControls;
|
|
26
|
+
/** Envoi vers l'iframe (l'origine cible explicite est fixée par l'appelant). */
|
|
27
|
+
post(message: unknown, transfer?: Transferable[]): void;
|
|
28
|
+
limits?: Partial<Limits>;
|
|
29
|
+
hostVersion?: string;
|
|
30
|
+
onConnect?(granted: CapabilityGranted[], denied: CapabilityDenied[]): void;
|
|
31
|
+
onClose?(reason: string): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Connexion hôte ↔ une app embarquée, indépendante du DOM : l'appelant filtre déjà la source et l'origine
|
|
36
|
+
* (`event.source === iframe.contentWindow`, `event.origin === origine autorisée`) et lui remet `event.data`.
|
|
37
|
+
*/
|
|
38
|
+
export class HostConnection {
|
|
39
|
+
state: ConnectionState = 'idle';
|
|
40
|
+
private nonce?: string;
|
|
41
|
+
private rpc?: RpcEndpoint;
|
|
42
|
+
private cleanup?: () => void;
|
|
43
|
+
|
|
44
|
+
constructor(private readonly o: ConnectionOptions) {}
|
|
45
|
+
|
|
46
|
+
/** Nouvelle poignée de main (à chaque chargement de l'iframe) : ferme toute connexion précédente. */
|
|
47
|
+
hello(): void {
|
|
48
|
+
this.reset();
|
|
49
|
+
this.nonce = createNonce();
|
|
50
|
+
this.state = 'hello';
|
|
51
|
+
this.o.post(wrapHandshake(this.o.moduleName, { kind: 'hello', nonce: this.nonce, protocols: [EGEN_EMBED_PROTOCOL, 1], hostVersion: this.o.hostVersion }));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Traite un message de poignée de main v2 ; `true` si le message est de la famille v2 (consommé). */
|
|
55
|
+
handle(data: unknown): boolean {
|
|
56
|
+
const env = parseEnvelope(data);
|
|
57
|
+
if (!env || env.egen !== EGEN_EMBED_PROTOCOL || env.moduleName !== this.o.moduleName) return false;
|
|
58
|
+
const m = env.message;
|
|
59
|
+
if (m.kind === 'probe') {
|
|
60
|
+
if (this.state === 'idle') this.hello();
|
|
61
|
+
else if (this.state === 'hello' && this.nonce) this.o.post(wrapHandshake(this.o.moduleName, { kind: 'hello', nonce: this.nonce, protocols: [EGEN_EMBED_PROTOCOL, 1], hostVersion: this.o.hostVersion }));
|
|
62
|
+
} else if (m.kind === 'connect' && this.state === 'hello') {
|
|
63
|
+
const c = parseConnect(m);
|
|
64
|
+
if (!c || c.nonce !== this.nonce || negotiateProtocol(c.protocol, [EGEN_EMBED_PROTOCOL]) === null) return true;
|
|
65
|
+
this.open(c.requested);
|
|
66
|
+
}
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private open(requested: Parameters<typeof negotiateCapabilities>[0]): void {
|
|
71
|
+
const avail = availableCapabilities(this.o.providers);
|
|
72
|
+
const { granted: g0, denied: d0 } = negotiateCapabilities(requested, this.o.grants);
|
|
73
|
+
const denied: CapabilityDenied[] = [...d0];
|
|
74
|
+
const granted: CapabilityGranted[] = [];
|
|
75
|
+
for (const g of g0) {
|
|
76
|
+
if (avail.has(g.id)) granted.push(g);
|
|
77
|
+
else denied.push({ id: g.id, reason: 'UNAVAILABLE' });
|
|
78
|
+
}
|
|
79
|
+
const { table, subscribe, cleanup } = createCapabilityTable({
|
|
80
|
+
moduleName: this.o.moduleName,
|
|
81
|
+
granted,
|
|
82
|
+
providers: this.o.providers,
|
|
83
|
+
controls: this.o.controls,
|
|
84
|
+
callApp: (cap, method, args) => {
|
|
85
|
+
if (!this.rpc) return Promise.reject(new Error('non connecté'));
|
|
86
|
+
return this.rpc.call(cap, method, args);
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
const { port1, port2 } = new MessageChannel();
|
|
90
|
+
this.cleanup = cleanup;
|
|
91
|
+
this.rpc = new RpcEndpoint({
|
|
92
|
+
port: port1,
|
|
93
|
+
handlers: table,
|
|
94
|
+
onSubscribe: subscribe,
|
|
95
|
+
validate: (cap, method, args) => validateCall(cap, method, args, 'app-to-host'),
|
|
96
|
+
limits: this.o.limits,
|
|
97
|
+
onClose: (reason) => {
|
|
98
|
+
this.cleanup?.();
|
|
99
|
+
this.cleanup = undefined;
|
|
100
|
+
if (this.state !== 'closed') this.state = 'idle';
|
|
101
|
+
this.o.onClose?.(reason);
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
this.state = 'connected';
|
|
105
|
+
this.o.post(wrapHandshake(this.o.moduleName, { kind: 'port', nonce: this.nonce!, protocol: EGEN_EMBED_PROTOCOL, granted, denied, hostVersion: this.o.hostVersion }), [port2]);
|
|
106
|
+
this.o.onConnect?.(granted, denied);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Appel hôte → app (ex. `lifecycle.canLeave`) ; `undefined` si l'app n'est pas connectée en v2. */
|
|
110
|
+
async callApp<T = unknown>(cap: string, method: string, args: unknown[] = []): Promise<T | undefined> {
|
|
111
|
+
return this.rpc && !this.rpc.closed ? this.rpc.call<T>(cap, method, args) : undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
get connected(): boolean {
|
|
115
|
+
return this.state === 'connected' && !!this.rpc && !this.rpc.closed;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Ferme la connexion courante (rechargement de l'iframe) sans détruire l'objet. */
|
|
119
|
+
reset(): void {
|
|
120
|
+
this.rpc?.close();
|
|
121
|
+
this.rpc = undefined;
|
|
122
|
+
this.cleanup?.();
|
|
123
|
+
this.cleanup = undefined;
|
|
124
|
+
this.nonce = undefined;
|
|
125
|
+
if (this.state !== 'closed') this.state = 'idle';
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
destroy(): void {
|
|
129
|
+
this.reset();
|
|
130
|
+
this.state = 'closed';
|
|
131
|
+
}
|
|
132
|
+
}
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { DEFAULT_SESSION_FIELDS, pickFields, type CapabilityDenied, type CapabilityGranted, type EffectiveGrants, type Limits } from '@egen-civitas/esm-embed-protocol';
|
|
2
|
+
import { createBus } from './bus.js';
|
|
3
|
+
import { HostConnection } from './connection.js';
|
|
4
|
+
import { buildCoreUrl, buildEmbedSrc, coreSubpath, createRateLimiter, stripSensitive, toAppPath, toCorePath, normalizeAppPath, type NavigationOptions } from './navigation.js';
|
|
5
|
+
import type { HostProviders, Unsub } from './providers.js';
|
|
6
|
+
import type { HostControls } from './table.js';
|
|
7
|
+
|
|
8
|
+
export interface EmbedHostOptions {
|
|
9
|
+
/** Nom du module (= `name` du manifeste). */
|
|
10
|
+
moduleName: string;
|
|
11
|
+
/** URL de base de l'application embarquée. */
|
|
12
|
+
src: string;
|
|
13
|
+
/** Origine autorisée (défaut : origine de `src`). Jamais `*`. */
|
|
14
|
+
allowedOrigin?: string;
|
|
15
|
+
/** Grants effectifs (`effectiveGrants(manifeste.capabilities, approuvés)`). */
|
|
16
|
+
grants: EffectiveGrants;
|
|
17
|
+
providers: HostProviders;
|
|
18
|
+
/** Attribut `sandbox` (défaut : scripts, même origine, formulaires, popups). */
|
|
19
|
+
sandbox?: string;
|
|
20
|
+
title?: string;
|
|
21
|
+
minHeight?: number;
|
|
22
|
+
/** Navigation partagée Core ↔ app (URL du Core = source de vérité). Absent ou `none` : opaque. */
|
|
23
|
+
navigation?: NavigationOptions;
|
|
24
|
+
/** Navigation demandée par l'app vers le Core (défaut : `singleSpaNavigate`). */
|
|
25
|
+
onNavigate?: (to: string) => void;
|
|
26
|
+
limits?: Partial<Limits>;
|
|
27
|
+
hostVersion?: string;
|
|
28
|
+
/** Accepter aussi les apps qui parlent encore le pont 1.1 (défaut : oui). */
|
|
29
|
+
legacy?: boolean;
|
|
30
|
+
window?: Window;
|
|
31
|
+
onConnect?(granted: CapabilityGranted[], denied: CapabilityDenied[]): void;
|
|
32
|
+
onClose?(reason: string): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface EmbedHost {
|
|
36
|
+
readonly iframe: HTMLIFrameElement;
|
|
37
|
+
readonly connection: HostConnection;
|
|
38
|
+
mount(container: Element): void;
|
|
39
|
+
/** L'app accepte-t-elle qu'on la quitte ? `true` si non connectée, sans réponse, ou en cas d'erreur (on ne piège jamais l'utilisateur). */
|
|
40
|
+
canLeave(timeoutMs?: number): Promise<boolean>;
|
|
41
|
+
destroy(): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const DEFAULT_SANDBOX = 'allow-scripts allow-same-origin allow-forms allow-popups';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Hôte d'une app embarquée : iframe sécurisée, poignée de main v2 (`HostConnection`), navigation partagée,
|
|
48
|
+
* événements de cycle de vie, et pont 1.1 pour les apps qui ne parlent pas encore le protocole 2.
|
|
49
|
+
* Sécurité : messages acceptés seulement de l'iframe elle-même ET de l'origine autorisée ; envoi toujours avec une origine explicite.
|
|
50
|
+
*/
|
|
51
|
+
export function createEmbedHost(opts: EmbedHostOptions): EmbedHost {
|
|
52
|
+
const win: Window = opts.window ?? window;
|
|
53
|
+
const doc = win.document;
|
|
54
|
+
const nav = opts.navigation && (opts.navigation.mode ?? 'history') !== 'none' ? { ...opts.navigation, mode: opts.navigation.mode ?? ('history' as const) } : undefined;
|
|
55
|
+
const spaBase = (): string => (win as any).getEgenSpaBase?.() ?? '/';
|
|
56
|
+
const currentCorePath = (): string | null => {
|
|
57
|
+
if (!nav) return null;
|
|
58
|
+
const sub = coreSubpath(win.location.pathname, spaBase(), nav.route);
|
|
59
|
+
return sub === null ? null : stripSensitive(sub + win.location.search + win.location.hash, nav.sensitiveParams);
|
|
60
|
+
};
|
|
61
|
+
let lastCorePath = currentCorePath() ?? '/';
|
|
62
|
+
const initialAppPath = nav ? (toAppPath(lastCorePath, nav) ?? '/') : '/';
|
|
63
|
+
const src = nav ? buildEmbedSrc(opts.src, initialAppPath, nav.mode) : opts.src;
|
|
64
|
+
const origin = opts.allowedOrigin ?? new URL(src, win.location.href).origin;
|
|
65
|
+
if (origin === '*' || origin === 'null') throw new Error('allowedOrigin invalide : une origine explicite est requise.');
|
|
66
|
+
const sandbox = opts.sandbox ?? DEFAULT_SANDBOX;
|
|
67
|
+
if (origin === win.location.origin && /allow-scripts/.test(sandbox) && /allow-same-origin/.test(sandbox)) {
|
|
68
|
+
console.warn(`[egen] ${opts.moduleName} : application embarquée de même origine que le Shell avec « allow-scripts allow-same-origin » : le bac à sable est sans effet. Héberger l'application sur une autre origine (sous-domaine).`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const iframe = doc.createElement('iframe');
|
|
72
|
+
iframe.src = src;
|
|
73
|
+
iframe.title = opts.title ?? opts.moduleName;
|
|
74
|
+
iframe.setAttribute('sandbox', sandbox);
|
|
75
|
+
iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
|
|
76
|
+
iframe.setAttribute('data-egen-fill', '');
|
|
77
|
+
iframe.style.cssText = `width:100%;border:0;display:block;min-height:${opts.minHeight ?? 400}px`;
|
|
78
|
+
|
|
79
|
+
const channel = createBus();
|
|
80
|
+
const allowLocation = createRateLimiter();
|
|
81
|
+
const stop: Unsub[] = [];
|
|
82
|
+
let seq = 0;
|
|
83
|
+
let legacySeen = false;
|
|
84
|
+
let legacyReady = false;
|
|
85
|
+
|
|
86
|
+
const postRaw = (message: unknown, transfer?: Transferable[]) => iframe.contentWindow?.postMessage(message, origin, transfer);
|
|
87
|
+
const legacySend = (message: unknown) => postRaw({ egen: 1, moduleName: opts.moduleName, message });
|
|
88
|
+
|
|
89
|
+
/** Page courante annoncée par l'app → URL du Core (partagé entre le protocole 2 et le pont 1.1). */
|
|
90
|
+
const reportLocation = (path: unknown, o?: { replace?: boolean; title?: string }) => {
|
|
91
|
+
if (!nav || !allowLocation()) return;
|
|
92
|
+
if (typeof o?.title === 'string') {
|
|
93
|
+
iframe.title = o.title.slice(0, 200);
|
|
94
|
+
nav.onTitle?.(iframe.title);
|
|
95
|
+
}
|
|
96
|
+
const corePath = toCorePath(path, nav);
|
|
97
|
+
if (!corePath || corePath === lastCorePath) return;
|
|
98
|
+
lastCorePath = corePath;
|
|
99
|
+
win.history[o?.replace ? 'replaceState' : 'pushState'](win.history.state, '', buildCoreUrl(spaBase(), nav.route, corePath));
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const controls: HostControls = {
|
|
103
|
+
channel,
|
|
104
|
+
report: (path, o) => reportLocation(path, o),
|
|
105
|
+
navigate: (to) => {
|
|
106
|
+
if (normalizeAppPath(to) === null) return;
|
|
107
|
+
(opts.onNavigate ?? ((t) => (win as any).singleSpaNavigate?.(spaBase() + t.replace(/^\//, ''))))(to);
|
|
108
|
+
},
|
|
109
|
+
setTitle: (t) => void (iframe.title = String(t).slice(0, 200)),
|
|
110
|
+
resize: (h) => {
|
|
111
|
+
if (Number.isFinite(h) && h >= 0) iframe.style.height = `${Math.min(Math.ceil(h), 100_000)}px`;
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const connection = new HostConnection({
|
|
116
|
+
moduleName: opts.moduleName,
|
|
117
|
+
grants: opts.grants,
|
|
118
|
+
providers: opts.providers,
|
|
119
|
+
controls,
|
|
120
|
+
post: postRaw,
|
|
121
|
+
limits: opts.limits,
|
|
122
|
+
hostVersion: opts.hostVersion,
|
|
123
|
+
onConnect: opts.onConnect,
|
|
124
|
+
onClose: opts.onClose,
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
const sessionFields = () => {
|
|
128
|
+
const f = opts.grants.session?.fields;
|
|
129
|
+
return Array.isArray(f) && f.length ? (f as string[]) : [...DEFAULT_SESSION_FIELDS];
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/** Pont 1.1 : mêmes services, ancien format. Inactif dès qu'une connexion v2 est ouverte. */
|
|
133
|
+
const handleLegacy = async (data: any) => {
|
|
134
|
+
if (opts.legacy === false || connection.connected) return;
|
|
135
|
+
if (!data || data.egen !== 1 || data.moduleName !== opts.moduleName || !data.message || typeof data.message.kind !== 'string') return;
|
|
136
|
+
const msg = data.message;
|
|
137
|
+
switch (msg.kind) {
|
|
138
|
+
case 'ready': {
|
|
139
|
+
legacySeen = true;
|
|
140
|
+
legacyReady = true;
|
|
141
|
+
const session = opts.providers.session ? pickFields(await opts.providers.session.get(), sessionFields()) : undefined;
|
|
142
|
+
const locale = opts.providers.locale ? await opts.providers.locale.get() : (win as any).i18next?.language;
|
|
143
|
+
legacySend({ kind: 'init', payload: { moduleName: opts.moduleName, locale, spaBase: spaBase(), session, navigation: nav ? { mode: nav.mode, route: nav.route } : undefined } });
|
|
144
|
+
break;
|
|
145
|
+
}
|
|
146
|
+
case 'navigate':
|
|
147
|
+
controls.navigate?.(msg.to);
|
|
148
|
+
break;
|
|
149
|
+
case 'resize':
|
|
150
|
+
controls.resize?.(msg.height);
|
|
151
|
+
break;
|
|
152
|
+
case 'title':
|
|
153
|
+
if (typeof msg.title === 'string') iframe.title = msg.title.slice(0, 200);
|
|
154
|
+
break;
|
|
155
|
+
case 'location':
|
|
156
|
+
legacySeen = true;
|
|
157
|
+
reportLocation(msg.path, { replace: !!msg.replace, title: msg.title });
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const onMessage = (event: MessageEvent) => {
|
|
163
|
+
if (event.source !== iframe.contentWindow || event.origin !== origin) return;
|
|
164
|
+
if (!connection.handle(event.data)) void handleLegacy(event.data);
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
iframe,
|
|
169
|
+
connection,
|
|
170
|
+
mount(container) {
|
|
171
|
+
win.addEventListener('message', onMessage as EventListener);
|
|
172
|
+
stop.push(() => win.removeEventListener('message', onMessage as EventListener));
|
|
173
|
+
|
|
174
|
+
const onLoad = () => connection.hello();
|
|
175
|
+
iframe.addEventListener('load', onLoad);
|
|
176
|
+
stop.push(() => iframe.removeEventListener('load', onLoad));
|
|
177
|
+
|
|
178
|
+
if (nav) {
|
|
179
|
+
const onCoreLocation = () => {
|
|
180
|
+
const cur = currentCorePath();
|
|
181
|
+
if (cur === null || cur === lastCorePath) return;
|
|
182
|
+
lastCorePath = cur;
|
|
183
|
+
const appPath = toAppPath(cur, nav);
|
|
184
|
+
if (!appPath) return;
|
|
185
|
+
if (connection.connected) channel.emit('goto', { path: appPath, seq: ++seq });
|
|
186
|
+
else if (legacySeen) legacySend({ kind: 'goto', path: appPath, seq: ++seq });
|
|
187
|
+
else iframe.src = buildEmbedSrc(opts.src, appPath, nav.mode);
|
|
188
|
+
};
|
|
189
|
+
win.addEventListener('single-spa:routing-event', onCoreLocation);
|
|
190
|
+
win.addEventListener('popstate', onCoreLocation);
|
|
191
|
+
stop.push(() => {
|
|
192
|
+
win.removeEventListener('single-spa:routing-event', onCoreLocation);
|
|
193
|
+
win.removeEventListener('popstate', onCoreLocation);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const onVisibility = () => channel.emit('visibility', !doc.hidden);
|
|
198
|
+
const onFocus = () => channel.emit('focus', true);
|
|
199
|
+
const onBlur = () => channel.emit('focus', false);
|
|
200
|
+
doc.addEventListener('visibilitychange', onVisibility);
|
|
201
|
+
win.addEventListener('focus', onFocus);
|
|
202
|
+
win.addEventListener('blur', onBlur);
|
|
203
|
+
stop.push(() => {
|
|
204
|
+
doc.removeEventListener('visibilitychange', onVisibility);
|
|
205
|
+
win.removeEventListener('focus', onFocus);
|
|
206
|
+
win.removeEventListener('blur', onBlur);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Pont 1.1 : session et langue poussées après `ready`.
|
|
210
|
+
const p = opts.providers;
|
|
211
|
+
if (p.session?.subscribe) stop.push(p.session.subscribe((s) => legacyReady && !connection.connected && legacySend({ kind: 'session', session: pickFields(s, sessionFields()) })));
|
|
212
|
+
if (p.locale?.subscribe) stop.push(p.locale.subscribe((l) => legacyReady && !connection.connected && l && legacySend({ kind: 'locale', locale: l })));
|
|
213
|
+
|
|
214
|
+
container.appendChild(iframe);
|
|
215
|
+
},
|
|
216
|
+
async canLeave(timeoutMs = 1500) {
|
|
217
|
+
if (!connection.connected) return true;
|
|
218
|
+
try {
|
|
219
|
+
const r = await Promise.race([connection.callApp<boolean>('lifecycle', 'canLeave'), new Promise<undefined>((res) => setTimeout(res, timeoutMs))]);
|
|
220
|
+
return r === undefined ? true : !!r;
|
|
221
|
+
} catch {
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
destroy() {
|
|
226
|
+
while (stop.length) stop.pop()!();
|
|
227
|
+
connection.destroy();
|
|
228
|
+
iframe.remove();
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|