@jsenv/plugin-commonjs 2.0.4 → 2.0.6

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.
@@ -1,77 +1,77 @@
1
1
  // https://github.com/snowpackjs/snowpack/blob/main/esinstall/src/rollup-plugins/rollup-plugin-wrap-install-targets.ts
2
2
 
3
- import { readFileSync } from "node:fs"
4
- import { fileURLToPath, pathToFileURL } from "node:url"
5
- import path from "node:path"
6
- import { VM as VM2 } from "vm2"
7
- import resolve from "resolve"
8
- import isValidIdentifier from "is-valid-identifier"
9
- import { init, parse } from "cjs-module-lexer"
3
+ import { readFileSync } from "node:fs";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import path from "node:path";
6
+ import { VM as VM2 } from "vm2";
7
+ import resolve from "resolve";
8
+ import isValidIdentifier from "is-valid-identifier";
9
+ import { init, parse } from "cjs-module-lexer";
10
10
 
11
11
  const importWrapper = {
12
12
  wrap: (specifier) => {
13
- return `cjs_scan:${specifier}`
13
+ return `cjs_scan:${specifier}`;
14
14
  },
15
15
  unwrap: (specifier) => {
16
- return specifier.slice("cjs_scan:".length)
16
+ return specifier.slice("cjs_scan:".length);
17
17
  },
18
18
  isWrapped: (specifier) => {
19
- return specifier.startsWith("cjs_scan:")
19
+ return specifier.startsWith("cjs_scan:");
20
20
  },
21
- }
21
+ };
22
22
 
23
23
  export const rollupPluginCommonJsNamedExports = ({ logger }) => {
24
- const scanResults = {}
24
+ const scanResults = {};
25
25
 
26
26
  return {
27
27
  name: "scan_cjs_named_exports",
28
28
  async buildStart({ input }) {
29
- await init()
29
+ await init();
30
30
  Object.keys(input).forEach((key) => {
31
- const inputFilePath = input[key]
31
+ const inputFilePath = input[key];
32
32
  const namedCjs =
33
33
  detectStaticExports({ logger, filePath: inputFilePath }) ||
34
34
  detectExportsUsingSandboxedRuntime({
35
35
  logger,
36
36
  filePath: inputFilePath,
37
- })
37
+ });
38
38
  scanResults[inputFilePath] = {
39
39
  all: true,
40
40
  default: true,
41
41
  namespace: true,
42
42
  named: [],
43
43
  namedCjs,
44
- }
45
- input[key] = importWrapper.wrap(inputFilePath)
46
- })
44
+ };
45
+ input[key] = importWrapper.wrap(inputFilePath);
46
+ });
47
47
  },
48
48
  resolveId(specifier) {
49
49
  if (importWrapper.isWrapped(specifier)) {
50
- return specifier
50
+ return specifier;
51
51
  }
52
- return null
52
+ return null;
53
53
  },
54
54
  load(id) {
55
55
  if (!importWrapper.isWrapped(id)) {
56
- return null
56
+ return null;
57
57
  }
58
- const inputFilePath = importWrapper.unwrap(id)
59
- const scanResult = scanResults[inputFilePath]
60
- let uniqueNamedExports = scanResult.named
61
- const namedCjs = scanResult.namedCjs
58
+ const inputFilePath = importWrapper.unwrap(id);
59
+ const scanResult = scanResults[inputFilePath];
60
+ let uniqueNamedExports = scanResult.named;
61
+ const namedCjs = scanResult.namedCjs;
62
62
  if (namedCjs.length) {
63
- uniqueNamedExports = namedCjs
64
- scanResult.default = true
63
+ uniqueNamedExports = namedCjs;
64
+ scanResult.default = true;
65
65
  }
66
66
  const codeForExports = generateCodeForExports({
67
67
  uniqueNamedExports,
68
68
  scanResult,
69
69
  inputFilePath,
70
- })
71
- return codeForExports
70
+ });
71
+ return codeForExports;
72
72
  },
73
- }
74
- }
73
+ };
74
+ };
75
75
 
76
76
  /*
77
77
  * Attempt #1: Static analysis: Lower Fidelity, but faster.
@@ -80,48 +80,48 @@ export const rollupPluginCommonJsNamedExports = ({ logger }) => {
80
80
  * depending on how they were build/written/compiled.
81
81
  */
82
82
  const detectStaticExports = ({ logger, filePath, visited = new Set() }) => {
83
- const isMainEntrypoint = visited.size === 0
83
+ const isMainEntrypoint = visited.size === 0;
84
84
  // Prevent infinite loops via circular dependencies.
85
85
  if (visited.has(filePath)) {
86
- return []
86
+ return [];
87
87
  }
88
- visited.add(filePath)
88
+ visited.add(filePath);
89
89
 
90
- const fileContents = readFileSync(filePath, "utf8")
90
+ const fileContents = readFileSync(filePath, "utf8");
91
91
  try {
92
- const { exports, reexports } = parse(fileContents)
92
+ const { exports, reexports } = parse(fileContents);
93
93
  // If re-exports were detected (`exports.foo = require(...)`) then resolve them here.
94
- let resolvedReexports = []
94
+ let resolvedReexports = [];
95
95
  if (reexports.length > 0) {
96
96
  reexports.forEach((reexport) => {
97
97
  const reExportedFilePath = resolve.sync(reexport, {
98
98
  basedir: fileURLToPath(new URL("./", pathToFileURL(filePath))),
99
- })
99
+ });
100
100
  const staticExports = detectStaticExports({
101
101
  logger,
102
102
  filePath: reExportedFilePath,
103
103
  visited,
104
- })
104
+ });
105
105
  if (staticExports) {
106
- resolvedReexports = [...resolvedReexports, ...staticExports]
106
+ resolvedReexports = [...resolvedReexports, ...staticExports];
107
107
  }
108
- })
108
+ });
109
109
  }
110
110
  const resolvedExports = Array.from(
111
111
  new Set([...exports, ...resolvedReexports]),
112
- ).filter(isValidNamedExport)
112
+ ).filter(isValidNamedExport);
113
113
 
114
114
  if (isMainEntrypoint && resolvedExports.length === 0) {
115
- return []
115
+ return [];
116
116
  }
117
117
 
118
- return resolvedExports
118
+ return resolvedExports;
119
119
  } catch (err) {
120
120
  // Safe to ignore, this is usually due to the file not being CJS.
121
- logger.debug(`detectStaticExports ${filePath}: ${err.message}`)
122
- return []
121
+ logger.debug(`detectStaticExports ${filePath}: ${err.message}`);
122
+ return [];
123
123
  }
124
- }
124
+ };
125
125
 
126
126
  /*
127
127
  * Attempt #2b - Sandboxed runtime analysis: More powerful, but slower.
@@ -131,59 +131,59 @@ const detectStaticExports = ({ logger, filePath, visited = new Set() }) => {
131
131
  */
132
132
  const detectExportsUsingSandboxedRuntime = ({ logger, filePath }) => {
133
133
  try {
134
- const fileContents = readFileSync(filePath, "utf8")
135
- const vm = new VM2({ wasm: false, fixAsync: false })
136
- const codeToRun = wrapCodeToRunInVm(fileContents)
137
- const vmResult = vm.run(codeToRun)
138
- const exportsResult = Object.keys(vmResult)
134
+ const fileContents = readFileSync(filePath, "utf8");
135
+ const vm = new VM2({ wasm: false, fixAsync: false });
136
+ const codeToRun = wrapCodeToRunInVm(fileContents);
137
+ const vmResult = vm.run(codeToRun);
138
+ const exportsResult = Object.keys(vmResult);
139
139
  logger.debug(
140
140
  `detectExportsUsingSandboxedRuntime success ${filePath}: ${exportsResult}`,
141
- )
142
- return exportsResult.filter((identifier) => isValidIdentifier(identifier))
141
+ );
142
+ return exportsResult.filter((identifier) => isValidIdentifier(identifier));
143
143
  } catch (err) {
144
144
  logger.debug(
145
145
  `detectExportsUsingSandboxedRuntime error ${filePath}: ${err.message}`,
146
- )
147
- return []
146
+ );
147
+ return [];
148
148
  }
149
- }
149
+ };
150
150
 
151
151
  const isValidNamedExport = (name) =>
152
- name !== "default" && name !== "__esModule" && isValidIdentifier(name)
152
+ name !== "default" && name !== "__esModule" && isValidIdentifier(name);
153
153
 
154
154
  const wrapCodeToRunInVm = (code) => {
155
155
  return `const exports = {};
156
156
  const module = { exports };
157
157
  ${code};;
158
- module.exports;`
159
- }
158
+ module.exports;`;
159
+ };
160
160
 
161
161
  const generateCodeForExports = ({
162
162
  uniqueNamedExports,
163
163
  scanResult,
164
164
  inputFilePath,
165
165
  }) => {
166
- const from = inputFilePath.split(path.win32.sep).join(path.posix.sep)
166
+ const from = inputFilePath.split(path.win32.sep).join(path.posix.sep);
167
167
  const lines = [
168
168
  ...(scanResult.namespace ? [stringifyNamespaceReExport({ from })] : []),
169
169
  ...(scanResult.default ? [stringifyDefaultReExport({ from })] : []),
170
170
  ...(uniqueNamedExports.length
171
171
  ? [stringifyNamedReExports({ namedExports: uniqueNamedExports, from })]
172
172
  : []),
173
- ]
173
+ ];
174
174
  return lines.join(`
175
- `)
176
- }
175
+ `);
176
+ };
177
177
 
178
178
  const stringifyNamespaceReExport = ({ from }) => {
179
- return `export * from "${from}";`
180
- }
179
+ return `export * from "${from}";`;
180
+ };
181
181
 
182
182
  const stringifyDefaultReExport = ({ from }) => {
183
183
  return `import __jsenv_default_import__ from "${from}";
184
- export default __jsenv_default_import__;`
185
- }
184
+ export default __jsenv_default_import__;`;
185
+ };
186
186
 
187
187
  const stringifyNamedReExports = ({ namedExports, from }) => {
188
- return `export { ${namedExports.join(",")} } from "${from}";`
189
- }
188
+ return `export { ${namedExports.join(",")} } from "${from}";`;
189
+ };