@wyw-in-js/rollup 0.8.1 → 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
@@ -12,6 +12,8 @@ npm i -D @wyw-in-js/rollup
12
12
  yarn add --dev @wyw-in-js/rollup
13
13
  # pnpm
14
14
  pnpm add -D @wyw-in-js/rollup
15
+ # bun
16
+ bun add -d @wyw-in-js/rollup
15
17
  ```
16
18
 
17
19
  ## Usage
@@ -30,4 +32,26 @@ export default {
30
32
  };
31
33
  ```
32
34
 
35
+ ### Concurrency (tsdown/rolldown)
36
+
37
+ Some Rollup-compatible bundlers may execute plugin hooks concurrently (e.g. tsdown/rolldown). To keep evaluation deterministic, `@wyw-in-js/rollup` serializes `transform()` calls by default.
38
+
39
+ To opt out, pass:
40
+
41
+ ```js
42
+ wyw({
43
+ serializeTransform: false,
44
+ });
45
+ ```
46
+
47
+ ## Disabling vendor prefixing
48
+
49
+ Stylis adds vendor-prefixed CSS by default. To disable it (and reduce CSS size), pass `prefixer: false`:
50
+
51
+ ```js
52
+ wyw({
53
+ prefixer: false,
54
+ });
55
+ ```
56
+
33
57
  To get details about supported options by the plugin, please check [documentation](https://wyw-in-js.dev/bundlers/rollup).
package/esm/index.mjs CHANGED
@@ -5,13 +5,15 @@
5
5
  */
6
6
 
7
7
  import { createFilter } from '@rollup/pluginutils';
8
- import { logger, slugify, syncResolve } from '@wyw-in-js/shared';
8
+ import { asyncResolverFactory, logger, slugify, syncResolve } from '@wyw-in-js/shared';
9
9
  import { getFileIdx, transform, TransformCacheCollection } from '@wyw-in-js/transform';
10
10
  export default function wywInJS({
11
11
  exclude,
12
12
  include,
13
+ keepComments,
13
14
  prefixer,
14
15
  preprocessor,
16
+ serializeTransform = true,
15
17
  sourceMap,
16
18
  ...rest
17
19
  } = {}) {
@@ -19,6 +21,42 @@ export default function wywInJS({
19
21
  const cssLookup = {};
20
22
  const cache = new TransformCacheCollection();
21
23
  const emptyConfig = {};
24
+ let transformQueue = Promise.resolve();
25
+ const runSerialized = async fn => {
26
+ if (!serializeTransform) {
27
+ return fn();
28
+ }
29
+ let release;
30
+ const previous = transformQueue;
31
+ transformQueue = new Promise(resolve => {
32
+ release = resolve;
33
+ });
34
+ await previous;
35
+ try {
36
+ return await fn();
37
+ } finally {
38
+ release();
39
+ }
40
+ };
41
+ const createAsyncResolver = asyncResolverFactory(async (resolved, what, importer, stack) => {
42
+ if (resolved) {
43
+ if (resolved.external) {
44
+ // If module is marked as external, Rollup will not resolve it,
45
+ // so we need to resolve it ourselves with default resolver
46
+ return syncResolve(what, importer, stack);
47
+ }
48
+
49
+ // Vite adds param like `?v=667939b3` to cached modules
50
+ const resolvedId = resolved.id.split('?')[0];
51
+ if (resolvedId.startsWith('\0')) {
52
+ // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
53
+ // https://rollupjs.org/guide/en/#outputexports
54
+ return null;
55
+ }
56
+ return resolvedId;
57
+ }
58
+ throw new Error(`Could not resolve ${what}`);
59
+ }, (what, importer) => [what, importer]);
22
60
  const plugin = {
23
61
  name: 'wyw-in-js',
24
62
  load(id) {
@@ -29,63 +67,43 @@ export default function wywInJS({
29
67
  if (importee in cssLookup) return importee;
30
68
  },
31
69
  async transform(code, id) {
32
- // Do not transform ignored and generated files
33
- if (!filter(id) || id in cssLookup) return;
34
- const log = logger.extend('rollup').extend(getFileIdx(id));
35
- log('init %s', id);
36
- const asyncResolve = async (what, importer, stack) => {
37
- const resolved = await this.resolve(what, importer);
38
- if (resolved) {
39
- if (resolved.external) {
40
- // If module is marked as external, Rollup will not resolve it,
41
- // so we need to resolve it ourselves with default resolver
42
- const resolvedId = syncResolve(what, importer, stack);
43
- log("resolve: ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
44
- return resolvedId;
45
- }
46
- log("resolve: ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
47
-
48
- // Vite adds param like `?v=667939b3` to cached modules
49
- const resolvedId = resolved.id.split('?')[0];
50
- if (resolvedId.startsWith('\0')) {
51
- // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
52
- // https://rollupjs.org/guide/en/#outputexports
53
- return null;
54
- }
55
- return resolvedId;
70
+ return runSerialized(async () => {
71
+ // Do not transform ignored and generated files
72
+ if (!filter(id) || id in cssLookup) return;
73
+ const log = logger.extend('rollup').extend(getFileIdx(id));
74
+ log('init %s', id);
75
+ const transformServices = {
76
+ options: {
77
+ filename: id,
78
+ pluginOptions: rest,
79
+ prefixer,
80
+ keepComments,
81
+ preprocessor,
82
+ root: process.cwd()
83
+ },
84
+ cache,
85
+ emitWarning: message => this.warn(message)
86
+ };
87
+ const result = await transform(transformServices, code, createAsyncResolver(this.resolve), emptyConfig);
88
+ if (!result.cssText) return;
89
+ let {
90
+ cssText
91
+ } = result;
92
+ const slug = slugify(cssText);
93
+ const filename = `${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`;
94
+ if (sourceMap && result.cssSourceMapText) {
95
+ const map = Buffer.from(result.cssSourceMapText).toString('base64');
96
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
56
97
  }
57
- log("resolve: '%s'@'%s", what, importer);
58
- throw new Error(`Could not resolve ${what}`);
59
- };
60
- const transformServices = {
61
- options: {
62
- filename: id,
63
- pluginOptions: rest,
64
- prefixer,
65
- preprocessor,
66
- root: process.cwd()
67
- },
68
- cache
69
- };
70
- const result = await transform(transformServices, code, asyncResolve, emptyConfig);
71
- if (!result.cssText) return;
72
- let {
73
- cssText
74
- } = result;
75
- const slug = slugify(cssText);
76
- const filename = `${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`;
77
- if (sourceMap && result.cssSourceMapText) {
78
- const map = Buffer.from(result.cssSourceMapText).toString('base64');
79
- cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
80
- }
81
- cssLookup[filename] = cssText;
82
- result.code += `\nimport ${JSON.stringify(filename)};\n`;
98
+ cssLookup[filename] = cssText;
99
+ result.code += `\nimport ${JSON.stringify(filename)};\n`;
83
100
 
84
- /* eslint-disable-next-line consistent-return */
85
- return {
86
- code: result.code,
87
- map: result.sourceMap
88
- };
101
+ /* eslint-disable-next-line consistent-return */
102
+ return {
103
+ code: result.code,
104
+ map: result.sourceMap
105
+ };
106
+ });
89
107
  }
90
108
  };
91
109
  return new Proxy(plugin, {
package/esm/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["createFilter","logger","slugify","syncResolve","getFileIdx","transform","TransformCacheCollection","wywInJS","exclude","include","prefixer","preprocessor","sourceMap","rest","filter","cssLookup","cache","emptyConfig","plugin","name","load","id","resolveId","importee","code","log","extend","asyncResolve","what","importer","stack","resolved","resolve","external","resolvedId","split","startsWith","Error","transformServices","options","filename","pluginOptions","root","process","cwd","result","cssText","slug","replace","cssSourceMapText","map","Buffer","from","toString","JSON","stringify","Proxy","get","target","prop","getOwnPropertyDescriptor","Object"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * This file contains a Rollup loader for wyw-in-js.\n * It uses the transform.ts function to generate class names from source code,\n * returns transformed code without template literals and attaches generated source maps\n */\n\nimport { createFilter } from '@rollup/pluginutils';\nimport type { Plugin } from 'rollup';\n\nimport { logger, slugify, syncResolve } from '@wyw-in-js/shared';\nimport type { PluginOptions, Preprocessor, Result } from '@wyw-in-js/transform';\nimport {\n getFileIdx,\n transform,\n TransformCacheCollection,\n} from '@wyw-in-js/transform';\n\ntype RollupPluginOptions = {\n exclude?: string | string[];\n include?: string | string[];\n prefixer?: boolean;\n preprocessor?: Preprocessor;\n sourceMap?: boolean;\n} & Partial<PluginOptions>;\n\nexport default function wywInJS({\n exclude,\n include,\n prefixer,\n preprocessor,\n sourceMap,\n ...rest\n}: RollupPluginOptions = {}): Plugin {\n const filter = createFilter(include, exclude);\n const cssLookup: { [key: string]: string } = {};\n const cache = new TransformCacheCollection();\n const emptyConfig = {};\n\n const plugin: Plugin = {\n name: 'wyw-in-js',\n load(id: string) {\n return cssLookup[id];\n },\n /* eslint-disable-next-line consistent-return */\n resolveId(importee: string) {\n if (importee in cssLookup) return importee;\n },\n async transform(\n code: string,\n id: string\n ): Promise<{ code: string; map: Result['sourceMap'] } | undefined> {\n // Do not transform ignored and generated files\n if (!filter(id) || id in cssLookup) return;\n\n const log = logger.extend('rollup').extend(getFileIdx(id));\n\n log('init %s', id);\n\n const asyncResolve = async (\n what: string,\n importer: string,\n stack: string[]\n ) => {\n const resolved = await this.resolve(what, importer);\n if (resolved) {\n if (resolved.external) {\n // If module is marked as external, Rollup will not resolve it,\n // so we need to resolve it ourselves with default resolver\n const resolvedId = syncResolve(what, importer, stack);\n log(\"resolve: ✅ '%s'@'%s -> %O\\n%s\", what, importer, resolved);\n return resolvedId;\n }\n\n log(\"resolve: ✅ '%s'@'%s -> %O\\n%s\", what, importer, resolved);\n\n // Vite adds param like `?v=667939b3` to cached modules\n const resolvedId = resolved.id.split('?')[0];\n\n if (resolvedId.startsWith('\\0')) {\n // \\0 is a special character in Rollup that tells Rollup to not include this in the bundle\n // https://rollupjs.org/guide/en/#outputexports\n return null;\n }\n\n return resolvedId;\n }\n\n log(\"resolve: ❌ '%s'@'%s\", what, importer);\n throw new Error(`Could not resolve ${what}`);\n };\n\n const transformServices = {\n options: {\n filename: id,\n pluginOptions: rest,\n prefixer,\n preprocessor,\n root: process.cwd(),\n },\n cache,\n };\n\n const result = await transform(\n transformServices,\n code,\n asyncResolve,\n emptyConfig\n );\n\n if (!result.cssText) return;\n\n let { cssText } = result;\n\n const slug = slugify(cssText);\n const filename = `${id.replace(/\\.[jt]sx?$/, '')}_${slug}.css`;\n\n if (sourceMap && result.cssSourceMapText) {\n const map = Buffer.from(result.cssSourceMapText).toString('base64');\n cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;\n }\n\n cssLookup[filename] = cssText;\n\n result.code += `\\nimport ${JSON.stringify(filename)};\\n`;\n\n /* eslint-disable-next-line consistent-return */\n return { code: result.code, map: result.sourceMap };\n },\n };\n\n return new Proxy<Plugin>(plugin, {\n get(target, prop) {\n return target[prop as keyof Plugin];\n },\n\n getOwnPropertyDescriptor(target, prop) {\n return Object.getOwnPropertyDescriptor(target, prop as keyof Plugin);\n },\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,qBAAqB;AAGlD,SAASC,MAAM,EAAEC,OAAO,EAAEC,WAAW,QAAQ,mBAAmB;AAEhE,SACEC,UAAU,EACVC,SAAS,EACTC,wBAAwB,QACnB,sBAAsB;AAU7B,eAAe,SAASC,OAAOA,CAAC;EAC9BC,OAAO;EACPC,OAAO;EACPC,QAAQ;EACRC,YAAY;EACZC,SAAS;EACT,GAAGC;AACgB,CAAC,GAAG,CAAC,CAAC,EAAU;EACnC,MAAMC,MAAM,GAAGd,YAAY,CAACS,OAAO,EAAED,OAAO,CAAC;EAC7C,MAAMO,SAAoC,GAAG,CAAC,CAAC;EAC/C,MAAMC,KAAK,GAAG,IAAIV,wBAAwB,CAAC,CAAC;EAC5C,MAAMW,WAAW,GAAG,CAAC,CAAC;EAEtB,MAAMC,MAAc,GAAG;IACrBC,IAAI,EAAE,WAAW;IACjBC,IAAIA,CAACC,EAAU,EAAE;MACf,OAAON,SAAS,CAACM,EAAE,CAAC;IACtB,CAAC;IACD;IACAC,SAASA,CAACC,QAAgB,EAAE;MAC1B,IAAIA,QAAQ,IAAIR,SAAS,EAAE,OAAOQ,QAAQ;IAC5C,CAAC;IACD,MAAMlB,SAASA,CACbmB,IAAY,EACZH,EAAU,EACuD;MACjE;MACA,IAAI,CAACP,MAAM,CAACO,EAAE,CAAC,IAAIA,EAAE,IAAIN,SAAS,EAAE;MAEpC,MAAMU,GAAG,GAAGxB,MAAM,CAACyB,MAAM,CAAC,QAAQ,CAAC,CAACA,MAAM,CAACtB,UAAU,CAACiB,EAAE,CAAC,CAAC;MAE1DI,GAAG,CAAC,SAAS,EAAEJ,EAAE,CAAC;MAElB,MAAMM,YAAY,GAAG,MAAAA,CACn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AO,CAAC4C,OAAO,CAAC;MAC7B,MAAMN,QAAQ,GAAI,GAAEnB,EAAE,CAAC2B,OAAO,CAAC,YAAY,EAAE,EAAE,CAAE,IAAGD,IAAK,MAAK;MAE9D,IAAInC,SAAS,IAAIiC,MAAM,CAACI,gBAAgB,EAAE;QACxC,MAAMC,GAAG,GAAGC,MAAM,CAACC,IAAI,CAACP,MAAM,CAACI,gBAAgB,CAAC,CAACI,QAAQ,CAAC,QAAQ,CAAC;QACnEP,OAAO,IAAK,qDAAoDI,GAAI,IAAG;MACzE;MAEAnC,SAAS,CAACyB,QAAQ,CAAC,GAAGM,OAAO;MAE7BD,MAAM,CAACrB,IAAI,IAAK,YAAW8B,IAAI,CAACC,SAAS,CAACf,QAAQ,CAAE,KAAI;;MAExD;MACA,OAAO;QAAEhB,IAAI,EAAEqB,MAAM,CAACrB,IAAI;QAAE0B,GAAG,EAAEL,MAAM,CAACjC;MAAU,CAAC;IACrD;EACF,CAAC;EAED,OAAO,IAAI4C,KAAK,CAAStC,MAAM,EAAE;IAC/BuC,GAAGA,CAACC,MAAM,EAAEC,IAAI,EAAE;MAChB,OAAOD,MAAM,CAACC,IAAI,CAAiB;IACrC,CAAC;IAEDC,wBAAwBA,CAACF,MAAM,EAAEC,IAAI,EAAE;MACrC,OAAOE,MAAM,CAACD,wBAAwB,CAACF,MAAM,EAAEC,IAAoB,CAAC;IACtE;EACF,CAAC,CAAC;AACJ"}
1
+ {"version":3,"file":"index.mjs","names":["createFilter","asyncResolverFactory","logger","slugify","syncResolve","getFileIdx","transform","TransformCacheCollection","wywInJS","exclude","include","keepComments","prefixer","preprocessor","serializeTransform","sourceMap","rest","filter","cssLookup","cache","emptyConfig","transformQueue","Promise","resolve","runSerialized","fn","release","previous","createAsyncResolver","resolved","what","importer","stack","external","resolvedId","id","split","startsWith","Error","plugin","name","load","resolveId","importee","code","log","extend","transformServices","options","filename","pluginOptions","root","process","cwd","emitWarning","message","warn","result","cssText","slug","replace","cssSourceMapText","map","Buffer","from","toString","JSON","stringify","Proxy","get","target","prop","getOwnPropertyDescriptor","Object"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * This file contains a Rollup loader for wyw-in-js.\n * It uses the transform.ts function to generate class names from source code,\n * returns transformed code without template literals and attaches generated source maps\n */\n\nimport { createFilter } from '@rollup/pluginutils';\nimport type { Plugin, ResolvedId } from 'rollup';\n\nimport {\n asyncResolverFactory,\n logger,\n slugify,\n syncResolve,\n} from '@wyw-in-js/shared';\nimport type { PluginOptions, Preprocessor, Result } from '@wyw-in-js/transform';\nimport {\n getFileIdx,\n transform,\n TransformCacheCollection,\n} from '@wyw-in-js/transform';\n\ntype RollupPluginOptions = {\n exclude?: string | string[];\n include?: string | string[];\n keepComments?: boolean | RegExp;\n prefixer?: boolean;\n preprocessor?: Preprocessor;\n serializeTransform?: boolean;\n sourceMap?: boolean;\n} & Partial<PluginOptions>;\n\nexport default function wywInJS({\n exclude,\n include,\n keepComments,\n prefixer,\n preprocessor,\n serializeTransform = true,\n sourceMap,\n ...rest\n}: RollupPluginOptions = {}): Plugin {\n const filter = createFilter(include, exclude);\n const cssLookup: { [key: string]: string } = {};\n const cache = new TransformCacheCollection();\n const emptyConfig = {};\n let transformQueue = Promise.resolve();\n\n const runSerialized = async <T>(fn: () => Promise<T>): Promise<T> => {\n if (!serializeTransform) {\n return fn();\n }\n\n let release: () => void;\n const previous = transformQueue;\n transformQueue = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n\n try {\n return await fn();\n } finally {\n release!();\n }\n };\n\n const createAsyncResolver = asyncResolverFactory(\n async (resolved: ResolvedId | null, what, importer, stack) => {\n if (resolved) {\n if (resolved.external) {\n // If module is marked as external, Rollup will not resolve it,\n // so we need to resolve it ourselves with default resolver\n return syncResolve(what, importer, stack);\n }\n\n // Vite adds param like `?v=667939b3` to cached modules\n const resolvedId = resolved.id.split('?')[0];\n\n if (resolvedId.startsWith('\\0')) {\n // \\0 is a special character in Rollup that tells Rollup to not include this in the bundle\n // https://rollupjs.org/guide/en/#outputexports\n return null;\n }\n\n return resolvedId;\n }\n\n throw new Error(`Could not resolve ${what}`);\n },\n (what, importer) => [what, importer]\n );\n\n const plugin: Plugin = {\n name: 'wyw-in-js',\n load(id: string) {\n return cssLookup[id];\n },\n /* eslint-disable-next-line consistent-return */\n resolveId(importee: string) {\n if (importee in cssLookup) return importee;\n },\n async transform(\n code: string,\n id: string\n ): Promise<{ code: string; map: Result['sourceMap'] } | undefined> {\n return runSerialized(async () => {\n // Do not transform ignored and generated files\n if (!filter(id) || id in cssLookup) return;\n\n const log = logger.extend('rollup').extend(getFileIdx(id));\n\n log('init %s', id);\n\n const transformServices = {\n options: {\n filename: id,\n pluginOptions: rest,\n prefixer,\n keepComments,\n preprocessor,\n root: process.cwd(),\n },\n cache,\n emitWarning: (message: string) => this.warn(message),\n };\n\n const result = await transform(\n transformServices,\n code,\n createAsyncResolver(this.resolve),\n emptyConfig\n );\n\n if (!result.cssText) return;\n\n let { cssText } = result;\n\n const slug = slugify(cssText);\n const filename = `${id.replace(/\\.[jt]sx?$/, '')}_${slug}.css`;\n\n if (sourceMap && result.cssSourceMapText) {\n const map = Buffer.from(result.cssSourceMapText).toString('base64');\n cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;\n }\n\n cssLookup[filename] = cssText;\n\n result.code += `\\nimport ${JSON.stringify(filename)};\\n`;\n\n /* eslint-disable-next-line consistent-return */\n return { code: result.code, map: result.sourceMap };\n });\n },\n };\n\n return new Proxy<Plugin>(plugin, {\n get(target, prop) {\n return target[prop as keyof Plugin];\n },\n\n getOwnPropertyDescriptor(target, prop) {\n return Object.getOwnPropertyDescriptor(target, prop as keyof Plugin);\n },\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,qBAAqB;AAGlD,SACEC,oBAAoB,EACpBC,MAAM,EACNC,OAAO,EACPC,WAAW,QACN,mBAAmB;AAE1B,SACEC,UAAU,EACVC,SAAS,E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CAAC;QAED,IAAI,CAACqC,MAAM,CAACC,OAAO,EAAE;QAErB,IAAI;UAAEA;QAAQ,CAAC,GAAGD,MAAM;QAExB,MAAME,IAAI,GAAGxD,OAAO,CAACuD,OAAO,CAAC;QAC7B,MAAMT,QAAQ,GAAG,GAAGd,EAAE,CAACyB,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,IAAID,IAAI,MAAM;QAE9D,IAAI5C,SAAS,IAAI0C,MAAM,CAACI,gBAAgB,EAAE;UACxC,MAAMC,GAAG,GAAGC,MAAM,CAACC,IAAI,CAACP,MAAM,CAACI,gBAAgB,CAAC,CAACI,QAAQ,CAAC,QAAQ,CAAC;UACnEP,OAAO,IAAI,qDAAqDI,GAAG,IAAI;QACzE;QAEA5C,SAAS,CAAC+B,QAAQ,CAAC,GAAGS,OAAO;QAE7BD,MAAM,CAACb,IAAI,IAAI,YAAYsB,IAAI,CAACC,SAAS,CAAClB,QAAQ,CAAC,KAAK;;QAExD;QACA,OAAO;UAAEL,IAAI,EAAEa,MAAM,CAACb,IAAI;UAAEkB,GAAG,EAAEL,MAAM,CAAC1C;QAAU,CAAC;MACrD,CAAC,CAAC;IACJ;EACF,CAAC;EAED,OAAO,IAAIqD,KAAK,CAAS7B,MAAM,EAAE;IAC/B8B,GAAGA,CAACC,MAAM,EAAEC,IAAI,EAAE;MAChB,OAAOD,MAAM,CAACC,IAAI,CAAiB;IACrC,CAAC;IAEDC,wBAAwBA,CAACF,MAAM,EAAEC,IAAI,EAAE;MACrC,OAAOE,MAAM,CAACD,wBAAwB,CAACF,MAAM,EAAEC,IAAoB,CAAC;IACtE;EACF,CAAC,CAAC;AACJ","ignoreList":[]}
package/lib/index.js CHANGED
@@ -16,8 +16,10 @@ var _transform = require("@wyw-in-js/transform");
16
16
  function wywInJS({
17
17
  exclude,
18
18
  include,
19
+ keepComments,
19
20
  prefixer,
20
21
  preprocessor,
22
+ serializeTransform = true,
21
23
  sourceMap,
22
24
  ...rest
23
25
  } = {}) {
@@ -25,6 +27,42 @@ function wywInJS({
25
27
  const cssLookup = {};
26
28
  const cache = new _transform.TransformCacheCollection();
27
29
  const emptyConfig = {};
30
+ let transformQueue = Promise.resolve();
31
+ const runSerialized = async fn => {
32
+ if (!serializeTransform) {
33
+ return fn();
34
+ }
35
+ let release;
36
+ const previous = transformQueue;
37
+ transformQueue = new Promise(resolve => {
38
+ release = resolve;
39
+ });
40
+ await previous;
41
+ try {
42
+ return await fn();
43
+ } finally {
44
+ release();
45
+ }
46
+ };
47
+ const createAsyncResolver = (0, _shared.asyncResolverFactory)(async (resolved, what, importer, stack) => {
48
+ if (resolved) {
49
+ if (resolved.external) {
50
+ // If module is marked as external, Rollup will not resolve it,
51
+ // so we need to resolve it ourselves with default resolver
52
+ return (0, _shared.syncResolve)(what, importer, stack);
53
+ }
54
+
55
+ // Vite adds param like `?v=667939b3` to cached modules
56
+ const resolvedId = resolved.id.split('?')[0];
57
+ if (resolvedId.startsWith('\0')) {
58
+ // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
59
+ // https://rollupjs.org/guide/en/#outputexports
60
+ return null;
61
+ }
62
+ return resolvedId;
63
+ }
64
+ throw new Error(`Could not resolve ${what}`);
65
+ }, (what, importer) => [what, importer]);
28
66
  const plugin = {
29
67
  name: 'wyw-in-js',
30
68
  load(id) {
@@ -35,63 +73,43 @@ function wywInJS({
35
73
  if (importee in cssLookup) return importee;
36
74
  },
37
75
  async transform(code, id) {
38
- // Do not transform ignored and generated files
39
- if (!filter(id) || id in cssLookup) return;
40
- const log = _shared.logger.extend('rollup').extend((0, _transform.getFileIdx)(id));
41
- log('init %s', id);
42
- const asyncResolve = async (what, importer, stack) => {
43
- const resolved = await this.resolve(what, importer);
44
- if (resolved) {
45
- if (resolved.external) {
46
- // If module is marked as external, Rollup will not resolve it,
47
- // so we need to resolve it ourselves with default resolver
48
- const resolvedId = (0, _shared.syncResolve)(what, importer, stack);
49
- log("resolve: ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
50
- return resolvedId;
51
- }
52
- log("resolve: ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
53
-
54
- // Vite adds param like `?v=667939b3` to cached modules
55
- const resolvedId = resolved.id.split('?')[0];
56
- if (resolvedId.startsWith('\0')) {
57
- // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
58
- // https://rollupjs.org/guide/en/#outputexports
59
- return null;
60
- }
61
- return resolvedId;
76
+ return runSerialized(async () => {
77
+ // Do not transform ignored and generated files
78
+ if (!filter(id) || id in cssLookup) return;
79
+ const log = _shared.logger.extend('rollup').extend((0, _transform.getFileIdx)(id));
80
+ log('init %s', id);
81
+ const transformServices = {
82
+ options: {
83
+ filename: id,
84
+ pluginOptions: rest,
85
+ prefixer,
86
+ keepComments,
87
+ preprocessor,
88
+ root: process.cwd()
89
+ },
90
+ cache,
91
+ emitWarning: message => this.warn(message)
92
+ };
93
+ const result = await (0, _transform.transform)(transformServices, code, createAsyncResolver(this.resolve), emptyConfig);
94
+ if (!result.cssText) return;
95
+ let {
96
+ cssText
97
+ } = result;
98
+ const slug = (0, _shared.slugify)(cssText);
99
+ const filename = `${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`;
100
+ if (sourceMap && result.cssSourceMapText) {
101
+ const map = Buffer.from(result.cssSourceMapText).toString('base64');
102
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
62
103
  }
63
- log("resolve: '%s'@'%s", what, importer);
64
- throw new Error(`Could not resolve ${what}`);
65
- };
66
- const transformServices = {
67
- options: {
68
- filename: id,
69
- pluginOptions: rest,
70
- prefixer,
71
- preprocessor,
72
- root: process.cwd()
73
- },
74
- cache
75
- };
76
- const result = await (0, _transform.transform)(transformServices, code, asyncResolve, emptyConfig);
77
- if (!result.cssText) return;
78
- let {
79
- cssText
80
- } = result;
81
- const slug = (0, _shared.slugify)(cssText);
82
- const filename = `${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`;
83
- if (sourceMap && result.cssSourceMapText) {
84
- const map = Buffer.from(result.cssSourceMapText).toString('base64');
85
- cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
86
- }
87
- cssLookup[filename] = cssText;
88
- result.code += `\nimport ${JSON.stringify(filename)};\n`;
104
+ cssLookup[filename] = cssText;
105
+ result.code += `\nimport ${JSON.stringify(filename)};\n`;
89
106
 
90
- /* eslint-disable-next-line consistent-return */
91
- return {
92
- code: result.code,
93
- map: result.sourceMap
94
- };
107
+ /* eslint-disable-next-line consistent-return */
108
+ return {
109
+ code: result.code,
110
+ map: result.sourceMap
111
+ };
112
+ });
95
113
  }
96
114
  };
97
115
  return new Proxy(plugin, {
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_pluginutils","require","_shared","_transform","wywInJS","exclude","include","prefixer","preprocessor","sourceMap","rest","filter","createFilter","cssLookup","cache","TransformCacheCollection","emptyConfig","plugin","name","load","id","resolveId","importee","transform","code","log","logger","extend","getFileIdx","asyncResolve","what","importer","stack","resolved","resolve","external","resolvedId","syncResolve","split","startsWith","Error","transformServices","options","filename","pluginOptions","root","process","cwd","result","cssText","slug","slugify","replace","cssSourceMapText","map","Buffer","from","toString","JSON","stringify","Proxy","get","target","prop","getOwnPropertyDescriptor","Object"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * This file contains a Rollup loader for wyw-in-js.\n * It uses the transform.ts function to generate class names from source code,\n * returns transformed code without template literals and attaches generated source maps\n */\n\nimport { createFilter } from '@rollup/pluginutils';\nimport type { Plugin } from 'rollup';\n\nimport { logger, slugify, syncResolve } from '@wyw-in-js/shared';\nimport type { PluginOptions, Preprocessor, Result } from '@wyw-in-js/transform';\nimport {\n getFileIdx,\n transform,\n TransformCacheCollection,\n} from '@wyw-in-js/transform';\n\ntype RollupPluginOptions = {\n exclude?: string | string[];\n include?: string | string[];\n prefixer?: boolean;\n preprocessor?: Preprocessor;\n sourceMap?: boolean;\n} & Partial<PluginOptions>;\n\nexport default function wywInJS({\n exclude,\n include,\n prefixer,\n preprocessor,\n sourceMap,\n ...rest\n}: RollupPluginOptions = {}): Plugin {\n const filter = createFilter(include, exclude);\n const cssLookup: { [key: string]: string } = {};\n const cache = new TransformCacheCollection();\n const emptyConfig = {};\n\n const plugin: Plugin = {\n name: 'wyw-in-js',\n load(id: string) {\n return cssLookup[id];\n },\n /* eslint-disable-next-line consistent-return */\n resolveId(importee: string) {\n if (importee in cssLookup) return importee;\n },\n async transform(\n code: string,\n id: string\n ): Promise<{ code: string; map: Result['sourceMap'] } | undefined> {\n // Do not transform ignored and generated files\n if (!filter(id) || id in cssLookup) return;\n\n const log = logger.extend('rollup').extend(getFileIdx(id));\n\n log('init %s', id);\n\n const asyncResolve = async (\n what: string,\n importer: string,\n stack: string[]\n ) => {\n const resolved = await this.resolve(what, importer);\n if (resolved) {\n if (resolved.external) {\n // If module is marked as external, Rollup will not resolve it,\n // so we need to resolve it ourselves with default resolver\n const resolvedId = syncResolve(what, importer, stack);\n log(\"resolve: ✅ '%s'@'%s -> %O\\n%s\", what, importer, resolved);\n return resolvedId;\n }\n\n log(\"resolve: ✅ '%s'@'%s -> %O\\n%s\", what, importer, resolved);\n\n // Vite adds param like `?v=667939b3` to cached modules\n const resolvedId = resolved.id.split('?')[0];\n\n if (resolvedId.startsWith('\\0')) {\n // \\0 is a special character in Rollup that tells Rollup to not include this in the bundle\n // https://rollupjs.org/guide/en/#outputexports\n return null;\n }\n\n return resolvedId;\n }\n\n log(\"resolve: ❌ '%s'@'%s\", what, importer);\n throw new Error(`Could not resolve ${what}`);\n };\n\n const transformServices = {\n options: {\n filename: id,\n pluginOptions: rest,\n prefixer,\n preprocessor,\n root: process.cwd(),\n },\n cache,\n };\n\n const result = await transform(\n transformServices,\n code,\n asyncResolve,\n emptyConfig\n );\n\n if (!result.cssText) return;\n\n let { cssText } = result;\n\n const slug = slugify(cssText);\n const filename = `${id.replace(/\\.[jt]sx?$/, '')}_${slug}.css`;\n\n if (sourceMap && result.cssSourceMapText) {\n const map = Buffer.from(result.cssSourceMapText).toString('base64');\n cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;\n }\n\n cssLookup[filename] = cssText;\n\n result.code += `\\nimport ${JSON.stringify(filename)};\\n`;\n\n /* eslint-disable-next-line consistent-return */\n return { code: result.code, map: result.sourceMap };\n },\n };\n\n return new Proxy<Plugin>(plugin, {\n get(target, prop) {\n return target[prop as keyof Plugin];\n },\n\n getOwnPropertyDescriptor(target, prop) {\n return Object.getOwnPropertyDescriptor(target, prop as keyof Plugin);\n },\n });\n}\n"],"mappings":";;;;;;AAMA,IAAAA,YAAA,GAAAC,OAAA;AAGA,IAAAC,OAAA,GAAAD,OAAA;AAEA,IAAAE,UAAA,GAAAF,OAAA;AAXA;AACA;AACA;AACA;AACA;;AAqBe,SAASG,OAAOA,CAAC;EAC9BC,OAAO;EACPC,OAAO;EACPC,QAAQ;EACRC,YAAY;EACZC,SAAS;EACT,GAAGC;AACgB,CAAC,GAAG,CAAC,CAAC,EAAU;EACnC,MAAMC,MAAM,GAAG,IAAAC,yBAAY,EAACN,OAAO,EAAED,OAAO,CAAC;EAC7C,MAAMQ,SAAoC,GAAG,CAAC,CAAC;EAC/C,MAAMC,KAAK,GAAG,IAAIC,mCAAwB,CAAC,CAAC;EAC5C,MAAMC,WAAW,GAAG,CAAC,CAAC;EAEtB,MAAMC,MAAc,GAAG;IACrBC,IAAI,EAAE,WAAW;IACjBC,IAAIA,CAACC,EAAU,EAAE;MACf,OAAOP,SAAS,CAACO,EAAE,CAAC;IACtB,CAAC;IACD;IACAC,SAASA,CAACC,QAAgB,EAAE;MAC1B,IAAIA,QAAQ,IAAIT,SAAS,EAAE,OAAOS,QAAQ;IAC5C,CAAC;IACD,MAAMC,SAASA,CACbC,IAAY,EACZJ,EAAU,EACuD;MACjE;MACA,IAAI,CAACT,MAAM,CAACS,EAAE,CAAC,IAAIA,EAAE,IAAIP,SAAS,EAAE;MAEpC,MAAMY,GAAG,GAAGC,cAAM,CAACC,MAAM,CAAC,QAAQ,C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B,IAAI,EACJK,YAAY,EACZb,WACF,CAAC;MAED,IAAI,CAACgC,MAAM,CAACC,OAAO,EAAE;MAErB,IAAI;QAAEA;MAAQ,CAAC,GAAGD,MAAM;MAExB,MAAME,IAAI,GAAG,IAAAC,eAAO,EAACF,OAAO,CAAC;MAC7B,MAAMN,QAAQ,GAAI,GAAEvB,EAAE,CAACgC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAE,IAAGF,IAAK,MAAK;MAE9D,IAAIzC,SAAS,IAAIuC,MAAM,CAACK,gBAAgB,EAAE;QACxC,MAAMC,GAAG,GAAGC,MAAM,CAACC,IAAI,CAACR,MAAM,CAACK,gBAAgB,CAAC,CAACI,QAAQ,CAAC,QAAQ,CAAC;QACnER,OAAO,IAAK,qDAAoDK,GAAI,IAAG;MACzE;MAEAzC,SAAS,CAAC8B,QAAQ,CAAC,GAAGM,OAAO;MAE7BD,MAAM,CAACxB,IAAI,IAAK,YAAWkC,IAAI,CAACC,SAAS,CAAChB,QAAQ,CAAE,KAAI;;MAExD;MACA,OAAO;QAAEnB,IAAI,EAAEwB,MAAM,CAACxB,IAAI;QAAE8B,GAAG,EAAEN,MAAM,CAACvC;MAAU,CAAC;IACrD;EACF,CAAC;EAED,OAAO,IAAImD,KAAK,CAAS3C,MAAM,EAAE;IAC/B4C,GAAGA,CAACC,MAAM,EAAEC,IAAI,EAAE;MAChB,OAAOD,MAAM,CAACC,IAAI,CAAiB;IACrC,CAAC;IAEDC,wBAAwBA,CAACF,MAAM,EAAEC,IAAI,EAAE;MACrC,OAAOE,MAAM,CAACD,wBAAwB,CAACF,MAAM,EAAEC,IAAoB,CAAC;IACtE;EACF,CAAC,CAAC;AACJ"}
1
+ {"version":3,"file":"index.js","names":["_pluginutils","require","_shared","_transform","wywInJS","exclude","include","keepComments","prefixer","preprocessor","serializeTransform","sourceMap","rest","filter","createFilter","cssLookup","cache","TransformCacheCollection","emptyConfig","transformQueue","Promise","resolve","runSerialized","fn","release","previous","createAsyncResolver","asyncResolverFactory","resolved","what","importer","stack","external","syncResolve","resolvedId","id","split","startsWith","Error","plugin","name","load","resolveId","importee","transform","code","log","logger","extend","getFileIdx","transformServices","options","filename","pluginOptions","root","process","cwd","emitWarning","message","warn","result","cssText","slug","slugify","replace","cssSourceMapText","map","Buffer","from","toString","JSON","stringify","Proxy","get","target","prop","getOwnPropertyDescriptor","Object"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * This file contains a Rollup loader for wyw-in-js.\n * It uses the transform.ts function to generate class names from source code,\n * returns transformed code without template literals and attaches generated source maps\n */\n\nimport { createFilter } from '@rollup/pluginutils';\nimport type { Plugin, ResolvedId } from 'rollup';\n\nimport {\n asyncResolverFactory,\n logger,\n slugify,\n syncResolve,\n} from '@wyw-in-js/shared';\nimport type { PluginOptions, Preprocessor, Result } from '@wyw-in-js/transform';\nimport {\n getFileIdx,\n transform,\n TransformCacheCollection,\n} from '@wyw-in-js/transform';\n\ntype RollupPluginOptions = {\n exclude?: string | string[];\n include?: string | string[];\n keepComments?: boolean | RegExp;\n prefixer?: boolean;\n preprocessor?: Preprocessor;\n serializeTransform?: boolean;\n sourceMap?: boolean;\n} & Partial<PluginOptions>;\n\nexport default function wywInJS({\n exclude,\n include,\n keepComments,\n prefixer,\n preprocessor,\n serializeTransform = true,\n sourceMap,\n ...rest\n}: RollupPluginOptions = {}): Plugin {\n const filter = createFilter(include, exclude);\n const cssLookup: { [key: string]: string } = {};\n const cache = new TransformCacheCollection();\n const emptyConfig = {};\n let transformQueue = Promise.resolve();\n\n const runSerialized = async <T>(fn: () => Promise<T>): Promise<T> => {\n if (!serializeTransform) {\n return fn();\n }\n\n let release: () => void;\n const previous = transformQueue;\n transformQueue = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n\n try {\n return await fn();\n } finally {\n release!();\n }\n };\n\n const createAsyncResolver = asyncResolverFactory(\n async (resolved: ResolvedId | null, what, importer, stack) => {\n if (resolved) {\n if (resolved.external) {\n // If module is marked as external, Rollup will not resolve it,\n // so we need to resolve it ourselves with default resolver\n return syncResolve(what, importer, stack);\n }\n\n // Vite adds param like `?v=667939b3` to cached modules\n const resolvedId = resolved.id.split('?')[0];\n\n if (resolvedId.startsWith('\\0')) {\n // \\0 is a special character in Rollup that tells Rollup to not include this in the bundle\n // https://rollupjs.org/guide/en/#outputexports\n return null;\n }\n\n return resolvedId;\n }\n\n throw new Error(`Could not resolve ${what}`);\n },\n (what, importer) => [what, importer]\n );\n\n const plugin: Plugin = {\n name: 'wyw-in-js',\n load(id: string) {\n return cssLookup[id];\n },\n /* eslint-disable-next-line consistent-return */\n resolveId(importee: string) {\n if (importee in cssLookup) return importee;\n },\n async transform(\n code: string,\n id: string\n ): Promise<{ code: string; map: Result['sourceMap'] } | undefined> {\n return runSerialized(async () => {\n // Do not transform ignored and generated files\n if (!filter(id) || id in cssLookup) return;\n\n const log = logger.extend('rollup').extend(getFileIdx(id));\n\n log('init %s', id);\n\n const transformServices = {\n options: {\n filename: id,\n pluginOptions: rest,\n prefixer,\n keepComments,\n preprocessor,\n root: process.cwd(),\n },\n cache,\n emitWarning: (message: string) => this.warn(message),\n };\n\n const result = await transform(\n transformServices,\n code,\n createAsyncResolver(this.resolve),\n emptyConfig\n );\n\n if (!result.cssText) return;\n\n let { cssText } = result;\n\n const slug = slugify(cssText);\n const filename = `${id.replace(/\\.[jt]sx?$/, '')}_${slug}.css`;\n\n if (sourceMap && result.cssSourceMapText) {\n const map = Buffer.from(result.cssSourceMapText).toString('base64');\n cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;\n }\n\n cssLookup[filename] = cssText;\n\n result.code += `\\nimport ${JSON.stringify(filename)};\\n`;\n\n /* eslint-disable-next-line consistent-return */\n return { code: result.code, map: result.sourceMap };\n });\n },\n };\n\n return new Proxy<Plugin>(plugin, {\n get(target, prop) {\n return target[prop as keyof Plugin];\n },\n\n getOwnPropertyDescriptor(target, prop) {\n return Object.getOwnPropertyDescriptor(target, prop as keyof Plugin);\n },\n });\n}\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ollup",
3
- "version": "0.8.1",
3
+ "version": "1.0.0",
4
4
  "dependencies": {
5
5
  "@rollup/pluginutils": "^5.0.5",
6
- "@wyw-in-js/shared": "0.8.1",
7
- "@wyw-in-js/transform": "0.8.1"
6
+ "@wyw-in-js/shared": "workspace:*",
7
+ "@wyw-in-js/transform": "workspace:*"
8
8
  },
9
9
  "devDependencies": {
10
10
  "@types/node": "^16.18.55",
11
+ "@wyw-in-js/babel-config": "workspace:*",
12
+ "@wyw-in-js/eslint-config": "workspace:*",
13
+ "@wyw-in-js/ts-config": "workspace:*",
11
14
  "rollup": "^4.0.0",
12
- "source-map": "^0.7.4",
13
- "@wyw-in-js/babel-config": "0.8.1",
14
- "@wyw-in-js/eslint-config": "0.8.1",
15
- "@wyw-in-js/jest-preset": "0.8.1",
16
- "@wyw-in-js/ts-config": "0.8.1"
15
+ "source-map": "^0.7.4"
17
16
  },
18
17
  "engines": {
19
18
  "node": ">=16.0.0"
@@ -37,11 +36,12 @@
37
36
  "publishConfig": {
38
37
  "access": "public"
39
38
  },
40
- "types": "types/index.d.ts",
41
39
  "scripts": {
42
40
  "build:esm": "babel src --out-dir esm --out-file-extension .mjs --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
43
41
  "build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
44
42
  "build:types": "tsc --project ./tsconfig.lib.json --baseUrl . --rootDir ./src",
45
- "lint": "eslint --ext .js,.ts ."
46
- }
47
- }
43
+ "lint": "eslint --ext .js,.ts .",
44
+ "test": "bun test src"
45
+ },
46
+ "types": "types/index.d.ts"
47
+ }
package/types/index.d.ts CHANGED
@@ -8,9 +8,11 @@ import type { PluginOptions, Preprocessor } from '@wyw-in-js/transform';
8
8
  type RollupPluginOptions = {
9
9
  exclude?: string | string[];
10
10
  include?: string | string[];
11
+ keepComments?: boolean | RegExp;
11
12
  prefixer?: boolean;
12
13
  preprocessor?: Preprocessor;
14
+ serializeTransform?: boolean;
13
15
  sourceMap?: boolean;
14
16
  } & Partial<PluginOptions>;
15
- export default function wywInJS({ exclude, include, prefixer, preprocessor, sourceMap, ...rest }?: RollupPluginOptions): Plugin;
17
+ export default function wywInJS({ exclude, include, keepComments, prefixer, preprocessor, serializeTransform, sourceMap, ...rest }?: RollupPluginOptions): Plugin;
16
18
  export {};
package/types/index.js CHANGED
@@ -5,14 +5,51 @@
5
5
  * returns transformed code without template literals and attaches generated source maps
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.default = wywInJS;
8
9
  const pluginutils_1 = require("@rollup/pluginutils");
9
10
  const shared_1 = require("@wyw-in-js/shared");
10
11
  const transform_1 = require("@wyw-in-js/transform");
11
- function wywInJS({ exclude, include, prefixer, preprocessor, sourceMap, ...rest } = {}) {
12
+ function wywInJS({ exclude, include, keepComments, prefixer, preprocessor, serializeTransform = true, sourceMap, ...rest } = {}) {
12
13
  const filter = (0, pluginutils_1.createFilter)(include, exclude);
13
14
  const cssLookup = {};
14
15
  const cache = new transform_1.TransformCacheCollection();
15
16
  const emptyConfig = {};
17
+ let transformQueue = Promise.resolve();
18
+ const runSerialized = async (fn) => {
19
+ if (!serializeTransform) {
20
+ return fn();
21
+ }
22
+ let release;
23
+ const previous = transformQueue;
24
+ transformQueue = new Promise((resolve) => {
25
+ release = resolve;
26
+ });
27
+ await previous;
28
+ try {
29
+ return await fn();
30
+ }
31
+ finally {
32
+ release();
33
+ }
34
+ };
35
+ const createAsyncResolver = (0, shared_1.asyncResolverFactory)(async (resolved, what, importer, stack) => {
36
+ if (resolved) {
37
+ if (resolved.external) {
38
+ // If module is marked as external, Rollup will not resolve it,
39
+ // so we need to resolve it ourselves with default resolver
40
+ return (0, shared_1.syncResolve)(what, importer, stack);
41
+ }
42
+ // Vite adds param like `?v=667939b3` to cached modules
43
+ const resolvedId = resolved.id.split('?')[0];
44
+ if (resolvedId.startsWith('\0')) {
45
+ // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
46
+ // https://rollupjs.org/guide/en/#outputexports
47
+ return null;
48
+ }
49
+ return resolvedId;
50
+ }
51
+ throw new Error(`Could not resolve ${what}`);
52
+ }, (what, importer) => [what, importer]);
16
53
  const plugin = {
17
54
  name: 'wyw-in-js',
18
55
  load(id) {
@@ -24,58 +61,39 @@ function wywInJS({ exclude, include, prefixer, preprocessor, sourceMap, ...rest
24
61
  return importee;
25
62
  },
26
63
  async transform(code, id) {
27
- // Do not transform ignored and generated files
28
- if (!filter(id) || id in cssLookup)
29
- return;
30
- const log = shared_1.logger.extend('rollup').extend((0, transform_1.getFileIdx)(id));
31
- log('init %s', id);
32
- const asyncResolve = async (what, importer, stack) => {
33
- const resolved = await this.resolve(what, importer);
34
- if (resolved) {
35
- if (resolved.external) {
36
- // If module is marked as external, Rollup will not resolve it,
37
- // so we need to resolve it ourselves with default resolver
38
- const resolvedId = (0, shared_1.syncResolve)(what, importer, stack);
39
- log("resolve: ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
40
- return resolvedId;
41
- }
42
- log("resolve: ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
43
- // Vite adds param like `?v=667939b3` to cached modules
44
- const resolvedId = resolved.id.split('?')[0];
45
- if (resolvedId.startsWith('\0')) {
46
- // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
47
- // https://rollupjs.org/guide/en/#outputexports
48
- return null;
49
- }
50
- return resolvedId;
64
+ return runSerialized(async () => {
65
+ // Do not transform ignored and generated files
66
+ if (!filter(id) || id in cssLookup)
67
+ return;
68
+ const log = shared_1.logger.extend('rollup').extend((0, transform_1.getFileIdx)(id));
69
+ log('init %s', id);
70
+ const transformServices = {
71
+ options: {
72
+ filename: id,
73
+ pluginOptions: rest,
74
+ prefixer,
75
+ keepComments,
76
+ preprocessor,
77
+ root: process.cwd(),
78
+ },
79
+ cache,
80
+ emitWarning: (message) => this.warn(message),
81
+ };
82
+ const result = await (0, transform_1.transform)(transformServices, code, createAsyncResolver(this.resolve), emptyConfig);
83
+ if (!result.cssText)
84
+ return;
85
+ let { cssText } = result;
86
+ const slug = (0, shared_1.slugify)(cssText);
87
+ const filename = `${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`;
88
+ if (sourceMap && result.cssSourceMapText) {
89
+ const map = Buffer.from(result.cssSourceMapText).toString('base64');
90
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
51
91
  }
52
- log("resolve: '%s'@'%s", what, importer);
53
- throw new Error(`Could not resolve ${what}`);
54
- };
55
- const transformServices = {
56
- options: {
57
- filename: id,
58
- pluginOptions: rest,
59
- prefixer,
60
- preprocessor,
61
- root: process.cwd(),
62
- },
63
- cache,
64
- };
65
- const result = await (0, transform_1.transform)(transformServices, code, asyncResolve, emptyConfig);
66
- if (!result.cssText)
67
- return;
68
- let { cssText } = result;
69
- const slug = (0, shared_1.slugify)(cssText);
70
- const filename = `${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`;
71
- if (sourceMap && result.cssSourceMapText) {
72
- const map = Buffer.from(result.cssSourceMapText).toString('base64');
73
- cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
74
- }
75
- cssLookup[filename] = cssText;
76
- result.code += `\nimport ${JSON.stringify(filename)};\n`;
77
- /* eslint-disable-next-line consistent-return */
78
- return { code: result.code, map: result.sourceMap };
92
+ cssLookup[filename] = cssText;
93
+ result.code += `\nimport ${JSON.stringify(filename)};\n`;
94
+ /* eslint-disable-next-line consistent-return */
95
+ return { code: result.code, map: result.sourceMap };
96
+ });
79
97
  },
80
98
  };
81
99
  return new Proxy(plugin, {
@@ -87,4 +105,3 @@ function wywInJS({ exclude, include, prefixer, preprocessor, sourceMap, ...rest
87
105
  },
88
106
  });
89
107
  }
90
- exports.default = wywInJS;
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 Anton Evzhakov
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.