@appdirect/sfb-toolkit 5.0.8 → 6.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.
Files changed (120) hide show
  1. package/.eslintrc +35 -35
  2. package/CHANGELOG.md +32 -0
  3. package/Dockerfile +2 -1
  4. package/agent/.cursor/rules/sfb-storefront.mdc +17 -0
  5. package/agent/.cursor/skills/sfb-custom-components/COMPONENT-CATALOG.md +130 -0
  6. package/agent/.cursor/skills/sfb-custom-components/SKILL.md +43 -0
  7. package/agent/.cursor/skills/sfb-localization-settings/SKILL.md +29 -0
  8. package/agent/.cursor/skills/sfb-theme-customize/SKILL.md +25 -0
  9. package/agent/.cursor/skills/sfb-toolkit-commands/SKILL.md +35 -0
  10. package/agent/AGENTS.md +160 -0
  11. package/agent/CLAUDE.md +19 -0
  12. package/bin/index.js +82 -100
  13. package/coverage/clover.xml +1921 -335
  14. package/coverage/coverage-final.json +41 -20
  15. package/coverage/lcov-report/{controllers/controllers-utils → config}/index.html +19 -19
  16. package/coverage/lcov-report/config/index.js.html +124 -0
  17. package/coverage/lcov-report/index.html +108 -78
  18. package/coverage/lcov-report/{constants → src/constants}/customUserAttributesMock.js.html +12 -12
  19. package/coverage/lcov-report/{constants → src/constants}/index.html +10 -10
  20. package/coverage/lcov-report/{constants → src/constants}/pageUrls.js.html +14 -14
  21. package/coverage/lcov-report/{constants → src/constants}/userMock.js.html +13 -13
  22. package/coverage/lcov-report/{controllers → src/controllers}/controllers-utils/assetsUtils.js.html +20 -20
  23. package/coverage/lcov-report/src/controllers/controllers-utils/index.html +131 -0
  24. package/coverage/lcov-report/src/controllers/controllers-utils/locale.js.html +115 -0
  25. package/coverage/lcov-report/{controllers → src/controllers}/data-filters/bootstrap-data-filter.js.html +15 -15
  26. package/coverage/lcov-report/{controllers → src/controllers}/data-filters/call-to-actions-filter.js.html +22 -22
  27. package/coverage/lcov-report/{controllers → src/controllers}/data-filters/index.html +37 -22
  28. package/coverage/lcov-report/src/controllers/data-filters/media-url-filter.js.html +394 -0
  29. package/coverage/lcov-report/{controllers → src/controllers}/index.html +27 -27
  30. package/coverage/lcov-report/{controllers → src/controllers}/index.js.html +159 -126
  31. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/base/ResultItem.js.html +43 -43
  32. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/base/SearchBar.js.html +22 -22
  33. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/base/index.html +28 -28
  34. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/base/item.js.html +28 -28
  35. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/container.js.html +31 -31
  36. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/data-view.js.html +29 -29
  37. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/header-view.js.html +35 -38
  38. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/index.html +45 -45
  39. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/components/search.js.html +54 -54
  40. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/constants/index.html +22 -22
  41. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/constants/pageUrl.js.html +17 -17
  42. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/constants/roleType.js.html +14 -14
  43. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/constants/searchType.js.html +17 -17
  44. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/utils/debounce.js.html +15 -15
  45. package/coverage/lcov-report/{front-end-utils → src/front-end-utils}/src/utils/index.html +20 -20
  46. package/coverage/lcov-report/{middlewares → src/middlewares}/config.js.html +11 -11
  47. package/coverage/lcov-report/{middlewares → src/middlewares}/index.html +10 -10
  48. package/coverage/lcov-report/{tools → src/routes}/index.html +30 -30
  49. package/coverage/lcov-report/src/routes/media-proxy.js.html +613 -0
  50. package/coverage/lcov-report/src/tools/compile-styles.js.html +1018 -0
  51. package/coverage/lcov-report/src/tools/custom-components-export-compat-loader.js.html +745 -0
  52. package/coverage/lcov-report/src/tools/index.html +371 -0
  53. package/coverage/lcov-report/src/tools/prompt-questions.js.html +1117 -0
  54. package/coverage/lcov-report/{tools → src/tools}/proxy-fetch.js.html +15 -15
  55. package/coverage/lcov-report/src/tools/resolve-components-react.js.html +457 -0
  56. package/coverage/lcov-report/src/tools/sass-legacy-compat.js.html +1192 -0
  57. package/coverage/lcov-report/src/tools/toolkit-cli-argv.js.html +226 -0
  58. package/coverage/lcov-report/src/tools/toolkit-common-fun.js.html +1192 -0
  59. package/coverage/lcov-report/src/tools/toolkit-common-vars-namespace.js.html +403 -0
  60. package/coverage/lcov-report/src/tools/toolkit-common-vars.js.html +283 -0
  61. package/coverage/lcov-report/src/tools/toolkit-components-fun.js.html +1237 -0
  62. package/coverage/lcov-report/src/tools/toolkit-components-vars.js.html +232 -0
  63. package/coverage/lcov-report/src/tools/toolkit-install-agent-guidance.js.html +439 -0
  64. package/coverage/lcov-report/src/tools/toolkit-live-reload.js.html +688 -0
  65. package/coverage/lcov-report/src/tools/toolkit-path.js.html +184 -0
  66. package/coverage/lcov-report/src/tools/toolkit-spawn.js.html +199 -0
  67. package/coverage/lcov-report/src/tools/toolkit-v6-theme-risk.js.html +1039 -0
  68. package/coverage/lcov-report/src/tools/toolkit-zip-utils.js.html +190 -0
  69. package/coverage/lcov.info +3356 -727
  70. package/index.js +40 -20
  71. package/npm-shrinkwrap.json +19445 -35435
  72. package/package.json +50 -41
  73. package/readme.md +23 -1
  74. package/rspack-components.config.cjs +81 -0
  75. package/rspack-components.config.prod.cjs +71 -0
  76. package/rspack.config.cjs +25 -0
  77. package/rspack.shared.cjs +164 -0
  78. package/src/controllers/controllers-utils/locale.js +10 -0
  79. package/src/controllers/data-filters/media-url-filter.js +103 -0
  80. package/src/controllers/index.js +15 -4
  81. package/src/front-end-utils/dist/toolbar.bundle.js +1 -2
  82. package/src/front-end-utils/src/components/header-view.js +0 -1
  83. package/src/routes/cors.js +29 -0
  84. package/src/routes/index.js +2 -0
  85. package/src/routes/media-proxy.js +176 -0
  86. package/src/tools/compile-styles.js +311 -0
  87. package/src/tools/compiler-components-prod.js +32 -21
  88. package/src/tools/compiler-css.js +7 -7
  89. package/src/tools/custom-components-export-compat-loader.js +220 -0
  90. package/src/tools/resolve-components-react.js +124 -0
  91. package/src/tools/sass-legacy-compat.js +369 -0
  92. package/src/tools/toolkit-checkout.js +3 -6
  93. package/src/tools/toolkit-cli-argv.js +47 -0
  94. package/src/tools/toolkit-common-fun.js +66 -18
  95. package/src/tools/toolkit-common-utils.js +5 -3
  96. package/src/tools/toolkit-common-vars.js +4 -3
  97. package/src/tools/toolkit-components-copy.js +6 -4
  98. package/src/tools/toolkit-components-fun.js +6 -4
  99. package/src/tools/toolkit-config-setup.js +2 -1
  100. package/src/tools/toolkit-create.js +5 -7
  101. package/src/tools/toolkit-import.js +5 -6
  102. package/src/tools/toolkit-install-agent-guidance-cli.js +24 -0
  103. package/src/tools/toolkit-install-agent-guidance.js +118 -0
  104. package/src/tools/toolkit-install.js +8 -8
  105. package/src/tools/toolkit-live-reload.js +201 -0
  106. package/src/tools/toolkit-package.js +25 -7
  107. package/src/tools/toolkit-path.js +33 -0
  108. package/src/tools/toolkit-setup-e2e.js +2 -1
  109. package/src/tools/toolkit-setup.js +5 -1
  110. package/src/tools/toolkit-spawn.js +38 -0
  111. package/src/tools/toolkit-start.js +98 -54
  112. package/src/tools/toolkit-storybook.js +38 -19
  113. package/src/tools/toolkit-update.js +5 -3
  114. package/src/tools/toolkit-v6-theme-risk.js +318 -0
  115. package/themes-param.json +1 -0
  116. package/src/front-end-utils/dist/toolbar.bundle.js.LICENSE.txt +0 -52
  117. package/src/tools/gulp-tasks.js +0 -80
  118. package/webpack-components.config.cjs +0 -123
  119. package/webpack-components.config.prod.cjs +0 -113
  120. package/webpack.config.cjs +0 -25
@@ -70,7 +70,6 @@ const LOGGED_IN_HEADER_TEMPLATE = "headerIn";
70
70
  const COOKIE_EXPIRATION_IN_DAYS = 1 / 3;
71
71
 
72
72
  const updateMockUserCookies = (role) => {
73
- console.log(role);
74
73
  switch (role) {
75
74
  case USER:
76
75
  Cookies.set("mockUserLoggedInHeader", true, {
@@ -6,6 +6,7 @@ const userMemberships = require("./mockRoutes/user/memberships");
6
6
  const marketplaceManagerMemberships = require("./mockRoutes/marketplaceManager/memberships");
7
7
  const marketplaceManagerAssignmetns = require("./mockRoutes/marketplaceManager/assignments");
8
8
  const marketplaceManagerBootstrapContext = require("./mockRoutes/marketplaceManager/bootstrapContext");
9
+ const fetch = require("../tools/proxy-fetch");
9
10
 
10
11
  const currentPath = process.cwd();
11
12
  // eslint-disable-next-line import/no-dynamic-require
@@ -98,4 +99,32 @@ module.exports = (routes) => {
98
99
  corsPipe.callApi(req, res);
99
100
  }
100
101
  });
102
+ routes.post("/api/graphql/preview", async (req, res) => {
103
+ try {
104
+ const response = await fetch(
105
+ `${req.config.marketplacePath}/api/graphql/preview`,
106
+ {
107
+ method: "POST",
108
+ headers: {
109
+ "Content-Type": "application/json",
110
+ },
111
+ body: JSON.stringify({
112
+ query: req.body.query,
113
+ variables: req.body.variables,
114
+ }),
115
+ }
116
+ );
117
+
118
+ if (!response.ok) {
119
+ throw new Error(`HTTP error! status: ${response.status}`);
120
+ }
121
+
122
+ const data = await response.json();
123
+ res.send({
124
+ ...data,
125
+ });
126
+ } catch (error) {
127
+ console.error("Error making GraphQL call:", error);
128
+ }
129
+ });
101
130
  };
@@ -1,9 +1,11 @@
1
1
  const routes = require("express").Router();
2
2
  const corsRoutes = require("./cors");
3
+ const mediaProxyRoutes = require("./media-proxy");
3
4
  const PageCtrl = require("../controllers");
4
5
  const CartCtrl = require("../controllers/cart");
5
6
 
6
7
  corsRoutes(routes);
8
+ mediaProxyRoutes(routes);
7
9
  routes.get("/", (req, res) =>
8
10
  new PageCtrl({ req, res, page: "home" }).redirectToLocalePage()
9
11
  );
@@ -0,0 +1,176 @@
1
+ const fetch = require('../tools/proxy-fetch');
2
+ const {
3
+ MEDIA_PROXY_PATH,
4
+ isAllowedPdfHost,
5
+ isPdfPath
6
+ } = require('../controllers/data-filters/media-url-filter');
7
+
8
+ const MAX_REDIRECTS = 5;
9
+ const ALLOWED_PORTS = new Set(['', '80', '443']);
10
+
11
+ function looksLikePdf(buffer, contentType) {
12
+ if (buffer && buffer.length >= 4) {
13
+ const magic = buffer.slice(0, 5).toString('utf8');
14
+ if (magic.startsWith('%PDF-')) {
15
+ return true;
16
+ }
17
+ }
18
+ const type = (contentType || '').toLowerCase();
19
+ return type.includes('application/pdf');
20
+ }
21
+
22
+ function looksLikeHtml(buffer, contentType) {
23
+ const type = (contentType || '').toLowerCase();
24
+ if (type.includes('text/html') || type.includes('application/xhtml')) {
25
+ return true;
26
+ }
27
+ if (!buffer || buffer.length === 0) {
28
+ return false;
29
+ }
30
+ const head = buffer.slice(0, 256).toString('utf8').trim().toLowerCase();
31
+ return head.startsWith('<!doctype html') || head.startsWith('<html');
32
+ }
33
+
34
+ function isIpHostname(hostname) {
35
+ // Block literal IPs — allowlist is DNS suffixes only (CloudFront / AppDirect CDNs).
36
+ if (!hostname) {
37
+ return true;
38
+ }
39
+ if (hostname.startsWith('[') && hostname.endsWith(']')) {
40
+ return true;
41
+ }
42
+ return /^(?:\d{1,3}\.){3}\d{1,3}$/.test(hostname);
43
+ }
44
+
45
+ /**
46
+ * Validate and rebuild a PDF URL from allowlisted components.
47
+ * Never return the raw user string — CodeQL SSRF / redirect pivot safe.
48
+ * @returns {string|null}
49
+ */
50
+ function toSafePdfFetchUrl(candidate) {
51
+ if (!candidate || typeof candidate !== 'string') {
52
+ return null;
53
+ }
54
+
55
+ let parsed;
56
+ try {
57
+ parsed = new URL(candidate);
58
+ } catch (err) {
59
+ return null;
60
+ }
61
+
62
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
63
+ return null;
64
+ }
65
+ if (parsed.username || parsed.password) {
66
+ return null;
67
+ }
68
+ if (!ALLOWED_PORTS.has(parsed.port)) {
69
+ return null;
70
+ }
71
+ if (isIpHostname(parsed.hostname) || !isAllowedPdfHost(parsed.hostname)) {
72
+ return null;
73
+ }
74
+ if (!isPdfPath(parsed.pathname)) {
75
+ return null;
76
+ }
77
+
78
+ // Rebuild from validated pieces only (drop hash; keep query for CDN signed URLs).
79
+ const safe = new URL('https://placeholder.invalid/');
80
+ safe.protocol = parsed.protocol;
81
+ safe.hostname = parsed.hostname.toLowerCase();
82
+ safe.port = parsed.port;
83
+ safe.pathname = parsed.pathname;
84
+ safe.search = parsed.search;
85
+ safe.hash = '';
86
+ return safe.href;
87
+ }
88
+
89
+ async function fetchPdfWithoutOpenRedirect(safeUrl) {
90
+ let current = safeUrl;
91
+
92
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
93
+ const upstream = await fetch(current, {
94
+ method: 'GET',
95
+ redirect: 'manual',
96
+ headers: {
97
+ 'User-Agent': 'sfb-toolkit-media-proxy',
98
+ Accept: 'application/pdf'
99
+ }
100
+ });
101
+
102
+ if (upstream.status >= 300 && upstream.status < 400) {
103
+ const location = upstream.headers.get('location');
104
+ if (!location) {
105
+ return { errorStatus: 502, errorBody: 'Redirect without location' };
106
+ }
107
+ let next;
108
+ try {
109
+ next = new URL(location, current).href;
110
+ } catch (err) {
111
+ return { errorStatus: 502, errorBody: 'Invalid redirect' };
112
+ }
113
+ const nextSafe = toSafePdfFetchUrl(next);
114
+ if (!nextSafe) {
115
+ return { errorStatus: 403, errorBody: 'Redirect host or path not allowed' };
116
+ }
117
+ current = nextSafe;
118
+ continue;
119
+ }
120
+
121
+ return { upstream };
122
+ }
123
+
124
+ return { errorStatus: 502, errorBody: 'Too many redirects' };
125
+ }
126
+
127
+ /**
128
+ * Same-origin PDF proxy for toolkit resource previews.
129
+ * Host allowlist + .pdf path + no open redirects + PDF body sniff.
130
+ */
131
+ function mediaProxyRoutes(routes) {
132
+ routes.get(MEDIA_PROXY_PATH, async (req, res) => {
133
+ const safeUrl = toSafePdfFetchUrl(req.query.url);
134
+ if (!safeUrl) {
135
+ res.status(403).send('Host or path not allowed');
136
+ return;
137
+ }
138
+
139
+ try {
140
+ const result = await fetchPdfWithoutOpenRedirect(safeUrl);
141
+ if (result.errorStatus) {
142
+ res.status(result.errorStatus).send(result.errorBody);
143
+ return;
144
+ }
145
+
146
+ const { upstream } = result;
147
+ if (!upstream.ok) {
148
+ res.status(upstream.status).send(`Upstream ${upstream.status}`);
149
+ return;
150
+ }
151
+
152
+ const upstreamType = upstream.headers.get('content-type') || '';
153
+ const buffer = await upstream.buffer();
154
+
155
+ if (looksLikeHtml(buffer, upstreamType) || !looksLikePdf(buffer, upstreamType)) {
156
+ res.status(502).send('Upstream response is not a PDF');
157
+ return;
158
+ }
159
+
160
+ // Always force PDF document headers — never forward untrusted Content-Type.
161
+ res.setHeader('Content-Type', 'application/pdf');
162
+ res.setHeader('Content-Disposition', 'inline');
163
+ res.setHeader('X-Content-Type-Options', 'nosniff');
164
+ res.setHeader('Cache-Control', 'private, max-age=300');
165
+ res.removeHeader('X-Frame-Options');
166
+
167
+ res.send(buffer);
168
+ } catch (err) {
169
+ console.error('sfb-toolkit-media-proxy failed', err);
170
+ res.status(502).send('Proxy failed');
171
+ }
172
+ });
173
+ }
174
+
175
+ module.exports = mediaProxyRoutes;
176
+ module.exports.toSafePdfFetchUrl = toSafePdfFetchUrl;
@@ -0,0 +1,311 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { pathToFileURL } = require("url");
4
+ const glob = require("glob");
5
+ const sass = require("sass-embedded");
6
+ const chokidar = require("chokidar");
7
+ const {
8
+ legacyCompileOptionsForEntry,
9
+ readLegacyEntrySource,
10
+ createLegacySassImporters,
11
+ applyLegacySourceRewrites
12
+ } = require("./sass-legacy-compat");
13
+
14
+ // Theme SCSS still uses @import / legacy APIs; silence until themes migrate to @use.
15
+ // Matches rspack.shared.cjs so toolkit start logs stay clean.
16
+ // Keep sass-embedded pinned <1.92 so mixed-decls still hoist (old cascade).
17
+ // Silence the warning until themes move declarations above nested rules.
18
+ const SILENCE_DEPRECATIONS = [
19
+ "import",
20
+ "global-builtin",
21
+ "color-functions",
22
+ "slash-div",
23
+ "legacy-js-api",
24
+ "mixed-decls",
25
+ // sfb-theme-components: mix($color, $color, 15) without %
26
+ "function-units"
27
+ ];
28
+
29
+ const ASSET_GLOBS = ["assets/**/*.scss", "assets/**/*.sass"];
30
+ const HEADER_FOOTER_GLOB = "header-footer/**/*.scss";
31
+ const COMPONENTS_GLOB = "components/**/*.scss";
32
+ const WATCH_DEBOUNCE_MS = 150;
33
+
34
+ const getThemePaths = (cwd, theme) => {
35
+ const themeRoot = path.join(cwd, "themes", theme);
36
+ return {
37
+ themeRoot,
38
+ componentsDest: path.join(themeRoot, "assets", "css", "components"),
39
+ // Watch SCSS only — writing .css/.map must not retrigger the compiler.
40
+ watchGlobs: [
41
+ path.join(themeRoot, "assets/**/*.{scss,sass}"),
42
+ path.join(themeRoot, "header-footer/**/*.scss"),
43
+ path.join(themeRoot, "components/**/*.scss")
44
+ ],
45
+ // Rspack owns customComponents SCSS; theme watch must not rebuild on those.
46
+ watchIgnored: [
47
+ /(^|[/\\])\../,
48
+ /\.css(\.map)?$/i,
49
+ /[/\\]customComponents[/\\]/
50
+ ]
51
+ };
52
+ };
53
+
54
+ const isScssPartial = filePath => /^_/.test(path.basename(filePath));
55
+
56
+ // Packaging copies component SCSS under assets/customComponents; those belong to
57
+ // the Rspack customComponents build (sfb-components.css), not theme entries.
58
+ const isCustomComponentsPath = filePath =>
59
+ filePath.replace(/\\/g, "/").includes("/customComponents/");
60
+
61
+ // Some themes (e.g. Trimble) name the real header/footer entry `_header-index.scss`.
62
+ // Sass treats that as a partial, but the storefront expects `header-index.css`.
63
+ const FORCE_ENTRY_PARTIAL_RE = /^_(header|footer)-index\.(scss|sass)$/i;
64
+ const isForcedEntryPartial = filePath =>
65
+ FORCE_ENTRY_PARTIAL_RE.test(path.basename(filePath));
66
+
67
+ const globFiles = (themeRoot, patterns, { includePartials = true } = {}) => {
68
+ const files = [];
69
+ for (const pattern of patterns) {
70
+ for (const rel of glob.sync(pattern, {
71
+ cwd: themeRoot,
72
+ nodir: true,
73
+ ignore: ["**/customComponents/**"]
74
+ })) {
75
+ const abs = path.join(themeRoot, rel);
76
+ if (!includePartials && isScssPartial(abs)) {
77
+ continue;
78
+ }
79
+ if (isCustomComponentsPath(abs)) {
80
+ continue;
81
+ }
82
+ files.push(abs);
83
+ }
84
+ }
85
+ return files;
86
+ };
87
+
88
+ const buildSassOptions = ({ compressed, sourceMap }) => ({
89
+ style: compressed ? "compressed" : "expanded",
90
+ quietDeps: true,
91
+ silenceDeprecations: SILENCE_DEPRECATIONS,
92
+ sourceMap: Boolean(sourceMap),
93
+ sourceMapIncludeSources: Boolean(sourceMap)
94
+ });
95
+
96
+ const cssPathFor = scssPath => {
97
+ const dir = path.dirname(scssPath);
98
+ const base = path.basename(scssPath);
99
+ const stem = base.replace(/\.s[ac]ss$/i, "");
100
+ const outStem = isForcedEntryPartial(scssPath) ? stem.slice(1) : stem;
101
+ return path.join(dir, `${outStem}.css`);
102
+ };
103
+
104
+ const writeCompileResult = (scssPath, result, { sourceMap }) => {
105
+ const outCss = cssPathFor(scssPath);
106
+ let css = result.css;
107
+ if (sourceMap && result.sourceMap) {
108
+ const mapPath = `${outCss}.map`;
109
+ fs.writeFileSync(mapPath, JSON.stringify(result.sourceMap));
110
+ css = `${css}\n/*# sourceMappingURL=${path.basename(mapPath)} */`;
111
+ }
112
+ fs.writeFileSync(outCss, css);
113
+ return outCss;
114
+ };
115
+
116
+ /**
117
+ * Compile one SCSS/Sass entry. Failures are logged and skipped (same as gulp-sass logError).
118
+ * @returns {string|null} written CSS path, or null on failure / skip
119
+ */
120
+ const logCompileError = (err, { quiet }) => {
121
+ if (quiet) return;
122
+ // eslint-disable-next-line no-console
123
+ console.error(err.formatted || err.message || err);
124
+ };
125
+
126
+ const compileScssFile = (scssPath, options) => {
127
+ try {
128
+ const result = sass.compileString(readLegacyEntrySource(scssPath), {
129
+ ...buildSassOptions(options),
130
+ ...legacyCompileOptionsForEntry(scssPath)
131
+ });
132
+ return writeCompileResult(scssPath, result, options);
133
+ } catch (err) {
134
+ logCompileError(err, options);
135
+ return null;
136
+ }
137
+ };
138
+
139
+ const compileStringToFile = (source, outCssPath, options, { loadPaths, sourcePath }) => {
140
+ try {
141
+ const resolvedLoadPaths = (loadPaths || []).map(p => path.resolve(p));
142
+ const result = sass.compileString(applyLegacySourceRewrites(source), {
143
+ ...buildSassOptions(options),
144
+ // Virtual entry under legacy importers so nested theme @imports get compat.
145
+ url: pathToFileURL(sourcePath),
146
+ loadPaths: resolvedLoadPaths,
147
+ importers: createLegacySassImporters(resolvedLoadPaths)
148
+ });
149
+ const dir = path.dirname(outCssPath);
150
+ fs.mkdirSync(dir, { recursive: true });
151
+ let css = result.css;
152
+ if (options.sourceMap && result.sourceMap) {
153
+ const mapPath = `${outCssPath}.map`;
154
+ fs.writeFileSync(mapPath, JSON.stringify(result.sourceMap));
155
+ css = `${css}\n/*# sourceMappingURL=${path.basename(mapPath)} */`;
156
+ }
157
+ fs.writeFileSync(outCssPath, css);
158
+ return outCssPath;
159
+ } catch (err) {
160
+ logCompileError(err, options);
161
+ return null;
162
+ }
163
+ };
164
+
165
+ // Entry roots only — Sass partials (_*.scss) are pulled in via @import, not compiled alone,
166
+ // except forced header/footer index entries (see FORCE_ENTRY_PARTIAL_RE).
167
+ const listAssetEntries = themeRoot => {
168
+ const entries = globFiles(themeRoot, [...ASSET_GLOBS, HEADER_FOOTER_GLOB], {
169
+ includePartials: false
170
+ });
171
+ const seen = new Set(entries);
172
+ for (const abs of globFiles(themeRoot, [HEADER_FOOTER_GLOB], {
173
+ includePartials: true
174
+ })) {
175
+ if (isForcedEntryPartial(abs) && !seen.has(abs)) {
176
+ entries.push(abs);
177
+ seen.add(abs);
178
+ }
179
+ }
180
+ return entries;
181
+ };
182
+
183
+ const compileAssets = (themePaths, options) => {
184
+ const written = [];
185
+ for (const file of listAssetEntries(themePaths.themeRoot)) {
186
+ const out = compileScssFile(file, options);
187
+ if (out) written.push(out);
188
+ }
189
+ return written;
190
+ };
191
+
192
+ const compileComponents = (themePaths, options) => {
193
+ const files = globFiles(themePaths.themeRoot, [COMPONENTS_GLOB]);
194
+ if (!files.length) {
195
+ return [];
196
+ }
197
+ const source = files.map(f => fs.readFileSync(f, "utf8")).join("\n");
198
+ const outCss = path.join(themePaths.componentsDest, "components.css");
199
+ const out = compileStringToFile(source, outCss, options, {
200
+ loadPaths: [
201
+ ...new Set(files.map(f => path.dirname(f))),
202
+ process.cwd()
203
+ ],
204
+ sourcePath: path.join(themePaths.componentsDest, "components.scss")
205
+ });
206
+ return out ? [out] : [];
207
+ };
208
+
209
+ /**
210
+ * Compile theme styles (assets + header-footer + concatenated components).
211
+ * @param {{ cwd?: string, theme: string, mode?: 'production'|'development', quiet?: boolean }} opts
212
+ * @returns {string[]} paths of CSS files written
213
+ */
214
+ const compileStyles = ({
215
+ cwd = process.cwd(),
216
+ theme,
217
+ mode = "production",
218
+ quiet = false
219
+ } = {}) => {
220
+ if (!theme) {
221
+ throw new Error("compileStyles: theme is required");
222
+ }
223
+ const themePaths = getThemePaths(cwd, theme);
224
+ const options = {
225
+ compressed: mode === "production",
226
+ sourceMap: mode !== "production",
227
+ quiet
228
+ };
229
+ return [...compileAssets(themePaths, options), ...compileComponents(themePaths, options)];
230
+ };
231
+
232
+ /**
233
+ * Watch theme SCSS and recompile on change (development).
234
+ * @returns {{ close: () => Promise<void> }}
235
+ */
236
+ const watchStyles = ({ cwd = process.cwd(), theme } = {}) => {
237
+ if (!theme) {
238
+ throw new Error("watchStyles: theme is required");
239
+ }
240
+ const themePaths = getThemePaths(cwd, theme);
241
+ const options = { compressed: false, sourceMap: true };
242
+ let timer = null;
243
+ let rebuilding = false;
244
+ let pending = false;
245
+
246
+ const runRebuild = () => {
247
+ if (rebuilding) {
248
+ pending = true;
249
+ return;
250
+ }
251
+ rebuilding = true;
252
+ try {
253
+ compileAssets(themePaths, options);
254
+ compileComponents(themePaths, options);
255
+ } finally {
256
+ rebuilding = false;
257
+ if (pending) {
258
+ pending = false;
259
+ runRebuild();
260
+ }
261
+ }
262
+ };
263
+
264
+ const scheduleRebuild = () => {
265
+ clearTimeout(timer);
266
+ timer = setTimeout(runRebuild, WATCH_DEBOUNCE_MS);
267
+ };
268
+
269
+ const watcher = chokidar.watch(themePaths.watchGlobs, {
270
+ ignoreInitial: true,
271
+ ignored: themePaths.watchIgnored
272
+ });
273
+ watcher.on("add", scheduleRebuild).on("change", scheduleRebuild).on("unlink", scheduleRebuild);
274
+ return {
275
+ close: () => {
276
+ clearTimeout(timer);
277
+ return watcher.close();
278
+ }
279
+ };
280
+ };
281
+
282
+ // Back-compat names used by compiler-css.js / older scripts
283
+ const resolveThemeFromProjectConfig = cwd => {
284
+ // eslint-disable-next-line import/no-dynamic-require, global-require
285
+ const config = require(path.join(cwd, "config"));
286
+ return config.theme;
287
+ };
288
+
289
+ const compileStylesTask = () => {
290
+ const cwd = process.cwd();
291
+ compileStyles({ cwd, theme: resolveThemeFromProjectConfig(cwd), mode: "production" });
292
+ };
293
+
294
+ const compileStylesDevTask = () => {
295
+ const cwd = process.cwd();
296
+ compileStyles({ cwd, theme: resolveThemeFromProjectConfig(cwd), mode: "development" });
297
+ };
298
+
299
+ const watchStylesTask = () => {
300
+ const cwd = process.cwd();
301
+ watchStyles({ cwd, theme: resolveThemeFromProjectConfig(cwd) });
302
+ };
303
+
304
+ module.exports = {
305
+ compileStyles,
306
+ watchStyles,
307
+ SILENCE_DEPRECATIONS,
308
+ compileStylesTask,
309
+ compileStylesDevTask,
310
+ watchStylesTask
311
+ };
@@ -1,30 +1,41 @@
1
- const webpack = require("webpack")
1
+ const { rspack } = require("@rspack/core")
2
2
  const fs = require("fs")
3
3
  const fsExtra = require("fs-extra")
4
4
  const { TOOLKIT_PATH } = require("./toolkit-common-vars")
5
5
 
6
- const getConfigComponentsProdWebpack = require(`${TOOLKIT_PATH}/webpack-components.config.prod.cjs`)
6
+ const getConfigComponentsProd = require(`${TOOLKIT_PATH}/rspack-components.config.prod.cjs`)
7
7
  const currentPath = process.cwd() // used to get current dev folder
8
8
  const config = require(`${currentPath}/config`)
9
- const customComponentsAssets = `${currentPath}/themes/${
10
- config.theme
11
- }/assets/js/components`
9
+ const customComponentsPath = `${currentPath}/themes/${config.theme}/customComponents`
10
+ const customComponentsAssets = `${currentPath}/themes/${config.theme}/assets/js/components`
12
11
 
13
- if (fs.existsSync(customComponentsAssets)) {
14
- // Remove unnecessary hot directory for the webpack hot module reload
15
- fsExtra.remove(`${customComponentsAssets}/hot`, fsError => {
16
- if (fsError) {
17
- console.error(fsError)
18
- }
12
+ if (!fs.existsSync(customComponentsPath)) {
13
+ process.exit(0)
14
+ }
15
+
16
+ fsExtra.ensureDirSync(customComponentsAssets)
17
+
18
+ // Remove unnecessary hot directory for the hot module reload
19
+ fsExtra.remove(`${customComponentsAssets}/hot`, (fsError) => {
20
+ if (fsError) {
21
+ console.error(fsError)
22
+ }
19
23
 
20
- const configComponentsWebpackAsset = getConfigComponentsProdWebpack(
21
- currentPath,
22
- config
23
- )
24
- webpack(configComponentsWebpackAsset, (err, stats) => {
25
- if (err || stats.hasErrors()) {
26
- console.log(stats.hasErrors())
27
- }
28
- })
24
+ const configComponentsAsset = getConfigComponentsProd(currentPath, config)
25
+ rspack(configComponentsAsset, (err, stats) => {
26
+ if (err) {
27
+ console.error(err)
28
+ process.exit(1)
29
+ }
30
+ if (stats.hasErrors()) {
31
+ console.error(
32
+ stats.toString({
33
+ colors: true,
34
+ errors: true,
35
+ warnings: false,
36
+ })
37
+ )
38
+ process.exit(1)
39
+ }
29
40
  })
30
- }
41
+ })
@@ -1,12 +1,12 @@
1
1
  const {
2
- gulpCompileStylesDevTask,
3
- gulpCompileStylesTask,
4
- gulpWatchStylesTask
5
- } = require("./gulp-tasks")
2
+ compileStylesDevTask,
3
+ compileStylesTask,
4
+ watchStylesTask
5
+ } = require("./compile-styles");
6
6
 
7
7
  if (process.env.RUNDEVSERVER === "true") {
8
- gulpCompileStylesDevTask();
9
- gulpWatchStylesTask();
8
+ compileStylesDevTask();
9
+ watchStylesTask();
10
10
  } else {
11
- gulpCompileStylesTask()
11
+ compileStylesTask();
12
12
  }