@egen-civitas/esm-embed-host 0.7.1 → 0.10.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/src/table.ts CHANGED
@@ -9,15 +9,27 @@ import {
9
9
  type CapabilityId,
10
10
  type GrantConfig,
11
11
  type HandlerTable,
12
+ type NavigateOptions,
13
+ type NotificationCloseReason,
14
+ type PublishOptions,
15
+ type NavigationResult,
16
+ type RouteInfo,
12
17
  type SubscribeHandler,
13
18
  } from '@egen-civitas/esm-embed-protocol';
14
19
  import type { Bus } from './bus.js';
15
- import type { CallerContext, HostProviders } from './providers.js';
20
+ import type { CallerContext, HostProviders, NotificationShown } from './providers.js';
16
21
 
17
22
  /** Actions du Shell pilotées par les capacités `navigation` et `lifecycle`. */
18
23
  export interface HostControls {
19
24
  report?(path: string, opts?: { replace?: boolean; title?: string }): void;
20
- navigate?(to: string): void;
25
+ /** Navigation demandée par l'app. Sans résultat renvoyé, l'hôte répond `{ status: 'done' }`. */
26
+ navigate?(to: string, options?: NavigateOptions): NavigationResult | void | Promise<NavigationResult | void>;
27
+ /** Lecture/gardes de navigation (B4) : servies seulement si fournies ; sinon `UNKNOWN_METHOD` côté app. */
28
+ current?(): RouteInfo | Promise<RouteInfo>;
29
+ exists?(path: string): boolean | Promise<boolean>;
30
+ back?(result?: unknown): void | Promise<void>;
31
+ canGoBack?(): boolean | Promise<boolean>;
32
+ intent?(slug: string, params?: Record<string, unknown>, options?: NavigateOptions): NavigationResult | Promise<NavigationResult>;
21
33
  /** L'app signale une page introuvable (`path` : chemin de l'app, absent = page courante). */
22
34
  notFound?(path?: string): void;
23
35
  setTitle?(title: string): void;
@@ -81,9 +93,10 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
81
93
  if (cfgOf.has('events') && p.events) {
82
94
  const pub = list(cfgOf.get('events'), 'publish');
83
95
  table.events = {
84
- publish: (topic: string, payload?: unknown) => {
96
+ publish: (topic: string, payload?: unknown, options?: PublishOptions) => {
85
97
  if (!topicAllowed(pub, topic)) throw denied(`Publication non autorisée sur : ${topic}`);
86
- p.events!.publish(topic, payload, ctx);
98
+ if (options === undefined) p.events!.publish(topic, payload, ctx);
99
+ else p.events!.publish(topic, payload, ctx, options);
87
100
  },
88
101
  };
89
102
  }
@@ -91,14 +104,42 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
91
104
  // Anti-spam : une iframe ne doit pas pouvoir inonder l'interface du Core (ni imiter des messages système en rafale).
92
105
  const policy = notificationPolicy(cfgOf.get('notifications'));
93
106
  const allow = createSlidingLimiter(policy.rate.max, policy.rate.perSeconds);
107
+ const open = new Map<string, { dismiss(): void }>(); // toasts encore ouverts de cette app, par id
94
108
  table.notifications = {
95
109
  show: async (n: any) => {
96
110
  if (!allow()) throw new EmbedError('RATE_LIMITED', 'Trop de notifications');
97
- return { displayed: (await p.notifications!.show(n, ctx)) !== false };
111
+ const r = await p.notifications!.show(n, ctx);
112
+ const shown: NotificationShown = r !== null && typeof r === 'object' ? r : {};
113
+ const id: string = n.id ?? `n-${++toastSeq}`;
114
+ if (r === false || shown.displayed === false) return { displayed: false, id, reason: 'deduplicated' as const };
115
+ let settled = false;
116
+ let timer: ReturnType<typeof setTimeout> | undefined;
117
+ const finish = (reason: NotificationCloseReason) => {
118
+ if (settled) return;
119
+ settled = true;
120
+ if (timer) clearTimeout(timer);
121
+ if (open.get(id) === handle) open.delete(id);
122
+ c.channel.emit('notifications.closed', { id, reason });
123
+ };
124
+ const handle = { dismiss: () => (shown.dismiss?.(), finish('api')) };
125
+ open.set(id, handle);
126
+ if (shown.closed) shown.closed.then(finish, () => finish('api'));
127
+ else {
128
+ // Le Core ne dit pas quand le toast se ferme : fermeture estimée à `timeoutMs` (la promesse `closed` n'est jamais pendante).
129
+ timer = setTimeout(() => finish('timeout'), n.timeoutMs || DEFAULT_TOAST_MS);
130
+ (timer as { unref?: () => void }).unref?.();
131
+ }
132
+ return { displayed: true, id };
98
133
  },
134
+ dismiss: (id: string) => open.get(id)?.dismiss(),
135
+ };
136
+ }
137
+ if (cfgOf.has('dialogs') && p.dialogs) {
138
+ table.dialogs = {
139
+ confirm: async (d: any) => !!(await p.dialogs!.confirm(d, ctx)),
140
+ ...(p.dialogs.alert ? { alert: async (d: any) => void (await p.dialogs!.alert!(d, ctx)) } : {}),
99
141
  };
100
142
  }
101
- if (cfgOf.has('dialogs') && p.dialogs) table.dialogs = { confirm: async (d: any) => !!(await p.dialogs!.confirm(d, ctx)) };
102
143
  if (cfgOf.has('extensions') && p.extensions) {
103
144
  const discover = list(cfgOf.get('extensions'), 'discover');
104
145
  table.extensions = {
@@ -117,7 +158,12 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
117
158
  if (cfgOf.has('navigation')) {
118
159
  table.navigation = {
119
160
  report: (path: string, opts?: { replace?: boolean; title?: string }) => c.report?.(path, opts),
120
- navigate: (to: string) => c.navigate?.(to),
161
+ navigate: async (to: string, options?: NavigateOptions): Promise<NavigationResult> => (await c.navigate?.(to, options)) ?? { status: 'done', path: to },
162
+ ...(c.current ? { current: () => c.current!() } : {}),
163
+ ...(c.exists ? { exists: (path: string) => c.exists!(path) } : {}),
164
+ ...(c.back ? { back: (result?: unknown) => c.back!(result) } : {}),
165
+ ...(c.canGoBack ? { canGoBack: () => c.canGoBack!() } : {}),
166
+ ...(c.intent ? { intent: (slug: string, params?: Record<string, unknown>, options?: NavigateOptions) => c.intent!(slug, params, options) } : {}),
121
167
  notFound: (path?: string) => c.notFound?.(path),
122
168
  setTitle: (t: string) => c.setTitle?.(t),
123
169
  resize: (h: number) => c.resize?.(h),
@@ -129,7 +175,21 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
129
175
  const cfg = cfgOf.get(cap as CapabilityId);
130
176
  const desc = CAPABILITIES[cap as CapabilityId];
131
177
  if (!cfg || !desc || !table[cap]) return undefined;
132
- if (cap === 'events') return topicAllowed(list(cfg, 'subscribe'), ev) ? p.events!.subscribe(ev, emit) : undefined;
178
+ if (cap === 'events') {
179
+ // `@sujet` : abonnement « enveloppe » (EgenEvent avec meta) ; `sujet` : charge utile seule (clients historiques).
180
+ const envelope = ev.startsWith('@');
181
+ const topic = envelope ? ev.slice(1) : ev;
182
+ if (!topicAllowed(list(cfg, 'subscribe'), topic)) return undefined;
183
+ return p.events!.subscribe(
184
+ topic,
185
+ (payload, meta) => {
186
+ if (meta?.to !== undefined && meta.to !== ctx.moduleName) return; // ciblage : les autres apps ne reçoivent rien
187
+ if (!envelope) return emit(payload);
188
+ emit({ topic, payload, meta: { id: meta?.id ?? randomId(), source: meta?.source ?? 'unknown', ts: meta?.ts ?? Date.now(), ...(meta?.v !== undefined ? { v: meta.v } : {}), ...(meta?.correlationId !== undefined ? { correlationId: meta.correlationId } : {}) } });
189
+ },
190
+ ctx,
191
+ );
192
+ }
133
193
  if (cap === 'extensions') return slotAllowed(list(cfg, 'discover'), ev) && p.extensions!.subscribe ? p.extensions!.subscribe(ev, emit as (l: any) => void) : undefined;
134
194
  if (!desc.events.includes(ev)) return undefined;
135
195
  switch (cap) {
@@ -144,6 +204,8 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
144
204
  case 'navigation':
145
205
  case 'lifecycle':
146
206
  return c.channel.on(ev, emit);
207
+ case 'notifications':
208
+ return c.channel.on('notifications.closed', emit);
147
209
  default:
148
210
  return undefined;
149
211
  }
@@ -154,3 +216,12 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
154
216
  subscribe,
155
217
  };
156
218
  }
219
+
220
+ let toastSeq = 0;
221
+ const DEFAULT_TOAST_MS = 6000;
222
+ let idSeq = 0;
223
+ /** Identifiant d'événement quand le bus n'en fournit pas : unique pour la session de l'hôte. */
224
+ function randomId(): string {
225
+ const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
226
+ return c?.randomUUID ? c.randomUUID() : `evt-${Date.now().toString(36)}-${(++idSeq).toString(36)}`;
227
+ }