-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
504 lines (456 loc) · 12.4 KB
/
Copy pathindex.js
File metadata and controls
504 lines (456 loc) · 12.4 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
#!/usr/bin/env node
const fs = require('fs');
const { join } = require('path');
const { promisify } = require('util');
const childProcess = require('child_process');
const askQuestion = require('./ask-question.js');
const mkdir = promisify(fs.mkdir);
const exec = promisify(childProcess.exec);
const read = promisify(fs.readFile);
const write = promisify(fs.writeFile);
const cp = promisify(fs.cp);
/*
* calculate project directory name
*/
const defaultFolderName = 'new-typescript-package';
const initWorkingDirectory = process.cwd();
let folderName = defaultFolderName;
if (process.argv.slice(2).length > 0) {
folderName = process.argv.slice(2)[0];
}
const projectWorkingDirectory = join(initWorkingDirectory, folderName);
/* END */
async function main() {
/*
* make new directory and move into it
*/
console.log(`creating directory ${folderName}`);
await mkdir(projectWorkingDirectory);
process.chdir(projectWorkingDirectory);
/* END */
/*
* initialize npm in new project directory
*/
console.log('npm init');
await exec('npm init --yes');
await exec('npm pkg set version=0.0.0');
/* END */
/*
* install TypeScript
*/
console.log('installing TypeScript (this may take a while)');
await exec('npm install --save-dev typescript @types/node');
console.log('initializing typescript');
await exec('npx tsc --init');
console.log('updating tsconfig');
let tsconfig = await read(
join(projectWorkingDirectory, 'tsconfig.json'),
'utf8'
);
configUpdates = [
{
key: 'target',
value: '"ES2019"',
},
{
key: 'module',
value: '"Node18"',
},
{
key: 'rootDir',
value: '"./src"',
},
{
key: 'moduleResolution',
value: '"Node16"',
},
{
key: 'baseUrl',
value: '"."',
},
{
key: 'paths',
value: JSON.stringify({
'@/*': ['src/*'],
'@utils/*': ['src/utils/*'],
}),
},
{
key: 'rewriteRelativeImportExtensions',
value: true,
},
{
key: 'declaration',
value: true,
},
{
key: 'sourceMap',
value: true,
},
{
key: 'outDir',
value: '"./dist"',
},
{
key: 'removeComments',
value: false,
},
{
key: 'esModuleInterop',
value: true,
},
{
key: 'skipLibCheck',
value: true,
},
];
const valueReg = '(("[^"]+")|(true|false)|(\\[[^\\]]*\\])|({[^}]*}))';
configUpdates.forEach((update) => {
const reg = new RegExp(
`(\/\/)?\\s*"(${update.key})"\\s*:\\s*${valueReg}(,?\\s*\/\\*)`,
'gm'
);
tsconfig = tsconfig.replace(
reg,
(match, p1, p2, p3, p4, p5, p6, p7, p8) => {
return `${p1 ? '' : '\n '}"${p2}": ${update.value}${p8 || ''}`;
}
);
});
tsconfig = tsconfig.replace(
/}\r?\n}/,
`},
"include": ["src/**/*"],
"exclude": [
"node_modules",
"dist",
"tests"
]
}`
);
await write(join(projectWorkingDirectory, 'tsconfig.json'), tsconfig);
console.log('writing tsconfig for CommonJS');
await write(
join(projectWorkingDirectory, 'tsconfig.commonjs.json'),
JSON.stringify(
{
extends: './tsconfig.json',
compilerOptions: {
module: 'CommonJS',
moduleResolution: 'Node10',
target: 'ES5',
outDir: './dist/cjs',
declaration: false,
declarationMap: false,
},
},
null,
2
)
);
console.log('writing tsconfig for ESM');
await write(
join(projectWorkingDirectory, 'tsconfig.esm.json'),
JSON.stringify(
{
extends: './tsconfig.json',
compilerOptions: {
module: 'NodeNext',
moduleResolution: 'NodeNext',
target: 'ES2023',
outDir: './dist/esm',
declaration: false,
declarationMap: false,
},
},
null,
2
)
);
console.log('writing tsconfig for Types');
await write(
join(projectWorkingDirectory, 'tsconfig.types.json'),
JSON.stringify(
{
extends: './tsconfig.json',
compilerOptions: {
outDir: './dist/types',
emitDeclarationOnly: true,
declaration: true,
declarationMap: true,
},
},
null,
2
)
);
if (fs.existsSync(join(__dirname, '..', 'src'))) {
console.log('copying src directory');
await cp(
join(__dirname, '..', 'src'),
join(projectWorkingDirectory, 'src'),
{
recursive: true,
}
);
}
console.log('updating main in package.json');
await exec('npm pkg set main=./dist/cjs/index.js');
console.log('adding types to package.json');
await exec('npm pkg set types=./dist/types/index.d.ts');
console.log('adding module to package.json');
await exec('npm pkg set module=./dist/esm/index.js');
console.log('setting type in package.json');
await exec('npm pkg set type=module');
console.log('adding exports in package.json');
await exec('npm pkg set exports["."].import=./dist/esm/index.js');
await exec('npm pkg set exports["."].require=./dist/cjs/index.js');
await exec('npm pkg set exports["."].types=./dist/types/index.d.ts');
console.log('adding files in package.json');
await exec('npm pkg set files[0]=dist/**/*');
await exec('npm pkg set files[1]=README.md');
console.log('adding build script(s)');
await exec(
'npm pkg set scripts.build:cjs="tsc --project tsconfig.commonjs.json"'
);
await exec('npm pkg set scripts.build:esm="tsc --project tsconfig.esm.json"');
await exec(
'npm pkg set scripts.build="npm run build:cjs && npm run build:esm"'
);
await exec('npm pkg set scripts.build:types="tsc --project tsconfig.types.json"');
console.log('adding prepublishOnly script');
await exec('npm pkg set scripts.prepublishOnly="npm run build"');
console.log('adding clean script');
await exec(
`npm pkg set scripts.clean="node -e \\"require('fs').rmSync('./dist', { recursive: true, force: true })\\""`
);
console.log('adding prebuild script');
await exec('npm pkg set scripts.prebuild="npm run clean"');
console.log('adding postbuild script');
await exec('npm pkg set scripts.postbuild="npm run build:types"');
/* END */
/*
* install tsc-alias
*/
console.log('installing tsc-alias (this may take a while)');
await exec('npm install --save-dev tsc-alias');
console.log('updating build script(s)');
await exec(
'npm pkg set scripts.build:cjs="tsc --project tsconfig.commonjs.json && tsc-alias -p tsconfig.commonjs.json"'
);
await exec(
'npm pkg set scripts.build:esm="tsc --project tsconfig.esm.json && tsc-alias -p tsconfig.esm.json"'
);
/* END */
/*
* install ESLint
* TSLint has been deprecated in favor of ESLint
*/
console.log('installing ESLint (this may take a while)');
await exec('npm install --save-dev eslint@^8.56.0');
console.log('installing typescript-eslint (this may take a while)');
await exec(
'npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin'
);
console.log('writing eslintrc');
await write(
join(projectWorkingDirectory, '.eslintrc'),
JSON.stringify(
{
root: true,
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
'no-console': 0, // off
'no-shadow': 1, // warn
},
},
null,
2
)
);
console.log('writing eslintignore');
await write(
join(projectWorkingDirectory, '.eslintignore'),
['node_modules', 'dist', ''].join('\n')
);
console.log('adding lint script');
await exec('npm pkg set scripts.lint="eslint . --ext .ts,.js --fix"');
/* END */
/*
* install Mocha
*/
console.log('installing Mocha (this may take a while)');
await exec('npm install --save-dev mocha @types/mocha');
console.log('installing tsx (this may take a while)');
await exec('npm install --save-dev tsx tsconfig-paths');
console.log('installing cross-env (this may take a while)');
await exec('npm install --save-dev cross-env');
console.log('writing mocharc');
await write(
join(projectWorkingDirectory, '.mocharc.json'),
JSON.stringify(
{
extension: ['ts'],
spec: 'tests/**/*.spec.ts',
require: ['tsx', 'tsconfig-paths/register'],
recursive: true,
},
null,
2
)
);
console.log('writing test tsconfig');
await write(
join(projectWorkingDirectory, 'tsconfig.test.json'),
JSON.stringify(
{
extends: './tsconfig.json',
compilerOptions: {
module: 'CommonJS',
target: 'ES2017',
outDir: './dist/test',
rootDir: './',
noEmit: false,
types: ['node', 'mocha'],
sourceMap: true,
baseUrl: '.',
paths: {
'@/*': ['src/*'],
'@utils/*': ['src/utils/*'],
},
esModuleInterop: true,
},
include: ['src/**/*.ts', 'tests/**/*.spec.ts'],
exclude: ['node_modules', 'dist'],
},
null,
2
)
);
if (fs.existsSync(join(__dirname, '..', 'tests'))) {
console.log('copying tests directory');
await cp(
join(__dirname, '..', 'tests'),
join(projectWorkingDirectory, 'tests'),
{
recursive: true,
}
);
}
console.log('adding test script');
await exec(
`npm pkg set scripts.test="cross-env TSX_TSCONFIG_PATH='./tsconfig.test.json' mocha"`
);
/* END */
/*
* deno
*/
try {
await exec('deno --version');
await write(
join(projectWorkingDirectory, 'deno.json'),
JSON.stringify(
{
name: folderName,
version: '0.0.0',
exports: './src/index.ts',
tasks: {
dev: 'deno test --watch ./src/index.ts',
},
license: 'MIT',
imports: {
'@/': './src/',
'@utils/': './src/utils/',
'@std/assert': 'jsr:@std/assert@1',
},
lint: {
include: ['./src/'],
exclude: ['./tests/**/*.spec.ts'],
rules: {
tags: ['recommended'],
},
},
fmt: {
useTabs: false,
lineWidth: 80,
indentWidth: 2,
semiColons: true,
singleQuote: true,
proseWrap: 'preserve',
include: ['./src/'],
exclude: ['./tests/**/*.spec.ts'],
},
nodeModulesDir: 'auto',
exclude: ['./dist/'],
publish: {
include: ['./src/', 'README.md', 'deno.json'],
},
},
null,
2
)
);
} catch (error) {
if (error.message.includes('not found')) {
console.log('error finding deno, skipping deno setup');
} else {
console.log(`error: ${error.message}`);
}
}
/* END */
/*
* initialize and configure git
* ALWAYS goes last
*/
const usingGit = !!(
await askQuestion('Are you using git (Y/n)? ', 'y', (a) =>
a.trim().match(/^(y|n|yes|no)$/i) ? true : 'Please enter y or n'
)
)
.trim()
.match(/^(y|yes)$/i);
if (usingGit) {
const gitUrl = await askQuestion('What is the URL for your Git repo? ');
console.log('setting package repository');
await exec('npm pkg set repository.type=git');
await exec(`npm pkg set repository.url=git+${gitUrl}.git`);
console.log('setting package bugs');
await exec(`npm pkg set bugs.url=${gitUrl}/issues`);
console.log('setting package homepage');
await exec(`npm pkg set homepage=${gitUrl}#readme`);
console.log('adding node gitignore');
await exec('npx gitignore node');
if (fs.existsSync(join(__dirname, 'github'))) {
console.log('copying github directory');
await cp(
join(__dirname, 'github'),
join(projectWorkingDirectory, '.github'),
{
recursive: true,
}
);
}
console.log('git init');
await exec('git init');
console.log('initial commit');
await exec('git add --all');
await exec('git commit -m "initial commit"');
console.log('adding git remote origin');
await exec(`git remote add origin ${gitUrl}.git`);
}
/* END */
}
main()
.catch((err) => {
console.error('Error: ', err);
process.exit(1);
})
.then(() => {
console.log('Done');
});