@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/dist/table.js CHANGED
@@ -35,6 +35,19 @@ function _async_to_generator(fn) {
35
35
  });
36
36
  };
37
37
  }
38
+ function _define_property(obj, key, value) {
39
+ if (key in obj) {
40
+ Object.defineProperty(obj, key, {
41
+ value: value,
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true
45
+ });
46
+ } else {
47
+ obj[key] = value;
48
+ }
49
+ return obj;
50
+ }
38
51
  function _iterable_to_array_limit(arr, i) {
39
52
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
40
53
  if (_i == null) return;
@@ -62,9 +75,52 @@ function _iterable_to_array_limit(arr, i) {
62
75
  function _non_iterable_rest() {
63
76
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
64
77
  }
78
+ function _object_spread(target) {
79
+ for(var i = 1; i < arguments.length; i++){
80
+ var source = arguments[i] != null ? arguments[i] : {};
81
+ var ownKeys = Object.keys(source);
82
+ if (typeof Object.getOwnPropertySymbols === "function") {
83
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
84
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
85
+ }));
86
+ }
87
+ ownKeys.forEach(function(key) {
88
+ _define_property(target, key, source[key]);
89
+ });
90
+ }
91
+ return target;
92
+ }
93
+ function ownKeys(object, enumerableOnly) {
94
+ var keys = Object.keys(object);
95
+ if (Object.getOwnPropertySymbols) {
96
+ var symbols = Object.getOwnPropertySymbols(object);
97
+ if (enumerableOnly) {
98
+ symbols = symbols.filter(function(sym) {
99
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
100
+ });
101
+ }
102
+ keys.push.apply(keys, symbols);
103
+ }
104
+ return keys;
105
+ }
106
+ function _object_spread_props(target, source) {
107
+ source = source != null ? source : {};
108
+ if (Object.getOwnPropertyDescriptors) {
109
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
110
+ } else {
111
+ ownKeys(Object(source)).forEach(function(key) {
112
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
113
+ });
114
+ }
115
+ return target;
116
+ }
65
117
  function _sliced_to_array(arr, i) {
66
118
  return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
67
119
  }
120
+ function _type_of(obj) {
121
+ "@swc/helpers - typeof";
122
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
123
+ }
68
124
  function _unsupported_iterable_to_array(o, minLen) {
69
125
  if (!o) return;
70
126
  if (typeof o === "string") return _array_like_to_array(o, minLen);
@@ -319,9 +375,10 @@ var list = function list(cfg, key) {
319
375
  if (cfgOf.has('events') && p.events) {
320
376
  var pub = list(cfgOf.get('events'), 'publish');
321
377
  table.events = {
322
- publish: function publish(topic, payload) {
378
+ publish: function publish(topic, payload, options) {
323
379
  if (!topicAllowed(pub, topic)) throw denied("Publication non autoris\xe9e sur : ".concat(topic));
324
- p.events.publish(topic, payload, ctx);
380
+ if (options === undefined) p.events.publish(topic, payload, ctx);
381
+ else p.events.publish(topic, payload, ctx, options);
325
382
  }
326
383
  };
327
384
  }
@@ -329,50 +386,118 @@ var list = function list(cfg, key) {
329
386
  // Anti-spam : une iframe ne doit pas pouvoir inonder l'interface du Core (ni imiter des messages système en rafale).
330
387
  var policy = notificationPolicy(cfgOf.get('notifications'));
331
388
  var allow = createSlidingLimiter(policy.rate.max, policy.rate.perSeconds);
389
+ var open = new Map(); // toasts encore ouverts de cette app, par id
332
390
  table.notifications = {
333
391
  show: function show(n) {
334
392
  return _async_to_generator(function() {
335
- var _tmp;
393
+ var _n_id, r, shown, id, settled, timer, finish, handle, _timer_unref;
336
394
  return _ts_generator(this, function(_state) {
337
395
  switch(_state.label){
338
396
  case 0:
339
397
  if (!allow()) throw new EmbedError('RATE_LIMITED', 'Trop de notifications');
340
- _tmp = {};
341
398
  return [
342
399
  4,
343
400
  p.notifications.show(n, ctx)
344
401
  ];
345
402
  case 1:
403
+ r = _state.sent();
404
+ shown = r !== null && (typeof r === "undefined" ? "undefined" : _type_of(r)) === 'object' ? r : {};
405
+ id = (_n_id = n.id) !== null && _n_id !== void 0 ? _n_id : "n-".concat(++toastSeq);
406
+ if (r === false || shown.displayed === false) return [
407
+ 2,
408
+ {
409
+ displayed: false,
410
+ id: id,
411
+ reason: 'deduplicated'
412
+ }
413
+ ];
414
+ settled = false;
415
+ finish = function finish(reason) {
416
+ if (settled) return;
417
+ settled = true;
418
+ if (timer) clearTimeout(timer);
419
+ if (open.get(id) === handle) open.delete(id);
420
+ c.channel.emit('notifications.closed', {
421
+ id: id,
422
+ reason: reason
423
+ });
424
+ };
425
+ handle = {
426
+ dismiss: function dismiss() {
427
+ var _shown_dismiss;
428
+ return (_shown_dismiss = shown.dismiss) === null || _shown_dismiss === void 0 ? void 0 : _shown_dismiss.call(shown), finish('api');
429
+ }
430
+ };
431
+ open.set(id, handle);
432
+ if (shown.closed) shown.closed.then(finish, function() {
433
+ return finish('api');
434
+ });
435
+ else {
436
+ ;
437
+ // Le Core ne dit pas quand le toast se ferme : fermeture estimée à `timeoutMs` (la promesse `closed` n'est jamais pendante).
438
+ timer = setTimeout(function() {
439
+ return finish('timeout');
440
+ }, n.timeoutMs || DEFAULT_TOAST_MS);
441
+ (_timer_unref = timer.unref) === null || _timer_unref === void 0 ? void 0 : _timer_unref.call(timer);
442
+ }
346
443
  return [
347
444
  2,
348
- (_tmp.displayed = _state.sent() !== false, _tmp)
445
+ {
446
+ displayed: true,
447
+ id: id
448
+ }
349
449
  ];
350
450
  }
351
451
  });
352
452
  })();
453
+ },
454
+ dismiss: function dismiss(id) {
455
+ var _open_get;
456
+ return (_open_get = open.get(id)) === null || _open_get === void 0 ? void 0 : _open_get.dismiss();
353
457
  }
354
458
  };
355
459
  }
356
- if (cfgOf.has('dialogs') && p.dialogs) table.dialogs = {
357
- confirm: function confirm(d) {
358
- return _async_to_generator(function() {
359
- return _ts_generator(this, function(_state) {
360
- switch(_state.label){
361
- case 0:
362
- return [
363
- 4,
364
- p.dialogs.confirm(d, ctx)
365
- ];
366
- case 1:
367
- return [
368
- 2,
369
- !!_state.sent()
370
- ];
371
- }
372
- });
373
- })();
374
- }
375
- };
460
+ if (cfgOf.has('dialogs') && p.dialogs) {
461
+ table.dialogs = _object_spread({
462
+ confirm: function confirm(d) {
463
+ return _async_to_generator(function() {
464
+ return _ts_generator(this, function(_state) {
465
+ switch(_state.label){
466
+ case 0:
467
+ return [
468
+ 4,
469
+ p.dialogs.confirm(d, ctx)
470
+ ];
471
+ case 1:
472
+ return [
473
+ 2,
474
+ !!_state.sent()
475
+ ];
476
+ }
477
+ });
478
+ })();
479
+ }
480
+ }, p.dialogs.alert ? {
481
+ alert: function alert(d) {
482
+ return _async_to_generator(function() {
483
+ return _ts_generator(this, function(_state) {
484
+ switch(_state.label){
485
+ case 0:
486
+ return [
487
+ 4,
488
+ p.dialogs.alert(d, ctx)
489
+ ];
490
+ case 1:
491
+ return [
492
+ 2,
493
+ void _state.sent()
494
+ ];
495
+ }
496
+ });
497
+ })();
498
+ }
499
+ } : {});
500
+ }
376
501
  if (cfgOf.has('extensions') && p.extensions) {
377
502
  var discover = list(cfgOf.get('extensions'), 'discover');
378
503
  table.extensions = {
@@ -402,15 +527,54 @@ var list = function list(cfg, key) {
402
527
  };
403
528
  }
404
529
  if (cfgOf.has('navigation')) {
405
- table.navigation = {
530
+ table.navigation = _object_spread_props(_object_spread({
406
531
  report: function report(path, opts) {
407
532
  var _c_report;
408
533
  return (_c_report = c.report) === null || _c_report === void 0 ? void 0 : _c_report.call(c, path, opts);
409
534
  },
410
- navigate: function navigate(to) {
411
- var _c_navigate;
412
- return (_c_navigate = c.navigate) === null || _c_navigate === void 0 ? void 0 : _c_navigate.call(c, to);
413
- },
535
+ navigate: function navigate(to, options) {
536
+ return _async_to_generator(function() {
537
+ var _ref, _c_navigate;
538
+ return _ts_generator(this, function(_state) {
539
+ switch(_state.label){
540
+ case 0:
541
+ return [
542
+ 4,
543
+ (_c_navigate = c.navigate) === null || _c_navigate === void 0 ? void 0 : _c_navigate.call(c, to, options)
544
+ ];
545
+ case 1:
546
+ return [
547
+ 2,
548
+ (_ref = _state.sent()) !== null && _ref !== void 0 ? _ref : {
549
+ status: 'done',
550
+ path: to
551
+ }
552
+ ];
553
+ }
554
+ });
555
+ })();
556
+ }
557
+ }, c.current ? {
558
+ current: function current() {
559
+ return c.current();
560
+ }
561
+ } : {}, c.exists ? {
562
+ exists: function exists(path) {
563
+ return c.exists(path);
564
+ }
565
+ } : {}, c.back ? {
566
+ back: function back(result) {
567
+ return c.back(result);
568
+ }
569
+ } : {}, c.canGoBack ? {
570
+ canGoBack: function canGoBack() {
571
+ return c.canGoBack();
572
+ }
573
+ } : {}, c.intent ? {
574
+ intent: function intent(slug, params, options) {
575
+ return c.intent(slug, params, options);
576
+ }
577
+ } : {}), {
414
578
  notFound: function notFound(path) {
415
579
  var _c_notFound;
416
580
  return (_c_notFound = c.notFound) === null || _c_notFound === void 0 ? void 0 : _c_notFound.call(c, path);
@@ -423,7 +587,7 @@ var list = function list(cfg, key) {
423
587
  var _c_resize;
424
588
  return (_c_resize = c.resize) === null || _c_resize === void 0 ? void 0 : _c_resize.call(c, h);
425
589
  }
426
- };
590
+ });
427
591
  }
428
592
  if (cfgOf.has('lifecycle')) table.lifecycle = {
429
593
  ready: function ready() {
@@ -435,7 +599,30 @@ var list = function list(cfg, key) {
435
599
  var cfg = cfgOf.get(cap);
436
600
  var desc = CAPABILITIES[cap];
437
601
  if (!cfg || !desc || !table[cap]) return undefined;
438
- if (cap === 'events') return topicAllowed(list(cfg, 'subscribe'), ev) ? p.events.subscribe(ev, emit) : undefined;
602
+ if (cap === 'events') {
603
+ // `@sujet` : abonnement « enveloppe » (EgenEvent avec meta) ; `sujet` : charge utile seule (clients historiques).
604
+ var envelope = ev.startsWith('@');
605
+ var topic = envelope ? ev.slice(1) : ev;
606
+ if (!topicAllowed(list(cfg, 'subscribe'), topic)) return undefined;
607
+ return p.events.subscribe(topic, function(payload, meta) {
608
+ var _ref, _ref1, _ref2;
609
+ if ((meta === null || meta === void 0 ? void 0 : meta.to) !== undefined && meta.to !== ctx.moduleName) return; // ciblage : les autres apps ne reçoivent rien
610
+ if (!envelope) return emit(payload);
611
+ emit({
612
+ topic: topic,
613
+ payload: payload,
614
+ meta: _object_spread({
615
+ id: (_ref = meta === null || meta === void 0 ? void 0 : meta.id) !== null && _ref !== void 0 ? _ref : randomId(),
616
+ source: (_ref1 = meta === null || meta === void 0 ? void 0 : meta.source) !== null && _ref1 !== void 0 ? _ref1 : 'unknown',
617
+ ts: (_ref2 = meta === null || meta === void 0 ? void 0 : meta.ts) !== null && _ref2 !== void 0 ? _ref2 : Date.now()
618
+ }, (meta === null || meta === void 0 ? void 0 : meta.v) !== undefined ? {
619
+ v: meta.v
620
+ } : {}, (meta === null || meta === void 0 ? void 0 : meta.correlationId) !== undefined ? {
621
+ correlationId: meta.correlationId
622
+ } : {})
623
+ });
624
+ }, ctx);
625
+ }
439
626
  if (cap === 'extensions') return slotAllowed(list(cfg, 'discover'), ev) && p.extensions.subscribe ? p.extensions.subscribe(ev, emit) : undefined;
440
627
  if (!desc.events.includes(ev)) return undefined;
441
628
  switch(cap){
@@ -456,6 +643,8 @@ var list = function list(cfg, key) {
456
643
  case 'navigation':
457
644
  case 'lifecycle':
458
645
  return c.channel.on(ev, emit);
646
+ case 'notifications':
647
+ return c.channel.on('notifications.closed', emit);
459
648
  default:
460
649
  return undefined;
461
650
  }
@@ -465,3 +654,10 @@ var list = function list(cfg, key) {
465
654
  subscribe: subscribe
466
655
  };
467
656
  }
657
+ var toastSeq = 0;
658
+ var DEFAULT_TOAST_MS = 6000;
659
+ var idSeq = 0;
660
+ /** Identifiant d'événement quand le bus n'en fournit pas : unique pour la session de l'hôte. */ function randomId() {
661
+ var c = globalThis.crypto;
662
+ return (c === null || c === void 0 ? void 0 : c.randomUUID) ? c.randomUUID() : "evt-".concat(Date.now().toString(36), "-").concat((++idSeq).toString(36));
663
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egen-civitas/esm-embed-host",
3
- "version": "0.7.1",
3
+ "version": "0.10.0",
4
4
  "license": "MPL-2.0",
5
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
6
  "type": "module",
@@ -57,7 +57,7 @@
57
57
  "access": "public"
58
58
  },
59
59
  "devDependencies": {
60
- "@egen-civitas/esm-embed-client": "^0.8.0",
60
+ "@egen-civitas/esm-embed-client": "^0.11.0",
61
61
  "@swc/cli": "0.8.1",
62
62
  "@swc/core": "1.15.21",
63
63
  "@types/node": "^20",
@@ -69,6 +69,6 @@
69
69
  "vitest": "^4.1.2"
70
70
  },
71
71
  "dependencies": {
72
- "@egen-civitas/esm-embed-protocol": "^0.7.0"
72
+ "@egen-civitas/esm-embed-protocol": "^0.10.0"
73
73
  }
74
74
  }
@@ -6,7 +6,8 @@ export const ORIGIN = 'https://shell.exemple.org';
6
6
  export const MODULE = '@acme/esm-demo-app';
7
7
 
8
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'] } = {}) {
9
+ export async function harness(opts: { providers?: HostProviders; approved?: ApprovedGrants; requested?: Parameters<typeof connectToEgen>[0]['capabilities']; controls?: Partial<HostControls>; grants?: EffectiveGrants; limits?: ConnectionOptions['limits']; moduleName?: string } = {}) {
10
+ const moduleName = opts.moduleName ?? MODULE;
10
11
  const appWindow = new EventTarget();
11
12
  const hostWindow: any = {
12
13
  postMessage: (message: unknown, targetOrigin: string) => {
@@ -19,7 +20,7 @@ export async function harness(opts: { providers?: HostProviders; approved?: Appr
19
20
  const channel = createBus();
20
21
  const controls: HostControls = { channel, ...opts.controls };
21
22
  const conn: HostConnection = new HostConnection({
22
- moduleName: MODULE,
23
+ moduleName,
23
24
  grants: opts.grants ?? effectiveGrants(undefined, opts.approved ?? {}),
24
25
  providers: opts.providers ?? {},
25
26
  controls,
@@ -34,7 +35,7 @@ export async function harness(opts: { providers?: HostProviders; approved?: Appr
34
35
  },
35
36
  });
36
37
  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
+ connectToEgen({ moduleName, hostOrigins: [ORIGIN], window: appWindow as any, host: hostWindow, capabilities: opts.requested, timeoutMs: 400 }).then(resolve);
38
39
  });
39
40
  return { client, conn, channel, sentByApp, close: () => (client.close(), conn.destroy()) };
40
41
  }
@@ -0,0 +1,53 @@
1
+ import type { PublishOptions } from '@egen-civitas/esm-embed-protocol';
2
+ import type { CallerContext, EventMetaIn, HostProviders, Unsub } from './providers.js';
3
+
4
+ export type ShellEventBus = NonNullable<HostProviders['events']> & {
5
+ /** Publication par le Shell lui-même : `meta.source` vaut `shell`. */
6
+ publishAsShell(topic: string, payload?: unknown, options?: PublishOptions): void;
7
+ };
8
+
9
+ let seq = 0;
10
+ const newId = () => {
11
+ const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
12
+ return c?.randomUUID ? c.randomUUID() : `evt-${Date.now().toString(36)}-${(++seq).toString(36)}`;
13
+ };
14
+
15
+ /**
16
+ * « Shell Event Bus » de référence (spec §5) : en mémoire, éphémère, propre à l'onglet, sans garantie de livraison inter-onglets.
17
+ * Il pose lui-même `meta.source` (depuis le `ctx` de la connexion approuvée, jamais depuis le message) et transmet `to`,
18
+ * que l'hôte applique à la livraison. Un abonné reçoit aussi ses propres publications, comme le pont `egen:event` du Core.
19
+ */
20
+ export function createEventBus(now: () => number = () => Date.now()): ShellEventBus {
21
+ const subs = new Map<string, Set<(payload: unknown, meta?: EventMetaIn) => void>>();
22
+ const deliver = (topic: string, payload: unknown, meta: EventMetaIn) => {
23
+ for (const cb of [...(subs.get(topic) ?? [])]) {
24
+ try {
25
+ cb(payload, meta);
26
+ } catch {
27
+ /* un abonné fautif ne bloque pas les autres */
28
+ }
29
+ }
30
+ };
31
+ const metaOf = (source: string, o?: PublishOptions): EventMetaIn => ({
32
+ id: newId(),
33
+ source,
34
+ ts: now(),
35
+ ...(o?.v !== undefined ? { v: o.v } : {}),
36
+ ...(o?.correlationId !== undefined ? { correlationId: o.correlationId } : {}),
37
+ ...(o?.to !== undefined ? { to: o.to } : {}),
38
+ });
39
+ return {
40
+ publish(topic: string, payload: unknown, ctx: CallerContext, options?: PublishOptions) {
41
+ deliver(topic, payload, metaOf(ctx.moduleName, options));
42
+ },
43
+ publishAsShell(topic, payload, options) {
44
+ deliver(topic, payload, metaOf('shell', options));
45
+ },
46
+ subscribe(topic, cb): Unsub {
47
+ let set = subs.get(topic);
48
+ if (!set) subs.set(topic, (set = new Set()));
49
+ set.add(cb);
50
+ return () => void set!.delete(cb);
51
+ },
52
+ };
53
+ }
package/src/host.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { EGEN_EMBED_PROTOCOL, parseEnvelope, sanitizeIframeRights, type CapabilityDenied, type CapabilityGranted, type EffectiveGrants, type IframeRights, type Limits } from '@egen-civitas/esm-embed-protocol';
1
+ import { EGEN_EMBED_PROTOCOL, EmbedError, buildInternalHref, parseEnvelope, sanitizeIframeRights, type CapabilityDenied, type CapabilityGranted, type EffectiveGrants, type IframeRights, type Limits, type NavigateOptions, type NavigationResult, type RouteInfo } from '@egen-civitas/esm-embed-protocol';
2
2
  import { createBus } from './bus.js';
3
3
  import { HostConnection } from './connection.js';
4
4
  import { buildCoreUrl, buildEmbedSrc, coreSubpath, createRateLimiter, stripSensitive, toAppPath, toCorePath, normalizeAppPath, type NavigationOptions } from './navigation.js';
@@ -24,8 +24,12 @@ export interface EmbedHostOptions {
24
24
  minHeight?: number;
25
25
  /** Navigation partagée Core ↔ app (URL du Core = source de vérité). Absent ou `none` : opaque. */
26
26
  navigation?: NavigationOptions;
27
- /** Navigation demandée par l'app vers le Core (défaut : `singleSpaNavigate`). */
28
- onNavigate?: (to: string) => void;
27
+ /** Navigation demandée par l'app vers le Core (défaut : `singleSpaNavigate`, ou `replaceState` si `options.replace`). */
28
+ onNavigate?: (to: string, options?: NavigateOptions) => void;
29
+ /** Table des routes du Shell : `navigation.exists` et `NOT_FOUND` sur `navigate`. Absente : `exists` non servie. */
30
+ routeExists?: (path: string) => boolean | Promise<boolean>;
31
+ /** Correspondance d'intents (`objet-action`) → chemin du Shell, gouvernée par l'opérateur. `null` : intent inconnu (`NOT_FOUND`). */
32
+ intents?: (slug: string, params: Record<string, unknown>) => string | null | Promise<string | null>;
29
33
  /** Où écrire les diagnostics de poignée de main (défaut : `console`). */
30
34
  logger?: Pick<Console, 'warn'>;
31
35
  /**
@@ -46,6 +50,11 @@ export interface EmbedHost {
46
50
  mount(container: Element): void;
47
51
  /** 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). */
48
52
  canLeave(timeoutMs?: number): Promise<boolean>;
53
+ /**
54
+ * Fermeture ordonnée : laisse à l'app `lifecycle.closing` (≤ `timeoutMs`, défaut 2 s) pour nettoyer, puis détruit l'hôte.
55
+ * Au mieux — une app muette ou plus ancienne n'empêche jamais la fermeture. `destroy()` reste la fermeture immédiate.
56
+ */
57
+ close(timeoutMs?: number): Promise<void>;
49
58
  destroy(): void;
50
59
  }
51
60
 
@@ -107,13 +116,61 @@ export function createEmbedHost(opts: EmbedHostOptions): EmbedHost {
107
116
  win.history[o?.replace ? 'replaceState' : 'pushState'](win.history.state, '', buildCoreUrl(spaBase(), nav.route, corePath));
108
117
  };
109
118
 
119
+ /** `navigate` / `intent` : résolution du chemin, existence, garde de sortie, puis exécution. */
120
+ const performNavigate = async (to: string, options?: NavigateOptions): Promise<NavigationResult> => {
121
+ let target = to;
122
+ if (options?.relativeTo === 'app') {
123
+ const corePath = nav ? toCorePath(to, nav) : null;
124
+ if (!nav || !corePath) return { status: 'blocked', reason: 'forbidden-by-shell' };
125
+ target = '/' + buildCoreUrl(spaBase(), nav.route, corePath).slice(spaBase().length).replace(/^\//, '');
126
+ }
127
+ if (normalizeAppPath(target) === null) return { status: 'blocked', reason: 'forbidden-by-shell' };
128
+ const href = options && (options.query || options.hash) ? buildInternalHref(target, { query: options.query, hash: options.hash }) : target;
129
+ const pathOnly = href.split(/[?#]/, 1)[0]!;
130
+ if (opts.routeExists && !(await opts.routeExists(pathOnly))) throw new EmbedError('NOT_FOUND', `Route inconnue : ${pathOnly}`);
131
+ if (options?.target === 'newTab') {
132
+ win.open(spaBase() + href.replace(/^\//, ''), '_blank', 'noopener,noreferrer');
133
+ return { status: 'done', path: href };
134
+ }
135
+ const staying = options?.relativeTo === 'app' || (!!nav && coreSubpath(spaBase() + pathOnly.replace(/^\//, ''), spaBase(), nav.route) !== null);
136
+ if (!staying && !(await api.canLeave())) return { status: 'blocked', reason: 'dirty-declined' };
137
+ const go =
138
+ opts.onNavigate ??
139
+ ((t: string, o?: NavigateOptions) => {
140
+ if (o?.replace) {
141
+ win.history.replaceState(win.history.state, '', spaBase() + t.replace(/^\//, ''));
142
+ win.dispatchEvent(new PopStateEvent('popstate'));
143
+ } else (win as any).singleSpaNavigate?.(spaBase() + t.replace(/^\//, ''));
144
+ });
145
+ if (options?.replace) go(href, options);
146
+ else go(href);
147
+ return { status: 'done', path: href };
148
+ };
149
+
110
150
  const controls: HostControls = {
111
151
  channel,
112
152
  report: (path, o) => reportLocation(path, o),
113
- navigate: (to) => {
114
- if (normalizeAppPath(to) === null) return;
115
- (opts.onNavigate ?? ((t) => (win as any).singleSpaNavigate?.(spaBase() + t.replace(/^\//, ''))))(to);
116
- },
153
+ navigate: (to, options) => performNavigate(to, options),
154
+ ...(nav
155
+ ? {
156
+ current: (): RouteInfo => {
157
+ const u = new URL(toAppPath(lastCorePath, nav) ?? '/', 'http://app.invalid');
158
+ return { path: u.pathname, query: Object.fromEntries(u.searchParams), hash: u.hash, app: opts.moduleName, title: iframe.title };
159
+ },
160
+ }
161
+ : {}),
162
+ ...(opts.routeExists ? { exists: (path: string) => !!opts.routeExists!(path) } : {}),
163
+ back: () => void win.history.back(),
164
+ canGoBack: () => win.history.length > 1,
165
+ ...(opts.intents
166
+ ? {
167
+ intent: async (slug: string, params?: Record<string, unknown>, options?: NavigateOptions): Promise<NavigationResult> => {
168
+ const target = await opts.intents!(slug, params ?? {});
169
+ if (target === null || normalizeAppPath(target) === null) throw new EmbedError('NOT_FOUND', `Intent inconnu : ${slug}`);
170
+ return performNavigate(target, options);
171
+ },
172
+ }
173
+ : {}),
117
174
  notFound: (path) => {
118
175
  if (!opts.onNotFound || !allowLocation()) return;
119
176
  const normalized = path === undefined ? null : normalizeAppPath(path);
@@ -172,7 +229,7 @@ export function createEmbedHost(opts: EmbedHostOptions): EmbedHost {
172
229
  }
173
230
  };
174
231
 
175
- return {
232
+ const api: EmbedHost = {
176
233
  iframe,
177
234
  connection,
178
235
  mount(container) {
@@ -224,10 +281,21 @@ export function createEmbedHost(opts: EmbedHostOptions): EmbedHost {
224
281
  return true;
225
282
  }
226
283
  },
284
+ async close(timeoutMs = 2000) {
285
+ if (connection.connected) {
286
+ try {
287
+ await Promise.race([connection.callApp('lifecycle', 'closing'), new Promise<void>((res) => setTimeout(res, timeoutMs))]);
288
+ } catch {
289
+ /* app plus ancienne (UNKNOWN_METHOD), déjà fermée, en erreur : la fermeture continue */
290
+ }
291
+ }
292
+ api.destroy();
293
+ },
227
294
  destroy() {
228
295
  while (stop.length) stop.pop()!();
229
296
  connection.destroy();
230
297
  iframe.remove();
231
298
  },
232
299
  };
300
+ return api;
233
301
  }
package/src/index.ts CHANGED
@@ -4,3 +4,4 @@ export * from './table.js';
4
4
  export * from './connection.js';
5
5
  export * from './navigation.js';
6
6
  export * from './host.js';
7
+ export * from './event-bus.js';
package/src/providers.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { NotificationCloseReason, PublishOptions } from '@egen-civitas/esm-embed-protocol';
1
2
  export type Unsub = () => void;
2
3
 
3
4
  /** Valeur lisible et observable fournie par le Core. */
@@ -6,11 +7,30 @@ export interface Watchable<T> {
6
7
  subscribe?(cb: (value: T) => void): Unsub;
7
8
  }
8
9
 
10
+ /** Métadonnées fournies par le bus avec chaque événement livré. */
11
+ export interface EventMetaIn {
12
+ id?: string;
13
+ source?: string;
14
+ ts?: number;
15
+ v?: number;
16
+ correlationId?: string;
17
+ to?: string;
18
+ }
19
+
9
20
  export interface CallerContext {
10
21
  /** Nom du module de l'app appelante (non falsifiable : porté par la connexion, pas par le message). */
11
22
  moduleName: string;
12
23
  }
13
24
 
25
+ /** Ce que le Core peut renvoyer de `show` pour suivre son toast (tout est optionnel : renvoyer `void`/`boolean` reste valide). */
26
+ export interface NotificationShown {
27
+ displayed?: boolean;
28
+ /** Résolue à la fermeture du toast, avec sa cause. Absente : l'hôte estime la fermeture à `timeoutMs` (6 s par défaut). */
29
+ closed?: Promise<NotificationCloseReason>;
30
+ /** Ferme le toast sur demande de l'app (`dismiss`). */
31
+ dismiss?: () => void;
32
+ }
33
+
14
34
  export interface NotificationInput {
15
35
  /** Clé de dédoublonnage facultative : un même `id` ne produit pas deux toasts rapprochés. */
16
36
  id?: string;
@@ -18,6 +38,8 @@ export interface NotificationInput {
18
38
  title: string;
19
39
  subtitle?: string;
20
40
  timeoutMs?: number;
41
+ /** Bouton du toast : le Shell publie `topic` sur le bus d'événements (aucun code n'est exécuté). */
42
+ action?: { label: string; topic: string };
21
43
  }
22
44
 
23
45
  export interface ExtensionInfo {
@@ -39,10 +61,22 @@ export interface HostProviders {
39
61
  locale?: Watchable<string>;
40
62
  config?: Watchable<Record<string, unknown>>;
41
63
  flags?: { isEnabled(name: string): boolean | Promise<boolean>; subscribe?(cb: () => void): Unsub };
42
- events?: { publish(topic: string, payload: unknown, ctx: CallerContext): void; subscribe(topic: string, cb: (payload: unknown) => void): Unsub };
64
+ /**
65
+ * Bus d'événements du Shell. `publish`/`subscribe` historiques inchangés ; les paramètres ajoutés sont optionnels (un fournisseur
66
+ * plus ancien qui les ignore reste valide : `meta.source` vaut alors `unknown`, `to` n'est pas appliqué).
67
+ * Le fournisseur DOIT poser `source` lui-même (depuis `ctx.moduleName`, jamais depuis la charge utile).
68
+ */
69
+ events?: {
70
+ publish(topic: string, payload: unknown, ctx: CallerContext, options?: PublishOptions): void;
71
+ subscribe(topic: string, cb: (payload: unknown, meta?: EventMetaIn) => void, ctx?: CallerContext): Unsub;
72
+ };
43
73
  /** 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> };
45
- dialogs?: { confirm(d: { title: string; message: string; danger?: boolean }, ctx: CallerContext): boolean | Promise<boolean> };
74
+ notifications?: { show(n: NotificationInput, ctx: CallerContext): void | boolean | NotificationShown | Promise<void | boolean | NotificationShown> };
75
+ dialogs?: {
76
+ confirm(d: { title: string; message: string; danger?: boolean }, ctx: CallerContext): boolean | Promise<boolean>;
77
+ /** Information à acquitter. Absente : `dialogs.alert` n'est pas servie (`UNKNOWN_METHOD`) — jamais simulée par un `confirm`. */
78
+ alert?(d: { title: string; message: string }, ctx: CallerContext): void | Promise<void>;
79
+ };
46
80
  /** Extensions attachées à un slot du Core (apps internes, framework, autres apps) : métadonnées seulement, jamais le rendu. */
47
81
  extensions?: { list(slot: string): ExtensionInfo[] | Promise<ExtensionInfo[]>; subscribe?(slot: string, cb: (list: ExtensionInfo[]) => void): Unsub };
48
82
  telemetry?: {