@jesscss/plugin-node-modules 2.0.0-alpha.1 → 2.0.0-alpha.11

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
@@ -1,74 +1,35 @@
1
1
  # @jesscss/plugin-node-modules
2
2
 
3
- Jess plugin for resolving and loading npm packages from `node_modules`.
4
-
5
- ## Overview
6
-
7
- This plugin provides npm/node_modules resolution and loading capabilities for all Jess language plugins. It uses Node's module resolution algorithm (`require.resolve`) to find and load npm packages.
8
-
9
- ## Usage
10
-
11
- ```typescript
12
- import { Compiler } from '@jesscss/jess';
13
- import nodeModulesPlugin from '@jesscss/plugin-node-modules';
14
-
15
- const compiler = new Compiler({
16
- compile: {
17
- plugins: [
18
- nodeModulesPlugin(),
19
- // ... other plugins
20
- ]
21
- }
22
- });
23
- ```
24
-
25
- ## API
26
-
27
- ### `resolvePackage(packageName: string): string | null`
28
-
29
- Resolve an npm package name to its absolute path.
30
-
31
- ```typescript
32
- const plugin = new NodeModulesPlugin();
33
- const path = plugin.resolvePackage('less-plugin-clean-css');
34
- // Returns: '/path/to/node_modules/less-plugin-clean-css/index.js' or null
35
- ```
36
-
37
- ### `loadPackage(packageName: string): Promise<Record<string, any> | null>`
38
-
39
- Load an npm package module.
40
-
41
- ```typescript
42
- const plugin = new NodeModulesPlugin();
43
- const module = await plugin.loadPackage('less-plugin-clean-css');
44
- // Returns: the module exports, or null if not found
45
- ```
46
-
47
- ### `tryResolvePackages(packageNames: string[]): Promise<{ name: string; module: Record<string, any> } | null>`
48
-
49
- Try to resolve a package name with multiple possible names. Returns the first successfully resolved package.
50
-
51
- ```typescript
52
- const plugin = new NodeModulesPlugin();
53
- const result = await plugin.tryResolvePackages([
54
- 'clean-css',
55
- 'less-plugin-clean-css'
56
- ]);
57
- // Returns: { name: 'less-plugin-clean-css', module: {...} } or null
58
- ```
59
-
60
- ## Integration with Other Plugins
61
-
62
- Other plugins (like `@jesscss/plugin-less-compat`) can use this plugin to resolve npm packages:
63
-
64
- ```typescript
65
- // In jess-plugin-less-compat
66
- const nodeModulesPlugin = plugins.find(p => p.name === 'node-modules');
67
- if (nodeModulesPlugin instanceof NodeModulesPlugin) {
68
- const module = await nodeModulesPlugin.loadPackage('less-plugin-clean-css');
69
- }
70
- ```
71
-
72
- ## Options
73
-
74
- - `enabled` (boolean, default: `true`): Whether to enable auto-resolution of npm packages.
3
+ **Import resolver that loads npm packages from `node_modules` — a seed of the
4
+ JavaScript-execution / CSS-in-JS story.**
5
+
6
+ This plugin gives Jess's language plugins a way to resolve and load npm packages
7
+ by name, using Node's module resolution (`require.resolve` /
8
+ `createRequire`). Other plugins use it to pull in packages referenced from a
9
+ stylesheet — for example [`@jesscss/plugin-less-compat`](../jess-plugin-less-compat)
10
+ resolving a Less `@plugin "package-name"` off `node_modules`.
11
+
12
+ ## Why it exists the convergence angle
13
+
14
+ One of the four tools [Jess](https://github.com/jesscss/jess) aims to converge is
15
+ **CSS-in-JS**: running real JavaScript inside your stylesheets (`@use` /
16
+ `@plugin`) so styles can be dynamic without leaving CSS files. Reaching npm
17
+ packages is a building block of that story. Paired with
18
+ [`@jesscss/plugin-js`](../jess-plugin-js) (which executes the modules), it lets a
19
+ stylesheet pull logic and data from the JS ecosystem.
20
+
21
+ That convergence is **roadmap — being proven through the alpha, not claimed as
22
+ done.** What ships here today is just the resolver seam; don't read it as a
23
+ finished CSS-in-JS system.
24
+
25
+ ## Status
26
+
27
+ **Alpha.** Part of Jess. The programmatic plugin/compiler API is **not yet
28
+ stabilized** — the `jess` CLI is the documented public surface for the alpha.
29
+ Watch the
30
+ [docs site](https://jesscss.github.io/) for the API once it settles.
31
+
32
+ - Project overview & positioning: <https://github.com/jesscss/jess#readme>
33
+ - Docs: <https://jesscss.github.io/> (currently pre-alpha content)
34
+ - Issues: <https://github.com/jesscss/jess/issues>
35
+ - License: MIT
package/lib/index.cjs ADDED
@@ -0,0 +1,171 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let _jesscss_core = require("@jesscss/core");
28
+ let node_module = require("node:module");
29
+ let node_url = require("node:url");
30
+ let node_path = require("node:path");
31
+ node_path = __toESM(node_path);
32
+ //#region src/index.ts
33
+ /**
34
+ * Plugin that provides npm/node_modules resolution and loading capabilities.
35
+ *
36
+ * This plugin implements the `import()` method to resolve and load npm packages
37
+ * using Node's module resolution algorithm (require.resolve).
38
+ *
39
+ * It can be used by other plugins (like jess-plugin-less-compat) to load
40
+ * npm packages when processing directives like `@plugin "package-name"`.
41
+ */
42
+ var NodeModulesPlugin = class extends _jesscss_core.AbstractPlugin {
43
+ name = "node-modules";
44
+ _require;
45
+ constructor(opts = {}) {
46
+ super();
47
+ this.opts = opts;
48
+ try {
49
+ let currentDir;
50
+ if (opts.basePath !== void 0) currentDir = opts.basePath;
51
+ else if (typeof __filename !== "undefined") currentDir = node_path.dirname(__filename);
52
+ else try {
53
+ const url = require("url").pathToFileURL(__filename).href;
54
+ currentDir = node_path.dirname((0, node_url.fileURLToPath)(url));
55
+ } catch {
56
+ currentDir = process.cwd();
57
+ }
58
+ this._require = (0, node_module.createRequire)(currentDir + "/");
59
+ } catch {
60
+ this._require = typeof require !== "undefined" ? require : (0, node_module.createRequire)(process.cwd() + "/");
61
+ }
62
+ }
63
+ /**
64
+ * Resolve an npm package name to its absolute path.
65
+ * Uses Node's module resolution algorithm (same as require.resolve).
66
+ *
67
+ * @param packageName - The npm package name (e.g., "less-plugin-clean-css")
68
+ * @param fromDir - Optional directory to start `node_modules` resolution from
69
+ * (walked up per Node's algorithm). When given it takes precedence over the
70
+ * plugin's `basePath`; used to resolve a package relative to the importing
71
+ * file (e.g. an `@import "pkg/x"` resolving against the importer's directory).
72
+ * @returns The absolute path to the package, or null if not found
73
+ */
74
+ resolvePackage(packageName, fromDir) {
75
+ if (this.opts.enabled === false) return null;
76
+ try {
77
+ return fromDir !== void 0 ? this._require.resolve(packageName, { paths: [fromDir] }) : this._require.resolve(packageName);
78
+ } catch (e) {
79
+ if (e instanceof Error && e.code === "MODULE_NOT_FOUND") return null;
80
+ throw e;
81
+ }
82
+ }
83
+ /**
84
+ * Context resolution hook for bare package specifiers. Core owns only the
85
+ * resolver-plugin pipeline; this plugin owns Node's module-resolution policy.
86
+ */
87
+ resolve(filePath, currentDir, searchPaths) {
88
+ const paths = Array.isArray(filePath) ? filePath : [filePath];
89
+ const bases = [currentDir, ...searchPaths];
90
+ const resolved = [];
91
+ for (const candidate of paths) {
92
+ if (!isBareModuleSpecifier(candidate)) {
93
+ resolved.push(candidate);
94
+ continue;
95
+ }
96
+ let modulePath = null;
97
+ for (const base of bases) {
98
+ modulePath = this.resolvePackage(candidate, base) ?? this.resolvePackage(`${candidate}.less`, base);
99
+ if (modulePath) break;
100
+ }
101
+ modulePath ??= this.resolvePackage(candidate) ?? this.resolvePackage(`${candidate}.less`);
102
+ resolved.push(modulePath ?? candidate);
103
+ }
104
+ return resolved;
105
+ }
106
+ /**
107
+ * Load an npm package module.
108
+ *
109
+ * @param packageName - The npm package name (e.g., "less-plugin-clean-css")
110
+ * @returns The loaded module, or null if not found
111
+ */
112
+ async loadPackage(packageName) {
113
+ const resolvedPath = this.resolvePackage(packageName);
114
+ if (!resolvedPath) return null;
115
+ try {
116
+ const module = this._require(resolvedPath);
117
+ return isRecord(module) ? module : null;
118
+ } catch {
119
+ return null;
120
+ }
121
+ }
122
+ /**
123
+ * Try to resolve a package name with multiple possible names.
124
+ * Useful for plugins that want to try different variations
125
+ * (e.g., "clean-css" and "less-plugin-clean-css").
126
+ *
127
+ * @param packageNames - Array of package names to try in order
128
+ * @returns The first successfully resolved package, or null if none found
129
+ */
130
+ async tryResolvePackages(packageNames) {
131
+ for (const name of packageNames) {
132
+ const module = await this.loadPackage(name);
133
+ if (module !== null) return {
134
+ name,
135
+ module
136
+ };
137
+ }
138
+ return null;
139
+ }
140
+ /**
141
+ * Import method for loading JavaScript modules from npm.
142
+ * This is called by the context when importing modules.
143
+ *
144
+ * @param absoluteFilePath - The absolute path to the module
145
+ * @returns The loaded module, or throws if this plugin can't handle it
146
+ */
147
+ async import(absoluteFilePath) {
148
+ if (this.opts.enabled === false) throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}" (disabled)`);
149
+ if (absoluteFilePath.includes("node_modules")) try {
150
+ const module = this._require(absoluteFilePath);
151
+ if (!isRecord(module)) throw new TypeError(`Module "${absoluteFilePath}" did not export an object.`);
152
+ return module;
153
+ } catch (e) {
154
+ const message = e instanceof Error ? e.message : String(e);
155
+ throw new Error(`Failed to import "${absoluteFilePath}": ${message}`);
156
+ }
157
+ throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}" (not a node_modules path)`);
158
+ }
159
+ };
160
+ function isBareModuleSpecifier(candidate) {
161
+ return !node_path.isAbsolute(candidate) && !candidate.startsWith("./") && !candidate.startsWith("../") && !candidate.startsWith("/") && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(candidate);
162
+ }
163
+ function isRecord(value) {
164
+ return value !== null && typeof value === "object";
165
+ }
166
+ const nodeModulesPlugin = ((opts) => {
167
+ return new NodeModulesPlugin(opts);
168
+ });
169
+ //#endregion
170
+ exports.NodeModulesPlugin = NodeModulesPlugin;
171
+ exports.default = nodeModulesPlugin;
package/lib/index.d.ts CHANGED
@@ -5,6 +5,14 @@ interface NodeModulesPluginOptions {
5
5
  * Default: true
6
6
  */
7
7
  enabled?: boolean;
8
+ /**
9
+ * Directory to anchor Node's module resolution at. When set, `require.resolve`
10
+ * walks `node_modules` starting from this directory (instead of the plugin's own
11
+ * location). Used to resolve packages relative to a consuming project or a
12
+ * fixture tree rather than where the plugin is installed.
13
+ * Default: the plugin file's directory (falling back to `process.cwd()`).
14
+ */
15
+ basePath?: string;
8
16
  }
9
17
  export type { NodeModulesPluginOptions };
10
18
  /**
@@ -26,9 +34,18 @@ export declare class NodeModulesPlugin extends AbstractPlugin {
26
34
  * Uses Node's module resolution algorithm (same as require.resolve).
27
35
  *
28
36
  * @param packageName - The npm package name (e.g., "less-plugin-clean-css")
37
+ * @param fromDir - Optional directory to start `node_modules` resolution from
38
+ * (walked up per Node's algorithm). When given it takes precedence over the
39
+ * plugin's `basePath`; used to resolve a package relative to the importing
40
+ * file (e.g. an `@import "pkg/x"` resolving against the importer's directory).
29
41
  * @returns The absolute path to the package, or null if not found
30
42
  */
31
- resolvePackage(packageName: string): string | null;
43
+ resolvePackage(packageName: string, fromDir?: string): string | null;
44
+ /**
45
+ * Context resolution hook for bare package specifiers. Core owns only the
46
+ * resolver-plugin pipeline; this plugin owns Node's module-resolution policy.
47
+ */
48
+ resolve(filePath: string | string[], currentDir: string, searchPaths: string[]): string[];
32
49
  /**
33
50
  * Load an npm package module.
34
51
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,c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BAAkB,SAAQ,cAAc;IAKhC,IAAI,EAAE,wBAAwB;IAJjD,IAAI,SAAkB;IAEtB,OAAO,CAAC,QAAQ,CAAc;gBAEX,IAAI,GAAE,wBAA6B;IAwCtD;;;;;;;;;;OAUG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAyBpE;;;OAGG;IACM,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE;IAyBlG;;;;;OAKG;IACG,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC;IAiB3E;;;;;;;OAOG;IACG,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;KAAE,GAAG,IAAI,CAAC;IAU/G;;;;;;OAMG;IACG,MAAM,CAAC,gBAAgB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAyBrE;AAcD,QAAA,MAAM,iBAAiB,UAAY,wBAAwB,sBAExC,CAAC;AAEpB,eAAe,iBAAiB,CAAC"}
package/lib/index.js CHANGED
@@ -1,150 +1,146 @@
1
- import { AbstractPlugin } from '@jesscss/core';
2
- import { createRequire } from 'node:module';
3
- import { fileURLToPath } from 'node:url';
4
- import * as path from 'node:path';
1
+ import { createRequire } from "node:module";
2
+ import { AbstractPlugin } from "@jesscss/core";
3
+ import { fileURLToPath } from "node:url";
4
+ import * as path from "node:path";
5
+ //#region \0rolldown/runtime.js
6
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
7
+ //#endregion
8
+ //#region src/index.ts
5
9
  /**
6
- * Plugin that provides npm/node_modules resolution and loading capabilities.
7
- *
8
- * This plugin implements the `import()` method to resolve and load npm packages
9
- * using Node's module resolution algorithm (require.resolve).
10
- *
11
- * It can be used by other plugins (like jess-plugin-less-compat) to load
12
- * npm packages when processing directives like `@plugin "package-name"`.
13
- */
14
- export class NodeModulesPlugin extends AbstractPlugin {
15
- opts;
16
- name = 'node-modules';
17
- _require;
18
- constructor(opts = {}) {
19
- super();
20
- this.opts = opts;
21
- // Create a require function that can resolve modules
22
- // Use createRequire to get a require function in ES module contexts
23
- try {
24
- // Try to use the current file's directory as the base for resolution
25
- let currentDir;
26
- if (typeof __filename !== 'undefined') {
27
- currentDir = path.dirname(__filename);
28
- }
29
- else {
30
- // In ES module contexts, try to use import.meta.url
31
- // This will only work if the module system supports it
32
- try {
33
- // eslint-disable-next-line @typescript-eslint/no-var-requires
34
- const url = globalThis.import?.meta?.url;
35
- if (url) {
36
- currentDir = path.dirname(fileURLToPath(url));
37
- }
38
- else {
39
- throw new Error('import.meta not available');
40
- }
41
- }
42
- catch {
43
- // Fallback to process.cwd()
44
- currentDir = process.cwd();
45
- }
46
- }
47
- this._require = createRequire(currentDir + '/');
48
- }
49
- catch {
50
- // Fallback to global require if available
51
- this._require = typeof require !== 'undefined' ? require : (() => {
52
- throw new Error('require is not available');
53
- });
54
- }
55
- }
56
- /**
57
- * Resolve an npm package name to its absolute path.
58
- * Uses Node's module resolution algorithm (same as require.resolve).
59
- *
60
- * @param packageName - The npm package name (e.g., "less-plugin-clean-css")
61
- * @returns The absolute path to the package, or null if not found
62
- */
63
- resolvePackage(packageName) {
64
- if (this.opts.enabled === false) {
65
- return null;
66
- }
67
- try {
68
- // Use require.resolve to find the package
69
- // This will search node_modules using Node's resolution algorithm
70
- const resolved = this._require.resolve(packageName);
71
- return resolved;
72
- }
73
- catch (e) {
74
- // MODULE_NOT_FOUND is expected when package doesn't exist
75
- if (e.code === 'MODULE_NOT_FOUND') {
76
- return null;
77
- }
78
- // Re-throw other errors
79
- throw e;
80
- }
81
- }
82
- /**
83
- * Load an npm package module.
84
- *
85
- * @param packageName - The npm package name (e.g., "less-plugin-clean-css")
86
- * @returns The loaded module, or null if not found
87
- */
88
- async loadPackage(packageName) {
89
- const resolvedPath = this.resolvePackage(packageName);
90
- if (!resolvedPath) {
91
- return null;
92
- }
93
- try {
94
- // Load the module using require
95
- const module = this._require(resolvedPath);
96
- return module || null;
97
- }
98
- catch (e) {
99
- // If loading fails, return null
100
- return null;
101
- }
102
- }
103
- /**
104
- * Try to resolve a package name with multiple possible names.
105
- * Useful for plugins that want to try different variations
106
- * (e.g., "clean-css" and "less-plugin-clean-css").
107
- *
108
- * @param packageNames - Array of package names to try in order
109
- * @returns The first successfully resolved package, or null if none found
110
- */
111
- async tryResolvePackages(packageNames) {
112
- for (const name of packageNames) {
113
- const module = await this.loadPackage(name);
114
- if (module !== null) {
115
- return { name, module: module };
116
- }
117
- }
118
- return null;
119
- }
120
- /**
121
- * Import method for loading JavaScript modules from npm.
122
- * This is called by the context when importing modules.
123
- *
124
- * @param absoluteFilePath - The absolute path to the module
125
- * @returns The loaded module, or throws if this plugin can't handle it
126
- */
127
- async import(absoluteFilePath) {
128
- if (this.opts.enabled === false) {
129
- throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}" (disabled)`);
130
- }
131
- // Check if this looks like a node_modules path
132
- // We can't directly resolve from absolute paths, but we can try to require it
133
- if (absoluteFilePath.includes('node_modules')) {
134
- try {
135
- const module = this._require(absoluteFilePath);
136
- return module;
137
- }
138
- catch (e) {
139
- throw new Error(`Failed to import "${absoluteFilePath}": ${e.message}`);
140
- }
141
- }
142
- // For non-node_modules paths, throw to let other plugins handle it
143
- throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}" (not a node_modules path)`);
144
- }
10
+ * Plugin that provides npm/node_modules resolution and loading capabilities.
11
+ *
12
+ * This plugin implements the `import()` method to resolve and load npm packages
13
+ * using Node's module resolution algorithm (require.resolve).
14
+ *
15
+ * It can be used by other plugins (like jess-plugin-less-compat) to load
16
+ * npm packages when processing directives like `@plugin "package-name"`.
17
+ */
18
+ var NodeModulesPlugin = class extends AbstractPlugin {
19
+ name = "node-modules";
20
+ _require;
21
+ constructor(opts = {}) {
22
+ super();
23
+ this.opts = opts;
24
+ try {
25
+ let currentDir;
26
+ if (opts.basePath !== void 0) currentDir = opts.basePath;
27
+ else if (typeof __filename !== "undefined") currentDir = path.dirname(__filename);
28
+ else try {
29
+ const url = import.meta.url;
30
+ currentDir = path.dirname(fileURLToPath(url));
31
+ } catch {
32
+ currentDir = process.cwd();
33
+ }
34
+ this._require = createRequire(currentDir + "/");
35
+ } catch {
36
+ this._require = typeof __require !== "undefined" ? __require : createRequire(process.cwd() + "/");
37
+ }
38
+ }
39
+ /**
40
+ * Resolve an npm package name to its absolute path.
41
+ * Uses Node's module resolution algorithm (same as require.resolve).
42
+ *
43
+ * @param packageName - The npm package name (e.g., "less-plugin-clean-css")
44
+ * @param fromDir - Optional directory to start `node_modules` resolution from
45
+ * (walked up per Node's algorithm). When given it takes precedence over the
46
+ * plugin's `basePath`; used to resolve a package relative to the importing
47
+ * file (e.g. an `@import "pkg/x"` resolving against the importer's directory).
48
+ * @returns The absolute path to the package, or null if not found
49
+ */
50
+ resolvePackage(packageName, fromDir) {
51
+ if (this.opts.enabled === false) return null;
52
+ try {
53
+ return fromDir !== void 0 ? this._require.resolve(packageName, { paths: [fromDir] }) : this._require.resolve(packageName);
54
+ } catch (e) {
55
+ if (e instanceof Error && e.code === "MODULE_NOT_FOUND") return null;
56
+ throw e;
57
+ }
58
+ }
59
+ /**
60
+ * Context resolution hook for bare package specifiers. Core owns only the
61
+ * resolver-plugin pipeline; this plugin owns Node's module-resolution policy.
62
+ */
63
+ resolve(filePath, currentDir, searchPaths) {
64
+ const paths = Array.isArray(filePath) ? filePath : [filePath];
65
+ const bases = [currentDir, ...searchPaths];
66
+ const resolved = [];
67
+ for (const candidate of paths) {
68
+ if (!isBareModuleSpecifier(candidate)) {
69
+ resolved.push(candidate);
70
+ continue;
71
+ }
72
+ let modulePath = null;
73
+ for (const base of bases) {
74
+ modulePath = this.resolvePackage(candidate, base) ?? this.resolvePackage(`${candidate}.less`, base);
75
+ if (modulePath) break;
76
+ }
77
+ modulePath ??= this.resolvePackage(candidate) ?? this.resolvePackage(`${candidate}.less`);
78
+ resolved.push(modulePath ?? candidate);
79
+ }
80
+ return resolved;
81
+ }
82
+ /**
83
+ * Load an npm package module.
84
+ *
85
+ * @param packageName - The npm package name (e.g., "less-plugin-clean-css")
86
+ * @returns The loaded module, or null if not found
87
+ */
88
+ async loadPackage(packageName) {
89
+ const resolvedPath = this.resolvePackage(packageName);
90
+ if (!resolvedPath) return null;
91
+ try {
92
+ const module = this._require(resolvedPath);
93
+ return isRecord(module) ? module : null;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+ /**
99
+ * Try to resolve a package name with multiple possible names.
100
+ * Useful for plugins that want to try different variations
101
+ * (e.g., "clean-css" and "less-plugin-clean-css").
102
+ *
103
+ * @param packageNames - Array of package names to try in order
104
+ * @returns The first successfully resolved package, or null if none found
105
+ */
106
+ async tryResolvePackages(packageNames) {
107
+ for (const name of packageNames) {
108
+ const module = await this.loadPackage(name);
109
+ if (module !== null) return {
110
+ name,
111
+ module
112
+ };
113
+ }
114
+ return null;
115
+ }
116
+ /**
117
+ * Import method for loading JavaScript modules from npm.
118
+ * This is called by the context when importing modules.
119
+ *
120
+ * @param absoluteFilePath - The absolute path to the module
121
+ * @returns The loaded module, or throws if this plugin can't handle it
122
+ */
123
+ async import(absoluteFilePath) {
124
+ if (this.opts.enabled === false) throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}" (disabled)`);
125
+ if (absoluteFilePath.includes("node_modules")) try {
126
+ const module = this._require(absoluteFilePath);
127
+ if (!isRecord(module)) throw new TypeError(`Module "${absoluteFilePath}" did not export an object.`);
128
+ return module;
129
+ } catch (e) {
130
+ const message = e instanceof Error ? e.message : String(e);
131
+ throw new Error(`Failed to import "${absoluteFilePath}": ${message}`);
132
+ }
133
+ throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}" (not a node_modules path)`);
134
+ }
135
+ };
136
+ function isBareModuleSpecifier(candidate) {
137
+ return !path.isAbsolute(candidate) && !candidate.startsWith("./") && !candidate.startsWith("../") && !candidate.startsWith("/") && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(candidate);
138
+ }
139
+ function isRecord(value) {
140
+ return value !== null && typeof value === "object";
145
141
  }
146
142
  const nodeModulesPlugin = ((opts) => {
147
- return new NodeModulesPlugin(opts);
143
+ return new NodeModulesPlugin(opts);
148
144
  });
149
- export default nodeModulesPlugin;
150
- //# sourceMappingURL=index.js.map
145
+ //#endregion
146
+ export { NodeModulesPlugin, nodeModulesPlugin as default };
package/package.json CHANGED
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "name": "@jesscss/plugin-node-modules",
3
- "version": "2.0.0-alpha.1",
3
+ "version": "2.0.0-alpha.11",
4
+ "engines": {
5
+ "node": "^20.19.0 || >=22.12.0"
6
+ },
4
7
  "description": "Jess plugin for resolving and loading npm packages from node_modules",
5
- "main": "lib/index.js",
8
+ "main": "lib/index.cjs",
6
9
  "types": "lib/index.d.ts",
7
10
  "exports": {
8
11
  ".": {
9
- "import": "./lib/index.js",
10
12
  "types": "./lib/index.d.ts",
11
- "source": "./src/index.ts"
13
+ "import": "./lib/index.js",
14
+ "require": "./lib/index.cjs"
12
15
  },
13
16
  "./package.json": "./package.json"
14
17
  },
@@ -16,7 +19,7 @@
16
19
  "lib"
17
20
  ],
18
21
  "dependencies": {
19
- "@jesscss/core": "2.0.0-alpha.1"
22
+ "@jesscss/core": "2.0.0-alpha.11"
20
23
  },
21
24
  "devDependencies": {
22
25
  "@types/node": "^20.0.0",
@@ -27,10 +30,12 @@
27
30
  "publishConfig": {
28
31
  "access": "public"
29
32
  },
33
+ "type": "module",
34
+ "module": "lib/index.js",
30
35
  "scripts": {
31
36
  "build": "pnpm compile",
32
- "compile": "tsc -b tsconfig.build.json",
33
- "dev": "tsc -b tsconfig.json -w",
37
+ "compile": "tsdown --tsconfig tsconfig.build.json --no-dts && tsc -p tsconfig.build.json --emitDeclarationOnly",
38
+ "dev": "tsdown --tsconfig tsconfig.build.json --watch",
34
39
  "lint:fix": "eslint --fix '**/*.{js,ts}'",
35
40
  "lint": "eslint '**/*.{js,ts}'"
36
41
  }
package/lib/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,cAAc,EACf,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAYlC;;;;;;;;GAQG;AACH,MAAM,OAAO,iBAAkB,SAAQ,cAAc;IAKhC;IAJnB,IAAI,GAAG,cAAc,CAAC;IAEd,QAAQ,CAAc;IAE9B,YAAmB,OAAiC,EAAE;QACpD,KAAK,EAAE,CAAC;QADS,SAAI,GAAJ,IAAI,CAA+B;QAGpD,qDAAqD;QACrD,oEAAoE;QACpE,IAAI,CAAC;YACH,qEAAqE;YACrE,IAAI,UAAkB,CAAC;YACvB,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE,CAAC;gBACtC,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;YACxC,CAAC;iBAAM,CAAC;gBACN,oDAAoD;gBACpD,uDAAuD;gBACvD,IAAI,CAAC;oBACH,8DAA8D;oBAC9D,MAAM,GAAG,GAAI,UAAkB,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC;oBAClD,IAAI,GAAG,EAAE,CAAC;wBACR,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;oBAChD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