jitsu-cli 1.10.3 → 2.14.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,900 +0,0 @@
1
- import * as path from 'path';
2
- import path__default, { resolve as resolve$1, dirname, relative } from 'path';
3
- import { createFilter } from '@rollup/pluginutils';
4
- import typescript$1 from 'typescript';
5
- import { fileURLToPath } from 'url';
6
- import resolve from 'resolve';
7
- import fs, { readFileSync, promises } from 'fs';
8
-
9
- /**
10
- * Create a format diagnostics host to use with the Typescript type checking APIs.
11
- * Typescript hosts are used to represent the user's system,
12
- * with an API for checking case sensitivity etc.
13
- * @param compilerOptions Typescript compiler options. Affects functions such as `getNewLine`.
14
- * @see https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
15
- */
16
- function createFormattingHost(ts, compilerOptions) {
17
- return {
18
- /** Returns the compiler options for the project. */
19
- getCompilationSettings: () => compilerOptions,
20
- /** Returns the current working directory. */
21
- getCurrentDirectory: () => process.cwd(),
22
- /** Returns the string that corresponds with the selected `NewLineKind`. */
23
- getNewLine() {
24
- switch (compilerOptions.newLine) {
25
- case ts.NewLineKind.CarriageReturnLineFeed:
26
- return '\r\n';
27
- case ts.NewLineKind.LineFeed:
28
- return '\n';
29
- default:
30
- return ts.sys.newLine;
31
- }
32
- },
33
- /** Returns a lower case name on case insensitive systems, otherwise the original name. */
34
- getCanonicalFileName: (fileName) => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase()
35
- };
36
- }
37
-
38
- /**
39
- * Create a helper for resolving modules using Typescript.
40
- * @param host Typescript host that extends `ModuleResolutionHost`
41
- * with methods for sanitizing filenames and getting compiler options.
42
- */
43
- function createModuleResolver(ts, host, filter) {
44
- const compilerOptions = host.getCompilationSettings();
45
- const cache = ts.createModuleResolutionCache(process.cwd(), host.getCanonicalFileName, compilerOptions);
46
- const moduleHost = { ...ts.sys, ...host };
47
- return (moduleName, containingFile, redirectedReference, mode) => {
48
- const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, compilerOptions, moduleHost, cache, redirectedReference, mode);
49
- /**
50
- * If the module's path contains 'node_modules', ts considers it an external library and refuses to compile it,
51
- * so we have to change the value of `isExternalLibraryImport` to false if it's true
52
- * */
53
- if ((resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.isExternalLibraryImport) && filter(resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.resolvedFileName)) {
54
- resolvedModule.isExternalLibraryImport = false;
55
- }
56
- return resolvedModule;
57
- };
58
- }
59
-
60
- // const resolveIdAsync = (file: string, opts: AsyncOpts) =>
61
- // new Promise<string>((fulfil, reject) =>
62
- // resolveId(file, opts, (err, contents) =>
63
- // err || typeof contents === 'undefined' ? reject(err) : fulfil(contents)
64
- // )
65
- // );
66
- const resolveId = (file, opts) => resolve.sync(file, opts);
67
- /**
68
- * Returns code asynchronously for the tslib helper library.
69
- */
70
- const getTsLibPath = () => {
71
- // Note: This isn't preferable, but we've no other way to test this bit. Removing the tslib devDep
72
- // during the test run doesn't work due to the nature of the pnpm flat node_modules, and
73
- // other workspace dependencies that depenend upon tslib.
74
- try {
75
- // eslint-disable-next-line no-underscore-dangle
76
- return resolveId(process.env.__TSLIB_TEST_PATH__ || 'tslib/tslib.es6.js', {
77
- // @ts-ignore import.meta.url is allowed because the Rollup plugin injects the correct module format
78
- basedir: fileURLToPath(new URL('.', import.meta.url))
79
- });
80
- }
81
- catch (_) {
82
- return null;
83
- }
84
- };
85
-
86
- /**
87
- * Separate the Rollup plugin options from the Typescript compiler options,
88
- * and normalize the Rollup options.
89
- * @returns Object with normalized options:
90
- * - `filter`: Checks if a file should be included.
91
- * - `tsconfig`: Path to a tsconfig, or directive to ignore tsconfig.
92
- * - `compilerOptions`: Custom Typescript compiler options that override tsconfig.
93
- * - `typescript`: Instance of Typescript library (possibly custom).
94
- * - `tslib`: ESM code from the tslib helper library (possibly custom).
95
- */
96
- const getPluginOptions = (options) => {
97
- const { cacheDir, exclude, include, filterRoot, noForceEmit, transformers, tsconfig, tslib, typescript, outputToFilesystem, compilerOptions,
98
- // previously was compilerOptions
99
- ...extra } = options;
100
- return {
101
- cacheDir,
102
- include,
103
- exclude,
104
- filterRoot,
105
- noForceEmit: noForceEmit || false,
106
- tsconfig,
107
- compilerOptions: { ...extra, ...compilerOptions },
108
- typescript: typescript || typescript$1,
109
- tslib: tslib || getTsLibPath(),
110
- transformers,
111
- outputToFilesystem
112
- };
113
- };
114
-
115
- /**
116
- * Converts a Typescript type error into an equivalent Rollup warning object.
117
- */
118
- function diagnosticToWarning(ts, host, diagnostic) {
119
- const pluginCode = `TS${diagnostic.code}`;
120
- const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
121
- // Build a Rollup warning object from the diagnostics object.
122
- const warning = {
123
- pluginCode,
124
- message: `@rollup/plugin-typescript ${pluginCode}: ${message}`
125
- };
126
- if (diagnostic.file) {
127
- // Add information about the file location
128
- const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
129
- warning.loc = {
130
- column: character + 1,
131
- line: line + 1,
132
- file: diagnostic.file.fileName
133
- };
134
- if (host) {
135
- // Extract a code frame from Typescript
136
- const formatted = ts.formatDiagnosticsWithColorAndContext([diagnostic], host);
137
- // Typescript only exposes this formatter as a string prefixed with the flattened message.
138
- // We need to remove it here since Rollup treats the properties as separate parts.
139
- let frame = formatted.slice(formatted.indexOf(message) + message.length);
140
- const newLine = host.getNewLine();
141
- if (frame.startsWith(newLine)) {
142
- frame = frame.slice(frame.indexOf(newLine) + newLine.length);
143
- }
144
- warning.frame = frame;
145
- }
146
- }
147
- return warning;
148
- }
149
-
150
- const DEFAULT_COMPILER_OPTIONS = {
151
- module: 'esnext',
152
- skipLibCheck: true
153
- };
154
- const OVERRIDABLE_EMIT_COMPILER_OPTIONS = {
155
- noEmit: false,
156
- emitDeclarationOnly: false
157
- };
158
- const FORCED_COMPILER_OPTIONS = {
159
- // Always use tslib
160
- noEmitHelpers: true,
161
- importHelpers: true,
162
- // Preventing Typescript from resolving code may break compilation
163
- noResolve: false
164
- };
165
-
166
- /* eslint-disable no-param-reassign */
167
- const DIRECTORY_PROPS = ['outDir', 'declarationDir'];
168
- /**
169
- * Mutates the compiler options to convert paths from relative to absolute.
170
- * This should be used with compiler options passed through the Rollup plugin options,
171
- * not those found from loading a tsconfig.json file.
172
- * @param compilerOptions Compiler options to _mutate_.
173
- * @param relativeTo Paths are resolved relative to this path.
174
- */
175
- function makePathsAbsolute(compilerOptions, relativeTo) {
176
- for (const pathProp of DIRECTORY_PROPS) {
177
- if (compilerOptions[pathProp]) {
178
- compilerOptions[pathProp] = resolve$1(relativeTo, compilerOptions[pathProp]);
179
- }
180
- }
181
- }
182
- /**
183
- * Mutates the compiler options to normalize some values for Rollup.
184
- * @param compilerOptions Compiler options to _mutate_.
185
- * @returns True if the source map compiler option was not initially set.
186
- */
187
- function normalizeCompilerOptions(ts, compilerOptions) {
188
- let autoSetSourceMap = false;
189
- if (compilerOptions.inlineSourceMap) {
190
- // Force separate source map files for Rollup to work with.
191
- compilerOptions.sourceMap = true;
192
- compilerOptions.inlineSourceMap = false;
193
- }
194
- else if (typeof compilerOptions.sourceMap !== 'boolean') {
195
- // Default to using source maps.
196
- // If the plugin user sets sourceMap to false we keep that option.
197
- compilerOptions.sourceMap = true;
198
- // Using inlineSources to make sure typescript generate source content
199
- // instead of source path.
200
- compilerOptions.inlineSources = true;
201
- autoSetSourceMap = true;
202
- }
203
- switch (compilerOptions.module) {
204
- case ts.ModuleKind.ES2015:
205
- case ts.ModuleKind.ESNext:
206
- case ts.ModuleKind.Node16:
207
- case ts.ModuleKind.NodeNext:
208
- case ts.ModuleKind.CommonJS:
209
- // OK module type
210
- return autoSetSourceMap;
211
- case ts.ModuleKind.None:
212
- case ts.ModuleKind.AMD:
213
- case ts.ModuleKind.UMD:
214
- case ts.ModuleKind.System: {
215
- // Invalid module type
216
- const moduleType = ts.ModuleKind[compilerOptions.module];
217
- throw new Error(`@rollup/plugin-typescript: The module kind should be 'ES2015', 'ESNext', 'node16' or 'nodenext', found: '${moduleType}'`);
218
- }
219
- default:
220
- // Unknown or unspecified module type, force ESNext
221
- compilerOptions.module = ts.ModuleKind.ESNext;
222
- }
223
- return autoSetSourceMap;
224
- }
225
-
226
- const { ModuleKind: ModuleKind$1, ModuleResolutionKind } = typescript$1;
227
- function makeForcedCompilerOptions(noForceEmit) {
228
- return { ...FORCED_COMPILER_OPTIONS, ...(noForceEmit ? {} : OVERRIDABLE_EMIT_COMPILER_OPTIONS) };
229
- }
230
- /**
231
- * Finds the path to the tsconfig file relative to the current working directory.
232
- * @param relativePath Relative tsconfig path given by the user.
233
- * If `false` is passed, then a null path is returned.
234
- * @returns The absolute path, or null if the file does not exist.
235
- */
236
- function getTsConfigPath(ts, relativePath) {
237
- if (relativePath === false)
238
- return null;
239
- // Resolve path to file. `tsConfigOption` defaults to 'tsconfig.json'.
240
- const tsConfigPath = resolve$1(process.cwd(), relativePath || 'tsconfig.json');
241
- if (!ts.sys.fileExists(tsConfigPath)) {
242
- if (relativePath) {
243
- // If an explicit path was provided but no file was found, throw
244
- throw new Error(`Could not find specified tsconfig.json at ${tsConfigPath}`);
245
- }
246
- else {
247
- return null;
248
- }
249
- }
250
- return tsConfigPath;
251
- }
252
- /**
253
- * Tries to read the tsconfig file at `tsConfigPath`.
254
- * @param tsConfigPath Absolute path to tsconfig JSON file.
255
- * @param explicitPath If true, the path was set by the plugin user.
256
- * If false, the path was computed automatically.
257
- */
258
- function readTsConfigFile(ts, tsConfigPath) {
259
- const { config, error } = ts.readConfigFile(tsConfigPath, (path) => readFileSync(path, 'utf8'));
260
- if (error) {
261
- throw Object.assign(Error(), diagnosticToWarning(ts, null, error));
262
- }
263
- return config || {};
264
- }
265
- /**
266
- * Returns true if any of the `compilerOptions` contain an enum value (i.e.: ts.ScriptKind) rather than a string.
267
- * This indicates that the internal CompilerOptions type is used rather than the JsonCompilerOptions.
268
- */
269
- function containsEnumOptions(compilerOptions) {
270
- const enums = [
271
- 'module',
272
- 'target',
273
- 'jsx',
274
- 'moduleResolution',
275
- 'newLine'
276
- ];
277
- return enums.some((prop) => prop in compilerOptions && typeof compilerOptions[prop] === 'number');
278
- }
279
- /**
280
- * The module resolution kind is a function of the resolved `compilerOptions.module`.
281
- * This needs to be set explicitly for `resolveModuleName` to select the correct resolution method
282
- */
283
- function setModuleResolutionKind(parsedConfig) {
284
- const moduleKind = parsedConfig.options.module;
285
- // Fallback if `parsedConfig.options.moduleResolution` is not set
286
- const moduleResolution = moduleKind === ModuleKind$1.Node16
287
- ? ModuleResolutionKind.Node16
288
- : moduleKind === ModuleKind$1.NodeNext
289
- ? ModuleResolutionKind.NodeNext
290
- : ModuleResolutionKind.NodeJs;
291
- return {
292
- ...parsedConfig,
293
- options: {
294
- moduleResolution,
295
- ...parsedConfig.options
296
- }
297
- };
298
- }
299
- const configCache = new Map();
300
- /**
301
- * Parse the Typescript config to use with the plugin.
302
- * @param ts Typescript library instance.
303
- * @param tsconfig Path to the tsconfig file, or `false` to ignore the file.
304
- * @param compilerOptions Options passed to the plugin directly for Typescript.
305
- *
306
- * @returns Parsed tsconfig.json file with some important properties:
307
- * - `options`: Parsed compiler options.
308
- * - `fileNames` Type definition files that should be included in the build.
309
- * - `errors`: Any errors from parsing the config file.
310
- */
311
- function parseTypescriptConfig(ts, tsconfig, compilerOptions, noForceEmit) {
312
- /* eslint-disable no-undefined */
313
- const cwd = process.cwd();
314
- makePathsAbsolute(compilerOptions, cwd);
315
- let parsedConfig;
316
- // Resolve path to file. If file is not found, pass undefined path to `parseJsonConfigFileContent`.
317
- // eslint-disable-next-line no-undefined
318
- const tsConfigPath = getTsConfigPath(ts, tsconfig) || undefined;
319
- const tsConfigFile = tsConfigPath ? readTsConfigFile(ts, tsConfigPath) : {};
320
- const basePath = tsConfigPath ? dirname(tsConfigPath) : cwd;
321
- // If compilerOptions has enums, it represents an CompilerOptions object instead of parsed JSON.
322
- // This determines where the data is passed to the parser.
323
- if (containsEnumOptions(compilerOptions)) {
324
- parsedConfig = setModuleResolutionKind(ts.parseJsonConfigFileContent({
325
- ...tsConfigFile,
326
- compilerOptions: {
327
- ...DEFAULT_COMPILER_OPTIONS,
328
- ...tsConfigFile.compilerOptions
329
- }
330
- }, ts.sys, basePath, { ...compilerOptions, ...makeForcedCompilerOptions(noForceEmit) }, tsConfigPath, undefined, undefined, configCache));
331
- }
332
- else {
333
- parsedConfig = setModuleResolutionKind(ts.parseJsonConfigFileContent({
334
- ...tsConfigFile,
335
- compilerOptions: {
336
- ...DEFAULT_COMPILER_OPTIONS,
337
- ...tsConfigFile.compilerOptions,
338
- ...compilerOptions
339
- }
340
- }, ts.sys, basePath, makeForcedCompilerOptions(noForceEmit), tsConfigPath, undefined, undefined, configCache));
341
- }
342
- const autoSetSourceMap = normalizeCompilerOptions(ts, parsedConfig.options);
343
- return {
344
- ...parsedConfig,
345
- autoSetSourceMap
346
- };
347
- }
348
- /**
349
- * If errors are detected in the parsed options,
350
- * display all of them as warnings then emit an error.
351
- */
352
- function emitParsedOptionsErrors(ts, context, parsedOptions) {
353
- if (parsedOptions.errors.length > 0) {
354
- parsedOptions.errors.forEach((error) => context.warn(diagnosticToWarning(ts, null, error)));
355
- context.error(`@rollup/plugin-typescript: Couldn't process compiler options`);
356
- }
357
- }
358
-
359
- /**
360
- * Validate that the `compilerOptions.sourceMap` option matches `outputOptions.sourcemap`.
361
- * @param context Rollup plugin context used to emit warnings.
362
- * @param compilerOptions Typescript compiler options.
363
- * @param outputOptions Rollup output options.
364
- * @param autoSetSourceMap True if the `compilerOptions.sourceMap` property was set to `true`
365
- * by the plugin, not the user.
366
- */
367
- function validateSourceMap(context, compilerOptions, outputOptions, autoSetSourceMap) {
368
- if (compilerOptions.sourceMap && !outputOptions.sourcemap && !autoSetSourceMap) {
369
- context.warn(`@rollup/plugin-typescript: Rollup 'sourcemap' option must be set to generate source maps.`);
370
- }
371
- else if (!compilerOptions.sourceMap && outputOptions.sourcemap) {
372
- context.warn(`@rollup/plugin-typescript: Typescript 'sourceMap' compiler option must be set to generate source maps.`);
373
- }
374
- }
375
- /**
376
- * Validate that the out directory used by Typescript can be controlled by Rollup.
377
- * @param context Rollup plugin context used to emit errors.
378
- * @param compilerOptions Typescript compiler options.
379
- * @param outputOptions Rollup output options.
380
- */
381
- function validatePaths(context, compilerOptions, outputOptions) {
382
- if (compilerOptions.out) {
383
- context.error(`@rollup/plugin-typescript: Deprecated Typescript compiler option 'out' is not supported. Use 'outDir' instead.`);
384
- }
385
- else if (compilerOptions.outFile) {
386
- context.error(`@rollup/plugin-typescript: Typescript compiler option 'outFile' is not supported. Use 'outDir' instead.`);
387
- }
388
- for (const dirProperty of DIRECTORY_PROPS) {
389
- if (compilerOptions[dirProperty] && outputOptions.dir) {
390
- // Checks if the given path lies within Rollup output dir
391
- const fromRollupDirToTs = relative(outputOptions.dir, compilerOptions[dirProperty]);
392
- if (fromRollupDirToTs.startsWith('..')) {
393
- context.error(`@rollup/plugin-typescript: Path of Typescript compiler option '${dirProperty}' must be located inside Rollup 'dir' option.`);
394
- }
395
- }
396
- }
397
- if (compilerOptions.declaration || compilerOptions.declarationMap || compilerOptions.composite) {
398
- if (DIRECTORY_PROPS.every((dirProperty) => !compilerOptions[dirProperty])) {
399
- context.error(`@rollup/plugin-typescript: You are using one of Typescript's compiler options 'declaration', 'declarationMap' or 'composite'. ` +
400
- `In this case 'outDir' or 'declarationDir' must be specified to generate declaration files.`);
401
- }
402
- }
403
- }
404
-
405
- /**
406
- * Checks if the given OutputFile represents some code
407
- */
408
- function isCodeOutputFile(name) {
409
- return !isMapOutputFile(name) && !isDeclarationOutputFile(name);
410
- }
411
- /**
412
- * Checks if the given OutputFile represents some source map
413
- */
414
- function isMapOutputFile(name) {
415
- return name.endsWith('.map');
416
- }
417
- /**
418
- * Checks if the given OutputFile represents some TypeScript source map
419
- */
420
- function isTypeScriptMapOutputFile(name) {
421
- return name.endsWith('ts.map');
422
- }
423
- /**
424
- * Checks if the given OutputFile represents some declaration
425
- */
426
- function isDeclarationOutputFile(name) {
427
- return /\.d\.[cm]?ts$/.test(name);
428
- }
429
- /**
430
- * Returns the content of a filename either from the current
431
- * typescript compiler instance or from the cached content.
432
- * @param fileName The filename for the contents to retrieve
433
- * @param emittedFiles The files emitted in the current typescript instance
434
- * @param tsCache A cache to files cached by Typescript
435
- */
436
- function getEmittedFile(fileName, emittedFiles, tsCache) {
437
- let code;
438
- if (fileName) {
439
- if (emittedFiles.has(fileName)) {
440
- code = emittedFiles.get(fileName);
441
- }
442
- else {
443
- code = tsCache.getCached(fileName);
444
- }
445
- }
446
- return code;
447
- }
448
- /**
449
- * Finds the corresponding emitted Javascript files for a given Typescript file.
450
- * @param id Path to the Typescript file.
451
- * @param emittedFiles Map of file names to source code,
452
- * containing files emitted by the Typescript compiler.
453
- */
454
- function findTypescriptOutput(ts, parsedOptions, id, emittedFiles, tsCache) {
455
- const emittedFileNames = ts.getOutputFileNames(parsedOptions, id, !ts.sys.useCaseSensitiveFileNames);
456
- const codeFile = emittedFileNames.find(isCodeOutputFile);
457
- const mapFile = emittedFileNames.find(isMapOutputFile);
458
- return {
459
- code: getEmittedFile(codeFile, emittedFiles, tsCache),
460
- map: getEmittedFile(mapFile, emittedFiles, tsCache),
461
- declarations: emittedFileNames.filter((name) => name !== codeFile && name !== mapFile)
462
- };
463
- }
464
- function normalizePath(fileName) {
465
- return fileName.split(path.win32.sep).join(path.posix.sep);
466
- }
467
- async function emitFile({ dir }, outputToFilesystem, context, filePath, fileSource) {
468
- const normalizedFilePath = normalizePath(filePath);
469
- // const normalizedPath = normalizePath(filePath);
470
- // Note: `dir` can be a value like `dist` in which case, `path.relative` could result in a value
471
- // of something like `'../.tsbuildinfo'. Our else-case below needs to mimic `path.relative`
472
- // returning a dot-notated relative path, so the first if-then branch is entered into
473
- const relativePath = dir ? path.relative(dir, normalizedFilePath) : '..';
474
- // legal paths do not start with . nor .. : https://github.com/rollup/rollup/issues/3507#issuecomment-616495912
475
- if (relativePath.startsWith('..')) {
476
- if (outputToFilesystem == null) {
477
- context.warn(`@rollup/plugin-typescript: outputToFilesystem option is defaulting to true.`);
478
- }
479
- if (outputToFilesystem !== false) {
480
- await promises.mkdir(path.dirname(normalizedFilePath), { recursive: true });
481
- await promises.writeFile(normalizedFilePath, fileSource);
482
- }
483
- }
484
- else {
485
- context.emitFile({
486
- type: 'asset',
487
- fileName: relativePath,
488
- source: fileSource
489
- });
490
- }
491
- }
492
-
493
- // import { resolveIdAsync } from './tslib';
494
- const { ModuleKind } = typescript$1;
495
- const pluginName = '@rollup/plugin-typescript';
496
- const moduleErrorMessage = `
497
- ${pluginName}: Rollup requires that TypeScript produces ES Modules. Unfortunately your configuration specifies a
498
- "module" other than "esnext". Unless you know what you're doing, please change "module" to "esnext"
499
- in the target tsconfig.json file or plugin options.`.replace(/\n/g, '');
500
- const tsLibErrorMessage = `${pluginName}: Could not find module 'tslib', which is required by this plugin. Is it installed?`;
501
- let undef;
502
- const validModules = [
503
- ModuleKind.ES2015,
504
- ModuleKind.ES2020,
505
- ModuleKind.ESNext,
506
- ModuleKind.Node16,
507
- ModuleKind.NodeNext,
508
- undef
509
- ];
510
- // eslint-disable-next-line import/prefer-default-export
511
- const preflight = ({ config, context, inputPreserveModules, tslib }) => {
512
- if (!validModules.includes(config.options.module)) {
513
- context.warn(moduleErrorMessage);
514
- }
515
- if (!inputPreserveModules && tslib === null) {
516
- context.error(tsLibErrorMessage);
517
- }
518
- };
519
-
520
- // `Cannot compile modules into 'es6' when targeting 'ES5' or lower.`
521
- const CANNOT_COMPILE_ESM = 1204;
522
- /**
523
- * Emit a Rollup warning or error for a Typescript type error.
524
- */
525
- function emitDiagnostic(ts, context, host, diagnostic) {
526
- if (diagnostic.code === CANNOT_COMPILE_ESM)
527
- return;
528
- const { noEmitOnError } = host.getCompilationSettings();
529
- // Build a Rollup warning object from the diagnostics object.
530
- const warning = diagnosticToWarning(ts, host, diagnostic);
531
- // Errors are fatal. Otherwise emit warnings.
532
- if (noEmitOnError && diagnostic.category === ts.DiagnosticCategory.Error) {
533
- context.error(warning);
534
- }
535
- else {
536
- context.warn(warning);
537
- }
538
- }
539
- function buildDiagnosticReporter(ts, context, host) {
540
- return function reportDiagnostics(diagnostic) {
541
- emitDiagnostic(ts, context, host, diagnostic);
542
- };
543
- }
544
-
545
- /**
546
- * Merges all received custom transformer definitions into a single CustomTransformers object
547
- */
548
- function mergeTransformers(builder, ...input) {
549
- // List of all transformer stages
550
- const transformerTypes = ['after', 'afterDeclarations', 'before'];
551
- const accumulator = {
552
- after: [],
553
- afterDeclarations: [],
554
- before: []
555
- };
556
- let program;
557
- let typeChecker;
558
- input.forEach((transformers) => {
559
- if (!transformers) {
560
- // Skip empty arguments lists
561
- return;
562
- }
563
- transformerTypes.forEach((stage) => {
564
- getTransformers(transformers[stage]).forEach((transformer) => {
565
- if (!transformer) {
566
- // Skip empty
567
- return;
568
- }
569
- if ('type' in transformer) {
570
- if (typeof transformer.factory === 'function') {
571
- // Allow custom factories to grab the extra information required
572
- program = program || builder.getProgram();
573
- typeChecker = typeChecker || program.getTypeChecker();
574
- let factory;
575
- if (transformer.type === 'program') {
576
- program = program || builder.getProgram();
577
- factory = transformer.factory(program);
578
- }
579
- else {
580
- program = program || builder.getProgram();
581
- typeChecker = typeChecker || program.getTypeChecker();
582
- factory = transformer.factory(typeChecker);
583
- }
584
- // Forward the requested reference to the custom transformer factory
585
- if (factory) {
586
- accumulator[stage].push(factory);
587
- }
588
- }
589
- }
590
- else {
591
- // Add normal transformer factories as is
592
- accumulator[stage].push(transformer);
593
- }
594
- });
595
- });
596
- });
597
- return accumulator;
598
- }
599
- function getTransformers(transformers) {
600
- return transformers || [];
601
- }
602
-
603
- const { DiagnosticCategory } = typescript$1;
604
- // @see https://github.com/microsoft/TypeScript/blob/master/src/compiler/diagnosticMessages.json
605
- // eslint-disable-next-line no-shadow
606
- var DiagnosticCode;
607
- (function (DiagnosticCode) {
608
- DiagnosticCode[DiagnosticCode["FILE_CHANGE_DETECTED"] = 6032] = "FILE_CHANGE_DETECTED";
609
- DiagnosticCode[DiagnosticCode["FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES"] = 6193] = "FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES";
610
- DiagnosticCode[DiagnosticCode["FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES"] = 6194] = "FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES";
611
- })(DiagnosticCode || (DiagnosticCode = {}));
612
- function createDeferred(timeout) {
613
- let promise;
614
- let resolve = () => { };
615
- if (timeout) {
616
- promise = Promise.race([
617
- new Promise((r) => setTimeout(r, timeout, true)),
618
- new Promise((r) => (resolve = r))
619
- ]);
620
- }
621
- else {
622
- promise = new Promise((r) => (resolve = r));
623
- }
624
- return { promise, resolve };
625
- }
626
- /**
627
- * Typescript watch program helper to sync Typescript watch status with Rollup hooks.
628
- */
629
- class WatchProgramHelper {
630
- constructor() {
631
- this._startDeferred = null;
632
- this._finishDeferred = null;
633
- }
634
- watch(timeout = 1000) {
635
- // Race watcher start promise against a timeout in case Typescript and Rollup change detection is not in sync.
636
- this._startDeferred = createDeferred(timeout);
637
- this._finishDeferred = createDeferred();
638
- }
639
- handleStatus(diagnostic) {
640
- // Fullfil deferred promises by Typescript diagnostic message codes.
641
- if (diagnostic.category === DiagnosticCategory.Message) {
642
- switch (diagnostic.code) {
643
- case DiagnosticCode.FILE_CHANGE_DETECTED:
644
- this.resolveStart();
645
- break;
646
- case DiagnosticCode.FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES:
647
- case DiagnosticCode.FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES:
648
- this.resolveFinish();
649
- break;
650
- }
651
- }
652
- }
653
- resolveStart() {
654
- if (this._startDeferred) {
655
- this._startDeferred.resolve(false);
656
- this._startDeferred = null;
657
- }
658
- }
659
- resolveFinish() {
660
- if (this._finishDeferred) {
661
- this._finishDeferred.resolve(false);
662
- this._finishDeferred = null;
663
- }
664
- }
665
- async wait() {
666
- var _a;
667
- if (this._startDeferred) {
668
- const timeout = await this._startDeferred.promise;
669
- // If there is no file change detected by Typescript skip deferred promises.
670
- if (timeout) {
671
- this._startDeferred = null;
672
- this._finishDeferred = null;
673
- }
674
- await ((_a = this._finishDeferred) === null || _a === void 0 ? void 0 : _a.promise);
675
- }
676
- }
677
- }
678
- /**
679
- * Create a language service host to use with the Typescript compiler & type checking APIs.
680
- * Typescript hosts are used to represent the user's system,
681
- * with an API for reading files, checking directories and case sensitivity etc.
682
- * @see https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
683
- */
684
- function createWatchHost(ts, context, { formatHost, parsedOptions, writeFile, status, resolveModule, transformers }) {
685
- const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
686
- const baseHost = ts.createWatchCompilerHost(parsedOptions.fileNames, parsedOptions.options, ts.sys, createProgram, buildDiagnosticReporter(ts, context, formatHost), status, parsedOptions.projectReferences);
687
- return {
688
- ...baseHost,
689
- /** Override the created program so an in-memory emit is used */
690
- afterProgramCreate(program) {
691
- const origEmit = program.emit;
692
- // eslint-disable-next-line no-param-reassign
693
- program.emit = (targetSourceFile, _, ...args) => origEmit(targetSourceFile, writeFile,
694
- // cancellationToken
695
- args[0],
696
- // emitOnlyDtsFiles
697
- args[1], mergeTransformers(program, transformers, args[2]));
698
- return baseHost.afterProgramCreate(program);
699
- },
700
- /** Add helper to deal with module resolution */
701
- resolveModuleNames(moduleNames, containingFile, _reusedNames, redirectedReference, _optionsOnlyWithNewerTsVersions, containingSourceFile) {
702
- return moduleNames.map((moduleName, i) => {
703
- var _a;
704
- const mode = containingSourceFile
705
- ? (_a = ts.getModeForResolutionAtIndex) === null || _a === void 0 ? void 0 : _a.call(ts, containingSourceFile, i)
706
- : undefined; // eslint-disable-line no-undefined
707
- return resolveModule(moduleName, containingFile, redirectedReference, mode);
708
- });
709
- }
710
- };
711
- }
712
- function createWatchProgram(ts, context, options) {
713
- return ts.createWatchProgram(createWatchHost(ts, context, options));
714
- }
715
-
716
- /** Creates the folders needed given a path to a file to be saved*/
717
- const createFileFolder = (filePath) => {
718
- const folderPath = path__default.dirname(filePath);
719
- fs.mkdirSync(folderPath, { recursive: true });
720
- };
721
- class TSCache {
722
- constructor(cacheFolder = '.rollup.cache') {
723
- this._cacheFolder = cacheFolder;
724
- }
725
- /** Returns the path to the cached file */
726
- cachedFilename(fileName) {
727
- return path__default.join(this._cacheFolder, fileName.replace(/^([a-zA-Z]+):/, '$1'));
728
- }
729
- /** Emits a file in the cache folder */
730
- cacheCode(fileName, code) {
731
- const cachedPath = this.cachedFilename(fileName);
732
- createFileFolder(cachedPath);
733
- fs.writeFileSync(cachedPath, code);
734
- }
735
- /** Checks if a file is in the cache */
736
- isCached(fileName) {
737
- return fs.existsSync(this.cachedFilename(fileName));
738
- }
739
- /** Read a file from the cache given the output name*/
740
- getCached(fileName) {
741
- let code;
742
- if (this.isCached(fileName)) {
743
- code = fs.readFileSync(this.cachedFilename(fileName), { encoding: 'utf-8' });
744
- }
745
- return code;
746
- }
747
- }
748
-
749
- function typescript(options = {}) {
750
- const { cacheDir, compilerOptions, exclude, filterRoot, include, outputToFilesystem, noForceEmit, transformers, tsconfig, tslib, typescript: ts } = getPluginOptions(options);
751
- const tsCache = new TSCache(cacheDir);
752
- const emittedFiles = new Map();
753
- const watchProgramHelper = new WatchProgramHelper();
754
- const parsedOptions = parseTypescriptConfig(ts, tsconfig, compilerOptions, noForceEmit);
755
- const filter = createFilter(include || '{,**/}*.(cts|mts|ts|tsx)', exclude, {
756
- resolve: filterRoot !== null && filterRoot !== void 0 ? filterRoot : parsedOptions.options.rootDir
757
- });
758
- parsedOptions.fileNames = parsedOptions.fileNames.filter(filter);
759
- const formatHost = createFormattingHost(ts, parsedOptions.options);
760
- const resolveModule = createModuleResolver(ts, formatHost, filter);
761
- let program = null;
762
- return {
763
- name: 'typescript',
764
- buildStart(rollupOptions) {
765
- emitParsedOptionsErrors(ts, this, parsedOptions);
766
- preflight({
767
- config: parsedOptions,
768
- context: this,
769
- // TODO drop rollup@3 support and remove
770
- inputPreserveModules: rollupOptions
771
- .preserveModules,
772
- tslib
773
- });
774
- // Fixes a memory leak https://github.com/rollup/plugins/issues/322
775
- if (this.meta.watchMode !== true) {
776
- // eslint-disable-next-line
777
- program === null || program === void 0 ? void 0 : program.close();
778
- program = null;
779
- }
780
- if (!program) {
781
- program = createWatchProgram(ts, this, {
782
- formatHost,
783
- resolveModule,
784
- parsedOptions,
785
- writeFile(fileName, data) {
786
- if (parsedOptions.options.composite || parsedOptions.options.incremental) {
787
- tsCache.cacheCode(fileName, data);
788
- }
789
- emittedFiles.set(fileName, data);
790
- },
791
- status(diagnostic) {
792
- watchProgramHelper.handleStatus(diagnostic);
793
- },
794
- transformers
795
- });
796
- }
797
- },
798
- watchChange(id) {
799
- if (!filter(id))
800
- return;
801
- watchProgramHelper.watch();
802
- },
803
- buildEnd() {
804
- if (this.meta.watchMode !== true) {
805
- // ESLint doesn't understand optional chaining
806
- // eslint-disable-next-line
807
- program === null || program === void 0 ? void 0 : program.close();
808
- }
809
- },
810
- renderStart(outputOptions) {
811
- validateSourceMap(this, parsedOptions.options, outputOptions, parsedOptions.autoSetSourceMap);
812
- validatePaths(this, parsedOptions.options, outputOptions);
813
- },
814
- resolveId(importee, importer) {
815
- if (importee === 'tslib') {
816
- return tslib;
817
- }
818
- if (!importer)
819
- return null;
820
- // Convert path from windows separators to posix separators
821
- const containingFile = normalizePath(importer);
822
- // when using node16 or nodenext module resolution, we need to tell ts if
823
- // we are resolving to a commonjs or esnext module
824
- const mode = typeof ts.getImpliedNodeFormatForFile === 'function'
825
- ? ts.getImpliedNodeFormatForFile(
826
- // @ts-expect-error
827
- containingFile, undefined, // eslint-disable-line no-undefined
828
- { ...ts.sys, ...formatHost }, parsedOptions.options)
829
- : undefined; // eslint-disable-line no-undefined
830
- // eslint-disable-next-line no-undefined
831
- const resolved = resolveModule(importee, containingFile, undefined, mode);
832
- if (resolved) {
833
- if (/\.d\.[cm]?ts/.test(resolved.extension))
834
- return null;
835
- if (!filter(resolved.resolvedFileName))
836
- return null;
837
- return path.normalize(resolved.resolvedFileName);
838
- }
839
- return null;
840
- },
841
- async load(id) {
842
- if (!filter(id))
843
- return null;
844
- this.addWatchFile(id);
845
- await watchProgramHelper.wait();
846
- const fileName = normalizePath(id);
847
- if (!parsedOptions.fileNames.includes(fileName)) {
848
- // Discovered new file that was not known when originally parsing the TypeScript config
849
- parsedOptions.fileNames.push(fileName);
850
- }
851
- const output = findTypescriptOutput(ts, parsedOptions, id, emittedFiles, tsCache);
852
- return output.code != null ? output : null;
853
- },
854
- async generateBundle(outputOptions) {
855
- const declarationAndTypeScriptMapFiles = [...emittedFiles.keys()].filter((fileName) => isDeclarationOutputFile(fileName) || isTypeScriptMapOutputFile(fileName));
856
- declarationAndTypeScriptMapFiles.forEach((id) => {
857
- const code = getEmittedFile(id, emittedFiles, tsCache);
858
- if (!code || !parsedOptions.options.declaration) {
859
- return;
860
- }
861
- let baseDir;
862
- if (outputOptions.dir) {
863
- baseDir = outputOptions.dir;
864
- }
865
- else if (outputOptions.file) {
866
- // find common path of output.file and configured declation output
867
- const outputDir = path.dirname(outputOptions.file);
868
- const configured = path.resolve(parsedOptions.options.declarationDir ||
869
- parsedOptions.options.outDir ||
870
- tsconfig ||
871
- process.cwd());
872
- const backwards = path
873
- .relative(outputDir, configured)
874
- .split(path.sep)
875
- .filter((v) => v === '..')
876
- .join(path.sep);
877
- baseDir = path.normalize(`${outputDir}/${backwards}`);
878
- }
879
- if (!baseDir)
880
- return;
881
- this.emitFile({
882
- type: 'asset',
883
- fileName: normalizePath(path.relative(baseDir, id)),
884
- source: code
885
- });
886
- });
887
- const tsBuildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(parsedOptions.options);
888
- if (tsBuildInfoPath) {
889
- const tsBuildInfoSource = emittedFiles.get(tsBuildInfoPath);
890
- // https://github.com/rollup/plugins/issues/681
891
- if (tsBuildInfoSource) {
892
- await emitFile(outputOptions, outputToFilesystem, this, tsBuildInfoPath, tsBuildInfoSource);
893
- }
894
- }
895
- }
896
- };
897
- }
898
-
899
- export { typescript as default };
900
- //# sourceMappingURL=index.js.map