useblocks-cli 1.1.88 → 1.1.102

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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +142 -114
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -16,7 +16,7 @@ var __copyProps = (to, from, except, desc) => {
16
16
  }
17
17
  return to;
18
18
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
@@ -26,37 +26,17 @@ let fs = require("fs");
26
26
  fs = __toESM(fs);
27
27
  let path = require("path");
28
28
  path = __toESM(path);
29
- require("dotenv");
30
- let node_fs = require("node:fs");
31
- node_fs = __toESM(node_fs);
32
29
  let module$1 = require("module");
33
30
  let prompts = require("prompts");
34
31
  prompts = __toESM(prompts);
32
+ let node_fs = require("node:fs");
33
+ node_fs = __toESM(node_fs);
35
34
  let node_path = require("node:path");
36
35
  node_path = __toESM(node_path);
37
36
  let yargs_yargs = require("yargs/yargs");
38
37
  yargs_yargs = __toESM(yargs_yargs);
39
38
  let eta = require("eta");
40
- //#region ../config/repo/paths.ts
41
- /**
42
- * Константы путей проекта
43
- *
44
- * Этот файл НЕ должен импортировать Vite плагины или другие ESM-only зависимости,
45
- * чтобы его можно было использовать в скриптах запускаемых через tsx.
46
- */
47
- /** Корневая директория проекта */
48
- var ROOT_DIR$2 = (0, path.resolve)(__dirname, "../../..");
49
- (0, path.resolve)(ROOT_DIR$2, "./src");
50
- (0, path.resolve)(ROOT_DIR$2, "node_modules/.vite-cache");
51
- (0, path.resolve)(ROOT_DIR$2, "./packages");
52
- (0, path.resolve)(ROOT_DIR$2, "./local_modules");
53
- (0, path.resolve)(ROOT_DIR$2, "./build");
54
- (0, path.resolve)(ROOT_DIR$2, "index.html"), (0, path.resolve)(ROOT_DIR$2, "src/index.tsx"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/loader/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/core/entry.ts"), (0, path.resolve)(ROOT_DIR$2, "packages/po/index.ts"), (0, path.resolve)(ROOT_DIR$2, "iframe"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe.html"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe-eblock.html"), (0, path.resolve)(ROOT_DIR$2, "public"), (0, path.resolve)(ROOT_DIR$2, "src/pluginExamples"), (0, path.resolve)(ROOT_DIR$2, "src/extensions"), (0, path.resolve)(ROOT_DIR$2, "src/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "tsconfig.types.json"), (0, path.resolve)(ROOT_DIR$2, "src"), (0, path.resolve)(ROOT_DIR$2, "iframe/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "src/extensions/api/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/extensions/react/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/assets/images/atoms"), (0, path.resolve)(ROOT_DIR$2, "src/assets"), (0, path.resolve)(ROOT_DIR$2, "src"), (0, path.resolve)(ROOT_DIR$2, "packages/extensions-core/identifiers"), (0, path.resolve)(ROOT_DIR$2, "src/app/identifiers"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/pluginRegistry"), (0, path.resolve)(ROOT_DIR$2, "src/constants/errors"), (0, path.resolve)(ROOT_DIR$2, "src/helpers/shared/mapHttpStatusToErrorCode"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/const"), (0, path.resolve)(ROOT_DIR$2, "src/helpers/guid"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/utils/waitForElement"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/mixins/auth"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/mixins/base");
55
- (0, path.resolve)(ROOT_DIR$2, "apps/widget/saas/index.tsx"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/entries/loader.ts"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/entries/core.ts"), (0, path.resolve)(ROOT_DIR$2, "iframe"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe.html"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe-eblock.html"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/public"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/pluginExamples"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/extensions"), (0, path.resolve)(ROOT_DIR$2, "apps/widget"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget"), (0, path.resolve)(ROOT_DIR$2, "iframe/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/extensions/api/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/src/assets"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/src"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/pluginRuntime");
56
- (0, path.resolve)(ROOT_DIR$2, "iframe/js/extensions/api/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "packages/ui-kit/src"), (0, path.resolve)(ROOT_DIR$2, "packages/ui-kit/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "packages/ui-kit/public"), (0, path.resolve)(ROOT_DIR$2, "build-tools/config/runtime"), (0, path.resolve)(ROOT_DIR$2, "packages/core-loader/src"), (0, path.resolve)(ROOT_DIR$2, "build-tools/plugins/loaders/loaders/amd-loader.js");
57
- path.default.resolve(__dirname, "../../..");
58
- path.default.resolve(__dirname, "../../versions.json");
59
- path.default.resolve(__dirname, "../..");
39
+ //#region ../utils/envMode.ts
60
40
  /** All supported loadEnv / pipeline env modes. */
61
41
  var ENV_MODES = [
62
42
  "dev",
@@ -323,11 +303,13 @@ var DEFAULT_UI_TEXT = {
323
303
  nextStepStart: "Start the project:",
324
304
  nextStepStartDebug: "Start the debug mode:",
325
305
  nextStepStartRelease: "Run the production-like check:",
306
+ nextStepStartProduction: "Run the full production check:",
326
307
  promptInstallDependencies: "Install dependencies now?",
327
308
  promptStartMode: "Which start mode should be used?",
328
309
  promptStartModeSkip: "Do not start now",
329
310
  promptStartModeDebug: "Development mode (debug host + sandbox watcher)",
330
311
  promptStartModeRelease: "Production-like check (build + host using built assets)",
312
+ promptStartModeProduction: "Full production (both the plugin and the host are built)",
331
313
  promptStandStartModeDebug: "Development (dev server, /api proxy, live reload)",
332
314
  promptStandStartModeRelease: "Production-like (build + static server)",
333
315
  promptStandStartModeRepro: "Repro: rebundle + cross-origin chunks",
@@ -420,9 +402,9 @@ var DEFAULT_EXTENSIONS_API_PACKAGE = "useblocks-extensions-api";
420
402
  var DEFAULT_EXTENSIONS_REACT_PACKAGE = "useblocks-extensions-react";
421
403
  var DEFAULT_EXTENSIONS_SANDBOX_PACKAGE = "useblocks-extensions-sandbox";
422
404
  var DEFAULT_CLI_PACKAGE = "useblocks-cli";
423
- var DEFAULT_VERSION = "1.1.88";
424
- var DEFAULT_UI_KIT_VERSION = "1.1.88";
425
- var DEFAULT_CLI_VERSION = "1.1.88";
405
+ var DEFAULT_VERSION = "1.1.102";
406
+ var DEFAULT_UI_KIT_VERSION = "1.1.102";
407
+ var DEFAULT_CLI_VERSION = "1.1.102";
426
408
  var DEFAULT_OPENAPI_BASE_URL = "https://app.useblocks.io/api";
427
409
  var DEFAULT_CDN_URL = "https://cdn.useblocks.io";
428
410
  var DEFAULT_BACKEND_DOMAIN = "api.useblocks.io";
@@ -1462,13 +1444,13 @@ var ROOT_PKG = {
1462
1444
  engines: { "node": ">=24.0.0" },
1463
1445
  packageManager: "pnpm@11.4.0",
1464
1446
  dependencies: {
1447
+ "@ant-design/icons": "^6.1.0",
1448
+ "@babel/runtime": "^7.26.0",
1465
1449
  "@easylogic/colorpicker": "1.10.7",
1466
- "@emailmaker/filemanager": "workspace:*",
1467
- "@emailmaker/ui-kit": "workspace:*",
1468
1450
  "@emailmaker/extensions-api": "workspace:*",
1469
1451
  "@emailmaker/extensions-react": "workspace:*",
1470
- "@ant-design/icons": "^6.1.0",
1471
- "@babel/runtime": "^7.26.0",
1452
+ "@emailmaker/filemanager": "workspace:*",
1453
+ "@emailmaker/ui-kit": "workspace:*",
1472
1454
  "@internal/core-loader": "workspace:*",
1473
1455
  "app-core": "workspace:*",
1474
1456
  "browserExtensionSanitizer": "workspace:*",
@@ -1499,7 +1481,7 @@ var ROOT_PKG = {
1499
1481
  "@react-hook/window-size": "^3.0.7",
1500
1482
  "@react-oauth/google": "^0.12.1",
1501
1483
  "@reduxjs/toolkit": "^2.12.0",
1502
- "@sentry/browser": "^9.18.0",
1484
+ "@sentry/browser": "^10.56.0",
1503
1485
  "@sentry/cli": "^2.58.2",
1504
1486
  "@sentry/react": "^10.18.0",
1505
1487
  "@sentry/tracing": "^7.120.3",
@@ -1509,7 +1491,7 @@ var ROOT_PKG = {
1509
1491
  "@types/js-cookie": "^3.0.6",
1510
1492
  "@wordpress/i18n": "^4.58.0",
1511
1493
  "@wordpress/react-i18n": "^3.15.0",
1512
- "antd": "^6.3.5",
1494
+ "antd": "6.4.3",
1513
1495
  "autoprefixer": "10.4.5",
1514
1496
  "axios": "^1.7.9",
1515
1497
  "browser-image-compression": "^2.0.2",
@@ -1520,8 +1502,9 @@ var ROOT_PKG = {
1520
1502
  "darkreader": "4.9.125",
1521
1503
  "date-fns": "^2.27.0",
1522
1504
  "dayjs": "^1.11.8",
1523
- "deepmerge-ts": "^5.1.0",
1524
1505
  "deepmerge": "^4.3.1",
1506
+ "deepmerge-ts": "^5.1.0",
1507
+ "documentCore": "workspace:*",
1525
1508
  "effection": "^3.0.3",
1526
1509
  "emmet": "^2.3.6",
1527
1510
  "emmet-monaco-es": "file:local_modules/emmet-monaco-es",
@@ -1546,14 +1529,15 @@ var ROOT_PKG = {
1546
1529
  "mutation-summary": "^1.0.0",
1547
1530
  "path-browserify": "^1.0.1",
1548
1531
  "postal-mime": "^3.0.0",
1532
+ "source": "workspace:*",
1549
1533
  "process": "^0.11.10",
1550
1534
  "prop-types": "^15.8.1",
1535
+ "rc-input-number": "^9.5.0",
1551
1536
  "react": "19.2.7",
1552
1537
  "react-dom": "19.2.7",
1553
1538
  "react-filerobot-image-editor": "5.0.0-beta.159",
1554
1539
  "react-infinite-scroll-component": "^7.2.1",
1555
1540
  "react-konva": "19.2.5",
1556
- "rc-input-number": "^9.5.0",
1557
1541
  "react-masonry-css": "^1.0.16",
1558
1542
  "react-redux": "^7.2.3",
1559
1543
  "react-refresh": "^0.18.0",
@@ -1561,16 +1545,16 @@ var ROOT_PKG = {
1561
1545
  "react-split": "^2.0.13",
1562
1546
  "react-sticky-box": "^1.0.1",
1563
1547
  "react-transition-group": "^4.4.5",
1564
- "regenerator-runtime": "^0.14.1",
1565
1548
  "recharts": "^2.15.4",
1549
+ "regenerator-runtime": "^0.14.1",
1566
1550
  "sass": "^1.44.0",
1567
1551
  "save": "^2.9.0",
1568
1552
  "selderee": "^0.11.0",
1569
1553
  "sortablejs": "^1.15.2",
1570
1554
  "stream-browserify": "^3.0.0",
1571
1555
  "styled-components": "^6.1.13",
1556
+ "textChange": "workspace:*",
1572
1557
  "util": "^0.12.5",
1573
- "uuid": "^13.0.0",
1574
1558
  "vscode-html-languageservice": "^5.0.2",
1575
1559
  "webfontloader": "^1.6.28",
1576
1560
  "xss": "^1.0.14",
@@ -1583,6 +1567,7 @@ var ROOT_PKG = {
1583
1567
  "build:global": "tsx build-tools/pipeline.ts --envMode=global",
1584
1568
  "preview": "vite preview --config build-tools/config/presets/build.main.ts --mode production",
1585
1569
  "build:cli": "tsx build-tools/cli/scripts/build.ts",
1570
+ "cli:local": "node build/cli/bin/createPlugin.js --local-test --local-build-dir ./build",
1586
1571
  "emailmaker-cli": "node build/cli/bin/createPlugin.js --local-test --local-build-dir ./build",
1587
1572
  "verify:cli": "tsx build-tools/cli/scripts/e2e/verify-global-cli.ts --cli-dir=build/cli",
1588
1573
  "verify:cli:source": "tsx build-tools/cli/scripts/e2e/verify-global-cli.ts --source-tools",
@@ -1603,6 +1588,8 @@ var ROOT_PKG = {
1603
1588
  "publish:npm": "node build-tools/scripts/publish/publish-from-manifest.mjs",
1604
1589
  "publish:plan": "tsx build-tools/scripts/publish/publish-plan.ts",
1605
1590
  "build:translations": "tsx build-tools/translations/extract.ts",
1591
+ "delivery:groups": "tsx build-tools/scripts/build/update-delivery-groups.ts",
1592
+ "measure:delivery": "vite build --config build-tools/config/presets/build.ui-kit-host.ts --mode production && vite build --config build-tools/config/presets/build.core.ts --mode production && vite build --config build-tools/config/presets/delivery.split.ts --mode production",
1606
1593
  "build:bundler-plugins": "tsx build-tools/scripts/build/bundler-plugins.ts --build-dir build --mode dev",
1607
1594
  "send:translations": "tsx build-tools/scripts/i18n/send-translations.ts",
1608
1595
  "start:proxy": "env-cmd -f .env.dev tsx build-tools/proxy/client/server.ts --mountPath=/proxy",
@@ -1637,6 +1624,7 @@ var ROOT_PKG = {
1637
1624
  "lint:types": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsc --noEmit && tsc -p build-tools/tsconfig.tooling.json",
1638
1625
  "test:typecheck": "npm run lint:types && tsc -p iframe/tsconfig.json --noEmit && tsc -p packages/po/tsconfig.json --noEmit",
1639
1626
  "type-check:tooling": "tsc -p build-tools/tsconfig.tooling.json",
1627
+ "diag:measure": "tsx build-tools/scripts/diagnostics/measure.ts",
1640
1628
  "lint:new": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsx build-tools/scripts/lint/diffAwareLint.ts",
1641
1629
  "test:plugin-matrix": "tsx build-tools/scripts/dev/run-plugin-matrix.ts",
1642
1630
  "lint:ci": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsx build-tools/scripts/lint/diffAwareLint.ts",
@@ -1646,7 +1634,8 @@ var ROOT_PKG = {
1646
1634
  "sentry:sourcemaps-dev": "sentry-cli sourcemaps inject --org sentry --project emailmaker-dev ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project emailmaker-dev ./build",
1647
1635
  "sentry:sourcemaps-prod": "sentry-cli sourcemaps inject --org sentry --project emailmaker-prod ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project emailmaker-prod ./build",
1648
1636
  "sentry:sourcemaps-bl-dev": "sentry-cli sourcemaps inject --org sentry --project blocks-dev ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project blocks-dev ./build",
1649
- "sentry:sourcemaps-bl-prod": "sentry-cli sourcemaps inject --org sentry --project blocks-prod ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project blocks-prod ./build"
1637
+ "sentry:sourcemaps-bl-prod": "sentry-cli sourcemaps inject --org sentry --project blocks-prod ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project blocks-prod ./build",
1638
+ "saas-check": "tsx build-tools/scripts/saas-check/run.ts"
1650
1639
  },
1651
1640
  browserslist: {
1652
1641
  "production": [
@@ -1685,9 +1674,11 @@ var ROOT_PKG = {
1685
1674
  "@vitejs/plugin-react": "^6.0.2",
1686
1675
  "allure-jest": "^3.5.0",
1687
1676
  "babel-preset-react-app": "^10.1.0",
1677
+ "cjs-module-lexer": "2.2.0",
1688
1678
  "cross-env": "^7.0.3",
1689
1679
  "dotenv": "^17.3.1",
1690
1680
  "ejs": "^5.0.1",
1681
+ "enhanced-resolve": "^5.23.0",
1691
1682
  "env-cmd": "^10.1.0",
1692
1683
  "eslint-plugin-sonarjs": "^3.0.1",
1693
1684
  "express": "^5.2.1",
@@ -1700,6 +1691,7 @@ var ROOT_PKG = {
1700
1691
  "jest-junit": "^16.0.0",
1701
1692
  "jsdom": "^16.7.0",
1702
1693
  "less": "^4.1.3",
1694
+ "line-awesome": "^1.3.0",
1703
1695
  "napi-postinstall": "^0.3.4",
1704
1696
  "oxlint": "1.77.0",
1705
1697
  "oxlint-tsgolint": "7.0.2001",
@@ -1709,7 +1701,7 @@ var ROOT_PKG = {
1709
1701
  "postcss-preset-env": "^9.5.0",
1710
1702
  "prettier": "^3.4.2",
1711
1703
  "react-error-overlay": "6.0.9",
1712
- "rolldown": "~1.1.5",
1704
+ "rolldown": "~1.2.6",
1713
1705
  "rolldown-plugin-dts": "^0.28.0",
1714
1706
  "rollup": "^4.61.1",
1715
1707
  "sass-cast": "^0.5.6",
@@ -1728,7 +1720,7 @@ var ROOT_PKG = {
1728
1720
  "tsdown": "^0.21.0-beta.2",
1729
1721
  "tsx": "^4.21.0",
1730
1722
  "typescript": "^7.0.2",
1731
- "vite": "^8.1.5",
1723
+ "vite": "^8.3.0",
1732
1724
  "vite-plugin-commonjs": "^0.10.4",
1733
1725
  "vite-plugin-css-injected-by-js": "^4.0.1",
1734
1726
  "vite-plugin-monaco-editor": "^1.1.0",
@@ -1739,7 +1731,7 @@ var ROOT_PKG = {
1739
1731
  "yargs": "^17.5.1"
1740
1732
  },
1741
1733
  overrides: {
1742
- "rolldown": "~1.1.5",
1734
+ "rolldown": "~1.2.6",
1743
1735
  "monaco-html-linter": { "monaco-editor": "0.34.0" },
1744
1736
  "@vitest/expect": "4.1.4",
1745
1737
  "@vitest/runner": "4.1.4",
@@ -1811,6 +1803,7 @@ var LEGACY_REACT_DEPENDENCIES = {
1811
1803
  react: extractPinned(getRootDependencyVersion("react")),
1812
1804
  "react-dom": extractPinned(getRootDependencyVersion("react-dom")),
1813
1805
  antd: extractPinned(getRootDependencyVersion("antd")),
1806
+ "@ant-design/icons": extractPinned(getRootDependencyVersion("@ant-design/icons")),
1814
1807
  "@types/react": extractPinned(getRootDependencyVersion("@types/react")),
1815
1808
  "@types/react-dom": extractPinned(getRootDependencyVersion("@types/react-dom"))
1816
1809
  };
@@ -1953,6 +1946,21 @@ function ensurePnpmStandaloneWorkspaceFile(targetDir) {
1953
1946
  if (repaired !== existing) node_fs.default.writeFileSync(wsPath, repaired, "utf8");
1954
1947
  }
1955
1948
  //#endregion
1949
+ //#region ../config/repo/paths.ts
1950
+ /**
1951
+ * Константы путей проекта
1952
+ *
1953
+ * Этот файл НЕ должен импортировать Vite плагины или другие ESM-only зависимости,
1954
+ * чтобы его можно было использовать в скриптах запускаемых через tsx.
1955
+ */
1956
+ /** Корневая директория проекта */
1957
+ var ROOT_DIR = (0, path.resolve)(__dirname, "../../..");
1958
+ (0, path.resolve)(ROOT_DIR, "./src");
1959
+ (0, path.resolve)(ROOT_DIR, "node_modules/.vite-cache");
1960
+ (0, path.resolve)(ROOT_DIR, "./packages");
1961
+ (0, path.resolve)(ROOT_DIR, "./local_modules");
1962
+ (0, path.resolve)(ROOT_DIR, "./build");
1963
+ //#endregion
1956
1964
  //#region ../config/runtime/runtime-contract.ts
1957
1965
  function e(input) {
1958
1966
  const { delivery: deliveryOverride, ...rest } = input;
@@ -1995,14 +2003,21 @@ e({
1995
2003
  name: "antd",
1996
2004
  exportName: "Antd",
1997
2005
  hasDefault: false,
1998
- isCjs: true,
2006
+ isCjs: false,
2007
+ isLocalWorkspace: false
2008
+ }), e({
2009
+ name: "@ant-design/icons/es/components/AntdIcon",
2010
+ exportName: "AntDesignIconBase",
2011
+ hasDefault: true,
2012
+ isCjs: false,
1999
2013
  isLocalWorkspace: false
2000
2014
  }), e({
2001
2015
  name: "@ant-design/icons",
2002
2016
  exportName: "AntDesignIcons",
2003
2017
  hasDefault: true,
2004
2018
  isCjs: false,
2005
- isLocalWorkspace: false
2019
+ isLocalWorkspace: false,
2020
+ delivery: "compat-lazy"
2006
2021
  }), e({
2007
2022
  name: "@ant-design/cssinjs",
2008
2023
  exportName: "AntDesignCssinjs",
@@ -2022,12 +2037,6 @@ e({
2022
2037
  hasDefault: true,
2023
2038
  isCjs: true,
2024
2039
  isLocalWorkspace: false
2025
- }), e({
2026
- name: "uuid",
2027
- exportName: "Uuid",
2028
- hasDefault: false,
2029
- isCjs: false,
2030
- isLocalWorkspace: false
2031
2040
  }), e({
2032
2041
  name: "di",
2033
2042
  exportName: "Di",
@@ -2660,7 +2669,7 @@ var MESSAGES = {
2660
2669
  "readmeStand.modeAdvancedUmd": "advanced: UMD from page script",
2661
2670
  "readmeStand.modeAdvancedMemoryUsage": "advanced: memory usage test",
2662
2671
  "readmeStand.modeAdvancedModuleFederation": "advanced: Module Federation host + remote",
2663
- "readmeStand.moduleFederationHint": "## Module Federation stand (local CLI only)\n\nCross-origin: host `http://localhost:3000`, remote/CDN `http://localhost:3001/remoteEntry.js`. Editor `publicPath` points to port 3001.\n\nOpen `http://localhost:3000/`.\n\n`npm start`: remote `vite build --watch` + preview on :3001, host Vite dev on :3000. First remote build takes a few seconds; host starts after `remoteEntry.js` is ready.",
2672
+ "readmeStand.moduleFederationHint": "## Module Federation stand (local CLI only)\n\nCross-origin: host `http://localhost:3000`, remote/CDN `http://localhost:3001/remoteEntry.js`. Editor `publicPath` points to port 3001.\n\nOpen `http://localhost:3000/`.\n\n`npm start`: remote `vite build --watch` + preview on :3001, host Vite dev on :3000. First remote build takes a few seconds; host starts after `remoteEntry.js` is ready.\n\nOther ports: `PLUGIN_DEV_PORT=4000 npm start` puts the host on 4000 and the remote on 4001 (`npm start -- --port` does not reach `concurrently` children).",
2664
2673
  "readmeStand.whatIncluded": "## What is included",
2665
2674
  "readmeStand.simpleProject": "- simple project with {title} connected",
2666
2675
  "readmeStand.storageProvider": "- StorageProvider with pathMode - files are stored in `./storage`",
@@ -2783,7 +2792,7 @@ function buildViteStandScripts(options) {
2783
2792
  const remotePreviewOnly = `vite preview ${remoteConfigFlag}`;
2784
2793
  const hostPreviewOnly = `vite preview ${configFlag}`;
2785
2794
  return {
2786
- start: `${concurrently} -n remote-build,remote,host "${`vite build --watch ${remoteConfigFlag}`}" "${`wait-on dist/remote/remoteEntry.js -t 120000 && vite preview ${remoteConfigFlag}`}" "wait-on http://localhost:3001/remoteEntry.js -t 120000 && vite ${configFlag}"`,
2795
+ start: `${concurrently} -n remote-build,remote,host "${`vite build --watch ${remoteConfigFlag}`}" "${`wait-on dist/remote/remoteEntry.js -t 120000 && vite preview ${remoteConfigFlag}`}" "vite ${configFlag}"`,
2787
2796
  build: `vite build ${remoteConfigFlag} && vite build ${configFlag}`,
2788
2797
  preview: `${remoteDistGuard} && ${distGuard} && ${concurrently} -n remote,host "${remotePreviewOnly}" "${hostPreviewOnly}"`,
2789
2798
  "serve:dist": `${remoteDistGuard} && ${distGuard} && ${concurrently} -n remote,host "${remotePreviewOnly}" "${hostPreviewOnly}"`
@@ -3415,6 +3424,7 @@ function buildStandEtaContext(templateOptions) {
3415
3424
  standShowSubpathBanner: standMode === "advanced" && advancedProfile === "subpath",
3416
3425
  standViteOutputFolder: computeStandViteOutputFolder(templateOptions),
3417
3426
  includeSmokeHelpers: Boolean(templateOptions.localTest),
3427
+ standCdnUrl: packageConfig.cdnUrl || "",
3418
3428
  standAngular: isAngularStand,
3419
3429
  ...standMode === "angular-esbuild" || standMode === "angular" ? {
3420
3430
  standAngularProductAssetsOutput: `${STAND_ANGULAR_ESBUILD_PRODUCT_PATH_PREFIX}/${appNameSlug}/`,
@@ -3537,6 +3547,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3537
3547
  "../../project-templates/plugin/shared-base/scripts/dev-runner.ts": "import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ChildProcess } from 'node:child_process';\nimport { runScript, runScriptSync } from './runScript.ts';\nimport { resolvePluginDevHostArgs } from './resolvePluginDevPort.ts';\n\nfunction waitForFile(filePath: string, timeoutMs = 30_000, pollMs = 250): Promise<void> {\n const startedAt = Date.now();\n\n return new Promise((resolve, reject) => {\n const check = (): void => {\n if (fs.existsSync(filePath)) {\n resolve();\n return;\n }\n\n if (Date.now() - startedAt >= timeoutMs) {\n reject(new Error(`Timed out waiting for file: ${filePath}`));\n return;\n }\n\n setTimeout(check, pollMs);\n };\n\n check();\n });\n}\n\nfunction hasLegacyPluginDevScripts(): boolean {\n try {\n const packageJsonPath = path.resolve(process.cwd(), 'package.json');\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as {\n scripts?: Record<string, string>;\n };\n return typeof packageJson.scripts?.['dev:plugin:once'] === 'string';\n } catch {\n return false;\n }\n}\n\nasync function main(): Promise<void> {\n const forwardedArgs = process.argv.slice(2);\n const sandboxFilePath = path.resolve(process.cwd(), 'public', 'sandbox.js');\n const pluginDistPath = path.resolve(process.cwd(), 'dist', 'index.js');\n let sandbox: ChildProcess | undefined;\n let plugin: ChildProcess | undefined;\n let app: ChildProcess | undefined;\n\n const shutdown = (): void => {\n sandbox?.kill('SIGINT');\n plugin?.kill('SIGINT');\n app?.kill('SIGINT');\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n try {\n runScriptSync('dev:sandbox:once');\n await waitForFile(sandboxFilePath, 5_000);\n\n if (hasLegacyPluginDevScripts()) {\n runScriptSync('dev:plugin:once');\n await waitForFile(pluginDistPath, 60_000);\n plugin = runScript('dev:plugin');\n }\n\n sandbox = runScript('dev:sandbox');\n const { port, hostArgs } = await resolvePluginDevHostArgs(forwardedArgs);\n console.log(`[dev] http://localhost:${port}/`);\n app = runScript('dev:host', {\n args: hostArgs,\n env: { PLUGIN_DEV_PORT: String(port) },\n });\n } catch (error) {\n shutdown();\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exit(1);\n }\n}\n\nvoid main();\n",
3538
3548
  "../../project-templates/plugin/shared-base/scripts/findFreePort.ts": "import net from 'node:net';\n\n/**\n * Hosts a dev server may bind to. `::` comes first: on Windows a second bind to an IPv4\n * address of a busy port still succeeds, so only the IPv6 socket reports the conflict.\n */\nconst DEV_BIND_HOSTS: readonly string[] = ['::', '0.0.0.0', '127.0.0.1'];\n\n/** The port cannot be bound on this host: taken by another process or denied by the OS. */\nconst PORT_UNAVAILABLE_CODES = new Set(['EADDRINUSE', 'EACCES']);\n\n/** The address family is unavailable (no IPv6 and such) — says nothing about the port, so skip the host. */\nconst HOST_UNSUPPORTED_CODES = new Set(['EAFNOSUPPORT', 'EADDRNOTAVAIL', 'EINVAL', 'ENOTFOUND']);\n\nexport const DEFAULT_PLUGIN_DEV_PORT = 3000;\n\ntype PortProbeResult = 'free' | 'taken' | 'host-unsupported';\n\n/**\n * Tries to bind the port on one host. An unknown error code counts as unusable:\n * moving to the next port is cheaper than crashing the dev server on EADDRINUSE.\n */\nfunction probePort(port: number, host: string): Promise<PortProbeResult> {\n return new Promise((resolve) => {\n const server = net.createServer();\n\n server.once('error', (err: NodeJS.ErrnoException) => {\n const code = err.code ?? '';\n if (HOST_UNSUPPORTED_CODES.has(code)) {\n resolve('host-unsupported');\n return;\n }\n if (!PORT_UNAVAILABLE_CODES.has(code)) {\n console.log(`[findFreePort] ${host}:${port} — unexpected bind error (${code || err.message})`);\n }\n resolve('taken');\n });\n\n server.once('listening', () => {\n server.close(() => resolve('free'));\n });\n\n server.listen({ port, host, exclusive: true });\n });\n}\n\nexport async function isDevListenPortTaken(port: number): Promise<boolean> {\n for (const host of DEV_BIND_HOSTS) {\n if ((await probePort(port, host)) === 'taken') {\n return true;\n }\n }\n return false;\n}\n\nexport async function findFreePort(\n startPort: number,\n maxAttempts = 50,\n): Promise<number | null> {\n for (let i = 0; i < maxAttempts; i++) {\n const port = startPort + i;\n if (!(await isDevListenPortTaken(port))) {\n return port;\n }\n console.log(`[findFreePort] Port ${port} is in use, trying ${port + 1}...`);\n }\n return null;\n}\n",
3539
3549
  "../../project-templates/plugin/shared-base/scripts/hostDevServerHeaders.ts.eta": "<%~ include('stand-host-dev-server-webpack', it) %>\n",
3550
+ "../../project-templates/plugin/shared-base/scripts/production-runner.ts": "import fs from 'node:fs';\nimport path from 'node:path';\nimport { buildProject } from './build-runner.ts';\nimport { runScript, runScriptSync } from './runScript.ts';\nimport { resolvePluginDevHostArgs } from './resolvePluginDevPort.ts';\n\n/**\n * Third mode: both the plugin and the host are built, nothing is served from sources.\n *\n * `start:release` builds the plugin but still runs a dev server for the host, and a dev server\n * hands every dependency to the bundler's optimizer — it bundles each one whole and deliberately\n * skips tree shaking. Weights and request counts seen there describe the optimizer, not the\n * delivered result. This mode is the one to judge them by.\n */\nfunction assertArtifacts(files: readonly string[], label: string): void {\n for (const filePath of files) {\n if (!fs.existsSync(filePath)) {\n throw new Error(`[production] Expected ${label} artifact is missing: ${filePath}`);\n }\n }\n}\n\n/**\n * `--bundler-runtime-strict` — same contract as in `release-runner.ts`: the flag is set only by a\n * local CLI build and must not reach vite/webpack.\n */\nfunction consumeStrictFlag(args: string[]): string[] {\n const idx = args.indexOf('--bundler-runtime-strict');\n if (idx < 0) {\n return args;\n }\n process.env.BUNDLER_RUNTIME_STRICT ??= '1';\n return [...args.slice(0, idx), ...args.slice(idx + 1)];\n}\n\n/**\n * The built plugin next to the built host.\n *\n * `release.html` loads the plugin from `/dist/index.js`. A dev server maps that path to the\n * project folder; a preview server serves only what the host build emitted, so the plugin has to\n * be copied in or the page 404s on its own entry.\n */\nfunction publishPluginDist(): void {\n const from = path.resolve(process.cwd(), 'dist');\n const to = path.resolve(process.cwd(), 'dist-host', 'dist');\n fs.rmSync(to, { recursive: true, force: true });\n fs.cpSync(from, to, { recursive: true });\n}\n\nasync function main(): Promise<void> {\n const forwardedArgs = consumeStrictFlag(process.argv.slice(2));\n\n buildProject();\n assertArtifacts(\n [path.resolve(process.cwd(), 'dist', 'index.js'), path.resolve(process.cwd(), 'dist', 'sandbox.js')],\n 'plugin',\n );\n\n runScriptSync('build:release-host');\n publishPluginDist();\n\n try {\n const { port, hostArgs } = await resolvePluginDevHostArgs(forwardedArgs);\n console.log(`[production] http://localhost:${port}/release.html`);\n const app = runScript('preview:release-host', {\n args: hostArgs,\n env: { PLUGIN_DEV_PORT: String(port) },\n });\n\n const shutdown = (): void => {\n app.kill('SIGINT');\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exit(1);\n }\n}\n\nvoid main();\n",
3540
3551
  "../../project-templates/plugin/shared-base/scripts/release-runner.ts": "import fs from 'node:fs';\nimport path from 'node:path';\nimport { buildProject } from './build-runner.ts';\nimport { runScript } from './runScript.ts';\nimport { resolvePluginDevHostArgs } from './resolvePluginDevPort.ts';\n\nfunction assertReleaseArtifacts(): void {\n const requiredFiles = [\n path.resolve(process.cwd(), 'dist', 'index.js'),\n path.resolve(process.cwd(), 'dist', 'sandbox.js'),\n ];\n\n for (const filePath of requiredFiles) {\n if (!fs.existsSync(filePath)) {\n throw new Error(`[release] Expected build artifact is missing: ${filePath}`);\n }\n }\n}\n\n/**\n * `--bundler-runtime-strict` — CLI выставляет этот флаг только при локальной\n * сборке плагина из нашего репо (`--local-test`). Переключает defensive\n * детекторы host plugin + PluginDev в throw-режим: дублирование React'а или\n * bare-импорт runtime-пакета валит сборку с диагностикой вместо тихого warn'а.\n *\n * Production-CLI (опубликованный npm) этот аргумент не подставляет, поэтому\n * integrator'ские sandbox'ы не падают из-за heuristic-сигнала. См.\n * `docs/build-architecture/RUNTIME_DELIVERY_CR.md` §12.\n */\nfunction consumeStrictFlag(args: string[]): string[] {\n const idx = args.indexOf('--bundler-runtime-strict');\n if (idx < 0) {\n return args;\n }\n process.env.BUNDLER_RUNTIME_STRICT ??= '1';\n return [...args.slice(0, idx), ...args.slice(idx + 1)];\n}\n\nasync function main(): Promise<void> {\n const forwardedArgs = consumeStrictFlag(process.argv.slice(2));\n buildProject();\n assertReleaseArtifacts();\n if (process.env.BUNDLER_RUNTIME_STRICT === '1') {\n console.log('[release] BUNDLER_RUNTIME_STRICT=1 (local CLI build) — defensive checks fail-fast');\n }\n\n try {\n const { port, hostArgs } = await resolvePluginDevHostArgs(forwardedArgs);\n console.log(`[release] http://localhost:${port}/release.html`);\n const app = runScript('dev:release-host', {\n args: hostArgs,\n env: { PLUGIN_DEV_PORT: String(port) },\n });\n\n const shutdown = (): void => {\n app.kill('SIGINT');\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exit(1);\n }\n}\n\nvoid main();\n",
3541
3552
  "../../project-templates/plugin/shared-base/scripts/resolvePluginDevPort.test.ts": "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { parsePortFromArgs } from './resolvePluginDevPort.ts';\n\ntest('parsePortFromArgs extracts --port and keeps other args', () => {\n assert.deepEqual(parsePortFromArgs(['--port', '3005', '--open']), {\n explicitPort: 3005,\n restArgs: ['--open'],\n });\n});\n\ntest('parsePortFromArgs supports --port= syntax', () => {\n assert.deepEqual(parsePortFromArgs(['--port=3010']), {\n explicitPort: 3010,\n restArgs: [],\n });\n});\n\ntest('parsePortFromArgs rejects invalid port', () => {\n assert.throws(() => parsePortFromArgs(['--port', '0']), /Invalid --port value/);\n});\n",
3542
3553
  "../../project-templates/plugin/shared-base/scripts/resolvePluginDevPort.ts": "import { DEFAULT_PLUGIN_DEV_PORT, findFreePort, isDevListenPortTaken } from './findFreePort.ts';\n\nexport function parsePortFromArgs(args: string[]): {\n explicitPort?: number;\n restArgs: string[];\n} {\n const restArgs: string[] = [];\n let explicitPort: number | undefined;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n\n if (arg === '--') {\n continue;\n }\n\n if (arg === '--port') {\n const value = args[i + 1];\n if (value === undefined) {\n throw new Error('Missing value for --port');\n }\n explicitPort = Number(value);\n i += 1;\n continue;\n }\n\n if (arg.startsWith('--port=')) {\n explicitPort = Number(arg.slice('--port='.length));\n continue;\n }\n\n restArgs.push(arg);\n }\n\n if (explicitPort !== undefined && (!Number.isInteger(explicitPort) || explicitPort <= 0)) {\n throw new Error(`Invalid --port value: ${explicitPort}`);\n }\n\n return { explicitPort, restArgs };\n}\n\nexport async function resolvePluginDevHostArgs(\n forwardedArgs: string[],\n options: { defaultPort?: number } = {},\n): Promise<{ port: number; hostArgs: string[] }> {\n const defaultPort = options.defaultPort ?? DEFAULT_PLUGIN_DEV_PORT;\n const { explicitPort, restArgs } = parsePortFromArgs(forwardedArgs);\n const envPortRaw = process.env.PLUGIN_DEV_PORT;\n const envPort = envPortRaw ? Number(envPortRaw) : undefined;\n\n let port: number;\n if (explicitPort !== undefined) {\n if (await isDevListenPortTaken(explicitPort)) {\n throw new Error(\n `Port ${explicitPort} is already in use. Omit --port to auto-select a free port, or choose another value.`,\n );\n }\n port = explicitPort;\n } else if (envPort !== undefined && Number.isInteger(envPort) && envPort > 0) {\n if (await isDevListenPortTaken(envPort)) {\n throw new Error(\n `Port ${envPort} is already in use. Omit --port to auto-select a free port, or choose another value.`,\n );\n }\n port = envPort;\n } else {\n const freePort = await findFreePort(defaultPort);\n if (freePort === null) {\n throw new Error(`Could not find free port starting from ${defaultPort}`);\n }\n port = freePort;\n }\n\n return {\n port,\n hostArgs: [...restArgs, '--port', String(port)],\n };\n}\n",
@@ -3559,7 +3570,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3559
3570
  "../../project-templates/plugin/templating/src/app/__PLUGIN_CLASS_NAME__.tsx.eta": "import { pluginRegistry, createComponentIdentifier } from '<%= it.packageConfig.extensionsApiPackageName %>';\nimport { ComponentRegistry } from '<%= it.packageConfig.extensionsReactPackageName %>';\nimport type { IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Options } from '../public-types';\nimport {\n <%= it.pluginClassName %>TemplateDataPanel,\n type <%= it.pluginClassName %>TemplateDataPanelProps,\n} from './ui/<%= it.pluginClassName %>Panel';\nimport {\n OPEN_TEMPLATE_DATA_PANEL_MESSAGE,\n PREVIEW_STATES,\n TEMPLATE_DATA_MESSAGE,\n TEMPLATE_DATA_META_KEY,\n TWIG_RUNTIME_URL,\n clonePreviewData,\n type PreviewTemplateData,\n} from '../interfaces';\n\nconst <%= it.pluginClassName %>TemplateDataPanelId =\n createComponentIdentifier<<%= it.pluginClassName %>TemplateDataPanelProps>('<%= it.pluginClassName %>TemplateDataPanel');\n\nComponentRegistry.add(<%= it.pluginClassName %>TemplateDataPanelId, <%= it.pluginClassName %>TemplateDataPanel);\n\nfunction normalizePublicPath(value?: string): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const trimmed = value.replace(/\\/+$/, '');\n return `${trimmed}/`;\n}\n\nconst AUTO_PUBLIC_PATH = (() => {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const currentScript = document.currentScript as HTMLScriptElement | null;\n if (!currentScript?.src) {\n return undefined;\n }\n\n return normalizePublicPath(currentScript.src.replace(/[^/]*$/, ''));\n})();\n\nfunction getDefaultPreviewData(): PreviewTemplateData {\n return clonePreviewData(PREVIEW_STATES[0]?.data ?? {});\n}\n\nexport class <%= it.pluginClassName %> implements IPlugin {\n private _previewData: PreviewTemplateData = getDefaultPreviewData();\n private _matcherReadyPromise: Promise<void> = Promise.resolve();\n private readonly _disposables: Array<{ dispose(): void }> = [];\n private _settingsPanel?: { showSettingsPanel?: (options: unknown) => void };\n\n constructor(\n private readonly _editor: Instance,\n private readonly _options: <%= it.pluginClassName %>Options = {},\n ) {}\n\n init() {\n const sandboxApi = this._editor.use('SandboxScriptApi');\n const settingsPanel = this._editor.use('SettingsPanelApi');\n const messageService = this._editor.use('MessageService');\n this._settingsPanel = settingsPanel;\n\n const publicPath = normalizePublicPath(this._options.publicPath) || AUTO_PUBLIC_PATH;\n const twigRuntimeHandle = sandboxApi.registerSandboxScript(TWIG_RUNTIME_URL);\n\n if (publicPath) {\n this._matcherReadyPromise = twigRuntimeHandle.ready\n .then(() => sandboxApi.registerSandboxScript(publicPath + 'sandbox.js').ready)\n .then(() => undefined);\n } else {\n this._matcherReadyPromise = twigRuntimeHandle.ready.then(() => undefined);\n }\n\n this._trackDisposable(messageService.addListener(OPEN_TEMPLATE_DATA_PANEL_MESSAGE, () => {\n this._openTemplateDataPanel(this._settingsPanel);\n }));\n\n this._trackDisposable(this._editor.handleEmailInit?.((email) => {\n void this._hydratePreviewData(email);\n }));\n }\n\n afterInit() {\n void this._hydratePreviewData();\n }\n\n dispose() {\n while (this._disposables.length > 0) {\n this._disposables.pop()?.dispose();\n }\n }\n\n private _trackDisposable(value: { dispose(): void } | (() => void) | void) {\n if (!value) {\n return;\n }\n\n if (typeof value === 'function') {\n this._disposables.push({ dispose: value });\n return;\n }\n\n if (typeof value.dispose === 'function') {\n this._disposables.push(value);\n }\n }\n\n private _readPreviewDataFromEmail(email: unknown): PreviewTemplateData {\n const emailMeta = (email as { meta?: Record<string, unknown> } | undefined)?.meta;\n const storedData = emailMeta?.[TEMPLATE_DATA_META_KEY];\n if (storedData && typeof storedData === 'object') {\n return clonePreviewData(storedData as PreviewTemplateData);\n }\n\n return getDefaultPreviewData();\n }\n\n private async _hydratePreviewData(email?: unknown) {\n const sourceEmail = email ?? await this._editor.getEmail?.();\n this._previewData = this._readPreviewDataFromEmail(sourceEmail);\n await this._sendPreviewData();\n }\n\n private _persistPreviewData(nextData: PreviewTemplateData) {\n this._previewData = clonePreviewData(nextData);\n this._editor.setEmailMeta?.({\n [TEMPLATE_DATA_META_KEY]: clonePreviewData(nextData),\n });\n }\n\n private _openTemplateDataPanel(settingsPanel: { showSettingsPanel?: (options: unknown) => void } | undefined) {\n if (!settingsPanel || typeof settingsPanel.showSettingsPanel !== 'function') {\n return;\n }\n\n settingsPanel.showSettingsPanel({\n caption: 'Template data JSON',\n deletable: false,\n content: {\n type: <%= it.pluginClassName %>TemplateDataPanelId,\n props: {\n initialValue: JSON.stringify(this._previewData ?? {}, null, 2),\n onValidJson: (nextData) => {\n this._persistPreviewData(nextData);\n void this._sendPreviewData();\n },\n },\n },\n });\n }\n\n private async _sendPreviewData() {\n const messageService = this._editor.use('MessageService');\n await this._matcherReadyPromise;\n messageService.send(TEMPLATE_DATA_MESSAGE, this._previewData);\n }\n}\n\npluginRegistry.add(<%~ it.pluginKeyLiteral %>, <%= it.pluginClassName %>);\n",
3560
3571
  "../../project-templates/plugin/templating/src/app/ui/__PLUGIN_PANEL_CLASS_NAME__.tsx.eta": "import React, { useEffect, useState } from 'react';\nimport type { PreviewTemplateData } from '../../interfaces';\n\nexport interface <%= it.pluginClassName %>TemplateDataPanelProps {\n initialValue: string;\n onValidJson?(value: PreviewTemplateData): void;\n}\n\nexport function <%= it.pluginClassName %>TemplateDataPanel({\n initialValue,\n onValidJson,\n}: <%= it.pluginClassName %>TemplateDataPanelProps) {\n const [value, setValue] = useState(initialValue);\n const [status, setStatus] = useState('Valid JSON applies automatically to the preview.');\n const [statusColor, setStatusColor] = useState('#64748b');\n\n useEffect(() => {\n setValue(initialValue);\n setStatus('Valid JSON applies automatically to the preview.');\n setStatusColor('#64748b');\n }, [initialValue]);\n\n useEffect(() => {\n const timer = window.setTimeout(() => {\n try {\n onValidJson?.(JSON.parse(value) as PreviewTemplateData);\n setStatus('Preview updated from sidebar JSON.');\n setStatusColor('#15803d');\n } catch (error) {\n setStatus(`JSON error: ${String(error instanceof Error ? error.message : error)}`);\n setStatusColor('#b91c1c');\n }\n }, 250);\n\n return () => {\n window.clearTimeout(timer);\n };\n }, [onValidJson, value]);\n\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', height: '100%', padding: '16px', boxSizing: 'border-box' }}>\n <div style={{ font: '13px/1.5 Arial,sans-serif', color: '#475569' }}>\n Edit template data as raw JSON. Valid JSON applies to the Twig preview automatically.\n </div>\n <textarea\n spellCheck={false}\n wrap=\"off\"\n value={value}\n onChange={(event) => {\n setStatus('Validating JSON...');\n setStatusColor('#64748b');\n setValue(event.target.value);\n }}\n style={{\n width: '100%',\n minHeight: '320px',\n flex: 1,\n padding: '12px',\n border: '1px solid #cbd5e1',\n borderRadius: '8px',\n background: '#0f172a',\n color: '#e2e8f0',\n font: '13px/1.5 Consolas, Monaco, monospace',\n resize: 'vertical',\n boxSizing: 'border-box',\n }}\n />\n <div style={{ font: '12px/1.5 Arial,sans-serif', color: statusColor, whiteSpace: 'pre-wrap' }}>\n {status}\n </div>\n </div>\n );\n}\n",
3561
3572
  "../../project-templates/plugin/templating/src/dev/editorConfig.ts.eta": "import type { Config } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Config } from '../public-types';\n\nconst mergeTagItems = [\n {\n label: 'System',\n value: 'system',\n children: [\n { label: 'Additional field \"Name\"', value: 'Name' },\n { label: 'Recipient name', value: 'ToName' },\n ],\n },\n];\n\nconst baseEditorConfig = {\n theme: 'light',\n locale: 'en_US',\n historyEnabled: true,\n commonStylesEnabled: true,\n previewIconEnabled: true,\n previewModeEnabled: true,\n livePreviewEnabled: true,\n sendTestEnabled: false,\n emailExportEnabled: false,\n sharePreviewEnabled: false,\n codeModeDirection: 'bottom',\n codeMode: 'true',\n mergeTagsShow: true,\n mergeTags: {\n syntax: ['{{' + '%value%' + '}}'],\n items: mergeTagItems,\n },\n} satisfies Partial<Config & <%= it.pluginClassName %>Config>;\n\nexport function createEditorConfig(): Partial<Config> {\n return baseEditorConfig;\n}\n\nexport const editorConfig = createEditorConfig();\n",
3562
- "../../project-templates/plugin/templating/src/dev/hostApp.tsx.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport { editorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\nimport { TWIG_EMAIL_CODE } from '../interfaces';\n\nfunction createDemoEmailId() {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n\n return `demo-email-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-templating',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: TWIG_EMAIL_CODE,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ margin: '12px 0', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
3573
+ "../../project-templates/plugin/templating/src/dev/hostApp.tsx.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport { editorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\nimport { TWIG_EMAIL_CODE } from '../interfaces';\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-templating',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: TWIG_EMAIL_CODE,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ margin: '12px 0', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n {/* The editor fills its container: without a definite height the side panels shrink to their content. */}\n <div id=\"editor-root\" style={{ height: '100vh' }} />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
3563
3574
  "../../project-templates/plugin/templating/src/interfaces/index.ts.eta": "export interface PreviewTemplateData {\n product?: {\n title?: string;\n sku?: string;\n cards?: Array<{\n title?: string;\n price?: string;\n badge?: string;\n }>;\n };\n}\n\nexport interface PreviewState {\n label: string;\n data: PreviewTemplateData;\n}\n\nexport const TWIG_RUNTIME_URL = 'https://cdn.jsdelivr.net/npm/twig@3.0.0/twig.min.js';\nexport const TEMPLATE_DATA_MESSAGE = 'templating:preview-data';\nexport const OPEN_TEMPLATE_DATA_PANEL_MESSAGE = 'templating:open-panel';\nexport const TEMPLATE_DATA_META_KEY = 'templatingPreviewData';\nexport const TEMPLATE_DATA_PREVIEW_ATTRIBUTE = 'data-em-templating-preview';\n\nexport const PREVIEW_STATES: PreviewState[] = [\n {\n label: 'Featured products',\n data: {\n product: {\n title: 'Featured products for Alice',\n sku: 'SKU-ALPHA-001',\n cards: [\n { title: 'Starter pack', price: '$29', badge: 'Popular' },\n { title: 'Growth pack', price: '$79', badge: 'Best value' },\n ],\n },\n },\n },\n {\n label: 'Empty catalog',\n data: {\n product: {\n title: 'Recommended products for Bob',\n sku: 'SKU-BETA-002',\n cards: [],\n },\n },\n },\n];\n\nexport const TWIG_EMAIL_CODE = `<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <title>Twig matcher demo</title>\n </head>\n <body style=\"margin:0;padding:24px;font-family:Arial,sans-serif;background:#f8fafc;\">\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n <tr>\n <td align=\"center\">\n <table role=\"presentation\" width=\"640\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"background:#ffffff;border-radius:16px;overflow:hidden;\">\n <tr>\n <td style=\"padding:32px;\">\n <h1 style=\"margin:0 0 16px;\">{{ product.title }}</h1>\n {# sandbox matcher should replace this comment with preview html #}\n {% if product.cards is not empty %}\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"margin:16px 0 0;\">\n <tr>\n {% for card in product.cards %}\n <td style=\"width:50%;padding:8px;vertical-align:top;\">\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"border:1px solid #dbe4f0;border-radius:12px;background:#f8fafc;\">\n <tr>\n <td style=\"padding:16px;\">\n <div style=\"font-size:12px;line-height:16px;color:#475569;text-transform:uppercase;\">{{ card.badge }}</div>\n <div style=\"margin-top:8px;font-size:18px;line-height:24px;color:#0f172a;font-weight:bold;\">{{ card.title }}</div>\n <div style=\"margin-top:8px;font-size:14px;line-height:20px;color:#2563eb;\">{{ card.price }}</div>\n </td>\n </tr>\n </table>\n </td>\n {% endfor %}\n </tr>\n </table>\n {% endif %}\n <p style=\"margin:16px 0 0;color:#475569;\">SKU: {{ product.sku }}</p>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </body>\n</html>`;\n\nexport function clonePreviewData<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n",
3564
3575
  "../../project-templates/plugin/templating/src/sandbox/index.ts.eta": "import { App } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport type { IPlugin } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport {\n OPEN_TEMPLATE_DATA_PANEL_MESSAGE,\n TEMPLATE_DATA_MESSAGE,\n TEMPLATE_DATA_PREVIEW_ATTRIBUTE,\n type PreviewTemplateData,\n} from '../interfaces';\n\ntype Disposable = { dispose(): void };\ntype MatcherRange = { start: number; end: number };\ntype MatcherMapping = {\n registerMatcherPair(config: {\n syntax?: string;\n escape: {\n match(text: string): MatcherRange[];\n mapFn(text: string): string | false;\n overrideBuiltins?: boolean;\n };\n unescape: {\n match(text: string): MatcherRange[];\n mapFn(text: string): string | false;\n overrideBuiltins?: boolean;\n };\n }): Disposable;\n rebuildFromBase?(): void;\n};\n\nclass <%= it.pluginClassName %>Sandbox implements IPlugin {\n private _previewData: PreviewTemplateData = {};\n private readonly _disposables: Disposable[] = [];\n private _messageService?: { send(message: string, data?: unknown): void; addListener(message: string, listener: (value: PreviewTemplateData) => void): Disposable };\n\n init() {\n const mapping = App.use('Mapping') as MatcherMapping | undefined;\n const messageService = App.use('MessageService');\n this._messageService = messageService;\n\n if (!mapping || typeof mapping.registerMatcherPair !== 'function') {\n console.warn('[<%= it.pluginClassName %>Sandbox] Mapping.registerMatcherPair is unavailable');\n return;\n }\n\n const registration = mapping.registerMatcherPair({\n syntax: 'twig-preview',\n escape: {\n match: (text) => this._findTwigRanges(text),\n mapFn: (text) => this._renderTwigSource(text),\n overrideBuiltins: true,\n },\n unescape: {\n match: (text) => this._findPreviewRanges(text),\n mapFn: (text) => this._restoreTwigSource(text),\n overrideBuiltins: true,\n },\n });\n\n this._disposables.push(\n registration,\n {\n dispose: this._bindPreviewClickHandler(),\n },\n messageService.addListener(TEMPLATE_DATA_MESSAGE, (nextPreviewData: PreviewTemplateData) => {\n this._previewData = nextPreviewData || {};\n mapping.rebuildFromBase?.();\n }),\n );\n }\n\n dispose() {\n while (this._disposables.length > 0) {\n this._disposables.pop()?.dispose();\n }\n }\n\n private _encodeSource(source: string): string {\n const bytes = new TextEncoder().encode(source);\n let binary = '';\n bytes.forEach((byte) => {\n binary += String.fromCharCode(byte);\n });\n return btoa(binary);\n }\n\n private _decodeSource(encodedSource: string): string {\n const binary = atob(encodedSource);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return new TextDecoder().decode(bytes);\n }\n\n private _collectMatches(text: string, patterns: RegExp[]): MatcherRange[] {\n const ranges: MatcherRange[] = [];\n patterns.forEach((pattern) => {\n pattern.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(text)) !== null) {\n ranges.push({\n start: match.index,\n end: match.index + match[0].length,\n });\n }\n });\n ranges.sort((first, second) => first.start - second.start || first.end - second.end);\n return ranges;\n }\n\n private _isIntersectRange(first: MatcherRange, second: MatcherRange): boolean {\n return first.start < second.end && second.start < first.end;\n }\n\n private _mergeRanges(ranges: MatcherRange[]): MatcherRange[] {\n const sorted = ranges.slice().sort((first, second) => first.start - second.start || first.end - second.end);\n const merged: MatcherRange[] = [];\n sorted.forEach((range) => {\n const previous = merged[merged.length - 1];\n if (previous && range.start < previous.end) {\n previous.end = Math.max(previous.end, range.end);\n return;\n }\n merged.push({ start: range.start, end: range.end });\n });\n return merged;\n }\n\n private _findBlockTwigRanges(text: string): MatcherRange[] {\n const ranges: MatcherRange[] = [];\n const stack: Array<{ type: 'if' | 'for'; start: number }> = [];\n const tokenPattern = /\\{%\\s*(if|for|endif|endfor)\\b[\\s\\S]*?%\\}/g;\n const validStartPositions = new Set<number>();\n let match: RegExpExecArray | null;\n\n while ((match = tokenPattern.exec(text)) !== null) {\n const keyword = match[1];\n const tokenEnd = match.index + match[0].length;\n if (keyword === 'if' || keyword === 'for') {\n validStartPositions.add(match.index);\n stack.push({ type: keyword, start: match.index });\n continue;\n }\n\n const startType = keyword === 'endif' ? 'if' : 'for';\n for (let index = stack.length - 1; index >= 0; index -= 1) {\n if (stack[index].type === startType) {\n const start = stack[index].start;\n stack.splice(index);\n ranges.push({ start, end: tokenEnd });\n break;\n }\n }\n }\n\n stack.forEach((entry) => {\n ranges.push({ start: entry.start, end: text.length });\n });\n\n const rawStartPattern = /\\{%\\s*(if|for)\\b/g;\n while ((match = rawStartPattern.exec(text)) !== null) {\n if (!validStartPositions.has(match.index) && !ranges.some((range) => match.index >= range.start && match.index < range.end)) {\n ranges.push({ start: match.index, end: text.length });\n }\n }\n\n return this._mergeRanges(ranges);\n }\n\n private _findInlineTwigRanges(text: string): MatcherRange[] {\n const ranges = this._collectMatches(text, [\n /\\{\\{[\\s\\S]*?\\}\\}/g,\n /\\{#[\\s\\S]*?#\\}/g,\n ]);\n const rawStartPattern = /\\{\\{|\\{#/g;\n let match: RegExpExecArray | null;\n\n while ((match = rawStartPattern.exec(text)) !== null) {\n if (!ranges.some((range) => match.index >= range.start && match.index < range.end)) {\n ranges.push({ start: match.index, end: text.length });\n }\n }\n\n return this._mergeRanges(ranges);\n }\n\n private _findTwigRanges(text: string): MatcherRange[] {\n const blockRanges = this._findBlockTwigRanges(text);\n const inlineRanges = this._findInlineTwigRanges(text)\n .filter((range) => !blockRanges.some((blockRange) => this._isIntersectRange(blockRange, range)));\n\n return [...blockRanges, ...inlineRanges].sort((first, second) => first.start - second.start || first.end - second.end);\n }\n\n private _findPreviewRanges(text: string): MatcherRange[] {\n return this._collectMatches(text, [\n /<!--twig-preview-start:[A-Za-z0-9+/=]+-->[\\s\\S]*?<!--twig-preview-end-->/g,\n ]);\n }\n\n private _createPreviewMarkers(source: string, renderedHtml: string): string {\n const encodedSource = this._encodeSource(source);\n return '<!--twig-preview-start:' + encodedSource + '-->' + this._wrapRenderedHtml(source, renderedHtml) + '<!--twig-preview-end-->';\n }\n\n private _createEmptyPreview(source: string): string {\n const encodedSource = this._encodeSource(source);\n return '<!--twig-preview-start:' + encodedSource + '--><!--twig-preview-end-->';\n }\n\n private _renderTwigSource(source: string): string {\n const twigRuntime = (window as Window & { Twig?: { twig?: (options: { data: string; allowInlineIncludes: boolean; autoescape: boolean }) => { render(data: PreviewTemplateData): string } } }).Twig;\n if (!twigRuntime || typeof twigRuntime.twig !== 'function') {\n console.warn('[<%= it.pluginClassName %>Sandbox] Twig runtime is unavailable');\n return this._createEmptyPreview(source);\n }\n\n try {\n const template = twigRuntime.twig({\n data: source,\n allowInlineIncludes: true,\n autoescape: false,\n });\n const rendered = template.render(this._previewData || {});\n return this._createPreviewMarkers(source, rendered);\n } catch (error) {\n console.warn('[<%= it.pluginClassName %>Sandbox] Twig render failed, showing empty preview', error);\n return this._createEmptyPreview(source);\n }\n }\n\n private _restoreTwigSource(previewMarkup: string): string {\n const match = previewMarkup.match(/<!--twig-preview-start:([A-Za-z0-9+/=]+)-->/);\n return match ? this._decodeSource(match[1]) : previewMarkup;\n }\n\n private _wrapRenderedHtml(source: string, renderedHtml: string): string {\n const attribute = TEMPLATE_DATA_PREVIEW_ATTRIBUTE + '=\"1\"';\n const className = 'em-prevent-action';\n const trimmed = renderedHtml.trim();\n const isBlockTwig = source.includes('{%');\n\n if (isBlockTwig) {\n return '<div ' + attribute + ' class=\"' + className + '\" style=\"display:block;cursor:pointer;\">' + renderedHtml + '</div>';\n }\n\n if (trimmed.startsWith('<')) {\n return '<span ' + attribute + ' class=\"' + className + '\" style=\"display:inline-block;cursor:pointer;\">' + renderedHtml + '</span>';\n }\n\n return '<span ' + attribute + ' class=\"' + className + '\" style=\"cursor:pointer;\">' + renderedHtml + '</span>';\n }\n\n private _bindPreviewClickHandler(): () => void {\n const onClick = (event: MouseEvent) => {\n const target = event.target as HTMLElement | null;\n const previewRoot = target?.closest?.('[' + TEMPLATE_DATA_PREVIEW_ATTRIBUTE + ']');\n if (!previewRoot) {\n return;\n }\n\n this._messageService?.send(OPEN_TEMPLATE_DATA_PANEL_MESSAGE);\n };\n\n document.addEventListener('click', onClick);\n return () => {\n document.removeEventListener('click', onClick);\n };\n }\n}\n\nApp.use(<%= it.pluginClassName %>Sandbox);\n",
3565
3576
  "../../project-templates/shared/comments/plugin-host-comments.en.ts": "export const pluginHostComments = {\n devHostMode: 'Source-mode host: load the plugin from source and keep dev helpers enabled.',\n releasePackages: 'Keep editor/runtime packages external here so the release host stays on the same DI/runtime contract as the built plugin.',\n releaseOptimizeDeps: 'Do not prebundle these packages in Vite, otherwise the host can evaluate its own runtime copy and duplicate singletons.',\n releaseAlias: 'Point the release smoke test to the built plugin bundle from dist/.',\n apiProxy: 'Proxy local /api calls to the target backend and preserve the expected origin header.',\n releaseEntry: 'Release smoke-test entry: boot the host against built assets from dist/.',\n} as const;\n",
@@ -3569,34 +3580,34 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3569
3580
  "../../project-templates/shared/partials/editor-init-smoke.eta": "<% if (it.includeSmokeHelpers) { %>\n<%~ include('editor-init-smoke-helpers', it) %>\n<% } else { %>\nfunction formatEditorInitError(error: unknown): string {\n if (error instanceof Error && error.message) {\n return error.message;\n }\n\n if (typeof error === 'string' && error.trim()) {\n return error.trim();\n }\n\n return 'Unknown editor initialization error.';\n}\n\nfunction reportEditorReady(_meta: unknown, _mountElement?: Element | null): void {}\n\nfunction reportEditorInitError(_meta: unknown, error: unknown, _mountElement?: Element | null): string {\n const message = formatEditorInitError(error);\n console.error('[editor-host] Editor initialization failed', error);\n return message;\n}\n<% } %>\n",
3570
3581
  "../../project-templates/shared/partials/plugin-app-advanced.eta": "import { pluginRegistry, createComponentIdentifier } from '<%= it.packageConfig.extensionsApiPackageName %>';\nimport { ComponentRegistry } from '<%= it.packageConfig.extensionsReactPackageName %>';\nimport type { ExportedApi, IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Config, <%= it.pluginClassName %>Options } from '../public-types';\nimport type { Group, VisualSettings } from '../interfaces';\nimport { Activate_Product_Settings, Change_Product_Settings } from '../interfaces';\nimport {\n <%= it.pluginClassName %>Icon,\n <%= it.pluginClassName %>SaveForm,\n <%= it.pluginClassName %>SettingsPanel,\n type <%= it.pluginClassName %>SaveFormProps,\n} from './ui/<%= it.pluginClassName %>Panel';\n\ntype DisposableLike = { dispose(): void } | (() => void) | void;\ntype Email = ExportedApi.Email;\ntype ProductBlockConfig = <%~ `NonNullable<${it.pluginClassName}Config['productBlock']>` %>;\ntype ProductBlockGroup = NonNullable<ProductBlockConfig['groups']>[number];\n\nfunction normalizePublicPath(value?: string): string | undefined {\n if (!value) {\n return undefined;\n }\n const trimmed = value.replace(/\\/+$/, '');\n return `${trimmed}/`;\n}\n\nconst AUTO_PUBLIC_PATH = (() => {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const currentScript = document.currentScript as HTMLScriptElement | null;\n if (!currentScript?.src) {\n return undefined;\n }\n\n return normalizePublicPath(currentScript.src.replace(/[^/]*$/, ''));\n})();\n\ninterface SaveParams {\n email: Email;\n content: string;\n format: string;\n}\n\nconst ELEMENT_NAME = <%~ it.literalPluginAppElementTitle %>;\nconst PRODUCT_HTML = <%~ it.productHtmlLiteral %>;\nconst PRODUCT_CARD_CSS = <%~ it.productCardCssLiteral %>;\nconst PRODUCT_CARD_SANDBOX_CSS_KEY = 'product-card-styles';\nconst <%= it.pluginClassName %>IconId = createComponentIdentifier<{ size?: number }>('<%= it.pluginClassName %>Icon');\nconst <%= it.pluginClassName %>SettingsPanelId = createComponentIdentifier<{\n groups: Group[];\n settings: VisualSettings;\n selectedGroup?: string;\n onChange?(group: Group | undefined, settings: VisualSettings): void;\n}>('<%= it.pluginClassName %>SettingsPanel');\nconst <%= it.pluginClassName %>SaveFormId = <%~ `createComponentIdentifier<${it.pluginClassName}SaveFormProps>` %>('<%= it.pluginClassName %>SaveForm');\n\n// Step 0 — register React panel/icon components for ElementsApi and SettingsPanelApi.\nComponentRegistry.add(<%= it.pluginClassName %>IconId, <%= it.pluginClassName %>Icon);\nComponentRegistry.add(<%= it.pluginClassName %>SettingsPanelId, <%= it.pluginClassName %>SettingsPanel);\nComponentRegistry.add(<%= it.pluginClassName %>SaveFormId, <%= it.pluginClassName %>SaveForm);\n\nexport class <%= it.pluginClassName %> implements IPlugin {\n private readonly _disposables: Array<{ dispose(): void }> = [];\n private _groups: ProductBlockGroup[] = [];\n\n constructor(\n private readonly _editor: Instance,\n private readonly _options: <%= it.pluginClassName %>Options = {},\n ) {}\n\n init() {\n // Step 1 — sandbox assets: CSS for the email iframe + sandbox.js (see end of init).\n const sandboxApi = this._editor.use('SandboxScriptApi');\n this._disposables.push(\n sandboxApi.registerSandboxCSSCode(PRODUCT_CARD_SANDBOX_CSS_KEY, PRODUCT_CARD_CSS),\n );\n\n const elementsApi = this._editor.use('ElementsApi');\n const messageService = this._editor.use('MessageService');\n const modalApi = this._editor.use('ModalApi');\n const config = this._editor.getConfig?.() as <%~ `Partial<${it.pluginClassName}Config>` %> | undefined;\n this._groups = config?.productBlock?.groups ?? [];\n\n // Step 2 — sidebar element + listen for clicks from sandbox (Activate_Product_Settings).\n this._disposables.push(\n elementsApi.insert({\n name: ELEMENT_NAME,\n title: ELEMENT_NAME,\n icon: {\n type: <%= it.pluginClassName %>IconId,\n props: { size: 24 },\n },\n className: 'product-atom',\n html: PRODUCT_HTML,\n }),\n messageService.addListener(Activate_Product_Settings, this._handleShowPanel),\n );\n\n // Optional demo — save modal + compileEmail download (not required for the product-card loop).\n this._trackDisposable(this._editor.handleSaveEmail?.((event) => {\n const { value } = event;\n let values: SaveParams = {\n email: value,\n content: value.code ?? '',\n format: 'text',\n };\n\n modalApi.show({\n title: <%~ it.literalPluginAppSaveEmailTitle %>,\n onOk: async () => {\n await this._onSave(values);\n },\n content: {\n type: <%= it.pluginClassName %>SaveFormId,\n props: {\n content: value.code ?? '',\n onChange: (nextValues: Omit<SaveParams, 'email'>) => {\n values = { ...values, ...nextValues };\n },\n },\n },\n });\n }));\n\n this._trackDisposable(this._editor.handleNotify?.((event: { id?: string }) => {\n if (event.id === 'EMAIL_SAVING_SUCCESS') {\n return false;\n }\n return undefined;\n }));\n\n this._trackDisposable(this._editor.handleConfigChanged?.(this._onConfigChanged));\n\n // Step 3 — load sandbox script from plugin publicPath (dev: `/`, release: `/dist/`).\n const publicPath = normalizePublicPath(this._options.publicPath) || AUTO_PUBLIC_PATH;\n if (publicPath) {\n this._disposables.push(\n sandboxApi.registerSandboxScript(publicPath + 'sandbox.js'),\n );\n }\n }\n\n private _trackDisposable(value: DisposableLike) {\n if (!value) {\n return;\n }\n\n if (typeof value === 'function') {\n this._disposables.push({ dispose: value });\n return;\n }\n\n if (typeof value.dispose === 'function') {\n this._disposables.push(value);\n }\n }\n\n private _onConfigChanged = (nextConfig: <%~ `Partial<${it.pluginClassName}Config>` %>) => {\n this._groups = nextConfig.productBlock?.enabled !== false\n ? nextConfig.productBlock?.groups ?? []\n : [];\n };\n\n private async _onSave({ email, content, format }: SaveParams) {\n try {\n if (typeof this._editor.compileEmail !== 'function') {\n throw new Error('compileEmail is not available');\n }\n\n const nextEmail: Email = { ...email, code: content };\n const result = await this._editor.compileEmail(nextEmail, true);\n const compiled = result.compiled;\n\n const lowerFormat = format.toLowerCase();\n let fileContent;\n let fileExtension;\n\n if (lowerFormat === 'amp' && compiled.ampHtml) {\n fileContent = compiled.ampHtml;\n fileExtension = 'html';\n } else if (lowerFormat === 'text' && compiled.text) {\n fileContent = compiled.text;\n fileExtension = 'txt';\n } else if (compiled.html) {\n fileContent = compiled.html;\n fileExtension = 'html';\n } else {\n throw new Error('Unable to resolve compiled email content.');\n }\n\n const blob = new Blob([fileContent], {\n type: fileExtension === 'txt' ? 'text/plain' : 'text/html',\n });\n\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = 'email-' + new Date().toISOString().slice(0, 10) + '.' + fileExtension;\n\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n\n if (typeof this._editor.notify === 'function') {\n this._editor.notify(<%~ it.literalPluginAppSavedSuccessfully %>);\n }\n } catch (error) {\n console.error('[<%= it.pluginClassName %>] Save failed', error);\n }\n }\n\n // Step 4 — open React settings panel; panel changes go back to sandbox via Change_Product_Settings.\n private _handleShowPanel = ({\n groupId,\n visualSettings,\n }: {\n groupId?: string;\n visualSettings: VisualSettings;\n }) => {\n if (!this._groups.length) return;\n const settingsPanel = this._editor.use('SettingsPanelApi');\n settingsPanel.showSettingsPanel({\n content: {\n type: <%= it.pluginClassName %>SettingsPanelId,\n props: {\n groups: this._groups,\n settings: visualSettings,\n selectedGroup: groupId || '',\n onChange: (group, settings) => {\n this._editor.use('MessageService').send(Change_Product_Settings, {\n group,\n visualSettings: settings,\n });\n },\n },\n },\n });\n };\n\n dispose() {\n this._editor.use('ElementsApi').delete(ELEMENT_NAME);\n while (this._disposables.length > 0) {\n const d = this._disposables.pop();\n d?.dispose();\n }\n }\n}\n\npluginRegistry.add(<%~ it.pluginKeyLiteral %>, <%= it.pluginClassName %>);\n",
3571
3582
  "../../project-templates/shared/partials/plugin-app-minimal.eta": "import { pluginRegistry } from '<%= it.packageConfig.extensionsApiPackageName %>';\nimport type { IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Options } from '../public-types';\n\ntype Disposable = { dispose(): void };\n\nfunction normalizePublicPath(value?: string): string | undefined {\n if (!value) {\n return undefined;\n }\n const trimmed = value.replace(/\\/+$/, '');\n return trimmed + '/';\n}\n\nconst AUTO_PUBLIC_PATH = (() => {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const currentScript = document.currentScript as HTMLScriptElement | null;\n if (!currentScript?.src) {\n return undefined;\n }\n\n return normalizePublicPath(currentScript.src.replace(/[^/]*$/, ''));\n})();\n\nexport class <%= it.pluginClassName %> implements IPlugin {\n private readonly _disposables: Disposable[] = [];\n\n constructor(\n private readonly _editor: Instance,\n private readonly _options: <%= it.pluginClassName %>Options = {},\n ) {}\n\n init() {\n const publicPath = normalizePublicPath(this._options.publicPath) || AUTO_PUBLIC_PATH;\n if (publicPath) {\n const sandboxApi = this._editor.use('SandboxScriptApi');\n this._disposables.push(\n sandboxApi.registerSandboxScript(publicPath + 'sandbox.js'),\n );\n }\n }\n\n dispose() {\n while (this._disposables.length > 0) {\n const disposable = this._disposables.pop();\n disposable?.dispose();\n }\n }\n}\n\npluginRegistry.add(<%~ it.pluginKeyLiteral %>, <%= it.pluginClassName %>);\n",
3572
- "../../project-templates/shared/partials/plugin-dev-get-auth-token.eta": "import { hasOAuthCredentials, oauthCredentials } from './oauthCredentials';\n\nexport async function getAuthToken() {\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ it.devAuthMissing %>);\n }\n\n const formData = new FormData();\n formData.append('grant_type', 'client_credentials');\n formData.append('client_id', oauthCredentials.clientId);\n formData.append('client_secret', oauthCredentials.clientSecret);\n\n const response = await fetch('/api?oauth=token', {\n method: 'POST',\n body: formData,\n redirect: 'follow',\n });\n const payload = await response.json().catch(() => null);\n\n if (!response.ok || !payload || typeof payload.access_token !== 'string') {\n throw new Error(\n <%~ it.devAuthTokenFailed %>,\n );\n }\n\n return payload.access_token;\n}\n",
3573
- "../../project-templates/shared/partials/plugin-dev-host-app-advanced.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './email.html?raw';\nimport { createEditorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\n\nconst productBlockGroups = [\n {\n id: 'group1',\n name: 'iPhone X',\n image_url: '/demo/product-1.svg',\n price: 999.95,\n count: 5,\n },\n {\n id: 'group2',\n name: 'MacBook Pro',\n image_url: '/demo/product-2.svg',\n price: 1499.95,\n count: 1,\n },\n];\n\nconst editorConfig = createEditorConfig({ productBlockGroups });\n\nfunction createDemoEmailId() {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n\n return `demo-email-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n// Demo hint injected into the starter email HTML (see README → Demo Flow).\nconst DEMO_TARGET_MARKUP = [\n '<tr em=\"block\" class=\"empty-structure\">',\n ' <td align=\"center\">',\n ' <table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"max-width: 660px;\">',\n ' <tr>',\n ' <td align=\"center\">',\n ' <table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"91%\">',\n ' <tr>',\n ' <td align=\"left\"></td>',\n ' </tr>',\n ' </table>',\n ' </td>',\n ' </tr>',\n ' </table>',\n ' </td>',\n '</tr>',\n '<tr>',\n ' <td style=\"padding: 32px; font-family: Arial, sans-serif; font-size: 16px; line-height: 24px; color: #333333;\">',\n ' <div style=\"padding: 16px; border: 1px dashed #d9d9d9; border-radius: 8px; background: #ffffff;\">',\n <%~ it.demoMessageLiteral %>,\n ' </div>',\n ' </td>',\n '</tr>',\n].join('');\n\nconst EMPTY_EMAIL_CONTAINER = '<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" border=\"0\" style=\"max-width: 660px; min-width: 660px; width: 660px;\" class=\"em-narrow-table\"></table>';\n\nfunction createDemoEmailHtml() {\n const populatedContainer = EMPTY_EMAIL_CONTAINER.replace('</table>', DEMO_TARGET_MARKUP + '</table>');\n return baseEmailHtml.includes(EMPTY_EMAIL_CONTAINER)\n ? baseEmailHtml.replace(EMPTY_EMAIL_CONTAINER, populatedContainer)\n : baseEmailHtml;\n}\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n const contentCode = createDemoEmailHtml();\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-advanced',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: contentCode,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
3574
- "../../project-templates/shared/partials/plugin-dev-host-app-minimal.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './email.html?raw';\nimport { editorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\n\nfunction createDemoEmailId() {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n\n return `demo-email-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-minimal',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
3575
- "../../project-templates/shared/partials/plugin-dev-tsx-debug.eta": "<% if (it.isLegacyWebpack) { %>\n\n\n\nimport '<%= it.packageConfig.packageName %>';\n\n\n\nimport './dev/legacyRuntimeDiagAfterProduct';\n\n\n\nimport PluginClass from './index';\n\n\n\nimport './dev/legacyRuntimeDiagAfterPlugin';\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\nimport { logLegacyRuntimeStage } from './dev/legacyRuntimeDiag';\n\n\n\nlogLegacyRuntimeStage('before-renderHostApp');\n\n\n\n\n\n\n\nif (!PluginClass) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n}\n\n\n\n\n\n\n\nconst plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [PluginClass, { publicPath: '/' }],\n\n\n\n];\n\n\n\n\n\n\n\nrenderHostApp({ plugins });\n\n\n\n<% } else { %>\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\n\n\n\n\n\nasync function main(): Promise<void> {\n\n\n\n const pluginModule = await import('./index');\n\n\n\n\n\n\n\n if (!pluginModule.default) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n }\n\n\n\n\n\n\n\n const plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [pluginModule.default, { publicPath: '/' }],\n\n\n\n ];\n\n\n\n\n\n\n\n renderHostApp({ plugins });\n\n\n\n}\n\n\n\n\n\n\n\nvoid main();\n\n\n\n<% } %>\n\n",
3583
+ "../../project-templates/shared/partials/plugin-dev-get-auth-token.eta": "import { hasOAuthCredentials, oauthCredentials } from './oauthCredentials';\n\nexport async function getAuthToken() {\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ it.devAuthMissing %>);\n }\n\n const formData = new URLSearchParams();\n formData.append('grant_type', 'client_credentials');\n formData.append('client_id', oauthCredentials.clientId);\n formData.append('client_secret', oauthCredentials.clientSecret);\n\n const response = await fetch('/api/oauth/token', {\n method: 'POST',\n body: formData,\n redirect: 'follow',\n });\n const payload = await response.json().catch(() => null);\n\n if (!response.ok || !payload || typeof payload.access_token !== 'string') {\n throw new Error(\n <%~ it.devAuthTokenFailed %>,\n );\n }\n\n return payload.access_token;\n}\n",
3584
+ "../../project-templates/shared/partials/plugin-dev-host-app-advanced.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './email.html?raw';\nimport { createEditorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\n\nconst productBlockGroups = [\n {\n id: 'group1',\n name: 'iPhone X',\n image_url: '/demo/product-1.svg',\n price: 999.95,\n count: 5,\n },\n {\n id: 'group2',\n name: 'MacBook Pro',\n image_url: '/demo/product-2.svg',\n price: 1499.95,\n count: 1,\n },\n];\n\nconst editorConfig = createEditorConfig({ productBlockGroups });\n\n// Demo hint injected into the starter email HTML (see README → Demo Flow).\nconst DEMO_TARGET_MARKUP = [\n '<tr em=\"block\" class=\"empty-structure\">',\n ' <td align=\"center\">',\n ' <table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"max-width: 660px;\">',\n ' <tr>',\n ' <td align=\"center\">',\n ' <table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"91%\">',\n ' <tr>',\n ' <td align=\"left\"></td>',\n ' </tr>',\n ' </table>',\n ' </td>',\n ' </tr>',\n ' </table>',\n ' </td>',\n '</tr>',\n '<tr>',\n ' <td style=\"padding: 32px; font-family: Arial, sans-serif; font-size: 16px; line-height: 24px; color: #333333;\">',\n ' <div style=\"padding: 16px; border: 1px dashed #d9d9d9; border-radius: 8px; background: #ffffff;\">',\n <%~ it.demoMessageLiteral %>,\n ' </div>',\n ' </td>',\n '</tr>',\n].join('');\n\nconst EMPTY_EMAIL_CONTAINER = '<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" border=\"0\" style=\"max-width: 660px; min-width: 660px; width: 660px;\" class=\"em-narrow-table\"></table>';\n\nfunction createDemoEmailHtml() {\n const populatedContainer = EMPTY_EMAIL_CONTAINER.replace('</table>', DEMO_TARGET_MARKUP + '</table>');\n return baseEmailHtml.includes(EMPTY_EMAIL_CONTAINER)\n ? baseEmailHtml.replace(EMPTY_EMAIL_CONTAINER, populatedContainer)\n : baseEmailHtml;\n}\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n const contentCode = createDemoEmailHtml();\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-advanced',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: contentCode,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n {/* The editor fills its container: without a definite height the side panels shrink to their content. */}\n <div id=\"editor-root\" style={{ height: '100vh' }} />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
3585
+ "../../project-templates/shared/partials/plugin-dev-host-app-minimal.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './email.html?raw';\nimport { editorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-minimal',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n {/* The editor fills its container: without a definite height the side panels shrink to their content. */}\n <div id=\"editor-root\" style={{ height: '100vh' }} />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
3586
+ "../../project-templates/shared/partials/plugin-dev-tsx-debug.eta": "<% if (it.devHostCompatGlobals) { %>\n// Plugin sources resolve their dependencies from `window.<ns>.modules`: turn the compatibility layer on.\nimport '<%= it.packageConfig.packageName %>/compat-globals';\n<% } %>\n<% if (it.isLegacyWebpack) { %>\n\n\n\nimport '<%= it.packageConfig.packageName %>';\n\n\n\nimport './dev/legacyRuntimeDiagAfterProduct';\n\n\n\nimport PluginClass from './index';\n\n\n\nimport './dev/legacyRuntimeDiagAfterPlugin';\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\nimport { logLegacyRuntimeStage } from './dev/legacyRuntimeDiag';\n\n\n\nlogLegacyRuntimeStage('before-renderHostApp');\n\n\n\n\n\n\n\nif (!PluginClass) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n}\n\n\n\n\n\n\n\nconst plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [PluginClass, { publicPath: '/' }],\n\n\n\n];\n\n\n\n\n\n\n\nrenderHostApp({ plugins });\n\n\n\n<% } else { %>\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\n\n\n\n\n\nasync function main(): Promise<void> {\n\n\n\n const pluginModule = await import('./index');\n\n\n\n\n\n\n\n if (!pluginModule.default) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n }\n\n\n\n\n\n\n\n const plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [pluginModule.default, { publicPath: '/' }],\n\n\n\n ];\n\n\n\n\n\n\n\n renderHostApp({ plugins });\n\n\n\n}\n\n\n\n\n\n\n\nvoid main();\n\n\n\n<% } %>\n\n",
3576
3587
  "../../project-templates/shared/partials/plugin-dev-tsx-minimal.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\n\n<%~ include('plugin-dev-tsx-runtime-helpers', it) %>\n<%~ include('editor-init-smoke', it) %>\nfunction createDemoEmailId() {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n\n return `demo-email-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-dev-minimal',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const PluginClass = IS_RELEASE_MODE && <%= it.releaseUsesUmd ? 'true' : 'false' %>\n ? undefined\n : await loadPluginConstructor();\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n plugins: getPluginEntries(PluginClass),\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" />\n </>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3577
- "../../project-templates/shared/partials/plugin-dev-tsx-release.eta": "<% if (it.isLegacyWebpack) { %>\n\n\n\nimport '<%= it.packageConfig.packageName %>';\n\n\n\nimport './dev/legacyRuntimeDiagAfterProduct';\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\nimport { logLegacyRuntimeStage } from './dev/legacyRuntimeDiag';\n\n\n\n// <%= it.commentReleaseEntry %>\n\n\n\n<% if (it.releaseUsesUmd) { %>\n\n\n\nlogLegacyRuntimeStage('release-before-renderHostApp-umd');\n\n\n\nrenderHostApp({\n\n\n\n plugins: [{\n\n\n\n type: 'umd',\n\n\n\n url: '/dist/index.js',\n\n\n\n name: <%~ it.pluginKeyLiteral %>,\n\n\n\n resolve: 'registry',\n\n\n\n }] as NonNullable<ExportedApi.Options['plugins']>,\n\n\n\n});\n\n\n\n<% } else { %>\n\n\n\nimport PluginClass from './index';\n\n\n\nimport './dev/legacyRuntimeDiagAfterPlugin';\n\n\n\nif (!PluginClass) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n}\n\n\n\n\n\n\n\nrenderHostApp({\n\n\n\n plugins: [[PluginClass, { publicPath: '/dist/' }]],\n\n\n\n});\n\n\n\n<% } %>\n\n\n\n<% } else { %>\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\n// <%= it.commentReleaseEntry %>\n\n\n\n<% if (it.releaseUsesUmd) { %>\n\n\n\nrenderHostApp({\n\n\n\n plugins: [{\n\n\n\n type: 'umd',\n\n\n\n url: '/dist/index.js',\n\n\n\n name: <%~ it.pluginKeyLiteral %>,\n\n\n\n resolve: 'registry',\n\n\n\n }] as NonNullable<ExportedApi.Options['plugins']>,\n\n\n\n});\n\n\n\n<% } else { %>\n\n\n\nasync function main(): Promise<void> {\n\n\n\n const pluginModule = await import(/* @vite-ignore */ '../dist/index.js') as {\n\n\n\n default?: typeof import('./index').default;\n\n\n\n };\n\n\n\n\n\n\n\n if (!pluginModule.default) {\n\n\n\n throw new Error('Unable to resolve the built plugin constructor from ../dist/index.js.');\n\n\n\n }\n\n\n\n\n\n\n\n const plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [pluginModule.default, { publicPath: '/dist/' }],\n\n\n\n ];\n\n\n\n\n\n\n\n renderHostApp({ plugins });\n\n\n\n}\n\n\n\n\n\n\n\nvoid main();\n\n\n\n<% } %>\n\n\n\n<% } %>\n\n",
3588
+ "../../project-templates/shared/partials/plugin-dev-tsx-release.eta": "<% if (it.releaseHostCompatGlobals) { %>\n// The built plugin reads its dependencies from `window.<ns>.modules`: turn the compatibility layer on.\nimport '<%= it.packageConfig.packageName %>/compat-globals';\n<% } %>\n<% if (it.isLegacyWebpack) { %>\n\n\n\nimport '<%= it.packageConfig.packageName %>';\n\n\n\nimport './dev/legacyRuntimeDiagAfterProduct';\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\nimport { logLegacyRuntimeStage } from './dev/legacyRuntimeDiag';\n\n\n\n// <%= it.commentReleaseEntry %>\n\n\n\n<% if (it.releaseUsesUmd) { %>\n\n\n\nlogLegacyRuntimeStage('release-before-renderHostApp-umd');\n\n\n\nrenderHostApp({\n\n\n\n plugins: [{\n\n\n\n type: 'umd',\n\n\n\n url: '/dist/index.js',\n\n\n\n name: <%~ it.pluginKeyLiteral %>,\n\n\n\n resolve: 'registry',\n\n\n\n }] as NonNullable<ExportedApi.Options['plugins']>,\n\n\n\n});\n\n\n\n<% } else { %>\n\n\n\nimport PluginClass from './index';\n\n\n\nimport './dev/legacyRuntimeDiagAfterPlugin';\n\n\n\nif (!PluginClass) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n}\n\n\n\n\n\n\n\nrenderHostApp({\n\n\n\n plugins: [[PluginClass, { publicPath: '/dist/' }]],\n\n\n\n});\n\n\n\n<% } %>\n\n\n\n<% } else { %>\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\n// <%= it.commentReleaseEntry %>\n\n\n\n<% if (it.releaseUsesUmd) { %>\n\n\n\nrenderHostApp({\n\n\n\n plugins: [{\n\n\n\n type: 'umd',\n\n\n\n url: '/dist/index.js',\n\n\n\n name: <%~ it.pluginKeyLiteral %>,\n\n\n\n resolve: 'registry',\n\n\n\n }] as NonNullable<ExportedApi.Options['plugins']>,\n\n\n\n});\n\n\n\n<% } else { %>\n\n\n\nasync function main(): Promise<void> {\n\n\n\n const pluginModule = await import('../dist/index.js') as {\n\n\n\n default?: typeof import('./index').default;\n\n\n\n };\n\n\n\n\n\n\n\n if (!pluginModule.default) {\n\n\n\n throw new Error('Unable to resolve the built plugin constructor from ../dist/index.js.');\n\n\n\n }\n\n\n\n\n\n\n\n const plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [pluginModule.default, { publicPath: '/dist/' }],\n\n\n\n ];\n\n\n\n\n\n\n\n renderHostApp({ plugins });\n\n\n\n}\n\n\n\n\n\n\n\nvoid main();\n\n\n\n<% } %>\n\n\n\n<% } %>\n\n",
3578
3589
  "../../project-templates/shared/partials/plugin-dev-tsx-runtime-helpers.eta": "type PluginConstructor = typeof import('./index').default;\ntype PluginEntries = NonNullable<ExportedApi.Options['plugins']>;\ntype PluginRunMode = 'debug' | 'release';\nconst RELEASE_PLUGIN_ENTRY: string = '/dist/index.js';\n\ndeclare global {\n var __EM_PLUGIN_RUN_MODE__: PluginRunMode | undefined;\n}\n\nconst RUN_MODE: PluginRunMode = globalThis.__EM_PLUGIN_RUN_MODE__ ?? 'debug';\nconst IS_RELEASE_MODE = RUN_MODE === 'release';\nconst SANDBOX_PUBLIC_PATH = IS_RELEASE_MODE ? '/dist/' : '/';\n\n<% if (it.releaseUsesUmd) { %>\nconst RELEASE_PLUGIN_DESCRIPTOR = {\n type: 'umd',\n url: RELEASE_PLUGIN_ENTRY,\n name: <%~ it.pluginKeyLiteral %>,\n resolve: 'registry',\n} as const;\n<% } %>\nasync function loadPluginConstructor() {\n if (!IS_RELEASE_MODE) {\n const pluginModule = await import('./index');\n if (!pluginModule.default) {\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n }\n return pluginModule.default;\n }\n\n <% if (it.releaseUsesUmd) { %>throw new Error('Release UMD bundle should be passed as a descriptor.');<% } else { %>throw new Error('Release ESM bundle should be resolved by the release host entry.');<% } %>\n}\n\nfunction getPluginEntries(pluginClass?: PluginConstructor): PluginEntries {\n if (IS_RELEASE_MODE && <%= it.releaseUsesUmd ? 'true' : 'false' %>) {\n return [RELEASE_PLUGIN_DESCRIPTOR] as PluginEntries;\n }\n\n if (!pluginClass) {\n throw new Error('Unable to resolve the plugin constructor.');\n }\n\n return [[pluginClass, { publicPath: SANDBOX_PUBLIC_PATH }] as const] as PluginEntries;\n}\n",
3579
3590
  "../../project-templates/shared/partials/plugin-editor-config.eta": "<% if (it.isAdvanced) { %>\nimport type { Config } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Config, <%= it.pluginClassName %>ProductGroup } from '../public-types';\n\ntype EditorConfigOptions = {\n productBlockGroups?: <%= it.pluginClassName %>ProductGroup[];\n};\n\n/** Minimal dev-host config: product groups for the demo. Extend with merge tags, fileManager, etc. as needed. */\nconst baseEditorConfig = {\n theme: 'light',\n locale: 'ru_RU',\n} satisfies Partial<<%~ it.baseConfigTarget %>>;\n\nexport function createEditorConfig(options: EditorConfigOptions = {}): Partial<Config> {\n if (options.productBlockGroups?.length) {\n return {\n ...baseEditorConfig,\n productBlock: {\n enabled: true,\n groups: options.productBlockGroups,\n },\n } satisfies <%~ `Partial<Config & ${it.pluginClassName}Config>` %>;\n }\n\n return baseEditorConfig;\n}\n\nexport const editorConfig = createEditorConfig();\n<% } else { %>\nimport type { Config } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Config } from '../public-types';\n\nconst mergeTagItems = [\n {\n label: 'Profile',\n value: 'profile',\n children: [\n { label: 'First name', value: 'profile.firstName' },\n { label: 'Last name', value: 'profile.lastName' },\n { label: 'Email', value: 'profile.email' },\n ],\n },\n {\n label: 'Company',\n value: 'company',\n children: [\n { label: 'Name', value: 'company.name' },\n { label: 'Industry', value: 'company.industry' },\n { label: 'Website', value: 'company.website' },\n ],\n },\n {\n label: 'Campaign',\n value: 'campaign',\n children: [\n { label: 'Title', value: 'campaign.title' },\n { label: 'Promo code', value: 'campaign.promoCode' },\n { label: 'CTA URL', value: 'campaign.ctaUrl' },\n ],\n },\n];\n\nconst baseEditorConfig = {\n theme: 'light',\n locale: 'ru_RU',\n autosaveTimeout: 15000,\n commonStylesEnabled: true,\n mergeTagsShow: true,\n imageCenterFileManagerView: true,\n fileManager: {\n defaultFolderName: 'demo-assets',\n enableMoveFolder: true,\n enableEdit: true,\n enableTrash: true,\n enableCopyFile: true,\n enableCopyFolder: true,\n },\n mergeTags: {\n syntax: ['{{' + '%value%' + '}}'],\n items: mergeTagItems,\n },\n} satisfies Partial<<%~ it.baseConfigTarget %>>;\n\nexport function createEditorConfig(): Partial<Config> {\n return baseEditorConfig;\n}\n\nexport const editorConfig = createEditorConfig();\n<% } %>\n",
3580
3591
  "../../project-templates/shared/partials/plugin-index-ts.eta": "import { <%= it.pluginClassName %> } from './app/<%= it.pluginClassName %>';\n\nexport default <%= it.pluginClassName %>;\n",
3581
- "../../project-templates/shared/partials/plugin-panel-advanced.eta": "import React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { Collapse, Form, Input, Select, Typography } from 'antd';\nimport { ColorPicker, EmIcons } from '<%= it.packageConfig.uiKitPackageName %>';\nimport type { Group, VisualSettings } from '../../interfaces';\n\nconst { Panel } = Collapse;\nconst { Text } = Typography;\nconst { TextArea } = Input;\n\nconst UI_TEXT = {\n contentSettings: <%~ it.panelUi.contentSettings %>,\n visualSettings: <%~ it.panelUi.visualSettings %>,\n selectGroup: <%~ it.panelUi.selectGroup %>,\n itemsCount: <%~ it.panelUi.itemsCount %>,\n blockBorder: <%~ it.panelUi.blockBorder %>,\n blockPadding: <%~ it.panelUi.blockPadding %>,\n cardBackgroundColor: <%~ it.panelUi.cardBackgroundColor %>,\n cardTextColor: <%~ it.panelUi.cardTextColor %>,\n cardTextAlign: <%~ it.panelUi.cardTextAlign %>,\n alignLeft: <%~ it.panelUi.alignLeft %>,\n alignCenter: <%~ it.panelUi.alignCenter %>,\n alignRight: <%~ it.panelUi.alignRight %>,\n buttonText: <%~ it.panelUi.buttonText %>,\n buttonColor: <%~ it.panelUi.buttonColor %>,\n saveTitle: <%~ it.panelUi.saveTitle %>,\n saveSize: <%~ it.panelUi.saveSize %>,\n bytes: <%~ it.panelUi.bytes %>,\n contentPlaceholder: <%~ it.panelUi.contentPlaceholder %>,\n emailFormat: <%~ it.panelUi.emailFormat %>,\n};\n\nexport function <%= it.pluginClassName %>Icon() {\n return React.createElement(EmIcons, { icon: 'Sun' });\n}\n\nexport interface <%= it.pluginClassName %>SettingsPanelProps {\n groups: Group[];\n settings: VisualSettings;\n selectedGroup?: string;\n onChange?(group: Group | undefined, settings: VisualSettings): void;\n}\n\nexport type EmailFormat = 'amp' | 'text' | 'html';\n\nexport interface <%= it.pluginClassName %>SaveFormProps {\n content?: string;\n initialFormat?: EmailFormat;\n onChange?: (values: { content: string; format: EmailFormat }) => void;\n}\n\nfunction renderGroupOption(group: Group) {\n return (\n <div style={{ display: 'flex', alignItems: 'center', padding: '8px', borderBottom: '1px solid #ddd' }}>\n <img\n src={group.image_url}\n alt={group.name}\n style={{ width: 40, height: 40, marginRight: 10, borderRadius: 4 }}\n />\n <div>\n <Text strong>{group.name}</Text>\n <br />\n <Text type=\"secondary\">{group.count} {UI_TEXT.itemsCount}</Text>\n </div>\n </div>\n );\n}\n\nfunction ContentSettings({\n groups,\n selectedGroup,\n onChange,\n}: {\n groups: Group[];\n selectedGroup: string;\n onChange: (value: string) => void;\n}) {\n return (\n <Form layout=\"vertical\" style={{ padding: '10px' }}>\n <Form.Item label={UI_TEXT.selectGroup}>\n <Select\n value={groups.some((group) => group.id === selectedGroup) ? selectedGroup : undefined}\n onChange={onChange}\n style={{ width: '100%', height: '60px' }}\n dropdownStyle={{ padding: 0 }}\n >\n {groups.map((group) => (\n <Select.Option key={group.id} value={group.id}>\n {renderGroupOption(group)}\n </Select.Option>\n ))}\n </Select>\n </Form.Item>\n </Form>\n );\n}\n\nfunction VisualSettingsForm({\n settings,\n onChange,\n}: {\n settings: VisualSettings;\n onChange: (nextSettings: VisualSettings) => void;\n}) {\n const [local, setLocal] = useState(settings);\n const isEditingRef = useRef(false);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n if (!isEditingRef.current) {\n setLocal(settings);\n }\n }, [settings]);\n\n useEffect(() => () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n }, []);\n\n const updateField = (key: keyof VisualSettings, value: VisualSettings[keyof VisualSettings]) => {\n isEditingRef.current = true;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n const updated = { ...local, [key]: value };\n setLocal(updated);\n onChange(updated);\n\n timeoutRef.current = setTimeout(() => {\n isEditingRef.current = false;\n }, 50);\n };\n\n return (\n <Form layout=\"vertical\" style={{ padding: '10px' }}>\n <Form.Item label={UI_TEXT.blockBorder}>\n <Input\n type=\"number\"\n value={local.blockBorder}\n onChange={(e) => updateField('blockBorder', parseInt(e.target.value, 10) || 0)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.blockPadding}>\n <Input\n type=\"number\"\n value={local.blockPadding}\n onChange={(e) => updateField('blockPadding', parseInt(e.target.value, 10) || 0)}\n />\n </Form.Item>\n\n {/*\n ColorPicker fills Form.Item width by default (ui-kit).\n With antd Form + field names prefer FormColorField from ui-kit — see docs/plugin-system/06-ui/UI_KIT.md.\n */}\n <Form.Item label={UI_TEXT.cardBackgroundColor}>\n <ColorPicker\n value={local.cardBackgroundColor}\n onChange={(color) => updateField('cardBackgroundColor', color)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.cardTextColor}>\n <ColorPicker\n value={local.cardTextColor}\n onChange={(color) => updateField('cardTextColor', color)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.cardTextAlign}>\n <Select\n value={local.cardTextAlign}\n onChange={(value) => updateField('cardTextAlign', value)}\n >\n <Select.Option value=\"left\">{UI_TEXT.alignLeft}</Select.Option>\n <Select.Option value=\"center\">{UI_TEXT.alignCenter}</Select.Option>\n <Select.Option value=\"right\">{UI_TEXT.alignRight}</Select.Option>\n </Select>\n </Form.Item>\n\n <Form.Item label={UI_TEXT.buttonText}>\n <Input\n value={local.cardButtonText}\n onChange={(e) => updateField('cardButtonText', e.target.value)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.buttonColor}>\n <ColorPicker\n value={local.cardButtonColor}\n onChange={(color) => updateField('cardButtonColor', color)}\n />\n </Form.Item>\n </Form>\n );\n}\n\nexport function <%= it.pluginClassName %>SettingsPanel({\n groups,\n settings,\n selectedGroup,\n onChange,\n}: <%= it.pluginClassName %>SettingsPanelProps) {\n const [currentGroupId, setCurrentGroupId] = useState<string>(selectedGroup || '');\n const [currentSettings, setCurrentSettings] = useState<VisualSettings>(settings);\n const isFirstRender = useRef(true);\n const isDirty = useRef(false);\n\n const currentGroup = useMemo(\n () => groups.find((group) => group.id === currentGroupId),\n [groups, currentGroupId],\n );\n\n useEffect(() => {\n setCurrentSettings(settings);\n setCurrentGroupId(selectedGroup !== undefined ? selectedGroup : '');\n isDirty.current = false;\n }, [settings, selectedGroup]);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n\n if (isDirty.current && onChange) {\n onChange(currentGroup, currentSettings);\n }\n }, [currentSettings, currentGroup, onChange]);\n\n return (\n <div style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box' }}>\n <Collapse defaultActiveKey={['1', '2']} style={{ borderRadius: '8px' }}>\n <Panel header={<Text strong>{UI_TEXT.contentSettings}</Text>} key=\"1\">\n <ContentSettings\n groups={groups}\n selectedGroup={currentGroupId}\n onChange={(groupId) => {\n setCurrentGroupId(groupId);\n isDirty.current = true;\n\n const group = groups.find((item) => item.id === groupId);\n onChange?.(group, currentSettings);\n }}\n />\n </Panel>\n <Panel header={<Text strong>{UI_TEXT.visualSettings}</Text>} key=\"2\">\n <VisualSettingsForm\n settings={currentSettings}\n onChange={(nextSettings) => {\n setCurrentSettings(nextSettings);\n isDirty.current = true;\n }}\n />\n </Panel>\n </Collapse>\n </div>\n );\n}\n\nexport function <%= it.pluginClassName %>SaveForm({\n content: initialContent = '',\n initialFormat = 'text',\n onChange,\n}: <%= it.pluginClassName %>SaveFormProps) {\n const [content, setContent] = useState(initialContent);\n const [format, setFormat] = useState<EmailFormat>(initialFormat);\n\n const getByteLength = (value: string): number => new TextEncoder().encode(value).length;\n\n useEffect(() => {\n onChange?.({ content, format });\n }, [content, format, onChange]);\n\n return (\n <Form layout=\"vertical\" autoComplete=\"off\">\n <Form.Item label={UI_TEXT.saveSize + ': ' + String(getByteLength(content)) + ' ' + UI_TEXT.bytes}>\n <TextArea\n rows={6}\n value={content}\n onChange={(e) => setContent(e.target.value)}\n placeholder={UI_TEXT.contentPlaceholder}\n allowClear\n data-testid=\"email-content-input\"\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.emailFormat} required>\n <Select<EmailFormat>\n value={format}\n onChange={(value) => setFormat(value)}\n data-testid=\"email-format-select\"\n >\n <Select.Option value=\"amp\">AMP</Select.Option>\n <Select.Option value=\"text\">Text/plain</Select.Option>\n <Select.Option value=\"html\">HTML</Select.Option>\n </Select>\n </Form.Item>\n </Form>\n );\n}\n",
3592
+ "../../project-templates/shared/partials/plugin-panel-advanced.eta": "import React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { Collapse, Form, Input, Select, Typography } from 'antd';\n/*\n * Icons come from the plugin's own `@ant-design/icons` copy and are tree-shaken there: the host\n * publishes only the `AntdIcon` machinery, not the 831-entry catalogue. Any icon of the package\n * works, including ones the host never uses — and it still renders in the host's icon context,\n * because the machinery that computes the class is a single shared copy.\n */\nimport { ApiOutlined, SunOutlined } from '@ant-design/icons';\n/*\n * No `EmIcons icon=\"…\"` here: a plugin is built without the host's icon codemod, so a name is\n * looked up in the registry at runtime and pulls the whole ui-kit catalog.\n */\nimport { ColorPicker } from '<%= it.packageConfig.uiKitPackageName %>';\nimport type { Group, VisualSettings } from '../../interfaces';\n\nconst { Panel } = Collapse;\nconst { Text } = Typography;\nconst { TextArea } = Input;\n\nconst UI_TEXT = {\n contentSettings: <%~ it.panelUi.contentSettings %>,\n visualSettings: <%~ it.panelUi.visualSettings %>,\n selectGroup: <%~ it.panelUi.selectGroup %>,\n itemsCount: <%~ it.panelUi.itemsCount %>,\n blockBorder: <%~ it.panelUi.blockBorder %>,\n blockPadding: <%~ it.panelUi.blockPadding %>,\n cardBackgroundColor: <%~ it.panelUi.cardBackgroundColor %>,\n cardTextColor: <%~ it.panelUi.cardTextColor %>,\n cardTextAlign: <%~ it.panelUi.cardTextAlign %>,\n alignLeft: <%~ it.panelUi.alignLeft %>,\n alignCenter: <%~ it.panelUi.alignCenter %>,\n alignRight: <%~ it.panelUi.alignRight %>,\n buttonText: <%~ it.panelUi.buttonText %>,\n buttonColor: <%~ it.panelUi.buttonColor %>,\n saveTitle: <%~ it.panelUi.saveTitle %>,\n saveSize: <%~ it.panelUi.saveSize %>,\n bytes: <%~ it.panelUi.bytes %>,\n contentPlaceholder: <%~ it.panelUi.contentPlaceholder %>,\n emailFormat: <%~ it.panelUi.emailFormat %>,\n};\n\nexport function <%= it.pluginClassName %>Icon() {\n return React.createElement(SunOutlined);\n}\n\nexport interface <%= it.pluginClassName %>SettingsPanelProps {\n groups: Group[];\n settings: VisualSettings;\n selectedGroup?: string;\n onChange?(group: Group | undefined, settings: VisualSettings): void;\n}\n\nexport type EmailFormat = 'amp' | 'text' | 'html';\n\nexport interface <%= it.pluginClassName %>SaveFormProps {\n content?: string;\n initialFormat?: EmailFormat;\n onChange?: (values: { content: string; format: EmailFormat }) => void;\n}\n\nfunction renderGroupOption(group: Group) {\n return (\n <div style={{ display: 'flex', alignItems: 'center', padding: '8px', borderBottom: '1px solid #ddd' }}>\n <img\n src={group.image_url}\n alt={group.name}\n style={{ width: 40, height: 40, marginRight: 10, borderRadius: 4 }}\n />\n <div>\n <Text strong>{group.name}</Text>\n <br />\n <Text type=\"secondary\">{group.count} {UI_TEXT.itemsCount}</Text>\n </div>\n </div>\n );\n}\n\nfunction ContentSettings({\n groups,\n selectedGroup,\n onChange,\n}: {\n groups: Group[];\n selectedGroup: string;\n onChange: (value: string) => void;\n}) {\n return (\n <Form layout=\"vertical\" style={{ padding: '10px' }}>\n <Form.Item label={UI_TEXT.selectGroup}>\n <Select\n value={groups.some((group) => group.id === selectedGroup) ? selectedGroup : undefined}\n onChange={onChange}\n style={{ width: '100%', height: '60px' }}\n dropdownStyle={{ padding: 0 }}\n >\n {groups.map((group) => (\n <Select.Option key={group.id} value={group.id}>\n {renderGroupOption(group)}\n </Select.Option>\n ))}\n </Select>\n </Form.Item>\n </Form>\n );\n}\n\nfunction VisualSettingsForm({\n settings,\n onChange,\n}: {\n settings: VisualSettings;\n onChange: (nextSettings: VisualSettings) => void;\n}) {\n const [local, setLocal] = useState(settings);\n const isEditingRef = useRef(false);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n if (!isEditingRef.current) {\n setLocal(settings);\n }\n }, [settings]);\n\n useEffect(() => () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n }, []);\n\n const updateField = (key: keyof VisualSettings, value: VisualSettings[keyof VisualSettings]) => {\n isEditingRef.current = true;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n const updated = { ...local, [key]: value };\n setLocal(updated);\n onChange(updated);\n\n timeoutRef.current = setTimeout(() => {\n isEditingRef.current = false;\n }, 50);\n };\n\n return (\n <Form layout=\"vertical\" style={{ padding: '10px' }}>\n <Form.Item label={UI_TEXT.blockBorder}>\n <Input\n type=\"number\"\n value={local.blockBorder}\n onChange={(e) => updateField('blockBorder', parseInt(e.target.value, 10) || 0)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.blockPadding}>\n <Input\n type=\"number\"\n value={local.blockPadding}\n onChange={(e) => updateField('blockPadding', parseInt(e.target.value, 10) || 0)}\n />\n </Form.Item>\n\n {/*\n ColorPicker fills Form.Item width by default (ui-kit).\n With antd Form + field names prefer FormColorField from ui-kit — see docs/plugin-system/06-ui/UI_KIT.md.\n */}\n <Form.Item label={UI_TEXT.cardBackgroundColor}>\n <ColorPicker\n value={local.cardBackgroundColor}\n onChange={(color) => updateField('cardBackgroundColor', color)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.cardTextColor}>\n <ColorPicker\n value={local.cardTextColor}\n onChange={(color) => updateField('cardTextColor', color)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.cardTextAlign}>\n <Select\n value={local.cardTextAlign}\n onChange={(value) => updateField('cardTextAlign', value)}\n >\n <Select.Option value=\"left\">{UI_TEXT.alignLeft}</Select.Option>\n <Select.Option value=\"center\">{UI_TEXT.alignCenter}</Select.Option>\n <Select.Option value=\"right\">{UI_TEXT.alignRight}</Select.Option>\n </Select>\n </Form.Item>\n\n <Form.Item label={UI_TEXT.buttonText}>\n <Input\n value={local.cardButtonText}\n onChange={(e) => updateField('cardButtonText', e.target.value)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.buttonColor}>\n <ColorPicker\n value={local.cardButtonColor}\n onChange={(color) => updateField('cardButtonColor', color)}\n />\n </Form.Item>\n </Form>\n );\n}\n\nexport function <%= it.pluginClassName %>SettingsPanel({\n groups,\n settings,\n selectedGroup,\n onChange,\n}: <%= it.pluginClassName %>SettingsPanelProps) {\n const [currentGroupId, setCurrentGroupId] = useState<string>(selectedGroup || '');\n const [currentSettings, setCurrentSettings] = useState<VisualSettings>(settings);\n const isFirstRender = useRef(true);\n const isDirty = useRef(false);\n\n const currentGroup = useMemo(\n () => groups.find((group) => group.id === currentGroupId),\n [groups, currentGroupId],\n );\n\n useEffect(() => {\n setCurrentSettings(settings);\n setCurrentGroupId(selectedGroup !== undefined ? selectedGroup : '');\n isDirty.current = false;\n }, [settings, selectedGroup]);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n\n if (isDirty.current && onChange) {\n onChange(currentGroup, currentSettings);\n }\n }, [currentSettings, currentGroup, onChange]);\n\n return (\n <div style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box' }}>\n <Collapse defaultActiveKey={['1', '2']} style={{ borderRadius: '8px' }}>\n <Panel\n header={\n <Text strong>\n <ApiOutlined /> {UI_TEXT.contentSettings}\n </Text>\n }\n key=\"1\"\n >\n <ContentSettings\n groups={groups}\n selectedGroup={currentGroupId}\n onChange={(groupId) => {\n setCurrentGroupId(groupId);\n isDirty.current = true;\n\n const group = groups.find((item) => item.id === groupId);\n onChange?.(group, currentSettings);\n }}\n />\n </Panel>\n <Panel header={<Text strong>{UI_TEXT.visualSettings}</Text>} key=\"2\">\n <VisualSettingsForm\n settings={currentSettings}\n onChange={(nextSettings) => {\n setCurrentSettings(nextSettings);\n isDirty.current = true;\n }}\n />\n </Panel>\n </Collapse>\n </div>\n );\n}\n\nexport function <%= it.pluginClassName %>SaveForm({\n content: initialContent = '',\n initialFormat = 'text',\n onChange,\n}: <%= it.pluginClassName %>SaveFormProps) {\n const [content, setContent] = useState(initialContent);\n const [format, setFormat] = useState<EmailFormat>(initialFormat);\n\n const getByteLength = (value: string): number => new TextEncoder().encode(value).length;\n\n useEffect(() => {\n onChange?.({ content, format });\n }, [content, format, onChange]);\n\n return (\n <Form layout=\"vertical\" autoComplete=\"off\">\n <Form.Item label={UI_TEXT.saveSize + ': ' + String(getByteLength(content)) + ' ' + UI_TEXT.bytes}>\n <TextArea\n rows={6}\n value={content}\n onChange={(e) => setContent(e.target.value)}\n placeholder={UI_TEXT.contentPlaceholder}\n allowClear\n data-testid=\"email-content-input\"\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.emailFormat} required>\n <Select<EmailFormat>\n value={format}\n onChange={(value) => setFormat(value)}\n data-testid=\"email-format-select\"\n >\n <Select.Option value=\"amp\">AMP</Select.Option>\n <Select.Option value=\"text\">Text/plain</Select.Option>\n <Select.Option value=\"html\">HTML</Select.Option>\n </Select>\n </Form.Item>\n </Form>\n );\n}\n",
3582
3593
  "../../project-templates/shared/partials/plugin-panel-minimal.eta": "import {\n DomComponentRegistry,\n createComponentIdentifier,\n type IDomComponentFactory,\n} from '<%= it.packageConfig.extensionsApiPackageName %>';\n\nexport const <%= it.pluginClassName %>PanelId = <%~ `createComponentIdentifier<${it.pluginClassName}PanelProps>` %>(\n '<%= it.pluginClassName %>SettingsPanel',\n);\n\nexport interface <%= it.pluginClassName %>PanelProps {\n initialValue: string;\n onApply(value: string): void;\n}\n\nconst create<%= it.pluginClassName %>PanelNode: <%~ `IDomComponentFactory<${it.pluginClassName}PanelProps>` %> = (props) => {\n const root = document.createElement('div');\n root.style.display = 'grid';\n root.style.gap = '12px';\n\n const text = document.createElement('div');\n text.textContent = <%~ it.panelUi.minimalInstructions %>;\n\n const input = document.createElement('input');\n input.value = props.initialValue;\n input.style.padding = '8px 12px';\n input.style.border = '1px solid #d9d9d9';\n input.style.borderRadius = '6px';\n\n const button = document.createElement('button');\n button.type = 'button';\n button.textContent = <%~ it.panelUi.minimalApply %>;\n button.style.padding = '8px 12px';\n button.style.border = '0';\n button.style.borderRadius = '6px';\n button.style.background = '#1677ff';\n button.style.color = '#ffffff';\n button.style.cursor = 'pointer';\n\n let currentProps = props;\n const handleClick = () => {\n currentProps.onApply(input.value);\n };\n\n button.addEventListener('click', handleClick);\n\n root.append(text, input, button);\n\n return {\n node: root,\n update(nextProps) {\n currentProps = nextProps;\n input.value = nextProps.initialValue;\n },\n dispose() {\n button.removeEventListener('click', handleClick);\n },\n };\n};\n\nlet panelRegistered = false;\n\nexport function ensure<%= it.pluginClassName %>PanelRegistered() {\n if (panelRegistered) {\n return;\n }\n\n DomComponentRegistry.add(<%= it.pluginClassName %>PanelId, create<%= it.pluginClassName %>PanelNode);\n panelRegistered = true;\n}\n",
3583
3594
  "../../project-templates/shared/partials/plugin-public-types.eta": "import type { IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\n\nexport interface <%= it.pluginClassName %>Options {\n publicPath?: string;\n}\n\n<% if (it.isAdvanced) { %>\nexport interface <%= it.pluginClassName %>ProductGroup {\n id: string;\n name: string;\n image_url: string;\n price: number;\n count: number;\n}\n\nexport interface <%= it.pluginClassName %>Config {\n productBlock?: {\n enabled?: boolean;\n groups?: <%= it.pluginClassName %>ProductGroup[];\n };\n}\n\n<% } else { %>\nexport interface <%= it.pluginClassName %>Config {}\n\n<% } %>\nexport declare class <%= it.pluginClassName %> implements IPlugin {\n constructor(instance: Instance, options?: <%= it.pluginClassName %>Options);\n init?(): Promise<void> | void;\n afterInit?(): Promise<void> | void;\n dispose?(): Promise<void> | void;\n}\n\nexport default <%= it.pluginClassName %>;\n\ndeclare module '<%= it.packageConfig.packageName %>' {\n interface PluginTypeMap {\n <%= it.pluginKey %>: typeof <%= it.pluginClassName %>;\n }\n\n interface Config extends <%= it.pluginClassName %>Config {}\n}\n\nexport {};\n",
3584
3595
  "../../project-templates/shared/partials/plugin-readme.eta": "# <%= it.pluginPackageName %>\n\n<%= it.readme.generated %>\n\n<%= it.readme.whatIncluded %>\n\n<%= it.readme.lineMinimalScaffold %>\n<%= it.readme.lineMinimalSandbox %>\n<% if (it.readme.lineAdvancedProductCard) { %><%= it.readme.lineAdvancedProductCard %>\n<% } %><% if (it.readme.lineTemplatingPreview) { %><%= it.readme.lineTemplatingPreview %>\n<% } %><%= it.readme.localDebugHost %>\n<%= it.readme.presetLine %>\n<%= it.readme.bundlerLine %>\n<%= it.readme.deliveryTarget %>\n\n<%= it.readme.commands %>\n\n```bash\nnpm install\nnpm run start\nnpm run start:release\nnpm run build\n```\n\n<%= it.readme.commandStartDebug %>\n<%= it.readme.commandStartRelease %>\n\n<%= it.readme.localAuthSetup %>\n\n<%= it.readme.fillOAuthCredentials %>\n\n```ts\nexport const oauthCredentials = {\n clientId: 'YOUR_CLIENT_ID',\n clientSecret: 'YOUR_CLIENT_SECRET',\n};\n```\n\n<%= it.readme.afterAuth %>\n\n<% if (it.readme.advancedDemoFlow) { %><%= it.readme.advancedDemoFlow %>\n\n<%= it.readme.advancedDemoFlowBody %>\n<% } %>\n<%= it.readme.structure %>\n\n<%= it.readme.structureApp %>\n<%= it.readme.structureSandbox %>\n<% if (it.readme.structureCommon) { %><%= it.readme.structureCommon %>\n<% } %><% if (it.readme.structureInterfaces) { %><%= it.readme.structureInterfaces %>\n<% } %><%= it.readme.structureDevHost %>\n<%= it.readme.structureEmail %>\n<%= it.readme.structureCredentials %>\n<%= it.readme.structurePublicTypes %>\n<%= it.readme.structureEditorConfig %>\n<% if (it.readme.advancedEditorConfigNote) { %><%= it.readme.advancedEditorConfigNote %>\n<% } %><%= it.readme.structureConfig %>\n\n<%= it.readme.notes %>\n\n<%= it.readme.registeredInPluginRegistry %>\n<%= it.readme.sandboxLoadedFrom %>\n<%= it.readme.releaseBundleTarget %>\n<%= it.readme.reactIntegrations %>\n<%= it.readme.troubleshooting %>\n<% if (it.readme.legacyMappings) { %><%= it.readme.legacyMappings %>\n<% } %><% if (it.readme.localTarballs) { %><%= it.readme.localTarballs %>\n<% } %>\n",
3585
3596
  "../../project-templates/shared/partials/plugin-sandbox-advanced.eta": "import { App, MessageService, SyncService } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport type { IPlugin } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport {\n Activate_Product_Settings,\n Change_Product_Settings,\n Group,\n VisualSettings,\n} from '../interfaces';\n\nimport groupCardTemplate from '../common/templates/group-card.html?raw';\nimport emptyGroupTemplate from '../common/templates/empty-group.html?raw';\n\n/** SSOT: same CSS as plugin-app-advanced (`plugin/assets/advanced/product-card.css` via Eta). */\nconst PRODUCT_CARD_CSS = <%~ it.productCardCssLiteral %>;\n\ntype Disposable = { dispose(): void };\n\nclass ProductCardSandbox implements IPlugin {\n private _messageService!: MessageService;\n private _syncService?: SyncService;\n private _activeAtom: HTMLElement | null = null;\n private readonly _disposables: Disposable[] = [];\n\n private _hasExtensionStyles(): boolean {\n return Boolean(document.querySelector('style[data-extension=\"product-card-styles\"]'));\n }\n\n private _injectStylesFallback() {\n if (this._hasExtensionStyles()) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute('data-extension', 'product-card-styles');\n style.textContent = PRODUCT_CARD_CSS;\n document.head.appendChild(style);\n }\n\n private async _ensureStyles() {\n for (let attempt = 0; attempt < 40; attempt += 1) {\n if (this._hasExtensionStyles()) {\n return;\n }\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n this._injectStylesFallback();\n }\n\n private _fillTemplate(template: string, data: Record<string, string>): string {\n return template.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_, key) => data[key] || '');\n }\n\n private _onClick = (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n const atom = target.closest('.product-atom') as HTMLElement | null;\n if (!atom) return;\n this._activeAtom = atom;\n const groupId = this._getGroupId(atom);\n const settings = this._extractVisualSettings(atom);\n this._messageService.send(Activate_Product_Settings, { groupId, visualSettings: settings });\n e.preventDefault();\n };\n\n private _onChangeSettings = ({\n group,\n visualSettings,\n }: {\n group?: Group;\n visualSettings: VisualSettings;\n }) => {\n if (!this._activeAtom) return;\n if (this._getGroupId(this._activeAtom) !== group?.id) {\n this._renderGroupCard(this._activeAtom, group);\n const groupId = this._getGroupId(this._activeAtom);\n const settings = this._extractVisualSettings(this._activeAtom);\n this._messageService.send(Activate_Product_Settings, {\n groupId,\n visualSettings: settings,\n });\n }\n setTimeout(() => {\n this._applyVisualSettings(this._activeAtom!, visualSettings);\n }, 0);\n };\n\n private _renderGroupCard(containerAtom: HTMLElement, group?: Group) {\n const container = containerAtom.querySelector('.groups-container') as HTMLElement;\n if (!container) return;\n const html = group\n ? this._fillTemplate(groupCardTemplate, {\n groupId: group.id,\n imageUrl: group.image_url,\n name: group.name,\n price: String(group.price),\n count: String(group.count),\n })\n : emptyGroupTemplate;\n container.innerHTML = html;\n this._syncService?.commit();\n }\n\n private _applyVisualSettings(atom: HTMLElement, settings: VisualSettings) {\n const card = atom.querySelector('.group-container') as HTMLElement | null;\n if (!card) return;\n const button = card.querySelector('.button-buy') as HTMLElement | null;\n if (settings.blockBorder !== undefined) {\n card.style.border = settings.blockBorder + 'px solid #ccc';\n }\n if (settings.blockPadding !== undefined) {\n card.style.padding = settings.blockPadding + 'px';\n }\n if (settings.cardBackgroundColor) card.style.backgroundColor = settings.cardBackgroundColor;\n if (settings.cardTextColor && button) button.style.color = settings.cardTextColor;\n if (settings.cardTextAlign) card.style.textAlign = settings.cardTextAlign;\n if (button) {\n if (settings.cardButtonColor) button.style.backgroundColor = settings.cardButtonColor;\n if (settings.cardButtonText) button.textContent = settings.cardButtonText;\n }\n this._syncService?.commit();\n }\n\n private _extractVisualSettings(atom: HTMLElement): VisualSettings {\n const card = atom.querySelector('.group-container') as HTMLElement | null;\n const button = card?.querySelector('.button-buy') as HTMLElement | null;\n const cardStyle = card && getComputedStyle(card);\n const buttonStyle = button && getComputedStyle(button);\n return {\n blockBorder: cardStyle?.border ? parseInt(cardStyle.border, 10) : 0,\n blockPadding: cardStyle?.padding ? parseInt(cardStyle.padding, 10) : 0,\n cardBackgroundColor: cardStyle?.backgroundColor || undefined,\n cardTextColor: buttonStyle?.color || cardStyle?.color || undefined,\n cardTextAlign: (cardStyle?.textAlign as VisualSettings['cardTextAlign']) || 'left',\n cardButtonText: button?.textContent || '',\n cardButtonColor: buttonStyle?.backgroundColor || undefined,\n };\n }\n\n private _getGroupId(atom: HTMLElement): string | undefined {\n const container = atom.querySelector('.group-container');\n return container?.getAttribute('data-group-id') || undefined;\n }\n\n init() {\n this._messageService = App.use('MessageService');\n this._syncService = App.use('SyncService');\n void this._ensureStyles();\n // Click on .product-atom in the email → tell app to open the settings panel.\n document.addEventListener('mousedown', this._onClick, true);\n this._disposables.push(\n this._messageService.addListener(Change_Product_Settings, this._onChangeSettings),\n );\n }\n\n dispose() {\n document.removeEventListener('mousedown', this._onClick, true);\n while (this._disposables.length > 0) {\n this._disposables.pop()?.dispose();\n }\n }\n}\n\nApp.use(ProductCardSandbox);\n",
3586
3597
  "../../project-templates/shared/partials/plugin-sandbox-minimal.eta": "import { App } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport type { IPlugin } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\n\nclass <%= it.pluginClassName %>Sandbox implements IPlugin {}\n\nApp.use(<%= it.pluginClassName %>Sandbox);\n",
3587
3598
  "../../project-templates/shared/partials/plugin-types-dts.eta": "declare module '*.html?raw' {\n const content: string;\n export default content;\n}\n\ndeclare module '*.css?raw' {\n const content: string;\n export default content;\n}\n",
3588
- "../../project-templates/shared/partials/plugin-vite-dev-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport VitePlugin from '<%= it.packageConfig.packageName %>/vite';\nimport PluginDev from '<%= it.packageConfig.packageName %>/vite/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n // <%= it.commentDevHostMode %>\n plugins: [\n PluginDev({ externals: false }),\n react(),\n VitePlugin(),\n ],\n optimizeDeps: {\n entries: ['index.html'],\n },\n server: {\n port: devPort,\n strictPort: true,\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n configure: (proxy) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
3599
+ "../../project-templates/shared/partials/plugin-vite-dev-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport VitePlugin from '<%= it.packageConfig.packageName %>/vite';\nimport PluginDev from '<%= it.packageConfig.packageName %>/vite/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n // <%= it.commentDevHostMode %>\n plugins: [\n PluginDev({ externals: false }),\n react(),\n VitePlugin(),\n ],\n optimizeDeps: {\n entries: ['index.html'],\n },\n server: {\n port: devPort,\n strictPort: true,\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n rewrite: (path) => path.replace(/^\\/api/, '') || '/',\n configure: (proxy) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
3589
3600
  "../../project-templates/shared/partials/plugin-vite-index-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> <%= it.indexHtmlTitleSuffix %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"<%= it.pluginViteIndexScriptSrc %>\"><\/script>\n </body>\n</html>\n",
3590
3601
  "../../project-templates/shared/partials/plugin-vite-plugin-build.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport PluginDev from '<%= it.packageConfig.packageName %>/vite/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst pluginDevExternals = <%~ it.importsModeLiteral %>;\n\nconst config = defineConfig({\n root: projectRoot,\n plugins: [\n PluginDev({ externals: pluginDevExternals }),\n ],\n build: {\n sourcemap: true,\n minify: true,\n outDir: 'dist',\n emptyOutDir: false,\n lib: {\n entry: path.resolve(projectRoot, 'src/index.ts'),\n formats: ['<%= it.pluginFormatVite %>'],\n name: '<%= it.pluginClassName %>',\n fileName: () => 'index.js',\n },\n },\n}) satisfies UserConfigExport;\n\nexport default config;\n",
3591
- "../../project-templates/shared/partials/plugin-vite-release-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport VitePlugin from '<%= it.packageConfig.packageName %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n plugins: [\n react(),\n VitePlugin(),\n ],\n server: {\n port: devPort,\n strictPort: true,\n open: '/release.html',\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n configure: (proxy) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
3602
+ "../../project-templates/shared/partials/plugin-vite-release-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport VitePlugin from '<%= it.packageConfig.packageName %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\n/**\n * Proxy shared by the dev server and the preview server: the production host serves built assets,\n * but still talks to the same API.\n */\nconst apiProxy = {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n rewrite: (path) => path.replace(/^\\/api/, '') || '/',\n configure: (proxy: any) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq: any) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n};\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n plugins: [\n react(),\n VitePlugin(),\n ],\n /**\n * Production host: `build` + `preview` instead of the dev server.\n *\n * The dev server hands every dependency to vite's optimizer, which bundles each one whole and on\n * purpose does not shake it. Weights seen there say nothing about the delivered result — only a\n * built host does.\n */\n build: {\n outDir: 'dist-host',\n emptyOutDir: true,\n rollupOptions: {\n input: path.resolve(projectRoot, 'release.html'),\n },\n },\n preview: {\n port: devPort,\n strictPort: true,\n open: '/release.html',\n proxy: apiProxy,\n },\n server: {\n port: devPort,\n strictPort: true,\n open: '/release.html',\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: apiProxy,\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
3592
3603
  "../../project-templates/shared/partials/plugin-vite-release-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> release host</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/dev-release.tsx\"><\/script>\n </body>\n</html>\n",
3593
3604
  "../../project-templates/shared/partials/plugin-vite-sandbox-build.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = defineConfig(({ mode }) => ({\n root: projectRoot,\n build: {\n sourcemap: true,\n minify: mode === 'production',\n outDir: mode === 'development' ? 'public' : 'dist',\n emptyOutDir: false,\n lib: {\n entry: path.resolve(projectRoot, 'src/sandbox/index.ts'),\n formats: ['iife'],\n name: '<%= it.pluginClassName %>Sandbox',\n fileName: () => 'sandbox.js',\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
3594
- "../../project-templates/shared/partials/plugin-webpack-dev-host-legacy.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n\n\n<%~ include('plugin-wp-legacy-externals', it) %>\n\n\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n externals: getExternals(),\n\n // <%= it.commentDevHostMode %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
3595
- "../../project-templates/shared/partials/plugin-webpack-dev-host-modern.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Configuration } from 'webpack';\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport PluginDev from '<%= it.packageConfig.packageName %>/webpack/pluginDev';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n ? Number(process.env.PLUGIN_DEV_PORT)\n : 'auto';\n\nconst config = {\n mode: 'development',\n devtool: 'eval-source-map',\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n // <%= it.commentDevHostMode %>\n plugins: [\n new WebpackPlugin(),\n new PluginDev({ externals: false }),\n ],\n output: {\n filename: 'dev.js',\n path: path.resolve(projectRoot, 'dev-build'),\n publicPath: '/',\n },\n devServer: {\n static: [\n { directory: path.resolve(projectRoot, 'public') },\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n ],\n port: devServerPort,\n hot: false,\n liveReload: true,\n allowedHosts: 'all',\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n onProxyReq: (proxyReq) => {\n // <%= it.commentApiProxy %>\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n },\n },\n ],\n },\n} satisfies Configuration;\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
3605
+ "../../project-templates/shared/partials/plugin-webpack-dev-host-legacy.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n\n\n<%~ include('plugin-wp-legacy-externals', it) %>\n\n\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n externals: getExternals(),\n\n // <%= it.commentDevHostMode %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
3606
+ "../../project-templates/shared/partials/plugin-webpack-dev-host-modern.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Configuration } from 'webpack';\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport PluginDev from '<%= it.packageConfig.packageName %>/webpack/pluginDev';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n ? Number(process.env.PLUGIN_DEV_PORT)\n : 'auto';\n\nconst config = {\n mode: 'development',\n devtool: 'eval-source-map',\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n // <%= it.commentDevHostMode %>\n plugins: [\n new WebpackPlugin(),\n new PluginDev({ externals: false }),\n ],\n output: {\n filename: 'dev.js',\n path: path.resolve(projectRoot, 'dev-build'),\n publicPath: '/',\n },\n devServer: {\n static: [\n { directory: path.resolve(projectRoot, 'public') },\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n ],\n port: devServerPort,\n hot: false,\n liveReload: true,\n allowedHosts: 'all',\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n onProxyReq: (proxyReq) => {\n // <%= it.commentApiProxy %>\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n },\n },\n ],\n },\n} satisfies Configuration;\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
3596
3607
  "../../project-templates/shared/partials/plugin-webpack-dev-host.eta": "<% if (it.isLegacyWebpack) { %><%~ include('plugin-webpack-dev-host-legacy', it) %><% } else { %><%~ include('plugin-webpack-dev-host-modern', it) %><% } %>\n",
3597
3608
  "../../project-templates/shared/partials/plugin-webpack-index-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> <%= it.indexHtmlTitleSuffix %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script src=\"<%= it.webpackIndexScriptSrc %>\"><\/script>\n </body>\n</html>\n",
3598
3609
  "../../project-templates/shared/partials/plugin-webpack-plugin-build.eta": "<% if (it.isLegacyWebpack) { %>\n<% if (it.pluginFormat === 'umd') { %><%~ include('plugin-wp-legacy-umd', it) %><% } else { %><%~ include('plugin-wp-legacy-module', it) %><% } %>\n<% } else { %>\n<% if (it.pluginFormat === 'umd') { %><%~ include('plugin-wp-modern-umd', it) %><% } else { %><%~ include('plugin-wp-modern-module', it) %><% } %>\n<% } %>\n",
3599
- "../../project-templates/shared/partials/plugin-webpack-release-host.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n<% if (it.isLegacyWebpack) { %>\n<%~ include('plugin-wp-legacy-externals', it) %>\n<% } %>\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev-release.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n<% if (it.isLegacyWebpack) { %>\n\n externals: getExternals(),\n\n<% } %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n open: '/release.html',\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n\n",
3610
+ "../../project-templates/shared/partials/plugin-webpack-release-host.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n<% if (it.isLegacyWebpack) { %>\n<%~ include('plugin-wp-legacy-externals', it) %>\n<% } %>\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev-release.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n<% if (it.isLegacyWebpack) { %>\n\n externals: getExternals(),\n\n<% } %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n open: '/release.html',\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n\n",
3600
3611
  "../../project-templates/shared/partials/plugin-webpack-release-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> release host</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script src=\"<%= it.webpackIndexScriptSrc %>\"><\/script>\n </body>\n</html>\n",
3601
3612
  "../../project-templates/shared/partials/plugin-webpack-sandbox-build.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Configuration } from 'webpack';\n\ninterface WebpackArgv {\n mode?: string;\n}\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = (_env: Record<string, never>, argv: WebpackArgv = {}) => {\n const isDev = argv.mode !== 'production';\n\n return {\n mode: isDev ? 'development' : 'production',\n devtool: 'source-map',\n entry: path.resolve(projectRoot, 'src/sandbox/index.ts'),\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n optimization: {\n minimize: !isDev,\n },\n output: {\n filename: 'sandbox.js',\n path: path.resolve(projectRoot, isDev ? 'public' : 'dist'),\n clean: false,\n iife: true,\n },\n } satisfies Configuration;\n};\n\nexport default config;\n",
3602
3613
  "../../project-templates/shared/partials/plugin-wp-legacy-externals.eta": "type LegacyExternalValue = string | string[];\ntype LegacyExternals = Record<string, LegacyExternalValue>;\n\nfunction readJsonSync(relativePath: string): LegacyExternals {\n return JSON.parse(fs.readFileSync(path.resolve(projectRoot, relativePath), 'utf8')) as LegacyExternals;\n}\n\nfunction getExternal(packageName: string): LegacyExternals {\n try {\n return readJsonSync(`node_modules/${packageName}/externals.json`);\n } catch {\n return {};\n }\n}\n\nfunction mergeLegacyExternals(): LegacyExternals {\n return {\n ...getExternal('<%= it.packageConfig.extensionsApiPackageName %>'),\n ...getExternal('<%= it.packageConfig.extensionsReactPackageName %>'),\n ...getExternal('<%= it.packageConfig.extensionsSandboxPackageName %>'),\n ...getExternal('<%= it.packageConfig.uiKitPackageName %>'),\n };\n}\n\n/** simple_plugin style: raw externals.json merge (`[\"promise __ns__.modules\", \"Export\"]`). */\nfunction getExternals(): LegacyExternals {\n return mergeLegacyExternals();\n}\n",
@@ -3613,36 +3624,36 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3613
3624
  "../../project-templates/shared/partials/stand-dev-host-vite-subpath.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createViteStandConfig } from './lib/createViteStandConfig.ts';\nimport VitePlugin from '<%~ it.standVitePluginPackage %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createViteStandConfig({\n projectRoot,\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n closedLoop: <%= it.standClosedLoop %>,\n plugins: [VitePlugin({ outputFolder: <%~ JSON.stringify(it.standViteOutputFolder) %> })],\n extraServerMiddlewares: [],\n build: {\n rollupOptions: {\n input: path.resolve(projectRoot, 'advanced', 'subpath', 'index.html'),\n },\n },\n});\n",
3614
3625
  "../../project-templates/shared/partials/stand-dev-host-vite-umd.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createRequire } from 'node:module';\nimport { createViteStandConfig } from './lib/createViteStandConfig.ts';\nimport { createUmdServeMiddleware } from './lib/umdServeMiddleware.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst require = createRequire(import.meta.url);\nconst umdPackageRoot = path.dirname(require.resolve('<%~ it.packageName %>/package.json'));\nconst umdMw = createUmdServeMiddleware({ packageRoot: umdPackageRoot, publicPath: <%~ JSON.stringify(it.standUmdPublicPath) %> });\n\nexport default createViteStandConfig({\n projectRoot,\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n closedLoop: <%= it.standClosedLoop %>,\n plugins: [],\n extraServerMiddlewares: [umdMw],\n});\n",
3615
3626
  "../../project-templates/shared/partials/stand-dev-host-vite.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createViteStandConfig } from './lib/createViteStandConfig.ts';\nimport VitePlugin from '<%~ it.standVitePluginPackage %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createViteStandConfig({\n projectRoot,\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n closedLoop: <%= it.standClosedLoop %>,\n plugins: [VitePlugin()],\n extraServerMiddlewares: [],\n});\n\n",
3616
- "../../project-templates/shared/partials/stand-dev-host-webpack-subpath.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\nimport <%= it.standWebpackPluginClassName %> from '<%~ it.packageName %>/webpack';\n\nconst umdOpts = null;\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [new <%= it.standWebpackPluginClassName %>({ publicPath: <%~ JSON.stringify(it.standRoutePath) %> })],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public', 'advanced', 'subpath'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n umd: umdOpts,\n});\n\nexport default config;\n",
3617
- "../../project-templates/shared/partials/stand-dev-host-webpack-umd.eta": "import path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst require = createRequire(import.meta.url);\nconst umdPackageRoot = path.dirname(require.resolve(<%~ JSON.stringify(it.packageName + '/package.json') %>));\nconst umdOpts = { packageRoot: umdPackageRoot, publicPath: <%~ JSON.stringify(it.standUmdPublicPath) %> };\n\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n<% if (it.standClosedLoop) { %>\n proxy: [],\n<% } else { %>\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n<% } %>\n umd: umdOpts,\n});\n\nexport default config;\n",
3618
- "../../project-templates/shared/partials/stand-dev-host-webpack.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\nimport <%= it.standWebpackPluginClassName %> from '<%~ it.packageName %>/webpack';\n\nconst umdOpts = null;\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [new <%= it.standWebpackPluginClassName %>()],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n<% if (it.standClosedLoop) { %>\n proxy: [],\n<% } else { %>\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n<% } %>\n umd: umdOpts,\n});\n\nexport default config;\n",
3627
+ "../../project-templates/shared/partials/stand-dev-host-webpack-subpath.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\nimport <%= it.standWebpackPluginClassName %> from '<%~ it.packageName %>/webpack';\n\nconst umdOpts = null;\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [new <%= it.standWebpackPluginClassName %>({ publicPath: <%~ JSON.stringify(it.standRoutePath) %> })],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public', 'advanced', 'subpath'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n umd: umdOpts,\n});\n\nexport default config;\n",
3628
+ "../../project-templates/shared/partials/stand-dev-host-webpack-umd.eta": "import path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst require = createRequire(import.meta.url);\nconst umdPackageRoot = path.dirname(require.resolve(<%~ JSON.stringify(it.packageName + '/package.json') %>));\nconst umdOpts = { packageRoot: umdPackageRoot, publicPath: <%~ JSON.stringify(it.standUmdPublicPath) %> };\n\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n<% if (it.standClosedLoop) { %>\n proxy: [],\n<% } else { %>\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n<% } %>\n umd: umdOpts,\n});\n\nexport default config;\n",
3629
+ "../../project-templates/shared/partials/stand-dev-host-webpack.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\nimport <%= it.standWebpackPluginClassName %> from '<%~ it.packageName %>/webpack';\n\nconst umdOpts = null;\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [new <%= it.standWebpackPluginClassName %>()],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n<% if (it.standClosedLoop) { %>\n proxy: [],\n<% } else { %>\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n<% } %>\n umd: umdOpts,\n});\n\nexport default config;\n",
3619
3630
  "../../project-templates/shared/partials/stand-dev-storage-middleware.eta": "import fs from 'node:fs';\nimport path from 'node:path';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport formidable from 'formidable';\n\ninterface StorageItem {\n id: string;\n name: string;\n folderId: string;\n isFolder: boolean;\n size?: number;\n date: string;\n type?: string;\n url?: string;\n}\n\ninterface StorageRequestBody {\n name?: string;\n newName?: string;\n parentId?: string;\n parentid?: string;\n folderId?: string;\n targetFolderId?: string;\n url?: string;\n path?: string;\n id?: string;\n}\n\nconst STORAGE_DIR = path.resolve(process.cwd(), 'storage');\nconst BASE = '/dev-storage';\n\nfunction ensureDir(dir: string): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n}\n\nfunction sanitizePath(relativePath: string): string {\n if (!relativePath || relativePath === '/' || relativePath === '.') {\n return '';\n }\n\n return path.normalize(relativePath).replace(/^(\\.\\.(\\/|\\\\|$))+/, '').replace(/\\\\/g, '/').trim();\n}\n\nfunction resolvePath(relativePath: string): string | null {\n const safe = sanitizePath(relativePath);\n const full = path.join(STORAGE_DIR, safe);\n const resolved = path.resolve(full);\n if (!resolved.startsWith(path.resolve(STORAGE_DIR))) {\n return null;\n }\n\n return resolved;\n}\n\nfunction toFileItem(fullPath: string): StorageItem {\n const stat = fs.statSync(fullPath);\n const name = path.basename(fullPath);\n const rel = path.relative(STORAGE_DIR, fullPath).replace(/\\\\/g, '/');\n const folderId = path.dirname(rel) === '.' ? '' : path.dirname(rel).replace(/\\\\/g, '/');\n\n return {\n id: rel,\n name,\n folderId,\n isFolder: stat.isDirectory(),\n size: stat.isFile() ? stat.size : undefined,\n date: stat.mtime.toISOString(),\n type: stat.isFile() ? getMimeType(name) : undefined,\n };\n}\n\nfunction getMimeType(name: string): string {\n const ext = path.extname(name).toLowerCase();\n const types = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.svg': 'image/svg+xml',\n '.pdf': 'application/pdf',\n '.zip': 'application/zip',\n } as const;\n\n return types[ext as keyof typeof types] || 'application/octet-stream';\n}\n\nfunction normalizeJsonBody(rawBody: string): StorageRequestBody {\n if (!rawBody) {\n return {};\n }\n\n const parsed = JSON.parse(rawBody) as Partial<Record<keyof StorageRequestBody, string>>;\n return {\n name: typeof parsed.name === 'string' ? parsed.name : undefined,\n newName: typeof parsed.newName === 'string' ? parsed.newName : undefined,\n parentId: typeof parsed.parentId === 'string' ? parsed.parentId : undefined,\n parentid: typeof parsed.parentid === 'string' ? parsed.parentid : undefined,\n folderId: typeof parsed.folderId === 'string' ? parsed.folderId : undefined,\n targetFolderId: typeof parsed.targetFolderId === 'string' ? parsed.targetFolderId : undefined,\n url: typeof parsed.url === 'string' ? parsed.url : undefined,\n path: typeof parsed.path === 'string' ? parsed.path : undefined,\n id: typeof parsed.id === 'string' ? parsed.id : undefined,\n };\n}\n\nfunction parseJsonBody(req: IncomingMessage): Promise<StorageRequestBody> {\n return new Promise((resolve) => {\n let body = '';\n req.on('data', (chunk: Buffer | string) => {\n body += typeof chunk === 'string' ? chunk : chunk.toString('utf8');\n });\n req.on('end', () => {\n try {\n resolve(normalizeJsonBody(body));\n } catch {\n resolve({});\n }\n });\n });\n}\n\nfunction sendJson<T>(res: ServerResponse, data: T, status = 200): void {\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(data));\n}\n\nfunction sendStorageError(res: ServerResponse, error: unknown, status = 500): void {\n const message = error instanceof Error ? error.message : String(error);\n sendJson(res, { error: message }, status);\n}\n\nfunction runStorageHandler(\n res: ServerResponse,\n handler: () => Promise<void>,\n): void {\n void handler().catch((error) => {\n sendStorageError(res, error);\n });\n}\n\nfunction resolveItemPath(body: StorageRequestBody, fallbackPath = ''): string {\n return (fallbackPath || body.path || body.id || '').trim();\n}\n\nfunction isValidItemName(name: string): boolean {\n return Boolean(name) && !/[\\\\/:*?\"<>|]/.test(name);\n}\n\nfunction sendItemsResponse(res: ServerResponse, items: StorageItem[]): void {\n sendJson(res, {\n items,\n pagination: { page: 1, limit: 1000, total: items.length, totalPages: 1 },\n });\n}\n\nasync function handleGetItems(_req: IncomingMessage, res: ServerResponse, url: string): Promise<void> {\n const folderId = (new URL(url, 'http://x').searchParams.get('folderId') || '').trim();\n const dir = folderId ? resolvePath(folderId) : path.resolve(STORAGE_DIR);\n if (!dir || !fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {\n sendItemsResponse(res, []);\n return;\n }\n\n const items = fs.readdirSync(dir).map((name) => toFileItem(path.join(dir, name)));\n sendItemsResponse(res, items);\n}\n\nasync function handleCreateFolder(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await parseJsonBody(req);\n const name = (body.name || '').trim();\n const parentId = (body.parentId ?? body.parentid ?? '').trim();\n if (!name || /[\\\\/:*?\"<>|]/.test(name)) {\n sendJson(res, { error: 'Invalid folder name' }, 400);\n return;\n }\n\n const parentDir = parentId ? resolvePath(parentId) : STORAGE_DIR;\n if (!parentDir || !fs.existsSync(parentDir)) {\n sendJson(res, { error: 'Parent folder not found' }, 404);\n return;\n }\n\n const folderPath = path.join(parentDir, name);\n ensureDir(folderPath);\n const rel = path.relative(STORAGE_DIR, folderPath).replace(/\\\\/g, '/');\n const folderId = path.dirname(rel) === '.' ? '' : path.dirname(rel).replace(/\\\\/g, '/');\n sendJson(res, {\n id: rel,\n name,\n folderId,\n isFolder: true,\n date: fs.statSync(folderPath).mtime.toISOString(),\n });\n}\n\nfunction readFormField(field: string | string[] | undefined): string {\n if (typeof field === 'string') {\n return field.trim();\n }\n\n if (Array.isArray(field) && typeof field[0] === 'string') {\n return field[0].trim();\n }\n\n return '';\n}\n\nasync function handleUpload(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const form = formidable({ multiples: true });\n const [fields, files] = await new Promise<[formidable.Fields, formidable.Files]>((resolve, reject) => {\n form.parse(req, (error, parsedFields, parsedFiles) => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve([parsedFields, parsedFiles]);\n });\n });\n\n const folderId = readFormField(fields.folderId);\n const targetDir = folderId ? resolvePath(folderId) : STORAGE_DIR;\n if (!targetDir || !fs.existsSync(targetDir)) {\n sendJson(res, { error: 'Folder not found' }, 404);\n return;\n }\n\n const fileEntries = Array.isArray(files.file)\n ? files.file\n : files.file\n ? [files.file]\n : [];\n const items: StorageItem[] = [];\n\n for (const file of fileEntries) {\n if (!file.filepath || !fs.existsSync(file.filepath)) {\n continue;\n }\n\n const originalName = file.originalFilename || file.newFilename || path.basename(file.filepath);\n const name = originalName.replace(/[\\\\/:*?\"<>|]/g, '_');\n const destination = path.join(targetDir, name);\n fs.copyFileSync(file.filepath, destination);\n\n const rel = path.relative(STORAGE_DIR, destination).replace(/\\\\/g, '/');\n const responseFolderId = path.dirname(rel) === '.' ? '' : path.dirname(rel).replace(/\\\\/g, '/');\n items.push({\n id: rel,\n name,\n folderId: responseFolderId,\n isFolder: false,\n size: fs.statSync(destination).size,\n date: fs.statSync(destination).mtime.toISOString(),\n type: getMimeType(name),\n });\n }\n\n if (items.length === 0) {\n sendJson(res, { error: 'No files received' }, 400);\n return;\n }\n\n sendJson(res, { items, success: true });\n}\n\nasync function handleUploadByUrl(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await parseJsonBody(req);\n const url = (body.url || '').trim();\n const folderId = (body.folderId || '').trim();\n if (!url) {\n sendJson(res, { error: 'Missing url' }, 400);\n return;\n }\n\n const targetDir = folderId ? resolvePath(folderId) : STORAGE_DIR;\n if (!targetDir || !fs.existsSync(targetDir)) {\n sendJson(res, { error: 'Folder not found' }, 404);\n return;\n }\n\n try {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error('Fetch failed');\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n const name = (url.split('/').pop() || 'file').split('?')[0] || 'file';\n const destination = path.join(targetDir, name);\n fs.writeFileSync(destination, buffer);\n\n const rel = path.relative(STORAGE_DIR, destination).replace(/\\\\/g, '/');\n const responseFolderId = path.dirname(rel) === '.' ? '' : path.dirname(rel).replace(/\\\\/g, '/');\n sendJson(res, {\n id: rel,\n name,\n folderId: responseFolderId,\n isFolder: false,\n size: buffer.length,\n date: fs.statSync(destination).mtime.toISOString(),\n type: getMimeType(name),\n url: `/dev-storage/file/${encodeURIComponent(rel)}`,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n sendJson(res, { error: message }, 500);\n }\n}\n\nasync function handleDeleteItem(req: IncomingMessage, res: ServerResponse, pathOverride = ''): Promise<void> {\n let targetPath = pathOverride.trim();\n\n if (!targetPath) {\n const pathParam = (new URL(req.url || '/', 'http://x').searchParams.get('path') || '').trim();\n const body = await parseJsonBody(req);\n targetPath = pathParam || (body.path || body.id || '').trim();\n }\n\n if (!targetPath) {\n sendJson(res, { error: 'Missing path' }, 400);\n return;\n }\n\n const fullPath = resolvePath(targetPath);\n if (!fullPath || !fs.existsSync(fullPath)) {\n sendJson(res, { error: 'Not found' }, 404);\n return;\n }\n\n fs.rmSync(fullPath, { recursive: true });\n sendJson(res, { success: true });\n}\n\nasync function handleRenameItem(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await parseJsonBody(req);\n const targetPath = resolveItemPath(body);\n const newName = (body.newName || body.name || '').trim();\n if (!targetPath) {\n sendJson(res, { error: 'Missing path' }, 400);\n return;\n }\n if (!isValidItemName(newName)) {\n sendJson(res, { error: 'Invalid item name' }, 400);\n return;\n }\n\n const fullPath = resolvePath(targetPath);\n if (!fullPath || !fs.existsSync(fullPath)) {\n sendJson(res, { error: 'Not found' }, 404);\n return;\n }\n\n const destination = path.join(path.dirname(fullPath), newName);\n if (fs.existsSync(destination)) {\n sendJson(res, { error: 'Target already exists' }, 409);\n return;\n }\n\n fs.renameSync(fullPath, destination);\n sendJson(res, toFileItem(destination));\n}\n\nasync function handleMoveItem(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await parseJsonBody(req);\n const targetPath = resolveItemPath(body);\n const folderId = (body.targetFolderId ?? body.folderId ?? '').trim();\n if (!targetPath) {\n sendJson(res, { error: 'Missing path' }, 400);\n return;\n }\n\n const fullPath = resolvePath(targetPath);\n if (!fullPath || !fs.existsSync(fullPath)) {\n sendJson(res, { error: 'Not found' }, 404);\n return;\n }\n\n const targetDir = folderId ? resolvePath(folderId) : STORAGE_DIR;\n if (!targetDir || !fs.existsSync(targetDir) || !fs.statSync(targetDir).isDirectory()) {\n sendJson(res, { error: 'Target folder not found' }, 404);\n return;\n }\n\n const destination = path.join(targetDir, path.basename(fullPath));\n if (fs.existsSync(destination)) {\n sendJson(res, { error: 'Target already exists' }, 409);\n return;\n }\n\n fs.renameSync(fullPath, destination);\n sendJson(res, toFileItem(destination));\n}\n\nfunction handleGetFile(res: ServerResponse, pathPart: string): void {\n const decoded = decodeURIComponent(pathPart);\n const fullPath = resolvePath(decoded);\n if (!fullPath || !fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {\n res.writeHead(404);\n res.end();\n return;\n }\n\n const stream = fs.createReadStream(fullPath);\n const mime = getMimeType(path.basename(fullPath));\n res.writeHead(200, { 'Content-Type': mime });\n stream.pipe(res);\n}\n\nexport default function devStorageMiddleware() {\n ensureDir(STORAGE_DIR);\n\n return (req: IncomingMessage, res: ServerResponse, next: () => void): void => {\n if (!req.url || !req.url.startsWith(BASE)) {\n next();\n return;\n }\n\n const pathPart = req.url.slice(BASE.length).replace(/^\\//, '');\n const method = req.method || 'GET';\n\n if (method === 'GET' && (pathPart === 'items' || pathPart.startsWith('items?'))) {\n runStorageHandler(res, () => handleGetItems(req, res, req.url || ''));\n return;\n }\n\n if (method === 'GET' && pathPart.startsWith('file/')) {\n handleGetFile(res, pathPart.slice(5));\n return;\n }\n\n if (method === 'POST' && pathPart === 'folder') {\n runStorageHandler(res, () => handleCreateFolder(req, res));\n return;\n }\n\n if (method === 'POST' && pathPart === 'upload') {\n runStorageHandler(res, () => handleUpload(req, res));\n return;\n }\n\n if (method === 'POST' && pathPart === 'upload-by-url') {\n runStorageHandler(res, () => handleUploadByUrl(req, res));\n return;\n }\n\n if (method === 'POST' && pathPart === 'rename') {\n runStorageHandler(res, () => handleRenameItem(req, res));\n return;\n }\n\n if (method === 'POST' && pathPart === 'move') {\n runStorageHandler(res, () => handleMoveItem(req, res));\n return;\n }\n\n if (method === 'DELETE' && pathPart === 'item') {\n runStorageHandler(res, () => handleDeleteItem(req, res));\n return;\n }\n\n if (method === 'DELETE' && pathPart.startsWith('item/')) {\n runStorageHandler(res, () => handleDeleteItem(req, res, decodeURIComponent(pathPart.slice(5))));\n return;\n }\n\n next();\n };\n}\n",
3620
3631
  "../../project-templates/shared/partials/stand-editor-config-resource-proxy.eta": "import type { Config } from '<%~ it.packageName %>';\nimport { demoStandConfig } from './demoStandConfig';\n\nconst defaultCdnBase = <%~ JSON.stringify(it.standCdnUrl) %>.replace(/\\/+$/, '');\nconst cdnProjectId = demoStandConfig.cdnSampleProjectId;\nconst proxyCdnEnabled = <%= JSON.stringify(it.standProxyCdnEnabled) %>;\n\nfunction getProxyBase() {\n const origin = typeof window !== 'undefined' ? window.location.origin : 'http://localhost:<%= it.standDevServerPort %>';\n return `${origin}/proxy`;\n}\n\nfunction buildProxyRule(proxyBase: string, routeKey: string) {\n return {\n proxyBase: `${proxyBase}/${routeKey}`,\n rewrite: '{path}?proxy_url={origin}{search}{hash}',\n };\n}\n\nconst directHostDemoHostname = <%~ JSON.stringify(it.resourceProxyDemoDirectHost) %>;\n\nfunction createResourceProxyEditorConfig(): Partial<Config> {\n const proxyBase = getProxyBase();\n\n const resourceProxy = [\n {\n id: 'cdn',\n match: `${defaultCdnBase}/${cdnProjectId}/{path}`,\n proxyBase: `${proxyBase}/cdn`,\n rewrite: '{matched_path}{search}{hash}',\n },\n {\n id: 'stock-images-api',\n match: 'https://api.unsplash.com/{path}',\n ...buildProxyRule(proxyBase, 'stock-images-api'),\n },\n {\n id: 'stock-images-cdn',\n match: 'https://images.unsplash.com/{path}',\n ...buildProxyRule(proxyBase, 'stock-images-cdn'),\n },\n {\n id: 'generic-primary',\n ...buildProxyRule(proxyBase, 'generic-primary'),\n },\n {\n id: 'generic-backup',\n ...buildProxyRule(proxyBase, 'generic-backup'),\n },\n ];\n\n const backendProxy = [\n {\n id: 'em-files-primary',\n match: ['{origin}/api/wp-json/em-files/{path}', '{origin}/wp-json/em-files/{path}'],\n proxyBase: `${proxyBase}/em-files-primary`,\n rewrite: '{matched_path}{search}{hash}',\n },\n {\n id: 'em-files-backup',\n match: ['{origin}/api/wp-json/em-files/{path}', '{origin}/wp-json/em-files/{path}'],\n proxyBase: `${proxyBase}/em-files-backup`,\n rewrite: '{matched_path}{search}{hash}',\n },\n {\n id: 'ai-primary',\n match: ['{origin}/api/wp-json/ai-generator/{path}', '{origin}/wp-json/ai-generator/{path}'],\n proxyBase: `${proxyBase}/ai-primary`,\n rewrite: '{matched_path}{search}{hash}',\n },\n {\n id: 'ai-backup',\n match: ['{origin}/api/wp-json/ai-generator/{path}', '{origin}/wp-json/ai-generator/{path}'],\n proxyBase: `${proxyBase}/ai-backup`,\n rewrite: '{matched_path}{search}{hash}',\n },\n ];\n\n return {\n mode: 'pro',\n locale: <%~ JSON.stringify(it.standEditorLocale) %>,\n imageCenterStockEnabled: true,\n imageCenterGifEnabled: true,\n imageCenterIconStockEnabled: true,\n imageCenterLocalUploadEnabled: true,\n resourceProxy,\n backendProxy,\n resourceProxyPolicy: {\n inheritDefaults: false,\n directHosts: [directHostDemoHostname],\n recoveryTtlMs: 300000,\n proxyBlobFetch: true,\n proxyImgSrc: true,\n // Intentional for lab: same-origin /dev-storage assets also exercise /proxy routes.\n proxySameOrigin: true,\n proxyCdn: proxyCdnEnabled,\n proxyStockImages: true,\n },\n backendProxyPolicy: {\n proxyEmFiles: true,\n proxyAi: true,\n },\n fileManager: {\n previewFallbackToFileUrl: true,\n dedupeUploadNamesOnClient: true,\n },\n };\n}\n\nexport const editorConfig = createResourceProxyEditorConfig();\n",
3621
3632
  "../../project-templates/shared/partials/stand-editor-config.eta": "import type { Config } from '<%~ it.packageName %>';\n\nconst mergeTagItems = [\n {\n label: 'Profile',\n value: 'profile',\n children: [\n { label: 'First name', value: 'profile.firstName' },\n { label: 'Last name', value: 'profile.lastName' },\n { label: 'Email', value: 'profile.email' },\n ],\n },\n {\n label: 'Company',\n value: 'company',\n children: [\n { label: 'Name', value: 'company.name' },\n { label: 'Industry', value: 'company.industry' },\n { label: 'Website', value: 'company.website' },\n ],\n },\n {\n label: 'Campaign',\n value: 'campaign',\n children: [\n { label: 'Title', value: 'campaign.title' },\n { label: 'Promo code', value: 'campaign.promoCode' },\n { label: 'CTA URL', value: 'campaign.ctaUrl' },\n ],\n },\n];\n\nconst baseEditorConfig = {\n theme: 'light',\n locale: 'ru_RU',\n autosaveTimeout: 15000,\n commonStylesEnabled: true,\n mergeTagsShow: true,\n imageCenterFileManagerView: true,\n fileManager: {\n defaultFolderName: 'demo-assets',\n enableMoveFolder: true,\n enableEdit: true,\n enableTrash: true,\n enableCopyFile: true,\n enableCopyFolder: true,\n },\n mergeTags: {\n syntax: ['{{' + '%value%' + '}}'],\n items: mergeTagItems,\n },\n} satisfies Partial<Config>;\n\nexport function createEditorConfig(): Partial<Config> {\n return baseEditorConfig;\n}\n\nexport const editorConfig = createEditorConfig();\n",
3622
- "../../project-templates/shared/partials/stand-ensure-locale-script.eta": "import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { editorConfig } from '../src/dev/editorConfig';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst locale = String(editorConfig.locale || '').trim();\nconst localeDir = path.resolve(projectRoot, 'public', 'locales');\nconst localeFilePath = path.resolve(localeDir, `${locale}.po`);\nconst apiBaseUrl = <%~ JSON.stringify(it.standClosedLoopBaseUrl) %>;\nconst localeUrl = new URL(`wp-json/translations/v1/react_app/${encodeURIComponent(locale)}`, `${apiBaseUrl.replace(/\\/+$/, '')}/`).href;\n\nfunction normalizeLocaleText(text: string): string {\n const normalized = text.replace(/\\uFEFF/g, '').replace(/\\r\\n?/g, '\\n');\n return normalized.endsWith('\\n') ? normalized : `${normalized}\\n`;\n}\n\nfunction isPoCatalog(text: string): boolean {\n const normalized = normalizeLocaleText(text);\n return normalized.startsWith('msgid \"\"\\nmsgstr \"\"\\n') || normalized.includes('\\n\"Plural-Forms:');\n}\n\nasync function ensureLocaleFile(): Promise<void> {\n if (!locale) {\n throw new Error('editorConfig.locale is required for the closed-loop stand.');\n }\n\n try {\n const existing = await fs.readFile(localeFilePath, 'utf8');\n if (existing.trim() && isPoCatalog(existing)) {\n console.log(`[stand-locale] using existing public/locales/${locale}.po`);\n return;\n }\n } catch {\n // Download on first start when the file is absent.\n }\n\n const res = await fetch(localeUrl);\n if (!res.ok) {\n throw new Error(`Failed to download locale ${locale}: ${res.status} ${res.statusText}`);\n }\n\n const localeText = await res.text();\n if (!isPoCatalog(localeText)) {\n throw new Error(`Downloaded locale ${locale} is not a gettext catalog.`);\n }\n\n await fs.mkdir(localeDir, { recursive: true });\n await fs.writeFile(localeFilePath, normalizeLocaleText(localeText), 'utf8');\n console.log(`[stand-locale] saved public/locales/${locale}.po`);\n}\n\nensureLocaleFile().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[stand-locale] ${message}`);\n process.exit(1);\n});\n",
3623
- "../../project-templates/shared/partials/stand-get-auth-token.eta": "import { hasOAuthCredentials, oauthCredentials } from './oauthCredentials';\n\nexport async function getAuthToken() {\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingOAuthCredentials) %>);\n }\n\n const formData = new FormData();\n formData.append('grant_type', 'client_credentials');\n formData.append('client_id', oauthCredentials.clientId);\n formData.append('client_secret', oauthCredentials.clientSecret);\n\n const response = await fetch('/api?oauth=token', {\n method: 'POST',\n body: formData,\n redirect: 'follow',\n });\n const payload = await response.json().catch(() => null);\n\n if (!response.ok || !payload || typeof payload.access_token !== 'string') {\n throw new Error(\n <%~ JSON.stringify(it.devAuthOauthTokenFetchFailed) %>,\n );\n }\n\n return payload.access_token;\n}\n",
3624
- "../../project-templates/shared/partials/stand-host-closed.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { hasStandaloneCredentials, standaloneCredentials } from './dev/standaloneCredentials';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\nconst baseUrl = <%~ JSON.stringify(it.standClosedLoopBaseUrl) %>;\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-closed-loop',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n if (!hasStandaloneCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingStandaloneCredentials) %>);\n }\n\n const instance = await <%= it.standProductApiName %>.init({\n standaloneKey: standaloneCredentials.standaloneKey,\n baseUrl,\n handleReadLocale: async (locale: string) => {\n const url = `/locales/${encodeURIComponent(locale)}.po`;\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`Locale file not found: ${url}`);\n }\n return res.text();\n },\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostClosedLoopDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" />\n </>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3633
+ "../../project-templates/shared/partials/stand-ensure-locale-script.eta": "import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { editorConfig } from '../src/dev/editorConfig';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst locale = String(editorConfig.locale || '').trim();\nconst localeDir = path.resolve(projectRoot, 'public', 'locales');\nconst localeFilePath = path.resolve(localeDir, `${locale}.po`);\nconst apiBaseUrl = <%~ JSON.stringify(it.standClosedLoopBaseUrl) %>;\nconst localeUrl = new URL(`wp-json/translations/v1/react_app/${encodeURIComponent(locale)}`, `${apiBaseUrl.replace(/\\/+$/, '')}/`).href;\n\nfunction normalizeLocaleText(text: string): string {\n const normalized = text.replace(/\\uFEFF/g, '').replace(/\\r\\n?/g, '\\n');\n return normalized.endsWith('\\n') ? normalized : `${normalized}\\n`;\n}\n\nfunction isPoCatalog(text: string): boolean {\n const normalized = normalizeLocaleText(text);\n return normalized.startsWith('msgid \"\"\\nmsgstr \"\"\\n') || normalized.includes('\\n\"Plural-Forms:');\n}\n\n// The translations endpoint answers with application/json: the .po text arrives as a JSON string.\nfunction unwrapJsonCatalog(body: string, contentType: string | null): string {\n const trimmed = body.trim();\n const isJson = /\\bjson\\b/i.test(contentType || '') || trimmed.startsWith('\"');\n if (!isJson) {\n return body;\n }\n try {\n const parsed: unknown = JSON.parse(trimmed);\n return typeof parsed === 'string' ? parsed : body;\n } catch {\n return body;\n }\n}\n\nasync function ensureLocaleFile(): Promise<void> {\n if (!locale) {\n throw new Error('editorConfig.locale is required for the closed-loop stand.');\n }\n\n try {\n const existing = await fs.readFile(localeFilePath, 'utf8');\n if (existing.trim() && isPoCatalog(existing)) {\n console.log(`[stand-locale] using existing public/locales/${locale}.po`);\n return;\n }\n } catch {\n // Download on first start when the file is absent.\n }\n\n const res = await fetch(localeUrl);\n if (!res.ok) {\n throw new Error(`Failed to download locale ${locale}: ${res.status} ${res.statusText}`);\n }\n\n const localeText = unwrapJsonCatalog(await res.text(), res.headers.get('content-type'));\n if (!isPoCatalog(localeText)) {\n throw new Error(`Downloaded locale ${locale} is not a gettext catalog.`);\n }\n\n await fs.mkdir(localeDir, { recursive: true });\n await fs.writeFile(localeFilePath, normalizeLocaleText(localeText), 'utf8');\n console.log(`[stand-locale] saved public/locales/${locale}.po`);\n}\n\nensureLocaleFile().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[stand-locale] ${message}`);\n process.exit(1);\n});\n",
3634
+ "../../project-templates/shared/partials/stand-get-auth-token.eta": "import { hasOAuthCredentials, oauthCredentials } from './oauthCredentials';\n\nexport async function getAuthToken() {\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingOAuthCredentials) %>);\n }\n\n const formData = new URLSearchParams();\n formData.append('grant_type', 'client_credentials');\n formData.append('client_id', oauthCredentials.clientId);\n formData.append('client_secret', oauthCredentials.clientSecret);\n\n const response = await fetch('/api/oauth/token', {\n method: 'POST',\n body: formData,\n redirect: 'follow',\n });\n const payload = await response.json().catch(() => null);\n\n if (!response.ok || !payload || typeof payload.access_token !== 'string') {\n throw new Error(\n <%~ JSON.stringify(it.devAuthOauthTokenFetchFailed) %>,\n );\n }\n\n return payload.access_token;\n}\n",
3635
+ "../../project-templates/shared/partials/stand-host-closed.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { hasStandaloneCredentials, standaloneCredentials } from './dev/standaloneCredentials';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\nconst baseUrl = <%~ JSON.stringify(it.standClosedLoopBaseUrl) %>;\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-closed-loop',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n if (!hasStandaloneCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingStandaloneCredentials) %>);\n }\n\n const instance = await <%= it.standProductApiName %>.init({\n standaloneKey: standaloneCredentials.standaloneKey,\n baseUrl,\n handleReadLocale: async (locale: string) => {\n const url = `/locales/${encodeURIComponent(locale)}.po`;\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`Locale file not found: ${url}`);\n }\n return res.text();\n },\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostClosedLoopDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3625
3636
  "../../project-templates/shared/partials/stand-host-dev-server-webpack.eta": "/**\n * webpack-dev-server 5.2+ blocks cross-site script loads (403) unless assets\n * declare CORP cross-origin. Required for sandboxed editor iframe (no allow-same-origin).\n */\nexport const HOST_EDITOR_ASSET_HEADERS = Object.freeze({\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n});\n\ntype DevServerConfig = {\n allowedHosts?: unknown;\n headers?: Record<string, string>;\n devMiddleware?: { headers?: Record<string, string> } & Record<string, unknown>;\n setupMiddlewares?: SetupMiddlewaresFn;\n} & Record<string, unknown>;\n\ntype WebpackConfig = {\n devServer?: DevServerConfig;\n};\n\ntype DevServerLike = {\n app?: {\n use: (middleware: HostEditorHeaderMiddleware) => void;\n };\n};\n\ntype HostEditorHeaderMiddleware = (\n req: unknown,\n res: { setHeader: (name: string, value: string) => void },\n next: () => void,\n) => void;\n\ntype SetupMiddlewaresFn = (\n middlewares: unknown[],\n devServer: DevServerLike,\n) => unknown[];\n\nexport function createHostEditorDevServerHeaderMiddleware(): HostEditorHeaderMiddleware {\n return (_req, res, next) => {\n for (const [key, value] of Object.entries(HOST_EDITOR_ASSET_HEADERS)) {\n res.setHeader(key, value);\n }\n next();\n };\n}\n\nexport function chainHostEditorDevServerSetupMiddleware(\n setupMiddlewares?: SetupMiddlewaresFn,\n): SetupMiddlewaresFn {\n return (middlewares, devServer) => {\n devServer.app?.use(createHostEditorDevServerHeaderMiddleware());\n if (typeof setupMiddlewares === 'function') {\n return setupMiddlewares(middlewares, devServer);\n }\n return middlewares;\n };\n}\n\nexport function mergeHostEditorDevServer(config: WebpackConfig): WebpackConfig {\n const existing = config.devServer || {};\n const existingDevMiddleware = existing.devMiddleware || {};\n\n config.devServer = {\n ...existing,\n allowedHosts: existing.allowedHosts ?? 'all',\n headers: {\n ...(existing.headers || {}),\n ...HOST_EDITOR_ASSET_HEADERS,\n },\n devMiddleware: {\n ...existingDevMiddleware,\n headers: {\n ...(existingDevMiddleware.headers || {}),\n ...HOST_EDITOR_ASSET_HEADERS,\n },\n },\n setupMiddlewares: chainHostEditorDevServerSetupMiddleware(existing.setupMiddlewares),\n };\n\n return config;\n}\n",
3626
- "../../project-templates/shared/partials/stand-host-oauth-default-banners.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-default-banners',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ minHeight: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n<% if (it.standShowMemoryUsageBanner) { %>\n <div style={{ marginBottom: '12px', color: '#7c2d12', fontSize: '14px' }}>\n Memory usage stand: eager editor import + Vite 8 + host-side asset plugins for build reproduction.\n </div>\n<% } %>\n<% if (it.standShowSubpathBanner) { %>\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n Advanced subpath stand: page route and editor publicPath are intentionally not at server root.\n </div>\n<% } %>\n <div id=\"editor-root\" style={{ minHeight: '100vh' }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3627
- "../../project-templates/shared/partials/stand-host-oauth.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-oauth',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ minHeight: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ minHeight: '100vh' }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3628
- "../../project-templates/shared/partials/stand-host-react-adapter.eta": "import { createRoot } from 'react-dom/client';\nimport <%= it.standReactAdapterComponentName %> from '<%~ it.standReactAdapterPackage %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('stand-demo-email-id', it) %>\n\nfunction StandHostApp() {\n return (\n <div style={{ minHeight: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ margin: '0 auto', maxWidth: '1280px' }}>\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n React adapter demo stand\n </div>\n <<%= it.standReactAdapterComponentName %>\n getAuthToken={getAuthToken}\n storageProvider={createLocalFolderStorageProvider()}\n content={{\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n }}\n config={editorConfig}\n container={{ style: { minHeight: '100vh' } }}\n />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<StandHostApp />);\n",
3629
- "../../project-templates/shared/partials/stand-host-resource-proxy-body.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\n<% if (it.standResourceProxyAuth === 'oauth') { %>\nimport { hasOAuthCredentials } from './dev/oauthCredentials';\n<% } else { %>\nimport { hasStandaloneCredentials, standaloneCredentials } from './dev/standaloneCredentials';\n<% } %>\nimport { demoStandConfig, hasDemoStandConfig } from './dev/demoStandConfig';\nimport { createResourceProxyDemoStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: <% if (it.standResourceProxyAuth === 'oauth') { %>'stand-resource-proxy-oauth'<% } else { %>'stand-resource-proxy-standalone'<% } %>,\n mountLabel: '#editor-root',\n } as const;\n\n try {\n<% if (it.standResourceProxyAuth === 'oauth') { %>\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingOAuthCredentials) %>);\n }\n<% } else { %>\n if (!hasStandaloneCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingStandaloneCredentials) %>);\n }\n<% } %>\n if (!hasDemoStandConfig()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingDemoStandConfig) %>);\n }\n\n const emailCode = baseEmailHtml.replaceAll(\n 'YOUR_CDN_SAMPLE_PROJECT_ID',\n demoStandConfig.cdnSampleProjectId,\n );\n\n const instance = await <%= it.standProductApiName %>.init({\n<% if (it.standResourceProxyAuth !== 'oauth') { %>\n standaloneKey: standaloneCredentials.standaloneKey,\n<% } %>\n getAuthToken,\n storageProvider: createResourceProxyDemoStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: emailCode,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ minHeight: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ margin: '0 auto', maxWidth: '1280px' }}>\n <div\n style={{\n marginBottom: '12px',\n padding: '12px 16px',\n borderRadius: '8px',\n background: '#eef4ff',\n color: '#1e3a8a',\n fontSize: '13px',\n lineHeight: '20px',\n }}\n >\n <strong>Resource proxy demo:</strong>{' '}\n <code>placehold.co</code> is in <code>directHosts</code> (direct fetch);{' '}\n <code>dummyimage.com</code> goes through <code>/proxy/</code>.\n Open File Manager for seeded demo files or inspect the letter images.\n </div>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ minHeight: '100vh' }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3637
+ "../../project-templates/shared/partials/stand-host-oauth-default-banners.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-default-banners',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n<% if (it.standShowMemoryUsageBanner) { %>\n <div style={{ marginBottom: '12px', color: '#7c2d12', fontSize: '14px' }}>\n Memory usage stand: eager editor import + Vite 8 + host-side asset plugins for build reproduction.\n </div>\n<% } %>\n<% if (it.standShowSubpathBanner) { %>\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n Advanced subpath stand: page route and editor publicPath are intentionally not at server root.\n </div>\n<% } %>\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3638
+ "../../project-templates/shared/partials/stand-host-oauth.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-oauth',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3639
+ "../../project-templates/shared/partials/stand-host-react-adapter.eta": "import { createRoot } from 'react-dom/client';\nimport <%= it.standReactAdapterComponentName %> from '<%~ it.standReactAdapterPackage %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\nconst EDITOR_MOUNT_ID = 'editor-root';\nconst smokeMeta = {\n hostKind: 'stand-host',\n variant: 'react-adapter',\n mountLabel: `#${EDITOR_MOUNT_ID}`,\n} as const;\n\n// The adapter fires handleLoad once the editor app is up; that is the readiness signal.\nfunction handleEditorLoad(): void {\n reportEditorReady(smokeMeta, document.getElementById(EDITOR_MOUNT_ID));\n}\n\nfunction StandHostApp() {\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n React adapter demo stand\n </div>\n <<%= it.standReactAdapterComponentName %>\n getAuthToken={getAuthToken}\n storageProvider={createLocalFolderStorageProvider()}\n content={{\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n }}\n config={editorConfig}\n handleLoad={handleEditorLoad}\n container={{ id: EDITOR_MOUNT_ID, style: { flex: 1, minHeight: 0 } }}\n />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<StandHostApp />);\n",
3640
+ "../../project-templates/shared/partials/stand-host-resource-proxy-body.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\n<% if (it.standResourceProxyAuth === 'oauth') { %>\nimport { hasOAuthCredentials } from './dev/oauthCredentials';\n<% } else { %>\nimport { hasStandaloneCredentials, standaloneCredentials } from './dev/standaloneCredentials';\n<% } %>\nimport { demoStandConfig, hasDemoStandConfig } from './dev/demoStandConfig';\nimport { createResourceProxyDemoStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: <% if (it.standResourceProxyAuth === 'oauth') { %>'stand-resource-proxy-oauth'<% } else { %>'stand-resource-proxy-standalone'<% } %>,\n mountLabel: '#editor-root',\n } as const;\n\n try {\n<% if (it.standResourceProxyAuth === 'oauth') { %>\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingOAuthCredentials) %>);\n }\n<% } else { %>\n if (!hasStandaloneCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingStandaloneCredentials) %>);\n }\n<% } %>\n if (!hasDemoStandConfig()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingDemoStandConfig) %>);\n }\n\n const emailCode = baseEmailHtml.replaceAll(\n 'YOUR_CDN_SAMPLE_PROJECT_ID',\n demoStandConfig.cdnSampleProjectId,\n );\n\n const instance = await <%= it.standProductApiName %>.init({\n<% if (it.standResourceProxyAuth !== 'oauth') { %>\n standaloneKey: standaloneCredentials.standaloneKey,\n<% } %>\n getAuthToken,\n storageProvider: createResourceProxyDemoStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: emailCode,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n <div\n style={{\n marginBottom: '12px',\n padding: '12px 16px',\n borderRadius: '8px',\n background: '#eef4ff',\n color: '#1e3a8a',\n fontSize: '13px',\n lineHeight: '20px',\n }}\n >\n <strong>Resource proxy demo:</strong>{' '}\n <code>placehold.co</code> is in <code>directHosts</code> (direct fetch);{' '}\n <code>dummyimage.com</code> goes through <code>/proxy/</code>.\n Open File Manager for seeded demo files or inspect the letter images.\n </div>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3630
3641
  "../../project-templates/shared/partials/stand-host-resource-proxy.eta": "<%~ include('stand-host-resource-proxy-body', it) %>\n",
3631
- "../../project-templates/shared/partials/stand-host-shadow-dom.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const shadowHostRef = useRef<HTMLDivElement | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n const shadowHost = shadowHostRef.current;\n if (!shadowHost || shadowHost.dataset.mounted === 'true' || instanceRef.current) {\n return;\n }\n\n shadowHost.dataset.mounted = 'true';\n\n const shadowRoot = shadowHost.attachShadow({ mode: 'closed' });\n const shadowStyle = document.createElement('style');\n shadowStyle.textContent = [\n ':host { display: block; min-height: 100vh; background: #ffffff; color: #111827; }',\n '#editor-root { min-height: 100vh; }',\n ].join(' ');\n\n const editorRoot = document.createElement('div');\n editorRoot.id = 'editor-root';\n\n shadowRoot.appendChild(shadowStyle);\n shadowRoot.appendChild(editorRoot);\n\n async function run() {\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-advanced-shadow-dom',\n mountLabel: '#shadow-host -> #editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: editorRoot,\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, editorRoot);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, editorRoot);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n <style>{`\n html, body, #root {\n margin: 0;\n min-height: 100%;\n }\n\n body {\n background:\n linear-gradient(135deg, rgba(255, 84, 89, 0.15), rgba(91, 146, 255, 0.18)),\n repeating-linear-gradient(90deg, rgba(17, 24, 39, 0.04) 0 8px, transparent 8px 16px);\n }\n\n body * {\n box-sizing: border-box;\n font-family: 'Courier New', monospace !important;\n letter-spacing: 0.02em;\n }\n\n button, input, select, textarea {\n border-radius: 0 !important;\n }\n `}</style>\n <div style={{ padding: '24px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div style={{ marginBottom: '12px', color: '#111827', fontSize: '14px' }}>\n Advanced shadow-dom stand: closed shadow root + OAuth credentials + hostile host CSS\n </div>\n <div\n ref={shadowHostRef}\n id=\"shadow-host\"\n style={{ minHeight: '100vh', border: '2px dashed #111827', background: '#ffffff' }}\n />\n </div>\n </>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3632
- "../../project-templates/shared/partials/stand-host-umd.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\nconst editorGlobalName = <%~ JSON.stringify(it.standUmdEditorGlobalName) %>;\n\nfunction getEditorApi() {\n const editorApi = globalThis[editorGlobalName];\n if (!editorApi || typeof editorApi.init !== 'function') {\n throw new Error(`UMD bundle \"${editorGlobalName}\" was not found on window. Check <%~ it.standUmdScriptPath %>.`);\n }\n\n return editorApi;\n}\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorApi = ReturnType<typeof getEditorApi>;\ntype EditorInstance = Awaited<ReturnType<EditorApi['init']>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-advanced-umd',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await getEditorApi().init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ minHeight: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n Advanced UMD stand: editor loads from <%= it.standUmdScriptPath %> via a plain script tag.\n </div>\n <div id=\"editor-root\" style={{ minHeight: '100vh' }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3642
+ "../../project-templates/shared/partials/stand-host-shadow-dom.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const shadowHostRef = useRef<HTMLDivElement | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n const shadowHost = shadowHostRef.current;\n if (!shadowHost || shadowHost.dataset.mounted === 'true' || instanceRef.current) {\n return;\n }\n\n shadowHost.dataset.mounted = 'true';\n\n const shadowRoot = shadowHost.attachShadow({ mode: 'closed' });\n const shadowStyle = document.createElement('style');\n shadowStyle.textContent = [\n ':host { display: block; background: #ffffff; color: #111827; }',\n '#editor-root { height: 100%; }',\n ].join(' ');\n\n const editorRoot = document.createElement('div');\n editorRoot.id = 'editor-root';\n\n shadowRoot.appendChild(shadowStyle);\n shadowRoot.appendChild(editorRoot);\n\n async function run() {\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-advanced-shadow-dom',\n mountLabel: '#shadow-host -> #editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: editorRoot,\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, editorRoot);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, editorRoot);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n <style>{`\n html, body, #root {\n margin: 0;\n min-height: 100%;\n }\n\n body {\n background:\n linear-gradient(135deg, rgba(255, 84, 89, 0.15), rgba(91, 146, 255, 0.18)),\n repeating-linear-gradient(90deg, rgba(17, 24, 39, 0.04) 0 8px, transparent 8px 16px);\n }\n\n body * {\n box-sizing: border-box;\n font-family: 'Courier New', monospace !important;\n letter-spacing: 0.02em;\n }\n\n button, input, select, textarea {\n border-radius: 0 !important;\n }\n `}</style>\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', padding: '24px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div style={{ marginBottom: '12px', color: '#111827', fontSize: '14px' }}>\n Advanced shadow-dom stand: closed shadow root + OAuth credentials + hostile host CSS\n </div>\n <div\n ref={shadowHostRef}\n id=\"shadow-host\"\n style={{ flex: 1, minHeight: 0, border: '2px dashed #111827', background: '#ffffff' }}\n />\n </div>\n </>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3643
+ "../../project-templates/shared/partials/stand-host-umd.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\nconst editorGlobalName = <%~ JSON.stringify(it.standUmdEditorGlobalName) %>;\n\nfunction getEditorApi() {\n const editorApi = globalThis[editorGlobalName];\n if (!editorApi || typeof editorApi.init !== 'function') {\n throw new Error(`UMD bundle \"${editorGlobalName}\" was not found on window. Check <%~ it.standUmdScriptPath %>.`);\n }\n\n return editorApi;\n}\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorApi = ReturnType<typeof getEditorApi>;\ntype EditorInstance = Awaited<ReturnType<EditorApi['init']>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-advanced-umd',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await getEditorApi().init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n Advanced UMD stand: editor loads from <%= it.standUmdScriptPath %> via a plain script tag.\n </div>\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
3633
3644
  "../../project-templates/shared/partials/stand-package-json.eta": "<%~ JSON.stringify(it.standPackageJson, null, 2) + '\\n' %>\n",
3634
3645
  "../../project-templates/shared/partials/stand-readme.eta": "# <%= it.readmePluginPackageName %>\n\n<%= it.readmeGenerated %>\n\n<%= it.readmeWhatIncluded %>\n\n<%= it.readmeSimpleProject %>\n<%= it.readmeStorageProvider %>\n<%= it.readmeDevServer %>\n<% if (it.standAngular) { %>\n<%= it.readmeAngularHost %>\n<% } else { %>\n<%= it.readmeReactWrapper %>\n<%= it.readmeRouteHint %>\n<% } %>\n<% if (it.standReadmeIsResourceProxy === 'true') { %>\n\n<%= it.readmeStandResourceProxyAuth %>\n\n<%= it.readmeOauthTokenFile %>\n<% } else if (it.standReadmeIsClosedLoop === 'true') { %>\n<%= it.readmeClosedStandaloneKey %>\n<%= it.readmeClosedHandleReadLocale %>\n\n<%= it.readmeConfiguration %>\n\n<%= it.readmeClosedConfigHint %>\n<% } else { %>\n<%= it.readmeOauthProxy %>\n\n<%= it.readmeOauthTitle %>\n\n<%= it.readmeOauthHint %>\n<% } %>\n<% if (it.standReadmeIsResourceProxy === 'true') { %>\n\n<%= it.readmeStandResourceProxyHint %>\n\n<%= it.readmeStandResourceProxySecurityWarning %>\n\n<%= it.readmeStandResourceProxyDevRoutes %>\n\n<%= it.readmeStandResourceProxySampleProject %>\n<% } %>\n\n<%= it.readmeCommands %>\n\n```bash\nnpm install\n```\n\n<%= it.readmeCommandsDevelopment %>\n\n```bash\nnpm start\n```\n\n<%= it.readmeCommandsProduction %>\n\n<% if (it.standBundler === 'vite') { %>\n```bash\nnpm run build\nnpm run preview\n# alias: npm run serve:dist\n```\n<% } else { %>\n```bash\nnpm run build\nnpm run serve:dist\n```\n<% } %>\n\n<%= it.readmeCommandsProductionNote %>\n\n<% if (it.readmeModuleFederationHint) { %>\n\n<%= it.readmeModuleFederationHint %>\n\n<% } %>\n\n<% if (it.standAngular) { %>\n<%= it.readmeAngularCommandsDevUrl %>\n<%= it.readmeAngularCommandsProdUrl %>\n<% if (it.readmeAngularEsbuildClientProd) { %>\n<%= it.readmeAngularEsbuildClientProd %>\n<% } %>\n<% } else { %>\n> Production-like URL: `http://localhost:<%~ it.standPreviewPort %>/` (webpack/vite). Subpath stands may need the route suffix from dev mode.\n<% } %>\n\n<%= it.readmeStructure %>\n\n<%= it.readmeEntryPoint %>\n<%= it.readmeEmailTemplate %>\n<%= it.readmeEditorConfigFile %>\n<%= it.readmeStorageProviderFile %>\n<%= it.readmeStorageMiddleware %>\n<%= it.readmeStorageFolder %>\n<%= it.readmeConfigDir %>\n<% if (it.standReadmeIsClosedLoop === 'true') { %>\n<%= it.readmeStandaloneCredentialsFile %>\n<% } else if (it.standReadmeIsResourceProxy !== 'true') { %>\n<%= it.readmeOauthCredentialsFile %>\n<%= it.readmeOauthTokenFile %>\n<% } %>\n",
3635
3646
  "../../project-templates/shared/partials/stand-resource-proxy-demo-storage-provider.eta": "/** Demo URLs from buildResourceProxyStandPolicy (email + FM seed). */\nconst RESOURCE_PROXY_DEMO_DIRECT_URL = <%~ JSON.stringify(it.resourceProxyDemoDirectUrl) %>;\nconst RESOURCE_PROXY_DEMO_PROXY_URL = <%~ JSON.stringify(it.resourceProxyDemoProxyUrl) %>;\n\nfunction createResourceProxyDemoSeedFiles(): FileSystemItem[] {\n const date = new Date().toISOString();\n return [\n {\n id: 'demo-direct-placehold',\n name: 'directHosts (placehold.co).png',\n folderId: '',\n isFolder: false,\n type: 'image/png',\n size: 0,\n date,\n url: RESOURCE_PROXY_DEMO_DIRECT_URL,\n thumbnailUrl: RESOURCE_PROXY_DEMO_DIRECT_URL,\n },\n {\n id: 'demo-proxy-dummyimage',\n name: 'via proxy (dummyimage.com).png',\n folderId: '',\n isFolder: false,\n type: 'image/png',\n size: 0,\n date,\n url: RESOURCE_PROXY_DEMO_PROXY_URL,\n thumbnailUrl: RESOURCE_PROXY_DEMO_PROXY_URL,\n },\n ];\n}\n\nfunction isResourceProxyDemoFileId(id: string | undefined): boolean {\n return id === 'demo-direct-placehold' || id === 'demo-proxy-dummyimage';\n}\n\nfunction normalizeFolderId(folderId: string | undefined, rootId: string | undefined): string {\n if (!folderId || folderId === rootId) {\n return '';\n }\n return folderId;\n}\n\nfunction filterDemoItems(\n demoFiles: FileSystemItem[],\n folderId: string | undefined,\n rootId: string | undefined,\n options: { search?: string; itemType?: 'all' | 'file' | 'folder' },\n): FileSystemItem[] {\n const normalizedFolderId = normalizeFolderId(folderId, rootId);\n if (options.itemType === 'folder') {\n return [];\n }\n\n let items = demoFiles.filter((item) => item.folderId === normalizedFolderId);\n const search = (options.search || '').trim().toLowerCase();\n if (search) {\n items = items.filter((item) => item.name.toLowerCase().includes(search));\n }\n return items;\n}\n\nfunction removeDemoFile(demoFiles: FileSystemItem[], id: string): void {\n const index = demoFiles.findIndex((demoItem) => demoItem.id === id);\n if (index >= 0) {\n demoFiles.splice(index, 1);\n }\n}\n\n/**\n * Local folder storage with two seeded external-image demo files for resource-proxy stand.\n * Demo files can be deleted or moved during the session; they reappear after page reload.\n */\nexport function createResourceProxyDemoStorageProvider(): StorageProvider {\n const inner = createLocalFolderStorageProvider();\n const demoFiles = createResourceProxyDemoSeedFiles();\n\n return {\n ...inner,\n\n async getItems(options) {\n const result = await inner.getItems(options);\n const demoItems = filterDemoItems(demoFiles, options.folderId, inner.rootId, options);\n const items = [...demoItems, ...(result.items || [])];\n const pagination = result.pagination\n ? {\n ...result.pagination,\n total: (result.pagination.total ?? result.items?.length ?? 0) + demoItems.length,\n }\n : result.pagination;\n\n return { items, pagination };\n },\n\n async deleteItem(item, options) {\n if (isResourceProxyDemoFileId(item.id)) {\n removeDemoFile(demoFiles, item.id);\n return;\n }\n\n return inner.deleteItem!(item, options);\n },\n\n async deleteItems(items, options) {\n const demoItems = items.filter((item) => isResourceProxyDemoFileId(item.id));\n for (const item of demoItems) {\n removeDemoFile(demoFiles, item.id);\n }\n\n const remaining = items.filter((item) => !isResourceProxyDemoFileId(item.id));\n if (remaining.length === 0) {\n return {\n success: demoItems.every(() => true),\n detailed: demoItems.map((item) => ({ success: true, requestId: item.id })),\n };\n }\n\n const innerResult = await inner.deleteItems!(remaining, options);\n const demoDetailed = demoItems.map((item) => ({ success: true, requestId: item.id }));\n return {\n success: innerResult.success && demoDetailed.every((entry) => entry.success),\n detailed: [...demoDetailed, ...(innerResult.detailed || [])],\n };\n },\n\n async moveItem(item, targetFolderId) {\n if (isResourceProxyDemoFileId(item.id)) {\n const demoItem = demoFiles.find((entry) => entry.id === item.id);\n if (!demoItem) {\n throw new Error('Demo file not found');\n }\n demoItem.folderId = normalizeFolderId(targetFolderId, inner.rootId);\n return { id: demoItem.id, folderId: demoItem.folderId };\n }\n\n return inner.moveItem!(item, targetFolderId);\n },\n\n async renameItem(item, newName) {\n if (isResourceProxyDemoFileId(item.id)) {\n const demoItem = demoFiles.find((entry) => entry.id === item.id);\n if (!demoItem) {\n throw new Error('Demo file not found');\n }\n demoItem.name = newName;\n return { id: demoItem.id, name: newName };\n }\n\n return inner.renameItem!(item, newName);\n },\n };\n}\n",
3636
3647
  "../../project-templates/shared/partials/stand-storage-provider.eta": "import type {\n BatchResult,\n FileSystemItem,\n OperationResult,\n StorageProvider,\n UploadFilesRequest,\n} from '<%~ it.storageTypesPackage %>';\n\n/**\n * StorageProvider for dev stand. Stores files in ./storage via /dev-storage.\n * Uses pathMode: true - folderId and id are path strings.\n */\nexport function createLocalFolderStorageProvider(): StorageProvider {\n const base = '/dev-storage';\n\n const toPath = (id: string | null | undefined): string => {\n if (!id || id === '/' || id === '.') return '';\n return id.replace(/^\\/+/, '');\n };\n\n const readErrorMessage = async (res: Response, fallback: string): Promise<string> => {\n const err = await res.json().catch(() => ({})) as { error?: string };\n return err.error || fallback;\n };\n\n return {\n pathMode: true,\n rootId: '',\n ensureFolderTrailingSlash: true,\n\n async getItems(options) {\n const folderId = toPath(options.folderId);\n const q = folderId ? `?folderId=${encodeURIComponent(folderId)}` : '';\n const res = await fetch(`${base}/items${q}`);\n if (!res.ok) throw new Error(`getItems failed: ${res.status}`);\n const data = await res.json();\n return {\n items: (data.items || []).map((it: Record<string, unknown>) => ({\n ...it,\n folderId: it['folderId'] ?? '',\n })),\n pagination: data.pagination,\n };\n },\n\n async createFolder(name: string, parentid?: string) {\n const res = await fetch(`${base}/folder`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n name,\n parentId: toPath(parentid),\n }),\n });\n if (!res.ok) {\n const err = await res.json().catch(() => ({}));\n throw new Error(err.error || `createFolder failed: ${res.status}`);\n }\n const item = await res.json();\n return item as FileSystemItem;\n },\n\n async uploadFile(file: {\n name: string;\n size: number;\n type: string;\n folderId?: string;\n data: Blob | File;\n }) {\n const form = new FormData();\n form.append('file', file.data instanceof Blob ? new File([file.data], file.name, { type: file.type }) : file.data);\n form.append('folderId', toPath(file.folderId) || '');\n const res = await fetch(`${base}/upload`, {\n method: 'POST',\n body: form,\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `uploadFile failed: ${res.status}`));\n }\n const data = await res.json();\n const items = data.items || [];\n const first = items[0];\n if (!first) throw new Error('No file returned');\n return { id: first.id, ...first } as FileSystemItem;\n },\n\n async uploadFiles(request: UploadFilesRequest): Promise<BatchResult<FileSystemItem>> {\n const form = new FormData();\n form.append('folderId', toPath(request.folderId) || '');\n for (const it of request.items) {\n const file = it.data instanceof Blob ? new File([it.data], it.name, { type: it.type }) : it.data;\n form.append('file', file);\n }\n const res = await fetch(`${base}/upload`, {\n method: 'POST',\n body: form,\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `uploadFiles failed: ${res.status}`));\n }\n const data = await res.json();\n const items = (data.items || []).map((it: Record<string, unknown>) => ({\n ...it,\n id: String(it['id'] || ''),\n })) as FileSystemItem[];\n if (request.items.length > 0 && items.length === 0) {\n throw new Error('No files returned');\n }\n const detailed: OperationResult<FileSystemItem>[] = items.map((it, index) => ({\n success: true,\n requestId: request.items[index]?.requestId,\n data: it,\n }));\n return { success: true, detailed };\n },\n\n async uploadFileByUrl(url: string, folderId?: string) {\n const res = await fetch(`${base}/upload-by-url`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ url, folderId: toPath(folderId) }),\n });\n if (!res.ok) {\n const err = await res.json().catch(() => ({}));\n throw new Error(err.error || `uploadFileByUrl failed: ${res.status}`);\n }\n const item = await res.json();\n return item as FileSystemItem;\n },\n\n async deleteItem(item: FileSystemItem, _options: { permanent: boolean }) {\n const res = await fetch(`${base}/item`, {\n method: 'DELETE',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: item.id }),\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `deleteItem failed: ${res.status}`));\n }\n },\n\n async deleteItems(\n items: FileSystemItem[],\n _options: { permanent: boolean },\n ): Promise<BatchResult<never>> {\n const detailed: OperationResult<never>[] = await Promise.all(\n items.map(async (item) => {\n try {\n const res = await fetch(`${base}/item`, {\n method: 'DELETE',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: item.id }),\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `deleteItem failed: ${res.status}`));\n }\n return { success: true, requestId: item.id };\n } catch (error) {\n return {\n success: false,\n requestId: item.id,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n }),\n );\n\n return {\n success: detailed.every((entry) => entry.success),\n detailed,\n };\n },\n\n async renameItem(item: FileSystemItem, newName: string) {\n const res = await fetch(`${base}/rename`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: item.id, newName }),\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `renameItem failed: ${res.status}`));\n }\n const updated = await res.json();\n return updated as FileSystemItem;\n },\n\n async moveItem(item: FileSystemItem, targetFolderId?: string) {\n const res = await fetch(`${base}/move`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n path: item.id,\n targetFolderId: toPath(targetFolderId),\n }),\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `moveItem failed: ${res.status}`));\n }\n const updated = await res.json();\n return updated as FileSystemItem;\n },\n\n getUrl(file: FileSystemItem) {\n return `${base}/file/${encodeURIComponent(file.id)}`;\n },\n };\n}\n",
3637
3648
  "../../project-templates/shared/partials/stand-vite-index-body.eta": "<% if (it.standAdvancedUmd) { %>\n <script src=\"<%= it.standUmdScriptPath %>\"><\/script>\n<% } %>\n <script type=\"module\" src=\"<%~ it.standIndexScriptSrc %>\"><\/script>\n",
3638
- "../../project-templates/shared/partials/stand-vite-index-shell.eta": "<!doctype html>\n<html lang=\"<%= it.standIndexHtmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.standIndexHtmlTitle %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-vite-index-body', it) %>\n </body>\n</html>\n",
3649
+ "../../project-templates/shared/partials/stand-vite-index-shell.eta": "<!doctype html>\n<html lang=\"<%= it.standIndexHtmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.standIndexHtmlTitle %></title>\n <style>\n body {\n margin: 0;\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-vite-index-body', it) %>\n </body>\n</html>\n",
3639
3650
  "../../project-templates/shared/partials/stand-webpack-index-body.eta": "<% if (it.standAdvancedUmd) { %>\n <script src=\"<%= it.standUmdScriptPath %>\"><\/script>\n<% } %>\n <script src=\"<%= it.standWebpackScriptSrc %>\"><\/script>\n",
3640
- "../../project-templates/shared/partials/stand-webpack-index-shell.eta": "<!doctype html>\n<html lang=\"<%= it.standIndexHtmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.standIndexHtmlTitle %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-webpack-index-body', it) %>\n </body>\n</html>\n",
3651
+ "../../project-templates/shared/partials/stand-webpack-index-shell.eta": "<!doctype html>\n<html lang=\"<%= it.standIndexHtmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.standIndexHtmlTitle %></title>\n <style>\n body {\n margin: 0;\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-webpack-index-body', it) %>\n </body>\n</html>\n",
3641
3652
  "../../project-templates/shared/stand-assets/scripts/assertDistReady.cjs": "#!/usr/bin/env node\n/**\n * Guards `serve:dist` / `vite preview` — fails fast when build output is missing.\n *\n * Usage: node ./scripts/assertDistReady.cjs [distRelativePath]\n * Default path: `dist`\n */\nconst fs = require('node:fs');\nconst path = require('node:path');\n\nconst distRelative = process.argv[2] || 'dist';\nconst distDir = path.resolve(process.cwd(), distRelative);\n\nfunction hasIndexHtml(dir) {\n if (fs.existsSync(path.join(dir, 'index.html'))) {\n return true;\n }\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n if (hasIndexHtml(path.join(dir, entry.name))) {\n return true;\n }\n }\n return false;\n}\n\nif (!fs.existsSync(distDir)) {\n console.error(`[serve:dist] Missing ${distRelative}/ — run \\`npm run build\\` first.`);\n process.exit(1);\n}\n\nif (!fs.statSync(distDir).isDirectory()) {\n console.error(`[serve:dist] Expected ${distRelative}/ to be a directory.`);\n process.exit(1);\n}\n\nif (!hasIndexHtml(distDir)) {\n console.error(`[serve:dist] No index.html under ${distRelative}/ — run \\`npm run build\\` first.`);\n process.exit(1);\n}\n",
3642
3653
  "../../project-templates/shared/stand-assets/scripts/serveDist.cjs.eta": "#!/usr/bin/env node\n/**\n * Production-like static server for demo stands (`serve:dist`).\n * Serves built `dist/`, mirrors dev-server `/api` proxy for OAuth (`getAuthToken`),\n * and mounts local `./storage` via `/dev-storage` (same middleware as `ng serve`).\n *\n * Usage: node ./scripts/serveDist.cjs [distRelativePath] [port]\n */\nconst http = require('node:http');\nconst https = require('node:https');\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst { URL } = require('node:url');\n\nconst API_PROXY_ENABLED = <%= it.standClosedLoop ? 'false' : 'true' %>;\nconst API_TARGET = <%~ JSON.stringify(it.standOpenApiBaseUrl) %>;\nconst API_ORIGIN = <%~ JSON.stringify(it.standOpenApiOrigin) %>;\nconst DEFAULT_PORT = <%~ it.standPreviewPort %>;\n\nconst STATIC_HEADERS = {\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n};\n\nconst MIME_TYPES = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.ico': 'image/x-icon',\n '.map': 'application/json; charset=utf-8',\n};\n\nfunction resolveContentType(filePath) {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] || 'application/octet-stream';\n}\n\nfunction hasIndexHtml(dir) {\n if (fs.existsSync(path.join(dir, 'index.html'))) {\n return true;\n }\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n if (hasIndexHtml(path.join(dir, entry.name))) {\n return true;\n }\n }\n return false;\n}\n\nfunction resolveStaticFile(distDir, requestPath) {\n const safeSuffix = path.normalize(requestPath).replace(/^(\\.\\.[/\\\\])+/, '');\n const candidate = path.join(distDir, safeSuffix);\n if (!candidate.startsWith(distDir)) {\n return null;\n }\n if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\n return candidate;\n }\n if (fs.existsSync(path.join(candidate, 'index.html'))) {\n return path.join(candidate, 'index.html');\n }\n return null;\n}\n\nfunction sendFile(res, filePath) {\n res.writeHead(200, {\n ...STATIC_HEADERS,\n 'Content-Type': resolveContentType(filePath),\n });\n fs.createReadStream(filePath).pipe(res);\n}\n\nfunction readRequestBody(req) {\n return new Promise((resolve, reject) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n req.on('error', reject);\n });\n}\n\nfunction buildProxyRequestHeaders(req, targetUrl, bodyLength) {\n const headers = { ...req.headers, host: targetUrl.host };\n if (headers.origin) {\n headers.origin = API_ORIGIN;\n }\n delete headers.connection;\n delete headers['transfer-encoding'];\n if (bodyLength > 0) {\n headers['content-length'] = String(bodyLength);\n } else {\n delete headers['content-length'];\n }\n return headers;\n}\n\nfunction drainResponse(proxyRes) {\n return new Promise((resolve) => {\n proxyRes.on('end', resolve);\n proxyRes.resume();\n });\n}\n\nfunction proxyApiRequest(req, res, targetUrl, body, redirectCount, method) {\n const MAX_REDIRECTS = 5;\n if (redirectCount > MAX_REDIRECTS) {\n res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Too many redirects');\n return;\n }\n\n const requestMethod = method || req.method || 'GET';\n const transport = targetUrl.protocol === 'https:' ? https : http;\n const headers = buildProxyRequestHeaders(req, targetUrl, body.length);\n\n const proxyReq = transport.request(\n targetUrl,\n { method: requestMethod, headers },\n (proxyRes) => {\n const status = proxyRes.statusCode || 502;\n const location = proxyRes.headers.location;\n if (status >= 300 && status < 400 && location) {\n drainResponse(proxyRes).then(() => {\n const nextUrl = new URL(location, targetUrl);\n const useGet = status === 303;\n proxyApiRequest(\n req,\n res,\n nextUrl,\n useGet ? Buffer.alloc(0) : body,\n redirectCount + 1,\n useGet ? 'GET' : requestMethod,\n );\n });\n return;\n }\n\n const outHeaders = { ...proxyRes.headers };\n delete outHeaders.location;\n res.writeHead(status, outHeaders);\n proxyRes.pipe(res);\n },\n );\n\n proxyReq.on('error', (error) => {\n console.error('[serveDist] API proxy error:', error.message);\n if (!res.headersSent) {\n res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Bad Gateway');\n }\n });\n\n if (body.length > 0) {\n proxyReq.write(body);\n }\n proxyReq.end();\n}\n\nasync function proxyApi(req, res) {\n const body = await readRequestBody(req);\n const targetUrl = new URL(req.url || '/', API_TARGET);\n proxyApiRequest(req, res, targetUrl, body, 0);\n}\n\nfunction loadDevStorageMiddleware() {\n const middlewarePath = path.join(__dirname, 'devStorageMiddleware.ts');\n if (!fs.existsSync(middlewarePath)) {\n return null;\n }\n\n try {\n const { register } = require('tsx/cjs/api');\n register();\n const mod = require(middlewarePath);\n const factory = mod && (mod.default || mod);\n return typeof factory === 'function' ? factory() : null;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[serveDist] dev-storage middleware not loaded: ${message}`);\n return null;\n }\n}\n\nfunction handleStaticRequest(distDir, req, res, pathname) {\n if (API_PROXY_ENABLED && pathname.startsWith('/api')) {\n proxyApi(req, res);\n return;\n }\n\n const filePath = resolveStaticFile(distDir, pathname === '/' ? '/index.html' : pathname);\n if (filePath) {\n sendFile(res, filePath);\n return;\n }\n\n res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Not Found');\n}\n\nfunction createServer(distDir, devStorageMiddleware) {\n return http.createServer((req, res) => {\n const requestUrl = new URL(req.url || '/', 'http://localhost');\n const pathname = decodeURIComponent(requestUrl.pathname);\n\n if (pathname.startsWith('/dev-storage')) {\n if (!devStorageMiddleware) {\n res.writeHead(503, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('dev-storage middleware unavailable (missing scripts/devStorageMiddleware.ts or tsx)');\n return;\n }\n\n devStorageMiddleware(req, res, () => {\n if (!res.headersSent) {\n res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Not Found');\n }\n });\n return;\n }\n\n handleStaticRequest(distDir, req, res, pathname);\n });\n}\n\nfunction main() {\n const distRelative = process.argv[2] || 'dist';\n const portArg = process.argv[3];\n const port = portArg !== undefined ? Number(portArg) : DEFAULT_PORT;\n const distDir = path.resolve(process.cwd(), distRelative);\n\n if (!fs.existsSync(distDir) || !fs.statSync(distDir).isDirectory()) {\n console.error(`[serveDist] Missing ${distRelative}/ — run \\`npm run build\\` first.`);\n process.exit(1);\n }\n\n if (!hasIndexHtml(distDir)) {\n console.error(`[serveDist] No index.html under ${distRelative}/ — run \\`npm run build\\` first.`);\n process.exit(1);\n }\n\n const devStorageMiddleware = loadDevStorageMiddleware();\n const server = createServer(distDir, devStorageMiddleware);\n server.listen(port, () => {\n console.log(`[serveDist] ${distRelative} → http://localhost:${port}/`);\n if (API_PROXY_ENABLED) {\n console.log(`[serveDist] /api → ${API_TARGET}`);\n }\n if (devStorageMiddleware) {\n console.log('[serveDist] /dev-storage → ./storage');\n }\n });\n}\n\nmain();\n",
3643
3654
  "../../project-templates/shared/stand-assets/serve.json": "{\n \"headers\": [\n {\n \"source\": \"**/*\",\n \"headers\": [\n {\n \"key\": \"Cross-Origin-Resource-Policy\",\n \"value\": \"cross-origin\"\n },\n {\n \"key\": \"Access-Control-Allow-Origin\",\n \"value\": \"*\"\n }\n ]\n }\n ]\n}\n",
3644
3655
  "../../project-templates/shared/stand-vite-base/config/lib/createViteStandConfig.ts": "import type { IncomingMessage, ServerResponse } from 'node:http';\nimport react from '@vitejs/plugin-react';\nimport type { PluginOption, UserConfig, UserConfigExport, ViteDevServer } from 'vite';\nimport { defineConfig } from 'vite';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_PREVIEW_HEADERS, STAND_PREVIEW_PORT } from './standPreviewSettings.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\n\ntype DevServerMiddleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;\n\ninterface CreateViteStandConfigOptions {\n projectRoot: string;\n open?: string;\n apiBaseUrl: string;\n apiOrigin: string;\n closedLoop?: boolean;\n plugins?: PluginOption[];\n extraServerMiddlewares?: DevServerMiddleware[];\n extraProxy?: Record<string, import('vite').ProxyOptions>;\n onConfigureServer?: (server: ViteDevServer) => void | (() => void);\n build?: UserConfig['build'];\n resolve?: UserConfig['resolve'];\n serverPort?: number;\n}\n\nexport function createViteStandConfig(options: CreateViteStandConfigOptions): UserConfigExport {\n const {\n projectRoot,\n open,\n apiBaseUrl,\n apiOrigin,\n closedLoop,\n plugins = [],\n extraServerMiddlewares = [],\n extraProxy = {},\n onConfigureServer,\n build,\n resolve,\n serverPort = 3000,\n } = options;\n\n return defineConfig(() => {\n const apiProxy = closedLoop\n ? undefined\n : {\n ...createStandApiProxyOptions(apiBaseUrl, apiOrigin),\n ...extraProxy,\n };\n\n return {\n root: projectRoot,\n plugins: [\n react(),\n ...plugins,\n {\n name: 'dev-storage',\n configureServer(server) {\n let disposeConfigureServer: void | (() => void);\n if (open && open !== '/') {\n server.middlewares.use((req, res, next) => {\n if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {\n res.statusCode = 302;\n res.setHeader('Location', open);\n res.end();\n return;\n }\n next();\n });\n }\n server.middlewares.use(devStorageMiddleware());\n for (const middleware of extraServerMiddlewares) {\n server.middlewares.use(middleware);\n }\n disposeConfigureServer = onConfigureServer?.(server);\n return () => {\n disposeConfigureServer?.();\n };\n },\n },\n ],\n ...(resolve ? { resolve } : {}),\n server: {\n ...(open !== undefined && open !== null ? { open } : {}),\n port: serverPort,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n ...build,\n },\n preview: {\n port: STAND_PREVIEW_PORT,\n ...(open && open !== '/' ? { open } : {}),\n headers: STAND_PREVIEW_HEADERS,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n };\n });\n}\n",
3645
- "../../project-templates/shared/stand-vite-base/config/lib/standApiProxy.ts": "import type { ProxyOptions } from 'vite';\n\nexport function createStandApiProxyOptions(\n apiBaseUrl: string,\n apiOrigin: string,\n): Record<string, ProxyOptions> {\n return {\n '/api': {\n target: apiBaseUrl,\n secure: false,\n changeOrigin: true,\n configure: (proxyInstance) => {\n proxyInstance.on('proxyReq', (proxyRequest) => {\n if (proxyRequest.getHeader('origin')) {\n proxyRequest.setHeader('origin', apiOrigin);\n }\n });\n },\n },\n };\n}\n",
3656
+ "../../project-templates/shared/stand-vite-base/config/lib/standApiProxy.ts": "import type { ProxyOptions } from 'vite';\n\nexport function createStandApiProxyOptions(\n apiBaseUrl: string,\n apiOrigin: string,\n): Record<string, ProxyOptions> {\n return {\n '/api': {\n target: apiBaseUrl,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n rewrite: (path) => path.replace(/^\\/api/, '') || '/',\n configure: (proxyInstance) => {\n proxyInstance.on('proxyReq', (proxyRequest) => {\n if (proxyRequest.getHeader('origin')) {\n proxyRequest.setHeader('origin', apiOrigin);\n }\n });\n },\n },\n };\n}\n",
3646
3657
  "../../project-templates/shared/stand-vite-base/config/lib/standPreviewSettings.ts.eta": "/**\n * Preview port for production-like stand runs (`npm run preview` / `serve:dist`).\n * Rendered from CLI `standScriptPorts.ts` at stand generation time.\n */\nexport const STAND_PREVIEW_PORT = <%~ it.standPreviewPort %>;\n\nexport const STAND_PREVIEW_HEADERS = {\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n} as const;\n",
3647
3658
  "../../project-templates/shared/stand-vite-base/config/lib/standProductionBuild.ts": "import type { BuildOptions } from 'vite';\n\n/** Production build defaults for demo stands (`vite build` / `vite preview`). */\nexport const STAND_VITE_PRODUCTION_BUILD = {\n minify: 'esbuild',\n cssMinify: true,\n sourcemap: false,\n} satisfies BuildOptions;\n",
3648
3659
  "../../project-templates/shared/stand-vite-base/scripts/devStorageMiddleware.ts.eta": "<%~ include('stand-dev-storage-middleware', it) %>\n",
@@ -3669,11 +3680,11 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3669
3680
  "../../project-templates/stand/advanced/module-federation/vite/README.md.eta": "<%~ include('stand-readme', it) %>\n",
3670
3681
  "../../project-templates/stand/advanced/module-federation/vite/config/dev-host.ts.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createModuleFederationHostConfig } from './lib/createModuleFederationHostConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createModuleFederationHostConfig({\n projectRoot,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n});\n",
3671
3682
  "../../project-templates/stand/advanced/module-federation/vite/config/dev-remote.ts.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport VitePlugin from '<%~ it.standVitePluginPackage %>/vite';\nimport { createModuleFederationRemoteConfig } from './lib/createModuleFederationRemoteConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createModuleFederationRemoteConfig({\n projectRoot,\n vitePlugin: VitePlugin,\n closedLoop: <%= it.standClosedLoop %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n});\n",
3672
- "../../project-templates/stand/advanced/module-federation/vite/config/lib/createModuleFederationHostConfig.ts": "import path from 'node:path';\nimport react from '@vitejs/plugin-react';\nimport { federation } from '@module-federation/vite';\nimport type { UserConfigExport } from 'vite';\nimport { defineConfig } from 'vite';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\nimport { crossOriginAssetCorsPlugin } from './crossOriginAssetCorsPlugin.ts';\nimport {\n MF_STAND_HOST,\n MF_STAND_HOST_PORT,\n moduleFederationHostRemotes,\n moduleFederationRemoteEntryUrl,\n} from './moduleFederationHosts.ts';\nimport { MODULE_FEDERATION_HOST_SHARED } from './moduleFederationShared.ts';\nimport { getModuleFederationHostOptimizeDepsEntries } from './moduleFederationOptimizeDeps.ts';\nimport { STAND_PREVIEW_HEADERS } from './standPreviewSettings.ts';\n\ninterface CreateModuleFederationHostConfigOptions {\n projectRoot: string;\n apiBaseUrl: string;\n apiOrigin: string;\n}\n\nexport function createModuleFederationHostConfig(options: CreateModuleFederationHostConfigOptions): UserConfigExport {\n const { projectRoot, apiBaseUrl, apiOrigin } = options;\n const remoteEntry = moduleFederationRemoteEntryUrl();\n\n return defineConfig(() => {\n const apiProxy = createStandApiProxyOptions(apiBaseUrl, apiOrigin);\n\n return {\n root: projectRoot,\n base: '/',\n plugins: [\n react(),\n federation({\n name: 'mf_stand_host',\n manifest: true,\n dts: false,\n shareStrategy: 'loaded-first',\n remotes: moduleFederationHostRemotes(remoteEntry),\n shared: MODULE_FEDERATION_HOST_SHARED,\n }),\n crossOriginAssetCorsPlugin(),\n {\n name: 'dev-storage',\n configureServer(server) {\n server.middlewares.use(devStorageMiddleware());\n },\n },\n ],\n resolve: {\n alias: {\n '@': path.join(projectRoot, 'src'),\n },\n dedupe: ['react', 'react-dom'],\n },\n optimizeDeps: {\n entries: getModuleFederationHostOptimizeDepsEntries(projectRoot),\n include: ['react', 'react-dom', 'react/jsx-dev-runtime'],\n exclude: ['editor/Editor'],\n },\n server: {\n port: MF_STAND_HOST_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_HOST_PORT}`,\n proxy: apiProxy,\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n target: 'esnext',\n outDir: './dist/host',\n },\n preview: {\n port: MF_STAND_HOST_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_HOST_PORT}`,\n headers: STAND_PREVIEW_HEADERS,\n proxy: apiProxy,\n },\n };\n });\n}\n",
3683
+ "../../project-templates/stand/advanced/module-federation/vite/config/lib/createModuleFederationHostConfig.ts": "import path from 'node:path';\nimport react from '@vitejs/plugin-react';\nimport { federation } from '@module-federation/vite';\nimport type { UserConfigExport } from 'vite';\nimport { defineConfig } from 'vite';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\nimport { crossOriginAssetCorsPlugin } from './crossOriginAssetCorsPlugin.ts';\nimport {\n MF_STAND_HOST,\n MF_STAND_HOST_PORT,\n moduleFederationHostRemotes,\n moduleFederationRemoteEntryUrl,\n waitForModuleFederationRemote,\n} from './moduleFederationHosts.ts';\nimport { MODULE_FEDERATION_HOST_SHARED } from './moduleFederationShared.ts';\nimport { getModuleFederationHostOptimizeDepsEntries } from './moduleFederationOptimizeDeps.ts';\nimport { STAND_PREVIEW_HEADERS } from './standPreviewSettings.ts';\n\ninterface CreateModuleFederationHostConfigOptions {\n projectRoot: string;\n apiBaseUrl: string;\n apiOrigin: string;\n}\n\nexport function createModuleFederationHostConfig(options: CreateModuleFederationHostConfigOptions): UserConfigExport {\n const { projectRoot, apiBaseUrl, apiOrigin } = options;\n const remoteEntry = moduleFederationRemoteEntryUrl();\n\n return defineConfig(() => {\n const apiProxy = createStandApiProxyOptions(apiBaseUrl, apiOrigin);\n\n return {\n root: projectRoot,\n base: '/',\n plugins: [\n react(),\n federation({\n name: 'mf_stand_host',\n manifest: true,\n dts: false,\n shareStrategy: 'loaded-first',\n remotes: moduleFederationHostRemotes(remoteEntry),\n shared: MODULE_FEDERATION_HOST_SHARED,\n }),\n crossOriginAssetCorsPlugin(),\n {\n name: 'wait-for-module-federation-remote',\n apply: 'serve',\n async configureServer() {\n await waitForModuleFederationRemote(remoteEntry);\n },\n },\n {\n name: 'dev-storage',\n configureServer(server) {\n server.middlewares.use(devStorageMiddleware());\n },\n },\n ],\n resolve: {\n alias: {\n '@': path.join(projectRoot, 'src'),\n },\n dedupe: ['react', 'react-dom'],\n },\n optimizeDeps: {\n entries: getModuleFederationHostOptimizeDepsEntries(projectRoot),\n include: ['react', 'react-dom', 'react/jsx-dev-runtime'],\n exclude: ['editor/Editor'],\n },\n server: {\n port: MF_STAND_HOST_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_HOST_PORT}`,\n proxy: apiProxy,\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n target: 'esnext',\n outDir: './dist/host',\n },\n preview: {\n port: MF_STAND_HOST_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_HOST_PORT}`,\n headers: STAND_PREVIEW_HEADERS,\n proxy: apiProxy,\n },\n };\n });\n}\n",
3673
3684
  "../../project-templates/stand/advanced/module-federation/vite/config/lib/createModuleFederationRemoteConfig.ts": "import path from 'node:path';\nimport react from '@vitejs/plugin-react';\nimport { federation } from '@module-federation/vite';\nimport { v4 as uuid } from 'uuid';\nimport type { PluginOption, UserConfigExport } from 'vite';\nimport { defineConfig } from 'vite';\nimport cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\nimport { crossOriginAssetCorsPlugin } from './crossOriginAssetCorsPlugin.ts';\nimport { editorWorkerCorsPlugin } from './editorWorkerCorsPlugin.ts';\nimport {\n MF_STAND_HOST,\n MF_STAND_REMOTE_PORT,\n moduleFederationCdnPublicPath,\n} from './moduleFederationHosts.ts';\nimport { MODULE_FEDERATION_REMOTE_SHARED } from './moduleFederationShared.ts';\nimport { getModuleFederationRemoteOptimizeDepsEntries } from './moduleFederationOptimizeDeps.ts';\nimport { STAND_PREVIEW_HEADERS } from './standPreviewSettings.ts';\n\ninterface CreateModuleFederationRemoteConfigOptions {\n projectRoot: string;\n vitePlugin: (options?: { publicPath?: string }) => PluginOption[];\n closedLoop?: boolean;\n apiBaseUrl: string;\n apiOrigin: string;\n}\n\nfunction remoteIndexHtmlPlugin(): PluginOption {\n return {\n name: 'module-federation-remote-index-html',\n configureServer(server) {\n server.middlewares.use((req, _res, next) => {\n if (req.url === '/' || req.url === '/index.html') {\n req.url = '/remote-index.html';\n }\n next();\n });\n },\n };\n}\n\nexport function createModuleFederationRemoteConfig(options: CreateModuleFederationRemoteConfigOptions): UserConfigExport {\n const {\n projectRoot,\n vitePlugin,\n closedLoop,\n apiBaseUrl,\n apiOrigin,\n } = options;\n const cdnPublicPath = moduleFederationCdnPublicPath();\n\n return defineConfig(() => {\n const apiProxy = closedLoop\n ? undefined\n : createStandApiProxyOptions(apiBaseUrl, apiOrigin);\n\n return {\n root: projectRoot,\n base: '/',\n plugins: [\n react(),\n federation({\n name: 'editor',\n filename: 'remoteEntry.js',\n manifest: true,\n dts: false,\n publicPath: cdnPublicPath,\n shareStrategy: 'loaded-first',\n exposes: {\n './Editor': './src/remote/EditorApp.tsx',\n },\n shared: MODULE_FEDERATION_REMOTE_SHARED,\n }),\n ...vitePlugin({\n publicPath: cdnPublicPath,\n }),\n cssInjectedByJsPlugin({\n injectCode: (content) => ``\n + `if (document) {`\n + `const style = document.createElement('style');`\n + `style.setAttribute('data-mf-app', 'module-federation-editor-remote');`\n + `style.innerHTML = ${content};`\n + `document.body.append(style);`\n + `}`,\n }),\n editorWorkerCorsPlugin(),\n crossOriginAssetCorsPlugin(),\n remoteIndexHtmlPlugin(),\n {\n name: 'dev-storage',\n configureServer(server) {\n server.middlewares.use(devStorageMiddleware());\n },\n },\n ],\n resolve: {\n alias: {\n '@': path.join(projectRoot, 'src'),\n },\n dedupe: ['react', 'react-dom'],\n },\n optimizeDeps: {\n entries: getModuleFederationRemoteOptimizeDepsEntries(projectRoot),\n include: ['react', 'react-dom', 'react/jsx-dev-runtime'],\n },\n server: {\n port: MF_STAND_REMOTE_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_REMOTE_PORT}`,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n target: 'esnext',\n outDir: './dist/remote',\n rollupOptions: {\n input: {\n remote: path.join(projectRoot, 'remote-index.html'),\n },\n output: {\n entryFileNames: `[name]${uuid()}.js`,\n chunkFileNames: `[name]${uuid()}.js`,\n assetFileNames: `[name]${uuid()}.[ext]`,\n },\n },\n },\n preview: {\n port: MF_STAND_REMOTE_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_REMOTE_PORT}`,\n headers: STAND_PREVIEW_HEADERS,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n };\n });\n}\n",
3674
3685
  "../../project-templates/stand/advanced/module-federation/vite/config/lib/crossOriginAssetCorsPlugin.ts": "import type { Plugin } from 'vite';\nimport type { ServerResponse } from 'node:http';\n\nfunction applyCrossOriginAssetHeaders(res: ServerResponse): void {\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');\n}\n\n/** CORS on the CDN dev/preview server: lets the host origin load static assets cross-origin. */\nexport function crossOriginAssetCorsPlugin(): Plugin {\n return {\n name: 'cross-origin-asset-cors',\n enforce: 'pre',\n configureServer(server) {\n server.middlewares.use((_req, res, next) => {\n applyCrossOriginAssetHeaders(res);\n next();\n });\n },\n configurePreviewServer(server) {\n server.middlewares.use((_req, res, next) => {\n applyCrossOriginAssetHeaders(res);\n next();\n });\n },\n };\n}\n",
3675
3686
  "../../project-templates/stand/advanced/module-federation/vite/config/lib/editorWorkerCorsPlugin.ts": "import type { Plugin } from 'vite';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nconst EDITOR_WORKER_PATH = '/monacoeditorwork/';\n\nfunction applyEditorWorkerCorsHeaders(res: ServerResponse): void {\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');\n res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');\n}\n\nfunction editorWorkerCorsMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: unknown) => void,\n): void {\n if (!req.url?.includes(EDITOR_WORKER_PATH)) {\n next();\n return;\n }\n\n applyEditorWorkerCorsHeaders(res);\n\n if (req.method === 'OPTIONS') {\n res.statusCode = 204;\n res.end();\n return;\n }\n\n next();\n}\n\n/** CORS for editor worker bundles under cross-origin Module Federation. */\nexport function editorWorkerCorsPlugin(): Plugin {\n return {\n name: 'editor-worker-cors',\n enforce: 'pre',\n configureServer(server) {\n server.middlewares.use(editorWorkerCorsMiddleware);\n },\n configurePreviewServer(server) {\n server.middlewares.use(editorWorkerCorsMiddleware);\n },\n };\n}\n",
3676
- "../../project-templates/stand/advanced/module-federation/vite/config/lib/moduleFederationHosts.ts": "/** Host and CDN remote both on localhost; different ports make them cross-origin, like MF behind a separate CDN. */\nexport const MF_STAND_HOST = 'localhost';\nexport const MF_STAND_HOST_PORT = 3000;\nexport const MF_STAND_REMOTE_PORT = 3001;\n\nexport function moduleFederationCdnPublicPath(port = MF_STAND_REMOTE_PORT): string {\n return `http://${MF_STAND_HOST}:${port}/`;\n}\n\nexport function moduleFederationRemoteEntryUrl(port = MF_STAND_REMOTE_PORT): string {\n return `${moduleFederationCdnPublicPath(port)}remoteEntry.js`;\n}\n\nexport function moduleFederationHostPageUrl(port = MF_STAND_HOST_PORT): string {\n return `http://${MF_STAND_HOST}:${port}/`;\n}\n\n/** Remotes host: a Vite remoteEntry is ESM, so it needs type module rather than a classic script. */\nexport function moduleFederationHostRemotes(remoteEntryUrl = moduleFederationRemoteEntryUrl()) {\n return {\n editor: {\n type: 'module' as const,\n name: 'editor',\n entry: remoteEntryUrl,\n entryGlobalName: 'editor',\n shareScope: 'default',\n },\n };\n}\n",
3687
+ "../../project-templates/stand/advanced/module-federation/vite/config/lib/moduleFederationHosts.ts": "/** Host and CDN remote both on localhost; different ports make them cross-origin, like MF behind a separate CDN. */\nexport const MF_STAND_HOST = 'localhost';\nconst MF_STAND_DEFAULT_HOST_PORT = 3000;\n\n/**\n * Host port comes from PLUGIN_DEV_PORT, like the other stands: `concurrently` drops a trailing\n * `--port`, so the environment is the only channel that reaches both the host and the remote.\n */\nfunction resolveModuleFederationHostPort(): number {\n const port = Number(process.env.PLUGIN_DEV_PORT);\n return Number.isInteger(port) && port > 0 ? port : MF_STAND_DEFAULT_HOST_PORT;\n}\n\nexport const MF_STAND_HOST_PORT = resolveModuleFederationHostPort();\n/** The remote (CDN) always sits on the next port, so one number describes the whole stand. */\nexport const MF_STAND_REMOTE_PORT = MF_STAND_HOST_PORT + 1;\n\nexport function moduleFederationCdnPublicPath(port = MF_STAND_REMOTE_PORT): string {\n return `http://${MF_STAND_HOST}:${port}/`;\n}\n\nexport function moduleFederationRemoteEntryUrl(port = MF_STAND_REMOTE_PORT): string {\n return `${moduleFederationCdnPublicPath(port)}remoteEntry.js`;\n}\n\nexport function moduleFederationHostPageUrl(port = MF_STAND_HOST_PORT): string {\n return `http://${MF_STAND_HOST}:${port}/`;\n}\n\n/** Remotes host: a Vite remoteEntry is ESM, so it needs type module rather than a classic script. */\nexport function moduleFederationHostRemotes(remoteEntryUrl = moduleFederationRemoteEntryUrl()) {\n return {\n editor: {\n type: 'module' as const,\n name: 'editor',\n entry: remoteEntryUrl,\n entryGlobalName: 'editor',\n shareScope: 'default',\n },\n };\n}\n\n/** Delays the host dev server until the remote serves remoteEntry.js; the port is not known to npm scripts. */\nexport async function waitForModuleFederationRemote(\n remoteEntryUrl = moduleFederationRemoteEntryUrl(),\n timeoutMs = 120_000,\n): Promise<void> {\n const startedAt = Date.now();\n let lastError = '';\n while (Date.now() - startedAt < timeoutMs) {\n try {\n const response = await fetch(remoteEntryUrl, { signal: AbortSignal.timeout(2_000) });\n if (response.ok) {\n return;\n }\n lastError = `HTTP ${response.status}`;\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n throw new Error(`Module Federation remote is not reachable at ${remoteEntryUrl} (${lastError || 'no response'})`);\n}\n",
3677
3688
  "../../project-templates/stand/advanced/module-federation/vite/config/lib/moduleFederationOptimizeDeps.ts": "import path from 'node:path';\n\n/** Entrypoints for the remote dev server dep scan, excluding the host index and editor/Editor. */\nexport function getModuleFederationRemoteOptimizeDepsEntries(projectRoot: string): string[] {\n return [\n path.join(projectRoot, 'remote-index.html'),\n path.join(projectRoot, 'src/remote/EditorApp.tsx'),\n path.join(projectRoot, 'src/remote/devShell.tsx'),\n ];\n}\n\n/** Entrypoints for the host dev server dep scan. */\nexport function getModuleFederationHostOptimizeDepsEntries(projectRoot: string): string[] {\n return [\n path.join(projectRoot, 'index.html'),\n path.join(projectRoot, 'src/index.tsx'),\n ];\n}\n",
3678
3689
  "../../project-templates/stand/advanced/module-federation/vite/config/lib/moduleFederationShared.ts": "/** Shared deps for @module-federation/vite; versions match the stand package.json. */\nexport const MODULE_FEDERATION_REACT_VERSION = '19.2.7';\n\nexport const MODULE_FEDERATION_REMOTE_SHARED = {\n react: {\n singleton: true,\n requiredVersion: MODULE_FEDERATION_REACT_VERSION,\n import: false,\n },\n 'react-dom': {\n singleton: true,\n requiredVersion: MODULE_FEDERATION_REACT_VERSION,\n import: false,\n },\n} as const;\n\n/** The host must load React before the MF runtime; otherwise ReactCurrentDispatcher breaks. */\nexport const MODULE_FEDERATION_HOST_SHARED = {\n react: {\n singleton: true,\n requiredVersion: MODULE_FEDERATION_REACT_VERSION,\n eager: true,\n },\n 'react-dom': {\n singleton: true,\n requiredVersion: MODULE_FEDERATION_REACT_VERSION,\n eager: true,\n },\n} as const;\n",
3679
3690
  "../../project-templates/stand/advanced/module-federation/vite/index.html.eta": "<%~ include('stand-vite-index-shell', it) %>\n",
@@ -3684,9 +3695,9 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3684
3695
  "../../project-templates/stand/advanced/module-federation/vite/src/dev/getAuthToken.ts.eta": "<%~ include('stand-get-auth-token', it) %>\n",
3685
3696
  "../../project-templates/stand/advanced/module-federation/vite/src/dev/oauthCredentials.ts": "export const oauthCredentials = {\n clientId: 'YOUR_CLIENT_ID',\n clientSecret: 'YOUR_CLIENT_SECRET',\n};\n\nexport function hasOAuthCredentials() {\n return oauthCredentials.clientId !== 'YOUR_CLIENT_ID'\n && oauthCredentials.clientSecret !== 'YOUR_CLIENT_SECRET';\n}\n",
3686
3697
  "../../project-templates/stand/advanced/module-federation/vite/src/dev/storageProvider.ts.eta": "<%~ include('stand-storage-provider', it) %>\n",
3687
- "../../project-templates/stand/advanced/module-federation/vite/src/index.tsx.eta": "import { lazy, Suspense } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nconst EditorRemote = lazy(() => import('editor/Editor'));\n\nfunction HostApp() {\n return (\n <div style={{ minHeight: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ margin: '0 auto', maxWidth: '1280px' }}>\n<% if (it.standShowModuleFederationBanner) { %>\n <div style={{ marginBottom: '12px', color: '#7c2d12', fontSize: '14px' }}>\n Module Federation stand — open <code>http://localhost:3000/</code> (remote/CDN on port 3001).\n </div>\n<% } %>\n <Suspense fallback={<div style={{ padding: '16px', fontSize: '14px' }}>Loading editor remote…</div>}>\n <EditorRemote />\n </Suspense>\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<HostApp />);\n",
3688
- "../../project-templates/stand/advanced/module-federation/vite/src/remote/EditorApp.tsx.eta": "import { useEffect, useRef, useState } from 'react';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from '../dev/email.html?raw';\nimport { editorConfig } from '../dev/editorConfig';\nimport { getAuthToken } from '../dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from '../dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nexport default function EditorRemoteApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'module-federation',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: {\n ...editorConfig,\n codeMode: 'true',\n codeModeDirection: 'bottom',\n },\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ minHeight: '80vh' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ minHeight: '80vh' }} />\n </div>\n );\n}\n",
3689
- "../../project-templates/stand/advanced/module-federation/vite/src/remote/devShell.tsx": "import { createRoot } from 'react-dom/client';\n\n/** Dev-only remote shell; the MF host runs on localhost:3000. */\nfunction RemoteDevShell() {\n return (\n <div style={{ padding: '16px', fontFamily: 'system-ui, sans-serif', fontSize: '14px', color: '#44506b' }}>\n Editor MF remote (localhost:3001). Open host at <code>http://localhost:3000/</code>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (rootElement) {\n createRoot(rootElement).render(<RemoteDevShell />);\n}\n",
3698
+ "../../project-templates/stand/advanced/module-federation/vite/src/index.tsx.eta": "import { lazy, Suspense } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nconst EditorRemote = lazy(() => import('editor/Editor'));\n\nfunction HostApp() {\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n<% if (it.standShowModuleFederationBanner) { %>\n <div style={{ marginBottom: '12px', color: '#7c2d12', fontSize: '14px' }}>\n Module Federation stand — host at <code>{window.location.origin}/</code>, remote/CDN on the next port (set both with PLUGIN_DEV_PORT).\n </div>\n<% } %>\n <Suspense fallback={<div style={{ padding: '16px', fontSize: '14px' }}>Loading editor remote…</div>}>\n <EditorRemote />\n </Suspense>\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<HostApp />);\n",
3699
+ "../../project-templates/stand/advanced/module-federation/vite/src/remote/EditorApp.tsx.eta": "import { useEffect, useRef, useState } from 'react';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from '../dev/email.html?raw';\nimport { editorConfig } from '../dev/editorConfig';\nimport { getAuthToken } from '../dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from '../dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nexport default function EditorRemoteApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'module-federation',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: {\n ...editorConfig,\n codeMode: 'true',\n codeModeDirection: 'bottom',\n },\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0 }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n );\n}\n",
3700
+ "../../project-templates/stand/advanced/module-federation/vite/src/remote/devShell.tsx": "import { createRoot } from 'react-dom/client';\n\n/** Dev-only remote shell; the MF host runs on the port just below this one. */\nfunction RemoteDevShell() {\n return (\n <div style={{ padding: '16px', fontFamily: 'system-ui, sans-serif', fontSize: '14px', color: '#44506b' }}>\n Editor MF remote ({window.location.host}). Open the host on the previous port.\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (rootElement) {\n createRoot(rootElement).render(<RemoteDevShell />);\n}\n",
3690
3701
  "../../project-templates/stand/advanced/module-federation/vite/src/types/mf.d.ts": "declare module 'editor/Editor' {\n import type { ComponentType } from 'react';\n\n const EditorRemoteApp: ComponentType;\n export default EditorRemoteApp;\n}\n",
3691
3702
  "../../project-templates/stand/advanced/shadow-dom/vite/README.md.eta": "<%~ include('stand-readme', it) %>\n",
3692
3703
  "../../project-templates/stand/advanced/shadow-dom/vite/config/dev-host.ts.eta": "<%~ include('stand-dev-host-vite', it) %>\n",
@@ -3754,13 +3765,13 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3754
3765
  "../../project-templates/stand/angular/esbuild/esbuild/plugins.cjs.eta": "const fs = require('node:fs');\nconst path = require('node:path');\n\n/** Vite-style `?raw` imports for stand dev email HTML (webpack used asset/source rule). */\nconst rawImportPlugin = {\n name: 'stand-raw-import',\n setup(build) {\n build.onResolve({ filter: /\\?raw$/ }, (args) => {\n const sourcePath = args.path.replace(/\\?raw$/, '');\n return {\n path: path.resolve(args.resolveDir, sourcePath),\n namespace: 'stand-raw-import',\n };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'stand-raw-import' }, async (args) => {\n const contents = await fs.promises.readFile(args.path, 'utf8');\n return {\n contents: `export default ${JSON.stringify(contents)};`,\n loader: 'js',\n };\n });\n },\n};\n\nmodule.exports = [rawImportPlugin];\n",
3755
3766
  "../../project-templates/stand/angular/esbuild/esbuild/publicPath-shim.ts.eta": "type ProductNamespace = {\n publicPath?: string;\n};\n\nconst namespace = <%~ JSON.stringify(it.standWindowNamespace) %>;\nconst publicPath = <%~ JSON.stringify(it.standAngularProductPublicPath + '/') %>;\n\nconst root = window as unknown as Record<string, ProductNamespace | undefined>;\n\nroot[namespace] = {\n ...(root[namespace] ?? {}),\n publicPath,\n};\n\nexport {};\n",
3756
3767
  "../../project-templates/stand/angular/esbuild/package.json.eta": "<%~ include('stand-package-json', it) %>\n",
3757
- "../../project-templates/stand/angular/esbuild/proxy.conf.json.eta": "{\n \"/api\": {\n \"target\": <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n \"secure\": false,\n \"changeOrigin\": true,\n \"headers\": {\n \"origin\": <%~ JSON.stringify(it.standOpenApiOrigin) %>\n }\n }\n}\n",
3768
+ "../../project-templates/stand/angular/esbuild/proxy.conf.json.eta": "{\n \"/api\": {\n \"target\": <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n \"secure\": false,\n \"changeOrigin\": true,\n \"pathRewrite\": { \"^/api\": \"\" },\n \"headers\": {\n \"origin\": <%~ JSON.stringify(it.standOpenApiOrigin) %>\n }\n }\n}\n",
3758
3769
  "../../project-templates/stand/angular/esbuild/scripts/chunkRepro.cjs.eta": "#!/usr/bin/env node\n/**\n * Cross-origin chunk repro: HTML on :4200, JS chunks and <base href> on :4201.\n * Lazy chunk import.meta.url points at the CDN host; product assets stay on the page\n * origin (panel/<app>/).\n * Compile graph: thin facade only (~0.4 MB); static/esm is copied into panel/, not bundled.\n *\n * Usage: npm run build:rebundle && npm run serve:chunk-repro\n */\nconst http = require('node:http');\nconst https = require('node:https');\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst { URL } = require('node:url');\n\nconst API_PROXY_ENABLED = <%= it.standClosedLoop ? 'false' : 'true' %>;\nconst API_TARGET = <%~ JSON.stringify(it.standOpenApiBaseUrl) %>;\nconst API_ORIGIN = <%~ JSON.stringify(it.standOpenApiOrigin) %>;\nconst SITE_PORT = 4200;\nconst CDN_PORT = 4201;\n// <base href> points at the CDN, so every relative path (publicPath from the shim,\n// iframe src, worker url) resolves against that origin instead of the page origin.\n// STAND_CDN_BASE_HREF=0 keeps the page base href for comparison.\nconst CDN_BASE_HREF = process.env.STAND_CDN_BASE_HREF !== '0';\nconst DIST_RELATIVE = <%~ JSON.stringify(it.standAngularChunkReproDistRelative) %>;\n\nconst MIME = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n};\n\nconst STATIC_HEADERS = {\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n};\n\n// The page origin and the API port differ under this repro, so proxied answers need CORS.\nconst CORS_HEADERS = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Max-Age': '600',\n};\n\nfunction contentType(filePath) {\n return MIME[path.extname(filePath).toLowerCase()] || 'application/octet-stream';\n}\n\nfunction resolveFile(distDir, requestPath) {\n const safe = path.normalize(requestPath).replace(/^(\\.\\.[/\\\\])+/, '');\n const candidate = path.join(distDir, safe);\n if (!candidate.startsWith(distDir)) return null;\n if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;\n return null;\n}\n\nfunction patchIndexHtml(html, cdnOrigin) {\n const patched = html.replace(\n /(<script\\b[^>]*\\ssrc=\")(?!https?:|\\/\\/)([^\"]+)\"/gi,\n (_, prefix, src) => `${prefix}${cdnOrigin}/${src.replace(/^\\//, '')}\"`,\n );\n\n if (!CDN_BASE_HREF) {\n return patched;\n }\n\n return patched.replace(/(<base\\b[^>]*\\shref=\")[^\"]*\"/i, (_, prefix) => `${prefix}${cdnOrigin}/\"`);\n}\n\nfunction readRequestBody(req) {\n return new Promise((resolve, reject) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n req.on('error', reject);\n });\n}\n\nfunction buildProxyRequestHeaders(req, targetUrl, bodyLength) {\n const headers = { ...req.headers, host: targetUrl.host };\n if (headers.origin) {\n headers.origin = API_ORIGIN;\n }\n delete headers.connection;\n delete headers['transfer-encoding'];\n if (bodyLength > 0) {\n headers['content-length'] = String(bodyLength);\n } else {\n delete headers['content-length'];\n }\n return headers;\n}\n\nfunction drainResponse(proxyRes) {\n return new Promise((resolve) => {\n proxyRes.on('end', resolve);\n proxyRes.resume();\n });\n}\n\nfunction proxyApiRequest(req, res, targetUrl, body, redirectCount, method) {\n const MAX_REDIRECTS = 5;\n if (redirectCount > MAX_REDIRECTS) {\n res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Too many redirects');\n return;\n }\n\n const requestMethod = method || req.method || 'GET';\n const transport = targetUrl.protocol === 'https:' ? https : http;\n const headers = buildProxyRequestHeaders(req, targetUrl, body.length);\n\n const proxyReq = transport.request(\n targetUrl,\n { method: requestMethod, headers },\n (proxyRes) => {\n const status = proxyRes.statusCode || 502;\n const location = proxyRes.headers.location;\n if (status >= 300 && status < 400 && location) {\n drainResponse(proxyRes).then(() => {\n const nextUrl = new URL(location, targetUrl);\n const useGet = status === 303;\n proxyApiRequest(\n req,\n res,\n nextUrl,\n useGet ? Buffer.alloc(0) : body,\n redirectCount + 1,\n useGet ? 'GET' : requestMethod,\n );\n });\n return;\n }\n\n const outHeaders = { ...proxyRes.headers, ...CORS_HEADERS };\n delete outHeaders.location;\n res.writeHead(status, outHeaders);\n proxyRes.pipe(res);\n },\n );\n\n proxyReq.on('error', (error) => {\n console.error('[chunkRepro] API proxy error:', error.message);\n if (!res.headersSent) {\n res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Bad Gateway');\n }\n });\n\n if (body.length > 0) {\n proxyReq.write(body);\n }\n proxyReq.end();\n}\n\nasync function proxyApi(req, res) {\n const body = await readRequestBody(req);\n const targetUrl = new URL(req.url || '/', API_TARGET);\n proxyApiRequest(req, res, targetUrl, body, 0);\n}\n\nfunction createStaticServer(distDir, port, options = {}) {\n const { patchIndex = false, cdnOrigin = '' } = options;\n\n return http.createServer((req, res) => {\n const url = new URL(req.url || '/', `http://127.0.0.1:${port}`);\n const pathname = decodeURIComponent(url.pathname);\n\n // Both servers proxy /api: with <base href> on the CDN even a root-relative\n // fetch('/api') takes its origin from the base, so it lands on the CDN port.\n if (API_PROXY_ENABLED && pathname.startsWith('/api')) {\n if ((req.method || '').toUpperCase() === 'OPTIONS') {\n res.writeHead(204, CORS_HEADERS);\n res.end();\n return;\n }\n proxyApi(req, res);\n return;\n }\n\n let filePath = resolveFile(distDir, pathname === '/' ? '/index.html' : pathname);\n\n if (!filePath) {\n res.writeHead(404, STATIC_HEADERS);\n res.end('Not found');\n return;\n }\n\n if (patchIndex && filePath.endsWith('index.html')) {\n const raw = fs.readFileSync(filePath, 'utf8');\n res.writeHead(200, { ...STATIC_HEADERS, 'Content-Type': 'text/html; charset=utf-8' });\n res.end(patchIndexHtml(raw, cdnOrigin));\n return;\n }\n\n res.writeHead(200, { ...STATIC_HEADERS, 'Content-Type': contentType(filePath) });\n fs.createReadStream(filePath).pipe(res);\n }).listen(port, () => {\n console.log(`[chunkRepro] ${patchIndex ? 'site' : 'cdn'} → http://localhost:${port}/`);\n if (API_PROXY_ENABLED) {\n console.log(`[chunkRepro] /api → ${API_TARGET}`);\n }\n });\n}\n\nconst distDir = path.resolve(process.cwd(), DIST_RELATIVE);\nif (!fs.existsSync(path.join(distDir, 'index.html'))) {\n console.error(`[chunkRepro] Missing ${DIST_RELATIVE}/index.html — run \\`npm run build:rebundle\\` first.`);\n process.exit(1);\n}\n\nconst cdnOrigin = `http://localhost:${CDN_PORT}`;\ncreateStaticServer(distDir, CDN_PORT);\ncreateStaticServer(distDir, SITE_PORT, { patchIndex: true, cdnOrigin });\n\nconsole.log(\n CDN_BASE_HREF\n ? `[chunkRepro] <base href> → ${cdnOrigin}/ (set STAND_CDN_BASE_HREF=0 to disable)`\n : '[chunkRepro] <base href> left on the page origin',\n);\nconsole.log('[chunkRepro] Open http://localhost:4200/ — check Network + console [publicPath-diag]');\n",
3759
3770
  "../../project-templates/stand/angular/esbuild/scripts/devStorageMiddleware.ts.eta": "<%~ include('stand-dev-storage-middleware', it) %>\n",
3760
3771
  "../../project-templates/stand/angular/esbuild/scripts/formidable.d.ts": "declare module 'formidable';\n",
3761
3772
  "../../project-templates/stand/angular/esbuild/scripts/publicPathDiagnostics.ts.eta": "type ProductNamespace = {\n publicPath?: string;\n};\n\nexport type PublicPathDiagSnapshot = {\n label: string;\n pageOrigin: string;\n pageHref: string;\n baseURI: string;\n windowNamespacePublicPath: string | undefined;\n expectedShimPrefix: string;\n bareNamespaceReadable: boolean;\n bareNamespacePublicPath: string | undefined;\n resolvedFromBaseURI: string;\n resolvedFromPageOrigin: string;\n basesDiverge: boolean;\n};\n\n/**\n * resolveAgainst expands publicPath against the given base; empty string when the base is invalid.\n * A relative publicPath resolves to different addresses against <base href> and the page origin;\n * that divergence is what breaks asset loading when base href points at another origin.\n */\nfunction resolveAgainst(publicPath: string | undefined, base: string): string {\n if (!publicPath || !base) {\n return '';\n }\n try {\n return new URL(publicPath, base).href;\n } catch {\n return '';\n }\n}\n\nconst namespace = <%~ JSON.stringify(it.standWindowNamespace) %>;\nconst expectedShimPrefix = <%~ JSON.stringify(it.standAngularProductPublicPath + '/') %>;\n\nfunction readBareNamespacePublicPath(): { readable: boolean; publicPath: string | undefined } {\n try {\n // eslint-disable-next-line no-new-func\n const read = new Function(\n `try { return typeof <%= it.standWindowNamespace %> !== 'undefined' ? <%= it.standWindowNamespace %>.publicPath : undefined; } catch (e) { return undefined; }`,\n ) as () => string | undefined;\n return { readable: true, publicPath: read() };\n } catch {\n return { readable: false, publicPath: undefined };\n }\n}\n\nexport function snapshotPublicPathDiagnostics(label: string): PublicPathDiagSnapshot {\n const root = window as unknown as Record<string, ProductNamespace | undefined>;\n const bare = readBareNamespacePublicPath();\n const pageOrigin = window.location.origin;\n const baseURI = typeof document !== 'undefined' ? document.baseURI : '';\n const publicPath = root[namespace]?.publicPath;\n const resolvedFromBaseURI = resolveAgainst(publicPath, baseURI);\n const resolvedFromPageOrigin = resolveAgainst(publicPath, pageOrigin);\n\n const snapshot: PublicPathDiagSnapshot = {\n label,\n pageOrigin,\n pageHref: window.location.href,\n baseURI,\n windowNamespacePublicPath: publicPath,\n expectedShimPrefix,\n bareNamespaceReadable: bare.readable,\n bareNamespacePublicPath: bare.publicPath,\n resolvedFromBaseURI,\n resolvedFromPageOrigin,\n basesDiverge: Boolean(resolvedFromBaseURI) && resolvedFromBaseURI !== resolvedFromPageOrigin,\n };\n\n const bag = window as unknown as { __standPublicPathDiagnostics?: PublicPathDiagSnapshot[] };\n bag.__standPublicPathDiagnostics = [...(bag.__standPublicPathDiagnostics ?? []), snapshot];\n console.info('[publicPath-diag]', label, snapshot);\n return snapshot;\n}\n",
3762
3773
  "../../project-templates/stand/angular/esbuild/scripts/standDevMiddleware.ts.eta": "import type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport devStorageMiddleware from './devStorageMiddleware';\n\nconst HOST_EDITOR_ASSET_HEADERS = Object.freeze({\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n});\n\ntype ConnectMiddleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\nfunction createHostEditorHeaderMiddleware(): ConnectMiddleware {\n return (_req, res, next) => {\n for (const [key, value] of Object.entries(HOST_EDITOR_ASSET_HEADERS)) {\n res.setHeader(key, value);\n }\n next();\n };\n}\n\nconst middlewares: ConnectMiddleware[] = [\n createHostEditorHeaderMiddleware(),\n devStorageMiddleware(),\n];\n\nexport default middlewares;\n",
3763
- "../../project-templates/stand/angular/esbuild/src/app/app.component.css": ".page {\n font-family: system-ui, sans-serif;\n margin: 0 auto;\n max-width: 1200px;\n padding: 16px;\n}\n\n.error {\n color: #b42318;\n margin: 0 0 12px;\n}\n\n.diag {\n background: #f4f4f5;\n border: 1px solid #d4d4d8;\n font-size: 12px;\n margin: 0 0 12px;\n max-height: 200px;\n overflow: auto;\n padding: 8px;\n}\n\n.editor-mount {\n min-height: 640px;\n}\n",
3774
+ "../../project-templates/stand/angular/esbuild/src/app/app.component.css": ".page {\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n font-family: system-ui, sans-serif;\n height: 100vh;\n margin: 0 auto;\n max-width: 1200px;\n padding: 16px;\n}\n\n.error {\n color: #b42318;\n margin: 0 0 12px;\n}\n\n.diag {\n background: #f4f4f5;\n border: 1px solid #d4d4d8;\n flex-shrink: 0;\n font-size: 12px;\n margin: 0 0 12px;\n max-height: 200px;\n overflow: auto;\n padding: 8px;\n}\n\n.editor-mount {\n flex: 1;\n min-height: 0;\n}\n",
3764
3775
  "../../project-templates/stand/angular/esbuild/src/app/app.component.html.eta": "<main class=\"page\">\n @if (initError()) {\n <p class=\"error\">Editor failed: {{ initError() }}</p>\n }\n @if (publicPathDiag()) {\n <pre class=\"diag\">{{ publicPathDiag() }}</pre>\n }\n <div id=\"editor-root\" class=\"editor-mount\"></div>\n</main>\n",
3765
3776
  "../../project-templates/stand/angular/esbuild/src/app/app.component.ts.eta": "import { Component, AfterViewInit, signal } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport type { PublicPathDiagSnapshot } from '../../scripts/publicPathDiagnostics';\n\ntype DiagBag = { __standPublicPathDiagnostics?: PublicPathDiagSnapshot[] };\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [CommonModule],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css',\n})\nexport class AppComponent implements AfterViewInit {\n readonly initError = signal<string | null>(null);\n readonly publicPathDiag = signal<string | null>(null);\n\n ngAfterViewInit(): void {\n import('./editor-host')\n .then(({ initOAuthEditor }) => initOAuthEditor())\n .then(() => {\n const bag = window as unknown as DiagBag;\n const last = bag.__standPublicPathDiagnostics?.at(-1);\n if (last) {\n this.publicPathDiag.set(JSON.stringify(last, null, 2));\n }\n })\n .catch((error) => {\n this.initError.set(error instanceof Error ? error.message : String(error));\n });\n }\n}\n",
3766
3777
  "../../project-templates/stand/angular/esbuild/src/app/app.config.ts.eta": "import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\n\nexport const appConfig: ApplicationConfig = {\n providers: [provideZoneChangeDetection({ eventCoalescing: true })],\n};\n",
@@ -3786,7 +3797,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3786
3797
  "../../project-templates/stand/angular/webpack/scripts/hostDevServerHeaders.ts.eta": "<%~ include('stand-host-dev-server-webpack', it) %>\n",
3787
3798
  "../../project-templates/stand/angular/webpack/scripts/publicPath-shim.ts.eta": "type ProductNamespace = {\n publicPath?: string;\n};\n\nconst namespace = <%~ JSON.stringify(it.standWindowNamespace) %>;\nconst publicPath = <%~ JSON.stringify(it.standAngularProductPublicPath + '/') %>;\n\nconst root = window as unknown as Record<string, ProductNamespace | undefined>;\n\nroot[namespace] = {\n ...(root[namespace] ?? {}),\n publicPath,\n};\n\nexport {};\n",
3788
3799
  "../../project-templates/stand/angular/webpack/scripts/publicPathDiagnostics.ts.eta": "type ProductNamespace = {\n publicPath?: string;\n};\n\nexport type PublicPathDiagSnapshot = {\n label: string;\n pageOrigin: string;\n pageHref: string;\n baseURI: string;\n windowNamespacePublicPath: string | undefined;\n expectedShimPrefix: string;\n bareNamespaceReadable: boolean;\n bareNamespacePublicPath: string | undefined;\n};\n\nconst namespace = <%~ JSON.stringify(it.standWindowNamespace) %>;\nconst expectedShimPrefix = <%~ JSON.stringify(it.standAngularProductPublicPath + '/') %>;\n\nfunction readBareNamespacePublicPath(): { readable: boolean; publicPath: string | undefined } {\n try {\n // eslint-disable-next-line no-new-func\n const read = new Function(\n `try { return typeof <%= it.standWindowNamespace %> !== 'undefined' ? <%= it.standWindowNamespace %>.publicPath : undefined; } catch (e) { return undefined; }`,\n ) as () => string | undefined;\n return { readable: true, publicPath: read() };\n } catch {\n return { readable: false, publicPath: undefined };\n }\n}\n\nexport function snapshotPublicPathDiagnostics(label: string): PublicPathDiagSnapshot {\n const root = window as unknown as Record<string, ProductNamespace | undefined>;\n const bare = readBareNamespacePublicPath();\n\n const snapshot: PublicPathDiagSnapshot = {\n label,\n pageOrigin: window.location.origin,\n pageHref: window.location.href,\n baseURI: typeof document !== 'undefined' ? document.baseURI : '',\n windowNamespacePublicPath: root[namespace]?.publicPath,\n expectedShimPrefix,\n bareNamespaceReadable: bare.readable,\n bareNamespacePublicPath: bare.publicPath,\n };\n\n const bag = window as unknown as { __standPublicPathDiagnostics?: PublicPathDiagSnapshot[] };\n bag.__standPublicPathDiagnostics = [...(bag.__standPublicPathDiagnostics ?? []), snapshot];\n console.info('[publicPath-diag]', label, snapshot);\n return snapshot;\n}\n",
3789
- "../../project-templates/stand/angular/webpack/src/app/app.component.css": ".page {\n font-family: system-ui, sans-serif;\n margin: 0 auto;\n max-width: 1200px;\n padding: 16px;\n}\n\n.error {\n color: #b42318;\n margin: 0 0 12px;\n}\n\n.diag {\n background: #f4f4f5;\n border: 1px solid #d4d4d8;\n font-size: 12px;\n margin: 0 0 12px;\n max-height: 200px;\n overflow: auto;\n padding: 8px;\n}\n\n.editor-mount {\n min-height: 640px;\n}\n",
3800
+ "../../project-templates/stand/angular/webpack/src/app/app.component.css": ".page {\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n font-family: system-ui, sans-serif;\n height: 100vh;\n margin: 0 auto;\n max-width: 1200px;\n padding: 16px;\n}\n\n.error {\n color: #b42318;\n margin: 0 0 12px;\n}\n\n.diag {\n background: #f4f4f5;\n border: 1px solid #d4d4d8;\n flex-shrink: 0;\n font-size: 12px;\n margin: 0 0 12px;\n max-height: 200px;\n overflow: auto;\n padding: 8px;\n}\n\n.editor-mount {\n flex: 1;\n min-height: 0;\n}\n",
3790
3801
  "../../project-templates/stand/angular/webpack/src/app/app.component.html.eta": "<main class=\"page\">\n @if (initError()) {\n <p class=\"error\">Editor failed: {{ initError() }}</p>\n }\n @if (publicPathDiag()) {\n <pre class=\"diag\">{{ publicPathDiag() }}</pre>\n }\n <div id=\"editor-root\" class=\"editor-mount\"></div>\n</main>\n",
3791
3802
  "../../project-templates/stand/angular/webpack/src/app/app.component.ts.eta": "import { Component, AfterViewInit, signal } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport type { PublicPathDiagSnapshot } from '../../scripts/publicPathDiagnostics';\n\ntype DiagBag = { __standPublicPathDiagnostics?: PublicPathDiagSnapshot[] };\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [CommonModule],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css',\n})\nexport class AppComponent implements AfterViewInit {\n readonly initError = signal<string | null>(null);\n readonly publicPathDiag = signal<string | null>(null);\n\n ngAfterViewInit(): void {\n import('./editor-host')\n .then(({ initOAuthEditor }) => initOAuthEditor())\n .then(() => {\n const bag = window as unknown as DiagBag;\n const last = bag.__standPublicPathDiagnostics?.at(-1);\n if (last) {\n this.publicPathDiag.set(JSON.stringify(last, null, 2));\n }\n })\n .catch((error) => {\n this.initError.set(error instanceof Error ? error.message : String(error));\n });\n }\n}\n",
3792
3803
  "../../project-templates/stand/angular/webpack/src/app/app.config.ts.eta": "import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\n\nexport const appConfig: ApplicationConfig = {\n providers: [provideZoneChangeDetection({ eventCoalescing: true })],\n};\n",
@@ -3999,6 +4010,7 @@ function buildPluginPackageJsonData(options) {
3999
4010
  const extensionsSandboxVersion = localTarballs?.extensionsSandboxPackageName || packageConfig.extensionsSandboxVersion;
4000
4011
  const extensionsReactVersion = localTarballs?.extensionsReactPackageName || packageConfig.extensionsReactVersion;
4001
4012
  const uiKitVersion = localTarballs?.uiKitPackageName || packageConfig.uiKitVersion;
4013
+ const startProductionScript = localTarballs ? "tsx ./scripts/production-runner.ts --bundler-runtime-strict" : "tsx ./scripts/production-runner.ts";
4002
4014
  const releaseHostCommand = bundler === "vite" ? `vite --config ./${releaseConfig}` : `${WEBPACK_CLI_COMMAND} serve --config ./${releaseConfig} --mode development`;
4003
4015
  const mainPkgKey = resolveLocalPublishedPackageKey(localPublishedNames, "packageName", packageConfig.packageName);
4004
4016
  const extApiKey = resolveLocalPublishedPackageKey(localPublishedNames, "extensionsApiPackageName", packageConfig.extensionsApiPackageName);
@@ -4046,9 +4058,12 @@ function buildPluginPackageJsonData(options) {
4046
4058
  scripts: bundler === "vite" ? {
4047
4059
  start: "tsx ./scripts/dev-runner.ts",
4048
4060
  "start:release": startReleaseScript,
4061
+ "start:production": startProductionScript,
4049
4062
  "dev:app": "tsx ./scripts/dev-runner.ts",
4050
4063
  "dev:host": `vite --config ./${generatedPaths.devConfig}`,
4051
4064
  "dev:release-host": releaseHostCommand,
4065
+ "build:release-host": `vite build --config ./${releaseConfig}`,
4066
+ "preview:release-host": `vite preview --config ./${releaseConfig}`,
4052
4067
  "dev:sandbox": `vite build --config ./${generatedPaths.sandboxBuildConfig} --watch --mode development`,
4053
4068
  "dev:sandbox:once": `vite build --config ./${generatedPaths.sandboxBuildConfig} --mode development`,
4054
4069
  build: "tsx ./scripts/build-runner.ts",
@@ -4058,9 +4073,12 @@ function buildPluginPackageJsonData(options) {
4058
4073
  } : {
4059
4074
  start: "tsx ./scripts/dev-runner.ts",
4060
4075
  "start:release": startReleaseScript,
4076
+ "start:production": startProductionScript,
4061
4077
  "dev:app": "tsx ./scripts/dev-runner.ts",
4062
4078
  "dev:host": `${WEBPACK_CLI_COMMAND} serve --config ./${generatedPaths.devConfig} --mode development`,
4063
4079
  "dev:release-host": releaseHostCommand,
4080
+ "build:release-host": `${WEBPACK_CLI_COMMAND} --config ./${releaseConfig} --mode production`,
4081
+ "preview:release-host": `${WEBPACK_CLI_COMMAND} serve --config ./${releaseConfig} --mode production`,
4064
4082
  "dev:sandbox": `${WEBPACK_CLI_COMMAND} --config ./${generatedPaths.sandboxBuildConfig} --mode development --watch`,
4065
4083
  "dev:sandbox:once": `${WEBPACK_CLI_COMMAND} --config ./${generatedPaths.sandboxBuildConfig} --mode development`,
4066
4084
  build: "tsx ./scripts/build-runner.ts",
@@ -4216,6 +4234,8 @@ function buildPluginEtaData(templateOptions) {
4216
4234
  const isTemplating = preset === "templating";
4217
4235
  const productApiName = String(packageConfig?.appName || "app").replace(/[^a-zA-Z0-9_$]/g, "") || "app";
4218
4236
  const releaseUsesUmd = pluginFormat === "umd";
4237
+ const releaseHostCompatGlobals = importsMode !== "esm";
4238
+ const devHostCompatGlobals = isLegacyWebpack;
4219
4239
  const targetLabel = formatPluginTargetTemplateLabel(t, target, advancedTarget);
4220
4240
  const pluginKeyLiteral = toLiteral(pluginKey);
4221
4241
  const importsModeLiteral = toLiteral(importsMode);
@@ -4264,6 +4284,8 @@ function buildPluginEtaData(templateOptions) {
4264
4284
  pluginFormatVite,
4265
4285
  productApiName,
4266
4286
  releaseUsesUmd,
4287
+ releaseHostCompatGlobals,
4288
+ devHostCompatGlobals,
4267
4289
  bundler,
4268
4290
  importsMode,
4269
4291
  pluginFormat,
@@ -4400,6 +4422,7 @@ function getPostCreateRunCommands(startMode, options, packageManager = "npm") {
4400
4422
  if (isAngularEsbuildStand(options)) return [[packageManager, ["run", "build"]], [packageManager, ["run", "serve:chunk-repro"]]];
4401
4423
  return [[packageManager, ["run", "build:rebundle"]], [packageManager, ["run", "serve:chunk-repro"]]];
4402
4424
  }
4425
+ if (startMode === "production" && options.kind !== "demo-stand") return [[packageManager, ["run", "start:production"]]];
4403
4426
  if (options.kind === "demo-stand") {
4404
4427
  if (isModuleFederationStand(options)) return [[packageManager, ["run", "start"]]];
4405
4428
  const serveScript = getStandProductionServeScript(options);
@@ -4519,6 +4542,10 @@ async function promptForPostCreateActions(options, messages) {
4519
4542
  title: isStand ? messages.promptStandStartModeRelease : messages.promptStartModeRelease,
4520
4543
  value: "release"
4521
4544
  },
4545
+ ...isStand ? [] : [{
4546
+ title: messages.promptStartModeProduction,
4547
+ value: "production"
4548
+ }],
4522
4549
  ...isAngularReproStand ? [{
4523
4550
  title: messages.promptStandStartModeRepro,
4524
4551
  value: "repro"
@@ -4554,34 +4581,35 @@ function printNextSteps(result, options, actions, messages, credentialsReady = f
4554
4581
  title: messages.nextStepFillCredentials,
4555
4582
  command: getCredentialsMessage(options, messages)
4556
4583
  });
4557
- if (options.kind === "plugin") if (!actions.installDependencies) steps.push({
4558
- title: messages.nextStepInstall,
4559
- command: installCommand
4560
- }, {
4561
- title: messages.nextStepStartDebug,
4562
- command: startDebugCommand
4563
- }, {
4564
- title: messages.nextStepStartRelease,
4565
- command: startReleaseCommand
4566
- });
4567
- else if (actions.startMode === "none") steps.push({
4568
- title: messages.nextStepAlreadyInstalled,
4569
- command: null
4570
- }, {
4571
- title: messages.nextStepStartDebug,
4572
- command: startDebugCommand
4573
- }, {
4574
- title: messages.nextStepStartRelease,
4575
- command: startReleaseCommand
4576
- });
4577
- else steps.push({
4578
- title: messages.nextStepAlreadyInstalled,
4579
- command: null
4580
- }, {
4581
- title: actions.startMode === "release" ? messages.nextStepServerStartingRelease : messages.nextStepServerStartingDebug,
4582
- command: null
4583
- });
4584
- else if (!actions.installDependencies) steps.push({
4584
+ if (options.kind === "plugin") {
4585
+ if (!actions.installDependencies) steps.push({
4586
+ title: messages.nextStepInstall,
4587
+ command: installCommand
4588
+ }, {
4589
+ title: messages.nextStepStartDebug,
4590
+ command: startDebugCommand
4591
+ }, {
4592
+ title: messages.nextStepStartRelease,
4593
+ command: startReleaseCommand
4594
+ });
4595
+ else if (actions.startMode === "none") steps.push({
4596
+ title: messages.nextStepAlreadyInstalled,
4597
+ command: null
4598
+ }, {
4599
+ title: messages.nextStepStartDebug,
4600
+ command: startDebugCommand
4601
+ }, {
4602
+ title: messages.nextStepStartRelease,
4603
+ command: startReleaseCommand
4604
+ });
4605
+ else steps.push({
4606
+ title: messages.nextStepAlreadyInstalled,
4607
+ command: null
4608
+ }, {
4609
+ title: actions.startMode === "release" ? messages.nextStepServerStartingRelease : messages.nextStepServerStartingDebug,
4610
+ command: null
4611
+ });
4612
+ } else if (!actions.installDependencies) steps.push({
4585
4613
  title: messages.nextStepInstall,
4586
4614
  command: installCommand
4587
4615
  }, {