Debian Codegraph @

charcodes/packages/babel-plugin-transform-charcodes/src/index.js

raw
1 import * as charcodes from "charcodes";
2 import { parse } from "@babel/parser";
3 import traverse from '@babel/traverse';
4
5 type ast = Object
6
7 export default function (babel) {
8 const { types: t } = babel;
9
10 function parseFunctionSource(str: string): ast {
11 const root = parse(str, {
12 sourceType: 'script',
13 })
14
15 return root.program.body[0];
16 }
17
18 function createInlineFunction(func: ast, id: ast): ast {
19
20 traverse(func, {
21 noScope: true,
22
23 Identifier(path) {
24 const name = path.node.name
25
26 if (typeof charcodes[name] !== "undefined" && typeof charcodes[name] !== "function") {
27 path.replaceWith(t.NumericLiteral(charcodes[name]))
28 }
29 }
30 })
31
32 return t.variableDeclaration(
33 'var',
34 [t.variableDeclarator(
35 id,
36 t.toExpression(func),
37 )]
38 )
39 }
40
41 return {
42
43 visitor: {
44
45 ImportDeclaration(path, state) {
46
47 if (path.node.source.value === "charcodes") {
48 state.importedLocalName = path.node.specifiers[0].local.name
49
50 // We remove the import just in case
51 path.remove()
52 }
53 },
54
55 MemberExpression(path, state) {
56 if (typeof state.importedLocalName !== "undefined" && path.node.object.name == state.importedLocalName) {
57 const rightName = path.node.property.name
58 const charCodeValue = charcodes[rightName]
59
60 if (typeof charCodeValue === "undefined") {
61 throw new Error("unknown key " + rightName)
62 } else if (typeof charCodeValue !== "function") {
63 path.replaceWith(t.NumericLiteral(charCodeValue))
64 } else {
65 const fn = parseFunctionSource(charCodeValue.toString())
66 const id = path.scope.generateUidIdentifier(rightName)
67
68 state._toHoist.push(createInlineFunction(fn, id))
69
70 path.replaceWith(id)
71 }
72 }
73 },
74
75 Program: {
76 enter(path, state) {
77 state._toHoist = [];
78 },
79
80 exit(path, state) {
81 state._toHoist.forEach(x => {
82 path.node.body.unshift(x)
83 })
84 }
85 }
86 }
87
88 };
89 }