@egen-civitas/esm-embed-host 0.2.0 → 0.4.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 +33 -0
- package/README.md +6 -7
- package/dist/connection.d.ts +0 -1
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +4 -14
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +27 -84
- package/dist/providers.d.ts +15 -49
- package/dist/providers.d.ts.map +1 -1
- package/dist/providers.js +6 -300
- package/dist/table.d.ts +1 -4
- package/dist/table.d.ts.map +1 -1
- package/dist/table.js +38 -251
- package/package.json +3 -3
- package/src/connection.ts +1 -11
- package/src/host.ts +7 -11
- package/src/providers.ts +13 -88
- package/src/table.ts +23 -73
package/src/providers.ts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { EmbedError } from '@egen-civitas/esm-embed-protocol';
|
|
2
|
-
|
|
3
1
|
export type Unsub = () => void;
|
|
4
2
|
|
|
5
3
|
/** Valeur lisible et observable fournie par le Core. */
|
|
@@ -13,115 +11,42 @@ export interface CallerContext {
|
|
|
13
11
|
moduleName: string;
|
|
14
12
|
}
|
|
15
13
|
|
|
16
|
-
export interface ThemeState {
|
|
17
|
-
mode?: string;
|
|
18
|
-
tokens: Record<string, string>;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
14
|
export interface NotificationInput {
|
|
15
|
+
/** Clé de dédoublonnage facultative : un même `id` ne produit pas deux toasts rapprochés. */
|
|
16
|
+
id?: string;
|
|
22
17
|
kind: 'info' | 'success' | 'warning' | 'error';
|
|
23
18
|
title: string;
|
|
24
19
|
subtitle?: string;
|
|
25
20
|
timeoutMs?: number;
|
|
26
21
|
}
|
|
27
22
|
|
|
28
|
-
export interface
|
|
29
|
-
path?: string;
|
|
30
|
-
url?: string;
|
|
31
|
-
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
32
|
-
headers?: Record<string, string>;
|
|
33
|
-
body?: string;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface ApiResponse {
|
|
37
|
-
status: number;
|
|
38
|
-
headers: Record<string, string>;
|
|
39
|
-
body: string;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export interface AiToolDescriptor {
|
|
23
|
+
export interface ExtensionInfo {
|
|
43
24
|
name: string;
|
|
44
|
-
|
|
45
|
-
|
|
25
|
+
moduleName: string;
|
|
26
|
+
order?: number;
|
|
27
|
+
meta: Record<string, unknown>;
|
|
46
28
|
}
|
|
47
29
|
|
|
48
30
|
/**
|
|
49
31
|
* Services du Core mis à disposition des apps embarquées. Toute capacité sans fournisseur est
|
|
50
32
|
* automatiquement refusée à la négociation (`UNAVAILABLE`) : on ne promet que ce qu'on sait servir.
|
|
33
|
+
*
|
|
34
|
+
* Règle d'or (doc 17 §2) : seulement ce dont le Core est lui-même la source. Pas d'identité/session, de droits, de thème ni d'appels
|
|
35
|
+
* API relayés : l'app les obtient directement auprès de leurs sources (Keycloak, backends, service de thèmes).
|
|
51
36
|
*/
|
|
52
37
|
export interface HostProviders {
|
|
53
|
-
session?: Watchable<Record<string, unknown> | undefined>;
|
|
54
38
|
tenant?: Watchable<{ id: string | null }>;
|
|
55
39
|
locale?: Watchable<string>;
|
|
56
|
-
theme?: Watchable<ThemeState>;
|
|
57
40
|
config?: Watchable<Record<string, unknown>>;
|
|
58
41
|
flags?: { isEnabled(name: string): boolean | Promise<boolean>; subscribe?(cb: () => void): Unsub };
|
|
59
|
-
permissions?: { can(permission: string): boolean | Promise<boolean>; subscribe?(cb: () => void): Unsub };
|
|
60
42
|
events?: { publish(topic: string, payload: unknown, ctx: CallerContext): void; subscribe(topic: string, cb: (payload: unknown) => void): Unsub };
|
|
61
|
-
|
|
43
|
+
/** Affiche le toast dans l'interface du Core ; retourne `false` si non affiché (doublon, etc.). Le Core attribue le toast à son app d'origine. */
|
|
44
|
+
notifications?: { show(n: NotificationInput, ctx: CallerContext): void | boolean | Promise<void | boolean> };
|
|
62
45
|
dialogs?: { confirm(d: { title: string; message: string; danger?: boolean }, ctx: CallerContext): boolean | Promise<boolean> };
|
|
63
|
-
|
|
46
|
+
/** Extensions attachées à un slot du Core (apps internes, framework, autres apps) : métadonnées seulement, jamais le rendu. */
|
|
47
|
+
extensions?: { list(slot: string): ExtensionInfo[] | Promise<ExtensionInfo[]>; subscribe?(slot: string, cb: (list: ExtensionInfo[]) => void): Unsub };
|
|
64
48
|
telemetry?: {
|
|
65
49
|
log(level: 'debug' | 'info' | 'warn' | 'error', message: string, ctx: Record<string, unknown> | undefined, from: CallerContext): void;
|
|
66
50
|
metric(name: string, value: number, tags: Record<string, unknown> | undefined, from: CallerContext): void;
|
|
67
51
|
};
|
|
68
|
-
aiTools?: {
|
|
69
|
-
register(moduleName: string, tools: AiToolDescriptor[], invoke: (name: string, args: Record<string, unknown>) => Promise<unknown>): void;
|
|
70
|
-
unregister(moduleName: string, names: string[]): void;
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export interface FetchProviderOptions {
|
|
75
|
-
/** Base de l'API du Core (ex. `https://api.exemple.org/v1`) : résolution des `path`. */
|
|
76
|
-
baseUrl: string;
|
|
77
|
-
/** En-têtes d'authentification/tenant ajoutés aux appels `path` UNIQUEMENT (jamais aux `url` externes). */
|
|
78
|
-
getHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
|
|
79
|
-
fetchImpl?: typeof fetch;
|
|
80
|
-
timeoutMs?: number;
|
|
81
|
-
/** Taille maximale du corps de réponse (octets approximatifs). Défaut 200 000. */
|
|
82
|
-
maxResponseBytes?: number;
|
|
83
|
-
/** En-têtes de réponse exposés à l'app. Défaut : content-type, etag, cache-control, content-language. */
|
|
84
|
-
exposeResponseHeaders?: string[];
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Fournisseur `api.fetch` : la requête s'exécute côté Core. Le jeton ne quitte jamais le Core ;
|
|
89
|
-
* `path` → API du Core (cookies + en-têtes d'auth) ; `url` → hôte externe autorisé par le grant, sans cookies ni auth, sans redirection.
|
|
90
|
-
*/
|
|
91
|
-
export function createFetchApiProvider(o: FetchProviderOptions): NonNullable<HostProviders['api']> {
|
|
92
|
-
const doFetch = o.fetchImpl ?? ((...a: Parameters<typeof fetch>) => fetch(...a));
|
|
93
|
-
const maxBytes = o.maxResponseBytes ?? 200_000;
|
|
94
|
-
const expose = new Set((o.exposeResponseHeaders ?? ['content-type', 'etag', 'cache-control', 'content-language']).map((h) => h.toLowerCase()));
|
|
95
|
-
return {
|
|
96
|
-
async fetch(req) {
|
|
97
|
-
const internal = req.path !== undefined;
|
|
98
|
-
const target = internal ? o.baseUrl.replace(/\/+$/, '') + req.path : (req.url as string);
|
|
99
|
-
const headers: Record<string, string> = { ...(req.headers ?? {}) };
|
|
100
|
-
if (internal && o.getHeaders) Object.assign(headers, await o.getHeaders());
|
|
101
|
-
const ctrl = new AbortController();
|
|
102
|
-
const timer = setTimeout(() => ctrl.abort(), o.timeoutMs ?? 10_000);
|
|
103
|
-
try {
|
|
104
|
-
const res = await doFetch(target, {
|
|
105
|
-
method: req.method ?? 'GET',
|
|
106
|
-
headers,
|
|
107
|
-
body: req.body,
|
|
108
|
-
credentials: internal ? 'include' : 'omit',
|
|
109
|
-
redirect: internal ? 'follow' : 'error',
|
|
110
|
-
signal: ctrl.signal,
|
|
111
|
-
});
|
|
112
|
-
const body = await res.text();
|
|
113
|
-
if (body.length > maxBytes) throw new EmbedError('TOO_LARGE', 'Réponse trop volumineuse');
|
|
114
|
-
const outHeaders: Record<string, string> = {};
|
|
115
|
-
res.headers.forEach((v, k) => {
|
|
116
|
-
if (expose.has(k.toLowerCase())) outHeaders[k.toLowerCase()] = v;
|
|
117
|
-
});
|
|
118
|
-
return { status: res.status, headers: outHeaders, body };
|
|
119
|
-
} catch (e) {
|
|
120
|
-
if (e instanceof EmbedError) throw e;
|
|
121
|
-
throw new EmbedError('INTERNAL', ctrl.signal.aborted ? 'Délai dépassé' : 'Requête impossible');
|
|
122
|
-
} finally {
|
|
123
|
-
clearTimeout(timer);
|
|
124
|
-
}
|
|
125
|
-
},
|
|
126
|
-
};
|
|
127
52
|
}
|
package/src/table.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CAPABILITIES,
|
|
3
|
-
|
|
3
|
+
createSlidingLimiter,
|
|
4
|
+
notificationPolicy,
|
|
4
5
|
EmbedError,
|
|
5
|
-
|
|
6
|
-
pickFields,
|
|
6
|
+
slotAllowed,
|
|
7
7
|
topicAllowed,
|
|
8
8
|
type CapabilityGranted,
|
|
9
9
|
type CapabilityId,
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
type SubscribeHandler,
|
|
13
13
|
} from '@egen-civitas/esm-embed-protocol';
|
|
14
14
|
import type { Bus } from './bus.js';
|
|
15
|
-
import type {
|
|
15
|
+
import type { CallerContext, HostProviders } from './providers.js';
|
|
16
16
|
|
|
17
17
|
/** Actions du Shell pilotées par les capacités `navigation` et `lifecycle`. */
|
|
18
18
|
export interface HostControls {
|
|
@@ -29,18 +29,14 @@ export interface HostControls {
|
|
|
29
29
|
export function availableCapabilities(p: HostProviders): Set<CapabilityId> {
|
|
30
30
|
const s = new Set<CapabilityId>(['navigation', 'lifecycle', 'telemetry']);
|
|
31
31
|
const map: Array<[CapabilityId, unknown]> = [
|
|
32
|
-
['session', p.session],
|
|
33
32
|
['tenant', p.tenant],
|
|
34
33
|
['locale', p.locale],
|
|
35
|
-
['theme', p.theme],
|
|
36
34
|
['config', p.config],
|
|
37
35
|
['flags', p.flags],
|
|
38
|
-
['permissions', p.permissions],
|
|
39
36
|
['events', p.events],
|
|
40
37
|
['notifications', p.notifications],
|
|
41
38
|
['dialogs', p.dialogs],
|
|
42
|
-
['
|
|
43
|
-
['ai-tools', p.aiTools],
|
|
39
|
+
['extensions', p.extensions],
|
|
44
40
|
];
|
|
45
41
|
for (const [id, prov] of map) if (prov) s.add(id);
|
|
46
42
|
return s;
|
|
@@ -48,56 +44,29 @@ export function availableCapabilities(p: HostProviders): Set<CapabilityId> {
|
|
|
48
44
|
|
|
49
45
|
const list = (cfg: GrantConfig | undefined, key: string): string[] => (Array.isArray(cfg?.[key]) ? (cfg![key] as string[]) : []);
|
|
50
46
|
|
|
51
|
-
function normOrigin(u: string): string {
|
|
52
|
-
try {
|
|
53
|
-
return new URL(u).origin;
|
|
54
|
-
} catch {
|
|
55
|
-
return u;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
47
|
export interface TableOptions {
|
|
60
48
|
moduleName: string;
|
|
61
49
|
granted: CapabilityGranted[];
|
|
62
50
|
providers: HostProviders;
|
|
63
51
|
controls: HostControls;
|
|
64
|
-
/** Appel hôte → app (`ai-tools.invoke`). */
|
|
65
|
-
callApp: (cap: string, method: string, args: unknown[]) => Promise<unknown>;
|
|
66
52
|
}
|
|
67
53
|
|
|
68
54
|
/**
|
|
69
55
|
* Construit la table de dispatch FERMÉE d'une connexion : seules les capacités accordées (et servies) y figurent,
|
|
70
|
-
* chaque méthode applique son grant (
|
|
56
|
+
* chaque méthode applique son grant (sujets d'événements, slots découvrables, drapeaux).
|
|
71
57
|
*/
|
|
72
|
-
export function createCapabilityTable(o: TableOptions): { table: HandlerTable; subscribe: SubscribeHandler
|
|
58
|
+
export function createCapabilityTable(o: TableOptions): { table: HandlerTable; subscribe: SubscribeHandler } {
|
|
73
59
|
const { providers: p, controls: c } = o;
|
|
74
60
|
const ctx: CallerContext = { moduleName: o.moduleName };
|
|
75
61
|
const cfgOf = new Map(o.granted.map((g) => [g.id, g.config]));
|
|
76
62
|
const table: HandlerTable = {};
|
|
77
|
-
const registeredTools = new Set<string>();
|
|
78
63
|
|
|
79
|
-
const sessionFields = () => {
|
|
80
|
-
const f = list(cfgOf.get('session'), 'fields');
|
|
81
|
-
return f.length ? f : [...DEFAULT_SESSION_FIELDS];
|
|
82
|
-
};
|
|
83
|
-
const pick = (s: unknown) => pickFields(s, sessionFields());
|
|
84
64
|
const denied = (msg: string) => new EmbedError('DENIED', msg);
|
|
85
65
|
|
|
86
|
-
if (cfgOf.has('session') && p.session) table.session = { get: async () => pick(await p.session!.get()) };
|
|
87
66
|
if (cfgOf.has('tenant') && p.tenant) table.tenant = { get: async () => p.tenant!.get() };
|
|
88
67
|
if (cfgOf.has('locale') && p.locale) table.locale = { get: async () => p.locale!.get() };
|
|
89
|
-
if (cfgOf.has('theme') && p.theme) table.theme = { get: async () => p.theme!.get() };
|
|
90
68
|
if (cfgOf.has('config') && p.config) table.config = { get: async () => p.config!.get() };
|
|
91
69
|
|
|
92
|
-
if (cfgOf.has('permissions') && p.permissions) {
|
|
93
|
-
const probe = list(cfgOf.get('permissions'), 'probe');
|
|
94
|
-
table.permissions = {
|
|
95
|
-
can: async (perm: string) => {
|
|
96
|
-
if (!probe.includes(perm)) throw denied(`Permission non sondable : ${perm}`);
|
|
97
|
-
return !!(await p.permissions!.can(perm));
|
|
98
|
-
},
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
70
|
if (cfgOf.has('flags') && p.flags) {
|
|
102
71
|
const names = list(cfgOf.get('flags'), 'names');
|
|
103
72
|
table.flags = {
|
|
@@ -116,34 +85,24 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
|
|
|
116
85
|
},
|
|
117
86
|
};
|
|
118
87
|
}
|
|
119
|
-
if (cfgOf.has('notifications') && p.notifications)
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
fetch: async (req: ApiRequest) => {
|
|
128
|
-
if (req.url !== undefined && !hosts.includes(normOrigin(req.url))) throw denied("Hôte non autorisé par le grant de l'app");
|
|
129
|
-
// Sans liste de chemins (deny-by-default) une app ne peut PAS appeler l'API du Core avec la session de l'utilisateur.
|
|
130
|
-
if (req.path !== undefined && !pathAllowed(paths, req.path)) throw denied(`Chemin d'API non autorisé par le grant de l'app : ${req.path}`);
|
|
131
|
-
for (const h of Object.keys(req.headers ?? {})) if (!headers.includes(h.toLowerCase())) throw denied(`En-tête non autorisé : ${h}`);
|
|
132
|
-
return p.api!.fetch(req, ctx);
|
|
88
|
+
if (cfgOf.has('notifications') && p.notifications) {
|
|
89
|
+
// Anti-spam : une iframe ne doit pas pouvoir inonder l'interface du Core (ni imiter des messages système en rafale).
|
|
90
|
+
const policy = notificationPolicy(cfgOf.get('notifications'));
|
|
91
|
+
const allow = createSlidingLimiter(policy.rate.max, policy.rate.perSeconds);
|
|
92
|
+
table.notifications = {
|
|
93
|
+
show: async (n: any) => {
|
|
94
|
+
if (!allow()) throw new EmbedError('RATE_LIMITED', 'Trop de notifications');
|
|
95
|
+
return { displayed: (await p.notifications!.show(n, ctx)) !== false };
|
|
133
96
|
},
|
|
134
97
|
};
|
|
135
98
|
}
|
|
136
|
-
if (cfgOf.has('
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
},
|
|
144
|
-
unregister: (names: string[]) => {
|
|
145
|
-
p.aiTools!.unregister(o.moduleName, names);
|
|
146
|
-
for (const n of names) registeredTools.delete(n);
|
|
99
|
+
if (cfgOf.has('dialogs') && p.dialogs) table.dialogs = { confirm: async (d: any) => !!(await p.dialogs!.confirm(d, ctx)) };
|
|
100
|
+
if (cfgOf.has('extensions') && p.extensions) {
|
|
101
|
+
const discover = list(cfgOf.get('extensions'), 'discover');
|
|
102
|
+
table.extensions = {
|
|
103
|
+
list: async (slot: string) => {
|
|
104
|
+
if (!slotAllowed(discover, slot)) throw denied(`Slot non découvrable par le grant de l'app : ${slot}`);
|
|
105
|
+
return p.extensions!.list(slot);
|
|
147
106
|
},
|
|
148
107
|
};
|
|
149
108
|
}
|
|
@@ -168,22 +127,17 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
|
|
|
168
127
|
const desc = CAPABILITIES[cap as CapabilityId];
|
|
169
128
|
if (!cfg || !desc || !table[cap]) return undefined;
|
|
170
129
|
if (cap === 'events') return topicAllowed(list(cfg, 'subscribe'), ev) ? p.events!.subscribe(ev, emit) : undefined;
|
|
130
|
+
if (cap === 'extensions') return slotAllowed(list(cfg, 'discover'), ev) && p.extensions!.subscribe ? p.extensions!.subscribe(ev, emit as (l: any) => void) : undefined;
|
|
171
131
|
if (!desc.events.includes(ev)) return undefined;
|
|
172
132
|
switch (cap) {
|
|
173
|
-
case 'session':
|
|
174
|
-
return p.session!.subscribe?.((v) => emit(pick(v)));
|
|
175
133
|
case 'tenant':
|
|
176
134
|
return p.tenant!.subscribe?.(emit);
|
|
177
135
|
case 'locale':
|
|
178
136
|
return p.locale!.subscribe?.(emit);
|
|
179
|
-
case 'theme':
|
|
180
|
-
return p.theme!.subscribe?.(emit);
|
|
181
137
|
case 'config':
|
|
182
138
|
return p.config!.subscribe?.(emit);
|
|
183
139
|
case 'flags':
|
|
184
140
|
return p.flags!.subscribe?.(() => emit());
|
|
185
|
-
case 'permissions':
|
|
186
|
-
return p.permissions!.subscribe?.(() => emit());
|
|
187
141
|
case 'navigation':
|
|
188
142
|
case 'lifecycle':
|
|
189
143
|
return c.channel.on(ev, emit);
|
|
@@ -195,9 +149,5 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
|
|
|
195
149
|
return {
|
|
196
150
|
table,
|
|
197
151
|
subscribe,
|
|
198
|
-
cleanup: () => {
|
|
199
|
-
if (registeredTools.size && p.aiTools) p.aiTools.unregister(o.moduleName, [...registeredTools]);
|
|
200
|
-
registeredTools.clear();
|
|
201
|
-
},
|
|
202
152
|
};
|
|
203
153
|
}
|