UNPKG

3.04 kBJavaScriptView Raw
1!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("path"),require("@babel/template")):"function"==typeof define&&define.amd?define(["exports","path","@babel/template"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).jotaiPreset={},e.path,e.templateBuilder)}(this,(function(e,t,a){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=i(t),r=i(a);function o(e,t){if(e.isIdentifier(t)&&l.includes(t.name))return!0;if(e.isMemberExpression(t)){var a=t.property;if(e.isIdentifier(a)&&l.includes(a.name))return!0}return!1}var l=["atom","atomFamily","atomWithDefault","atomWithObservable","atomWithReducer","atomWithReset","atomWithStorage","freezeAtom","loadable","selectAtom","splitAtom"];function s(e){var t=e.types;return{visitor:{ExportDefaultDeclaration:function(e,a){var i=e.node;if(t.isCallExpression(i.declaration)&&o(t,i.declaration.callee)){var l=a.filename||"unknown",s=n.default.basename(l,n.default.extname(l));"index"===s&&(s=n.default.basename(n.default.dirname(l)));var d=r.default("\n const %%atomIdentifier%% = %%atom%%;\n export default %%atomIdentifier%%\n ")({atomIdentifier:t.identifier(s),atom:i.declaration});e.replaceWithMultiple(d)}},VariableDeclarator:function(e){t.isIdentifier(e.node.id)&&t.isCallExpression(e.node.init)&&o(t,e.node.init.callee)&&e.parentPath.insertAfter(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(e.node.id.name),t.identifier("debugLabel")),t.stringLiteral(e.node.id.name))))}}}}function d(e){var t=e.types;return{pre:function(e){if(!e.opts.filename)throw new Error("Filename must be available")},visitor:{Program:{exit:function(e){var t=r.default("\n globalThis.jotaiAtomCache = globalThis.jotaiAtomCache || {\n cache: new Map(),\n get(name, inst) { \n if (this.cache.has(name)) {\n return this.cache.get(name)\n }\n this.cache.set(name, inst)\n return inst\n },\n }")();e.unshiftContainer("body",t)}},ExportDefaultDeclaration:function(e,a){var i=e.node;if(t.isCallExpression(i.declaration)&&o(t,i.declaration.callee)){var n=(a.filename||"unknown")+"/defaultExport",l=r.default("export default globalThis.jotaiAtomCache.get(%%atomKey%%, %%atom%%)")({atomKey:t.stringLiteral(n),atom:i.declaration});e.replaceWith(l)}},VariableDeclarator:function(e,a){var i,n;if(t.isIdentifier(e.node.id)&&t.isCallExpression(e.node.init)&&o(t,e.node.init.callee)&&(null!=(i=e.parentPath.parentPath)&&i.isProgram()||null!=(n=e.parentPath.parentPath)&&n.isExportNamedDeclaration())){var l=(a.filename||"unknown")+"/"+e.node.id.name,s=r.default("const %%atomIdentifier%% = globalThis.jotaiAtomCache.get(%%atomKey%%, %%atom%%)")({atomIdentifier:t.identifier(e.node.id.name),atomKey:t.stringLiteral(l),atom:e.node.init});e.parentPath.replaceWith(s)}}}}}e.default=function(){return{plugins:[s,d]}},Object.defineProperty(e,"__esModule",{value:!0})}));