-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
build.mjs
211 lines (180 loc) · 6.28 KB
/
build.mjs
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
/*/
This script generates the files `neutralino.js`, `neutralino.mjs`, and `neutralino.d.ts`.
For a development version, use: `node ./build.mjs --dev`
this will produce an unminified `neutralino.js` file and the neutralino.js.map file.
neutralino.js.map can be moved without the source code.
ISSUE:
rollup-plugin-ts produce an empty `neutralino.d.ts.map`
/*/
// @ts-check
import { readFileSync, writeFile, writeFileSync, mkdirSync, existsSync, readdirSync } from 'fs'
import { exec } from 'child_process'
import { join as joinPath } from 'path'
import { rollup } from 'rollup'
import Ts from 'rollup-plugin-ts'
import Json from '@rollup/plugin-json'
import Minify from '@rollup/plugin-terser'
import cleanup from 'rollup-plugin-cleanup';
// JSON modules is experimental https://nodejs.org/api/esm.html#esm_experimental_json_modules
const { version } = JSON.parse (readFileSync ('./package.json', { encoding: 'utf8' }))
const outdir = 'dist'
const devmode = process.argv.includes ('--dev')
let commitHash = null
if (existsSync (outdir) === false)
mkdirSync (outdir, { recursive: true })
console.log ('Preprocessing files...')
addCommitHash ()
console.log ('import src/index.ts')
rollup ({
input: 'src/index.ts',
plugins: [
Json (),
Ts ({
tsconfig: config => ({
...config,
// rollup-plugin-ts produce an empty map, maybe we will find a solution in the future.
// declarationMap: devmode
include: ['src/**/*.ts', 'types/**/*.d.ts']
})
}),
devmode ? cleanup({comments: 'none'}) : Minify ({ format: { comments: false } })
]
})
.then (build =>
{
console.log ('generate dist/neutralino.mjs')
build.write ({
file : joinPath (outdir, 'neutralino.mjs'),
format : 'esm',
name : 'Neutralino',
sourcemap : devmode
})
console.log ('generate lib')
build.write ({
dir : outdir,
format : 'cjs',
sourcemap : devmode
})
console.log ('generate dist/neutralino.js')
return build.generate ({
file : 'neutralino.js',
format : 'iife',
name : 'Neutralino',
sourcemap : devmode,
freeze : false,
esModule : false
})
})
.then (({ output }) =>
{
for (var entry of output)
{
var filepath = joinPath (outdir, entry.fileName)
if (entry.type === 'chunk')
{
// rollup-plugin-ts does not move the map in individual chunk
if (entry.map) {
write (filepath + '.map', entry.map.toString ())
var code = entry.code + '\n//# sourceMappingURL=neutralino.js.map'
} else {
var code = entry.code
}
write (filepath, code)
}
else if (entry.fileName === 'neutralino.d.ts')
{
var code = entry.source.toString ()
writeDts (joinPath (outdir, 'neutralino.d.ts'),
code.substring (code.indexOf("declare namespace"), code.lastIndexOf ("export")))
}
else
{
write (filepath, entry.source)
}
}
resetCommitHash()
})
.catch (err =>
{
console.error (
'\n' + err +
// RollupLogProps, https://github.com/rollup/rollup/blob/master/src/rollup/types.d.ts#L24
(typeof err.loc === 'object' ? '\n' + err.loc.file + ':' + err.loc.line : '') +
(typeof err.frame === 'string' ? '\n' + err.frame : '')
)
})
function write (filepath, content)
{
console.log ('write', filepath)
writeFile (filepath, content, { encoding: 'utf8' }, (err) =>
{
if (err)
console.error (''+err)
})
}
function patchInitFile (search, replace)
{
let initSource = readFileSync ('./src/api/init.ts', { encoding: 'utf8' })
initSource = initSource.replace (search, replace)
writeFileSync ('./src/api/init.ts', initSource, { encoding: 'utf8' })
}
function addCommitHash ()
{
exec ('git log -n 1 main --pretty=format:"%H"', (err, stdout) => {
let hash = stdout.trim()
patchInitFile ('<git_commit_hash_latest>', hash)
commitHash = hash
})
}
function resetCommitHash ()
{
patchInitFile (commitHash, '<git_commit_hash_latest>')
}
// Function to fetch all .ts files from the typings directory
const getTypeDefinitionFiles = () => {
const typingsDir = './src/types'; // Path to your typings directory
try {
const files = readdirSync(typingsDir);
return files.filter(file => file.endsWith('.ts'));
} catch (error) {
console.error('Error reading typings directory:', error);
return [];
}
};
// Fetch all .d.ts files from the typings directory
const typeFiles = getTypeDefinitionFiles();
const writeDts = (filepath, definitions) => {
// A 'declare' modifier cannot be used in an already ambient context.
definitions = definitions.replaceAll ('declare namespace', 'namespace')
definitions = definitions.replaceAll ('declare function', 'function')
// Read the type definition files
let typesSource = ''
typeFiles.forEach(file => {
let source = readFileSync (`./src/types/${file}`, { encoding: 'utf8' }) + '\n\n';
// Remove export keyword in the ambient declaration file
source = source.replaceAll ('export ', '');
typesSource += source;
});
let globalsSource = readFileSync ('./src/index.ts', { encoding: 'utf8' })
let globals = globalsSource.substring(globalsSource.indexOf('// --- globals ---'),
globalsSource.lastIndexOf('// --- globals ---'))
.trim()
.split('\n')
.map((s) => s.includes('NL_') ? s.replace(/NL_/g, 'declare const $&') : s )
.map((s) => s.trim())
.join('\n')
write (filepath,
`// Type definitions for Neutralino ${version}
// Project: https://github.com/neutralinojs
// Definitions project: https://github.com/neutralinojs/neutralino.js
declare namespace Neutralino {
${definitions}
}
${typesSource}
${globals}
${
// rollup-plugin-ts produce an empty map, maybe we will find a solution in the future.
// devmode ? '//# sourceMappingURL=neutralino.d.ts.map' : ''
''
}`/*dtsTemplate*/)
}