@equinor/fusion-framework-dev-server 2.1.0 → 2.1.1

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.
@@ -1,124 +0,0 @@
1
- import { defineConfig, mergeConfig, type UserConfig } from 'vite';
2
-
3
- import reactPlugin from '@vitejs/plugin-react';
4
-
5
- import apiServicePlugin, {
6
- createProxyHandler,
7
- } from '@equinor/fusion-framework-vite-plugin-api-service';
8
-
9
- import fusionSpaPlugin from '@equinor/fusion-framework-vite-plugin-spa';
10
- import { ConsoleLogger, LogLevel } from '@equinor/fusion-log';
11
-
12
- import { processServices as defaultProcessServices } from './process-services.js';
13
-
14
- import type { DevServerOptions, TemplateEnv, TemplateEnvFn } from './types.js';
15
-
16
- /**
17
- * Create a default {@link ConsoleLogger} instance for the dev server.
18
- *
19
- * @param lvl - Log verbosity level; defaults to {@link LogLevel.Info}.
20
- * @param title - Logger title printed as a prefix in console output; defaults to `'dev-server'`.
21
- * @returns A configured {@link ConsoleLogger} instance.
22
- */
23
- const createDefaultLogger = (lvl: LogLevel = LogLevel.Info, title = 'dev-server') => {
24
- const logger = new ConsoleLogger(title);
25
- logger.level = lvl;
26
- return logger;
27
- };
28
-
29
- /**
30
- * Build a Vite {@link import('vite').UserConfig | UserConfig} for a Fusion Framework dev server
31
- * without starting the server.
32
- *
33
- * Use this function when you need control over the server lifecycle (e.g. to pass the config
34
- * to another Vite tool). For a simpler create-and-listen workflow, use {@link createDevServer}.
35
- *
36
- * The generated config includes:
37
- * - `@vitejs/plugin-react` for React Fast Refresh / HMR
38
- * - `@equinor/fusion-framework-vite-plugin-api-service` for service discovery proxying
39
- * - `@equinor/fusion-framework-vite-plugin-spa` for template environment injection
40
- * - CORS disabled so backend services handle OPTIONS with proper headers
41
- *
42
- * @template TEnv - Environment variable shape extending `Partial<TemplateEnv>`, used to type-check
43
- * the SPA template environment object or factory function.
44
- * @param options - Development server options containing SPA, API, and logging settings.
45
- * @param overrides - Optional Vite config merged on top of the generated base config via
46
- * {@link import('vite').mergeConfig | mergeConfig}.
47
- * @returns A fully resolved Vite `UserConfig` ready for {@link import('vite').createServer | createServer}.
48
- *
49
- * @remarks
50
- * - `spa.templateEnv` accepts either a static object or a factory function returning the environment.
51
- * - `api.processServices` defaults to the built-in {@link processServices} when omitted.
52
- * - The default log level is `Info`; set `log.level` to `4` for debug output.
53
- *
54
- * @example
55
- * ```typescript
56
- * import { createDevServerConfig } from '@equinor/fusion-framework-dev-server';
57
- * import { createServer } from 'vite';
58
- *
59
- * const config = createDevServerConfig({
60
- * spa: {
61
- * templateEnv: {
62
- * portal: { id: 'my-portal' },
63
- * title: 'My App',
64
- * serviceDiscovery: { url: 'https://discovery.example.com', scopes: [] },
65
- * msal: { clientId: 'cid', tenantId: 'tid', redirectUri: '/auth/cb', requiresAuth: 'true' },
66
- * },
67
- * },
68
- * api: { serviceDiscoveryUrl: 'https://discovery.example.com' },
69
- * });
70
- *
71
- * const server = await createServer(config);
72
- * await server.listen();
73
- * ```
74
- */
75
- export const createDevServerConfig = <TEnv extends Partial<TemplateEnv>>(
76
- options: DevServerOptions<TEnv>,
77
- overrides?: UserConfig,
78
- ): UserConfig => {
79
- const { spa, api, log } = options;
80
- const processServices = api.processServices ?? defaultProcessServices;
81
- const generateTemplateEnv: TemplateEnvFn<TEnv> =
82
- // ensure that the templateEnv is a function
83
- typeof spa?.templateEnv === 'function'
84
- ? spa.templateEnv
85
- : () => spa?.templateEnv as Partial<TEnv>;
86
-
87
- // setup log instance
88
- const logger = log?.logger ?? createDefaultLogger(log?.level);
89
-
90
- const apiServiceLogger = logger.createSubLogger('api-service');
91
- const spaLogger = logger.createSubLogger('spa');
92
-
93
- const baseConfig = defineConfig({
94
- appType: 'custom',
95
- define: {
96
- 'process.env': JSON.stringify({
97
- FUSION_LOG_LEVEL: String(logger.level),
98
- }),
99
- },
100
- server: {
101
- // Disable Vite's internal CORS handling to allow backend to handle OPTIONS requests properly
102
- // This ensures that OPTIONS requests are forwarded to the backend with proper headers
103
- cors: false,
104
- },
105
- plugins: [
106
- reactPlugin(),
107
- apiServicePlugin(
108
- {
109
- proxyHandler: createProxyHandler(api.serviceDiscoveryUrl, processServices, {
110
- logger: apiServiceLogger,
111
- }),
112
- routes: api.routes,
113
- },
114
- {
115
- logger: apiServiceLogger,
116
- },
117
- ),
118
- fusionSpaPlugin({ generateTemplateEnv, logger: spaLogger }),
119
- ],
120
- });
121
- return mergeConfig(baseConfig, overrides ?? {});
122
- };
123
-
124
- export default createDevServerConfig;
@@ -1,48 +0,0 @@
1
- import { createServer, type UserConfig } from 'vite';
2
- import { createDevServerConfig } from './create-dev-server-config.js';
3
-
4
- import type { DevServerOptions } from './types.js';
5
-
6
- /**
7
- * Create and return a fully configured Vite development server for a Fusion Framework application.
8
- *
9
- * Combines SPA template environment injection, service discovery proxying, and React HMR into
10
- * a single ready-to-listen server instance. Use this function when you want the default
11
- * development workflow; use {@link createDevServerConfig} instead if you only need the Vite
12
- * configuration object without starting the server.
13
- *
14
- * @param options - Development server configuration including SPA template environment,
15
- * API proxy settings, and optional logging overrides.
16
- * @param overrides - Optional Vite {@link import('vite').UserConfig | UserConfig} merged on top
17
- * of the generated configuration (e.g. custom port, extra plugins).
18
- * @returns A promise that resolves to a Vite {@link import('vite').ViteDevServer | ViteDevServer}
19
- * ready for {@link import('vite').ViteDevServer.listen | listen()} and
20
- * {@link import('vite').ViteDevServer.printUrls | printUrls()}.
21
- *
22
- * @example
23
- * ```typescript
24
- * import { createDevServer } from '@equinor/fusion-framework-dev-server';
25
- *
26
- * const server = await createDevServer({
27
- * spa: {
28
- * templateEnv: {
29
- * portal: { id: 'my-portal' },
30
- * title: 'My App',
31
- * serviceDiscovery: { url: 'https://discovery.example.com', scopes: [] },
32
- * msal: { clientId: 'id', tenantId: 'tid', redirectUri: '/auth/callback', requiresAuth: 'true' },
33
- * },
34
- * },
35
- * api: { serviceDiscoveryUrl: 'https://discovery.example.com' },
36
- * });
37
- *
38
- * await server.listen();
39
- * server.printUrls();
40
- * ```
41
- */
42
- export const createDevServer = async (options: DevServerOptions, overrides?: UserConfig) => {
43
- const config = createDevServerConfig(options, overrides);
44
- const server = await createServer(config);
45
- return server;
46
- };
47
-
48
- export default createDevServer;
package/src/index.ts DELETED
@@ -1,40 +0,0 @@
1
- /**
2
- * @packageDocumentation
3
- *
4
- * Development server for Fusion Framework applications.
5
- *
6
- * Provides a pre-configured Vite dev server with integrated service discovery proxying,
7
- * SPA template environment injection, and React HMR support. Use this package when you
8
- * need a local development environment that mirrors production Fusion portal behaviour.
9
- *
10
- * @remarks
11
- * Main entry points:
12
- * - {@link createDevServer} — create and start a fully configured Vite dev server
13
- * - {@link createDevServerConfig} — build a Vite `UserConfig` without starting the server
14
- * - {@link processServices} — remap Fusion service URIs to local proxy routes
15
- *
16
- * @example
17
- * ```typescript
18
- * import { createDevServer } from '@equinor/fusion-framework-dev-server';
19
- *
20
- * const server = await createDevServer({
21
- * api: { serviceDiscoveryUrl: 'https://discovery.example.com' },
22
- * });
23
- * await server.listen();
24
- * server.printUrls();
25
- * ```
26
- */
27
-
28
- /** Re-export of Vite's {@link import('vite').UserConfig | UserConfig} for consumer convenience when passing overrides. */
29
- export type { UserConfig } from 'vite';
30
-
31
- export { processServices } from './process-services.js';
32
-
33
- export { default, createDevServer } from './create-dev-server.js';
34
-
35
- export { createDevServerConfig } from './create-dev-server-config.js';
36
-
37
- /** Re-export of the SPA template environment type used to configure portal, MSAL, and service discovery settings. */
38
- export type { FusionTemplateEnv } from '@equinor/fusion-framework-vite-plugin-spa';
39
-
40
- export * from './types.js';
@@ -1,36 +0,0 @@
1
- import { IncomingMessage } from 'node:http';
2
- import { Socket } from 'node:net';
3
-
4
- import { describe, expect, it } from 'vitest';
5
-
6
- import { processServices } from './process-services.js';
7
-
8
- const request = new IncomingMessage(new Socket());
9
- request.headers.referer = 'http://localhost:3000';
10
-
11
- describe('processServices', () => {
12
- it('proxies localhost subdomains through the portable shared-host route', () => {
13
- const result = processServices(
14
- [{ key: 'people', name: 'People', uri: 'http://people.localhost:4010' }],
15
- { route: '/@fusion-api', request },
16
- );
17
-
18
- expect(result.routes).toEqual([
19
- {
20
- match: '/people/*sub',
21
- proxy: { target: 'http://localhost:4010' },
22
- },
23
- ]);
24
- });
25
-
26
- it('preserves normal upstream proxy targets and path rewriting', () => {
27
- const result = processServices(
28
- [{ key: 'people', name: 'People', uri: 'https://people.example/api' }],
29
- { route: '/@fusion-api', request },
30
- );
31
- const [route] = result.routes ?? [];
32
-
33
- expect(route?.proxy?.target).toBe('https://people.example');
34
- expect(route?.proxy?.rewrite?.('/people/api/persons')).toBe('/api/persons');
35
- });
36
- });
@@ -1,99 +0,0 @@
1
- import type { ApiDataProcessor, ApiRoute } from '@equinor/fusion-framework-vite-plugin-api-service';
2
- import type { FusionService } from './types.js';
3
-
4
- /**
5
- * Remap Fusion service discovery entries so their URIs point through the local dev server proxy,
6
- * and generate matching Vite proxy routes for each service.
7
- *
8
- * Use this as the default `api.processServices` handler in {@link DevServerOptions}, or call it
9
- * inside a custom handler to get the base mapping before applying additional transformations
10
- * (e.g. adding mock services or filtering environments).
11
- *
12
- * @param data - Array of {@link FusionService} entries returned by the service discovery endpoint.
13
- * @param args - Context provided by the API service plugin.
14
- * @param args.route - Base route path used to construct local proxy URLs (e.g. `'/services-proxy'`).
15
- * @param args.request - Incoming HTTP request; the `referer` header is used to resolve the local origin.
16
- * @returns An object with `data` (services with rewritten URIs) and `routes` (Vite proxy route configs).
17
- * @throws {Error} When `data` is not an array, indicating an unexpected service discovery response.
18
- *
19
- * @example
20
- * ```typescript
21
- * const services = [
22
- * { key: 'service1', uri: 'http://example.com/api', name: 'Service 1' },
23
- * { key: 'service2', uri: 'http://example.org/api', name: 'Service 2' },
24
- * ];
25
- * const args = {
26
- * route: '/proxy',
27
- * request: { headers: { referer: 'http://localhost:3000' } },
28
- * };
29
- * const result = processServices(services, args);
30
- * console.log(result.data); // Processed services with updated URIs
31
- *
32
- * // Expected output:
33
- * // result.data:
34
- * // [
35
- * // { key: 'service1', uri: 'http://localhost:3000/proxy/service1', name: 'Service 1' },
36
- * // { key: 'service2', uri: 'http://localhost:3000/proxy/service2', name: 'Service 2' },
37
- * // ]
38
- *
39
- * console.log(result.routes); // Generated proxy routes
40
- *
41
- * // result.routes:
42
- * // [
43
- * // {
44
- * // match: '/service1/api*sub',
45
- * // proxy: {
46
- * // target: 'http://example.com',
47
- * // rewrite: (path) => path.replace('/service1', ''),
48
- * // },
49
- * // },
50
- * // {
51
- * // match: '/service2/api*sub',
52
- * // proxy: {
53
- * // target: 'http://example.org',
54
- * // rewrite: (path) => path.replace('/service2', ''),
55
- * // },
56
- * // },
57
- * // ]
58
- * ```
59
- */
60
- export const processServices: ApiDataProcessor<FusionService[]> = (data, args) => {
61
- const { route, request } = args;
62
- const apiRoutes = [] as ApiRoute[];
63
- const apiServices = [] as FusionService[];
64
-
65
- // Fail fast when the upstream response isn't the expected service-list shape
66
- if (!Array.isArray(data)) {
67
- throw new Error('Invalid data format');
68
- }
69
-
70
- // remap all services to proxy though the dev server
71
- // and generate the proxy routes
72
- for (const service of data as FusionService[]) {
73
- // append host, port and protocol to the service uri
74
- // and replace the path with the local proxy path
75
- const serviceUrl = new URL(`${route}/${service.key}`, request.headers.referer);
76
- apiServices.push({ ...service, uri: String(serviceUrl) });
77
-
78
- // Add the proxy route for this service.
79
- const url = new URL(service.uri);
80
- const usesLocalhostSubdomain = url.hostname.endsWith('.localhost');
81
- // Node does not resolve localhost subdomains consistently across operating systems. The mock
82
- // server also accepts /<service>/* on plain localhost, so proxy through that portable address.
83
- if (usesLocalhostSubdomain) {
84
- url.hostname = 'localhost';
85
- }
86
- apiRoutes.push({
87
- match: `/${service.key}${url.pathname}*sub`,
88
- proxy: usesLocalhostSubdomain
89
- ? { target: url.origin }
90
- : {
91
- target: url.origin,
92
- rewrite: (path) => path.replace(`/${service.key}`, ''),
93
- },
94
- });
95
- }
96
- return { data: apiServices, routes: apiRoutes };
97
- };
98
-
99
- export default processServices;
package/src/types.ts DELETED
@@ -1,105 +0,0 @@
1
- import type { ApiDataProcessor, ApiRoute } from '@equinor/fusion-framework-vite-plugin-api-service';
2
- import type { FusionTemplateEnv, TemplateEnvFn } from '@equinor/fusion-framework-vite-plugin-spa';
3
- import type { ConsoleLogger } from '@equinor/fusion-log';
4
-
5
- /**
6
- * A service entry returned by the Fusion service discovery endpoint.
7
- *
8
- * Each entry represents a single backend service that can be proxied
9
- * through the development server via {@link processServices}.
10
- */
11
- export type FusionService = {
12
- /** Unique service identifier used as the proxy path segment (e.g. `'context'`, `'people'`). */
13
- key: string;
14
- /** Absolute URL of the upstream service endpoint. */
15
- uri: string;
16
- /** Human-readable display name of the service. */
17
- name: string;
18
- /**
19
- * OAuth scopes required when requesting tokens for this service.
20
- *
21
- * @remarks
22
- * When present, these scopes are forwarded through {@link processServices} so the
23
- * Fusion Framework HTTP module can acquire a Bearer token for service requests.
24
- * If absent (i.e. the service discovery endpoint does not return scopes), the HTTP
25
- * client will make unauthenticated requests — use the service worker resource
26
- * configuration to inject auth in that case.
27
- */
28
- scopes?: string[];
29
- };
30
-
31
- /**
32
- * Re-export of {@link FusionTemplateEnv} under the local alias `TemplateEnv`.
33
- *
34
- * Describes the environment variables injected into the SPA HTML template
35
- * (portal ID, service discovery URL, MSAL settings, telemetry level, etc.).
36
- */
37
- export {
38
- FusionTemplateEnv as TemplateEnv,
39
- TemplateEnvFn,
40
- } from '@equinor/fusion-framework-vite-plugin-spa';
41
-
42
- /**
43
- * Alias for Vite's `UserConfig`, used as the optional overrides parameter
44
- * of {@link createDevServer} and {@link createDevServerConfig}.
45
- */
46
- export { UserConfig as DevServerOverrides } from 'vite';
47
-
48
- /**
49
- * Configuration options for the Fusion Framework development server.
50
- *
51
- * Pass an instance of this type to {@link createDevServer} or {@link createDevServerConfig}
52
- * to configure SPA template injection, API service discovery proxying, and server-side logging.
53
- *
54
- * @template TEnv - Shape of the SPA template environment variables, extending
55
- * `Partial<FusionTemplateEnv>`. Defaults to `Partial<FusionTemplateEnv>`.
56
- *
57
- * @example
58
- * ```typescript
59
- * const opts: DevServerOptions = {
60
- * spa: {
61
- * templateEnv: {
62
- * portal: { id: 'my-portal' },
63
- * title: 'My App',
64
- * serviceDiscovery: { url: 'https://discovery.example.com', scopes: [] },
65
- * msal: { clientId: 'id', tenantId: 'tid', redirectUri: '/auth/cb', requiresAuth: 'true' },
66
- * },
67
- * },
68
- * api: { serviceDiscoveryUrl: 'https://discovery.example.com' },
69
- * log: { level: 3 },
70
- * };
71
- * ```
72
- */
73
- export interface DevServerOptions<
74
- TEnv extends Partial<FusionTemplateEnv> = Partial<FusionTemplateEnv>,
75
- > {
76
- /** SPA template settings. When provided, the dev server injects these values into the HTML template at serve time. */
77
- spa?: {
78
- /** Static environment object or factory function that produces it on each request. */
79
- templateEnv: TEnv | TemplateEnvFn<TEnv>;
80
- };
81
- api: {
82
- /**
83
- * The URL of the service discovery proxy endpoint.
84
- */
85
- serviceDiscoveryUrl: string;
86
-
87
- /**
88
- * Route mapper for processing service discovery data.
89
- */
90
- processServices?: ApiDataProcessor<FusionService[]>;
91
-
92
- /**
93
- * Additional routes to be added to the API service proxy.
94
- * @remarks used for overriding proxy responses and mocking services.
95
- */
96
- routes?: ApiRoute[];
97
- };
98
- /** Server-side (CLI) logging configuration. */
99
- log?: {
100
- /** Log verbosity: 0 = None, 1 = Error, 2 = Warning, 3 = Info, 4 = Debug. Defaults to Info (3). */
101
- level?: number;
102
- /** Custom logger instance. When omitted a default {@link ConsoleLogger} is created. */
103
- logger?: ConsoleLogger;
104
- };
105
- }
package/src/version.ts DELETED
@@ -1,2 +0,0 @@
1
- // Generated by genversion.
2
- export const version = '2.1.0';
package/tsconfig.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "rootDir": "src",
5
- "outDir": "dist/esm",
6
- "declarationDir": "./dist/types",
7
- "paths": {
8
- "*": ["./*"]
9
- }
10
- },
11
- "references": [
12
- {
13
- "path": "../vite-plugins/api-service"
14
- },
15
- {
16
- "path": "../vite-plugins/spa"
17
- }
18
- ],
19
- "include": ["src/**/*"],
20
- "exclude": ["node_modules", "tests"]
21
- }
package/vitest.config.ts DELETED
@@ -1,11 +0,0 @@
1
- import { defineProject } from 'vitest/config';
2
-
3
- import { name, version } from './package.json' with { type: 'json' };
4
-
5
- export default defineProject({
6
- test: {
7
- environment: 'node',
8
- include: ['src/**/*.test.ts'],
9
- name: `${name}@${version}`,
10
- },
11
- });