From ee4bc20524004dc084c2935b2f477986cf698c17 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 06:17:12 +0300 Subject: [PATCH 01/13] refactor usage file --- src/bin/index.js | 19 ++----------------- src/bin/usage.js | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 17 deletions(-) create mode 100644 src/bin/usage.js diff --git a/src/bin/index.js b/src/bin/index.js index e9bcacf..ea57b2b 100755 --- a/src/bin/index.js +++ b/src/bin/index.js @@ -1,9 +1,9 @@ #!/usr/bin/env node import argufy from 'argufy' -import usually from 'usually' import { version } from '../../package.json' import catcher from './catcher' import { transpile } from './transpile' +import getUsage from './usage' const { input: _input, @@ -22,22 +22,7 @@ const { }) if (_help) { - const usage = usually({ - usage: { - source: `Location of the input to the transpiler, -either a directory or a file.`, - '--output, -o': `Location to save results to. Passing "-" -will print to stdout when source is a file.`, - '--help, -h': 'Display help information.', - '--version, -v': 'Show version.', - '--ignore, -i': `Paths to files to ignore, relative to -source.`, - '--noSourceMaps, -s': 'Don\'t generate source maps.', - }, - description: 'A tool to transpile JavaScript packages using regular expressions.', - line: 'alamode source [-o destination]', - example: 'alamode src -o build', - }) + const usage = getUsage() console.log(usage) process.exit() } else if (_version) { diff --git a/src/bin/usage.js b/src/bin/usage.js new file mode 100644 index 0000000..a0acfd4 --- /dev/null +++ b/src/bin/usage.js @@ -0,0 +1,21 @@ +import usually from 'usually' + +export default () => { + const usage = usually({ + usage: { + source: `Location of the input to the transpiler, +either a directory or a file.`, + '--output, -o': `Location to save results to. Passing "-" +will print to stdout when source is a file.`, + '--help, -h': 'Display help information.', + '--version, -v': 'Show version.', + '--ignore, -i': `Paths to files to ignore, relative to +source.`, + '--noSourceMaps, -s': 'Don\'t generate source maps.', + }, + description: 'A tool to transpile JavaScript packages using regular expressions.', + line: 'alamode source [-o destination]', + example: 'alamode src -o build', + }) + return usage +} \ No newline at end of file From 6a5f06b1357e446a910bce6133261c169055e08f Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 06:17:55 +0300 Subject: [PATCH 02/13] advanced transform --- src/lib/transform.js | 20 +++++++++++++------- test/context/index.js | 10 ++++++++++ test/fixture/advanced.js | 16 ++++++++++++++++ test/snapshot/transform-stream/advanced.js | 19 +++++++++++++++++++ test/spec/transform/default.js | 13 +++++++++++++ 5 files changed, 71 insertions(+), 7 deletions(-) create mode 100644 test/fixture/advanced.js create mode 100644 test/snapshot/transform-stream/advanced.js diff --git a/src/lib/transform.js b/src/lib/transform.js index 1c4b6f7..13de9d1 100644 --- a/src/lib/transform.js +++ b/src/lib/transform.js @@ -1,7 +1,7 @@ import { Replaceable } from 'restream' -import makeRules from '@a-la/markers' -import ALaImport from '@a-la/import' -import ALaExport from '@a-la/export' +import makeRules, { makeAdvancedRules } from '@a-la/markers' +import ALaImport, { advancedSeq as advancedALaImport } from '@a-la/import' +import ALaExport, { advancedSeq as advancedALaExport } from '@a-la/export' import whichStream from 'which-stream' import Catchment from 'catchment' import { createReadStream } from 'fs' @@ -23,12 +23,17 @@ const getConfig = () => { } -const makeReplaceable = () => { +const makeReplaceable = (advanced) => { const config = getConfig() - const { rules, markers } = makeRules([ + const r = advanced ? [ + ...advancedALaImport, + ...advancedALaExport, + ] : [ ...ALaImport, ...ALaExport, - ]) + ] + const mr = advanced ? makeAdvancedRules : makeRules + const { rules, markers } = mr(r) const replaceable = new Replaceable(rules) replaceable.markers = markers @@ -43,8 +48,9 @@ export const transformStream = async ({ source, destination, writable, + advanced = false, }) => { - const replaceable = makeReplaceable() + const replaceable = makeReplaceable(advanced) const readable = createReadStream(source) diff --git a/test/context/index.js b/test/context/index.js index c8bbc9c..4e2579f 100644 --- a/test/context/index.js +++ b/test/context/index.js @@ -58,6 +58,16 @@ export default class Context { get JS_FIXTURE() { return resolve(FIXTURE, 'fixture.js') } + /** + * Path to a fixture file which contains template literals with import and export statements. + * @example + * const e = ` + export { test } from 'test' +` + */ + get ADVANCED_FIXTURE() { + return resolve(FIXTURE, 'advanced.js') + } get SOURCE() { return resolve(FIXTURE, 'src') } diff --git a/test/fixture/advanced.js b/test/fixture/advanced.js new file mode 100644 index 0000000..4f8d3ee --- /dev/null +++ b/test/fixture/advanced.js @@ -0,0 +1,16 @@ +// this is an advanced fixture file, where strings are replaced +import helloWorld from 'hello-world' + +export const test = () => { + const res = helloWorld() + console.log(res) +} + +export { test2 } from 'test' + +const i = ` + import helloWorld from 'hello-world' +` +const e = ` + export { test } from 'test' +` \ No newline at end of file diff --git a/test/snapshot/transform-stream/advanced.js b/test/snapshot/transform-stream/advanced.js new file mode 100644 index 0000000..f715a57 --- /dev/null +++ b/test/snapshot/transform-stream/advanced.js @@ -0,0 +1,19 @@ +// this is an advanced fixture file, where strings are replaced +let helloWorld = require('hello-world'); if (helloWorld && helloWorld.__esModule) helloWorld = helloWorld.default; + + const test = () => { + const res = helloWorld() + console.log(res) +} + +const $test = require('test'); + +const i = ` + import helloWorld from 'hello-world' +` +const e = ` + export { test } from 'test' +` + +module.exports.test = test +module.exports.test2 = $test.test2 \ No newline at end of file diff --git a/test/spec/transform/default.js b/test/spec/transform/default.js index 12ee581..d5a20bb 100644 --- a/test/spec/transform/default.js +++ b/test/spec/transform/default.js @@ -18,6 +18,19 @@ const T = { const res = await writable.promise await test('transform-stream/fixture.js', res) }, + async 'transforms source code (advanced)'( + { ADVANCED_FIXTURE: source, SNAPSHOT_DIR }, { setDir, test }, + ) { + setDir(SNAPSHOT_DIR) + const writable = new Catchment() + await transformStream({ + source, + writable, + advanced: true, + }) + const res = await writable.promise + await test('transform-stream/advanced.js', res) + }, } export default T \ No newline at end of file From cc9de892cecc01795b449aa2b44de14432ef8e94 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 06:26:56 +0300 Subject: [PATCH 03/13] add sync transform tests --- src/lib/transform.js | 28 +++++++++++++++++----------- test/context/index.js | 14 +++++++++++++- test/spec/transform/default.js | 18 +++++++++++++++++- 3 files changed, 47 insertions(+), 13 deletions(-) diff --git a/src/lib/transform.js b/src/lib/transform.js index 13de9d1..876e18c 100644 --- a/src/lib/transform.js +++ b/src/lib/transform.js @@ -22,9 +22,7 @@ const getConfig = () => { return c } - -const makeReplaceable = (advanced) => { - const config = getConfig() +const getRules = (advanced) => { const r = advanced ? [ ...advancedALaImport, ...advancedALaExport, @@ -34,6 +32,13 @@ const makeReplaceable = (advanced) => { ] const mr = advanced ? makeAdvancedRules : makeRules const { rules, markers } = mr(r) + return { rules, markers } +} + +const makeReplaceable = (advanced) => { + const config = getConfig() + const { rules, markers } = getRules(advanced) + const replaceable = new Replaceable(rules) replaceable.markers = markers @@ -87,21 +92,22 @@ class Context { } } -/** - * @param {string} source Source code as a string. - */ -export const syncTransform = (source, filename) => { - const { rules, markers } = makeRules([ - ...ALaImport, - ...ALaExport, - ]) +export const transformString = (source, advanced) => { + const { rules, markers } = getRules(advanced) const context = new Context(markers) const replaced = rules.reduce((acc, { re, replacement }) => { const newAcc = acc.replace(re, replacement.bind(context)) return newAcc }, source) + return replaced +} +/** + * @param {string} source Source code as a string. + */ +export const syncTransform = (source, filename, advanced) => { + const replaced = transformString(advanced) const file = basename(filename) const sourceRoot = dirname(filename) const map = getMap({ diff --git a/test/context/index.js b/test/context/index.js index 4e2579f..2bd6a43 100644 --- a/test/context/index.js +++ b/test/context/index.js @@ -1,8 +1,16 @@ import { resolve } from 'path' import { debuglog } from 'util' -import { unlink, rmdir } from 'fs' +import { unlink, rmdir, createReadStream } from 'fs' import ensurePath from '@wrote/ensure-path' import readDirStructure from '@wrote/read-dir-structure' +import Catchment from 'catchment' + +const read = async (src) => { + const rs = createReadStream(src) + const { promise } = new Catchment({ rs }) + const res = await promise + return res +} const removeDir = async (path) => { const { content } = await readDirStructure(path) @@ -58,6 +66,10 @@ export default class Context { get JS_FIXTURE() { return resolve(FIXTURE, 'fixture.js') } + async readFile(path) { + const res = await read(path) + return res + } /** * Path to a fixture file which contains template literals with import and export statements. * @example diff --git a/test/spec/transform/default.js b/test/spec/transform/default.js index d5a20bb..c2010a4 100644 --- a/test/spec/transform/default.js +++ b/test/spec/transform/default.js @@ -1,7 +1,7 @@ import Catchment from 'catchment' import SnapshotContext from 'snapshot-context' import Context from '../../context' -import { transformStream } from '../../../src/lib/transform' +import { transformStream, transformString } from '../../../src/lib/transform' /** @type {Object.} */ const T = { @@ -18,6 +18,14 @@ const T = { const res = await writable.promise await test('transform-stream/fixture.js', res) }, + async 'transforms source code (sync)'( + { JS_FIXTURE: source, SNAPSHOT_DIR, readFile }, { setDir, test }, + ) { + setDir(SNAPSHOT_DIR) + const src = await readFile(source) + const res = transformString(src) + await test('transform-stream/fixture.js', res) + }, async 'transforms source code (advanced)'( { ADVANCED_FIXTURE: source, SNAPSHOT_DIR }, { setDir, test }, ) { @@ -31,6 +39,14 @@ const T = { const res = await writable.promise await test('transform-stream/advanced.js', res) }, + async 'transforms source code (sync, advanced)'( + { ADVANCED_FIXTURE: source, SNAPSHOT_DIR, readFile }, { setDir, test }, + ) { + setDir(SNAPSHOT_DIR) + const src = await readFile(source) + const res = transformString(src, true) + await test('transform-stream/advanced.js', res) + }, } export default T \ No newline at end of file From fdb7ec35a0558fb478e8900807c24b3d3f5f7c76 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 06:48:25 +0300 Subject: [PATCH 04/13] pass advanced --- src/bin/index.js | 3 +++ src/bin/transpile.js | 8 ++++++- src/bin/usage.js | 6 +++-- src/index.js | 6 +++-- src/lib/transform.js | 18 ++++++++++----- test/context/index.js | 32 +++++++++++++++++++++++++++ test/spec/intergration.js | 46 +++++++-------------------------------- 7 files changed, 70 insertions(+), 49 deletions(-) diff --git a/src/bin/index.js b/src/bin/index.js index ea57b2b..0784dc8 100755 --- a/src/bin/index.js +++ b/src/bin/index.js @@ -12,6 +12,7 @@ const { help: _help, ignore: _ignore, noSourceMaps: _noSourceMaps, + advanced: _advanced, } = argufy({ input: { command: true }, output: { short: 'o' }, @@ -19,6 +20,7 @@ const { help: { short: 'h', boolean: true }, ignore: { short: 'i' }, noSourceMaps: { short: 's', boolean: true }, + advanced: { short: 'a', boolean: true }, }) if (_help) { @@ -38,6 +40,7 @@ if (_help) { output: _output, noSourceMaps: _noSourceMaps, ignore, + advanced: _advanced, }) } catch (err) { catcher(err) diff --git a/src/bin/transpile.js b/src/bin/transpile.js index 2181267..008e452 100644 --- a/src/bin/transpile.js +++ b/src/bin/transpile.js @@ -10,7 +10,7 @@ import { transformStream } from '../lib/transform' const LOG = debuglog('alamode') const processFile = async ({ - input, relPath, name, output, ignore, noSourceMaps, + input, relPath, name, output, ignore, noSourceMaps, advanced, }) => { const file = join(relPath, name) if (ignore.includes(file)) return @@ -27,6 +27,7 @@ const processFile = async ({ const originalSource = await transformStream({ source, destination, + advanced, }) if (output != '-') { @@ -49,6 +50,7 @@ const processDir = async ({ relPath = '.', ignore = [], noSourceMaps, + advanced, }) => { const path = join(input, relPath) const { content } = await readDirStructure(path) @@ -68,6 +70,7 @@ const processDir = async ({ ignore, relPath: newRelPath, noSourceMaps, + advanced, }) } }, Promise.resolve()) @@ -78,6 +81,7 @@ export const transpile = async ({ output = '-', ignore = [], noSourceMaps, + advanced, }) => { if (!input) throw new Error('Please specify the source file or directory.') @@ -89,6 +93,7 @@ export const transpile = async ({ output, ignore, noSourceMaps, + advanced, }) } else if (ls.isFile()) { await processFile({ @@ -98,6 +103,7 @@ export const transpile = async ({ output, ignore, noSourceMaps, + advanced, }) } if (output != '-') process.stdout.write(`Transpiled code saved to ${output}\n`) diff --git a/src/bin/usage.js b/src/bin/usage.js index a0acfd4..c34d93c 100644 --- a/src/bin/usage.js +++ b/src/bin/usage.js @@ -9,9 +9,11 @@ either a directory or a file.`, will print to stdout when source is a file.`, '--help, -h': 'Display help information.', '--version, -v': 'Show version.', - '--ignore, -i': `Paths to files to ignore, relative to -source.`, + '--ignore, -i': `Paths to files to ignore, relative to the +source directory.`, '--noSourceMaps, -s': 'Don\'t generate source maps.', + '--advanced, -a': `Attempt to skip statements inside of template +literals.`, }, description: 'A tool to transpile JavaScript packages using regular expressions.', line: 'alamode source [-o destination]', diff --git a/src/index.js b/src/index.js index 557b41e..d0b0391 100644 --- a/src/index.js +++ b/src/index.js @@ -2,10 +2,12 @@ import { addHook } from 'pirates' import { syncTransform } from './lib/transform' /** Enable transpilation of files on-the file as a require hook. */ -const alamode = () => { +const alamode = ({ + advanced = false, +} = {}) => { addHook( (code, filename) => { - const res = syncTransform(code, filename) + const res = syncTransform(code, filename, advanced) return res }, { exts: ['.js'] } diff --git a/src/lib/transform.js b/src/lib/transform.js index 876e18c..32f6944 100644 --- a/src/lib/transform.js +++ b/src/lib/transform.js @@ -13,7 +13,9 @@ const getConfig = () => { try { const r = join(process.cwd(), '.alamoderc.json') config = require(r) - } catch (err) { /* no config */ } + } catch (err) { + return config + } const { env: { ALAMODE_ENV } } = process const c = config.env && ALAMODE_ENV in config.env ? config.env[ALAMODE_ENV] : config @@ -37,7 +39,7 @@ const getRules = (advanced) => { const makeReplaceable = (advanced) => { const config = getConfig() - const { rules, markers } = getRules(advanced) + const { rules, markers } = getRules(config.advanced || advanced) const replaceable = new Replaceable(rules) replaceable.markers = markers @@ -79,10 +81,10 @@ export const transformStream = async ({ } class Context { - constructor(markers) { + constructor(config, markers) { this.listeners = {} this.markers = markers - this.config = getConfig() + this.config = config } on(event, listener) { this.listeners[event] = listener @@ -90,11 +92,15 @@ class Context { emit(event, data) { this.listeners[event](data) } + get advanced() { + return this.config.advanced + } } export const transformString = (source, advanced) => { - const { rules, markers } = getRules(advanced) - const context = new Context(markers) + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + const context = new Context(config, markers) const replaced = rules.reduce((acc, { re, replacement }) => { const newAcc = acc.replace(re, replacement.bind(context)) diff --git a/test/context/index.js b/test/context/index.js index 2bd6a43..a83dcb4 100644 --- a/test/context/index.js +++ b/test/context/index.js @@ -4,6 +4,7 @@ import { unlink, rmdir, createReadStream } from 'fs' import ensurePath from '@wrote/ensure-path' import readDirStructure from '@wrote/read-dir-structure' import Catchment from 'catchment' +import { fork } from 'spawncommand' const read = async (src) => { const rs = createReadStream(src) @@ -96,4 +97,35 @@ export default class Context { LOG('destroy context') await removeDir(TEMP) } + /** + * Path to alamode binary. + */ + get BIN() { + return BIN + } + async fork(args) { + const { promise, stdout, stderr } = fork(this.BIN, args, { + stdio: 'pipe', + env: { + NODE_DEBUG: 'alamode', + }, + execArgv: [], + }) + const { promise: stdoutPromise } = new Catchment({ + rs: stdout, + }) + const { promise: stderrPromise } = new Catchment({ + rs: stderr, + }) + await promise + const [, so, se] = await Promise.all([ + promise, + stdoutPromise, + stderrPromise, + ]) + return { stdout: so, stderr: se } + } } + +const ALAMODE = process.env.ALAMODE_ENV == 'test-build' ? '../../build/bin' : '../../src/bin/alamode' +const BIN = resolve(__dirname, ALAMODE) \ No newline at end of file diff --git a/test/spec/intergration.js b/test/spec/intergration.js index f698480..3204191 100644 --- a/test/spec/intergration.js +++ b/test/spec/intergration.js @@ -1,7 +1,5 @@ import { equal, ok } from 'zoroaster/assert' import { resolve } from 'path' -import Catchment from 'catchment' -import { fork } from 'spawncommand' import SnapshotContext from 'snapshot-context' import { readDir } from 'wrote' import { accessSync, constants } from 'fs' @@ -9,54 +7,26 @@ import Context from '../context' const { X_OK } = constants -const ALAMODE = process.env.BABEL_ENV == 'test-build' ? '../../build/bin' : '../../src/bin/alamode' -const BIN = resolve(__dirname, ALAMODE) - /** @type {Object.} */ const T = { context: [Context, SnapshotContext], - async 'transpiles source code'({ SOURCE, OUTPUT, SNAPSHOT_DIR }, { setDir, test }) { + async 'transpiles source code'({ SOURCE, OUTPUT, SNAPSHOT_DIR, fork }, { setDir, test }) { const args = [SOURCE, '-o', OUTPUT] - const { promise, stdout, stderr } = fork(BIN, args, { - stdio: 'pipe', - env: { - NODE_DEBUG: 'alamode', - }, - execArgv: [], - }) - const { promise: stdoutPromise } = new Catchment({ - rs: stdout, - }) - const { promise: stderrPromise } = new Catchment({ - rs: stderr, - }) - await promise - const [, so, se] = await Promise.all([ - promise, - stdoutPromise, - stderrPromise, - ]) - equal(so, `Transpiled code saved to ${OUTPUT}\n`) - ok(/ index.js/.test(se)) - ok(/ lib\/index.js/.test(se)) - ok(/ lib\/method.js/.test(se)) + const { stdout, stderr } = await fork(args) + equal(stdout, `Transpiled code saved to ${OUTPUT}\n`) + ok(/ index.js/.test(stderr)) + ok(/ lib\/index.js/.test(stderr)) + ok(/ lib\/method.js/.test(stderr)) const res = await readDir(OUTPUT, true) setDir(SNAPSHOT_DIR) await test('integration.json', res) }, - async 'sets the correct permissions'({ SOURCE, TEMP }) { + async 'sets the correct permissions'({ SOURCE, TEMP, fork }) { const file = 'index.js' const src = resolve(SOURCE, file) const output = resolve(TEMP, file) const args = [src, '-o', output] - const { promise } = fork(BIN, args, { - stdio: 'pipe', - env: { - NODE_DEBUG: 'alamode', - }, - execArgv: [], - }) - await promise + await fork(args) accessSync(output, X_OK) }, } From 1a6515becbf585a336c1407958c42e2d1e611ac4 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 06:58:04 +0300 Subject: [PATCH 05/13] add integration advanced in rc test --- .vscode/launch.json | 2 +- package.json | 1 + test/context/index.js | 8 +++++++ test/spec/{intergration.js => integration.js} | 21 +++++++++++++++++++ yarn.lock | 4 ++++ 5 files changed, 35 insertions(+), 1 deletion(-) rename test/spec/{intergration.js => integration.js} (58%) diff --git a/.vscode/launch.json b/.vscode/launch.json index 698f151..952fdf3 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -49,7 +49,7 @@ }, "console": "integratedTerminal", "args": [ - "test/spec/transform", + "test/spec/integration.js", "-a", "-w", ], diff --git a/package.json b/package.json index 3ec79b4..14eef21 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ }, "homepage": "https://github.com/a-la/alamode#readme", "devDependencies": { + "bosom": "1.0.0", "catchment": "3.0.1", "documentary": "1.10.0", "eslint-config-artdeco": "1.0.1", diff --git a/test/context/index.js b/test/context/index.js index a83dcb4..3f86334 100644 --- a/test/context/index.js +++ b/test/context/index.js @@ -5,6 +5,7 @@ import ensurePath from '@wrote/ensure-path' import readDirStructure from '@wrote/read-dir-structure' import Catchment from 'catchment' import { fork } from 'spawncommand' +import bosom from 'bosom' const read = async (src) => { const rs = createReadStream(src) @@ -58,6 +59,12 @@ export default class Context { async _init() { await ensurePath(resolve(TEMP, 'temp')) } + async writeRc(config) { + await bosom(this.TEMP_RC_PATH, config, { space: 2 }) + } + get TEMP_RC_PATH() { + return resolve(TEMP, '.alamoderc.json') + } /** * Path to the fixture file. */ @@ -110,6 +117,7 @@ export default class Context { NODE_DEBUG: 'alamode', }, execArgv: [], + cwd: this.TEMP, }) const { promise: stdoutPromise } = new Catchment({ rs: stdout, diff --git a/test/spec/intergration.js b/test/spec/integration.js similarity index 58% rename from test/spec/intergration.js rename to test/spec/integration.js index 3204191..0100dc0 100644 --- a/test/spec/intergration.js +++ b/test/spec/integration.js @@ -29,6 +29,27 @@ const T = { await fork(args) accessSync(output, X_OK) }, + async 'transpiles advanced'({ ADVANCED_FIXTURE, SNAPSHOT_DIR, fork }, { setDir, test }) { + const args = [ADVANCED_FIXTURE, '-a'] + const { stdout } = await fork(args) + setDir(SNAPSHOT_DIR) + await test('transform-stream/advanced.js', stdout) + }, + async '!transpiles via rc file'({ ADVANCED_FIXTURE, SNAPSHOT_DIR, fork, writeRc }, { setDir, test }) { + const args = [ADVANCED_FIXTURE] + await writeRc({ + advanced: true, + }) + const { stdout } = await fork(args) + setDir(SNAPSHOT_DIR) + await test('transform-stream/advanced.js', stdout) + }, + async 'transpiles normal'({ JS_FIXTURE, SNAPSHOT_DIR, fork }, { setDir, test }) { + const args = [JS_FIXTURE] + const { stdout } = await fork(args) + setDir(SNAPSHOT_DIR) + await test('transform-stream/fixture.js', stdout) + }, } export default T diff --git a/yarn.lock b/yarn.lock index 1b31aba..025e498 100644 --- a/yarn.lock +++ b/yarn.lock @@ -83,6 +83,10 @@ assert-throws@2.1.0: erotic "1.1.0" erte "1.1.1" +bosom@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/bosom/-/bosom-1.0.0.tgz#b3f1f4771f5232c27ccc739a75606eab4fb2aa5f" + catchment@2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/catchment/-/catchment-2.0.1.tgz#df0a05ac2e1194cf280c2444d5bb564a9cc8f488" From 8dec5fc443b9b72b793e940fea7be12399f61ca9 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 07:14:17 +0300 Subject: [PATCH 06/13] add require integration tests --- test/context/index.js | 62 ++++++++++++++++++++------------ test/fixture/require-advanced.js | 2 ++ test/fixture/require.js | 2 ++ test/fixture/src/run-advanced.js | 22 ++++++++++++ test/snapshot/integration.json | 2 ++ test/spec/integration.js | 21 ++++++++++- 6 files changed, 87 insertions(+), 24 deletions(-) create mode 100644 test/fixture/require-advanced.js create mode 100644 test/fixture/require.js create mode 100644 test/fixture/src/run-advanced.js diff --git a/test/context/index.js b/test/context/index.js index 3f86334..3cc1cb7 100644 --- a/test/context/index.js +++ b/test/context/index.js @@ -110,30 +110,46 @@ export default class Context { get BIN() { return BIN } + async forkRequire() { + const path = resolve(FIXTURE, 'require') + return runFork(path, [], this.TEMP) + } + async forkRequireAdvanced() { + const path = resolve(FIXTURE, 'require-advanced') + return runFork(path, [], this.TEMP) + } async fork(args) { - const { promise, stdout, stderr } = fork(this.BIN, args, { - stdio: 'pipe', - env: { - NODE_DEBUG: 'alamode', - }, - execArgv: [], - cwd: this.TEMP, - }) - const { promise: stdoutPromise } = new Catchment({ - rs: stdout, - }) - const { promise: stderrPromise } = new Catchment({ - rs: stderr, - }) - await promise - const [, so, se] = await Promise.all([ - promise, - stdoutPromise, - stderrPromise, - ]) - return { stdout: so, stderr: se } + return runFork(this.BIN, args, this.TEMP) + } + get TEST_BUILD() { + return TEST_BUILD } } -const ALAMODE = process.env.ALAMODE_ENV == 'test-build' ? '../../build/bin' : '../../src/bin/alamode' -const BIN = resolve(__dirname, ALAMODE) \ No newline at end of file +const TEST_BUILD = process.env.ALAMODE_ENV == 'test-build' +const ALAMODE = TEST_BUILD ? '../../build/bin' : '../../src/bin/alamode' +const BIN = resolve(__dirname, ALAMODE) + +async function runFork(path, args, cwd) { + const { promise, stdout, stderr } = fork(path, args, { + stdio: 'pipe', + env: { + NODE_DEBUG: 'alamode', + }, + execArgv: [], + cwd, + }) + const { promise: stdoutPromise } = new Catchment({ + rs: stdout, + }) + const { promise: stderrPromise } = new Catchment({ + rs: stderr, + }) + await promise + const [, so, se] = await Promise.all([ + promise, + stdoutPromise, + stderrPromise, + ]) + return { stdout: so, stderr: se } +} \ No newline at end of file diff --git a/test/fixture/require-advanced.js b/test/fixture/require-advanced.js new file mode 100644 index 0000000..04a6c4b --- /dev/null +++ b/test/fixture/require-advanced.js @@ -0,0 +1,2 @@ +require('../..')() +require('./src/run-advanced') \ No newline at end of file diff --git a/test/fixture/require.js b/test/fixture/require.js new file mode 100644 index 0000000..cad8d73 --- /dev/null +++ b/test/fixture/require.js @@ -0,0 +1,2 @@ +require('../..')() +require('./src/run') \ No newline at end of file diff --git a/test/fixture/src/run-advanced.js b/test/fixture/src/run-advanced.js new file mode 100644 index 0000000..5998b7d --- /dev/null +++ b/test/fixture/src/run-advanced.js @@ -0,0 +1,22 @@ +const e = ` + export { test } from 'test' +` + +const i = ` + import test from 'test' +` + +import main from '.' + +// test + +/** + * test + */ +debugger + +(async () => { + debugger + console.log(123); /* console.log(456); */ console.log(456) + await main() // ok node +})() \ No newline at end of file diff --git a/test/snapshot/integration.json b/test/snapshot/integration.json index 8b69156..2183945 100644 --- a/test/snapshot/integration.json +++ b/test/snapshot/integration.json @@ -7,6 +7,8 @@ "method.js": "/**\n * A library method to write `method`.\n * @param {Object} param0\n * @param {string} [param0.test] First string to test\n * @param {string} [param0.test2=\"hello-world\"] Second string to test.\n */\nconst method = ({\n test,\n test2 = 'hello-world',\n} = {}) => {\n process.stdout.write(' method: ')\n process.stdout.write(test ? test : test2)\n process.stdout.write('\\n')\n}\n\nmodule.exports=method\n//# sourceMappingURL=method.js.map", "method.js.map": "{\"version\":3,\"sources\":[\"../../../fixture/src/lib/method.js\"],\"names\":[],\"mappings\":\";;;;;;AAMA,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;EACd,IAAI;EACJ,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC;AACvB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EACT,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;EAChC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK;EACxC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3B;;AAEA,MAAM,CAAC,OAAO,CAAC\",\"file\":\"lib/method.js\",\"sourcesContent\":[\"/**\\n * A library method to write `method`.\\n * @param {Object} param0\\n * @param {string} [param0.test] First string to test\\n * @param {string} [param0.test2=\\\"hello-world\\\"] Second string to test.\\n */\\nconst method = ({\\n test,\\n test2 = 'hello-world',\\n} = {}) => {\\n process.stdout.write(' method: ')\\n process.stdout.write(test ? test : test2)\\n process.stdout.write('\\\\n')\\n}\\n\\nexport default method\"]}" }, + "run-advanced.js": "const e = `\nconst $test = require('test');\n`\n\nconst i = `\nlet test = require('test'); if (test && test.__esModule) test = test.default;\n`\n\nlet main = require('.'); if (main && main.__esModule) main = main.default;\n\n// test\n\n/**\n * test\n */\ndebugger\n\n(async () => {\n debugger\n console.log(123); /* console.log(456); */ console.log(456)\n await main() // ok node\n})()\n\nmodule.exports.test = $test.test\n//# sourceMappingURL=run-advanced.js.map", + "run-advanced.js.map": "{\"version\":3,\"sources\":[\"../../fixture/src/run-advanced.js\"],\"names\":[],\"mappings\":\"AAAA,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;EACR,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI;AAC5B;;AAEA,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;EACR,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI;AACxB;;AAEA,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;;;;;;;AAOnB;;AAEA,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EACX;EACA,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,yBAAyB,OAAO,CAAC,GAAG,CAAC,GAAG;EACzD,KAAK,CAAC,IAAI,CAAC,CAAC;AACd,CAAC,CAAC,CAAC\",\"file\":\"run-advanced.js\",\"sourcesContent\":[\"const e = `\\n export { test } from 'test'\\n`\\n\\nconst i = `\\n import test from 'test'\\n`\\n\\nimport main from '.'\\n\\n// test\\n\\n/**\\n * test\\n */\\ndebugger\\n\\n(async () => {\\n debugger\\n console.log(123); /* console.log(456); */ console.log(456)\\n await main() // ok node\\n})()\"]}", "run.js": "let main = require('.'); if (main && main.__esModule) main = main.default;\n\n// test\n\n/**\n * test\n */\ndebugger\n\n(async () => {\n debugger\n console.log(123); /* console.log(456); */ console.log(456)\n await main() // ok node\n})()\n//# sourceMappingURL=run.js.map", "run.js.map": "{\"version\":3,\"sources\":[\"../../fixture/src/run.js\"],\"names\":[],\"mappings\":\"AAAA,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;;;;;;;AAOnB;;AAEA,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EACX;EACA,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,yBAAyB,OAAO,CAAC,GAAG,CAAC,GAAG;EACzD,KAAK,CAAC,IAAI,CAAC,CAAC;AACd,CAAC,CAAC,CAAC\",\"file\":\"run.js\",\"sourcesContent\":[\"import main from '.'\\n\\n// test\\n\\n/**\\n * test\\n */\\ndebugger\\n\\n(async () => {\\n debugger\\n console.log(123); /* console.log(456); */ console.log(456)\\n await main() // ok node\\n})()\"]}" } \ No newline at end of file diff --git a/test/spec/integration.js b/test/spec/integration.js index 0100dc0..81d2c79 100644 --- a/test/spec/integration.js +++ b/test/spec/integration.js @@ -35,7 +35,9 @@ const T = { setDir(SNAPSHOT_DIR) await test('transform-stream/advanced.js', stdout) }, - async '!transpiles via rc file'({ ADVANCED_FIXTURE, SNAPSHOT_DIR, fork, writeRc }, { setDir, test }) { + async 'transpiles via rc file'( + { ADVANCED_FIXTURE, SNAPSHOT_DIR, fork, writeRc }, { setDir, test }, + ) { const args = [ADVANCED_FIXTURE] await writeRc({ advanced: true, @@ -44,6 +46,23 @@ const T = { setDir(SNAPSHOT_DIR) await test('transform-stream/advanced.js', stdout) }, + async 'uses require hook'({ TEST_BUILD, forkRequire }) { + if (!TEST_BUILD) { + console.log('not testing non-built') + return + } + const { stdout } = await forkRequire() + console.log(stdout) + }, + async 'uses advanced require hook'({ TEST_BUILD, forkRequireAdvanced, writeRc }) { + if (!TEST_BUILD) { + console.log('not testing non-built') + return + } + await writeRc() + const { stdout } = await forkRequireAdvanced() + console.log(stdout) + }, async 'transpiles normal'({ JS_FIXTURE, SNAPSHOT_DIR, fork }, { setDir, test }) { const args = [JS_FIXTURE] const { stdout } = await fork(args) From 636d29055dcf139a333ee387cb4e39135737ffa2 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 07:21:29 +0300 Subject: [PATCH 07/13] fix and test sync transform --- src/lib/transform.js | 2 +- .../transform-stream/advanced-sourcemap.js | 10 ++++++++++ .../transform-stream/fixture-sourcemap.js | 10 ++++++++++ test/spec/integration.js | 12 +++++++----- test/spec/transform/default.js | 18 +++++++++++++++++- 5 files changed, 45 insertions(+), 7 deletions(-) create mode 100644 test/snapshot/transform-stream/advanced-sourcemap.js create mode 100644 test/snapshot/transform-stream/fixture-sourcemap.js diff --git a/src/lib/transform.js b/src/lib/transform.js index 32f6944..64603b0 100644 --- a/src/lib/transform.js +++ b/src/lib/transform.js @@ -113,7 +113,7 @@ export const transformString = (source, advanced) => { * @param {string} source Source code as a string. */ export const syncTransform = (source, filename, advanced) => { - const replaced = transformString(advanced) + const replaced = transformString(source, advanced) const file = basename(filename) const sourceRoot = dirname(filename) const map = getMap({ diff --git a/test/snapshot/transform-stream/advanced-sourcemap.js b/test/snapshot/transform-stream/advanced-sourcemap.js new file mode 100644 index 0000000..07786f7 --- /dev/null +++ b/test/snapshot/transform-stream/advanced-sourcemap.js @@ -0,0 +1,10 @@ +// this is a fixture file +let helloWorld = require('hello-world'); if (helloWorld && helloWorld.__esModule) helloWorld = helloWorld.default; + + const test = () => { + const res = helloWorld() + console.log(res) +} + +module.exports.test = test +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImZpeHR1cmUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUNBLE1BQU0sQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLENBQUMsS0FBSyxDQUFDLEtBQUs7O0FBRW5DLE1BQU0sQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztFQUN4QixLQUFLLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxVQUFVLENBQUM7RUFDdkIsT0FBTyxDQUFDLEdBQUcsQ0FBQyxHQUFHO0FBQ2pCIiwic291cmNlUm9vdCI6Ii9Vc2Vycy96YXZyL2EtbGEvYWxhbW9kZS90ZXN0L2ZpeHR1cmUiLCJzb3VyY2VzQ29udGVudCI6WyIvLyB0aGlzIGlzIGEgZml4dHVyZSBmaWxlXG5pbXBvcnQgaGVsbG9Xb3JsZCBmcm9tICdoZWxsby13b3JsZCdcblxuZXhwb3J0IGNvbnN0IHRlc3QgPSAoKSA9PiB7XG4gIGNvbnN0IHJlcyA9IGhlbGxvV29ybGQoKVxuICBjb25zb2xlLmxvZyhyZXMpXG59Il19 \ No newline at end of file diff --git a/test/snapshot/transform-stream/fixture-sourcemap.js b/test/snapshot/transform-stream/fixture-sourcemap.js new file mode 100644 index 0000000..07786f7 --- /dev/null +++ b/test/snapshot/transform-stream/fixture-sourcemap.js @@ -0,0 +1,10 @@ +// this is a fixture file +let helloWorld = require('hello-world'); if (helloWorld && helloWorld.__esModule) helloWorld = helloWorld.default; + + const test = () => { + const res = helloWorld() + console.log(res) +} + +module.exports.test = test +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImZpeHR1cmUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUNBLE1BQU0sQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLENBQUMsS0FBSyxDQUFDLEtBQUs7O0FBRW5DLE1BQU0sQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztFQUN4QixLQUFLLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxVQUFVLENBQUM7RUFDdkIsT0FBTyxDQUFDLEdBQUcsQ0FBQyxHQUFHO0FBQ2pCIiwic291cmNlUm9vdCI6Ii9Vc2Vycy96YXZyL2EtbGEvYWxhbW9kZS90ZXN0L2ZpeHR1cmUiLCJzb3VyY2VzQ29udGVudCI6WyIvLyB0aGlzIGlzIGEgZml4dHVyZSBmaWxlXG5pbXBvcnQgaGVsbG9Xb3JsZCBmcm9tICdoZWxsby13b3JsZCdcblxuZXhwb3J0IGNvbnN0IHRlc3QgPSAoKSA9PiB7XG4gIGNvbnN0IHJlcyA9IGhlbGxvV29ybGQoKVxuICBjb25zb2xlLmxvZyhyZXMpXG59Il19 \ No newline at end of file diff --git a/test/spec/integration.js b/test/spec/integration.js index 81d2c79..0220970 100644 --- a/test/spec/integration.js +++ b/test/spec/integration.js @@ -51,17 +51,19 @@ const T = { console.log('not testing non-built') return } - const { stdout } = await forkRequire() - console.log(stdout) + const { stdout, stderr } = await forkRequire() + console.log(stdout, stderr) }, async 'uses advanced require hook'({ TEST_BUILD, forkRequireAdvanced, writeRc }) { if (!TEST_BUILD) { console.log('not testing non-built') return } - await writeRc() - const { stdout } = await forkRequireAdvanced() - console.log(stdout) + await writeRc({ + advanced: true, + }) + const { stdout, stderr } = await forkRequireAdvanced() + console.log(stdout, stderr) }, async 'transpiles normal'({ JS_FIXTURE, SNAPSHOT_DIR, fork }, { setDir, test }) { const args = [JS_FIXTURE] diff --git a/test/spec/transform/default.js b/test/spec/transform/default.js index c2010a4..2a7c097 100644 --- a/test/spec/transform/default.js +++ b/test/spec/transform/default.js @@ -1,7 +1,7 @@ import Catchment from 'catchment' import SnapshotContext from 'snapshot-context' import Context from '../../context' -import { transformStream, transformString } from '../../../src/lib/transform' +import { transformStream, transformString, syncTransform } from '../../../src/lib/transform' /** @type {Object.} */ const T = { @@ -26,6 +26,14 @@ const T = { const res = transformString(src) await test('transform-stream/fixture.js', res) }, + async 'transforms source code with sourcemap (sync)'( + { JS_FIXTURE: source, SNAPSHOT_DIR, readFile }, { setDir, test }, + ) { + setDir(SNAPSHOT_DIR) + const src = await readFile(source) + const res = syncTransform(src, source) + await test('transform-stream/fixture-sourcemap.js', res) + }, async 'transforms source code (advanced)'( { ADVANCED_FIXTURE: source, SNAPSHOT_DIR }, { setDir, test }, ) { @@ -47,6 +55,14 @@ const T = { const res = transformString(src, true) await test('transform-stream/advanced.js', res) }, + async 'transforms source code with sourcemap (sync, advanced)'( + { JS_FIXTURE: source, SNAPSHOT_DIR, readFile }, { setDir, test }, + ) { + setDir(SNAPSHOT_DIR) + const src = await readFile(source) + const res = syncTransform(src, source, true) + await test('transform-stream/advanced-sourcemap.js', res) + }, } export default T \ No newline at end of file From 608ba9908010cc5e5bf8a290c750b2654724acee Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 07:23:13 +0300 Subject: [PATCH 08/13] build advanced --- build/bin/index.js | 22 ++++---------- build/bin/index.js.map | 2 +- build/bin/transpile.js | 8 ++++- build/bin/transpile.js.map | 2 +- build/bin/usage.js | 24 +++++++++++++++ build/bin/usage.js.map | 1 + build/index.js | 6 ++-- build/index.js.map | 2 +- build/lib/transform.js | 61 +++++++++++++++++++++++++------------- build/lib/transform.js.map | 2 +- 10 files changed, 85 insertions(+), 45 deletions(-) create mode 100644 build/bin/usage.js create mode 100644 build/bin/usage.js.map diff --git a/build/bin/index.js b/build/bin/index.js index 8c17aff..5c9e908 100755 --- a/build/bin/index.js +++ b/build/bin/index.js @@ -1,9 +1,9 @@ #!/usr/bin/env node let argufy = require('argufy'); if (argufy && argufy.__esModule) argufy = argufy.default; -let usually = require('usually'); if (usually && usually.__esModule) usually = usually.default; const { version } = require('../../package.json'); let catcher = require('./catcher'); if (catcher && catcher.__esModule) catcher = catcher.default; const { transpile } = require('./transpile'); +let getUsage = require('./usage'); if (getUsage && getUsage.__esModule) getUsage = getUsage.default; const { input: _input, @@ -12,6 +12,7 @@ const { help: _help, ignore: _ignore, noSourceMaps: _noSourceMaps, + advanced: _advanced, } = argufy({ input: { command: true }, output: { short: 'o' }, @@ -19,25 +20,11 @@ const { help: { short: 'h', boolean: true }, ignore: { short: 'i' }, noSourceMaps: { short: 's', boolean: true }, + advanced: { short: 'a', boolean: true }, }) if (_help) { - const usage = usually({ - usage: { - source: `Location of the input to the transpiler, -either a directory or a file.`, - '--output, -o': `Location to save results to. Passing "-" -will print to stdout when source is a file.`, - '--help, -h': 'Display help information.', - '--version, -v': 'Show version.', - '--ignore, -i': `Paths to files to ignore, relative to -source.`, - '--noSourceMaps, -s': 'Don\'t generate source maps.', - }, - description: 'A tool to transpile JavaScript packages using regular expressions.', - line: 'alamode source [-o destination]', - example: 'alamode src -o build', - }) + const usage = getUsage() console.log(usage) process.exit() } else if (_version) { @@ -53,6 +40,7 @@ source.`, output: _output, noSourceMaps: _noSourceMaps, ignore, + advanced: _advanced, }) } catch (err) { catcher(err) diff --git a/build/bin/index.js.map b/build/bin/index.js.map index 71b5755..383e85c 100644 --- a/build/bin/index.js.map +++ b/build/bin/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/bin/index.js"],"names":[],"mappings":"AAAA,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC;AACf,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM;AAC1B,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO;AAC5B,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI;AAC3C,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO;AAC9B,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;;AAEtC,KAAK,CAAC;EACJ,KAAK,CAAC,CAAC,MAAM;EACb,MAAM,CAAC,CAAC,OAAO;EACf,OAAO,CAAC,CAAC,QAAQ;EACjB,IAAI,CAAC,CAAC,KAAK;EACX,MAAM,CAAC,CAAC,OAAO;EACf,YAAY,CAAC,CAAC,aAAa;AAC7B,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;EACT,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC;EACxB,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EACtB,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC;EACtC,IAAI,CAAC,CAAC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G,CAAC,CAAC;IACZ,OAAO,CAAC,GAAG;EACb;AACF,CAAC,CAAC,CAAC","file":"bin/index.js","sourcesContent":["#!/usr/bin/env node\nimport argufy from 'argufy'\nimport usually from 'usually'\nimport { version } from '../../package.json'\nimport catcher from './catcher'\nimport { transpile } from './transpile'\n\nconst {\n input: _input,\n output: _output,\n version: _version,\n help: _help,\n ignore: _ignore,\n noSourceMaps: _noSourceMaps,\n} = argufy({\n input: { command: true },\n output: { short: 'o' },\n version: { short: 'v', boolean: true },\n help: { short: 'h', boolean: true },\n ignore: { short: 'i' },\n noSourceMaps: { short: 's', boolean: true },\n})\n\nif (_help) {\n const usage = usually({\n usage: {\n source: `Location of the input to the transpiler,\neither a directory or a file.`,\n '--output, -o': `Location to save results to. Passing \"-\"\nwill print to stdout when source is a file.`,\n '--help, -h': 'Display help information.',\n '--version, -v': 'Show version.',\n '--ignore, -i': `Paths to files to ignore, relative to\nsource.`,\n '--noSourceMaps, -s': 'Don\\'t generate source maps.',\n },\n description: 'A tool to transpile JavaScript packages using regular expressions.',\n line: 'alamode source [-o destination]',\n example: 'alamode src -o build',\n })\n console.log(usage)\n process.exit()\n} else if (_version) {\n console.log('v%s', version)\n process.exit()\n}\n\n(async () => {\n try {\n const ignore = _ignore ? _ignore.split(','): []\n await transpile({\n input: _input,\n output: _output,\n noSourceMaps: _noSourceMaps,\n ignore,\n })\n } catch (err) {\n catcher(err)\n }\n})()"]} \ No newline at end of file +{"version":3,"sources":["../../src/bin/index.js"],"names":[],"mappings":"AAAA,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC;AACf,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM;AAC1B,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI;AAC3C,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAA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,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC;EACvB,OAAO,CAAC,GAAG,CAAC,KAAK;EACjB,OAAO,CAAC,IAAI,CAAC;AACf,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC;EACnB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO;EAC1B,OAAO,CAAC,IAAI,CAAC;AACf;;AAEA,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EACX,GAAG,CAAC;IACF,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9C,KAAK,CAAC,SAAS,CAAC;MACd,KAAK,CAAC,CAAC,MAAM;MACb,MAAM,CAAC,CAAC,OAAO;MACf,YAAY,CAAC,CAAC,aAAa;MAC3B,MAAM;MACN,QAAQ,CAAC,CAAC,SAAS;IACrB,CAAC;EACH,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC;IACZ,OAAO,CAAC,GAAG;EACb;AACF,CAAC,CAAC,CAAC","file":"bin/index.js","sourcesContent":["#!/usr/bin/env node\nimport argufy from 'argufy'\nimport { version } from '../../package.json'\nimport catcher from './catcher'\nimport { transpile } from './transpile'\nimport getUsage from './usage'\n\nconst {\n input: _input,\n output: _output,\n version: _version,\n help: _help,\n ignore: _ignore,\n noSourceMaps: _noSourceMaps,\n advanced: _advanced,\n} = argufy({\n input: { command: true },\n output: { short: 'o' },\n version: { short: 'v', boolean: true },\n help: { short: 'h', boolean: true },\n ignore: { short: 'i' },\n noSourceMaps: { short: 's', boolean: true },\n advanced: { short: 'a', boolean: true },\n})\n\nif (_help) {\n const usage = getUsage()\n console.log(usage)\n process.exit()\n} else if (_version) {\n console.log('v%s', version)\n process.exit()\n}\n\n(async () => {\n try {\n const ignore = _ignore ? _ignore.split(','): []\n await transpile({\n input: _input,\n output: _output,\n noSourceMaps: _noSourceMaps,\n ignore,\n advanced: _advanced,\n })\n } catch (err) {\n catcher(err)\n }\n})()"]} \ No newline at end of file diff --git a/build/bin/transpile.js b/build/bin/transpile.js index 4eec079..bff2c9c 100644 --- a/build/bin/transpile.js +++ b/build/bin/transpile.js @@ -10,7 +10,7 @@ const { transformStream } = require('../lib/transform'); const LOG = debuglog('alamode') const processFile = async ({ - input, relPath, name, output, ignore, noSourceMaps, + input, relPath, name, output, ignore, noSourceMaps, advanced, }) => { const file = join(relPath, name) if (ignore.includes(file)) return @@ -27,6 +27,7 @@ const processFile = async ({ const originalSource = await transformStream({ source, destination, + advanced, }) if (output != '-') { @@ -49,6 +50,7 @@ const processDir = async ({ relPath = '.', ignore = [], noSourceMaps, + advanced, }) => { const path = join(input, relPath) const { content } = await readDirStructure(path) @@ -68,6 +70,7 @@ const processDir = async ({ ignore, relPath: newRelPath, noSourceMaps, + advanced, }) } }, Promise.resolve()) @@ -78,6 +81,7 @@ const processDir = async ({ output = '-', ignore = [], noSourceMaps, + advanced, }) => { if (!input) throw new Error('Please specify the source file or directory.') @@ -89,6 +93,7 @@ const processDir = async ({ output, ignore, noSourceMaps, + advanced, }) } else if (ls.isFile()) { await processFile({ @@ -98,6 +103,7 @@ const processDir = async ({ output, ignore, noSourceMaps, + advanced, }) } if (output != '-') process.stdout.write(`Transpiled code saved to ${output}\n`) diff --git a/build/bin/transpile.js.map b/build/bin/transpile.js.map index 02325f3..5598944 100644 --- a/build/bin/transpile.js.map +++ b/build/bin/transpile.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/bin/transpile.js"],"names":[],"mappings":"AAAA,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI;AAC7C,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC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C,WAAW,CAAC,CAAC,CAAC,CAAC;IACpB,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACnE,KAAK,CAAC,UAAU,CAAC;MACf,KAAK;MACL,MAAM;MACN,MAAM;MACN,YAAY;IACd,CAAC;EACH,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACtB,KAAK,CAAC,WAAW,CAAC;MAChB,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;MACrB,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;MACZ,IAAI,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC;MACrB,MAAM;MACN,MAAM;MACN,YAAY;IACd,CAAC;EACH;EACA,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAChF","file":"bin/transpile.js","sourcesContent":["import { join, basename, dirname } from 'path'\nimport { lstatSync } from 'fs'\nimport readDirStructure from '@wrote/read-dir-structure'\nimport ensurePath from '@wrote/ensure-path'\nimport { debuglog } from 'util'\nimport { copyMode } from '../lib'\nimport writeSourceMap from '../lib/source-map'\nimport { transformStream } from '../lib/transform'\n\nconst LOG = debuglog('alamode')\n\nconst processFile = async ({\n input, relPath, name, output, ignore, noSourceMaps,\n}) => {\n const file = join(relPath, name)\n if (ignore.includes(file)) return\n\n const isOutputStdout = output == '-'\n const source = join(input, file)\n\n const outputDir = isOutputStdout ? null : join(output, relPath)\n const destination = isOutputStdout ? '-' : join(outputDir, name)\n LOG(file)\n\n await ensurePath(destination)\n\n const originalSource = await transformStream({\n source,\n destination,\n })\n\n if (output != '-') {\n copyMode(source, destination)\n if (noSourceMaps) return\n writeSourceMap({\n destination,\n file,\n name,\n outputDir,\n source,\n originalSource,\n })\n }\n}\n\nconst processDir = async ({\n input,\n output,\n relPath = '.',\n ignore = [],\n noSourceMaps,\n}) => {\n const path = join(input, relPath)\n const { content } = await readDirStructure(path)\n const k = Object.keys(content)\n await k.reduce(async (acc, name) => {\n await acc\n const { type } = content[name]\n if (type == 'File') {\n await processFile({\n input, relPath, name, output, ignore, noSourceMaps,\n })\n } else if (type == 'Directory') {\n const newRelPath = join(relPath, name)\n await processDir({\n input,\n output,\n ignore,\n relPath: newRelPath,\n noSourceMaps,\n })\n }\n }, Promise.resolve())\n}\n\nexport const transpile = async ({\n input,\n output = '-',\n ignore = [],\n noSourceMaps,\n}) => {\n if (!input) throw new Error('Please specify the source file or directory.')\n\n const ls = lstatSync(input)\n if (ls.isDirectory()) {\n if (!output) throw new Error('Please specify the output directory.')\n await processDir({\n input,\n output,\n ignore,\n noSourceMaps,\n })\n } else if (ls.isFile()) {\n await processFile({\n input: dirname(input),\n relPath: '.',\n name: basename(input),\n output,\n ignore,\n noSourceMaps,\n })\n }\n if (output != '-') process.stdout.write(`Transpiled code saved to ${output}\\n`)\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/bin/transpile.js"],"names":[],"mappings":"AAAA,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI;AAC7C,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE;AAC7B,MAAM,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS;AACvD,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CA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,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACnE,KAAK,CAAC,UAAU,CAAC;MACf,KAAK;MACL,MAAM;MACN,MAAM;MACN,YAAY;MACZ,QAAQ;IACV,CAAC;EACH,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACtB,KAAK,CAAC,WAAW,CAAC;MAChB,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;MACrB,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;MACZ,IAAI,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC;MACrB,MAAM;MACN,MAAM;MACN,YAAY;MACZ,QAAQ;IACV,CAAC;EACH;EACA,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAChF","file":"bin/transpile.js","sourcesContent":["import { join, basename, dirname } from 'path'\nimport { lstatSync } from 'fs'\nimport readDirStructure from '@wrote/read-dir-structure'\nimport ensurePath from '@wrote/ensure-path'\nimport { debuglog } from 'util'\nimport { copyMode } from '../lib'\nimport writeSourceMap from '../lib/source-map'\nimport { transformStream } from '../lib/transform'\n\nconst LOG = debuglog('alamode')\n\nconst processFile = async ({\n input, relPath, name, output, ignore, noSourceMaps, advanced,\n}) => {\n const file = join(relPath, name)\n if (ignore.includes(file)) return\n\n const isOutputStdout = output == '-'\n const source = join(input, file)\n\n const outputDir = isOutputStdout ? null : join(output, relPath)\n const destination = isOutputStdout ? '-' : join(outputDir, name)\n LOG(file)\n\n await ensurePath(destination)\n\n const originalSource = await transformStream({\n source,\n destination,\n advanced,\n })\n\n if (output != '-') {\n copyMode(source, destination)\n if (noSourceMaps) return\n writeSourceMap({\n destination,\n file,\n name,\n outputDir,\n source,\n originalSource,\n })\n }\n}\n\nconst processDir = async ({\n input,\n output,\n relPath = '.',\n ignore = [],\n noSourceMaps,\n advanced,\n}) => {\n const path = join(input, relPath)\n const { content } = await readDirStructure(path)\n const k = Object.keys(content)\n await k.reduce(async (acc, name) => {\n await acc\n const { type } = content[name]\n if (type == 'File') {\n await processFile({\n input, relPath, name, output, ignore, noSourceMaps,\n })\n } else if (type == 'Directory') {\n const newRelPath = join(relPath, name)\n await processDir({\n input,\n output,\n ignore,\n relPath: newRelPath,\n noSourceMaps,\n advanced,\n })\n }\n }, Promise.resolve())\n}\n\nexport const transpile = async ({\n input,\n output = '-',\n ignore = [],\n noSourceMaps,\n advanced,\n}) => {\n if (!input) throw new Error('Please specify the source file or directory.')\n\n const ls = lstatSync(input)\n if (ls.isDirectory()) {\n if (!output) throw new Error('Please specify the output directory.')\n await processDir({\n input,\n output,\n ignore,\n noSourceMaps,\n advanced,\n })\n } else if (ls.isFile()) {\n await processFile({\n input: dirname(input),\n relPath: '.',\n name: basename(input),\n output,\n ignore,\n noSourceMaps,\n advanced,\n })\n }\n if (output != '-') process.stdout.write(`Transpiled code saved to ${output}\\n`)\n}\n"]} \ No newline at end of file diff --git a/build/bin/usage.js b/build/bin/usage.js new file mode 100644 index 0000000..47988b2 --- /dev/null +++ b/build/bin/usage.js @@ -0,0 +1,24 @@ +let usually = require('usually'); if (usually && usually.__esModule) usually = usually.default; + +module.exports=() => { + const usage = usually({ + usage: { + source: `Location of the input to the transpiler, +either a directory or a file.`, + '--output, -o': `Location to save results to. Passing "-" +will print to stdout when source is a file.`, + '--help, -h': 'Display help information.', + '--version, -v': 'Show version.', + '--ignore, -i': `Paths to files to ignore, relative to the +source directory.`, + '--noSourceMaps, -s': 'Don\'t generate source maps.', + '--advanced, -a': `Attempt to skip statements inside of template +literals.`, + }, + description: 'A tool to transpile JavaScript packages using regular expressions.', + line: 'alamode source [-o destination]', + example: 'alamode src -o build', + }) + return usage +} +//# sourceMappingURL=usage.js.map \ No newline at end of file diff --git a/build/bin/usage.js.map b/build/bin/usage.js.map new file mode 100644 index 0000000..7b6cca9 --- /dev/null +++ b/build/bin/usage.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/bin/usage.js"],"names":[],"mappings":"AAAA,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO;;AAE5B,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EACnB,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC;IACpB,KAAK,CAAC,CAAC;MACL,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,UAAU;AACtD,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;MACxB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;AAC9D,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;MACtC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;MACzC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;MAChC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;AAC7D,MAAM,CAAC,SAAS,CAAC,CAAC;MACZ,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;MACpD,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;AAC9D,QAAQ,CAAC,CAAC;IACN,CAAC;IACD,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IACjF,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;IACvC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;EACjC,CAAC;EACD,MAAM,CAAC;AACT","file":"bin/usage.js","sourcesContent":["import usually from 'usually'\n\nexport default () => {\n const usage = usually({\n usage: {\n source: `Location of the input to the transpiler,\neither a directory or a file.`,\n '--output, -o': `Location to save results to. Passing \"-\"\nwill print to stdout when source is a file.`,\n '--help, -h': 'Display help information.',\n '--version, -v': 'Show version.',\n '--ignore, -i': `Paths to files to ignore, relative to the\nsource directory.`,\n '--noSourceMaps, -s': 'Don\\'t generate source maps.',\n '--advanced, -a': `Attempt to skip statements inside of template\nliterals.`,\n },\n description: 'A tool to transpile JavaScript packages using regular expressions.',\n line: 'alamode source [-o destination]',\n example: 'alamode src -o build',\n })\n return usage\n}"]} \ No newline at end of file diff --git a/build/index.js b/build/index.js index 311ba31..927a9ee 100644 --- a/build/index.js +++ b/build/index.js @@ -2,10 +2,12 @@ const { addHook } = require('pirates'); const { syncTransform } = require('./lib/transform'); /** Enable transpilation of files on-the file as a require hook. */ -const alamode = () => { +const alamode = ({ + advanced = false, +} = {}) => { addHook( (code, filename) => { - const res = syncTransform(code, filename) + const res = syncTransform(code, filename, advanced) return res }, { exts: ['.js'] } diff --git a/build/index.js.map b/build/index.js.map index fffb31a..876b543 100644 --- a/build/index.js.map +++ b/build/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.js"],"names":[],"mappings":"AAAA,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO;AAChC,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS;;;AAG9C,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EACpB,OAAO;IACL,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;MAClB,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,QAAQ;MACxC,MAAM,CAAC;IACT,CAAC;IACD,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;EAClB;AACF;;AAEA,MAAM,CAAC,OAAO,CAAC","file":"index.js","sourcesContent":["import { addHook } from 'pirates'\nimport { syncTransform } from './lib/transform'\n\n/** Enable transpilation of files on-the file as a require hook. */\nconst alamode = () => {\n addHook(\n (code, filename) => {\n const res = syncTransform(code, filename)\n return res\n },\n { exts: ['.js'] }\n )\n}\n\nexport default alamode"]} \ No newline at end of file +{"version":3,"sources":["../src/index.js"],"names":[],"mappings":"AAAA,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO;AAChC,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS;;;AAG9C,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;EACf,QAAQ,CAAC,CAAC,CAAC,KAAK;AAClB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EACT,OAAO;IACL,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;MAClB,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ;MAClD,MAAM,CAAC;IACT,CAAC;IACD,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;EAClB;AACF;;AAEA,MAAM,CAAC,OAAO,CAAC","file":"index.js","sourcesContent":["import { addHook } from 'pirates'\nimport { syncTransform } from './lib/transform'\n\n/** Enable transpilation of files on-the file as a require hook. */\nconst alamode = ({\n advanced = false,\n} = {}) => {\n addHook(\n (code, filename) => {\n const res = syncTransform(code, filename, advanced)\n return res\n },\n { exts: ['.js'] }\n )\n}\n\nexport default alamode"]} \ No newline at end of file diff --git a/build/lib/transform.js b/build/lib/transform.js index 325d269..f89f21f 100644 --- a/build/lib/transform.js +++ b/build/lib/transform.js @@ -1,7 +1,7 @@ const { Replaceable } = require('restream'); -let makeRules = require('@a-la/markers'); if (makeRules && makeRules.__esModule) makeRules = makeRules.default; -let ALaImport = require('@a-la/import'); if (ALaImport && ALaImport.__esModule) ALaImport = ALaImport.default; -let ALaExport = require('@a-la/export'); if (ALaExport && ALaExport.__esModule) ALaExport = ALaExport.default; +let makeRules = require('@a-la/markers'); if (makeRules && makeRules.__esModule) makeRules = makeRules.default; const { makeAdvancedRules } = makeRules +let ALaImport = require('@a-la/import'); if (ALaImport && ALaImport.__esModule) ALaImport = ALaImport.default; const { advancedSeq: advancedALaImport } = ALaImport +let ALaExport = require('@a-la/export'); if (ALaExport && ALaExport.__esModule) ALaExport = ALaExport.default; const { advancedSeq: advancedALaExport } = ALaExport let whichStream = require('which-stream'); if (whichStream && whichStream.__esModule) whichStream = whichStream.default; let Catchment = require('catchment'); if (Catchment && Catchment.__esModule) Catchment = Catchment.default; const { createReadStream } = require('fs'); @@ -13,7 +13,9 @@ const getConfig = () => { try { const r = join(process.cwd(), '.alamoderc.json') config = require(r) - } catch (err) { /* no config */ } + } catch (err) { + return config + } const { env: { ALAMODE_ENV } } = process const c = config.env && ALAMODE_ENV in config.env ? config.env[ALAMODE_ENV] : config @@ -22,13 +24,23 @@ const getConfig = () => { return c } - -const makeReplaceable = () => { - const config = getConfig() - const { rules, markers } = makeRules([ +const getRules = (advanced) => { + const r = advanced ? [ + ...advancedALaImport, + ...advancedALaExport, + ] : [ ...ALaImport, ...ALaExport, - ]) + ] + const mr = advanced ? makeAdvancedRules : makeRules + const { rules, markers } = mr(r) + return { rules, markers } +} + +const makeReplaceable = (advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + const replaceable = new Replaceable(rules) replaceable.markers = markers @@ -43,8 +55,9 @@ const makeReplaceable = () => { source, destination, writable, + advanced = false, }) => { - const replaceable = makeReplaceable() + const replaceable = makeReplaceable(advanced) const readable = createReadStream(source) @@ -68,10 +81,10 @@ const makeReplaceable = () => { } class Context { - constructor(markers) { + constructor(config, markers) { this.listeners = {} this.markers = markers - this.config = getConfig() + this.config = config } on(event, listener) { this.listeners[event] = listener @@ -79,23 +92,28 @@ class Context { emit(event, data) { this.listeners[event](data) } + get advanced() { + return this.config.advanced + } } -/** - * @param {string} source Source code as a string. - */ - const syncTransform = (source, filename) => { - const { rules, markers } = makeRules([ - ...ALaImport, - ...ALaExport, - ]) - const context = new Context(markers) + const transformString = (source, advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + const context = new Context(config, markers) const replaced = rules.reduce((acc, { re, replacement }) => { const newAcc = acc.replace(re, replacement.bind(context)) return newAcc }, source) + return replaced +} +/** + * @param {string} source Source code as a string. + */ + const syncTransform = (source, filename, advanced) => { + const replaced = transformString(source, advanced) const file = basename(filename) const sourceRoot = dirname(filename) const map = getMap({ @@ -112,5 +130,6 @@ class Context { } module.exports.transformStream = transformStream +module.exports.transformString = transformString module.exports.syncTransform = syncTransform //# sourceMappingURL=transform.js.map \ No newline at end of file diff --git a/build/lib/transform.js.map b/build/lib/transform.js.map index 3b8b2a0..d609793 100644 --- a/build/lib/transform.js.map +++ b/build/lib/transform.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/lib/transform.js"],"names":[],"mappings":"AAAA,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ;AACrC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO;AACpC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM;AACnC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM;AACnC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,MAAM;AACrC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,SAAS;AAChC,MAAM,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE;AACpC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI;AAC7C,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG;;AAEpC,KAAK,CAAC,SAAS,CAA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,UAAU;EACZ,CAAC;EACD,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC;EAC9C,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;;EAEX,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;;EAE/B,MAAM,CAAC;AACT","file":"lib/transform.js","sourcesContent":["import { Replaceable } from 'restream'\nimport makeRules from '@a-la/markers'\nimport ALaImport from '@a-la/import'\nimport ALaExport from '@a-la/export'\nimport whichStream from 'which-stream'\nimport Catchment from 'catchment'\nimport { createReadStream } from 'fs'\nimport { basename, dirname, join } from 'path'\nimport { getMap } from './source-map'\n\nconst getConfig = () => {\n let config = {}\n try {\n const r = join(process.cwd(), '.alamoderc.json')\n config = require(r)\n } catch (err) { /* no config */ }\n const { env: { ALAMODE_ENV } } = process\n const c = config.env && ALAMODE_ENV in config.env ? config.env[ALAMODE_ENV] : config\n\n delete c.env\n\n return c\n}\n\n\nconst makeReplaceable = () => {\n const config = getConfig()\n const { rules, markers } = makeRules([\n ...ALaImport,\n ...ALaExport,\n ])\n const replaceable = new Replaceable(rules)\n replaceable.markers = markers\n\n replaceable.config = config\n return replaceable\n}\n\n/**\n * Run a transform stream.\n */\nexport const transformStream = async ({\n source,\n destination,\n writable,\n}) => {\n const replaceable = makeReplaceable()\n\n const readable = createReadStream(source)\n\n readable.pipe(replaceable)\n const { promise: sourcePromise } = new Catchment({ rs: readable })\n\n const [,, sourceCode] = await Promise.all([\n whichStream({\n source,\n ...(writable ? { writable } : { destination }),\n readable: replaceable,\n }),\n new Promise((r, j) => {\n replaceable.once('error', j)\n replaceable.once('end', r)\n }),\n sourcePromise,\n ])\n\n return sourceCode\n}\n\nclass Context {\n constructor(markers) {\n this.listeners = {}\n this.markers = markers\n this.config = getConfig()\n }\n on(event, listener) {\n this.listeners[event] = listener\n }\n emit(event, data) {\n this.listeners[event](data)\n }\n}\n\n/**\n * @param {string} source Source code as a string.\n */\nexport const syncTransform = (source, filename) => {\n const { rules, markers } = makeRules([\n ...ALaImport,\n ...ALaExport,\n ])\n const context = new Context(markers)\n\n const replaced = rules.reduce((acc, { re, replacement }) => {\n const newAcc = acc.replace(re, replacement.bind(context))\n return newAcc\n }, source)\n\n const file = basename(filename)\n const sourceRoot = dirname(filename)\n const map = getMap({\n originalSource: source,\n pathToSrc: file,\n sourceRoot,\n })\n const b64 = Buffer.from(map).toString('base64')\n const s = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${b64}`\n\n const code = `${replaced}\\n${s}`\n\n return code\n}"]} \ No newline at end of file +{"version":3,"sources":["../../src/lib/transform.js"],"names":[],"mappings":"AAAA,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ;AACrC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO;AAC3D,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM;AACzE,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM;AACzE,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,MAAM;AACrC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,SAAS;AAChC,MAAM,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE;AACpC,MA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AC,CAAC,IAAI;IACf,UAAU;EACZ,CAAC;EACD,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC;EAC9C,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;;EAEX,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;;EAE/B,MAAM,CAAC;AACT","file":"lib/transform.js","sourcesContent":["import { Replaceable } from 'restream'\nimport makeRules, { makeAdvancedRules } from '@a-la/markers'\nimport ALaImport, { advancedSeq as advancedALaImport } from '@a-la/import'\nimport ALaExport, { advancedSeq as advancedALaExport } from '@a-la/export'\nimport whichStream from 'which-stream'\nimport Catchment from 'catchment'\nimport { createReadStream } from 'fs'\nimport { basename, dirname, join } from 'path'\nimport { getMap } from './source-map'\n\nconst getConfig = () => {\n let config = {}\n try {\n const r = join(process.cwd(), '.alamoderc.json')\n config = require(r)\n } catch (err) {\n return config\n }\n const { env: { ALAMODE_ENV } } = process\n const c = config.env && ALAMODE_ENV in config.env ? config.env[ALAMODE_ENV] : config\n\n delete c.env\n\n return c\n}\n\nconst getRules = (advanced) => {\n const r = advanced ? [\n ...advancedALaImport,\n ...advancedALaExport,\n ] : [\n ...ALaImport,\n ...ALaExport,\n ]\n const mr = advanced ? makeAdvancedRules : makeRules\n const { rules, markers } = mr(r)\n return { rules, markers }\n}\n\nconst makeReplaceable = (advanced) => {\n const config = getConfig()\n const { rules, markers } = getRules(config.advanced || advanced)\n\n const replaceable = new Replaceable(rules)\n replaceable.markers = markers\n\n replaceable.config = config\n return replaceable\n}\n\n/**\n * Run a transform stream.\n */\nexport const transformStream = async ({\n source,\n destination,\n writable,\n advanced = false,\n}) => {\n const replaceable = makeReplaceable(advanced)\n\n const readable = createReadStream(source)\n\n readable.pipe(replaceable)\n const { promise: sourcePromise } = new Catchment({ rs: readable })\n\n const [,, sourceCode] = await Promise.all([\n whichStream({\n source,\n ...(writable ? { writable } : { destination }),\n readable: replaceable,\n }),\n new Promise((r, j) => {\n replaceable.once('error', j)\n replaceable.once('end', r)\n }),\n sourcePromise,\n ])\n\n return sourceCode\n}\n\nclass Context {\n constructor(config, markers) {\n this.listeners = {}\n this.markers = markers\n this.config = config\n }\n on(event, listener) {\n this.listeners[event] = listener\n }\n emit(event, data) {\n this.listeners[event](data)\n }\n get advanced() {\n return this.config.advanced\n }\n}\n\nexport const transformString = (source, advanced) => {\n const config = getConfig()\n const { rules, markers } = getRules(config.advanced || advanced)\n const context = new Context(config, markers)\n\n const replaced = rules.reduce((acc, { re, replacement }) => {\n const newAcc = acc.replace(re, replacement.bind(context))\n return newAcc\n }, source)\n return replaced\n}\n\n/**\n * @param {string} source Source code as a string.\n */\nexport const syncTransform = (source, filename, advanced) => {\n const replaced = transformString(source, advanced)\n const file = basename(filename)\n const sourceRoot = dirname(filename)\n const map = getMap({\n originalSource: source,\n pathToSrc: file,\n sourceRoot,\n })\n const b64 = Buffer.from(map).toString('base64')\n const s = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${b64}`\n\n const code = `${replaced}\\n${s}`\n\n return code\n}"]} \ No newline at end of file From 15a37fa9b59efff13a85593d9cf1d377ab1a02f9 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 07:23:22 +0300 Subject: [PATCH 09/13] integration test require build --- test/spec/integration.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/test/spec/integration.js b/test/spec/integration.js index 0220970..98f3624 100644 --- a/test/spec/integration.js +++ b/test/spec/integration.js @@ -51,8 +51,10 @@ const T = { console.log('not testing non-built') return } - const { stdout, stderr } = await forkRequire() - console.log(stdout, stderr) + const { stdout } = await forkRequire() + ok(/123/.test(stdout)) + ok(/456/.test(stdout)) + ok(/hello-world/.test(stdout)) }, async 'uses advanced require hook'({ TEST_BUILD, forkRequireAdvanced, writeRc }) { if (!TEST_BUILD) { @@ -62,8 +64,10 @@ const T = { await writeRc({ advanced: true, }) - const { stdout, stderr } = await forkRequireAdvanced() - console.log(stdout, stderr) + const { stdout } = await forkRequireAdvanced() + ok(/123/.test(stdout)) + ok(/456/.test(stdout)) + ok(/hello-world/.test(stdout)) }, async 'transpiles normal'({ JS_FIXTURE, SNAPSHOT_DIR, fork }, { setDir, test }) { const args = [JS_FIXTURE] From 3706bfca477d26032897e296984475ab46f23910 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 07:26:01 +0300 Subject: [PATCH 10/13] test advanced require via config --- test/context/index.js | 4 ++++ test/fixture/require-advanced-config.js | 4 ++++ test/spec/integration.js | 16 +++++++++++++++- 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 test/fixture/require-advanced-config.js diff --git a/test/context/index.js b/test/context/index.js index 3cc1cb7..81f155c 100644 --- a/test/context/index.js +++ b/test/context/index.js @@ -118,6 +118,10 @@ export default class Context { const path = resolve(FIXTURE, 'require-advanced') return runFork(path, [], this.TEMP) } + async forkRequireAdvancedConfig() { + const path = resolve(FIXTURE, 'require-advanced-config') + return runFork(path, [], this.TEMP) + } async fork(args) { return runFork(this.BIN, args, this.TEMP) } diff --git a/test/fixture/require-advanced-config.js b/test/fixture/require-advanced-config.js new file mode 100644 index 0000000..24bedcb --- /dev/null +++ b/test/fixture/require-advanced-config.js @@ -0,0 +1,4 @@ +require('../..')({ + advanced: true, +}) +require('./src/run-advanced') \ No newline at end of file diff --git a/test/spec/integration.js b/test/spec/integration.js index 98f3624..c558ac2 100644 --- a/test/spec/integration.js +++ b/test/spec/integration.js @@ -56,7 +56,9 @@ const T = { ok(/456/.test(stdout)) ok(/hello-world/.test(stdout)) }, - async 'uses advanced require hook'({ TEST_BUILD, forkRequireAdvanced, writeRc }) { + async 'uses advanced require hook via rc file'( + { TEST_BUILD, forkRequireAdvanced, writeRc }, + ) { if (!TEST_BUILD) { console.log('not testing non-built') return @@ -69,6 +71,18 @@ const T = { ok(/456/.test(stdout)) ok(/hello-world/.test(stdout)) }, + async 'uses advanced require hook via config'( + { TEST_BUILD, forkRequireAdvancedConfig }, + ) { + if (!TEST_BUILD) { + console.log('not testing non-built') + return + } + const { stdout } = await forkRequireAdvancedConfig() + ok(/123/.test(stdout)) + ok(/456/.test(stdout)) + ok(/hello-world/.test(stdout)) + }, async 'transpiles normal'({ JS_FIXTURE, SNAPSHOT_DIR, fork }, { setDir, test }) { const args = [JS_FIXTURE] const { stdout } = await fork(args) From fe149804dcd0741ca54b5c4d79d0fcfff4971c0a Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 09:28:56 +0300 Subject: [PATCH 11/13] up doc, zoroaster --- package.json | 4 +-- yarn.lock | 83 ++++++++++++++++++++++------------------------------ 2 files changed, 37 insertions(+), 50 deletions(-) diff --git a/package.json b/package.json index 14eef21..6f6e82b 100644 --- a/package.json +++ b/package.json @@ -59,12 +59,12 @@ "devDependencies": { "bosom": "1.0.0", "catchment": "3.0.1", - "documentary": "1.10.0", + "documentary": "1.11.0", "eslint-config-artdeco": "1.0.1", "snapshot-context": "2.0.4", "spawncommand": "2.0.1", "yarn-s": "1.1.0", - "zoroaster": "2.4.0" + "zoroaster": "3.0.0" }, "dependencies": { "@a-la/export": "1.3.0", diff --git a/yarn.lock b/yarn.lock index 025e498..3dd6233 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,18 +2,10 @@ # yarn lockfile v1 -"@a-la/export@1.2.1": - version "1.2.1" - resolved "https://registry.yarnpkg.com/@a-la/export/-/export-1.2.1.tgz#366ca88e43f41c9614fc03dcb945e6a20c45e64e" - "@a-la/export@1.3.0": version "1.3.0" resolved "https://registry.yarnpkg.com/@a-la/export/-/export-1.3.0.tgz#aaa22530315f85557331ddd2fc096b1b20d11afb" -"@a-la/import@1.4.1": - version "1.4.1" - resolved "https://registry.yarnpkg.com/@a-la/import/-/import-1.4.1.tgz#a544c91572c96ef8394bc08a9deb88f7899846f7" - "@a-la/import@1.6.1": version "1.6.1" resolved "https://registry.yarnpkg.com/@a-la/import/-/import-1.6.1.tgz#ff370c9addd3d59629301d6012289121670e1fdc" @@ -42,24 +34,21 @@ dependencies: makepromise "2.0.0" -alamode@1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/alamode/-/alamode-1.2.1.tgz#8c0d7d573cbdac6b2f9b99a10fdbb6931e2ed55e" +alamode@1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/alamode/-/alamode-1.4.0.tgz#e12844a9bdc4d352a01c92d1684adcf12139a61c" dependencies: - "@a-la/export" "1.2.1" - "@a-la/import" "1.4.1" + "@a-la/export" "1.3.0" + "@a-la/import" "1.6.1" + "@a-la/markers" "1.0.3" "@wrote/ensure-path" "1.0.2" "@wrote/read-dir-structure" "1.0.1" argufy "1.2.1" pirates "4.0.0" - restream "3.1.0" + restream "3.1.1" source-map "0.7.3" usually "1.0.0" - which-stream "1.0.0" - -argufy@1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/argufy/-/argufy-1.1.2.tgz#e99107e00e84b6272bedc0b9a93e42014edd5a72" + which-stream "1.0.1" argufy@1.2.1: version "1.2.1" @@ -91,10 +80,6 @@ catchment@2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/catchment/-/catchment-2.0.1.tgz#df0a05ac2e1194cf280c2444d5bb564a9cc8f488" -catchment@3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/catchment/-/catchment-3.0.0.tgz#b909a59639c37201c3d0ee550062e2ade0ff0a80" - catchment@3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/catchment/-/catchment-3.0.1.tgz#11dab5fea86d412343e797e052b21091b7e83a55" @@ -123,15 +108,18 @@ difflib@~0.2.1: dependencies: heap ">= 0.2.0" -documentary@1.10.0: - version "1.10.0" - resolved "https://registry.yarnpkg.com/documentary/-/documentary-1.10.0.tgz#f3d5e915a1d6d71805f804e0b71fef278680c68b" +documentary@1.11.0: + version "1.11.0" + resolved "https://registry.yarnpkg.com/documentary/-/documentary-1.11.0.tgz#b0211293858ef749ac2fd589be02398af122810f" dependencies: - argufy "1.1.2" - catchment "2.0.1" + argufy "1.2.1" + catchment "3.0.1" + mismatch "1.0.2" pedantry "1.0.1" - restream "2.1.0" + restream "3.1.1" + rexml "1.1.0" spawncommand "2.0.1" + which-stream "1.0.1" dreamopt@~0.6.0: version "0.6.0" @@ -207,6 +195,12 @@ makepromise@2.0.0: dependencies: erotic "1.0.1" +makepromise@3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/makepromise/-/makepromise-3.0.1.tgz#5610962047452f91b278c4d3bdc1c854185d913e" + dependencies: + erotic "1.2.1" + mismatch@1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/mismatch/-/mismatch-1.0.2.tgz#80262a922a420b7ace005195ee14508787d9072f" @@ -241,18 +235,14 @@ restream@1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/restream/-/restream-1.2.0.tgz#fd13b031a54e80cc65d1878c43149f1b3a40efbb" -restream@2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/restream/-/restream-2.1.0.tgz#934e177343e81bd6a64fc555f91085544da56db1" - -restream@3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/restream/-/restream-3.1.0.tgz#4245024bcb7cdcc0a63b1676ab1bbded24062a10" - restream@3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/restream/-/restream-3.1.1.tgz#36084997bd3e765c2da484700e16b850c2f9ffb4" +rexml@1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/rexml/-/rexml-1.1.0.tgz#d005c515528aa0c81a39cd456a0da40321ab3fe8" + snapshot-context@2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/snapshot-context/-/snapshot-context-2.0.4.tgz#b8121d9bff2eded0462a74fa503186fdaea17444" @@ -283,12 +273,6 @@ usually@1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/usually/-/usually-1.0.0.tgz#3ace5b09471ddf35cccca85971ca178b5255d4b0" -which-stream@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/which-stream/-/which-stream-1.0.0.tgz#1c28212ce6a1d590619ad8683bfc58c17bf63b3d" - dependencies: - catchment "3.0.0" - which-stream@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/which-stream/-/which-stream-1.0.1.tgz#2b495b083b1c31ff68dd4d770b0caa7f86e769af" @@ -313,17 +297,20 @@ yarn-s@1.1.0: dependencies: spawncommand "1.1.0" -zoroaster@2.4.0: - version "2.4.0" - resolved "https://registry.yarnpkg.com/zoroaster/-/zoroaster-2.4.0.tgz#bd434b9fb4bfff8e2302611b31f2ae3007754730" +zoroaster@3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/zoroaster/-/zoroaster-3.0.0.tgz#6aaaf940cb59e0dcbf2d1aa7493ed1dd96875b22" dependencies: - alamode "1.2.1" + alamode "1.4.0" + argufy "1.2.1" assert-diff "2.0.3" assert-throws "2.1.0" - catchment "3.0.0" + catchment "3.0.1" clean-stack "1.3.0" erte "1.1.4" + makepromise "3.0.1" mismatch "1.0.2" promto "1.0.1" spawncommand "2.0.1" + usually "1.0.0" yarn-s "1.1.0" From 03266a6bce72206cf7d8e7788ade22020965e12c Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 3 Sep 2018 11:26:21 +0300 Subject: [PATCH 12/13] doc advanced --- README.md | 1845 ++++++++++++++++++++++++++++- documentary/3-CLI/index.md | 3 +- documentary/4-tranforms/footer.md | 32 + documentary/4-tranforms/index.md | 4 + documentary/5-modes/1-comments.md | 2 + documentary/5-modes/index.md | 19 + 6 files changed, 1903 insertions(+), 2 deletions(-) create mode 100644 documentary/4-tranforms/footer.md create mode 100644 documentary/5-modes/1-comments.md create mode 100644 documentary/5-modes/index.md diff --git a/README.md b/README.md index 29a0f3e..4588a7c 100644 --- a/README.md +++ b/README.md @@ -22,12 +22,16 @@ The package can be used via the [CLI](#CLI) to build packages, or via the [requi * [Show Help](#show-help) * [Ignore Paths](#ignore-paths) * [No Source Maps](#no-source-maps) + * [Advanced](#advanced) * [`NODE_DEBUG`](#node_debug) - [.alamoderc.json](#alamodercjson) + * [`advanced`](#advanced) - [Transforms](#transforms) * [`@a-la/import`](#a-laimport) * [Replace Path](#replace-path) * [`@a-la/export`](#a-laexport) + * [Advanced Mode](#advanced-mode) +- [Modes](#modes) - [Require Hook](#require-hook) - [Source Maps](#source-maps) * [debug session](#debug-session) @@ -88,6 +92,7 @@ There are other arguments which can be passed. | Show Help | `-h`, `--help` | Display help information and quit. | | Ignore Paths | `-i`, `--ignore` | A list of files inside of the source directory to ignore, separated with a comma. For example, to ignore `src/bin/alamode.js` when building `src`, the `-i bin/alamode.js` should be passed | | No Source Maps | `-s`, `--noSourceMaps` | Don't generate source maps. | +| Advanced | `-a`, `--advanced` | Attempt to exclude template strings from participating in transforms. [See more](#advanced-mode). | Setting the `NODE_DEBUG` environmental variable to `alamode` will print the list of processed files to the `stderr`. @@ -120,6 +125,10 @@ A transform can support options which can be set in the `.alamoderc.json` config } ``` +### `advanced` + +When set in the `.alamoderc`, the `advanced` option will make transforms run in the [advanced mode](#advanced-mode). + ## Transforms There are a number of built-in transforms, which don't need to be installed separately because their size is small enough to be included as direct dependencies. @@ -139,6 +148,431 @@ import { version } from '../../package.json' ``` ```js +123 +#!/usr/bin/env node +import argufy from 'argufy' +import { version } from '../../package.json' +import catcher from './catcher' +import { transpile } from './transpile' +import getUsage from './usage' + +const { + input: _input, + output: _output, + version: _version, + help: _help, + ignore: _ignore, + noSourceMaps: _noSourceMaps, + advanced: _advanced, +} = argufy({ + input: { command: true }, + output: { short: 'o' }, + version: { short: 'v', boolean: true }, + help: { short: 'h', boolean: true }, + ignore: { short: 'i' }, + noSourceMaps: { short: 's', boolean: true }, + advanced: { short: 'a', boolean: true }, +}) + +if (_help) { + const usage = getUsage() + console.log(usage) + process.exit() +} else if (_version) { + console.log('v%s', version) + process.exit() +} + +(async () => { + try { + const ignore = _ignore ? _ignore.split(','): [] + await transpile({ + input: _input, + output: _output, + noSourceMaps: _noSourceMaps, + ignore, + advanced: _advanced, + }) + } catch (err) { + catcher(err) + } +})() +123 +123 +import { debuglog } from 'util' + +const LOG = debuglog('alamode') +const DEBUG = /alamode/.test(process.env.NODE_DEBUG) + +const catcher = (err) => { + let stack + let message + if (err instanceof Error) { + ({ stack, message } = err) + } else { + stack = message = err + } + DEBUG ? LOG(stack) : console.log(message) + process.exit(1) +} + +export default catcher +123 +123 +import { join, basename, dirname } from 'path' +import { lstatSync } from 'fs' +import readDirStructure from '@wrote/read-dir-structure' +import ensurePath from '@wrote/ensure-path' +import { debuglog } from 'util' +import { copyMode } from '../lib' +import writeSourceMap from '../lib/source-map' +import { transformStream } from '../lib/transform' + +const LOG = debuglog('alamode') + +const processFile = async ({ + input, relPath, name, output, ignore, noSourceMaps, advanced, +}) => { + const file = join(relPath, name) + if (ignore.includes(file)) return + + const isOutputStdout = output == '-' + const source = join(input, file) + + const outputDir = isOutputStdout ? null : join(output, relPath) + const destination = isOutputStdout ? '-' : join(outputDir, name) + LOG(file) + + await ensurePath(destination) + + const originalSource = await transformStream({ + source, + destination, + advanced, + }) + + if (output != '-') { + copyMode(source, destination) + if (noSourceMaps) return + writeSourceMap({ + destination, + file, + name, + outputDir, + source, + originalSource, + }) + } +} + +const processDir = async ({ + input, + output, + relPath = '.', + ignore = [], + noSourceMaps, + advanced, +}) => { + const path = join(input, relPath) + const { content } = await readDirStructure(path) + const k = Object.keys(content) + await k.reduce(async (acc, name) => { + await acc + const { type } = content[name] + if (type == 'File') { + await processFile({ + input, relPath, name, output, ignore, noSourceMaps, + }) + } else if (type == 'Directory') { + const newRelPath = join(relPath, name) + await processDir({ + input, + output, + ignore, + relPath: newRelPath, + noSourceMaps, + advanced, + }) + } + }, Promise.resolve()) +} + +export const transpile = async ({ + input, + output = '-', + ignore = [], + noSourceMaps, + advanced, +}) => { + if (!input) throw new Error('Please specify the source file or directory.') + + const ls = lstatSync(input) + if (ls.isDirectory()) { + if (!output) throw new Error('Please specify the output directory.') + await processDir({ + input, + output, + ignore, + noSourceMaps, + advanced, + }) + } else if (ls.isFile()) { + await processFile({ + input: dirname(input), + relPath: '.', + name: basename(input), + output, + ignore, + noSourceMaps, + advanced, + }) + } + if (output != '-') process.stdout.write(`Transpiled code saved to ${output}\n`) +} + +123 +123 +import { chmodSync, lstatSync } from 'fs' + +export const copyMode = (input, output) => { + const ls = lstatSync(input) + const { mode } = ls + chmodSync(output, mode) +} +123 +123 +import { relative, join } from 'path' +import { appendFileSync, writeFileSync } from 'fs' +import { SourceMapGenerator } from 'source-map' +import { inlineCommentsRe, commentsRe } from '@a-la/markers/build/lib' + +export const getMap = ({ + file, + originalSource, + pathToSrc, + sourceRoot, +}) => { + const gen = new SourceMapGenerator({ + file, + sourceRoot, + }) + const linesInSource = originalSource + .replace(commentsRe, (match, pos) => { + const next = originalSource[pos + match.length] + if (next == '\n') return '\n'.repeat(match.split('\n').length - 1) + + const lines = match.split('\n') + const lastLineI = lines.length - 1 + const lastLine = lines[lastLineI] + const ss = ' '.repeat(lastLine.length) + const ws = '\n'.repeat(lastLineI) + return `${ws}${ss}` + }) + .replace(inlineCommentsRe, (match) => { + return ' '.repeat(match.length) + }) + .split('\n') + linesInSource.forEach((l, i) => { + const line = i + 1 + l + .replace(/(?:(?:\s+)|(?:[$_\w\d]+)|.)/g, (match, column) => { + if (column == 0 && /^\s+$/.test(match)) return + const pp = { + line, + column, + } + const m = { + generated: pp, + source: pathToSrc, + original: pp, + } + gen.addMapping(m) + }) + }) + gen.setSourceContent(pathToSrc, originalSource) + const sourceMap = gen.toString() + return sourceMap +} + +export default function addSourceMap({ + source, outputDir, name, destination, file, originalSource, +}) { + const pathToSrc = relative(outputDir, source) + + const map = getMap({ + file, originalSource, pathToSrc, + }) + + const sourceMapName = `${name}.map` + const comment = `\n%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% + appendFileSync(destination, comment) + + const sourceMapPath = join(outputDir, sourceMapName) + writeFileSync(sourceMapPath, map) +} +123 +123 +import { Replaceable } from 'restream' +import makeRules, { makeAdvancedRules } from '@a-la/markers' +import ALaImport, { advancedSeq as advancedALaImport } from '@a-la/import' +import ALaExport, { advancedSeq as advancedALaExport } from '@a-la/export' +import whichStream from 'which-stream' +import Catchment from 'catchment' +import { createReadStream } from 'fs' +import { basename, dirname, join } from 'path' +import { getMap } from './source-map' + +const getConfig = () => { + let config = {} + try { + const r = join(process.cwd(), '.alamoderc.json') + config = require(r) + } catch (err) { + return config + } + const { env: { ALAMODE_ENV } } = process + const c = config.env && ALAMODE_ENV in config.env ? config.env[ALAMODE_ENV] : config + + delete c.env + + return c +} + +const getRules = (advanced) => { + const r = advanced ? [ + ...advancedALaImport, + ...advancedALaExport, + ] : [ + ...ALaImport, + ...ALaExport, + ] + const mr = advanced ? makeAdvancedRules : makeRules + const { rules, markers } = mr(r) + return { rules, markers } +} + +const makeReplaceable = (advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + + const replaceable = new Replaceable(rules) + replaceable.markers = markers + + replaceable.config = config + return replaceable +} + +%%_RESTREAM_COMMENTS_REPLACEMENT_0_%% +export const transformStream = async ({ + source, + destination, + writable, + advanced = false, +}) => { + const replaceable = makeReplaceable(advanced) + + const readable = createReadStream(source) + + readable.pipe(replaceable) + const { promise: sourcePromise } = new Catchment({ rs: readable }) + + const [,, sourceCode] = await Promise.all([ + whichStream({ + source, + ...(writable ? { writable } : { destination }), + readable: replaceable, + }), + new Promise((r, j) => { + replaceable.once('error', j) + replaceable.once('end', r) + }), + sourcePromise, + ]) + + return sourceCode +} + +class Context { + constructor(config, markers) { + this.listeners = {} + this.markers = markers + this.config = config + } + on(event, listener) { + this.listeners[event] = listener + } + emit(event, data) { + this.listeners[event](data) + } + get advanced() { + return this.config.advanced + } +} + +export const transformString = (source, advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + const context = new Context(config, markers) + + const replaced = rules.reduce((acc, { re, replacement }) => { + const newAcc = acc.replace(re, replacement.bind(context)) + return newAcc + }, source) + return replaced +} + +%%_RESTREAM_COMMENTS_REPLACEMENT_1_%% +export const syncTransform = (source, filename, advanced) => { + const replaced = transformString(source, advanced) + const file = basename(filename) + const sourceRoot = dirname(filename) + const map = getMap({ + originalSource: source, + pathToSrc: file, + sourceRoot, + }) + const b64 = Buffer.from(map).toString('base64') + const s = `%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% + + const code = `${replaced}\n${s}` + + return code +} +123 +123 +import usually from 'usually' + +export default () => { + const usage = usually({ + usage: { + source: `Location of the input to the transpiler, +either a directory or a file.`, + '--output, -o': `Location to save results to. Passing "-" +will print to stdout when source is a file.`, + '--help, -h': 'Display help information.', + '--version, -v': 'Show version.', + '--ignore, -i': `Paths to files to ignore, relative to the +source directory.`, + '--noSourceMaps, -s': 'Don\'t generate source maps.', + '--advanced, -a': `Attempt to skip statements inside of template +literals.`, + }, + description: 'A tool to transpile JavaScript packages using regular expressions.', + line: 'alamode source [-o destination]', + example: 'alamode src -o build', + }) + return usage +} +123 +123 +import argufy from 'argufy' +import restream, { + Replaceable, + makeMarkers, makeCutRule, makePasteRule, +} from 'restream' +import { resolve, join } from 'path' +import { version } from '../../package.json' +123 let argufy = require('argufy'); if (argufy && argufy.__esModule) argufy = argufy.default; let restream = require('restream'); if (restream && restream.__esModule) restream = restream.default; const { Replaceable, @@ -223,7 +657,436 @@ export { example2 as alias } ```js -async function example () {} +123 +#!/usr/bin/env node +import argufy from 'argufy' +import { version } from '../../package.json' +import catcher from './catcher' +import { transpile } from './transpile' +import getUsage from './usage' + +const { + input: _input, + output: _output, + version: _version, + help: _help, + ignore: _ignore, + noSourceMaps: _noSourceMaps, + advanced: _advanced, +} = argufy({ + input: { command: true }, + output: { short: 'o' }, + version: { short: 'v', boolean: true }, + help: { short: 'h', boolean: true }, + ignore: { short: 'i' }, + noSourceMaps: { short: 's', boolean: true }, + advanced: { short: 'a', boolean: true }, +}) + +if (_help) { + const usage = getUsage() + console.log(usage) + process.exit() +} else if (_version) { + console.log('v%s', version) + process.exit() +} + +(async () => { + try { + const ignore = _ignore ? _ignore.split(','): [] + await transpile({ + input: _input, + output: _output, + noSourceMaps: _noSourceMaps, + ignore, + advanced: _advanced, + }) + } catch (err) { + catcher(err) + } +})() +123 +123 +import { debuglog } from 'util' + +const LOG = debuglog('alamode') +const DEBUG = /alamode/.test(process.env.NODE_DEBUG) + +const catcher = (err) => { + let stack + let message + if (err instanceof Error) { + ({ stack, message } = err) + } else { + stack = message = err + } + DEBUG ? LOG(stack) : console.log(message) + process.exit(1) +} + +export default catcher +123 +123 +import { join, basename, dirname } from 'path' +import { lstatSync } from 'fs' +import readDirStructure from '@wrote/read-dir-structure' +import ensurePath from '@wrote/ensure-path' +import { debuglog } from 'util' +import { copyMode } from '../lib' +import writeSourceMap from '../lib/source-map' +import { transformStream } from '../lib/transform' + +const LOG = debuglog('alamode') + +const processFile = async ({ + input, relPath, name, output, ignore, noSourceMaps, advanced, +}) => { + const file = join(relPath, name) + if (ignore.includes(file)) return + + const isOutputStdout = output == '-' + const source = join(input, file) + + const outputDir = isOutputStdout ? null : join(output, relPath) + const destination = isOutputStdout ? '-' : join(outputDir, name) + LOG(file) + + await ensurePath(destination) + + const originalSource = await transformStream({ + source, + destination, + advanced, + }) + + if (output != '-') { + copyMode(source, destination) + if (noSourceMaps) return + writeSourceMap({ + destination, + file, + name, + outputDir, + source, + originalSource, + }) + } +} + +const processDir = async ({ + input, + output, + relPath = '.', + ignore = [], + noSourceMaps, + advanced, +}) => { + const path = join(input, relPath) + const { content } = await readDirStructure(path) + const k = Object.keys(content) + await k.reduce(async (acc, name) => { + await acc + const { type } = content[name] + if (type == 'File') { + await processFile({ + input, relPath, name, output, ignore, noSourceMaps, + }) + } else if (type == 'Directory') { + const newRelPath = join(relPath, name) + await processDir({ + input, + output, + ignore, + relPath: newRelPath, + noSourceMaps, + advanced, + }) + } + }, Promise.resolve()) +} + +export const transpile = async ({ + input, + output = '-', + ignore = [], + noSourceMaps, + advanced, +}) => { + if (!input) throw new Error('Please specify the source file or directory.') + + const ls = lstatSync(input) + if (ls.isDirectory()) { + if (!output) throw new Error('Please specify the output directory.') + await processDir({ + input, + output, + ignore, + noSourceMaps, + advanced, + }) + } else if (ls.isFile()) { + await processFile({ + input: dirname(input), + relPath: '.', + name: basename(input), + output, + ignore, + noSourceMaps, + advanced, + }) + } + if (output != '-') process.stdout.write(`Transpiled code saved to ${output}\n`) +} + +123 +123 +import { chmodSync, lstatSync } from 'fs' + +export const copyMode = (input, output) => { + const ls = lstatSync(input) + const { mode } = ls + chmodSync(output, mode) +} +123 +123 +import { relative, join } from 'path' +import { appendFileSync, writeFileSync } from 'fs' +import { SourceMapGenerator } from 'source-map' +import { inlineCommentsRe, commentsRe } from '@a-la/markers/build/lib' + +export const getMap = ({ + file, + originalSource, + pathToSrc, + sourceRoot, +}) => { + const gen = new SourceMapGenerator({ + file, + sourceRoot, + }) + const linesInSource = originalSource + .replace(commentsRe, (match, pos) => { + const next = originalSource[pos + match.length] + if (next == '\n') return '\n'.repeat(match.split('\n').length - 1) + + const lines = match.split('\n') + const lastLineI = lines.length - 1 + const lastLine = lines[lastLineI] + const ss = ' '.repeat(lastLine.length) + const ws = '\n'.repeat(lastLineI) + return `${ws}${ss}` + }) + .replace(inlineCommentsRe, (match) => { + return ' '.repeat(match.length) + }) + .split('\n') + linesInSource.forEach((l, i) => { + const line = i + 1 + l + .replace(/(?:(?:\s+)|(?:[$_\w\d]+)|.)/g, (match, column) => { + if (column == 0 && /^\s+$/.test(match)) return + const pp = { + line, + column, + } + const m = { + generated: pp, + source: pathToSrc, + original: pp, + } + gen.addMapping(m) + }) + }) + gen.setSourceContent(pathToSrc, originalSource) + const sourceMap = gen.toString() + return sourceMap +} + +export default function addSourceMap({ + source, outputDir, name, destination, file, originalSource, +}) { + const pathToSrc = relative(outputDir, source) + + const map = getMap({ + file, originalSource, pathToSrc, + }) + + const sourceMapName = `${name}.map` + const comment = `\n%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% + appendFileSync(destination, comment) + + const sourceMapPath = join(outputDir, sourceMapName) + writeFileSync(sourceMapPath, map) +} +123 +123 +import { Replaceable } from 'restream' +import makeRules, { makeAdvancedRules } from '@a-la/markers' +import ALaImport, { advancedSeq as advancedALaImport } from '@a-la/import' +import ALaExport, { advancedSeq as advancedALaExport } from '@a-la/export' +import whichStream from 'which-stream' +import Catchment from 'catchment' +import { createReadStream } from 'fs' +import { basename, dirname, join } from 'path' +import { getMap } from './source-map' + +const getConfig = () => { + let config = {} + try { + const r = join(process.cwd(), '.alamoderc.json') + config = require(r) + } catch (err) { + return config + } + const { env: { ALAMODE_ENV } } = process + const c = config.env && ALAMODE_ENV in config.env ? config.env[ALAMODE_ENV] : config + + delete c.env + + return c +} + +const getRules = (advanced) => { + const r = advanced ? [ + ...advancedALaImport, + ...advancedALaExport, + ] : [ + ...ALaImport, + ...ALaExport, + ] + const mr = advanced ? makeAdvancedRules : makeRules + const { rules, markers } = mr(r) + return { rules, markers } +} + +const makeReplaceable = (advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + + const replaceable = new Replaceable(rules) + replaceable.markers = markers + + replaceable.config = config + return replaceable +} + +%%_RESTREAM_COMMENTS_REPLACEMENT_0_%% +export const transformStream = async ({ + source, + destination, + writable, + advanced = false, +}) => { + const replaceable = makeReplaceable(advanced) + + const readable = createReadStream(source) + + readable.pipe(replaceable) + const { promise: sourcePromise } = new Catchment({ rs: readable }) + + const [,, sourceCode] = await Promise.all([ + whichStream({ + source, + ...(writable ? { writable } : { destination }), + readable: replaceable, + }), + new Promise((r, j) => { + replaceable.once('error', j) + replaceable.once('end', r) + }), + sourcePromise, + ]) + + return sourceCode +} + +class Context { + constructor(config, markers) { + this.listeners = {} + this.markers = markers + this.config = config + } + on(event, listener) { + this.listeners[event] = listener + } + emit(event, data) { + this.listeners[event](data) + } + get advanced() { + return this.config.advanced + } +} + +export const transformString = (source, advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + const context = new Context(config, markers) + + const replaced = rules.reduce((acc, { re, replacement }) => { + const newAcc = acc.replace(re, replacement.bind(context)) + return newAcc + }, source) + return replaced +} + +%%_RESTREAM_COMMENTS_REPLACEMENT_1_%% +export const syncTransform = (source, filename, advanced) => { + const replaced = transformString(source, advanced) + const file = basename(filename) + const sourceRoot = dirname(filename) + const map = getMap({ + originalSource: source, + pathToSrc: file, + sourceRoot, + }) + const b64 = Buffer.from(map).toString('base64') + const s = `%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% + + const code = `${replaced}\n${s}` + + return code +} +123 +123 +import usually from 'usually' + +export default () => { + const usage = usually({ + usage: { + source: `Location of the input to the transpiler, +either a directory or a file.`, + '--output, -o': `Location to save results to. Passing "-" +will print to stdout when source is a file.`, + '--help, -h': 'Display help information.', + '--version, -v': 'Show version.', + '--ignore, -i': `Paths to files to ignore, relative to the +source directory.`, + '--noSourceMaps, -s': 'Don\'t generate source maps.', + '--advanced, -a': `Attempt to skip statements inside of template +literals.`, + }, + description: 'A tool to transpile JavaScript packages using regular expressions.', + line: 'alamode source [-o destination]', + example: 'alamode src -o build', + }) + return usage +} +123 +123 +export async function example () {} + +const example2 = () => {} + +export default class Example { + constructor() { + example() + } +} + +export { example2 as alias } +123 + async function example () {} const example2 = () => {} @@ -247,6 +1110,974 @@ module.exports.alias = example2 There are some [limitations](https://github.com/a-la/export#limitations) one should be aware about, however they will not typically cause problems for a Node.JS package. The line and column numbers are preserved for easier generation of the source maps, however this is likely to change in the future. +### Advanced Mode + +Advanced mode is required when there are template strings inside of which `import` and `export` statements are found. To prevent them from participating in the transforms, `alamode` will cut them out first to stop transform regexes detecting statements inside of template literals, and then paste them back. + +```js +import helloWorld from 'hello-world' + +export const test = () => { + const res = helloWorld() + console.log(res) +} + +export { test2 } from 'test' + +const i = ` + import helloWorld from 'hello-world' +` +const e = ` + export { test } from 'test' +` +``` + +Without the advanced mode: + +```js +123 +#!/usr/bin/env node +import argufy from 'argufy' +import { version } from '../../package.json' +import catcher from './catcher' +import { transpile } from './transpile' +import getUsage from './usage' + +const { + input: _input, + output: _output, + version: _version, + help: _help, + ignore: _ignore, + noSourceMaps: _noSourceMaps, + advanced: _advanced, +} = argufy({ + input: { command: true }, + output: { short: 'o' }, + version: { short: 'v', boolean: true }, + help: { short: 'h', boolean: true }, + ignore: { short: 'i' }, + noSourceMaps: { short: 's', boolean: true }, + advanced: { short: 'a', boolean: true }, +}) + +if (_help) { + const usage = getUsage() + console.log(usage) + process.exit() +} else if (_version) { + console.log('v%s', version) + process.exit() +} + +(async () => { + try { + const ignore = _ignore ? _ignore.split(','): [] + await transpile({ + input: _input, + output: _output, + noSourceMaps: _noSourceMaps, + ignore, + advanced: _advanced, + }) + } catch (err) { + catcher(err) + } +})() +123 +123 +import { debuglog } from 'util' + +const LOG = debuglog('alamode') +const DEBUG = /alamode/.test(process.env.NODE_DEBUG) + +const catcher = (err) => { + let stack + let message + if (err instanceof Error) { + ({ stack, message } = err) + } else { + stack = message = err + } + DEBUG ? LOG(stack) : console.log(message) + process.exit(1) +} + +export default catcher +123 +123 +import { join, basename, dirname } from 'path' +import { lstatSync } from 'fs' +import readDirStructure from '@wrote/read-dir-structure' +import ensurePath from '@wrote/ensure-path' +import { debuglog } from 'util' +import { copyMode } from '../lib' +import writeSourceMap from '../lib/source-map' +import { transformStream } from '../lib/transform' + +const LOG = debuglog('alamode') + +const processFile = async ({ + input, relPath, name, output, ignore, noSourceMaps, advanced, +}) => { + const file = join(relPath, name) + if (ignore.includes(file)) return + + const isOutputStdout = output == '-' + const source = join(input, file) + + const outputDir = isOutputStdout ? null : join(output, relPath) + const destination = isOutputStdout ? '-' : join(outputDir, name) + LOG(file) + + await ensurePath(destination) + + const originalSource = await transformStream({ + source, + destination, + advanced, + }) + + if (output != '-') { + copyMode(source, destination) + if (noSourceMaps) return + writeSourceMap({ + destination, + file, + name, + outputDir, + source, + originalSource, + }) + } +} + +const processDir = async ({ + input, + output, + relPath = '.', + ignore = [], + noSourceMaps, + advanced, +}) => { + const path = join(input, relPath) + const { content } = await readDirStructure(path) + const k = Object.keys(content) + await k.reduce(async (acc, name) => { + await acc + const { type } = content[name] + if (type == 'File') { + await processFile({ + input, relPath, name, output, ignore, noSourceMaps, + }) + } else if (type == 'Directory') { + const newRelPath = join(relPath, name) + await processDir({ + input, + output, + ignore, + relPath: newRelPath, + noSourceMaps, + advanced, + }) + } + }, Promise.resolve()) +} + +export const transpile = async ({ + input, + output = '-', + ignore = [], + noSourceMaps, + advanced, +}) => { + if (!input) throw new Error('Please specify the source file or directory.') + + const ls = lstatSync(input) + if (ls.isDirectory()) { + if (!output) throw new Error('Please specify the output directory.') + await processDir({ + input, + output, + ignore, + noSourceMaps, + advanced, + }) + } else if (ls.isFile()) { + await processFile({ + input: dirname(input), + relPath: '.', + name: basename(input), + output, + ignore, + noSourceMaps, + advanced, + }) + } + if (output != '-') process.stdout.write(`Transpiled code saved to ${output}\n`) +} + +123 +123 +import { chmodSync, lstatSync } from 'fs' + +export const copyMode = (input, output) => { + const ls = lstatSync(input) + const { mode } = ls + chmodSync(output, mode) +} +123 +123 +import { relative, join } from 'path' +import { appendFileSync, writeFileSync } from 'fs' +import { SourceMapGenerator } from 'source-map' +import { inlineCommentsRe, commentsRe } from '@a-la/markers/build/lib' + +export const getMap = ({ + file, + originalSource, + pathToSrc, + sourceRoot, +}) => { + const gen = new SourceMapGenerator({ + file, + sourceRoot, + }) + const linesInSource = originalSource + .replace(commentsRe, (match, pos) => { + const next = originalSource[pos + match.length] + if (next == '\n') return '\n'.repeat(match.split('\n').length - 1) + + const lines = match.split('\n') + const lastLineI = lines.length - 1 + const lastLine = lines[lastLineI] + const ss = ' '.repeat(lastLine.length) + const ws = '\n'.repeat(lastLineI) + return `${ws}${ss}` + }) + .replace(inlineCommentsRe, (match) => { + return ' '.repeat(match.length) + }) + .split('\n') + linesInSource.forEach((l, i) => { + const line = i + 1 + l + .replace(/(?:(?:\s+)|(?:[$_\w\d]+)|.)/g, (match, column) => { + if (column == 0 && /^\s+$/.test(match)) return + const pp = { + line, + column, + } + const m = { + generated: pp, + source: pathToSrc, + original: pp, + } + gen.addMapping(m) + }) + }) + gen.setSourceContent(pathToSrc, originalSource) + const sourceMap = gen.toString() + return sourceMap +} + +export default function addSourceMap({ + source, outputDir, name, destination, file, originalSource, +}) { + const pathToSrc = relative(outputDir, source) + + const map = getMap({ + file, originalSource, pathToSrc, + }) + + const sourceMapName = `${name}.map` + const comment = `\n%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% + appendFileSync(destination, comment) + + const sourceMapPath = join(outputDir, sourceMapName) + writeFileSync(sourceMapPath, map) +} +123 +123 +import { Replaceable } from 'restream' +import makeRules, { makeAdvancedRules } from '@a-la/markers' +import ALaImport, { advancedSeq as advancedALaImport } from '@a-la/import' +import ALaExport, { advancedSeq as advancedALaExport } from '@a-la/export' +import whichStream from 'which-stream' +import Catchment from 'catchment' +import { createReadStream } from 'fs' +import { basename, dirname, join } from 'path' +import { getMap } from './source-map' + +const getConfig = () => { + let config = {} + try { + const r = join(process.cwd(), '.alamoderc.json') + config = require(r) + } catch (err) { + return config + } + const { env: { ALAMODE_ENV } } = process + const c = config.env && ALAMODE_ENV in config.env ? config.env[ALAMODE_ENV] : config + + delete c.env + + return c +} + +const getRules = (advanced) => { + const r = advanced ? [ + ...advancedALaImport, + ...advancedALaExport, + ] : [ + ...ALaImport, + ...ALaExport, + ] + const mr = advanced ? makeAdvancedRules : makeRules + const { rules, markers } = mr(r) + return { rules, markers } +} + +const makeReplaceable = (advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + + const replaceable = new Replaceable(rules) + replaceable.markers = markers + + replaceable.config = config + return replaceable +} + +%%_RESTREAM_COMMENTS_REPLACEMENT_0_%% +export const transformStream = async ({ + source, + destination, + writable, + advanced = false, +}) => { + const replaceable = makeReplaceable(advanced) + + const readable = createReadStream(source) + + readable.pipe(replaceable) + const { promise: sourcePromise } = new Catchment({ rs: readable }) + + const [,, sourceCode] = await Promise.all([ + whichStream({ + source, + ...(writable ? { writable } : { destination }), + readable: replaceable, + }), + new Promise((r, j) => { + replaceable.once('error', j) + replaceable.once('end', r) + }), + sourcePromise, + ]) + + return sourceCode +} + +class Context { + constructor(config, markers) { + this.listeners = {} + this.markers = markers + this.config = config + } + on(event, listener) { + this.listeners[event] = listener + } + emit(event, data) { + this.listeners[event](data) + } + get advanced() { + return this.config.advanced + } +} + +export const transformString = (source, advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + const context = new Context(config, markers) + + const replaced = rules.reduce((acc, { re, replacement }) => { + const newAcc = acc.replace(re, replacement.bind(context)) + return newAcc + }, source) + return replaced +} + +%%_RESTREAM_COMMENTS_REPLACEMENT_1_%% +export const syncTransform = (source, filename, advanced) => { + const replaced = transformString(source, advanced) + const file = basename(filename) + const sourceRoot = dirname(filename) + const map = getMap({ + originalSource: source, + pathToSrc: file, + sourceRoot, + }) + const b64 = Buffer.from(map).toString('base64') + const s = `%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% + + const code = `${replaced}\n${s}` + + return code +} +123 +123 +import usually from 'usually' + +export default () => { + const usage = usually({ + usage: { + source: `Location of the input to the transpiler, +either a directory or a file.`, + '--output, -o': `Location to save results to. Passing "-" +will print to stdout when source is a file.`, + '--help, -h': 'Display help information.', + '--version, -v': 'Show version.', + '--ignore, -i': `Paths to files to ignore, relative to the +source directory.`, + '--noSourceMaps, -s': 'Don\'t generate source maps.', + '--advanced, -a': `Attempt to skip statements inside of template +literals.`, + }, + description: 'A tool to transpile JavaScript packages using regular expressions.', + line: 'alamode source [-o destination]', + example: 'alamode src -o build', + }) + return usage +} +123 +123 +import helloWorld from 'hello-world' + +export const test = () => { + const res = helloWorld() + console.log(res) +} + +export { test2 } from 'test' + +const i = ` + import helloWorld from 'hello-world' +` +const e = ` + export { test } from 'test' +` +123 +let helloWorld = require('hello-world'); if (helloWorld && helloWorld.__esModule) helloWorld = helloWorld.default; + + const test = () => { + const res = helloWorld() + console.log(res) +} + +const $test = require('test'); + +const i = ` +let helloWorld = require('hello-world'); if (helloWorld && helloWorld.__esModule) helloWorld = helloWorld.default; +` +const e = ` +const $test = require('test'); +` + +module.exports.test = $test.test +module.exports.test2 = $test.test2 +``` + +With the advanced mode: + +```js +123 +#!/usr/bin/env node +import argufy from 'argufy' +import { version } from '../../package.json' +import catcher from './catcher' +import { transpile } from './transpile' +import getUsage from './usage' + +const { + input: _input, + output: _output, + version: _version, + help: _help, + ignore: _ignore, + noSourceMaps: _noSourceMaps, + advanced: _advanced, +} = argufy({ + input: { command: true }, + output: { short: 'o' }, + version: { short: 'v', boolean: true }, + help: { short: 'h', boolean: true }, + ignore: { short: 'i' }, + noSourceMaps: { short: 's', boolean: true }, + advanced: { short: 'a', boolean: true }, +}) + +if (_help) { + const usage = getUsage() + console.log(usage) + process.exit() +} else if (_version) { + console.log('v%s', version) + process.exit() +} + +(async () => { + try { + const ignore = _ignore ? _ignore.split(','): [] + await transpile({ + input: _input, + output: _output, + noSourceMaps: _noSourceMaps, + ignore, + advanced: _advanced, + }) + } catch (err) { + catcher(err) + } +})() +123 +123 +import { debuglog } from 'util' + +const LOG = debuglog('alamode') +const DEBUG = /alamode/.test(process.env.NODE_DEBUG) + +const catcher = (err) => { + let stack + let message + if (err instanceof Error) { + ({ stack, message } = err) + } else { + stack = message = err + } + DEBUG ? LOG(stack) : console.log(message) + process.exit(1) +} + +export default catcher +123 +123 +import { join, basename, dirname } from 'path' +import { lstatSync } from 'fs' +import readDirStructure from '@wrote/read-dir-structure' +import ensurePath from '@wrote/ensure-path' +import { debuglog } from 'util' +import { copyMode } from '../lib' +import writeSourceMap from '../lib/source-map' +import { transformStream } from '../lib/transform' + +const LOG = debuglog('alamode') + +const processFile = async ({ + input, relPath, name, output, ignore, noSourceMaps, advanced, +}) => { + const file = join(relPath, name) + if (ignore.includes(file)) return + + const isOutputStdout = output == '-' + const source = join(input, file) + + const outputDir = isOutputStdout ? null : join(output, relPath) + const destination = isOutputStdout ? '-' : join(outputDir, name) + LOG(file) + + await ensurePath(destination) + + const originalSource = await transformStream({ + source, + destination, + advanced, + }) + + if (output != '-') { + copyMode(source, destination) + if (noSourceMaps) return + writeSourceMap({ + destination, + file, + name, + outputDir, + source, + originalSource, + }) + } +} + +const processDir = async ({ + input, + output, + relPath = '.', + ignore = [], + noSourceMaps, + advanced, +}) => { + const path = join(input, relPath) + const { content } = await readDirStructure(path) + const k = Object.keys(content) + await k.reduce(async (acc, name) => { + await acc + const { type } = content[name] + if (type == 'File') { + await processFile({ + input, relPath, name, output, ignore, noSourceMaps, + }) + } else if (type == 'Directory') { + const newRelPath = join(relPath, name) + await processDir({ + input, + output, + ignore, + relPath: newRelPath, + noSourceMaps, + advanced, + }) + } + }, Promise.resolve()) +} + +export const transpile = async ({ + input, + output = '-', + ignore = [], + noSourceMaps, + advanced, +}) => { + if (!input) throw new Error('Please specify the source file or directory.') + + const ls = lstatSync(input) + if (ls.isDirectory()) { + if (!output) throw new Error('Please specify the output directory.') + await processDir({ + input, + output, + ignore, + noSourceMaps, + advanced, + }) + } else if (ls.isFile()) { + await processFile({ + input: dirname(input), + relPath: '.', + name: basename(input), + output, + ignore, + noSourceMaps, + advanced, + }) + } + if (output != '-') process.stdout.write(`Transpiled code saved to ${output}\n`) +} + +123 +123 +import { chmodSync, lstatSync } from 'fs' + +export const copyMode = (input, output) => { + const ls = lstatSync(input) + const { mode } = ls + chmodSync(output, mode) +} +123 +123 +import { relative, join } from 'path' +import { appendFileSync, writeFileSync } from 'fs' +import { SourceMapGenerator } from 'source-map' +import { inlineCommentsRe, commentsRe } from '@a-la/markers/build/lib' + +export const getMap = ({ + file, + originalSource, + pathToSrc, + sourceRoot, +}) => { + const gen = new SourceMapGenerator({ + file, + sourceRoot, + }) + const linesInSource = originalSource + .replace(commentsRe, (match, pos) => { + const next = originalSource[pos + match.length] + if (next == '\n') return '\n'.repeat(match.split('\n').length - 1) + + const lines = match.split('\n') + const lastLineI = lines.length - 1 + const lastLine = lines[lastLineI] + const ss = ' '.repeat(lastLine.length) + const ws = '\n'.repeat(lastLineI) + return `${ws}${ss}` + }) + .replace(inlineCommentsRe, (match) => { + return ' '.repeat(match.length) + }) + .split('\n') + linesInSource.forEach((l, i) => { + const line = i + 1 + l + .replace(/(?:(?:\s+)|(?:[$_\w\d]+)|.)/g, (match, column) => { + if (column == 0 && /^\s+$/.test(match)) return + const pp = { + line, + column, + } + const m = { + generated: pp, + source: pathToSrc, + original: pp, + } + gen.addMapping(m) + }) + }) + gen.setSourceContent(pathToSrc, originalSource) + const sourceMap = gen.toString() + return sourceMap +} + +export default function addSourceMap({ + source, outputDir, name, destination, file, originalSource, +}) { + const pathToSrc = relative(outputDir, source) + + const map = getMap({ + file, originalSource, pathToSrc, + }) + + const sourceMapName = `${name}.map` + const comment = `\n%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% + appendFileSync(destination, comment) + + const sourceMapPath = join(outputDir, sourceMapName) + writeFileSync(sourceMapPath, map) +} +123 +123 +import { Replaceable } from 'restream' +import makeRules, { makeAdvancedRules } from '@a-la/markers' +import ALaImport, { advancedSeq as advancedALaImport } from '@a-la/import' +import ALaExport, { advancedSeq as advancedALaExport } from '@a-la/export' +import whichStream from 'which-stream' +import Catchment from 'catchment' +import { createReadStream } from 'fs' +import { basename, dirname, join } from 'path' +import { getMap } from './source-map' + +const getConfig = () => { + let config = {} + try { + const r = join(process.cwd(), '.alamoderc.json') + config = require(r) + } catch (err) { + return config + } + const { env: { ALAMODE_ENV } } = process + const c = config.env && ALAMODE_ENV in config.env ? config.env[ALAMODE_ENV] : config + + delete c.env + + return c +} + +const getRules = (advanced) => { + const r = advanced ? [ + ...advancedALaImport, + ...advancedALaExport, + ] : [ + ...ALaImport, + ...ALaExport, + ] + const mr = advanced ? makeAdvancedRules : makeRules + const { rules, markers } = mr(r) + return { rules, markers } +} + +const makeReplaceable = (advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + + const replaceable = new Replaceable(rules) + replaceable.markers = markers + + replaceable.config = config + return replaceable +} + +%%_RESTREAM_COMMENTS_REPLACEMENT_0_%% +export const transformStream = async ({ + source, + destination, + writable, + advanced = false, +}) => { + const replaceable = makeReplaceable(advanced) + + const readable = createReadStream(source) + + readable.pipe(replaceable) + const { promise: sourcePromise } = new Catchment({ rs: readable }) + + const [,, sourceCode] = await Promise.all([ + whichStream({ + source, + ...(writable ? { writable } : { destination }), + readable: replaceable, + }), + new Promise((r, j) => { + replaceable.once('error', j) + replaceable.once('end', r) + }), + sourcePromise, + ]) + + return sourceCode +} + +class Context { + constructor(config, markers) { + this.listeners = {} + this.markers = markers + this.config = config + } + on(event, listener) { + this.listeners[event] = listener + } + emit(event, data) { + this.listeners[event](data) + } + get advanced() { + return this.config.advanced + } +} + +export const transformString = (source, advanced) => { + const config = getConfig() + const { rules, markers } = getRules(config.advanced || advanced) + const context = new Context(config, markers) + + const replaced = rules.reduce((acc, { re, replacement }) => { + const newAcc = acc.replace(re, replacement.bind(context)) + return newAcc + }, source) + return replaced +} + +%%_RESTREAM_COMMENTS_REPLACEMENT_1_%% +export const syncTransform = (source, filename, advanced) => { + const replaced = transformString(source, advanced) + const file = basename(filename) + const sourceRoot = dirname(filename) + const map = getMap({ + originalSource: source, + pathToSrc: file, + sourceRoot, + }) + const b64 = Buffer.from(map).toString('base64') + const s = `%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% + + const code = `${replaced}\n${s}` + + return code +} +123 +123 +import usually from 'usually' + +export default () => { + const usage = usually({ + usage: { + source: `Location of the input to the transpiler, +either a directory or a file.`, + '--output, -o': `Location to save results to. Passing "-" +will print to stdout when source is a file.`, + '--help, -h': 'Display help information.', + '--version, -v': 'Show version.', + '--ignore, -i': `Paths to files to ignore, relative to the +source directory.`, + '--noSourceMaps, -s': 'Don\'t generate source maps.', + '--advanced, -a': `Attempt to skip statements inside of template +literals.`, + }, + description: 'A tool to transpile JavaScript packages using regular expressions.', + line: 'alamode source [-o destination]', + example: 'alamode src -o build', + }) + return usage +} +123 +let helloWorld = require('hello-world'); if (helloWorld && helloWorld.__esModule) helloWorld = helloWorld.default; + + const test = () => { + const res = helloWorld() + console.log(res) +} + +const $test = require('test'); + +const i = ` + import helloWorld from 'hello-world' +` +const e = ` + export { test } from 'test' +` + +module.exports.test = test +module.exports.test2 = $test.test2 +``` + +However, this option is not perfect, and + + + +If it was the other way around (with template literals being detected first), e.g., + +```js +const bool = false +const url = 'test' +/* A path to an example ` */ +const t = 'https://example.com' +export const t +/* A path to the test ` */ +const t2 = 'https://test.org' +``` + +there still would be a problem, as the same logic would apply to stripping everything between 2 \`s. This shows that `alamode` is not very robust because it does not build an AST, and can work for many simpler cases. Most of the time, there would be no need to write `export` and `import` statements in the template literals where they receive a dedicated line. +## Modes + +Any block comments are stripped by default, to prevent issues such as detecting `import` and `export` statements inside of examples, e.g., + +```js +/** + * Use this method to show an example usage. + * @example + * + * import { example } from './example' + * + * example() + */ +export const example = () => console.log('example') +``` + +However, this might backfire and prevent the program from being transpiled correctly when block comments are incorrectly deduced, e.g., + +```js +const t = `https://example.com/*` +export default t +const t2 = `https://example.com/*/test` +export { t2 } +``` + +The above will not work because `/* */` is used to strip out comments before detecting template literals, and in the example it is included in 2 distinct template literals, so that the code with the `export` statement in-between is temporarily removed and does not participate in transforms. + +The string which will reach the transforms therefore will be: + +```js +const t = `https:%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% +export { t2 } +``` +## ## Require Hook The purpose of the require hook is to be able to run transpile files automatically when they are imported. @@ -304,6 +2135,18 @@ require('.') By executing the `node require.js` command, `alamode` will be installed and it will do its job dynamically for every `.js` file that is required, enabling to use `import` and `export` statements. ``` +123 +import getInfo from './lib' + +console.log(getInfo()) +123 +123 +import { platform, arch } from 'os' + +export default () => { + return `${platform()}:${arch()}` +} +123 darwin:x64 ``` diff --git a/documentary/3-CLI/index.md b/documentary/3-CLI/index.md index 80f9000..f1f66ca 100644 --- a/documentary/3-CLI/index.md +++ b/documentary/3-CLI/index.md @@ -16,7 +16,8 @@ There are other arguments which can be passed. ["[Watch Mode](t)", "`-w`, `--watch`", "Keep `alamode` running and re-build on chages."], ["[Show Help](t)", "`-h`, `--help`", "Display help information and quit."], ["[Ignore Paths](t)", "`-i`, `--ignore`", "A list of files inside of the source directory to ignore, separated with a comma. For example, to ignore `src/bin/alamode.js` when building `src`, the `-i bin/alamode.js` should be passed"], - ["[No Source Maps](t)", "`-s`, `--noSourceMaps`", "Don't generate source maps."] + ["[No Source Maps](t)", "`-s`, `--noSourceMaps`", "Don't generate source maps."], + ["[Advanced](t)", "`-a`, `--advanced`", "Attempt to exclude template strings from participating in transforms. [See more](#advanced-mode)."] ] ``` diff --git a/documentary/4-tranforms/footer.md b/documentary/4-tranforms/footer.md new file mode 100644 index 0000000..eeb8a90 --- /dev/null +++ b/documentary/4-tranforms/footer.md @@ -0,0 +1,32 @@ + +### Advanced Mode + +Advanced mode is required when there are template strings inside of which `import` and `export` statements are found. To prevent them from participating in the transforms, `alamode` will cut them out first to stop transform regexes detecting statements inside of template literals, and then paste them back. + +%EXAMPLE: example/advanced.js% + +Without the advanced mode: + +%FORK-js src/bin/alamode example/advanced.js% + +With the advanced mode: + +%FORK-js src/bin/alamode example/advanced.js -a% + +However, this option is not perfect, and + + + +If it was the other way around (with template literals being detected first), e.g., + +```js +const bool = false +const url = 'test' +/* A path to an example ` */ +const t = 'https://example.com' +export const t +/* A path to the test ` */ +const t2 = 'https://test.org' +``` + +there still would be a problem, as the same logic would apply to stripping everything between 2 \`s. This shows that `alamode` is not very robust because it does not build an AST, and can work for many simpler cases. Most of the time, there would be no need to write `export` and `import` statements in the template literals where they receive a dedicated line. \ No newline at end of file diff --git a/documentary/4-tranforms/index.md b/documentary/4-tranforms/index.md index 0c7f4cb..55b04e2 100644 --- a/documentary/4-tranforms/index.md +++ b/documentary/4-tranforms/index.md @@ -18,6 +18,10 @@ A transform can support options which can be set in the `.alamoderc.json` config } ``` +### `advanced` + +When set in the `.alamoderc`, the `advanced` option will make transforms run in the [advanced mode](#advanced-mode). + ## Transforms There are a number of built-in transforms, which don't need to be installed separately because their size is small enough to be included as direct dependencies. diff --git a/documentary/5-modes/1-comments.md b/documentary/5-modes/1-comments.md new file mode 100644 index 0000000..4a2af8d --- /dev/null +++ b/documentary/5-modes/1-comments.md @@ -0,0 +1,2 @@ + +## \ No newline at end of file diff --git a/documentary/5-modes/index.md b/documentary/5-modes/index.md new file mode 100644 index 0000000..fb4c8ab --- /dev/null +++ b/documentary/5-modes/index.md @@ -0,0 +1,19 @@ + +## Modes + +Any block comments are stripped by default, to prevent issues such as detecting `import` and `export` statements inside of examples, e.g., + +%EXAMPLE: example/modes/comments.js% + +However, this might backfire and prevent the program from being transpiled correctly when block comments are incorrectly deduced, e.g., + +%EXAMPLE: example/modes/comments-incorrect.js% + +The above will not work because `/* */` is used to strip out comments before detecting template literals, and in the example it is included in 2 distinct template literals, so that the code with the `export` statement in-between is temporarily removed and does not participate in transforms. + +The string which will reach the transforms therefore will be: + +```js +const t = `https:%%_RESTREAM_INLINECOMMENTS_REPLACEMENT_0_%% +export { t2 } +``` \ No newline at end of file From e429c9b6b361ed979ecd49fc701a9174855ffca4 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 14 Sep 2018 22:54:50 +0300 Subject: [PATCH 13/13] stash --- .vscode/launch.json | 6 ++++ example/advanced.js | 15 +++++++++ example/modes/comments-incorrect.js | 4 +++ example/modes/comments.js | 9 ++++++ t.js | 50 +++++++++++++++++++++++++++++ t2.js | 8 +++++ 6 files changed, 92 insertions(+) create mode 100644 example/advanced.js create mode 100644 example/modes/comments-incorrect.js create mode 100644 example/modes/comments.js create mode 100644 t.js create mode 100644 t2.js diff --git a/.vscode/launch.json b/.vscode/launch.json index 952fdf3..d9271af 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,12 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Launch t", + "program": "${workspaceFolder}/t.js" + }, { "type": "node", "request": "launch", diff --git a/example/advanced.js b/example/advanced.js new file mode 100644 index 0000000..df10563 --- /dev/null +++ b/example/advanced.js @@ -0,0 +1,15 @@ +import helloWorld from 'hello-world' + +export const test = () => { + const res = helloWorld() + console.log(res) +} + +export { test2 } from 'test' + +const i = ` + import helloWorld from 'hello-world' +` +const e = ` + export { test } from 'test' +` \ No newline at end of file diff --git a/example/modes/comments-incorrect.js b/example/modes/comments-incorrect.js new file mode 100644 index 0000000..76c180f --- /dev/null +++ b/example/modes/comments-incorrect.js @@ -0,0 +1,4 @@ +const t = `https://example.com/*` +export default t +const t2 = `https://example.com/*/test` +export { t2 } \ No newline at end of file diff --git a/example/modes/comments.js b/example/modes/comments.js new file mode 100644 index 0000000..1dc6b65 --- /dev/null +++ b/example/modes/comments.js @@ -0,0 +1,9 @@ +/** + * Use this method to show an example usage. + * @example + * + * import { example } from './example' + * + * example() + */ +export const example = () => console.log('example') \ No newline at end of file diff --git a/t.js b/t.js new file mode 100644 index 0000000..98a71d7 --- /dev/null +++ b/t.js @@ -0,0 +1,50 @@ +const { addHook } = require('pirates') +const { Script } = require('vm') + +const accepted = [ + 'Unexpected token export', + 'Unexpected token import', +] + +// https://stackoverflow.com/questions/14480345/how-to-get-the-nth-occurrence-in-a-string +function nthIndex(str, pat, n) { + var L = str.length, i = -1 + while (n-- && i++ < L) { + i = str.indexOf(pat, i) + if (i < 0) break + } + return i +} + +const compile = (source, filename) => { + try { + const res = new Script(source, { + filename, + }) + return res + } catch (err) { + const isAccepted = accepted.includes(err.message) + if (!isAccepted) throw err + + const lines = err.stack.split('\n', 3) + /** @type {string} */ + const [line,, line3] = lines + const ln = parseInt(line.substr(filename.length + 1)) + const col = line3.indexOf('^') + const n = nthIndex(source, '\n', ln - 1) + const nn = n + col + 1 + const sub = source.substr(nn) + // substitute now + console.log(sub) + debugger + } +} + +// const m = Module +addHook( + /** @param {string} source */ + (source, filename) => { + + }, { exts: ['.js'] }) +require('./t2') +debugger \ No newline at end of file diff --git a/t2.js b/t2.js new file mode 100644 index 0000000..e2b8e74 --- /dev/null +++ b/t2.js @@ -0,0 +1,8 @@ +const { join } = require('path') + +console.log(123) + +/* test */ export { + join +} +// import { resolve } from 'path' \ No newline at end of file