Repository navigation
Expand file tree
/
Copy pathrolldown.config.mjs
More file actions
333 lines (303 loc) · 12.9 KB
/
Copy pathrolldown.config.mjs
File metadata and controls
333 lines (303 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/**
* Copyright 2020-2022, 2025-2026 Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createRequire } from 'module';
import { fileURLToPath } from 'url';
import { readdirSync } from 'fs';
import { dirname, join, relative, resolve } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);
const { dependencies, peerDependencies } = require('./package.json');
const aliasEntries = {
'error_message': join(__dirname, '.build/message/error_message.gen.js'),
'log_message': join(__dirname, '.build/message/log_message.gen.js'),
};
const externalDeps = ['https', 'http', 'url'].concat(Object.keys({ ...dependencies, ...peerDependencies } || {}));
// uuid@13 is ESM-only and does not provide a CommonJS export.
// Since our CJS bundles must work in CommonJS environments, we bundle uuid
// into the CJS output instead of leaving it as an external dependency.
const externalDepsWithoutUuid = externalDeps.filter(dep => dep !== 'uuid');
// Every bundle sets the output syntax target, matching tsconfig.json's target (ES6). The input is already ES6
// (compiled by tsc), but Rolldown's minifier defaults to the newest syntax and would rewrite compiled code back
// into later syntax, e.g. `a == null ? void 0 : a.b` into `a?.b` (ES2020). Rolldown doesn't read the target from
// tsconfig.json.
const transform = { target: 'es2015' };
// CJS and UMD outputs set `strict: true`. Rolldown otherwise adds "use strict" only when the source has the
// directive, and tsc's ES module output has none (modules are always strict), so the bundles would run in sloppy
// mode. The Rollup bundles were strict.
// React Native optional import shims (lib/import.react_native) are not bundled into the main bundles.
// Each is shipped as its own module at the same relative location in dist, because Metro before 0.82.5
// shifts every later require in a module when an optional dependency is missing.
// See lib/import.react_native/README.md.
const BUILD_DIR = join(__dirname, '.build');
const RN_IMPORT_SHIM_DIR = 'import.react_native';
// Shim paths relative to the shim directory, without extension. Shims are named after their package, so
// a scoped package's shim is in a subdirectory, e.g. '@react-native-async-storage/async-storage'.
const listShims = (subdir = '') =>
readdirSync(join(__dirname, 'lib', RN_IMPORT_SHIM_DIR, subdir), { withFileTypes: true }).flatMap(entry => {
const path = subdir ? `${subdir}/${entry.name}` : entry.name;
if (entry.isDirectory()) return listShims(path);
return entry.name.endsWith('.ts') && !entry.name.endsWith('.spec.ts') ? [path.replace(/\.ts$/, '')] : [];
});
const RN_IMPORT_SHIMS = listShims();
// Leaves shim imports out of the main bundles and writes them as a path relative to the bundle, e.g.
// import '../../../import.react_native/@react-native-async-storage/async-storage' (from a file deep in .build)
// -> require("./import.react_native/@react-native-async-storage/async-storage.js") (in dist/index.react_native.min.js)
// The bundles are at the root of dist and the shims are built to dist/import.react_native,
// so that path points to the built shim.
// Marking the imports external via the `external` option is not enough: the bundler would resolve them to
// the file in .build and write a path from the bundle back into .build (../.build/import.react_native/...).
// Returning a relative id from resolveId makes the bundler write it exactly as given.
//
// Shims are built as CommonJS with __esModule set, so a default import of a shim must read its `default`
// export. Rolldown's CJS interop for externals (__toESM) already does that for modules with __esModule set,
// so no per-import interop override is needed (Rollup needed `output.interop: 'esModule'` for these).
const rnImportShimExternalPlugin = {
name: 'rn-import-shim-external',
resolveId(source, importer) {
if (!importer || !source.startsWith('.')) return null;
const pathInBuild = relative(BUILD_DIR, resolve(dirname(importer), source)).replace(/\.js$/, '');
if (!pathInBuild.startsWith(`${RN_IMPORT_SHIM_DIR}/`)) return null;
return { id: `./${pathInBuild}.js`, external: true };
},
};
// Fails the build unless every built shim contains exactly one require(), of its own package (the shim's
// name). Any other require in a shim could be shifted by the Metro bug when the package is missing. This
// catches imports of other packages, tslib helpers, and code shared between shims (the bundler moves it into
// a shared chunk that the shims require). The shim's own require() is plain code, so it isn't listed in
// chunk.imports; the generated code is parsed instead, with the bundler's parser.
const rnImportShimCheckPlugin = {
name: 'rn-import-shim-check',
generateBundle(_, bundle) {
// Module names of every require(...) call in an ESTree AST; a call whose argument is not a string is
// listed as '<non-literal>'.
const findRequireCalls = (node, found = []) => {
if (Array.isArray(node)) {
node.forEach(child => findRequireCalls(child, found));
} else if (node && typeof node.type === 'string') {
if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'require') {
const [arg] = node.arguments;
found.push(arg && arg.type === 'Literal' && typeof arg.value === 'string' ? arg.value : '<non-literal>');
}
for (const value of Object.values(node)) {
if (value && typeof value === 'object') findRequireCalls(value, found);
}
}
return found;
};
for (const chunk of Object.values(bundle)) {
if (chunk.type !== 'chunk') continue;
const required = findRequireCalls(this.parse(chunk.code));
if (!chunk.isEntry || required.length !== 1 || required[0] !== chunk.name) {
this.error(
`${RN_IMPORT_SHIM_DIR}/${chunk.fileName}: a shim must contain exactly one require(), of its own package` +
` '${chunk.name}' (found: ${required.join(', ') || 'none'}). See lib/${RN_IMPORT_SHIM_DIR}/README.md.`
);
}
}
},
};
const rnImportShimsBundle = {
input: Object.fromEntries(
RN_IMPORT_SHIMS.map(name => [name, join(BUILD_DIR, RN_IMPORT_SHIM_DIR, `${name}.js`)])
),
output: {
exports: 'named',
format: 'cjs',
strict: true,
dir: join('dist', RN_IMPORT_SHIM_DIR),
entryFileNames: '[name].js',
},
plugins: [rnImportShimCheckPlugin],
transform,
external: externalDeps,
};
// Every bundle sets `platform` explicitly. Rolldown otherwise defaults it to 'node' for cjs output and
// 'browser' for other formats, and always adds that platform's export condition, even when conditionNames
// is set. A browser cjs bundle would then resolve the 'node' condition and pull Node-only builds of bundled
// deps (e.g. uuid's dist-node, which requires node:crypto). `platform` also sets the default mainFields,
// and only 'browser' applies the package.json `browser` field's file mappings (aliasFields).
const rolldownPlatformFor = (platform) => {
switch (platform) {
case 'node':
return 'node';
case 'browser':
return 'browser';
default:
return 'neutral';
}
};
// Resolution on top of each platform's defaults. Rolldown adds 'import'/'require' (by import kind) and
// 'default' to conditionNames on every platform.
// - node, browser: the platform defaults are used as is ('node' or 'browser' plus 'module' conditions;
// mainFields ['main', 'module'] for node, ['browser', 'module', 'main'] and `browser` field mappings
// for browser).
// - react_native: resolves like Metro, which reads the `react-native` and `browser` fields (entry points
// and file mappings, `react-native` first) and the 'react-native' condition.
// - neutral (universal and the platform-independent bundles): unlike node and browser, the platform
// doesn't add the 'module' condition (it only has 'import'/'require' and 'default'), and its mainFields
// default is empty, so a package without an `exports` map would not resolve at all. 'module' and
// ['module', 'main'] match Rollup's plain nodeResolve(), which these bundles used.
const resolveForPlatform = (platform) => {
const base = { alias: aliasEntries };
switch (platform) {
case 'node':
case 'browser':
return base;
case 'react_native':
return {
...base,
conditionNames: ['react-native', 'module'],
mainFields: ['react-native', 'browser', 'module', 'main'],
aliasFields: [['react-native'], ['browser']],
};
default:
return { ...base, conditionNames: ['module'], mainFields: ['module', 'main'] };
}
};
const cjsBundleFor = (platform, opt = {}) => {
const { minify = true, ext = '.js' } = opt;
const min = minify ? '.min' : '';
return {
input: `./.build/index.${platform}.js`,
output: {
exports: 'named',
format: 'cjs',
strict: true,
file: `dist/index.${platform}${min}${ext}`,
sourcemap: true,
minify,
},
plugins: [rnImportShimExternalPlugin],
transform,
platform: rolldownPlatformFor(platform),
resolve: resolveForPlatform(platform),
external: externalDepsWithoutUuid,
};
};
const esmBundleFor = (platform, opt = {}) => {
const { minify = true, ext = '.js' } = opt;
const min = minify ? '.min' : '';
return {
...cjsBundleFor(platform),
external: externalDeps,
output: {
format: 'es',
file: `dist/index.${platform}.es${min}${ext}`,
sourcemap: true,
minify,
},
};
};
const cjsBundleForUAParser = (opt = {}) => {
const { minify = true, ext = '.js' } = opt;
const min = minify ? '.min' : '';
return {
input: `./.build/odp/ua_parser/ua_parser.js`,
output: {
exports: 'named',
format: 'cjs',
strict: true,
file: `dist/ua_parser${min}${ext}`,
sourcemap: true,
minify,
},
transform,
platform: rolldownPlatformFor('neutral'),
resolve: resolveForPlatform('neutral'),
external: externalDepsWithoutUuid,
};
};
const esmBundleForUAParser = (opt = {}) => {
const { minify = true, ext = '.js' } = opt;
const min = minify ? '.min' : '';
return {
...cjsBundleForUAParser(),
external: externalDeps,
output: {
format: 'es',
file: `dist/ua_parser.es${min}${ext}`,
sourcemap: true,
minify,
},
};
};
const jsonSchemaBundle = {
input: './.build/utils/json_schema_validator/index.js',
output: {
exports: 'named',
format: 'cjs',
strict: true,
file: 'dist/optimizely.json_schema_validator.min.js',
sourcemap: true,
minify: true,
},
transform,
platform: rolldownPlatformFor('neutral'),
resolve: resolveForPlatform('neutral'),
external: ['json-schema'],
};
const umdBundle = {
input: './.build/index.browser.js',
output: [
{
name: 'optimizelySdk',
format: 'umd',
strict: true,
file: 'dist/optimizely.browser.umd.js',
exports: 'named',
},
{
name: 'optimizelySdk',
format: 'umd',
strict: true,
file: 'dist/optimizely.browser.umd.min.js',
exports: 'named',
minify: true,
sourcemap: true,
},
],
transform,
platform: rolldownPlatformFor('browser'),
resolve: resolveForPlatform('browser'),
};
const bundles = {
'cjs-node-min': cjsBundleFor('node'),
'cjs-browser-min': cjsBundleFor('browser'),
'cjs-react-native-min': cjsBundleFor('react_native'),
'cjs-universal': cjsBundleFor('universal'),
'esm-browser-min': esmBundleFor('browser'),
'esm-node-min': esmBundleFor('node', { ext: '.mjs' }),
'esm-react-native-min': esmBundleFor('react_native'),
'esm-universal': esmBundleFor('universal'),
'cjs-react-native-import-shims': rnImportShimsBundle,
'json-schema': jsonSchemaBundle,
'cjs-ua-parser-min': cjsBundleForUAParser(),
'esm-ua-parser-min': esmBundleForUAParser(),
umd: umdBundle,
};
// Collect all --config-* options and return the matching bundle configs
// Builds all bundles if no --config-* option given
// --config-cjs will build all cjs-* bundles
// --config-umd will build only the umd bundle (both the plain and minified outputs)
// --config-umd --config-json will build both umd and the json-schema bundles
const patterns = process.argv
.filter(arg => arg.startsWith('--config-'))
.map(arg => arg.replace(/^--config-/, ''));
if (!patterns.length) patterns.push(/.*/);
export default Object.entries(bundles)
.filter(([name]) => patterns.some(pattern => name.match(pattern)))
.map(([, config]) => config);