{"version":3,"file":"scion-microfrontend-platform.mjs","sources":["../../../../projects/scion/microfrontend-platform/src/lib/platform-state.ts","../../../../projects/scion/microfrontend-platform/src/lib/platform.model.ts","../../../../projects/scion/microfrontend-platform/src/lib/ɵplatform.model.ts","../../../../projects/scion/microfrontend-platform/src/lib/microfrontend-platform-stopper.ts","../../../../projects/scion/microfrontend-platform/src/lib/logger.ts","../../../../projects/scion/microfrontend-platform/src/lib/microfrontend-platform.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/microfrontend-platform-config.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/host-manifest-interceptor.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/client-registry/client.registry.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/messaging/message-client.ts","../../../../projects/scion/microfrontend-platform/src/lib/ɵmessaging.model.ts","../../../../projects/scion/microfrontend-platform/src/lib/messaging.model.ts","../../../../projects/scion/microfrontend-platform/src/lib/topics.util.ts","../../../../projects/scion/microfrontend-platform/src/lib/topic-matcher.util.ts","../../../../projects/scion/microfrontend-platform/src/lib/operators.ts","../../../../projects/scion/microfrontend-platform/src/lib/safe-runner.ts","../../../../projects/scion/microfrontend-platform/src/lib/error.util.ts","../../../../projects/scion/microfrontend-platform/src/lib/observable-decorator.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/messaging/message-selector.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/messaging/broker-gateway.ts","../../../../projects/scion/microfrontend-platform/src/lib/platform-property-service.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/http-client.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/manifest-registry/manifest-registry.ts","../../../../projects/scion/microfrontend-platform/src/lib/url.util.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/application-registry.ts","../../../../projects/scion/microfrontend-platform/src/lib/qualifier-matcher.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/manifest-registry/manifest-object-store.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/manifest-registry/capability-interceptors.ts","../../../../projects/scion/microfrontend-platform/src/lib/qualifiers.util.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/manifest-registry/ɵmanifest-registry.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/focus/focus-tracker.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/manifest-fetcher.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/message-broker/message-subscription.registry.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/message-broker/topic-subscription.registry.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/message-broker/message-interception.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/semver.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/client-registry/client.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/client-registry/ɵclient.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/message-broker/intent-subscription.registry.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/message-broker/predicates.util.ts","../../../../projects/scion/microfrontend-platform/src/lib/param-matcher.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/message-broker/intent-params.util.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/message-broker/message-broker.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/manifest-registry/manifest-service.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/context/context.model.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/context/router-outlet-context-provider.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/router-outlet/router-outlet-url-assigner.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/keyboard-event/keystroke.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/router-outlet/metadata.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/router-outlet/router-outlet.element.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/context/context-service.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/router-outlet/relative-path-resolver.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/messaging/intent-client.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/router-outlet/outlet-router.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/router/microfrontend-intent-navigator.interceptor.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/client-registry/ɵclient.registry.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/host-app-config-provider.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/progress-monitor/progress-monitor.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/progress-monitor/progress-monitors.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/app-installer.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/activator/activator-installer.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/focus/focus-monitor.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/focus/focus-in-event-dispatcher.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/mouse-event/mouse-move-event-dispatcher.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/mouse-event/mouse-up-event-dispatcher.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/preferred-size/preferred-size-service.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/keyboard-event/keyboard-event-dispatcher.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/messaging/message-handler.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/messaging/ɵmessage-client.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/messaging/ɵintent-client.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/microfrontend-platform-client.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/microfrontend-platform-host.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/host-config.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/application-config.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/manifest-registry/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/message-broker/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/liveness-config.ts","../../../../projects/scion/microfrontend-platform/src/lib/host/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/connect-options.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/router-outlet/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/context/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/focus/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/preferred-size/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/manifest-registry/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/messaging/public_api.ts","../../../../projects/scion/microfrontend-platform/src/lib/client/public_api.ts","../../../../projects/scion/microfrontend-platform/src/public-api.ts","../../../../projects/scion/microfrontend-platform/src/scion-microfrontend-platform.ts"],"sourcesContent":["/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Lifecycle states of the microfrontend platform.\n *\n * @category Platform\n */\nexport enum PlatformState {\n  /**\n   * Indicates that the platform is about to start.\n   */\n  Starting = 1,\n  /**\n   * Indicates that the platform started.\n   */\n  Started = 2,\n  /**\n   * Indicates that the platform is about to stop.\n   */\n  Stopping = 3,\n  /**\n   * Indicates that the platform is not yet started.\n   */\n  Stopped = 4,\n}\n\n/**\n * Runlevels are used to control in which startup phase to execute initializers when starting the platform.\n *\n * The platform reports that it has started after all initializers have completed successfully.\n *\n * @internal\n */\nexport enum Runlevel {\n  /**\n   * In runlevel 0, the platform host fetches manifests of registered micro applications.\n   */\n  Zero = 0,\n  /**\n   * In runlevel 1, the platform constructs eager beans.\n   */\n  One = 1,\n  /**\n   * From runlevel 2 and above, messaging is enabled. This is the default runlevel at which initializers execute if not specifying any runlevel.\n   */\n  Two = 2,\n  /**\n   * In runlevel 3, the platform host installs activator microfrontends.\n   */\n  Three = 3,\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Manifest of an application.\n *\n * The manifest is a special file that contains information about a micro application. A micro application declares\n * its intentions and capabilities in its manifest file. The manifest needs to be registered in the host application.\n *\n * @category Platform\n * @category Intention API\n */\nexport interface Manifest {\n  /**\n   * The name of the application, e.g. displayed in the DevTools.\n   */\n  name: string;\n  /**\n   * URL to the application root. The URL can be fully qualified, or a path relative to the origin under\n   * which serving the manifest file. If not specified, the origin of the manifest file acts as the base\n   * URL. The platform uses the base URL to resolve microfrontends such as activator endpoints.\n   * For a Single Page Application that uses hash-based routing, you typically specify the hash symbol (`#`)\n   * as the base URL.\n   */\n  baseUrl?: string;\n  /**\n   * Functionality which this application intends to use.\n   */\n  intentions?: Intention[];\n  /**\n   * Functionality which this application provides that qualified apps can call via intent.\n   */\n  capabilities?: Capability[];\n}\n\n/**\n * Represents a dictionary of key-value pairs to qualify an intention, intent or capability.\n *\n * See {@link Intention}, {@link Capability} or {@link Intent} for the usage of wildcards\n * in qualifier properties.\n *\n * @category Intention API\n */\nexport interface Qualifier {\n  [key: string]: string | number | boolean;\n}\n\n/**\n * Represents an application registered in the platform.\n *\n * @category Platform\n */\nexport interface Application {\n  /**\n   * Unique symbolic name of the application.\n   */\n  symbolicName: string;\n  /**\n   * Name of the application as specified in the manifest.\n   */\n  name: string;\n  /**\n   * URL to the application root.\n   */\n  baseUrl: string;\n  /**\n   * URL to the manifest of this application.\n   */\n  manifestUrl: string;\n  /**\n   * Maximum time (in milliseconds) that the host waits until the manifest for this application is loaded.\n   *\n   * This is the effective timeout, i.e, either the application-specific timeout as defined in {@link ApplicationConfig.manifestLoadTimeout},\n   * or the global timeout as defined in {@link MicrofrontendPlatformConfig.manifestLoadTimeout}, otherwise `undefined`.\n   */\n  manifestLoadTimeout?: number;\n  /**\n   * Maximum time (in milliseconds) that the host waits for this application to signal readiness.\n   *\n   * This is the effective timeout, i.e, either the application-specific timeout as defined in {@link ApplicationConfig.activatorLoadTimeout},\n   * or the global timeout as defined in {@link MicrofrontendPlatformConfig.activatorLoadTimeout}, otherwise `undefined`.\n   */\n  activatorLoadTimeout?: number;\n  /**\n   * Indicates whether this application is allowed to access private capabilities of other applications.\n   */\n  scopeCheckDisabled: boolean;\n  /**\n   * Indicates whether this application is allowed to access public capabilities of other applications without declaring an intention.\n   */\n  intentionCheckDisabled: boolean;\n  /**\n   * Indicates whether this application is allowed to access inactive capabilities.\n   */\n  capabilityActiveCheckDisabled: boolean;\n  /**\n   * Indicates whether this application is allowed to register and unregister intentions at runtime.\n   */\n  intentionRegisterApiDisabled: boolean;\n  /**\n   * Version of the SCION Microfrontend Platform used by this application.\n   */\n  platformVersion: Promise<string>;\n}\n\n/**\n * The term capability refers to the Intention API of the SCION Microfrontend Platform.\n *\n * A capability represents some functionality of a micro application that is available to qualified micro applications through the Intention API.\n * A micro application declares its capabilities in its manifest. Qualified micro applications can browse capabilities similar to a catalog, or\n * interact with capabilities via intent.\n *\n * A capability is formulated in an abstract way consisting of a type and optionally a qualifier. The type categorizes a capability in terms of its\n * functional semantics. A capability may also define a qualifier to differentiate different capabilities of the same type.\n *\n * A capability can have private or public visibility. If private, which is by default, the capability is not visible to other micro\n * applications; thus, it can only be invoked or browsed by the providing micro application itself.\n *\n * A capability can specify parameters which the intent issuer can/must pass along with the intent. Parameters are part of the contract between\n * the intent publisher and the capability provider. They do not affect the intent routing, unlike the qualifier.\n *\n * Metadata can be associated with a capability in its properties section. For example, if providing a microfrontend, the URL to the\n * microfrontend can be added as property, or if the capability contributes an item to a menu, its label to be displayed.\n *\n * @category Intention API\n */\nexport interface Capability {\n  /**\n   * Categorizes the capability in terms of its functional semantics (e.g., `microfrontend` if providing a microfrontend).\n   * It can be an arbitrary `string` literal and has no meaning to the platform.\n   */\n  type: string;\n  /**\n   * The qualifier is a dictionary of arbitrary key-value pairs to differentiate capabilities of the same `type` and is like\n   * an abstract description of the capability. It should include enough information to uniquely identify the capability.\n   *\n   * Intents must exactly match the qualifier of the capability, if any.\n   */\n  qualifier?: Qualifier;\n  /**\n   * Specifies parameters which the intent issuer can/must pass along with the intent.\n   *\n   * Parameters are part of the contract between the intent publisher and the capability provider.\n   * They do not affect the intent routing, unlike the qualifier.\n   */\n  params?: ParamDefinition[];\n  /**\n   * Controls whether this capability is private. Defaults to `true`.\n   *\n   * If private, the capability is not visible to other applications and can only be accessed by the providing application.\n   *\n   * Note: Applications configured with `scopeCheckDisabled` can still access private capabilities (discouraged).\n   */\n  private?: boolean;\n  /**\n   * Controls whether this capability is inactive. Defaults to `false`.\n   *\n   * Capabilities can be marked as inactive in a capability interceptor, for example, based on user permissions.\n   * Inactive capabilities are unavailable to applications but still visible in the SCION DevTools for discovery.\n   *\n   * Note: Applications configured with `capabilityActiveCheckDisabled` can still access inactive capabilities (discouraged).\n   */\n  inactive?: boolean;\n  /**\n   * A short description to explain the capability.\n   */\n  description?: string;\n  /**\n   * Arbitrary metadata to be associated with the capability.\n   */\n  properties?: {\n    [key: string]: unknown;\n  };\n  /**\n   * Metadata about the capability (read-only, exclusively managed by the platform).\n   * @ignore\n   */\n  metadata?: {\n    /**\n     * Unique identity of this capability.\n     */\n    id: string;\n    /**\n     * Symbolic name of the application which provides this capability.\n     */\n    appSymbolicName: string;\n  };\n}\n\n/**\n * The term intention refers to the Intention API of the SCION Microfrontend Platform.\n *\n * An intention refers to one or more capabilities that a micro application wants to interact with.\n *\n * Intentions are declared in the application’s manifest and are formulated in an abstract way, consisting of a type\n * and optionally a qualifier. The qualifier is used to differentiate capabilities of the same type.\n *\n * @category Intention API\n */\nexport interface Intention {\n  /**\n   * The type of capability to interact with.\n   */\n  type: string;\n  /**\n   * Qualifies the capability which to interact with.\n   *\n   * The qualifier is a dictionary of arbitrary key-value pairs to differentiate capabilities of the same `type`.\n   *\n   * The intention must exactly match the qualifier of the capability, if any. The intention qualifier allows using\n   * wildcards to match multiple capabilities simultaneously.\n   *\n   * In the intention, the following wildcards are supported:\n   * - **Asterisk wildcard character (`*`):**\\\n   *   Matches capabilities with such a qualifier property no matter of its value (except `null` or `undefined`).\n   *   Use it like this: `{property: '*'}`.\n   * - **Partial wildcard (`**`):**\n   *   Matches capabilities even if having additional properties. Use it like this: `{'*': '*'}`.\n   */\n  qualifier?: Qualifier;\n  /**\n   * Metadata about this intention (read-only, exclusively managed by the platform).\n   * @ignore\n   */\n  metadata?: {\n    /**\n     * Unique identity of this intent declaration.\n     */\n    id: string;\n    /**\n     * Symbolic name of the application which declares this intention.\n     */\n    appSymbolicName: string;\n  };\n}\n\n/**\n * Built in capability types.\n *\n * @category Intention API\n */\nexport enum PlatformCapabilityTypes {\n  /**\n   * Type for registering an activator capability.\n   *\n   * @see ActivatorCapability\n   */\n  Activator = 'activator',\n  /**\n   * Type for registering a microfrontend capability.\n   *\n   * @see MicrofrontendCapability\n   */\n  Microfrontend = 'microfrontend',\n}\n\n/**\n * An activator allows a micro application to initialize and connect to the platform upon host application's startup,\n * i.e., when the user loads the web application into the browser.\n *\n * In the broadest sense, an activator is a kind of microfrontend, i.e. an HTML page that runs in an iframe. In contrast\n * to regular microfrontends, however, at platform startup, the platform loads activator microfrontends into hidden iframes\n * for the entire platform lifecycle, thus, providing a stateful session to the micro application on the client-side.\n *\n * Some typical use cases for activators are receiving messages and intents, preloading data, or flexibly providing capabilities.\n *\n * A micro application registers an activator as public _activator_ capability in its manifest, as follows:\n *\n * ```json\n * \"capabilities\": [\n *   {\n *     \"type\": \"activator\",\n *     \"private\": false,\n *     \"properties\": {\n *       \"path\": \"path/to/the/activator\"\n *     }\n *   }\n * ]\n * ```\n *\n * #### Activation Context\n * An activator's microfrontend runs inside an activation context. The context provides access\n * to the activator capability, allowing to read properties declared on the activator capability.\n *\n * You can obtain the activation context using the {@link ContextService} as following.\n *\n * ```ts\n * // Looks up the activation context.\n * const ctx: ActivationContext = await Beans.get(ContextService).lookup(ACTIVATION_CONTEXT);\n * ```\n *\n * #### Multiple Activators\n * A micro application can register multiple activators. Note, that each activator boots the micro\n * application on its own and runs in a separate browsing context. The platform nominates one activator\n * of each micro application as its primary activator. The nomination has no relevance to the platform but\n * can help code decide whether to install singleton functionality.\n *\n * You can test if running in the primary activation context as following.\n * ```ts\n * // Looks up the activation context.\n * const ctx = await Beans.get(ContextService).lookup<ActivationContext>(ACTIVATION_CONTEXT);\n * // Checks if running in the context of the primary activator.\n * const isPrimary: boolean = ctx.primary;\n * ```\n *\n * #### Sharing State\n * Since an activator runs in a separate browsing context, microfrontends cannot directly access its state.\n * Instead, an activator could put data, for example, into session storage, so that microfrontends of its micro\n * application can access it. Alternatively, an activator could install a message listener, allowing microfrontends\n * to request data via client-side messaging.\n *\n * @category Platform\n * @category Intention API\n */\nexport interface ActivatorCapability extends Capability {\n  type: PlatformCapabilityTypes.Activator;\n  private: false;\n  properties: {\n    /**\n     * Path where the platform can load the activator microfrontend. The path is relative to the base URL\n     * of the micro application, as specified in the application manifest.\n     */\n    path: string;\n    /**\n     * Starting an activator may take some time. In order not to miss any messages or intents, you can instruct the platform host to\n     * wait to enter started state until you signal the activator to be ready. For this purpose, you can define a set of topics where\n     * to publish a ready message to signal readiness. If you specify multiple topics, the activator enters ready state after you have\n     * published a ready message to all these topics. A ready message is an event; thus, a message without payload.\n     *\n     * If not specifying a readiness topic, the platform host does not wait for this activator to become ready. However, if you specify a\n     * readiness topic, make sure that your activator has a fast startup time and signals readiness as early as possible not to delay\n     * the startup of the platform host.\n     */\n    readinessTopics?: string | string[];\n    /**\n     * Arbitrary metadata to be associated with the capability.\n     */\n    [key: string]: unknown;\n  };\n}\n\n/**\n * Represents a microfrontend that can be loaded into a <sci-router-outlet> using the {@link OutletRouter}.\n *\n * @category Intention API\n */\nexport interface MicrofrontendCapability extends Capability {\n  type: PlatformCapabilityTypes.Microfrontend;\n  properties: {\n    /**\n     * Specifies the path of the microfrontend.\n     *\n     * The path is relative to the base URL, as specified in the application manifest. If the\n     * application does not declare a base URL, it is relative to the origin of the manifest file.\n     *\n     * The path allows the use of navigational symbols and named parameters to reference qualifier and parameter values.\n     * A named parameter begins with a colon (`:`) followed by the qualifier or parameter name, and is allowed in path segments,\n     * query parameters, matrix parameters and the fragment part. Named query and matrix parameters without a replacement are removed,\n     * e.g., if referencing an optional parameter.\n     *\n     * #### Usage of named parameters in the path:\n     * ```json\n     * {\n     *   \"type\": \"microfrontend\",\n     *   \"qualifier\": {\n     *     \"entity\": \"product\"\n     *   },\n     *   \"params\": [\n     *     {\"name\": \"id\", \"required\": true}\n     *   ]\n     *   \"properties\": {\n     *     \"path\": \"product/:id\",\n     *   }\n     * }\n     * ```\n     *\n     * #### Path parameter example:\n     * segment/:param1/segment/:param2\n     *\n     * #### Matrix parameter example:\n     * segment/segment;matrixParam1=:param1;matrixParam2=:param2\n     *\n     * #### Query parameter example:\n     * segment/segment?queryParam1=:param1&queryParam2=:param2\n     */\n    path: string;\n    /**\n     * Specifies the preferred outlet to load this microfrontend into.\n     * Note that this preference is only a hint that will be ignored if the navigator\n     * specifies an outlet for navigation.\n     *\n     * The precedence is as follows:\n     * - Outlet as specified by navigator via {@link NavigationOptions#outlet}.\n     * - Preferred outlet as specified in the microfrontend capability.\n     * - Current outlet if navigating in the context of an outlet.\n     * - {@link PRIMARY_OUTLET primary} outlet.\n     */\n    outlet?: string;\n    /**\n     * Instructs the router outlet to show a splash, such as a skeleton or loading indicator, until the microfrontend signals readiness.\n     * The splash is the markup between the opening and closing tags of the router outlet element.\n     *\n     * @see SciRouterOutletElement\n     * @see MicrofrontendPlatformClient.signalReady\n     */\n    showSplash?: boolean;\n    /**\n     * Arbitrary metadata to be associated with the capability.\n     */\n    [key: string]: unknown;\n  };\n}\n\n/**\n * Describes a parameter to be passed along with an intent.\n *\n * @category Intention API\n */\nexport interface ParamDefinition {\n  /**\n   * Specifies the name of the parameter.\n   */\n  name: string;\n  /**\n   * Describes the parameter and its usage in more detail.\n   */\n  description?: string;\n  /**\n   * Specifies whether the parameter must be passed along with the intent.\n   */\n  required: boolean;\n  /**\n   * Defines a default value. Only applies to optional parameters.\n   *\n   * The default value is used when the parameter is not provided.\n   */\n  default?: unknown;\n  /**\n   * Allows deprecating the parameter.\n   *\n   * It is good practice to explain the deprecation, provide the date of removal, and how to migrate.\n   * If renaming the parameter, you can set the `useInstead` property to specify which parameter to use\n   * instead. At runtime, this will map the parameter to the specified replacement, allowing for\n   * straightforward migration on the provider side.\n   */\n  deprecated?: true | {message?: string; useInstead?: string};\n\n  /**\n   * Allows the declaration of additional metadata that can be interpreted in an interceptor, for example.\n   */\n  [property: string]: unknown;\n}\n\n/**\n * Symbol to determine if this app instance is running as the platform host.\n *\n * ```ts\n * const isPlatformHost: boolean = Beans.get(IS_PLATFORM_HOST);\n * ```\n *\n * @category Platform\n */\nexport const IS_PLATFORM_HOST = Symbol('IS_PLATFORM_HOST');\n\n/**\n * Symbol to get the application's symbolic name from the bean manager.\n *\n * @category Platform\n */\nexport const APP_IDENTITY = Symbol('APP_IDENTITY');\n\n/**\n * Key for obtaining the current activation context using {@link ContextService}.\n *\n * The activation context is only available to microfrontends loaded by an activator.\n *\n * @see {@link ActivationContext}\n * @see {@link ContextService}\n * @category Platform\n */\nexport const ACTIVATION_CONTEXT = 'ɵACTIVATION_CONTEXT';\n\n/**\n * Information about the activator that loaded a microfrontend.\n *\n * This context is available to a microfrontend if loaded by an application activator.\n * This object can be obtained from the {@link ContextService} using the name {@link ACTIVATION_CONTEXT}.\n *\n * ```ts\n * const ctx = await Beans.get(ContextService).lookup<ActivationContext>(ACTIVATION_CONTEXT);\n * ```\n *\n * @see {@link ACTIVATION_CONTEXT}\n * @see {@link ContextService}\n * @category Platform\n */\nexport interface ActivationContext {\n  /**\n   * Indicates whether running in the context of the primary activator.\n   * The platform nominates one activator of each app as primary activator.\n   */\n  primary: boolean;\n  /**\n   * Metadata about the activator that activated the microfrontend.\n   */\n  activator: ActivatorCapability;\n}\n\n/**\n * Allows filtering manifest objects like capabilities or intentions.\n *\n * All specified filter criteria are \"AND\"ed together. Unspecified filter criteria are ignored.\n * If no filter criterion is specified, no filtering takes place, thus all available objects are returned.\n *\n * @category Intention API\n */\nexport interface ManifestObjectFilter {\n  /**\n   * Manifest objects of the given identity.\n   */\n  id?: string;\n  /**\n   * Manifest objects of the given function type.\n   */\n  type?: string;\n  /**\n   * Manifest objects matching the given qualifier.\n   */\n  qualifier?: Qualifier;\n  /**\n   * Manifest objects provided by the given app.\n   */\n  appSymbolicName?: string;\n}\n\n/**\n * Represents a request to determine if an application is qualified to interact with a given capability.\n */\nexport interface ApplicationQualifiedForCapabilityRequest {\n  /**\n   * Specifies the symbolic name of the application under test.\n   */\n  appSymbolicName: string;\n  /**\n   * Identifies the capability for which to request the application's qualification.\n   */\n  capabilityId: string;\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Application} from './platform.model';\n\n/**\n * Represents an application registered in the platform.\n *\n * The version is omitted because not known at the time of registration, but only when first connecting to the host, e.g., in an activator.\n *\n * @internal\n */\nexport interface ɵApplication extends Omit<Application, 'platformVersion'> {\n  /**\n   * Specifies the origin(s) where message from this application must originate from. Messages of a different origin will be rejected.\n   */\n  allowedMessageOrigins: Set<string>;\n}\n\n/**\n * Symbol to get the version of the SCION Microfrontend Platform.\n *\n * @internal\n */\nexport const ɵVERSION = Symbol('ɵVERSION');\n\n/**\n * Symbol to get the topmost window in the window hierarchy from the bean manager.\n *\n * Alias for `window.top` that can be overridden in tests, e.g., to simulate\n * the client to connect to a remote host.\n *\n * @internal\n */\nexport const ɵWINDOW_TOP = Symbol('ɵWINDOW_TOP');\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {PreDestroy} from '@scion/toolkit/bean-manager';\nimport {MicrofrontendPlatform} from './microfrontend-platform';\nimport {fromEvent, race, Subject} from 'rxjs';\nimport {take, takeUntil} from 'rxjs/operators';\n\n/**\n * Stops the platform and disconnects this client from the host when the browser unloads the document.\n *\n * By default, the platform initiates shutdown when the browser unloads the document, i.e., when `beforeunload` is triggered.\n * The main reason for `beforeunload` instead of `unload` is to avoid posting messages to disposed windows.\n * However, if `beforeunload` is not triggered, e.g., when an iframe is removed, we fall back to `unload`.\n *\n * @category Platform\n */\nexport abstract class MicrofrontendPlatformStopper {\n}\n\n/**\n * @internal\n */\nexport class ɵMicrofrontendPlatformStopper implements MicrofrontendPlatformStopper, PreDestroy {\n\n  private _destroy$ = new Subject<void>();\n\n  constructor() {\n    race(fromEvent(window, 'beforeunload'), fromEvent(window, 'unload'))\n      .pipe(\n        take(1),\n        takeUntil(this._destroy$),\n      )\n      .subscribe(() => {\n        void MicrofrontendPlatform.destroy();\n      });\n  }\n\n  public preDestroy(): void {\n    this._destroy$.next();\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {APP_IDENTITY} from './platform.model';\nimport {ɵVERSION} from './ɵplatform.model';\n\n/**\n * Logger used by the platform to log to the console.\n *\n * Replace this bean to capture the log output.\n *\n * @category Platform\n */\nexport abstract class Logger {\n\n  /**\n   * Logs with severity debug.\n   */\n  public abstract debug(message?: unknown, ...args: unknown[]): void;\n\n  /**\n   * Logs with severity info.\n   */\n  public abstract info(message?: unknown, ...args: unknown[]): void;\n\n  /**\n   * Logs with severity warn.\n   */\n  public abstract warn(message?: unknown, ...args: unknown[]): void;\n\n  /**\n   * Logs with severity error.\n   */\n  public abstract error(message?: unknown, ...args: unknown[]): void;\n}\n\n/**\n * Logger used by the platform to log to the console.\n *\n * Replace this bean to capture the log output.\n *\n * @internal\n */\nexport class ConsoleLogger implements Logger {\n\n  public debug(message?: unknown, ...args: unknown[]): void {\n    this.log('debug', message, args);\n  }\n\n  public info(message?: unknown, ...args: unknown[]): void {\n    this.log('info', message, args);\n  }\n\n  public warn(message?: unknown, ...args: unknown[]): void {\n    this.log('warn', message, args);\n  }\n\n  public error(message?: unknown, ...args: unknown[]): void {\n    this.log('error', message, args);\n  }\n\n  private log(severity: 'debug' | 'info' | 'warn' | 'error', message: unknown, args: unknown[]): void {\n    const loggingContext = (args[0] instanceof LoggingContext ? args.shift() : {appSymbolicName: Beans.get(APP_IDENTITY), version: Beans.get(ɵVERSION)}) as LoggingContext;\n    const prefix = new Array<string>()\n      .concat(loggingContext.version ? `[@scion/microfrontend-platform@${loggingContext.version}]` : '[@scion/microfrontend-platform]')\n      .concat(`[${loggingContext.appSymbolicName}]`)\n      .join('');\n\n    if (console && typeof console[severity] === 'function') { // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n      const consoleFn = console[severity];\n      args?.length ? consoleFn(`${prefix} ${message}`, ...args) : consoleFn(`${prefix} ${message}`); // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n    }\n  }\n}\n\n/**\n * Logger that does nothing.\n *\n * @internal\n */\nexport const NULL_LOGGER = new class extends Logger {\n\n  public debug(message?: unknown, ...args: unknown[]): void {\n    // NOOP\n  }\n\n  public info(message?: unknown, ...args: unknown[]): void {\n    // NOOP\n  }\n\n  public warn(message?: unknown, ...args: unknown[]): void {\n    // NOOP\n  }\n\n  public error(message?: unknown, ...args: unknown[]): void {\n    // NOOP\n  }\n}();\n\n/**\n * Contextual information to add to the log message.\n *\n * Pass an instance of this class as the first argument to the logger when logging a message.\n *\n * @internal\n */\nexport class LoggingContext {\n\n  constructor(public appSymbolicName: string, public version?: string) {\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {BehaviorSubject, Observable} from 'rxjs';\nimport {first} from 'rxjs/operators';\nimport {PlatformState, Runlevel} from './platform-state';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {APP_IDENTITY, IS_PLATFORM_HOST} from './platform.model';\nimport {ɵVERSION, ɵWINDOW_TOP} from './ɵplatform.model';\nimport {MicrofrontendPlatformStopper, ɵMicrofrontendPlatformStopper} from './microfrontend-platform-stopper';\nimport {ConsoleLogger, Logger} from './logger';\n\n/**\n * Current version of the SCION Microfrontend Platform.\n */\nconst version = '2.1.0';\n\n/**\n * The central class of the SCION Microfrontend Platform. This class cannot be instantiated. All functionality is provided by static methods.\n *\n * To enable tree-shaking of the SCION Microfrontend Platform, the platform provides three separate entry points:\n * - {@link MicrofrontendPlatformHost} to configure and start the platform in the host\n * - {@link MicrofrontendPlatformClient} to connect to the platform from a microfrontend\n * - {@link MicrofrontendPlatform} to react to platform lifecycle events and stop the platform\n *\n * ## SCION Microfrontend Platform\n *\n * SCION Microfrontend Platform is a TypeScript-based open source library that enables the implementation of a framework-agnostic\n * microfrontend architecture using iframes. It provides fundamental APIs for microfrontends to communicate with each other across origins\n * and facilitates embedding microfrontends using a web component and a router. SCION Microfrontend Platform is a lightweight, web stack\n * agnostic library that has no user-facing components and does not dictate any form of application structure.\n *\n * You can continue using the frameworks you love since the platform integrates microfrontends via iframes. Iframes by nature provide\n * maximum isolation and allow the integration of any web application without complex adaptation. The platform aims to shield developers\n * from iframe specifics and the low-level messaging mechanism to focus instead on integrating microfrontends.\n *\n * #### Cross-microfrontend communication\n * The platform adds a pub/sub layer on top of the native `postMessage` mechanism to enable microfrontends to communicate with each other\n * easily across origins. Communication comes in two flavors: topic-based and intent-based. Both models feature request-response message\n * exchange, support retained messages for late subscribers to receive the latest messages, and provide API to intercept messages to\n * implement cross-cutting messaging concerns.\n *\n * Topic-based messaging enables you to publish messages to multiple subscribers via a common topic. Intent-based communication focuses on\n * controlled collaboration between applications. To collaborate, an application must express an intention. Manifesting intentions enables\n * us to see dependencies between applications down to the functional level.\n *\n * #### Microfrontend Integration and Routing\n * The platform makes it easy to integrate microfrontends through its router-outlet. The router-outlet is a web component that wraps an iframe.\n * It solves many of the cumbersome quirks of iframes and helps to overcome iframe restrictions. For example, it can adapt its size to the\n * preferred size of embedded content, supports keyboard event propagation and lets you pass contextual data to embedded content.\n * Using the router, you control which web content to display in an outlet. Multiple outlets can display different content, determined by\n * different outlet names, all at the same time. Routing works across application boundaries and enables features such as persistent navigation.\n *\n * ***\n *\n * A microfrontend architecture can be achieved in many ways, each with its pros and cons. The SCION Microfrontend Platform uses\n * the iframe approach primarily since iframes by nature provide the highest possible level of isolation through a separate browsing context.\n * The microfrontend design approach is very tempting and has obvious advantages, especially for large-scale and long-lasting projects, most\n * notably because we are observing an enormous dynamic in web frameworks. The SCION Microfrontend Platform provides you with the necessary\n * tools to best support you in implementing such an architecture.\n *\n * @see {@link MicrofrontendPlatformHost}\n * @see {@link MicrofrontendPlatformClient}\n *\n * @see {@link MessageClient}\n * @see {@link IntentClient}\n * @see {@link SciRouterOutletElement}\n * @see {@link OutletRouter}\n * @see {@link ContextService}\n * @see {@link PreferredSizeService}\n * @see {@link ManifestService}\n * @see {@link FocusMonitor}\n * @see {@link ActivatorCapability}\n *\n * @category Platform\n * @category Lifecycle\n */\nexport class MicrofrontendPlatform {\n\n  private static readonly _state$ = new BehaviorSubject<PlatformState>(PlatformState.Stopped);\n\n  private constructor() {\n  }\n\n  /**\n   * @internal\n   */\n  public static async startPlatform(startupFn?: () => void): Promise<void> {\n    if (this.state === PlatformState.Started) {\n      throw Error('[MicrofrontendPlatformStartupError] Platform already started');\n    }\n\n    try {\n      startupFn?.();\n      await this.enterState(PlatformState.Starting);\n      await Beans.start({eagerBeanConstructRunlevel: Runlevel.One, initializerDefaultRunlevel: Runlevel.Two});\n      await this.enterState(PlatformState.Started);\n    }\n    catch (error) {\n      await this.destroy();\n      throw Error(`[MicrofrontendPlatformStartupError] Microfrontend platform failed to start: ${error}`);\n    }\n  }\n\n  /**\n   * Destroys this platform and releases resources allocated.\n   *\n   * @return a Promise that resolves once the platformed stopped.\n   */\n  public static async destroy(): Promise<void> {\n    await this.enterState(PlatformState.Stopping);\n    Beans.destroy();\n    await this.enterState(PlatformState.Stopped);\n  }\n\n  /**\n   * @return the current platform state.\n   */\n  public static get state(): PlatformState {\n    return this._state$.getValue();\n  }\n\n  /**\n   * Observable that, when subscribed, emits the current platform lifecycle state.\n   * It never completes and emits continuously when the platform enters\n   * another state.\n   */\n  public static get state$(): Observable<PlatformState> {\n    return this._state$;\n  }\n\n  /**\n   * Waits for the platform to enter the specified {@link PlatformState}.\n   * If already in that state, the Promise resolves instantly.\n   *\n   * @param  state - the state to wait for.\n   * @return A Promise that resolves when the platform enters the given state.\n   *         If already in that state, the Promise resolves instantly.\n   */\n  public static async whenState(state: PlatformState): Promise<void> {\n    return new Promise<void>((resolve, reject) => {\n      this._state$\n        .pipe(first(it => it === state))\n        .subscribe({\n          error: reject,\n          complete: resolve,\n        });\n    });\n  }\n\n  private static async enterState(newState: PlatformState): Promise<void> {\n    const currentState = (this.state === PlatformState.Stopped) ? -1 : this.state;\n    if (currentState >= newState) {\n      throw Error(`[PlatformStateError] Failed to enter platform state [prevState=${PlatformState[this.state]}, newState=${PlatformState[newState]}].`);\n    }\n\n    this._state$.next(newState);\n\n    // Let microtasks waiting for entering that state to resolve first.\n    await this.whenState(newState);\n  }\n}\n\n/**\n * @internal\n */\nexport function providePlatformEnvironment(config: {symbolicName: string; isPlatformHost: boolean}): void {\n  Beans.register(IS_PLATFORM_HOST, {useValue: config.isPlatformHost});\n  Beans.register(APP_IDENTITY, {useValue: config.symbolicName});\n  Beans.registerIfAbsent(ɵWINDOW_TOP, {useValue: window.top});\n  Beans.registerIfAbsent(ɵVERSION, {useValue: version, destroyOrder: BeanDestroyOrders.CORE});\n  Beans.registerIfAbsent(MicrofrontendPlatformStopper, {useClass: ɵMicrofrontendPlatformStopper, eager: true});\n  Beans.registerIfAbsent(Logger, {useClass: ConsoleLogger, destroyOrder: BeanDestroyOrders.CORE});\n}\n\n/**\n * Specifies destroy orders of platform-specific beans, enabling controlled termination of the platform.\n *\n * @internal\n */\nexport enum BeanDestroyOrders {\n  /**\n   * Use for core platform beans which should be destroyed as the very last beans.\n   */\n  CORE = Number.MAX_SAFE_INTEGER, // eslint-disable-line @typescript-eslint/prefer-literal-enum-member\n  /**\n   * Use for the {@link MessageBroker}.\n   */\n  BROKER = CORE - 1, // eslint-disable-line @typescript-eslint/prefer-literal-enum-member\n  /**\n   * Use for messaging-related beans.\n   */\n  MESSAGING = BROKER - 1, // eslint-disable-line @typescript-eslint/prefer-literal-enum-member\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {ApplicationConfig} from './application-config';\nimport {HostConfig} from './host-config';\nimport {LivenessConfig} from './liveness-config';\n\n/**\n * Configures the platform and defines the micro applications running in the platform.\n *\n * @category Platform\n */\nexport abstract class MicrofrontendPlatformConfig {\n  /**\n   * Lists the micro applications able to connect to the platform to interact with other micro applications.\n   */\n  public abstract readonly applications: ApplicationConfig[];\n  /**\n   * Configures the interaction of the host application with the platform.\n   *\n   * As with micro applications, you can provide a manifest for the host, allowing the host to contribute capabilities and declare intentions.\n   */\n  public abstract readonly host?: HostConfig;\n  /**\n   * Controls whether the Activator API is enabled.\n   *\n   * Activating the Activator API enables micro applications to contribute `activator` microfrontends. Activator microfrontends are loaded\n   * at platform startup for the entire lifecycle of the platform. An activator is a startup hook for micro applications to initialize\n   * or register message or intent handlers to provide functionality.\n   *\n   * By default, this API is enabled.\n   *\n   * @see {@link ActivatorCapability}\n   */\n  public abstract readonly activatorApiDisabled?: boolean;\n  /**\n   * Maximum time (in milliseconds) that the platform waits until the manifest of an application is loaded.\n   * You can set a different timeout per application via {@link ApplicationConfig.manifestLoadTimeout}.\n   * If not set, by default, the browser's HTTP fetch timeout applies.\n   *\n   * Consider setting this timeout if, for example, a web application firewall delays the responses of unavailable\n   * applications.\n   */\n  public abstract readonly manifestLoadTimeout?: number;\n  /**\n   * Maximum time (in milliseconds) for each application to signal readiness.\n   *\n   * If specified and activating an application takes longer, the host logs an error and continues startup.\n   * Has no effect for applications which provide no activator(s) or are not configured to signal readiness.\n   * You can set a different timeout per application via {@link ApplicationConfig.activatorLoadTimeout}.\n   *\n   * By default, no timeout is set, meaning that if an app fails to signal readiness, e.g., due to an error,\n   * that app would block the host startup process indefinitely. It is therefore recommended to specify a\n   * timeout accordingly.\n   */\n  public abstract readonly activatorLoadTimeout?: number;\n  /**\n   * Configures the liveness probe performed at regular intervals between host and clients to detect and dispose stale clients.\n   * Clients not replying to the probe are removed.\n   */\n  public abstract readonly liveness?: LivenessConfig;\n  /**\n   * Defines user-defined properties which can be read by micro applications via {@link PlatformPropertyService}.\n   */\n  public abstract readonly properties?: {\n    [key: string]: unknown;\n  };\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Intention, Manifest, PlatformCapabilityTypes} from '../platform.model';\nimport {MicrofrontendPlatformConfig} from './microfrontend-platform-config';\nimport {Beans} from '@scion/toolkit/bean-manager';\n\n/**\n * Hook to intercept the host manifest before it is registered in the platform.\n *\n * If integrating the platform in a library, you may need to intercept the manifest of the host in order to introduce library-specific behavior.\n *\n * You can register the interceptor in the bean manager, as follows:\n *\n * ```ts\n * Beans.register(HostManifestInterceptor, {useClass: YourInterceptor, multi: true});\n * ```\n *\n * The interceptor may look as following:\n * ```ts\n *  class YourInterceptor implements HostManifestInterceptor {\n *\n *   public intercept(hostManifest: Manifest): void {\n *     hostManifest.intentions = [\n *       ...hostManifest.intentions || [],\n *       provideMicrofrontendIntention(),\n *     ];\n *     hostManifest.capabilities = [\n *       ...hostManifest.capabilities || [],\n *       provideMessageBoxCapability(),\n *     ];\n *   }\n * }\n *\n * function provideMicrofrontendIntention(): Intention {\n *    return {\n *      type: 'microfrontend',\n *      qualifier: {'*': '*'},\n *    };\n *  }\n *\n * function provideMessageBoxCapability(): Capability {\n *    return {\n *      type: 'messagebox',\n *      qualifier: {},\n *      private: false,\n *      description: 'Allows displaying a simple message to the user.',\n *    };\n *  }\n *\n * ```\n *\n * @category Platform\n * @category Intention API\n */\nexport abstract class HostManifestInterceptor {\n\n  /**\n   * Allows modifying the host manifest before it is registered in the platform, e.g., to register capabilities or intentions.\n   */\n  public abstract intercept(hostManifest: Manifest): void;\n}\n\n/**\n * Intercepts the host manifest, registering platform-specific intentions and capabilities.\n *\n * @internal\n */\nexport class ɵHostManifestInterceptor implements HostManifestInterceptor {\n\n  public intercept(hostManifest: Manifest): void {\n    hostManifest.intentions = [\n      ...hostManifest.intentions ?? [],\n      ...provideActivatorIntentionIfEnabled(),\n    ];\n  }\n}\n\n/**\n * Provides a wildcard activator intention for the platform to read activator capabilities for installing activator microfrontends.\n */\nfunction provideActivatorIntentionIfEnabled(): Intention[] {\n  const activatorApiDisabled = Beans.get(MicrofrontendPlatformConfig).activatorApiDisabled ?? false;\n  if (activatorApiDisabled) {\n    return [];\n  }\n  return [{\n    type: PlatformCapabilityTypes.Activator,\n    qualifier: {'*': '*'},\n  }];\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {Observable} from 'rxjs';\nimport {Client} from './client';\n\n/**\n * Central point for managing client registrations.\n *\n * @internal\n */\nexport abstract class ClientRegistry {\n\n  /**\n   * Emits when registered a client.\n   */\n  public abstract readonly register$: Observable<Client>;\n\n  /**\n   * Emits when unregistered a client.\n   */\n  public abstract readonly unregister$: Observable<Client>;\n\n  /**\n   * Registers given client.\n   *\n   * If another client is already registered under the same window,\n   * a warning is logged and the \"stale\" client removed.\n   */\n  public abstract registerClient(client: Client): void;\n\n  /**\n   * Unregisters given client.\n   */\n  public abstract unregisterClient(client: Client): void;\n\n  /**\n   * Returns the client associated with the given id, or `undefined` if not found.\n   */\n  public abstract getByClientId(clientId: string): Client | undefined;\n\n  /**\n   * Returns the client associated with the given {@link Window}, or `undefined` if not found.\n   */\n  public abstract getByWindow(window: Window): Client | undefined;\n\n  /**\n   * Returns the clients associated with the given application.\n   */\n  public abstract getByApplication(appSymbolicName: string): Client[];\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {MonoTypeOperatorFunction, Observable, Subscription} from 'rxjs';\nimport {TopicMessage} from '../../messaging.model';\nimport {first, takeUntil} from 'rxjs/operators';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {PublishOptions, RequestOptions} from './publish-options';\n\n/**\n * Message client for sending and receiving messages between microfrontends across origins.\n *\n * This client implements the topic-based pub/sub (publish/subscribe) messaging model, allowing for one message to be delivered to\n * multiple subscribers using topic addressing.\n *\n * The communication is built on top of the native `postMessage` mechanism. The host app acts as message broker.\n *\n * ### Topic Addressing\n * A publisher publishes a message to a topic, which then is transported to consumers subscribed to the topic. Topics are case-sensitive\n * and consist of one or more segments, each separated by a forward slash. When publishing a message to a topic, the topic must be exact,\n * thus not contain wildcards. Messages published to a topic are transported to all consumers subscribed to the topic. Consumers, on the\n * other hand, can subscribe to multiple topics simultaneously by using wildcard segments in the topic.\n *\n * ### Retained Message\n * You can mark a message as \"retained\" for helping newly subscribed clients to get the last message published to a topic immediately upon\n * subscription. The broker stores one retained message per topic, i.e., a later sent retained message will replace a previously sent retained\n * message. To delete a retained message, send a retained message without payload to the topic.\n *\n * ### Retained Request\n * Unlike retained messages, retained requests are not replaced by later retained requests/messages and remain in the broker until the requestor unsubscribes.\n *\n * ### Request-Response Messaging\n * Sometimes it is useful to initiate a request-response communication to wait for a response. Unlike with fire-and-forget messaging, a temporary\n * inbox is created for the sender to receive replies. If there is no consumer subscribed on the topic, the platform throws an error.\n *\n * @see {@link TopicMessage}\n * @see {@link takeUntilUnsubscribe}\n *\n * @category Messaging\n */\nexport abstract class MessageClient {\n\n  /**\n   * Publishes a message to the given topic. The message is transported to all consumers subscribed to the topic.\n   *\n   * A message can be marked as \"retained\" by setting the {@link PublishOptions.retain} flag to `true`. It instructs the broker to store this message and\n   * deliver it to new subscribers, even if they subscribe after the message has been published. The broker stores one retained message per topic. To\n   * delete a retained message, send a retained message without payload to the topic. Deletion messages are not transported to subscribers.\n   *\n   * @param  topic - Specifies the topic to which the message should be sent.\n   *         Topics are case-sensitive and consist of one or more segments, each separated by a forward slash.\n   *         The topic is required and must be exact, thus not contain wildcards.\n   * @param  message - Specifies optional transfer data to be carried along with this message.\n   *         It can be any object which is serializable with the structured clone algorithm.\n   * @param  options - Controls how to publish the message and allows setting message headers.\n   * @return A Promise that resolves when dispatched the message, or that rejects if the message could not be dispatched.\n   */\n  public abstract publish<T = unknown>(topic: string, message?: T, options?: PublishOptions): Promise<void>;\n\n  /**\n   * Sends a request to the given topic and receives one or more replies.\n   *\n   * A request can be marked as \"retained\" by setting the {@link RequestOptions.retain} flag to `true`. It instructs the broker to store this request and\n   * deliver it to new subscribers, even if they subscribe after the request has been sent. Retained requests are not replaced by later retained requests/\n   * messages and remain in the broker until the requestor unsubscribes.\n   *\n   * If not marking the request as \"retained\", at least one subscriber must be subscribed to the topic. Otherwise, the request is rejected.\n   *\n   * @param  topic - Specifies the topic to which the request should be sent.\n   *         Topics are case-sensitive and consist of one or more segments, each separated by a forward slash.\n   *         The topic is required and must be exact, thus not contain wildcards.\n   * @param  request - Specifies optional transfer data to be carried along with the request.\n   *         It can be any object which is serializable with the structured clone algorithm.\n   * @param  options - Controls how to send the request and allows setting request headers.\n   * @return An Observable that emits when receiving a reply. It never completes unless the replier sets the status code {@link ResponseStatusCodes.TERMINAL}\n   *         in the {@link MessageHeaders.Status} message header. Then, the Observable completes immediately after emitted the reply.\n   *         The Observable errors if the request could not be dispatched. It will also error if the replier sets a status code greater than or equal to 400, e.g., {@link ResponseStatusCodes.ERROR}.\n   */\n  public abstract request$<T>(topic: string, request?: unknown, options?: RequestOptions): Observable<TopicMessage<T>>;\n\n  /**\n   * Receives messages published to the given topic.\n   *\n   * You can subscribe to multiple topics simultaneously by using wildcard segments in the topic. If a segment begins with a colon (`:`),\n   * then the segment acts as a placeholder for any segment value. Substituted segment values are then available via the params property\n   * of the received message.\n   *\n   * ```ts\n   * const topic: string = 'myhome/:room/temperature';\n   *\n   * Beans.get(MessageClient).observe$(topic).subscribe((message: TopicMessage) => {\n   *   console.log(message.params);\n   * });\n   * ```\n   *\n   * If the received message has the {@link MessageHeaders.ReplyTo} header field set, the publisher expects the receiver to send one or more\n   * replies to that {@link MessageHeaders.ReplyTo ReplyTo} topic. If streaming responses, you can use the {@link takeUntilUnsubscribe}\n   * operator to stop replying when the requestor unsubscribes.\n   *\n   * ```ts\n   * const topic: string = 'myhome/livingroom/temperature';\n   *\n   * Beans.get(MessageClient).observe$(topic).subscribe((request: TopicMessage) => {\n   *   const replyTo = request.headers.get(MessageHeaders.ReplyTo);\n   *   sensor$\n   *     .pipe(takeUntilUnsubscribe(replyTo))\n   *     .subscribe(temperature => {\n   *       Beans.get(MessageClient).publish(replyTo, `${temperature}°C`);\n   *     });\n   * });\n   * ```\n   *\n   * @param  topic - Specifies the topic which to observe.\n   *         Topics are case-sensitive and consist of one or more segments, each separated by a forward slash.\n   *         You can subscribe to the exact topic of a published message, or use wildcards to subscribe to multiple\n   *         topics simultaneously. If a segment begins with a colon (`:`), then the segment acts as a placeholder for any\n   *         string value. Substituted segment values are available in the {@link TopicMessage.params} on the received message.\n   * @return An Observable that emits messages sent to the given topic. It never completes.\n   */\n  public abstract observe$<T>(topic: string): Observable<TopicMessage<T>>;\n\n  /**\n   * Convenience API for handling messages.\n   *\n   * Unlike `observe$`, messages are passed to a callback function rather than emitted from an Observable. Response(s) can be returned directly\n   * from the callback. It supports error propagation and request termination. Using this method over `observe$` significantly reduces the code\n   * required to respond to requests.\n   *\n   * For each message received, the specified callback function is called. When used in request-response communication,\n   * the callback function can return the response either directly or in the form of a Promise or Observable. Returning a Promise\n   * allows the response to be computed asynchronously, and an Observable allows to return one or more responses, e.g., for\n   * streaming data.\n   * If the callback function returns no value (void), returns `undefined`, or returns a Promise that resolves to `undefined`, communication is terminated\n   * immediately without a response. If the callback returns an Observable, all its emissions are transported to the requestor and communication is not\n   * terminated until the Observable completes. Termination of communication always completes the requestor's Observable.\n   * If the callback throws an error, or the returned Promise or Observable errors, the error is\n   * transported to the requestor, erroring the requestor's Observable.\n   *\n   * @param  topic - Specifies the topic which to observe.\n   *         For more information, see the API description of {@link observe$}.\n   * @param  callback - Specifies the callback to be called for each message. When used in request-response communication,\n   *         the callback function can return the response either directly or in the form of a Promise or Observable. If returning\n   *         a response in fire-and-forget communication, it is ignored. Throwing an error in the callback does not unregister the callback.\n   * @return Subscription to unregister the callback. Calling {@link rxjs!Subscription.unsubscribe Subscription.unsubscribe} will complete the Observable of all\n   *         requestors, if any.\n   */\n  public abstract onMessage<IN = unknown, OUT = unknown>(topic: string, callback: (message: TopicMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription;\n\n  /**\n   * Allows observing the number of subscriptions on a topic. The Observable never completes.\n   *\n   * @param  topic - Specifies the topic to observe. The topic must be exact, thus not contain wildcards.\n   * @return An Observable that, when subscribed, emits the current number of subscribers on it. It never completes and\n   *         emits continuously when the number of subscribers changes.\n   */\n  public abstract subscriberCount$(topic: string): Observable<number>;\n}\n\n/**\n * Returns an Observable that mirrors the source Observable as long as there is at least one subscriber subscribed to the\n * given topic. When the subscription count on the given topic drops to zero, the returned Observable completes. If there\n * is no topic subscription present at the time when subscribing to the Observable, then it completes immediately.\n *\n * This operator is similar to the RxJS {@link rxjs!takeUntil takeUntil} operator, but accepts a topic instead of a notifier Observable.\n *\n * @category Messaging\n */\nexport function takeUntilUnsubscribe<T>(topic: string): MonoTypeOperatorFunction<T> {\n  return takeUntil(Beans.get(MessageClient).subscriberCount$(topic).pipe(first(count => count === 0)));\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {Message} from './messaging.model';\nimport {IntentSelector} from './client/messaging/intent-client';\n\n/**\n * Declares the message transports.\n *\n * @internal\n */\nexport enum MessagingTransport {\n  /**\n   * Transport used by clients to communicate with the broker.\n   */\n  ClientToBroker = 'sci://microfrontend-platform/client-to-broker',\n  /**\n   * Transport used by the broker to communicate with its clients.\n   */\n  BrokerToClient = 'sci://microfrontend-platform/broker-to-client',\n  /**\n   * Transport used by a microfrontend to communicate with its embedding outlet.\n   */\n  MicrofrontendToOutlet = 'sci://microfrontend-platform/microfrontend-to-outlet',\n}\n\n/**\n * Defines the channels to which messages can be sent.\n *\n * @internal\n */\nexport enum MessagingChannel {\n  /**\n   * Channel for clients to subscribe to a topic destination.\n   */\n  TopicSubscribe = 'topic-subscribe',\n  /**\n   * Channel for clients to unsubscribe from a topic destination.\n   */\n  TopicUnsubscribe = 'topic-unsubscribe',\n  /**\n   * Channel for clients to subscribe to intents.\n   */\n  IntentSubscribe = 'intent-subscribe',\n  /**\n   * Channel for clients to unsubscribe from intents.\n   */\n  IntentUnsubscribe = 'intent-unsubscribe',\n  /**\n   * Channel for the host to transport topic message to subscribed clients.\n   */\n  Topic = 'topic',\n  /**\n   * Channel for the host to transport intent messages to subscribed clients.\n   */\n  Intent = 'intent',\n  /**\n   * Channel for clients to send a connect request.\n   */\n  ClientConnect = 'client-connect',\n  /**\n   * Channel for clients to send a disconnect request.\n   */\n  ClientDisconnect = 'client-disconnect',\n}\n\n/**\n * Envelope for all messages.\n *\n * @internal\n */\nexport interface MessageEnvelope<MSG extends Message = Message> {\n  transport: MessagingTransport;\n  channel: MessagingChannel;\n  message: MSG;\n}\n\n/**\n * Declares internal platform topics.\n *\n * @internal\n */\nexport namespace PlatformTopics {\n  /**\n   * Topic to request the subscription count on a topic.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link string}\n   * Response Type: {@link number}\n   */\n  export const RequestSubscriberCount = 'ɵREQUEST_SUBSCRIBER_COUNT';\n  /**\n   * Topic to signal when gained the focus.\n   *\n   * Messaging Pattern: Publish-Subscribe\n   * Payload: {@link void}\n   */\n  export const FocusIn = 'ɵFOCUS_IN';\n  /**\n   * Topic to request whether the requesting client (or a microfrontend embedded in the client) has gained focus.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link void}\n   * Response Type: {@link boolean}\n   */\n  export const IsFocusWithin = 'ɵIS_FOCUS_WITHIN';\n  /**\n   * Topic to request whether the requesting client has gained focus.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link void}\n   * Response Type: {@link boolean}\n   */\n  export const HasFocus = 'ɵHAS_FOCUS';\n  /**\n   * Topic to read platform properties.\n   *\n   * Messaging Pattern: Publish-Subscribe\n   * Payload: {@link Record}\n   */\n  export const PlatformProperties = 'ɵPLATFORM_PROPERTIES';\n  /**\n   * Topic to read platform registered applications.\n   *\n   * Messaging Pattern: Publish-Subscribe\n   * Payload: {@link ɵApplication}\n   */\n  export const Applications = 'ɵAPPLICATIONS';\n  /**\n   * Topic to request capabilities.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link ManifestObjectFilter}\n   * Response Type: {@link Array<Capability>}\n   */\n  export const LookupCapabilities = 'ɵLOOKUP_CAPABILITIES';\n  /**\n   * Topic to request intentions.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link ManifestObjectFilter}\n   * Response Type: {@link Array<Intention>}\n   */\n  export const LookupIntentions = 'ɵLOOKUP_INTENTIONS';\n  /**\n   * Topic to register a capability.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link Capability}\n   * Response Type: {@link string}\n   */\n  export const RegisterCapability = 'ɵREGISTER_CAPABILITY';\n  /**\n   * Topic to unregister a capability.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link ManifestObjectFilter}\n   * Response Type: {@link void}\n   */\n  export const UnregisterCapabilities = 'ɵUNREGISTER_CAPABILITIES';\n  /**\n   * Topic to register an intentions.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link Intention}\n   * Response Type: {@link string}\n   */\n  export const RegisterIntention = 'ɵREGISTER_INTENTION';\n  /**\n   * Topic to unregister an intention.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link ManifestObjectFilter}\n   * Response Type: {@link void}\n   */\n  export const UnregisterIntentions = 'ɵUNREGISTER_INTENTIONS';\n  /**\n   * Topic to check if application is qualified for the capability.\n   *\n   * Messaging Pattern: Request-Response\n   * Request Type: {@link ApplicationQualifiedForCapabilityRequest}\n   * Response Type: {@link boolean}\n   */\n  export const IsApplicationQualifiedForCapability = 'ɵIS_APPLICATION_QUALIFIED_FOR_CAPABILITY';\n\n  /**\n   * Topic to request the platform version of a specific application.\n   */\n  export function platformVersion(appSymbolicName: string): string {\n    return `ɵapplication/${appSymbolicName}/platform/version`;\n  }\n\n  /**\n   * Topic to ping a client for liveness.\n   */\n  export function ping(clientId: string): string {\n    return `ɵclient/${clientId}/ping`;\n  }\n}\n\n/**\n * Sent by the broker in response to a connect request from a client gateway.\n *\n * @internal\n */\nexport interface ConnackMessage {\n  returnCode: 'accepted' | 'refused:bad-request' | 'refused:rejected' | 'refused:blocked';\n  returnMessage?: string;\n  /**\n   * Unique id assigned to the client by the broker. Is only set on success.\n   */\n  clientId?: string;\n}\n\n/**\n * @internal\n */\nexport interface SubscribeCommand extends Message {\n  /**\n   * Unique identify of the subscriber.\n   */\n  subscriberId: string;\n}\n\n/**\n * @internal\n */\nexport interface TopicSubscribeCommand extends SubscribeCommand {\n  /**\n   * Topic to subscribe.\n   */\n  topic: string;\n}\n\n/**\n * @internal\n */\nexport interface IntentSubscribeCommand extends SubscribeCommand {\n  /**\n   * Selects intents that match the specified selector and for which the application provides a fulfilling capability.\n   */\n  selector?: IntentSelector;\n}\n\n/**\n * @internal\n */\nexport interface UnsubscribeCommand extends Message {\n  /**\n   * Unique identify of the subscriber.\n   */\n  subscriberId: string;\n}\n\n/**\n * @internal\n */\nexport interface MessageDeliveryStatus {\n  ok: boolean;\n  details?: string;\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {Capability, Qualifier} from './platform.model';\nimport {MonoTypeOperatorFunction, Observable, of, OperatorFunction, pipe, throwError} from 'rxjs';\nimport {filter, map, mergeMap, takeWhile} from 'rxjs/operators';\n\n/**\n * Represents a message with headers to transport additional information with a message.\n *\n * @category Messaging\n */\nexport interface Message {\n  /**\n   * Additional information attached to this message.\n   *\n   * Header values must be JSON serializable. If no headers are set, the `Map` is empty.\n   */\n  headers: Map<string, unknown>;\n  /**\n   * Indicates whether this message is retained on the broker for late subscribers.\n   */\n  retain?: boolean;\n}\n\n/**\n * Represents an intent sent by an application.\n *\n * The intent is transported to applications that provide a fulfilling capability visible to the sending application.\n *\n * @category Messaging\n * @category Intention API\n */\nexport interface IntentMessage<BODY = unknown> extends Message {\n  /**\n   * Intent that represents this message.\n   */\n  intent: Intent;\n  /**\n   * Optional data passed along with the intent.\n   */\n  body?: BODY;\n  /**\n   * Capability that fulfills the intent.\n   */\n  capability: Capability;\n}\n\n/**\n * The term intention refers to the Intention API of the SCION Microfrontend Platform.\n *\n * The intent is the message that a micro application sends to interact with functionality that is available in the form of a capability.\n *\n * The platform transports the intent to the micro applications that provide the requested capability. A micro application can issue an\n * intent only if having declared an intention in its manifest. Otherwise, the platform rejects the intent.\n *\n * An intent is formulated in an abstract way, having assigned a type, and optionally a qualifier. This information is used for resolving\n * the capability; thus, it can be thought of as a form of capability addressing. See the definition of a capability for more information.\n *\n * @category Messaging\n * @category Intention API\n */\nexport interface Intent {\n  /**\n   * Type of functionality to intend.\n   */\n  type: string;\n  /**\n   * The qualifier is an abstract description of the intent and is expressed in the form of a dictionary.\n   *\n   * When issuing an intent, the qualifier must be exact, i.e. not contain wildcards.\n   */\n  qualifier?: Qualifier;\n  /**\n   * Parameters allow additional data to be passed along with the intent.\n   *\n   * They are part of the contract between the intent publisher and the capability provider. The capability provider\n   * can declare mandatory and optional parameters. No additional parameters may be included.\n   *\n   * Parameters have no effect on the intent routing, unlike the qualifier. If mandatory parameters\n   * are missing or non-specified parameters are included, the intent is rejected.\n   */\n  params?: Map<string, unknown>;\n}\n\n/**\n * Represents a message published to a topic.\n *\n * The message is transported to all consumers subscribed to the topic.\n *\n * @category Messaging\n */\nexport interface TopicMessage<BODY = unknown> extends Message {\n  /**\n   * The topic where to publish this message to.\n   */\n  topic: string;\n  /**\n   * Optional message.\n   */\n  body?: BODY;\n  /**\n   * Contains the resolved values of the wildcard segments as specified in the topic.\n   * For example: If subscribed to the topic `person/:id` and a message is published to the topic `person/5`,\n   * the resolved id with the value `5` is contained in the params map.\n   */\n  params?: Map<string, string>;\n}\n\n/**\n * Declares headers set by the platform when sending a message.\n *\n * Clients are allowed to read platform-defined headers from a message.\n *\n * @category Messaging\n */\nexport enum MessageHeaders {\n  /**\n   * Identifies the sending client instance of a message.\n   * This header is set by the platform when publishing a message or intent.\n   */\n  ClientId = 'ɵCLIENT_ID',\n  /**\n   * Identifies the sending application of a message.\n   * This header is set by the platform when publishing a message or intent.\n   */\n  AppSymbolicName = 'ɵAPP_SYMBOLIC_NAME',\n  /**\n   * Unique identity of the message.\n   * This header is set by the platform when publishing a message or intent.\n   */\n  MessageId = 'ɵMESSAGE_ID',\n  /**\n   * Destination to which to send a response to this message.\n   * This header is set by the platform when sending a request.\n   */\n  ReplyTo = 'ɵREPLY_TO',\n  /**\n   * The time the message was sent.\n   * This header is set by the platform when publishing a message or intent.\n   */\n  Timestamp = 'ɵTIMESTAMP',\n  /**\n   * The version of the client.\n   */\n  Version = 'ɵVERSION',\n  /**\n   * Use this header to set the request method to indicate the desired action to be performed for a given resource.\n   * @see RequestMethods\n   */\n  Method = 'ɵMETHOD',\n  /**\n   * Use this header to set the response status code to indicate whether a request has been successfully completed.\n   * See {@link ResponseStatusCodes} for available status codes. Other codes are also allowed.\n   *\n   * Status codes are primarily used in request-reply communication. In request-response communication, by default,\n   * the requestor’s Observable never completes. However, the replier can include the response status code in the reply’s\n   * headers, allowing to control the lifecycle of the requestor’s Observable.\n   *\n   * For example, the status code {@link ResponseStatusCodes.TERMINAL 250} allows completing the requestor’s Observable\n   * after emitted the reply, or the status code {@link ResponseStatusCodes.ERROR 500} to error the Observable.\n   *\n   * Note that the platform evaluates status codes only in request-response communication. They are ignored when observing\n   * topics or intents in pub/sub communication but can still be used; however, they must be handled by the application,\n   * e.g., by using the {@link throwOnErrorStatus} SCION RxJS operator.\n   *\n   * @see ResponseStatusCodes\n   */\n  Status = 'ɵSTATUS',\n  /**\n   * Unique identity of a message or intent subscriber.\n   *\n   * @internal\n   */\n  ɵSubscriberId = 'ɵSUBSCRIBER_ID',\n}\n\n/**\n * Defines a set of request methods to indicate the desired action to be performed for a given resource.\n *\n * @category Messaging\n */\nexport enum RequestMethods {\n  /**\n   * The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.\n   */\n  GET = 'GET',\n  /**\n   * The DELETE method deletes the specified resource.\n   */\n  DELETE = 'DELETE',\n  /**\n   * The PUT method replaces all current representations of the target resource with the request payload.\n   */\n  PUT = 'PUT',\n  /**\n   * The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.\n   */\n  POST = 'POST',\n  /**\n   * The OBSERVE method is used to observe the specified resource.\n   */\n  OBSERVE = 'OBSERVE',\n}\n\n/**\n * Defines a set of response status codes to indicate whether a request has been successfully completed.\n *\n * @see throwOnErrorStatus\n * @see MessageClient.request$\n * @see IntentClient.request$\n *\n * @category Messaging\n */\nexport enum ResponseStatusCodes {\n  /**\n   * The request has succeeded.\n   */\n  OK = 200,\n  /**\n   * The request has succeeded. No further response to be expected.\n   *\n   * In request-reply communication, setting this status code will complete the requestor's Observable\n   * after emitted the reply. The reply is only emitted if not `undefined`.\n   */\n  TERMINAL = 250,\n  /**\n   * The receiver could not understand the request due to invalid syntax.\n   *\n   * In request-reply communication, setting this status code will error the requestor's Observable.\n   */\n  BAD_REQUEST = 400,\n  /**\n   * The receiver could not find the requested resource.\n   *\n   * In request-reply communication, setting this status code will error the requestor's Observable.\n   */\n  NOT_FOUND = 404,\n  /**\n   * The receiver encountered an internal error. Optionally, set the error as message payload.\n   *\n   * In request-reply communication, setting this status code will error the requestor's Observable.\n   */\n  ERROR = 500,\n}\n\n/**\n * Returns an Observable that mirrors the source Observable unless receiving a message with\n * a response status code greater than or equal to 400. Then, the stream will end with an\n * {@link RequestError error} and the source Observable unsubscribed.\n *\n * When receiving a message with the response status code {@link ResponseStatusCodes.TERMINAL},\n * the Observable emits this message and completes.\n *\n * If a message does not include a response status code, the message is emitted as is.\n *\n * Note that this operator is installed in {@link MessageClient.request$} and {@link IntentClient.request$}.\n *\n * @category Messaging\n */\nexport function throwOnErrorStatus<BODY>(): MonoTypeOperatorFunction<TopicMessage<BODY>> {\n  return pipe(\n    mergeMap((message: TopicMessage<BODY>): Observable<TopicMessage<BODY>> => {\n      const status = message.headers.get(MessageHeaders.Status) as number | undefined ?? ResponseStatusCodes.OK;\n      if (status < 400) {\n        return of(message); // 1xx: informational responses, 2xx: successful responses, 4xx: client errors, 5xx: server errors\n      }\n\n      if (typeof message.body === 'string') {\n        const messageBody: string = message.body;\n        return throwError(() => new RequestError(messageBody, status, message));\n      }\n\n      switch (status) {\n        case ResponseStatusCodes.BAD_REQUEST: {\n          return throwError(() => new RequestError('The receiver could not understand the request due to invalid syntax.', status, message));\n        }\n        case ResponseStatusCodes.NOT_FOUND: {\n          return throwError(() => new RequestError('The receiver could not find the requested resource.', status, message));\n        }\n        case ResponseStatusCodes.ERROR: {\n          return throwError(() => new RequestError('The receiver encountered an internal error.', status, message));\n        }\n        default: {\n          return throwError(() => new RequestError('Request error.', status, message));\n        }\n      }\n    }),\n    takeWhile((message: TopicMessage<BODY>) => {\n      return message.headers.get(MessageHeaders.Status) !== ResponseStatusCodes.TERMINAL;\n    }, true),\n    filter((message: TopicMessage<BODY>) => {\n      const isTerminalMessage = message.headers.get(MessageHeaders.Status) === ResponseStatusCodes.TERMINAL;\n      return (!isTerminalMessage || message.body !== undefined);\n    }),\n  );\n}\n\n/**\n * Maps each message to its body.\n *\n * @category Messaging\n */\nexport function mapToBody<T>(): OperatorFunction<TopicMessage<T> | IntentMessage<T>, T> {\n  return map(message => message.body!);\n}\n\n/**\n * Indicates that the request handler responded with an error response.\n *\n * @category Messaging\n */\nexport class RequestError extends Error {\n\n  constructor(error: string, public status: number, public msg: Message) {\n    super(error);\n    this.name = 'RequestError';\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Provides utilities for working with topics.\n *\n * @internal\n */\nexport namespace Topics {\n\n  /**\n   * Tests whether given topic contains wildcard segments.\n   */\n  export function containsWildcardSegments(topic: string): boolean {\n    return split(topic).some(isWildcardSegment);\n  }\n\n  /**\n   * Tests whether given topic contains empty segments.\n   */\n  export function containsEmptySegments(topic: string): boolean {\n    return topic.split('/').some(segment => !segment.length);\n  }\n\n  /**\n   * Tests whether given segment is a wildcard segment.\n   */\n  export function isWildcardSegment(segment: string): boolean {\n    return segment.startsWith(':') && segment.length > 1;\n  }\n\n  /**\n   * Splits given topic into its segments.\n   */\n  export function split(topic: string | null | undefined): string[] {\n    return topic?.split('/').filter(Boolean) ?? [];\n  }\n\n  /**\n   * Returns unnamed wildcard permutations for given exact topic.\n   * These are 2^n variations, where n is the number of segments.\n   *\n   * Example:\n   * Topic: myhome/kitchen/temperature\n   *\n   * +-----------+-----------+-----------*-+\n   * | Segment 1 | Segment 2 | Segment 3   |\n   * +-----------+-----------+-*-----------+\n   * | myhome    | kitchen   | temperature |\n   * | myhome    | kitchen   | *           |\n   * | myhome    | *         | temperature |\n   * | myhome    | *         | *           |\n   * | *         | kitchen   | temperature |\n   * | *         | kitchen   | *           |\n   * | *         | *         | temperature |\n   * | *         | *         | *           |\n   * +-----------+-----------+-------------+\n   */\n  export function computeWildcardSegmentPermutations(topic: string | string[], wildcardCharacter: string): string[] {\n    const segments = typeof topic === 'string' ? Topics.split(topic) : topic;\n\n    if (segments.length === 1) {\n      return [segments[0]!, wildcardCharacter];\n    }\n\n    return computeWildcardSegmentPermutations(segments.slice(1), wildcardCharacter).reduce((permutations, permutation) => {\n      permutations.push(`${segments[0]}/${permutation}`);\n      permutations.push(`${wildcardCharacter}/${permutation}`);\n      return permutations;\n    }, new Array<string>());\n  }\n\n  /**\n   * Replaces named wildcard segments with given replacement.\n   *\n   * Example: \"myhome/:room/temperature\" => \"myhome/REPLACEMENT/temperature\"\n   *\n   */\n  export function replaceWildcardSegments(topic: string, replacement: string): string {\n    return topic.replace(/:[^/]+/g, replacement);\n  }\n\n  /**\n   * Validates given topic.\n   *\n   * @return `null` if valid, or the `Error` otherwise.\n   */\n  export function validateTopic(topic: string | null | undefined, options: {exactTopic: boolean}): Error | null {\n    if (!topic) {\n      return Error('[IllegalTopicError] Topic must not be `null`, `undefined` or empty');\n    }\n    if (Topics.containsEmptySegments(topic)) {\n      return Error(`[IllegalTopicError] Topic must not contain empty segments [topic='${topic}']`);\n    }\n    if (options.exactTopic && Topics.containsWildcardSegments(topic)) {\n      return Error(`[IllegalTopicError] Topic must be exact, i.e., not contain wildcard segments [topic='${topic}']`);\n    }\n    return null;\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Arrays} from '@scion/toolkit/util';\nimport {Topics} from './topics.util';\n\n/**\n * Allows testing whether an exact topic matches a pattern topic. The pattern topic may contain wildcard segments.\n *\n * Topics are case-sensitive and consist of one or more segments, each separated by a forward slash.\n *\n * @category Messaging\n */\nexport class TopicMatcher {\n\n  private readonly _patternSegments: string[];\n\n  /**\n   * Constructs a matcher that will match given topics against this pattern.\n   *\n   * @param pattern - Pattern to match topics. The pattern is a topic, not a regular expression; thus, it must consist of one or more segments,\n   *                  each separated by a forward slash. The pattern supports wildcard segments beginning with a colon (`:`). Wildcard segments\n   *                  act as a placeholder for any segment value.\n   */\n  constructor(pattern: string) {\n    this._patternSegments = Topics.split(pattern);\n    if (!this._patternSegments.length) {\n      throw Error('[TopicMatcherError] Invalid pattern syntax. The pattern must consist of one or more topic segments, each separated by a forward slash.');\n    }\n  }\n\n  /**\n   * Attempts to match the given topic against the pattern which was passed to the constructor.\n   *\n   * If the match succeeds, then {@link MatcherResult.matches} evaluates to `true`. If the pattern contains wildcard segments,\n   * the matched segments can be read using the property {@link TopicMessage.params} property.\n   *\n   * @param topic - The topic to match against the configured pattern; must be an exact topic, thus not contain wildcard segments.\n   * @return The result of the topic matcher test.\n   */\n  public match(topic: string): MatcherResult {\n    const inputTopicSegments = Topics.split(topic);\n    const patternSegments = this._patternSegments;\n\n    if (!inputTopicSegments.length) {\n      throw Error('[TopicMatcherError] Invalid topic. The topic must consist of one or more segments, each separated by a forward slash.');\n    }\n    if (inputTopicSegments.some(Topics.isWildcardSegment)) {\n      throw Error('[TopicMatcherError] Invalid topic. Wildcard segments not allowed in an exact topic.');\n    }\n    if (patternSegments.length !== inputTopicSegments.length) {\n      return {matches: false};\n    }\n    if (Arrays.isEqual(inputTopicSegments, patternSegments, {exactOrder: true})) {\n      return {matches: true, params: new Map()};\n    }\n    if (!patternSegments.some(Topics.isWildcardSegment)) {\n      return {matches: false};\n    }\n    if (!patternSegments.every((patternSegment, i) => patternSegment === inputTopicSegments[i] || Topics.isWildcardSegment(patternSegment))) {\n      return {matches: false};\n    }\n\n    return {\n      matches: true,\n      params: patternSegments.reduce((params, segment, i) => {\n        if (Topics.isWildcardSegment(segment)) {\n          return params.set(segment.substring(1), inputTopicSegments[i]);\n        }\n        return params;\n      }, new Map()),\n    };\n  }\n}\n\n/**\n * Represents the result of a topic matcher test.\n *\n * @category Messaging\n */\nexport interface MatcherResult {\n  /**\n   * Indicates if the topic matches the pattern topic.\n   */\n  matches: boolean;\n  /**\n   * Contains the actual values for the wildcard segments as defined in the pattern topic; is only set if the match is successful.\n   */\n  params?: Map<string, string>;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {MonoTypeOperatorFunction, OperatorFunction, pipe} from 'rxjs';\nimport {filter, map} from 'rxjs/operators';\nimport {MessageEnvelope, MessagingChannel, MessagingTransport} from './ɵmessaging.model';\nimport {Message, TopicMessage} from './messaging.model';\nimport {TopicMatcher} from './topic-matcher.util';\nimport {Arrays} from '@scion/toolkit/util';\n\n/** @internal */\nexport function filterByTransport(transport: MessagingTransport): OperatorFunction<MessageEvent, MessageEvent<MessageEnvelope>> {\n  return filter((event: MessageEvent): event is MessageEvent<MessageEnvelope> => {\n    const envelope = event.data as Partial<MessageEnvelope> | undefined;\n    return envelope?.transport === transport && !!envelope.channel && !!envelope.message?.headers;\n  });\n}\n\n/** @internal */\nexport function filterByChannel<T extends Message>(...channel: MessagingChannel[]): OperatorFunction<MessageEvent<MessageEnvelope>, MessageEvent<MessageEnvelope<T>>> {\n  const channels = new Set(Arrays.coerce(channel));\n  return filter((event: MessageEvent<MessageEnvelope>): event is MessageEvent<MessageEnvelope<T>> => {\n    return channels.has(event.data.channel);\n  });\n}\n\n/** @internal */\nexport function filterByTopicChannel<T>(topic: string): OperatorFunction<MessageEvent<MessageEnvelope>, MessageEvent<MessageEnvelope<TopicMessage<T>>>> {\n  return pipe(\n    filterByChannel<TopicMessage<T>>(MessagingChannel.Topic),\n    filter((event: MessageEvent<MessageEnvelope<TopicMessage<T>>>): boolean => {\n      const messageTopic = event.data.message.topic;\n      return !!messageTopic && new TopicMatcher(topic).match(messageTopic).matches;\n    }),\n  );\n}\n\n/** @internal */\nexport function filterByOrigin(origin: string): MonoTypeOperatorFunction<MessageEvent> {\n  return filter((event: MessageEvent): boolean => {\n    return event.origin === origin;\n  });\n}\n\n/** @internal */\nexport function filterByWindow(window: Window): MonoTypeOperatorFunction<MessageEvent> {\n  return filter((event: MessageEvent): boolean => {\n    return event.source === window;\n  });\n}\n\n/** @internal */\nexport function pluckMessage<T extends Message>(): OperatorFunction<MessageEvent<MessageEnvelope<T>>, T> {\n  return map((messageEvent: MessageEvent<MessageEnvelope<T>>): T => {\n    return messageEvent.data.message;\n  });\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {Logger} from './logger';\nimport {Beans} from '@scion/toolkit/bean-manager';\n\n/**\n * Runs the given function. Errors are caught and logged.\n *\n * If producing a Promise, returns that Promise, but with a catch handler installed.\n *\n * @internal\n */\nexport function runSafe<T = void>(runnable: () => T): T | undefined {\n  let result: T;\n  try {\n    result = runnable();\n  }\n  catch (error) {\n    Beans.opt(Logger)?.error('[UnexpectedError] An unexpected error occurred.', error);\n    return undefined;\n  }\n\n  if (result instanceof Promise) {\n    return result.catch((error: unknown) => {\n      Beans.opt(Logger)?.error('[UnexpectedError] An unexpected error occurred.', error);\n      return undefined;\n    }) as T;\n  }\n  return result;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Returns the error message if given an error object, or the `toString` representation otherwise.\n *\n * @internal\n */\nexport function stringifyError(error: string | Error | unknown): string {\n  if (error instanceof Error) {\n    return error.message;\n  }\n  return `${error}`;\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {MonoTypeOperatorFunction, Observable} from 'rxjs';\nimport {Beans} from '@scion/toolkit/bean-manager';\n\n/**\n * Enables the decoration of RxJS Observables provided by the SCION Microfrontend Platform to control their emission context.\n *\n * The emission context of an Observables may be different than the subscription context, which can lead to unexpected behavior\n * on the subscriber side. For example, Angular uses zones (Zone.js) to trigger change detection. Angular applications expect\n * an RxJS Observable to emit in the same Angular zone in which subscribed to the Observable. That is, if subscribing inside\n * the Angular zone, emissions are expected to be received inside the Angular zone. Otherwise, the UI may not be updated as\n * expected but delayed until the next change detection cycle. Similarly, if subscribing outside the Angular zone, emissions\n * are expected to be received outside the Angular zone. Otherwise, this would cause unnecessary change detection cycles\n * resulting in potential performance degradation.\n *\n * ### Example for Angular Applications\n *\n * For Angular applications, we recommend installing the following decorator:\n *\n * ```ts\n * import {NgZone} from '@angular/core';\n * import {ObservableDecorator} from '@scion/microfrontend-platform';\n * import {Observable} from 'rxjs';\n * import {observeIn, subscribeIn} from '@scion/toolkit/operators';\n *\n * export class NgZoneObservableDecorator implements ObservableDecorator {\n *\n *   constructor(private zone: NgZone) {\n *   }\n *\n *   public decorate$<T>(source$: Observable<T>): Observable<T> {\n *      return new Observable<T>(observer => {\n *        const insideAngular = NgZone.isInAngularZone();\n *        const subscription = source$\n *          .pipe(\n *            subscribeIn(fn => this.zone.runOutsideAngular(fn)),\n *            observeIn(fn => insideAngular ? this.zone.run(fn) : this.zone.runOutsideAngular(fn)),\n *          )\n *          .subscribe(observer);\n *        return () => subscription.unsubscribe();\n *      });\n *    }\n * }\n * ```\n *\n * A decorator can be registered with the bean manager under the symbol `ObservableDecorator`, as following:\n *\n * ```ts\n * Beans.register(ObservableDecorator, {useValue: new NgZoneObservableDecorator(zone)});\n * ```\n *\n * @category Messaging\n */\nexport abstract class ObservableDecorator {\n\n  /**\n   * Decorates given Observable.\n   *\n   * @param  source$ - Observable to be decorated.\n   * @return Decorated Observable.\n   */\n  public abstract decorate$<T>(source$: Observable<T>): Observable<T>;\n}\n\n/**\n * Decorates the source with registered {@link ObservableDecorator}, if any.\n *\n * @internal\n */\nexport function decorateObservable<T>(): MonoTypeOperatorFunction<T> {\n  return (source$: Observable<T>) => Beans.opt(ObservableDecorator)?.decorate$(source$) ?? source$;\n}\n","/*\n * Copyright (c) 2018-2023 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {merge, Observable, Subject, Subscriber} from 'rxjs';\nimport {takeUntil} from 'rxjs/operators';\nimport {Maps} from '@scion/toolkit/util';\n\n/**\n * Selects items emitted by an Observable according to a static criterion.\n *\n * This selector was introduced to quickly filter many messages from many subscribers.\n * Instead of a predicate, a key is used to dispatch messages with O(1) complexity to the subscribers.\n *\n * Prior to this selector, performance degraded significantly when sending more than 1000 messages\n * simultaneously, since filtering of message acknowledgements per-subscriber scaled worse than linearly.\n *\n * ---\n * ### Usage\n *\n * ```ts\n * // Create message source.\n * const messages$ = new Subject<{id: string; text: string}>();\n *\n * // Create selector to filter messages by id.\n * const selectMessagesById = new MessageSelector({source$: messages$, keySelector: message => message.id});\n *\n * // Receive only messages with id '1'.\n * selectMessagesById.select$('1').subscribe(msg => {\n *   // do something\n * });\n *\n * // Emit messages.\n * messages$.next({id: '1', text: 'foo'});\n * messages$.next({id: '2', text: 'bar'});\n * ```\n *\n * @internal\n */\nexport class MessageSelector<T> {\n\n  private _selectors = new Map<string, Array<Subject<T>>>();\n  private _sourceError$ = new Subject<never>();\n  private _sourceComplete$ = new Subject<void>();\n  private _destroy$ = new Subject<void>();\n\n  /**\n   * @param config - Controls how to select messages.\n   */\n  constructor(config: SelectorConfig<T>) {\n    const {source$, keySelector} = config;\n\n    source$\n      .pipe(takeUntil(this._destroy$))\n      .subscribe({\n        next: item => {\n          const key = keySelector(item);\n          this._selectors.get(key)?.forEach(selector => selector.next(item));\n        },\n        error: error => this._sourceError$.error(error),\n        complete: () => this._sourceComplete$.next(),\n      });\n  }\n\n  /**\n   * Selects items emitted by the source Observable that match the given key.\n   *\n   * @param key - Specifies the key to select items.\n   */\n  public select$<R extends T>(key: string): Observable<R> {\n    return new Observable<R>((observer: Subscriber<T>) => {\n      const selector$ = new Subject<T>();\n      Maps.addListValue(this._selectors, key, selector$);\n      const subscription = merge(selector$, this._sourceError$)\n        .pipe(takeUntil(this._sourceComplete$))\n        .subscribe(observer);\n\n      return () => {\n        Maps.removeListValue(this._selectors, key, selector$);\n        subscription.unsubscribe();\n      };\n    });\n  }\n\n  /**\n   * Returns the current subscriber count.\n   */\n  public ɵsubscriberCount(): number {\n    return Array.from(this._selectors.values()).reduce((count, selectors) => count + selectors.length, 0);\n  }\n\n  /**\n   * Disconnects this selector from the source Observable.\n   */\n  public disconnect(): void {\n    this._destroy$.next();\n  }\n}\n\n/**\n * Controls how to select items.\n *\n * @internal\n */\nexport interface SelectorConfig<T> {\n  /**\n   * Specifies the Observable to select items from.\n   */\n  source$: Observable<T>;\n  /**\n   * Specifies the function to compute the key of an item.\n   *\n   * A selector can then subscribe for items matching the key.\n   */\n  keySelector: (item: T) => string;\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {AsyncSubject, EMPTY, firstValueFrom, fromEvent, lastValueFrom, merge, MonoTypeOperatorFunction, NEVER, noop, Observable, Observer, of, ReplaySubject, Subject, TeardownLogic, throwError, timeout, timer} from 'rxjs';\nimport {ConnackMessage, MessageDeliveryStatus, MessageEnvelope, MessagingChannel, MessagingTransport, PlatformTopics, SubscribeCommand, UnsubscribeCommand} from '../../ɵmessaging.model';\nimport {finalize, map, mergeMap, take, takeUntil, tap} from 'rxjs/operators';\nimport {filterByChannel, filterByOrigin, filterByTopicChannel, filterByTransport, filterByWindow, pluckMessage} from '../../operators';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {IntentMessage, Message, MessageHeaders, ResponseStatusCodes, TopicMessage} from '../../messaging.model';\nimport {Logger, NULL_LOGGER} from '../../logger';\nimport {Dictionaries} from '@scion/toolkit/util';\nimport {Beans, Initializer, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {APP_IDENTITY, IS_PLATFORM_HOST} from '../../platform.model';\nimport {ɵVERSION, ɵWINDOW_TOP} from '../../ɵplatform.model';\nimport {PlatformState} from '../../platform-state';\nimport {ConnectOptions} from '../connect-options';\nimport {MicrofrontendPlatform} from '../../microfrontend-platform';\nimport {MessageClient} from './message-client';\nimport {runSafe} from '../../safe-runner';\nimport {stringifyError} from '../../error.util';\nimport {decorateObservable} from '../../observable-decorator';\nimport {MessageSelector} from './message-selector';\n\n/**\n * The gateway is responsible for dispatching messages between the client and the broker.\n *\n * To initiate a connection, the gateway sends a CONNECT message to the current and all parent windows. When the broker window\n * receives the CONNECT message, the broker responds with a CONNACK message. If no CONNACK message is received within the discovery\n * timeout, the gateway errors. When the gateway is being disposed, it sends a DISCONNECT message to the broker.\n *\n * @internal\n */\nexport abstract class BrokerGateway {\n\n  /**\n   * Returns whether this gateway is connected to the message broker. It never throws a broker discovery timeout error.\n   */\n  public abstract isConnected(): Promise<boolean>;\n\n  /**\n   * Posts a message to the message broker. If not connected to the broker yet, waits posting the message\n   * until established the connection to the broker.\n   *\n   * @return a Promise that resolves when successfully posted the message to the broker, or that rejects otherwise.\n   */\n  public abstract postMessage(channel: MessagingChannel, message: Message): Promise<void>;\n\n  /**\n   * Posts a message to the message broker and receives replies. The Observable never completes.\n   */\n  public abstract requestReply$<T = unknown>(channel: MessagingChannel, message: IntentMessage | TopicMessage): Observable<TopicMessage<T>>;\n\n  /**\n   * Subscribes to described destination, unless the platform has been stopped at the time of subscription.\n   */\n  public abstract subscribe$<T extends Message>(subscriptionDescriptor: SubscriptionDescriptor): Observable<T>;\n}\n\n/**\n * Broker gateway that does nothing.\n *\n * Use this gateway in tests to not connect to the platform host.\n *\n * @internal\n */\nexport class NullBrokerGateway implements BrokerGateway {\n\n  constructor() {\n    console.log('[NullBrokerGateway] Using \\'NullBrokerGateway\\'. Messages cannot be sent or received.');\n  }\n\n  public isConnected(): Promise<boolean> {\n    return Promise.resolve(true);\n  }\n\n  public get message$(): Observable<MessageEvent<MessageEnvelope>> {\n    return NEVER;\n  }\n\n  public async postMessage(channel: MessagingChannel, message: Message): Promise<void> {\n    return Promise.resolve();\n  }\n\n  public requestReply$<T = unknown>(channel: MessagingChannel, message: IntentMessage | TopicMessage): Observable<TopicMessage<T>> {\n    return NEVER;\n  }\n\n  public subscribe$<T extends Message>(subscriptionDescriptor: SubscriptionDescriptor): Observable<T> {\n    return NEVER;\n  }\n}\n\n/**\n * @internal\n */\nexport class ɵBrokerGateway implements BrokerGateway, PreDestroy, Initializer {\n\n  /*\n   * This Observable is primarily used as a notifier for the `takeUntil` operator to complete Observable subscriptions when the platform is shutting down.\n   * Since some subscriptions trigger subsequent broker interactions, e.g., unsubscribing from a topic subscription, the notifier must \"replay\" its state\n   * to avoid waiting for broker responses, which would never arrive and otherwise cause timeout errors.\n   */\n  private _platformStopping$ = new ReplaySubject<void>(1);\n  private _appSymbolicName: string;\n  private _brokerDiscoverTimeout: number;\n  private _messageDeliveryTimeout: number;\n  private _session: Session | null = null;\n  private _session$ = new AsyncSubject<Session>();\n  private _message$ = new Subject<MessageEvent<MessageEnvelope>>();\n\n  private _selectMessagesByTopic = new MessageSelector({\n    source$: this._message$.pipe(filterByChannel<TopicMessage>(MessagingChannel.Topic)),\n    keySelector: event => event.data.message.topic,\n  });\n  private _selectMessagesBySubscriberIdHeader = new MessageSelector({\n    source$: this._message$,\n    keySelector: event => event.data.message.headers.get(MessageHeaders.ɵSubscriberId) as string,\n  });\n\n  constructor(connectOptions?: ConnectOptions) {\n    this._appSymbolicName = Beans.get<string>(APP_IDENTITY);\n    this._brokerDiscoverTimeout = connectOptions?.brokerDiscoverTimeout ?? 10_000;\n    this._messageDeliveryTimeout = connectOptions?.messageDeliveryTimeout ?? 10_000;\n  }\n\n  public async init(): Promise<void> {\n    try {\n      const session = await this.connectToBroker();\n      this.installBrokerMessageListener(session);\n      this.installPingReplier(session);\n      this._session = session;\n      this._session$.next(session);\n      this._session$.complete();\n    }\n    catch (error) {\n      this._session$.error(error);\n      throw error;\n    }\n  }\n\n  public isConnected(): Promise<boolean> {\n    return lastValueFrom(this._session$).then(() => true).catch(() => false);\n  }\n\n  public get session(): Session | null {\n    return this._session;\n  }\n\n  public async postMessage(channel: MessagingChannel, message: Message): Promise<void> {\n    if (isPlatformStopped()) {\n      throw GatewayErrors.PLATFORM_STOPPED_ERROR;\n    }\n\n    // If not connected to the broker, wait until connected. If connected, continue execution immediately\n    // without spawning a microtask. Otherwise, messages cannot be published during platform shutdown.\n    const session = this._session ?? await lastValueFrom(this._session$);\n\n    const messageId = UUID.randomUUID();\n    const envelope: MessageEnvelope = {\n      transport: MessagingTransport.ClientToBroker,\n      channel: channel,\n      message: message,\n    };\n    envelope.message.headers\n      .set(MessageHeaders.MessageId, messageId)\n      .set(MessageHeaders.Timestamp, Date.now())\n      .set(MessageHeaders.AppSymbolicName, this._appSymbolicName)\n      .set(MessageHeaders.ClientId, session.clientId);\n\n    // Install Promise that resolves once the broker has acknowledged the message, or that rejects otherwise.\n    const postError$ = new Subject<never>();\n    const whenPosted = new Promise<void>((resolve, reject) => {\n      merge(this._selectMessagesByTopic.select$<MessageEvent<MessageEnvelope<TopicMessage<MessageDeliveryStatus>>>>(messageId), postError$)\n        .pipe(\n          take(1),\n          pluckMessage(),\n          timeout({first: this._messageDeliveryTimeout, with: () => throwError(() => GatewayErrors.MESSAGE_DISPATCH_ERROR(this._messageDeliveryTimeout, envelope))}),\n          mergeMap(statusMessage => statusMessage.body!.ok ? EMPTY : throwError(() => Error(statusMessage.body!.details))),\n          takeUntil(this._platformStopping$),\n        )\n        .subscribe({\n          error: reject,\n          complete: resolve,\n        });\n    });\n\n    try {\n      session.broker.window.postMessage(envelope, session.broker.origin);\n    }\n    catch (error) {\n      postError$.error(error);\n    }\n\n    await whenPosted;\n  }\n\n  public requestReply$<T = unknown>(channel: MessagingChannel, request: IntentMessage | TopicMessage): Observable<TopicMessage<T>> {\n    return new Observable((observer: Observer<TopicMessage<T>>): TeardownLogic => {\n      if (isPlatformStopped()) {\n        observer.error(GatewayErrors.PLATFORM_STOPPED_ERROR);\n        return noop;\n      }\n\n      const replyTo = UUID.randomUUID();\n      const subscriberId = UUID.randomUUID();\n      const unsubscribe$ = new Subject<void>();\n      const requestError$ = new Subject<never>();\n\n      request.headers\n        .set(MessageHeaders.ReplyTo, replyTo) // message header for the replier where to send replies to\n        .set(MessageHeaders.ɵSubscriberId, subscriberId); // message header to subscribe for replies\n\n      // Receive replies sent to the reply topic.\n      merge(this._selectMessagesBySubscriberIdHeader.select$<MessageEvent<MessageEnvelope<TopicMessage>>>(subscriberId), requestError$)\n        .pipe(\n          filterByChannel<TopicMessage<T>>(MessagingChannel.Topic),\n          pluckMessage(),\n          decorateObservable(),\n          takeUntil(merge(this._platformStopping$, unsubscribe$)),\n          finalize(() => void this.unsubscribe({unsubscribeChannel: MessagingChannel.TopicUnsubscribe, subscriberId, logContext: `[subscriberId=${subscriberId}, topic=${replyTo}]`})),\n        )\n        .subscribe({\n          next: reply => observer.next(reply),\n          error: error => observer.error(error),\n          complete: noop, // As per the API, the Observable never completes.\n        });\n\n      // Post the request to the broker.\n      this.postMessage(channel, request)\n        .catch((error: unknown) => requestError$.error(error));\n\n      return (): void => unsubscribe$.next();\n    });\n  }\n\n  public subscribe$<T extends Message>(subscriptionDescriptor: SubscriptionDescriptor): Observable<T> {\n    const {messageChannel, subscribeChannel, unsubscribeChannel, newSubscribeCommand} = subscriptionDescriptor;\n\n    return new Observable((observer: Observer<T>): TeardownLogic => {\n      if (isPlatformStopped()) {\n        observer.error(GatewayErrors.PLATFORM_STOPPED_ERROR);\n        return noop;\n      }\n\n      const subscriberId = UUID.randomUUID();\n      const unsubscribe$ = new Subject<void>();\n      const subscribeError$ = new Subject<never>();\n\n      // Receive messages of given subscription.\n      merge(this._selectMessagesBySubscriberIdHeader.select$<MessageEvent<MessageEnvelope<T>>>(subscriberId), subscribeError$)\n        .pipe(\n          filterByChannel<T>(messageChannel),\n          pluckMessage(),\n          decorateObservable(),\n          takeUntil(merge(this._platformStopping$, unsubscribe$)),\n          finalize(() => void this.unsubscribe({unsubscribeChannel, subscriberId, logContext: JSON.stringify(newSubscribeCommand(subscriberId))})),\n        )\n        .subscribe({\n          next: message => observer.next(message),\n          error: error => observer.error(error),\n          complete: noop, // As per the API, the Observable never completes.\n        });\n\n      // Post the subscription to the broker.\n      this.postMessage(subscribeChannel, newSubscribeCommand(subscriberId))\n        .catch((error: unknown) => subscribeError$.error(error));\n\n      return (): void => unsubscribe$.next();\n    });\n  }\n\n  /**\n   * Unsubscribes from described destination. Does nothing if the platform is stopped.\n   */\n  private async unsubscribe(descriptor: {unsubscribeChannel: MessagingChannel; subscriberId: string; logContext: string}): Promise<void> {\n    if (isPlatformStopped()) {\n      return;\n    }\n\n    const {unsubscribeChannel, subscriberId, logContext} = descriptor;\n    const unsubscribeCommand: UnsubscribeCommand = {subscriberId, headers: new Map()};\n    try {\n      await this.postMessage(unsubscribeChannel, unsubscribeCommand);\n    }\n    catch (error) {\n      Beans.get(Logger, {orElseGet: NULL_LOGGER}).error(`[UnsubscribeError] Failed to unsubscribe from destination: '${logContext}'. Caused by: ${error}`); // Fall back using NULL_LOGGER, e.g., when the platform is stopping.\n    }\n  }\n\n  /**\n   * Subscribes to messages sent to this client.\n   * Messages are dispatched to {@link _message$}.\n   */\n  private installBrokerMessageListener(session: Session): void {\n    fromEvent<MessageEvent>(window, 'message')\n      .pipe(\n        filterByWindow(session.broker.window),\n        filterByOrigin(session.broker.origin),\n        filterByTransport(MessagingTransport.BrokerToClient),\n        fixMapObjects(),\n        takeUntil(this._platformStopping$),\n      )\n      .subscribe(this._message$);\n  }\n\n  /**\n   * Installs a ping replier to indicate that this client is connected to the host.\n   *\n   * Note that no ping replier is installed if running in the context of the host application.\n   */\n  private installPingReplier(session: Session): void {\n    if (Beans.get(IS_PLATFORM_HOST)) {\n      return; // The host app client does not reply to pings.\n    }\n\n    Beans.get(MessageClient).observe$(PlatformTopics.ping(session.clientId))\n      .pipe(takeUntil(this._platformStopping$))\n      .subscribe(request => runSafe(() => {\n        const replyTo = request.headers.get(MessageHeaders.ReplyTo) as string;\n        void Beans.get(MessageClient).publish(replyTo, undefined, {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.TERMINAL)});\n      }));\n  }\n\n  /**\n   * Connects this client to the broker by sending a CONNECT message to the current and all parent windows.\n   *\n   * When the broker receives the CONNECT message and trusts this client, the broker responds with a CONNACK message,\n   * or rejects the connect attempt otherwise.\n   *\n   * @return A Promise that, when connected, resolves to information about the connected client and broker, or that rejects if the connect attempt\n   * failed, either because the broker could not be found or because the application is not allowed to connect.\n   */\n  public connectToBroker(): Promise<Session> {\n    const replyTo = UUID.randomUUID();\n    const connectPromise = firstValueFrom(fromEvent<MessageEvent>(window, 'message')\n      .pipe(\n        filterByTransport(MessagingTransport.BrokerToClient),\n        filterByTopicChannel<ConnackMessage>(replyTo),\n        mergeMap((messageEvent: MessageEvent<MessageEnvelope<TopicMessage<ConnackMessage>>>) => {\n          const response: ConnackMessage | undefined = messageEvent.data.message.body;\n          if (response?.returnCode !== 'accepted') {\n            return throwError(() => Error(`${response?.returnMessage ?? 'UNEXPECTED: Empty broker discovery response'} [code: '${response?.returnCode ?? 'n/a'}']`));\n          }\n          return of<Session>({\n            clientId: response.clientId!,\n            broker: {\n              window: messageEvent.source as Window,\n              origin: messageEvent.origin,\n            },\n          });\n        }),\n        timeout({first: this._brokerDiscoverTimeout, with: () => throwError(() => GatewayErrors.BROKER_DISCOVER_ERROR(this._brokerDiscoverTimeout))}),\n        tap({error: error => Beans.get(Logger, {orElseGet: NULL_LOGGER}).error(stringifyError(error))}), // Fall back using NULL_LOGGER, e.g., when the platform is stopping.\n        takeUntil(this._platformStopping$),\n      ));\n\n    const connectMessage: MessageEnvelope = {\n      transport: MessagingTransport.ClientToBroker,\n      channel: MessagingChannel.ClientConnect,\n      message: {\n        headers: new Map<string, unknown>()\n          .set(MessageHeaders.MessageId, UUID.randomUUID())\n          .set(MessageHeaders.Timestamp, Date.now())\n          .set(MessageHeaders.AppSymbolicName, this._appSymbolicName)\n          .set(MessageHeaders.ReplyTo, replyTo)\n          .set(MessageHeaders.Version, Beans.get(ɵVERSION)),\n      },\n    };\n\n    if (Beans.get(IS_PLATFORM_HOST)) {\n      window.postMessage(connectMessage, window.origin);\n    }\n    else if (window === Beans.get(ɵWINDOW_TOP)) {\n      // If loading the client into the topmost window it may be integrated into a rich client, with the host running in a different browser window (remote host).\n      // The rich client then bridges messages between the windows of the client and the remote host. Since the rich client may not be able to bridge messages\n      // right away when the client loads, the client repeatedly sends a connect request until acknowledged by the remote host.\n      const windowHierarchy = this.collectWindowHierarchy();\n      timer(0, 25)\n        .pipe(takeUntil(connectPromise.catch(() => null)))\n        .subscribe(() => {\n          windowHierarchy.forEach(window => window.postMessage(connectMessage, '*'));\n        });\n    }\n    else {\n      this.collectWindowHierarchy().forEach(window => window.postMessage(connectMessage, '*'));\n    }\n\n    return connectPromise;\n  }\n\n  /**\n   * Disconnects this client from the broker by sending a DISCONNECT message.\n   * Has no effect if not connected to the broker. If this operation fails, the error is logged as\n   * a warning, but not thrown.\n   */\n  private disconnectFromBroker(): void {\n    if (!this._session) {\n      return;\n    }\n\n    const disconnectMessage: MessageEnvelope = {\n      transport: MessagingTransport.ClientToBroker,\n      channel: MessagingChannel.ClientDisconnect,\n      message: {\n        headers: new Map<string, unknown>()\n          .set(MessageHeaders.MessageId, UUID.randomUUID())\n          .set(MessageHeaders.Timestamp, Date.now())\n          .set(MessageHeaders.AppSymbolicName, this._appSymbolicName)\n          .set(MessageHeaders.ClientId, this._session.clientId),\n      },\n    };\n\n    try {\n      this._session.broker.window.postMessage(disconnectMessage, this._session.broker.origin);\n    }\n    catch (error) {\n      Beans.get(Logger, {orElseGet: NULL_LOGGER}).warn(`[ClientDisconnectError] Failed to disconnect from the broker. Caused by: ${error}`);\n    }\n  }\n\n  /**\n   * Returns an array of the current `Window` hierarchy.\n   * Windows are sorted in top-down order, i.e., parent windows precede child windows.\n   */\n  private collectWindowHierarchy(): Window[] {\n    const candidates: Window[] = [];\n\n    for (let candidate = window as Window; candidate !== Beans.get(ɵWINDOW_TOP); candidate = candidate.parent) {\n      candidates.unshift(candidate);\n    }\n\n    candidates.unshift(Beans.get<Window>(ɵWINDOW_TOP));\n    return candidates;\n  }\n\n  /**\n   * Method invoked when the platform enters state {@link PlatformState.Stopping}.\n   *\n   * Since this gateway is registered in the bean manager with the maximum destruction order `{destroyOrder: Number.MAX_SAFE_INTEGER}`,\n   * the platform will destroy this bean after destroying other beans, which is important so that other beans can send messages\n   * when the platform shuts down.\n   */\n  public preDestroy(): void {\n    this.disconnectFromBroker();\n    this._platformStopping$.next();\n    this._selectMessagesByTopic.disconnect();\n    this._selectMessagesBySubscriberIdHeader.disconnect();\n  }\n}\n\n/**\n * Replaces `Map` objects contained in the message with a `Map` object of the current JavaScript realm.\n *\n * Data sent from one JavaScript realm to another is serialized with the structured clone algorithm.\n * Although the algorithm supports the `Map` data type, a deserialized map object cannot be checked to be instance of `Map`.\n * This is most likely because the serialization takes place in a different realm.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\n * @see http://man.hubwiz.com/docset/JavaScript.docset/Contents/Resources/Documents/developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm.html\n */\nfunction fixMapObjects<T extends Message>(): MonoTypeOperatorFunction<MessageEvent<MessageEnvelope<T>>> {\n  return map((event: MessageEvent<MessageEnvelope<T>>): MessageEvent<MessageEnvelope<T>> => {\n    const envelope: MessageEnvelope = event.data;\n    envelope.message.headers = new Map(envelope.message.headers);\n\n    if (envelope.channel === MessagingChannel.Intent) {\n      const intentMessage = envelope.message as IntentMessage;\n      intentMessage.intent.params = new Map(intentMessage.intent.params ?? []);\n    }\n    if (envelope.channel === MessagingChannel.Topic) {\n      const topicMessage = envelope.message as TopicMessage;\n      topicMessage.params = new Map(topicMessage.params ?? []);\n    }\n    return event;\n  });\n}\n\n/**\n * Creates a string representation of the given {@link MessageEnvelope}.\n */\nfunction stringifyEnvelope(envelope: MessageEnvelope): string {\n  return JSON.stringify(envelope, (key: string, value: unknown) => (value instanceof Map) ? Dictionaries.coerce(value) : value);\n}\n\nfunction isPlatformStopped(): boolean {\n  return MicrofrontendPlatform.state >= PlatformState.Stopped;\n}\n\n/**\n * Session created after successful connection with the broker.\n */\ninterface Session {\n  clientId: string;\n  broker: {\n    origin: string;\n    window: Window;\n  };\n}\n\nnamespace GatewayErrors {\n\n  export const PLATFORM_STOPPED_ERROR = Error('[GatewayError] Platform is stopped. Messages cannot be published or received.');\n\n  export function MESSAGE_DISPATCH_ERROR(timeout: number, message: MessageEnvelope): Error {\n    return Error(`[GatewayError] No acknowledgement received within ${timeout}ms for a message sent to the broker. [msg=${stringifyEnvelope(message)}]`);\n  }\n\n  export function BROKER_DISCOVER_ERROR(timeout: number): Error {\n    return Error(`[GatewayError] Message broker not discovered within ${timeout}ms. Messages cannot be published or received.`);\n  }\n}\n\n/**\n * Describes how to subscribe for messages.\n *\n * @internal\n */\nexport interface SubscriptionDescriptor {\n  /**\n   * Channel for receiving subscribed messages.\n   */\n  messageChannel: MessagingChannel;\n  /**\n   * Channel to send the subscribe request.\n   */\n  subscribeChannel: MessagingChannel;\n  /**\n   * Channel to send the unsubscribe request.\n   */\n  unsubscribeChannel: MessagingChannel;\n  /**\n   * Callback that is invoked to create the subscription command that will be sent over the subscription channel.\n   */\n  newSubscribeCommand: (subscriberId: string) => SubscribeCommand;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {MessageClient} from './client/messaging/message-client';\nimport {PlatformTopics} from './ɵmessaging.model';\nimport {map} from 'rxjs/operators';\nimport {Dictionary, Maps} from '@scion/toolkit/util';\nimport {firstValueFrom} from 'rxjs';\nimport {mapToBody} from './messaging.model';\nimport {Beans, Initializer} from '@scion/toolkit/bean-manager';\nimport {BrokerGateway, NullBrokerGateway} from './client/messaging/broker-gateway';\n\n/**\n * Allows looking up properties defined in the platform host.\n *\n * @category Platform\n */\nexport class PlatformPropertyService implements Initializer {\n\n  private _properties = new Map<string, unknown>();\n\n  public async init(): Promise<void> {\n    const messagingDisabled = Beans.get(BrokerGateway) instanceof NullBrokerGateway;\n    if (messagingDisabled) {\n      return;\n    }\n\n    // Wait until obtained platform properties so that they can be accessed synchronously by the application via `PlatformPropertyService#properties`.\n    const properties$ = Beans.get(MessageClient).observe$<Dictionary>(PlatformTopics.PlatformProperties);\n    this._properties = await firstValueFrom(properties$.pipe(mapToBody(), map(properties => Maps.coerce(properties))));\n  }\n\n  /**\n   * Indicates whether a property with the specified key exists or not.\n   */\n  public contains(key: string): boolean {\n    return this._properties.has(key);\n  }\n\n  /**\n   * Returns the property of the given key, or `defaultValue` if the property does not exist.\n   *\n   * Throws an error if `defaultValue` is not specified and the property does not exist.\n   */\n  public get<T>(key: string, defaultValue?: T): T {\n    if (this._properties.has(key)) {\n      return this._properties.get(key) as T;\n    }\n    if (defaultValue !== undefined) {\n      return defaultValue;\n    }\n    throw Error(`[PropertyNotFoundError] No property of given name found [prop=${key}]`);\n  }\n\n  /**\n   * Returns the properties map.\n   */\n  public properties(): Map<string, unknown> {\n    return this._properties;\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Uses the native Web Fetch API to fetch a resource from the network.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n * @internal\n */\nexport class HttpClient {\n\n  /**\n   * Allows fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves\n   * to the Response object representing the response to your request. The promise does not reject on HTTP errors — instead it only rejects on\n   * network errors; then handlers must check for HTTP errors.\n   *\n   * @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch\n   *\n   * @param  input - Defines the resource that you wish to fetch.\n   * @param  init - Options object containing any custom settings that you want to apply to the request.\n   * @return A Promise that resolves to a Response object.\n   */\n  public fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {\n    return fetch(input, init); // native call\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Capability, Intention} from '../../platform.model';\nimport {Intent} from '../../messaging.model';\nimport {Observable} from 'rxjs';\n\n/**\n * Central point for looking up or managing capabilities or intentions available in the platform.\n *\n * @internal\n */\nexport abstract class ManifestRegistry {\n\n  /**\n   * Returns capabilities which are visible to the given application and match the given intent.\n   * The intent is not allowed to contain wildcards in its qualifier.\n   */\n  public abstract resolveCapabilitiesByIntent(intent: Intent, appSymbolicName: string): Capability[];\n\n  /**\n   * Tests whether the given app has declared an intention for the given intent, or is providing a capability matching the given intent.\n   */\n  public abstract hasIntention(intent: Intent, appSymbolicName: string): boolean;\n\n  /**\n   * Registers the given capability for the given application.\n   *\n   * @return unique identity of the capability, if registered, or `null` if rejected by a {@link CapabilityInterceptor}.\n   */\n  public abstract registerCapability(capability: Capability, appSymbolicName: string): Promise<string | null>;\n\n  /**\n   * Registers the given intention for the given application.\n   */\n  public abstract registerIntention(intention: Intention, appSymbolicName: string): string;\n\n  /**\n   * Notifies when a capability is registered with the platform.\n   */\n  public abstract readonly capabilityRegister$: Observable<Capability>;\n\n  /**\n   * Notifies when capabilities are unregistered from the platform.\n   */\n  public abstract readonly capabilityUnregister$: Observable<Capability[]>;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nconst ABSOLUTE_URL_REGEX = /^(https?:\\/\\/)|(blob:)/;\n\n/**\n * @internal\n */\nexport namespace Urls {\n\n  /**\n   * Returns `true` if the given URL is an absolute URL, a blob or the 'about:blank' page.\n   */\n  export function isAbsoluteUrl(url: string): boolean {\n    return url === 'about:blank' || ABSOLUTE_URL_REGEX.test(url);\n  }\n\n  /**\n   * Constructs the {@link URL} for the given url and optional base, applying relative navigational symbols if contained in the url.\n   *\n   * Following rules apply:\n   * - base is required if providing a relative url\n   * - search and fragment parts of the base are ignored\n   * - relative navigational symbols are only applied if passing a base (native support)\n   *\n   * This function is similar to `new URL(url, base)` except that it works for bases that do not have a trailing slash.\n   * If you use `new URL(url, base)` without a trailing slash in the base, the last segment is discarded.\n   *\n   * // new URL('x/y', 'http://localhost:4200/a/b/').toString() -> \"http://localhost:4200/a/b/x/y\" // what we expect\n   * // new URL('x/y', 'http://localhost:4200/a/b').toString() -> \"http://localhost:4200/a/x/y\" // not what we expect\n   *\n   * We observed this behavior in Chromium and Firefox browsers.\n   */\n  export function newUrl(url: string, base?: string): URL {\n    if (base) {\n      const baseUrl = new URL(base);\n      if (baseUrl.pathname && !baseUrl.pathname.endsWith('/')) {\n        baseUrl.pathname += '/';\n      }\n      return new URL(url, baseUrl);\n    }\n\n    return new URL(url);\n  }\n\n  /**\n   * Adds a trailing slash to the given URL, if not already present.\n   */\n  export function ensureTrailingSlash(url: string): string {\n    if (!url.endsWith('/')) {\n      return url + '/';\n    }\n    return url;\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Manifest} from '../platform.model';\nimport {ɵApplication} from '../ɵplatform.model';\nimport {Arrays, Defined} from '@scion/toolkit/util';\nimport {Urls} from '../url.util';\nimport {MicrofrontendPlatformConfig} from './microfrontend-platform-config';\nimport {ManifestRegistry} from './manifest-registry/manifest-registry';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {Logger} from '../logger';\nimport {ApplicationConfig} from './application-config';\n\n/**\n * Registry with all registered applications.\n *\n * @internal\n */\nexport class ApplicationRegistry {\n\n  private static readonly SYMBOLIC_NAME_REGEXP = /^[a-z0-9-]+$/;\n\n  private readonly _applications = new Map<string, ɵApplication>();\n\n  /**\n   * Registers the given application.\n   *\n   * Throws an error if the application's symbolic name is not unique or contains illegal characters.\n   */\n  public async registerApplication(applicationConfig: ApplicationConfig, manifest: Manifest): Promise<void> {\n    Defined.orElseThrow(applicationConfig.symbolicName, () => Error(`[ApplicationRegistrationError] Invalid application config. Missing required property 'symbolicName'. [appConfig=\"${JSON.stringify(applicationConfig)}\", manifest=\"${JSON.stringify(manifest)}\"]`));\n    Defined.orElseThrow(applicationConfig.manifestUrl, () => Error(`[ApplicationRegistrationError] Invalid application config. Missing required property 'manifestUrl'. [appConfig=\"${JSON.stringify(applicationConfig)}\", manifest=\"${JSON.stringify(manifest)}\"]`));\n\n    if (!ApplicationRegistry.SYMBOLIC_NAME_REGEXP.test(applicationConfig.symbolicName)) {\n      throw Error(`[ApplicationRegistrationError] Symbolic name must be lowercase and contain alphanumeric and dash characters [symbolicName='${applicationConfig.symbolicName}'].`);\n    }\n\n    const notUniqueSymbolicName = Array.from(this._applications.values()).some(application => application.symbolicName === applicationConfig.symbolicName);\n    if (notUniqueSymbolicName) {\n      throw Error(`[ApplicationRegistrationError] Symbolic name must be unique [symbolicName='${applicationConfig.symbolicName}'].`);\n    }\n\n    const baseUrl = this.computeBaseUrl(applicationConfig, manifest);\n    this._applications.set(applicationConfig.symbolicName, {\n      symbolicName: applicationConfig.symbolicName,\n      name: manifest.name ?? applicationConfig.symbolicName, // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n      baseUrl: baseUrl,\n      manifestUrl: Urls.newUrl(applicationConfig.manifestUrl, Urls.isAbsoluteUrl(applicationConfig.manifestUrl) ? applicationConfig.manifestUrl : window.origin).toString(),\n      manifestLoadTimeout: applicationConfig.manifestLoadTimeout ?? Beans.get(MicrofrontendPlatformConfig).manifestLoadTimeout,\n      activatorLoadTimeout: applicationConfig.activatorLoadTimeout ?? Beans.get(MicrofrontendPlatformConfig).activatorLoadTimeout,\n      allowedMessageOrigins: new Set(Arrays.coerce(applicationConfig.secondaryOrigin)).add(Urls.newUrl(baseUrl).origin),\n      scopeCheckDisabled: applicationConfig.scopeCheckDisabled ?? false,\n      intentionCheckDisabled: applicationConfig.intentionCheckDisabled ?? false,\n      intentionRegisterApiDisabled: applicationConfig.intentionRegisterApiDisabled ?? true,\n      capabilityActiveCheckDisabled: applicationConfig.capabilityActiveCheckDisabled ?? false,\n    });\n\n    for (const capability of manifest.capabilities ?? []) {\n      try {\n        await Beans.get(ManifestRegistry).registerCapability(capability, applicationConfig.symbolicName);\n      }\n      catch (error) {\n        Beans.get(Logger).error(`[CapabilityRegisterError] Failed to register capability for application '${applicationConfig.symbolicName}'. [capability=${JSON.stringify(capability)}]`, error);\n      }\n    }\n\n    manifest.intentions?.forEach(intention => {\n      try {\n        Beans.get(ManifestRegistry).registerIntention(intention, applicationConfig.symbolicName);\n      }\n      catch (error) {\n        Beans.get(Logger).error(`[IntentionRegisterError] Failed to register intention for application '${applicationConfig.symbolicName}' [intention=${JSON.stringify(intention)}].`, error);\n      }\n    });\n  }\n\n  /**\n   * Finds the application of given symbolic name. If not found, by default, throws an error unless setting the `orElseNull` option.\n   */\n  public getApplication(symbolicName: string): ɵApplication;\n  public getApplication(symbolicName: string, options: {orElse: null}): ɵApplication | null;\n  public getApplication(symbolicName: string, options?: {orElse: null}): ɵApplication | null {\n    const application = this._applications.get(symbolicName);\n    if (!application && !options) {\n      throw Error(`[NullApplicationError] No application registered under the symbolic name '${symbolicName}'.`);\n    }\n    return application ?? null;\n  }\n\n  public getApplications(): ɵApplication[] {\n    return Array.from(this._applications.values());\n  }\n\n  /**\n   * Indicates whether the specified application is allowed to access private capabilities of other applications.\n   */\n  public isScopeCheckDisabled(appSymbolicName: string): boolean {\n    return Defined.orElseThrow(this._applications.get(appSymbolicName), () => Error(`[NullApplicationError] No application registered under the symbolic name '${appSymbolicName}'.`)).scopeCheckDisabled;\n  }\n\n  /**\n   * Indicates whether the specified application is allowed to access public capabilities of other applications without declaring an intention.\n   */\n  public isIntentionCheckDisabled(appSymbolicName: string): boolean {\n    return Defined.orElseThrow(this._applications.get(appSymbolicName), () => Error(`[NullApplicationError] No application registered under the symbolic name '${appSymbolicName}'.`)).intentionCheckDisabled;\n  }\n\n  /**\n   * Indicates whether the specified application is allowed to access inactive capabilities.\n   */\n  public isCapabilityActiveCheckDisabled(appSymbolicName: string): boolean {\n    return Defined.orElseThrow(this._applications.get(appSymbolicName), () => Error(`[NullApplicationError] No application registered under the symbolic name '${appSymbolicName}'.`)).capabilityActiveCheckDisabled;\n  }\n\n  /**\n   * Indicates whether the specified application is allowed to register and unregister intentions at runtime.\n   */\n  public isIntentionRegisterApiDisabled(appSymbolicName: string): boolean {\n    return Defined.orElseThrow(this._applications.get(appSymbolicName), () => Error(`[NullApplicationError] No application registered under the symbolic name '${appSymbolicName}'.`)).intentionRegisterApiDisabled;\n  }\n\n  /**\n   * Computes the base URL as following:\n   *\n   * - if base URL is specified in the manifest, that URL is used (either as an absolute URL, or relative to the origin of 'manifestUrl')\n   * - if base URL is not specified in the manifest, the origin from 'manifestUrl' is used as the base URL, or the origin from the current window if the 'manifestUrl' is relative\n   * - if base URL has no trailing slash, adds a trailing slash\n   */\n  private computeBaseUrl(applicationConfig: ApplicationConfig, manifest: Manifest): string {\n    const manifestURL = Urls.isAbsoluteUrl(applicationConfig.manifestUrl) ? Urls.newUrl(applicationConfig.manifestUrl) : Urls.newUrl(applicationConfig.manifestUrl, window.origin);\n\n    if (!manifest.baseUrl) {\n      return Urls.ensureTrailingSlash(manifestURL.origin);\n    }\n\n    if (Urls.isAbsoluteUrl(manifest.baseUrl)) {\n      return Urls.ensureTrailingSlash(manifest.baseUrl);\n    }\n    else {\n      return Urls.ensureTrailingSlash(Urls.newUrl(manifest.baseUrl, manifestURL.origin).toString());\n    }\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Qualifier} from './platform.model';\n\n/**\n * Allows testing whether a qualifier matches a qualifier pattern.\n *\n * @category Intention API\n */\nexport class QualifierMatcher {\n\n  private readonly _pattern: Qualifier;\n  private readonly _patternKeys: string[];\n\n  /**\n   * Constructs a matcher that will match given qualifiers against a pattern.\n   *\n   * @param pattern - Pattern to match qualifiers. If `null` or `undefined`, uses an empty qualifier pattern.\n   */\n  constructor(pattern: Qualifier | null | undefined) {\n    this._pattern = pattern ?? {};\n    this._patternKeys = Object.keys(this._pattern);\n  }\n\n  /**\n   * Attempts to match the given qualifier against the pattern which was passed to the constructor.\n   */\n  public matches(qualifier: Qualifier | null | undefined): boolean {\n    const testee = qualifier ?? {};\n    const testeeKeys = Object.keys(testee);\n    const {_patternKeys: patternKeys, _pattern: pattern} = this;\n\n    // Test if the testee has no additional entries\n    if (!patternKeys.includes('*') && testeeKeys.some(key => !patternKeys.includes(key))) {\n      return false;\n    }\n\n    return patternKeys\n      .filter(key => key !== '*')\n      .every(key => {\n        if (pattern[key] === testee[key]) {\n          return true;\n        }\n        if (pattern[key] === '*' && testee[key] !== undefined && testee[key] !== null) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n          return true;\n        }\n        return false;\n      });\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {QualifierMatcher} from '../../qualifier-matcher';\nimport {merge, Observable, Subject} from 'rxjs';\nimport {Arrays, Maps} from '@scion/toolkit/util';\nimport {ManifestObjectFilter, Qualifier} from '../../platform.model';\nimport {map} from 'rxjs/operators';\nimport {Predicate} from '../message-broker/predicates.util';\n\n/**\n * Provides an in-memory store for provided capabilities and registered intentions.\n *\n * @internal\n */\nexport class ManifestObjectStore<T extends ManifestObject> {\n\n  private readonly _objectById = new Map<string, T>();\n  private readonly _objectsByType = new Map<string, T[]>();\n  private readonly _objectsByApplication = new Map<string, T[]>();\n  private readonly _add$ = new Subject<T>();\n  private readonly _remove$ = new Subject<T[]>();\n\n  /**\n   * Adds the given {@link ManifestObject} to this store.\n   */\n  public add(object: T): void {\n    this._objectById.set(object.metadata!.id, object);\n    Maps.addListValue(this._objectsByType, object.type, object);\n    Maps.addListValue(this._objectsByApplication, object.metadata!.appSymbolicName, object);\n    this._add$.next(object);\n  }\n\n  /**\n   * Removes manifest objects from this store that match the given filter.\n   *\n   * @param filter - Control which manifest objects to remove by specifying filter criteria which are \"AND\"ed together.\n   *        Wildcards in the qualifier criterion, if any, are interpreted as such.\n   */\n  public remove(filter: ManifestObjectFilter): void {\n    const objectsToRemove = this.find(filter);\n    this._remove(objectsToRemove);\n  }\n\n  /**\n   * Finds manifest objects that match the given filter.\n   *\n   * @param filter - Control which manifest objects to return.\n   *        Specified filter criteria are \"AND\"ed together. If no filter criteria are specified, all objects will be returned.\n   */\n  public find(filter: Omit<ManifestObjectFilter, 'qualifier'> & {qualifier?: Qualifier | Predicate<Qualifier>}): T[] {\n    const filterById = filter.id !== undefined;\n    const filterByType = filter.type !== undefined;\n    const filterByApp = filter.appSymbolicName !== undefined;\n\n    return Arrays\n      .intersect(\n        filterById ? Arrays.coerce(this._objectById.get(filter.id!)) : undefined,\n        filterByType ? Arrays.coerce(this._objectsByType.get(filter.type!)) : undefined,\n        filterByApp ? Arrays.coerce(this._objectsByApplication.get(filter.appSymbolicName!)) : undefined,\n        (filterById || filterByType || filterByApp) ? undefined : Array.from(this._objectById.values()),\n      )\n      .filter(object => {\n        if (filter.qualifier === undefined) {\n          return true;\n        }\n        if (typeof filter.qualifier === 'function') {\n          return filter.qualifier(object.qualifier ?? {});\n        }\n\n        return new QualifierMatcher(filter.qualifier).matches(object.qualifier);\n      });\n  }\n\n  /**\n   * Finds the manifest object of given id. If not found, by default, throws an error unless setting the `orElseNull` option.\n   *\n   * @param id - Identifies the manifest object.\n   */\n  public findById(id: string): T;\n  public findById(id: string, options: {orElse: null}): T | null;\n  public findById(id: string, options?: {orElse: null}): T | null {\n    const object = this._objectById.get(id);\n    if (!object && !options) {\n      throw Error(`[NullManifestObjectError] Manifest object '${id}' not found.`);\n    }\n    return object ?? null;\n  }\n\n  /**\n   * Emits when an object is added to or removed from this store.\n   */\n  public get change$(): Observable<void> {\n    return merge(this.add$, this.remove$).pipe(map(() => undefined as void));\n  }\n\n  /**\n   * Emits when an object is added to this store.\n   */\n  public get add$(): Observable<T> {\n    return this._add$;\n  }\n\n  /**\n   * Emits when object(s) are removed from this store.\n   */\n  public get remove$(): Observable<T[]> {\n    return this._remove$;\n  }\n\n  /**\n   * Removes the given objects from all internal maps.\n   */\n  private _remove(objects: T[]): void {\n    const deleted = new Set<T>();\n    objects.forEach(object => {\n      const objectId = object.metadata!.id;\n      if (this._objectById.delete(objectId)) {\n        Maps.removeListValue(this._objectsByType, object.type, candidate => candidate.metadata?.id === objectId);\n        Maps.removeListValue(this._objectsByApplication, object.metadata!.appSymbolicName, candidate => candidate.metadata?.id === objectId);\n        deleted.add(object);\n      }\n    });\n    deleted.size && this._remove$.next(objects);\n  }\n}\n\n/**\n * Represents an object in the manifest registry like a capability or an intention.\n *\n * @internal\n */\nexport interface ManifestObject {\n  type: string;\n  qualifier?: Qualifier;\n  metadata?: {\n    id: string;\n    appSymbolicName: string;\n  };\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Capability, Intention} from '../../platform.model';\n\n/**\n * Enables modification of capabilities before they are registered.\n *\n * Interceptors can intercept capabilities before they are registered, for example,\n * to perform validation checks, add metadata, change properties, or prevent registration\n * based on user permissions.\n *\n * The following interceptor assigns a stable identifier to each microfrontend capability.\n *\n * ```ts\n * class MicrofrontendCapabilityInterceptor implements CapabilityInterceptor {\n *\n *   public async intercept(capability: Capability): Promise<Capability> {\n *     if (capability.type === 'microfrontend') {\n *       return {\n *         ...capability,\n *         // `hash()` is illustrative and not part of the Microfrontend Platform API.\n *         metadata: {...capability.metadata, id: hash(capability)},\n *       };\n *     }\n *     return capability;\n *   }\n * }\n * ```\n *\n * The following interceptor marks capabilities as inactive based on user permissions.\n *\n * ```ts\n * class UserAuthorizedCapabilityInterceptor implements CapabilityInterceptor {\n *\n *   public async intercept(capability: Capability): Promise<Capability> {\n *     // Read required role from capability properties.\n *     const requiredRole = capability.properties?.['role'];\n *\n *     // Mark capability as inactive if the user has no permission.\n *     // `hasRole()` is illustrative and not part of the Microfrontend Platform API.\n *     capability.inactive = requiredRole && !hasRole(requiredRole);\n *\n *     return capability;\n *   }\n * }\n * ```\n * Alternatively, the capability can be rejected. Unlike inactive capabilities, rejected capabilities are not listed in the SCION DevTools.\n *\n * ```ts\n * class UserAuthorizedCapabilityInterceptor implements CapabilityInterceptor {\n *\n *   public async intercept(capability: Capability): Promise<Capability | null> {\n *     // Read required role from capability properties.\n *     const requiredRole = capability.properties?.['role'];\n *\n *     // `hasRole()` is illustrative and not part of the Microfrontend Platform API.\n *     return !requiredRole || hasRole(requiredRole) ? capability : null;\n *   }\n * }\n * ```\n *\n * The following interceptor extracts user information to a new capability.\n *\n * ```ts\n * class UserCapabilityMigrator implements CapabilityInterceptor {\n *\n *   public async intercept(capability: Capability, manifest: CapabilityInterceptor.Manifest): Promise<Capability> {\n *     if (capability.type === 'user' && capability.properties['info']) {\n *       // Move user info to new capability.\n *       await manifest.addCapability({\n *         type: 'user-info',\n *         properties: {\n *           ...capability.properties['info'],\n *         },\n *       });\n *       // Remove info on intercepted capability.\n *       delete capability.properties['info'];\n *     }\n *     return capability;\n *   }\n * }\n * ```\n *\n * #### Registering Interceptors\n * Interceptors are registered in the bean manager of the host application under the symbol `CapabilityInterceptor` as multi bean.\n * Multiple interceptors can be registered, forming a chain in which each interceptor is called one by one in registration order.\n *\n * ```ts\n * Beans.register(CapabilityInterceptor, {useClass: MicrofrontendCapabilityInterceptor, multi: true});\n * Beans.register(CapabilityInterceptor, {useClass: UserAuthorizedCapabilityInterceptor, multi: true});\n * Beans.register(CapabilityInterceptor, {useClass: UserCapabilityMigrator, multi: true});\n * ```\n *\n * @category Intention API\n */\nexport abstract class CapabilityInterceptor {\n\n  /**\n   * Intercepts a capability before being registered.\n   *\n   * An interceptor can add extra capabilities and intentions to the manifest of the intercepted capability. This may be necessary to migrate capabilities.\n   *\n   * @param capability - Capability to be intercepted.\n   * @param manifest - Manifest of the application that provides the intercepted capability, allowing for the registration of extra capabilities and intentions.\n   * @return Promise that resolves to the intercepted capability, or `null` to prevent registration.\n   */\n  public abstract intercept(capability: Capability, manifest: CapabilityInterceptor.Manifest): Promise<Capability | null>;\n}\n\n/**\n * Declares objects local to CapabilityInterceptor.\n */\nexport namespace CapabilityInterceptor {\n\n  /**\n   * Manifest of the application that provides the intercepted capability.\n   */\n  export interface Manifest {\n\n    /**\n     * Adds specified capability to the application of the intercepted capability.\n     */\n    addCapability<T extends Capability>(capability: T): Promise<string | null>;\n\n    /**\n     * Adds specified intention to the application of the intercepted capability.\n     */\n    addIntention(intention: Intention): Promise<string>;\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Qualifier} from './platform.model';\n\n/**\n * Provides utilities for working with qualifiers.\n *\n * @internal\n */\nexport namespace Qualifiers {\n\n  const ALLOWED_VALUE_TYPES = new Set<string>().add('string').add('number').add('boolean');\n\n  /**\n   * Validates given qualifier.\n   *\n   * @return `null` if valid, or the `Error` otherwise.\n   */\n  export function validateQualifier(qualifier: Qualifier | null | undefined, options: {exactQualifier: boolean}): Error | null {\n    if (!qualifier || Object.keys(qualifier).length === 0) {\n      return null;\n    }\n    if (options.exactQualifier && Object.entries(qualifier).some(([key, value]) => key === '*' || value === '*')) {\n      return Error(`[IllegalQualifierError] Qualifier must be exact, i.e., not contain wildcards. [qualifier='${JSON.stringify(qualifier)}']`);\n    }\n    if (Object.values(qualifier).some(value => value === '' || value === null || value === undefined)) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n      return Error(`[IllegalQualifierError] Qualifier must not contain empty, \\`null\\`, or \\`undefined\\` entries. [qualifier='${JSON.stringify(qualifier)}']`);\n    }\n    if (Object.values(qualifier).some(value => !ALLOWED_VALUE_TYPES.has(typeof value))) {\n      return Error(`[IllegalQualifierError] Qualifier contains entries with an illegal data type. Supported data types are [${[...ALLOWED_VALUE_TYPES].join(', ')}]. [qualifier='${JSON.stringify(qualifier)}']`);\n    }\n    return null;\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {ApplicationQualifiedForCapabilityRequest, Capability, Intention, ManifestObjectFilter, ParamDefinition} from '../../platform.model';\nimport {ManifestObjectStore} from './manifest-object-store';\nimport {concatWith, defer, EMPTY, filter, merge, Observable, of, Subscription} from 'rxjs';\nimport {distinctUntilChanged, expand, map, mergeMap, startWith, take} from 'rxjs/operators';\nimport {Intent, MessageHeaders, TopicMessage} from '../../messaging.model';\nimport {MessageClient} from '../../client/messaging/message-client';\nimport {ApplicationRegistry} from '../application-registry';\nimport {filterArray} from '@scion/toolkit/operators';\nimport {ManifestRegistry} from './manifest-registry';\nimport {QualifierMatcher} from '../../qualifier-matcher';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {ClientRegistry} from '../client-registry/client.registry';\nimport {CapabilityInterceptor} from './capability-interceptors';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {Qualifiers} from '../../qualifiers.util';\nimport {PlatformTopics} from '../../ɵmessaging.model';\n\n/**\n * @internal\n */\nexport class ɵManifestRegistry implements ManifestRegistry, PreDestroy {\n\n  private _capabilityStore: ManifestObjectStore<Capability>;\n  private _intentionStore: ManifestObjectStore<Intention>;\n  private _subscriptions = new Set<Subscription>();\n\n  public capabilityRegister$: Observable<Capability>;\n  public capabilityUnregister$: Observable<Capability[]>;\n\n  constructor() {\n    this._capabilityStore = new ManifestObjectStore<Capability>();\n    this._intentionStore = new ManifestObjectStore<Intention>();\n\n    this.capabilityRegister$ = this._capabilityStore.add$;\n    this.capabilityUnregister$ = this._capabilityStore.remove$;\n\n    this.installCapabilityRegisterRequestHandler();\n    this.installCapabilityUnregisterRequestHandler();\n\n    this.installIntentionRegisterRequestHandler();\n    this.installIntentionUnregisterRequestHandler();\n\n    this.installCapabilitiesLookupRequestHandler();\n    this.installIntentionsLookupRequestHandler();\n    this.installIsApplicationQualifiedRequestHandler();\n    this.installVersionLookupHandler();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public resolveCapabilitiesByIntent(intent: Intent, appSymbolicName: string): Capability[] {\n    const illegalQualifierError = Qualifiers.validateQualifier(intent.qualifier, {exactQualifier: true});\n    if (illegalQualifierError) {\n      throw illegalQualifierError;\n    }\n\n    const filter: ManifestObjectFilter = {type: intent.type, qualifier: intent.qualifier ?? {}};\n    return this._capabilityStore.find(filter)\n      .filter(capability => this.isApplicationQualifiedForCapability(appSymbolicName, capability));\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public hasIntention(intent: Intent, appSymbolicName: string): boolean {\n    const illegalQualifierError = Qualifiers.validateQualifier(intent.qualifier, {exactQualifier: true});\n    if (illegalQualifierError) {\n      throw illegalQualifierError;\n    }\n\n    const filter: ManifestObjectFilter = {appSymbolicName, type: intent.type};\n    const isIntentionCheckDisabled = Beans.get(ApplicationRegistry).isIntentionCheckDisabled(appSymbolicName);\n    const isCapabilityActiveCheckDisabled = Beans.get(ApplicationRegistry).isCapabilityActiveCheckDisabled(appSymbolicName);\n\n    // Tests if the app has declared an intention.\n    const hasIntention = (): boolean => this._intentionStore.find({...filter, qualifier: intentionQualifier => new QualifierMatcher(intentionQualifier).matches(intent.qualifier)}).length > 0;\n    // Tests if the app has an implicit intention if it provides the capability.\n    const hasImplicitIntention = (): boolean => this._capabilityStore.find({...filter, qualifier: intent.qualifier ?? {}})\n      .filter(capability => isCapabilityActiveCheckDisabled || !capability.inactive)\n      .length > 0;\n\n    return isIntentionCheckDisabled || hasIntention() || hasImplicitIntention();\n  }\n\n  /**\n   * Tests whether the specified application is qualified to access the given capability.\n   *\n   * An application is qualified if following criteria are met:\n   * - The capability is active (1).\n   * - The capability is provided by the application, or provided by another application with\n   *   public visibility (2), and the application has an intention (3) for the capability.\n   *\n   * (1) Unless 'Capability Active Check' is disabled for the application.\n   * (2) Unless 'Scope Check' is disabled for the application.\n   * (3) Unless 'Intention Check' is disabled for the application.\n   */\n  private isApplicationQualifiedForCapability(appSymbolicName: string, capability: Capability): boolean {\n    const isScopeCheckDisabled = Beans.get(ApplicationRegistry).isScopeCheckDisabled(appSymbolicName);\n    const isIntentionCheckDisabled = Beans.get(ApplicationRegistry).isIntentionCheckDisabled(appSymbolicName);\n    const isCapabilityActiveCheckDisabled = Beans.get(ApplicationRegistry).isCapabilityActiveCheckDisabled(appSymbolicName);\n    const isCapabilityProvider = capability.metadata!.appSymbolicName === appSymbolicName;\n\n    // Perform active check.\n    if (capability.inactive && !isCapabilityActiveCheckDisabled) {\n      return false;\n    }\n\n    // Perform scope check.\n    if (!isCapabilityProvider && capability.private && !isScopeCheckDisabled) {\n      return false;\n    }\n\n    // Perform intention check.\n    if (!isCapabilityProvider && !this.hasIntentionForCapability(appSymbolicName, capability) && !isIntentionCheckDisabled) {\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Tests whether the given app has declared a matching intention for the given capability.\n   */\n  private hasIntentionForCapability(appSymbolicName: string, capability: Capability): boolean {\n    return this._intentionStore.find({\n      appSymbolicName,\n      type: capability.type,\n      qualifier: intentionQualifier => new QualifierMatcher(intentionQualifier).matches(capability.qualifier),\n    }).length > 0;\n  }\n\n  public async registerCapability(capability: Capability, appSymbolicName: string): Promise<string | null> {\n    if (!capability) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n      throw Error('[CapabilityRegisterError] Capability must not be null or undefined.');\n    }\n    if (!capability.type) {\n      throw Error('[CapabilityRegisterError] Missing capability property: type');\n    }\n    const illegalQualifierError = Qualifiers.validateQualifier(capability.qualifier, {exactQualifier: true});\n    if (illegalQualifierError) {\n      throw illegalQualifierError;\n    }\n\n    assertCapabilityParamDefinitions(capability.params);\n\n    // Let the host app intercept the capability to register.\n    const capabilityToRegister = await interceptCapability({\n      ...capability,\n      qualifier: capability.qualifier ?? {},\n      params: capability.params ?? [],\n      private: capability.private ?? true,\n      inactive: capability.inactive ?? false,\n      metadata: {\n        id: UUID.randomUUID(),\n        appSymbolicName: appSymbolicName,\n      },\n    });\n\n    // Register the capability.\n    if (capabilityToRegister) {\n      this._capabilityStore.add(capabilityToRegister);\n      return capabilityToRegister.metadata!.id;\n    }\n    return null;\n  }\n\n  public unregisterCapabilities(appSymbolicName: string, filter: ManifestObjectFilter): void {\n    this._capabilityStore.remove({...filter, appSymbolicName});\n  }\n\n  public registerIntention(intention: Intention, appSymbolicName: string): string {\n    if (!intention) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n      throw Error('[IntentionRegisterError] Intention must not be null or undefined.');\n    }\n    if (!intention.type) {\n      throw Error('[IntentionRegisterError] Missing intention property: type');\n    }\n    const illegalQualifierError = Qualifiers.validateQualifier(intention.qualifier, {exactQualifier: false});\n    if (illegalQualifierError) {\n      throw illegalQualifierError;\n    }\n\n    const intentionToRegister: Intention = {\n      ...intention,\n      metadata: {\n        id: UUID.randomUUID(),\n        appSymbolicName: appSymbolicName,\n      },\n    };\n\n    // Register the intention.\n    this._intentionStore.add(intentionToRegister);\n    return intentionToRegister.metadata!.id;\n  }\n\n  private unregisterIntention(appSymbolicName: string, filter: ManifestObjectFilter): void {\n    this._intentionStore.remove({...filter, appSymbolicName});\n  }\n\n  private installCapabilityRegisterRequestHandler(): void {\n    this._subscriptions.add(Beans.get(MessageClient).onMessage<Capability, string | null>(PlatformTopics.RegisterCapability, (request: TopicMessage<Capability>) => {\n      const capability = request.body!;\n      const appSymbolicName = request.headers.get(MessageHeaders.AppSymbolicName) as string;\n      return this.registerCapability(capability, appSymbolicName);\n    }));\n  }\n\n  private installCapabilityUnregisterRequestHandler(): void {\n    this._subscriptions.add(Beans.get(MessageClient).onMessage<ManifestObjectFilter, void>(PlatformTopics.UnregisterCapabilities, (request: TopicMessage<ManifestObjectFilter>) => {\n      const capabilityFilter = request.body ?? {};\n      const appSymbolicName = request.headers.get(MessageHeaders.AppSymbolicName) as string;\n      this.unregisterCapabilities(appSymbolicName, capabilityFilter);\n    }));\n  }\n\n  private installIntentionRegisterRequestHandler(): void {\n    this._subscriptions.add(Beans.get(MessageClient).onMessage<Intention, string>(PlatformTopics.RegisterIntention, (request: TopicMessage<Intention>) => {\n      const intention = request.body!;\n      const appSymbolicName = request.headers.get(MessageHeaders.AppSymbolicName) as string;\n      assertIntentionRegisterApiEnabled(appSymbolicName);\n      return this.registerIntention(intention, appSymbolicName);\n    }));\n  }\n\n  private installIntentionUnregisterRequestHandler(): void {\n    this._subscriptions.add(Beans.get(MessageClient).onMessage<ManifestObjectFilter, void>(PlatformTopics.UnregisterIntentions, (request: TopicMessage<ManifestObjectFilter>) => {\n      const intentFilter = request.body ?? {};\n      const appSymbolicName = request.headers.get(MessageHeaders.AppSymbolicName) as string;\n      assertIntentionRegisterApiEnabled(appSymbolicName);\n      this.unregisterIntention(appSymbolicName, intentFilter);\n    }));\n  }\n\n  private installCapabilitiesLookupRequestHandler(): void {\n    this._subscriptions.add(Beans.get(MessageClient).onMessage<ManifestObjectFilter, Capability[]>(PlatformTopics.LookupCapabilities, (request: TopicMessage<ManifestObjectFilter>) => {\n      const appSymbolicName = request.headers.get(MessageHeaders.AppSymbolicName) as string;\n      const lookupFilter = request.body ?? {};\n\n      const illegalQualifierError = Qualifiers.validateQualifier(lookupFilter.qualifier, {exactQualifier: false});\n      if (illegalQualifierError) {\n        throw illegalQualifierError;\n      }\n\n      // The queried capabilities may change on both, capability or intention change, because the computation\n      // of visible and qualified capabilities depends on registered capabilities and manifested intentions.\n      const registryChange$ = merge(this._capabilityStore.change$, this._intentionStore.change$);\n      const finder$ = defer(() => of(this._capabilityStore.find(lookupFilter)));\n      return finder$\n        .pipe(\n          expand(() => registryChange$.pipe(take(1), mergeMap(() => finder$))),\n          filterArray(capability => this.isApplicationQualifiedForCapability(appSymbolicName, capability)),\n          distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),\n        );\n    }));\n  }\n\n  private installIntentionsLookupRequestHandler(): void {\n    this._subscriptions.add(Beans.get(MessageClient).onMessage<ManifestObjectFilter, Intention[]>(PlatformTopics.LookupIntentions, (request: TopicMessage<ManifestObjectFilter>) => {\n      const lookupFilter = request.body ?? {};\n\n      const illegalQualifierError = Qualifiers.validateQualifier(lookupFilter.qualifier, {exactQualifier: false});\n      if (illegalQualifierError) {\n        throw illegalQualifierError;\n      }\n\n      const finder$ = defer(() => of(this._intentionStore.find(lookupFilter)));\n      return finder$\n        .pipe(\n          expand(() => this._intentionStore.change$.pipe(take(1), mergeMap(() => finder$))),\n          distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),\n        );\n    }));\n  }\n\n  private installIsApplicationQualifiedRequestHandler(): void {\n    this._subscriptions.add(Beans.get(MessageClient).onMessage<ApplicationQualifiedForCapabilityRequest, boolean>(PlatformTopics.IsApplicationQualifiedForCapability, (request: TopicMessage<ApplicationQualifiedForCapabilityRequest>) => {\n      return merge(this._intentionStore.change$, this._capabilityStore.change$)\n        .pipe(\n          startWith<void>(undefined),\n          map(() => {\n            const application = Beans.get(ApplicationRegistry).getApplication(request.body!.appSymbolicName);\n            const capability = this._capabilityStore.findById(request.body!.capabilityId);\n            return this.isApplicationQualifiedForCapability(application.symbolicName, capability);\n          }),\n          distinctUntilChanged(),\n        );\n    }));\n  }\n\n  private installVersionLookupHandler(): void {\n    this._subscriptions.add(Beans.get(MessageClient).onMessage<void, string>(PlatformTopics.platformVersion(':appSymbolicName'), message => {\n      const appSymbolicName = message.params!.get('appSymbolicName')!;\n      const clientRegister$ = Beans.get(ClientRegistry).register$.pipe(filter(client => client.application.symbolicName === appSymbolicName));\n      const platformVersion$ = defer(() => {\n        const clients = Beans.get(ClientRegistry).getByApplication(appSymbolicName);\n        return clients.length ? of(clients[0]!.version) : EMPTY;\n      });\n      return platformVersion$\n        .pipe(\n          concatWith(clientRegister$.pipe(mergeMap(() => platformVersion$))),\n          take(1),\n        );\n    }));\n  }\n\n  public preDestroy(): void {\n    this._subscriptions.forEach(subscription => subscription.unsubscribe());\n  }\n}\n\n/**\n * Checks if the 'Intention Registration API' is enabled for the given app. If not, an error is thrown.\n */\nfunction assertIntentionRegisterApiEnabled(appSymbolicName: string): void {\n  if (Beans.get(ApplicationRegistry).isIntentionRegisterApiDisabled(appSymbolicName)) {\n    throw Error(`[IntentionRegisterError] The 'Intention Registration API' is disabled for the application '${appSymbolicName}'. Contact the platform administrator to enable this API.`);\n  }\n}\n\n/**\n * Asserts given parameter definitions to be valid.\n */\nfunction assertCapabilityParamDefinitions(params: Partial<ParamDefinition>[] | undefined): void {\n  if (!params?.length) {\n    return;\n  }\n\n  const validSubstitutes = params.filter(param => !param.deprecated).map(param => param.name);\n\n  params.forEach(param => {\n    if (param.required === undefined) {\n      throw Error(`[CapabilityParamError] Parameter '${param.name}' must be explicitly defined as required or optional.`);\n    }\n\n    if (param.deprecated !== undefined) {\n      // Ensure deprecated param to be optional\n      if (param.required) {\n        throw Error(`[CapabilityParamError] Deprecated parameters must be optional, not required. Alternatively, deprecated parameters can define a mapping to a required parameter via the 'useInstead' property. [param='${param.name}']`);\n      }\n\n      // Ensure existing substitute\n      if (typeof param.deprecated === 'object' && param.deprecated.useInstead && !validSubstitutes.includes(param.deprecated.useInstead)) {\n        throw Error(`[CapabilityParamError] The deprecated parameter '${param.name}' defines an invalid substitute '${param.deprecated.useInstead}'. Valid substitutes are: [${validSubstitutes}]`);\n      }\n    }\n    return param;\n  });\n}\n\n/**\n * Intercepts capability before its registration.\n */\nasync function interceptCapability(capability: Capability): Promise<Capability | null> {\n  const interceptors = Beans.all(CapabilityInterceptor);\n  const appSymbolicName = capability.metadata!.appSymbolicName;\n  const manifest = new class implements CapabilityInterceptor.Manifest {\n    public addCapability<T extends Capability>(capability: T): Promise<string | null> {\n      return Beans.get(ManifestRegistry).registerCapability(capability, appSymbolicName);\n    }\n\n    public async addIntention(intention: Intention): Promise<string> {\n      return Beans.get(ManifestRegistry).registerIntention(intention, appSymbolicName);\n    }\n  }();\n\n  let interceptedCapability: Capability | null = capability;\n  for (const interceptor of interceptors) {\n    interceptedCapability = await interceptor.intercept(interceptedCapability, manifest);\n    if (interceptedCapability === null) {\n      break; // rejected by the interceptor\n    }\n  }\n  return interceptedCapability;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {BehaviorSubject, Subscription} from 'rxjs';\nimport {distinctUntilChanged, map} from 'rxjs/operators';\nimport {MessageClient} from '../../client/messaging/message-client';\nimport {MessageHeaders} from '../../messaging.model';\nimport {runSafe} from '../../safe-runner';\nimport {PlatformTopics} from '../../ɵmessaging.model';\nimport {ClientRegistry} from '../client-registry/client.registry';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {Client} from '../client-registry/client';\n\n/**\n * Tracks the focus across microfrontends and answers {@link PlatformTopics.IsFocusWithin} and {@link PlatformTopics.HasFocus} requests.\n *\n * @see FocusInEventDispatcher\n * @see FocusMonitor\n * @internal\n */\nexport class FocusTracker implements PreDestroy {\n\n  private _focusOwner$ = new BehaviorSubject<Client | undefined>(undefined);\n  private _subscriptions = new Set<Subscription>();\n\n  constructor() {\n    this._subscriptions.add(this.monitorFocusInEvents());\n    this._subscriptions.add(this.replyToIsFocusWithinRequests());\n    this._subscriptions.add(this.replyToHasFocusRequests());\n  }\n\n  /**\n   * Monitors when a client gains the focus.\n   */\n  private monitorFocusInEvents(): Subscription {\n    return Beans.get(MessageClient).observe$<void>(PlatformTopics.FocusIn)\n      .pipe(\n        map(event => event.headers.get(MessageHeaders.ClientId) as string),\n        distinctUntilChanged(),\n      )\n      .subscribe(clientId => runSafe(() => {\n        this._focusOwner$.next(Beans.get(ClientRegistry).getByClientId(clientId) ?? undefined);\n      }));\n  }\n\n  /**\n   * Replies to 'focus-within' requests.\n   */\n  private replyToIsFocusWithinRequests(): Subscription {\n    return Beans.get(MessageClient).onMessage<void, boolean>(PlatformTopics.IsFocusWithin, request => {\n      const clientId = request.headers.get(MessageHeaders.ClientId) as string;\n      return this._focusOwner$\n        .pipe(\n          map(focusOwner => this.isFocusWithin(clientId, focusOwner)),\n          distinctUntilChanged(),\n        );\n    });\n  }\n\n  /**\n   * Replies to 'focus' requests.\n   */\n  private replyToHasFocusRequests(): Subscription {\n    return Beans.get(MessageClient).onMessage<void, boolean>(PlatformTopics.HasFocus, request => {\n      const clientId = request.headers.get(MessageHeaders.ClientId);\n      return this._focusOwner$\n        .pipe(\n          map(focusOwner => focusOwner?.id === clientId),\n          distinctUntilChanged(),\n        );\n    });\n  }\n\n  /**\n   * Tests whether the given client has received focus or contains embedded web content that has received focus.\n   */\n  private isFocusWithin(clientId: string, focusOwner: Client | undefined): boolean {\n    for (let client = focusOwner; client !== undefined; client = this.getParentClient(client)) {\n      if (client.id === clientId) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private getParentClient(client: Client): Client | undefined {\n    if (client.window.parent === client.window) {\n      return undefined; // window has no parent as it is the top-level window\n    }\n    return Beans.get(ClientRegistry).getByWindow(client.window.parent);\n  }\n\n  public preDestroy(): void {\n    this._subscriptions.forEach(subscription => subscription.unsubscribe());\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {MicrofrontendPlatformConfig} from './microfrontend-platform-config';\nimport {HttpClient} from './http-client';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {firstValueFrom, from, identity, Observable, throwError, timeout} from 'rxjs';\nimport {Manifest} from '../platform.model';\nimport {ApplicationConfig} from './application-config';\n\n/**\n * Fetches the manifest of an application.\n *\n * @internal\n */\nexport class ManifestFetcher {\n\n  /**\n   * Fetches the manifest for given application.\n   *\n   * @return Promise that resolves to the manifest after successful retrieval, or that rejects if the manifest could not be fetched\n   *         or the maximum retrieval time has elapsed.\n   *         See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful.\n   */\n  public async fetch(appConfig: ApplicationConfig): Promise<Manifest> {\n    if (!appConfig.symbolicName) {\n      throw Error('[ManifestFetchError] Invalid application config. Missing required property \\'symbolicName\\'.');\n    }\n    if (!appConfig.manifestUrl) {\n      throw Error('[ManifestFetchError] Invalid application config. Missing required property \\'manifestUrl\\'.');\n    }\n\n    const fetchManifest$ = from(Beans.get(HttpClient).fetch(appConfig.manifestUrl));\n    const manifestFetchTimeout = appConfig.manifestLoadTimeout ?? Beans.get(MicrofrontendPlatformConfig).manifestLoadTimeout;\n    const onManifestFetchTimeout = (): Observable<never> => throwError(() => Error(`[ManifestFetchError] Failed to fetch manifest for application '${appConfig.symbolicName}'. Timeout of ${manifestFetchTimeout}ms elapsed.`));\n    const manifestFetchResponse = await firstValueFrom(fetchManifest$.pipe(manifestFetchTimeout ? timeout({first: manifestFetchTimeout, with: onManifestFetchTimeout}) : identity));\n\n    if (!manifestFetchResponse.ok) {\n      throw Error(`[ManifestFetchError] Failed to fetch manifest for application '${appConfig.symbolicName}'. Maybe the application is currently unavailable. [httpStatusCode=${manifestFetchResponse.status}, httpStatusText=${manifestFetchResponse.statusText}]`);\n    }\n\n    return await manifestFetchResponse.json() as Manifest;\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Client} from '../client-registry/client';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {ClientRegistry} from '../client-registry/client.registry';\nimport {takeUntil} from 'rxjs/operators';\nimport {runSafe} from '../../safe-runner';\nimport {Observable, Subject} from 'rxjs';\nimport {Arrays, Maps} from '@scion/toolkit/util';\n\n/**\n * Central point for managing message subscriptions.\n *\n * @internal\n */\nexport class MessageSubscriptionRegistry<T extends MessageSubscription = MessageSubscription> implements PreDestroy {\n\n  private readonly _destroy$ = new Subject<void>();\n  private readonly _subscriptions = new Map<string, T>();\n  private readonly _subscriptionsByApp = new Map<string, Set<T>>();\n  private readonly _subscriptionsByClient = new Map<string, Set<T>>();\n\n  private readonly _register$ = new Subject<T>();\n  private readonly _unregister$ = new Subject<T[]>();\n\n  constructor() {\n    Beans.get(ClientRegistry).unregister$\n      .pipe(takeUntil(this._destroy$))\n      .subscribe((client: Client) => runSafe(() => {\n        this.unregister({clientId: client.id});\n      }));\n  }\n\n  /**\n   * Registers given subscription.\n   */\n  public register(subscription: T): void {\n    this._subscriptions.set(subscription.subscriberId, subscription);\n    Maps.addSetValue(this._subscriptionsByApp, subscription.client.application.symbolicName, subscription);\n    Maps.addSetValue(this._subscriptionsByClient, subscription.client.id, subscription);\n    this.onRegister?.(subscription);\n    this._register$.next(subscription);\n  }\n\n  /**\n   * Unregisters matching subscriptions.\n   *\n   * @param filter - Control which subscriptions to remove by specifying filter criteria which are \"AND\"ed together.\n   */\n  public unregister(filter: {subscriberId?: string; clientId?: string}): void {\n    const subscriptions = this.subscriptions(filter);\n    subscriptions.forEach(subscription => {\n      this._subscriptions.delete(subscription.subscriberId);\n      Maps.removeSetValue(this._subscriptionsByApp, subscription.client.application.symbolicName, subscription);\n      Maps.removeSetValue(this._subscriptionsByClient, subscription.client.id, subscription);\n      this.onUnregister?.(subscription);\n      subscription.notifyUnsubscribe();\n    });\n    this._unregister$.next(subscriptions);\n  }\n\n  /**\n   * Returns subscriptions matching the passed filter.\n   *\n   * @param filter - Control which subscriptions to return by specifying filter criteria which are \"AND\"ed together.\n   *                 If not specified, returns all subscriptions.\n   */\n  public subscriptions(filter?: {subscriberId?: string; clientId?: string; appSymbolicName?: string}): T[] {\n    const filterById = filter?.subscriberId;\n    const filterByClient = filter?.clientId;\n    const filterByApp = filter?.appSymbolicName;\n\n    return Arrays.intersect(\n      filterById ? this.subscriptionById(filterById) : undefined,\n      filterByClient ? this.subscriptionsByClient(filterByClient) : undefined,\n      filterByApp ? this.subscriptionsByApp(filterByApp) : undefined,\n      (filterById || filterByApp || filterByClient) ? undefined : Array.from(this._subscriptions.values()),\n    );\n  }\n\n  /**\n   * Returns the subscription of given subscriber.\n   */\n  private subscriptionById(subscriberId: string): [T] | [] {\n    const subscription = this._subscriptions.get(subscriberId);\n    return subscription ? [subscription] : [];\n  }\n\n  /**\n   * Returns the subscriptions of given client.\n   */\n  private subscriptionsByClient(clientId: string): T[] {\n    const subscriptions = this._subscriptionsByClient.get(clientId);\n    return subscriptions ? Array.from(subscriptions) : [];\n  }\n\n  /**\n   * Returns the subscriptions of given application.\n   */\n  private subscriptionsByApp(appSymbolicName: string): T[] {\n    const subscriptions = this._subscriptionsByApp.get(appSymbolicName);\n    return subscriptions ? Array.from(subscriptions) : [];\n  }\n\n  /**\n   * Emits when registered a subscription via {@link MessageSubscriptionRegistry#register}.\n   */\n  public get register$(): Observable<T> {\n    return this._register$;\n  }\n\n  /**\n   * Emits when unregistered a subscription via {@link MessageSubscriptionRegistry#unregister}.\n   */\n  public get unregister$(): Observable<T[]> {\n    return this._unregister$;\n  }\n\n  /**\n   * Method invoked when registered a subscription, but before the change was emitted.\n   */\n  protected onRegister?(subscription: T): void;\n\n  /**\n   * Method invoked when unregistered a subscription, but before the change was emitted.\n   */\n  protected onUnregister?(subscription: T): void;\n\n  public preDestroy(): void {\n    this._destroy$.next();\n  }\n}\n\n/**\n * Represents a subscription for a given subscriber.\n *\n * @internal\n */\nexport class MessageSubscription {\n\n  /**\n   * Notify when the subscriber unsubscribes.\n   */\n  public notifyUnsubscribe!: () => void;\n  /**\n   * Promise that resolves when the subscriber unsubscribes.\n   */\n  public readonly whenUnsubscribe = new Promise<void>(resolve => this.notifyUnsubscribe = resolve);\n\n  constructor(public readonly subscriberId: string, public readonly client: Client) {\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {TopicMatcher} from '../../topic-matcher.util';\nimport {Client} from '../client-registry/client';\nimport {MessageSubscription, MessageSubscriptionRegistry} from './message-subscription.registry';\nimport {filter, Observable, Subject, throwError} from 'rxjs';\nimport {takeUntil} from 'rxjs/operators';\nimport {Arrays, Maps} from '@scion/toolkit/util';\nimport {Topics} from '../../topics.util';\nimport {filterArray} from '@scion/toolkit/operators';\n\nconst ASTERISK = ':ɵANY';\n\n/**\n * Central point for managing topic subscriptions.\n *\n * @internal\n */\nexport class TopicSubscriptionRegistry extends MessageSubscriptionRegistry<TopicSubscription> {\n\n  private readonly _subscriptionsByTopic = new Map<string, Set<TopicSubscription>>();\n\n  protected override onRegister(subscription: TopicSubscription): void {\n    const topic = Topics.replaceWildcardSegments(subscription.topic, ASTERISK);\n    Maps.addSetValue(this._subscriptionsByTopic, topic, subscription);\n  }\n\n  protected override onUnregister(subscription: TopicSubscription): void {\n    const topic = Topics.replaceWildcardSegments(subscription.topic, ASTERISK);\n    Maps.removeSetValue(this._subscriptionsByTopic, topic, subscription);\n  }\n\n  public override subscriptions(filter?: {subscriberId?: string; clientId?: string; appSymbolicName?: string; topic?: string}): TopicSubscription[] {\n    // Note that we need to identify matching subscriptions very quickly, otherwise the broker's throughput would decrease massively.\n    // Therefore, we must never iterate over all subscriptions, but resolve subscriptions by index.\n    const filterByTopic = filter?.topic;\n    const filterById = filter?.subscriberId;\n    const filterByClient = filter?.clientId;\n    const filterByApp = filter?.appSymbolicName;\n\n    return Arrays.intersect(\n      filterByTopic ? this.subscriptionsByTopic(filterByTopic) : undefined,\n      (filterById || filterByApp || filterByClient) ? super.subscriptions(filter) : undefined,\n      (filterById || filterByApp || filterByClient || filterByTopic) ? undefined : super.subscriptions(),\n    );\n  }\n\n  /**\n   * Returns the subscription of given topic.\n   */\n  private subscriptionsByTopic(topic: string): TopicSubscription[] {\n    const subscriptions = new Array<TopicSubscription>();\n    Topics.computeWildcardSegmentPermutations(topic, ASTERISK).forEach(permutation => {\n      subscriptions.push(...this._subscriptionsByTopic.get(permutation) ?? []);\n    });\n    return subscriptions;\n  }\n\n  /**\n   * Allows observing the number of subscriptions on a topic. It is not allowed to use wildcards in the topic to observe.\n   *\n   * @param  topic - Specifies the topic to observe.\n   * @return An Observable that, when subscribed, emits the current number of subscribers on it. It never completes and\n   *         emits continuously when the number of subscribers changes.\n   */\n  public subscriptionCount$(topic: string): Observable<number> {\n    const illegalTopicError = Topics.validateTopic(topic, {exactTopic: true});\n    if (illegalTopicError) {\n      return throwError(() => illegalTopicError);\n    }\n\n    return new Observable(observer => {\n      const unsubscribe$ = new Subject<void>();\n\n      // Emit current subscription count.\n      let count = this.subscriptions({topic}).length;\n      observer.next(count);\n\n      // Increment count when matching subscriptions are added.\n      this.register$\n        .pipe(\n          filter(subscription => subscription.matches(topic)),\n          takeUntil(unsubscribe$),\n        )\n        .subscribe(() => {\n          count++;\n          observer.next(count);\n        });\n\n      // Decrement count when matching subscriptions are removed.\n      this.unregister$\n        .pipe(\n          filterArray(subscription => subscription.matches(topic)),\n          filter(subscriptions => subscriptions.length > 0),\n          takeUntil(unsubscribe$),\n        )\n        .subscribe(subscriptions => {\n          count -= subscriptions.length;\n          observer.next(count);\n        });\n\n      return (): void => unsubscribe$.next();\n    });\n  }\n}\n\n/**\n * Represents a subscription on a topic. The topic may contain wildcard segments.\n *\n * @internal\n */\nexport class TopicSubscription extends MessageSubscription {\n\n  constructor(public readonly topic: string, subscriberId: string, client: Client) {\n    super(subscriberId, client);\n  }\n\n  /**\n   * Tests whether the given topic matches this subscription.\n   */\n  public matches(topic: string): boolean {\n    return topic === this.topic || new TopicMatcher(this.topic).match(topic).matches;\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {IntentMessage, TopicMessage} from '../../messaging.model';\n\n/**\n * Allows intercepting messages before their publication.\n *\n * An interceptor can reject or modify messages. Multiple interceptors can be registered, forming a chain in which each interceptor\n * is called one by one in registration order.\n *\n * For each message, the platform invokes the intercept method of the first registered interceptor, passing the message and the next\n * handler as arguments. By calling the next handler in the intercept method, message dispatching is continued. If there is no more\n * interceptor in the chain, the message is transported to the receivers, if any. But, if throwing an error in the intercept method,\n * message dispatching is aborted, and the error transported back to the sender.\n *\n * #### Registering Interceptors\n * You register interceptors with the bean manager when the host application starts. Interceptors can be registered only in the host\n * application. They are invoked in registration order.\n *\n * ```ts\n * Beans.register(MessageInterceptor, {useClass: MessageLoggerInterceptor, multi: true});\n * ```\n *\n * #### Filtering Messages for Interception\n * The platform passes all messages to the interceptors, including platform messages vital for its operation.\n * You can use the TopicMatcher to filter messages, allowing you to test whether a topic matches a pattern. The pattern must be a topic,\n * not a regular expression; thus, it must consist of one or more segments, each separated by a forward slash. The pattern can contain\n * wildcard segments. Wildcard segments start with a colon (:), acting act as a placeholder for any segment value.\n *\n * ```ts\n * class ProductValidatorInterceptor implements MessageInterceptor {\n *\n *   private topicMatcher = new TopicMatcher('product/:id');\n *\n *   public intercept(message: TopicMessage, next: Handler<TopicMessage>): Promise<void> {\n *     // Pass messages sent to other topics.\n *     if (!this.topicMatcher.match(message.topic).matches) {\n *       return next.handle(message);\n *     }\n *\n *     // Validate the payload of the message.\n *     if (isValid(message.body)) {\n *       return next.handle(message);\n *     }\n *\n *     throw Error('Message failed schema validation');\n *   }\n * }\n * ```\n *\n * @category Messaging\n */\nexport abstract class MessageInterceptor implements Interceptor<TopicMessage, Handler<TopicMessage>> {\n\n  /**\n   * Intercepts a message before being published to its topic.\n   *\n   * Decide if to continue publishing by passing the message to the next handler, or to reject publishing by throwing an error,\n   * or to swallow the message by not calling the next handler at all. If rejecting publishing, the error is transported to the\n   * message publisher.\n   *\n   * Important: When passing the message to the next handler, either return its Promise or await it.\n   * Otherwise, errors of subsequent interceptors would not be reported to the sender.\n   *\n   * @param  message - the message to be published to its topic\n   * @param  next - the next handler in the chain; invoke its {@link Handler.handle} method to continue publishing.\n   * @throws throw an error to reject publishing; the error is transported to the message publisher.\n   */\n  public abstract intercept(message: TopicMessage, next: Handler<TopicMessage>): Promise<void>;\n}\n\n/**\n * Allows intercepting intents before their publication.\n *\n * An interceptor can reject or modify intents. Multiple interceptors can be registered, forming a chain in which each interceptor\n * is called one by one in registration order.\n *\n * For each intent, the platform invokes the intercept method of the first registered interceptor, passing the intent and the next\n * handler as arguments. By calling the next handler in the intercept method, intent dispatching is continued. If there is no more\n * interceptor in the chain, the intent is transported to the receivers, if any. But, if throwing an error in the intercept method,\n * intent dispatching is aborted, and the error transported back to the sender.\n *\n * #### Registering Interceptors\n * You register interceptors with the bean manager when the host application starts. Interceptors can be registered only in the host\n * application. They are invoked in registration order.\n *\n * ```ts\n * Beans.register(IntentInterceptor, {useClass: IntentLoggerInterceptor, multi: true});\n * ```\n *\n * #### Filtering intents for Interception\n * The platform passes all intents to the interceptors. The interceptor must filter intents of interest.\n *\n * @category Messaging\n * @category Intention API\n */\nexport abstract class IntentInterceptor implements Interceptor<IntentMessage, Handler<IntentMessage>> {\n\n  /**\n   * Intercepts an intent before being published.\n   *\n   * Decide if to continue publishing by passing the intent to the next handler, or to reject publishing by throwing an error,\n   * or to swallow the intent by not calling the next handler at all. If rejecting publishing, the error is transported to\n   * the intent issuer.\n   *\n   * Important: When passing the message to the next handler, either return its Promise or await it.\n   * Otherwise, errors of subsequent interceptors would not be reported to the sender.\n   *\n   * @param  intent - the intent to be published\n   * @param  next - the next handler in the chain; invoke its {@link Handler.handle} method to continue publishing.\n   * @throws throw an error to reject publishing; the error is transported to the intent issuer.\n   */\n  public abstract intercept(intent: IntentMessage, next: Handler<IntentMessage>): Promise<void>;\n}\n\n/**\n * Chain to intercept messages before they are published. The chain is implemented according to the 'Chain of Responsibility' design pattern.\n *\n * A message travels along the chain of interceptors. If all interceptors let the message pass, it is published.\n *\n * @internal\n */\nexport interface PublishInterceptorChain<T> {\n\n  /**\n   * Passes a message along the chain of interceptors, if any, and publishes it.\n   *\n   * Each interceptor in the chain can reject publishing by throwing an error, ignore the message by not calling the next handler,\n   * or continue the chain by calling the next handler.\n   *\n   * @throws throws an error if an interceptor rejected publishing.\n   */\n  interceptAndPublish(message: T): Promise<void>;\n}\n\n/**\n * Assembles the given interceptors to a chain of handlers which are called one after another. The publisher is added as terminal handler.\n *\n * @param interceptors - interceptors to be assembled to a chain\n * @param publisher - terminal handler to publish messages\n * @internal\n */\nexport function chainInterceptors<T>(interceptors: Interceptor<T, Handler<T>>[], publisher: (message: T) => Promise<void>): PublishInterceptorChain<T> {\n  const terminalHandler = new class extends Handler<T> {\n    public handle(message: T): Promise<void> {\n      return publisher(message);\n    }\n  }();\n\n  const handlerChain = interceptors.reduceRight((next, interceptor) => new class extends Handler<T> {\n    public handle(element: T): Promise<void> {\n      return interceptor.intercept(element, next);\n    }\n  }(), terminalHandler);\n\n  return new class implements PublishInterceptorChain<T> {\n    public interceptAndPublish(element: T): Promise<void> {\n      return handlerChain.handle(element);\n    }\n  }();\n}\n\n/**\n * Allows the interception of messages or intents before their publication.\n *\n * @see {@link MessageInterceptor}\n * @see {@link IntentInterceptor}\n * @category Messaging\n */\nexport interface Interceptor<T, H extends Handler<T>> {\n\n  intercept(message: T, next: H): Promise<void>;\n}\n\n/**\n * Represents a handler in the chain of interceptors.\n *\n * @category Messaging\n */\nexport abstract class Handler<T> {\n  /**\n   * Invoke to continue the chain with the given message.\n   */\n  public abstract handle(message: T): Promise<void>;\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n// See semantic versioning specification: https://semver.org/#semantic-versioning-specification-semver\nconst SEMVER_REGEX = /(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)(-(?<prerelease>.+))?/;\n\n/*\n * Allows working with semantic versions (semver).\n *\n * ### Why not using `semver` NPM package (as of 2022-04)\n * We no longer depend on the NPM package `semver` as not yet been published as an ECMAScript module (ESM).\n * It is recommended to avoid dependencies on CommonJS modules as bundlers and minifiers may not be able to\n * optimize the application code, resulting in larger bundle size.\n *\n * For example, the Angular compiler would generate the following warning when using `semver`:\n * `Warning: ... depends on 'semver'. CommonJS or AMD dependencies can cause optimization bailouts.`\n *\n * ---\n *\n * The following rules for comparing two semantic versions are copied directly from the semantic versioning specification,\n * which can be found here: https://semver.org/#semantic-versioning-specification-semver\n *\n * ```\n * Precedence refers to how versions are compared to each other when ordered.\n *\n * 1. Precedence MUST be calculated by separating the version into major, minor, patch and pre-release identifiers\n *    in that order (Build metadata does not figure into precedence).\n *\n * 2. Precedence is determined by the first difference when comparing each of these identifiers from left to right as follows:\n *    Major, minor, and patch versions are always compared numerically.\n *    Example: 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1.\n *\n * 3. When major, minor, and patch are equal, a pre-release version has lower precedence than a normal version:\n *    Example: 1.0.0-alpha < 1.0.0.\n *\n * 4. Precedence for two pre-release versions with the same major, minor, and patch version MUST be determined by comparing\n *    each dot separated identifier from left to right until a difference is found as follows:\n *\n *    1. Identifiers consisting of only digits are compared numerically.\n *    2. Identifiers with letters or hyphens are compared lexically in ASCII sort order.\n *    3. Numeric identifiers always have lower precedence than non-numeric identifiers.\n *    4. A larger set of pre-release fields has a higher precedence than a smaller set, if all of the preceding identifiers are equal.\n *\n *   Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0.\n * ```\n *\n * NOTE: Use static class instead of namespace to be tree shakable, i.e., to not be included in client app.\n *\n * @internal\n */\nexport class semver {\n\n  private constructor() {\n  }\n\n  /**\n   * Return the major version number.\n   */\n  public static major(version: string | undefined | null): number {\n    return parseVersion(version ?? '0.0.0').major;\n  }\n\n  /**\n   * Tests if `version1` is lower than `version2`.\n   *\n   * @return `true` if `version1` is lower than `version2`, or `false` otherwise.\n   *         The values `null` and `undefined` have lower precedence than a normal version.\n   * @throws throws if passed version is not a valid semantic version.\n   */\n  public static lt(version1: string | undefined | null, version2: string | undefined | null): boolean {\n    return compare(version1, version2) < 0;\n  }\n}\n\n/**\n * Compares given two versions.\n *\n * @return -1: if `v1` is lower than `v2`\n *          0: if both version are identical\n *          1: if `v1` is greater than `v2`\n */\nfunction compare(v1: string | undefined | null, v2: string | undefined | null): number {\n  if (!v1 && v2) {\n    return -1;\n  }\n  if (!v1 && !v2) {\n    return 0;\n  }\n  if (v1 && !v2) {\n    return 1;\n  }\n\n  const semVer1 = parseVersion(v1!);\n  const semVer2 = parseVersion(v2!);\n\n  // Compare major version\n  const majorCompare = Math.sign(semVer1.major - semVer2.major);\n  if (majorCompare !== 0) {\n    return majorCompare;\n  }\n\n  // Compare minor version\n  const minorCompare = Math.sign(semVer1.minor - semVer2.minor);\n  if (minorCompare !== 0) {\n    return minorCompare;\n  }\n\n  // Compare patch version\n  const patchCompare = Math.sign(semVer1.patch - semVer2.patch);\n  if (patchCompare !== 0) {\n    return patchCompare;\n  }\n\n  // Compare pre-release portion.\n  return comparePreRelease(semVer1, semVer2);\n}\n\n/**\n * Compares the prerelease portion of two versions.\n *\n * @return -1: if `version1` is lower than `version2`\n *          0: if both version are identical\n *          1: if `version1` is greater than `version2`\n */\nfunction comparePreRelease(v1: SemVer, v2: SemVer): number {\n  if (v1.preRelease && !v2.preRelease) {\n    return -1;\n  }\n  if (!v1.preRelease && !v2.preRelease) {\n    return 0;\n  }\n  if (!v1.preRelease && v2.preRelease) {\n    return 1;\n  }\n\n  for (let i = 0; i < Math.max(v1.preRelease!.length, v2.preRelease!.length); i++) {\n    const identifier1 = v1.preRelease![i];\n    const identifier2 = v2.preRelease![i];\n\n    if (identifier1 === undefined) {\n      return -1;\n    }\n    if (identifier2 === undefined) {\n      return 1;\n    }\n\n    if (typeof identifier1 === 'number' && typeof identifier2 === 'string') {\n      return -1;\n    }\n    if (typeof identifier1 === 'string' && typeof identifier2 === 'number') {\n      return 1;\n    }\n\n    if (identifier1 < identifier2) {\n      return -1;\n    }\n    if (identifier1 > identifier2) {\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/**\n * Parses given version into a {@link SemVer} instance.\n *\n * @throws throws if passed version is not a valid semantic version.\n */\nfunction parseVersion(version: string): SemVer {\n  const match = SEMVER_REGEX.exec(version);\n  if (!match) {\n    throw Error(`[SemVerError] Version '${version}' is not a valid semantic version (semver).`);\n  }\n\n  return {\n    major: +match.groups!['major']!,\n    minor: +match.groups!['minor']!,\n    patch: +match.groups!['patch']!,\n    preRelease: match.groups!['prerelease']?.split('.').map(identifier => {\n      const numericIdentifier = +identifier;\n      return Number.isNaN(numericIdentifier) ? identifier : numericIdentifier;\n    }),\n  };\n}\n\n/**\n * Represents a parsed semantic version.\n */\ninterface SemVer {\n  major: number;\n  minor: number;\n  patch: number;\n  preRelease?: Array<string | number>;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {ɵApplication} from '../../ɵplatform.model';\n\n/**\n * Represents a client which is connected to the message broker.\n *\n * @internal\n */\nexport interface Client {\n\n  /**\n   * Unique identity of this client.\n   */\n  readonly id: string;\n\n  /**\n   * The window this client is loaded into.\n   */\n  readonly window: Window;\n\n  /**\n   * The origin of this client; is one of {@link ɵApplication.allowedMessageOrigins}.\n   */\n  readonly origin: string;\n\n  /**\n   * The application this client belongs to.\n   */\n  readonly application: ɵApplication;\n\n  /**\n   * The version of the @scion/microfrontend-platform installed on the client.\n   */\n  readonly version: string;\n\n  /**\n   * Indicates whether this client is stale and no more messages can be transported to this client.\n   */\n  readonly stale: boolean;\n\n  /**\n   * Releases resources allocated by this client.\n   */\n  dispose(): void;\n}\n\n/**\n * Specifies the interval (in milliseconds) at which the host pings connected clients.\n *\n * By default, if not set, a ping interval of 60s is used.\n *\n * NOTE: Use pure inline comment to be tree shakable, i.e., to not be included in client app.\n *\n * @internal\n */\nexport const CLIENT_PING_INTERVAL = /* @__PURE__ */Symbol('CLIENT_PING_INTERVAL');\n\n/**\n * Specifies the ping timeout (in milliseconds) for unregistering a client.\n *\n * By default, if not set, clients are unregistered if not answering the ping within 10 seconds.\n *\n * NOTE: Use pure inline comment to be tree shakable, i.e., to not be included in client app.\n *\n * @internal\n */\nexport const CLIENT_PING_TIMEOUT = /* @__PURE__ */Symbol('CLIENT_PING_TIMEOUT');\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {interval, retry, Subscription, switchMap, timeout} from 'rxjs';\nimport {APP_IDENTITY} from '../../platform.model';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {MessageClient} from '../../client/messaging/message-client';\nimport {PlatformTopics} from '../../ɵmessaging.model';\nimport {Logger, LoggingContext} from '../../logger';\nimport {ClientRegistry} from './client.registry';\nimport {Client, CLIENT_PING_INTERVAL, CLIENT_PING_TIMEOUT} from './client';\nimport {ɵApplication} from '../../ɵplatform.model';\n\n/**\n * @internal\n */\nexport class ɵClient implements Client {\n\n  public readonly version: string;\n  private _livenessDetector: Subscription | undefined;\n\n  constructor(public readonly id: string,\n              public readonly window: Window,\n              public readonly origin: string,\n              public readonly application: ɵApplication,\n              version?: string) {\n    this.version = version ?? '0.0.0';\n    this.installLivenessDetector();\n  }\n\n  /**\n   * Starts performing liveness tests to detect when this client is no longer connected to the host.\n   *\n   * Liveness is detected by sending ping requests at regular intervals.\n   *\n   * A client may fail to disconnect from the broker for a number of reasons:\n   * - The client was disposed without notice, i.e., without receiving the browser's \"unload\" event.\n   * - The browser discarded the \"DISCONNECT\" message because the client window became stale.\n   *   Typically, the browser discards messages for windows that are already closed or if another page\n   *   has been loaded into the window, both indicating a high load on the client during unloading.\n   */\n  private installLivenessDetector(): void {\n    // The client of the host app needs not to be checked for liveness as it is part of the host.\n    if (this.application.symbolicName === Beans.get(APP_IDENTITY)) {\n      return;\n    }\n\n    // Observable to perform the ping. If the client does not respond, we ping the client again to account for the rare situation where\n    // the computer goes into standby immediately after sending the ping. Upon resumption, the timeout would expire immediately without\n    // the client being able to send the response.\n    const performPing$ = Beans.get(MessageClient).request$(PlatformTopics.ping(this.id))\n      .pipe(timeout(Beans.get<number>(CLIENT_PING_TIMEOUT)), retry(1));\n\n    this._livenessDetector = interval(Beans.get<number>(CLIENT_PING_INTERVAL))\n      .pipe(switchMap(() => performPing$))\n      .subscribe({\n        error: () => {\n          this.logStaleClientWarning();\n          Beans.get(ClientRegistry).unregisterClient(this);\n        },\n      });\n  }\n\n  public get stale(): boolean {\n    return this.window.closed;\n  }\n\n  public dispose(): void {\n    this._livenessDetector?.unsubscribe();\n  }\n\n  private logStaleClientWarning(): void {\n    Beans.get(Logger).warn(\n      `[StaleClient] Stale client registration of application '${this.application.symbolicName}' detected.\n       Removing stale registration. Most likely, the client could not disconnect from the broker, for example, because the client was\n       disposed without notice, i.e., without receiving the browser's \"unload\" event, or because the browser discarded the 'DISCONNECT'\n       message. Typically, the browser discards messages for windows that are already closed or if another page has been loaded into the\n       window, both indicating a high load on the client during unloading.`.replace(/\\s+/g, ' '),\n      new LoggingContext(this.application.symbolicName, this.version),\n    );\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Client} from '../client-registry/client';\nimport {MessageSubscription, MessageSubscriptionRegistry} from './message-subscription.registry';\nimport {Intent} from '../../messaging.model';\nimport {IntentSelector} from '../../client/messaging/intent-client';\nimport {QualifierMatcher} from '../../qualifier-matcher';\n\n/**\n * Central point for managing intent subscriptions.\n *\n * @internal\n */\nexport class IntentSubscriptionRegistry extends MessageSubscriptionRegistry<IntentSubscription> {\n\n  public override subscriptions(filter?: {subscriberId?: string; clientId?: string; appSymbolicName?: string; intent?: Intent}): IntentSubscription[] {\n    return super.subscriptions(filter).filter(subscription => filter?.intent ? subscription.matches(filter.intent) : true);\n  }\n}\n\n/**\n * Represents a subscription for intents matching the passed selector.\n *\n * @internal\n */\nexport class IntentSubscription extends MessageSubscription {\n\n  constructor(public readonly selector: IntentSelector, subscriberId: string, client: Client) {\n    super(subscriberId, client);\n  }\n\n  /**\n   * Tests whether the given intent matches this subscription.\n   *\n   * Note that only a type and qualifier check is performed, but not whether the application is eligible\n   * to receive matching intents, i.e., provides a fulfilling capability.\n   */\n  public matches(intent: Intent): boolean {\n    if (this.selector.type && this.selector.type !== intent.type) {\n      return false;\n    }\n    if (this.selector.qualifier && !new QualifierMatcher(this.selector.qualifier).matches(intent.qualifier)) {\n      return false;\n    }\n    return true;\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Provides utilities for working with predicates.\n *\n * NOTE: Use static class instead of namespace to be tree shakable, i.e., to not be included in client app.\n *\n * @internal\n */\nexport class Predicates {\n\n  private constructor() {\n  }\n\n  /**\n   * Negates the given predicate.\n   */\n  public static not<T>(predicate: Predicate<T>): Predicate<T> {\n    return (value: T) => !predicate(value);\n  }\n\n  /**\n   * Represents a predicate that always evaluates to `true`.\n   */\n  public static alwaysTrue = (): true => true;\n}\n\n/**\n * Represents a predicate (boolean-valued function) of one argument.\n *\n * @internal\n */\nexport type Predicate<T> = (value: T) => boolean;\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {ParamDefinition} from './platform.model';\nimport {Dictionaries, Maps} from '@scion/toolkit/util';\n\n/**\n * Allows testing whether params match the param definitions.\n *\n * @category Intention API\n */\nexport class ParamMatcher {\n\n  private readonly _requiredParamDefs = new Array<ParamDefinition>();\n  private readonly _optionalParamDefs = new Array<ParamDefinition>();\n  private readonly _deprecatedParamDefs = new Array<ParamDefinition>();\n\n  constructor(definitions: ParamDefinition[] | undefined | null) {\n    definitions?.forEach(paramDef => {\n      if (paramDef.required ?? true) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n        this._requiredParamDefs.push(paramDef);\n      }\n      else {\n        this._optionalParamDefs.push(paramDef);\n      }\n\n      if (paramDef.deprecated) {\n        this._deprecatedParamDefs.push(paramDef);\n      }\n    });\n  }\n\n  /**\n   * Tests if the given params match the param definitions.\n   */\n  public match(params: Map<string, unknown> | {[name: string]: unknown} | null | undefined): ParamMatcherResult {\n    const paramsCopy = Maps.coerce(Dictionaries.coerce(params));\n\n    const matcherResult: ParamMatcherResult = {\n      matches: true,\n      params: paramsCopy,\n      missingParams: [],\n      unexpectedParams: [],\n      deprecatedParams: [],\n    };\n\n    // Map deprecated params to their substitute, if any.\n    this._deprecatedParamDefs\n      .filter(paramDef => paramsCopy.has(paramDef.name))\n      .forEach(paramDef => {\n        matcherResult.deprecatedParams.push(paramDef);\n\n        // Try mapping the deprecated param to its substitute.\n        const deprecation = paramDef.deprecated;\n        if (typeof deprecation === 'object' && deprecation.useInstead) {\n          paramsCopy.set(deprecation.useInstead, paramsCopy.get(paramDef.name));\n          paramsCopy.delete(paramDef.name);\n        }\n      });\n\n    // Test if required params are passed.\n    this._requiredParamDefs\n      .filter(paramDef => !paramsCopy.has(paramDef.name) || paramsCopy.get(paramDef.name) === undefined)\n      .filter(paramDef => !this._deprecatedParamDefs.includes(paramDef))\n      .forEach(paramDef => {\n        matcherResult.matches = false;\n        matcherResult.missingParams.push(paramDef);\n      });\n\n    // Apply default values for optional params. Ignore deprecated params defining a `useInstead` since already mapped.\n    this._optionalParamDefs\n      .filter(paramDef => paramDef.default !== undefined)\n      .filter(paramDef => !(typeof paramDef.deprecated === 'object' && paramDef.deprecated.useInstead))\n      .forEach(paramDef => {\n        if (paramsCopy.get(paramDef.name) === undefined) {\n          paramsCopy.set(paramDef.name, paramDef.default);\n        }\n      });\n\n    // Test if no additional params are passed.\n    Array.from(paramsCopy.keys())\n      .filter(param => !this._requiredParamDefs.some(paramDef => paramDef.name === param) && !this._optionalParamDefs.some(paramDef => paramDef.name === param))\n      .forEach(param => {\n        matcherResult.matches = false;\n        matcherResult.unexpectedParams.push(param);\n      });\n\n    if (!matcherResult.matches) {\n      matcherResult.params = undefined;\n    }\n\n    return matcherResult;\n  }\n}\n\n/**\n * Represents the result of a params matcher test.\n */\nexport interface ParamMatcherResult {\n  /**\n   * Indicates whether the params match the param definitions.\n   */\n  matches: boolean;\n  /**\n   * Params as passed to the matcher, but with deprecated params mapped to their substitute,\n   * or `undefined` if the match is not successful.\n   */\n  params: Map<string, unknown> | undefined;\n  /**\n   * Required params that are missing.\n   */\n  missingParams: ParamDefinition[];\n  /**\n   * Params that are not expected.\n   */\n  unexpectedParams: string[];\n  /**\n   * Params that are deprecated.\n   */\n  deprecatedParams: ParamDefinition[];\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {Intent, IntentMessage, MessageHeaders} from '../../messaging.model';\nimport {ParamMatcher, ParamMatcherResult} from '../../param-matcher';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {Logger, LoggingContext} from '../../logger';\nimport {ParamDefinition} from '../../platform.model';\n\n/**\n * Provides utilities for working with intent params.\n *\n * NOTE: Use static class instead of namespace to be tree shakable, i.e., to not be included in client app.\n *\n * @internal\n */\nexport class IntentParams {\n\n  private constructor() {\n  }\n\n  /**\n   * Validates params of given intent.\n   *\n   * @throws if the message contains invalid params.\n   */\n  public static validateParams(intentMessage: IntentMessage): void {\n    const {intent, capability} = intentMessage;\n    const sender = intentMessage.headers.get(MessageHeaders.AppSymbolicName) as string;\n    intent.params = new Map(intent.params);\n\n    // Remove params with `undefined` as value.\n    intent.params.forEach((value, key) => {\n      if (value === undefined) {\n        intent.params!.delete(key);\n      }\n    });\n\n    // Test params passed with the intent to match expected params as declared on the capability.\n    const paramMatcherResult = new ParamMatcher(capability.params).match(intent.params);\n    if (!paramMatcherResult.matches) {\n      const error = toParamValidationError(paramMatcherResult, intent);\n      throw Error(`[IntentParamValidationError] ${error}`);\n    }\n\n    // Warn about the usage of deprecated params.\n    if (paramMatcherResult.deprecatedParams.length) {\n      paramMatcherResult.deprecatedParams.forEach(deprecatedParam => {\n        const warning = toDeprecatedParamWarning(deprecatedParam, {appSymbolicName: sender});\n        Beans.get(Logger).warn(`[DEPRECATION][4EAC5956] ${warning}`, new LoggingContext(sender), intent);\n      });\n    }\n    // Use the matcher's parameters to have deprecated params mapped to their replacement and default values applied.\n    intent.params = paramMatcherResult.params;\n  }\n}\n\nfunction toParamValidationError(paramsMatcherResult: ParamMatcherResult, intent: Intent): string {\n  const intentStringified = JSON.stringify(intent, (key, value: unknown) => (key === 'params') ? undefined : value);\n  const missingParams = paramsMatcherResult.missingParams.map(param => param.name);\n  const unexpectedParams = paramsMatcherResult.unexpectedParams;\n  return `Params of intent do not match expected params of capability. The intent must have required params and not have additional params. [intent=${intentStringified}, missingParams=[${missingParams}], unexpectedParams=[${unexpectedParams}]].`;\n}\n\nfunction toDeprecatedParamWarning(param: ParamDefinition, metadata: {appSymbolicName: string}): string {\n  const deprecation = param.deprecated!;\n  const useInstead = typeof deprecation === 'object' ? deprecation.useInstead : undefined;\n  const message = typeof deprecation === 'object' ? deprecation.message : undefined;\n\n  return new Array<string>()\n    .concat(`Application '${metadata.appSymbolicName}' passes a deprecated parameter in the intent: '${param.name}'.`)\n    .concat(useInstead ? `Pass parameter '${useInstead}' instead.` : [])\n    .concat(message ?? [])\n    .join(' ');\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {EMPTY, from, fromEvent, merge, MonoTypeOperatorFunction, Observable, of, Subject} from 'rxjs';\nimport {catchError, filter, mergeMap, share, takeUntil} from 'rxjs/operators';\nimport {IntentMessage, Message, MessageHeaders, ResponseStatusCodes, TopicMessage} from '../../messaging.model';\nimport {ConnackMessage, IntentSubscribeCommand, MessageDeliveryStatus, MessageEnvelope, MessagingChannel, MessagingTransport, PlatformTopics, TopicSubscribeCommand, UnsubscribeCommand} from '../../ɵmessaging.model';\nimport {ApplicationRegistry} from '../application-registry';\nimport {ManifestRegistry} from '../manifest-registry/manifest-registry';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {Logger, LoggingContext} from '../../logger';\nimport {runSafe} from '../../safe-runner';\nimport {TopicSubscription, TopicSubscriptionRegistry} from './topic-subscription.registry';\nimport {ClientRegistry} from '../client-registry/client.registry';\nimport {chainInterceptors, IntentInterceptor, MessageInterceptor, PublishInterceptorChain} from './message-interception';\nimport {Beans, Initializer, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {Runlevel} from '../../platform-state';\nimport {APP_IDENTITY} from '../../platform.model';\nimport {ɵVERSION} from '../../ɵplatform.model';\nimport {bufferUntil} from '@scion/toolkit/operators';\nimport {filterByChannel, filterByTransport} from '../../operators';\nimport {Client} from '../client-registry/client';\nimport {semver} from '../semver';\nimport {ɵClient} from '../client-registry/ɵclient';\nimport {stringifyError} from '../../error.util';\nimport {IntentSubscription, IntentSubscriptionRegistry} from './intent-subscription.registry';\nimport {TopicMatcher} from '../../topic-matcher.util';\nimport {Defined, Maps} from '@scion/toolkit/util';\nimport {MessageClient} from '../../client/messaging/message-client';\nimport {Predicates} from './predicates.util';\nimport {Topics} from '../../topics.util';\nimport {Qualifiers} from '../../qualifiers.util';\nimport {IntentParams} from './intent-params.util';\n\n/**\n * The broker is responsible for receiving all messages, filtering the messages, determining who is\n * subscribed to each message, and sending the message to these subscribed clients.\n *\n * The broker allows topic-based and intent-based messaging and supports retained messages.\n *\n * When the broker receives a message from a client, the broker identifies the sending client using the {@Window}\n * contained in the {@link MessageEvent}. The user agent sets the window, which cannot be tampered by the client.\n * However, when the client unloads, the window is not set because already been destroyed. Then, the broker identifies\n * the client using the unique client id. In both cases, the broker checks the origin of the message to match the\n * origin of the registered application.\n *\n * The broker processes client connect requests in runlevel 1 or higher. Message dispatching is enabled in runlevel 2.\n * Prior requests are buffered until entering the respective runlevel.\n *\n * @internal\n */\nexport class MessageBroker implements Initializer, PreDestroy {\n\n  private readonly _destroy$ = new Subject<void>();\n  private readonly _clientMessage$: Observable<MessageEvent<MessageEnvelope>>;\n\n  private readonly _clientRegistry = Beans.get(ClientRegistry);\n  private readonly _topicSubscriptionRegistry = Beans.get(TopicSubscriptionRegistry);\n  private readonly _intentSubscriptionRegistry = Beans.get(IntentSubscriptionRegistry);\n\n  private readonly _retainedMessageStore = new Map<string, TopicMessage[]>();\n  private readonly _retainedIntentStore = new Map<string, IntentMessage[]>();\n\n  private readonly _applicationRegistry: ApplicationRegistry;\n  private readonly _manifestRegistry: ManifestRegistry;\n\n  private readonly _messagePublisher: PublishInterceptorChain<TopicMessage>;\n  private readonly _intentPublisher: PublishInterceptorChain<IntentMessage>;\n\n  constructor() {\n    this._applicationRegistry = Beans.get(ApplicationRegistry);\n    this._manifestRegistry = Beans.get(ManifestRegistry);\n\n    // Construct a stream of messages sent by clients.\n    this._clientMessage$ = fromEvent<MessageEvent>(window, 'message')\n      .pipe(\n        filterByTransport(MessagingTransport.ClientToBroker),\n        filterByChannel(MessagingChannel.Intent, MessagingChannel.Topic, MessagingChannel.TopicSubscribe, MessagingChannel.TopicUnsubscribe, MessagingChannel.IntentSubscribe, MessagingChannel.IntentUnsubscribe),\n        bufferUntil(Beans.whenRunlevel(Runlevel.Two)),\n        checkOriginTrusted(),\n        catchErrorAndRetry(),\n        share(),\n      );\n\n    // Install client connect listeners.\n    this.installClientConnectListener();\n    this.installClientDisconnectListener();\n\n    // Install message handling.\n    this.installMessageDispatcher();\n    this.installTopicSubscribeListener();\n    this.installTopicUnsubscribeListener();\n    this.installTopicSubscriberCountObserver();\n    this.sendRetainedMessageOnSubscribe();\n\n    // Install intent handling.\n    this.installIntentDispatcher();\n    this.installIntentSubscribeListener();\n    this.installIntentUnsubscribeListener();\n    this.sendRetainedIntentOnSubscribe();\n    this.deleteRetainedIntentOnCapabilityUnregister();\n\n    // Assemble message interceptors to a chain of handlers which are called one after another. The publisher is added as terminal handler.\n    this._messagePublisher = this.createMessagePublisher();\n    this._intentPublisher = this.createIntentPublisher();\n  }\n\n  public init(): Promise<void> {\n    return Promise.resolve();\n  }\n\n  private installClientConnectListener(): void {\n    fromEvent<MessageEvent>(window, 'message')\n      .pipe(\n        filterByTransport(MessagingTransport.ClientToBroker),\n        filterByChannel(MessagingChannel.ClientConnect),\n        bufferUntil(Beans.whenRunlevel(Runlevel.One)),\n        catchErrorAndRetry(),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MessageEvent) => runSafe(() => {\n        // Ignore stale CONNECT request, e.g. if the origin window has been closed or a page with a different origin has been loaded.\n        if (!event.source) {\n          Beans.get(Logger).debug(`[CONNECT] Ignoring stale connect request from \"${event.origin}\".`);\n          return;\n        }\n\n        const eventSource: Window = event.source as Window;\n        const envelope = event.data as MessageEnvelope<TopicMessage<void>>;\n        const clientAppName = envelope.message.headers.get(MessageHeaders.AppSymbolicName) as string;\n        const clientMessageTarget = new MessageTarget(event);\n        const replyTo = envelope.message.headers.get(MessageHeaders.ReplyTo) as string;\n\n        if (!clientAppName) {\n          const warning = `Client connect attempt rejected: Bad request. [origin='${event.origin}']`;\n          Beans.get(Logger).warn(`[CONNECT] ${warning}`);\n          sendTopicMessage<ConnackMessage>(clientMessageTarget, {\n            topic: replyTo,\n            body: {returnCode: 'refused:bad-request', returnMessage: `[ClientConnectError] ${warning}`},\n            headers: new Map(),\n          });\n          return;\n        }\n\n        const application = this._applicationRegistry.getApplication(clientAppName, {orElse: null});\n        if (!application) {\n          const warning = `Client connect attempt rejected: Unknown client. [app='${clientAppName}']`;\n          Beans.get(Logger).warn(`[CONNECT] ${warning}`);\n          sendTopicMessage<ConnackMessage>(clientMessageTarget, {\n            topic: replyTo,\n            body: {returnCode: 'refused:rejected', returnMessage: `[ClientConnectError] ${warning}`},\n            headers: new Map(),\n          });\n          return;\n        }\n\n        if (!application.allowedMessageOrigins.has(event.origin)) {\n          const warning = `Client connect attempt blocked: Wrong origin [actual='${event.origin}', expected='${Array.from(application.allowedMessageOrigins)}', app='${application.symbolicName}']`;\n          Beans.get(Logger).warn(`[CONNECT] ${warning}`);\n\n          sendTopicMessage<ConnackMessage>(clientMessageTarget, {\n            topic: replyTo,\n            body: {returnCode: 'refused:blocked', returnMessage: `[ClientConnectError] ${warning}`},\n            headers: new Map(),\n          });\n          return;\n        }\n\n        // Check if the client is already connected. If already connected, do nothing. A client can potentially initiate multiple connect requests, for example,\n        // when not receiving connect confirmation in time.\n        const currentClient = this._clientRegistry.getByWindow(eventSource);\n        if (currentClient?.origin === event.origin && currentClient.application.symbolicName === application.symbolicName) {\n          sendTopicMessage<ConnackMessage>(currentClient, {\n            topic: replyTo,\n            body: {\n              returnCode: 'accepted',\n              clientId: currentClient.id,\n            },\n            headers: new Map(),\n          });\n          return;\n        }\n\n        const client = new ɵClient(UUID.randomUUID(), eventSource, event.origin, application, envelope.message.headers.get(MessageHeaders.Version) as string);\n        this._clientRegistry.registerClient(client);\n\n        // Check if the client is compatible with the platform version of the host.\n        if (semver.major(client.version) !== semver.major(Beans.get<string>(ɵVERSION))) {\n          Beans.get(Logger).warn(`[VersionMismatch] Application '${application.symbolicName}' uses a different major version of the @scion/microfrontend-platform than the host application, which may not be compatible. Please upgrade @scion/microfrontend-platform of application '${application.symbolicName}' from version '${(client.version)}' to version '${(Beans.get<string>(ɵVERSION))}'.`, new LoggingContext(application.symbolicName, client.version));\n        }\n\n        sendTopicMessage<ConnackMessage>(client, {\n          topic: replyTo,\n          body: {\n            returnCode: 'accepted',\n            clientId: client.id,\n          },\n          headers: new Map(),\n        });\n      }));\n  }\n\n  /**\n   * Listens for client disconnect requests.\n   */\n  private installClientDisconnectListener(): void {\n    fromEvent<MessageEvent>(window, 'message')\n      .pipe(\n        filterByTransport(MessagingTransport.ClientToBroker),\n        filterByChannel(MessagingChannel.ClientDisconnect),\n        bufferUntil(Beans.whenRunlevel(Runlevel.One)),\n        checkOriginTrusted(),\n        catchErrorAndRetry(),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MessageEvent<MessageEnvelope>) => runSafe(() => {\n        const client = getSendingClient(event);\n        this._clientRegistry.unregisterClient(client);\n      }));\n  }\n\n  /**\n   * Replies to requests to observe the number of subscribers on a topic.\n   */\n  private installTopicSubscriberCountObserver(): void {\n    Beans.get(MessageClient).observe$<string>(PlatformTopics.RequestSubscriberCount)\n      .pipe(takeUntil(this._destroy$))\n      .subscribe(request => runSafe(() => {\n        const topic = request.body!;\n        const replyTo = request.headers.get(MessageHeaders.ReplyTo) as string;\n        const unsubscribe$ = this._topicSubscriptionRegistry.subscriptionCount$(replyTo).pipe(filter(count => count === 0));\n\n        this._topicSubscriptionRegistry.subscriptionCount$(topic)\n          .pipe(takeUntil(merge(this._destroy$, unsubscribe$)))\n          .subscribe({ // eslint-disable-line @smarttools/rxjs/no-nested-subscribe\n            next: count => void Beans.get(MessageClient).publish(replyTo, count),\n            error: error => void Beans.get(MessageClient).publish(replyTo, stringifyError(error), {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.ERROR)}),\n          });\n      }));\n  }\n\n  /**\n   * Dispatches topic messages to subscribed clients.\n   */\n  private installMessageDispatcher(): void {\n    this._clientMessage$\n      .pipe(\n        filterByChannel<TopicMessage>(MessagingChannel.Topic),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MessageEvent<MessageEnvelope<TopicMessage>>) => void runSafe(async () => {\n        const client = getSendingClient(event);\n        const message = event.data.message;\n        const messageId = message.headers.get(MessageHeaders.MessageId) as string;\n\n        const illegalTopicError = Topics.validateTopic(message.topic, {exactTopic: true});\n        if (illegalTopicError) {\n          sendDeliveryStatusError(client, messageId, illegalTopicError);\n          return;\n        }\n\n        // If a retained message without payload, remove any stored retained message on that topic, if any.\n        if (message.retain && !isRequest(message) && message.body === undefined) {\n          Maps.removeListValue(this._retainedMessageStore, message.topic, Predicates.not(isRequest));\n          sendDeliveryStatusSuccess(client, messageId);\n          return;\n        }\n\n        try {\n          // If a request of a request-response communication, create a subscription for the requestor to receive replies.\n          const requestorReplySubscription = this.subscribeForRepliesIfRequest(message, client);\n          // Ensure the message header 'ɵSUBSCRIBER_ID' to be removed; is set in request-response communication by the client gateway.\n          message.headers.delete(MessageHeaders.ɵSubscriberId);\n          // Dispatch the message.\n          await this._messagePublisher.interceptAndPublish(message);\n          // If a retained message or request, store it for late subscribers.\n          this.storeMessageIfRetained(message, requestorReplySubscription);\n\n          sendDeliveryStatusSuccess(client, messageId);\n        }\n        catch (error) {\n          sendDeliveryStatusError(client, messageId, error);\n        }\n      }));\n  }\n\n  /**\n   * Dispatches intents to qualified clients.\n   */\n  private installIntentDispatcher(): void {\n    this._clientMessage$\n      .pipe(\n        filterByChannel<IntentMessage>(MessagingChannel.Intent),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MessageEvent<MessageEnvelope<IntentMessage>>) => void runSafe(async () => {\n        const client = getSendingClient(event);\n        const message = event.data.message;\n        const messageId = message.headers.get(MessageHeaders.MessageId) as string;\n\n        if (!message.intent) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition\n          const error = '[MessagingError] Missing message property: intent';\n          sendDeliveryStatusError(client, messageId, error);\n          return;\n        }\n\n        if (!message.intent.type) {\n          const error = '[MessagingError] Missing message property: type';\n          sendDeliveryStatusError(client, messageId, error);\n          return;\n        }\n\n        const illegalQualifierError = Qualifiers.validateQualifier(message.intent.qualifier, {exactQualifier: true});\n        if (illegalQualifierError) {\n          sendDeliveryStatusError(client, messageId, illegalQualifierError);\n          return;\n        }\n\n        if (!this._manifestRegistry.hasIntention(message.intent, client.application.symbolicName)) {\n          const error = `[NotQualifiedError] Application '${client.application.symbolicName}' is not qualified to publish intents of the type '${message.intent.type}' and qualifier '${JSON.stringify(message.intent.qualifier ?? {})}'. Ensure to have listed the intention in the application manifest.`;\n          sendDeliveryStatusError(client, messageId, error);\n          return;\n        }\n\n        // Find capabilities fulfilling the intent, or send an error otherwise.\n        const capabilities = this._manifestRegistry.resolveCapabilitiesByIntent(message.intent, client.application.symbolicName);\n        if (capabilities.length === 0) {\n          const error = `[NullProviderError] No application found to provide a capability of the type '${message.intent.type}' and qualifiers '${JSON.stringify(message.intent.qualifier ?? {})}'. Maybe, the capability is not public API or the providing application not available.`;\n          sendDeliveryStatusError(client, messageId, error);\n          return;\n        }\n\n        // If a retained message without payload, remove any stored retained message for the resolved capabilities.\n        if (message.retain && !isRequest(message) && message.body === undefined) {\n          capabilities.forEach(capability => {\n            Maps.removeListValue(this._retainedIntentStore, capability.metadata!.id, Predicates.not(isRequest));\n            sendDeliveryStatusSuccess(client, messageId);\n          });\n          return;\n        }\n\n        try {\n          // If a request of a request-response communication, create a subscription for the requestor to receive replies.\n          const requestorReplySubscription = this.subscribeForRepliesIfRequest(message, client);\n          // Ensure the message header 'ɵSUBSCRIBER_ID' to be removed; is set in request-response communication by the client gateway.\n          message.headers.delete(MessageHeaders.ɵSubscriberId);\n\n          // Dispatch the message.\n          await Promise.all(capabilities\n            // Associate capability with the intent.\n            .map<IntentMessage>(capability => ({...message, capability}))\n            .map(async message => {\n              // Validate intent params.\n              IntentParams.validateParams(message);\n              // Publish the intent.\n              await this._intentPublisher.interceptAndPublish(message);\n              // If a retained message or request, store it for late subscribers.\n              this.storeIntentIfRetained(message, requestorReplySubscription);\n            }));\n          sendDeliveryStatusSuccess(client, messageId);\n        }\n        catch (error) {\n          sendDeliveryStatusError(client, messageId, error);\n        }\n      }));\n  }\n\n  /**\n   * Installs a listener that sends retained messages to new subscribers.\n   */\n  private sendRetainedMessageOnSubscribe(): void {\n    this._topicSubscriptionRegistry.register$\n      .pipe(takeUntil(this._destroy$))\n      .subscribe(subscription => runSafe(() => {\n        Array.from(this._retainedMessageStore.values())\n          .flat()\n          .filter(retainedMessage => subscription.matches(retainedMessage.topic))\n          .forEach(retainedMessage => void this._messagePublisher.interceptAndPublish({\n            ...retainedMessage,\n            headers: new Map(retainedMessage.headers).set(MessageHeaders.ɵSubscriberId, subscription.subscriberId),\n          }));\n      }));\n  }\n\n  /**\n   * Installs a listener that sends retained intents to new subscribers.\n   */\n  private sendRetainedIntentOnSubscribe(): void {\n    this._intentSubscriptionRegistry.register$\n      .pipe(takeUntil(this._destroy$))\n      .subscribe(subscription => runSafe(() => {\n        Array.from(this._retainedIntentStore.values())\n          .flat()\n          .filter(retainedMessage => subscription.client.application.symbolicName === retainedMessage.capability.metadata!.appSymbolicName)\n          .filter(retainedMessage => subscription.matches(retainedMessage.intent))\n          .forEach(retainedMessage => void this._intentPublisher.interceptAndPublish({\n            ...retainedMessage,\n            headers: new Map(retainedMessage.headers).set(MessageHeaders.ɵSubscriberId, subscription.subscriberId),\n          }));\n      }));\n  }\n\n  /**\n   * Installs a listener that removes retained intent(s) when associated capability is removed.\n   */\n  private deleteRetainedIntentOnCapabilityUnregister(): void {\n    this._manifestRegistry.capabilityUnregister$\n      .pipe(\n        mergeMap(capabilities => from(capabilities)),\n        takeUntil(this._destroy$),\n      )\n      .subscribe(capability => runSafe(() => {\n        Maps.removeListValue(this._retainedIntentStore, capability.metadata!.id, Predicates.alwaysTrue);\n      }));\n  }\n\n  /**\n   * Listens for topic subscription requests.\n   */\n  private installTopicSubscribeListener(): void {\n    this._clientMessage$\n      .pipe(\n        filterByChannel<TopicSubscribeCommand>(MessagingChannel.TopicSubscribe),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MessageEvent<MessageEnvelope<TopicSubscribeCommand>>) => runSafe(() => {\n        const client = getSendingClient(event);\n        const envelope = event.data;\n        const messageId = envelope.message.headers.get(MessageHeaders.MessageId) as string;\n        const topic = envelope.message.topic;\n\n        const illegalTopicError = Topics.validateTopic(topic, {exactTopic: false});\n        if (illegalTopicError) {\n          sendDeliveryStatusError(client, messageId, illegalTopicError);\n          return;\n        }\n\n        try {\n          const subscriberId = Defined.orElseThrow(envelope.message.subscriberId, () => Error('[TopicSubscribeError] Missing property: subscriberId'));\n          this._topicSubscriptionRegistry.register(new TopicSubscription(topic, subscriberId, client));\n          sendDeliveryStatusSuccess(client, messageId);\n        }\n        catch (error) {\n          sendDeliveryStatusError(client, messageId, error);\n        }\n      }));\n  }\n\n  /**\n   * Listens for topic unsubscription requests.\n   */\n  private installTopicUnsubscribeListener(): void {\n    this._clientMessage$\n      .pipe(\n        filterByChannel<UnsubscribeCommand>(MessagingChannel.TopicUnsubscribe),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MessageEvent<MessageEnvelope<UnsubscribeCommand>>) => runSafe(() => {\n        const client = getSendingClient(event);\n        const envelope = event.data;\n        const messageId = envelope.message.headers.get(MessageHeaders.MessageId) as string;\n\n        try {\n          const subscriberId = Defined.orElseThrow(envelope.message.subscriberId, () => Error('[TopicUnsubscribeError] Missing property: subscriberId'));\n          this._topicSubscriptionRegistry.unregister({subscriberId});\n          sendDeliveryStatusSuccess(client, messageId);\n        }\n        catch (error) {\n          sendDeliveryStatusError(client, messageId, error);\n        }\n      }));\n  }\n\n  /**\n   * Listens for intent subscription requests.\n   */\n  private installIntentSubscribeListener(): void {\n    this._clientMessage$\n      .pipe(\n        filterByChannel<IntentSubscribeCommand>(MessagingChannel.IntentSubscribe),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MessageEvent<MessageEnvelope<IntentSubscribeCommand>>) => runSafe(() => {\n        const client = getSendingClient(event);\n        const envelope = event.data;\n        const messageId = envelope.message.headers.get(MessageHeaders.MessageId) as string;\n\n        const illegalQualifierError = Qualifiers.validateQualifier(envelope.message.selector?.qualifier, {exactQualifier: false});\n        if (illegalQualifierError) {\n          sendDeliveryStatusError(client, messageId, illegalQualifierError);\n          return;\n        }\n\n        try {\n          const subscriberId = Defined.orElseThrow(envelope.message.subscriberId, () => Error('[IntentSubscribeError] Missing property: subscriberId'));\n          this._intentSubscriptionRegistry.register(new IntentSubscription(envelope.message.selector ?? {}, subscriberId, client));\n          sendDeliveryStatusSuccess(client, messageId);\n        }\n        catch (error) {\n          sendDeliveryStatusError(client, messageId, error);\n        }\n      }));\n  }\n\n  /**\n   * Listens for intent unsubscription requests.\n   */\n  private installIntentUnsubscribeListener(): void {\n    this._clientMessage$\n      .pipe(\n        filterByChannel<UnsubscribeCommand>(MessagingChannel.IntentUnsubscribe),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MessageEvent<MessageEnvelope<UnsubscribeCommand>>) => runSafe(() => {\n        const client = getSendingClient(event);\n        const envelope = event.data;\n        const messageId = envelope.message.headers.get(MessageHeaders.MessageId) as string;\n\n        try {\n          const subscriberId = Defined.orElseThrow(envelope.message.subscriberId, () => Error('[IntentUnsubscribeError] Missing property: subscriberId'));\n          this._intentSubscriptionRegistry.unregister({subscriberId});\n          sendDeliveryStatusSuccess(client, messageId);\n        }\n        catch (error) {\n          sendDeliveryStatusError(client, messageId, error);\n        }\n      }));\n  }\n\n  /**\n   * Creates the interceptor chain to intercept message publishing. The publisher is added as terminal handler.\n   */\n  private createMessagePublisher(): PublishInterceptorChain<TopicMessage> {\n    return chainInterceptors(Beans.all(MessageInterceptor), async (message: TopicMessage): Promise<void> => {\n      const subscribers = this._topicSubscriptionRegistry.subscriptions({\n        subscriberId: message.headers.get(MessageHeaders.ɵSubscriberId) as string,\n        topic: message.topic,\n      });\n\n      // If request-reply communication, reply with an error if no subscriber is registered to answer the request.\n      if (isRequest(message) && !message.retain && !subscribers.length) {\n        throw Error(`[MessagingError] No subscriber registered to answer the request [topic=${message.topic}]`);\n      }\n\n      subscribers.forEach(subscriber => runSafe(() => sendTopicMessage(subscriber, message)));\n    });\n  }\n\n  /**\n   * Creates the interceptor chain to intercept intent publishing. The publisher is added as terminal handler.\n   */\n  private createIntentPublisher(): PublishInterceptorChain<IntentMessage> {\n    return chainInterceptors(Beans.all(IntentInterceptor), async (message: IntentMessage): Promise<void> => {\n      const subscribers = this._intentSubscriptionRegistry.subscriptions({\n        subscriberId: message.headers.get(MessageHeaders.ɵSubscriberId) as string,\n        appSymbolicName: message.capability.metadata!.appSymbolicName,\n        intent: message.intent,\n      });\n\n      // If request-reply communication, reply with an error if no subscriber is registered to answer the intent.\n      if (isRequest(message) && !message.retain && !subscribers.length) {\n        throw Error(`[MessagingError] No subscriber registered to answer the intent [intent=${JSON.stringify(message.intent)}]`);\n      }\n\n      subscribers.forEach(subscriber => runSafe(() => sendIntentMessage(subscriber, message)));\n    });\n  }\n\n  /**\n   * Create a subscription for the sender to receive replies if request-response communication.\n   */\n  private subscribeForRepliesIfRequest(message: Message, sender: Client): TopicSubscription | null {\n    if (!isRequest(message)) {\n      return null;\n    }\n\n    const subscriberId = Defined.orElseThrow(message.headers.get(MessageHeaders.ɵSubscriberId) as string | undefined, () => Error('[MessagingError] Missing message header: subscriberId'));\n    const replyTo = message.headers.get(MessageHeaders.ReplyTo) as string;\n    const subscription = new TopicSubscription(replyTo, subscriberId, sender);\n    this._topicSubscriptionRegistry.register(subscription);\n    return subscription;\n  }\n\n  /**\n   * Stores the message if retained.\n   *\n   * Unlike a regular message, a retained message remains in the broker and is delivered to new subscribers, even if they subscribe\n   * after the request has been sent. The broker stores one retained message per topic, i.e., a later sent retained message will replace\n   * a previously sent retained message. This, however, does not apply to retained requests in request-response communication.\n   * Retained requests are NEVER replaced and remain in the broker until the requestor unsubscribes.\n   *\n   * @param message - Message to be stored if retained.\n   * @param requestorReplySubscription - Subscription of the requestor to receive replies; only set in request-response communication.\n   */\n  private storeMessageIfRetained(message: TopicMessage, requestorReplySubscription: TopicSubscription | null): void {\n    if (!message.retain) {\n      return;\n    }\n\n    // If a retained request, store it. Retained requests are not replaced and are retained until the requestor unsubscribes.\n    if (isRequest(message)) {\n      Defined.orElseThrow(requestorReplySubscription, () => Error('[InternalMessagingError] An unexpected error occurred. Expected subscription not to be null.'));\n      Maps.addListValue(this._retainedMessageStore, message.topic, message);\n      void requestorReplySubscription!.whenUnsubscribe.then(() => Maps.removeListValue(this._retainedMessageStore, message.topic, message));\n    }\n    // If a retained message (not a request), replace any previously stored retained message on that topic, if any.\n    else {\n      Maps.removeListValue(this._retainedMessageStore, message.topic, Predicates.not(isRequest));\n      Maps.addListValue(this._retainedMessageStore, message.topic, message);\n    }\n  }\n\n  private storeIntentIfRetained(message: IntentMessage, requestorReplySubscription: TopicSubscription | null): void {\n    if (!message.retain) {\n      return;\n    }\n\n    const capabilityId = message.capability.metadata!.id;\n\n    // If a retained request, store it. Retained requests are not replaced and are retained until the requestor unsubscribes.\n    if (isRequest(message)) {\n      Defined.orElseThrow(requestorReplySubscription, () => Error('[InternalMessagingError] An unexpected error occurred. Expected subscription not to be null.'));\n      Maps.addListValue(this._retainedIntentStore, capabilityId, message);\n      void requestorReplySubscription!.whenUnsubscribe.then(() => Maps.removeListValue(this._retainedIntentStore, capabilityId, message));\n    }\n    // If a retained message (i.e. not a request), replace any previously stored retained message for that capability, if any.\n    else {\n      Maps.removeListValue(this._retainedIntentStore, capabilityId, Predicates.not(isRequest));\n      Maps.addListValue(this._retainedIntentStore, capabilityId, message);\n    }\n  }\n\n  public preDestroy(): void {\n    this._destroy$.next();\n  }\n}\n\n/**\n * Resolves to the client that sent the passed message.\n *\n * Throws an error if the client could not be resolved.\n */\nfunction getSendingClient(event: MessageEvent<MessageEnvelope>): Client {\n  const clientId = event.data.message.headers.get(MessageHeaders.ClientId) as string;\n  const client = Beans.get(ClientRegistry).getByClientId(clientId);\n  if (!client) {\n    throw Error(`[NullClientError] Client not found in client registry. [clientId=${clientId}]`);\n  }\n  return client;\n}\n\n/**\n * Passes only messages originating from trusted and registered clients.\n */\nfunction checkOriginTrusted<T extends Message>(): MonoTypeOperatorFunction<MessageEvent<MessageEnvelope<T>>> {\n  return mergeMap((event: MessageEvent<MessageEnvelope<T>>): Observable<MessageEvent<MessageEnvelope<T>>> => {\n    const envelope: MessageEnvelope = event.data;\n    const messageId = envelope.message.headers.get(MessageHeaders.MessageId) as string;\n    const clientId = envelope.message.headers.get(MessageHeaders.ClientId) as string;\n    const client = Beans.get(ClientRegistry).getByClientId(clientId);\n\n    // Assert client registration.\n    if (!client) {\n      if (event.source !== null) {\n        const sender = new MessageTarget(event);\n        const error = `[MessagingError] Message rejected: Client not registered [origin=${event.origin}]`;\n        sendDeliveryStatusError(sender, messageId, error);\n      }\n      return EMPTY;\n    }\n\n    // Assert source origin.\n    if (event.origin !== client.origin) {\n      if (event.source !== null) {\n        const sender = new MessageTarget(event);\n        const error = `[MessagingError] Message rejected: Wrong origin [actual=${event.origin}, expected=${client.origin}, application=${client.application.symbolicName}]`;\n        sendDeliveryStatusError(sender, messageId, error);\n      }\n      return EMPTY;\n    }\n\n    // Assert the source window unless it is `null`, that is, it has been closed or a page from another origin has been loaded into the window.\n    // We still process requests of stale clients to enable proper disconnection, such as delivery of messages published by the client during shutdown.\n    if (event.source !== null && event.source !== client.window) {\n      const sender = new MessageTarget(event);\n      const error = `[MessagingError] Message rejected: Wrong window [origin=${event.origin}]`;\n      sendDeliveryStatusError(sender, messageId, error);\n      return EMPTY;\n    }\n\n    return of(event);\n  });\n}\n\nfunction sendDeliveryStatusSuccess(target: MessageTarget | Client, topic: string): void {\n  sendTopicMessage<MessageDeliveryStatus>(target, {\n    topic: topic,\n    body: {ok: true},\n    headers: new Map(),\n  });\n}\n\nfunction sendDeliveryStatusError(target: MessageTarget | Client, topic: string, error: string | Error | unknown): void {\n  sendTopicMessage<MessageDeliveryStatus>(target, {\n    topic: topic,\n    body: {ok: false, details: stringifyError(error)},\n    headers: new Map(),\n  });\n}\n\nfunction sendTopicMessage<T>(target: MessageTarget | Client | TopicSubscription, message: TopicMessage<T>): void {\n  const envelope: MessageEnvelope<TopicMessage<T>> = {\n    transport: MessagingTransport.BrokerToClient,\n    channel: MessagingChannel.Topic,\n    message: {\n      ...message,\n      params: new Map(message.params),\n      headers: new Map(message.headers)\n        .set(MessageHeaders.MessageId, message.headers.get(MessageHeaders.MessageId) ?? UUID.randomUUID())\n        .set(MessageHeaders.AppSymbolicName, message.headers.get(MessageHeaders.AppSymbolicName) ?? Beans.get<string>(APP_IDENTITY)),\n    },\n  };\n\n  if (target instanceof MessageTarget) {\n    !target.window.closed && target.window.postMessage(envelope, target.origin);\n  }\n  else if (target instanceof TopicSubscription) {\n    const subscription = target;\n    const client = subscription.client;\n    envelope.message.headers.set(MessageHeaders.ɵSubscriberId, target.subscriberId);\n    envelope.message.params = new TopicMatcher(subscription.topic).match(message.topic).params;\n    !client.stale && client.window.postMessage(envelope, client.origin);\n  }\n  else {\n    !target.stale && target.window.postMessage(envelope, target.origin);\n  }\n}\n\nfunction sendIntentMessage(subscription: IntentSubscription, message: IntentMessage): void {\n  const envelope: MessageEnvelope<IntentMessage> = {\n    transport: MessagingTransport.BrokerToClient,\n    channel: MessagingChannel.Intent,\n    message: {\n      ...message,\n      headers: new Map(message.headers)\n        .set(MessageHeaders.ɵSubscriberId, subscription.subscriberId)\n        .set(MessageHeaders.MessageId, message.headers.get(MessageHeaders.MessageId) ?? UUID.randomUUID())\n        .set(MessageHeaders.AppSymbolicName, message.headers.get(MessageHeaders.AppSymbolicName) ?? Beans.get<string>(APP_IDENTITY)),\n    },\n  };\n  const client = subscription.client;\n  !client.stale && client.window.postMessage(envelope, client.origin);\n}\n\n/**\n * Catches and logs errors, and resubscribes to the source observable.\n */\nfunction catchErrorAndRetry<T>(): MonoTypeOperatorFunction<T> {\n  return catchError((error, caught) => {\n    Beans.get(Logger).error('[UnexpectedError] An unexpected error occurred.', error);\n    return caught;\n  });\n}\n\n/**\n * Tests whether given message is a request of a request-response communication.\n * That is a message that contains the {@link MessageHeaders#ReplyTo} message header.\n */\nfunction isRequest(message: Message): boolean {\n  return message.headers.has(MessageHeaders.ReplyTo);\n}\n\n/**\n * Represents the target where to send a message.\n */\nclass MessageTarget {\n\n  public readonly window: Window;\n  public readonly origin: string;\n\n  constructor(event: MessageEvent) {\n    this.window = event.source as Window;\n    this.origin = event.origin;\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {firstValueFrom, lastValueFrom, Observable, OperatorFunction} from 'rxjs';\nimport {MessageClient} from '../messaging/message-client';\nimport {Application, ApplicationQualifiedForCapabilityRequest, Capability, Intention, ManifestObjectFilter} from '../../platform.model';\nimport {PlatformTopics} from '../../ɵmessaging.model';\nimport {mapToBody} from '../../messaging.model';\nimport {Beans, Initializer} from '@scion/toolkit/bean-manager';\nimport {BrokerGateway, NullBrokerGateway} from '../messaging/broker-gateway';\nimport {mapArray} from '@scion/toolkit/operators';\nimport {ɵApplication} from '../../ɵplatform.model';\n\n/**\n * Allows browsing the catalog of capabilities and managing the capabilities of the application.\n *\n * The app can browse only capabilities which are visible to it, i.e., for which the app has declared an intention and\n * which are also publicly available. Capabilities that the app provides itself are always visible to the app.\n *\n * The app can also provide new capabilities or remove existing ones. If the *Intention Registration API* is enabled\n * for the app, the app can also manage its intentions, which, however, is discouraged. Instead, apps should\n * declare the required functionality in their manifests using wildcard intentions.\n *\n * @category Intention API\n */\nexport class ManifestService implements Initializer {\n\n  private _applications: Application[] = [];\n\n  public async init(): Promise<void> {\n    const messagingDisabled = Beans.get(BrokerGateway) instanceof NullBrokerGateway;\n    if (messagingDisabled) {\n      return;\n    }\n\n    // Wait until obtained registered applications so that they can be accessed synchronously by the application via `ManifestService#applications`.\n    const applications$ = Beans.get(MessageClient).observe$<ɵApplication[]>(PlatformTopics.Applications);\n    this._applications = await firstValueFrom(applications$.pipe(mapToBody(), mapToApplication()));\n  }\n\n  /**\n   * Applications installed in the platform.\n   */\n  public get applications(): ReadonlyArray<Application> {\n    return this._applications;\n  }\n\n  /**\n   * Returns the specified application. If not found, by default, throws an error unless setting the `orElseNull` option.\n   */\n  public getApplication(symbolicName: string): Application;\n  public getApplication(symbolicName: string, options: {orElse: null}): Application | null;\n  public getApplication(symbolicName: string, options?: {orElse: null}): Application | null {\n    const application = this._applications.find(application => application.symbolicName === symbolicName);\n    if (!application && !options) {\n      throw Error(`[NullApplicationError] No application found with symbolic name '${symbolicName}'.`);\n    }\n    return application ?? null;\n  }\n\n  /**\n   * Allows browsing the catalog of capabilities that match the given filter.\n   *\n   * <strong>\n   * You can only browse capabilities that are visible to your application, that is, capabilities that you provide yourself or that are\n   * publicly available and for which you have declared an intention in your manifest.\n   * </strong>\n   *\n   * @param  filter - Control which capabilities to browse. If no or an empty filter is given, all capabilities visible to the requesting\n   *         app are returned. Specified filter criteria are \"AND\"ed together.\\\n   *         <p>\n   *         If specifying a qualifier filter, the capabilities must match that filter exactly. The filter supports the asterisk wildcard\n   *         to match any value, e.g., `{property: '*'}`, or partial matching to find capabilities with at least the specified qualifier\n   *         properties. Partial matching is enabled by appending the _any-more_ entry to the qualifier, as following: `{'*': '*'}`.\n   * @return An Observable that, when subscribed, emits the requested capabilities.\n   *         It never completes and emits continuously when fulfilling capabilities are registered or unregistered.\n   */\n  public lookupCapabilities$<T extends Capability>(filter?: ManifestObjectFilter): Observable<T[]> {\n    return Beans.get(MessageClient).request$<T[]>(PlatformTopics.LookupCapabilities, filter)\n      .pipe(mapToBody());\n  }\n\n  /**\n   * Allows browsing the catalog of intentions that match the given filter.\n   *\n   * @param  filter - Control which intentions to return. If no or an empty filter is given, no filtering takes place. Specified filter\n   *         criteria are \"AND\"ed together.\\\n   *         <p>\n   *         If specifying a qualifier filter, the intentions must match that filter exactly. The filter supports the asterisk wildcard\n   *         to match any value, e.g., `{property: '*'}`, or partial matching to find intentions with at least the specified qualifier\n   *         properties. Partial matching is enabled by appending the _any-more_ entry to the qualifier, as following: `{'*': '*'}`.\n   * @return An Observable that, when subscribed, emits the requested intentions.\n   *         It never completes and emits continuously when matching intentions are registered or unregistered.\n   */\n  public lookupIntentions$(filter?: ManifestObjectFilter): Observable<Intention[]> {\n    return Beans.get(MessageClient).request$<Intention[]>(PlatformTopics.LookupIntentions, filter)\n      .pipe(mapToBody());\n  }\n\n  /**\n   * Registers given capability. If the capability has public visibility, other applications can browse the capability and interact with it.\n   *\n   * @return A Promise that resolves to the identity of the registered capability, if registered, or `null` if rejected by a {@link CapabilityInterceptor}.\n   *         The promise rejects if the registration failed.\n   */\n  public registerCapability<T extends Capability>(capability: T): Promise<string | null> {\n    const register$ = Beans.get(MessageClient).request$<string>(PlatformTopics.RegisterCapability, capability);\n    return lastValueFrom(register$.pipe(mapToBody()));\n  }\n\n  /**\n   * Unregisters capabilities matching the given filter.\n   *\n   * <strong>You can only unregister capabilities of your application.</strong>\n   *\n   * @param  filter - Control which capabilities to unregister by specifying filter criteria which are \"AND\"ed together. If not passing a filter,\n   *         all capabilities of the requesting app are unregistered.\\\n   *         <p>\n   *         If specifying a qualifier filter, the capabilities to unregister must match that filter exactly. The filter supports the asterisk\n   *         wildcard to match any value, e.g., `{property: '*'}`, or partial matching to unregister capabilities with at least the specified\n   *         qualifier properties. Partial matching is enabled by appending the _any-more_ entry to the qualifier, as following: `{'*': '*'}`.\n   *         Note that specifying a symbolic app name in the filter has no effect.\n   * @return A Promise that resolves when unregistered the capability,\n   *         or that rejects if the unregistration failed.\n   */\n  public unregisterCapabilities(filter?: ManifestObjectFilter): Promise<void> {\n    return new Promise<void>((resolve, reject) => {\n      Beans.get(MessageClient).request$<void>(PlatformTopics.UnregisterCapabilities, filter).subscribe({\n        error: reject,\n        complete: resolve,\n      });\n    });\n  }\n\n  /**\n   * Registers the given intention, allowing the application to interact with public capabilities matching the intention.\n   *\n   * The intention can match multiple capabilities by using the asterisk wildcard in the qualifier.\n   *\n   * <strong>This operation requires that the 'Intention Registration API' is enabled for your application.</strong>\n   *\n   * @return A Promise that resolves to the identity of the registered intention,\n   *         or that rejects if the registration failed.\n   */\n  public registerIntention(intention: Intention): Promise<string> {\n    const register$ = Beans.get(MessageClient).request$<string>(PlatformTopics.RegisterIntention, intention);\n    return lastValueFrom(register$.pipe(mapToBody()));\n  }\n\n  /**\n   * Unregisters intentions matching the given filter.\n   *\n   * <strong>You can only unregister intentions of your application.</strong>\n   * <strong>This operation requires that the 'Intention Registration API' is enabled for your application.</strong>\n   *\n   * @param  filter - Control which intentions to unregister by specifying filter criteria which are \"AND\"ed together. If not passing a filter,\n   *         all intentions of the requesting app are unregistered.\\\n   *         <p>\n   *         If specifying a qualifier filter, the intentions to unregister must match that filter exactly. The filter supports the asterisk\n   *         wildcard to match any value, e.g., `{property: '*'}`, or partial matching to unregister intentions with at least the specified\n   *         qualifier properties. Partial matching is enabled by appending the _any-more_ entry to the qualifier, as following: `{'*': '*'}`.\n   *         Note that specifying a symbolic app name in the filter has no effect.\n   * @return A Promise that resolves when unregistered the intention,\n   *         or that rejects if the unregistration failed.\n   */\n  public unregisterIntentions(filter?: ManifestObjectFilter): Promise<void> {\n    return new Promise<void>((resolve, reject) => {\n      Beans.get(MessageClient).request$<void>(PlatformTopics.UnregisterIntentions, filter).subscribe({\n        error: reject,\n        complete: resolve,\n      });\n    });\n  }\n\n  /**\n   * Tests whether the specified application is qualified to access the given capability.\n   *\n   * An application is qualified if following criteria are met:\n   * - The capability is active (1).\n   * - The capability is provided by the application, or provided by another application with\n   *   public visibility (2), and the application has an intention (3) for the capability.\n   *\n   * (1) Unless 'Capability Active Check' is disabled for the application.\n   * (2) Unless 'Scope Check' is disabled for the application.\n   * (3) Unless 'Intention Check' is disabled for the application.\n   *\n   * @param appSymbolicName - Symbolic name of the application under test.\n   * @param qualifiedFor\n   * @param qualifiedFor.capabilityId - Identifies the capability to test.\n   * @return An Observable that, when subscribed, emits the qualification of specified application.\n   *         It never completes and emits continuously when capabilites or intentions are registered or unregistered.\n   */\n  public isApplicationQualified$(appSymbolicName: string, qualifiedFor: {capabilityId: string}): Observable<boolean> {\n    const request: ApplicationQualifiedForCapabilityRequest = {appSymbolicName, capabilityId: qualifiedFor.capabilityId};\n    return Beans.get(MessageClient).request$<boolean>(PlatformTopics.IsApplicationQualifiedForCapability, request)\n      .pipe(mapToBody());\n  }\n}\n\nfunction mapToApplication(): OperatorFunction<ɵApplication[], Application[]> {\n  return mapArray(application => {\n    return {\n      ...application,\n      platformVersion: firstValueFrom(Beans.get(MessageClient).request$<string>(PlatformTopics.platformVersion(application.symbolicName)).pipe(mapToBody())),\n    };\n  });\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {MessageEnvelope, MessagingChannel, MessagingTransport} from '../../ɵmessaging.model';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {MessageHeaders, TopicMessage} from '../../messaging.model';\n\n/**\n * Context lookup options header to control if values should be collected.\n *\n * @internal\n */\nexport const CONTEXT_LOOKUP_OPTIONS = 'ɵCONTEXT_LOOKUP_OPTIONS';\n\n/**\n * Instructs how to look up context values.\n *\n * @category Context\n */\nexport interface ContextLookupOptions {\n  /**\n   * Controls whether to collect the most specific context value or to collect all values in the context\n   * hierarchy that are associated with a context name. Defaults to `false` if not specified.\n   *\n   * If `true`, collects all values in the context hierarchy that are associated with the context name.\n   * Collected values are returned as an array in context-descending order, i.e., values of parent contexts\n   * come after values of child contexts.\n   *\n   * If `false`, the most specific context value is returned, i.e., the value of the closest context\n   * that has a value associated with that name.\n   */\n  collect?: boolean;\n}\n\n/**\n * Provides the API to lookup context related information.\n *\n * @internal\n */\nexport namespace Contexts {\n\n  /**\n   * Returns the request-reply topic to lookup the names of associated context values in the context tree.\n   */\n  export function contextTreeNamesLookupTopic(): string {\n    return 'contexttree/names';\n  }\n\n  /**\n   * Returns the request-reply topic to get notified when some context changes at any level in the context tree.\n   */\n  export function contextTreeChangeTopic(): string {\n    return 'contexttree/change';\n  }\n\n  /**\n   * Computes the request-reply topic to lookup a context value from embedded router outlet web content.\n   */\n  export function contextValueLookupTopic(name: string): string {\n    return `context/${name}`;\n  }\n\n  /**\n   * Creates a message envelope to request the context value associated with the given name.\n   *\n   * @param name - The name of the value to lookup.\n   * @param replyTo - The 'replyTo' topic where to send the reply.\n   * @param options - Options to control context lookup.\n   * @param values - The collected values passed to the parent context during a context lookup.\n   *                 Used to collect all values associated with the context name in the context hierarchy.\n   */\n  export function newContextValueLookupRequest(name: string, replyTo: string, options?: ContextLookupOptions, values?: unknown[]): MessageEnvelope<TopicMessage<unknown[]>> {\n    return {\n      transport: MessagingTransport.MicrofrontendToOutlet,\n      channel: MessagingChannel.Topic,\n      message: {\n        topic: contextValueLookupTopic(encodeURIComponent(name)), // Encode in order to support names containing forward slashes or starting with a colon.\n        body: values ?? [],\n        headers: new Map<string, unknown>()\n          .set(MessageHeaders.MessageId, UUID.randomUUID())\n          .set(MessageHeaders.ReplyTo, replyTo)\n          .set(CONTEXT_LOOKUP_OPTIONS, options),\n      },\n    };\n  }\n\n  /**\n   * Creates a message envelope to lookup the names of associated context values in the context tree.\n   *\n   * @param replyTo - The 'replyTo' topic where to send the reply.\n   * @param names - The names of the current context to be combined with the names of the parent contexts.\n   */\n  export function newContextTreeNamesLookupRequest(replyTo: string, names?: Set<string>): MessageEnvelope<TopicMessage<Set<string>>> {\n    return {\n      transport: MessagingTransport.MicrofrontendToOutlet,\n      channel: MessagingChannel.Topic,\n      message: {\n        topic: Contexts.contextTreeNamesLookupTopic(),\n        body: names ?? new Set<string>(),\n        headers: new Map<string, unknown>()\n          .set(MessageHeaders.MessageId, UUID.randomUUID())\n          .set(MessageHeaders.ReplyTo, replyTo),\n      },\n    };\n  }\n\n  /**\n   * Creates a message envelope to get notified when some context changes at any level in the context tree.\n   *\n   * @param replyTo - The 'replyTo' topic where to send the reply.\n   */\n  export function newContextTreeObserveRequest(replyTo: string): MessageEnvelope<TopicMessage<void>> {\n    return {\n      transport: MessagingTransport.MicrofrontendToOutlet,\n      channel: MessagingChannel.Topic,\n      message: {\n        topic: Contexts.contextTreeChangeTopic(),\n        headers: new Map<string, unknown>()\n          .set(MessageHeaders.MessageId, UUID.randomUUID())\n          .set(MessageHeaders.ReplyTo, replyTo),\n      },\n    };\n  }\n\n  /**\n   * Event emitted when a context value changed.\n   */\n  export interface ContextTreeChangeEvent {\n    type: 'set' | 'remove';\n    name: string;\n    value?: unknown;\n  }\n\n  /**\n   * Event emitted by the root context when subscribed to it.\n   */\n  export const RootContextSubscribeEvent = 'RootContextSubscribeEvent';\n  export type RootContextSubscribeEventType = 'RootContextSubscribeEvent';\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {BehaviorSubject, fromEvent, Observable, Subject} from 'rxjs';\nimport {filter, share, takeUntil} from 'rxjs/operators';\nimport {filterByChannel, filterByTopicChannel, filterByTransport, pluckMessage} from '../../operators';\nimport {MessageEnvelope, MessagingChannel, MessagingTransport} from '../../ɵmessaging.model';\nimport {TopicMatcher} from '../../topic-matcher.util';\nimport {MessageHeaders, ResponseStatusCodes, TopicMessage} from '../../messaging.model';\nimport {MessageClient, takeUntilUnsubscribe} from '../messaging/message-client';\nimport {CONTEXT_LOOKUP_OPTIONS, ContextLookupOptions, Contexts} from './context.model';\nimport {runSafe} from '../../safe-runner';\nimport {IS_PLATFORM_HOST} from '../../platform.model';\nimport {Beans} from '@scion/toolkit/bean-manager';\n\n/**\n * Provides a context to the {@link SciRouterOutletElement} allowing the outlet to associate values with that context.\n * For embedded outlet web content, it allows looking up context names and values.\n *\n * A context is a hierarchical key-value map which are linked together to form a tree structure. When a key is not found\n * in a context, the lookup is retried on the parent, repeating until either a value is found or the root of the tree has\n * been reached.\n *\n * @internal\n */\nexport class RouterOutletContextProvider {\n\n  private _microfrontendRequest$: Observable<MessageEvent<MessageEnvelope<TopicMessage>>>;\n\n  private _entries$ = new BehaviorSubject<Map<string, unknown>>(new Map());\n  private _entryChange$ = new Subject<Contexts.ContextTreeChangeEvent>();\n  private _outletDisconnect$ = new Subject<void>();\n\n  constructor(iframe: HTMLIFrameElement) {\n    // Listen for requests from embedded web content of the outlet.\n    this._microfrontendRequest$ = fromEvent<MessageEvent>(window, 'message')\n      .pipe(\n        filter(event => event.source === iframe.contentWindow),\n        filterByTransport(MessagingTransport.MicrofrontendToOutlet),\n        filterByChannel<TopicMessage>(MessagingChannel.Topic),\n        share(),\n      );\n  }\n\n  /**\n   * Sets a value to be associated with a given name in this context.\n   *\n   * @param name - Specifies the name to store a value for.\n   * @param value - Specifies the value to be stored. It can be any object which\n   *        is serializable with the structured clone algorithm.\n   */\n  public set(name: string, value: unknown): void {\n    this._entries$.next(new Map(this._entries$.getValue()).set(name, value));\n    this._entryChange$.next({name, value, type: 'set'});\n  }\n\n  /**\n   * Removes the given name and any corresponding value from this context.\n   *\n   * Removal does not affect parent contexts, so it is possible that a subsequent call to {@link ContextService#observe$} with the same name\n   * will return a non-null result, due to a value being stored in a parent context.\n   *\n   * @param  name - Specifies the name to remove.\n   * @return `true` if the value in the outlet context has been removed successfully; otherwise `false`.\n   */\n  public remove(name: string): boolean {\n    const entries = new Map(this._entries$.getValue());\n    if (entries.delete(name)) {\n      this._entries$.next(entries);\n      this._entryChange$.next({name, type: 'remove'});\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Returns an Observable that emits the values registered in this outlet. Values inherited from parent contexts are not returned.\n   * The Observable never completes, and emits when a context value is added or removed.\n   */\n  public get entries$(): Observable<Map<string, unknown>> {\n    return this._entries$;\n  }\n\n  /**\n   * Method invoked when the outlet is mounted to the DOM.\n   */\n  public onOutletMount(): void {\n    this.installContextValueLookupListener();\n    this.installContextTreeNamesLookupListener();\n    this.installContextTreeObserveListener();\n  }\n\n  /**\n   * Method invoked when the outlet is removed from the DOM.\n   */\n  public onOutletUnmount(): void {\n    this._outletDisconnect$.next();\n  }\n\n  /**\n   * Installs a listener to reply to context value lookup requests from embedded content.\n   * When a key is not found in this context, the lookup is passed on to the parent context.\n   */\n  private installContextValueLookupListener(): void {\n    this._microfrontendRequest$\n      .pipe(\n        filterByTopicChannel<unknown[]>(Contexts.contextValueLookupTopic(':name')),\n        pluckMessage(),\n        takeUntil(this._outletDisconnect$),\n      )\n      .subscribe((lookupRequest: TopicMessage<unknown[]>) => runSafe(() => {\n        const encodedName = new TopicMatcher(Contexts.contextValueLookupTopic(':name')).match(lookupRequest.topic).params!.get('name')!;\n\n        // The name has to be decoded here because it was encoded in `newContextValueLookupRequest` where the topic was created.\n        const name = decodeURIComponent(encodedName);\n        const replyTo = lookupRequest.headers.get(MessageHeaders.ReplyTo) as string;\n        const options = lookupRequest.headers.get(CONTEXT_LOOKUP_OPTIONS) as ContextLookupOptions | undefined;\n        const entries = this._entries$.getValue();\n\n        if (options?.collect) {\n          const collectedValues = lookupRequest.body ?? [];\n          if (entries.has(name) && entries.get(name) !== undefined) {\n            collectedValues.push(entries.get(name));\n          }\n\n          if (Beans.get(IS_PLATFORM_HOST)) {\n            // Reply with the collected context values.\n            void Beans.get(MessageClient).publish(replyTo, collectedValues, {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.OK)});\n          }\n          else {\n            // Pass on the lookup request to the parent context.\n            window.parent.postMessage(Contexts.newContextValueLookupRequest(name, replyTo, options, collectedValues), '*');\n          }\n        }\n        else {\n          if (entries.has(name) && entries.get(name) !== undefined) {\n            // Reply with the found context value.\n            void Beans.get(MessageClient).publish(replyTo, entries.get(name), {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.OK)});\n          }\n          else if (Beans.get(IS_PLATFORM_HOST)) {\n            // No context value found; the root of the context tree has been reached; reply with `NOT_FOUND` status code.\n            void Beans.get(MessageClient).publish(replyTo, undefined, {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.NOT_FOUND)});\n          }\n          else {\n            // Pass on the lookup request to the parent context.\n            window.parent.postMessage(Contexts.newContextValueLookupRequest(name, replyTo, options), '*');\n          }\n        }\n      }));\n  }\n\n  /**\n   * Installs a listener to reply to context names lookup requests from embedded content.\n   *\n   * The context names are accumulated in the lookup request and passed on to the parent context.\n   * When the root context is reached, the request is finally answered with all collected context names.\n   */\n  private installContextTreeNamesLookupListener(): void {\n    this._microfrontendRequest$\n      .pipe(\n        filterByTopicChannel<Set<string>>(Contexts.contextTreeNamesLookupTopic()),\n        pluckMessage(),\n        takeUntil(this._outletDisconnect$),\n      )\n      .subscribe((lookupRequest: TopicMessage<Set<string>>) => runSafe(() => {\n        const replyTo = lookupRequest.headers.get(MessageHeaders.ReplyTo) as string;\n        const entries = this._entries$.getValue();\n        const collectedNames = new Set<string>([...entries.keys(), ...(lookupRequest.body ?? [])]);\n        if (Beans.get(IS_PLATFORM_HOST)) {\n          // Answer the request when reaching the root of the context tree.\n          void Beans.get(MessageClient).publish(replyTo, collectedNames, {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.OK)});\n        }\n        else {\n          // Pass on the lookup request to the parent context.\n          window.parent.postMessage(Contexts.newContextTreeNamesLookupRequest(replyTo, collectedNames), '*');\n        }\n      }));\n  }\n\n  /**\n   * Installs a listener to publish a context change event when this context changes.\n   *\n   * For every request a replier is installed which emits when this context changes. It stops replying\n   * when the requestor unsubscribes. The request is also passed on to the parent context.\n   */\n  private installContextTreeObserveListener(): void {\n    this._microfrontendRequest$\n      .pipe(\n        filterByTopicChannel<void>(Contexts.contextTreeChangeTopic()),\n        pluckMessage(),\n        takeUntil(this._outletDisconnect$),\n      )\n      .subscribe((observeRequest: TopicMessage<void>) => runSafe(() => {\n        const replyTo = observeRequest.headers.get(MessageHeaders.ReplyTo) as string;\n\n        this._entryChange$\n          .pipe(\n            takeUntilUnsubscribe(replyTo),\n            takeUntil(this._outletDisconnect$),\n          )\n          .subscribe((event: Contexts.ContextTreeChangeEvent) => { // eslint-disable-line @smarttools/rxjs/no-nested-subscribe\n            void Beans.get(MessageClient).publish<Contexts.ContextTreeChangeEvent>(replyTo, event);\n          });\n\n        if (Beans.get(IS_PLATFORM_HOST)) {\n          // Notify that the subscriber subscribed to the root context.\n          void Beans.get(MessageClient).publish<Contexts.RootContextSubscribeEventType>(replyTo, Contexts.RootContextSubscribeEvent);\n        }\n        else {\n          // Pass on the registration request to the parent context.\n          window.parent.postMessage(Contexts.newContextTreeObserveRequest(replyTo), '*');\n        }\n      }));\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {runSafe} from '../../safe-runner';\nimport {Navigation} from './metadata';\nimport {Urls} from '../../url.util';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {ɵWINDOW_TOP} from '../../ɵplatform.model';\n\n/**\n * Assigns a URL to the iframe of a {@link SciRouterOutletElement `<sci-router-outlet>`}.\n *\n * @category Routing\n */\nexport class RouterOutletUrlAssigner {\n\n  /**\n   * Assigns a URL to the iframe of a {@link SciRouterOutletElement `<sci-router-outlet>`}.\n   *\n   * @param iframe - Iframe for which to set the URL.\n   * @param currNavigation - Current navigation.\n   * @param prevNavigation - Previous navigation, if any.\n   */\n  public assign(iframe: HTMLIFrameElement, currNavigation: Navigation, prevNavigation: Navigation | null): void {\n    // Patch the URL to force Chrome to load the content of specified URL.\n    const patchedUrl = this.patchUrl(currNavigation.url, prevNavigation?.url);\n\n    if (currNavigation.pushStateToSessionHistoryStack) {\n      iframe.contentWindow!.location.assign(patchedUrl);\n    }\n    else {\n      iframe.contentWindow!.location.replace(patchedUrl);\n    }\n  }\n\n  /**\n   * Patches the URL to force Chrome to load the content of the given URL into an iframe.\n   *\n   * #### Problem:\n   * Chrome browser does not load the content of a nested iframe if already loaded a document from the same origin and path in a parent iframe.\n   * The problem does not occur if the URL contains query parameters. Also, the hash fragment of the URL does not matter.\n   *\n   * This problem could not be observed in Firefox and Edge.\n   *\n   * #### Motivation:\n   * If using hash-based routing, the microfrontends of an application are served under the same origin and path, and routing is based on the URL hash fragment only.\n   * This Chrome issue would prevent a microfrontend from embedding other microfrontends of its application.\n   *\n   * #### Fix:\n   * If the URL does not contain a query parameter, an arbitrary query parameter is appended to the URL to force Chrome to load the content.\n   * The name and value of the query param do not matter. However, it is crucial always to use the same param to allow the browser to cache the request.\n   *\n   * The only exception to appending a query param is when replacing an outlet's content with content from the same app. Then, the browser already loaded\n   * the application. Otherwise, if appending a query param, the application would load anew.\n   *\n   * #### Alternative fix:\n   * An alternative (but partial) fix would be to initialize the iframe with a `null` source. This fix is partial because only working when setting the initial URL\n   * of the iframe and not when changing it. Also, it has the drawback of temporarily loading the main entry point of the outlet host.\n   *\n   * @param currUrl - Specifies the URL to be patched.\n   * @param prevUrl - Specifies the previous URL, if any.\n   *\n   * @see https://stackoverflow.com/q/36985731\n   * @internal\n   */\n  public patchUrl(currUrl: string, prevUrl?: string): string {\n    const patchedUrl = runSafe(() => {\n      const prevURL = prevUrl ? Urls.newUrl(prevUrl) : undefined;\n      const currURL = Urls.newUrl(currUrl);\n\n      // Do not apply the fix for the \"about\" and \"blob\" protocol.\n      if (currURL.protocol === 'about:' || currURL.protocol === 'blob:') {\n        return currUrl;\n      }\n\n      // Do not apply the fix for top-level iframes.\n      if (window === Beans.get(ɵWINDOW_TOP)) {\n        return currUrl;\n      }\n\n      // Do not apply the fix if the URL already contains query params.\n      if (currURL.search) {\n        return currUrl;\n      }\n\n      // Do not apply the fix when navigating within the same application using hash-based routing.\n      if (prevURL?.origin === currURL.origin && prevURL.pathname === currURL.pathname) {\n        return currUrl;\n      }\n\n      // Add an arbitrary but fixed query param to the URL.\n      const patchedURL = Urls.newUrl(currUrl);\n      patchedURL.searchParams.set('_', '');\n      return patchedURL.toString();\n    });\n\n    return patchedUrl ?? currUrl;\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {Logger} from '../../logger';\n\n/**\n * Describes a user interaction with the keyboard.\n *\n * @internal\n */\nexport class Keystroke {\n\n  /**\n   * Represents this keystroke as a string with its parts separated by a dot.\n   */\n  public readonly parts: string;\n\n  /**\n   * Flags to control keystroke handling.\n   */\n  public flags?: KeystrokeFlags;\n\n  constructor(public readonly eventType: string, key: string, modifiers?: {control?: boolean; shift?: boolean; alt?: boolean; meta?: boolean}, flags?: KeystrokeFlags) {\n    const parts = [];\n    parts.push(eventType);\n    if (modifiers) {\n      modifiers.control && parts.push('control');\n      modifiers.alt && parts.push('alt');\n      modifiers.shift && parts.push('shift');\n      modifiers.meta && parts.push('meta');\n    }\n    parts.push(key.toLowerCase());\n    this.parts = parts.join('.');\n    this.flags = flags;\n  }\n\n  public withFlags(flags: KeystrokeFlags): this {\n    this.flags = flags;\n    return this;\n  }\n\n  /**\n   * Creates a {@link Keystroke} from the given keyboard event.\n   */\n  public static fromEvent(event: KeyboardEvent): Keystroke {\n    return new Keystroke(event.type, escapeKeyboardEventKey(event.key), {control: event.ctrlKey, shift: event.shiftKey, alt: event.altKey, meta: event.metaKey});\n  }\n\n  /**\n   * Parses the textual representation of a keystroke into a {@link Keystroke} object.\n   *\n   * keydown.control.alt.enter{preventDefault=true}\n   * |<--1->|<----2---->|<-3->|<--------4--------->|\n   *\n   * 1: Event type\n   * 2: Modifier part(s) (optional)\n   * 3. Key as defined in https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values.\n   *    Two keys are an exception to the value of the {@link KeyboardEvent#key} property: dot and space.\n   * 4. flags (optional)\n   */\n  public static fromString(value: string): Keystroke {\n    if (!value) {\n      throw Error('[KeystrokeParseError] Cannot parse the keystroke from \\'null\\' or \\'undefined\\'.');\n    }\n\n    const flags = parseFlags(value);\n    if (flags !== undefined) {\n      value = value.substring(0, value.indexOf('{'));\n    }\n\n    const parts = value.split('.');\n    if (parts.length < 2) {\n      throw Error(`[KeystrokeParseError] Cannot parse the keystroke '${value}'. Requires at least the event type and keyboard key, and optionally some modifiers. Examples: 'keydown.control.z', 'keydown.escape', 'keyup.enter', 'keydown.control.alt.enter', 'keydown.control.space'`);\n    }\n\n    const eventType = parts[0];\n    if (eventType !== 'keydown' && eventType !== 'keyup') {\n      throw Error(`[KeystrokeParseError] Cannot parse the keystroke '${value}'. Unsupported event type. Supported event types are: 'keydown' or 'keyup'. Examples: 'keydown.control.z', 'keydown.escape', 'keyup.enter', 'keydown.control.alt.enter', 'keydown.control.space'`);\n    }\n\n    const key = parts[parts.length - 1];\n    if (!key || new Set().add('alt').add('shift').add('control').add('meta').has(key.toLowerCase())) {\n      throw Error(`[KeystrokeParseError] Cannot parse the keystroke '${value}'. The keyboard key must be the last part. Examples: 'keydown.control.z', 'keydown.escape', 'keyup.enter', 'keydown.control.alt.enter', 'keydown.control.space'`);\n    }\n\n    const modifiers = new Set(parts.slice(1, -1));\n    const keystroke = new Keystroke(eventType, key, {control: modifiers.delete('control'), shift: modifiers.delete('shift'), alt: modifiers.delete('alt'), meta: modifiers.delete('meta')}, flags);\n    if (modifiers.size > 0) {\n      throw Error(`[KeystrokeParseError] Cannot parse the keystroke '${value}'. Illegal modifier found. Supported modifiers are: 'alt', 'shift', 'control' or 'meta'. Examples: 'keydown.control.z', 'keydown.escape', 'keyup.enter', 'keydown.control.alt.enter', 'keydown.control.space'`);\n    }\n\n    return keystroke;\n  }\n}\n\nfunction escapeKeyboardEventKey(key: string): string {\n  switch (key) {\n    case '.':\n      return 'dot';\n    case ' ':\n      return 'space';\n    default:\n      return key;\n  }\n}\n\nfunction parseFlags(keystroke: string): KeystrokeFlags | undefined {\n  const flagsStr = (/{(?<flagsDictionary>.*)}/.exec(keystroke))?.groups!['flagsDictionary'] ?? null;\n  if (flagsStr === null) {\n    return undefined;\n  }\n  if (flagsStr === '') {\n    return {};\n  }\n\n  return flagsStr\n    .split(';')\n    .map(flag => flag.split('='))\n    .reduce((flags, [flagName, flagValue]) => {\n      switch (flagName) {\n        case 'preventDefault':\n          return {...flags, preventDefault: flagValue === 'true'};\n        default: {\n          Beans.get(Logger).warn(`[KeystrokeParseError] Ignore unkown flag '${keystroke}'. Supported flags are: 'preventDefault'.`);\n          return flags;\n        }\n      }\n    }, {} as KeystrokeFlags);\n}\n\n/**\n * Flags to control keystroke handling.\n *\n * @internal\n */\nexport interface KeystrokeFlags {\n  /**\n   * If set to `true`, the default action of the keystroke is prevented.\n   */\n  preventDefault?: boolean;\n}\n","import {Dictionary} from '@scion/toolkit/util';\n\n/**\n * Options to control outlet navigation.\n *\n * @category Routing\n */\nexport interface NavigationOptions {\n  /**\n   * Specifies the routing target. If not specifying an outlet and if navigating in the context of an outlet, that outlet will be used as the\n   * navigation target, or the {@link PRIMARY_OUTLET primary} outlet otherwise.\n   */\n  outlet?: string;\n  /**\n   * Instructs the router outlet to show a splash, such as a skeleton or loading indicator, until the microfrontend signals readiness.\n   * The splash is the markup between the opening and closing tags of the router outlet element.\n   *\n   * This flag is ignored when navigating by intent as specified by the microfrontend capability in {@link MicrofrontendCapability.properties.showSplash}.\n   *\n   * @see SciRouterOutletElement\n   * @see MicrofrontendPlatformClient.signalReady\n   */\n  showSplash?: boolean;\n  /**\n   * Specifies the base URL to resolve a relative url. If not specified, the current window location is used to resolve a relative path.\n   *\n   * Note that this property has no effect if navigating via intent.\n   */\n  relativeTo?: string;\n  /**\n   * Specifies the parameters that, if navigating via URL, are used to substitute named URL parameters or that are passed along with the intent\n   * if navigating via intent.\n   */\n  params?: Map<string, unknown> | Dictionary;\n  /**\n   * Instructs the router to push a state to the browser's session history stack, allowing the user to use the back button to navigate back in the outlet.\n   * By default, this behavior is disabled.\n   */\n  pushStateToSessionHistoryStack?: boolean;\n  /**\n   * Reference to the microfrontend capability when navigating via intent.\n   * Internal property used by the router outlet to determine if to ignore the `showSplash` instruction when navigating to the same microfrontend capability again.\n   * @ignore\n   */\n  ɵcapabilityId?: string;\n}\n\n/**\n * Routing message header to control if to push a state to the browser's session history stack.\n *\n * @internal\n */\nexport const PUSH_STATE_TO_SESSION_HISTORY_STACK_MESSAGE_HEADER = 'ɵPUSH_STATE_TO_SESSION_HISTORY_STACK';\n\n/**\n * Routing message header to control if to show a splash until the microfrontend signals readiness.\n *\n * @internal\n */\nexport const SHOW_SPLASH_MESSAGE_HEADER = 'ɵSHOW_SPLASH';\n\n/**\n * Routing message header that contains the microfrontend capability when navigating via intent.\n *\n * @internal\n */\nexport const CAPABILITY_ID_MESSAGE_HEADER = 'ɵCAPABILITY_ID';\n\n/**\n * Represents a navigation.\n *\n * @category Routing\n */\nexport interface Navigation {\n  /**\n   * The URL where to navigate to.\n   */\n  url: string;\n  /**\n   * If `true`, adds a state to the browser's session history stack.\n   */\n  pushStateToSessionHistoryStack?: boolean;\n  /**\n   * If `true`, instructs the router outlet to show a splash, such as a skeleton or loading indicator,\n   * until the microfrontend signals readiness.\n   *\n   * @see SciRouterOutletElement\n   * @see MicrofrontendPlatformClient.signalReady\n   */\n  showSplash?: boolean;\n  /**\n   * The microfrontend capability when navigating via intent.\n   */\n  capabilityId?: string;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {BehaviorSubject, Observable, Subject} from 'rxjs';\nimport {RouterOutletContextProvider} from '../context/router-outlet-context-provider';\nimport {runSafe} from '../../safe-runner';\nimport {distinctUntilChanged, map, pairwise, skipWhile, startWith, switchMap, takeUntil, tap} from 'rxjs/operators';\nimport {RouterOutletUrlAssigner} from './router-outlet-url-assigner';\nimport {MessageClient} from '../messaging/message-client';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {mapToBody, TopicMessage} from '../../messaging.model';\nimport {Keystroke} from '../keyboard-event/keystroke';\nimport {PreferredSize} from '../preferred-size/preferred-size';\nimport {CAPABILITY_ID_MESSAGE_HEADER, Navigation, PUSH_STATE_TO_SESSION_HISTORY_STACK_MESSAGE_HEADER, SHOW_SPLASH_MESSAGE_HEADER} from './metadata';\nimport {Beans} from '@scion/toolkit/bean-manager';\n\nconst ELEMENT_NAME = 'sci-router-outlet';\nconst ATTR_NAME = 'name';\nconst ATTR_SCROLLABLE = 'scrollable';\nconst ATTR_KEYSTROKES = 'keystrokes';\nconst HTML_TEMPLATE = `\n  <iframe src=\"about:blank\" scrolling=\"yes\" marginheight=\"0\" marginwidth=\"0\"></iframe>\n  \n  <template id=\"splash\">\n    <div part=\"splash\" class=\"e2e-splash\">\n      <slot></slot>\n    </div>  \n  </template>\n`;\nconst STYLE_SHEET = `\n  :host {\n    display: block;\n    overflow: hidden;\n    position: relative; /* positioning context for splash */\n  }\n\n  iframe {\n    width: 100%;\n    height: 100%;\n    border: none;\n    margin: 0;\n  }\n  \n  /* Ensure transparent router-outlet if empty.\n   *\n   * An iframe is transparent only if the embedded content has the same color scheme as the embedding document.\n   * An empty router-outlet loads the 'about:blank' page. This page has the user's preferred OS color scheme,\n   * which may be different from the application's color scheme, making the iframe opaque. Therefore, we hide\n   * the iframe to make the router-outlet transparent again.\n   *\n   * More information about iframe transparency:\n   * - https://github.com/w3c/csswg-drafts/issues/4772#issuecomment-591553929\n   * - https://fvsch.com/transparent-iframes\n   */\n  :host-context(.sci-empty) iframe {\n    display: none;\n  }\n\n  div[part=\"splash\"] {\n    position: absolute;\n    inset: 0;\n  }\n`;\n\n/**\n * Web component that allows embedding web content using the {@link OutletRouter}. The content is displayed inside\n * an iframe to achieve the highest possible level of isolation between the microfrontends via a separate browsing context.\n *\n * To embed a microfrontend, place this custom HMTL element `<sci-router-outlet></sci-router-outlet>` in an HTML\n * template, give it a name via its `name` attribute and navigate via {@link OutletRouter} to instruct the outlet to\n * load the microfrontend.\n *\n * 1. Place the web component in an HTML template:\n * ```html\n * <sci-router-outlet name=\"detail\"></sci-router-outlet>\n * ```\n *\n * 2. Control the outlet's content:\n * ```ts\n * Beans.get(OutletRouter).navigate('https://micro-frontends.org', {outlet: 'detail'});\n * ```\n *\n * Outlets can be nested, allowing a microfrontend to embed another microfrontend. There is no limit to the number of\n * nested outlets. However, be aware that nested content is loaded cascaded, that is, only loaded once its parent content\n * finished loading.\n *\n * When adding the outlet to the DOM, the outlet displays the last URL routed for it, if any. When repeating routing for\n * an outlet, its content is replaced.\n *\n * ***\n *\n * ### Outlet Context\n * The router outlet allows associating contextual data, which then is available to embedded content at any nesting level.\n * Data must be serializable with the structured clone algorithm. Embedded content can look up contextual data using the\n * {@link ContextService}. Typically, contextual data is  used to provide microfrontends with information about their embedding\n * environment. Looking up contextual data requires the embedded microfrontend to be a registered micro application.\n *\n * Each outlet spans a new context. A context is like a `Map` with key-value entries. Contexts form a hierarchical tree structure.\n * When looking up a value and if the value is not found in the current context, the lookup is retried on the parent context,\n * repeating until either a value is found, or the root of the context tree has been reached.\n *\n * You can set contextual data as following:\n * ```ts\n *  const outlet: SciRouterOutletElement = document.querySelector('sci-router-outlet');\n *  outlet.setContextValue('key', 'value');\n * ```\n *\n * Embedded content can look up contextual data as following:\n * ```ts\n * Beans.get(ContextService).observe$('key').subscribe(value => {\n *   ...\n * });\n * ```\n *\n * ### Outlet size\n * The router outlet can adapt its size to the preferred size of its embedded content. The preferred size is set by the microfrontend embedded\n * in the router outlet, which, therefore, requires the embedded microfrontend to be connected to the platform.\n *\n * Embedded content can report its preferred size using the {@link PreferredSizeService}, causing the outlet to adapt its size.\n *\n * ### Keystroke Bubbling\n * The router outlet allows the registration of keystrokes, instructing embedded content at any nesting level to propagate corresponding keyboard events\n * to this outlet. The outlet dispatches keyboard events for registered keystrokes as synthetic keyboard events via its event dispatcher. They bubble up\n * the DOM tree like regular events. Propagated events are of the original type, meaning that when the user presses a key on the keyboard, a `keydown`\n * keyboard event is dispatched, or a `keyup` event when releasing a key, respectively. Keystroke bubbling requires the embedded microfrontend to be a\n * registered micro application.\n *\n * A keystroke is a `string` that has several parts, each separated with a dot. The first part specifies the event type (`keydown` or `keyup`), followed\n * by optional modifier part(s) (`alt`, `shift`, `control`, `meta`, or a combination thereof) and with the keyboard key as the last part. The key is a\n * case-insensitive value of the `KeyboardEvent.key` property. Two keys are an exception to the value of the `KeyboardEvent.key` property: `dot` and `space`.\n * For a complete list of valid key values, see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values.\n *\n * You can register keystrokes via the `keystrokes` attribute in the HTML template, or via the `keystrokes` property on the DOM\n * element. If setting keystrokes via the HTML template, multiple keystrokes are separated by a comma.\n *\n * If you want to prevent the default action of a keystroke, add the `preventDefault` flag. If not specifying the flag, the default action won't be prevented.\n *\n * HTML template:\n * ```html\n * <sci-router-outlet keystrokes=\"keydown.control.alt.enter{preventDefault=true},keydown.escape,keydown.control.space\"></sci-router-outlet>\n * ```\n *\n * Alternatively, you can register keystrokes on the DOM element as shown below.\n *\n * TypeScript:\n * ```ts\n *  const outlet: SciRouterOutletElement = document.querySelector('sci-router-outlet');\n *  outlet.keystrokes = [\n *      'keydown.control.alt.enter{preventDefault=true}',\n *      'keydown.escape',\n *      'keydown.control.space'\n *  ];\n * ```\n *\n * ### Scrollable Content\n * By default, page scrolling is enabled for the embedded content, displaying a scrollbar when it overflows. If disabled, overflowing content is clipped,\n * unless the embedded content uses a viewport, or reports its preferred size to the outlet.\n *\n * The below code snippet illustrates how to disable page scrolling for the embedded content.\n * ```html\n * <sci-router-outlet scrollable=\"false\"></sci-router-outlet>\n * ```\n *\n * ### Router Outlet Events\n *\n * The router outlet emits the following events as custom DOM events. You can attach an event listener declaratively in the HTML template using the `onevent`\n * handler syntax, or programmatically using the `addEventListener` method.\n *\n * - `activate`\n *   The `activate` custom DOM event is fired when a microfrontend is mounted. It contains the URL of the mounted microfrontend in its `details` property as `string`\n *   value. The microfrontend may not be fully loaded yet.\n * - `deactivate`\n *   The `deactivate` custom DOM event is fired when a microfrontend is about to be unmounted. It contains the URL of the unmounted microfrontend in its `details`\n *   property as `string` value.\n * - `focuswithin`\n *   The `focuswithin` custom DOM event is fired when the microfrontend loaded into the outlet, or any of its child microfrontends, has gained or lost focus.\n *   It contains the current focus-within state in its `details` property as a `boolean` value: `true` if focus was gained, or `false` if focus was lost.\n *   The event does not bubble up through the DOM. After gaining focus, the event is not triggered again until embedded content loses focus completely, i.e.,\n *   when focus does not remain in the embedded content at any nesting level. This event behaves like the `:focus-within` CSS pseudo-class but operates across iframe\n *   boundaries. For example, it can be useful when implementing overlays that close upon focus loss.\n *\n *   Note that SCION can only monitor microfrontends of registered micro apps that are connected to the platform.\n *\n * Usage:\n *\n * ```html\n * <sci-router-outlet onfocuswithin=\"onFocusWithin()\"></sci-router-outlet>\n * ```\n *\n * For an Angular application, it would look as follows:\n * ```html\n * <sci-router-outlet (focuswithin)=\"onFocusWithin($event)\"></sci-router-outlet>\n * ```\n *\n * ### Splash\n *\n * Loading and bootstrapping a microfrontend can take some time, at worst, only displaying content once initialized.\n *\n * To indicate the loading of a microfrontend, the navigator can instruct the router outlet to display a splash until the microfrontend signals readiness.\n *\n * ```ts\n * Beans.get(OutletRouter).navigate('path/to/microfrontend', {showSplash: true});\n * ```\n *\n * The splash is the markup between the opening and closing tags of the router outlet element.\n *\n * ```html\n * <sci-router-outlet>\n *   Loading...\n * </sci-router-outlet>\n * ```\n *\n * The splash is displayed until the embedded microfrontend signals readiness.\n *\n * ```ts\n * MicrofrontendPlatformClient.signalReady();\n * ```\n *\n * #### Layouting the Splash\n *\n * To lay out the content of the splash use the pseudo-element selector `::part(splash)`.\n *\n * Example of centering splash content in a CSS grid container:\n * ```css\n * sci-router-outlet::part(splash) {\n *   display: grid;\n *   place-content: center;\n * }\n * ```\n *\n * ### Web component\n * The outlet is registered as a custom element in the browser's custom element registry as defined by the Web Components standard.\n * See https://developer.mozilla.org/en-US/docs/Web/Web_Components for more information.\n *\n * ### Miscellaneous\n * If no content is routed for display in the router outlet, the CSS class `sci-empty` is added to the outlet. An outlet will not display content if\n * either there has not yet been any navigation for the outlet or the outlet content has been cleared.\n *\n * @see {@link OutletRouter}\n * @see {@link PreferredSizeService}\n * @see {@link ContextService}\n *\n * @category Routing\n */\nexport class SciRouterOutletElement extends HTMLElement {\n\n  private _shadowRoot: ShadowRoot;\n  private _disconnect$ = new Subject<void>();\n\n  private _uid = UUID.randomUUID();\n  private _iframe: HTMLIFrameElement;\n  private _outletName$: BehaviorSubject<string>;\n  private _contextProvider: RouterOutletContextProvider;\n  private _empty$ = new BehaviorSubject<boolean>(true);\n  private _splash: Splash;\n\n  /**\n   * Emits whether content is routed for display in this router outlet.\n   * Upon subscription, the Observable emits the current empty state, and then continuously emits when it changes. It never completes.\n   *\n   * An outlet does not display content if no navigation has taken place yet, or if the outlet content has been cleared.\n   */\n  public readonly empty$: Observable<boolean>;\n\n  constructor() {\n    super();\n    this._outletName$ = new BehaviorSubject<string>(PRIMARY_OUTLET);\n    this._shadowRoot = this.attachShadow({mode: 'open'});\n    this._shadowRoot.innerHTML = HTML_TEMPLATE.trim();\n\n    // Add styles using a constructable stylesheet instead of inline styles, as inline styles require a nonce if CSP blocks 'unsafe-inline' styles.\n    const styleSheet = new CSSStyleSheet();\n    styleSheet.replaceSync(STYLE_SHEET);\n    this._shadowRoot.adoptedStyleSheets.push(styleSheet);\n\n    this._iframe = this._shadowRoot.querySelector('iframe')!;\n    this._contextProvider = new RouterOutletContextProvider(this._iframe);\n    this._splash = new Splash(this._shadowRoot, this._iframe);\n    this.empty$ = this._empty$.pipe(distinctUntilChanged());\n  }\n\n  /**\n   * Sets the name of this outlet.\n   *\n   * By giving the outlet a name, you can reference the outlet when navigating. The name is optional;\n   * if not set, it defaults to {@link PRIMARY_OUTLET primary}\n   */\n  public set name(name: string | undefined) {\n    if (name) {\n      this.setAttribute(ATTR_NAME, name);\n    }\n    else {\n      this.removeAttribute(ATTR_NAME);\n    }\n  }\n\n  /**\n   * Returns the name of this outlet.\n   */\n  public get name(): string | undefined {\n    return this.getAttribute(ATTR_NAME) ?? undefined;\n  }\n\n  /**\n   * Specifies whether to enable or disable native page scrolling in the embedded document.\n   *\n   * By default, page scrolling is enabled for the embedded content, displaying a scrollbar when it overflows.\n   * If disabled, overflowing content is clipped, unless the embedded content uses a viewport, or reports\n   * its preferred size to the outlet.\n   */\n  public set scrollable(scrollable: boolean) {\n    if (scrollable) {\n      this.setAttribute(ATTR_SCROLLABLE, 'true');\n    }\n    else {\n      this.removeAttribute(ATTR_SCROLLABLE);\n    }\n  }\n\n  /**\n   * Returns whether the embedded document is natively page scrollable.\n   */\n  public get scrollable(): boolean {\n    return this.getAttribute(ATTR_SCROLLABLE) === 'true';\n  }\n\n  /**\n   * Instructs embedded content at any nesting level to propagate keyboard events to this outlet. The outlet dispatches keyboard events for registered\n   * keystrokes as synthetic keyboard events via its event dispatcher. They bubble up the DOM tree like regular events. Propagated events are of the\n   * original type, meaning that when the user presses a key on the keyboard, a `keydown` keyboard event is dispatched, or a `keyup` event when releasing\n   * a key, respectively.\n   *\n   * @param keystrokes - A keystroke is specified as a string that has several parts, each separated with a dot. The first part specifies the event type\n   *                   (`keydown` or `keyup`), followed by optional modifier part(s) (`alt`, `shift`, `control`, `meta`, or a combination thereof) and\n   *                   with the keyboard key as the last part. The key is a case-insensitive value of the `KeyboardEvent#key` property. For a complete\n   *                   list of valid key values, see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values. Two keys are an\n   *                   exception to the value of the `KeyboardEvent#key` property: `dot` and `space`.\n   *                   <br>\n   *                   To prevent the default action of a keystroke, the `preventDefault` flag can be added.\n   *                   <br>\n   *                   Examples: `keydown.control.z{preventDefault=true}`, `keydown.escape`, `keyup.enter`, `keydown.control.alt.enter`, `keydown.control.space`.\n   */\n  public set keystrokes(keystrokes: string[]) {\n    if (keystrokes.length) {\n      this.setAttribute(ATTR_KEYSTROKES, KeystrokesAttributeUtil.join(keystrokes));\n    }\n    else {\n      this.removeAttribute(ATTR_KEYSTROKES);\n    }\n  }\n\n  /**\n   * Returns the keystrokes which to bubble across the iframe boundaries.\n   */\n  public get keystrokes(): string[] {\n    return KeystrokesAttributeUtil.split(this.getAttribute(ATTR_KEYSTROKES));\n  }\n\n  /**\n   * Makes contextual data available to embedded content. Embedded content can lookup contextual data using the {@link ContextService}.\n   * Contextual data must be serializable with the structured clone algorithm.\n   */\n  public setContextValue<T = unknown>(name: string, value: T): void {\n    this._contextProvider.set(name, value);\n  }\n\n  /**\n   * Removes data registered under the given key from the context.\n   *\n   * Removal does not affect parent contexts, so it is possible that a subsequent call to {@link ContextService.observe$} with the same name\n   * will return a non-null result, due to a value being stored in a parent context.\n   *\n   * @return `true` if removed the value from the outlet context; otherwise `false`.\n   */\n  public removeContextValue(name: string): boolean {\n    return this._contextProvider.remove(name);\n  }\n\n  /**\n   * Returns an Observable that emits the context of this outlet. Context values inherited from parent contexts are not returned.\n   * The Observable never completes, and emits when a context value is added to or removed from the outlet context.\n   */\n  public get contextValues$(): Observable<Map<string, unknown>> {\n    return this._contextProvider.entries$;\n  }\n\n  /**\n   * Resets the preferred size which may have been set by the embedded content.\n   */\n  public resetPreferredSize(): void {\n    void Beans.get(MessageClient).publish(RouterOutlets.preferredSizeTopic(this._uid), null);\n  }\n\n  /**\n   * Returns the preferred size, if any, or `undefined` otherwise.\n   */\n  public get preferredSize(): PreferredSize | undefined {\n    const preferredSize: PreferredSize = {\n      minWidth: this.style.minWidth || undefined,\n      width: this.style.width || undefined,\n      maxWidth: this.style.maxWidth || undefined,\n      minHeight: this.style.minHeight || undefined,\n      height: this.style.height || undefined,\n      maxHeight: this.style.maxHeight || undefined,\n    };\n    if (Object.values(preferredSize).some(Boolean)) {\n      return preferredSize;\n    }\n    return undefined;\n  }\n\n  /**\n   * Returns the reference to the iframe of this outlet.\n   */\n  public get iframe(): HTMLIFrameElement {\n    return this._iframe;\n  }\n\n  private installOutletContext(): void {\n    this._outletName$\n      .pipe(takeUntil(this._disconnect$))\n      .subscribe((name: string) => {\n        const outletContext: OutletContext = {name: name, uid: this._uid};\n        this.iframe.name = name;\n        this.setContextValue(OUTLET_CONTEXT, outletContext);\n      });\n  }\n\n  private installOutletUrlListener(): void {\n    this._outletName$\n      .pipe(\n        switchMap(outlet => outletNavigate$(outlet).pipe(startWith(null! as Navigation))), // start with a `null` navigation in case no navigation took place yet\n        tap((navigation: Navigation | null) => this._empty$.next(!navigation || navigation.url === 'about:blank')),\n        pairwise(),\n        takeUntil(this._disconnect$),\n      )\n      .subscribe(([prevNavigation, currNavigation]: [Navigation | null, Navigation | null]) => runSafe(() => {\n        // Display splash if instructed by the navigator, but only if not navigating to the same capability, if any.\n        // Otherwise, the micro app would have to signal readiness not only after loading the microfrontend, but also when the parameters change.\n        // For example, the same microfrontend that displays data based on a path or query parameter.\n        if (!currNavigation?.capabilityId || currNavigation.capabilityId !== prevNavigation?.capabilityId) {\n          currNavigation?.showSplash ? this._splash.attach() : this._splash.detach();\n        }\n        // Emit a page deactivate event, unless not having a previous navigation\n        prevNavigation && this.dispatchEvent(new CustomEvent('deactivate', {detail: prevNavigation.url}));\n        // Change the outlet URL\n        Beans.get(RouterOutletUrlAssigner).assign(this._iframe, currNavigation ?? {url: 'about:blank'}, prevNavigation);\n        // Emit a page activate event, unless not having a current navigation\n        currNavigation && this.dispatchEvent(new CustomEvent('activate', {detail: currNavigation.url}));\n      }));\n  }\n\n  private installPreferredSizeListener(): void {\n    Beans.get(MessageClient).observe$<PreferredSize>(RouterOutlets.preferredSizeTopic(this._uid))\n      .pipe(\n        mapToBody(),\n        takeUntil(this._disconnect$),\n      )\n      .subscribe((preferredSize: PreferredSize | undefined) => {\n        setStyle(this, {\n          'min-width': preferredSize?.minWidth ?? null,\n          'width': preferredSize?.width ?? null,\n          'max-width': preferredSize?.maxWidth ?? null,\n          'min-height': preferredSize?.minHeight ?? null,\n          'height': preferredSize?.height ?? null,\n          'max-height': preferredSize?.maxHeight ?? null,\n        });\n      });\n  }\n\n  /**\n   * Dispatches synthetic keyboard events that bubble up the DOM like regular events.\n   * Note that synthetic events have the `isTrusted` flag set to `false`, preventing them of triggering default actions.\n   *\n   * Therefore, if default actions should be prevented, it has to be done where the original event is listened to.\n   * @see KeyboardEventDispatcher\n   *\n   * For more information about trusted events\n   * @see https://www.w3.org/TR/DOM-Level-3-Events/#trusted-events\n   * @see https://www.chromestatus.com/features#istrusted\n   */\n  private installKeyboardEventDispatcher(): void {\n    Beans.get(MessageClient).observe$<KeyboardEventInit>(RouterOutlets.keyboardEventTopic(this._uid, ':eventType'))\n      .pipe(takeUntil(this._disconnect$))\n      .subscribe((event: TopicMessage<KeyboardEventInit>) => {\n        const type = event.params!.get('eventType')!;\n        this.dispatchEvent(new KeyboardEvent(type, event.body));\n      });\n  }\n\n  private installFocusWithinEventDispatcher(): void {\n    Beans.get(MessageClient).observe$<boolean>(RouterOutlets.focusWithinOutletTopic(this._uid))\n      .pipe(\n        mapToBody(),\n        skipWhile(focusWithin => !focusWithin), // wait until first receiving the focus, otherwise, it would emit immediately.\n        takeUntil(this._disconnect$),\n      )\n      .subscribe((focusWithin: boolean) => {\n        this.dispatchEvent(new CustomEvent('focuswithin', {\n          detail: focusWithin,\n          bubbles: false,\n          cancelable: false,\n        }));\n      });\n  }\n\n  private installHostElementDecorator(): void {\n    this._empty$\n      .pipe(takeUntil(this._disconnect$))\n      .subscribe((empty: boolean) => {\n        if (empty) {\n          this._shadowRoot.host.classList.add('sci-empty');\n        }\n        else {\n          this._shadowRoot.host.classList.remove('sci-empty');\n        }\n      });\n  }\n\n  /**\n   * Disposes the splash when receiving a readiness signal of the embedded microfrontend.\n   */\n  private installSplashDisposer(): void {\n    Beans.get(MessageClient).observe$(RouterOutlets.signalReadyTopic(this._uid))\n      .pipe(takeUntil(this._disconnect$))\n      .subscribe(() => {\n        this._splash.detach();\n      });\n  }\n\n  /**\n   * Lifecycle callback of the 'Custom element' Web Component standard.\n   *\n   * Invoked each time the custom element is appended into a document-connected element.\n   * This will happen each time the node is moved, and may happen before the element's contents have been fully parsed.\n   *\n   * @see https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks\n   * @internal\n   */\n  public connectedCallback(): void {\n    this.installOutletUrlListener();\n    this.installOutletContext();\n    this.installPreferredSizeListener();\n    this.installFocusWithinEventDispatcher();\n    this.installKeyboardEventDispatcher();\n    this.installHostElementDecorator();\n    this.installSplashDisposer();\n    this._contextProvider.onOutletMount();\n  }\n\n  /**\n   * Lifecycle callback of the 'Custom element' Web Component standard.\n   *\n   * Invoked each time the custom element is disconnected from the document's DOM.\n   *\n   * @see https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks\n   * @internal\n   */\n  public disconnectedCallback(): void {\n    this._disconnect$.next();\n    this._contextProvider.onOutletUnmount();\n  }\n\n  /**\n   * Lifecycle callback of the 'Custom element' Web Component standard.\n   *\n   * Specifies the attributes which to observe in {@link attributeChangedCallback} method.\n   *\n   * @see https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks\n   * @internal\n   */\n  public static observedAttributes = [ATTR_NAME, ATTR_SCROLLABLE, ATTR_KEYSTROKES]; // eslint-disable-line @typescript-eslint/member-ordering\n\n  /**\n   * Lifecycle callback of the 'Custom element' Web Component standard.\n   *\n   * Invoked each time one of the custom element's attributes is added, removed, or changed.\n   *\n   * @see https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks\n   * @internal\n   */\n  public attributeChangedCallback(name: string, oldValue: string, newValue: string): void {\n    switch (name) {\n      case ATTR_NAME: {\n        this._outletName$.next(newValue || PRIMARY_OUTLET);\n        break;\n      }\n      case ATTR_SCROLLABLE: {\n        this._iframe.setAttribute('scrolling', coerceBooleanProperty(newValue) ? 'yes' : 'no');\n        break;\n      }\n      case ATTR_KEYSTROKES: {\n        KeystrokesAttributeUtil.split(oldValue).forEach(keystroke => this.removeContextValue(KEYSTROKE_CONTEXT_NAME_PREFIX + Keystroke.fromString(keystroke).parts));\n        KeystrokesAttributeUtil.split(newValue).forEach(keystrokeStr => {\n          const keystroke = Keystroke.fromString(keystrokeStr);\n          this.setContextValue(KEYSTROKE_CONTEXT_NAME_PREFIX + keystroke.parts, keystroke.flags);\n        });\n        break;\n      }\n    }\n  }\n\n  /**\n   * Defines this outlet as custom element in the browser custom element registry; has no effect if the element was already defined.\n   *\n   * @return A Promise that resolves once this custom element is defined.\n   * @internal\n   */\n  public static define(): Promise<void> {\n    if (customElements.get(ELEMENT_NAME)) {\n      return Promise.resolve();\n    }\n    else {\n      customElements.define(ELEMENT_NAME, SciRouterOutletElement);\n      return customElements.whenDefined(ELEMENT_NAME).then(() => Promise.resolve());\n    }\n  }\n}\n\n/**\n * Information about the outlet which embeds a microfrontend.\n *\n * This object can be obtained from the {@link ContextService} using the name {@link OUTLET_CONTEXT}.\n *\n * ```ts\n * Beans.get(ContextService).observe$(OUTLET_CONTEXT).subscribe((outletContext: OutletContext) => {\n *   ...\n * });\n * ```\n *\n * @see {@link OUTLET_CONTEXT}\n * @see {@link ContextService}\n * @category Context\n */\nexport interface OutletContext {\n  name: string;\n  uid: string;\n}\n\n/**\n * Coerces a data-bound value (typically a string) to a boolean.\n */\nfunction coerceBooleanProperty(value: unknown): boolean {\n  return value !== null && value !== undefined && `${value}` !== 'false';\n}\n\n/**\n * Key for obtaining the current outlet context using {@link ContextService}.\n *\n * @category Context\n * @see {@link OutletContext}\n * @see {@link ContextService}\n */\nexport const OUTLET_CONTEXT = 'ɵOUTLET';\n\n/**\n * Default name for an outlet if no explicit name is specified.\n * @category Routing\n */\nexport const PRIMARY_OUTLET = 'primary';\n\n/**\n * Defines constants for {@link SciRouterOutletElement} and {@link OutletRouter}.\n *\n * @internal\n */\nexport namespace RouterOutlets {\n\n  /**\n   * Computes the topic via which the URL for an outlet is exchanged as retained message.\n   */\n  export function urlTopic(outletName: string): string {\n    return `sci-router-outlets/${outletName}/url`;\n  }\n\n  /**\n   * Computes the topic via which a microfrontend signals readiness.\n   */\n  export function signalReadyTopic(outletUid: string): string {\n    return `sci-router-outlets/${outletUid}/ready`;\n  }\n\n  /**\n   * Computes the topic where to post keyboard events to be dispatched.\n   */\n  export function keyboardEventTopic(outletUid: string, eventType: string): string {\n    return `sci-router-outlets/${outletUid}/keyboard-events/${eventType}`;\n  }\n\n  /**\n   * Computes the topic to which the preferred outlet size can be published to.\n   */\n  export function preferredSizeTopic(outletUid: string): string {\n    return `sci-router-outlets/${outletUid}/preferred-size`;\n  }\n\n  /**\n   * Computes the topic to which the focus-within event can be published to.\n   */\n  export function focusWithinOutletTopic(outletUid: string): string {\n    return `sci-router-outlets/${outletUid}/focus-within`;\n  }\n}\n\nnamespace KeystrokesAttributeUtil {\n\n  const delimiter = ',';\n\n  export function split(attributeValue: string | null): string[] {\n    return attributeValue ? attributeValue.split(delimiter) : [];\n  }\n\n  export function join(keystrokes: string[]): string {\n    return keystrokes.join(delimiter);\n  }\n}\n\n/**\n * Keystroke bindings are prefixed with `keystroke:` when registered in the outlet context.\n *\n * @internal\n */\nexport const KEYSTROKE_CONTEXT_NAME_PREFIX = 'keystroke:';\n\n/**\n * Emits when a navigation for the given outlet occurs.\n */\nfunction outletNavigate$(outlet: string): Observable<Navigation> {\n  const outletNavigationTopic = RouterOutlets.urlTopic(outlet);\n  return Beans.get(MessageClient).observe$<string>(outletNavigationTopic)\n    .pipe(map((navigateMessage: TopicMessage<string>): Navigation => {\n      return {\n        url: navigateMessage.body ?? 'about:blank',\n        pushStateToSessionHistoryStack: navigateMessage.headers.get(PUSH_STATE_TO_SESSION_HISTORY_STACK_MESSAGE_HEADER) as boolean | undefined ?? false,\n        showSplash: navigateMessage.headers.get(SHOW_SPLASH_MESSAGE_HEADER) as boolean | undefined ?? false,\n        capabilityId: navigateMessage.headers.get(CAPABILITY_ID_MESSAGE_HEADER) as string | undefined,\n      };\n    }));\n}\n\n/**\n * Applies the given style(s) to the given element.\n *\n * Specify styles to be modified by passing a dictionary containing CSS property names (hyphen case).\n * To remove a style, set its value to `null`.\n */\nfunction setStyle(element: HTMLElement, style: {[style: string]: string | null}): void {\n  Object.keys(style).forEach(key => element.style.setProperty(key, style[key]!));\n}\n\n/**\n * Represents the splash of the router outlet element.\n *\n * The splash is created from the template with the id \"splash\" contained in the shadow DOM and is placed over the iframe.\n * When displaying the splash, we hide the iframe so that the splash does not have to set the background color.\n */\nclass Splash {\n\n  private readonly _template: HTMLTemplateElement;\n  private _element: Element | undefined;\n\n  constructor(private readonly _shadowRoot: ShadowRoot, private readonly _iframeElement: HTMLIFrameElement) {\n    this._template = this._shadowRoot.querySelector('template#splash')!;\n  }\n\n  /**\n   * Attaches the splash if not already attached.\n   */\n  public attach(): void {\n    if (this._element) {\n      return;\n    }\n    const documentFragment = this._template.content.cloneNode(true) as DocumentFragment;\n    this._element = this._shadowRoot.appendChild(documentFragment.querySelector('div[part=\"splash\"]')!);\n    this._iframeElement.style.setProperty('visibility', 'hidden');\n  }\n\n  /**\n   * Detaches the splash if attached.\n   */\n  public detach(): void {\n    if (!this._element) {\n      return;\n    }\n    this._element.remove();\n    this._element = undefined;\n    this._iframeElement.style.removeProperty('visibility');\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {concat, firstValueFrom, NEVER, Observable, Observer, of, Subject, switchMap, TeardownLogic} from 'rxjs';\nimport {filter, first, map, startWith, take, takeUntil} from 'rxjs/operators';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {MessageClient} from '../messaging/message-client';\nimport {mapToBody, MessageHeaders, ResponseStatusCodes} from '../../messaging.model';\nimport {ContextLookupOptions, Contexts} from './context.model';\nimport {IS_PLATFORM_HOST} from '../../platform.model';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {decorateObservable} from '../../observable-decorator';\n\n/**\n * Allows looking up contextual data set on a {@link SciRouterOutletElement `<sci-router-outlet>`} at any parent level.\n *\n * The platform allows associating contextual data with an outlet, which then is available in embedded content using {@link ContextService}.\n * Contextual data must be serializable with the structured clone algorithm.\n *\n * Each outlet spans a new context. A context is similar to a `Map`, but is linked to its parent outlet context, if any, thus forming a hierarchical tree structure.\n * When looking up a value and if the value is not found in the outlet context, the lookup is retried on the parent context, repeating until either a value\n * is found or the root of the context tree has been reached.\n *\n * The platform sets the following context values by default:\n *\n * | Key | Value type | Description |\n * |-----|------------|-------------|\n * | {@link OUTLET_CONTEXT ɵOUTLET} | {@link OutletContext} | Information about the outlet which embeds the microfrontend. |\n * | {@link ACTIVATION_CONTEXT ɵACTIVATION_CONTEXT} | {@link ActivationContext} | Information about the activation context if loaded by an activator. See {@link ActivatorCapability} for more information about activators. |\n *\n *\n * @category Context\n */\nexport class ContextService implements PreDestroy {\n\n  private _destroy$ = new Subject<void>();\n  private _contextTreeChange$ = new Subject<Contexts.ContextTreeChangeEvent>();\n  private _whenContextTreeChangeListenerInstalled: Promise<void>;\n\n  constructor() {\n    this._whenContextTreeChangeListenerInstalled = this.installContextTreeChangeListener(changeEvent => this._contextTreeChange$.next(changeEvent));\n  }\n\n  /**\n   * Observes the context value associated with the given name.\n   *\n   * The Observable emits the most specific value, i.e., the value of the closest context that has a value associated with that name.\n   * To collect all values in the context hierarchy associated with that name, set {@link ContextLookupOptions#collect} to `true`.\n   *\n   * If not finding a value associated with the given name in the current context, the lookup is retried on the parent context, repeating\n   * until either a value is found or the root of the context tree has been reached. If not finding a value in any context, the Observable\n   * emits `null`.\n   *\n   * @param  name - The name of the context value to observe.\n   * @param  options - Instructs how to look up the context value.\n   * @return An Observable that emits the value associated with the given name, or `null` if not finding a value.\n   *         Upon subscription, the Observable emits the currently associated value, and then continuously when it changes, at any level\n   *         in the context tree. It never completes.\n   */\n  public observe$<T>(name: string, options?: ContextLookupOptions & {collect: false}): Observable<T | null>;\n  /**\n   * Observes the context values associated with the given name.\n   *\n   * The Observable emits all associated values in the context tree as array in context-descending order,\n   * i.e., more specific context values precede others, in other words, values of child contexts precede values of parent contexts.\n   * If not finding a value in any context, the Observable emits an empty array.\n   *\n   * To only obtain the most specific value, i.e., the value of the closest context that has a value associated with that name,\n   * set {@link ContextLookupOptions#collect} to `false`.\n   *\n   * @param  name - The name of the context values to observe.\n   * @param  options - Instructs how to look up context values.\n   * @return An Observable that emits the values associated with the given name, or an empty array if not finding a value.\n   *         Upon subscription, the Observable emits currently associated values, and then continuously when they change.\n   *         It never completes. Collected values are emitted as array in context-descending order, i.e., more specific\n   *         context values precede others, in other words, values of child contexts precede values of parent contexts.\n   */\n  public observe$<T>(name: string, options: ContextLookupOptions & {collect: true}): Observable<T[]>;\n\n  public observe$<T>(name: string, options?: ContextLookupOptions): Observable<T | T[] | null>;\n  public observe$<T>(name: string, options?: ContextLookupOptions): Observable<T | T[] | null> {\n    if (Beans.get(IS_PLATFORM_HOST)) {\n      return concat(of(options?.collect ? [] : null), NEVER);\n    }\n\n    return this._contextTreeChange$\n      .pipe(\n        filter(event => event.name === name),\n        startWith(undefined as void),\n        switchMap(() => this.lookupContextValue$<T>(name, options)),\n        decorateObservable(),\n      );\n  }\n\n  /**\n   * Looks up the context value associated with the given name.\n   *\n   * The Promise resolves to the most specific value, i.e., the value of the closest context that has a value associated with that name.\n   * To collect all values in the context hierarchy associated with that name, set {@link ContextLookupOptions#collect} to `true`.\n   *\n   * If not finding a value associated with the given name in the current context, the lookup is retried on the parent context, repeating\n   * until either a value is found or the root of the context tree has been reached. If not finding a value in any context, the returned\n   * Promise resolves to `null`.\n   *\n   * @param  name - The name of the context value to look up.\n   * @param  options - Instructs how to look up the context value.\n   * @return A Promise that resolves to the value associated with the given name, or `null` if not finding a value.\n   */\n  public lookup<T>(name: string, options?: ContextLookupOptions & {collect: false}): Promise<T | null>;\n  /**\n   * Looks up context values associated with the given name.\n   *\n   * The Promise resolves to all associated values in the context tree as array in context-descending order,\n   * i.e., more specific context values precede others, in other words, values of child contexts precede values of parent contexts.\n   * If not finding a value in any context, the Promise resolves to an empty array.\n   *\n   * To only obtain the most specific value, i.e., the value of the closest context that has a value associated with that name,\n   * set {@link ContextLookupOptions#collect} to `false`.\n   *\n   * @param  name - The name of the context values to look up.\n   * @param  options - Instructs how to look up context values.\n   * @return A Promise that resolves to the values associated with the given name, or an empty array if not finding a value.\n   *         Collected values are sorted in context-descending order, i.e., more specific context values precede others, in\n   *         other words, values of child contexts precede values of parent contexts.\n   */\n  public lookup<T>(name: string, options: ContextLookupOptions & {collect: true}): Promise<T[]>;\n  public lookup<T>(name: string, options?: ContextLookupOptions): Promise<T | T[] | null>;\n  public lookup<T>(name: string, options?: ContextLookupOptions): Promise<T | T[] | null> {\n    return firstValueFrom(this.observe$<T>(name, options));\n  }\n\n  /**\n   * Checks if a context value is associated with the given name at any level in the context tree.\n   *\n   * @param name - The name of the context value to check if present.\n   * @return A Promise that resolves to `true` if a context value is associated with the given name, or that resolves to `false` otherwise.\n   */\n  public isPresent(name: string): Promise<boolean> {\n    return this.lookup(name).then(value => value !== null);\n  }\n\n  /**\n   * Observes the names of context values registered at any level in the context tree.\n   *\n   * @return An Observable that emits the names of context values registered at any level in the context tree.\n   *         Upon subscription, it emits the names of context values currently registered, and then it emits whenever\n   *         some value is registered or unregistered from a context. The Observable never completes.\n   */\n  public names$(): Observable<Set<string>> {\n    if (Beans.get(IS_PLATFORM_HOST)) {\n      return concat(of(new Set<string>()), NEVER);\n    }\n\n    return this._contextTreeChange$\n      .pipe(\n        startWith(undefined as void),\n        switchMap(() => this.lookupContextNames$()),\n        decorateObservable(),\n      );\n  }\n\n  /**\n   * Looks up the context tree for a value associated with the given name.\n   *\n   * @param  name - The name of the value to return.\n   * @param  options - Options to control context lookup.\n   * @return An Observable that emits the context value associated with the given key and then completes.\n   *         When the requested value is not found in a context, the Observable emits `null` and then completes.\n   */\n  private lookupContextValue$<T>(name: string, options?: ContextLookupOptions): Observable<T | T[] | null> {\n    return new Observable((observer: Observer<T | T[] | null>): TeardownLogic => {\n      const replyTo = UUID.randomUUID();\n      const unsubscribe$ = new Subject<void>();\n      const contextValueLookupRequest = Contexts.newContextValueLookupRequest(name, replyTo, options);\n\n      // Wait until the reply is received.\n      Beans.get(MessageClient).observe$<T | T[] | null | undefined>(replyTo)\n        .pipe(\n          take(1),\n          map(reply => reply.headers.get(MessageHeaders.Status) === ResponseStatusCodes.OK ? (reply.body ?? null) : null),\n          takeUntil(unsubscribe$),\n        )\n        .subscribe(observer);\n\n      // Send the request.\n      Promise.all([whenSubscribedToReplyTopic(replyTo), this._whenContextTreeChangeListenerInstalled])\n        .then(() => window.parent.postMessage(contextValueLookupRequest, '*'))\n        .catch((error: unknown) => observer.error(error));\n\n      return (): void => unsubscribe$.next();\n    });\n  }\n\n  /**\n   * Looks up the context names of all values registered in the current and parent contexts.\n   *\n   * @return An Observable that emits the names of all values registered in the current and parent contexts and then completes.\n   */\n  private lookupContextNames$(): Observable<Set<string>> {\n    return new Observable((observer: Observer<Set<string>>): TeardownLogic => {\n      const replyTo = UUID.randomUUID();\n      const unsubscribe$ = new Subject<void>();\n      const contextNamesLookupRequest = Contexts.newContextTreeNamesLookupRequest(replyTo);\n\n      // Wait until the reply is received.\n      Beans.get(MessageClient).observe$<Set<string>>(replyTo)\n        .pipe(\n          take(1),\n          map(reply => reply.headers.get(MessageHeaders.Status) === ResponseStatusCodes.OK ? reply.body! : new Set<string>()),\n          takeUntil(unsubscribe$),\n        )\n        .subscribe(observer);\n\n      // Send the request.\n      Promise.all([whenSubscribedToReplyTopic(replyTo), this._whenContextTreeChangeListenerInstalled])\n        .then(() => window.parent.postMessage(contextNamesLookupRequest, '*'))\n        .catch((error: unknown) => observer.error(error));\n      return (): void => unsubscribe$.next();\n    });\n  }\n\n  /**\n   * Installs a listener to get notified about context changes at any level in the context tree.\n   *\n   * @return A Promise that resolves when installed the listener.\n   */\n  private installContextTreeChangeListener(listener: (changeEvent: Contexts.ContextTreeChangeEvent) => void): Promise<void> {\n    const replyTo = UUID.randomUUID();\n    const contextObserveRequest = Contexts.newContextTreeObserveRequest(replyTo);\n\n    return new Promise<void>((resolve, reject) => {\n      // Receive change notifications.\n      Beans.get(MessageClient).observe$<Contexts.ContextTreeChangeEvent | Contexts.RootContextSubscribeEventType>(replyTo)\n        .pipe(\n          mapToBody(),\n          takeUntil(this._destroy$),\n        )\n        .subscribe({\n          next: (event: Contexts.ContextTreeChangeEvent | Contexts.RootContextSubscribeEventType) => {\n            if (event === Contexts.RootContextSubscribeEvent) {\n              resolve(); // resolve the promise as subscribed to all parent contexts.\n            }\n            else {\n              listener(event);\n            }\n          },\n          error: reject,\n        });\n\n      // Send the observe request.\n      whenSubscribedToReplyTopic(replyTo)\n        .then(() => window.parent.postMessage(contextObserveRequest, '*'))\n        .catch((error: unknown) => reject(error as Error));\n    });\n  }\n\n  /** @ignore */\n  public preDestroy(): void {\n    this._destroy$.next();\n  }\n}\n\n/**\n * Resolves when subscribed to the given reply topic.\n */\nfunction whenSubscribedToReplyTopic(topic: string): Promise<void> {\n  return new Promise<void>((resolve, reject) => {\n    Beans.get(MessageClient).subscriberCount$(topic)\n      .pipe(first(count => count === 1))\n      .subscribe({\n        error: reject,\n        complete: resolve,\n      });\n  });\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Urls} from '../../url.util';\n\n/**\n * Used by {@link OutletRouter} to convert relative paths to absolute paths.\n *\n * Replace this bean to use a different relative path resolution strategy.\n *\n * @see {@link OutletRouter}\n * @category Routing\n */\nexport class RelativePathResolver {\n\n  /**\n   * Converts the given relative path into a navigable URL with relative navigational symbols like `/`, `./`, or `../` resolved.\n   *\n   * @param  path - Specifies the path which to convert into an absolute path.\n   * @param  options - Specifies to which url the given path is relative to.\n   * @return the absolute path.\n   */\n  public resolve(path: string, options: {relativeTo: string}): string {\n    const relativeTo = Urls.newUrl(options.relativeTo);\n\n    // Check if hash-based routing is used\n    if (relativeTo.hash.startsWith('#/')) {\n      // Apply navigational symbols only to the path of the hash-based route, and not to the context path before the hash, if any.\n      // For that reason, we temporarily remove the context path when constructing the URL.\n      const {pathname, search, hash} = Urls.newUrl(path, `${relativeTo.origin}${relativeTo.hash.substring(1)}`);\n      return relativeTo.origin + relativeTo.pathname + '#' + pathname + search + hash;\n    }\n    else {\n      return Urls.newUrl(path, options.relativeTo).toString();\n    }\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Observable, Subscription} from 'rxjs';\nimport {Intent, IntentMessage, TopicMessage} from '../../messaging.model';\nimport {Qualifier} from '../../platform.model';\nimport {PublishOptions, RequestOptions} from './publish-options';\n\n/**\n * Allows sending and receiving intents between microfrontends across origins.\n * This client is part of the Intention API of the SCION Microfrontend Platform.\n *\n * Intent-based messaging enables controlled collaboration between micro applications, a mechanism known from Android development\n * where an application can start an activity via an intent (such as sending an email).\n *\n * Like topic-based communication, intent-based communication implements the pub/sub (publish/subscribe) messaging pattern, but is,\n * in contrast, more restrictive when sending messages. Sending messages is also referred to as issuing intents. It requires the sending\n * application to declare an intention in its manifest. Intents are received only by applications that provide a fulfilling capability.\n * If no application provides a fulfilling capability, the platform rejects the intent.\n *\n * The communication is built on top of the native `postMessage` mechanism. The host app acts as message broker.\n *\n * #### Intent Addressing\n * In intent-based communication, the destination are capabilities, formulated in an abstract way, consisting of a a type, and optionally\n * a qualifier. The type categorizes a capability in terms of its functional semantics. A capability may also define a qualifier to\n * differentiate the different capabilities of the same type. The type is a string literal and the qualifier a dictionary of key-value pairs.\n *\n * ### Retained Intents\n * You can mark an intent as \"retained\" for helping newly subscribed clients to get the last intent published for a capability immediately upon\n * subscription. The broker stores one retained intent per capability, i.e., a later sent retained intent will replace a previously sent retained\n * intent. To delete a retained intent, send a retained intent without payload to the same destination.\n *\n * ### Retained Request\n * Unlike retained intents, retained requests are not replaced by later retained requests/intents and remain in the broker until the requestor unsubscribes.\n *\n * ### Request-Response Messaging\n * Sometimes it is useful to initiate a request-response communication to wait for a response. Unlike with fire-and-forget intents, a temporary\n * inbox is created for the intent issuer to receive replies.\n *\n * @see {@link IntentMessage}\n * @see {@link Intent}\n * @see {@link MessageHeaders}\n *\n * @category Messaging\n * @category Intention API\n */\nexport abstract class IntentClient {\n\n  /**\n   * Sends an intent.\n   *\n   * A micro application can send intents for intentions declared in its manifest. The platform transports the intent to micro applications\n   * that provide a fulfilling capability. Along with the intent, the application can pass transfer data, either as payload, message headers\n   * or parameters. Passed data must be serializable with the Structured Clone Algorithm.\n   *\n   * A micro application is implicitly qualified to interact with capabilities that it provides; thus, it must not declare an intention.\n   *\n   * An intent can be marked as \"retained\" by setting the {@link PublishOptions.retain} flag to `true`. It instructs the broker to store this intent and\n   * deliver it to new subscribers, even if they subscribe after the intent has been published. The broker stores one retained intent per capability. To\n   * delete a retained intent, send a retained intent without payload. Deletion intents are not transported to subscribers.\n   *\n   * @param  intent - Describes the intent. The qualifier, if any, must be exact, thus not contain wildcards.\n   * @param  body - Specifies optional transfer data to be carried along with the intent.\n   *         It can be any object which is serializable with the structured clone algorithm.\n   * @param  options - Controls how to issue the intent and allows setting message headers.\n   * @return A Promise that resolves when dispatched the intent, or that rejects if the intent could not be dispatched,\n   *         e.g., if missing the intention declaration, or because no application is registered to handle the intent.\n   */\n  public abstract publish<T = unknown>(intent: Intent, body?: T, options?: PublishOptions): Promise<void>;\n\n  /**\n   * Sends an intent and receives one or more replies.\n   *\n   * A micro application can send intents for intentions declared in its manifest. The platform transports the intent to micro applications\n   * that provide a fulfilling capability. Along with the intent, the application can pass transfer data, either as payload, message headers\n   * or parameters. Passed data must be serializable with the Structured Clone Algorithm.\n   *\n   * A micro application is implicitly qualified to interact with capabilities that it provides; thus, it must not declare an intention.\n   *\n   * A request can be marked as \"retained\" by setting the {@link RequestOptions.retain} flag to `true`. It instructs the broker to store this request and\n   * deliver it to new subscribers, even if they subscribe after the request has been sent. Retained requests are not replaced by later retained requests/\n   * intents and remain in the broker until the requestor unsubscribes.\n   *\n   * If not marking the request as \"retained\", at least one subscriber must be subscribed to the intent. Otherwise, the request is rejected.\n   *\n   * @param  intent - Describes the intent. The qualifier, if any, must be exact, thus not contain wildcards.\n   * @param  body - Specifies optional transfer data to be carried along with the intent.\n   *         It can be any object which is serializable with the structured clone algorithm.\n   * @param  options - Controls how to send the request and allows setting request headers.\n   * @return An Observable that emits when receiving a reply. It never completes unless the replier sets the status code {@link ResponseStatusCodes.TERMINAL}\n   *         in the {@link MessageHeaders.Status} message header. Then, the Observable completes immediately after emitted the reply.\n   *         The Observable errors if the request could not be dispatched. It will also error if the replier sets a status code greater than or equal to 400, e.g., {@link ResponseStatusCodes.ERROR}.\n   */\n  public abstract request$<T>(intent: Intent, body?: unknown, options?: RequestOptions): Observable<TopicMessage<T>>;\n\n  /**\n   * Receives an intent when some micro application wants to collaborate with this micro application.\n   *\n   * Intents are typically subscribed to in an activator. Refer to {@link ActivatorCapability} for more information.\n   *\n   * The micro application receives only intents for which it provides a fulfilling capability.\n   * You can filter received intents by passing a selector. The selector supports the use of wildcards.\n   *\n   * If the received intent has the {@link MessageHeaders.ReplyTo} header field set, the publisher expects the receiver to send one or more\n   * replies to that {@link MessageHeaders.ReplyTo ReplyTo} topic. If streaming responses, you can use the {@link takeUntilUnsubscribe}\n   * operator to stop replying when the requestor unsubscribes.\n   *\n   * ```typescript\n   *  const selector: IntentSelector = {\n   *    type: 'temperature',\n   *    qualifier: {room: 'kitchen'},\n   *  };\n   *\n   *  Beans.get(IntentClient).observe$(selector).subscribe((request: IntentMessage) => {\n   *    const replyTo = request.headers.get(MessageHeaders.ReplyTo);\n   *    sensor$\n   *      .pipe(takeUntilUnsubscribe(replyTo))\n   *      .subscribe(temperature => {\n   *        Beans.get(MessageClient).publish(replyTo, `${temperature}°C`);\n   *      });\n   *  });\n   * ```\n   *\n   * @param  selector - Allows filtering intents. Note that the passed filter is only a filter for intents the application is qualified for, i.e., provides a fulfilling capability visible to the sender.\n   *         In the qualifier of the filter, you can use the asterisk wildcard character (`*`) to match multiple intents simultaneously.\n   *         - Asterisk wildcard character (*)\n   *           Matches intents with such a qualifier property no matter of its value (except `null` or `undefined`). Use it like this: `{property: '*'}`.\n   *         - Partial wildcard (**)\n   *           Matches intents even if having additional properties. Use it like this: `{'*': '*'}`.\n   *\n   * @return An Observable that emits received intents. It never completes.\n   */\n  public abstract observe$<T>(selector?: IntentSelector): Observable<IntentMessage<T>>;\n\n  /**\n   * Convenience API for handling intents.\n   *\n   * Unlike `observe$`, intents are passed to a callback function rather than emitted from an Observable. Response(s) can be returned directly\n   * from the callback. It supports error propagation and request termination. Using this method over `observe$` significantly reduces the code\n   * required to respond to requests.\n   *\n   * For each intent received, the specified callback function is called. When used in request-response communication,\n   * the callback function can return the response either directly or in the form of a Promise or Observable. Returning a Promise\n   * allows the response to be computed asynchronously, and an Observable allows to return one or more responses, e.g., for\n   * streaming data.\n   * If the callback function returns no value (void), returns `undefined`, or returns a Promise that resolves to `undefined`, communication is terminated\n   * immediately without a response. If the callback returns an Observable, all its emissions are transported to the requestor and communication is not\n   * terminated until the Observable completes. Termination of communication always completes the requestor's Observable.\n   * If the callback throws an error, or the returned Promise or Observable errors, the error is\n   * transported to the requestor, erroring the requestor's Observable.\n   *\n   * @param  selector - Allows filtering intents.\n   *         For more information, see the API description of {@link observe$}.\n   * @param  callback - Specifies the callback to be called for each intent. When used in request-response communication,\n   *         the callback function can return the response either directly or in the form of a Promise or Observable. If returning\n   *         a response in fire-and-forget communication, it is ignored. Throwing an error in the callback does not unregister the callback.\n   * @return Subscription to unregister the callback. Calling {@link rxjs!Subscription.unsubscribe Subscription.unsubscribe} will complete the Observable of all\n   *         requestors, if any.\n   */\n  public abstract onIntent<IN = unknown, OUT = unknown>(selector: IntentSelector, callback: (intentMessage: IntentMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription;\n}\n\n/**\n * Allows filtering intents.\n *\n * @category Messaging\n * @category Intention API\n */\nexport interface IntentSelector {\n  /**\n   * If specified, filters intents of the given type.\n   */\n  type?: string;\n  /**\n   * If specified, filters intents matching the given qualifier. You can use the asterisk wildcard (`*`) to match multiple intents.\n   * - Asterisk wildcard character (*)\n   *   Matches intents with such a qualifier property no matter of its value (except `null` or `undefined`). Use it like this: `{property: '*'}`.\n   * - Partial wildcard (**)\n   *   Matches intents even if having additional properties. Use it like this: `{'*': '*'}`.\n   */\n  qualifier?: Qualifier;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {MessageClient} from '../messaging/message-client';\nimport {OUTLET_CONTEXT, OutletContext, PRIMARY_OUTLET, RouterOutlets} from './router-outlet.element';\nimport {ContextService} from '../context/context-service';\nimport {Urls} from '../../url.util';\nimport {RelativePathResolver} from './relative-path-resolver';\nimport {Maps} from '@scion/toolkit/util';\nimport {CAPABILITY_ID_MESSAGE_HEADER, NavigationOptions, PUSH_STATE_TO_SESSION_HISTORY_STACK_MESSAGE_HEADER, SHOW_SPLASH_MESSAGE_HEADER} from './metadata';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {Intent, mapToBody, RequestError} from '../../messaging.model';\nimport {lastValueFrom} from 'rxjs';\nimport {IntentClient} from '../messaging/intent-client';\nimport {ACTIVATION_CONTEXT, PlatformCapabilityTypes, Qualifier} from '../../platform.model';\n\n/**\n * Allows navigating to a web page or microfrontend in a {@link SciRouterOutletElement `<sci-router-outlet>`} element.\n *\n * In SCION Microfrontend Platform, routing means instructing a `<sci-router-outlet>` to display the content of a URL. Routing works\n * across microfrontend and micro application boundaries, allowing the URL of an outlet to be set from anywhere in the application. The\n * web content displayed in an outlet can be any HTML document that has not set the HTTP header X-Frame-Options. Routing is also referred\n * to as navigating.\n *\n * The router supports multiple outlets in the same application to co-exist. By giving an outlet a name, you can reference it as the\n * routing target. If not naming an outlet, its name defaults to {@link PRIMARY_OUTLET primary}. If multiple outlets have the same name,\n * they all show the same content. If routing in the context of a router outlet, that is inside a microfrontend, and not specifying a\n * routing target, the content of the current outlet is replaced.\n *\n * An outlet does not necessarily have to exist at the time of routing. When adding the outlet to the DOM, the outlet displays the last URL\n * routed for it. When repeating routing for an outlet, its content is replaced.\n *\n * A router outlet is defined as follows. If no navigation has been performed for the outlet yet, then its content is empty.\n *\n *  ```html\n * <sci-router-outlet name=\"aside\"></sci-router-outlet>\n * ```\n *\n * ### Navigation via URL\n * The URL of the page to be loaded into the router outlet is passed to the router, as follows:\n *\n * ```ts\n * Beans.get(OutletRouter).navigate('https://micro-frontends.org', {outlet: 'aside'});\n * ```\n *\n * #### Relative URL Navigation\n * The router allows to use both absolute and relative paths. A relative path begins with a navigational symbol `/`, `./`, or `../`. By default,\n * relative navigation is relative to the current window location of the navigating application, unless specifying a base path for the navigation.\n *\n * ```ts\n * // Navigation relative to the root path segment\n * Beans.get(OutletRouter).navigate('/products/:id', {outlet: PRIMARY_OUTLET});\n *\n * // Navigation relative to the parent path segment\n * Beans.get(OutletRouter).navigate('../products/:id', {outlet: PRIMARY_OUTLET});\n * ```\n *\n * #### Named URL Parameters\n * The URL being passed to the router can contain named parameters which the router replaces with values of the provided params object.\n * A named parameter begins with a colon (`:`) and is allowed in path segments, query parameters, matrix parameters and the fragment part,\n * e.g., `product/:id` or `product;id=:id` or `products?id=:id`.\n *\n * ### Navigating via Intent\n * As an alternative to navigating directly to a URL, the router supports navigation to a microfrontend capability via an intent.\n * We refer to this as intent-based routing.\n *\n * We recommend using intent-based routing over url-based routing, especially for cross-application navigations, since the navigation flows\n * are explicit, i.e., declared in the manifest, and to keep the microfrontend URLs an implementation detail of the micro applications that\n * provide the microfrontends.\n *\n * Note that if the microfrontend is provided by another micro app, the navigating app must manifest an intention. Also, the navigating\n * app can only navigate to public microfrontend capabilities.\n *\n * The following code snippet illustrates how to display the _product_ microfrontend in the \"aside\" outlet. Note that you only need to pass\n * the qualifier of the microfrontend capability and not its type. The capability type, which is always `microfrontend`, is implicitly set\n * by the router.\n *\n * ```ts\n * Beans.get(OutletRouter).navigate({entity: 'product'}, {\n *   outlet: 'aside',\n *   params: {id: 123},\n * });\n * ```\n *\n * Applications can provide microfrontend capabilities through their manifest. A microfrontend can be either application private or exposed to\n * other micro applications. The platform requires all microfrontend capabilities to be of type `microfrontend`. A particular microfrontend can\n * be identified using its qualifier.\n *\n * ```json\n * {\n *   \"type\": \"microfrontend\",\n *   \"qualifier\": {\n *     \"entity\": \"product\"\n *   },\n *   \"description\": \"Displays a product.\",\n *   \"params\": [\n *     {\"name\": \"id\", \"required\": true}\n *   ],\n *   \"private\": false,\n *   \"properties\": {\n *     \"path\": \"product/:id\",\n *   }\n * }\n * ```\n *\n * Note that the providing micro application does not need to install an intent handler for its microfrontend capabilities. The platform intercepts\n * microfrontend intents and performs the navigation.\n *\n * ### Persistent Navigation\n * Persistent navigation refers to the mechanism for restoring the navigational state after an application reload.\n *\n * The router does not provide an implementation for persistent navigation out-of-the-box, mostly because many persistence strategies are imaginable.\n * For example, the navigational state could be added to the top-level URL, stored in local storage, or persisted in the backend.\n * However, you can easily implement persistent navigation yourself. The router publishes navigations to the topic `sci-router-outlets/:outlet/url`;\n * thus, they can be captured and persisted. When starting the application, you can then replay persisted navigations using the router.\n *\n * ### Unloading Outlet Content\n * To unload an outlet’s content, use null as the URL when routing, as follows:\n *\n * ```ts\n * Beans.get(OutletRouter).navigate(null, {outlet: 'aside'});\n * ```\n *\n * ### Browsing History and Session History\n * Routing does not add an entry to the browsing history, and, by default, not push a navigational state to the browser’s session history stack.\n *\n * You can instruct the router to add a navigational state to the browser’s session history stack, allowing the user to use the back button of the browser to\n * navigate back in an outlet.\n *\n * ```ts\n * Beans.get(OutletRouter).navigate('https://micro-frontends.org', {\n *   outlet: 'aside',\n *   pushStateToSessionHistoryStack: true,\n * });\n * ```\n *\n * @see {@link SciRouterOutletElement}\n *\n * @category Routing\n */\nexport class OutletRouter {\n\n  /**\n   * Navigates to the passed URL.\n   *\n   * If not specifying an outlet and if navigating in the context of an outlet, that outlet will be used as the navigation target,\n   * or the {@link PRIMARY_OUTLET primary} outlet otherwise.\n   *\n   * @param  url - Specifies the URL of the page to be loaded into the router outlet. To clear the outlet, pass `null` as the URL.\n   *         The URL allows the use of navigational symbols and named parameters. A named parameter begins with a colon (`:`)\n   *         and is allowed in path segments, query parameters, matrix parameters and the fragment part. Named parameters\n   *         are replaced with values passed via {@link NavigationOptions#params}. Named query and matrix parameters without\n   *         a replacement are removed.\n   *         Examples:\n   *         - `product/:id` // named path parameter\n   *         - `product;id=:id` // named matrix parameter\n   *         - `products?id=:id` // named query parameter\n   * @param  options - Instructs the router how to navigate, for example, you can specify the router outlet or pass named parameter values for substitution.\n   * @return Promise that resolves when navigated, or that rejects otherwise.\n   */\n  public navigate(url: string | null, options?: NavigationOptions): Promise<void>;\n  /**\n   * Navigates to the microfrontend provided as {@link MicrofrontendCapability} matching the passed qualifier.\n   *\n   * We recommend using intent-based routing over url-based routing, especially for cross-application navigations, since the navigation flows are\n   * explicit, i.e., declared in the manifest, and to keep the microfrontend URLs an implementation detail of the micro applications that provide\n   * the microfrontends.\n   *\n   * If the microfrontend is provided by another micro app, the navigating app must manifest an intention. Also, the navigating app can only navigate\n   * to public microfrontend capabilities.\n   *\n   * If not specifying an outlet and if navigating in the context of an outlet, that outlet will be used as the navigation target,\n   * or the {@link PRIMARY_OUTLET primary} outlet otherwise.\n   *\n   * @param  qualifier - Qualifies the microfrontend which to load into the outlet.\n   * @param  options - Instructs the router how to navigate, for example, you can specify the router outlet or pass intent parameters.\n   * @return Promise that resolves when navigated, or that rejects otherwise.\n   */\n  public navigate(qualifier: Qualifier, options?: NavigationOptions): Promise<void>;\n\n  public async navigate(target: string | Qualifier | null, options?: NavigationOptions): Promise<void> {\n    if (!target || typeof target === 'string') {\n      await this.navigateByUrl(target, options);\n    }\n    else {\n      await this.navigateByIntent(target, options);\n    }\n  }\n\n  /**\n   * Navigates to specified URL.\n   */\n  private async navigateByUrl(url: string | null, options?: NavigationOptions): Promise<void> {\n    const outlet = options?.outlet ?? await this.resolveContextualOutlet() ?? PRIMARY_OUTLET;\n    const outletUrlTopic = RouterOutlets.urlTopic(outlet);\n    const navigationUrl = this.computeNavigationUrl(url, options);\n\n    await Beans.get(MessageClient).publish(outletUrlTopic, navigationUrl, {\n      retain: true,\n      headers: new Map<string, unknown>()\n        .set(PUSH_STATE_TO_SESSION_HISTORY_STACK_MESSAGE_HEADER, options?.pushStateToSessionHistoryStack ?? false)\n        .set(SHOW_SPLASH_MESSAGE_HEADER, options?.showSplash ?? false)\n        .set(CAPABILITY_ID_MESSAGE_HEADER, options?.ɵcapabilityId),\n    });\n\n    // Clear retained navigation message in case of a `null` URL navigation.\n    if (url === null) {\n      await Beans.get(MessageClient).publish(outletUrlTopic, undefined, {retain: true});\n    }\n  }\n\n  /**\n   * Navigates to a microfrontend available as {@link MicrofrontendCapability} matching the passed qualifier.\n   */\n  private async navigateByIntent(qualifier: Qualifier, options?: NavigationOptions): Promise<void> {\n    if (options?.relativeTo) {\n      throw Error('[OutletRouterError][UnsupportedOptionError] Unsupported navigation option \"relativeTo\". This option is not supported in intent-based routing.');\n    }\n\n    const contextualOutlet = await this.resolveContextualOutlet();\n    const intent: Intent = {type: PlatformCapabilityTypes.Microfrontend, qualifier, params: Maps.coerce(options?.params)};\n    const navigate$ = Beans.get(IntentClient).request$<void>(intent, options, {headers: new Map().set(ROUTING_CONTEXT_MESSAGE_HEADER, {[ROUTING_CONTEXT_OUTLET]: contextualOutlet})});\n    try {\n      await lastValueFrom(navigate$.pipe(mapToBody()));\n    }\n    catch (error) {\n      throw (error instanceof RequestError ? error.message : error);\n    }\n  }\n\n  private computeNavigationUrl(urlPattern: string | null | undefined, options?: NavigationOptions): string {\n    if (urlPattern === undefined || urlPattern === null) { // empty path is a valid url\n      return 'about:blank';\n    }\n\n    const params = Maps.coerce(options?.params);\n    const url = this.substituteNamedParameters(urlPattern, params);\n    if (Urls.isAbsoluteUrl(url)) {\n      return url;\n    }\n    else {\n      const relativeTo = options?.relativeTo ?? window.location.href;\n      return Beans.get(RelativePathResolver).resolve(url, {relativeTo});\n    }\n  }\n\n  private async resolveContextualOutlet(): Promise<string | undefined> {\n    // If navigating in the context of an activator, do not use that outlet as contextual outlet.\n    if (await Beans.get(ContextService).isPresent(ACTIVATION_CONTEXT)) {\n      return undefined;\n    }\n    return (await Beans.get(ContextService).lookup<OutletContext>(OUTLET_CONTEXT))?.name;\n  }\n\n  /**\n   * Replaces named parameters in the given path with values contained in the given {@link Map}.\n   * Named parameters begin with a colon (`:`) and are allowed in path segments, query parameters, matrix parameters\n   * and the fragment part.\n   *\n   * Empty query and matrix params are removed, but not empty path params.\n   *\n   * Some examples about the usage of named parameters:\n   * /segment/:param1/segment/:param2 // path params\n   * /segment/segment;matrixParam1=:param1;matrixParam2=:param2 // matrix params\n   * /segment/segment?queryParam1=:param1&queryParam2=:param2 // query params\n   */\n  private substituteNamedParameters(path: string, params: Map<string, unknown>): string {\n    return path\n      // 1. Replace named params contained in the params map.\n      .replace(/:([^/;&?#]+)/g, (match: string, paramName: string) => params.get(paramName) !== undefined ? params.get(paramName) as string : match)\n      // 2. Remove named matrix params not contained in the params map.\n      .replace(/(?<delimiter>;)(?<paramName>[^=]+)=:(?<placeholder>[^;#?/]+)/g, () => {\n        return '';\n      })\n      // 3. Remove named query params not contained in the params map. Replaces the first query param\n      //    with a special marker for later substitution.\n      .replace(/(?<delimiter>[?&])(?<paramName>[^=]+)=:(?<placeholder>[^&#]+)/g, (match, delimiter) => {\n        return (delimiter === '?') ? 'ɵ__?__' : '';\n      })\n      // 4. Replace the marker with the question mark if at least one query parameter is present.\n      .replace(/ɵ__\\?__&/, '?')\n      // 5. Remove marker if no query params are present.\n      .replace(/ɵ__\\?__/, '');\n  }\n}\n\n/**\n * Message header with information about the current context of the navigator.\n * @internal\n */\nexport const ROUTING_CONTEXT_MESSAGE_HEADER = 'context';\n\n/**\n * Name of the current outlet if navigating in the context of an outlet.\n * @internal\n */\nexport const ROUTING_CONTEXT_OUTLET = 'outlet';\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {IntentMessage, MessageHeaders, ResponseStatusCodes} from '../../messaging.model';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {MicrofrontendCapability, PlatformCapabilityTypes} from '../../platform.model';\nimport {Handler, IntentInterceptor} from '../message-broker/message-interception';\nimport {OutletRouter, ROUTING_CONTEXT_MESSAGE_HEADER, ROUTING_CONTEXT_OUTLET} from '../../client/router-outlet/outlet-router';\nimport {NavigationOptions} from '../../client/router-outlet/metadata';\nimport {MessageClient} from '../../client/messaging/message-client';\nimport {Dictionaries} from '@scion/toolkit/util';\nimport {ApplicationRegistry} from '../application-registry';\nimport {PRIMARY_OUTLET} from '../../client/router-outlet/router-outlet.element';\n\n/**\n * Handles microfrontend intents, instructing the {@link OutletRouter} to navigate to the microfrontend of the resolved microfrontend capability.\n *\n * Microfrontend intents are handled in this interceptor in order to support microfrontends not using the SCION Microfrontend Platform.\n * They are not transported to the providing application.\n *\n * @internal\n */\nexport class MicrofrontendIntentNavigator implements IntentInterceptor {\n\n  /**\n   * Microfrontend intents are handled in this interceptor and then swallowed.\n   */\n  public intercept(intentMessage: IntentMessage, next: Handler<IntentMessage>): Promise<void> {\n    if (intentMessage.intent.type === PlatformCapabilityTypes.Microfrontend) {\n      return this.consumeMicrofrontendIntent(intentMessage as IntentMessage<NavigationOptions>);\n    }\n    else {\n      return next.handle(intentMessage);\n    }\n  }\n\n  private async consumeMicrofrontendIntent(message: IntentMessage<NavigationOptions>): Promise<void> {\n    const replyTo = message.headers.get(MessageHeaders.ReplyTo) as string;\n    await this.navigate(message);\n    await Beans.get(MessageClient).publish(replyTo, null, {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.TERMINAL)});\n  }\n\n  private async navigate(message: IntentMessage<NavigationOptions>): Promise<void> {\n    const microfrontendCapability = message.capability as Partial<MicrofrontendCapability>;\n    const options = message.body;\n    const intent = message.intent;\n\n    const microfrontendPath = microfrontendCapability.properties?.path;\n    if (!microfrontendPath && microfrontendPath !== '') { // empty path is a valid path\n      throw Error(`[OutletRouterError][NullPathError] Microfrontend capability has no path to the microfrontend defined. [capability=${JSON.stringify(microfrontendCapability)}]`);\n    }\n    const appSymbolicName = microfrontendCapability.metadata!.appSymbolicName;\n    const application = Beans.get(ApplicationRegistry).getApplication(appSymbolicName, {orElse: null});\n    if (!application) {\n      throw Error(`[OutletRouterError][NullApplicationError] Unexpected error. No application found with the symbolic name \"${appSymbolicName}\".`);\n    }\n\n    await Beans.get(OutletRouter).navigate(microfrontendPath, {\n      ...options,\n      outlet: this.resolveTargetOutlet(message),\n      relativeTo: application.baseUrl,\n      params: {...intent.qualifier, ...Dictionaries.coerce(intent.params)},\n      showSplash: microfrontendCapability.properties?.showSplash,\n      ɵcapabilityId: microfrontendCapability.metadata!.id,\n    });\n  }\n\n  /**\n   * Resolves the target outlet in the following order:\n   *\n   * - Outlet as specified by navigator via {@link NavigationOptions#outlet}.\n   * - Preferred outlet as specified in the microfrontend capability.\n   * - Current outlet if navigating in the context of an outlet.\n   * - {@link PRIMARY_OUTLET primary} outlet.\n   */\n  private resolveTargetOutlet(message: IntentMessage<NavigationOptions>): string {\n    const microfrontendCapability = message.capability as MicrofrontendCapability;\n    const options = message.body;\n\n    if (options?.outlet) {\n      return options.outlet;\n    }\n    if (microfrontendCapability.properties.outlet) {\n      return microfrontendCapability.properties.outlet;\n    }\n    const contextualOutlet = (message.headers.get(ROUTING_CONTEXT_MESSAGE_HEADER) as {[ROUTING_CONTEXT_OUTLET]: string} | undefined)?.[ROUTING_CONTEXT_OUTLET];\n    if (contextualOutlet) {\n      return contextualOutlet;\n    }\n    return PRIMARY_OUTLET;\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {Subject} from 'rxjs';\nimport {Client} from './client';\nimport {Logger, LoggingContext} from '../../logger';\nimport {ClientRegistry} from './client.registry';\n\n/**\n * @internal\n */\nexport class ɵClientRegistry implements ClientRegistry, PreDestroy {\n\n  private readonly _clientsById = new Map<string, Client>();\n  private readonly _clientsByWindow = new Map<Window, Client>();\n  public readonly register$ = new Subject<Client>();\n  public readonly unregister$ = new Subject<Client>();\n\n  public registerClient(client: Client): void {\n    const staleClient = this._clientsByWindow.get(client.window);\n    if (staleClient) {\n      Beans.get(Logger).warn(\n        `[StaleClient] Stale client registration detected when loading application '${client.application.symbolicName}'\n        into the window of '${staleClient.application.symbolicName}'. Removing stale registration. Most likely, the client could not disconnect\n        from the broker, for example, because the client was disposed without notice, i.e., without receiving the browser's \"unload\" event, or\n        because the browser discarded the 'DISCONNECT' message, maybe due to a high load on the client during unloading.`.replace(/\\s+/g, ' '),\n        new LoggingContext(staleClient.application.symbolicName, staleClient.version),\n      );\n      this.unregisterClient(staleClient);\n    }\n    this._clientsById.set(client.id, client);\n    this._clientsByWindow.set(client.window, client);\n    this.register$.next(client);\n  }\n\n  public unregisterClient(client: Client): void {\n    this._clientsById.delete(client.id);\n    this._clientsByWindow.delete(client.window);\n    this.unregister$.next(client);\n    client.dispose();\n  }\n\n  public getByClientId(clientId: string): Client | undefined {\n    return this._clientsById.get(clientId);\n  }\n\n  public getByWindow(window: Window): Client | undefined {\n    return this._clientsByWindow.get(window);\n  }\n\n  public getByApplication(appSymbolicName: string): Client[] {\n    return Array.from(this._clientsById.values()).filter(client => client.application.symbolicName === appSymbolicName);\n  }\n\n  public preDestroy(): void {\n    this._clientsById.forEach(client => this.unregisterClient(client));\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Manifest} from '../platform.model';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {ApplicationConfig} from './application-config';\nimport {HostConfig} from './host-config';\nimport {MicrofrontendPlatform} from '../microfrontend-platform';\nimport {HostManifestInterceptor} from './host-manifest-interceptor';\nimport {PlatformState} from '../platform-state';\n\n/**\n * Provides the config for the host app.\n *\n * NOTE: Use static class instead of namespace to be tree shakable, i.e., to not be included in client app.\n *\n * @internal\n */\nexport class HostAppConfigProvider {\n\n  private constructor() {\n  }\n\n  /**\n   * Creates the {@link ApplicationConfig} for the host app.\n   */\n  public static createAppConfig(hostConfig: HostConfig & {symbolicName: string}): ApplicationConfig {\n    return {\n      symbolicName: hostConfig.symbolicName,\n      manifestUrl: provideHostManifestUrl(hostConfig.manifest),\n      scopeCheckDisabled: hostConfig.scopeCheckDisabled,\n      intentionCheckDisabled: hostConfig.intentionCheckDisabled,\n      intentionRegisterApiDisabled: hostConfig.intentionRegisterApiDisabled,\n      capabilityActiveCheckDisabled: hostConfig.capabilityActiveCheckDisabled,\n    };\n  }\n\n  /**\n   * Intercepts the host manifest by registered interceptors.\n   */\n  public static interceptManifest(manifest: Manifest): void {\n    Beans.all(HostManifestInterceptor).forEach(interceptor => interceptor.intercept(manifest));\n  }\n}\n\nfunction provideHostManifestUrl(hostManifest: string | Manifest | undefined): string {\n  if (typeof hostManifest === 'string') {\n    return hostManifest; // URL specified\n  }\n  return serveHostManifest(hostManifest ?? {name: 'Host Application'});\n}\n\nfunction serveHostManifest(manifest: Manifest): string {\n  const url = URL.createObjectURL(new Blob([JSON.stringify(manifest)], {type: 'application/json'}));\n  void MicrofrontendPlatform.whenState(PlatformState.Stopped).then(() => URL.revokeObjectURL(url));\n  return url;\n}\n","/*\n * Copyright (c) 2018-2021 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {BehaviorSubject, combineLatest, OperatorFunction, Subject} from 'rxjs';\nimport {distinctUntilChanged, map, takeUntil, takeWhile} from 'rxjs/operators';\n\n/**\n * Represents a monitor to track the progress of some work.\n *\n * A monitor can be split into child monitors, allowing the work to be broken down into smaller units,\n * with each child monitor contributing to the overall progress of the parent monitor.\n *\n * @internal\n */\nexport class ProgressMonitor {\n\n  private _progress$ = new BehaviorSubject<number>(0);\n  private _done$ = new Subject<void>();\n  private _hasSubMonitors = false;\n\n  /**\n   * Reports the current progress of this monitor in percent.\n   *\n   * Upon subscription, emits the current progress, and then continuously as the progress advances.\n   * At 100%, the Observable completes.\n   */\n  public readonly progress$ = this._progress$.pipe(\n    distinctUntilChanged(),\n    map(progress => Math.round(progress * 10000) / 100),\n    takeWhile(progress => progress < 100, true),\n  );\n\n  /**\n   * Splits this monitor into separate child monitors for breaking down this monitor's work into smaller units.\n   *\n   * Each child monitor contributes to the overall progress of this monitor. The ratio allows child monitors to be\n   * weighted differently, for example, one child monitor can contribute twice as much as another to the overall progress.\n   * After all child monitors reported \"done\", this monitor will also enter \"done\".\n   */\n  public split(...ratio: number[]): ProgressMonitor[] {\n    if (this._hasSubMonitors) {\n      throw Error('[IllegalMonitorStateError] Monitor cannot be split multiple times.');\n    }\n    this._hasSubMonitors = true;\n\n    const subMonitors = ratio.map(() => new ProgressMonitor());\n    combineLatest(subMonitors.map(subMonitor => subMonitor._progress$))\n      .pipe(\n        computeProgress(ratio),\n        takeWhile(progress => progress < 1, true),\n        takeUntil(this._done$),\n      )\n      .subscribe(progress => {\n        this._progress$.next(progress);\n      });\n\n    return subMonitors;\n  }\n\n  /**\n   * Like {@link split}, but creates `n` child monitors with the same weight.\n   */\n  public splitEven(n: number): ProgressMonitor[] {\n    if (n <= 0) {\n      throw Error(`[IllegalMonitorArgumentError] Monitor split count must be greater than 0, but was ${n}.`);\n    }\n    return this.split(...new Array<number>(n).fill(1));\n  }\n\n  /**\n   * Completes this monitor, setting its progress to '100%'.\n   * Has no effect if this monitor is already \"done\".\n   */\n  public done(): void {\n    this._progress$.next(1);\n    this._done$.next();\n  }\n}\n\nfunction computeProgress(ratio: number[]): OperatorFunction<number[], number> {\n  const ratioSum = ratio.reduce((sum, weight) => sum + weight, 0);\n  return map((subMonitorsProgress: number[]) => {\n    return ratio.reduce((totalProgress, subMonitorWeight, subMonitorIndex) => {\n      return totalProgress + subMonitorsProgress[subMonitorIndex]! * (subMonitorWeight / ratioSum);\n    }, 0);\n  });\n}\n","/*\n * Copyright (c) 2018-2021 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {ProgressMonitor} from './progress-monitor';\n\n/**\n * Tracks the progress of loading application manifests.\n *\n * @internal\n */\nexport abstract class ManifestLoadProgressMonitor extends ProgressMonitor {\n}\n\n/**\n * Tracks the progress of loading application activators.\n *\n * @internal\n */\nexport abstract class ActivatorLoadProgressMonitor extends ProgressMonitor {\n}\n\n/**\n * @internal\n */\nexport abstract class StartupProgressMonitor extends ProgressMonitor {\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {HostAppConfigProvider} from './host-app-config-provider';\nimport {ManifestFetcher} from './manifest-fetcher';\nimport {ApplicationRegistry} from './application-registry';\nimport {HostConfig} from './host-config';\nimport {ApplicationConfig} from './application-config';\nimport {Logger} from '../logger';\nimport {ManifestLoadProgressMonitor} from './progress-monitor/progress-monitors';\n\n/**\n * Installs registered applications in the platform.\n *\n * @internal\n */\nexport class AppInstaller {\n\n  private readonly _appConfigs: ApplicationConfig[];\n\n  constructor(private _hostConfig: HostConfig & {symbolicName: string}, appConfigs: ApplicationConfig[]) {\n    this._appConfigs = appConfigs.filter(appConfig => !appConfig.exclude);\n  }\n\n  /**\n   * Installs registered applications in the platform.\n   */\n  public async install(): Promise<void> {\n    // Create config for the host.\n    const hostAppConfig = HostAppConfigProvider.createAppConfig(this._hostConfig);\n    const appConfigs = [hostAppConfig, ...this._appConfigs];\n    const manifestLoadMonitors = Beans.get(ManifestLoadProgressMonitor).splitEven(appConfigs.length);\n\n    // Fetch manifests and register applications.\n    await Promise.all(appConfigs.map(async appConfig => {\n      const monitor = manifestLoadMonitors.shift()!;\n      try {\n        // Fetch the manifest.\n        const manifest = await Beans.get(ManifestFetcher).fetch(appConfig);\n\n        // Let interceptors intercept the host manifest, for example by libraries integrating the SCION Microfrontend Platform,\n        // e.g., to contribute integrator-specific capabilities and intentions.\n        if (appConfig === hostAppConfig) {\n          HostAppConfigProvider.interceptManifest(manifest);\n        }\n\n        // Register application in the platform.\n        await Beans.get(ApplicationRegistry).registerApplication(appConfig, manifest);\n        Beans.get(Logger).info(`Registered application '${appConfig.symbolicName}' in the SCION Microfrontend Platform.`);\n      }\n      catch (error) {\n        Beans.get(Logger).error(`[AppInstaller] Failed to install application '${appConfig.symbolicName}' in the SCION Microfrontend Platform.`, error);\n      }\n      finally {\n        monitor.done();\n      }\n    }));\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {ACTIVATION_CONTEXT, ActivationContext, ActivatorCapability, PlatformCapabilityTypes} from '../../platform.model';\nimport {first} from 'rxjs/operators';\nimport {ApplicationRegistry} from '../application-registry';\nimport {OutletRouter} from '../../client/router-outlet/outlet-router';\nimport {SciRouterOutletElement} from '../../client/router-outlet/router-outlet.element';\nimport {Arrays, Maps} from '@scion/toolkit/util';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {Logger} from '../../logger';\nimport {MessageHeaders} from '../../messaging.model';\nimport {EMPTY, firstValueFrom, identity, Observable, timeout} from 'rxjs';\nimport {PlatformState} from '../../platform-state';\nimport {Beans, Initializer} from '@scion/toolkit/bean-manager';\nimport {MicrofrontendPlatform} from '../../microfrontend-platform';\nimport {ProgressMonitor} from '../progress-monitor/progress-monitor';\nimport {ActivatorLoadProgressMonitor} from '../progress-monitor/progress-monitors';\nimport {ManifestService} from '../../client/manifest-registry/manifest-service';\nimport {MessageClient} from '../../client/messaging/message-client';\n\n/**\n * Activates micro applications which provide an activator capability.\n *\n * Activators enable micro applications to interact with the platform for the entire platform lifecycle.\n * Activators can signal when ready for operation, causing this initializer to wait until received respective readiness messages.\n *\n * @internal\n */\nexport class ActivatorInstaller implements Initializer {\n\n  public async init(): Promise<void> {\n    // Lookup activators.\n    const activators: ActivatorCapability[] = await firstValueFrom(Beans.get(ManifestService).lookupCapabilities$<ActivatorCapability>({type: PlatformCapabilityTypes.Activator}));\n\n    const monitor = Beans.get(ActivatorLoadProgressMonitor);\n    if (!activators.length) {\n      monitor.done();\n      return;\n    }\n\n    // Group activators by their providing application.\n    const activatorsGroupedByApp: Map<string, ActivatorCapability[]> = activators\n      .filter(this.skipInvalidActivators())\n      .reduce((grouped, activator) => Maps.addListValue(grouped, activator.metadata!.appSymbolicName, activator), new Map<string, ActivatorCapability[]>());\n\n    // Create Promises that wait for activators to signal ready.\n    const subMonitors = monitor.splitEven(activatorsGroupedByApp.size);\n    const activatorReadyPromises: Promise<void>[] = Array\n      .from(activatorsGroupedByApp.entries())\n      .reduce((acc, [appSymbolicName, appActivators], index) => {\n        return acc.concat(this.waitForActivatorsToSignalReady(appSymbolicName, appActivators, subMonitors[index]!));\n      }, [] as Promise<void>[]);\n\n    // Mount activators in hidden iframes\n    activatorsGroupedByApp.forEach((sameAppActivators: ActivatorCapability[]) => {\n      // Nominate one activator of each app as primary activator.\n      const primaryActivator = sameAppActivators[0];\n      sameAppActivators.forEach(activator => this.mountActivator(activator, activator === primaryActivator));\n    });\n\n    // Wait until activators signal ready.\n    await Promise.all(activatorReadyPromises);\n  }\n\n  private skipInvalidActivators(): (activator: ActivatorCapability) => boolean {\n    return (activator: Partial<ActivatorCapability>): boolean => {\n      if (!activator.properties?.path) {\n        Beans.get(Logger).error(`[ActivatorError] Failed to activate the application '${activator.metadata!.appSymbolicName}'. Missing required 'path' property in the provided activator capability.`, activator);\n        return false;\n      }\n      return true;\n    };\n  }\n\n  /**\n   * Creates a Promise that resolves when given activators signal ready.\n   */\n  private async waitForActivatorsToSignalReady(appSymbolicName: string, activators: ActivatorCapability[], monitor: ProgressMonitor): Promise<void> {\n    const t0 = Date.now();\n    const activatorLoadTimeout = Beans.get(ApplicationRegistry).getApplication(appSymbolicName).activatorLoadTimeout;\n    const readinessPromises: Promise<void>[] = activators\n      .reduce((acc, activator) => acc.concat(Arrays.coerce(activator.properties.readinessTopics)), new Array<string>()) // concat readiness topics\n      .map(readinessTopic => {\n        const onReadinessTimeout = (): Observable<never> => {\n          Beans.get(Logger).error(`[ActivatorLoadTimeoutError] Timeout elapsed while waiting for application to signal readiness [app=${appSymbolicName}, timeout=${activatorLoadTimeout}ms, readinessTopic=${readinessTopic}].`);\n          return EMPTY;\n        };\n        return new Promise((resolve, reject) => {\n          return Beans.get(MessageClient).observe$<void>(readinessTopic)\n            .pipe(\n              first(msg => msg.headers.get(MessageHeaders.AppSymbolicName) === appSymbolicName),\n              activatorLoadTimeout ? timeout({first: activatorLoadTimeout, with: onReadinessTimeout}) : identity,\n            )\n            .subscribe({\n              error: reject,\n              complete: resolve,\n            });\n        });\n      });\n\n    if (!readinessPromises.length) {\n      monitor.done();\n      return;\n    }\n\n    await Promise.all(readinessPromises);\n    monitor.done();\n    Beans.get(Logger).info(`Activator startup of '${appSymbolicName}' took ${Date.now() - t0}ms.`);\n  }\n\n  /**\n   * Mounts a hidden <sci-router-outlet> and loads the activator endpoint.\n   */\n  private mountActivator(activator: ActivatorCapability, primary: boolean): void {\n    const application = Beans.get(ApplicationRegistry).getApplication(activator.metadata!.appSymbolicName);\n\n    // Create the router outlet and navigate to the activator endpoint.\n    const routerOutlet = document.createElement('sci-router-outlet') as SciRouterOutletElement;\n    routerOutlet.name = UUID.randomUUID();\n    void Beans.get(OutletRouter).navigate(activator.properties.path, {\n      outlet: routerOutlet.name,\n      relativeTo: application.baseUrl,\n    });\n\n    // Provide the activation context\n    routerOutlet.setContextValue<ActivationContext>(ACTIVATION_CONTEXT, {primary, activator});\n    // Add CSS classes for debugging purposes\n    routerOutlet.classList.add('sci-activator');\n    // Add custom data attribute with the application's symbolic name for debugging purposes\n    routerOutlet.dataset['app'] = application.symbolicName;\n    // Make the router outlet invisible\n    routerOutlet.style.display = 'none';\n    // Take the router outlet out of the document flow\n    routerOutlet.style.position = 'absolute';\n    // Add the router outlet to the DOM\n    document.body.appendChild(routerOutlet);\n    // Unmount the router outlet on platform shutdown\n    void MicrofrontendPlatform.whenState(PlatformState.Stopped).then(() => document.body.removeChild(routerOutlet));\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {Observable} from 'rxjs';\nimport {PlatformTopics} from '../../ɵmessaging.model';\nimport {MessageClient} from '../messaging/message-client';\nimport {mapToBody} from '../../messaging.model';\nimport {Beans} from '@scion/toolkit/bean-manager';\n\n/**\n * Allow observing whether the current microfrontend has received focus or contains embedded web content that has received focus.\n *\n * @category Focus\n */\nexport class FocusMonitor {\n\n  /**\n   * Observable that emits when the current microfrontend or any of its child microfrontends has gained or lost focus.\n   * The Observable does not emit while the focus remains within this microfrontend or any of its child microfrontends.\n   * Upon subscription, the Observable emits the current focus-within state, and then continuously emits when it changes.\n   * It never completes.\n   *\n   * This Observable is like the `:focus-within` CSS pseudo-class but operates across iframe boundaries.\n   * For example, it can be useful when implementing overlays that close upon focus loss.\n   *\n   * Note that this Observable emits only for microfrontends that are connected to the platform as registered micro app.\n   *\n   * See also the `onfocuswithin` event triggered by `<sci-router-outlet>` when embedded content has gained or lost focus.\n   */\n  public readonly focusWithin$: Observable<boolean> = Beans.get(MessageClient).request$<boolean>(PlatformTopics.IsFocusWithin).pipe(mapToBody());\n\n  /**\n   * Observable that emits when the current microfrontend has gained or lost focus.\n   *\n   * Upon subscription, the Observable emits the current focus state, and then continuously emits when it changes.\n   * It never completes.\n   */\n  public readonly focus$: Observable<boolean> = Beans.get(MessageClient).request$<boolean>(PlatformTopics.HasFocus).pipe(mapToBody());\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {EMPTY, fromEvent, race, Subject, switchMap} from 'rxjs';\nimport {takeUntil} from 'rxjs/operators';\nimport {MessageClient} from '../messaging/message-client';\nimport {PlatformTopics} from '../../ɵmessaging.model';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {FocusMonitor} from './focus-monitor';\nimport {OUTLET_CONTEXT, OutletContext, RouterOutlets} from '../router-outlet/router-outlet.element';\nimport {ContextService} from '../context/context-service';\nimport {ACTIVATION_CONTEXT} from '../../platform.model';\n\n/**\n * Sends a 'focusin' event to the topic {@link PlatformTopics.FocusIn} when this document gains focus.\n *\n * @see FocusTracker\n * @internal\n */\nexport class FocusInEventDispatcher implements PreDestroy {\n\n  private _destroy$ = new Subject<void>();\n\n  constructor() {\n    // IMPORTANT: For Angular applications, the platform is started outside the Angular zone. To avoid excessive change detection cycles,\n    // this dispatcher is eagerly set up at platform startup and installed only for regular microfrontends, not activator microfrontends.\n    void this.installFocusEventDispatcher();\n  }\n\n  /**\n   * Installs focus event dispatching, but only if not loaded as activator.\n   */\n  private async installFocusEventDispatcher(): Promise<void> {\n    if (await Beans.get(ContextService).isPresent(ACTIVATION_CONTEXT)) {\n      return;\n    }\n\n    this.publishFocusInEvent();\n    await this.notifyOutletAboutFocusChange();\n  }\n\n  /**\n   * Publishes 'focusin' events for the platform to track focus ownership.\n   */\n  private publishFocusInEvent(): void {\n    Beans.get(FocusMonitor).focus$\n      .pipe(\n        switchMap(hasFocus => hasFocus ? EMPTY : race(\n          fromEvent(window, 'focusin', {once: true}), // when gaining focus, e.g., via click on focusable element or sequential keyboard navigation\n          fromEvent(window, 'mousedown', {once: true, capture: true}), // required if \"focusin\" is not triggered, e.g., if element is not focusable or prevent default was invoked on the mousedown event\n        )),\n        takeUntil(this._destroy$),\n      )\n      .subscribe(() => void Beans.get(MessageClient).publish<void>(PlatformTopics.FocusIn));\n  }\n\n  /**\n   * Reports the embedding outlet when the current microfrontend or any of its child microfrontends has gained or lost focus.\n   * It does not report while the focus remains within this microfrontend or any of its child microfrontends.\n   */\n  private async notifyOutletAboutFocusChange(): Promise<void> {\n    const outletContext = await Beans.get(ContextService).lookup<OutletContext>(OUTLET_CONTEXT);\n    if (!outletContext) {\n      return;\n    }\n\n    Beans.get(FocusMonitor).focusWithin$\n      .pipe(takeUntil(this._destroy$))\n      .subscribe(focusWithin => {\n        const publishTo = RouterOutlets.focusWithinOutletTopic(outletContext.uid);\n        void Beans.get(MessageClient).publish<boolean>(publishTo, focusWithin);\n      });\n  }\n\n  public preDestroy(): void {\n    this._destroy$.next();\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {EMPTY, fromEvent, Subject, switchMap} from 'rxjs';\nimport {auditTime, filter, takeUntil} from 'rxjs/operators';\nimport {MessageClient} from '../messaging/message-client';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {mapToBody} from '../../messaging.model';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {ContextService} from '../context/context-service';\nimport {ACTIVATION_CONTEXT} from '../../platform.model';\nimport {FocusMonitor} from '../focus/focus-monitor';\n\n/**\n * Dispatches 'mousemove' events originating from other documents as synthetic 'sci-mousemove' events on the document event bus.\n * The events are only dispatched if the user has pressed the primary mouse button.\n *\n * Mouse event dispatching is important if having non-focusable scrollbars which are positioned at the iframe border. It enables the user\n * to scroll seamlessly even when the mouse cursor leaves the iframe.\n *\n * @internal\n */\nexport class MouseMoveEventDispatcher implements PreDestroy {\n\n  private _destroy$ = new Subject<void>();\n  private _dispatcherId = UUID.randomUUID();\n\n  constructor() {\n    // IMPORTANT: For Angular applications, the platform is started outside the Angular zone. To avoid excessive change detection cycles,\n    // this dispatcher is eagerly set up at platform startup and installed only for regular microfrontends, not activator microfrontends.\n    void this.installMouseEventDispatcher();\n  }\n\n  /**\n   * Installs mouse event dispatching, but only if not loaded as activator.\n   */\n  private async installMouseEventDispatcher(): Promise<void> {\n    if (await Beans.get(ContextService).isPresent(ACTIVATION_CONTEXT)) {\n      return;\n    }\n\n    this.publishMouseMoveEvent();\n    this.receiveMouseMoveEvent();\n  }\n\n  /**\n   * Publishes 'mousemove' events if the user has pressed the primary mouse button, but only if this document does not have the focus,\n   * so that the active document can dispatch the events on its event bus.\n   */\n  private publishMouseMoveEvent(): void {\n    Beans.get(FocusMonitor).focus$\n      .pipe(\n        switchMap(hasFocus => hasFocus ? EMPTY : fromEvent<MouseEvent>(document, 'mousemove')),\n        filter(event => event.buttons === PRIMARY_MOUSE_BUTTON),\n        auditTime(20),\n        takeUntil(this._destroy$),\n      )\n      .subscribe((event: MouseEvent) => {\n        const options = {headers: new Map().set(DISPATCHER_ID_HEADER, this._dispatcherId)};\n        void Beans.get(MessageClient).publish(MOUSEMOVE_EVENT_TOPIC, [event.screenX, event.screenY], options);\n      });\n  }\n\n  /**\n   * Receives 'mousemove' events from other documents, but only if this document has the focus, and dispatches them on the event bus.\n   */\n  private receiveMouseMoveEvent(): void {\n    // Consume synth mouse events only if owning the focus.\n    Beans.get(FocusMonitor).focus$\n      .pipe(\n        switchMap(hasFocus => hasFocus ? Beans.get(MessageClient).observe$<[number, number]>(MOUSEMOVE_EVENT_TOPIC) : EMPTY),\n        filter(msg => msg.headers.get(DISPATCHER_ID_HEADER) !== this._dispatcherId),\n        mapToBody(),\n        takeUntil(this._destroy$),\n      )\n      .subscribe(([screenX, screenY]: [number, number]) => {\n        const sciMouseEvent = new Event('sci-mousemove') as Event & {screenX: number; screenY: number};\n        sciMouseEvent.screenX = screenX;\n        sciMouseEvent.screenY = screenY;\n        document.dispatchEvent(sciMouseEvent);\n      });\n  }\n\n  public preDestroy(): void {\n    this._destroy$.next();\n  }\n}\n\n/**\n * Indicates that the primary mouse button is pressed (usually left).\n */\nconst PRIMARY_MOUSE_BUTTON = 1;\n/**\n * Message header to pass the dispatcher's identity.\n */\nconst DISPATCHER_ID_HEADER = 'ɵDISPATCHER_ID';\n/**\n * Topic to publish 'mousemove' events so that they can be consumed by dispatchers of other documents.\n */\nconst MOUSEMOVE_EVENT_TOPIC = 'ɵMOUSEMOVE';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {EMPTY, fromEvent, Subject, switchMap} from 'rxjs';\nimport {filter, takeUntil} from 'rxjs/operators';\nimport {MessageClient} from '../messaging/message-client';\nimport {UUID} from '@scion/toolkit/uuid';\nimport {mapToBody} from '../../messaging.model';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {ACTIVATION_CONTEXT} from '../../platform.model';\nimport {FocusMonitor} from '../focus/focus-monitor';\nimport {ContextService} from '../context/context-service';\n\n/**\n * Dispatches 'mouseup' events originating from other documents as synthetic 'sci-mouseup' events on the document event bus.\n *\n * Mouse event dispatching is important if having non-focusable scrollbars which are positioned at the iframe border. It enables the user\n * to scroll seamlessly even when the mouse cursor leaves the iframe.\n *\n * @internal\n */\nexport class MouseUpEventDispatcher implements PreDestroy {\n\n  private _destroy$ = new Subject<void>();\n  private _dispatcherId = UUID.randomUUID();\n\n  constructor() {\n    // IMPORTANT: For Angular applications, the platform is started outside the Angular zone. To avoid excessive change detection cycles,\n    // this dispatcher is eagerly set up at platform startup and installed only for regular microfrontends, not activator microfrontends.\n    void this.installMouseEventDispatcher();\n  }\n\n  /**\n   * Installs mouse event dispatching, but only if not loaded as activator.\n   */\n  private async installMouseEventDispatcher(): Promise<void> {\n    if (await Beans.get(ContextService).isPresent(ACTIVATION_CONTEXT)) {\n      return;\n    }\n\n    this.publishMouseUpEvent();\n    this.receiveMouseMoveEvent();\n  }\n\n  /**\n   * Publishes 'mouseup' events, but only if this document does not have the focus, so that the active document can dispatch the events on its event bus.\n   */\n  private publishMouseUpEvent(): void {\n    Beans.get(FocusMonitor).focus$\n      .pipe(\n        switchMap(hasFocus => hasFocus ? EMPTY : fromEvent(window, 'mouseup', {capture: true})),\n        takeUntil(this._destroy$),\n      )\n      .subscribe(() => {\n        const options = {headers: new Map().set(DISPATCHER_ID_HEADER, this._dispatcherId)};\n        void Beans.get(MessageClient).publish(MOUSEUP_EVENT_TOPIC, undefined, options);\n      });\n  }\n\n  /**\n   * Receives 'mouseup' events from other documents, but only if this document has the focus, and dispatches them on the event bus.\n   */\n  private receiveMouseMoveEvent(): void {\n    Beans.get(FocusMonitor).focus$\n      .pipe(\n        switchMap(hasFocus => hasFocus ? Beans.get(MessageClient).observe$<void>(MOUSEUP_EVENT_TOPIC) : EMPTY),\n        filter(msg => msg.headers.get(DISPATCHER_ID_HEADER) !== this._dispatcherId),\n        mapToBody(),\n        takeUntil(this._destroy$),\n      )\n      .subscribe(() => {\n        document.dispatchEvent(new Event('sci-mouseup'));\n      });\n  }\n\n  public preDestroy(): void {\n    this._destroy$.next();\n  }\n}\n\n/**\n * Message header to pass the dispatcher's identity.\n */\nconst DISPATCHER_ID_HEADER = 'ɵDISPATCHER_ID';\n/**\n * Topic to publish 'mouseup' events so that they can be consumed by dispatchers of other documents.\n */\nconst MOUSEUP_EVENT_TOPIC = 'ɵMOUSEUP';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {fromResize$} from '@scion/toolkit/observable';\nimport {combineLatestWith, filter, takeUntil} from 'rxjs/operators';\nimport {merge, Subject} from 'rxjs';\nimport {ContextService} from '../context/context-service';\nimport {OUTLET_CONTEXT, OutletContext, RouterOutlets} from '../router-outlet/router-outlet.element';\nimport {MessageClient} from '../messaging/message-client';\nimport {PreferredSize} from './preferred-size';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {runSafe} from '../../safe-runner';\n\n/**\n * Allows web content displayed in a {@link SciRouterOutletElement `<sci-router-outlet>`} to define its preferred size.\n *\n * The preferred size of an element is the minimum size that will allow it to display normally.\n * Setting a preferred size is useful if the outlet is displayed in a layout that aligns its items based on the items's content size.\n *\n * When setting a preferred size, the outlet containing this microfrontend will adapt its size to the reported preferred size.\n *\n * @category Preferred Size\n */\nexport class PreferredSizeService implements PreDestroy {\n\n  private _destroy$ = new Subject<void>();\n  private _fromDimensionElementChange$ = new Subject<void>();\n  private _preferredSizePublisher = new PreferredSizePublisher();\n\n  /**\n   * Sets the preferred size of this web content.\n   * The size is reported to the router outlet embedding this web content and is used as the outlet's size.\n   */\n  public setPreferredSize(preferredSize: PreferredSize): void {\n    this._preferredSizePublisher.publish(preferredSize);\n  }\n\n  /**\n   * Determines the preferred size from the given element's dimension and reports it to the router outlet embedding this web content.\n   * As the value for the preferred size, the `offset-width` and `offset-height` of the element are used, which is the total amount of space\n   * the element occupies, including the width of the visible content, scrollbars (if any), padding, and border.\n   *\n   * When the size of the element changes, the changed size is reported to the outlet, which then adaps its size accordingly.\n   * To stop the notifying of the preferred size to the outlet, pass `undefined` as the value, which also unsets the preferred size.\n   *\n   * If the element is removed from the DOM, the preferred size is reset and reporting suspended until it is attached again.\n   * If a new element is set as dimension observer, then the previous one is unsubscribed.\n   *\n   * *Prerequisites*\n   * - The element to be observed must behave as block-level box and not as inline-level box. So, if you want to observe an inline element,\n   *   set its display type to either `block` or `inline-block`.\n   * - If the element to be observed should not fill the remaining space and may change in size, we recommend taking it out of the document\n   *   element flow, i.e., position it absolutely without defining a width and height. Otherwise, once the element has reported a preferred\n   *   size, it could not shrink below that size.\n   *\n   * @param element - The element of which the preferred size is to be observed and used as the outlet's size.\n   */\n  public fromDimension(element: HTMLElement | undefined): void {\n    this._fromDimensionElementChange$.next();\n\n    if (!element) {\n      this.resetPreferredSize();\n      return;\n    }\n\n    fromResize$(element)\n      .pipe(takeUntil(merge(this._fromDimensionElementChange$, this._destroy$)))\n      .subscribe(() => {\n        // If the element is removed from the DOM, the preferred size is reset and reporting suspended until it is attached again.\n        if (!document.body.contains(element)) {\n          this.resetPreferredSize();\n        }\n        else {\n          this.setPreferredSize({\n            minWidth: `${element.offsetWidth}px`,\n            width: `${element.offsetWidth}px`,\n            maxWidth: `${element.offsetWidth}px`,\n            minHeight: `${element.offsetHeight}px`,\n            height: `${element.offsetHeight}px`,\n            maxHeight: `${element.offsetHeight}px`,\n          });\n        }\n      });\n  }\n\n  /**\n   * Resets the preferred size. Has no effect if no preferred size is set.\n   */\n  public resetPreferredSize(): void {\n    this._preferredSizePublisher.publish(null);\n  }\n\n  /** @ignore */\n  public preDestroy(): void {\n    this._preferredSizePublisher.destroy();\n    this._destroy$.next();\n  }\n}\n\n/**\n * Publishes the preferred size to the outlet embedding this page.\n */\nclass PreferredSizePublisher {\n\n  private _preferredSize$ = new Subject<PreferredSize | null>();\n  private _destroy$ = new Subject<void>();\n\n  constructor() {\n    this._preferredSize$\n      .pipe(\n        combineLatestWith(Beans.get(ContextService).observe$<OutletContext>(OUTLET_CONTEXT).pipe(filter(Boolean))),\n        takeUntil(this._destroy$),\n      )\n      .subscribe(([preferredSize, outletContext]) => runSafe(() => {\n        const topic = RouterOutlets.preferredSizeTopic(outletContext.uid);\n        void Beans.get(MessageClient).publish(topic, preferredSize);\n      }));\n  }\n\n  public publish(preferredSize: PreferredSize | null): void {\n    this._preferredSize$.next(preferredSize);\n  }\n\n  public destroy(): void {\n    this._destroy$.next();\n  }\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {fromEvent, merge, MonoTypeOperatorFunction, Observable, Subject, withLatestFrom} from 'rxjs';\nimport {filter, map, switchMap, takeUntil, tap} from 'rxjs/operators';\nimport {MessageClient} from '../messaging/message-client';\nimport {ContextService} from '../context/context-service';\nimport {KEYSTROKE_CONTEXT_NAME_PREFIX, OUTLET_CONTEXT, OutletContext, RouterOutlets} from '../router-outlet/router-outlet.element';\nimport {Keystroke, KeystrokeFlags} from './keystroke';\nimport {runSafe} from '../../safe-runner';\nimport {Beans, PreDestroy} from '@scion/toolkit/bean-manager';\nimport {filterArray, mapArray} from '@scion/toolkit/operators';\nimport {ACTIVATION_CONTEXT} from '../../platform.model';\n\n/**\n * Propagates keyboard events for keystrokes registered in the current context or any parent contexts.\n *\n * This dispatcher listens to keyboard events for keystrokes registered in parent contexts and publishes\n * them as {@link KeyboardEventInit} events to the topic {@link RouterOutlets.keyboardEventTopic}.\n *\n * @internal\n */\nexport class KeyboardEventDispatcher implements PreDestroy {\n\n  private _destroy$ = new Subject<void>();\n\n  constructor() {\n    // IMPORTANT: For Angular applications, the platform is started outside the Angular zone. To avoid excessive change detection cycles,\n    // this dispatcher is eagerly set up at platform startup and installed only for regular microfrontends, not activator microfrontends.\n    void this.installKeystrokeDispatcher();\n  }\n\n  /**\n   * Dispatches keyboard events of registered keystrokes to the embedding router outlet.\n   */\n  private async installKeystrokeDispatcher(): Promise<void> {\n    if (!await Beans.get(ContextService).isPresent(OUTLET_CONTEXT) || await Beans.get(ContextService).isPresent(ACTIVATION_CONTEXT)) {\n      return;\n    }\n\n    Beans.get(ContextService).names$()\n      .pipe(\n        map(contextNames => Array.from(contextNames)),\n        filterArray(contextName => contextName.startsWith(KEYSTROKE_CONTEXT_NAME_PREFIX)),\n        mapArray(keystrokeContextName => keystrokeContextName.substring(KEYSTROKE_CONTEXT_NAME_PREFIX.length)),\n        mapArray(keystroke => this.observeKeyboardEvent$(keystroke)),\n        switchMap(keyboardEvents => merge(...keyboardEvents)),\n        withLatestFrom(Beans.get(ContextService).observe$<OutletContext>(OUTLET_CONTEXT)),\n        takeUntil(this._destroy$),\n      )\n      .subscribe(([event, outletContext]) => runSafe(() => {\n        const eventInit: KeyboardEventInit = {\n          key: event.key,\n          ctrlKey: event.ctrlKey,\n          shiftKey: event.shiftKey,\n          altKey: event.altKey,\n          metaKey: event.metaKey,\n          bubbles: event.bubbles,\n          location: event.location,\n        };\n\n        const publishTo = RouterOutlets.keyboardEventTopic(outletContext!.uid, event.type);\n        void Beans.get(MessageClient).publish<KeyboardEventInit>(publishTo, eventInit);\n      }));\n  }\n\n  /**\n   * Observes keyboard events matching the given keystroke, applying flags as declared on the keystroke.\n   */\n  private observeKeyboardEvent$(keystrokeFormat: string): Observable<KeyboardEvent> {\n    return Beans.get(ContextService).observe$<KeystrokeFlags>(KEYSTROKE_CONTEXT_NAME_PREFIX + keystrokeFormat, {collect: true})\n      .pipe(switchMap((keystrokeFlags: KeystrokeFlags[]) => {\n        const keystroke = Keystroke\n          .fromString(keystrokeFormat)\n          .withFlags(keystrokeFlags.reduceRight<KeystrokeFlags>((acc, flags) => ({...acc, ...flags}), {}));\n        return fromEvent<KeyboardEvent>(document, keystroke.eventType, {capture: true})\n          .pipe(\n            filter(event => event.bubbles && !!event.key),\n            filter(event => Keystroke.fromEvent(event).parts === keystroke.parts),\n            applyKeystrokeFlags(keystroke.flags),\n          );\n      }));\n  }\n\n  public preDestroy(): void {\n    this._destroy$.next();\n  }\n}\n\n/**\n * Applies keystroke flags on each keyboard event emitted by the source Observable.\n *\n * Note that `preventDefault()` has to be invoked on the original event, which has its `isTrusted` flag set to `true`.\n *\n * For more information about trusted events\n * @see https://www.w3.org/TR/DOM-Level-3-Events/#trusted-events\n * @see https://www.chromestatus.com/features#istrusted\n */\nfunction applyKeystrokeFlags(flags: KeystrokeFlags | undefined): MonoTypeOperatorFunction<KeyboardEvent> {\n  return tap(keystrokeEvent => {\n    if (flags?.preventDefault) {\n      keystrokeEvent.preventDefault();\n    }\n  });\n}\n","import {MessageClient, takeUntilUnsubscribe} from './message-client';\nimport {Message, MessageHeaders, ResponseStatusCodes} from '../../messaging.model';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {EMPTY, from, Observable, of, Subscription, throwError} from 'rxjs';\nimport {runSafe} from '../../safe-runner';\nimport {stringifyError} from '../../error.util';\nimport {filter, finalize, takeUntil} from 'rxjs/operators';\nimport {MicrofrontendPlatform} from '../../microfrontend-platform';\nimport {PlatformState} from '../../platform-state';\n\n/**\n * Subscribes to messages, passing each message to the callback.\n *\n * The callback can return a response to be transported to the requestor, if any. When the final response is produced,\n * the handler terminates the communication, completing the requestor's Observable. If the callback errors, the error is\n * transported to the requestor, erroring the requestor's Observable.\n *\n * @internal\n */\nexport class MessageHandler<MSG extends Message, REPLY> {\n\n  private _messageClient = Beans.get(MessageClient);\n\n  /**\n   * Represents this handler's subscription for receiving messages. Calling {@link Subscription.unsubscribe} will also complete\n   * the Observable of all requestors, if any.\n   */\n  public readonly subscription = new Subscription();\n\n  constructor(message$: Observable<MSG>, private _callback: (message: MSG) => Observable<REPLY> | Promise<REPLY> | REPLY | void) {\n    this.subscription.add(message$.subscribe(message => {\n      if (message.headers.has(MessageHeaders.ReplyTo)) {\n        this.handleMessage(message);\n      }\n      else {\n        this.consumeMessage(message);\n      }\n    }));\n  }\n\n  /**\n   * The requestor has initiated a fire-and-forget communication, thus we simply pass the message to the callback and ignore response(s).\n   */\n  private consumeMessage(message: MSG): void {\n    void runSafe(() => this._callback(message));\n  }\n\n  /**\n   * The requestor has initiated a request-response communication, thus we pass the request to the callback and send response(s)\n   * or a potential completion or error to the requestor.\n   */\n  private handleMessage(request: MSG): void {\n    const replyTo = request.headers.get(MessageHeaders.ReplyTo) as string;\n    const platformStopping$ = MicrofrontendPlatform.state$.pipe(filter(state => state === PlatformState.Stopping));\n\n    // Invoke the callback to produce value(s).\n    let reply: Observable<REPLY> | Promise<REPLY> | REPLY | void;\n    try {\n      reply = this._callback(request);\n    }\n    catch (error) {\n      reply = throwError(() => error);\n    }\n\n    // Send response(s) or a potential completion or error back to the requestor.\n    let observableStatus: 'alive' | 'completed' | 'errored' = 'alive';\n    this.subscription.add(fromCallbackResult$(reply)\n      .pipe(\n        takeUntilUnsubscribe(replyTo), // unsubscribe once the requestor terminates the communication\n        takeUntil(platformStopping$), // terminate the communication when the platform is shutting down.\n        finalize(() => {\n          // Note that the `finalize` operator is also called when unsubscribing from the observable, e.g. when unsubscribing\n          // from the handler. If the observable errors or completes, the `finalize` operator is guaranteed to be called after\n          // the observer's `complete` or `error` methods; thus, the variable `observableStatus` is only `alive` when\n          // unsubscribing from the observable.\n          if (observableStatus === 'alive') {\n            // Terminate the communication when the handler is being unsubscribed.\n            const replyHeaders = new Map().set(MessageHeaders.Status, ResponseStatusCodes.TERMINAL);\n            void this._messageClient.publish(replyTo, undefined, {headers: replyHeaders});\n          }\n        }),\n      )\n      .subscribe({\n        next: next => {\n          // Transport the value to the requestor.\n          const replyHeaders = new Map().set(MessageHeaders.Status, ResponseStatusCodes.OK);\n          void this._messageClient.publish(replyTo, next, {headers: replyHeaders});\n        },\n        error: error => {\n          observableStatus = 'errored';\n          // Transport the error to the requestor.\n          const replyHeaders = new Map().set(MessageHeaders.Status, ResponseStatusCodes.ERROR);\n          void this._messageClient.publish(replyTo, stringifyError(error), {headers: replyHeaders});\n        },\n        complete: () => {\n          observableStatus = 'completed';\n          // Terminate the communication when finished producing responses.\n          const replyHeaders = new Map().set(MessageHeaders.Status, ResponseStatusCodes.TERMINAL);\n          void this._messageClient.publish(replyTo, undefined, {headers: replyHeaders});\n        },\n      }));\n  }\n}\n\n/**\n * Creates an Observable from the result of the callback.\n *\n * If the callback returns no value (`void`), returns `undefined`, or returns a Promise that resolves to `undefined`,\n * the returned observable will complete immediately.\n */\nfunction fromCallbackResult$<T>(value: T | Observable<T> | Promise<T>): Observable<T> {\n  if (value === undefined) {\n    return EMPTY;\n  }\n  if (value instanceof Observable) {\n    return value;\n  }\n  if (value instanceof Promise) {\n    return from(value).pipe(filter(resolved => resolved !== undefined));\n  }\n  return of(value);\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {defer, noop, Observable, Subject, Subscription} from 'rxjs';\nimport {mapToBody, throwOnErrorStatus, TopicMessage} from '../../messaging.model';\nimport {BrokerGateway} from './broker-gateway';\nimport {MessagingChannel, PlatformTopics, TopicSubscribeCommand} from '../../ɵmessaging.model';\nimport {MessageClient} from './message-client';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {MessageHandler} from './message-handler';\nimport {takeUntil} from 'rxjs/operators';\nimport {PublishOptions, RequestOptions} from './publish-options';\n\n/**\n * @internal\n */\nexport class ɵMessageClient implements MessageClient {\n\n  private readonly _brokerGateway = Beans.get(BrokerGateway);\n\n  public publish<T = unknown>(topic: string, message?: T, options?: PublishOptions): Promise<void> {\n    const topicMessage: TopicMessage = {\n      topic,\n      retain: options?.retain ?? false,\n      headers: new Map(options?.headers),\n      body: message,\n    };\n    return this._brokerGateway.postMessage(MessagingChannel.Topic, topicMessage);\n  }\n\n  public request$<T>(topic: string, request?: unknown, options?: RequestOptions): Observable<TopicMessage<T>> {\n    // IMPORTANT:\n    // When sending a request, the platform adds various headers to the message. Therefore, to support multiple subscriptions\n    // to the returned Observable, each subscription must have its individual message instance and headers map.\n    // In addition, the headers are copied to prevent modifications before the effective subscription.\n    const headers = new Map(options?.headers);\n    return defer(() => {\n      const topicMessage: TopicMessage = {\n        topic,\n        retain: options?.retain ?? false,\n        headers: new Map(headers), /* make a copy for each subscription to support multiple subscriptions */\n        body: request,\n      };\n      return this._brokerGateway.requestReply$<T>(MessagingChannel.Topic, topicMessage).pipe(throwOnErrorStatus());\n    });\n  }\n\n  public observe$<T>(topic: string): Observable<TopicMessage<T>> {\n    return this._brokerGateway.subscribe$({\n      messageChannel: MessagingChannel.Topic,\n      subscribeChannel: MessagingChannel.TopicSubscribe,\n      unsubscribeChannel: MessagingChannel.TopicUnsubscribe,\n      newSubscribeCommand: (subscriberId: string): TopicSubscribeCommand => ({topic, subscriberId, headers: new Map()}),\n    });\n  }\n\n  public onMessage<IN = unknown, OUT = unknown>(topic: string, callback: (message: TopicMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription {\n    return new MessageHandler(Beans.get(MessageClient).observe$<IN>(topic), callback).subscription;\n  }\n\n  public subscriberCount$(topic: string): Observable<number> {\n    return new Observable<number>(observer => {\n      const unsubscribe$ = new Subject<void>();\n      this.request$<number>(PlatformTopics.RequestSubscriberCount, topic)\n        .pipe(\n          mapToBody(),\n          takeUntil(unsubscribe$),\n        )\n        .subscribe({\n          next: reply => observer.next(reply),\n          error: error => observer.error(error),\n          complete: noop, // As per the API, the Observable never completes, even if receiving a TERMINAL signal.\n        });\n      return (): void => unsubscribe$.next();\n    });\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {defer, Observable, Subscription} from 'rxjs';\nimport {Intent, IntentMessage, throwOnErrorStatus, TopicMessage} from '../../messaging.model';\nimport {BrokerGateway} from './broker-gateway';\nimport {IntentSubscribeCommand, MessagingChannel} from '../../ɵmessaging.model';\nimport {IntentClient, IntentSelector} from './intent-client';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {MessageHandler} from './message-handler';\nimport {PublishOptions, RequestOptions} from './publish-options';\n\n/**\n * @internal\n */\nexport class ɵIntentClient implements IntentClient {\n\n  private readonly _brokerGateway = Beans.get(BrokerGateway);\n\n  public publish<T = unknown>(intent: Intent, body?: T, options?: PublishOptions): Promise<void> {\n    const intentMessage: IntentMessage = {\n      intent,\n      retain: options?.retain ?? false,\n      headers: new Map(options?.headers),\n      capability: undefined!, /* set by the broker when dispatching the intent */\n      body,\n    };\n    return this._brokerGateway.postMessage(MessagingChannel.Intent, intentMessage);\n  }\n\n  public request$<T>(intent: Intent, body?: unknown, options?: RequestOptions): Observable<TopicMessage<T>> {\n    // IMPORTANT:\n    // When sending a request, the platform adds various headers to the message. Therefore, to support multiple subscriptions\n    // to the returned Observable, each subscription must have its individual message instance and headers map.\n    // In addition, the headers are copied to prevent modifications before the effective subscription.\n    const headers = new Map(options?.headers);\n    return defer(() => {\n      const intentMessage: IntentMessage = {\n        intent,\n        retain: options?.retain ?? false,\n        headers: new Map(headers) /* make a copy for each subscription to support multiple subscriptions */,\n        capability: undefined!, /* set by the broker when dispatching the intent */\n        body,\n      };\n      return this._brokerGateway.requestReply$<T>(MessagingChannel.Intent, intentMessage).pipe(throwOnErrorStatus());\n    });\n  }\n\n  public observe$<T>(selector?: IntentSelector): Observable<IntentMessage<T>> {\n    return this._brokerGateway.subscribe$({\n      messageChannel: MessagingChannel.Intent,\n      subscribeChannel: MessagingChannel.IntentSubscribe,\n      unsubscribeChannel: MessagingChannel.IntentUnsubscribe,\n      newSubscribeCommand: (subscriberId: string): IntentSubscribeCommand => ({selector, subscriberId, headers: new Map()}),\n    });\n  }\n\n  public onIntent<IN = unknown, OUT = unknown>(selector: IntentSelector, callback: (intentMessage: IntentMessage<IN>) => Observable<OUT> | Promise<OUT> | OUT | void): Subscription {\n    return new MessageHandler(Beans.get(IntentClient).observe$<IN>(selector), callback).subscription;\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {BeanDestroyOrders, MicrofrontendPlatform, providePlatformEnvironment} from '../microfrontend-platform';\nimport {ConnectOptions} from './connect-options';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {PlatformPropertyService} from '../platform-property-service';\nimport {MessageClient} from './messaging/message-client';\nimport {IntentClient} from './messaging/intent-client';\nimport {OutletRouter} from './router-outlet/outlet-router';\nimport {RelativePathResolver} from './router-outlet/relative-path-resolver';\nimport {RouterOutletUrlAssigner} from './router-outlet/router-outlet-url-assigner';\nimport {FocusInEventDispatcher} from './focus/focus-in-event-dispatcher';\nimport {FocusMonitor} from './focus/focus-monitor';\nimport {MouseMoveEventDispatcher} from './mouse-event/mouse-move-event-dispatcher';\nimport {MouseUpEventDispatcher} from './mouse-event/mouse-up-event-dispatcher';\nimport {PreferredSizeService} from './preferred-size/preferred-size-service';\nimport {ContextService} from './context/context-service';\nimport {ManifestService} from './manifest-registry/manifest-service';\nimport {KeyboardEventDispatcher} from './keyboard-event/keyboard-event-dispatcher';\nimport {PlatformState, Runlevel} from '../platform-state';\nimport {OUTLET_CONTEXT, OutletContext, RouterOutlets, SciRouterOutletElement} from './router-outlet/router-outlet.element';\nimport {BrokerGateway, NullBrokerGateway, ɵBrokerGateway} from './messaging/broker-gateway';\nimport {ɵMessageClient} from './messaging/ɵmessage-client';\nimport {ɵIntentClient} from './messaging/ɵintent-client';\n\n/**\n * Central point for a microfrontend to connect to the platform host in order to interact with the platform and other microfrontends.\n * This class cannot be instantiated. All functionality is provided by static methods.\n *\n * @see MicrofrontendPlatform\n * @see MicrofrontendPlatformHost\n * @see MicrofrontendPlatformClient\n *\n * @category Platform\n * @category Lifecycle\n */\nexport class MicrofrontendPlatformClient {\n\n  private constructor() {\n  }\n\n  /**\n   * Connects this microfrontend to the platform host.\n   *\n   * A microfrontend should connect to the platform host during application bootstrapping. In Angular, for example, this is typically\n   * done in an app initializer. Since connecting to the platform host is an asynchronous operation, the microfrontend should wait\n   * for the Promise to resolve before interacting with the platform or other microfrontends.\n   *\n   * The platform connects to the host through its window hierarchy. Therefore, the microfrontend must be embedded as direct or\n   * indirect child window of the host application window.\n   *\n   * @param  symbolicName - Specifies the symbolic name of the application of this microfrontend. The application must be registered\n   *         in the platform host under this symbol.\n   * @param  connectOptions - Controls how to connect to the platform host.\n   * @return Promise that resolves when successfully connected to the platform host, or that rejects otherwise, e.g., if not allowed\n   *         to connect because not registered.\n   */\n  public static connect(symbolicName: string, connectOptions?: ConnectOptions): Promise<void> {\n    return MicrofrontendPlatform.startPlatform(() => {\n      // Provide environment for running the platform as client.\n      providePlatformEnvironment({symbolicName, isPlatformHost: false});\n      provideClientEnvironment({...connectOptions, connectRunlevel: Runlevel.Zero});\n\n      // Provide initializers to start the platform as client.\n      provideClientStartupInitializers();\n    });\n  }\n\n  /**\n   * Tests whether this microfrontend is connected to the platform host.\n   */\n  public static async isConnected(): Promise<boolean> {\n    if (MicrofrontendPlatform.state === PlatformState.Stopped) {\n      return false;\n    }\n    const brokerGateway = Beans.opt(BrokerGateway);\n    if (!brokerGateway) {\n      return false;\n    }\n    return brokerGateway.isConnected();\n  }\n\n  /**\n   * Signals readiness to notify the platform that the microfrontend has completed initialization.\n   *\n   * When navigating to the microfrontend with `OutletRouter.navigate('path/to/microfrontend', {showSplash: true})`,\n   * a splash is displayed until the microfrontend signals readiness.\n   *\n   * @see SciRouterOutletElement\n   * @see NavigationOptions.showSplash\n   */\n  public static signalReady(): void {\n    void Beans.get(ContextService).lookup<OutletContext>(OUTLET_CONTEXT).then(outletContext => {\n      if (!outletContext) {\n        return Promise.reject(Error('[NullOutletContextError] not running in the context of a <sci-router-outlet>.'));\n      }\n      return Beans.get(MessageClient).publish(RouterOutlets.signalReadyTopic(outletContext.uid));\n    });\n  }\n}\n\n/**\n * Provides the environment for running the platform as client.\n *\n * @internal\n */\nexport function provideClientEnvironment(connectOptions: ConnectOptions & {connectRunlevel: number}): void {\n  Beans.registerIfAbsent(MessageClient, {useClass: ɵMessageClient, eager: true, destroyOrder: BeanDestroyOrders.MESSAGING});\n  Beans.registerIfAbsent(IntentClient, {useClass: ɵIntentClient, eager: true, destroyOrder: BeanDestroyOrders.MESSAGING});\n  Beans.registerIfAbsent(OutletRouter);\n  Beans.registerIfAbsent(RelativePathResolver);\n  Beans.registerIfAbsent(RouterOutletUrlAssigner);\n  Beans.register(FocusInEventDispatcher, {eager: true});\n  Beans.register(MouseMoveEventDispatcher, {eager: true});\n  Beans.register(MouseUpEventDispatcher, {eager: true});\n  Beans.register(KeyboardEventDispatcher, {eager: true});\n  Beans.register(PreferredSizeService, {eager: true});\n  Beans.register(ContextService);\n  Beans.register(ManifestService);\n  Beans.register(PlatformPropertyService);\n  Beans.register(FocusMonitor);\n  provideBrokerGateway(connectOptions);\n}\n\n/**\n * Provide initializers to start the platform as client.\n */\nfunction provideClientStartupInitializers(): void {\n  // Block until received platform properties to support synchronous access via `PlatformPropertyService#properties`.\n  Beans.registerInitializer({\n    useExisting: PlatformPropertyService,\n    runlevel: Runlevel.Two,\n  });\n\n  // Block until received list of applications to support synchronous access via `ManifestService#applications`.\n  Beans.registerInitializer({\n    useExisting: ManifestService,\n    runlevel: Runlevel.Two,\n  });\n\n  // Register router outlet, delaying its instantiation until initialized the platform.\n  // Otherwise, router outlet construction may fail or result in unexpected behavior, for example, because beans are not yet registered.\n  Beans.registerInitializer({\n    useFunction: () => SciRouterOutletElement.define(),\n    runlevel: Runlevel.Two,\n  });\n}\n\n/**\n * Provides the gateway to communicate with the host.\n */\nfunction provideBrokerGateway(connectOptions: ConnectOptions & {connectRunlevel: number}): void {\n  if (connectOptions.connect ?? true) {\n    Beans.register(ɵBrokerGateway, {\n      useFactory: () => new ɵBrokerGateway(connectOptions),\n      destroyOrder: BeanDestroyOrders.MESSAGING,\n    });\n    Beans.register(BrokerGateway, {useExisting: ɵBrokerGateway});\n    Beans.registerInitializer({useExisting: ɵBrokerGateway, runlevel: connectOptions.connectRunlevel});\n  }\n  else {\n    Beans.register(BrokerGateway, {useClass: NullBrokerGateway});\n  }\n}\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\nimport {MicrofrontendPlatformConfig} from './microfrontend-platform-config';\nimport {HostManifestInterceptor, ɵHostManifestInterceptor} from './host-manifest-interceptor';\nimport {BeanDestroyOrders, MicrofrontendPlatform, providePlatformEnvironment} from '../microfrontend-platform';\nimport {Beans} from '@scion/toolkit/bean-manager';\nimport {ClientRegistry} from './client-registry/client.registry';\nimport {Logger} from '../logger';\nimport {PlatformPropertyService} from '../platform-property-service';\nimport {HttpClient} from './http-client';\nimport {ManifestRegistry} from './manifest-registry/manifest-registry';\nimport {ApplicationRegistry} from './application-registry';\nimport {ɵManifestRegistry} from './manifest-registry/ɵmanifest-registry';\nimport {FocusTracker} from './focus/focus-tracker';\nimport {ManifestFetcher} from './manifest-fetcher';\nimport {MessageBroker} from './message-broker/message-broker';\nimport {TopicSubscriptionRegistry} from './message-broker/topic-subscription.registry';\nimport {IntentSubscriptionRegistry} from './message-broker/intent-subscription.registry';\nimport {ManifestService} from '../client/manifest-registry/manifest-service';\nimport {IntentInterceptor} from './message-broker/message-interception';\nimport {MicrofrontendIntentNavigator} from './router/microfrontend-intent-navigator.interceptor';\nimport {ɵClientRegistry} from './client-registry/ɵclient.registry';\nimport {MessageClient} from '../client/messaging/message-client';\nimport {PlatformState, Runlevel} from '../platform-state';\nimport {CLIENT_PING_INTERVAL, CLIENT_PING_TIMEOUT} from './client-registry/client';\nimport {LivenessConfig} from './liveness-config';\nimport {AppInstaller} from './app-installer';\nimport {ActivatorInstaller} from './activator/activator-installer';\nimport {PlatformTopics} from '../ɵmessaging.model';\nimport {SciRouterOutletElement} from '../client/router-outlet/router-outlet.element';\nimport {ProgressMonitor} from './progress-monitor/progress-monitor';\nimport {ActivatorLoadProgressMonitor, ManifestLoadProgressMonitor, StartupProgressMonitor} from './progress-monitor/progress-monitors';\nimport {provideClientEnvironment} from '../client/microfrontend-platform-client';\nimport {defer, Observable, ReplaySubject} from 'rxjs';\nimport {takeUntil} from 'rxjs/operators';\n\n/**\n * Main entry point for configuring and starting the platform in the host application. This class cannot be instantiated. All functionality is provided by static methods.\n *\n * The host application, sometimes also called the container application, provides the top-level integration container for microfrontends. Typically, it is the web\n * application which the user loads into the browser that provides the main application shell, defining areas to embed microfrontends.\n *\n * In the host application the SCION Microfrontend Platform is configured and web applications that want to interact with the platform are registered.\n * The host application can provide a manifest to contribute behavior to integrated applications. For more information, see {@link HostConfig.manifest}\n * in {@link MicrofrontendPlatformConfig.host}.\n *\n * If integrating the SCION Microfrontend Platform in a library, the manifest of the host can be augmented by registering a {@link HostManifestInterceptor}.\n *\n * @see MicrofrontendPlatform\n * @see MicrofrontendPlatformHost\n * @see MicrofrontendPlatformClient\n *\n * @category Platform\n * @category Lifecycle\n */\nexport class MicrofrontendPlatformHost {\n\n  private static _startupProgress$: Observable<number> | undefined;\n\n  private constructor() {\n  }\n\n  /**\n   * Starts the platform host.\n   *\n   * In the host application the SCION Microfrontend Platform is configured and web applications that want to interact with the platform are registered.\n   *\n   * The host application can provide a manifest to declare intentions and contribute behavior to integrated applications via {@link HostConfig.manifest} in\n   * {@link MicrofrontendPlatformConfig.host}. The manifest can be specified either as an object literal or as a URL to load it over the network.\n   *\n   * The platform should be started during the bootstrapping of the host application. In Angular, for example, the platform is typically\n   * started in an app initializer. Since starting the platform host may take some time, you should wait for the startup Promise to resolve\n   * before interacting with the platform.\n   *\n   * @param  config - Configures the platform and lists applications allowed to interact with the platform.\n   * @return A Promise that resolves when started the platform host.\n   */\n  public static start(config: MicrofrontendPlatformConfig): Promise<void> {\n    return MicrofrontendPlatform.startPlatform(() => {\n      const symbolicName = config.host?.symbolicName ?? 'host';\n\n      // Provide environment for running the platform as host.\n      providePlatformEnvironment({symbolicName, isPlatformHost: true});\n      provideClientEnvironment({\n        messageDeliveryTimeout: config.host?.messageDeliveryTimeout,\n        brokerDiscoverTimeout: config.host?.brokerDiscoverTimeout,\n        connectRunlevel: Runlevel.One, // Connect to the broker in runlevel 1, that is, after registration of the applications.\n      });\n      provideHostEnvironment(config);\n\n      // Provide initializers to start the platform as host.\n      provideHostStartupInitializers(symbolicName, config);\n    });\n  }\n\n  /**\n   * Monitors the startup progress of the platform host.\n   *\n   * Starting the platform host may take some time. During startup, the manifests of the registered applications are fetched,\n   * activator microfrontends are installed, and the platform waits until all applications have signaled readiness.\n   *\n   * Subscribe to this Observable to monitor the startup progress and provide feedback to the user like displaying a\n   * progress bar or a spinner. The Observable reports the progress as a percentage number. The Observable completes\n   * after the platform has been started.\n   */\n  public static get startupProgress$(): Observable<number> {\n    this._startupProgress$ = this._startupProgress$ ?? new Observable<number>(observer => {\n      const unsubscribe$ = new ReplaySubject<void>(1);\n      const progress$ = defer(() => Beans.get(StartupProgressMonitor).progress$).pipe(takeUntil(unsubscribe$));\n\n      if (MicrofrontendPlatform.state === PlatformState.Stopped) {\n        void MicrofrontendPlatform.whenState(PlatformState.Starting).then(() => progress$.subscribe(observer));\n      }\n      else {\n        progress$.subscribe(observer);\n      }\n      return () => unsubscribe$.next();\n    });\n    return this._startupProgress$;\n  }\n}\n\n/**\n * Provides the environment for running the platform as host.\n */\nfunction provideHostEnvironment(config: MicrofrontendPlatformConfig): void {\n  Beans.register(MicrofrontendPlatformConfig, {useValue: config});\n  Beans.register(HostManifestInterceptor, {useClass: ɵHostManifestInterceptor, multi: true});\n  Beans.register(ClientRegistry, {useClass: ɵClientRegistry, destroyOrder: BeanDestroyOrders.CORE});\n  Beans.registerIfAbsent(HttpClient);\n  Beans.register(ManifestRegistry, {useClass: ɵManifestRegistry, eager: true});\n  Beans.register(ApplicationRegistry, {eager: true});\n  Beans.register(FocusTracker, {eager: true});\n  Beans.register(MessageBroker, {destroyOrder: BeanDestroyOrders.BROKER});\n  Beans.register(ManifestFetcher);\n  Beans.register(TopicSubscriptionRegistry, {destroyOrder: BeanDestroyOrders.BROKER});\n  Beans.register(IntentSubscriptionRegistry, {destroyOrder: BeanDestroyOrders.BROKER});\n  Beans.register(IntentInterceptor, {useClass: MicrofrontendIntentNavigator, multi: true});\n\n  provideLivenessProbeConfig(config.liveness);\n  provideStartupProgressMonitor();\n}\n\n/**\n * Provide initializers to start the platform as host.\n */\nfunction provideHostStartupInitializers(symbolicName: string, config: MicrofrontendPlatformConfig): void {\n  // Construct message broker immediately to not lose connect requests from clients.\n  Beans.registerInitializer({\n    useExisting: MessageBroker,\n    runlevel: Runlevel.Zero,\n  });\n\n  // Install registered applications.\n  Beans.registerInitializer({\n    useFunction: () => new AppInstaller({...config.host, symbolicName}, config.applications).install(),\n    runlevel: Runlevel.Zero,\n  });\n\n  // Provide platform properties to clients.\n  Beans.registerInitializer({\n    useFunction: () => Beans.get(MessageClient).publish(PlatformTopics.PlatformProperties, config.properties ?? {}, {retain: true}),\n    runlevel: Runlevel.Two,\n  });\n\n  // Provide list of installed applications to clients.\n  Beans.registerInitializer({\n    useFunction: () => Beans.get(MessageClient).publish(PlatformTopics.Applications, Beans.get(ApplicationRegistry).getApplications(), {retain: true}),\n    runlevel: Runlevel.Two,\n  });\n\n  // Register router outlet, delaying its instantiation until initialized the platform.\n  // Otherwise, router outlet construction may fail or result in unexpected behavior, for example, because beans are not yet registered.\n  Beans.registerInitializer({\n    useFunction: () => SciRouterOutletElement.define(),\n    runlevel: Runlevel.Two,\n  });\n\n  // Block until received platform properties to support synchronous access via `PlatformPropertyService#properties`.\n  Beans.registerInitializer({\n    useExisting: PlatformPropertyService,\n    runlevel: Runlevel.Three,\n  });\n\n  // Block until received list of applications to support synchronous access via `ManifestService#applications`.\n  Beans.registerInitializer({\n    useExisting: ManifestService,\n    runlevel: Runlevel.Three,\n  });\n\n  // Install activator microfrontends.\n  Beans.registerInitializer({\n    useClass: ActivatorInstaller,\n    runlevel: Runlevel.Three,\n  });\n}\n\n/**\n * Provides beans to monitor the startup progress of the host.\n */\nfunction provideStartupProgressMonitor(): void {\n  const monitor = new ProgressMonitor();\n  const [platformProgressMonitor, manifestLoadProgressMonitor, activatorLoadProgressMonitor] = monitor.split(1, 3, 5) as [ProgressMonitor, ProgressMonitor, ProgressMonitor];\n  Beans.register(StartupProgressMonitor, {useValue: monitor});\n  Beans.register(ManifestLoadProgressMonitor, {useValue: manifestLoadProgressMonitor});\n  Beans.register(ActivatorLoadProgressMonitor, {useValue: activatorLoadProgressMonitor});\n  void MicrofrontendPlatform.whenState(PlatformState.Started).then(() => platformProgressMonitor.done());\n}\n\n/**\n * Provides beans describing how often to check connected clients to be alive.\n */\nfunction provideLivenessProbeConfig(config?: LivenessConfig): void {\n  const defaults = {interval: 60, timeout: 10};\n  const interval = config?.interval ?? defaults.interval;\n  const timeout = config?.timeout ?? defaults.timeout;\n\n  const invalid = interval <= 2 * timeout;\n  if (invalid) {\n    Beans.get(Logger).warn(`[LivenessProbeConfig] Illegal config provided. The interval [${interval}s] must be greater than twice the timeout period [${timeout}s]. Using platform defaults instead: [interval=${defaults.interval}s, timeout=${defaults.timeout}s]`);\n  }\n  Beans.registerIfAbsent(CLIENT_PING_INTERVAL, {useValue: (invalid ? defaults.interval : interval) * 1_000});\n  Beans.registerIfAbsent(CLIENT_PING_TIMEOUT, {useValue: (invalid ? defaults.timeout : timeout) * 1_000});\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nimport {Manifest} from '../platform.model';\n\n/**\n * Configures the interaction of the host application with the platform.\n *\n * As with micro applications, you can provide a manifest for the host, allowing the host to contribute capabilities and declare intentions.\n *\n * @category Platform\n */\nexport interface HostConfig {\n  /**\n   * Symbolic name of the host. If not set, 'host' is used as the symbolic name of the host.\n   *\n   * The symbolic name must be unique and contain only lowercase alphanumeric characters and hyphens.\n   */\n  symbolicName?: string;\n  /**\n   * The manifest of the host.\n   *\n   * The manifest can be passed either as an {@link Manifest object literal} or specified as a URL to be loaded over the network.\n   * Providing a manifest lets the host contribute capabilities or declare intentions.\n   */\n  readonly manifest?: Manifest | string;\n  /**\n   * Allows the host to access private capabilities of other applications.\n   *\n   * Disabling this check is discouraged. Enabled by default.\n   */\n  readonly scopeCheckDisabled?: boolean;\n  /**\n   * Allows the host to access public capabilities of other applications without declaring an intention.\n   *\n   * Disabling this check is discouraged. Enabled by default.\n   */\n  readonly intentionCheckDisabled?: boolean;\n  /**\n   * Allows the host to access inactive capabilities.\n   *\n   * Disabling this check is discouraged. Enabled by default.\n   */\n  readonly capabilityActiveCheckDisabled?: boolean;\n  /**\n   * Allows the host to register and unregister intentions at runtime.\n   *\n   * Enabling this API is discouraged. Disabled by default.\n   */\n  readonly intentionRegisterApiDisabled?: boolean;\n  /**\n   * Maximum time (in milliseconds) that the platform waits to receive dispatch confirmation for messages sent by the host until rejecting the publishing Promise.\n   * By default, a timeout of 10s is used.\n   */\n  readonly messageDeliveryTimeout?: number;\n  /**\n   * Maximum time (in milliseconds) to wait until the message broker is discovered on platform startup. If the broker is not discovered within\n   * the specified time, platform startup fails with an error. By default, a timeout of 10s is used.\n   *\n   * @internal\n   */\n  readonly brokerDiscoverTimeout?: number;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Describes how to register an application in the platform.\n *\n * @category Platform\n */\nexport interface ApplicationConfig {\n  /**\n   * Unique symbolic name of this micro application.\n   *\n   * The symbolic name must be unique and contain only lowercase alphanumeric characters and hyphens.\n   */\n  symbolicName: string;\n  /**\n   * URL to the application manifest.\n   */\n  manifestUrl: string;\n  /**\n   * Specifies an additional origin (in addition to the origin of the application) from which the application is allowed\n   * to connect to the platform.\n   *\n   * By default, if not set, the application is allowed to connect from the origin of the manifest URL or the base URL as\n   * specified in the manifest file. Setting an additional origin may be necessary if, for example, integrating microfrontends\n   * into a rich client, enabling an integrator to bridge messages between clients and host across browser boundaries.\n   */\n  secondaryOrigin?: string;\n  /**\n   * Maximum time (in milliseconds) that the host waits until the manifest for this application is loaded.\n   *\n   * If set, overrides the global timeout as configured in {@link MicrofrontendPlatformConfig.manifestLoadTimeout}.\n   */\n  manifestLoadTimeout?: number;\n  /**\n   * Maximum time (in milliseconds) for this application to signal readiness.\n   *\n   * If activating this application takes longer, the host logs an error and continues startup.\n   * If set, overrides the global timeout as configured in {@link MicrofrontendPlatformConfig.activatorLoadTimeout}.\n   */\n  activatorLoadTimeout?: number;\n  /**\n   * Excludes this micro application from registration, e.g. to not register it in a specific environment.\n   */\n  exclude?: boolean;\n  /**\n   * Allows this application to access private capabilities of other applications.\n   *\n   * Disabling this check is discouraged. Enabled by default.\n   */\n  scopeCheckDisabled?: boolean;\n  /**\n   * Allows this application to access public capabilities of other applications without declaring an intention.\n   *\n   * Disabling this check is discouraged. Enabled by default.\n   */\n  intentionCheckDisabled?: boolean;\n  /**\n   * Allows this application to access inactive capabilities.\n   *\n   * Disabling this check is discouraged. Enabled by default.\n   */\n  capabilityActiveCheckDisabled?: boolean;\n  /**\n   * Allows this application to register and unregister intentions at runtime.\n   *\n   * Enabling this API is discouraged. Disabled by default.\n   */\n  intentionRegisterApiDisabled?: boolean;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Entry point for all public APIs of this package.\n */\nexport {CapabilityInterceptor} from './capability-interceptors';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nexport * from './message-interception';\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Configures the liveness probe performed between host and clients to detect and dispose stale clients.\n * Clients not replying to the probe are removed.\n *\n * @category Platform\n */\nexport interface LivenessConfig {\n  /**\n   * Interval (in seconds) at which liveness probes are performed between host and connected clients.\n   * Note that the interval must not be 0 and be greater than twice the timeout period to give a probe enough time to complete before performing a new probe.\n   *\n   * By default, if not set, an interval of 60s is used.\n   */\n  interval: number;\n  /**\n   * Timeout (in seconds) after which a client is unregistered if not replying to the probe.\n   * Note that timeout must not be 0 and be less than half the interval period to give a probe enough time to complete before performing a new probe.\n   *\n   * By default, if not set, a timeout of 10s is used.\n   */\n  timeout: number;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Entry point for all public APIs of this package.\n */\nexport * from './microfrontend-platform-host';\nexport * from './microfrontend-platform-config';\nexport * from './host-config';\nexport * from './application-config';\nexport * from './manifest-registry/public_api';\nexport * from './message-broker/public_api';\nexport * from './host-manifest-interceptor';\nexport * from './liveness-config';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Controls how to connect to the platform host.\n *\n * @category Platform\n */\nexport interface ConnectOptions {\n  /**\n   * Controls whether to actually connect to the platform host.\n   *\n   * Disabling this flag can be useful in tests to not connect to the platform host but still have platform beans available.\n   * In this mode, messaging is disabled, i.e., sending and receiving messages results in a NOOP.\n   *\n   * By default, this flag is set to `true`.\n   */\n  connect?: boolean;\n  /**\n   * Specifies the maximum time (in milliseconds) to wait until the message broker is discovered on platform startup. If the broker is not discovered within\n   * the specified time, platform startup fails with an error. By default, a timeout of 10s is used.\n   */\n  brokerDiscoverTimeout?: number;\n  /**\n   * Specifies the maximum time (in milliseconds) that the platform waits to receive dispatch confirmation for messages sent by this application until rejecting\n   * the publishing Promise. By default, a timeout of 10s is used.\n   */\n  messageDeliveryTimeout?: number;\n}\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nexport {SciRouterOutletElement, type OutletContext, OUTLET_CONTEXT, PRIMARY_OUTLET} from './router-outlet.element';\nexport {OutletRouter} from './outlet-router';\nexport {RelativePathResolver} from './relative-path-resolver';\nexport {type NavigationOptions, type Navigation} from './metadata';\nexport {RouterOutletUrlAssigner} from './router-outlet-url-assigner';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nexport {type ContextLookupOptions} from './context.model';\nexport {ContextService} from './context-service';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nexport {FocusMonitor} from './focus-monitor';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nexport {PreferredSizeService} from './preferred-size-service';\nexport {type PreferredSize} from './preferred-size';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nexport {ManifestService} from './manifest-service';\n","/*\n * Copyright (c) 2018-2022 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\nexport {MessageClient, takeUntilUnsubscribe} from './message-client';\nexport {IntentClient, type IntentSelector} from './intent-client';\nexport {type PublishOptions, type RequestOptions} from './publish-options';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Entry point for all public APIs of this package.\n */\nexport * from './microfrontend-platform-client';\nexport * from './connect-options';\nexport * from './router-outlet/public_api';\nexport * from './context/public_api';\nexport * from './focus/public_api';\nexport * from './preferred-size/public_api';\nexport * from './manifest-registry/public_api';\nexport * from './messaging/public_api';\n","/*\n * Copyright (c) 2018-2020 Swiss Federal Railways\n *\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https://www.eclipse.org/legal/epl-2.0/\n *\n * SPDX-License-Identifier: EPL-2.0\n */\n\n/**\n * Entry point for all public APIs of this package.\n */\nexport * from './lib/microfrontend-platform';\nexport * from './lib/host/public_api';\nexport * from './lib/client/public_api';\nexport * from './lib/platform.model';\nexport * from './lib/messaging.model';\nexport * from './lib/platform-property-service';\nexport * from './lib/microfrontend-platform-stopper';\nexport * from './lib/platform-state';\nexport * from './lib/logger';\nexport * from './lib/topic-matcher.util';\nexport * from './lib/qualifier-matcher';\nexport * from './lib/param-matcher';\nexport * from './lib/observable-decorator';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["filter","switchMap","DISPATCHER_ID_HEADER"],"mappings":";;;;;;;;AAAA;;;;;;;;AAQG;AAEH;;;;AAIG;IACS;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB;;AAEG;AACH,IAAA,aAAA,CAAA,aAAA,CAAA,UAAA,CAAA,GAAA,CAAA,CAAA,GAAA,UAAY;AACZ;;AAEG;AACH,IAAA,aAAA,CAAA,aAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAW;AACX;;AAEG;AACH,IAAA,aAAA,CAAA,aAAA,CAAA,UAAA,CAAA,GAAA,CAAA,CAAA,GAAA,UAAY;AACZ;;AAEG;AACH,IAAA,aAAA,CAAA,aAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAW;AACb,CAAC,EAjBW,aAAa,KAAb,aAAa,GAAA,EAAA,CAAA,CAAA;AAmBzB;;;;;;A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