-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathrollup.js
More file actions
566 lines (505 loc) · 20.1 KB
/
rollup.js
File metadata and controls
566 lines (505 loc) · 20.1 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
/* eslint-disable */
// eslint is disabled because it keeps trying to change the iife to something that doesn't compile.
'use strict'
const { promises: fs } = require('fs')
const { existsSync } = require('fs')
const path = require('path')
const fg = require('fast-glob') //dbw adding for requiredFiles glob wildcard watch (**/)
const notifier = require('node-notifier')
const alias = require('@rollup/plugin-alias')
const colors = require('chalk')
const messenger = require('@codedungeon/messenger')
const strftime = require('strftime')
const rollup = require('rollup')
const commonjs = require('@rollup/plugin-commonjs')
const json = require('@rollup/plugin-json')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const { babel } = require('@rollup/plugin-babel')
const terser = require('@rollup/plugin-terser')
const mkdirp = require('mkdirp')
const { program } = require('commander')
const ProgressBar = require('progress')
const pkgInfo = require('../package.json')
const pluginConfig = require('../plugins.config')
const replace = require('rollup-plugin-replace')
const { caseSensitiveImports } = require('./shared')
let progress
// const requiredFilesWatchMsg = ''
let watcher
const { getFolderFromCommandLine, writeMinifiedPluginFileContents, getCopyTargetPath, getPluginConfig } = require('./shared')
// Command line options
program
.option('-b, --build', 'Rollup: build plugin only (no watcher)')
.option('-c, --compact', 'Rollup: use compact output')
.option('-ci, --ci', 'Rollup: build plugin only (no copy, no watcher) for CI')
.option('-d, --debug', 'Rollup: allow for better JS debugging - no minification or transpiling')
.option('-m, --minify', 'Rollup: create minified output to reduce file size')
.option('-n, --notify', 'Show Notification')
.option('-p, --pressure', 'Rollup: report memory pressure during run')
.parse(process.argv)
const options = program.opts()
const DEBUGGING = options.debug || false
const MINIFY = options.minify || false
const COMPACT = options.compact || false
const BUILD = options.build || false
const NOTIFY = options.notify || false
const CI = options.ci || false
const REPORT_MEMORY_USAGE = options.pressure || false
/**
* Most of the rollup plugins will the same for all files, so we can just create them once
*/
const defaultPlugins = DEBUGGING
? [
caseSensitiveImports(),
alias({
entries: [...pluginConfig.aliasEntries, { find: '@helpers', replacement: path.resolve(__dirname, '..', 'helpers') }],
}),
babel({
presets: ['@babel/flow'],
babelHelpers: 'bundled',
babelrc: false,
exclude: ['node_modules/**', '*.json'],
compact: false,
}),
commonjs(),
json(),
nodeResolve({ browser: true, jsnext: true }),
]
: MINIFY
? [
caseSensitiveImports(),
alias({
entries: pluginConfig.aliasEntries,
}),
babel({ babelHelpers: 'bundled', compact: true }),
commonjs(),
json(),
nodeResolve({ browser: true, jsnext: true }),
terser({
compress: true,
mangle: true,
output: {
comments: false,
beautify: false,
indent_level: 2,
},
}),
]
: [
alias({
entries: pluginConfig.aliasEntries,
}),
babel({ babelHelpers: 'bundled', compact: false }),
commonjs(),
json(),
nodeResolve({ browser: true, jsnext: true }),
terser({
compress: false,
mangle: false,
output: {
comments: false,
beautify: true,
indent_level: 2,
},
}),
]
const reportMemoryUsage = (msg = '') => {
if (!REPORT_MEMORY_USAGE) return
const used = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)
console.log(`${msg}: Memory used: ${used} MB`)
}
const message = (type, msg, leftwords, useIcon = false) => {
if (!messenger[type]) {
messenger.error(`Invalid message type in your code: "${type}" (should be one of: success, warn, critical, note, log)`, 'Coding Error', true)
type = 'log'
}
messenger[type](msg, leftwords.padEnd(7), useIcon)
}
const dt = () => {
const d = new Date()
const pad = (value) => (value < 10 ? `0${value}` : value.toString())
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${d.toLocaleTimeString('en-GB')}`
}
;(async function () {
reportMemoryUsage('top of script')
const FOLDERS_TO_IGNORE = ['scripts', 'flow-typed', 'node_modules', 'np.plugin-flow-skeleton']
const rootFolderPath = path.join(__dirname, '..')
/**
* Copy the built files to the target directory and display a success message.
* @param {string} outputFile - Path to the built output file.
* @param {boolean} isBuildTask - Flag indicating if this is part of the build process.
*/
const copyBuild = async (outputFile = '', isBuildTask = false) => {
if (CI) {
return
}
if (!existsSync(outputFile)) {
messenger.error(`Invalid Script: ${outputFile}`)
}
const pluginDevFolder = path.dirname(outputFile)
const rootFolder = await fs.readdir(rootFolderPath, { withFileTypes: true })
const copyTargetPath = await getCopyTargetPath(rootFolder)
if (pluginDevFolder != null) {
const targetFolder = path.join(copyTargetPath, pluginDevFolder.replace(rootFolderPath, ''))
await mkdirp(targetFolder)
await fs.copyFile(path.join(pluginDevFolder, 'script.js'), path.join(targetFolder, 'script.js'))
const pluginJson = path.join(pluginDevFolder, 'plugin.json')
await writeMinifiedPluginFileContents(pluginJson, path.join(targetFolder, 'plugin.json'))
// await fs.copyFile(pluginJson, path.join(targetFolder, 'plugin.json')) //the non-minified version
// $FlowFixMe
const pluginJsonData = JSON.parse(await fs.readFile(pluginJson))
const pluginFolder = pluginDevFolder.replace(rootFolderPath, '').substring(1)
// default dateTime, uses .pluginsrc if exists
// see https://www.strfti.me/ for formatting
const dateTimeFormat = await getPluginConfig('dateTimeFormat')
const dateTime = dateTimeFormat.length > 0 ? strftime(dateTimeFormat) : new Date().toISOString().slice(0, 16)
const dependencies = pluginJsonData['plugin.requiredFiles'] || []
let dependenciesCopied = 0,
dataFolder = null
if (dependencies.length > 0) {
// copy files also to data folder where we can save out the generated HTML files to test in browser
// this is only done for plugins that have dependencies and stored locally. not uploaded to github or to users plugins
dataFolder = path.join(targetFolder, '..', 'data', pluginJsonData['plugin.id'])
if (!existsSync(dataFolder)) {
await mkdirp(dataFolder)
console.log(`Created data folder: ${dataFolder}`)
} else {
dataFolder = null
}
// if requiredFiles exists, create a watcher that triggers a rebuild when any of these (e.g. JSX) files change
// even though they are not in the plugin build index.js
// if requiredFiles exists, create a symlink from the requiredFiles folder in the plugin to the data folder
// this allows the plugin to write an HTML file to the data folder and then we can access it in the development folder in VSCode
for (const dependency of dependencies) {
if (dependency.includes('/')) {
console.log(colors.red.bold(`Invalid requiredFile. "${dependency}" cannot contain a slash. All requiredFiles must be at the root level of the requiredFiles folder.`))
} else {
const filePath = path.join(pluginDevFolder, 'requiredFiles', dependency)
if (existsSync(filePath)) {
await fs.copyFile(filePath, path.join(targetFolder, dependency))
if (dataFolder) {
await await fs.copyFile(filePath, path.join(dataFolder, dependency))
}
dependenciesCopied++
// console.log(`Copying ${dependency} to ${targetFolder}`)
} else {
console.log(colors.red.bold(`Cannot copy plugin.dependency "${dependency}" (${filePath}) as it doesn't exist at this location.`))
}
}
}
}
// Prepare a single-line success message
const version = pluginJsonData['plugin.version'] + (pluginJsonData['plugin.releaseStatus'] && pluginJsonData['plugin.releaseStatus'] !== 'full' ? `-${pluginJsonData['plugin.releaseStatus']}` : '')
// let msg = `${dateTime} -- ${pluginFolder} (v${version}): Built ${
let msg = `${dt()} -- ${pluginFolder} (v${version}): Built ${
dependenciesCopied > 0 ? `script.js, plugin.json + ${dependenciesCopied} requiredFiles` : `script.js & copied plugin.json`
} to the "Plugins" folder.`
if (DEBUGGING) {
msg += ' Built in DEBUG mode. Not ready to deploy.'
} else {
if (!COMPACT) {
msg += ` Release: npm run release "${pluginFolder}"`
}
}
if (NOTIFY) {
notifier.notify({
title: 'NotePlan Plugin Build',
message: `${pluginJsonData['plugin.name']} v${pluginJsonData['plugin.version']}`,
})
}
if (!isBuildTask) {
// Use the `message` function to display a green "SUCCESS" line
message('success', msg, 'SUCCESS', true)
}
} else {
// $FlowIgnore
console.log(`Generated "${outputFile.replace(rootFolder, '')}"`)
}
}
console.log('')
console.log(colors.yellow.bold(`🧩 NotePlan Plugin Development v${pkgInfo.version} (${pkgInfo.build})`))
if (DEBUGGING && !COMPACT) {
console.log(
colors.yellow.bold(
`Running in DEBUG mode for purposes of seeing the Javascript script.js code exactly as it appears in your editor. This means no cleaning and no transpiling. Good for debugging, but bad for deployment to older machines. Make sure you run the autowatch command without the --debug flag before you release!\n`,
),
)
}
if (COMPACT) {
console.log('')
console.log(colors.green.bold(`==> Rollup autowatch running. Will use compact output when there are no errors\n`))
}
if (MINIFY) {
console.log(colors.cyan.bold(`==> Rollup autowatch running. Will use minified output\n`))
}
/**
* Rollup with watch
*/
async function watch() {
// const args = getArgs()
const limitToFolders = await getFolderFromCommandLine(rootFolderPath, program.args)
console.log('')
if (limitToFolders.length && !COMPACT) {
console.log(
colors.yellow.bold(
`\nWARNING: Keep in mind that if you are editing shared files used by other plugins that you could be affecting them by not rebuilding/testing them all here. You have been warned. :)\n`,
),
)
}
const rootFolder = await fs.readdir(rootFolderPath, {
withFileTypes: true,
}) // returns array of String, Buffer or fs.Dirent objects
const copyTargetPath = await getCopyTargetPath(rootFolder)
const rootLevelFolders = rootFolder
.filter(
(dirent) =>
// $FlowIgnore
dirent.isDirectory() && !dirent.name.startsWith('.') && !FOLDERS_TO_IGNORE.includes(dirent.name) && (limitToFolders.length === 0 || limitToFolders.includes(dirent.name)),
)
.map(async (dirent) => {
// $FlowIgnore
const pluginFolder = path.join(__dirname, '..', dirent.name)
const pluginContents = await fs.readdir(pluginFolder, {
withFileTypes: true,
})
// $FlowIgnore
const isBundled = pluginContents.some((dirent) => dirent.name === 'src' && dirent.isDirectory)
if (!isBundled) {
return null
}
const srcFiles = await fs.readdir(path.join(pluginFolder, 'src'))
const hasIndexFile = srcFiles.includes('index.js')
if (!hasIndexFile) {
return null
}
return pluginFolder
})
const bundledPlugins = (await Promise.all(rootLevelFolders)).filter(Boolean)
const rollupConfigs = bundledPlugins.map(getConfig).map((config) => ({ ...config, plugins: [...config.plugins, ...defaultPlugins] }))
watcher = rollup.watch(rollupConfigs)
watcher.on('change', (id /* , { event } */) => {
const filename = path.basename(id)
message('info', `${dt()} Rollup: file: "${filename}" changed`, 'CHANGE', true)
})
watcher.on('event', async (event) => {
if (event.result) {
event.result.close()
}
if (event.code === 'BUNDLE_END' && copyTargetPath != null) {
const outputFile = event.output[0]
const pluginDevFolder = bundledPlugins.find((pluginFolder) => outputFile.includes(pluginFolder))
if (pluginDevFolder != null) {
await copyBuild(outputFile)
reportMemoryUsage(`After ${event.code}`)
} else {
console.log(`Generated "${outputFile.replace(rootFolder, '')}"`)
}
} else if (event.code === 'BUNDLE_END') {
console.log('no copyTargetPath', copyTargetPath)
} else if (event.code === 'ERROR') {
messenger.error(`!!!!!!!!!!!!!!!\nRollup ${event.error}\n!!!!!!!!!!!!!!!\n`)
if (NOTIFY) {
notifier.notify({
title: 'NotePlan Plugins Build',
message: `An error occurred during build process.\nSee console for more information`,
})
}
}
})
if (!COMPACT) {
console.log('')
console.log(colors.green(`==> Building and Watching for changes\n`))
}
}
/**
* Single Build command (not watch)
*/
async function build() {
try {
const limitToFolders = await getFolderFromCommandLine(rootFolderPath, program.args, true)
const rootFolder = await fs.readdir(rootFolderPath, {
withFileTypes: true,
})
const copyTargetPath = CI ? '' : await getCopyTargetPath(rootFolder)
const rootLevelFolders = rootFolder
.filter(
(dirent) =>
// $FlowIgnore
dirent.isDirectory() &&
// $FlowIgnore
!dirent.name.startsWith('.') &&
// $FlowIgnore
!FOLDERS_TO_IGNORE.includes(dirent.name) &&
// $FlowIgnore
(limitToFolders.length === 0 || limitToFolders.includes(dirent.name)),
)
.map(async (dirent) => {
// $FlowIgnore
const pluginFolder = path.join(__dirname, '..', dirent.name)
const pluginContents = await fs.readdir(pluginFolder, {
withFileTypes: true,
})
// $FlowIgnore
const isBundled = pluginContents.some((dirent) => dirent.name === 'src' && dirent.isDirectory)
if (!isBundled) {
return null
}
const srcFiles = await fs.readdir(path.join(pluginFolder, 'src'))
const hasIndexFile = srcFiles.includes('index.js')
if (!hasIndexFile) {
return null
}
return pluginFolder
})
const bundledPlugins = (await Promise.all(rootLevelFolders)).filter(Boolean)
if (bundledPlugins.length > 1) {
const progressOptions = {
clear: true,
complete: '\u001b[42m \u001b[0m',
incomplete: '\u001b[40m \u001b[0m',
total: bundledPlugins.length,
width: 50,
}
progress = new ProgressBar(
`${colors.yellow(`:bar :current/:total (:percent) built :eta/secs remaining; building: :id${REPORT_MEMORY_USAGE ? ' :mem' : ''}`)}`,
progressOptions,
)
}
let cachedBundle = null
for (const plugin of bundledPlugins) {
const pluginJsonFilename = path.join(plugin, 'plugin.json')
// $FlowIgnore
const pluginJsonData = JSON.parse(await fs.readFile(pluginJsonFilename))
progress?.tick({ id: pluginJsonData['plugin.id'], mem: reportMemoryUsage('') })
if (bundledPlugins.length === 1) {
messenger.info(` Building ${path.basename(plugin)} (${pluginJsonData['plugin.version']})`)
}
const options = getConfig(plugin)
const inputOptions = {
external: options.external,
input: options.input,
plugins: [...options.plugins, ...defaultPlugins],
context: options.context,
cache: cachedBundle,
}
const outputOptions = options.output
if (CI) console.log(`Starting build of: ${pluginJsonData['plugin.id']} `)
// create a bundle
try {
const bundle = await rollup.rollup(inputOptions)
if (!CI) {
await bundle.write(outputOptions)
await copyBuild(path.join(plugin, 'script.js'), true)
cachedBundle = bundle
}
await bundle.close()
} catch (error) {
console.log(colors.red(`Build of plugin: "${plugin}" failed`), error)
if (CI) process.exit(1)
}
// const { output } = await bundle.generate(outputOptions)
// const bundle = await bundle.generate(outputOptions)
// if (bundledPlugins.length > 1) {
// processed++
// }
}
console.log('')
if (bundledPlugins.length > 1) {
messenger.success(`${bundledPlugins.length} Plugins Built Successfully`, 'SUCCESS')
} else {
messenger.success('Build Process Complete', 'SUCCESS')
}
} catch (error) {
progress?.interrupt('An error occurred; stopping...')
console.log(`\nError Building plugin`)
console.log(`${error.message}`)
console.log('')
messenger.error('Build Error Occurred', 'ERROR')
// process.exit(1)
}
}
/**
* Get specific rollup config for a plugin
* @param {string} pluginPath
* @returns
*/
function getConfig(pluginPath) {
// WATCH REQUIREDFILES IN PLUGIN FOLDER FOR CHANGES
let requiredFilesWatchPlugin = null
const requiredFilesInDevFolder = path.join(pluginPath, 'requiredFiles')
if (existsSync(requiredFilesInDevFolder)) {
// console.log(colors.yellow(`\n==> Gathering "${path.basename(pluginPath)}/requiredFiles" files`))
requiredFilesWatchPlugin = {
name: 'watch-external-files',
async buildStart() {
const files = await fg(path.join(requiredFilesInDevFolder, '**/*'))
for (const file of files) {
// console.log(`Watching ${file}`)
// $FlowFixMe - this works but Flow doesn't like "this" inside a function
this.addWatchFile(file)
}
},
}
}
// EXTRA FILES TO WATCH (other than those imported starting by index.js)
const pluginJsonPath = path.join(pluginPath, 'plugin.json')
const watchExtraFilesPlugin = {
name: 'watch-extra-files-plugin',
async buildStart() {
// watch a custom folder or file:
// You can add as many files/folders as you want.
this.addWatchFile(pluginJsonPath)
// this.addWatchFile(path.resolve(__dirname, '..', 'some-other-folder', 'whatever.css'));
},
}
const watchOptions = {
exclude: ['node_modules/**', '**/script.js'],
}
return {
external: ['fs'],
input: path.join(pluginPath, 'src/index.js'),
output: {
file: path.join(pluginPath, 'script.js'),
format: 'iife',
name: 'exports',
footer: 'Object.assign(typeof(globalThis) == "undefined" ? this : globalThis, exports)',
},
plugins: [requiredFilesWatchPlugin, watchExtraFilesPlugin] /* add non-changing plugins later */,
context: 'this',
watch: watchOptions,
/**
* Suppress specific Rollup warnings.
* @param {object} warning - Rollup warning object.
* @param {function} warn - Rollup warn function.
*/
onwarn: (warning, warn) => {
if (warning.code === 'EVAL') return
// Suppress warnings about module directives like "use client" being ignored
if (warning.code === 'MODULE_LEVEL_DIRECTIVE') return
warn(warning)
},
}
}
if (!BUILD) {
process.on('SIGINT', function () {
console.log('\n\n')
console.log(colors.yellow('Quitting...\n'))
if (watcher) {
watcher.close()
process.exit()
}
})
} else {
process.on('SIGINT', function () {
console.log('\n\n')
messenger.warn('Build Process Aborted', 'ABORT')
process.exit()
})
}
if (BUILD) {
await build()
} else {
await watch()
}
reportMemoryUsage('end of script')
})()