Skip to content
This repository has been archived by the owner on Aug 16, 2022. It is now read-only.

Commit

Permalink
feat(utils): addSourceMap
Browse files Browse the repository at this point in the history
  • Loading branch information
unicornware committed Oct 10, 2021
1 parent 9384aec commit 3983348
Show file tree
Hide file tree
Showing 14 changed files with 418 additions and 1 deletion.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
**/types/*

**/CHANGELOG.md
__tests__/__fixtures__/trext.plugin.js

!/src/types/*
1 change: 1 addition & 0 deletions .eslintrc.base.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ module.exports = {
'ttsc',
'typeof',
'usr',
'utf',
'wasm',
'wip',
'yargs'
Expand Down
6 changes: 5 additions & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module.exports = {
...RULES_SPELLCHECKER[1].skipWords,
'callee',
'errno',
'filenames',
'trext',
'trextel'
]
Expand All @@ -28,7 +29,10 @@ module.exports = {
overrides: [
...overrides,
{
files: ['src/plugins/trextel.plugin.ts'],
files: [
'__tests__/__fixtures__/trext-file-result.fixture.ts',
'src/plugins/trextel.plugin.ts'
],
rules: {
'no-useless-escape': 0
}
Expand Down
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@
**/.prettierignore
**/*.markdownlintignore
**/yarn.lock
__tests__/__fixtures__/trext.plugin.js

!/src/types/*
25 changes: 25 additions & 0 deletions __tests__/__fixtures__/filenames.fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @file Test Fixture - filenames
* @module tests/fixtures/filenames
*/

export default [
'__tests__/__fixtures__/trext.plugin.js',
'config/defaults.config.js',
'interfaces/index.js',
'interfaces/trext-options.interface.js',
'plugins/trexel.plugin.js',
'plugins/index.js',
'types/file-extension.type.js',
'types/index.js',
'types/regex-string.type.js',
'types/source-map-comment.type.js',
'types/trext-defaults.type.js',
'types/trext-to-fn.type.js',
'types/trext-to.type.js',
'utils/ignore-404.util.js',
'utils/index.js',
'utils/save-file.util.js',
'utils/souce-mapping-url.util.js',
'index.js'
]
91 changes: 91 additions & 0 deletions __tests__/__fixtures__/trext-file-result.fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import DEFAULTS from '@trext/config/defaults.config'
import type { TrextFileResult } from '@trext/types'
import fs from 'fs'
import FILENAMES from './filenames.fixture'

/**
* @file Test Fixture - TrextFileResult
* @module tests/fixtures/TrextFileResult
*/

export const SOURCE_FILENAME: string = FILENAMES[0]
export const CWD: string = process.cwd()
export const FILENAME: string = `${CWD}/${SOURCE_FILENAME}`

const SOURCE_CODE = fs.readFileSync(FILENAME, 'utf8').toString()

export default {
ast: null,
code: SOURCE_CODE,
map: {
file: SOURCE_FILENAME,
mappings:
// eslint-disable-next-line spellcheck/spell-checker
'AAAA,SAEE,kBAFF,QAIO,aAJP;OAKO,c;OAEA,O;AAOP,OAAO,EAAP,MAAe,IAAf;AACA,OAAO,IAAP,MAAiB,MAAjB;AACA,OAAO,MAAP,MAAmB,QAAnB;AACA,OAAO,IAAP,MAAiB,MAAjB;AACA,SAAS,SAAT,QAA0B,MAA1B;AAEA;;;AAGG;;AAEH;;AAEG;;AACH,MAAM,KAAN,CAAW;AACT;;;;;;;;;;AAUG;AAC6B,eAAnB,mBAAmB,CAC9B,OAD8B,EACX;AAEnB,QAAI;AACF,aAAO,MAAM,OAAb;AACD,KAFD,CAEE,OAAO,KAAP,EAAc;AACd,UAAK,KAA+B,CAAC,IAAhC,KAAyC,QAA9C,EAAwD,MAAM,KAAN;AACzD;;AAED,WAAO,IAAP;AACD;AAED;;;;;;;AAOG;;;AACkB,eAAR,QAAQ,CACnB,QADmB,EAEnB,IAFmB,EAEE;AAErB,UAAM,MAAM,CAAC,IAAI,CAAC,OAAL,CAAa,QAAb,CAAD,CAAZ;AACA,WAAO,MAAM,EAAE,CAAC,QAAH,CAAY,SAAZ,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ceRoot: '',
sources: ['../src/trext.ts'],
sourcesContent: [
`${SOURCE_CODE}\n"./config/defaults.config""./interfaces""./plugins/trextel.plugin""./types"`
],
version: 3
},
metadata: {},
options: {
assumptions: {},
babelrc: false,
browserslistConfigFile: false,
caller: { name: '@babel/cli' },
cloneInputAst: true,
configFile: false,
cwd: CWD,
envName: 'development',
filename: FILENAME,
generatorOpts: {
auxiliaryCommentAfter: undefined,
auxiliaryCommentBefore: undefined,
comments: true,
compact: 'auto',
filename: FILENAME,
minified: undefined,
retainLines: undefined,
shouldPrintComment: undefined,
sourceFileName: SOURCE_FILENAME,
sourceMaps: true,
sourceRoot: undefined
},
parserOpts: {
plugins: [],
sourceFileName: FILENAME,
sourceType: 'module'
},
passPerPreset: false,
plugins: [
{
generatorOverride: undefined,
key: 'Trextel',
manipulateOptions: undefined,
options: {
...DEFAULTS,
from: 'js',
to: 'cjs'
},
parserOverride: undefined,
post: undefined,
pre: undefined,
visitor: {
_exploded: true,
_verified: true,
CallExpression: { enter: [[jest.fn()]] },
ImportDeclaration: { enter: [[jest.fn()]] }
}
}
],
presets: [],
root: CWD,
rootMode: 'root',
sourceMaps: true,
targets: {}
},
sourceType: 'module'
} as TrextFileResult
104 changes: 104 additions & 0 deletions __tests__/__fixtures__/trext.plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { transformFileAsync } from '@babel/core';
import fs from 'fs/promises';
import DEFAULTS from "../config/defaults.config.mjs";
import addSourceMap from "../utils/add-source-map.util.mjs";
import glob from "../utils/glob.util.mjs";
import saveFile from "../utils/save-file.util.mjs";
import Trextel from "./trextel.plugin.mjs";
/**
* @file Plugins - Trext
* @module trext/plugins/Trext
*/

/**
* File extension and import statement transformer.
*/

class Trext {
/**
* Executes `trextFile` over a directory.
*
* @see {@link Trext.trextFile}
*
* @template F - Old file extension name(s)
* @template T - New file extension name(s)
*
* @async
* @param {string} cwd - Directory to perform transformation
* @param {TrextOptions<F, T>} options - Trext options
* @param {TransformOptions} [options.babel={}] - Babel transform options
* @param {F} options.from - File extension to transform
* @param {RegexString} [options.pattern=/\..+$/] - File extension pattern
* @param {To<T>} options.to - New file extension or generator function
* @return {Promise<TrextFileResult[]>} Transformation results
*/
static async trext(cwd, options) {
// Get files to transform
const filenames = await glob(`${cwd}/**/*.${options.from}`); // Transform files

const results = filenames.map(async f => Trext.trextFile(f, options)); // Return transformation results

return await Promise.all(results);
}
/**
* Transforms a file's extension, import statements, call expressions, and
* source map comment.
*
* @template F - Old file extension name(s)
* @template T - New file extension name(s)
*
* @async
* @param {string} filename - Name of file to transform
* @param {TrextOptions<F, T>} options - Trext options
* @param {TransformOptions} [options.babel={}] - Babel transform options
* @param {F} options.from - File extension to transform
* @param {RegexString} [options.pattern=/\..+$/] - File extension pattern
* @param {To<T>} options.to - New file extension or generator function
* @return {Promise<TrextFileResult>} Transformation result
* @throws {Error}
*/


static async trextFile(filename, options) {
// Merge user options with defaults
const opts = { ...DEFAULTS,
...options
};
const {
babel,
pattern,
to
} = opts; // Transform file

let result = await transformFileAsync(filename, { ...Object.assign({}, { ...DEFAULTS.babel,
...babel
}),
caller: {
name: '@babel/cli'
},
plugins: [[new Trextel().plugin, opts], ...(babel?.plugins ?? [])]
}); // Throw error if result is missing

if (!result) throw new Error(`Could not compile file ${filename}`); // Get output filename
// @ts-expect-error No overload matches this call

const output = filename.replace(pattern, to.call ? to : `.${to}`); // Stringify source code

result.code = String(result.code); // Handle source map

result = await addSourceMap(opts, result, {
input: filename,
output
}); // Save file, update file permissions, and remove references to old file

await saveFile(output, result.code);
await fs.chmod(output, (await fs.stat(filename)).mode);
await fs.unlink(filename);
return result;
}

}

export const trext = Trext.trext;
export const trextFile = Trext.trextFile;
export default Trext;
9 changes: 9 additions & 0 deletions src/utils/__mocks__/add-source-map.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* @file User Module Mock - addSourceMap
* @module utils/mocks/addSourceMap
* @see https://jestjs.io/docs/next/manual-mocks#mocking-user-modules
*/

export default jest.fn((...args) => {
return jest.requireActual('../add-source-map.util').default(...args)
})
9 changes: 9 additions & 0 deletions src/utils/__mocks__/ignore404.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* @file User Module Mock - ignore404
* @module utils/mocks/ignore404
* @see https://jestjs.io/docs/next/manual-mocks#mocking-user-modules
*/

export default jest.fn((...args) => {
return jest.requireActual('../ignore-404.util').default(...args)
})
7 changes: 7 additions & 0 deletions src/utils/__mocks__/save-file.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* @file User Module Mock - saveFile
* @module utils/mocks/saveFile
* @see https://jestjs.io/docs/next/manual-mocks#mocking-user-modules
*/

export default jest.fn()
9 changes: 9 additions & 0 deletions src/utils/__mocks__/source-mapping-url.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* @file User Module Mock - sourceMappingURL
* @module utils/mocks/sourceMappingURL
* @see https://jestjs.io/docs/next/manual-mocks#mocking-user-modules
*/

export default jest.fn((...args) => {
return jest.requireActual('../source-mapping-url.util').default(...args)
})
Loading

0 comments on commit 3983348

Please sign in to comment.