@lls/vitescripts 1.0.0-cb9fe24a9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,10 +4,4 @@ lls vite plugins
4
4
 
5
5
  Purpose is to factorize vite plugin scripts
6
6
 
7
- ## deploy
8
-
9
- ```
10
- npm version patch
11
- git push && git push origin $(git describe --tags --abbrev=0)
12
- npm publish
13
- ```
7
+ TODO: describe plugin usage
package/package.json CHANGED
@@ -1,30 +1,16 @@
1
1
  {
2
2
  "name": "@lls/vitescripts",
3
- "version": "1.0.0-cb9fe24a9",
3
+ "version": "1.0.0",
4
4
  "description": "lls vite plugins",
5
5
  "main": "src/index.mjs",
6
- "files": [
7
- "src/"
8
- ],
6
+ "files": ["src/"],
7
+ "scripts": {
8
+ "test": "echo \"Error: no test specified\" && exit 1"
9
+ },
9
10
  "dependencies": {
10
- "browserslist": "4.22.1",
11
- "esbuild-plugin-lightningcss-modules": "0.1.1",
12
- "lightningcss": "1.22.1"
11
+ "vite-plugin-require-transform": "1.0.9"
13
12
  },
14
13
  "type": "module",
15
14
  "author": "",
16
- "license": "ISC",
17
- "devDependencies": {
18
- "@lls/lls-kit": "23.0.0",
19
- "lodash": "4.17.21",
20
- "nano-staged": "0.8.0",
21
- "vitest": "1.0.4"
22
- },
23
- "nano-staged": {
24
- "*.{js,jsx,mjs,tsx,ts}": "pnpm vitest related --run"
25
- },
26
- "scripts": {
27
- "test": "pnpm vitest run",
28
- "precommit": "pnpm nano-staged"
29
- }
30
- }
15
+ "license": "ISC"
16
+ }
package/src/index.mjs CHANGED
@@ -1,10 +1,7 @@
1
- export { default as llsAssetsPlugin } from './llsAssetsPlugin.mjs'
2
- export { default as llsLinariaImportsPlugin } from './llsLinariaImportsPlugin.mjs'
3
- export { default as llsCssSsrCollectPlugin } from './llsCssSsrCollectPlugin.mjs'
4
- export { default as llsSideRefreshMetaPlugin } from './llsSideRefreshMetaPlugin.mjs'
5
- export { default as llsVitestMockPlugin } from './llsVitestMockPlugin.mjs'
6
- export { default as llsLadlePlugin } from './llsLadlePlugin.mjs'
7
- export { default as llsCssModuleMacroPlugin } from './llsCssModuleMacroPlugin.mjs'
8
- export { default as postBuildAutoprefixerPlugin } from './postBuildAutoprefixerPlugin.mjs'
9
- export { default as esbuildCssModulePlugin } from './esbuildCssModulePlugin.mjs'
10
- export { default as postBuildTsTypesPlugin } from './postBuildTsTypes.mjs'
1
+ export { default as llsAssetsPlugin } from './llsAssetsPlugin'
2
+ export { default as llsLinariaImportsPlugin } from './llsLinariaImportsPlugin'
3
+ export { default as llsLinariaSsrCollectPlugin } from './llsLinariaSsrCollectPlugin'
4
+ export { default as llsRequirePlugin } from './llsRequirePlugin'
5
+ export { default as llsSideRefreshMetaPlugin } from './llsSideRefreshMetaPlugin'
6
+ export { default as llsVitestMockPlugin } from './llsVitestMock'
7
+ export { default as llsLadlePlugin } from './llsLadlePlugin'
@@ -2,48 +2,22 @@ import fs from 'fs'
2
2
  import { promisify } from 'util'
3
3
  import { exec } from 'node:child_process'
4
4
  import path from 'path'
5
+ import VitePluginRequireTransform from 'vite-plugin-require-transform'
5
6
  const execP = promisify(exec)
7
+ const pwd = process.cwd()
6
8
 
7
9
  // https://github.com/vitejs/vite/pull/8574
8
- /**
9
- * Plugin that will copy assets from given repos to public dir of launched project
10
- * @param {*} llsRepos array containing names of the repos
11
- * @param {*} publicDir public dir to copy assets to
12
- * @returns config() method that copies assets
13
- * transform() method that replaces assets path to be resolved
14
- */
15
- const llsAssetsPlugin = (llsRepos, publicDir = 'ladleassets', { stripRoot = true } = {}) => {
10
+ const llsAssetsPlugin = (llsRepos, publicDir = 'ladleassets') => {
16
11
  const publicAssetDir = path.join(publicDir, 'assets')
17
12
  const fileExists = (s) => new Promise(resolve => fs.access(s, e => resolve(!e)))
18
13
  const srcRoot = process.cwd() + '/src'
19
14
  const storyRoot = process.cwd() + '/stories'
20
-
21
- if (process.env.VITEST) {
22
- return
23
- }
24
15
  return {
25
16
  name: 'lls:copyassets',
26
- async config () {
17
+ async config(conf, { command }) {
27
18
  await execP(`mkdir -p ${publicAssetDir}`)
28
- const pnpmNameToPath = await execP('pnpm ls -r @lls/lls-drawer --json'/*'pnpm ls -r -d 0 --json'*/)
29
- .then(({ stdout }) => JSON.parse(stdout))
30
- .then(json => {
31
- let drawer = null
32
- const back = json.map(({ name, path, dependencies }) => {
33
- if (dependencies?.['@lls/lls-drawer']?.path) {
34
- drawer = ['@lls/lls-drawer', dependencies?.['@lls/lls-drawer']?.path + '/lib/assets/*']
35
- }
36
- return [name, path + '/lib/assets/*']
37
- })
38
- return back.concat(drawer ? [drawer] : [])
39
- })
40
- .then(Object.fromEntries)
41
- .catch(e => {})
42
19
  const repoArgs = await Promise.all(llsRepos.map(async repo => {
43
20
  if (!repo.startsWith('@')) return repo
44
- const pnpmPath = pnpmNameToPath[repo]
45
- if (pnpmPath) return pnpmPath
46
-
47
21
  const aPath = 'lib/assets/*'
48
22
  const prefix = await fileExists(`${process.cwd()}/node_modules/${repo}`)
49
23
  ? `${process.cwd()}/node_modules/${repo}`
@@ -55,23 +29,21 @@ const llsAssetsPlugin = (llsRepos, publicDir = 'ladleassets', { stripRoot = true
55
29
  await execP(`cp -rf ${repo} ${publicAssetDir}`)
56
30
  }
57
31
  },
58
- ...(stripRoot && {
59
- transform (src, id) {
60
- if (
61
- llsRepos.some(repo => id.includes(repo)) ||
32
+ transform(src, id) {
33
+ if (
34
+ llsRepos.some(repo => id.includes(repo)) ||
62
35
  id.startsWith(srcRoot) ||
63
36
  id.startsWith(storyRoot)
64
- ) {
37
+ ) {
65
38
  // workaround because we don't use /assets (maybe we should ?)
66
39
  // specs orders than relative path in css is current container
67
40
  // so use relative path instead of / being the "fqdn"
68
- return {
69
- code: src.replace(/(= |url\(|Worker\()(['"])\/assets/g, '$1$2assets'),
70
- map: null
71
- }
41
+ return {
42
+ code: src.replace(/(= |url\(|Worker\()(['"])\/assets/g, '$1$2assets'),
43
+ map: null
72
44
  }
73
45
  }
74
- })
46
+ }
75
47
  }
76
48
  }
77
49
 
@@ -1,10 +1,18 @@
1
+ import fs from 'fs'
2
+ import { promisify } from 'util'
3
+ import { exec } from 'node:child_process'
4
+ import path from 'path'
5
+ import VitePluginRequireTransform from 'vite-plugin-require-transform'
6
+ const execP = promisify(exec)
7
+ const pwd = process.cwd()
8
+
1
9
  const llsLadlePlugin = (sbFolder) => ({
2
10
  name: 'lls:llsLadlePlugin',
3
- config (config, { command }) {
11
+ config(config, { command }) {
4
12
  const ladleCiEnv = /prod|tag|master|v\d/.test(process.env.LADLE_DEST) ? 'prod' : 'dev'
5
13
  return {
6
14
  base: command === 'serve' ? '/' : `https://build.lelivrescolaire.fr/storybook/${sbFolder}-${ladleCiEnv}/`,
7
- // base: command === 'serve' ? '/' : 'http://localhost:5000/ladledist/',
15
+ //base: command === 'serve' ? '/' : 'http://localhost:5000/ladledist/',
8
16
 
9
17
  build: {
10
18
  minify: false
@@ -13,4 +21,4 @@ const llsLadlePlugin = (sbFolder) => ({
13
21
  }
14
22
  })
15
23
 
16
- export default llsLadlePlugin
24
+ export default llsLadlePlugin
@@ -1,9 +1,15 @@
1
- const llsLinariaImports = ({ client } = {}) => {
1
+ import fs from 'fs'
2
+ import { promisify } from 'util'
3
+ import { exec } from 'node:child_process'
4
+ import path from 'path'
5
+ import VitePluginRequireTransform from 'vite-plugin-require-transform'
6
+ const execP = promisify(exec)
7
+ const pwd = process.cwd()
8
+
9
+ const llsLinariaImports = () => {
2
10
  return {
3
11
  name: 'lls:linaria-imports',
4
- load (id) {
5
- console.log('llsLinariaImports plugin is deprecated, remove usage. Already handled by llsSideRefreshMetaPlugin')
6
- if (client) return
12
+ load(id) {
7
13
  if (id.endsWith('@lls/viewer/lib/assets/viewer.css')) { return '' }
8
14
  if (id.endsWith('@lls/superkit/lib/assets/superkit.css')) { return '' }
9
15
  if (id.endsWith('@lls/lls-kit/lib/assets/lls-kit.css') || id.endsWith('@lls/lls-kit/lib/assets/lls-kit-fonts.css')) {
@@ -11,7 +17,6 @@ const llsLinariaImports = ({ client } = {}) => {
11
17
  }
12
18
  if (id.endsWith('@lls/lls-drawer/lib/assets/lls-drawer.css')) { return '' }
13
19
  if (id.endsWith('@lls/lls-code/lib/assets/lls-code.css')) { return '' }
14
- if (id.endsWith('@lls/core/lib/assets/core.css')) { return '' }
15
20
  }
16
21
  }
17
22
  }
@@ -0,0 +1,27 @@
1
+ import fs from 'fs'
2
+ import { promisify } from 'util'
3
+ import { exec } from 'node:child_process'
4
+ import path from 'path'
5
+ import VitePluginRequireTransform from 'vite-plugin-require-transform'
6
+ const execP = promisify(exec)
7
+ const pwd = process.cwd()
8
+
9
+ const llsLinariaSsrCollectPlugin = () => {
10
+ const cssIds = new Set()
11
+ let linariaPlugin
12
+ return {
13
+ name: 'lls:llsLinariaSsrCollect',
14
+ config (config) {
15
+ linariaPlugin = config.plugins.find(plugin => plugin.name === 'linaria')
16
+ },
17
+ async resolveId(id, from) {
18
+ if (id.includes('@linaria-cache')) { cssIds.add(id); return }
19
+ },
20
+
21
+ collectSsrStyles () {
22
+ return `<style>${[...cssIds].map(linariaPlugin.load).join('\n')}</style>`
23
+ }
24
+ }
25
+ }
26
+
27
+ export default llsLinariaSsrCollectPlugin
@@ -0,0 +1,28 @@
1
+ import fs from 'fs'
2
+ import { promisify } from 'util'
3
+ import { exec } from 'node:child_process'
4
+ import path from 'path'
5
+ import VitePluginRequireTransform from 'vite-plugin-require-transform'
6
+ const execP = promisify(exec)
7
+ const pwd = process.cwd()
8
+
9
+ // needed for viewer if siderefresh
10
+ const llsSsrRequirePlugin = () => {
11
+ const fileRegex = /(?:(Audio|Recorder|Python|Video|QuestionRich|CodemirrorEditor|useLazyModule)\.jsx$|@lls_lls-code)/
12
+ const back = VitePluginRequireTransform({ fileRegex })
13
+ return {
14
+ name: 'lls:require',
15
+ transform: async function (code, id) {
16
+ const { transform } = await back
17
+ if (fileRegex.test(id)) {
18
+ code = code.replace(/interop\(require\(['"][^'"]+\.browser['"]\)\)/, '() => null')
19
+ }
20
+ return {
21
+ ...await transform.apply(this, [code, id]),
22
+ map: null
23
+ }
24
+ }
25
+ }
26
+ }
27
+
28
+ export default llsSsrRequirePlugin
@@ -1,91 +1,42 @@
1
1
  import fs from 'fs'
2
+ import { promisify } from 'util'
3
+ import { exec } from 'node:child_process'
2
4
  import path from 'path'
5
+ import VitePluginRequireTransform from 'vite-plugin-require-transform'
6
+ const execP = promisify(exec)
7
+ const pwd = process.cwd()
3
8
 
4
- const toLocal = pkgName => new URL(pkgName, import.meta.url).pathname
5
- const pwd = toLocal('../')
6
9
 
7
- // sideRefreshActiveModules is of the form ['viewer', 'superkit', ...] with 'viewer' if repo launched
8
- // WITH_VIEWER=1 npm start
9
- export const makeSideRefreshThemeInterceptor = async (sideRefreshActiveModules) => {
10
- const parentDir = path.basename(path.dirname(process.cwd()))
11
- const sideRefreshThemes = {}
12
- const cssThemeMap = {
13
- viewer: path.join(pwd, '../viewer/src/utils/css-bare.mjs'),
14
- // kit: no themes for kit
15
- superkit: path.join(pwd, '../superkit/src/internals/utils/css-bare.mjs'),
16
- core: path.join(pwd, '../core/src/utils/css-bare.mjs'),
17
- audio: path.join(pwd, '../lls-audio/src/utils/css-bare.mjs'),
18
- code: path.join(pwd, '../lls-code/src/utils/css-bare.mjs')
19
- }
20
- await Promise.all(Object.keys(cssThemeMap).map(sideRefreshName => {
21
- if (!cssThemeMap[sideRefreshName]) {
22
- throw new Error('invalid side refresh name' + sideRefreshName)
23
- }
24
- return import(cssThemeMap[sideRefreshName]).then(m => {
25
- const mod = m.default || m
26
- sideRefreshThemes[`${sideRefreshName}_dark`] = mod.themeIsDarkMode
27
- sideRefreshThemes[`${sideRefreshName}_free`] = mod.themeIsFreeMode
28
- sideRefreshThemes[`${sideRefreshName}_light`] = mod.themeIsNotDarkMode
29
- })
30
- }))
31
- const folderRegex = new RegExp(Object.keys(sideRefreshThemes).map(capName => parentDir + '/' + capName.split('_')[0]).join('|'))
32
- return (cap, id, next) => {
33
- const match = id.match(folderRegex)?.[0]
34
- cap = match ? `${match.split('/')[1]}_${cap}` : cap
35
- return match && sideRefreshThemes[cap] ? sideRefreshThemes[cap] : next(cap)
36
- }
37
- }
38
-
39
- /**
40
- * Side refresh plugin for LLS clients
41
- * @param {*} param specifies which dependency is beign sideRefreshed
42
- * @returns a plugin to pass to vite and aliases for sideRefreshed packages
43
- */
44
- const llsSideRefreshMetaPlugin = ({ audio: iAudio, viewer: iViewer, superkit: iSuperkit, kit: iKit, utils: iUtils, core: iCore, code: iCode }, { client, publicDir = 'ladleassets' } = {}) => {
45
- const pwd = process.cwd()
46
- let activeModules = []
47
- if ([iViewer, iSuperkit, iKit, iUtils, iCore, iCode, iAudio].some(x => x)) {
48
- activeModules = [
49
- iViewer && 'viewer',
50
- iSuperkit && 'superkit',
51
- iKit && 'kit',
52
- iUtils && 'utils',
53
- iCore && 'core',
54
- iCode && 'code',
55
- iAudio && 'audio'
56
- ].filter(Boolean)
57
- // eslint-disable-next-line no-console
58
- console.log('sideResfresh: ', activeModules)
59
- }
60
-
61
- const makeResolver = (dirname, aliasImport) => {
62
- const projectPath = path.resolve(pwd, '../', dirname)
63
- const projectDir = path.join(projectPath, 'src/')
64
- const projectDirs = fs.readdirSync(projectDir).map(x => x.replace(/\.[jt]sx?$/, ''))
10
+ const llsSideRefreshMetaPlugin = ({
11
+ viewer: iViewer = process.env.WITH_VIEWER === '1',
12
+ superkit: iSuperkit = process.env.WITH_SUPERKIT === '1',
13
+ kit: iKit = process.env.WITH_KIT === '1'
14
+ }) => {
15
+ if (!iViewer && !iSuperkit && !iKit) { return { plugin: () => false, alias: {} } }
16
+ console.log('sideResfresh: ', [iViewer && 'viewer', iSuperkit && 'superkit', iKit && 'lls-kit'].filter(Boolean))
17
+ const makeResolver = dirname => {
18
+ const viewerPath = path.resolve(pwd, '../', dirname)
19
+ const viewerDir = path.join(viewerPath, 'src/')
20
+ const viewerDirs = fs.readdirSync(viewerDir).map(x => x.replace(/\.[jt]sx?$/,''))
65
21
  return {
66
- async resolve(id, from) {
67
- if (projectDirs.some(dir => id.startsWith(dir))) {
22
+ async resolve (id, from) {
23
+ if (viewerDirs.some(dir => id.startsWith(dir))) {
68
24
  try {
69
- const resolution = await this.resolve(projectDir + id, from, { skipSelf: true })
25
+ const resolution = await this.resolve(viewerDir + id, from, { skipSelf: true })
70
26
  return resolution.id
71
27
  } catch (e) {
28
+ return
72
29
  }
73
30
  }
74
31
  },
75
32
  alias: {
76
- // kit has no public/assets folder, and should fallback to next case (/lib)
77
- ...(dirname === 'lls-kit'
78
- ? {}
79
- : { ['@lls/' + dirname + '/lib/assets']: path.join(projectPath, 'static/assets') }
80
- ),
81
- // handle multiple cases : @lls/superkit/lib, @lls/superkit, @superkit, or alias import
82
- ['@lls/' + dirname + '/lib']: path.join(projectPath, 'src'),
83
- ['@lls/' + dirname]: path.join(projectPath, 'src/index'),
84
- ['@' + dirname]: path.join(projectPath, 'src'),
85
- [aliasImport || '@' + dirname]: path.join(projectPath, 'src')
33
+ ['@lls/'+dirname+'/lib/assets'] : path.join(viewerPath, 'public/assets'),
34
+ ['@lls/'+dirname+'/lib'] : path.join(viewerPath, 'src'),
35
+ ['@lls/'+dirname]: path.join(viewerPath, 'src/index.jsx'),
36
+ ['@'+dirname]: path.join(viewerPath, 'src')
86
37
  },
87
- shouldResolve(from) {
88
- return from.includes(dirname)
38
+ shouldResolve (from) {
39
+ return from.includes(dirname) && !from.includes('webview')
89
40
  }
90
41
  }
91
42
  }
@@ -93,58 +44,35 @@ const llsSideRefreshMetaPlugin = ({ audio: iAudio, viewer: iViewer, superkit: iS
93
44
  shouldResolve: () => false,
94
45
  alias: {}
95
46
  })
96
- const viewer = (iViewer && makeResolver('viewer')) || makeNoopResolver()
97
- const superkit = (iSuperkit && makeResolver('superkit')) || makeNoopResolver()
98
- const kit = (iKit && makeResolver('lls-kit', '@kit')) || makeNoopResolver()
99
- const utils = (iUtils && makeResolver('utils', '@utils')) || makeNoopResolver()
100
- const core = (iCore && makeResolver('core', '@core')) || makeNoopResolver()
101
- const code = (iCode && makeResolver('lls-code', '@code')) || makeNoopResolver()
102
- const audio = (iAudio && makeResolver('lls-audio', '@audio')) || makeNoopResolver()
103
-
104
- const VIRTUAL_ID = 'sideRefresh/node_modules' // specify node_modules to bypass linaria plugin parsing css file... (cant tweak exclude regex)
105
- const key = basename => path.join(pwd, publicDir, 'assets', basename)
106
- const loads = new Map(['core.css', 'viewer.css', 'superkit.css', 'lls-kit.css', 'lls-kit-fonts.css', 'lls-audio.css', 'lls-code.css', 'lls-audio.css'].map(basename => {
107
- let promise = ''
108
- const getPromise = () => {
109
- if (client && !pwd.includes(basename.replace('.css', ''))) {
110
- promise = fs.promises.readFile(key(basename), 'utf8')
111
- }
112
- return promise
113
- }
114
- return [VIRTUAL_ID + key(basename), getPromise]
115
- }))
47
+ const viewer = iViewer && makeResolver('viewer') || makeNoopResolver()
48
+ const superkit = iSuperkit && makeResolver('superkit') || makeNoopResolver()
49
+ const kit = iKit && makeResolver('lls-kit') || makeNoopResolver()
50
+
116
51
  const plugin = () => ({
117
52
  name: 'lls:sideRefresh',
118
- async resolveId(id, from) {
119
- const basename = path.basename(id)
120
- if (['core.css', 'viewer.css', 'superkit.css', 'lls-kit.css', 'lls-kit-fonts.css', 'lls-audio.css', 'lls-code.css', 'lls-audio.css'].includes(basename)) {
121
- return VIRTUAL_ID + key(basename)
122
- }
53
+ async resolveId (id, from) {
54
+ if (id.endsWith('viewer.css') && from.includes('viewer')) { return 'llslinaria' }
55
+ if (id.endsWith('superkit.css') && from.includes('superkit')) { return 'llslinaria' }
56
+ if (id.endsWith('lls-kit.css') && from.includes('lls-kit')) { return 'llslinaria' }
123
57
  if (viewer.shouldResolve(from)) { return viewer.resolve.call(this, id, from) }
124
58
  if (superkit.shouldResolve(from)) { return superkit.resolve.call(this, id, from) }
125
59
  if (kit.shouldResolve(from)) { return kit.resolve.call(this, id, from) }
126
- if (utils.shouldResolve(from)) { return utils.resolve.call(this, id, from) }
127
- if (core.shouldResolve(from)) { return core.resolve.call(this, id, from) }
128
- if (code.shouldResolve(from)) { return code.resolve.call(this, id, from) }
129
- if (audio.shouldResolve(from)) { return audio.resolve.call(this, id, from) }
130
60
  },
131
61
 
132
- async load(id) {
133
- if (loads.has(id)) {
134
- return loads.get(id)()
135
- }
62
+ load (id) {
63
+ if (id === 'llslinaria') { return '' }
136
64
  }
137
65
  })
138
66
  const alias = {
139
67
  ...viewer.alias,
140
- ...superkit.alias,
141
- ...kit.alias,
142
- ...utils.alias,
143
- ...core.alias,
144
- ...code.alias,
145
- ...audio.alias
68
+ ...superkit.alias
146
69
  }
147
- return { plugin, alias, activeModules }
70
+ plugin.ssrOptions = { noExternal: [
71
+ iViewer && '@lls/viewer',
72
+ iSuperkit && '@lls/superkit',
73
+ iKit && '@lls/lls-kit'
74
+ ].filter(Boolean) }
75
+ return { plugin, alias }
148
76
  }
149
77
 
150
- export default llsSideRefreshMetaPlugin
78
+ export default llsSideRefreshMetaPlugin
@@ -1,6 +1,14 @@
1
+ import fs from 'fs'
2
+ import { promisify } from 'util'
3
+ import { exec } from 'node:child_process'
4
+ import path from 'path'
5
+ import VitePluginRequireTransform from 'vite-plugin-require-transform'
6
+ const execP = promisify(exec)
7
+ const pwd = process.cwd()
8
+
1
9
  const llsVitestMock = () => ({
2
10
  name: 'lls:vitestmock',
3
- transform (code, id) {
11
+ transform(code, id) {
4
12
  if (id.endsWith('@lls/viewer/lib/index.js')) {
5
13
  return code
6
14
  .replace(/require\("(@lls\/lls-audio|@lls\/lls-code|@yorab\/react-paint)"\)/g, (__, cap) => {
@@ -11,4 +19,4 @@ const llsVitestMock = () => ({
11
19
  }
12
20
  })
13
21
 
14
- export default llsVitestMock
22
+ export default llsVitestMock
@@ -1,43 +0,0 @@
1
- import fs from 'fs'
2
- import path from 'path'
3
- import llsCssModuleMacroPlugin from './llsCssModuleMacroPlugin.mjs'
4
- import { cssModules } from 'esbuild-plugin-lightningcss-modules'
5
-
6
- export default ({ prefix = '', llsCssModuleMacroPluginArg }) => {
7
- const esbuildCssModule = cssModules({
8
- targets: { chrome: 80 << 16 },
9
- drafts: { nesting: true },
10
- cssModulesPattern: `${prefix ? prefix + '-' : ''}[hash]-[local]`
11
- })
12
- const tmpDir = path.join(process.cwd(), 'tmp_esbuild')
13
- return [
14
- {
15
- name: 'lls-cssmodule',
16
- async setup (build) {
17
- await fs.promises.mkdir(tmpDir, { recursive: true })
18
- const llsCssModuleMacroPluginInstance = await llsCssModuleMacroPlugin(llsCssModuleMacroPluginArg)
19
-
20
- // need to add the generated files to esbuild pipeline
21
- build.onResolve({ filter: /tmp_esbuild/ }, async args => {
22
- return { path: args.path }
23
- })
24
- build.onLoad({ filter: /module\.css$/ }, async args => {
25
- if (args.path.startsWith(tmpDir)) return
26
-
27
- const contents = await fs.promises.readFile(args.path, 'utf8').then(str => llsCssModuleMacroPluginInstance.transform(str, args.path))
28
- const id = args.path.replace(process.cwd(), '').replace(/\//g, '_')
29
- const out = path.join(tmpDir, id)
30
- await fs.promises.writeFile(out, contents)
31
- return {
32
- contents: `export { default } from '${out}'`,
33
- loader: 'js'
34
- }
35
- })
36
- build.onEnd(async () => {
37
- await fs.promises.rm(tmpDir, { recursive: true })
38
- })
39
- }
40
- },
41
- esbuildCssModule
42
- ]
43
- }
@@ -1,140 +0,0 @@
1
- import { transform as lightTransform } from 'lightningcss'
2
- import { makeSideRefreshThemeInterceptor } from './llsSideRefreshMetaPlugin.mjs'
3
-
4
- const llsCssModuleMacroPlugin = async ({ themeIsFreeMode, themeIsDarkMode, themeIsNotDarkMode, sideRefreshActiveModules = [] }) => {
5
- const keepProperties = [
6
- 'Supporting',
7
- 'Button1',
8
- 'Button2',
9
- 'Body1',
10
- 'Body2',
11
- 'Body3',
12
- 'RippleEffect',
13
- 'Heading1',
14
- 'Heading2',
15
- 'Heading3',
16
- 'Heading4',
17
- 'ThemeCss',
18
- 'FontFamily'
19
- ]
20
- const kitBag = await import('@lls/lls-kit')
21
- .then(m => m.default || m)
22
- .then(obj => Object.fromEntries(keepProperties.map(property => [property, obj[property]])))
23
-
24
- const cssMacroTheme = {
25
- themeIsFreeMode,
26
- themeIsDarkMode,
27
- themeIsNotDarkMode,
28
- dark: themeIsDarkMode,
29
- free: themeIsFreeMode,
30
- light: themeIsNotDarkMode
31
- }
32
- const replaceKitBag = (__, cap) => kitBag[cap]
33
-
34
- const interceptSideRefreshTheme = await makeSideRefreshThemeInterceptor(sideRefreshActiveModules)
35
- // replaces dark from @llsTheme(dark) with proper css macro
36
- const replaceTheme = (cap, id) => {
37
- // try to resolve proper macro from siderefreshed directory
38
- // otherwise defaults to standard resolving
39
- return interceptSideRefreshTheme(cap, id, (cap) => {
40
- const back = cssMacroTheme[cap]
41
- if (!back) {
42
- throw new Error('llsCssModuleMacroPlugin::missing definition for ' + cap)
43
- }
44
- return back
45
- })
46
- }
47
- const replaceGetFluidSize = (__, cap) => {
48
- const args = {
49
- minViewport: 320, // BREAKPOINT_XXS
50
- maxViewport: 1280, // BREAKPOINT_MD
51
- minSize: undefined,
52
- maxSize: undefined
53
- }
54
- for (const a of cap.matchAll(/(?<prop>maxSize|minSize|minViewport|maxViewport)\s*:\s*(?<value>.+?)(?=[,]|\s|$)/g)) {
55
- args[a.groups.prop] = a.groups.value
56
- }
57
- const { maxSize, minSize, minViewport, maxViewport } = args
58
- return `min(${maxSize}px, max(${minSize}px, calc(${minSize}px + (${maxSize} - ${minSize}) * ((100vw - ${minViewport}px) / (${maxViewport} - ${minViewport})))))`
59
- }
60
-
61
- // lightningcss helpers
62
- const token = (type) => ({ type: 'token', value: { type } })
63
- const delim = (operator) => ({ type: 'token', value: { type: 'delim', value: operator } })
64
- const length = (value, unit) => ({ type: 'length', value: { value, unit } })
65
- const func = (name, args) => ({ type: 'function', value: { name, arguments: args } })
66
- const num = value => ({ type: 'token', value: { type: 'number', value } })
67
- return {
68
- enforce: 'pre',
69
- transform (src, id) {
70
- if (!/module\.css(\?.*)?$/.test(id)) {
71
- return undefined
72
- }
73
- const back = src
74
- .replace(/@cx\((Body[123]|Heading[1234]|Button[12]|Supporting|RippleEffect|FontFamily)\)/g, replaceKitBag)
75
- .replace(/\${(Body[123]|Heading[1234]|Button[12]|Supporting|RippleEffect|FontFamily)}/g, replaceKitBag)
76
- .replace(/\${(themeIsFreeMode|themeIsDarkMode|themeIsNotDarkMode)}/g, (__, cap) => replaceTheme(cap, id))
77
- .replace(/@llsTheme\((dark|light|free)\)/g, (__, cap) => replaceTheme(cap, id))
78
-
79
- .replace(/\${getFluidSize\({(.*?)}\)}/gs, replaceGetFluidSize)
80
- .replace(/\${getTruePx\((.*?)\)}?/g, 'calc(var(--size-index, 1) * $1 * 1px)')
81
-
82
- const { code } = lightTransform({
83
- code: Buffer.from(back),
84
- visitor: {
85
- Function: {
86
- getTruePx ({ arguments: [value] }) {
87
- return {
88
- type: 'function',
89
- value: {
90
- name: 'calc',
91
- arguments: [
92
- value.type !== 'token' && token('parenthesis-block'),
93
- value,
94
- value.type !== 'token' && token('close-parenthesis'),
95
- delim('*'),
96
- { type: 'var', value: { name: { ident: '--size-index', from: null }, fallback: [{ type: 'token', value: { type: 'number', value: 1 } }] } },
97
- delim('*'),
98
- length(1, 'px')
99
- ].filter(Boolean)
100
- }
101
- }
102
- },
103
- getFluidSize ({ arguments: [minSize, comma1, maxSize, comma2, iMinViewport, comma3, iMaxViewport] }) {
104
- const minViewport = (typeof (iMinViewport) === 'undefined' || iMinViewport.value?.type === 'comma') ? length(320, 'px') : iMinViewport
105
- const max = iMinViewport?.value?.type === 'comma' ? comma3 : iMaxViewport
106
- const maxViewport = typeof (max) === 'undefined' ? length(1280, 'px') : max
107
- return func('min', [
108
- maxSize,
109
- token('comma'),
110
- func('max', [
111
- minSize,
112
- token('comma'),
113
- func('calc', [
114
- minSize,
115
- delim('+'),
116
- num(maxSize?.value?.value - minSize?.value?.value),
117
- delim('*'),
118
- token('parenthesis-block'),
119
- token('parenthesis-block'),
120
- length(100, 'vw'),
121
- delim('-'),
122
- minViewport,
123
- token('close-parenthesis'),
124
- delim('/'),
125
- num(maxViewport?.value?.value - minViewport?.value.value),
126
- token('close-parenthesis')
127
- ])
128
- ])
129
- ])
130
- }
131
- }
132
- }
133
- })
134
-
135
- return code.toString()
136
- }
137
- }
138
- }
139
-
140
- export default llsCssModuleMacroPlugin
@@ -1,25 +0,0 @@
1
- /**
2
- * flushStyles() method that generates and return <style> tag with refreshed style
3
- */
4
- import { transform } from 'lightningcss'
5
- const llsCssSsrCollectPlugin = () => {
6
- const cssIds = new Map()
7
- return {
8
- name: 'lls:llsCssSsrCollectPlugin',
9
- transform (src, id) {
10
- if (/module\.css$/.test(id)) {
11
- cssIds.set(id, src)
12
- }
13
- },
14
- flushStyles () {
15
- const css = [...cssIds.values()].join('\n')
16
-
17
- // when hmr, id changes but not css-selector so we get two rules with the same css-selector
18
- // we dedupe the rules so old rule is now stripped.
19
- const { code } = transform({ code: Buffer.from(css) })
20
- return `<style id="cssmodule-ssr-collect-plugin">${code.toString()}</style>`
21
- }
22
- }
23
- }
24
-
25
- export default llsCssSsrCollectPlugin
@@ -1,32 +0,0 @@
1
- /**
2
- * Plugin that collects styles from linaria cache to inject it in the page.
3
- * @returns config() method that instantiates linariaPlugin
4
- * resolveId() method that filters files to be added to css set
5
- * flushStyles() method that generates and return <style> tag with refreshed style
6
- */
7
- import { transform } from 'lightningcss'
8
- const llsLinariaSsrCollectPlugin = () => {
9
- const cssIds = new Set()
10
- let linariaPlugin
11
- return {
12
- name: 'lls:llsLinariaSsrCollect',
13
- /* we enforce pre because if vite-plugin-linaria resolves id, vite4 won't call us. Since we do not resolve, we can be put before */
14
- enforce: 'pre',
15
- config (config) {
16
- linariaPlugin = config.plugins.find(plugin => plugin.name === 'linaria')
17
- },
18
- async resolveId (id, from) {
19
- if (id.includes('@linaria-cache')) { cssIds.add(id) }
20
- },
21
- flushStyles () {
22
- const css = [...cssIds].map(linariaPlugin.load).join('\n')
23
-
24
- // when hmr, id changes but not css-selector so we get two rules with the same css-selector
25
- // we dedupe the rules so old rule is now stripped.
26
- const { code } = transform({ code: Buffer.from(css) })
27
- return `<style id="linaria-ssr-collect-plugin">${code.toString()}</style>`
28
- }
29
- }
30
- }
31
-
32
- export default llsLinariaSsrCollectPlugin
@@ -1,15 +0,0 @@
1
- import fs from 'fs'
2
-
3
- const esbuildAutoprefixerPlugin = async ({ from, to, lightningcssOptions: { minify = false } = {} }) => {
4
- const [{ transform, browserslistToTargets }, browserslist] = await Promise.all([import('lightningcss'), import('browserslist').then(m => m.default)])
5
- const contents = await fs.promises.readFile(from).then(async buf => {
6
- const { code } = transform({
7
- code: buf,
8
- targets: browserslistToTargets(browserslist('cover 99.5%')),
9
- minify
10
- })
11
- return code.toString()
12
- })
13
- return fs.promises.writeFile(to, contents)
14
- }
15
- export default esbuildAutoprefixerPlugin
@@ -1,36 +0,0 @@
1
- import fs from 'node:fs/promises'
2
- import path from 'path'
3
- import { exec } from 'child_process'
4
- import util from 'util'
5
- const execp = util.promisify(exec)
6
-
7
- const getDirectoryFileNames = async directory => {
8
- const fileNames = []
9
- const filesInDirectory = await fs.readdir(directory)
10
- for (const fileName of filesInDirectory) {
11
- const absolute = path.join(directory, fileName)
12
- if ((await fs.stat(absolute)).isDirectory()) {
13
- fileNames.push(...await getDirectoryFileNames(absolute))
14
- } else {
15
- fileNames.push(absolute)
16
- }
17
- }
18
- return fileNames
19
- }
20
-
21
- const postBuildTstypes = async ({ rootAliases = [] }) => {
22
- try {
23
- await fs.access('./builttypes', fs.constants.F_OK)
24
- } catch (e) {
25
- return
26
- }
27
- const fileNames = await getDirectoryFileNames('./builttypes')
28
- const rootAliasRegex = new RegExp(rootAliases.map(x => x + '/').join('|') || 'nevermatching/', 'g')
29
- for (const fileName of fileNames) {
30
- await fs.readFile(fileName, 'utf8').then(
31
- str => str.replaceAll(rootAliasRegex, `${path.relative(fileName, 'builttypes').slice(1)}/`) // builttypes/index.ts will be resolved to '..' so we always remove the first dot
32
- ).then(outStr => fs.writeFile(fileName, outStr))
33
- }
34
- await execp('cp -r builttypes/. lib')
35
- }
36
- export default postBuildTstypes