@bleedingdev/modern-js-plugin-bff-build-extensions 0.0.0 → 3.9.0-ultramodern.11

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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/client-artifacts.js +94 -0
  3. package/dist/cjs/compile.js +64 -0
  4. package/dist/cjs/cross-project.js +92 -0
  5. package/dist/cjs/generated-entries.js +96 -0
  6. package/dist/cjs/hono-client-codegen.js +107 -0
  7. package/dist/cjs/index.js +130 -0
  8. package/dist/cjs/self-module.js +55 -0
  9. package/dist/cjs/server-global-vars.js +113 -0
  10. package/dist/esm/client-artifacts.mjs +53 -0
  11. package/dist/esm/compile.mjs +26 -0
  12. package/dist/esm/cross-project.mjs +44 -0
  13. package/dist/esm/generated-entries.mjs +58 -0
  14. package/dist/esm/hono-client-codegen.mjs +59 -0
  15. package/dist/esm/index.mjs +90 -0
  16. package/dist/esm/self-module.mjs +14 -0
  17. package/dist/esm/server-global-vars.mjs +72 -0
  18. package/dist/esm-node/client-artifacts.mjs +54 -0
  19. package/dist/esm-node/compile.mjs +27 -0
  20. package/dist/esm-node/cross-project.mjs +45 -0
  21. package/dist/esm-node/generated-entries.mjs +60 -0
  22. package/dist/esm-node/hono-client-codegen.mjs +61 -0
  23. package/dist/esm-node/index.mjs +92 -0
  24. package/dist/esm-node/self-module.mjs +15 -0
  25. package/dist/esm-node/server-global-vars.mjs +73 -0
  26. package/dist/types/client-artifacts.d.ts +10 -0
  27. package/dist/types/compile.d.ts +3 -0
  28. package/dist/types/cross-project.d.ts +11 -0
  29. package/dist/types/generated-entries.d.ts +4 -0
  30. package/dist/types/hono-client-codegen.d.ts +2 -0
  31. package/dist/types/index.d.ts +4 -0
  32. package/dist/types/self-module.d.ts +12 -0
  33. package/dist/types/server-global-vars.d.ts +6 -0
  34. package/package.json +104 -8
  35. package/src/client-artifacts.ts +87 -0
  36. package/src/compile.ts +39 -0
  37. package/src/cross-project.ts +72 -0
  38. package/src/generated-entries.ts +105 -0
  39. package/src/hono-client-codegen.ts +83 -0
  40. package/src/index.ts +127 -0
  41. package/src/self-module.ts +26 -0
  42. package/src/server-global-vars.ts +145 -0
  43. package/README.md +0 -3
package/src/compile.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { AppTools, BffCompilation } from '@modern-js/app-tools';
2
+ import type { CLIPluginAPI } from '@modern-js/plugin';
3
+ import {
4
+ serializeServerGlobalVars,
5
+ transformServerGlobalVars,
6
+ } from './server-global-vars';
7
+
8
+ export function registerBffCompilation(api: CLIPluginAPI<AppTools>) {
9
+ const serialized = new WeakMap<
10
+ BffCompilation,
11
+ ReturnType<typeof serializeServerGlobalVars>
12
+ >();
13
+ api.onBeforeBffCompile(context => {
14
+ serialized.set(
15
+ context,
16
+ serializeServerGlobalVars(api.getNormalizedConfig().source.globalVars),
17
+ );
18
+ });
19
+ api.onAfterBffCompile(async context => {
20
+ const globals = serialized.get(context);
21
+ if (!globals)
22
+ throw new Error('BFF compilation completed without its before hook.');
23
+ serialized.delete(context);
24
+ await transformServerGlobalVars([...context.outputDirectories], globals);
25
+ if (api.getAppContext().bffRuntimeFramework !== 'effect') return;
26
+ // Hosted APIs use the producer's compiled entry; it is not emitted by this app.
27
+ if (api.getNormalizedConfig().bff?.isCrossProjectServer === true) return;
28
+ const { bundleBuiltEffectEntryForNode } = await import(
29
+ '@modern-js/plugin-bff-extensions/effect-source-loader'
30
+ );
31
+ await bundleBuiltEffectEntryForNode({
32
+ appDir: context.appDirectory,
33
+ apiDir: context.apiDirectory,
34
+ distDir: context.distDirectory,
35
+ effectEntry: api.getNormalizedConfig().bff?.effect?.entry,
36
+ format: context.moduleType === 'module' ? 'esm' : 'cjs',
37
+ });
38
+ });
39
+ }
@@ -0,0 +1,72 @@
1
+ import '@modern-js/server-runtime-extensions/server-config';
2
+ import path from 'node:path';
3
+ import {
4
+ type CrossProjectApiPluginOptions,
5
+ createCrossProjectApiPlugin,
6
+ } from '@modern-js/plugin-bff/cross-project';
7
+ import type { OperationContractMap } from '@modern-js/server-runtime-extensions/bff-policy/node';
8
+
9
+ export interface CrossProjectBffDescriptor {
10
+ native: Omit<CrossProjectApiPluginOptions, 'modifyResolvedConfig'>;
11
+ runtimeFramework: 'hono' | 'effect';
12
+ relativeEffectEntry: string;
13
+ requestId: string;
14
+ operationContracts: OperationContractMap;
15
+ }
16
+
17
+ export function createCrossProjectBffPlugin(
18
+ descriptor: CrossProjectBffDescriptor,
19
+ ) {
20
+ return createCrossProjectApiPlugin({
21
+ ...descriptor.native,
22
+ modifyResolvedConfig: (resolvedConfig, { sdkDistDirectory, api }) => {
23
+ const config = api.getConfig();
24
+ const configuredRuntimeFramework = config?.bff?.runtimeFramework;
25
+ if (
26
+ configuredRuntimeFramework &&
27
+ configuredRuntimeFramework !== descriptor.runtimeFramework
28
+ ) {
29
+ throw new Error(
30
+ `[${descriptor.native.packageName}] Runtime framework mismatch for cross-project BFF. Detected "${configuredRuntimeFramework}", but producer SDK requires "${descriptor.runtimeFramework}".`,
31
+ );
32
+ }
33
+ const effectEntry = descriptor.relativeEffectEntry
34
+ ? path.join(sdkDistDirectory, descriptor.relativeEffectEntry)
35
+ : undefined;
36
+ api.updateAppContext({
37
+ ...(effectEntry ? { apiDirectory: path.dirname(effectEntry) } : {}),
38
+ bffRuntimeFramework: descriptor.runtimeFramework,
39
+ });
40
+ resolvedConfig.bff ??= {};
41
+ resolvedConfig.bff.runtimeFramework = descriptor.runtimeFramework;
42
+ if (effectEntry)
43
+ resolvedConfig.bff.effect = {
44
+ ...resolvedConfig.bff.effect,
45
+ entry: effectEntry,
46
+ };
47
+ resolvedConfig.bff.requestId =
48
+ resolvedConfig.bff.requestId ||
49
+ config?.bff?.requestId ||
50
+ descriptor.requestId ||
51
+ descriptor.native.packageName ||
52
+ 'default';
53
+ const policy = resolvedConfig.bff.crossProjectPolicy;
54
+ resolvedConfig.bff.crossProjectPolicy = {
55
+ ...policy,
56
+ enabled: policy?.enabled ?? true,
57
+ requireEnvelope: policy?.requireEnvelope ?? true,
58
+ requireOperationContext: policy?.requireOperationContext ?? true,
59
+ requireOperationContextDetails:
60
+ policy?.requireOperationContextDetails ?? true,
61
+ requireOperationSchemaHash: policy?.requireOperationSchemaHash ?? true,
62
+ requireOperationVersion: policy?.requireOperationVersion ?? true,
63
+ allowUnknownOperations: policy?.allowUnknownOperations ?? false,
64
+ expectedOperationContracts: {
65
+ ...policy?.expectedOperationContracts,
66
+ ...descriptor.operationContracts,
67
+ },
68
+ };
69
+ return resolvedConfig;
70
+ },
71
+ });
72
+ }
@@ -0,0 +1,105 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import type {
3
+ AppTools,
4
+ BffGeneratedEntries,
5
+ BffGeneration,
6
+ } from '@modern-js/app-tools';
7
+ import type { CLIPluginAPI } from '@modern-js/plugin';
8
+ import { fs, upath as path } from '@modern-js/utils';
9
+ import {
10
+ BFF_REQUEST_RUNTIME,
11
+ type BffGenerationMetadata,
12
+ } from './client-artifacts';
13
+ import type { CrossProjectBffDescriptor } from './cross-project';
14
+
15
+ export function registerBffGeneratedEntries(
16
+ api: CLIPluginAPI<AppTools>,
17
+ metadata: WeakMap<BffGeneration, BffGenerationMetadata>,
18
+ ) {
19
+ api.modifyBffGeneratedEntries(async (entries: BffGeneratedEntries) => {
20
+ const { generation } = entries;
21
+ const details = metadata.get(generation);
22
+ if (!details)
23
+ throw new Error(
24
+ 'BFF entries require completed operation contract collection.',
25
+ );
26
+ metadata.delete(generation);
27
+ const packageJson = await fs.readJSON(
28
+ path.join(generation.appDirectory, 'package.json'),
29
+ );
30
+ const runtimeSpecifier =
31
+ api.getNormalizedConfig().bff?.runtimeCreateRequest ||
32
+ BFF_REQUEST_RUNTIME;
33
+ const dependencies = [
34
+ '@modern-js/plugin-bff-build-extensions',
35
+ '@modern-js/plugin-bff-extensions',
36
+ ];
37
+ const emitsClient =
38
+ details.runtimeFramework === 'hono' && generation.apiFiles.length > 0;
39
+ if (
40
+ details.runtimeFramework === 'hono' &&
41
+ (runtimeSpecifier === BFF_REQUEST_RUNTIME ||
42
+ (emitsClient &&
43
+ (generation.requestCreator || BFF_REQUEST_RUNTIME) ===
44
+ BFF_REQUEST_RUNTIME))
45
+ )
46
+ dependencies.push('@modern-js/runtime-extensions');
47
+ for (const name of dependencies) {
48
+ const specifier =
49
+ packageJson.dependencies?.[name] ||
50
+ packageJson.devDependencies?.[name] ||
51
+ fs.readJSONSync(require.resolve(`${name}/package.json`)).version;
52
+ entries.packageDependencies[name] = specifier;
53
+ }
54
+ const descriptor: CrossProjectBffDescriptor = {
55
+ native: {
56
+ packageName: packageJson.name,
57
+ prefix: generation.prefix,
58
+ relativeDistPath: path.normalize(generation.relativeDistPath),
59
+ relativeApiPath: path.relative(
60
+ generation.appDirectory,
61
+ generation.apiDirectory,
62
+ ),
63
+ relativeLambdaPath: path.relative(
64
+ generation.appDirectory,
65
+ generation.lambdaDirectory,
66
+ ),
67
+ },
68
+ runtimeFramework: details.runtimeFramework,
69
+ relativeEffectEntry: details.relativeEffectEntry,
70
+ requestId: generation.requestId,
71
+ operationContracts: details.operationContracts,
72
+ };
73
+ const isModule =
74
+ api.getAppContext().moduleType === 'module' ||
75
+ packageJson.type === 'module';
76
+ entries.plugin = {
77
+ code: isModule
78
+ ? `import { createCrossProjectBffPlugin } from '@modern-js/plugin-bff-build-extensions/cross-project';\nexport const crossProjectApiPlugin = () => createCrossProjectBffPlugin(${JSON.stringify(descriptor)});\n`
79
+ : `'use strict';\nconst { createCrossProjectBffPlugin } = require('@modern-js/plugin-bff-build-extensions/cross-project');\nexports.crossProjectApiPlugin = () => createCrossProjectBffPlugin(${JSON.stringify(descriptor)});\n`,
80
+ declaration: `import type { AppTools, CliPlugin } from '@modern-js/app-tools';
81
+ export declare const crossProjectApiPlugin: () => CliPlugin<AppTools>;
82
+ `,
83
+ };
84
+ if (details.runtimeFramework === 'effect') {
85
+ entries.runtime = null;
86
+ return entries;
87
+ }
88
+ const runtime = JSON.stringify(runtimeSpecifier);
89
+ const esmRuntime = JSON.stringify(
90
+ path.isAbsolute(runtimeSpecifier)
91
+ ? pathToFileURL(runtimeSpecifier).href
92
+ : runtimeSpecifier,
93
+ );
94
+ entries.runtime = {
95
+ code: isModule
96
+ ? `import { configure as _configure } from ${esmRuntime};\nimport { createProducerClient } from '@modern-js/plugin-bff-extensions/producer-runtime';\nexport const configure = createProducerClient(_configure, { requestId: ${JSON.stringify(generation.requestId)} });\nexport const initProducerClient = configure;\n`
97
+ : `'use strict';\nconst { configure: _configure } = require(${runtime});\nconst { createProducerClient } = require('@modern-js/plugin-bff-extensions/producer-runtime');\nconst configure = createProducerClient(_configure, { requestId: ${JSON.stringify(generation.requestId)} });\nexports.configure = configure;\nexports.initProducerClient = configure;\n`,
98
+ declaration: `type Runtime = typeof import(${runtime});
99
+ export declare const initProducerClient: (options?: Parameters<Runtime['configure']>[0]) => ReturnType<Runtime['configure']>;
100
+ export declare const configure: typeof initProducerClient;
101
+ `,
102
+ };
103
+ return entries;
104
+ });
105
+ }
@@ -0,0 +1,83 @@
1
+ import path from 'node:path';
2
+ import type { ClientCodegenPlugin } from '@modern-js/bff-core';
3
+ import {
4
+ buildOperationContractMap,
5
+ createOperationSchemaHash,
6
+ deriveOperationVersion,
7
+ } from '@modern-js/server-runtime-extensions/bff-policy/node';
8
+
9
+ const REQUEST_RUNTIME = '@modern-js/runtime-extensions/request-policy';
10
+
11
+ export const modifyClient: ClientCodegenPlugin = (draft, context) => {
12
+ const { appDir, requestId } = context.options;
13
+ draft.requestCreator = context.options.requestCreator || REQUEST_RUNTIME;
14
+ let version: string | undefined;
15
+ try {
16
+ version = require(path.resolve(appDir, 'package.json')).version;
17
+ } catch {
18
+ // Missing or invalid package metadata uses the established version fallback.
19
+ }
20
+ const operationVersion = deriveOperationVersion(version);
21
+ const normalizedRequestId = requestId || 'default';
22
+ const operationContracts = buildOperationContractMap({
23
+ handlers: [...context.handlerInfos],
24
+ requestId: normalizedRequestId,
25
+ operationVersion,
26
+ });
27
+ const operationEntries = context.handlerInfos
28
+ .map(handlerInfo => {
29
+ const httpMethod = handlerInfo.httpMethod.toUpperCase();
30
+ return {
31
+ name: handlerInfo.name,
32
+ httpMethod,
33
+ routePath: handlerInfo.routePath,
34
+ schemaHash:
35
+ operationContracts[`${httpMethod}:${handlerInfo.routePath}`]
36
+ ?.schemaHash ?? '',
37
+ };
38
+ })
39
+ .sort((a, b) =>
40
+ `${a.routePath}:${a.httpMethod}:${a.name}`.localeCompare(
41
+ `${b.routePath}:${b.httpMethod}:${b.name}`,
42
+ ),
43
+ );
44
+ const schemaHash = createOperationSchemaHash(
45
+ operationEntries,
46
+ normalizedRequestId,
47
+ );
48
+ for (const { handlerInfo, optionProperties } of draft.handlers) {
49
+ if (handlerInfo.action === 'upload' && !requestId) continue;
50
+ const method = handlerInfo.httpMethod.toUpperCase();
51
+ const operationContext = {
52
+ operationId: handlerInfo.name,
53
+ routePath: handlerInfo.routePath,
54
+ method,
55
+ schemaHash:
56
+ operationContracts[`${method}:${handlerInfo.routePath}`]?.schemaHash ??
57
+ '',
58
+ operationVersion,
59
+ };
60
+ optionProperties.push(
61
+ `operationContext: ${JSON.stringify(operationContext)}`,
62
+ );
63
+ }
64
+ if (requestId) {
65
+ draft.imports.push(
66
+ `import * as requestRuntime from ${JSON.stringify(draft.requestCreator)};`,
67
+ 'import { createProducerClient } from "@modern-js/plugin-bff-extensions/producer-runtime";',
68
+ );
69
+ draft.statements.push(`export const initProducerClient = (options = {}) => {
70
+ const configure = requestRuntime.configure;
71
+ if (typeof configure !== 'function') {
72
+ console.warn('[modernjs] Compatibility request creator path does not expose configure(); use default @modern-js/create-request or migrate the compatibility path.');
73
+ return undefined;
74
+ }
75
+ return createProducerClient(configure, { requestId: ${JSON.stringify(requestId)} })(options);
76
+ };`);
77
+ }
78
+ draft.statements.push(
79
+ `export const operationVersion = ${String(operationVersion)};`,
80
+ `export const operationSchemaHash = ${JSON.stringify(schemaHash)};`,
81
+ `export const operationManifest = ${JSON.stringify({ operationVersion, schemaHash, operations: operationEntries }, null, 2)};`,
82
+ );
83
+ };
package/src/index.ts ADDED
@@ -0,0 +1,127 @@
1
+ import '@modern-js/server-runtime-extensions/server-config';
2
+ import type { AppTools, BffGeneration, CliPlugin } from '@modern-js/app-tools';
3
+ import { bffPlugin as nativeBffPlugin } from '@modern-js/plugin-bff';
4
+ import { fs, upath as path } from '@modern-js/utils';
5
+ import {
6
+ BFF_REQUEST_RUNTIME,
7
+ type BffGenerationMetadata,
8
+ registerBffClientArtifacts,
9
+ } from './client-artifacts';
10
+ import { registerBffCompilation } from './compile';
11
+ import { registerBffGeneratedEntries } from './generated-entries';
12
+ import { resolveSelfModule } from './self-module';
13
+
14
+ export const bffPlugin = (): CliPlugin<AppTools> => ({
15
+ name: '@modern-js/plugin-bff-build-extensions',
16
+ usePlugins: [nativeBffPlugin()],
17
+ pre: ['@modern-js/plugin-bff'],
18
+ setup: api => {
19
+ const hooks = api.getHooks();
20
+ for (const name of [
21
+ 'onBeforeBffCompile',
22
+ 'onAfterBffCompile',
23
+ 'modifyBffClientArtifacts',
24
+ 'modifyBffGeneratedEntries',
25
+ ] as const) {
26
+ if (typeof hooks[name]?.tap !== 'function')
27
+ throw new Error(`Native BFF build hook ${name} is unavailable.`);
28
+ }
29
+ api.config(() => ({
30
+ bff: {
31
+ requestCreator: BFF_REQUEST_RUNTIME,
32
+ runtimeCreateRequest: BFF_REQUEST_RUNTIME,
33
+ clientCodegenPlugin: resolveSelfModule('hono-client-codegen'),
34
+ },
35
+ }));
36
+ const runtimeFramework = api.getConfig()?.bff?.runtimeFramework;
37
+ if (
38
+ runtimeFramework !== undefined &&
39
+ runtimeFramework !== 'hono' &&
40
+ runtimeFramework !== 'effect'
41
+ ) {
42
+ throw new Error(`Unsupported Effect BFF runtime "${runtimeFramework}".`);
43
+ }
44
+ api.updateAppContext({ bffRuntimeFramework: runtimeFramework ?? 'effect' });
45
+ api._internalServerPlugins(({ plugins }) => {
46
+ const nativePlugins = plugins.filter(
47
+ plugin => plugin.name === '@modern-js/plugin-bff/server-plugin',
48
+ );
49
+ if (nativePlugins.length !== 1) {
50
+ throw new Error('Expected exactly one native BFF server plugin.');
51
+ }
52
+ const native = nativePlugins[0]!;
53
+ const runtimeAdapters = native.options?.runtimeAdapters ?? {};
54
+ const effect = '@modern-js/plugin-bff-extensions/effect-adapter';
55
+ const honoRouteBinder = '@modern-js/plugin-bff-extensions/hono/node';
56
+ if (
57
+ native.options?.honoRouteBinder !== undefined &&
58
+ native.options.honoRouteBinder !== honoRouteBinder
59
+ ) {
60
+ throw new Error('The Hono BFF route binder is already configured.');
61
+ }
62
+ if (
63
+ runtimeAdapters.effect !== undefined &&
64
+ runtimeAdapters.effect !== effect
65
+ ) {
66
+ throw new Error(
67
+ 'The Effect BFF runtime adapter is already configured.',
68
+ );
69
+ }
70
+ native.options = {
71
+ ...native.options,
72
+ honoRouteBinder,
73
+ runtimeAdapters: { ...runtimeAdapters, effect },
74
+ };
75
+ return { plugins };
76
+ });
77
+ const metadata = new WeakMap<BffGeneration, BffGenerationMetadata>();
78
+ registerBffCompilation(api);
79
+ registerBffClientArtifacts(api, metadata);
80
+ registerBffGeneratedEntries(api, metadata);
81
+ api.modifyBundlerChain(async (chain, { CHAIN_ID }) => {
82
+ if (api.getAppContext().bffRuntimeFramework !== 'effect') return;
83
+ const { appDirectory, apiDirectory } = api.getAppContext();
84
+ const bff = api.getNormalizedConfig().bff;
85
+ if (!fs.existsSync(apiDirectory) && bff?.effect?.entry === undefined)
86
+ return;
87
+ const { resolveEffectEntryFile } = await import(
88
+ '@modern-js/plugin-bff-extensions/effect-source-loader'
89
+ );
90
+ const entry = resolveEffectEntryFile({
91
+ appDir: appDirectory,
92
+ apiDir: apiDirectory,
93
+ effectEntry: bff?.effect?.entry,
94
+ });
95
+ if (!entry)
96
+ throw new Error(`Cannot resolve Effect BFF entry in ${apiDirectory}.`);
97
+ const canonical = (file: string) =>
98
+ path.normalize(
99
+ fs.existsSync(file) ? fs.realpathSync(file) : path.resolve(file),
100
+ );
101
+ const entryPath = canonical(entry);
102
+ const isEntry = (resource: string) => canonical(resource) === entryPath;
103
+ chain.module.rule(CHAIN_ID.RULE.JS).exclude.add(isEntry);
104
+ chain.module.rule('js-bff-api').exclude.add(isEntry);
105
+ chain.module
106
+ .rule('js-bff-effect-entry')
107
+ .test(isEntry)
108
+ .use('effect-bff-loader')
109
+ .loader(
110
+ require.resolve(
111
+ '@modern-js/plugin-bff-extensions/effect-source-loader/rspack-loader',
112
+ ),
113
+ )
114
+ .options({
115
+ appDir: appDirectory,
116
+ apiDir: apiDirectory,
117
+ effectEntry: entry,
118
+ prefix: Array.isArray(bff?.prefix)
119
+ ? bff.prefix[0]
120
+ : bff?.prefix || '/api',
121
+ requestId: bff?.requestId,
122
+ });
123
+ });
124
+ },
125
+ });
126
+
127
+ export default bffPlugin;
@@ -0,0 +1,26 @@
1
+ import { createRequire } from 'node:module';
2
+
3
+ const selfRequire = createRequire(import.meta.url);
4
+
5
+ /**
6
+ * Resolve a file this package ships alongside the calling module.
7
+ *
8
+ * Resolving it by this package's own public name (`@modern-js/plugin-bff-build-extensions/<name>`)
9
+ * only works where the package can see itself in a `node_modules` directory —
10
+ * under pnpm's isolated layout it is anchored in its own `.pnpm` directory and
11
+ * the lookup fails for a consumer, surfacing as an opaque `require.resolve`
12
+ * error in the middle of a build. A sibling lookup works in every layout:
13
+ * source (`src/*.ts`), CommonJS (`dist/cjs/*.js`) and ESM (`dist/esm-node/*.mjs`)
14
+ * all place these files next to each other.
15
+ */
16
+ export const resolveSelfModule = (name: string): string => {
17
+ for (const extension of ['.js', '.mjs', '.cjs', '.ts']) {
18
+ try {
19
+ return selfRequire.resolve(`./${name}${extension}`);
20
+ } catch {
21
+ // Try the next extension this package may have been built with.
22
+ }
23
+ }
24
+ // A layout that hoists this package still resolves the public specifier.
25
+ return selfRequire.resolve(`@modern-js/plugin-bff-build-extensions/${name}`);
26
+ };
@@ -0,0 +1,145 @@
1
+ import type { AppTools } from '@modern-js/app-tools';
2
+ import type { RsbuildTarget } from '@modern-js/builder';
3
+ import { applyOptionsChain, fs, upath as path } from '@modern-js/utils';
4
+ import { transform } from '@swc/core';
5
+
6
+ type SerializedGlobalVars = Record<string, string>;
7
+ type ServerGlobalVarsOptions = NonNullable<
8
+ NonNullable<AppTools['config']>['source']
9
+ >['globalVars'];
10
+
11
+ const RELEASE_IDENTITY_GLOBAL_NAMES = [
12
+ 'ULTRAMODERN_BUILD_MARKER',
13
+ 'ULTRAMODERN_SOURCE_REVISION',
14
+ 'ULTRAMODERN_RELEASE_VERSION',
15
+ ] as const;
16
+
17
+ const collectJavaScriptFiles = (directory: string): Promise<string[]> =>
18
+ Promise.resolve()
19
+ .then(() => fs.readdir(directory, { withFileTypes: true }))
20
+ .then(entries =>
21
+ Promise.all(
22
+ entries.map(entry => {
23
+ const absolutePath = path.join(directory, entry.name);
24
+ if (entry.isDirectory()) {
25
+ return collectJavaScriptFiles(absolutePath);
26
+ }
27
+ return /\.(?:c|m)?js$/u.test(entry.name) ? [absolutePath] : [];
28
+ }),
29
+ ).then(nested => nested.flat()),
30
+ );
31
+
32
+ export const serializeServerGlobalVars = (
33
+ options: ServerGlobalVarsOptions,
34
+ ): SerializedGlobalVars => {
35
+ const globalVars = applyOptionsChain<
36
+ Record<string, unknown>,
37
+ { env: string; target: RsbuildTarget }
38
+ >({}, options, {
39
+ env: 'server',
40
+ target: 'node',
41
+ });
42
+
43
+ return Object.fromEntries(
44
+ Object.entries(globalVars).map(([key, value]) => {
45
+ let serialized: string | undefined;
46
+ try {
47
+ serialized = JSON.stringify(value);
48
+ } catch (error) {
49
+ throw new Error(
50
+ `source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`,
51
+ { cause: error },
52
+ );
53
+ }
54
+ if (serialized === undefined) {
55
+ throw new Error(
56
+ `source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`,
57
+ );
58
+ }
59
+ return [key, serialized];
60
+ }),
61
+ );
62
+ };
63
+
64
+ export const transformServerGlobalVars = (
65
+ outputDirectories: string[],
66
+ globalVars: SerializedGlobalVars,
67
+ ) =>
68
+ Promise.resolve().then(() => {
69
+ if (Object.keys(globalVars).length === 0) {
70
+ return undefined;
71
+ }
72
+
73
+ return Promise.all(
74
+ outputDirectories.map(directory =>
75
+ fs
76
+ .pathExists(directory)
77
+ .then(directoryExists => (directoryExists ? directory : undefined)),
78
+ ),
79
+ )
80
+ .then(existingDirectories => {
81
+ const filesPromise = Promise.all(
82
+ existingDirectories
83
+ .filter((directory): directory is string => directory !== undefined)
84
+ .map(collectJavaScriptFiles),
85
+ ).then(files => files.flat());
86
+
87
+ const releaseIdentityBanner = RELEASE_IDENTITY_GLOBAL_NAMES.every(
88
+ name => Object.hasOwn(globalVars, name),
89
+ )
90
+ ? `${RELEASE_IDENTITY_GLOBAL_NAMES.map(name => `void ${globalVars[name]};`).join('')}\n`
91
+ : '';
92
+
93
+ return filesPromise.then(files =>
94
+ Promise.all(
95
+ files.map(filename =>
96
+ fs.readFile(filename, 'utf8').then(source => {
97
+ const sourceMapFilename = `${filename}.map`;
98
+ return fs
99
+ .pathExists(sourceMapFilename)
100
+ .then(sourceMapExists => {
101
+ const inputSourceMapPromise: Promise<string | undefined> =
102
+ sourceMapExists
103
+ ? fs.readFile(sourceMapFilename, 'utf8')
104
+ : Promise.resolve(undefined);
105
+
106
+ return inputSourceMapPromise.then(inputSourceMap =>
107
+ transform(`${releaseIdentityBanner}${source}`, {
108
+ filename,
109
+ inputSourceMap,
110
+ sourceMaps: sourceMapExists,
111
+ jsc: {
112
+ parser: {
113
+ syntax: 'ecmascript',
114
+ },
115
+ preserveAllComments: true,
116
+ target: 'es2024',
117
+ transform: {
118
+ optimizer: {
119
+ globals: {
120
+ vars: globalVars,
121
+ },
122
+ },
123
+ },
124
+ },
125
+ }).then(result =>
126
+ fs.writeFile(filename, result.code).then(() => {
127
+ if (
128
+ sourceMapExists &&
129
+ result.map !== undefined &&
130
+ result.map.length > 0
131
+ ) {
132
+ return fs.writeFile(sourceMapFilename, result.map);
133
+ }
134
+ return undefined;
135
+ }),
136
+ ),
137
+ );
138
+ });
139
+ }),
140
+ ),
141
+ ),
142
+ );
143
+ })
144
+ .then(() => undefined);
145
+ });
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # @bleedingdev/modern-js-plugin-bff-build-extensions
2
-
3
- This 0.0.0 version only registers the package name so npm trusted publishing can be configured. It contains no runtime implementation. Use the subsequent UltraModern.js release, published from the repository workflow with provenance.