pax_global_header00006660000000000000000000000064141765545520014530gustar00rootroot0000000000000052 comment=08fe01bac64999e8108b895c64d22d90cec77dde babel-plugin-preval-5.1.0/000077500000000000000000000000001417655455200153635ustar00rootroot00000000000000babel-plugin-preval-5.1.0/.all-contributorsrc000066400000000000000000000143031417655455200212150ustar00rootroot00000000000000{ "projectName": "babel-plugin-preval", "projectOwner": "kentcdodds", "imageSize": 100, "commit": false, "contributorsPerLine": 7, "repoHost": "https://github.com", "repoType": "github", "skipCi": false, "files": [ "README.md" ], "contributors": [ { "login": "kentcdodds", "name": "Kent C. Dodds", "avatar_url": "https://avatars.githubusercontent.com/u/1500684?v=3", "profile": "https://kentcdodds.com", "contributions": [ "code", "doc", "infra", "test" ] }, { "login": "mattphillips", "name": "Matt Phillips", "avatar_url": "https://avatars3.githubusercontent.com/u/5610087?v=3", "profile": "http://mattphillips.io", "contributions": [ "code", "doc", "test" ] }, { "login": "philipodev", "name": "Philip Oliver", "avatar_url": "https://avatars1.githubusercontent.com/u/28024000?v=3", "profile": "https://twitter.com/philipodev", "contributions": [ "bug" ] }, { "login": "sorin-davidoi", "name": "Sorin Davidoi", "avatar_url": "https://avatars2.githubusercontent.com/u/2109702?v=3", "profile": "https://toot.cafe/@sorin", "contributions": [ "bug", "code", "test" ] }, { "login": "infiniteluke", "name": "Luke Herrington", "avatar_url": "https://avatars4.githubusercontent.com/u/1127238?v=4", "profile": "https://github.com/infiniteluke", "contributions": [ "example" ] }, { "login": "luftywiranda13", "name": "Lufty Wiranda", "avatar_url": "https://avatars4.githubusercontent.com/u/22868432?v=4", "profile": "http://instagram.com/luftywiranda13", "contributions": [ "code" ] }, { "login": "obartra", "name": "Oscar", "avatar_url": "https://avatars0.githubusercontent.com/u/3877773?v=4", "profile": "http://obartra.github.io", "contributions": [ "code", "test" ] }, { "login": "pro-nasa", "name": "pro-nasa", "avatar_url": "https://avatars1.githubusercontent.com/u/14310216?v=4", "profile": "https://github.com/pro-nasa", "contributions": [ "doc" ] }, { "login": "sergeybekrin", "name": "Sergey Bekrin", "avatar_url": "https://avatars0.githubusercontent.com/u/9248479?v=4", "profile": "http://bekrin.me", "contributions": [] }, { "login": "maurobringolf", "name": "Mauro Bringolf", "avatar_url": "https://avatars0.githubusercontent.com/u/18613301?v=4", "profile": "https://maurobringolf.ch", "contributions": [ "code", "test" ] }, { "login": "xjlim", "name": "Joe Lim", "avatar_url": "https://avatars1.githubusercontent.com/u/10875678?v=4", "profile": "https://joelim.me", "contributions": [ "code" ] }, { "login": "marzelin", "name": "Marcin Zielinski", "avatar_url": "https://avatars3.githubusercontent.com/u/13483453?v=4", "profile": "https://github.com/marzelin", "contributions": [ "code" ] }, { "login": "tleunen", "name": "Tommy", "avatar_url": "https://avatars3.githubusercontent.com/u/1972567?v=4", "profile": "http://www.tommyleunen.com", "contributions": [ "code" ] }, { "login": "PlayMa256", "name": "Matheus Gonçalves da Silva", "avatar_url": "https://avatars0.githubusercontent.com/u/831308?v=4", "profile": "https://github.com/PlayMa256", "contributions": [ "doc" ] }, { "login": "jdorfman", "name": "Justin Dorfman", "avatar_url": "https://avatars1.githubusercontent.com/u/398230?v=4", "profile": "https://stackshare.io/jdorfman/decisions", "contributions": [ "fundingFinding" ] }, { "login": "AndrewRot", "name": "Andrew Rottier", "avatar_url": "https://avatars2.githubusercontent.com/u/12818861?v=4", "profile": "https://github.com/AndrewRot", "contributions": [ "doc" ] }, { "login": "MichaelDeBoey", "name": "Michaël De Boey", "avatar_url": "https://avatars3.githubusercontent.com/u/6643991?v=4", "profile": "https://michaeldeboey.be", "contributions": [ "code" ] }, { "login": "nobrayner", "name": "Braydon Hall", "avatar_url": "https://avatars.githubusercontent.com/u/40751395?v=4", "profile": "https://github.com/nobrayner", "contributions": [ "code" ] }, { "login": "JacobMGEvans", "name": "Jacob M-G Evans", "avatar_url": "https://avatars.githubusercontent.com/u/27247160?v=4", "profile": "https://dev.to/jacobmgevans", "contributions": [ "code" ] }, { "login": "juhanakristian", "name": "Juhana Jauhiainen", "avatar_url": "https://avatars.githubusercontent.com/u/544386?v=4", "profile": "http://juhanajauhiainen.com", "contributions": [ "code" ] }, { "login": "Aprillion", "name": "Peter Hozák", "avatar_url": "https://avatars.githubusercontent.com/u/1087670?v=4", "profile": "http://peter.hozak.info/", "contributions": [ "code" ] }, { "login": "mpeyper", "name": "Michael Peyper", "avatar_url": "https://avatars.githubusercontent.com/u/23029903?v=4", "profile": "https://github.com/mpeyper", "contributions": [ "code" ] }, { "login": "MrcSnm", "name": "Marcelo Silva Nascimento Mancini", "avatar_url": "https://avatars.githubusercontent.com/u/10136262?v=4", "profile": "https://hipreme.itch.io/", "contributions": [ "doc", "plugin" ] }, { "login": "NMinhNguyen", "name": "Minh Nguyen", "avatar_url": "https://avatars.githubusercontent.com/u/2852660?v=4", "profile": "https://github.com/NMinhNguyen", "contributions": [ "code", "test", "infra" ] } ] } babel-plugin-preval-5.1.0/.gitattributes000066400000000000000000000000231417655455200202510ustar00rootroot00000000000000* text=auto eol=lf babel-plugin-preval-5.1.0/.github/000077500000000000000000000000001417655455200167235ustar00rootroot00000000000000babel-plugin-preval-5.1.0/.github/ISSUE_TEMPLATE.md000066400000000000000000000016741417655455200214400ustar00rootroot00000000000000 - `babel-plugin-preval` version: - `node` version: - `npm` (or `yarn`) version: Relevant code or config ```javascript ``` What you did: What happened: Reproduction repository: Problem description: Suggested solution: babel-plugin-preval-5.1.0/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000015211417655455200225230ustar00rootroot00000000000000 **What**: **Why**: **How**: babel-plugin-preval-5.1.0/.github/workflows/000077500000000000000000000000001417655455200207605ustar00rootroot00000000000000babel-plugin-preval-5.1.0/.github/workflows/validate.yml000066400000000000000000000037241417655455200233020ustar00rootroot00000000000000name: validate on: push: branches: - '+([0-9])?(.{+([0-9]),x}).x' - 'main' - 'next' - 'next-major' - 'beta' - 'alpha' - '!all-contributors/**' pull_request: {} jobs: main: # ignore all-contributors PRs if: ${{ !contains(github.head_ref, 'all-contributors') }} strategy: matrix: node: [12, 14, 16] runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo uses: actions/checkout@v2 - name: ⎔ Setup node uses: actions/setup-node@v1 with: node-version: ${{ matrix.node }} - name: 📥 Download deps uses: bahmutov/npm-install@v1 with: useLockFile: false - name: ▶️ Run validate script run: npm run validate - name: ⬆️ Upload coverage report uses: codecov/codecov-action@v1 release: needs: main runs-on: ubuntu-latest if: ${{ github.repository == 'kentcdodds/babel-plugin-preval' && contains('refs/heads/main,refs/heads/beta,refs/heads/next,refs/heads/alpha', github.ref) && github.event_name == 'push' }} steps: - name: ⬇️ Checkout repo uses: actions/checkout@v2 - name: ⎔ Setup node uses: actions/setup-node@v1 with: node-version: 16 - name: 📥 Download deps uses: bahmutov/npm-install@v1 with: useLockFile: false - name: 🏗 Run build script run: npm run build - name: 🚀 Release uses: cycjimmy/semantic-release-action@v2 with: semantic_version: 17 branches: | [ '+([0-9])?(.{+([0-9]),x}).x', 'main', 'next', 'next-major', {name: 'beta', prerelease: true}, {name: 'alpha', prerelease: true} ] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }} babel-plugin-preval-5.1.0/.gitignore000066400000000000000000000002051417655455200173500ustar00rootroot00000000000000node_modules coverage dist .DS_Store # these cause more harm than good # when working with contributors package-lock.json yarn.lock babel-plugin-preval-5.1.0/.huskyrc.js000066400000000000000000000000561417655455200174700ustar00rootroot00000000000000module.exports = require('kcd-scripts/husky') babel-plugin-preval-5.1.0/.npmrc000066400000000000000000000000451417655455200165020ustar00rootroot00000000000000registry=https://registry.npmjs.org/ babel-plugin-preval-5.1.0/.prettierignore000066400000000000000000000000331417655455200204220ustar00rootroot00000000000000node_modules coverage dist babel-plugin-preval-5.1.0/.prettierrc.js000066400000000000000000000000611417655455200201570ustar00rootroot00000000000000module.exports = require('kcd-scripts/prettier') babel-plugin-preval-5.1.0/CHANGELOG.md000066400000000000000000000002731417655455200171760ustar00rootroot00000000000000# CHANGELOG The changelog is automatically updated using [semantic-release](https://github.com/semantic-release/semantic-release). You can see it on the [releases page](../../releases). babel-plugin-preval-5.1.0/CONTRIBUTING.md000066400000000000000000000034231417655455200176160ustar00rootroot00000000000000# Contributing Thanks for being willing to contribute! **Working on your first Pull Request?** You can learn how from this _free_ series [How to Contribute to an Open Source Project on GitHub][egghead] ## Project setup 1. Fork and clone the repo 2. `$ npm install` to install dependencies 3. `$ npm run validate` to validate you've got it working 4. Create a branch for your PR with `git checkout -b pr/your-branch-name` > Tip: Keep your `main` branch pointing at the original repository and make pull > requests from branches on your fork. To do this, run: > > ``` > git remote add upstream https://github.com/kentcdodds/babel-plugin-preval > git fetch upstream > git branch --set-upstream-to=upstream/main main > ``` > > This will add the original repository as a "remote" called "upstream," Then > fetch the git information from that remote, then set your local `main` branch > to use the upstream main branch whenever you run `git pull`. Then you can make > all of your pull request branches based on this `main` branch. Whenever you > want to update your version of `main`, do a regular `git pull`. ## Committing and Pushing changes Please make sure to run the tests before you commit your changes. You can run `npm run test:update` which will update any snapshots that need updating. Make sure to include those changes (if they exist) in your commit. ## Help needed Please checkout the [the open issues][issues] Also, please watch the repo and respond to questions/bug reports/feature requests! Thanks! [egghead]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github [all-contributors]: https://github.com/all-contributors/all-contributors [issues]: https://github.com/kentcdodds/babel-plugin-preval/issues babel-plugin-preval-5.1.0/LICENSE000066400000000000000000000020671417655455200163750ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2017 Kent C. Dodds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. babel-plugin-preval-5.1.0/README.md000066400000000000000000000544631417655455200166560ustar00rootroot00000000000000

babel-plugin-preval

Pre-evaluate code at build-time

--- [![Build Status][build-badge]][build] [![Code Coverage][coverage-badge]][coverage] [![version][version-badge]][package] [![downloads][downloads-badge]][npmtrends] [![MIT License][license-badge]][license] [![All Contributors](https://img.shields.io/badge/all_contributors-24-orange.svg?style=flat-square)](#contributors-) [![PRs Welcome][prs-badge]][prs] [![Code of Conduct][coc-badge]][coc] [![Babel Macro][macros-badge]][babel-plugin-macros] [![Examples][examples-badge]][examples] ## The problem You need to do some dynamic stuff, but don't want to do it at runtime. Or maybe you want to do stuff like read the filesystem to get a list of files and you can't do that in the browser. ## This solution This allows you to specify some code that runs in Node and whatever you `module.exports` in there will be swapped. For example: ```js const x = preval`module.exports = 1` // ↓ ↓ ↓ ↓ ↓ ↓ const x = 1 ``` Or, more interestingly: ```javascript const x = preval` const fs = require('fs') const val = fs.readFileSync(__dirname + '/fixture1.md', 'utf8') module.exports = { val, getSplit: function(splitDelimiter) { return x.val.split(splitDelimiter) } } ` // ↓ ↓ ↓ ↓ ↓ ↓ const x = { val: '# fixture\n\nThis is some file thing...\n', getSplit: function getSplit(splitDelimiter) { return x.val.split(splitDelimiter) }, } ``` There's also `preval.require('./something')` and `import x from /* preval */ './something'` (which can both take some arguments) or add `// @preval` comment at the top of a file. See more below. ## Table of Contents - [Installation](#installation) - [Usage](#usage) - [Template Tag](#template-tag) - [import comment](#import-comment) - [preval.require](#prevalrequire) - [preval file comment (`// @preval`)](#preval-file-comment--preval) - [Exporting a function](#exporting-a-function) - [Configure with Babel](#configure-with-babel) - [Via `.babelrc` (Recommended)](#via-babelrc-recommended) - [Via CLI](#via-cli) - [Via Node API](#via-node-api) - [Use with `babel-plugin-macros`](#use-with-babel-plugin-macros) - [Examples](#examples) - [Notes](#notes) - [FAQ](#faq) - [How is this different from prepack?](#how-is-this-different-from-prepack) - [How is this different from webpack loaders?](#how-is-this-different-from-webpack-loaders) - [Inspiration](#inspiration) - [Related Projects](#related-projects) - [Other Solutions](#other-solutions) - [Issues](#issues) - [🐛 Bugs](#-bugs) - [💡 Feature Requests](#-feature-requests) - [Contributors ✨](#contributors-) - [LICENSE](#license) ## Installation This module is distributed via [npm][npm] which is bundled with [node][node] and should be installed as one of your project's `devDependencies`: ``` npm install --save-dev babel-plugin-preval ``` ## Usage Important notes: 1. All code run by `preval` is _not_ run in a sandboxed environment 2. All code _must_ run synchronously. 3. Code that is run by preval is not transpiled so it must run natively in the version of node you're running. (cannot use es modules). > You may like to watch > [this YouTube video](https://www.youtube.com/watch?v=1queadQ0048&list=PLV5CVI1eNcJgCrPH_e6d57KRUTiDZgs0u) > to get an idea of what preval is and how it can be used. ### Template Tag **Before**: ```javascript const greeting = preval` const fs = require('fs') module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8') ` ``` **After** (assuming `greeting.txt` contains the text: `"Hello world!"`): ```javascript const greeting = 'Hello world!' ``` `preval` can also handle _some_ simple dynamic values as well: **Before**: ```javascript const name = 'Bob Hope' const person = preval` const [first, last] = require('./name-splitter')(${name}) module.exports = {first, last} ` ``` **After** (assuming `./name-splitter` is a function that splits a name into first/last): ```javascript const name = 'Bob Hope' const person = {first: 'Bob', last: 'Hope'} ``` ### import comment **Before**: ```javascript import fileList from /* preval */ './get-list-of-files' ``` **After** (depending on what `./get-list-of-files does`, it might be something like): ```javascript const fileList = ['file1.md', 'file2.md', 'file3.md', 'file4.md'] ``` You can also provide arguments which themselves are prevaled! **Before**: ```javascript import fileList from /* preval(3) */ './get-list-of-files' ``` **After** (assuming `./get-list-of-files` accepts an argument limiting how many files are retrieved: ```javascript const fileList = ['file1.md', 'file2.md', 'file3.md'] ``` ### preval.require **Before**: ```javascript const fileLastModifiedDate = preval.require('./get-last-modified-date') ``` **After**: ```javascript const fileLastModifiedDate = '2017-07-05' ``` And you can provide _some_ simple dynamic arguments as well: **Before**: ```javascript const fileLastModifiedDate = preval.require( './get-last-modified-date', '../../some-other-file.js', ) ``` **After**: ```javascript const fileLastModifiedDate = '2017-07-04' ``` ### preval file comment (`// @preval`) Using the preval file comment will update a whole file to be evaluated down to an export. Whereas the above usages (assignment/import/require) will only preval the scope of the assignment or file being imported. **Before**: ```javascript // @preval const id = require('./path/identity') const one = require('./path/one') const compose = (...fns) => fns.reduce((f, g) => a => f(g(a))) const double = a => a * 2 const square = a => a * a module.exports = compose(square, id, double)(one) ``` **After**: ```javascript module.exports = 4 ``` ## Exporting a function If you export a function from a module that you're prevaling (whether using `preval.require` or the import comment), then that function will be called and whatever is returned will be the prevaled value. It's important to know this if you want to have the prevaled value itself be a function: **Example**: ```js // example-module.js const fn = message => `The message is: ${message}` module.exports = () => fn ``` **Usage of preval**: ```js const theFn = preval.require('./example-module.js') ``` **Generated code**: ```js const theFn = message => `The message is: ${message}` ``` ## Configure with Babel ### Via `.babelrc` (Recommended) **.babelrc** ```json { "plugins": ["preval"] } ``` ### Via CLI ```sh babel --plugins preval script.js ``` ### Via Node API ```javascript require('babel-core').transform('code', { plugins: ['preval'], }) ``` ## Use with `babel-plugin-macros` Once you've [configured `babel-plugin-macros`](https://github.com/kentcdodds/babel-plugin-macros/blob/main/other/docs/user.md) you can import/require the preval macro at `babel-plugin-preval/macro`. For example: ```javascript import preval from 'babel-plugin-preval/macro' const one = preval`module.exports = 1 + 2 - 1 - 1` ``` > You could also use [`preval.macro`][preval.macro] if you'd prefer to type less > 😀 ## Examples - [Mastodon](https://github.com/tootsuite/mastodon/pull/4202) saved 40kb (gzipped) using `babel-plugin-preval` - [glamorous-website](https://github.com/kentcdodds/glamorous-website/pull/235) uses [`preval.macro`][preval.macro] to determine Algolia options based on `process.env.LOCALE`. It also uses [`preval.macro`][preval.macro] to load an `svg` file as a string, `base64` encode it, and use it as a `background-url` for an input element. - [Generate documentation for React components](https://gist.github.com/souporserious/575609dc5a5d52e167dd2236079eccc0) - [Serverless with webpack](https://github.com/geovanisouza92/serverless-preval) build serverless functions using webpack and Babel for development and production with preval to replace (possible sensible) content in code. - [Read files at build time (video)](https://www.youtube.com/watch?v=NhmrbpVKgdQ&feature=youtu.be) ## Notes If you use `babel-plugin-transform-decorators-legacy`, there is a conflict because both plugins must be placed at the top Wrong: ```json { "plugins": ["preval", "transform-decorators-legacy"] } ``` Ok: ```json { "plugins": ["preval", ["transform-decorators-legacy"]] } ``` ## FAQ ### How is this different from prepack? [`prepack`][prepack] is intended to be run on your final bundle after you've run your webpack/etc magic on it. It does a TON of stuff, but the idea is that your code should work with or without prepack. `babel-plugin-preval` is intended to let you write code that would _not_ work otherwise. Doing things like reading something from the file system are not possible in the browser (or with prepack), but `preval` enables you to do this. ### How is this different from webpack loaders? This plugin was inspired by webpack's [val-loader][val-loader]. The benefit of using this over that loader (or any other loader) is that it integrates with your existing babel pipeline. This is especially useful for the server where you're probably not bundling your code with [`webpack`][webpack], but you may be using babel. (If you're not using either, configuring babel for this would be easier than configuring webpack for `val-loader`). In addition, you can implement pretty much any webpack loader using `babel-plugin-preval`. If you want to learn more, check `webpack` documentations about [`loaders`][webpack-loaders]. ## Inspiration I needed something like this for the [glamorous website](https://github.com/kentcdodds/glamorous-website). I live-streamed developing the whole thing. If you're interested you can find [the recording on my youtube channel](https://www.youtube.com/watch?v=3vxov5xUai8&index=19&list=PLV5CVI1eNcJh5CTgArGVwANebCrAh2OUE) (note, screen only recording, no audio). I was inspired by the [val-loader][val-loader] from webpack. ## Related Projects - [`preval.macro`][preval.macro] - nicer integration with `babel-plugin-macros` - [`define_macro-loader`](https://github.com/MrcSnm/define_macro-loader) - Integrate preval with C-Like macros, thus, increasing preval use cases. ## Other Solutions I'm not aware of any, if you are please [make a pull request][prs] and add it here! ## Issues _Looking to contribute? Look for the [Good First Issue][good-first-issue] label._ ### 🐛 Bugs Please file an issue for bugs, missing documentation, or unexpected behavior. [**See Bugs**][bugs] ### 💡 Feature Requests Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on. [**See Feature Requests**][requests] ## Contributors ✨ Thanks goes to these people ([emoji key][emojis]):

Kent C. Dodds

💻 📖 🚇 ⚠️

Matt Phillips

💻 📖 ⚠️

Philip Oliver

🐛

Sorin Davidoi

🐛 💻 ⚠️

Luke Herrington

💡

Lufty Wiranda

💻

Oscar

💻 ⚠️

pro-nasa

📖

Sergey Bekrin


Mauro Bringolf

💻 ⚠️

Joe Lim

💻

Marcin Zielinski

💻

Tommy

💻

Matheus Gonçalves da Silva

📖

Justin Dorfman

🔍

Andrew Rottier

📖

Michaël De Boey

💻

Braydon Hall

💻

Jacob M-G Evans

💻

Juhana Jauhiainen

💻

Peter Hozák

💻

Michael Peyper

💻

Marcelo Silva Nascimento Mancini

📖 🔌

Minh Nguyen

💻 ⚠️ 🚇
This project follows the [all-contributors][all-contributors] specification. Contributions of any kind welcome! ## LICENSE MIT [npm]: https://www.npmjs.com [node]: https://nodejs.org [build-badge]: https://img.shields.io/github/workflow/status/kentcdodds/babel-plugin-preval/validate?logo=github&style=flat-square [build]: https://github.com/kentcdodds/babel-plugin-preval/actions?query=workflow%3Avalidate [coverage-badge]: https://img.shields.io/codecov/c/github/kentcdodds/babel-plugin-preval.svg?style=flat-square [coverage]: https://codecov.io/github/kentcdodds/babel-plugin-preval [version-badge]: https://img.shields.io/npm/v/babel-plugin-preval.svg?style=flat-square [package]: https://www.npmjs.com/package/babel-plugin-preval [downloads-badge]: https://img.shields.io/npm/dm/babel-plugin-preval.svg?style=flat-square [npmtrends]: http://www.npmtrends.com/babel-plugin-preval [license-badge]: https://img.shields.io/npm/l/babel-plugin-preval.svg?style=flat-square [license]: https://github.com/kentcdodds/babel-plugin-preval/blob/main/LICENSE [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square [prs]: http://makeapullrequest.com [coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square [coc]: https://github.com/kentcdodds/babel-plugin-preval/blob/main/other/CODE_OF_CONDUCT.md [macros-badge]: https://img.shields.io/badge/babel--macro-%F0%9F%8E%A3-f5da55.svg?style=flat-square [babel-plugin-macros]: https://github.com/kentcdodds/babel-plugin-macros [examples-badge]: https://img.shields.io/badge/%F0%9F%92%A1-examples-8C8E93.svg?style=flat-square [examples]: https://github.com/kentcdodds/babel-plugin-preval/blob/main/other/EXAMPLES.md [emojis]: https://github.com/all-contributors/all-contributors#emoji-key [all-contributors]: https://github.com/all-contributors/all-contributors [bugs]: https://github.com/kentcdodds/babel-plugin-preval/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Acreated-desc+label%3Abug [requests]: https://github.com/kentcdodds/babel-plugin-preval/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement [good-first-issue]: https://github.com/kentcdodds/babel-plugin-preval/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement+label%3A%22good+first+issue%22 [prepack]: https://github.com/facebook/prepack [preval.macro]: https://github.com/kentcdodds/preval.macro [webpack]: https://webpack.js.org [webpack-loaders]: https://webpack.js.org/concepts/loaders [val-loader]: https://github.com/webpack-contrib/val-loader babel-plugin-preval-5.1.0/macro.d.ts000066400000000000000000000000701417655455200172530ustar00rootroot00000000000000import preval from './dist/macro' export default preval babel-plugin-preval-5.1.0/macro.js000066400000000000000000000002211417655455200170150ustar00rootroot00000000000000// this is here to make the import/require API nicer: // import preval from 'babel-plugin-preval/macro' module.exports = require('./dist/macro') babel-plugin-preval-5.1.0/other/000077500000000000000000000000001417655455200165045ustar00rootroot00000000000000babel-plugin-preval-5.1.0/other/CODE_OF_CONDUCT.md000066400000000000000000000062411417655455200213060ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at kent+coc@doddsfamily.us. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ babel-plugin-preval-5.1.0/other/EXAMPLES.md000066400000000000000000000030211417655455200202400ustar00rootroot00000000000000# Examples ## Usage with React/Next.js ### Use node's os module to get the user that ran the build and display their username. ```jsx import React from 'react' import preval from 'preval.macro' const whoami = preval` const userInfo = require('os').userInfo() module.exports = userInfo.username ` export default WhoAmI function WhoAmI() { return (

whoami: {whoami}

) } ``` ### Code reuse with babel-plugin-preval (Especially useful with [Next.js](https://github.com/zeit/next.js)) A small `getPosts.js` node module that loads in markdown files in a "posts" directory. ```js const frontMatter = require('yaml-front-matter') const fs = require('fs') const path = require('path') const posts = fs .readdirSync('./posts/') .filter(file => path.extname(file) === '.md') .map(file => frontMatter.loadFront(`./posts/${file}`, 'body')) module.exports = posts || [] ``` Preval the `getPosts.js` module so that posts are loaded and exported. ```js import preval from 'preval.macro' export default preval`module.exports = require('./getPosts')` ``` Now you can import the above posts and use a module like [marked](https://github.com/chjj/marked) to convert your markdown into blog posts! The underlying `getPosts.js` module can also be used required in `next.config.js` to build the static list of routes for `next export`. See the full example in the [Next Static](https://github.com/infiniteluke/next-static) project. babel-plugin-preval-5.1.0/other/MAINTAINING.md000066400000000000000000000063311417655455200205670ustar00rootroot00000000000000# Maintaining This is documentation for maintainers of this project. ## Code of Conduct Please review, understand, and be an example of it. Violations of the code of conduct are taken seriously, even (especially) for maintainers. ## Issues We want to support and build the community. We do that best by helping people learn to solve their own problems. We have an issue template and hopefully most folks follow it. If it's not clear what the issue is, invite them to create a minimal reproduction of what they're trying to accomplish or the bug they think they've found. Once it's determined that a code change is necessary, point people to [makeapullrequest.com](http://makeapullrequest.com) and invite them to make a pull request. If they're the one who needs the feature, they're the one who can build it. If they need some hand holding and you have time to lend a hand, please do so. It's an investment into another human being, and an investment into a potential maintainer. Remember that this is open source, so the code is not yours, it's ours. If someone needs a change in the codebase, you don't have to make it happen yourself. Commit as much time to the project as you want/need to. Nobody can ask any more of you than that. ## Pull Requests As a maintainer, you're fine to make your branches on the main repo or on your own fork. Either way is fine. When we receive a pull request, a GitHub Action is kicked off automatically (see the `.github/workflows/validate.yml` for what runs in the action). We avoid merging anything that breaks the validate action. Please review PRs and focus on the code rather than the individual. You never know when this is someone's first ever PR and we want their experience to be as positive as possible, so be uplifting and constructive. When you merge the pull request, 99% of the time you should use the [Squash and merge](https://help.github.com/articles/merging-a-pull-request/) feature. This keeps our git history clean, but more importantly, this allows us to make any necessary changes to the commit message so we release what we want to release. See the next section on Releases for more about that. ## Release Our releases are automatic. They happen whenever code lands into `main`. A GitHub Action gets kicked off and if it's successful, a tool called [`semantic-release`](https://github.com/semantic-release/semantic-release) is used to automatically publish a new release to npm as well as a changelog to GitHub. It is only able to determine the version and whether a release is necessary by the git commit messages. With this in mind, **please brush up on [the commit message convention][commit] which drives our releases.** > One important note about this: Please make sure that commit messages do NOT > contain the words "BREAKING CHANGE" in them unless we want to push a major > version. I've been burned by this more than once where someone will include > "BREAKING CHANGE: None" and it will end up releasing a new major version. Not > a huge deal honestly, but kind of annoying... ## Thanks! Thank you so much for helping to maintain this project! [commit]: https://github.com/conventional-changelog-archived-repos/conventional-changelog-angular/blob/ed32559941719a130bb0327f886d6a32a8cbc2ba/convention.md babel-plugin-preval-5.1.0/other/USERS.md000066400000000000000000000005201417655455200177240ustar00rootroot00000000000000# Users If you or your company uses this project, add your name to this list! Eventually we may have a website to showcase these (wanna build it!?) > No users have been added yet! babel-plugin-preval-5.1.0/other/manual-releases.md000066400000000000000000000024411417655455200221050ustar00rootroot00000000000000# manual-releases This project has an automated release set up. So things are only released when there are useful changes in the code that justify a release. But sometimes things get messed up one way or another and we need to trigger the release ourselves. When this happens, simply bump the number below and commit that with the following commit message based on your needs: **Major** ``` fix(release): manually release a major version There was an issue with a major release, so this manual-releases.md change is to release a new major version. Reference: # BREAKING CHANGE: ``` **Minor** ``` feat(release): manually release a minor version There was an issue with a minor release, so this manual-releases.md change is to release a new minor version. Reference: # ``` **Patch** ``` fix(release): manually release a patch version There was an issue with a patch release, so this manual-releases.md change is to release a new patch version. Reference: # ``` The number of times we've had to do a manual release is: 0 babel-plugin-preval-5.1.0/package.json000066400000000000000000000032651417655455200176570ustar00rootroot00000000000000{ "name": "babel-plugin-preval", "version": "0.0.0-semantically-released", "description": "Pre-evaluate code at build-time", "engines": { "node": ">=10", "npm": ">=6" }, "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "build": "kcd-scripts build", "lint": "kcd-scripts lint", "test": "kcd-scripts test", "test:update": "npm test -- --updateSnapshot --coverage", "typecheck": "kcd-scripts typecheck", "validate": "kcd-scripts validate" }, "files": [ "dist", "macro.js", "macro.d.ts" ], "keywords": [ "babel", "babel-plugin", "eval", "precompile", "babel-plugin-macros" ], "author": "Kent C. Dodds (https://kentcdodds.com)", "license": "MIT", "dependencies": { "@types/babel__core": "^7.1.12", "@babel/runtime": "^7.12.5", "babel-plugin-macros": "^3.0.1", "require-from-string": "^2.0.2" }, "devDependencies": { "@types/babel-plugin-macros": "^2.8.4", "@types/require-from-string": "^1.2.0", "ast-pretty-print": "^2.0.1", "babel-plugin-tester": "^10.0.0", "kcd-scripts": "^7.2.0", "type-fest": "^0.20.2", "typescript": "^4.1.3" }, "eslintConfig": { "extends": "./node_modules/kcd-scripts/eslint.js" }, "eslintIgnore": [ "node_modules", "coverage", "/macro.d.ts", "dist" ], "babel": { "presets": [ "kcd-scripts/babel" ] }, "repository": { "type": "git", "url": "https://github.com/kentcdodds/babel-plugin-preval" }, "bugs": { "url": "https://github.com/kentcdodds/babel-plugin-preval/issues" }, "homepage": "https://github.com/kentcdodds/babel-plugin-preval#readme" } babel-plugin-preval-5.1.0/src/000077500000000000000000000000001417655455200161525ustar00rootroot00000000000000babel-plugin-preval-5.1.0/src/__tests__/000077500000000000000000000000001417655455200201105ustar00rootroot00000000000000babel-plugin-preval-5.1.0/src/__tests__/__snapshots__/000077500000000000000000000000001417655455200227265ustar00rootroot00000000000000babel-plugin-preval-5.1.0/src/__tests__/__snapshots__/index.ts.snap000066400000000000000000000117641417655455200253560ustar00rootroot00000000000000// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`preval a-bunch-of-checks: a-bunch-of-checks 1`] = ` const x = preval\` const fs = require('fs') const val = fs.readFileSync(require.resolve('./fixture1.md'), 'utf8') module.exports = { val, getSplit: function(splitDelimiter) { return x.val.split(splitDelimiter) } } \` ↓ ↓ ↓ ↓ ↓ ↓ const x = { val: '# fixture\\n\\nThis is some file thing...\\n', getSplit: function (splitDelimiter) { return x.val.split(splitDelimiter) }, } `; exports[`preval absolute-path: absolute-path 1`] = ` const x = preval.require("../__tests__/fixtures/nested/absolute-path") ↓ ↓ ↓ ↓ ↓ ↓ const x = '/src/__tests__/index.ts' `; exports[`preval dynamic error: dynamic error 1`] = ` const x = preval\`module.exports = "\${dynamic}"\` ↓ ↓ ↓ ↓ ↓ ↓ Error: /src/__tests__/index.ts: Unable to determine the value of your preval string `; exports[`preval export undefined: export undefined 1`] = ` // @preval let smth = {} module.exports = smth.UNDEFINED; ↓ ↓ ↓ ↓ ↓ ↓ // this file was prevaled module.exports = undefined `; exports[`preval handles transpiled modules (uses default export): handles transpiled modules (uses default export) 1`] = ` let one = preval.require('./fixtures/es6-identity.js', 1) ↓ ↓ ↓ ↓ ↓ ↓ let one = 1 `; exports[`preval import comment (with extras before): import comment (with extras before) 1`] = ` import x from /* this is extra stuff */ /* preval */ "./fixtures/compute-one.js" ↓ ↓ ↓ ↓ ↓ ↓ const x = 1 `; exports[`preval import comment (with extras): import comment (with extras) 1`] = ` import x from /* preval */ /* this is extra stuff */ "./fixtures/compute-one.js" ↓ ↓ ↓ ↓ ↓ ↓ const x = 1 `; exports[`preval import comment: import comment 1`] = ` import x from /* preval */ "./fixtures/compute-one.js" ↓ ↓ ↓ ↓ ↓ ↓ const x = 1 `; exports[`preval import object arg: import object arg 1`] = ` import x from /* preval({object: "argument", withFunction: () => {}}) */ "./fixtures/identity.js" ↓ ↓ ↓ ↓ ↓ ↓ const x = { object: 'argument', withFunction: () => {}, } `; exports[`preval import required arg: import required arg 1`] = ` import x from /* preval(require("./fixtures/compute-one")) */ "./fixtures/identity" ↓ ↓ ↓ ↓ ↓ ↓ const x = 1 `; exports[`preval import string arg: import string arg 1`] = ` import x from /* preval("string argument") */ "./fixtures/identity.js" ↓ ↓ ↓ ↓ ↓ ↓ const x = 'string argument' `; exports[`preval require functions: require functions 1`] = ` const x = preval.require("./fixtures/multiple-functions") ↓ ↓ ↓ ↓ ↓ ↓ const x = { a: function a() { return 'a' }, b: function b() { return 'b' }, } `; exports[`preval require with arg but not a function: require with arg but not a function 1`] = ` const x = preval.require("./fixtures/compute-one", "should not be here...") ↓ ↓ ↓ ↓ ↓ ↓ Error: /src/__tests__/index.ts: \`preval.require\`-ed module (src/__tests__/index.ts) cannot accept arguments because it does not export a function. You passed the arguments: should not be here... `; exports[`preval require with arge: require with arge 1`] = ` const x = preval.require("./fixtures/identity", 3) ↓ ↓ ↓ ↓ ↓ ↓ const x = 3 `; exports[`preval require with unknown arg: require with unknown arg 1`] = ` const x = preval.require("./fixtures/identity", SOME_UNKNOWN_VARIABLE) ↓ ↓ ↓ ↓ ↓ ↓ Error: /src/__tests__/index.ts: preval cannot determine the value of an argument in preval.require `; exports[`preval simple comment: simple comment 1`] = ` // @preval module.exports = 1 + 2 - 1 - 1 ↓ ↓ ↓ ↓ ↓ ↓ // this file was prevaled module.exports = 1 `; exports[`preval simple function: simple function 1`] = ` const y = preval\` module.exports = { booyah: function() { return "booyah" } } \` ↓ ↓ ↓ ↓ ↓ ↓ const y = { booyah: function () { return 'booyah' }, } `; exports[`preval simple number: simple number 1`] = ` const x = preval\`module.exports = 1\` ↓ ↓ ↓ ↓ ↓ ↓ const x = 1 `; exports[`preval simple require: simple require 1`] = ` const x = preval.require("./fixtures/compute-one") ↓ ↓ ↓ ↓ ↓ ↓ const x = 1 `; exports[`preval simple string: simple string 1`] = ` preval\`module.exports = "foo"\` ↓ ↓ ↓ ↓ ↓ ↓ 'foo' `; exports[`preval with flow after: with flow after 1`] = ` // @preval // @flow module.exports = 1 + 2 - 1 - 1 ↓ ↓ ↓ ↓ ↓ ↓ // this file was prevaled // @flow module.exports = 1 `; exports[`preval with flow before: with flow before 1`] = ` // @flow // @preval module.exports = 1 + 2 - 1 - 1 ↓ ↓ ↓ ↓ ↓ ↓ // @flow // this file was prevaled module.exports = 1 `; babel-plugin-preval-5.1.0/src/__tests__/__snapshots__/macro.ts.snap000066400000000000000000000023371417655455200253440ustar00rootroot00000000000000// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`preval as function: as function 1`] = ` const myPreval = require('./helpers/preval.macro') const x = myPreval(\` module.exports = require('./fixtures/identity')({sayHi: () => 'hi'}) \`) ↓ ↓ ↓ ↓ ↓ ↓ const x = { sayHi: () => 'hi', } `; exports[`preval as jsx: as jsx 1`] = ` const Preval = require('./helpers/preval.macro') const ui = ( const fs = require('fs') module.exports = fs.readFileSync(require.resolve('./fixtures/fixture1.md'), 'utf8') ) ↓ ↓ ↓ ↓ ↓ ↓ const ui =
"# fixture\\n\\nThis is some file thing...\\n"
`; exports[`preval as tag: as tag 1`] = ` import preval from './helpers/preval.macro' const x = preval\`module.exports = require('./fixtures/compute-one')\` ↓ ↓ ↓ ↓ ↓ ↓ const x = 1 `; exports[`preval error for other nodes: error for other nodes 1`] = ` const preval = require('./helpers/preval.macro') x = 3 + preval ↓ ↓ ↓ ↓ ↓ ↓ Error: /src/__tests__/macro.ts: ./helpers/preval.macro: babel-plugin-preval/macro can only be used as tagged template expression, function call or JSX element. You tried BinaryExpression. `; babel-plugin-preval-5.1.0/src/__tests__/fixtures/000077500000000000000000000000001417655455200217615ustar00rootroot00000000000000babel-plugin-preval-5.1.0/src/__tests__/fixtures/.babelrc000066400000000000000000000001401417655455200233470ustar00rootroot00000000000000{ "presets": ["@babel/preset-env"], "plugins": ["transform-inline-environment-variables"] } babel-plugin-preval-5.1.0/src/__tests__/fixtures/.eslintrc000066400000000000000000000001101417655455200235750ustar00rootroot00000000000000{ "rules": { "no-unused-vars": "off", "no-undef": "off" } } babel-plugin-preval-5.1.0/src/__tests__/fixtures/a-bunch-of-checks.js000066400000000000000000000003611417655455200254740ustar00rootroot00000000000000const x = preval` const fs = require('fs') const val = fs.readFileSync(require.resolve('./fixture1.md'), 'utf8') module.exports = { val, getSplit: function(splitDelimiter) { return x.val.split(splitDelimiter) } } ` babel-plugin-preval-5.1.0/src/__tests__/fixtures/compute-one.js000066400000000000000000000000331417655455200245460ustar00rootroot00000000000000module.exports = 1 + 1 - 1 babel-plugin-preval-5.1.0/src/__tests__/fixtures/es6-identity.js000066400000000000000000000004331417655455200246430ustar00rootroot00000000000000/* eslint-disable */ // codegen can't accept non-transpiled esmodules // but it can handle transpiled esmodules // so we're simulating a pre-transpiled module here Object.defineProperty(exports, '__esModule', { value: true, }) exports.default = function(input) { return input } babel-plugin-preval-5.1.0/src/__tests__/fixtures/fixture1.md000066400000000000000000000000461417655455200240520ustar00rootroot00000000000000# fixture This is some file thing... babel-plugin-preval-5.1.0/src/__tests__/fixtures/identity.js000066400000000000000000000001071417655455200241460ustar00rootroot00000000000000module.exports = acceptsArg function acceptsArg(arg) { return arg } babel-plugin-preval-5.1.0/src/__tests__/fixtures/multiple-functions.js000066400000000000000000000001451417655455200261600ustar00rootroot00000000000000module.exports = { a: function a() { return 'a' }, b: function b() { return 'b' }, } babel-plugin-preval-5.1.0/src/__tests__/fixtures/nested/000077500000000000000000000000001417655455200232435ustar00rootroot00000000000000babel-plugin-preval-5.1.0/src/__tests__/fixtures/nested/absolute-path.js000066400000000000000000000001751417655455200263540ustar00rootroot00000000000000// preval.require would either resolve an absolute path or fail to resolve this // module at all module.exports = __filename babel-plugin-preval-5.1.0/src/__tests__/helpers/000077500000000000000000000000001417655455200215525ustar00rootroot00000000000000babel-plugin-preval-5.1.0/src/__tests__/helpers/preval.macro.d.ts000066400000000000000000000000671417655455200247400ustar00rootroot00000000000000import preval from '../../macro' export default preval babel-plugin-preval-5.1.0/src/__tests__/helpers/preval.macro.js000066400000000000000000000003601417655455200245000ustar00rootroot00000000000000// this is just here because the import needs to end in "macro" with no extension. // and if we don't do this, then babel-plugin-macros cannot find the macro.ts file (it's looking for a .js file). module.exports = require('../../macro.ts') babel-plugin-preval-5.1.0/src/__tests__/index.ts000066400000000000000000000067361417655455200216030ustar00rootroot00000000000000import path from 'path' import pluginTester from 'babel-plugin-tester' import plugin from '..' const projectRoot = path.join(__dirname, '../../') expect.addSnapshotSerializer({ print(val) { const valString = val as string return valString.split(projectRoot).join('/') }, test(val) { return typeof val === 'string' }, }) const error = (code: string) => ({code, error: true}) const noSnapshot = (code: string) => ({code, snapshot: false}) const fixture = (filename: string) => ({ fixture: require.resolve(`./fixtures/${filename}`), }) pluginTester({ plugin, pluginName: 'preval', snapshot: true, babelOptions: {filename: __filename}, tests: { 'not preval': noSnapshot('const x = notPreval`module.exports = "nothing"`'), 'simple number': 'const x = preval`module.exports = 1`', 'simple string': 'preval`module.exports = "foo"`', 'simple function': ` const y = preval\` module.exports = { booyah: function() { return "booyah" } } \` `, 'a-bunch-of-checks': fixture('a-bunch-of-checks'), 'dynamic error': error( `const x = preval\`module.exports = "\${dynamic}"\``, ), 'import comment': 'import x from /* preval */ "./fixtures/compute-one.js"', 'import comment (with extras)': 'import x from /* preval */ /* this is extra stuff */ "./fixtures/compute-one.js"', 'import comment (with extras before)': 'import x from /* this is extra stuff */ /* preval */ "./fixtures/compute-one.js"', 'invalid comment': { // no real changes here, but babel does weird stuff to comments like this... code: 'import x from /* this is extra stuff */"./fixtures/compute-one.js";', output: ` import x from /* this is extra stuff */ './fixtures/compute-one.js' `, snapshot: false, }, 'import string arg': 'import x from /* preval("string argument") */ "./fixtures/identity.js"', 'import object arg': 'import x from /* preval({object: "argument", withFunction: () => {}}) */ "./fixtures/identity.js"', 'import required arg': 'import x from /* preval(require("./fixtures/compute-one")) */ "./fixtures/identity"', 'simple require': 'const x = preval.require("./fixtures/compute-one")', 'require with arge': 'const x = preval.require("./fixtures/identity", 3)', 'require functions': 'const x = preval.require("./fixtures/multiple-functions")', 'absolute-path': 'const x = preval.require("../__tests__/fixtures/nested/absolute-path")', 'require with unknown arg': error( 'const x = preval.require("./fixtures/identity", SOME_UNKNOWN_VARIABLE)', ), 'require with arg but not a function': error( 'const x = preval.require("./fixtures/compute-one", "should not be here...")', ), 'simple comment': ` // @preval module.exports = 1 + 2 - 1 - 1 `, 'with flow before': ` // @flow // @preval module.exports = 1 + 2 - 1 - 1 `, 'with flow after': ` // @preval // @flow module.exports = 1 + 2 - 1 - 1 `, 'export undefined': ` // @preval let smth = {} module.exports = smth.UNDEFINED; `, 'comment no contents': noSnapshot('// @preval'), 'comment with only comment contents': noSnapshot(` // @preval /* comment */ `), 'handles transpiled modules (uses default export)': ` let one = preval.require('./fixtures/es6-identity.js', 1) `, }, }) babel-plugin-preval-5.1.0/src/__tests__/macro.ts000066400000000000000000000026661417655455200215730ustar00rootroot00000000000000import path from 'path' import pluginTester from 'babel-plugin-tester' import plugin from 'babel-plugin-macros' const projectRoot = path.join(__dirname, '../../') expect.addSnapshotSerializer({ print(val) { const valString = val as string return valString.split(projectRoot).join('/') }, test(val) { return typeof val === 'string' }, }) pluginTester({ plugin, pluginName: 'preval', snapshot: true, babelOptions: {filename: __filename, parserOpts: {plugins: ['jsx']}}, tests: [ { title: 'as tag', code: ` import preval from './helpers/preval.macro' const x = preval\`module.exports = require('./fixtures/compute-one')\` `, }, { title: 'as function', code: ` const myPreval = require('./helpers/preval.macro') const x = myPreval(\` module.exports = require('./fixtures/identity')({sayHi: () => 'hi'}) \`) `, }, { title: 'as jsx', code: ` const Preval = require('./helpers/preval.macro') const ui = ( const fs = require('fs') module.exports = fs.readFileSync(require.resolve('./fixtures/fixture1.md'), 'utf8') ) `, }, { title: 'error for other nodes', error: true, code: ` const preval = require('./helpers/preval.macro') x = 3 + preval `, }, ], }) babel-plugin-preval-5.1.0/src/helpers.ts000066400000000000000000000041371417655455200201710ustar00rootroot00000000000000import p from 'path' import requireFromStringOfCode from 'require-from-string' import type babelCore from '@babel/core' import objectToAST from './object-to-ast' type PrevalModuleExport = unknown | ((...args: Array) => unknown) type CompiledESModule = { __esModule: boolean default: PrevalModuleExport } function isCompiledESModule(module: unknown): module is CompiledESModule { return typeof module === 'object' && module !== null && '__esModule' in module } // istanbul ignore next because I don't know how to reproduce a situation // where the filename doesn't exist, but TypeScript gets mad when I don't handle that case. const getFilename = (fileOpts: babelCore.TransformOptions): string => fileOpts.filename ?? '"unknown"' type RequireFromStringOptions = { string: Buffer | string fileOpts: babelCore.TransformOptions args?: any[] } export function requireFromString({ string: stringToPreval, fileOpts, args = [], }: RequireFromStringOptions) { const filename = getFilename(fileOpts) let module = requireFromStringOfCode(String(stringToPreval), filename) as | CompiledESModule | PrevalModuleExport | unknown if (isCompiledESModule(module)) { // Allow for es modules (default export) module = module.default } if (typeof module === 'function') { // eslint-disable-next-line @typescript-eslint/no-unsafe-argument module = module(...args) } else if (args.length) { throw new Error( `\`preval.require\`-ed module (${p.relative( process.cwd(), filename, )}) cannot accept arguments because it does not export a function. You passed the arguments: ${args.join( ', ', )}`, ) } return module } type GetReplacementOptions = { string: Buffer | string fileOpts: babelCore.TransformOptions args?: any[] babel: typeof babelCore } export function getReplacement({ string, fileOpts, args, babel, }: GetReplacementOptions) { const module = requireFromString({string, fileOpts, args}) return objectToAST(module, {babel, fileOptions: fileOpts}) } /* eslint @typescript-eslint/no-explicit-any: "off", */ babel-plugin-preval-5.1.0/src/index.ts000066400000000000000000000171741417655455200176430ustar00rootroot00000000000000import p from 'path' import fs from 'fs' import type babelCore from '@babel/core' import type {Primitive} from 'type-fest' import {getReplacement, requireFromString} from './helpers' type VisitorState = { file: { opts: babelCore.TransformOptions } } export default function prevalPlugin( babel: typeof babelCore, ): babelCore.PluginObj { const {types: t, template, transformFromAst} = babel const assignmentBuilder = template('const NAME = VALUE') return { name: 'preval', visitor: { Program(path, {file: {opts: fileOpts}}) { const firstNode = path.node.body[0] || {} const comments = firstNode.leadingComments ?? [] const prevalComment = comments.find(isPrevalComment) if (!prevalComment) { return } prevalComment.value = ' this file was prevaled' // @ts-expect-error the types for this is wrong... const {code: string}: {code: string} = transformFromAst( path.node, // @ts-expect-error the types for this is wrong... null, /* istanbul ignore next (babel 6 vs babel 7 check) */ babel.version.startsWith('6.') ? {} : { babelrc: false, configFile: false, }, ) const replacement = getReplacement({string, fileOpts, babel}) // istanbul ignore next because this should never happen, but TypeScript needs me to handle it if (!replacement) return const moduleExports = { ...t.expressionStatement( t.assignmentExpression( '=', t.memberExpression( t.identifier('module'), t.identifier('exports'), ), replacement, ), ), leadingComments: comments, } path.replaceWith(t.program([moduleExports])) }, TaggedTemplateExpression(path, {file: {opts: fileOpts}}) { const isPreval = path.node.tag.type === 'Identifier' && path.node.tag.name === 'preval' if (!isPreval) { return } const string: unknown = path.get('quasi').evaluate().value if (typeof string !== 'string') { throw new Error('Unable to determine the value of your preval string') } const replacement = getReplacement({string, fileOpts, babel}) // istanbul ignore next because this should never happen, but TypeScript needs me to handle it if (!replacement) return path.replaceWith(replacement) }, ImportDeclaration(path, {file: {opts: fileOpts}}) { const isPreval = looksLike(path, { node: { source: { leadingComments( comments: typeof path.node.source.leadingComments, ) { // istanbul ignore next because the ?? false should never happen // because "comments" should never be null, but the types say it could... return comments?.some(isPrevalComment) ?? false }, }, }, }) if (!isPreval) { return } const prevalComment = path.node.source.leadingComments ?.find(isPrevalComment) ?.value.trim() // istanbul ignore next because we don't even call `asImportDeclaration` if // there's not a codegen comment, but TypeScript gets mad otherwise if (!prevalComment) return let argValues if (prevalComment !== 'preval') { const arg = prevalComment.replace(/preval\((.*)\)/, '$1').trim() const argValue = requireFromString({ string: `module.exports = ${arg}`, fileOpts, }) argValues = [argValue] } // istanbul ignore next because I don't know how to reproduce a situation // where the filename doesn't exist, but TypeScript gets mad when I don't handle that case. if (!fileOpts.filename) return const absolutePath = p.resolve( p.dirname(fileOpts.filename), path.node.source.value, ) const code = fs.readFileSync(require.resolve(absolutePath)) const replacement = getReplacement({ string: code, fileOpts, args: argValues, babel, }) const assignment = assignmentBuilder({ NAME: t.identifier(path.node.specifiers[0].local.name), VALUE: replacement, }) // istanbul ignore next because this should never happen, but TypeScript needs me to handle it if (!Array.isArray(assignment)) { path.replaceWith(assignment) } }, CallExpression(path, {file: {opts: fileOpts}}) { const isPreval = looksLike(path, { node: { callee: { type: 'MemberExpression', object: {name: 'preval'}, property: {name: 'require'}, }, }, }) if (!isPreval) { return } const [source, ...args] = path.get('arguments') const argValues = args.map(a => { const result = a.evaluate() if (!result.confident) { throw new Error( 'preval cannot determine the value of an argument in preval.require', ) } return result.value }) // istanbul ignore next because I don't know how to reproduce a situation // where the filename doesn't exist or source.node.type is not StringLiteral, // but TypeScript gets mad when I don't handle that case. if (!fileOpts.filename || source.node.type !== 'StringLiteral') return const absolutePath = p.resolve( p.dirname(fileOpts.filename), source.node.value, ) const code = fs.readFileSync(require.resolve(absolutePath)) const replacement = getReplacement({ string: code, fileOpts, args: argValues, babel, }) // istanbul ignore next because this should never happen, but TypeScript needs me to handle it if (!replacement) return path.replaceWith(replacement) }, }, } } function isPrevalComment(comment: babelCore.types.Comment) { const normalisedComment = comment.value.trim().split(' ')[0].trim() return ( normalisedComment.startsWith('preval') || normalisedComment.startsWith('@preval') ) } // really difficult (impossible?) to make this work with explicit types // but if I could, I would make it this: // type LooksLikeTarget = Primitive | Function | {[key: string]: LooksLikeTarget} type LooksLikeTarget = any type LooksLikeMatch = | Primitive | ((a: LooksLikeTarget) => boolean) | {[key: string]: LooksLikeMatch} function looksLike(a: LooksLikeTarget, b: LooksLikeMatch): boolean { if (isPrimitive(b)) return a === b if (typeof b === 'function') return b(a) // istanbul ignore next because we don't have this use case // but if anyone copy/pastes this handy utility, they might need it! // eslint-disable-next-line @typescript-eslint/no-unsafe-argument if (isPrimitive(a) || typeof a === 'function') return false return Object.keys(b).every(bKey => { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access return looksLike(a[bKey], b[bKey]) }) } function isPrimitive( val: Function | Primitive | {[key: string]: unknown}, ): val is Primitive { // eslint-disable-next-line return val == null || /^[sbn]/.test(typeof val) } /* eslint @typescript-eslint/no-explicit-any: off, import/no-unassigned-import: off, import/no-dynamic-require: off, max-lines-per-function: off, */ babel-plugin-preval-5.1.0/src/macro.ts000066400000000000000000000075131417655455200176310ustar00rootroot00000000000000// const printAST = require('ast-pretty-print') import type babelCore from '@babel/core' import {createMacro} from 'babel-plugin-macros' import type {MacroHandler} from 'babel-plugin-macros' import {getReplacement} from './helpers' const prevalMacros: MacroHandler = function prevalMacros({ references, state, babel, }) { const fileOpts = state.file.opts references.default.forEach(referencePath => { const path = referencePath as babelCore.NodePath const targetPath = path.parentPath if (targetPath.type === 'TaggedTemplateExpression') { asTag( targetPath as babelCore.NodePath, fileOpts, babel, ) } else if (targetPath.type === 'CallExpression') { asFunction( targetPath as babelCore.NodePath, fileOpts, babel, ) } else if (targetPath.type === 'JSXOpeningElement') { const jsxElement = targetPath.parentPath asJSX( jsxElement as babelCore.NodePath, fileOpts, babel, ) } else if (targetPath.type === 'JSXClosingElement') { // That's okay, we already prevaled this one on its opening element. } else { throw new Error( `babel-plugin-preval/macro can only be used as tagged template expression, function call or JSX element. You tried ${targetPath.type}.`, ) } }) } function asTag( path: babelCore.NodePath, fileOpts: babelCore.TransformOptions, babel: typeof babelCore, ) { const string = path.get('quasi').evaluate().value as string const replacement = getReplacement({ string, fileOpts, babel, }) // istanbul ignore next because this should never happen, but TypeScript needs me to handle it if (!replacement) return path.replaceWith(replacement) } function asFunction( path: babelCore.NodePath, fileOpts: babelCore.TransformOptions, babel: typeof babelCore, ) { const argumentsPaths = path.get('arguments') const string = argumentsPaths[0].evaluate().value as string const replacement = getReplacement({ string, fileOpts, babel, }) // istanbul ignore next because this should never happen, but TypeScript needs me to handle it if (!replacement) return argumentsPaths[0].parentPath.replaceWith(replacement) } // eslint-disable-next-line no-unused-vars function asJSX( path: babelCore.NodePath, fileOpts: babelCore.TransformOptions, babel: typeof babelCore, ) { const children = path.get('children') as Array< babelCore.NodePath > // It's a shame you cannot use evaluate() with JSX // @ts-expect-error value isn't on all nodes const string = children[0].node.value as string const replacement = getReplacement({ string, fileOpts, babel, }) // istanbul ignore next because this should never happen, but TypeScript needs me to handle it if (!replacement) return children[0].replaceWith(replacement) const { parentPath: { // @ts-expect-error OpeningElement and ClosingElement not present on all nodes node: {openingElement, closingElement}, }, } = children[0] openingElement.name.name = 'div' closingElement.name.name = 'div' } declare function preval( literals: TemplateStringsArray, ...interpolations: Array ): any declare function preval(code: string): any // eslint-disable-next-line @typescript-eslint/no-namespace declare namespace preval { function require(modulePath: string, ...args: Array): any } export default createMacro(prevalMacros) as typeof preval /* eslint @typescript-eslint/no-explicit-any: "off", @typescript-eslint/no-unsafe-member-access: "off", */ babel-plugin-preval-5.1.0/src/object-to-ast.ts000066400000000000000000000025611417655455200212010ustar00rootroot00000000000000import type babelCore from '@babel/core' type ObjectToASTOptions = { babel: typeof babelCore fileOptions: babelCore.TransformOptions } export default function objectToAST( object: unknown, {babel, fileOptions}: ObjectToASTOptions, ) { const stringified = stringify(object) const variableDeclarationNode = babel.template(`var x = ${stringified}`, { preserveComments: true, placeholderPattern: false, ...fileOptions.parserOpts, sourceType: 'module', })() as babelCore.types.VariableDeclaration return variableDeclarationNode.declarations[0].init } function stringify(object: unknown) { // This check is necessary as `JSON.stringify` can return undefined, // however the TypeScript definition for it does not include it. // See https://github.com/microsoft/TypeScript/issues/18879 for details. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const str = JSON.stringify(object, stringifyReplacer) ?? 'undefined' return str.replace( /"__FUNCTION_START__(.*?)__FUNCTION_END__"/g, functionReplacer, ) function stringifyReplacer(_key: string, value: unknown) { if (typeof value === 'function') { return `__FUNCTION_START__${value.toString()}__FUNCTION_END__` } return value } function functionReplacer(match: string, p1: string) { return p1.replace(/\\"/g, '"').replace(/\\n/g, '\n') } } babel-plugin-preval-5.1.0/tsconfig.json000066400000000000000000000001031417655455200200640ustar00rootroot00000000000000{ "extends": "./node_modules/kcd-scripts/shared-tsconfig.json" }