Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(macro): macro for vite #386

Merged
merged 31 commits into from
Mar 15, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
2cd2549
feat: init
Aslemammad Mar 6, 2022
0a01569
remove unused
Aslemammad Mar 6, 2022
c80b38b
feat: use unreleased code
Aslemammad Mar 6, 2022
13189af
update package.json
Aslemammad Mar 6, 2022
b88f637
relint
Aslemammad Mar 6, 2022
70be59b
use node 14 for github actions
Aslemammad Mar 6, 2022
9853d38
add macro-vite to build
Aslemammad Mar 6, 2022
40b2533
add chokidar
Aslemammad Mar 6, 2022
f410386
relint
Aslemammad Mar 6, 2022
978ed75
macro vite in exports
Aslemammad Mar 6, 2022
7f16d74
use aslemammad-vite-plugin-macro
Aslemammad Mar 13, 2022
53638ee
lint
Aslemammad Mar 13, 2022
e46d1b1
add readme
Aslemammad Mar 13, 2022
cfde197
Update package.json
Aslemammad Mar 14, 2022
618cd6f
rollup
Aslemammad Mar 14, 2022
f2088b0
Merge branch 'feat/vite-macro' of github.com:Aslemammad/valtio into f…
Aslemammad Mar 14, 2022
d39150d
revert eslint
Aslemammad Mar 14, 2022
6cd5ad7
update tsconfig
Aslemammad Mar 14, 2022
6d0480c
change vite version
Aslemammad Mar 15, 2022
4a0ad46
remove skipLibCheck
Aslemammad Mar 15, 2022
3a8779e
update yarn lock
Aslemammad Mar 15, 2022
0bb36a2
add ts-ignore
Aslemammad Mar 15, 2022
385f581
add eslint comment
Aslemammad Mar 15, 2022
cad1453
revert
Aslemammad Mar 15, 2022
faec07f
patch
Aslemammad Mar 15, 2022
5a3f72e
Update package.json
Aslemammad Mar 15, 2022
6d3387e
Update package.json
Aslemammad Mar 15, 2022
417a13b
Update package.json
Aslemammad Mar 15, 2022
2a40e21
update lock
Aslemammad Mar 15, 2022
68220ea
add postinstall
Aslemammad Mar 15, 2022
0588310
remove chokidar
Aslemammad Mar 15, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test-multiple-builds.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '12'
node-version: '14'
cache: yarn
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: yarn install --frozen-lockfile --check-files
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/test-multiple-versions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '12'
node-version: '14'
dai-shi marked this conversation as resolved.
Show resolved Hide resolved
cache: yarn
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: yarn install --frozen-lockfile --check-files
Expand Down Expand Up @@ -47,7 +47,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '12'
node-version: '14'
cache: yarn
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: yarn install --frozen-lockfile --check-files
Expand Down
29 changes: 27 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
"module": "./esm/macro.js",
"import": "./esm/macro.mjs",
"default": "./macro.js"
},
"./macro/vite": {
"types": "./esm/macro/vite.d.ts",
"module": "./esm/macro/vite.js",
"import": "./esm/macro/vite.mjs",
"default": "./macro/vite.js"
}
},
"files": [
Expand All @@ -54,6 +60,7 @@
"build:vanilla": "rollup -c --config-vanilla",
"build:utils": "rollup -c --config-utils",
"build:macro": "rollup -c --config-macro",
"build:macro-vite": "rollup -c --config-macro-vite",
Aslemammad marked this conversation as resolved.
Show resolved Hide resolved
"postbuild": "yarn copy",
"eslint": "eslint --fix '*.{js,json}' '{src,tests}/**/*.{ts,tsx}'",
"eslint:ci": "eslint '*.{js,json}' '{src,tests}/**/*.{ts,tsx}'",
Expand Down Expand Up @@ -150,6 +157,8 @@
"@swc/core": "^1.2.146",
"@swc/jest": "^0.2.20",
"@testing-library/react": "^12.1.3",
"@typed-macro/core": "^1.0.0-alpha",
"@typed-macro/runtime": "^1.0.0-alpha",
"@types/babel-plugin-macros": "^2.8.5",
"@types/jest": "^27.4.1",
"@types/react": "^17.0.39",
Expand All @@ -158,6 +167,7 @@
"@typescript-eslint/parser": "^5.12.1",
"babel-plugin-macros": "^3.1.0",
"babel-plugin-tester": "^10.1.0",
"chokidar": "^3.5.3",
"concurrently": "^7.0.0",
"downlevel-dts": "^0.8.0",
"esbuild": "^0.14.23",
Expand All @@ -181,18 +191,33 @@
"rollup-plugin-terser": "^7.0.2",
"shx": "^0.3.4",
"tslib": "^2.3.1",
"typescript": "^4.5.5"
"typescript": "^4.5.5",
"vite": "^2.8.6",
"vite-plugin-macro": "^0.2.0"
},
"resolutions": {
"date-fns": "2.27.0"
},
"peerDependencies": {
"@babel/helper-module-imports": ">=7.12",
"@babel/types": ">=7.13",
"@typed-macro/core": "^1.0.0-alpha",
"@typed-macro/runtime": "^1.0.0-alpha",
"babel-plugin-macros": ">=3.0",
"react": ">=16.8"
"react": ">=16.8",
"vite": "*",
"vite-plugin-macro": "^0.2.0"
},
"peerDependenciesMeta": {
"vite": {
"optional": true
},
"@typed-macro/core": {
"optional": true
},
"@typed-macro/runtime": {
"optional": true
},
"@babel/helper-module-imports": {
"optional": true
},
Expand Down
4 changes: 4 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,13 @@ export default function (args) {
let c = Object.keys(args).find((key) => key.startsWith('config-'))
if (c) {
c = c.slice('config-'.length).replace(/_/g, '/')
if (c === 'macro-vite') {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't config-macro_vite work??

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try that (I'm having some issues with types/exports, when importing valtio/macro/vite)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean L164 does the conversion, no?

Copy link
Member Author

@Aslemammad Aslemammad Mar 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, I thought you mean the cli command? yea, it does! in the end, it's valtio/macro/vite.js

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove L165-L167,

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove L171 empty line to to remove the changes in this file.

c = 'macro/vite'
}
} else {
c = 'index'
}

return [
...(c === 'index' ? [createDeclarationConfig(`src/${c}.ts`, 'dist')] : []),
createCommonJSConfig(`src/${c}.ts`, `dist/${c}`),
Expand Down
265 changes: 265 additions & 0 deletions src/macro/_plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/*
MIT License

Copyright (c) 2021 unbyte <i@shangyes.net>

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.
*/

import { join } from 'path'
import { EnvContext, MacroProvider, Modules } from '@typed-macro/core'
import {
FilterOptions,
Runtime,
TransformerOptions,
createRuntime,
} from '@typed-macro/runtime'
import {
getPackageManager,
getProjectPath,
isString,
} from '@typed-macro/shared'
import chokidar from 'chokidar'
import {
FSWatcher,
ModuleNode,
Plugin,
ViteDevServer,
WatchOptions,
} from 'vite'

/** @internal */
export type InternalModules = Modules & {
__setServer: (server: ViteDevServer) => void
}

export function createModules(_server?: ViteDevServer): InternalModules {
const container: Map<string, string> = new Map()
const queryByTag = (pattern: RegExp | string) => {
const result: string[] = []
const checker = isString(pattern)
? (tag: string, id: string) => pattern === tag && result.push(id)
: (tag: string, id: string) => pattern.test(tag) && result.push(id)
container.forEach(checker)
return result
}
const invalidateByTag = (pattern: RegExp | string) => {
const invalidatedFiles: string[] = []
const seen: Set<ModuleNode> = new Set()
for (const file of queryByTag(pattern)) {
const module = _server?.moduleGraph.getModuleById(file)
if (module) {
invalidatedFiles.push(file)
_server?.moduleGraph.invalidateModule(module, seen)
} else {
container.delete(file)
}
}
return invalidatedFiles
}

return {
getTag(id) {
return container.get(id)
},
setTag(id, tag) {
container.set(id, tag)
},
unsetTag(id) {
container.delete(id)
},
queryByTag,
invalidateByTag,
__setServer: (server) => (_server = server),
}
}

export function createEnvContext(
dev: boolean,
ssr: boolean,
watcherOptions?: WatchOptions
): EnvContext {
const projectPath = getProjectPath()
const packageManager =
projectPath.length > 0
? // @ts-ignore
getPackageManager(projectPath[0])
: /* istanbul ignore next */ 'unknown'

const watcher = dev
? (new chokidar.FSWatcher({
ignoreInitial: true,
ignorePermissionErrors: true,
...watcherOptions,
}) as FSWatcher)
: undefined

const modules = dev ? createModules() : undefined

// @ts-ignore
return {
host: 'vite',
projectPath,
packageManager,
dev,
ssr,
watcher,
modules,
}
}

export type MacroPlugin = Plugin & {
/**
* Register macro providers to this macro manager so that
* all macros in providers and plugins share the same runtime.
*
* For macro plugins:
* > Some options like `maxTraversals` or `typesPath` will be overridden by
* > manager's, `parserPlugins` will be merged with the manager's one.
* >
* > After registered, the original macro plugin will be attached to the manager,
* > which means no need to add the plugin to Vite/Rollup 's plugins array again.
* @param sources macro providers or plugins.
*/
use(...sources: MacroProvider[]): MacroPlugin
}

export type MacroPluginOptions = FilterOptions &
TransformerOptions & {
/**
* The path of the automatically generated type declaration file.
*
* @default '<projectDir>/macros.d.ts'
*/
typesPath?: string

/**
* Is in dev mode.
*
* @default mode !== 'production'
* @see https://vitejs.dev/guide/env-and-mode.html#modes
*/
dev?: boolean

/**
* Is in SSR mode.
*
* @default whether there is an SSR configuration
* @see https://vitejs.dev/guide/ssr.html
*/
ssr?: boolean

/**
* Configure chokidar FSWatcher.
*
* @see https://github.com/paulmillr/chokidar#api
*/
watcherOptions?: WatchOptions
}

/**
* Create macro plugin.
*
* For example,
* ```typescript
* // vite.config.ts
*
* export default defineConfig({
* plugins: [
* createMacroPlugin({ ... })
* .use(provideSomeMacros({ ... }))
* ],
* })
* ```
*/
export function createMacroPlugin(
/* istanbul ignore next */
options: MacroPluginOptions = {}
): MacroPlugin {
const {
exclude,
include,
maxTraversals,
typesPath,
dev,
ssr,
watcherOptions,
parserPlugins,
} = options

const uninstantiatedProviders: MacroProvider[] = []

let runtime: Runtime | undefined

const plugin: MacroPlugin = {
use(...sources) {
uninstantiatedProviders.push(...sources)
return plugin
},
name: 'vite-plugin-macro',
enforce: 'pre',
configResolved: async (config) => {
// create env
const env = createEnvContext(
dev ?? !config.isProduction,
ssr ?? !!config.build.ssr,
watcherOptions
)

// init runtime
runtime = createRuntime(env, {
// @ts-ignore
filter: { exclude, include },
// @ts-ignore
transformer: { maxTraversals, parserPlugins },
})

// add providers
uninstantiatedProviders.forEach((provider) => {
runtime!.appendProvider(provider)
})

// call onStart hook and render types
await Promise.all([
runtime!.start(),
runtime!.renderTypes(
/* @ts-ignore istanbul ignore next */
typesPath || join(env.projectPath[0], 'macros.d.ts')
),
])
},
configureServer: async (server) => {
// @ts-ignore
;(runtime!.internal.env.modules as InternalModules).__setServer(server)
},
resolveId: (id) => runtime?.resolveId(id),
load: (id) => runtime?.load(id),
transform: async (code, id) => {
if (!(await runtime?.filter(id))) return
const result = await runtime?.transform(code, id)
return result && { code: result, map: null }
},
buildEnd: async () => {
await runtime!.stop()
},
}

return plugin
}
Loading