Debian Codegraph @

node/esbuild-sass-plugin/src/utils.ts

raw
1 import {BuildOptions, OnLoadResult} from 'esbuild'
2 import {existsSync, readFileSync} from 'fs'
3 import {dirname, parse, relative, resolve} from 'path'
4 import {AcceptedPlugin, Postcss} from 'postcss'
5 import PostcssModulesPlugin from 'postcss-modules'
6 import {SyncOpts} from 'resolve'
7 import {Syntax} from 'sass'
8 import {SassPluginOptions, Type} from './index'
9
10 const cwd = process.cwd()
11
12 export const DEFAULT_FILTER = /\.(s[ac]ss|css)$/
13
14 export const posixRelative = require('path').sep === '/'
15 ? (path: string) => relative(cwd, path)
16 : (path: string) => relative(cwd, path).replace(/\\/g, '/')
17
18 export function modulesPaths(absWorkingDir?: string): string[] {
19 let path = absWorkingDir || process.cwd()
20 let {root} = parse(path)
21 let found: string[] = []
22 while (path !== root) {
23 const filename = resolve(path, 'node_modules')
24 if (existsSync(filename)) {
25 found.push(filename)
26 }
27 path = resolve(path, '..')
28 }
29 return [...found]
30 }
31
32 export function fileSyntax(filename: string): Syntax {
33 if (filename.endsWith('.scss')) {
34 return 'scss'
35 } else if (filename.endsWith('.css')) {
36 return 'css'
37 } else {
38 return 'indented'
39 }
40 }
41
42 export type PluginContext = {
43 instance: number
44 namespace: string
45 sourcemap: boolean
46 watched: { [path: string]: string[] }
47 }
48
49 const SASS_PLUGIN_CONTEXT = Symbol()
50
51 export function getContext(buildOptions: BuildOptions): PluginContext {
52 let descriptor = Object.getOwnPropertyDescriptor(buildOptions, SASS_PLUGIN_CONTEXT)
53 if (descriptor === undefined) {
54 Object.defineProperty(buildOptions, SASS_PLUGIN_CONTEXT, descriptor = {
55 value: {
56 instances: 0
57 }
58 })
59 }
60 const instance = descriptor.value.instances++
61 return {
62 instance,
63 namespace: `sass-plugin-${instance}`,
64 sourcemap: !!buildOptions.sourcemap,
65 watched: {}
66 }
67 }
68
69 export function sourceMappingURL(sourceMap: any): string {
70 const data = Buffer.from(JSON.stringify(sourceMap), 'utf-8').toString('base64')
71 return `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${data} */`
72 }
73
74 function requireTool(module: string, basedir?: string) {
75 try {
76 return require(module)
77 } catch (ignored) {
78 }
79 if (basedir) try {
80 return require(require.resolve(module, {paths: [basedir]}))
81 } catch (ignored) {
82 }
83 try {
84 return require(require.resolve(module, {paths: [process.cwd()]}))
85 } catch (e) {
86 try {
87 return require(module) // extra attempt at finding a co-located tool
88 } catch (ignored) {
89 console.error(`Cannot find module '${module}', make sure it's installed. e.g. yarn add -D ${module}`, e)
90 process.exit(1)
91 }
92 }
93 }
94
95 const cssTextModule = cssText => `\
96 export default \`${cssText.replace(/([$`\\])/g, '\\$1')}\`;
97 `
98
99 const cssResultModule = cssText => `\
100 import {css} from "lit-element/lit-element.js";
101 export default css\`${cssText.replace(/([$`\\])/g, '\\$1')}\`;
102 `
103
104 const styleModule = (cssText: string, nonce?: string) => nonce ? `\
105 const css = \`${cssText.replace(/([$`\\])/g, '\\$1')}\`;
106 const style = document.createElement("style");
107 style.setAttribute("nonce", ${nonce});
108 style.appendChild(document.createTextNode(css));
109 document.head.appendChild(style);
110 export {css};
111 ` : `\
112 const css = \`${cssText.replace(/([$`\\])/g, '\\$1')}\`;
113 document.head
114 .appendChild(document.createElement("style"))
115 .appendChild(document.createTextNode(css));
116 export {css};
117 `
118
119 export function makeModule(contents: string, type: Type, nonce?: string): string {
120 switch (type) {
121 case 'style':
122 return styleModule(contents, nonce)
123 case 'lit-css':
124 return cssResultModule(contents)
125 case 'css-text':
126 return cssTextModule(contents)
127 case 'css':
128 case 'local-css':
129 return contents
130 default:
131 return type(contents, nonce)
132 }
133 }
134
135 export function parseNonce(nonce: string | undefined): string | undefined {
136 if (nonce) {
137 if (nonce.startsWith('window.') || nonce.startsWith('process.') || nonce.startsWith('globalThis.')) {
138 return nonce
139 } else {
140 return JSON.stringify(nonce)
141 }
142 } else {
143 return nonce
144 }
145 }
146
147 export type PostcssModulesParams = Parameters<PostcssModulesPlugin>[0] & {
148 basedir?: string
149 };
150
151 export function postcssModules(options: PostcssModulesParams, plugins: AcceptedPlugin[] = []) {
152
153 const postcss: Postcss = requireTool('postcss', options.basedir)
154 const postcssModulesPlugin: PostcssModulesPlugin = requireTool('postcss-modules', options.basedir)
155
156 return async function (source: string, dirname: string, path: string): Promise<OnLoadResult> {
157
158 let cssModule
159
160 const {css} = await postcss([
161 postcssModulesPlugin({
162 ...(options as Parameters<PostcssModulesPlugin>[0]),
163 getJSON(cssFilename: string, json: { [name: string]: string }, outputFileName?: string): void {
164 cssModule = JSON.stringify(json, null, 2)
165 options.getJSON?.(cssFilename, json, outputFileName)
166 }
167 }),
168 ...plugins
169 ]).process(source, {from: path, map: false})
170
171 return {
172 contents: css,
173 pluginData: {exports: cssModule},
174 loader: 'js'
175 }
176 }
177 }
178
179 export function createResolver(options: SassPluginOptions = {}, loadPaths: string[]) {
180 if (options.prefer) {
181 const resolve = require('resolve')
182 const cache = {} as Record<string, { main: string }>
183 const prefer = options.prefer
184 const opts: SyncOpts = {
185 paths: ['.', ...loadPaths],
186 readPackageSync(readFileSync, pkgfile) {
187 let cached = cache[pkgfile]
188 if (!cached) {
189 const pkg = JSON.parse(readFileSync(pkgfile) as string)
190 cached = cache[pkgfile] = {main: pkg[prefer] || pkg.main}
191 }
192 return cached
193 }
194 }
195 return (id: string, basedir: string) => {
196 try {
197 opts.basedir = basedir
198 return resolve.sync!(id, opts)
199 } catch (ignored) {
200 return id
201 }
202 }
203 } else {
204 const opts = {
205 paths: ['.', ...loadPaths]
206 }
207 return (id: string, basedir: string) => {
208 try {
209 opts.paths[0] = basedir
210 const resolved = require.resolve(id, opts)
211 if (!resolved.endsWith('.js')) {
212 return resolved
213 }
214 // require.resolve found a JS entry point — look for a stylesheet instead.
215 // First check package.json style/sass/scss fields, then try adjacent files.
216 try {
217 const parts = id.split('/')
218 const pkgName = id.startsWith('@') ? parts[0] + '/' + parts[1] : parts[0]
219 const pkgPath = require.resolve(pkgName + '/package.json', opts)
220 const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))
221 for (const field of ['style', 'sass', 'scss']) {
222 if (typeof pkg[field] === 'string') {
223 const stylePath = resolve(dirname(pkgPath), pkg[field])
224 if (existsSync(stylePath)) return stylePath
225 }
226 }
227 } catch (ignored) {}
228 const base = resolved.slice(0, -3)
229 for (const ext of ['.scss', '.sass', '.css']) {
230 if (existsSync(base + ext)) return base + ext
231 }
232 return id
233 } catch (ignored) {
234 return id
235 }
236 }
237 }
238 }
239
240 const reserved = {
241 await: true,
242 break: true,
243 case: true,
244 catch: true,
245 class: true,
246 const: true,
247 continue: true,
248 debugger: true,
249 default: true,
250 delete: true,
251 do: true,
252 else: true,
253 enum: true,
254 export: true,
255 extends: true,
256 false: true,
257 finally: true,
258 for: true,
259 function: true,
260 if: true,
261 implements: true,
262 import: true,
263 in: true,
264 instanceof: true,
265 interface: true,
266 let: true,
267 new: true,
268 null: true,
269 package: true,
270 private: true,
271 protected: true,
272 public: true,
273 return: true,
274 static: true,
275 super: true,
276 switch: true,
277 this: true,
278 throw: true,
279 true: true,
280 try: true,
281 typeof: true,
282 var: true,
283 void: true,
284 while: true,
285 with: true,
286 yield: true
287 }
288
289 export function safeExport(identifier: string): string {
290 if (reserved[identifier]) {
291 return '_' + identifier
292 } else {
293 return identifier.trim().replace(/\W+([a-z])/g, (esc, c) => esc[0] === '-' ? c.toUpperCase() : '_')
294 }
295 }