UNPKG

2.95 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('path'), require('@babel/template')) :
3 typeof define === 'function' && define.amd ? define(['path', '@babel/template'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global["jotaiPlugin-debug-label"] = factory(global.path, global._templateBuilder));
5})(this, (function (path, _templateBuilder) { 'use strict';
6
7 function isAtom(t, callee, customAtomNames) {
8 if (customAtomNames === void 0) {
9 customAtomNames = [];
10 }
11 var atomNames = [].concat(atomFunctionNames, customAtomNames);
12 if (t.isIdentifier(callee) && atomNames.includes(callee.name)) {
13 return true;
14 }
15 if (t.isMemberExpression(callee)) {
16 var property = callee.property;
17 if (t.isIdentifier(property) && atomNames.includes(property.name)) {
18 return true;
19 }
20 }
21 return false;
22 }
23 var atomFunctionNames = ['abortableAtom', 'atom', 'atomFamily', 'atomWithDefault', 'atomWithHash', 'atomWithImmer', 'atomWithInfiniteQuery', 'atomWithMachine', 'atomWithMutation', 'atomWithObservable', 'atomWithProxy', 'atomWithQuery', 'atomWithReducer', 'atomWithReset', 'atomWithSubscription', 'atomWithStorage', 'atomWithStore', 'freezeAtom', 'loadable', 'selectAtom', 'splitAtom'];
24
25 var templateBuilder = _templateBuilder.default || _templateBuilder;
26 function debugLabelPlugin(_ref, options) {
27 var t = _ref.types;
28 return {
29 visitor: {
30 ExportDefaultDeclaration: function ExportDefaultDeclaration(nodePath, state) {
31 var node = nodePath.node;
32 if (t.isCallExpression(node.declaration) && isAtom(t, node.declaration.callee, options == null ? void 0 : options.customAtomNames)) {
33 var filename = state.filename || 'unknown';
34 var displayName = path.basename(filename, path.extname(filename));
35 if (displayName === 'index') {
36 displayName = path.basename(path.dirname(filename));
37 }
38 var buildExport = templateBuilder("\n const %%atomIdentifier%% = %%atom%%;\n export default %%atomIdentifier%%\n ");
39 var ast = buildExport({
40 atomIdentifier: t.identifier(displayName),
41 atom: node.declaration
42 });
43 nodePath.replaceWithMultiple(ast);
44 }
45 },
46 VariableDeclarator: function VariableDeclarator(path) {
47 if (t.isIdentifier(path.node.id) && t.isCallExpression(path.node.init) && isAtom(t, path.node.init.callee, options == null ? void 0 : options.customAtomNames)) {
48 path.parentPath.insertAfter(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(path.node.id.name), t.identifier('debugLabel')), t.stringLiteral(path.node.id.name))));
49 }
50 }
51 }
52 };
53 }
54
55 return debugLabelPlugin;
56
57}));