Repository navigation
Expand file tree
/
Copy pathwebpack.config.js
More file actions
635 lines (547 loc) · 21.8 KB
/
Copy pathwebpack.config.js
File metadata and controls
635 lines (547 loc) · 21.8 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
var path = require('path');
// Resolve webpack from the consumer so this config builds plugins with the same copy the
// compiler uses. In a linked dev setup the consumer and this repo have separate installs,
// and webpack >= 5.107 rejects a compilation created by a different copy.
var webpack = require(require.resolve('webpack', {paths: [process.cwd(), __dirname]}));
var lodash = require('lodash');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const fs = require('fs');
function getModuleDir(moduleName) {
return path.join(
require.resolve(
moduleName + '/package.json',
{paths: [__dirname, process.cwd()]}
),
'../'
);
}
function countOccurrences(_string, substring) {
return _string.split(substring).length - 1;
}
/**
* Replacements for TerserPlugin.swcMinify and CssMinimizerPlugin.esbuildMinify.
* The built-in ones require('@swc/core') / require('esbuild') from wherever npm
* hoisted the plugin, which fails when the package is nested under
* superdesk-core in a consuming repo. These are self-contained (the plugins
* stringify them for worker threads, so no closures) and receive the resolved
* module path through the minimizer options instead.
*/
function swcMinify(input, sourceMap, minimizerOptions) {
const {swcCorePath, ...swcOptions} = minimizerOptions;
const swc = require(swcCorePath);
const [[filename, code]] = Object.entries(input);
if (swcOptions.compress === true) {
swcOptions.compress = {};
}
// swc can otherwise emit arrow functions while compressing an ecma 5
// bundle (https://github.com/webpack/webpack/issues/16135)
if (swcOptions.compress && swcOptions.ecma === 5 && swcOptions.compress.arrows === undefined) {
swcOptions.compress.arrows = false;
}
if (sourceMap) {
swcOptions.sourceMap = true;
}
return swc.minify(code, swcOptions).then((result) => {
let map;
if (result.map) {
map = JSON.parse(result.map);
map.sources = [filename];
delete map.sourcesContent;
}
return {code: result.code, map: map};
});
}
function esbuildCssMinify(input, sourceMap, minimizerOptions) {
const esbuild = require(minimizerOptions.esbuildPath);
const [[filename, code]] = Object.entries(input);
const options = {
loader: 'css',
minify: true,
legalComments: 'inline',
sourcefile: filename,
sourcemap: false,
};
if (sourceMap) {
options.sourcemap = true;
options.sourcesContent = false;
}
return esbuild.transform(code, options).then((result) => ({
code: result.code,
map: result.map ? JSON.parse(result.map) : undefined,
warnings: result.warnings.map((item) => ({message: item.text})),
}));
}
// esbuild runs its own service process; spawning it once per worker thread
// would only add overhead, so keep this minifier on the main thread
esbuildCssMinify.supportsWorkerThreads = () => false;
function applyDefaults(appConfig) {
if (appConfig.startingDay == null) {
appConfig.startingDay = '0'; // sunday
}
if (appConfig.shortTimeFormat == null) {
appConfig.shortTimeFormat = 'HH:mm'; // 24h format
}
if (appConfig.ui == null) {
appConfig.ui = {};
}
if (appConfig.ui.sendEmbargo == null) {
appConfig.ui.sendEmbargo = false;
}
if (appConfig.ui.italicAbstract == null) {
appConfig.ui.italicAbstract = true;
}
if (appConfig.ui.publishEmbargo == null) {
appConfig.ui.publishEmbargo = true;
}
if (appConfig.authoring == null) {
appConfig.authoring = {};
}
if (appConfig.authoring.panels == null) {
appConfig.authoring.panels = {};
}
if (appConfig.authoring.panels.publish == null) {
appConfig.authoring.panels.publish = {};
}
if (appConfig.authoring.panels.publish.publishSchedule == null) {
appConfig.authoring.panels.publish.publishSchedule = true;
}
if (appConfig.authoring.panels.publish.publishingTarget == null) {
appConfig.authoring.panels.publish.publishingTarget = true;
}
if (appConfig.authoring.panels.sendTo == null) {
appConfig.authoring.panels.sendTo = {};
}
if (appConfig.authoring.panels.sendTo.publishSchedule == null) {
appConfig.authoring.panels.sendTo.publishSchedule = false;
}
const defaultDateFormat = 'MM/DD';
const defaultTimeFormat = 'hh:mm';
if (appConfig.view == null) {
appConfig.view = {
dateformat: defaultDateFormat,
timeformat: defaultTimeFormat,
};
}
if (appConfig.view.dateformat == null) {
appConfig.view.dateformat = defaultDateFormat;
}
if (appConfig.view.timeformat == null) {
appConfig.view.timeformat = defaultTimeFormat;
}
if (appConfig.longDateFormat == null) {
appConfig.longDateFormat = 'LLL';
}
if (appConfig.features == null) {
appConfig.features = {};
}
if (appConfig.features.autorefreshContent == null) {
appConfig.features.autorefreshContent = true; // default to true
}
}
// makeConfig creates a new webpack configuration.
module.exports = function makeConfig(grunt) {
var appConfigPath = path.join(process.cwd(), 'superdesk.config.js');
if (process.env.SUPERDESK_CONFIG) {
appConfigPath = path.join(process.cwd(), process.env.SUPERDESK_CONFIG);
}
if (grunt.option('config')) {
appConfigPath = path.join(process.cwd(), grunt.option('config'));
}
const sdConfig = lodash.defaultsDeep(require(appConfigPath)(grunt), getDefaults(grunt));
applyDefaults(sdConfig);
const apps = sdConfig.importApps || sdConfig.apps || [];
// include only 'superdesk-core' and valid modules inside node_modules
let validModules = [
'superdesk-core',
'planning', // on fireq we store superdesk-planning in linked `planning` folder
].concat(apps);
const jQueryModule = getModuleDir('jquery');
const superdeskCorePath = process.cwd() === __dirname
? __dirname // when running unit tests from this project
: getModuleDir('superdesk-core');
const uiFrameworkInsideClientCore = path.join(superdeskCorePath, 'node_modules/superdesk-ui-framework');
const uiFrameworkPath =
fs.existsSync(uiFrameworkInsideClientCore)
? uiFrameworkInsideClientCore
: getModuleDir('superdesk-ui-framework');
const sassLoadPaths = [
path.join(__dirname, 'styles', 'sass'),
path.join(__dirname, 'node_modules'),
path.join(process.cwd(), 'node_modules'),
];
const transpilationExcludes = function(rawPath) {
// Windows paths use backslashes; the checks below assume "/"
const absolutePath = rawPath.split(path.sep).join('/');
// don't exclude anything outside node_modules
if (absolutePath.indexOf('node_modules') === -1) {
return false;
}
// Exclude these packages - they are pre-built ESM modules
if (
absolutePath.includes('/@babel/runtime/')
|| absolutePath.includes('/react-resizable-panels/')
) {
return true;
}
if (
// date-fns uses optional chaining and nullish coalescing
absolutePath.includes('/node_modules/date-fns/')
// @sourcefabric/date-fns-tz uses logical OR assignment operator ||=
|| absolutePath.includes('/@sourcefabric/date-fns-tz/')
|| absolutePath.includes('/@sourcefabric/common/')
) {
return false;
}
// exclude everything else, unless it's a part of a superdesk app like superdesk-planning
// but is not its dependency.
// For example, `superdesk-planning/node_modules/**/*` will be excluded.
const exclude = !validModules.some(
(app) =>
absolutePath.includes(app) && countOccurrences(absolutePath, '/node_modules/') === 1
);
return exclude;
};
// Mirrors scripts/tsconfig.json: ES5, classic JSX, CommonJS. isModule "unknown"
// leaves files without import/export as scripts, like tsc, so legacy sloppy-mode
// code doesn't get "use strict" forced on it. useDefineForClassFields matches
// tsc's default at target es5: without it, declaration-only class fields
// (`scope: any;`) are defined as undefined after super() returns, wiping
// values that parent constructors assigned.
//
// @swc/helpers is declared in dependencies although nothing imports it directly
// (swc only emits imports of it with externalHelpers enabled, which is not used
// here). Repos that consume superdesk-core as a git dependency get @swc/helpers
// in their tree anyway through @swc/core's optional peer dependency, and
// Dependabot's lockfile regeneration drops optional-peer entries, leaving a lock
// that fails `npm ci` there. A regular dependency stays a hard lock entry that
// survives regeneration. Do not remove it as unused.
const swcOptions = (parser) => ({
isModule: 'unknown',
module: {type: 'commonjs'},
jsc: {
target: 'es5',
parser: parser,
transform: {
react: {runtime: 'classic'},
useDefineForClassFields: false,
},
},
});
// node_modules is normally trusted by package version, but superdesk app packages
// come from git branches (or symlinks) and change without a version bump, and
// patch-package edits immutable in place. Exclude them so content changes
// invalidate the cache.
const managedPathsPattern =
/^(.+?[\\/]node_modules[\\/](?!superdesk|planning[\\/]|immutable[\\/])(@[^\\/]+[\\/])?(?!@)[^\\/]+)[\\/]/;
return {
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename, appConfigPath],
},
},
snapshot: {
managedPaths: [managedPathsPattern],
},
// Production only (minimize is off in development). swc minifies several times
// faster than Terser with equivalent output. esbuild would be faster still, but
// at target es5 it errors on the ES2015+ syntax that prebuilt packages like
// @hello-pangea/dnd ship, and higher targets would widen the browser floor.
optimization: {
minimizer: [
new TerserPlugin({
minify: swcMinify,
// terser-only feature; license comments stay in the bundle instead
extractComments: false,
terserOptions: {
compress: true,
mangle: true,
format: {comments: 'some'},
ecma: 5,
swcCorePath: require.resolve('@swc/core'),
},
}),
new CssMinimizerPlugin({
minify: esbuildCssMinify,
minimizerOptions: {
esbuildPath: require.resolve('esbuild'),
},
}),
],
},
entry: {
init: path.join(__dirname, 'scripts', 'init'),
app: path.join(__dirname, 'scripts', 'index'),
},
output: {
path: path.join(process.cwd(), 'dist'),
filename: '[name].bundle.js',
chunkFilename: '[id].bundle.js',
pathinfo: false,
// Without this webpack's own runtime helpers use const/arrow functions,
// undermining the ES5 output the application code is compiled to.
environment: {
arrowFunction: false,
bigIntLiteral: false,
const: false,
destructuring: false,
dynamicImport: false,
forOf: false,
module: false,
optionalChaining: false,
templateLiteral: false,
},
},
plugins: [
new webpack.ProvidePlugin({
$: jQueryModule,
'window.$': jQueryModule,
jQuery: jQueryModule,
'window.jQuery': jQueryModule,
moment: 'moment',
}),
new webpack.DefinePlugin({
__SUPERDESK_CONFIG__: JSON.stringify(sdConfig),
}),
new MiniCssExtractPlugin({
filename: '[name].bundle.css',
chunkFilename: '[id].bundle.css',
}),
// Webpack 5 removed automatic Node.js polyfills for browser builds
// This plugin restores them for legacy code that depends on Node APIs (e.g., Buffer, process, stream)
// Exclude 'console' since browsers provide their own implementation
new NodePolyfillPlugin({
excludeAliases: ['console'],
}),
],
resolve: {
modules: [
__dirname,
path.join(__dirname, 'scripts'),
path.join(__dirname, 'styles', 'sass'),
path.join(__dirname, 'node_modules'),
'node_modules',
],
mainFields: ['module', 'browser', 'main'],
alias: {
'moment-timezone': 'moment-timezone/builds/moment-timezone-with-data-10-year-range',
'rangy-saverestore': 'rangy/lib/rangy-selectionsaverestore',
'angular-embedly': 'angular-embedly/em-minified/angular-embedly.min',
'jquery-gridster': 'gridster/dist/jquery.gridster.min',
'external-apps': path.join(process.cwd(), 'dist', 'app-importer.generated.js'),
'shallow-equal': 'shallow-equal/dist/index',
/**
* Ensure that react is loaded only once.
* external apps(planning, analytics, ui-framework) may try loading their own react,
* especially when linked with npm in development mode.
*/
react: getModuleDir('react'),
'react-dom': getModuleDir('react-dom'),
/**
* Required for development mode only.
* Otherwise throws "Invariant Violation: block is not a BlockNode" error
* which is likely due to multiple instances of the library being loaded.
* The error is only thrown in certain execution branches.
*/
'draft-js': getModuleDir('@sourcefabric/draft-js'),
/**
* Required for development mode only.
* Ensures that superdesk apps loaded via superdesk.config.js (planning, analytics)
* use a single version of superdesk-core.
*
* NOTE: superdesk apps themselves are unaware of this config
* and you will see import errors in code editor
* with a superdesk app open and superdesk-core not installed.
* running `npm link superdesk-core` inside of a superdesk app fixes this.
*/
'superdesk-core': superdeskCorePath,
'superdesk-ui-framework': uiFrameworkPath,
},
extensions: ['.js', '.jsx', '.mjs', '.ts', '.tsx'],
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: transpilationExcludes,
loader: require.resolve('swc-loader'),
options: swcOptions({syntax: 'typescript', tsx: true}),
},
{
test: /\.jsx?$/,
exclude: transpilationExcludes,
loader: require.resolve('swc-loader'),
options: swcOptions({syntax: 'ecmascript', jsx: true}),
},
{
test: /\.html$/,
loader: 'html-loader',
},
{
test: /\.css$/i,
use: [
{loader: MiniCssExtractPlugin.loader},
{
loader: 'css-loader',
options: {
modules: 'global',
},
},
],
},
{
test: /\.scss$/i,
use: [
{loader: MiniCssExtractPlugin.loader},
{
loader: 'css-loader',
options: {
modules: 'global',
},
},
{
loader: require.resolve('sass-loader'),
options: {
// several times faster than the pure-js sass package
implementation: require.resolve('sass-embedded'),
api: 'modern-compiler',
sassOptions: {
loadPaths: sassLoadPaths,
quietDeps: true,
},
},
},
],
},
{
test: /\.(png|gif|jpeg|jpg|woff|woff2|eot|ttf|svg|mov)(\?.*$|$)/,
type: 'asset/resource',
},
],
},
devServer: {
port: 9000,
host: '0.0.0.0',
compress: true,
headers: {'Cache-Control': 'no-store'},
// Errors stay visible; warnings hidden because the warning
// overlay iframe intercepts pointer events during Playwright runs.
client: {overlay: {errors: true, warnings: false}},
static: [
{directory: path.resolve(process.cwd(), 'dist')},
{directory: path.resolve(__dirname, 'scripts'), publicPath: '/scripts'},
{directory: path.resolve(__dirname, 'images'), publicPath: '/images'},
{directory: path.resolve(__dirname, 'styles'), publicPath: '/styles'},
{directory: path.resolve(__dirname, 'fonts'), publicPath: '/fonts'},
],
},
};
};
// getDefaults returns the default configuration for the app
function getDefaults(grunt) {
var version;
try {
version = require('git-rev-sync').short('..');
} catch (err) {
// pass
}
return {
// application version
version: version || grunt.file.readJSON(path.join(__dirname, 'package.json')).version,
// backend server URLs configuration
server: {
url: grunt.option('server') || process.env.SUPERDESK_URL || 'http://localhost:5000/api',
ws: grunt.option('ws') || process.env.SUPERDESK_WS_URL || 'ws://0.0.0.0:5100',
},
// iframely settings
iframely: {
key: process.env.IFRAMELY_KEY || '',
},
// google settings
google: {
key: process.env.GOOGLE_KEY || '',
},
// settings for various analytics
analytics: {
piwik: {
url: process.env.PIWIK_URL || '',
id: process.env.PIWIK_SITE_ID || '',
},
ga: {
id: process.env.TRACKING_ID || '',
},
},
// editor configuration
editor: {
// if true, the editor will not have a toolbar
disableEditorToolbar: grunt.option('disableEditorToolbar'),
},
editor3: {
browserSpellCheck: false,
},
// model date and time formats
model: {
dateformat: 'DD/MM/YYYY',
timeformat: 'HH:mm:ss',
},
// view formats for datepickers/timepickers
view: {
dateformat: process.env.VIEW_DATE_FORMAT || 'DD/MM/YYYY',
timeformat: process.env.VIEW_TIME_FORMAT || 'HH:mm',
},
// if environment name is not set
isTestEnvironment: !!grunt.option('environmentName') || !!process.env.SUPERDESK_ENVIRONMENT,
// environment name
environmentName: grunt.option('environmentName') || process.env.SUPERDESK_ENVIRONMENT,
// route to be redirected to from '/'
defaultRoute: '/workspace',
// override language translations
langOverride: {},
// app features
features: {
// tansa spellchecker
useTansaProofing: false,
},
// workspace defaults
workspace: {
ingest: false,
content: false,
tasks: false,
analytics: false,
},
// ingest defaults
ingest: {
PROVIDER_DASHBOARD_DEFAULTS: {
show_log_messages: true,
show_ingest_count: true,
show_time: true,
log_messages: 'error',
show_status: true,
},
DEFAULT_SCHEDULE: {minutes: 5, seconds: 0},
DEFAULT_IDLE_TIME: {hours: 0, minutes: 0},
},
// list of languages available in user profile
profileLanguages: [
'en',
'el',
'en_GB',
'fr_CA',
'es',
'da',
'ar',
'de_DE',
'ru_RU',
'nb',
'uk_UA',
'pt_BR',
'pl',
'ja',
'sr',
],
userOnlineMinutes: 15,
};
}