@egen-civitas/sdk 0.0.0-stage → 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/src/app.ts ADDED
@@ -0,0 +1,103 @@
1
+ import type { EgenClient } from '@egen-civitas/esm-embed-client';
2
+ import type { CapabilityDenied, CapabilityId, LifecycleState } from '@egen-civitas/esm-embed-protocol';
3
+ import { SDK_VERSION } from './version.js';
4
+
5
+ export type EgenMode = 'embedded' | 'standalone';
6
+
7
+ export interface Diagnosis {
8
+ mode: EgenMode;
9
+ state: LifecycleState;
10
+ /** `true` seulement si une connexion au Shell est établie. */
11
+ connected: boolean;
12
+ moduleName: string;
13
+ sdkVersion: string;
14
+ protocol: number | undefined;
15
+ granted: string[];
16
+ denied: CapabilityDenied[];
17
+ /** Pistes lisibles pour comprendre un comportement inattendu. */
18
+ hints: string[];
19
+ }
20
+
21
+ /**
22
+ * Application connectée à EGEN. Même surface quel que soit le mode : le code de l'app ne change pas selon qu'elle tourne
23
+ * dans le Shell (`embedded`) ou seule (`standalone`). `client` donne accès au client embarqué sous-jacent (échappatoire).
24
+ */
25
+ export class EgenApp {
26
+ readonly mode: EgenMode;
27
+ readonly sdkVersion = SDK_VERSION;
28
+ readonly client: EgenClient;
29
+
30
+ readonly tenant: EgenClient['tenant'];
31
+ readonly locale: EgenClient['locale'];
32
+ readonly navigation: EgenClient['navigation'];
33
+ readonly events: EgenClient['events'];
34
+ readonly notifications: EgenClient['notifications'];
35
+ readonly dialogs: EgenClient['dialogs'];
36
+ readonly flags: EgenClient['flags'];
37
+ readonly config: EgenClient['config'];
38
+ readonly telemetry: EgenClient['telemetry'];
39
+ readonly lifecycle: EgenClient['lifecycle'];
40
+ readonly extensions: EgenClient['extensions'];
41
+
42
+ constructor(client: EgenClient, mode: EgenMode, private readonly note?: string) {
43
+ this.client = client;
44
+ this.mode = mode;
45
+ this.tenant = client.tenant;
46
+ this.locale = client.locale;
47
+ this.navigation = client.navigation;
48
+ this.events = client.events;
49
+ this.notifications = client.notifications;
50
+ this.dialogs = client.dialogs;
51
+ this.flags = client.flags;
52
+ this.config = client.config;
53
+ this.telemetry = client.telemetry;
54
+ this.lifecycle = client.lifecycle;
55
+ this.extensions = client.extensions;
56
+ }
57
+
58
+ get moduleName(): string {
59
+ return this.client.moduleName;
60
+ }
61
+ /** Connexion au Shell établie (toujours `false` en mode autonome). */
62
+ get connected(): boolean {
63
+ return this.client.connected;
64
+ }
65
+ /** État du cycle de vie (spec §6.1). */
66
+ get state(): LifecycleState {
67
+ return this.client.lifecycle.state;
68
+ }
69
+ get closed(): boolean {
70
+ return this.client.closed;
71
+ }
72
+ /** Le Core affiche-t-il seul les notifications de l'app ? (voir `EgenClient.coreDisplaysNotifications`). */
73
+ get coreDisplaysNotifications(): boolean {
74
+ return this.client.coreDisplaysNotifications;
75
+ }
76
+
77
+ has(id: CapabilityId): boolean {
78
+ return this.client.has(id);
79
+ }
80
+ get capabilities(): { granted: CapabilityId[]; denied: CapabilityDenied[] } {
81
+ return { granted: this.client.capabilities.map((g) => g.id), denied: this.client.denied };
82
+ }
83
+
84
+ /** Notification sans doublon : Core si disponible, sinon `local`. */
85
+ notify: EgenClient['notify'] = (toast, local) => this.client.notify(toast, local);
86
+
87
+ diagnose(): Diagnosis {
88
+ const denied = this.client.denied;
89
+ const hints: string[] = [];
90
+ if (this.mode === 'standalone') hints.push(this.note ?? "Mode autonome : l'app n'est pas connectée au Shell EGEN.");
91
+ for (const d of denied) {
92
+ if (d.reason === 'NOT_APPROVED') hints.push(`« ${d.id} » : non approuvée par l'opérateur (external-apps.json).`);
93
+ else if (d.reason === 'UNAVAILABLE') hints.push(`« ${d.id} » : le Shell ne sert pas cette capacité (hôte plus ancien ?).`);
94
+ else if (d.reason === 'VERSION') hints.push(`« ${d.id} » : version de capacité non prise en charge par le Shell.`);
95
+ else hints.push(`« ${d.id} » : inconnue du Shell (SDK plus récent que le Shell ?).`);
96
+ }
97
+ return { mode: this.mode, state: this.state, connected: this.connected, moduleName: this.moduleName, sdkVersion: this.sdkVersion, protocol: this.client.protocol, granted: this.capabilities.granted, denied, hints };
98
+ }
99
+
100
+ close(): void {
101
+ this.client.close();
102
+ }
103
+ }
package/src/connect.ts ADDED
@@ -0,0 +1,100 @@
1
+ import { EgenClient, connectToEgen, type ConnectOptions as EmbeddedOptions } from '@egen-civitas/esm-embed-client';
2
+ import { EmbedError, CAPABILITIES, CAPABILITY_IDS, type CapabilityId, type LifecycleState } from '@egen-civitas/esm-embed-protocol';
3
+ import { EgenApp, type EgenMode } from './app.js';
4
+ import { STANDALONE_CAPABILITIES, createStandaloneRuntime, type StandaloneOptions } from './standalone.js';
5
+
6
+ /** Transitions d'état et erreurs de protocole (spec §6 / §497) : `connecting` et `failed` n'existent qu'ici. */
7
+ export type DiagnosticEvent = { type: 'state'; state: LifecycleState } | { type: 'error'; error: EmbedError };
8
+
9
+ export interface ConnectOptions extends Omit<EmbeddedOptions, 'hostOrigins'> {
10
+ /** Origines EXACTES du Shell. Obligatoire pour le mode embarqué ; sans elles, `auto` reste en mode autonome. */
11
+ hostOrigins?: string[];
12
+ /**
13
+ * `auto` (défaut) : embarqué si la page est dans une iframe, autonome sinon ou si le Shell ne répond pas ;
14
+ * `embedded` : exige le Shell (échec explicite sinon) ; `standalone` : n'essaie jamais de se connecter.
15
+ */
16
+ mode?: 'auto' | EgenMode;
17
+ /** Capacités sans lesquelles l'app ne peut pas fonctionner : `connect()` échoue si l'une manque. */
18
+ required?: CapabilityId[];
19
+ /** Comportement hors Shell. */
20
+ standalone?: StandaloneOptions;
21
+ /** Reçoit les transitions d'état (`connecting` → `ready`/`standalone`/`failed` → …) et les erreurs de protocole. */
22
+ onDiagnostic?: (e: DiagnosticEvent) => void;
23
+ }
24
+
25
+ const inIframe = (w?: unknown): boolean => {
26
+ if (w !== undefined) return true; // fenêtre injectée (tests) : on suppose un hôte
27
+ try {
28
+ return typeof window !== 'undefined' && window.parent !== window;
29
+ } catch {
30
+ return true; // accès à window.parent refusé : on est bien dans un cadre d'une autre origine
31
+ }
32
+ };
33
+
34
+ function localClient(options: ConnectOptions): EgenClient {
35
+ const requested = (options.capabilities ?? CAPABILITY_IDS.filter((id) => CAPABILITIES[id].defaultGrant)).map((c) => (typeof c === 'string' ? c : (c.id as CapabilityId)));
36
+ const ids = new Set<CapabilityId>([...requested, ...(options.required ?? [])]);
37
+ const granted = [...ids]
38
+ .filter((id) => STANDALONE_CAPABILITIES.includes(id))
39
+ .map((id) => ({ id, version: CAPABILITIES[id].version, config: id === 'notifications' ? { exclusive: false } : {} }));
40
+ const denied = [...ids].filter((id) => !STANDALONE_CAPABILITIES.includes(id)).map((id) => ({ id, reason: 'UNAVAILABLE' as const }));
41
+ return new EgenClient({ connected: false, moduleName: options.moduleName, granted: granted as never, denied, rpc: createStandaloneRuntime(options.standalone) });
42
+ }
43
+
44
+ function enforceRequired(app: EgenApp, required: CapabilityId[] | undefined): EgenApp {
45
+ const missing = (required ?? []).filter((id) => !app.has(id));
46
+ if (missing.length) {
47
+ app.close();
48
+ throw new EmbedError('DENIED', `Capacités requises non accordées (${app.mode}) : ${missing.join(', ')}`);
49
+ }
50
+ return app;
51
+ }
52
+
53
+ /**
54
+ * Point d'entrée unique du SDK. Retourne toujours une `EgenApp` utilisable, sauf si `required` n'est pas satisfait
55
+ * ou si `mode: 'embedded'` est exigé sans Shell (erreurs typées `EgenError`).
56
+ */
57
+ export async function connect(options: ConnectOptions): Promise<EgenApp> {
58
+ const emit = (e: DiagnosticEvent) => {
59
+ try {
60
+ options?.onDiagnostic?.(e);
61
+ } catch {
62
+ /* un observateur ne casse jamais la connexion */
63
+ }
64
+ };
65
+ emit({ type: 'state', state: 'connecting' });
66
+ try {
67
+ const app = await connectInner(options);
68
+ emit({ type: 'state', state: app.state });
69
+ app.client.lifecycle.onStateChange((state) => emit({ type: 'state', state }));
70
+ app.client.lifecycle.onError((error) => emit({ type: 'error', error }));
71
+ return app;
72
+ } catch (e) {
73
+ emit({ type: 'state', state: 'failed' });
74
+ if (e instanceof EmbedError) emit({ type: 'error', error: e });
75
+ throw e;
76
+ }
77
+ }
78
+
79
+ async function connectInner(options: ConnectOptions): Promise<EgenApp> {
80
+ if (!options || typeof options.moduleName !== 'string' || !options.moduleName) throw new EmbedError('INVALID_ARGS', 'connect : moduleName est obligatoire');
81
+ const mode = options.mode ?? 'auto';
82
+ const standalone = (note: string) => enforceRequired(new EgenApp(localClient(options), 'standalone', note), options.required);
83
+
84
+ if (mode === 'standalone') return standalone('Mode autonome demandé explicitement.');
85
+
86
+ const origins = options.hostOrigins;
87
+ if (!origins || origins.length === 0) {
88
+ if (mode === 'embedded') throw new EmbedError('INVALID_ARGS', 'connect : hostOrigins est obligatoire en mode embedded');
89
+ return standalone('Aucune origine de Shell fournie (hostOrigins) : mode autonome.');
90
+ }
91
+ if (!inIframe(options.window)) {
92
+ if (mode === 'embedded') throw new EmbedError('UNSUPPORTED_IN_MODE', "connect : mode embedded exigé mais la page n'est pas dans une iframe du Shell");
93
+ return standalone("Page ouverte hors d'une iframe : mode autonome.");
94
+ }
95
+
96
+ const client = await connectToEgen({ ...options, hostOrigins: origins });
97
+ if (client.connected) return enforceRequired(new EgenApp(client, 'embedded'), options.required);
98
+ if (mode === 'embedded') throw new EmbedError('TIMEOUT', `Aucune réponse du Shell pour « ${options.moduleName} » (voir les pistes de diagnostic dans la console)`);
99
+ return standalone("Le Shell n'a pas répondu à la poignée de main : mode autonome.");
100
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { EmbedError, type ErrorCode } from '@egen-civitas/esm-embed-protocol';
2
+
3
+ /**
4
+ * Erreur typée du SDK. C'est la MÊME classe que celle du protocole : toute erreur levée par le client
5
+ * embarqué est donc reconnue par `instanceof EgenError` / `isEgenError`.
6
+ * Codes : DENIED, UNKNOWN_CAPABILITY, UNKNOWN_METHOD, INVALID_ARGS, TIMEOUT, RATE_LIMITED, TOO_LARGE, CLOSED, INTERNAL,
7
+ * NOT_FOUND, CANCELLED, QUOTA_EXCEEDED, UNSUPPORTED_IN_MODE.
8
+ */
9
+ export { EmbedError as EgenError };
10
+ export type EgenErrorCode = ErrorCode;
11
+
12
+ export function isEgenError(e: unknown, code?: EgenErrorCode): e is EmbedError {
13
+ return e instanceof EmbedError && (code === undefined || e.code === code);
14
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export { connect, type ConnectOptions, type DiagnosticEvent } from './connect.js';
2
+ export { EgenApp, type Diagnosis, type EgenMode } from './app.js';
3
+ export { EgenError, isEgenError, type EgenErrorCode } from './errors.js';
4
+ export { createStandaloneRuntime, STANDALONE_CAPABILITIES, type StandaloneOptions } from './standalone.js';
5
+ export { SDK_VERSION } from './version.js';
6
+ // Compatibilité : les apps existantes gardent `connectToEgen` / `EgenClient` (dépréciation : voir roadmap §4).
7
+ export { connectToEgen, EgenClient } from '@egen-civitas/esm-embed-client';
8
+ export type { LifecycleState, CapabilityId, CapabilityDenied, CapabilityGranted } from '@egen-civitas/esm-embed-protocol';
@@ -0,0 +1,140 @@
1
+ import { EmbedError, buildInternalHref, validateCall, type CapabilityId, type NavigateOptions } from '@egen-civitas/esm-embed-protocol';
2
+ import type { RpcLike } from '@egen-civitas/esm-embed-client';
3
+
4
+ type Json = Record<string, unknown>;
5
+
6
+ /** Comportement de l'app HORS Shell (mode `standalone`) : la même application fonctionne sans EGEN (cahier §1). */
7
+ export interface StandaloneOptions {
8
+ tenantId?: string | null;
9
+ locale?: string;
10
+ /** Configuration publique servie par `config.get()`. */
11
+ config?: Json;
12
+ /** Drapeaux de fonctionnalité locaux. */
13
+ flags?: Record<string, boolean>;
14
+ /** Remplace `window.confirm` pour `dialogs.confirm`. */
15
+ confirm?: (d: { title: string; message: string; danger?: boolean }) => boolean | Promise<boolean>;
16
+ /** Reçoit `telemetry.log` / `telemetry.metric` (défaut : ignorés). */
17
+ onTelemetry?: (kind: 'log' | 'metric', data: unknown[]) => void;
18
+ /** Injectables pour les tests / hors navigateur. */
19
+ window?: Pick<Window, 'history' | 'document'> & { navigator?: { language?: string }; location?: Pick<Location, 'pathname' | 'search' | 'hash'>; open?: Window['open'] };
20
+ /** Table des routes locale (`navigation.exists`, `NOT_FOUND`). Absente : `exists` indisponible. */
21
+ routeExists?: (path: string) => boolean | Promise<boolean>;
22
+ /** Intents `objet-action` → chemin local (`null` : inconnu). Absent : `intent` indisponible. */
23
+ intents?: (slug: string, params: Record<string, unknown>) => string | null | Promise<string | null>;
24
+ }
25
+
26
+ type Handler = (args: unknown[]) => unknown | Promise<unknown>;
27
+
28
+ /**
29
+ * Runtime local qui sert les capacités du catalogue sans Shell. Il respecte la validation d'arguments du protocole
30
+ * (mêmes `INVALID_ARGS` qu'avec un hôte) ; ce qui n'a pas de sens hors Shell est refusé avec `UNSUPPORTED_IN_MODE`.
31
+ */
32
+ export function createStandaloneRuntime(opts: StandaloneOptions = {}): RpcLike {
33
+ const win = opts.window ?? (typeof window !== 'undefined' ? (window as unknown as NonNullable<StandaloneOptions['window']>) : undefined);
34
+ const listeners = new Map<string, Set<(v: unknown) => void>>();
35
+ let closed = false;
36
+ let seq = 0;
37
+ // Visibilité locale (spec §6.2 : `document.visibilitychange` en mode autonome).
38
+ const doc = win?.document as (Document & { hidden?: boolean }) | undefined;
39
+ const onVisibility = () => emit('lifecycle', 'visibility', !doc?.hidden);
40
+ doc?.addEventListener?.('visibilitychange', onVisibility);
41
+ const emit = (cap: string, ev: string, v: unknown) => listeners.get(`${cap}:${ev}`)?.forEach((cb) => cb(v));
42
+ const unsupported = (what: string) => new EmbedError('UNSUPPORTED_IN_MODE', `${what} : indisponible hors du Shell EGEN (mode autonome)`);
43
+
44
+ const navigateLocal = async (to: string, o?: NavigateOptions) => {
45
+ const href = o && (o.query || o.hash) ? buildInternalHref(to, { query: o.query, hash: o.hash }) : to;
46
+ const pathOnly = href.split(/[?#]/, 1)[0]!;
47
+ if (opts.routeExists && !(await opts.routeExists(pathOnly))) throw new EmbedError('NOT_FOUND', `Route inconnue : ${pathOnly}`);
48
+ if (o?.target === 'newTab') win?.open?.(href, '_blank', 'noopener,noreferrer');
49
+ else {
50
+ if (o?.replace) win?.history.replaceState(null, '', href);
51
+ else win?.history.pushState(null, '', href);
52
+ emit('navigation', 'goto', { path: href, seq: ++seq });
53
+ }
54
+ return { status: 'done' as const, path: href };
55
+ };
56
+
57
+ const handlers: Record<string, Record<string, Handler>> = {
58
+ tenant: { get: () => ({ id: opts.tenantId ?? null }) },
59
+ locale: { get: () => opts.locale ?? win?.navigator?.language ?? 'fr' },
60
+ config: { get: () => ({ ...(opts.config ?? {}) }) },
61
+ flags: { isEnabled: ([name]) => !!opts.flags?.[name as string] },
62
+ telemetry: {
63
+ log: (a) => void opts.onTelemetry?.('log', a),
64
+ metric: (a) => void opts.onTelemetry?.('metric', a),
65
+ },
66
+ lifecycle: { ready: () => undefined },
67
+ extensions: { list: () => [] },
68
+ events: { publish: ([topic, payload]) => void emit('events', topic as string, payload) },
69
+ notifications: { show: () => ({ displayed: false }) },
70
+ dialogs: {
71
+ confirm: async ([d]) => {
72
+ if (opts.confirm) return !!(await opts.confirm(d as never));
73
+ const g = globalThis as { confirm?: (m: string) => boolean };
74
+ if (typeof g.confirm === 'function') return g.confirm(String((d as Json).message));
75
+ throw unsupported('dialogs.confirm');
76
+ },
77
+ },
78
+ navigation: {
79
+ report: ([path, o]) => {
80
+ const replace = !!(o as Json | undefined)?.replace;
81
+ const title = (o as Json | undefined)?.title as string | undefined;
82
+ if (win) (replace ? win.history.replaceState : win.history.pushState).call(win.history, null, '', path as string);
83
+ if (title && win) win.document.title = title;
84
+ },
85
+ navigate: ([to, o]) => navigateLocal(to as string, o as NavigateOptions | undefined),
86
+ current: () => {
87
+ const l = win?.location;
88
+ const u = new URL(`${l?.pathname ?? '/'}${l?.search ?? ''}${l?.hash ?? ''}`, 'http://app.invalid');
89
+ return { path: u.pathname, query: Object.fromEntries(u.searchParams), hash: u.hash, title: win?.document.title };
90
+ },
91
+ exists: async ([path]) => {
92
+ if (!opts.routeExists) throw unsupported('navigation.exists');
93
+ return !!(await opts.routeExists(path as string));
94
+ },
95
+ back: () => void win?.history.back(),
96
+ canGoBack: () => (win?.history.length ?? 0) > 1,
97
+ intent: async ([slug, params, o]) => {
98
+ if (!opts.intents) throw unsupported('navigation.intent');
99
+ const target = await opts.intents(slug as string, (params as Json | undefined) ?? {});
100
+ if (target === null) throw new EmbedError('NOT_FOUND', `Intent inconnu : ${slug}`);
101
+ return navigateLocal(target, o as NavigateOptions | undefined);
102
+ },
103
+ notFound: () => undefined,
104
+ setTitle: ([t]) => {
105
+ if (win) win.document.title = t as string;
106
+ },
107
+ resize: () => undefined,
108
+ },
109
+ };
110
+
111
+ return {
112
+ get closed() {
113
+ return closed;
114
+ },
115
+ async call<T>(cap: string, method: string, args: unknown[] = []): Promise<T> {
116
+ if (closed) throw new EmbedError('CLOSED', 'Connexion fermée');
117
+ const invalid = validateCall(cap, method, args);
118
+ if (invalid) throw new EmbedError('INVALID_ARGS', invalid);
119
+ const h = handlers[cap]?.[method];
120
+ if (!h) throw unsupported(`${cap}.${method}`);
121
+ return (await h(args)) as T;
122
+ },
123
+ async subscribe(cap: string, ev: string, cb: (v: unknown) => void) {
124
+ if (closed) throw new EmbedError('CLOSED', 'Connexion fermée');
125
+ const key = `${cap}:${ev}`;
126
+ let set = listeners.get(key);
127
+ if (!set) listeners.set(key, (set = new Set()));
128
+ set.add(cb);
129
+ return () => void set!.delete(cb);
130
+ },
131
+ close() {
132
+ doc?.removeEventListener?.('visibilitychange', onVisibility);
133
+ closed = true;
134
+ listeners.clear();
135
+ },
136
+ };
137
+ }
138
+
139
+ /** Capacités servies localement en mode autonome. */
140
+ export const STANDALONE_CAPABILITIES: readonly CapabilityId[] = ['tenant', 'locale', 'config', 'flags', 'telemetry', 'lifecycle', 'extensions', 'events', 'notifications', 'dialogs', 'navigation'];
package/src/version.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Version de la façade SDK. Générée depuis le package.json par `scripts/sync-sdk-version.mjs` ; `version.test.ts` garde la cohérence. */
2
+ export const SDK_VERSION = '0.4.0';