@commerce-klaus/vite-plugin-sfcc-modules 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jens Simon
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.
package/README.md ADDED
@@ -0,0 +1,144 @@
1
+ [![NPM version][npm-image]][npm-url] [![Downloads][npm-downloads-image]][npm-url]
2
+
3
+ # @commerce-klaus/vite-plugin-sfcc-modules
4
+
5
+ A Vite plugin that resolves Salesforce Commerce Cloud (SFCC) server-side module patterns.
6
+
7
+ This package continues `vite-plugin-sfcc-modules` under the Commerce-Klaus organization.
8
+ It originates from `@commerce-klaus/babel-plugin-sfcc-modules` and is the port to a modern Vite ecosystem. The goal is the same DX for SFCC module resolution, but natively in Vite/Vitest without a Babel runtime layer.
9
+
10
+ ## TL;DR
11
+
12
+ ```ts
13
+ import sfccModules from "@commerce-klaus/vite-plugin-sfcc-modules"
14
+
15
+ export default defineConfig({
16
+ plugins: [
17
+ sfccModules({
18
+ cartridgePath: ["app_brand", "app_core", "app_storefront_base"],
19
+ basePath: "./cartridges",
20
+ }),
21
+ ],
22
+ })
23
+ ```
24
+
25
+ ```js
26
+ // resolves first match in cartridge path
27
+ const foo = require("*/cartridge/scripts/foo")
28
+
29
+ // resolves inside the caller's own cartridge
30
+ const bar = require("~/cartridge/scripts/bar")
31
+
32
+ // resolves to next cartridge in path — rewritten to a static import
33
+ const base = module.superModule
34
+ ```
35
+
36
+ ## Why this plugin exists
37
+
38
+ SFCC projects often use module patterns that are not standard Node.js resolution:
39
+
40
+ - `require("*/cartridge/scripts/foo")`
41
+ - `require("~/cartridge/scripts/bar")`
42
+ - `module.superModule`
43
+
44
+ This plugin resolves those patterns according to cartridge path order and rewrites source code so Vite can process the full module graph.
45
+
46
+ ## Features
47
+
48
+ - Resolves `require("*/...")` against the configured cartridge path in order.
49
+ - Resolves `require("~/...")` against the caller's own cartridge.
50
+ - Resolves `module.superModule` to the next cartridge implementation.
51
+ - Supports `.js`, `.ds`, and `.json` file extensions.
52
+ - Works in Vite and Vitest pipelines.
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ pnpm add -D @commerce-klaus/vite-plugin-sfcc-modules
58
+ ```
59
+
60
+ or
61
+
62
+ ```bash
63
+ npm i -D @commerce-klaus/vite-plugin-sfcc-modules
64
+ ```
65
+
66
+ or
67
+
68
+ ```bash
69
+ yarn add -D @commerce-klaus/vite-plugin-sfcc-modules
70
+ ```
71
+
72
+ ## Usage
73
+
74
+ Add the plugin to your Vite config:
75
+
76
+ ```ts
77
+ import { defineConfig } from "vite"
78
+ import sfccModules from "@commerce-klaus/vite-plugin-sfcc-modules"
79
+
80
+ export default defineConfig({
81
+ plugins: [
82
+ sfccModules({
83
+ cartridgePath: ["app_brand", "app_core", "app_storefront_base"],
84
+ basePath: "./cartridges",
85
+ }),
86
+ ],
87
+ })
88
+ ```
89
+
90
+ ### Options
91
+
92
+ | Option | Type | Required | Description |
93
+ | --------------- | ---------- | -------- | -------------------------------------------------------------------------------------------------- |
94
+ | `cartridgePath` | `string[]` | yes | Ordered cartridge lookup path. First match wins. |
95
+ | `basePath` | `string` | yes | Path to the folder containing cartridges in `cartridgePath`. Resolved relative to `process.cwd()`. |
96
+
97
+ ## Resolution behavior
98
+
99
+ ### 1. `require("*/...")`
100
+
101
+ Searches all cartridges in `cartridgePath` order and picks the first matching file.
102
+
103
+ ### 2. `require("~/...")`
104
+
105
+ Resolves only in the current file's cartridge.
106
+
107
+ ### 3. `module.superModule`
108
+
109
+ Resolves to the next matching module in cartridge path order after the current cartridge.
110
+
111
+ Important: `module.superModule` is rewritten to a static `import`, not a runtime `require()`. This is intentional so Vite can transform transitive super-module chains as part of the normal module graph.
112
+
113
+ ## Vite + Vitest notes
114
+
115
+ - Use the plugin in the top-level `plugins` array of `vite.config.ts`.
116
+ - Do not rely on test-only plugin wiring that skips transitive transforms.
117
+ - In tests, prefer static `import` over `createRequire`, since `createRequire` bypasses Vite transforms.
118
+
119
+ ## Relationship to @commerce-klaus/babel-plugin-sfcc-modules
120
+
121
+ | Topic | `@commerce-klaus/babel-plugin-sfcc-modules` | `@commerce-klaus/vite-plugin-sfcc-modules` |
122
+ | -------------------- | ------------------------------------------- | ------------------------------------------ |
123
+ | Transformation layer | Babel | Vite transform pipeline |
124
+ | Runtime setup | Often Babel tooling / register | Native Vite/Vitest |
125
+ | Main use case | Babel-based SFCC toolchains | Modern Vite-based SFCC toolchains |
126
+
127
+ ## Development
128
+
129
+ This repository uses Vite+ (`vp`):
130
+
131
+ ```bash
132
+ vp install
133
+ vp check
134
+ vp test
135
+ vp run build
136
+ ```
137
+
138
+ ## License
139
+
140
+ MIT
141
+
142
+ [npm-url]: https://www.npmjs.com/package/@commerce-klaus/vite-olugin-sfcc-modules
143
+ [npm-image]: https://badgen.net/npm/v/@commerce-klaus/vite-olugin-sfcc-modules
144
+ [npm-downloads-image]: https://badgen.net/npm/dw/@commerce-klaus/vite-olugin-sfcc-modules
package/dist/index.cjs ADDED
@@ -0,0 +1,105 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let node_fs = require("node:fs");
24
+ node_fs = __toESM(node_fs, 1);
25
+ let node_path = require("node:path");
26
+ node_path = __toESM(node_path, 1);
27
+ //#region src/index.ts
28
+ const EXTENSIONS = [
29
+ "js",
30
+ "ds",
31
+ "json"
32
+ ];
33
+ /**
34
+ * Finds the first existing file for a target module path across cartridges.
35
+ *
36
+ * The function tries all supported extensions in cartridgePath order.
37
+ */
38
+ function findFirst(basePath, cartridges, target) {
39
+ for (const cartridge of cartridges) for (const ext of EXTENSIONS) {
40
+ const full = node_path.default.join(basePath, cartridge, `${target}.${ext}`);
41
+ if (node_fs.default.existsSync(full)) return full;
42
+ }
43
+ }
44
+ /** Removes only the trailing file extension from a path string. */
45
+ function stripExt(p) {
46
+ return p.replace(/\.[^.]+$/, "");
47
+ }
48
+ /**
49
+ * Vite plugin to resolve SFCC-specific module patterns.
50
+ *
51
+ * Supported patterns:
52
+ * - `require("<asterisk>/cartridge/...")` resolves against cartridgePath in order.
53
+ * - `require("~/cartridge/...")` resolves in the importer's own cartridge.
54
+ * - `module.superModule` resolves to the next matching module in cartridgePath.
55
+ *
56
+ * module.superModule is rewritten to a static import so Vite can transform
57
+ * transitive super modules as part of the normal module graph.
58
+ */
59
+ function sfccModules({ cartridgePath, basePath: rawBasePath }) {
60
+ const basePath = node_path.default.resolve(rawBasePath);
61
+ return {
62
+ name: "vite-plugin-sfcc-modules",
63
+ resolveId(source, importer) {
64
+ if (source.startsWith("*/")) {
65
+ const found = findFirst(basePath, cartridgePath, source.slice(2));
66
+ if (found) return found;
67
+ }
68
+ if (source.startsWith("~/") && importer) {
69
+ const ownCartridge = node_path.default.relative(basePath, importer).split(node_path.default.sep)[0];
70
+ if (ownCartridge) {
71
+ const found = findFirst(basePath, [ownCartridge], source.slice(2));
72
+ if (found) return found;
73
+ }
74
+ }
75
+ },
76
+ transform(code, id) {
77
+ const parts = node_path.default.relative(basePath, id).split(node_path.default.sep);
78
+ const ownCartridge = parts[0];
79
+ const isInCartridge = ownCartridge && cartridgePath.includes(ownCartridge);
80
+ let transformed = code;
81
+ transformed = transformed.replace(/require\((['"])\*\/([^'"]+)\1\)/g, (_match, _quote, target) => {
82
+ const found = findFirst(basePath, cartridgePath, `/${target}`);
83
+ return found ? `require(${JSON.stringify(found)})` : _match;
84
+ });
85
+ if (isInCartridge) transformed = transformed.replace(/require\((['"])~\/([^'"]+)\1\)/g, (_match, _quote, target) => {
86
+ const found = findFirst(basePath, [ownCartridge], `/${target}`);
87
+ return found ? `require(${JSON.stringify(found)})` : _match;
88
+ });
89
+ if (isInCartridge && transformed.includes("module.superModule")) {
90
+ const modulePathWithoutExt = "/" + stripExt(parts.slice(1).join("/"));
91
+ const ownIndex = cartridgePath.indexOf(ownCartridge);
92
+ const found = findFirst(basePath, cartridgePath.slice(ownIndex + 1), modulePathWithoutExt);
93
+ if (found) transformed = `import __sfcc_superModule__ from ${JSON.stringify(found)}\n` + transformed.replace(/\bmodule\.superModule\b/g, "__sfcc_superModule__");
94
+ else transformed = transformed.replace(/\bmodule\.superModule\b/g, "undefined");
95
+ }
96
+ if (transformed === code) return null;
97
+ return {
98
+ code: transformed,
99
+ map: null
100
+ };
101
+ }
102
+ };
103
+ }
104
+ //#endregion
105
+ module.exports = sfccModules;
package/dist/index.mjs ADDED
@@ -0,0 +1,81 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ //#region src/index.ts
4
+ const EXTENSIONS = [
5
+ "js",
6
+ "ds",
7
+ "json"
8
+ ];
9
+ /**
10
+ * Finds the first existing file for a target module path across cartridges.
11
+ *
12
+ * The function tries all supported extensions in cartridgePath order.
13
+ */
14
+ function findFirst(basePath, cartridges, target) {
15
+ for (const cartridge of cartridges) for (const ext of EXTENSIONS) {
16
+ const full = path.join(basePath, cartridge, `${target}.${ext}`);
17
+ if (fs.existsSync(full)) return full;
18
+ }
19
+ }
20
+ /** Removes only the trailing file extension from a path string. */
21
+ function stripExt(p) {
22
+ return p.replace(/\.[^.]+$/, "");
23
+ }
24
+ /**
25
+ * Vite plugin to resolve SFCC-specific module patterns.
26
+ *
27
+ * Supported patterns:
28
+ * - `require("<asterisk>/cartridge/...")` resolves against cartridgePath in order.
29
+ * - `require("~/cartridge/...")` resolves in the importer's own cartridge.
30
+ * - `module.superModule` resolves to the next matching module in cartridgePath.
31
+ *
32
+ * module.superModule is rewritten to a static import so Vite can transform
33
+ * transitive super modules as part of the normal module graph.
34
+ */
35
+ function sfccModules({ cartridgePath, basePath: rawBasePath }) {
36
+ const basePath = path.resolve(rawBasePath);
37
+ return {
38
+ name: "vite-plugin-sfcc-modules",
39
+ resolveId(source, importer) {
40
+ if (source.startsWith("*/")) {
41
+ const found = findFirst(basePath, cartridgePath, source.slice(2));
42
+ if (found) return found;
43
+ }
44
+ if (source.startsWith("~/") && importer) {
45
+ const ownCartridge = path.relative(basePath, importer).split(path.sep)[0];
46
+ if (ownCartridge) {
47
+ const found = findFirst(basePath, [ownCartridge], source.slice(2));
48
+ if (found) return found;
49
+ }
50
+ }
51
+ },
52
+ transform(code, id) {
53
+ const parts = path.relative(basePath, id).split(path.sep);
54
+ const ownCartridge = parts[0];
55
+ const isInCartridge = ownCartridge && cartridgePath.includes(ownCartridge);
56
+ let transformed = code;
57
+ transformed = transformed.replace(/require\((['"])\*\/([^'"]+)\1\)/g, (_match, _quote, target) => {
58
+ const found = findFirst(basePath, cartridgePath, `/${target}`);
59
+ return found ? `require(${JSON.stringify(found)})` : _match;
60
+ });
61
+ if (isInCartridge) transformed = transformed.replace(/require\((['"])~\/([^'"]+)\1\)/g, (_match, _quote, target) => {
62
+ const found = findFirst(basePath, [ownCartridge], `/${target}`);
63
+ return found ? `require(${JSON.stringify(found)})` : _match;
64
+ });
65
+ if (isInCartridge && transformed.includes("module.superModule")) {
66
+ const modulePathWithoutExt = "/" + stripExt(parts.slice(1).join("/"));
67
+ const ownIndex = cartridgePath.indexOf(ownCartridge);
68
+ const found = findFirst(basePath, cartridgePath.slice(ownIndex + 1), modulePathWithoutExt);
69
+ if (found) transformed = `import __sfcc_superModule__ from ${JSON.stringify(found)}\n` + transformed.replace(/\bmodule\.superModule\b/g, "__sfcc_superModule__");
70
+ else transformed = transformed.replace(/\bmodule\.superModule\b/g, "undefined");
71
+ }
72
+ if (transformed === code) return null;
73
+ return {
74
+ code: transformed,
75
+ map: null
76
+ };
77
+ }
78
+ };
79
+ }
80
+ //#endregion
81
+ export { sfccModules as default };
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@commerce-klaus/vite-plugin-sfcc-modules",
3
+ "version": "0.0.0",
4
+ "description": "Vite plugin to handle non-standard module paths used by Salesforce Commerce Cloud (SFCC)",
5
+ "keywords": [
6
+ "cartridge",
7
+ "commercecloud",
8
+ "demandware",
9
+ "salesforce",
10
+ "sfcc",
11
+ "sfra",
12
+ "supermodule",
13
+ "vite",
14
+ "vite-plugin"
15
+ ],
16
+ "homepage": "https://github.com/commerce-klaus/commerce-klaus/tree/main/packages/vite-plugin-sfcc-modules#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/commerce-klaus/commerce-klaus/issues"
19
+ },
20
+ "license": "MIT",
21
+ "author": "Jens Simon <https://github.com/jenssimon>",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/commerce-klaus/commerce-klaus",
25
+ "directory": "packages/vite-plugin-sfcc-modules"
26
+ },
27
+ "files": [
28
+ "/dist"
29
+ ],
30
+ "type": "module",
31
+ "main": "./dist/index.cjs",
32
+ "module": "./dist/index.mjs",
33
+ "exports": {
34
+ ".": {
35
+ "import": "./dist/index.mjs",
36
+ "require": "./dist/index.cjs"
37
+ }
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "vp pack",
44
+ "test": "vp test",
45
+ "check": "vp check",
46
+ "prepublishOnly": "vp run build"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^25.0.0",
50
+ "@vitest/coverage-v8": "^4.1.5",
51
+ "typescript": "^6.0.0",
52
+ "vite-plus": "latest"
53
+ },
54
+ "peerDependencies": {
55
+ "vite": ">=5.0.0"
56
+ },
57
+ "packageManager": "pnpm@11.9.0"
58
+ }