@open-pioneer/runtime 2.1.4 → 2.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @open-pioneer/runtime
2
2
 
3
+ ## 2.1.5
4
+
5
+ ### Patch Changes
6
+
7
+ - 90d0cce: The `resolveConfig` callback of an app's configuration can now inspect the application's `hostElement`.
8
+ - 90d0cce: Add a builtin method on the `ApplicationContext` to change the application's locale.
9
+ Note that with the current implementation, the application will simply restart with the new locale.
10
+ The application's state will be lost.
11
+
12
+ Example:
13
+
14
+ ```ts
15
+ import { ApplicationContext } from "@open-pioneer/runtime";
16
+
17
+ const appCtx: ApplicationContext = ...; // injected
18
+ appCtx.setLocale("en-US");
19
+ ```
20
+
21
+ - @open-pioneer/runtime-react-support@1.0.2
22
+
3
23
  ## 2.1.4
4
24
 
5
25
  ### Patch Changes
@@ -40,6 +40,10 @@ export interface CustomElementOptions {
40
40
  * A context object that is passed to the `resolveProperties` function.
41
41
  */
42
42
  export interface ConfigContext {
43
+ /**
44
+ * The application's host element.
45
+ */
46
+ hostElement: HTMLElement;
43
47
  /**
44
48
  * Returns an attribute from the application's root node.
45
49
  */
package/CustomElement.js CHANGED
@@ -10,7 +10,10 @@ const LOG = createLogger("runtime:CustomElement");
10
10
  function createCustomElement(options) {
11
11
  class PioneerApplication extends HTMLElement {
12
12
  #shadowRoot;
13
- #state;
13
+ #instance;
14
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
+ #deferredRestart;
16
+ // A Timer
14
17
  static get observedAttributes() {
15
18
  return [];
16
19
  }
@@ -20,25 +23,28 @@ function createCustomElement(options) {
20
23
  mode: "open"
21
24
  });
22
25
  if (import.meta.env.DEV) {
23
- this.$inspectElementState = () => this.#state;
26
+ this.$inspectElementState = () => this.#instance;
24
27
  }
25
28
  }
26
29
  connectedCallback() {
27
30
  LOG.debug("Launching application");
28
- if (this.#state) {
29
- this.#state.destroy();
31
+ if (this.#instance) {
32
+ this.#instance.destroy();
30
33
  }
31
- this.#state = new ElementState(this, this.#shadowRoot, options);
32
- this.#state.start();
34
+ this.#instance = this.#createApplicationInstance();
35
+ this.#instance.start();
33
36
  }
34
37
  disconnectedCallback() {
35
38
  LOG.debug("Shutting down application");
36
- this.#state?.destroy();
37
- this.#state = void 0;
39
+ if (this.#deferredRestart) {
40
+ clearTimeout(this.#deferredRestart);
41
+ }
42
+ this.#instance?.destroy();
43
+ this.#instance = void 0;
38
44
  LOG.debug("Application destroyed");
39
45
  }
40
46
  when() {
41
- if (!this.#state) {
47
+ if (!this.#instance) {
42
48
  return Promise.reject(
43
49
  new Error(
44
50
  ErrorId.NOT_MOUNTED,
@@ -46,14 +52,35 @@ function createCustomElement(options) {
46
52
  )
47
53
  );
48
54
  }
49
- return this.#state.whenAPI();
55
+ return this.#instance.whenAPI();
56
+ }
57
+ #triggerReload(overrides) {
58
+ if (this.#deferredRestart) {
59
+ clearTimeout(this.#deferredRestart);
60
+ }
61
+ this.#deferredRestart = setTimeout(() => {
62
+ if (!this.#instance) {
63
+ return;
64
+ }
65
+ LOG.debug("Restarting application with new options", overrides);
66
+ this.#instance.destroy();
67
+ this.#instance = this.#createApplicationInstance(overrides);
68
+ this.#instance.start();
69
+ }, 1);
70
+ }
71
+ #createApplicationInstance(overrides) {
72
+ return new ApplicationInstance({
73
+ hostElement: this,
74
+ shadowRoot: this.#shadowRoot,
75
+ elementOptions: options,
76
+ overrides,
77
+ restart: this.#triggerReload.bind(this)
78
+ });
50
79
  }
51
80
  }
52
81
  return PioneerApplication;
53
82
  }
54
- class ElementState {
55
- hostElement;
56
- shadowRoot;
83
+ class ApplicationInstance {
57
84
  options;
58
85
  // Public API
59
86
  apiPromise;
@@ -68,9 +95,7 @@ class ElementState {
68
95
  lifecycleEvents;
69
96
  reactIntegration;
70
97
  stylesWatch;
71
- constructor(hostElement, shadowRoot, options) {
72
- this.hostElement = hostElement;
73
- this.shadowRoot = shadowRoot;
98
+ constructor(options) {
74
99
  this.options = options;
75
100
  }
76
101
  start() {
@@ -98,7 +123,7 @@ class ElementState {
98
123
  this.state = "destroyed";
99
124
  this.apiPromise?.reject(createAbortError());
100
125
  this.reactIntegration = destroyResource(this.reactIntegration);
101
- this.shadowRoot.replaceChildren();
126
+ this.options.shadowRoot.replaceChildren();
102
127
  this.container = void 0;
103
128
  this.lifecycleEvents = void 0;
104
129
  this.serviceLayer = destroyResource(this.serviceLayer);
@@ -112,11 +137,11 @@ class ElementState {
112
137
  return apiPromise.promise;
113
138
  }
114
139
  async startImpl() {
115
- const { options, shadowRoot, hostElement } = this;
116
- const config = this.config = await gatherConfig(hostElement, options);
140
+ const { shadowRoot, hostElement, elementOptions, overrides } = this.options;
141
+ const config = this.config = await gatherConfig(hostElement, elementOptions, overrides);
117
142
  this.checkAbort();
118
143
  LOG.debug("Application config is", config);
119
- const i18n = await initI18n(options.appMetadata, config.locale);
144
+ const i18n = await initI18n(elementOptions.appMetadata, config.locale);
120
145
  this.checkAbort();
121
146
  const container = this.container = createContainer(i18n.locale);
122
147
  const styles = this.initStyles();
@@ -135,7 +160,7 @@ class ElementState {
135
160
  this.reactIntegration = new ReactIntegration({
136
161
  rootNode: container,
137
162
  container: shadowRoot,
138
- theme: options.theme,
163
+ theme: elementOptions.theme,
139
164
  serviceLayer,
140
165
  packages
141
166
  });
@@ -145,13 +170,14 @@ class ElementState {
145
170
  LOG.debug("Application started");
146
171
  }
147
172
  render() {
148
- this.reactIntegration?.render(this.options.component ?? emptyComponent);
173
+ const component = this.options.elementOptions.component ?? emptyComponent;
174
+ this.reactIntegration?.render(component);
149
175
  }
150
176
  initStyles() {
151
177
  const builtinStyles = ":host { all: initial; display: block; }";
152
178
  const builtinStylesNode = document.createElement("style");
153
179
  applyStyles(builtinStylesNode, { value: builtinStyles });
154
- const appStyles = this.options.appMetadata?.styles;
180
+ const appStyles = this.options.elementOptions.appMetadata?.styles;
155
181
  const appStylesNode = document.createElement("style");
156
182
  applyStyles(appStylesNode, appStyles);
157
183
  if (import.meta.hot) {
@@ -163,15 +189,27 @@ class ElementState {
163
189
  return [builtinStylesNode, appStylesNode];
164
190
  }
165
191
  initServiceLayer(config) {
166
- const options = this.options;
192
+ const { hostElement, shadowRoot, elementOptions, restart } = this.options;
167
193
  const { container, properties, i18n } = config;
168
- const packageMetadata = options.appMetadata?.packages ?? {};
194
+ const packageMetadata = elementOptions.appMetadata?.packages ?? {};
169
195
  const builtinPackage = createBuiltinPackage({
170
- host: this.hostElement,
171
- shadowRoot: this.shadowRoot,
196
+ host: hostElement,
197
+ shadowRoot,
172
198
  container,
173
199
  locale: i18n.locale,
174
- supportedLocales: i18n.supportedLocales
200
+ supportedLocales: i18n.supportedMessageLocales,
201
+ changeLocale(locale) {
202
+ const supported = i18n.supportedMessageLocales;
203
+ if (locale != null && !i18n.supportsLocale(locale)) {
204
+ throw new Error(
205
+ ErrorId.UNSUPPORTED_LOCALE,
206
+ `Unsupported locale '${locale}' (supported locales: ${supported.join(
207
+ ", "
208
+ )}).`
209
+ );
210
+ }
211
+ restart({ locale });
212
+ }
175
213
  });
176
214
  const { serviceLayer, packages } = createServiceLayer({
177
215
  packageMetadata,
@@ -268,11 +306,12 @@ function getInternalService(serviceLayer, interfaceName) {
268
306
  }
269
307
  return result.value.getInstanceOrThrow();
270
308
  }
271
- async function gatherConfig(hostElement, options) {
309
+ async function gatherConfig(hostElement, options, overrides) {
272
310
  let configs;
273
311
  try {
274
312
  const staticConfig = options.config ?? {};
275
313
  const dynamicConfig = await options.resolveConfig?.({
314
+ hostElement,
276
315
  getAttribute(name) {
277
316
  return hostElement.getAttribute(name) ?? void 0;
278
317
  }
@@ -287,7 +326,11 @@ async function gatherConfig(hostElement, options) {
287
326
  }
288
327
  );
289
328
  }
290
- return mergeConfigs(configs);
329
+ const merged = mergeConfigs(configs);
330
+ if (overrides?.locale) {
331
+ merged.locale = overrides.locale;
332
+ }
333
+ return merged;
291
334
  }
292
335
  function mergeConfigs(configs) {
293
336
  const mergedConfig = Object.assign(
@@ -1 +1 @@
1
- {"version":3,"file":"CustomElement.js","sources":["CustomElement.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { ComponentType } from \"react\";\nimport {\n createAbortError,\n createLogger,\n createManualPromise,\n destroyResource,\n Error,\n isAbortError,\n ManualPromise,\n Resource,\n throwAbortError\n} from \"@open-pioneer/core\";\nimport { ErrorId } from \"./errors\";\nimport { ApplicationMetadata, PackageMetadata } from \"./metadata\";\nimport { PackageRepr, createPackages } from \"./service-layer/PackageRepr\";\nimport { ServiceLayer } from \"./service-layer/ServiceLayer\";\nimport { getErrorChain } from \"@open-pioneer/core\";\nimport { ReactIntegration } from \"./react-integration/ReactIntegration\";\nimport { ApiMethods, ApiService } from \"./api\";\nimport {\n createBuiltinPackage,\n RUNTIME_API_SERVICE,\n RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE,\n RUNTIME_AUTO_START\n} from \"./builtin-services\";\nimport { ReferenceSpec } from \"./service-layer/InterfaceSpec\";\nimport { AppI18n, initI18n } from \"./i18n\";\nimport { ApplicationLifecycleEventService } from \"./builtin-services/ApplicationLifecycleEventService\";\nconst LOG = createLogger(\"runtime:CustomElement\");\n\n/**\n * Options for the {@link createCustomElement} function.\n */\nexport interface CustomElementOptions {\n /**\n * Rendered UI component.\n */\n component?: ComponentType<Record<string, string>>;\n\n /**\n * Application metadata (packages, services etc.).\n * This is usually autogenerated by importing the virtual `\"open-pioneer:app\"` module.\n */\n appMetadata?: ApplicationMetadata;\n\n /**\n * Application defined configuration.\n *\n * This option can be used to override default properties of the application's packages.\n *\n * All instances of the web component will share this static configuration.\n */\n config?: ApplicationConfig;\n\n /**\n * Function to provide additional application defined configuration parameters.\n *\n * Compared to {@link config}, this function receives a context object\n * that allows the developer to provide dynamic properties on a per-application instance basis.\n *\n * Parameters returned by this function take precedence over the ones defined by {@link config}.\n */\n resolveConfig?(ctx: ConfigContext): Promise<ApplicationConfig | undefined>;\n\n /**\n * Chakra theming object.\n */\n theme?: Record<string, unknown>;\n}\n\n/**\n * A context object that is passed to the `resolveProperties` function.\n */\nexport interface ConfigContext {\n /**\n * Returns an attribute from the application's root node.\n */\n getAttribute(name: string): string | undefined;\n}\n\n/**\n * Runtime application configuration.\n */\nexport interface ApplicationConfig {\n /**\n * Set this value to a locale string (e.g. \"en\") to for the application's locale.\n * The default behavior is to choose an appropriate locale for the current user based\n * on the browser's settings.\n *\n * The locale must be supported by the application.\n */\n locale?: string | undefined;\n\n /**\n * Properties specified here will override default properties of the application's packages.\n */\n properties?: ApplicationProperties | undefined;\n}\n\n/**\n * Allows the application to override default properties in all packages.\n *\n * Properties are typed when the package contains type definitions for them.\n */\nexport interface ApplicationProperties {\n /**\n * Key: the name of the package.\n * Value: A record of configuration properties (key/value pairs).\n *\n * Properties will override default property values in the package.\n */\n [packageName: string]: Record<string, unknown>;\n}\n\n/**\n * The interface implemented by web components produced via {@link createCustomElement}.\n */\nexport interface ApplicationElement extends HTMLElement {\n /** Resolves to the element's API when the application has started. */\n when(): Promise<ApiMethods>;\n}\n\n/**\n * The class returned by a call to {@link createCustomElement}.\n */\nexport interface ApplicationElementConstructor {\n new (): ApplicationElement;\n}\n\n/**\n * Creates a new custom element class (web component) that can be registered within a DOM.\n *\n * @example\n * ```ts\n * import * as appMetadata from \"open-pioneer:app\";\n *\n * const CustomElementClazz = createCustomElement({\n * component: <div>Hello World!</div>,\n * appMetadata\n * });\n * customElements.define(\"sample-element\", CustomElementClazz);\n * ```\n */\nexport function createCustomElement(options: CustomElementOptions): ApplicationElementConstructor {\n class PioneerApplication extends HTMLElement implements ApplicationElement {\n #shadowRoot: ShadowRoot;\n #state: ElementState | undefined;\n\n static get observedAttributes(): string[] {\n return [];\n }\n\n constructor() {\n super();\n\n this.#shadowRoot = this.attachShadow({\n mode: \"open\"\n });\n\n if (import.meta.env.DEV) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).$inspectElementState = () => this.#state;\n }\n }\n\n connectedCallback() {\n LOG.debug(\"Launching application\");\n\n if (this.#state) {\n this.#state.destroy();\n }\n\n this.#state = new ElementState(this, this.#shadowRoot, options);\n this.#state.start();\n }\n\n disconnectedCallback() {\n LOG.debug(\"Shutting down application\");\n\n this.#state?.destroy();\n this.#state = undefined;\n\n LOG.debug(\"Application destroyed\");\n }\n\n when() {\n if (!this.#state) {\n return Promise.reject(\n new Error(\n ErrorId.NOT_MOUNTED,\n \"Cannot use the application's API because the HTML element has not yet been mounted into the DOM.\"\n )\n );\n }\n\n return this.#state.whenAPI();\n }\n }\n return PioneerApplication;\n}\n\nclass ElementState {\n private hostElement: HTMLElement;\n private shadowRoot: ShadowRoot;\n private options: CustomElementOptions;\n\n // Public API\n private apiPromise: ManualPromise<ApiMethods> | undefined; // Present when callers are waiting for the API\n private api: ApiMethods | undefined; // Present once started\n\n private state = \"not-started\" as \"not-started\" | \"starting\" | \"started\" | \"destroyed\";\n private locale: string | undefined;\n private container: HTMLDivElement | undefined;\n private config: ApplicationConfig | undefined;\n private serviceLayer: ServiceLayer | undefined;\n private lifecycleEvents: ApplicationLifecycleEventService | undefined;\n private reactIntegration: ReactIntegration | undefined;\n private stylesWatch: Resource | undefined;\n\n constructor(hostElement: HTMLElement, shadowRoot: ShadowRoot, options: CustomElementOptions) {\n this.hostElement = hostElement;\n this.shadowRoot = shadowRoot;\n this.options = options;\n }\n\n start() {\n if (this.state !== \"not-started\") {\n throw new Error(ErrorId.INTERNAL, `Cannot start element in state '${this.state}'`);\n }\n\n this.state = \"starting\";\n this.startImpl().catch((e) => {\n // TODO: Error splash?\n this.destroy();\n if (!isAbortError(e)) {\n logError(e);\n }\n });\n }\n\n destroy() {\n if (this.state === \"destroyed\") {\n return;\n }\n\n // Only call event listener when 'started' was also signalled.\n if (this.state === \"started\") {\n try {\n this.triggerApplicationLifecycleEvent(\"before-stop\");\n } catch (e) {\n void e; // Ignored\n }\n }\n this.state = \"destroyed\";\n this.apiPromise?.reject(createAbortError());\n this.reactIntegration = destroyResource(this.reactIntegration);\n this.shadowRoot.replaceChildren();\n this.container = undefined;\n this.lifecycleEvents = undefined;\n this.serviceLayer = destroyResource(this.serviceLayer);\n this.stylesWatch = destroyResource(this.stylesWatch);\n }\n\n whenAPI(): Promise<ApiMethods> {\n if (this.api) {\n return Promise.resolve(this.api);\n }\n\n const apiPromise = (this.apiPromise ??= createManualPromise());\n return apiPromise.promise;\n }\n\n private async startImpl() {\n const { options, shadowRoot, hostElement } = this;\n\n // Resolve custom application config\n const config = (this.config = await gatherConfig(hostElement, options));\n this.checkAbort();\n LOG.debug(\"Application config is\", config);\n\n // Decide on locale and load i18n messages (if any).\n const i18n = await initI18n(options.appMetadata, config.locale);\n this.checkAbort();\n\n // Setup application root node in the shadow dom\n const container = (this.container = createContainer(i18n.locale));\n const styles = this.initStyles();\n shadowRoot.replaceChildren(container, ...styles);\n\n // Launch the service layer\n const { serviceLayer, packages } = this.initServiceLayer({\n container,\n properties: config.properties,\n i18n\n });\n this.lifecycleEvents = getInternalService<ApplicationLifecycleEventService>(\n serviceLayer,\n RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE\n );\n\n await this.initAPI(serviceLayer);\n this.checkAbort();\n\n // Launch react\n this.reactIntegration = new ReactIntegration({\n rootNode: container,\n container: shadowRoot,\n theme: options.theme,\n serviceLayer,\n packages\n });\n this.render();\n this.state = \"started\";\n\n this.triggerApplicationLifecycleEvent(\"after-start\");\n LOG.debug(\"Application started\");\n }\n\n private render() {\n this.reactIntegration?.render(this.options.component ?? emptyComponent);\n }\n\n private initStyles() {\n // Prevent inheritance of certain css values and normalize to display: block by default.\n // See https://open-wc.org/guides/knowledge/styling/styles-piercing-shadow-dom/\n const builtinStyles = \":host { all: initial; display: block; }\";\n const builtinStylesNode = document.createElement(\"style\");\n applyStyles(builtinStylesNode, { value: builtinStyles });\n\n const appStyles = this.options.appMetadata?.styles;\n const appStylesNode = document.createElement(\"style\");\n applyStyles(appStylesNode, appStyles);\n if (import.meta.hot) {\n this.stylesWatch = appStyles?.on?.(\"changed\", () => {\n LOG.debug(\"Application styles changed\");\n applyStyles(appStylesNode, appStyles);\n });\n }\n return [builtinStylesNode, appStylesNode];\n }\n\n private initServiceLayer(config: {\n container: HTMLDivElement;\n properties: ApplicationProperties;\n i18n: AppI18n;\n }) {\n const options = this.options;\n const { container, properties, i18n } = config;\n const packageMetadata = options.appMetadata?.packages ?? {};\n const builtinPackage = createBuiltinPackage({\n host: this.hostElement,\n shadowRoot: this.shadowRoot,\n container: container,\n locale: i18n.locale,\n supportedLocales: i18n.supportedLocales\n });\n const { serviceLayer, packages } = createServiceLayer({\n packageMetadata,\n builtinPackage,\n properties,\n i18n\n });\n this.serviceLayer = serviceLayer;\n\n if (LOG.isDebug()) {\n LOG.debug(\"Launching service layer with packages\", Object.fromEntries(packages));\n }\n serviceLayer.start();\n return { serviceLayer, packages };\n }\n\n private async initAPI(serviceLayer: ServiceLayer) {\n const apiService = getInternalService<ApiService>(serviceLayer, RUNTIME_API_SERVICE);\n try {\n const api = (this.api = await apiService.getApi());\n LOG.debug(\"Application API initialized to\", api);\n this.apiPromise?.resolve(api);\n } catch (e) {\n throw new Error(ErrorId.INTERNAL, \"Failed to gather the application's API methods.\", {\n cause: e\n });\n }\n }\n\n private triggerApplicationLifecycleEvent(event: \"after-start\" | \"before-stop\") {\n this.lifecycleEvents?.emitLifecycleEvent(event);\n }\n\n private checkAbort() {\n if (this.state === \"destroyed\") {\n throwAbortError();\n }\n }\n}\n\nfunction createContainer(locale: string) {\n // Setup application root node in the shadow dom\n const container = document.createElement(\"div\");\n container.classList.add(\"pioneer-root\");\n container.style.minHeight = \"100%\";\n container.style.height = \"100%\";\n if (locale) {\n container.lang = locale;\n }\n return container;\n}\n\nfunction createServiceLayer(config: {\n packageMetadata: Record<string, PackageMetadata> | undefined;\n properties: ApplicationProperties;\n builtinPackage: PackageRepr;\n i18n: AppI18n;\n}) {\n const { packageMetadata, properties, builtinPackage, i18n } = config;\n\n let packages: PackageRepr[];\n try {\n packages = createPackages(packageMetadata ?? {}, i18n, properties);\n } catch (e) {\n throw new Error(ErrorId.INVALID_METADATA, \"Failed to parse package metadata.\", {\n cause: e\n });\n }\n\n // Add builtin services defined within this package.\n {\n const index = packages.findIndex((pkg) => pkg.name === builtinPackage.name);\n if (index >= 0) {\n packages.splice(index, 1);\n }\n packages.push(builtinPackage);\n }\n\n // Automatically required references (-> forces services to start)\n const forcedReferences: ReferenceSpec[] = [\n {\n interfaceName: RUNTIME_API_SERVICE\n },\n {\n interfaceName: RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE\n },\n {\n interfaceName: RUNTIME_AUTO_START,\n all: true\n }\n ];\n const serviceLayer = new ServiceLayer(packages, forcedReferences);\n return {\n packages: new Map(packages.map((pkg) => [pkg.name, pkg])),\n serviceLayer: serviceLayer\n };\n}\n\nfunction getInternalService<T = unknown>(serviceLayer: ServiceLayer, interfaceName: string) {\n const result = serviceLayer.getService(\n \"@open-pioneer/runtime\",\n {\n interfaceName\n },\n { ignoreDeclarationCheck: true }\n );\n if (result.type !== \"found\") {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find instance of '${interfaceName}' (result type '${result.type}').` +\n ` This is a builtin service that must be present exactly once.`\n );\n }\n\n return result.value.getInstanceOrThrow() as T;\n}\n\n/**\n * Gathers application properties by reading them from the options object\n * and by (optionally) invoking the `resolveProperties` hook.\n */\nasync function gatherConfig(hostElement: HTMLElement, options: CustomElementOptions) {\n let configs: ApplicationConfig[];\n try {\n const staticConfig = options.config ?? {};\n const dynamicConfig =\n (await options.resolveConfig?.({\n getAttribute(name) {\n return hostElement.getAttribute(name) ?? undefined;\n }\n })) ?? {};\n\n configs = [staticConfig, dynamicConfig];\n } catch (e) {\n throw new Error(\n ErrorId.CONFIG_RESOLUTION_FAILED,\n \"Failed to resolve application properties.\",\n {\n cause: e\n }\n );\n }\n\n return mergeConfigs(configs);\n}\n\n/**\n * Merges application configurations into a single object.\n * Properties / config parameters at a later position overwrite properties from earlier ones.\n */\nfunction mergeConfigs(configs: ApplicationConfig[]): Required<ApplicationConfig> {\n // Merge simple values by assigning them in order\n const mergedConfig: Required<ApplicationConfig> = Object.assign(\n {\n locale: undefined,\n properties: {}\n } satisfies ApplicationConfig,\n ...configs\n );\n\n // Deep merge for application properties\n const mergedProperties: ApplicationProperties = (mergedConfig.properties = {});\n for (const config of configs) {\n for (const [packageName, packageProperties] of Object.entries(config.properties ?? {})) {\n const mergedPackageProps = (mergedProperties[packageName] ??= {});\n Object.assign(mergedPackageProps, packageProperties);\n }\n }\n\n return mergedConfig;\n}\n\n// Applies application styles to the given style node.\n// Can be called multiple times in development mode to implement hot reloading.\nfunction applyStyles(styleNode: HTMLStyleElement, styles: { value: string } | undefined) {\n let cssValue = styles?.value ?? \"\";\n // Remove sourcemaps from inline css.\n // This currently does not work because a) the 'importer' (the index.html file) does not\n // match the actual path the source map would exist and b) vite refuses to generate it anyway, probably\n // because of our virtual modules.\n // TODO: both should be fixed once we can refer to actual `.css` files\n // and don't have to embed inline css anymore.\n cssValue = cssValue.replace(/\\/\\*# sourceMappingURL=.*$/, \"\");\n const cssNode = document.createTextNode(cssValue);\n styleNode.replaceChildren(cssNode);\n}\n\nfunction logError(e: unknown) {\n if (e instanceof Error) {\n const chain = getErrorChain(e).reverse();\n if (chain.length === 1) {\n console.error(e);\n return;\n }\n\n let n = 1;\n for (const error of chain) {\n console.error(`#${n}`, error);\n ++n;\n }\n } else {\n console.error(\"Unexpected error\", e);\n }\n}\n\nfunction emptyComponent() {\n return null;\n}\n"],"names":[],"mappings":";;;;;;;;AA8BA,MAAM,GAAA,GAAM,aAAa,uBAAuB,CAAA,CAAA;AAmHzC,SAAS,oBAAoB,OAA8D,EAAA;AAAA,EAC9F,MAAM,2BAA2B,WAA0C,CAAA;AAAA,IACvE,WAAA,CAAA;AAAA,IACA,MAAA,CAAA;AA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,CAAS,OAAQ,CAAA,4BAAA,EAA8B,EAAE,CAAA,CAAA;AAC5D,EAAM,MAAA,OAAA,GAAU,QAAS,CAAA,cAAA,CAAe,QAAQ,CAAA,CAAA;AAChD,EAAA,SAAA,CAAU,gBAAgB,OAAO,CAAA,CAAA;AACrC,CAAA;AAEA,SAAS,SAAS,CAAY,EAAA;AAC1B,EAAA,IAAI,aAAa,KAAO,EAAA;AACpB,IAAA,MAAM,KAAQ,GAAA,aAAA,CAAc,CAAC,CAAA,CAAE,OAAQ,EAAA,CAAA;AACvC,IAAI,IAAA,KAAA,CAAM,WAAW,CAAG,EAAA;AACpB,MAAA,OAAA,CAAQ,MAAM,CAAC,CAAA,CAAA;AACf,MAAA,OAAA;AAAA,KACJ;AAEA,IAAA,IAAI,CAAI,GAAA,CAAA,CAAA;AACR,IAAA,KAAA,MAAW,SAAS,KAAO,EAAA;AACvB,MAAA,OAAA,CAAQ,KAAM,CAAA,CAAA,CAAA,EAAI,CAAC,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA;AAC5B,MAAE,EAAA,CAAA,CAAA;AAAA,KACN;AAAA,GACG,MAAA;AACH,IAAQ,OAAA,CAAA,KAAA,CAAM,oBAAoB,CAAC,CAAA,CAAA;AAAA,GACvC;AACJ,CAAA;AAEA,SAAS,cAAiB,GAAA;AACtB,EAAO,OAAA,IAAA,CAAA;AACX;;;;"}
1
+ {"version":3,"file":"CustomElement.js","sources":["CustomElement.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { ComponentType } from \"react\";\nimport {\n createAbortError,\n createLogger,\n createManualPromise,\n destroyResource,\n Error,\n isAbortError,\n ManualPromise,\n Resource,\n throwAbortError\n} from \"@open-pioneer/core\";\nimport { ErrorId } from \"./errors\";\nimport { ApplicationMetadata, PackageMetadata } from \"./metadata\";\nimport { PackageRepr, createPackages } from \"./service-layer/PackageRepr\";\nimport { ServiceLayer } from \"./service-layer/ServiceLayer\";\nimport { getErrorChain } from \"@open-pioneer/core\";\nimport { ReactIntegration } from \"./react-integration/ReactIntegration\";\nimport { ApiMethods, ApiService } from \"./api\";\nimport {\n createBuiltinPackage,\n RUNTIME_API_SERVICE,\n RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE,\n RUNTIME_AUTO_START\n} from \"./builtin-services\";\nimport { ReferenceSpec } from \"./service-layer/InterfaceSpec\";\nimport { AppI18n, initI18n } from \"./i18n\";\nimport { ApplicationLifecycleEventService } from \"./builtin-services/ApplicationLifecycleEventService\";\nconst LOG = createLogger(\"runtime:CustomElement\");\n\n/**\n * Options for the {@link createCustomElement} function.\n */\nexport interface CustomElementOptions {\n /**\n * Rendered UI component.\n */\n component?: ComponentType<Record<string, string>>;\n\n /**\n * Application metadata (packages, services etc.).\n * This is usually autogenerated by importing the virtual `\"open-pioneer:app\"` module.\n */\n appMetadata?: ApplicationMetadata;\n\n /**\n * Application defined configuration.\n *\n * This option can be used to override default properties of the application's packages.\n *\n * All instances of the web component will share this static configuration.\n */\n config?: ApplicationConfig;\n\n /**\n * Function to provide additional application defined configuration parameters.\n *\n * Compared to {@link config}, this function receives a context object\n * that allows the developer to provide dynamic properties on a per-application instance basis.\n *\n * Parameters returned by this function take precedence over the ones defined by {@link config}.\n */\n resolveConfig?(ctx: ConfigContext): Promise<ApplicationConfig | undefined>;\n\n /**\n * Chakra theming object.\n */\n theme?: Record<string, unknown>;\n}\n\n/**\n * A context object that is passed to the `resolveProperties` function.\n */\nexport interface ConfigContext {\n /**\n * The application's host element.\n */\n hostElement: HTMLElement;\n\n /**\n * Returns an attribute from the application's root node.\n */\n getAttribute(name: string): string | undefined;\n}\n\n/**\n * Runtime application configuration.\n */\nexport interface ApplicationConfig {\n /**\n * Set this value to a locale string (e.g. \"en\") to for the application's locale.\n * The default behavior is to choose an appropriate locale for the current user based\n * on the browser's settings.\n *\n * The locale must be supported by the application.\n */\n locale?: string | undefined;\n\n /**\n * Properties specified here will override default properties of the application's packages.\n */\n properties?: ApplicationProperties | undefined;\n}\n\n/**\n * Allows the application to override default properties in all packages.\n *\n * Properties are typed when the package contains type definitions for them.\n */\nexport interface ApplicationProperties {\n /**\n * Key: the name of the package.\n * Value: A record of configuration properties (key/value pairs).\n *\n * Properties will override default property values in the package.\n */\n [packageName: string]: Record<string, unknown>;\n}\n\n/**\n * The interface implemented by web components produced via {@link createCustomElement}.\n */\nexport interface ApplicationElement extends HTMLElement {\n /** Resolves to the element's API when the application has started. */\n when(): Promise<ApiMethods>;\n}\n\n/**\n * The class returned by a call to {@link createCustomElement}.\n */\nexport interface ApplicationElementConstructor {\n new (): ApplicationElement;\n}\n\n/**\n * Creates a new custom element class (web component) that can be registered within a DOM.\n *\n * @example\n * ```ts\n * import * as appMetadata from \"open-pioneer:app\";\n *\n * const CustomElementClazz = createCustomElement({\n * component: <div>Hello World!</div>,\n * appMetadata\n * });\n * customElements.define(\"sample-element\", CustomElementClazz);\n * ```\n */\nexport function createCustomElement(options: CustomElementOptions): ApplicationElementConstructor {\n class PioneerApplication extends HTMLElement implements ApplicationElement {\n #shadowRoot: ShadowRoot;\n #instance: ApplicationInstance | undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n #deferredRestart: any; // A Timer\n\n static get observedAttributes(): string[] {\n return [];\n }\n\n constructor() {\n super();\n\n this.#shadowRoot = this.attachShadow({\n mode: \"open\"\n });\n\n if (import.meta.env.DEV) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).$inspectElementState = () => this.#instance;\n }\n }\n\n connectedCallback() {\n LOG.debug(\"Launching application\");\n\n if (this.#instance) {\n this.#instance.destroy();\n }\n\n this.#instance = this.#createApplicationInstance();\n this.#instance.start();\n }\n\n disconnectedCallback() {\n LOG.debug(\"Shutting down application\");\n\n if (this.#deferredRestart) {\n clearTimeout(this.#deferredRestart);\n }\n this.#instance?.destroy();\n this.#instance = undefined;\n\n LOG.debug(\"Application destroyed\");\n }\n\n when() {\n if (!this.#instance) {\n return Promise.reject(\n new Error(\n ErrorId.NOT_MOUNTED,\n \"Cannot use the application's API because the HTML element has not yet been mounted into the DOM.\"\n )\n );\n }\n\n return this.#instance.whenAPI();\n }\n\n #triggerReload(overrides?: ApplicationOverrides) {\n // Defer the restart operation a tiny bit so calling code does not get surprised by the application's destruction.\n if (this.#deferredRestart) {\n clearTimeout(this.#deferredRestart);\n }\n this.#deferredRestart = setTimeout(() => {\n if (!this.#instance) {\n // disconnectedCallback was called in the meantime\n return;\n }\n\n LOG.debug(\"Restarting application with new options\", overrides);\n this.#instance.destroy();\n this.#instance = this.#createApplicationInstance(overrides);\n this.#instance.start();\n }, 1);\n }\n\n #createApplicationInstance(overrides?: ApplicationOverrides) {\n return new ApplicationInstance({\n hostElement: this,\n shadowRoot: this.#shadowRoot,\n elementOptions: options,\n overrides: overrides,\n restart: this.#triggerReload.bind(this)\n });\n }\n }\n return PioneerApplication;\n}\n\ninterface InstanceOptions {\n /** The HTML element that embeds the application. */\n hostElement: HTMLElement;\n\n /** The shadow root inside the host element that contains the rest of the application. */\n shadowRoot: ShadowRoot;\n\n /** Trails options for the application. */\n elementOptions: CustomElementOptions;\n\n /** These have higher priority than the options in `elementOptions`. */\n overrides: ApplicationOverrides | undefined;\n\n /**\n * A callback to restart the application with new options.\n * Currently only used for reloading with a certain locale.\n */\n restart: (overrides?: ApplicationOverrides) => void;\n}\n\ninterface ApplicationOverrides {\n locale?: string;\n}\n\nclass ApplicationInstance {\n private options: InstanceOptions;\n\n // Public API\n private apiPromise: ManualPromise<ApiMethods> | undefined; // Present when callers are waiting for the API\n private api: ApiMethods | undefined; // Present once started\n\n private state = \"not-started\" as \"not-started\" | \"starting\" | \"started\" | \"destroyed\";\n private locale: string | undefined;\n private container: HTMLDivElement | undefined;\n private config: ApplicationConfig | undefined;\n private serviceLayer: ServiceLayer | undefined;\n private lifecycleEvents: ApplicationLifecycleEventService | undefined;\n private reactIntegration: ReactIntegration | undefined;\n private stylesWatch: Resource | undefined;\n\n constructor(options: InstanceOptions) {\n this.options = options;\n }\n\n start() {\n if (this.state !== \"not-started\") {\n throw new Error(ErrorId.INTERNAL, `Cannot start element in state '${this.state}'`);\n }\n\n this.state = \"starting\";\n this.startImpl().catch((e) => {\n // TODO: Error splash?\n this.destroy();\n if (!isAbortError(e)) {\n logError(e);\n }\n });\n }\n\n destroy() {\n if (this.state === \"destroyed\") {\n return;\n }\n\n // Only call event listener when 'started' was also signalled.\n if (this.state === \"started\") {\n try {\n this.triggerApplicationLifecycleEvent(\"before-stop\");\n } catch (e) {\n void e; // Ignored\n }\n }\n this.state = \"destroyed\";\n this.apiPromise?.reject(createAbortError());\n this.reactIntegration = destroyResource(this.reactIntegration);\n this.options.shadowRoot.replaceChildren();\n this.container = undefined;\n this.lifecycleEvents = undefined;\n this.serviceLayer = destroyResource(this.serviceLayer);\n this.stylesWatch = destroyResource(this.stylesWatch);\n }\n\n whenAPI(): Promise<ApiMethods> {\n if (this.api) {\n return Promise.resolve(this.api);\n }\n\n const apiPromise = (this.apiPromise ??= createManualPromise());\n return apiPromise.promise;\n }\n\n private async startImpl() {\n const { shadowRoot, hostElement, elementOptions, overrides } = this.options;\n\n // Resolve custom application config\n const config = (this.config = await gatherConfig(hostElement, elementOptions, overrides));\n this.checkAbort();\n LOG.debug(\"Application config is\", config);\n\n // Decide on locale and load i18n messages (if any).\n const i18n = await initI18n(elementOptions.appMetadata, config.locale);\n this.checkAbort();\n\n // Setup application root node in the shadow dom\n const container = (this.container = createContainer(i18n.locale));\n const styles = this.initStyles();\n shadowRoot.replaceChildren(container, ...styles);\n\n // Launch the service layer\n const { serviceLayer, packages } = this.initServiceLayer({\n container,\n properties: config.properties,\n i18n\n });\n this.lifecycleEvents = getInternalService<ApplicationLifecycleEventService>(\n serviceLayer,\n RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE\n );\n\n await this.initAPI(serviceLayer);\n this.checkAbort();\n\n // Launch react\n this.reactIntegration = new ReactIntegration({\n rootNode: container,\n container: shadowRoot,\n theme: elementOptions.theme,\n serviceLayer,\n packages\n });\n this.render();\n this.state = \"started\";\n\n this.triggerApplicationLifecycleEvent(\"after-start\");\n LOG.debug(\"Application started\");\n }\n\n private render() {\n const component = this.options.elementOptions.component ?? emptyComponent;\n this.reactIntegration?.render(component);\n }\n\n private initStyles() {\n // Prevent inheritance of certain css values and normalize to display: block by default.\n // See https://open-wc.org/guides/knowledge/styling/styles-piercing-shadow-dom/\n const builtinStyles = \":host { all: initial; display: block; }\";\n const builtinStylesNode = document.createElement(\"style\");\n applyStyles(builtinStylesNode, { value: builtinStyles });\n\n const appStyles = this.options.elementOptions.appMetadata?.styles;\n const appStylesNode = document.createElement(\"style\");\n applyStyles(appStylesNode, appStyles);\n if (import.meta.hot) {\n this.stylesWatch = appStyles?.on?.(\"changed\", () => {\n LOG.debug(\"Application styles changed\");\n applyStyles(appStylesNode, appStyles);\n });\n }\n return [builtinStylesNode, appStylesNode];\n }\n\n private initServiceLayer(config: {\n container: HTMLDivElement;\n properties: ApplicationProperties;\n i18n: AppI18n;\n }) {\n const { hostElement, shadowRoot, elementOptions, restart } = this.options;\n const { container, properties, i18n } = config;\n const packageMetadata = elementOptions.appMetadata?.packages ?? {};\n const builtinPackage = createBuiltinPackage({\n host: hostElement,\n shadowRoot: shadowRoot,\n container: container,\n locale: i18n.locale,\n supportedLocales: i18n.supportedMessageLocales,\n changeLocale(locale) {\n const supported = i18n.supportedMessageLocales;\n if (locale != null && !i18n.supportsLocale(locale)) {\n throw new Error(\n ErrorId.UNSUPPORTED_LOCALE,\n `Unsupported locale '${locale}' (supported locales: ${supported.join(\n \", \"\n )}).`\n );\n }\n restart({ locale });\n }\n });\n const { serviceLayer, packages } = createServiceLayer({\n packageMetadata,\n builtinPackage,\n properties,\n i18n\n });\n this.serviceLayer = serviceLayer;\n\n if (LOG.isDebug()) {\n LOG.debug(\"Launching service layer with packages\", Object.fromEntries(packages));\n }\n serviceLayer.start();\n return { serviceLayer, packages };\n }\n\n private async initAPI(serviceLayer: ServiceLayer) {\n const apiService = getInternalService<ApiService>(serviceLayer, RUNTIME_API_SERVICE);\n try {\n const api = (this.api = await apiService.getApi());\n LOG.debug(\"Application API initialized to\", api);\n this.apiPromise?.resolve(api);\n } catch (e) {\n throw new Error(ErrorId.INTERNAL, \"Failed to gather the application's API methods.\", {\n cause: e\n });\n }\n }\n\n private triggerApplicationLifecycleEvent(event: \"after-start\" | \"before-stop\") {\n this.lifecycleEvents?.emitLifecycleEvent(event);\n }\n\n private checkAbort() {\n if (this.state === \"destroyed\") {\n throwAbortError();\n }\n }\n}\n\nfunction createContainer(locale: string) {\n // Setup application root node in the shadow dom\n const container = document.createElement(\"div\");\n container.classList.add(\"pioneer-root\");\n container.style.minHeight = \"100%\";\n container.style.height = \"100%\";\n if (locale) {\n container.lang = locale;\n }\n return container;\n}\n\nfunction createServiceLayer(config: {\n packageMetadata: Record<string, PackageMetadata> | undefined;\n properties: ApplicationProperties;\n builtinPackage: PackageRepr;\n i18n: AppI18n;\n}) {\n const { packageMetadata, properties, builtinPackage, i18n } = config;\n\n let packages: PackageRepr[];\n try {\n packages = createPackages(packageMetadata ?? {}, i18n, properties);\n } catch (e) {\n throw new Error(ErrorId.INVALID_METADATA, \"Failed to parse package metadata.\", {\n cause: e\n });\n }\n\n // Add builtin services defined within this package.\n {\n const index = packages.findIndex((pkg) => pkg.name === builtinPackage.name);\n if (index >= 0) {\n packages.splice(index, 1);\n }\n packages.push(builtinPackage);\n }\n\n // Automatically required references (-> forces services to start)\n const forcedReferences: ReferenceSpec[] = [\n {\n interfaceName: RUNTIME_API_SERVICE\n },\n {\n interfaceName: RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE\n },\n {\n interfaceName: RUNTIME_AUTO_START,\n all: true\n }\n ];\n const serviceLayer = new ServiceLayer(packages, forcedReferences);\n return {\n packages: new Map(packages.map((pkg) => [pkg.name, pkg])),\n serviceLayer: serviceLayer\n };\n}\n\nfunction getInternalService<T = unknown>(serviceLayer: ServiceLayer, interfaceName: string) {\n const result = serviceLayer.getService(\n \"@open-pioneer/runtime\",\n {\n interfaceName\n },\n { ignoreDeclarationCheck: true }\n );\n if (result.type !== \"found\") {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find instance of '${interfaceName}' (result type '${result.type}').` +\n ` This is a builtin service that must be present exactly once.`\n );\n }\n\n return result.value.getInstanceOrThrow() as T;\n}\n\n/**\n * Gathers application properties by reading them from the options object\n * and by (optionally) invoking the `resolveProperties` hook.\n */\nasync function gatherConfig(\n hostElement: HTMLElement,\n options: CustomElementOptions,\n overrides?: ApplicationOverrides\n) {\n let configs: ApplicationConfig[];\n try {\n const staticConfig = options.config ?? {};\n const dynamicConfig =\n (await options.resolveConfig?.({\n hostElement,\n getAttribute(name) {\n return hostElement.getAttribute(name) ?? undefined;\n }\n })) ?? {};\n\n configs = [staticConfig, dynamicConfig];\n } catch (e) {\n throw new Error(\n ErrorId.CONFIG_RESOLUTION_FAILED,\n \"Failed to resolve application properties.\",\n {\n cause: e\n }\n );\n }\n\n const merged = mergeConfigs(configs);\n if (overrides?.locale) {\n merged.locale = overrides.locale;\n }\n return merged;\n}\n\n/**\n * Merges application configurations into a single object.\n * Properties / config parameters at a later position overwrite properties from earlier ones.\n */\nfunction mergeConfigs(configs: ApplicationConfig[]): Required<ApplicationConfig> {\n // Merge simple values by assigning them in order\n const mergedConfig: Required<ApplicationConfig> = Object.assign(\n {\n locale: undefined,\n properties: {}\n } satisfies ApplicationConfig,\n ...configs\n );\n\n // Deep merge for application properties\n const mergedProperties: ApplicationProperties = (mergedConfig.properties = {});\n for (const config of configs) {\n for (const [packageName, packageProperties] of Object.entries(config.properties ?? {})) {\n const mergedPackageProps = (mergedProperties[packageName] ??= {});\n Object.assign(mergedPackageProps, packageProperties);\n }\n }\n\n return mergedConfig;\n}\n\n// Applies application styles to the given style node.\n// Can be called multiple times in development mode to implement hot reloading.\nfunction applyStyles(styleNode: HTMLStyleElement, styles: { value: string } | undefined) {\n let cssValue = styles?.value ?? \"\";\n // Remove sourcemaps from inline css.\n // This currently does not work because a) the 'importer' (the index.html file) does not\n // match the actual path the source map would exist and b) vite refuses to generate it anyway, probably\n // because of our virtual modules.\n // TODO: both should be fixed once we can refer to actual `.css` files\n // and don't have to embed inline css anymore.\n cssValue = cssValue.replace(/\\/\\*# sourceMappingURL=.*$/, \"\");\n const cssNode = document.createTextNode(cssValue);\n styleNode.replaceChildren(cssNode);\n}\n\nfunction logError(e: unknown) {\n if (e instanceof Error) {\n const chain = getErrorChain(e).reverse();\n if (chain.length === 1) {\n console.error(e);\n return;\n }\n\n let n = 1;\n for (const error of chain) {\n console.error(`#${n}`, error);\n ++n;\n }\n } else {\n console.error(\"Unexpected error\", e);\n }\n}\n\nfunction emptyComponent() {\n return null;\n}\n"],"names":[],"mappings":";;;;;;;;AA8BA,MAAM,GAAA,GAAM,aAAa,uBAAuB,CAAA,CAAA;AAwHzC,SAAS,oBAAoB,OAA8D,EAAA;AAAA,EAC9F,MAAM,2BAA2B,WAA0C,CAAA;AAAA,IACvE,WAAA,CAAA;AAAA,IACA,SAAA,CAAA;AAAA;AAAA,IAGA,gBAAA,CAAA;AAAA;AAAA,IAEA,WAAW,kBAA+B,GAAA;AACtC,MAAA,OAAO,EAAC,CAAA;AAAA,KACZ;AAAA,IAEA,WAAc,GAAA;AACV,MAAM,KAAA,EAAA,CAAA;AAEN,MAAK,IAAA,CAAA,WAAA,GAAc,KAAK,YAAa,CAAA;AAAA,QACjC,IAAM,EAAA,MAAA;AAAA,OACT,CAAA,CAAA;AAED,MAAI,IAAA,MAAA,CAAA,IAAA,CAAY,IAAI,GAAK,EAAA;AAErB,QAAC,IAAA,CAAa,oBAAuB,GAAA,MAAM,IAAK,CAAA,SAAA,CAAA;AAAA,OACpD;AAAA,KACJ;AAAA,IAEA,iBAAoB,GAAA;AAChB,MAAA,GAAA,CAAI,MAAM,uBAAuB,CAAA,CAAA;AAEjC,MAAA,IAAI,KAAK,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O,EAAA;AACpB,IAAA,MAAM,KAAQ,GAAA,aAAA,CAAc,CAAC,CAAA,CAAE,OAAQ,EAAA,CAAA;AACvC,IAAI,IAAA,KAAA,CAAM,WAAW,CAAG,EAAA;AACpB,MAAA,OAAA,CAAQ,MAAM,CAAC,CAAA,CAAA;AACf,MAAA,OAAA;AAAA,KACJ;AAEA,IAAA,IAAI,CAAI,GAAA,CAAA,CAAA;AACR,IAAA,KAAA,MAAW,SAAS,KAAO,EAAA;AACvB,MAAA,OAAA,CAAQ,KAAM,CAAA,CAAA,CAAA,EAAI,CAAC,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA;AAC5B,MAAE,EAAA,CAAA,CAAA;AAAA,KACN;AAAA,GACG,MAAA;AACH,IAAQ,OAAA,CAAA,KAAA,CAAM,oBAAoB,CAAC,CAAA,CAAA;AAAA,GACvC;AACJ,CAAA;AAEA,SAAS,cAAiB,GAAA;AACtB,EAAO,OAAA,IAAA,CAAA;AACX;;;;"}
package/api.d.ts CHANGED
@@ -34,6 +34,7 @@ export interface ApplicationContext extends DeclaredService<"runtime.Application
34
34
  getHostElement(): HTMLElement;
35
35
  /**
36
36
  * The current web component's shadow root.
37
+ * This shadow root is located inside the host element.
37
38
  */
38
39
  getShadowRoot(): ShadowRoot;
39
40
  /**
@@ -46,6 +47,15 @@ export interface ApplicationContext extends DeclaredService<"runtime.Application
46
47
  * E.g. `"de-DE"`
47
48
  */
48
49
  getLocale(): string;
50
+ /**
51
+ * Changes the application's locale.
52
+ * `locale` must be one of the supported locales, see {@link getSupportedLocales()} or `undefined` (for automatic locale).
53
+ * Note that `locale` does not need to be a precise match, e.g. `"de-DE"` is also valid if `"de"` is supported.
54
+ *
55
+ * > NOTE: This method will currently trigger a full restart of the application.
56
+ * > Altering the locale on the fly is possible in theory but has not been implemented yet.
57
+ */
58
+ setLocale(locale: string | undefined): void;
49
59
  /**
50
60
  * Returns the locales supported by the application, i.e.
51
61
  * the locales that have associated i18n messages.
@@ -6,6 +6,8 @@ export interface ApplicationContextProperties {
6
6
  container: HTMLElement;
7
7
  locale: string;
8
8
  supportedLocales: string[];
9
+ /** A callback to change the application's locale is injected by the runtime. */
10
+ changeLocale(locale: string): void;
9
11
  }
10
12
  export declare class ApplicationContextImpl implements ApplicationContext {
11
13
  #private;
@@ -14,5 +16,6 @@ export declare class ApplicationContextImpl implements ApplicationContext {
14
16
  getShadowRoot(): ShadowRoot;
15
17
  getApplicationContainer(): HTMLElement;
16
18
  getLocale(): string;
19
+ setLocale(locale: string): void;
17
20
  getSupportedLocales(): readonly string[];
18
21
  }
@@ -4,12 +4,14 @@ class ApplicationContextImpl {
4
4
  #container;
5
5
  #locale;
6
6
  #supportedLocales;
7
+ #changeLocale;
7
8
  constructor(options, properties) {
8
9
  this.#host = properties.host;
9
10
  this.#shadowRoot = properties.shadowRoot;
10
11
  this.#container = properties.container;
11
12
  this.#locale = properties.locale;
12
13
  this.#supportedLocales = Object.freeze(Array.from(properties.supportedLocales));
14
+ this.#changeLocale = properties.changeLocale;
13
15
  }
14
16
  getHostElement() {
15
17
  return this.#host;
@@ -23,6 +25,9 @@ class ApplicationContextImpl {
23
25
  getLocale() {
24
26
  return this.#locale;
25
27
  }
28
+ setLocale(locale) {
29
+ this.#changeLocale(locale);
30
+ }
26
31
  getSupportedLocales() {
27
32
  return this.#supportedLocales;
28
33
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ApplicationContextImpl.js","sources":["ApplicationContextImpl.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { ApplicationContext } from \"../api\";\nimport { ServiceOptions } from \"../Service\";\n\nexport interface ApplicationContextProperties {\n host: HTMLElement;\n shadowRoot: ShadowRoot;\n container: HTMLElement;\n locale: string;\n supportedLocales: string[];\n}\n\nexport class ApplicationContextImpl implements ApplicationContext {\n #host: HTMLElement;\n #shadowRoot: ShadowRoot;\n #container: HTMLElement;\n #locale: string;\n #supportedLocales: readonly string[];\n\n constructor(options: ServiceOptions, properties: ApplicationContextProperties) {\n this.#host = properties.host;\n this.#shadowRoot = properties.shadowRoot;\n this.#container = properties.container;\n this.#locale = properties.locale;\n this.#supportedLocales = Object.freeze(Array.from(properties.supportedLocales));\n }\n\n getHostElement(): HTMLElement {\n return this.#host;\n }\n\n getShadowRoot(): ShadowRoot {\n return this.#shadowRoot;\n }\n\n getApplicationContainer(): HTMLElement {\n return this.#container;\n }\n\n getLocale(): string {\n return this.#locale;\n }\n\n getSupportedLocales(): readonly string[] {\n return this.#supportedLocales;\n }\n}\n"],"names":[],"mappings":"AAaO,MAAM,sBAAqD,CAAA;AAAA,EAC9D,KAAA,CAAA;AAAA,EACA,WAAA,CAAA;AAAA,EACA,UAAA,CAAA;AAAA,EACA,OAAA,CAAA;AAAA,EACA,iBAAA,CAAA;AAAA,EAEA,WAAA,CAAY,SAAyB,UAA0C,EAAA;AAC3E,IAAA,IAAA,CAAK,QAAQ,UAAW,CAAA,IAAA,CAAA;AACxB,IAAA,IAAA,CAAK,cAAc,UAAW,CAAA,UAAA,CAAA;AAC9B,IAAA,IAAA,CAAK,aAAa,UAAW,CAAA,SAAA,CAAA;AAC7B,IAAA,IAAA,CAAK,UAAU,UAAW,CAAA,MAAA,CAAA;AAC1B,IAAA,IAAA,CAAK,oBAAoB,MAAO,CAAA,MAAA,CAAO,MAAM,IAAK,CAAA,UAAA,CAAW,gBAAgB,CAAC,CAAA,CAAA;AAAA,GAClF;AAAA,EAEA,cAA8B,GAAA;AAC1B,IAAA,OAAO,IAAK,CAAA,KAAA,CAAA;AAAA,GAChB;AAAA,EAEA,aAA4B,GAAA;AACxB,IAAA,OAAO,IAAK,CAAA,WAAA,CAAA;AAAA,GAChB;AAAA,EAEA,uBAAuC,GAAA;AACnC,IAAA,OAAO,IAAK,CAAA,UAAA,CAAA;AAAA,GAChB;AAAA,EAEA,SAAoB,GAAA;AAChB,IAAA,OAAO,IAAK,CAAA,OAAA,CAAA;AAAA,GAChB;AAAA,EAEA,mBAAyC,GAAA;AACrC,IAAA,OAAO,IAAK,CAAA,iBAAA,CAAA;AAAA,GAChB;AACJ;;;;"}
1
+ {"version":3,"file":"ApplicationContextImpl.js","sources":["ApplicationContextImpl.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { ApplicationContext } from \"../api\";\nimport { ServiceOptions } from \"../Service\";\n\nexport interface ApplicationContextProperties {\n host: HTMLElement;\n shadowRoot: ShadowRoot;\n container: HTMLElement;\n locale: string;\n supportedLocales: string[];\n\n /** A callback to change the application's locale is injected by the runtime. */\n changeLocale(locale: string): void;\n}\n\nexport class ApplicationContextImpl implements ApplicationContext {\n #host: HTMLElement;\n #shadowRoot: ShadowRoot;\n #container: HTMLElement;\n #locale: string;\n #supportedLocales: readonly string[];\n #changeLocale: (locale: string) => void;\n\n constructor(options: ServiceOptions, properties: ApplicationContextProperties) {\n this.#host = properties.host;\n this.#shadowRoot = properties.shadowRoot;\n this.#container = properties.container;\n this.#locale = properties.locale;\n this.#supportedLocales = Object.freeze(Array.from(properties.supportedLocales));\n this.#changeLocale = properties.changeLocale;\n }\n\n getHostElement(): HTMLElement {\n return this.#host;\n }\n\n getShadowRoot(): ShadowRoot {\n return this.#shadowRoot;\n }\n\n getApplicationContainer(): HTMLElement {\n return this.#container;\n }\n\n getLocale(): string {\n return this.#locale;\n }\n\n setLocale(locale: string): void {\n this.#changeLocale(locale);\n }\n\n getSupportedLocales(): readonly string[] {\n return this.#supportedLocales;\n }\n}\n"],"names":[],"mappings":"AAgBO,MAAM,sBAAqD,CAAA;AAAA,EAC9D,KAAA,CAAA;AAAA,EACA,WAAA,CAAA;AAAA,EACA,UAAA,CAAA;AAAA,EACA,OAAA,CAAA;AAAA,EACA,iBAAA,CAAA;AAAA,EACA,aAAA,CAAA;AAAA,EAEA,WAAA,CAAY,SAAyB,UAA0C,EAAA;AAC3E,IAAA,IAAA,CAAK,QAAQ,UAAW,CAAA,IAAA,CAAA;AACxB,IAAA,IAAA,CAAK,cAAc,UAAW,CAAA,UAAA,CAAA;AAC9B,IAAA,IAAA,CAAK,aAAa,UAAW,CAAA,SAAA,CAAA;AAC7B,IAAA,IAAA,CAAK,UAAU,UAAW,CAAA,MAAA,CAAA;AAC1B,IAAA,IAAA,CAAK,oBAAoB,MAAO,CAAA,MAAA,CAAO,MAAM,IAAK,CAAA,UAAA,CAAW,gBAAgB,CAAC,CAAA,CAAA;AAC9E,IAAA,IAAA,CAAK,gBAAgB,UAAW,CAAA,YAAA,CAAA;AAAA,GACpC;AAAA,EAEA,cAA8B,GAAA;AAC1B,IAAA,OAAO,IAAK,CAAA,KAAA,CAAA;AAAA,GAChB;AAAA,EAEA,aAA4B,GAAA;AACxB,IAAA,OAAO,IAAK,CAAA,WAAA,CAAA;AAAA,GAChB;AAAA,EAEA,uBAAuC,GAAA;AACnC,IAAA,OAAO,IAAK,CAAA,UAAA,CAAA;AAAA,GAChB;AAAA,EAEA,SAAoB,GAAA;AAChB,IAAA,OAAO,IAAK,CAAA,OAAA,CAAA;AAAA,GAChB;AAAA,EAEA,UAAU,MAAsB,EAAA;AAC5B,IAAA,IAAA,CAAK,cAAc,MAAM,CAAA,CAAA;AAAA,GAC7B;AAAA,EAEA,mBAAyC,GAAA;AACrC,IAAA,OAAO,IAAK,CAAA,iBAAA,CAAA;AAAA,GAChB;AACJ;;;;"}
package/i18n.d.ts CHANGED
@@ -8,7 +8,9 @@ export interface AppI18n {
8
8
  /** Chosen locale */
9
9
  readonly locale: string;
10
10
  /** Supported locales from app metadata. */
11
- readonly supportedLocales: string[];
11
+ readonly supportedMessageLocales: string[];
12
+ /** True if the locale can be used in this application (i.e. if there are any messages). */
13
+ supportsLocale(locale: string): boolean;
12
14
  /** Given the package name, constructs a package i18n instance. */
13
15
  createPackageI18n(packageName: string): PackageIntl;
14
16
  }
@@ -24,7 +26,7 @@ export type PackageIntl = Pick<IntlShape, "locale" | "timeZone"> & IntlFormatter
24
26
  export declare function initI18n(appMetadata: ApplicationMetadata | undefined, forcedLocale: string | undefined): Promise<AppI18n>;
25
27
  /** Creates an empty i18n instance, e.g. for tests. */
26
28
  export declare function createEmptyI18n(locale?: string): PackageIntl;
27
- export interface LocalePickResult {
29
+ interface LocalePickResult {
28
30
  /** The actual locale (e.g. en-US) for number and date formatting etc. */
29
31
  locale: string;
30
32
  /**
@@ -34,9 +36,19 @@ export interface LocalePickResult {
34
36
  }
35
37
  /**
36
38
  * Picks a locale for the app. Exported for tests.
37
- *
38
- * @param forcedLocale Optional forced locale (must be satisfied)
39
- * @param appLocales Locales the app has i18n messages for (e.g. "en", "de")
40
- * @param userLocales Locales requested by the user's browser
41
39
  */
42
- export declare function pickLocale(forcedLocale: string | undefined, appLocales: string[], userLocales: string[]): LocalePickResult;
40
+ export declare class I18nConfig {
41
+ private appLocales;
42
+ /**
43
+ * @param appLocales Locales the app has i18n messages for (e.g. "en", "de")
44
+ */
45
+ constructor(appLocales: string[]);
46
+ /**
47
+ * @param forcedLocale Optional forced locale (must be satisfied)
48
+ * @param userLocales Locales requested by the user's browser
49
+ */
50
+ pickSupportedLocale(forcedLocale: string | undefined, userLocales: string[]): LocalePickResult;
51
+ supportsLocale(locale: string): boolean;
52
+ private pickImpl;
53
+ }
54
+ export {};
package/i18n.js CHANGED
@@ -14,27 +14,24 @@ function createPackageIntl(locale, messages) {
14
14
  );
15
15
  }
16
16
  async function initI18n(appMetadata, forcedLocale) {
17
- const supportedLocales = appMetadata?.locales ?? [];
17
+ const messageLocales = appMetadata?.locales ?? [];
18
18
  const userLocales = getBrowserLocales();
19
19
  if (LOG.isDebug()) {
20
20
  LOG.debug(
21
21
  `Attempting to pick locale for user (locales: ${userLocales.join(
22
22
  ", "
23
- )}) from app (supported locales: ${supportedLocales.join(
23
+ )}) from app (supported locales: ${messageLocales.join(
24
24
  ", "
25
25
  )}) [forcedLocale=${forcedLocale}].`
26
26
  );
27
27
  }
28
- const { locale, messageLocale } = pickLocale(
29
- forcedLocale,
30
- supportedLocales,
31
- getBrowserLocales()
32
- );
28
+ const i18nConfig = new I18nConfig(messageLocales);
29
+ const { locale, messageLocale } = i18nConfig.pickSupportedLocale(forcedLocale, userLocales);
33
30
  if (LOG.isDebug()) {
34
31
  LOG.debug(`Using locale '${locale}' with messages from locale '${messageLocale}'.`);
35
32
  }
36
33
  let messages;
37
- if (supportedLocales.includes(messageLocale)) {
34
+ if (messageLocales.includes(messageLocale)) {
38
35
  try {
39
36
  messages = await appMetadata?.loadMessages?.(messageLocale) ?? {};
40
37
  } catch (e) {
@@ -49,7 +46,10 @@ async function initI18n(appMetadata, forcedLocale) {
49
46
  }
50
47
  return {
51
48
  locale,
52
- supportedLocales,
49
+ supportedMessageLocales: messageLocales,
50
+ supportsLocale(locale2) {
51
+ return i18nConfig.supportsLocale(locale2);
52
+ },
53
53
  createPackageI18n(packageName) {
54
54
  const packageMessage = messages?.[packageName] ?? {};
55
55
  return createPackageIntl(locale, packageMessage);
@@ -59,8 +59,50 @@ async function initI18n(appMetadata, forcedLocale) {
59
59
  function createEmptyI18n(locale = "en") {
60
60
  return createPackageIntl(locale, {});
61
61
  }
62
- function pickLocale(forcedLocale, appLocales, userLocales) {
63
- const pickImpl = (requestedLocales) => {
62
+ class I18nConfig {
63
+ appLocales;
64
+ /**
65
+ * @param appLocales Locales the app has i18n messages for (e.g. "en", "de")
66
+ */
67
+ constructor(appLocales) {
68
+ this.appLocales = appLocales;
69
+ }
70
+ /**
71
+ * @param forcedLocale Optional forced locale (must be satisfied)
72
+ * @param userLocales Locales requested by the user's browser
73
+ */
74
+ pickSupportedLocale(forcedLocale, userLocales) {
75
+ const { appLocales } = this;
76
+ if (forcedLocale) {
77
+ const result = this.pickImpl([forcedLocale]);
78
+ if (!result) {
79
+ const localesList = appLocales.join(", ");
80
+ throw new Error(
81
+ ErrorId.UNSUPPORTED_LOCALE,
82
+ `Locale '${forcedLocale}' cannot be forced because it is not supported by the application. Supported locales are ${localesList}.`
83
+ );
84
+ }
85
+ if (result.locale !== result.messageLocale) {
86
+ LOG.warn(
87
+ `Non-exact match for forced locale '${forcedLocale}': using messages from '${result.messageLocale}'.`
88
+ );
89
+ }
90
+ return result;
91
+ }
92
+ const supportedLocale = this.pickImpl(userLocales);
93
+ if (supportedLocale) {
94
+ return supportedLocale;
95
+ }
96
+ return {
97
+ locale: userLocales[0] ?? "en",
98
+ messageLocale: appLocales[0] ?? "en"
99
+ };
100
+ }
101
+ supportsLocale(locale) {
102
+ return this.pickImpl([locale]) != null;
103
+ }
104
+ pickImpl(requestedLocales) {
105
+ const appLocales = this.appLocales;
64
106
  for (const requestedLocale of requestedLocales) {
65
107
  if (appLocales.includes(requestedLocale)) {
66
108
  return { messageLocale: requestedLocale, locale: requestedLocale };
@@ -71,28 +113,7 @@ function pickLocale(forcedLocale, appLocales, userLocales) {
71
113
  }
72
114
  }
73
115
  return void 0;
74
- };
75
- if (forcedLocale) {
76
- const result = pickImpl([forcedLocale]);
77
- if (!result) {
78
- const localesList = appLocales.join(", ");
79
- throw new Error(
80
- ErrorId.UNSUPPORTED_LOCALE,
81
- `Locale '${forcedLocale}' cannot be forced because it is not supported by the application. Supported locales are ${localesList}.`
82
- );
83
- }
84
- if (result.locale !== result.messageLocale) {
85
- LOG.warn(
86
- `Non-exact match for forced locale '${forcedLocale}': using messages from '${result.messageLocale}'.`
87
- );
88
- }
89
- return result;
90
- }
91
- const supportedLocale = pickImpl(userLocales);
92
- if (supportedLocale) {
93
- return supportedLocale;
94
116
  }
95
- return { locale: userLocales[0] ?? "en", messageLocale: appLocales[0] ?? "en" };
96
117
  }
97
118
  function getBrowserLocales() {
98
119
  if (window.navigator.languages && window.navigator.languages.length) {
@@ -101,5 +122,5 @@ function getBrowserLocales() {
101
122
  return [window.navigator.language];
102
123
  }
103
124
 
104
- export { createEmptyI18n, initI18n, pickLocale };
125
+ export { I18nConfig, createEmptyI18n, initI18n };
105
126
  //# sourceMappingURL=i18n.js.map
package/i18n.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"i18n.js","sources":["i18n.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { createIntl, createIntlCache, IntlFormatters, IntlShape } from \"@formatjs/intl\";\nimport { ErrorId } from \"./errors\";\nimport { createLogger, Error } from \"@open-pioneer/core\";\nimport { ApplicationMetadata } from \"./metadata\";\nconst LOG = createLogger(\"runtime:i18n\");\n\n/**\n * Represents i18n info for the entire application.\n * Currently not exposed to user code.\n */\nexport interface AppI18n {\n /** Chosen locale */\n readonly locale: string;\n\n /** Supported locales from app metadata. */\n readonly supportedLocales: string[];\n\n /** Given the package name, constructs a package i18n instance. */\n createPackageI18n(packageName: string): PackageIntl;\n}\n\n/**\n * Gives access to the package's i18n messages for the current locale.\n *\n * See also https://formatjs.io/docs/intl\n */\nexport type PackageIntl = Pick<IntlShape, \"locale\" | \"timeZone\"> & IntlFormatters<string>;\n\nfunction createPackageIntl(locale: string, messages: Record<string, string>) {\n const cache = createIntlCache();\n return createIntl(\n {\n locale,\n messages\n },\n cache\n );\n}\n\n/**\n * Initializes the application's locale and fetches the appropriate i18n messages.\n */\nexport async function initI18n(\n appMetadata: ApplicationMetadata | undefined,\n forcedLocale: string | undefined\n): Promise<AppI18n> {\n const supportedLocales = appMetadata?.locales ?? [];\n const userLocales = getBrowserLocales();\n if (LOG.isDebug()) {\n LOG.debug(\n `Attempting to pick locale for user (locales: ${userLocales.join(\n \", \"\n )}) from app (supported locales: ${supportedLocales.join(\n \", \"\n )}) [forcedLocale=${forcedLocale}].`\n );\n }\n\n const { locale, messageLocale } = pickLocale(\n forcedLocale,\n supportedLocales,\n getBrowserLocales()\n );\n\n if (LOG.isDebug()) {\n LOG.debug(`Using locale '${locale}' with messages from locale '${messageLocale}'.`);\n }\n\n let messages: Record<string, Record<string, string>>;\n if (supportedLocales.includes(messageLocale)) {\n try {\n messages = (await appMetadata?.loadMessages?.(messageLocale)) ?? {};\n } catch (e) {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to load messages for locale '${messageLocale}'.`,\n {\n cause: e\n }\n );\n }\n }\n return {\n locale,\n supportedLocales,\n createPackageI18n(packageName) {\n const packageMessage = messages?.[packageName] ?? {};\n return createPackageIntl(locale, packageMessage);\n }\n };\n}\n\n/** Creates an empty i18n instance, e.g. for tests. */\nexport function createEmptyI18n(locale = \"en\"): PackageIntl {\n return createPackageIntl(locale, {});\n}\n\nexport interface LocalePickResult {\n /** The actual locale (e.g. en-US) for number and date formatting etc. */\n locale: string;\n\n /**\n * The locale identifier to load messages for. E.g. \"en\".\n */\n messageLocale: string;\n}\n\n/**\n * Picks a locale for the app. Exported for tests.\n *\n * @param forcedLocale Optional forced locale (must be satisfied)\n * @param appLocales Locales the app has i18n messages for (e.g. \"en\", \"de\")\n * @param userLocales Locales requested by the user's browser\n */\nexport function pickLocale(\n forcedLocale: string | undefined,\n appLocales: string[],\n userLocales: string[]\n): LocalePickResult {\n const pickImpl = (requestedLocales: string[]): LocalePickResult | undefined => {\n for (const requestedLocale of requestedLocales) {\n // try exact match\n if (appLocales.includes(requestedLocale)) {\n return { messageLocale: requestedLocale, locale: requestedLocale };\n }\n\n // try plain language tag (e.g. \"en\") as fallback\n const plainLanguage = requestedLocale.match(/^([a-z]+)/i)?.[1];\n if (plainLanguage && appLocales.includes(plainLanguage)) {\n return { messageLocale: plainLanguage, locale: requestedLocale };\n }\n }\n return undefined;\n };\n\n // Attempt to satisfy forced locale\n if (forcedLocale) {\n const result = pickImpl([forcedLocale]);\n if (!result) {\n const localesList = appLocales.join(\", \");\n throw new Error(\n ErrorId.UNSUPPORTED_LOCALE,\n `Locale '${forcedLocale}' cannot be forced because it is not supported by the application.` +\n ` Supported locales are ${localesList}.`\n );\n }\n if (result.locale !== result.messageLocale) {\n LOG.warn(\n `Non-exact match for forced locale '${forcedLocale}': using messages from '${result.messageLocale}'.`\n );\n }\n return result;\n }\n\n // Match preferred locale\n const supportedLocale = pickImpl(userLocales);\n if (supportedLocale) {\n return supportedLocale;\n }\n\n // Fallback: Most preferred locale (for dates etc.), but some of our messages\n return { locale: userLocales[0] ?? \"en\", messageLocale: appLocales[0] ?? \"en\" };\n}\n\n/**\n * Returns locales supported by the browser, in order of preference (preferred first).\n *\n * See also https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages\n */\nfunction getBrowserLocales(): string[] {\n if (window.navigator.languages && window.navigator.languages.length) {\n return Array.from(window.navigator.languages);\n }\n return [window.navigator.language];\n}\n"],"names":[],"mappings":";;;;AAMA,MAAM,GAAA,GAAM,aAAa,cAAc,CAAA,CAAA;AAwBvC,SAAS,iBAAA,CAAkB,QAAgB,QAAkC,EAAA;AACzE,EAAA,MAAM,QAAQ,eAAgB,EAAA,CAAA;AAC9B,EAAO,OAAA,UAAA;AAAA,IACH;AAAA,MACI,MAAA;AAAA,MACA,QAAA;AAAA,KACJ;AAAA,IACA,KAAA;AAAA,GACJ,CAAA;AACJ,CAAA;AAKsB,eAAA,QAAA,CAClB,aACA,YACgB,EAAA;AAChB,EAAM,MAAA,gBAAA,GAAmB,WAAa,EAAA,OAAA,IAAW,EAAC,CAAA;AAClD,EAAA,MAAM,cAAc,iBAAkB,EAAA,CAAA;AACtC,EAAI,IAAA,GAAA,CAAI,SAAW,EAAA;AACf,IAAI,GAAA,CAAA,KAAA;AAAA,MACA,gDAAgD,WAAY,CAAA,IAAA;AAAA,QACxD,IAAA;AAAA,OACH,kCAAkC,gBAAiB,CAAA,IAAA;AAAA,QAChD,IAAA;AAAA,OACH,mBAAmB,YAAY,CAAA,EAAA,CAAA;AAAA,KACpC,CAAA;AAAA,GACJ;AAEA,EAAM,MAAA,EAAE,MAAQ,EAAA,aAAA,EAAkB,GAAA,UAAA;AAAA,IAC9B,YAAA;AAAA,IACA,gBAAA;AAAA,IACA,iBAAkB,EAAA;AAAA,GACtB,CAAA;AAEA,EAAI,IAAA,GA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,CAAA;AAClF,CAAA;AAOA,SAAS,iBAA8B,GAAA;AACnC,EAAA,IAAI,OAAO,SAAU,CAAA,SAAA,IAAa,MAAO,CAAA,SAAA,CAAU,UAAU,MAAQ,EAAA;AACjE,IAAA,OAAO,KAAM,CAAA,IAAA,CAAK,MAAO,CAAA,SAAA,CAAU,SAAS,CAAA,CAAA;AAAA,GAChD;AACA,EAAO,OAAA,CAAC,MAAO,CAAA,SAAA,CAAU,QAAQ,CAAA,CAAA;AACrC;;;;"}
1
+ {"version":3,"file":"i18n.js","sources":["i18n.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { createIntl, createIntlCache, IntlFormatters, IntlShape } from \"@formatjs/intl\";\nimport { ErrorId } from \"./errors\";\nimport { createLogger, Error } from \"@open-pioneer/core\";\nimport { ApplicationMetadata } from \"./metadata\";\nconst LOG = createLogger(\"runtime:i18n\");\n\n/**\n * Represents i18n info for the entire application.\n * Currently not exposed to user code.\n */\nexport interface AppI18n {\n /** Chosen locale */\n readonly locale: string;\n\n /** Supported locales from app metadata. */\n readonly supportedMessageLocales: string[];\n\n /** True if the locale can be used in this application (i.e. if there are any messages). */\n supportsLocale(locale: string): boolean;\n\n /** Given the package name, constructs a package i18n instance. */\n createPackageI18n(packageName: string): PackageIntl;\n}\n\n/**\n * Gives access to the package's i18n messages for the current locale.\n *\n * See also https://formatjs.io/docs/intl\n */\nexport type PackageIntl = Pick<IntlShape, \"locale\" | \"timeZone\"> & IntlFormatters<string>;\n\nfunction createPackageIntl(locale: string, messages: Record<string, string>) {\n const cache = createIntlCache();\n return createIntl(\n {\n locale,\n messages\n },\n cache\n );\n}\n\n/**\n * Initializes the application's locale and fetches the appropriate i18n messages.\n */\nexport async function initI18n(\n appMetadata: ApplicationMetadata | undefined,\n forcedLocale: string | undefined\n): Promise<AppI18n> {\n const messageLocales = appMetadata?.locales ?? [];\n const userLocales = getBrowserLocales();\n if (LOG.isDebug()) {\n LOG.debug(\n `Attempting to pick locale for user (locales: ${userLocales.join(\n \", \"\n )}) from app (supported locales: ${messageLocales.join(\n \", \"\n )}) [forcedLocale=${forcedLocale}].`\n );\n }\n\n const i18nConfig = new I18nConfig(messageLocales);\n const { locale, messageLocale } = i18nConfig.pickSupportedLocale(forcedLocale, userLocales);\n\n if (LOG.isDebug()) {\n LOG.debug(`Using locale '${locale}' with messages from locale '${messageLocale}'.`);\n }\n\n let messages: Record<string, Record<string, string>>;\n if (messageLocales.includes(messageLocale)) {\n try {\n messages = (await appMetadata?.loadMessages?.(messageLocale)) ?? {};\n } catch (e) {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to load messages for locale '${messageLocale}'.`,\n {\n cause: e\n }\n );\n }\n }\n return {\n locale,\n supportedMessageLocales: messageLocales,\n supportsLocale(locale) {\n return i18nConfig.supportsLocale(locale);\n },\n createPackageI18n(packageName) {\n const packageMessage = messages?.[packageName] ?? {};\n return createPackageIntl(locale, packageMessage);\n }\n };\n}\n\n/** Creates an empty i18n instance, e.g. for tests. */\nexport function createEmptyI18n(locale = \"en\"): PackageIntl {\n return createPackageIntl(locale, {});\n}\n\ninterface LocalePickResult {\n /** The actual locale (e.g. en-US) for number and date formatting etc. */\n locale: string;\n\n /**\n * The locale identifier to load messages for. E.g. \"en\".\n */\n messageLocale: string;\n}\n\n/**\n * Picks a locale for the app. Exported for tests.\n */\nexport class I18nConfig {\n private appLocales: string[];\n\n /**\n * @param appLocales Locales the app has i18n messages for (e.g. \"en\", \"de\")\n */\n constructor(appLocales: string[]) {\n this.appLocales = appLocales;\n }\n\n /**\n * @param forcedLocale Optional forced locale (must be satisfied)\n * @param userLocales Locales requested by the user's browser\n */\n pickSupportedLocale(forcedLocale: string | undefined, userLocales: string[]): LocalePickResult {\n const { appLocales } = this;\n // Attempt to satisfy forced locale\n if (forcedLocale) {\n const result = this.pickImpl([forcedLocale]);\n if (!result) {\n const localesList = appLocales.join(\", \");\n throw new Error(\n ErrorId.UNSUPPORTED_LOCALE,\n `Locale '${forcedLocale}' cannot be forced because it is not supported by the application.` +\n ` Supported locales are ${localesList}.`\n );\n }\n if (result.locale !== result.messageLocale) {\n LOG.warn(\n `Non-exact match for forced locale '${forcedLocale}': using messages from '${result.messageLocale}'.`\n );\n }\n return result;\n }\n\n // Match preferred locale\n const supportedLocale = this.pickImpl(userLocales);\n if (supportedLocale) {\n return supportedLocale;\n }\n\n // Fallback: Most preferred locale (for dates etc.), but some of our messages\n return {\n locale: userLocales[0] ?? \"en\",\n messageLocale: appLocales[0] ?? \"en\"\n };\n }\n\n supportsLocale(locale: string): boolean {\n return this.pickImpl([locale]) != null;\n }\n\n private pickImpl(requestedLocales: string[]) {\n const appLocales = this.appLocales;\n for (const requestedLocale of requestedLocales) {\n // try exact match\n if (appLocales.includes(requestedLocale)) {\n return { messageLocale: requestedLocale, locale: requestedLocale };\n }\n\n // try plain language tag (e.g. \"en\") as fallback\n const plainLanguage = requestedLocale.match(/^([a-z]+)/i)?.[1];\n if (plainLanguage && appLocales.includes(plainLanguage)) {\n return { messageLocale: plainLanguage, locale: requestedLocale };\n }\n }\n return undefined;\n }\n}\n\n/**\n * Returns locales supported by the browser, in order of preference (preferred first).\n *\n * See also https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages\n */\nfunction getBrowserLocales(): string[] {\n if (window.navigator.languages && window.navigator.languages.length) {\n return Array.from(window.navigator.languages);\n }\n return [window.navigator.language];\n}\n"],"names":["locale"],"mappings":";;;;AAMA,MAAM,GAAA,GAAM,aAAa,cAAc,CAAA,CAAA;AA2BvC,SAAS,iBAAA,CAAkB,QAAgB,QAAkC,EAAA;AACzE,EAAA,MAAM,QAAQ,eAAgB,EAAA,CAAA;AAC9B,EAAO,OAAA,UAAA;AAAA,IACH;AAAA,MACI,MAAA;AAAA,MACA,QAAA;AAAA,KACJ;AAAA,IACA,KAAA;AAAA,GACJ,CAAA;AACJ,CAAA;AAKsB,eAAA,QAAA,CAClB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AA,CAAU,UAAU,MAAQ,EAAA;AACjE,IAAA,OAAO,KAAM,CAAA,IAAA,CAAK,MAAO,CAAA,SAAA,CAAU,SAAS,CAAA,CAAA;AAAA,GAChD;AACA,EAAO,OAAA,CAAC,MAAO,CAAA,SAAA,CAAU,QAAQ,CAAA,CAAA;AACrC;;;;"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@open-pioneer/runtime",
4
- "version": "2.1.4",
4
+ "version": "2.1.5",
5
5
  "description": "Implements the runtime environment for Open Pioneer Trails apps.",
6
6
  "keywords": [
7
7
  "open-pioneer-trails"
@@ -18,9 +18,9 @@
18
18
  "react": "^18.3.1",
19
19
  "react-dom": "^18.2.0",
20
20
  "@open-pioneer/base-theme": "^0.3.2",
21
- "@open-pioneer/chakra-integration": "^1.1.3",
21
+ "@open-pioneer/runtime-react-support": "^1.0.2",
22
22
  "@open-pioneer/core": "^1.2.3",
23
- "@open-pioneer/runtime-react-support": "^1.0.2"
23
+ "@open-pioneer/chakra-integration": "^1.1.3"
24
24
  },
25
25
  "exports": {
26
26
  "./package.json": "./package.json",