UNPKG

2 kBtext/coffeescriptView Raw
1# import dd from 'ddeyes'
2import path from 'path'
3import fs from 'fs'
4
5import * as babylon from 'babylon'
6import traverse from '@babel/traverse'
7import generator from '@babel/generator'
8import * as t from '@babel/types'
9import transform from 'cfx.babel'
10
11# real coffee file Path
12rCFPath = (filePath) =>
13
14 getFileObj = (file) => {
15 exists: fs.existsSync file
16 (path.parse file)...
17 }
18
19 fileObj = getFileObj filePath
20
21 unless fileObj.exists # file isnt exists
22
23 fileObj =
24
25 coffee: do =>
26
27 _path = path.format
28 root: path.join fileObj.root, fileObj.dir + '/'
29 name: fileObj.base
30 ext: '.coffee'
31
32 path: _path
33 obj: getFileObj _path
34
35 js: do =>
36
37 _path = path.format
38 root: path.join fileObj.root, fileObj.dir + '/'
39 name: fileObj.base
40 ext: '.js'
41
42 path: _path
43 obj: getFileObj _path
44
45 if fileObj.coffee.obj.exists
46 return rCFPath fileObj.coffee.path
47 if fileObj.js.obj.exists
48 return rCFPath fileObj.js.path
49 return null
50
51 else # file exists
52
53 unless fileObj.ext is '' # isnt dir
54 then return filePath
55 else return rCFPath path.join filePath, 'index.coffee'
56
57# replace import coffee file from AST
58ricffAST = (ast, dirname = __dirname) =>
59
60 traverse ast
61 ,
62 ImportDeclaration: (_ast) =>
63
64 currentNode = _ast.node
65
66 fileParseObj = path.parse currentNode.source.value
67
68 return if (
69 fileParseObj.root is '' and
70 fileParseObj.dir is ''
71 )
72
73 filePath = rCFPath path.join dirname
74 , currentNode.source.value
75
76 _ast.node.source = t.StringLiteral filePath if filePath?
77
78 return
79
80 ast
81
82getAST = (source) =>
83
84 babylon.parse source
85 ,
86 sourceType: 'module'
87 plugins: [
88 'objectRestSpread'
89 'asyncGenerators'
90 ]
91
92ASTToCode = (ast, es = true, opts) =>
93 if es is false
94 then transform ast, opts
95 else ( generator ast ).code
96
97export {
98 rCFPath
99 ricffAST
100 getAST
101 ASTToCode
102}