@plugmatica/plugin-sdk 0.0.0-stage → 0.1.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/host.js ADDED
@@ -0,0 +1,2280 @@
1
+ import { createPluginRuntime, PluginRuntimeProvider } from './chunk-ACHELRPS.js';
2
+ import { compareRuntimeExtensions } from './chunk-AFVR6B2A.js';
3
+ import { UiExtensionValidationError } from '@plugmatica/ui-kit';
4
+ import { getInstance } from '@module-federation/enhanced/runtime';
5
+ import * as React from 'react';
6
+ import { useCallback, useSyncExternalStore, useState, useEffect, useMemo, Component } from 'react';
7
+ import { ExtensionBoundary, useUiExtensionEnvironmentKey } from '@plugmatica/ui-kit/host';
8
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
9
+ import { ScopedI18nGate } from '@plugmatica/i18n';
10
+ import { isStandardExtensionSurface, validateStandardContribution } from '@plugmatica/core-sdk';
11
+
12
+ // src/extensionRuntimePrimitives.ts
13
+ function pickExtensionCandidate(value) {
14
+ if (value === null || typeof value !== "object") return value;
15
+ const record = value;
16
+ if ("extension" in record) return pickExtensionCandidate(record.extension);
17
+ if ("default" in record) return pickExtensionCandidate(record.default);
18
+ return record;
19
+ }
20
+ function extensionRuntimeNow() {
21
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
22
+ }
23
+ function extensionErrorMessage(value) {
24
+ return value instanceof Error ? value.message : String(value);
25
+ }
26
+
27
+ // src/runtimeErrors.ts
28
+ var FederatedModuleLoadError = class extends Error {
29
+ /**
30
+ * Stable machine-readable code.
31
+ */
32
+ code;
33
+ /**
34
+ * Identifier of the plugin associated with this operation.
35
+ */
36
+ pluginIdentifier;
37
+ /**
38
+ * Module Federation expose name or generated contribution module path.
39
+ */
40
+ module;
41
+ /**
42
+ * Resolved Module Federation entry URL.
43
+ */
44
+ remoteUrl;
45
+ /**
46
+ * Module Federation remote name.
47
+ */
48
+ remoteName;
49
+ /**
50
+ * Whether callers may safely retry the failed load/resolve operation.
51
+ */
52
+ retryable;
53
+ constructor(options) {
54
+ super(
55
+ options.message,
56
+ options.cause === void 0 ? void 0 : { cause: options.cause }
57
+ );
58
+ this.name = "FederatedModuleLoadError";
59
+ this.code = options.code;
60
+ this.pluginIdentifier = options.pluginIdentifier;
61
+ this.module = options.module;
62
+ this.remoteUrl = options.remoteUrl;
63
+ this.remoteName = options.remoteName;
64
+ this.retryable = options.retryable;
65
+ }
66
+ };
67
+ var UiExtensionRuntimeError = class extends Error {
68
+ /**
69
+ * Stable machine-readable code.
70
+ */
71
+ code;
72
+ /**
73
+ * Stable runtime extension identifier.
74
+ */
75
+ extensionId;
76
+ /**
77
+ * Extension key associated with this ui extension runtime error.
78
+ */
79
+ extensionKey;
80
+ /**
81
+ * Identifier of the plugin associated with this operation.
82
+ */
83
+ pluginIdentifier;
84
+ /**
85
+ * Identifier of the plugin whose surface/operation is targeted.
86
+ */
87
+ targetPluginIdentifier;
88
+ /**
89
+ * Module Federation expose name or generated contribution module path.
90
+ */
91
+ module;
92
+ /**
93
+ * Whether callers may safely retry the failed load/resolve operation.
94
+ */
95
+ retryable;
96
+ constructor(options) {
97
+ super(
98
+ options.message,
99
+ options.cause === void 0 ? void 0 : { cause: options.cause }
100
+ );
101
+ this.name = "UiExtensionRuntimeError";
102
+ this.code = options.code;
103
+ this.extensionId = options.item.id;
104
+ this.extensionKey = options.item.extensionKey;
105
+ this.pluginIdentifier = options.item.pluginIdentifier;
106
+ this.targetPluginIdentifier = options.item.targetPluginIdentifier;
107
+ this.module = options.item.module;
108
+ this.retryable = Boolean(options.retryable);
109
+ }
110
+ };
111
+ function toFederatedModuleLoadError(value, context) {
112
+ if (value instanceof FederatedModuleLoadError) return value;
113
+ const raw = value instanceof Error ? value.message : String(value);
114
+ const lower = raw.toLowerCase();
115
+ let code;
116
+ let advice;
117
+ let retryable = true;
118
+ if (lower.includes("invalid federated module")) {
119
+ code = "invalid_module";
120
+ retryable = false;
121
+ advice = "Use a package expose such as './plugin' or './extensions/customer-tab'.";
122
+ } else if (lower.includes("module federation is not initialized")) {
123
+ code = "federation_unavailable";
124
+ retryable = false;
125
+ advice = "Ensure the runtime shell initializes Module Federation before rendering plugins.";
126
+ } else if (/not exposed|unknown expose|expose.*not found|module.*not found|cannot find module|does not exist|unknown module/.test(
127
+ lower
128
+ )) {
129
+ code = "stale_manifest_module_mismatch";
130
+ advice = "The runtime manifest and deployed remote appear out of sync. Rebuild/publish the plugin and refresh runtime bootstrap data.";
131
+ } else {
132
+ code = "remote_unavailable";
133
+ advice = "Check the plugin remote entry, installation state, network availability, and deployment health, then retry.";
134
+ }
135
+ const remote = context.remoteUrl ? ` from '${context.remoteUrl}'` : "";
136
+ return new FederatedModuleLoadError({
137
+ code,
138
+ pluginIdentifier: context.pluginIdentifier,
139
+ module: context.module,
140
+ remoteUrl: context.remoteUrl,
141
+ remoteName: context.remoteName,
142
+ retryable,
143
+ cause: value,
144
+ message: `Unable to load plugin '${context.pluginIdentifier}' module '${context.module}'${remote}. ${advice} Cause: ${raw}`
145
+ });
146
+ }
147
+ function emptyFederatedModuleError(context) {
148
+ return new FederatedModuleLoadError({
149
+ code: "empty_module",
150
+ pluginIdentifier: context.pluginIdentifier,
151
+ module: context.module,
152
+ remoteUrl: context.remoteUrl,
153
+ remoteName: context.remoteName,
154
+ retryable: false,
155
+ message: `Plugin '${context.pluginIdentifier}' module '${context.module}' resolved to an empty value. Rebuild the plugin and verify the manifest module expose matches the deployed remote.`
156
+ });
157
+ }
158
+ function toUiExtensionRuntimeError(item, value, phase = "resolve") {
159
+ if (value instanceof UiExtensionRuntimeError) return value;
160
+ if (value instanceof FederatedModuleLoadError) {
161
+ return new UiExtensionRuntimeError({
162
+ code: value.code === "stale_manifest_module_mismatch" || value.code === "empty_module" ? "extension_manifest_module_mismatch" : "extension_module_unavailable",
163
+ item,
164
+ retryable: value.retryable,
165
+ cause: value,
166
+ message: `Extension '${item.id}' from plugin '${item.pluginIdentifier}' could not load module '${item.module}'. ${value.message}`
167
+ });
168
+ }
169
+ const raw = value instanceof Error ? value.message : String(value);
170
+ return new UiExtensionRuntimeError({
171
+ code: phase === "render" ? "extension_render_failed" : "extension_contract_invalid",
172
+ item,
173
+ retryable: false,
174
+ cause: value,
175
+ message: `Extension '${item.id}' from plugin '${item.pluginIdentifier}' failed during ${phase}. ${raw}`
176
+ });
177
+ }
178
+
179
+ // src/FederatedRemoteRegistry.ts
180
+ var FederatedRemoteRegistry = class {
181
+ #current = /* @__PURE__ */ new Map();
182
+ /**
183
+ * Return current federated remote registration statistics.
184
+ *
185
+ * @returns Result returned by stats.
186
+ */
187
+ get stats() {
188
+ return Object.freeze({
189
+ registrations: this.#current.size,
190
+ generations: Object.freeze(
191
+ [...this.#current.values()].map((v) => Object.freeze({ ...v })).sort((a, b) => a.registrationName.localeCompare(b.registrationName))
192
+ )
193
+ });
194
+ }
195
+ /**
196
+ * Ensure the currently resolved remote is registered and return its generation.
197
+ *
198
+ * @param adapter Module Federation runtime adapter.
199
+ * @param value Resolved plugin remote descriptor.
200
+ * @returns Result returned by ensure.
201
+ */
202
+ ensure(adapter2, value) {
203
+ const key = owner(value.pluginIdentifier, value.producerName);
204
+ const existing = this.#current.get(key);
205
+ if (existing?.entry === value.entry)
206
+ return Object.freeze({ registration: existing, replaced: false });
207
+ const registrationName = stableRegistrationName(
208
+ value.pluginIdentifier,
209
+ value.producerName
210
+ );
211
+ adapter2.register(
212
+ {
213
+ name: registrationName,
214
+ entry: value.entry,
215
+ producerName: value.producerName
216
+ },
217
+ Boolean(existing)
218
+ );
219
+ const next = Object.freeze({
220
+ ...value,
221
+ registrationName,
222
+ generation: (existing?.generation ?? 0) + 1
223
+ });
224
+ this.#current.set(key, next);
225
+ return Object.freeze({ registration: next, replaced: Boolean(existing) });
226
+ }
227
+ /**
228
+ * Invalidate all remote registrations associated with one plugin identifier.
229
+ *
230
+ * @param adapter Module Federation runtime adapter.
231
+ * @param pluginIdentifier Plugin identifier to resolve/load.
232
+ */
233
+ invalidatePlugin(adapter2, pluginIdentifier) {
234
+ for (const [key, value] of [...this.#current])
235
+ if (value.pluginIdentifier === pluginIdentifier) {
236
+ try {
237
+ adapter2.unregister?.(value.registrationName);
238
+ } catch {
239
+ }
240
+ this.#current.delete(key);
241
+ }
242
+ }
243
+ /**
244
+ * Remove every registration tracked by this registry.
245
+ *
246
+ * @param adapter Module Federation runtime adapter.
247
+ */
248
+ reset(adapter2) {
249
+ for (const value of this.#current.values()) {
250
+ try {
251
+ adapter2.unregister?.(value.registrationName);
252
+ } catch {
253
+ }
254
+ }
255
+ this.#current.clear();
256
+ }
257
+ };
258
+ function owner(pluginIdentifier, producerName) {
259
+ return `${pluginIdentifier}::${producerName}`;
260
+ }
261
+ function stableRegistrationName(pluginIdentifier, producerName) {
262
+ return `pm_${pluginIdentifier.replace(/[^a-zA-Z0-9_]/g, "_")}_${simpleHash(producerName)}`;
263
+ }
264
+ function simpleHash(value) {
265
+ let hash = 2166136261;
266
+ for (let i = 0; i < value.length; i += 1) {
267
+ hash ^= value.charCodeAt(i);
268
+ hash = Math.imul(hash, 16777619);
269
+ }
270
+ return (hash >>> 0).toString(16);
271
+ }
272
+
273
+ // src/FederatedModuleCache.ts
274
+ var FederatedModuleCache = class {
275
+ #resolved = /* @__PURE__ */ new Map();
276
+ #inFlight = /* @__PURE__ */ new Map();
277
+ #versions = /* @__PURE__ */ new Map();
278
+ #epoch = 0;
279
+ #hits = 0;
280
+ #inFlightJoins = 0;
281
+ #misses = 0;
282
+ #loadsStarted = 0;
283
+ #loadsCompleted = 0;
284
+ #loadsFailed = 0;
285
+ get stats() {
286
+ return Object.freeze({
287
+ resolvedEntries: this.#resolved.size,
288
+ inFlightEntries: this.#inFlight.size,
289
+ hits: this.#hits,
290
+ inFlightJoins: this.#inFlightJoins,
291
+ misses: this.#misses,
292
+ loadsStarted: this.#loadsStarted,
293
+ loadsCompleted: this.#loadsCompleted,
294
+ loadsFailed: this.#loadsFailed
295
+ });
296
+ }
297
+ has(key) {
298
+ return this.#resolved.has(key);
299
+ }
300
+ /**
301
+ * A component prepared from an asynchronous module load may be cached only
302
+ * while its *same* resolved module remains current. Uninstall, a new remote
303
+ * entry, and a reset all invalidate stale in-flight resolutions.
304
+ */
305
+ isCurrentResolved(key, value) {
306
+ return this.#resolved.has(key) && Object.is(this.#resolved.get(key), value);
307
+ }
308
+ async load(key, loader) {
309
+ if (this.#resolved.has(key)) {
310
+ this.#hits += 1;
311
+ return this.#resolved.get(key);
312
+ }
313
+ const existing = this.#inFlight.get(key);
314
+ if (existing) {
315
+ this.#inFlightJoins += 1;
316
+ return existing;
317
+ }
318
+ this.#misses += 1;
319
+ this.#loadsStarted += 1;
320
+ const version = this.#versions.get(key) ?? 0;
321
+ const epoch = this.#epoch;
322
+ const pending = Promise.resolve().then(loader);
323
+ this.#inFlight.set(key, pending);
324
+ try {
325
+ const value = await pending;
326
+ if (this.#epoch === epoch && (this.#versions.get(key) ?? 0) === version && this.#inFlight.get(key) === pending) {
327
+ this.#resolved.set(key, value);
328
+ }
329
+ this.#loadsCompleted += 1;
330
+ return value;
331
+ } catch (error) {
332
+ this.#loadsFailed += 1;
333
+ throw error;
334
+ } finally {
335
+ if (this.#inFlight.get(key) === pending) {
336
+ this.#inFlight.delete(key);
337
+ }
338
+ }
339
+ }
340
+ invalidate(key) {
341
+ const resolved = this.#resolved.delete(key);
342
+ const pending = this.#inFlight.delete(key);
343
+ this.#versions.set(key, (this.#versions.get(key) ?? 0) + 1);
344
+ return resolved || pending;
345
+ }
346
+ invalidateWhere(predicate) {
347
+ let count = 0;
348
+ for (const key of [...this.#resolved.keys(), ...this.#inFlight.keys()]) {
349
+ if (predicate(key) && this.invalidate(key)) count += 1;
350
+ }
351
+ return count;
352
+ }
353
+ clear() {
354
+ this.#epoch += 1;
355
+ this.#resolved.clear();
356
+ this.#inFlight.clear();
357
+ this.#versions.clear();
358
+ }
359
+ reset() {
360
+ this.clear();
361
+ this.#hits = 0;
362
+ this.#inFlightJoins = 0;
363
+ this.#misses = 0;
364
+ this.#loadsStarted = 0;
365
+ this.#loadsCompleted = 0;
366
+ this.#loadsFailed = 0;
367
+ }
368
+ };
369
+
370
+ // src/FederatedPluginLifecycle.ts
371
+ var FederatedPluginLifecycle = class {
372
+ #sequence = 0;
373
+ #resetRevision = 0;
374
+ #revisions = /* @__PURE__ */ new Map();
375
+ #listeners = /* @__PURE__ */ new Map();
376
+ revision(identifier) {
377
+ return this.#revisions.get(identifier) ?? this.#resetRevision;
378
+ }
379
+ subscribe(identifier, callback) {
380
+ let listeners = this.#listeners.get(identifier);
381
+ if (!listeners) {
382
+ listeners = /* @__PURE__ */ new Set();
383
+ this.#listeners.set(identifier, listeners);
384
+ }
385
+ listeners.add(callback);
386
+ return () => {
387
+ listeners?.delete(callback);
388
+ if (listeners?.size === 0) this.#listeners.delete(identifier);
389
+ };
390
+ }
391
+ invalidate(identifier) {
392
+ this.#revisions.set(identifier, ++this.#sequence);
393
+ for (const notify of [...this.#listeners.get(identifier) ?? []]) notify();
394
+ }
395
+ reset() {
396
+ this.#resetRevision = ++this.#sequence;
397
+ this.#revisions.clear();
398
+ for (const listeners of [...this.#listeners.values()]) {
399
+ for (const notify of [...listeners]) notify();
400
+ }
401
+ }
402
+ };
403
+
404
+ // src/useFederatedPlugin.ts
405
+ var federatedModuleCache = new FederatedModuleCache();
406
+ var federatedPluginCache = /* @__PURE__ */ new Map();
407
+ var remoteRegistry = new FederatedRemoteRegistry();
408
+ var federatedPluginLifecycle = new FederatedPluginLifecycle();
409
+ var devCacheBustToken = typeof window !== "undefined" ? String(Date.now()) : "0";
410
+ function asError(value) {
411
+ return value instanceof Error ? value : new Error(String(value));
412
+ }
413
+ function shouldBustFederationCache() {
414
+ return typeof window !== "undefined" && (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1");
415
+ }
416
+ function defaultRemoteUrl(identifier) {
417
+ const query = new URLSearchParams();
418
+ if (shouldBustFederationCache()) query.set("t", devCacheBustToken);
419
+ const q = query.toString();
420
+ return `/api/plugins/${encodeURIComponent(identifier)}/assets/remoteEntry.js${q ? `?${q}` : ""}`;
421
+ }
422
+ function defaultRemoteName(identifier) {
423
+ return identifier.replace(/[^a-zA-Z0-9_]/g, "_");
424
+ }
425
+ function normalizeExpose(module) {
426
+ const value = module.trim().replace(/^\.\//, "");
427
+ if (!value || value.startsWith("/") || value.includes("\\") || value.split("/").some((v) => !v || v === "." || v === ".."))
428
+ throw new Error(`Invalid federated module '${module}'.`);
429
+ return value;
430
+ }
431
+ function resolveFederatedRequest(identifier, module, remoteUrl, remoteName) {
432
+ const expose = normalizeExpose(module?.trim() || "./plugin");
433
+ const entry = remoteUrl?.trim() || defaultRemoteUrl(identifier);
434
+ const producerName = remoteName?.trim() || defaultRemoteName(identifier);
435
+ const cacheKey = [identifier, producerName, expose, entry].join("::");
436
+ return { expose, entry, producerName, cacheKey };
437
+ }
438
+ function federationRuntime() {
439
+ const runtime = getInstance();
440
+ if (!runtime)
441
+ throw new Error("No Module Federation runtime instance exists.");
442
+ return runtime;
443
+ }
444
+ function adapter() {
445
+ const runtime = federationRuntime();
446
+ return {
447
+ register(value, force) {
448
+ runtime.registerRemotes(
449
+ [
450
+ {
451
+ name: value.name,
452
+ entry: value.entry,
453
+ type: "module",
454
+ entryGlobalName: value.producerName
455
+ }
456
+ ],
457
+ { force }
458
+ );
459
+ },
460
+ unregister(name) {
461
+ const r = runtime;
462
+ r.removeRemote?.(name);
463
+ }
464
+ };
465
+ }
466
+ function pickPluginExport(value) {
467
+ if (typeof value === "function") return value;
468
+ if (!value || typeof value !== "object") return null;
469
+ const r = value;
470
+ if (typeof r.plugin === "function") return r.plugin;
471
+ if (typeof r.default === "function") return r.default;
472
+ if (r.default && typeof r.default === "object") {
473
+ const n = r.default;
474
+ if (typeof n.plugin === "function") return n.plugin;
475
+ if (typeof n.default === "function") return n.default;
476
+ }
477
+ return null;
478
+ }
479
+ async function loadFederatedModule(identifier, module, remoteUrl, remoteName) {
480
+ const { expose, entry, producerName, cacheKey } = resolveFederatedRequest(
481
+ identifier,
482
+ module,
483
+ remoteUrl,
484
+ remoteName
485
+ );
486
+ return federatedModuleCache.load(cacheKey, async () => {
487
+ const runtime = federationRuntime();
488
+ const remote = remoteRegistry.ensure(adapter(), {
489
+ pluginIdentifier: identifier,
490
+ producerName,
491
+ entry
492
+ });
493
+ if (remote.replaced) {
494
+ federatedModuleCache.invalidateWhere(
495
+ (key) => key.startsWith(`${identifier}::`) && key !== cacheKey
496
+ );
497
+ for (const key of [...federatedPluginCache.keys()]) {
498
+ if (key.startsWith(`${identifier}::`) && key !== cacheKey) {
499
+ federatedPluginCache.delete(key);
500
+ }
501
+ }
502
+ federatedPluginLifecycle.invalidate(identifier);
503
+ }
504
+ const result = await runtime.loadRemote(
505
+ `${remote.registration.registrationName}/${expose}`
506
+ );
507
+ if (result == null)
508
+ throw new Error(
509
+ `Federated module '${identifier}/${expose}' resolved to an empty value.`
510
+ );
511
+ return result;
512
+ });
513
+ }
514
+ async function preloadFederatedPlugin(identifier, module = "./plugin", remoteUrl, remoteName) {
515
+ const { cacheKey } = resolveFederatedRequest(
516
+ identifier,
517
+ module,
518
+ remoteUrl,
519
+ remoteName
520
+ );
521
+ const cached = federatedPluginCache.get(cacheKey);
522
+ if (cached) return cached;
523
+ const resolved = await loadFederatedModule(
524
+ identifier,
525
+ module,
526
+ remoteUrl,
527
+ remoteName
528
+ );
529
+ const plugin = pickPluginExport(resolved);
530
+ if (!plugin) {
531
+ throw new Error(
532
+ `Plugin '${identifier}' module '${module}' did not export a React plugin component.`
533
+ );
534
+ }
535
+ if (federatedModuleCache.isCurrentResolved(cacheKey, resolved)) {
536
+ federatedPluginCache.set(cacheKey, plugin);
537
+ }
538
+ return plugin;
539
+ }
540
+ function invalidateFederatedPluginModules(identifier) {
541
+ federatedModuleCache.invalidateWhere((key) => key.startsWith(`${identifier}::`));
542
+ for (const key of [...federatedPluginCache.keys()]) {
543
+ if (key.startsWith(`${identifier}::`)) federatedPluginCache.delete(key);
544
+ }
545
+ try {
546
+ remoteRegistry.invalidatePlugin(adapter(), identifier);
547
+ } catch {
548
+ }
549
+ federatedPluginLifecycle.invalidate(identifier);
550
+ }
551
+ function resetFederatedModuleCache() {
552
+ federatedModuleCache.clear();
553
+ federatedPluginCache.clear();
554
+ try {
555
+ remoteRegistry.reset(adapter());
556
+ } catch {
557
+ }
558
+ federatedPluginLifecycle.reset();
559
+ }
560
+ function getFederatedModuleCacheStats() {
561
+ const stats = federatedModuleCache.stats;
562
+ return { entries: stats.resolvedEntries + stats.inFlightEntries };
563
+ }
564
+ function getFederatedRuntimeStats() {
565
+ return {
566
+ moduleCache: getFederatedModuleCacheStats(),
567
+ remoteRegistry: remoteRegistry.stats
568
+ };
569
+ }
570
+ function useFederatedPlugin(identifier, module = "./plugin", remoteUrl, remoteName) {
571
+ const { cacheKey } = resolveFederatedRequest(
572
+ identifier,
573
+ module,
574
+ remoteUrl,
575
+ remoteName
576
+ );
577
+ const subscribe = useCallback(
578
+ (notify) => federatedPluginLifecycle.subscribe(identifier, notify),
579
+ [identifier]
580
+ );
581
+ const getRevision = useCallback(
582
+ () => federatedPluginLifecycle.revision(identifier),
583
+ [identifier]
584
+ );
585
+ const revision = useSyncExternalStore(subscribe, getRevision, getRevision);
586
+ const requestKey = `${cacheKey}::generation:${revision}`;
587
+ const cachedPlugin = federatedPluginCache.get(cacheKey) ?? null;
588
+ const [state, setState] = useState(() => ({
589
+ key: requestKey,
590
+ plugin: cachedPlugin,
591
+ error: null,
592
+ loading: !cachedPlugin
593
+ }));
594
+ useEffect(() => {
595
+ let cancelled = false;
596
+ const cached = federatedPluginCache.get(cacheKey) ?? null;
597
+ if (cached) {
598
+ setState({ key: requestKey, plugin: cached, error: null, loading: false });
599
+ return () => {
600
+ cancelled = true;
601
+ };
602
+ }
603
+ setState({ key: requestKey, plugin: null, error: null, loading: true });
604
+ void preloadFederatedPlugin(identifier, module, remoteUrl, remoteName).then((plugin) => {
605
+ if (!cancelled && federatedPluginLifecycle.revision(identifier) === revision && federatedPluginCache.get(cacheKey) === plugin) {
606
+ setState({ key: requestKey, plugin, error: null, loading: false });
607
+ }
608
+ }).catch((error) => {
609
+ if (!cancelled && federatedPluginLifecycle.revision(identifier) === revision) {
610
+ setState({
611
+ key: requestKey,
612
+ plugin: null,
613
+ error: asError(error),
614
+ loading: false
615
+ });
616
+ }
617
+ });
618
+ return () => {
619
+ cancelled = true;
620
+ };
621
+ }, [cacheKey, identifier, module, remoteName, remoteUrl, requestKey, revision]);
622
+ if (state.key !== requestKey) {
623
+ return {
624
+ plugin: cachedPlugin,
625
+ error: null,
626
+ loading: !cachedPlugin,
627
+ revision
628
+ };
629
+ }
630
+ return {
631
+ plugin: state.plugin,
632
+ error: state.error,
633
+ loading: state.loading,
634
+ revision
635
+ };
636
+ }
637
+
638
+ // src/ExtensionExecutionRuntime.ts
639
+ var ExtensionExecutionRuntime = class {
640
+ #options;
641
+ constructor(options) {
642
+ this.#options = options;
643
+ }
644
+ /**
645
+ * Execute one host operation through matched operation hooks.
646
+ *
647
+ * @param request Request payload/options for this operation.
648
+ * @returns Result returned by runOperation.
649
+ */
650
+ async runOperation(request) {
651
+ assertNotAborted(request.signal);
652
+ if (this.#options.extensionIndex.operationHooks(
653
+ this.#options.targetPluginIdentifier,
654
+ request.surface,
655
+ request.surfaceKey,
656
+ request.operation
657
+ ).length === 0) {
658
+ return {
659
+ status: "completed",
660
+ execution: "owner",
661
+ result: await request.execute(request.payload)
662
+ };
663
+ }
664
+ const correlationId = createCorrelationId("operation");
665
+ const startedAt = extensionRuntimeNow();
666
+ const hooks = await this.#loadHooks(
667
+ request.surface,
668
+ request.surfaceKey,
669
+ request.operation,
670
+ correlationId,
671
+ request.signal
672
+ );
673
+ let payload = request.payload;
674
+ let result;
675
+ let executionError;
676
+ const operationTarget = {
677
+ targetPluginIdentifier: this.#options.targetPluginIdentifier,
678
+ surface: request.surface,
679
+ surfaceKey: request.surfaceKey,
680
+ instanceKey: request.instanceKey,
681
+ operation: request.operation,
682
+ correlationId
683
+ };
684
+ this.#emit({
685
+ level: "debug",
686
+ area: "operation_hook",
687
+ action: "operation",
688
+ status: "started",
689
+ message: `Started ${request.surface}:${request.surfaceKey}:${request.operation}.`,
690
+ ...operationTarget,
691
+ details: {
692
+ hookCount: hooks.length,
693
+ ...request.extensionContext !== void 0 ? { extensionContext: request.extensionContext } : {}
694
+ }
695
+ });
696
+ try {
697
+ for (const hook of hooks) {
698
+ assertNotAborted(request.signal);
699
+ if (hook.item.phases.includes("before") && hook.module.normalize) {
700
+ payload = await this.#runHookPhase(
701
+ hook,
702
+ "before",
703
+ "normalize",
704
+ correlationId,
705
+ () => hook.module.normalize(
706
+ this.#hookContext(hook, "before", request, payload, result)
707
+ )
708
+ );
709
+ }
710
+ }
711
+ const issues = [];
712
+ for (const hook of hooks) {
713
+ assertNotAborted(request.signal);
714
+ if (hook.item.phases.includes("before") && hook.module.validate) {
715
+ const next = await this.#runHookPhase(
716
+ hook,
717
+ "before",
718
+ "validate",
719
+ correlationId,
720
+ () => hook.module.validate(
721
+ this.#hookContext(hook, "before", request, payload, result)
722
+ )
723
+ );
724
+ if (next) {
725
+ issues.push(...next);
726
+ }
727
+ }
728
+ }
729
+ if (issues.length > 0) {
730
+ throw new UiExtensionValidationError(issues);
731
+ }
732
+ let execution = "owner";
733
+ let cancelled = false;
734
+ for (const hook of hooks) {
735
+ assertNotAborted(request.signal);
736
+ if (!hook.item.phases.includes("before") || !hook.module.before) {
737
+ continue;
738
+ }
739
+ const decision = await this.#runHookPhase(
740
+ hook,
741
+ "before",
742
+ "before",
743
+ correlationId,
744
+ () => hook.module.before(
745
+ this.#hookContext(hook, "before", request, payload, result)
746
+ )
747
+ );
748
+ if (decision.kind === "continue") {
749
+ if (decision.payload !== void 0)
750
+ payload = decision.payload;
751
+ continue;
752
+ }
753
+ if (decision.kind === "cancel") {
754
+ result = decision.result;
755
+ execution = "none";
756
+ cancelled = true;
757
+ break;
758
+ }
759
+ result = decision.result;
760
+ execution = "replacement";
761
+ break;
762
+ }
763
+ if (!cancelled && execution === "owner") {
764
+ assertNotAborted(request.signal);
765
+ result = await request.execute(payload);
766
+ }
767
+ if (!cancelled)
768
+ for (const hook of [...hooks].reverse()) {
769
+ assertNotAborted(request.signal);
770
+ if (!hook.item.phases.includes("after") || !hook.module.after) {
771
+ continue;
772
+ }
773
+ const next = await this.#runHookPhase(
774
+ hook,
775
+ "after",
776
+ "after",
777
+ correlationId,
778
+ () => hook.module.after(
779
+ this.#hookContext(hook, "after", request, payload, result)
780
+ )
781
+ );
782
+ if (next !== void 0) {
783
+ result = next;
784
+ }
785
+ }
786
+ this.#emit({
787
+ level: "info",
788
+ area: "operation_hook",
789
+ action: "operation",
790
+ status: "completed",
791
+ message: `Completed ${request.surface}:${request.surfaceKey}:${request.operation}.`,
792
+ ...operationTarget,
793
+ durationMs: extensionRuntimeNow() - startedAt,
794
+ details: { hookCount: hooks.length }
795
+ });
796
+ return {
797
+ status: cancelled ? "cancelled" : "completed",
798
+ execution,
799
+ result
800
+ };
801
+ } catch (error) {
802
+ executionError = error;
803
+ for (const hook of [...hooks].reverse()) {
804
+ if (!hook.item.phases.includes("error") || !hook.module.error) {
805
+ continue;
806
+ }
807
+ await this.#safeHook(
808
+ hook,
809
+ "error",
810
+ correlationId,
811
+ () => hook.module.error(
812
+ this.#hookContext(hook, "error", request, payload, result, error)
813
+ )
814
+ );
815
+ }
816
+ this.#emit({
817
+ level: "error",
818
+ area: "operation_hook",
819
+ action: "operation",
820
+ status: "failed",
821
+ message: extensionErrorMessage(error),
822
+ ...operationTarget,
823
+ durationMs: extensionRuntimeNow() - startedAt,
824
+ details: { hookCount: hooks.length }
825
+ });
826
+ throw error;
827
+ } finally {
828
+ for (const hook of [...hooks].reverse()) {
829
+ if (!hook.item.phases.includes("finally") || !hook.module.finally) {
830
+ continue;
831
+ }
832
+ await this.#safeHook(
833
+ hook,
834
+ "finally",
835
+ correlationId,
836
+ () => hook.module.finally(
837
+ this.#hookContext(
838
+ hook,
839
+ "finally",
840
+ request,
841
+ payload,
842
+ result,
843
+ executionError
844
+ )
845
+ )
846
+ );
847
+ }
848
+ }
849
+ }
850
+ /**
851
+ * Emit one event through all matched event handlers.
852
+ *
853
+ * @param request Request payload/options for this operation.
854
+ * @returns Completes when the operation finishes.
855
+ */
856
+ async emitEvent(request) {
857
+ await this.#dispatchIndexed(
858
+ "event",
859
+ request.event,
860
+ request.payload,
861
+ request.signal
862
+ );
863
+ }
864
+ /**
865
+ * Resolve values from all providers matching one provider request.
866
+ *
867
+ * @param request Request payload/options for this operation.
868
+ * @returns Result returned by resolveProviders.
869
+ */
870
+ async resolveProviders(request) {
871
+ return this.#dispatchIndexed(
872
+ "provider",
873
+ request.provider,
874
+ request.request,
875
+ request.signal
876
+ );
877
+ }
878
+ /**
879
+ * Events and providers share indexed dispatch, loading and failure isolation.
880
+ * Their distinct invocation contracts and observer fields remain explicit.
881
+ */
882
+ async #dispatchIndexed(kind, name, payload, signal) {
883
+ assertNotAborted(signal);
884
+ const isEvent = kind === "event";
885
+ const items = isEvent ? this.#options.extensionIndex.events(
886
+ this.#options.targetPluginIdentifier,
887
+ name
888
+ ) : this.#options.extensionIndex.providers(
889
+ this.#options.targetPluginIdentifier,
890
+ name
891
+ );
892
+ if (items.length === 0) return [];
893
+ const correlationId = createCorrelationId(kind);
894
+ const area = isEvent ? "event_handler" : "provider";
895
+ const target = isEvent ? { event: name } : { provider: name };
896
+ this.#emit({
897
+ level: "debug",
898
+ area,
899
+ action: isEvent ? "event_dispatch" : "provider_resolution",
900
+ status: "started",
901
+ message: isEvent ? `Dispatching '${name}' to ${items.length} handler(s).` : `Resolving '${name}' from ${items.length} provider(s).`,
902
+ targetPluginIdentifier: this.#options.targetPluginIdentifier,
903
+ ...target,
904
+ correlationId,
905
+ details: isEvent ? { handlerCount: items.length } : { providerCount: items.length }
906
+ });
907
+ const values = [];
908
+ for (const item of items) {
909
+ assertNotAborted(signal);
910
+ const startedAt = extensionRuntimeNow();
911
+ try {
912
+ const context = this.#options.resolveContext(item);
913
+ await context.i18n?.ensureReady(signal);
914
+ const candidate = pickExtensionCandidate(
915
+ await this.#load(item.pluginIdentifier, item.module)
916
+ );
917
+ if (isEvent) {
918
+ const handler = candidate;
919
+ if (!handler || typeof handler.handle !== "function") {
920
+ throw new Error(
921
+ `Event handler '${item.id}' must export handle(context).`
922
+ );
923
+ }
924
+ await handler.handle({
925
+ context,
926
+ extension: item,
927
+ event: name,
928
+ payload,
929
+ signal
930
+ });
931
+ } else {
932
+ const provider = candidate;
933
+ if (!provider || typeof provider.provide !== "function") {
934
+ throw new Error(
935
+ `Provider '${item.id}' must export provide(context).`
936
+ );
937
+ }
938
+ values.push(
939
+ await provider.provide({
940
+ context,
941
+ extension: item,
942
+ provider: name,
943
+ request: payload,
944
+ signal
945
+ })
946
+ );
947
+ }
948
+ this.#emit({
949
+ level: "info",
950
+ area,
951
+ action: isEvent ? "handler" : "provider",
952
+ status: "completed",
953
+ message: isEvent ? `Handled '${name}' with '${item.id}'.` : `Resolved '${name}' with '${item.id}'.`,
954
+ pluginIdentifier: item.pluginIdentifier,
955
+ targetPluginIdentifier: item.targetPluginIdentifier,
956
+ extensionId: item.id,
957
+ extensionKind: item.kind,
958
+ ...target,
959
+ module: item.module,
960
+ correlationId,
961
+ durationMs: extensionRuntimeNow() - startedAt
962
+ });
963
+ } catch (error) {
964
+ this.#emitFailure(area, item, error, {
965
+ ...target,
966
+ correlationId,
967
+ durationMs: extensionRuntimeNow() - startedAt
968
+ });
969
+ }
970
+ }
971
+ return values;
972
+ }
973
+ async #loadHooks(surface, surfaceKey, operation, correlationId, signal) {
974
+ const items = this.#options.extensionIndex.operationHooks(
975
+ this.#options.targetPluginIdentifier,
976
+ surface,
977
+ surfaceKey,
978
+ operation
979
+ );
980
+ return Promise.all(
981
+ items.map(async (item) => {
982
+ const startedAt = extensionRuntimeNow();
983
+ try {
984
+ const context = this.#options.resolveContext(item);
985
+ await context.i18n?.ensureReady(signal);
986
+ const candidate = pickExtensionCandidate(
987
+ await this.#load(item.pluginIdentifier, item.module)
988
+ );
989
+ if (!candidate || typeof candidate !== "object") {
990
+ throw new Error(
991
+ `Operation hook '${item.id}' did not export an object.`
992
+ );
993
+ }
994
+ this.#emit({
995
+ level: "debug",
996
+ area: "operation_hook",
997
+ action: "hook_load",
998
+ status: "completed",
999
+ message: `Loaded operation hook '${item.id}'.`,
1000
+ pluginIdentifier: item.pluginIdentifier,
1001
+ targetPluginIdentifier: item.targetPluginIdentifier,
1002
+ extensionId: item.id,
1003
+ extensionKind: item.kind,
1004
+ surface,
1005
+ surfaceKey,
1006
+ operation,
1007
+ module: item.module,
1008
+ correlationId,
1009
+ durationMs: extensionRuntimeNow() - startedAt
1010
+ });
1011
+ return {
1012
+ item,
1013
+ module: candidate,
1014
+ context
1015
+ };
1016
+ } catch (error) {
1017
+ this.#emitFailure("operation_hook", item, error, {
1018
+ phase: "load",
1019
+ surface,
1020
+ surfaceKey,
1021
+ operation,
1022
+ correlationId
1023
+ });
1024
+ throw error;
1025
+ }
1026
+ })
1027
+ );
1028
+ }
1029
+ #hookContext(hook, phase, request, payload, result, error) {
1030
+ return {
1031
+ context: hook.context,
1032
+ extension: hook.item,
1033
+ surface: request.surface,
1034
+ surfaceKey: request.surfaceKey,
1035
+ instanceKey: request.instanceKey,
1036
+ extensionContext: request.extensionContext,
1037
+ operation: request.operation,
1038
+ phase,
1039
+ payload,
1040
+ result,
1041
+ error,
1042
+ signal: request.signal
1043
+ };
1044
+ }
1045
+ async #runHookPhase(hook, phase, action, correlationId, callback) {
1046
+ const startedAt = extensionRuntimeNow();
1047
+ const hookTarget = {
1048
+ pluginIdentifier: hook.item.pluginIdentifier,
1049
+ targetPluginIdentifier: hook.item.targetPluginIdentifier,
1050
+ extensionId: hook.item.id,
1051
+ extensionKind: hook.item.kind,
1052
+ surface: hook.item.target.surface,
1053
+ surfaceKey: hook.item.target.key,
1054
+ operation: hook.item.target.operation,
1055
+ phase,
1056
+ module: hook.item.module,
1057
+ correlationId
1058
+ };
1059
+ this.#emit({
1060
+ level: "debug",
1061
+ area: "operation_hook",
1062
+ action,
1063
+ status: "started",
1064
+ message: `Running ${action} for '${hook.item.id}'.`,
1065
+ ...hookTarget
1066
+ });
1067
+ try {
1068
+ const value = await callback();
1069
+ this.#emit({
1070
+ level: "debug",
1071
+ area: "operation_hook",
1072
+ action,
1073
+ status: "completed",
1074
+ message: `Completed ${action} for '${hook.item.id}'.`,
1075
+ ...hookTarget,
1076
+ durationMs: extensionRuntimeNow() - startedAt
1077
+ });
1078
+ return value;
1079
+ } catch (error) {
1080
+ this.#emitFailure("operation_hook", hook.item, error, {
1081
+ phase,
1082
+ action,
1083
+ correlationId,
1084
+ durationMs: extensionRuntimeNow() - startedAt
1085
+ });
1086
+ throw error;
1087
+ }
1088
+ }
1089
+ async #safeHook(hook, phase, correlationId, callback) {
1090
+ try {
1091
+ await this.#runHookPhase(hook, phase, phase, correlationId, callback);
1092
+ } catch {
1093
+ }
1094
+ }
1095
+ async #load(pluginIdentifier, module) {
1096
+ const remote = this.#options.resolveRemote(pluginIdentifier);
1097
+ const loader = this.#options.loadModule ?? loadFederatedModule;
1098
+ try {
1099
+ return await loader(
1100
+ pluginIdentifier,
1101
+ module,
1102
+ remote?.entry,
1103
+ remote?.name
1104
+ );
1105
+ } catch (error) {
1106
+ throw toFederatedModuleLoadError(error, {
1107
+ pluginIdentifier,
1108
+ module,
1109
+ ...remote?.entry ? { remoteUrl: remote.entry } : {},
1110
+ ...remote?.name ? { remoteName: remote.name } : {}
1111
+ });
1112
+ }
1113
+ }
1114
+ #emitFailure(area, item, error, details) {
1115
+ this.#emit({
1116
+ level: "error",
1117
+ area,
1118
+ action: "execution",
1119
+ status: "failed",
1120
+ message: extensionErrorMessage(error),
1121
+ pluginIdentifier: item.pluginIdentifier,
1122
+ targetPluginIdentifier: item.targetPluginIdentifier,
1123
+ extensionId: item.id,
1124
+ extensionKind: item.kind,
1125
+ module: item.module,
1126
+ details
1127
+ });
1128
+ }
1129
+ #emit(event) {
1130
+ this.#options.observer?.emit(event);
1131
+ }
1132
+ };
1133
+ function assertNotAborted(signal) {
1134
+ if (signal?.aborted) {
1135
+ throw signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted.", "AbortError");
1136
+ }
1137
+ }
1138
+ function createCorrelationId(prefix) {
1139
+ const id = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
1140
+ return `${prefix}:${id}`;
1141
+ }
1142
+ function ExtensionHost({
1143
+ resolver,
1144
+ surface,
1145
+ surfaceKey,
1146
+ point,
1147
+ instanceKey,
1148
+ extensionContext,
1149
+ payload,
1150
+ active = true,
1151
+ failurePolicy = "fallback",
1152
+ loadingFallback = null,
1153
+ emptyFallback = null,
1154
+ errorFallback,
1155
+ className,
1156
+ itemClassName
1157
+ }) {
1158
+ const extensionEnvironmentKey = useUiExtensionEnvironmentKey();
1159
+ const stablePayload = useShallowStablePayload(payload);
1160
+ const routePath = resolver.routePath;
1161
+ const [state, setState] = React.useState({
1162
+ resolved: !active,
1163
+ loading: active,
1164
+ error: null,
1165
+ entries: []
1166
+ });
1167
+ React.useEffect(() => {
1168
+ let cancelled = false;
1169
+ const controller = new AbortController();
1170
+ if (!active) {
1171
+ setState({ resolved: true, loading: false, error: null, entries: [] });
1172
+ return () => {
1173
+ cancelled = true;
1174
+ controller.abort();
1175
+ };
1176
+ }
1177
+ setState((current) => ({ ...current, loading: true, error: null }));
1178
+ void resolver.resolveRenderableSettled({
1179
+ surface,
1180
+ surfaceKey,
1181
+ point,
1182
+ instanceKey,
1183
+ extensionContext,
1184
+ payload: stablePayload,
1185
+ signal: controller.signal
1186
+ }).then((entries) => {
1187
+ if (!cancelled) {
1188
+ setState({ resolved: true, loading: false, error: null, entries });
1189
+ }
1190
+ }).catch((value) => {
1191
+ if (!cancelled) {
1192
+ const error = value instanceof Error ? value : new Error(String(value));
1193
+ resolver.observer?.emit({
1194
+ level: "error",
1195
+ area: "ui_extension",
1196
+ action: "surface_resolution",
1197
+ status: "failed",
1198
+ message: error.message,
1199
+ targetPluginIdentifier: resolver.targetPluginIdentifier,
1200
+ surface,
1201
+ surfaceKey,
1202
+ point,
1203
+ routePath: resolver.routePath
1204
+ });
1205
+ setState((current) => ({
1206
+ resolved: true,
1207
+ loading: false,
1208
+ error,
1209
+ entries: current.entries
1210
+ }));
1211
+ }
1212
+ });
1213
+ return () => {
1214
+ cancelled = true;
1215
+ controller.abort(
1216
+ new DOMException(
1217
+ "Extension surface resolution became stale.",
1218
+ "AbortError"
1219
+ )
1220
+ );
1221
+ };
1222
+ }, [
1223
+ active,
1224
+ extensionEnvironmentKey,
1225
+ extensionContext,
1226
+ instanceKey,
1227
+ point,
1228
+ resolver,
1229
+ stablePayload,
1230
+ surface,
1231
+ surfaceKey
1232
+ ]);
1233
+ if (!active) {
1234
+ return /* @__PURE__ */ jsx(Fragment, { children: emptyFallback });
1235
+ }
1236
+ if (state.loading && !state.resolved) {
1237
+ return /* @__PURE__ */ jsx(Fragment, { children: loadingFallback });
1238
+ }
1239
+ if (state.error) {
1240
+ if (failurePolicy === "fail-page") throw state.error;
1241
+ if (failurePolicy === "ignore") return /* @__PURE__ */ jsx(Fragment, { children: emptyFallback });
1242
+ return /* @__PURE__ */ jsx(Fragment, { children: errorFallback?.(state.error) ?? defaultFailureFallback(state.error) });
1243
+ }
1244
+ const failures = state.entries.filter((entry) => entry.status === "failed");
1245
+ if (failures.length > 0 && failurePolicy === "fail-page") {
1246
+ throw failures[0].error;
1247
+ }
1248
+ if (failures.length > 0 && failurePolicy === "fail-surface") {
1249
+ const error = aggregateSurfaceFailure(
1250
+ failures.map((entry) => entry.error),
1251
+ surface,
1252
+ surfaceKey,
1253
+ point
1254
+ );
1255
+ return /* @__PURE__ */ jsx(Fragment, { children: errorFallback?.(error) ?? defaultFailureFallback(error) });
1256
+ }
1257
+ const visibleEntries = failurePolicy === "ignore" ? state.entries.filter((entry) => entry.status === "loaded") : state.entries;
1258
+ if (visibleEntries.length === 0) {
1259
+ return /* @__PURE__ */ jsx(Fragment, { children: emptyFallback });
1260
+ }
1261
+ const content = /* @__PURE__ */ jsx(
1262
+ "div",
1263
+ {
1264
+ className,
1265
+ "data-extension-host-surface": surface,
1266
+ "data-extension-host-key": surfaceKey,
1267
+ "data-extension-host-point": point,
1268
+ "data-extension-target-plugin": resolver.targetPluginIdentifier,
1269
+ "data-extension-failure-policy": failurePolicy,
1270
+ children: visibleEntries.map(
1271
+ (resolution) => resolution.status === "failed" ? /* @__PURE__ */ jsx(
1272
+ FailedHostedExtension,
1273
+ {
1274
+ item: resolution.item,
1275
+ error: resolution.error,
1276
+ errorFallback
1277
+ },
1278
+ resolution.item.id
1279
+ ) : /* @__PURE__ */ jsx(
1280
+ HostedExtension,
1281
+ {
1282
+ resolver,
1283
+ entry: resolution.entry,
1284
+ surface,
1285
+ surfaceKey,
1286
+ point,
1287
+ instanceKey,
1288
+ extensionContext,
1289
+ payload: stablePayload,
1290
+ routePath,
1291
+ className: itemClassName,
1292
+ failurePolicy,
1293
+ errorFallback
1294
+ },
1295
+ resolution.item.id
1296
+ )
1297
+ )
1298
+ }
1299
+ );
1300
+ if (failurePolicy !== "fail-surface") return content;
1301
+ return /* @__PURE__ */ jsx(
1302
+ ExtensionBoundary,
1303
+ {
1304
+ resetKey: `${surface}:${surfaceKey}:${point}`,
1305
+ fallback: ({ error }) => errorFallback?.(error) ?? defaultFailureFallback(error),
1306
+ onError: (error) => {
1307
+ resolver.observer?.emit({
1308
+ level: "error",
1309
+ area: "ui_extension",
1310
+ action: "surface_render",
1311
+ status: "failed",
1312
+ message: error.message,
1313
+ targetPluginIdentifier: resolver.targetPluginIdentifier,
1314
+ surface,
1315
+ surfaceKey,
1316
+ point,
1317
+ routePath: resolver.routePath
1318
+ });
1319
+ },
1320
+ children: content
1321
+ }
1322
+ );
1323
+ }
1324
+ function FailedHostedExtension({
1325
+ item,
1326
+ error,
1327
+ errorFallback
1328
+ }) {
1329
+ return /* @__PURE__ */ jsx(
1330
+ "div",
1331
+ {
1332
+ "data-extension-id": item.id,
1333
+ "data-extension-source-plugin": item.pluginIdentifier,
1334
+ "data-extension-kind": "ui",
1335
+ "data-extension-status": "failed",
1336
+ children: errorFallback?.(error) ?? defaultFailureFallback(error)
1337
+ }
1338
+ );
1339
+ }
1340
+ function HostedExtensionImpl({
1341
+ resolver,
1342
+ entry,
1343
+ surface,
1344
+ surfaceKey,
1345
+ point,
1346
+ instanceKey,
1347
+ extensionContext,
1348
+ payload,
1349
+ routePath,
1350
+ className,
1351
+ failurePolicy,
1352
+ errorFallback
1353
+ }) {
1354
+ const entryRef = React.useRef(entry);
1355
+ entryRef.current = entry;
1356
+ const runtime = React.useMemo(
1357
+ () => createPluginRuntime(entry.context),
1358
+ [entry.context]
1359
+ );
1360
+ const renderSignal = useMountedExtensionSignal([
1361
+ entry.item.id,
1362
+ instanceKey,
1363
+ point,
1364
+ resolver,
1365
+ surface,
1366
+ surfaceKey
1367
+ ]);
1368
+ const renderContext = React.useMemo(
1369
+ () => ({
1370
+ context: entry.context,
1371
+ extension: entry.item,
1372
+ surface,
1373
+ surfaceKey,
1374
+ point,
1375
+ instanceKey,
1376
+ extensionContext,
1377
+ routePath,
1378
+ payload,
1379
+ signal: renderSignal
1380
+ }),
1381
+ [
1382
+ entry.context,
1383
+ entry.item,
1384
+ extensionContext,
1385
+ instanceKey,
1386
+ payload,
1387
+ point,
1388
+ renderSignal,
1389
+ routePath,
1390
+ surface,
1391
+ surfaceKey
1392
+ ]
1393
+ );
1394
+ React.useEffect(() => {
1395
+ const mountedEntry = entryRef.current;
1396
+ const lifecycleController = new AbortController();
1397
+ const lifecycleContext = {
1398
+ context: mountedEntry.context,
1399
+ extension: mountedEntry.item,
1400
+ surface,
1401
+ surfaceKey,
1402
+ point,
1403
+ instanceKey,
1404
+ extensionContext,
1405
+ routePath: resolver.routePath,
1406
+ signal: lifecycleController.signal
1407
+ };
1408
+ resolver.observer?.emit({
1409
+ level: "debug",
1410
+ area: "ui_extension",
1411
+ action: "mount",
1412
+ status: "completed",
1413
+ message: `Mounted '${mountedEntry.item.id}'.`,
1414
+ pluginIdentifier: mountedEntry.item.pluginIdentifier,
1415
+ targetPluginIdentifier: mountedEntry.item.targetPluginIdentifier,
1416
+ extensionId: mountedEntry.item.id,
1417
+ extensionKind: mountedEntry.item.kind,
1418
+ surface,
1419
+ surfaceKey,
1420
+ point,
1421
+ module: mountedEntry.item.module,
1422
+ routePath: resolver.routePath
1423
+ });
1424
+ void runLifecycle(
1425
+ "onMount",
1426
+ () => mountedEntry.module.lifecycle?.onMount?.(lifecycleContext),
1427
+ resolver,
1428
+ mountedEntry,
1429
+ surface,
1430
+ surfaceKey,
1431
+ point
1432
+ );
1433
+ return () => {
1434
+ lifecycleController.abort(
1435
+ new DOMException("Extension instance unmounted.", "AbortError")
1436
+ );
1437
+ void runLifecycle(
1438
+ "onUnmount",
1439
+ () => mountedEntry.module.lifecycle?.onUnmount?.(lifecycleContext),
1440
+ resolver,
1441
+ mountedEntry,
1442
+ surface,
1443
+ surfaceKey,
1444
+ point
1445
+ );
1446
+ resolver.observer?.emit({
1447
+ level: "debug",
1448
+ area: "ui_extension",
1449
+ action: "unmount",
1450
+ status: "completed",
1451
+ message: `Unmounted '${mountedEntry.item.id}'.`,
1452
+ pluginIdentifier: mountedEntry.item.pluginIdentifier,
1453
+ targetPluginIdentifier: mountedEntry.item.targetPluginIdentifier,
1454
+ extensionId: mountedEntry.item.id,
1455
+ extensionKind: mountedEntry.item.kind,
1456
+ surface,
1457
+ surfaceKey,
1458
+ point,
1459
+ module: mountedEntry.item.module,
1460
+ routePath: resolver.routePath
1461
+ });
1462
+ };
1463
+ }, [
1464
+ entry.item.id,
1465
+ extensionContext,
1466
+ instanceKey,
1467
+ point,
1468
+ resolver,
1469
+ surface,
1470
+ surfaceKey
1471
+ ]);
1472
+ const content = /* @__PURE__ */ jsx(PluginRuntimeProvider, { value: runtime, children: /* @__PURE__ */ jsx(
1473
+ ExtensionModuleContent,
1474
+ {
1475
+ entry,
1476
+ renderContext,
1477
+ className
1478
+ }
1479
+ ) });
1480
+ return /* @__PURE__ */ jsx(
1481
+ ExtensionBoundary,
1482
+ {
1483
+ resetKey: entry.item.id,
1484
+ onError: (error) => {
1485
+ const wrapped = toUiExtensionRuntimeError(entry.item, error, "render");
1486
+ resolver.observer?.emit({
1487
+ level: "error",
1488
+ area: "ui_extension",
1489
+ action: "render",
1490
+ status: "failed",
1491
+ message: wrapped.message,
1492
+ pluginIdentifier: entry.item.pluginIdentifier,
1493
+ targetPluginIdentifier: entry.item.targetPluginIdentifier,
1494
+ extensionId: entry.item.id,
1495
+ extensionKind: entry.item.kind,
1496
+ surface,
1497
+ surfaceKey,
1498
+ point,
1499
+ module: entry.item.module,
1500
+ routePath,
1501
+ details: {
1502
+ code: wrapped.code,
1503
+ retryable: wrapped.retryable,
1504
+ ...instanceKey ? { instanceKey } : {}
1505
+ }
1506
+ });
1507
+ },
1508
+ fallback: ({ error }) => {
1509
+ const wrapped = toUiExtensionRuntimeError(entry.item, error, "render");
1510
+ if (failurePolicy === "ignore") return null;
1511
+ if (failurePolicy === "fail-surface" || failurePolicy === "fail-page") {
1512
+ return /* @__PURE__ */ jsx(RethrowExtensionFailure, { error: wrapped });
1513
+ }
1514
+ return errorFallback?.(wrapped) ?? defaultFailureFallback(wrapped);
1515
+ },
1516
+ children: content
1517
+ }
1518
+ );
1519
+ }
1520
+ var HostedExtension = React.memo(
1521
+ HostedExtensionImpl
1522
+ );
1523
+ function useMountedExtensionSignal(dependencies) {
1524
+ const lifetime = React.useMemo(
1525
+ () => ({ controller: new AbortController(), mounted: false }),
1526
+ dependencies
1527
+ );
1528
+ React.useEffect(() => {
1529
+ lifetime.mounted = true;
1530
+ return () => {
1531
+ lifetime.mounted = false;
1532
+ queueMicrotask(() => {
1533
+ if (!lifetime.mounted && !lifetime.controller.signal.aborted) {
1534
+ lifetime.controller.abort(
1535
+ new DOMException(
1536
+ "Extension render context became stale.",
1537
+ "AbortError"
1538
+ )
1539
+ );
1540
+ }
1541
+ });
1542
+ };
1543
+ }, [lifetime]);
1544
+ return lifetime.controller.signal;
1545
+ }
1546
+ function ExtensionModuleContent({
1547
+ entry,
1548
+ renderContext,
1549
+ className
1550
+ }) {
1551
+ return /* @__PURE__ */ jsx(
1552
+ "div",
1553
+ {
1554
+ className,
1555
+ "data-extension-id": entry.item.id,
1556
+ "data-extension-source-plugin": entry.item.pluginIdentifier,
1557
+ "data-extension-kind": "ui",
1558
+ "data-extension-status": "loaded",
1559
+ children: entry.module.render(renderContext)
1560
+ }
1561
+ );
1562
+ }
1563
+ function RethrowExtensionFailure({ error }) {
1564
+ throw error;
1565
+ }
1566
+ function defaultFailureFallback(error) {
1567
+ return /* @__PURE__ */ jsx("div", { role: "alert", "data-extension-fallback": "true", children: error.message });
1568
+ }
1569
+ function aggregateSurfaceFailure(errors, surface, surfaceKey, point) {
1570
+ const identities = errors.map((error) => `${error.pluginIdentifier}:${error.extensionId}`).join(", ");
1571
+ return new Error(
1572
+ `Extension surface '${surface}:${surfaceKey}:${point}' failed because ${errors.length} contribution(s) could not be loaded: ${identities}.`,
1573
+ { cause: errors[0] }
1574
+ );
1575
+ }
1576
+ function useShallowStablePayload(value) {
1577
+ const ref = React.useRef(value);
1578
+ if (!shallowPayloadEqual(ref.current, value)) {
1579
+ ref.current = value;
1580
+ }
1581
+ return ref.current;
1582
+ }
1583
+ function shallowPayloadEqual(left, right) {
1584
+ if (Object.is(left, right)) return true;
1585
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") {
1586
+ return false;
1587
+ }
1588
+ if (Array.isArray(left) || Array.isArray(right)) {
1589
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
1590
+ return false;
1591
+ }
1592
+ return left.every((value, index) => Object.is(value, right[index]));
1593
+ }
1594
+ const leftPrototype = Object.getPrototypeOf(left);
1595
+ const rightPrototype = Object.getPrototypeOf(right);
1596
+ const plainPrototype = leftPrototype === Object.prototype || leftPrototype === null;
1597
+ if (!plainPrototype || leftPrototype !== rightPrototype) return false;
1598
+ const leftKeys = Reflect.ownKeys(left);
1599
+ const rightKeys = Reflect.ownKeys(right);
1600
+ if (leftKeys.length !== rightKeys.length) return false;
1601
+ const leftRecord = left;
1602
+ const rightRecord = right;
1603
+ return leftKeys.every(
1604
+ (key) => Object.prototype.hasOwnProperty.call(rightRecord, key) && Object.is(leftRecord[key], rightRecord[key])
1605
+ );
1606
+ }
1607
+ async function runLifecycle(action, callback, resolver, entry, surface, surfaceKey, point) {
1608
+ try {
1609
+ await callback();
1610
+ } catch (value) {
1611
+ const error = value instanceof Error ? value : new Error(String(value));
1612
+ resolver.observer?.emit({
1613
+ level: "error",
1614
+ area: "ui_extension",
1615
+ action,
1616
+ status: "failed",
1617
+ message: error.message,
1618
+ pluginIdentifier: entry.item.pluginIdentifier,
1619
+ targetPluginIdentifier: entry.item.targetPluginIdentifier,
1620
+ extensionId: entry.item.id,
1621
+ extensionKind: entry.item.kind,
1622
+ surface,
1623
+ surfaceKey,
1624
+ point,
1625
+ module: entry.item.module,
1626
+ routePath: resolver.routePath,
1627
+ details: { stack: error.stack }
1628
+ });
1629
+ }
1630
+ }
1631
+ var PluginRuntimeObserverContext = React.createContext(null);
1632
+ function PluginRuntimeObserverProvider({
1633
+ observer,
1634
+ children
1635
+ }) {
1636
+ return /* @__PURE__ */ jsx(PluginRuntimeObserverContext.Provider, { value: observer, children });
1637
+ }
1638
+ function usePluginRuntimeObserver() {
1639
+ return React.useContext(PluginRuntimeObserverContext);
1640
+ }
1641
+ function PluginRenderer({
1642
+ identifier,
1643
+ module,
1644
+ remoteName,
1645
+ remoteUrl,
1646
+ context,
1647
+ loadingFallback = /* @__PURE__ */ jsx("div", { children: "Loading plugin..." }),
1648
+ errorFallback
1649
+ }) {
1650
+ const runtime = useMemo(() => createPluginRuntime(context), [context]);
1651
+ useEffect(() => {
1652
+ void preloadFederatedPlugin(
1653
+ identifier,
1654
+ module ?? "./plugin",
1655
+ remoteUrl,
1656
+ remoteName
1657
+ ).catch(() => void 0);
1658
+ }, [identifier, module, remoteName, remoteUrl]);
1659
+ return /* @__PURE__ */ jsx(
1660
+ ScopedI18nGate,
1661
+ {
1662
+ api: runtime.i18n,
1663
+ fallback: loadingFallback,
1664
+ errorFallback: (i18nError) => errorFallback?.(i18nError) ?? /* @__PURE__ */ jsxs("div", { role: "alert", children: [
1665
+ "Plugin translations failed to load: ",
1666
+ i18nError.message
1667
+ ] }),
1668
+ children: /* @__PURE__ */ jsx(
1669
+ FederatedPluginRenderer,
1670
+ {
1671
+ identifier,
1672
+ module,
1673
+ remoteName,
1674
+ remoteUrl,
1675
+ runtime,
1676
+ loadingFallback,
1677
+ errorFallback
1678
+ }
1679
+ )
1680
+ }
1681
+ );
1682
+ }
1683
+ function FederatedPluginRenderer({
1684
+ identifier,
1685
+ module,
1686
+ remoteName,
1687
+ remoteUrl,
1688
+ runtime,
1689
+ loadingFallback,
1690
+ errorFallback
1691
+ }) {
1692
+ const { plugin, error, loading, revision } = useFederatedPlugin(
1693
+ identifier,
1694
+ module,
1695
+ remoteUrl,
1696
+ remoteName
1697
+ );
1698
+ if (error) {
1699
+ return /* @__PURE__ */ jsx(Fragment, { children: errorFallback ? errorFallback(error) : `Error loading plugin: ${error.message}` });
1700
+ }
1701
+ if (loading || !plugin) {
1702
+ return /* @__PURE__ */ jsx(Fragment, { children: loadingFallback });
1703
+ }
1704
+ const PluginComponent = plugin;
1705
+ const boundaryKey = [
1706
+ identifier,
1707
+ remoteName ?? "",
1708
+ remoteUrl ?? "",
1709
+ module ?? "./plugin",
1710
+ // Force a new boundary and component state after an extension's removal,
1711
+ // upgrade or reinstall even when its public URL remains unchanged.
1712
+ revision
1713
+ ].join(":");
1714
+ return /* @__PURE__ */ jsx(PluginRenderBoundary, { errorFallback, children: /* @__PURE__ */ jsx(PluginRuntimeProvider, { value: runtime, children: /* @__PURE__ */ jsx(PluginComponent, {}) }) }, boundaryKey);
1715
+ }
1716
+ var PluginRenderBoundary = class extends Component {
1717
+ state = { error: null };
1718
+ static getDerivedStateFromError(error) {
1719
+ return { error };
1720
+ }
1721
+ componentDidCatch(error, info) {
1722
+ console.error("Plugin render failed", error, info);
1723
+ }
1724
+ render() {
1725
+ const { error } = this.state;
1726
+ if (!error) return this.props.children;
1727
+ if (this.props.errorFallback) return this.props.errorFallback(error);
1728
+ return /* @__PURE__ */ jsxs("div", { role: "alert", children: [
1729
+ /* @__PURE__ */ jsx("strong", { children: "Plugin failed to render:" }),
1730
+ " ",
1731
+ error.message
1732
+ ] });
1733
+ }
1734
+ };
1735
+
1736
+ // src/ExtensionRegistrationCoordinator.ts
1737
+ var ExtensionRegistrationCoordinator = class {
1738
+ #state = /* @__PURE__ */ new Map();
1739
+ run(key, transition) {
1740
+ const existing = this.#state.get(key);
1741
+ if (existing) return existing;
1742
+ const pending = Promise.resolve().then(transition);
1743
+ this.#state.set(key, pending);
1744
+ void pending.catch(() => {
1745
+ if (this.#state.get(key) === pending) this.#state.delete(key);
1746
+ });
1747
+ return pending;
1748
+ }
1749
+ has(key) {
1750
+ return this.#state.has(key);
1751
+ }
1752
+ reset() {
1753
+ this.#state.clear();
1754
+ }
1755
+ };
1756
+ var UiExtensionResolver = class {
1757
+ #options;
1758
+ #registrationState = new ExtensionRegistrationCoordinator();
1759
+ constructor(options) {
1760
+ this.#options = options;
1761
+ }
1762
+ /**
1763
+ * Return the host runtime observer configured for this resolver.
1764
+ *
1765
+ * @returns Result returned by observer.
1766
+ */
1767
+ get observer() {
1768
+ return this.#options.observer;
1769
+ }
1770
+ /**
1771
+ * Return the plugin identifier owning the target surface.
1772
+ *
1773
+ * @returns Result returned by targetPluginIdentifier.
1774
+ */
1775
+ get targetPluginIdentifier() {
1776
+ return this.#options.targetPluginIdentifier;
1777
+ }
1778
+ /**
1779
+ * Return the route path used to build extension lifecycle context.
1780
+ *
1781
+ * @returns Result returned by routePath.
1782
+ */
1783
+ get routePath() {
1784
+ const value = this.#options.routePath;
1785
+ return typeof value === "function" ? value() : value;
1786
+ }
1787
+ /**
1788
+ * Return normalized UI extensions matching one surface/key/point.
1789
+ *
1790
+ * @param surface Extension surface to query.
1791
+ * @param surfaceKey Stable semantic key for the target surface.
1792
+ * @param point Extension point within the surface.
1793
+ * @returns Result returned by matching.
1794
+ */
1795
+ matching(surface, surfaceKey, point) {
1796
+ const matches = this.#options.extensionIndex.ui(
1797
+ this.#options.targetPluginIdentifier,
1798
+ surface,
1799
+ surfaceKey,
1800
+ point
1801
+ );
1802
+ if (matches.length > 0) {
1803
+ this.#options.observer?.emit({
1804
+ level: "debug",
1805
+ area: "ui_extension",
1806
+ action: "match",
1807
+ status: "matched",
1808
+ message: `${matches.length} extension(s) matched ${surface}:${surfaceKey}:${point}.`,
1809
+ targetPluginIdentifier: this.#options.targetPluginIdentifier,
1810
+ surface,
1811
+ surfaceKey,
1812
+ point,
1813
+ routePath: this.routePath,
1814
+ details: {
1815
+ matchedExtensionIds: matches.map((item) => item.id)
1816
+ }
1817
+ });
1818
+ }
1819
+ return matches;
1820
+ }
1821
+ async #ensureRegistered(item, module, context, request) {
1822
+ const registrationKey = `${item.pluginIdentifier}@${item.pluginVersion}:${item.id}`;
1823
+ await this.#registrationState.run(registrationKey, async () => {
1824
+ const lifecycleContext = {
1825
+ context,
1826
+ extension: item,
1827
+ surface: request.surface,
1828
+ surfaceKey: request.surfaceKey,
1829
+ point: request.point,
1830
+ instanceKey: request.instanceKey,
1831
+ extensionContext: request.extensionContext,
1832
+ routePath: this.routePath,
1833
+ signal: lifecycleSignal(request.signal)
1834
+ };
1835
+ await this.#safeLifecycle(
1836
+ item,
1837
+ "onRegister",
1838
+ () => module.lifecycle?.onRegister?.(lifecycleContext)
1839
+ );
1840
+ });
1841
+ }
1842
+ /**
1843
+ * Resolve matching renderable extensions, throwing according to normal resolver semantics.
1844
+ *
1845
+ * @param request Request payload/options for this operation.
1846
+ * @returns Result returned by resolveRenderable.
1847
+ */
1848
+ async resolveRenderable(request) {
1849
+ const settled = await this.resolveRenderableSettled(request);
1850
+ return settled.filter(
1851
+ (value) => value.status === "loaded"
1852
+ ).map((value) => value.entry);
1853
+ }
1854
+ /**
1855
+ * Resolve only the modules for the requested rendered surface while retaining
1856
+ * individual failures. ExtensionHost uses this to isolate one broken third-
1857
+ * party contribution without hiding the identity of the offender.
1858
+ */
1859
+ /**
1860
+ * @param request Request payload/options for this operation.
1861
+ * @returns Result returned by resolveRenderableSettled.
1862
+ */
1863
+ async resolveRenderableSettled(request) {
1864
+ const matches = this.matching(
1865
+ request.surface,
1866
+ request.surfaceKey,
1867
+ request.point
1868
+ );
1869
+ if (matches.length === 0) {
1870
+ return [];
1871
+ }
1872
+ assertNotAborted2(request.signal);
1873
+ const settled = await Promise.all(
1874
+ matches.map(
1875
+ async (item) => {
1876
+ try {
1877
+ const sourceContext = this.#options.resolveContext(item);
1878
+ await sourceContext.i18n?.ensureReady(request.signal);
1879
+ const module = await this.#loadModule(item);
1880
+ assertNotAborted2(request.signal);
1881
+ const candidate = pickExtensionCandidate(module);
1882
+ let entry;
1883
+ if (typeof candidate === "function") {
1884
+ const Component2 = candidate;
1885
+ const renderable = {
1886
+ render: () => /* @__PURE__ */ jsx(Component2, {})
1887
+ };
1888
+ entry = await this.#prepare(
1889
+ item,
1890
+ renderable,
1891
+ sourceContext,
1892
+ request
1893
+ );
1894
+ } else {
1895
+ if (!candidate || typeof candidate !== "object" || typeof candidate.render !== "function") {
1896
+ throw new Error(
1897
+ `Extension '${item.id}' must export a zero-prop React component or render(context).`
1898
+ );
1899
+ }
1900
+ entry = await this.#prepare(
1901
+ item,
1902
+ candidate,
1903
+ sourceContext,
1904
+ request
1905
+ );
1906
+ }
1907
+ return entry ? { status: "loaded", entry, item, order: entry.order } : null;
1908
+ } catch (error) {
1909
+ if (isAbortError(error)) throw error;
1910
+ const resolvedError = toUiExtensionRuntimeError(item, error);
1911
+ this.#emitUiFailure(
1912
+ item,
1913
+ resolvedError,
1914
+ request,
1915
+ "resolve_renderable"
1916
+ );
1917
+ return {
1918
+ status: "failed",
1919
+ item,
1920
+ error: resolvedError,
1921
+ order: item.order
1922
+ };
1923
+ }
1924
+ }
1925
+ )
1926
+ );
1927
+ const resolved = settled.filter(
1928
+ (value) => value !== null
1929
+ ).sort((left, right) => compareRuntimeExtensions(left.item, right.item));
1930
+ const failures = resolved.filter(
1931
+ (entry) => entry.status === "failed"
1932
+ );
1933
+ const loaded = resolved.filter(
1934
+ (entry) => entry.status === "loaded"
1935
+ );
1936
+ this.#options.observer?.emit({
1937
+ level: failures.length > 0 ? "warning" : "info",
1938
+ area: "ui_extension",
1939
+ action: "resolve_renderable",
1940
+ status: "completed",
1941
+ message: `Resolved ${loaded.length} renderable extension(s) with ${failures.length} isolated failure(s) for ${request.surface}:${request.surfaceKey}:${request.point}.`,
1942
+ targetPluginIdentifier: this.#options.targetPluginIdentifier,
1943
+ surface: request.surface,
1944
+ surfaceKey: request.surfaceKey,
1945
+ point: request.point,
1946
+ routePath: this.routePath,
1947
+ details: {
1948
+ resolvedExtensionIds: loaded.map((entry) => entry.item.id),
1949
+ failedExtensionIds: failures.map((entry) => entry.item.id)
1950
+ }
1951
+ });
1952
+ return resolved;
1953
+ }
1954
+ /**
1955
+ * Resolve and flatten structured contributions for one surface point.
1956
+ *
1957
+ * @param request Request payload/options for this operation.
1958
+ * @returns Result returned by resolveContributions.
1959
+ */
1960
+ async resolveContributions(request) {
1961
+ const matches = this.matching(
1962
+ request.surface,
1963
+ request.surfaceKey,
1964
+ request.point
1965
+ );
1966
+ if (matches.length === 0) {
1967
+ return [];
1968
+ }
1969
+ assertNotAborted2(request.signal);
1970
+ const results = await Promise.all(
1971
+ matches.map(
1972
+ async (item) => {
1973
+ try {
1974
+ const sourceContext = this.#options.resolveContext(item);
1975
+ await sourceContext.i18n?.ensureReady(request.signal);
1976
+ const loaded = await this.#loadModule(item);
1977
+ assertNotAborted2(request.signal);
1978
+ const candidate = pickExtensionCandidate(loaded);
1979
+ if (!candidate || typeof candidate !== "object" || typeof candidate.contribute !== "function") {
1980
+ throw new Error(
1981
+ `Structured extension '${item.id}' must export contribute(context).`
1982
+ );
1983
+ }
1984
+ const module = candidate;
1985
+ const renderContext = this.#renderContext(
1986
+ sourceContext,
1987
+ item,
1988
+ request
1989
+ );
1990
+ await this.#ensureRegistered(item, module, sourceContext, request);
1991
+ if (module.visible && !await module.visible(renderContext)) {
1992
+ this.#options.observer?.emit({
1993
+ level: "debug",
1994
+ area: "ui_extension",
1995
+ action: "visibility",
1996
+ status: "skipped",
1997
+ message: `Structured extension '${item.id}' is not visible.`,
1998
+ pluginIdentifier: item.pluginIdentifier,
1999
+ targetPluginIdentifier: item.targetPluginIdentifier,
2000
+ extensionId: item.id,
2001
+ extensionKind: item.kind,
2002
+ surface: request.surface,
2003
+ surfaceKey: request.surfaceKey,
2004
+ point: request.point,
2005
+ routePath: this.routePath
2006
+ });
2007
+ return null;
2008
+ }
2009
+ const order = module.order ? await module.order(renderContext) : item.order;
2010
+ const contributionContext = this.#contributionContext(
2011
+ renderContext,
2012
+ sourceContext
2013
+ );
2014
+ const rawContribution = await module.contribute(contributionContext);
2015
+ assertNotAborted2(request.signal);
2016
+ if (isStandardExtensionSurface(request.surface)) {
2017
+ const issues = validateStandardContribution(
2018
+ request.surface,
2019
+ request.point,
2020
+ rawContribution
2021
+ );
2022
+ if (issues.length > 0) {
2023
+ throw new Error(
2024
+ `Structured extension '${item.id}' returned an invalid ${request.surface}:${request.point} contribution: ${issues.join(" ")}`
2025
+ );
2026
+ }
2027
+ }
2028
+ const contribution = wrapContributionRender(
2029
+ rawContribution,
2030
+ sourceContext,
2031
+ item,
2032
+ request,
2033
+ this.#options.observer,
2034
+ this.routePath
2035
+ );
2036
+ return {
2037
+ id: item.id,
2038
+ extensionKey: item.extensionKey,
2039
+ sourcePluginIdentifier: item.pluginIdentifier,
2040
+ order,
2041
+ label: item.labelKey ? sourceContext.i18n?.t(item.labelKey) ?? item.label ?? item.labelKey : item.label,
2042
+ contribution
2043
+ };
2044
+ } catch (error) {
2045
+ if (isAbortError(error)) throw error;
2046
+ this.#emitUiFailure(item, error, request, "resolve_structured");
2047
+ return null;
2048
+ }
2049
+ }
2050
+ )
2051
+ );
2052
+ const resolved = results.filter(
2053
+ (value) => value !== null
2054
+ ).sort(
2055
+ (left, right) => left.order - right.order || left.id.localeCompare(right.id)
2056
+ );
2057
+ this.#options.observer?.emit({
2058
+ level: "info",
2059
+ area: "ui_extension",
2060
+ action: "resolve_structured",
2061
+ status: "completed",
2062
+ message: `Resolved ${resolved.length} structured contribution(s) for ${request.surface}:${request.surfaceKey}:${request.point}.`,
2063
+ targetPluginIdentifier: this.#options.targetPluginIdentifier,
2064
+ surface: request.surface,
2065
+ surfaceKey: request.surfaceKey,
2066
+ point: request.point,
2067
+ routePath: this.routePath,
2068
+ details: {
2069
+ resolvedExtensionIds: resolved.map((entry) => entry.id)
2070
+ }
2071
+ });
2072
+ return resolved;
2073
+ }
2074
+ async #prepare(item, module, context, request) {
2075
+ const renderContext = this.#renderContext(context, item, request);
2076
+ assertNotAborted2(request.signal);
2077
+ await this.#ensureRegistered(item, module, context, request);
2078
+ assertNotAborted2(request.signal);
2079
+ if (module.visible && !await module.visible(renderContext)) {
2080
+ return null;
2081
+ }
2082
+ return {
2083
+ item,
2084
+ module,
2085
+ context,
2086
+ order: module.order ? await module.order(renderContext) : item.order
2087
+ };
2088
+ }
2089
+ #contributionContext(renderContext, context) {
2090
+ return {
2091
+ ...renderContext,
2092
+ // Use a wrapper rather than passing the method reference directly.
2093
+ // This preserves the ScopedI18nApi receiver if t() ever relies on it.
2094
+ t: (...args) => context.i18n.t(...args)
2095
+ };
2096
+ }
2097
+ #renderContext(context, item, request) {
2098
+ return {
2099
+ context,
2100
+ extension: item,
2101
+ surface: request.surface,
2102
+ surfaceKey: request.surfaceKey,
2103
+ point: request.point,
2104
+ instanceKey: request.instanceKey,
2105
+ extensionContext: request.extensionContext,
2106
+ routePath: this.routePath,
2107
+ payload: request.payload,
2108
+ signal: lifecycleSignal(request.signal)
2109
+ };
2110
+ }
2111
+ async #loadModule(item) {
2112
+ const startedAt = extensionRuntimeNow();
2113
+ const remote = this.#options.resolveRemote(item.pluginIdentifier);
2114
+ this.#options.observer?.emit({
2115
+ level: "debug",
2116
+ area: "federation",
2117
+ action: "module_load",
2118
+ status: "started",
2119
+ message: `Loading '${item.module}'.`,
2120
+ pluginIdentifier: item.pluginIdentifier,
2121
+ targetPluginIdentifier: item.targetPluginIdentifier,
2122
+ extensionId: item.id,
2123
+ extensionKind: "ui",
2124
+ module: item.module,
2125
+ routePath: this.routePath,
2126
+ details: { remoteEntry: remote?.entry, remoteName: remote?.name }
2127
+ });
2128
+ try {
2129
+ const loader = this.#options.loadModule ?? loadFederatedModule;
2130
+ const value = await loader(
2131
+ item.pluginIdentifier,
2132
+ item.module,
2133
+ remote?.entry,
2134
+ remote?.name
2135
+ );
2136
+ this.#options.observer?.emit({
2137
+ level: "info",
2138
+ area: "federation",
2139
+ action: "module_load",
2140
+ status: "completed",
2141
+ message: `Loaded '${item.module}'.`,
2142
+ pluginIdentifier: item.pluginIdentifier,
2143
+ targetPluginIdentifier: item.targetPluginIdentifier,
2144
+ extensionId: item.id,
2145
+ extensionKind: "ui",
2146
+ module: item.module,
2147
+ routePath: this.routePath,
2148
+ durationMs: extensionRuntimeNow() - startedAt
2149
+ });
2150
+ return value;
2151
+ } catch (error) {
2152
+ const resolvedError = toFederatedModuleLoadError(error, {
2153
+ pluginIdentifier: item.pluginIdentifier,
2154
+ module: item.module,
2155
+ ...remote?.entry ? { remoteUrl: remote.entry } : {},
2156
+ ...remote?.name ? { remoteName: remote.name } : {}
2157
+ });
2158
+ this.#options.observer?.emit({
2159
+ level: "error",
2160
+ area: "federation",
2161
+ action: "module_load",
2162
+ status: "failed",
2163
+ message: resolvedError.message,
2164
+ pluginIdentifier: item.pluginIdentifier,
2165
+ targetPluginIdentifier: item.targetPluginIdentifier,
2166
+ extensionId: item.id,
2167
+ extensionKind: "ui",
2168
+ module: item.module,
2169
+ routePath: this.routePath,
2170
+ durationMs: extensionRuntimeNow() - startedAt,
2171
+ details: {
2172
+ code: resolvedError.code,
2173
+ retryable: resolvedError.retryable
2174
+ }
2175
+ });
2176
+ throw resolvedError;
2177
+ }
2178
+ }
2179
+ #emitUiFailure(item, error, request, action) {
2180
+ this.#options.observer?.emit({
2181
+ level: "error",
2182
+ area: "ui_extension",
2183
+ action,
2184
+ status: "failed",
2185
+ message: extensionErrorMessage(error),
2186
+ pluginIdentifier: item.pluginIdentifier,
2187
+ targetPluginIdentifier: item.targetPluginIdentifier,
2188
+ extensionId: item.id,
2189
+ extensionKind: item.kind,
2190
+ surface: request.surface,
2191
+ surfaceKey: request.surfaceKey,
2192
+ point: request.point,
2193
+ module: item.module,
2194
+ routePath: this.routePath
2195
+ });
2196
+ }
2197
+ async #safeLifecycle(item, action, callback) {
2198
+ try {
2199
+ await callback();
2200
+ } catch (error) {
2201
+ this.#options.observer?.emit({
2202
+ level: "error",
2203
+ area: "ui_extension",
2204
+ action,
2205
+ status: "failed",
2206
+ message: extensionErrorMessage(error),
2207
+ pluginIdentifier: item.pluginIdentifier,
2208
+ targetPluginIdentifier: item.targetPluginIdentifier,
2209
+ extensionId: item.id,
2210
+ extensionKind: item.kind,
2211
+ module: item.module,
2212
+ routePath: this.routePath
2213
+ });
2214
+ throw error;
2215
+ }
2216
+ }
2217
+ };
2218
+ function wrapContributionRender(value, context, item, request, observer, routePath) {
2219
+ if (!value || typeof value !== "object") {
2220
+ return value;
2221
+ }
2222
+ const record = value;
2223
+ const runtime = createPluginRuntime(context);
2224
+ const wrapped = { ...record };
2225
+ for (const key of ["render", "renderCell"]) {
2226
+ const candidate = record[key];
2227
+ if (typeof candidate !== "function") {
2228
+ continue;
2229
+ }
2230
+ const render = candidate;
2231
+ wrapped[key] = (...args) => request.renderErrorPolicy === "bubble" ? /* @__PURE__ */ jsx(PluginRuntimeProvider, { value: runtime, children: render(...args) }) : /* @__PURE__ */ jsx(
2232
+ ExtensionBoundary,
2233
+ {
2234
+ resetKey: `${item.id}:${request.surface}:${request.surfaceKey}:${request.point}:${request.instanceKey ?? ""}:${key}`,
2235
+ onError: (error) => {
2236
+ const wrappedError = toUiExtensionRuntimeError(item, error, "render");
2237
+ observer?.emit({
2238
+ level: "error",
2239
+ area: "ui_extension",
2240
+ action: "structured_render",
2241
+ status: "failed",
2242
+ message: wrappedError.message,
2243
+ pluginIdentifier: item.pluginIdentifier,
2244
+ targetPluginIdentifier: item.targetPluginIdentifier,
2245
+ extensionId: item.id,
2246
+ extensionKind: item.kind,
2247
+ surface: request.surface,
2248
+ surfaceKey: request.surfaceKey,
2249
+ point: request.point,
2250
+ module: item.module,
2251
+ routePath,
2252
+ details: {
2253
+ renderMember: key,
2254
+ code: wrappedError.code,
2255
+ ...request.instanceKey ? { instanceKey: request.instanceKey } : {}
2256
+ }
2257
+ });
2258
+ },
2259
+ fallback: ({ error }) => /* @__PURE__ */ jsx("span", { role: "alert", "data-extension-fallback": "true", children: error.message }),
2260
+ children: /* @__PURE__ */ jsx(PluginRuntimeProvider, { value: runtime, children: render(...args) })
2261
+ }
2262
+ );
2263
+ }
2264
+ return wrapped;
2265
+ }
2266
+ function isAbortError(value) {
2267
+ return value instanceof DOMException ? value.name === "AbortError" : value instanceof Error && value.name === "AbortError";
2268
+ }
2269
+ function assertNotAborted2(signal) {
2270
+ if (!signal?.aborted) return;
2271
+ throw signal.reason instanceof Error ? signal.reason : new DOMException("The extension resolution was aborted.", "AbortError");
2272
+ }
2273
+ var neverAbortedSignal = new AbortController().signal;
2274
+ function lifecycleSignal(signal) {
2275
+ return signal ?? neverAbortedSignal;
2276
+ }
2277
+
2278
+ export { ExtensionExecutionRuntime, ExtensionHost, FederatedModuleLoadError, FederatedRemoteRegistry, PluginRenderer, PluginRuntimeObserverProvider, UiExtensionResolver, UiExtensionRuntimeError, emptyFederatedModuleError, getFederatedModuleCacheStats, getFederatedRuntimeStats, invalidateFederatedPluginModules, loadFederatedModule, preloadFederatedPlugin, resetFederatedModuleCache, toFederatedModuleLoadError, toUiExtensionRuntimeError, useFederatedPlugin, usePluginRuntimeObserver };
2279
+ //# sourceMappingURL=host.js.map
2280
+ //# sourceMappingURL=host.js.map