useblocks-cli 1.1.85-dev.1 → 1.1.85-dev.10

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 (2) hide show
  1. package/dist/index.js +41 -32
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -422,9 +422,9 @@ var DEFAULT_EXTENSIONS_API_PACKAGE = "useblocks-extensions-api";
422
422
  var DEFAULT_EXTENSIONS_REACT_PACKAGE = "useblocks-extensions-react";
423
423
  var DEFAULT_EXTENSIONS_SANDBOX_PACKAGE = "useblocks-extensions-sandbox";
424
424
  var DEFAULT_CLI_PACKAGE = "useblocks-cli";
425
- var DEFAULT_VERSION = "1.1.85-dev.1";
426
- var DEFAULT_UI_KIT_VERSION = "1.1.85-dev.1";
427
- var DEFAULT_CLI_VERSION = "1.1.85-dev.1";
425
+ var DEFAULT_VERSION = "1.1.85-dev.10";
426
+ var DEFAULT_UI_KIT_VERSION = "1.1.85-dev.10";
427
+ var DEFAULT_CLI_VERSION = "1.1.85-dev.10";
428
428
  var DEFAULT_OPENAPI_BASE_URL = "https://app.useblocks.io/api";
429
429
  var DEFAULT_CDN_URL = "https://cdn.useblocks.io";
430
430
  var DEFAULT_BACKEND_DOMAIN = "api.useblocks.io";
@@ -1457,8 +1457,7 @@ var ROOT_PKG = {
1457
1457
  "build-tools/cli",
1458
1458
  "build-tools/bundler-plugins",
1459
1459
  "build-tools/translations",
1460
- "local_modules/monaco",
1461
- "local_modules/pixie"
1460
+ "local_modules/monaco"
1462
1461
  ],
1463
1462
  files: ["build/"],
1464
1463
  main: "build/plugin.js",
@@ -1502,7 +1501,7 @@ var ROOT_PKG = {
1502
1501
  "@react-hook/window-size": "^3.0.7",
1503
1502
  "@react-oauth/google": "^0.12.1",
1504
1503
  "@reduxjs/toolkit": "^2.12.0",
1505
- "@sentry/browser": "^9.18.0",
1504
+ "@sentry/browser": "^10.56.0",
1506
1505
  "@sentry/cli": "^2.58.2",
1507
1506
  "@sentry/react": "^10.18.0",
1508
1507
  "@sentry/tracing": "^7.120.3",
@@ -1539,6 +1538,7 @@ var ROOT_PKG = {
1539
1538
  "immer": "^11.1.11",
1540
1539
  "js-cookie": "^3.0.1",
1541
1540
  "js-sha256": "^0.11.0",
1541
+ "konva": "9.3.18",
1542
1542
  "lodash.isequal": "^4.5.0",
1543
1543
  "mailparser": "^3.6.9",
1544
1544
  "md5": "^2.3.0",
@@ -1548,7 +1548,6 @@ var ROOT_PKG = {
1548
1548
  "monaco-html-linter": "^1.0.4",
1549
1549
  "mutation-summary": "^1.0.0",
1550
1550
  "path-browserify": "^1.0.1",
1551
- "pixie": "file:local_modules/pixie",
1552
1551
  "postal-mime": "^3.0.0",
1553
1552
  "source": "workspace:*",
1554
1553
  "process": "^0.11.10",
@@ -1556,7 +1555,9 @@ var ROOT_PKG = {
1556
1555
  "rc-input-number": "^9.5.0",
1557
1556
  "react": "19.2.7",
1558
1557
  "react-dom": "19.2.7",
1558
+ "react-filerobot-image-editor": "5.0.0-beta.159",
1559
1559
  "react-infinite-scroll-component": "^7.2.1",
1560
+ "react-konva": "19.2.5",
1560
1561
  "react-masonry-css": "^1.0.16",
1561
1562
  "react-redux": "^7.2.3",
1562
1563
  "react-refresh": "^0.18.0",
@@ -1571,6 +1572,7 @@ var ROOT_PKG = {
1571
1572
  "selderee": "^0.11.0",
1572
1573
  "sortablejs": "^1.15.2",
1573
1574
  "stream-browserify": "^3.0.0",
1575
+ "styled-components": "^6.1.13",
1574
1576
  "textChange": "workspace:*",
1575
1577
  "util": "^0.12.5",
1576
1578
  "vscode-html-languageservice": "^5.0.2",
@@ -1692,9 +1694,11 @@ var ROOT_PKG = {
1692
1694
  "@vitejs/plugin-react": "^6.0.2",
1693
1695
  "allure-jest": "^3.5.0",
1694
1696
  "babel-preset-react-app": "^10.1.0",
1697
+ "cjs-module-lexer": "2.2.0",
1695
1698
  "cross-env": "^7.0.3",
1696
1699
  "dotenv": "^17.3.1",
1697
1700
  "ejs": "^5.0.1",
1701
+ "enhanced-resolve": "^5.23.0",
1698
1702
  "env-cmd": "^10.1.0",
1699
1703
  "eslint-plugin-sonarjs": "^3.0.1",
1700
1704
  "express": "^5.2.1",
@@ -2670,7 +2674,7 @@ var MESSAGES = {
2670
2674
  "readmeStand.modeAdvancedUmd": "advanced: UMD from page script",
2671
2675
  "readmeStand.modeAdvancedMemoryUsage": "advanced: memory usage test",
2672
2676
  "readmeStand.modeAdvancedModuleFederation": "advanced: Module Federation host + remote",
2673
- "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.",
2677
+ "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).",
2674
2678
  "readmeStand.whatIncluded": "## What is included",
2675
2679
  "readmeStand.simpleProject": "- simple project with {title} connected",
2676
2680
  "readmeStand.storageProvider": "- StorageProvider with pathMode - files are stored in `./storage`",
@@ -2793,7 +2797,7 @@ function buildViteStandScripts(options) {
2793
2797
  const remotePreviewOnly = `vite preview ${remoteConfigFlag}`;
2794
2798
  const hostPreviewOnly = `vite preview ${configFlag}`;
2795
2799
  return {
2796
- 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}"`,
2800
+ start: `${concurrently} -n remote-build,remote,host "${`vite build --watch ${remoteConfigFlag}`}" "${`wait-on dist/remote/remoteEntry.js -t 120000 && vite preview ${remoteConfigFlag}`}" "vite ${configFlag}"`,
2797
2801
  build: `vite build ${remoteConfigFlag} && vite build ${configFlag}`,
2798
2802
  preview: `${remoteDistGuard} && ${distGuard} && ${concurrently} -n remote,host "${remotePreviewOnly}" "${hostPreviewOnly}"`,
2799
2803
  "serve:dist": `${remoteDistGuard} && ${distGuard} && ${concurrently} -n remote,host "${remotePreviewOnly}" "${hostPreviewOnly}"`
@@ -3425,6 +3429,7 @@ function buildStandEtaContext(templateOptions) {
3425
3429
  standShowSubpathBanner: standMode === "advanced" && advancedProfile === "subpath",
3426
3430
  standViteOutputFolder: computeStandViteOutputFolder(templateOptions),
3427
3431
  includeSmokeHelpers: Boolean(templateOptions.localTest),
3432
+ standCdnUrl: packageConfig.cdnUrl || "",
3428
3433
  standAngular: isAngularStand,
3429
3434
  ...standMode === "angular-esbuild" || standMode === "angular" ? {
3430
3435
  standAngularProductAssetsOutput: `${STAND_ANGULAR_ESBUILD_PRODUCT_PATH_PREFIX}/${appNameSlug}/`,
@@ -3570,7 +3575,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3570
3575
  "../../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",
3571
3576
  "../../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",
3572
3577
  "../../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",
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 <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",
3578
+ "../../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",
3574
3579
  "../../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",
3575
3580
  "../../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",
3576
3581
  "../../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",
@@ -3581,15 +3586,15 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3581
3586
  "../../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",
3582
3587
  "../../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",
3583
3588
  "../../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 <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",
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 <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",
3586
- "../../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",
3589
+ "../../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",
3590
+ "../../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",
3591
+ "../../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",
3587
3592
  "../../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",
3588
- "../../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('../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",
3593
+ "../../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",
3589
3594
  "../../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",
3590
3595
  "../../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",
3591
3596
  "../../project-templates/shared/partials/plugin-index-ts.eta": "import { <%= it.pluginClassName %> } from './app/<%= it.pluginClassName %>';\n\nexport default <%= it.pluginClassName %>;\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 } from '@ant-design/icons';\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\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",
3597
+ "../../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",
3593
3598
  "../../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",
3594
3599
  "../../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",
3595
3600
  "../../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",
@@ -3630,25 +3635,25 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3630
3635
  "../../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",
3631
3636
  "../../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",
3632
3637
  "../../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",
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\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",
3638
+ "../../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
3639
  "../../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 <>\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",
3640
+ "../../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",
3636
3641
  "../../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",
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={{ 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",
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={{ 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",
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('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",
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={{ 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",
3642
+ "../../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",
3643
+ "../../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",
3644
+ "../../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",
3645
+ "../../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",
3641
3646
  "../../project-templates/shared/partials/stand-host-resource-proxy.eta": "<%~ include('stand-host-resource-proxy-body', it) %>\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; 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",
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={{ 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",
3647
+ "../../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",
3648
+ "../../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",
3644
3649
  "../../project-templates/shared/partials/stand-package-json.eta": "<%~ JSON.stringify(it.standPackageJson, null, 2) + '\\n' %>\n",
3645
3650
  "../../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",
3646
3651
  "../../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",
3647
3652
  "../../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",
3648
3653
  "../../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",
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 </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-vite-index-body', it) %>\n </body>\n</html>\n",
3654
+ "../../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",
3650
3655
  "../../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",
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 </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-webpack-index-body', it) %>\n </body>\n</html>\n",
3656
+ "../../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",
3652
3657
  "../../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",
3653
3658
  "../../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",
3654
3659
  "../../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",
@@ -3680,11 +3685,11 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3680
3685
  "../../project-templates/stand/advanced/module-federation/vite/README.md.eta": "<%~ include('stand-readme', it) %>\n",
3681
3686
  "../../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",
3682
3687
  "../../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",
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} 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",
3688
+ "../../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",
3684
3689
  "../../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",
3685
3690
  "../../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",
3686
3691
  "../../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",
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';\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",
3692
+ "../../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",
3688
3693
  "../../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",
3689
3694
  "../../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",
3690
3695
  "../../project-templates/stand/advanced/module-federation/vite/index.html.eta": "<%~ include('stand-vite-index-shell', it) %>\n",
@@ -3695,9 +3700,9 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3695
3700
  "../../project-templates/stand/advanced/module-federation/vite/src/dev/getAuthToken.ts.eta": "<%~ include('stand-get-auth-token', it) %>\n",
3696
3701
  "../../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",
3697
3702
  "../../project-templates/stand/advanced/module-federation/vite/src/dev/storageProvider.ts.eta": "<%~ include('stand-storage-provider', it) %>\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={{ 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",
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={{ 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",
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 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",
3703
+ "../../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",
3704
+ "../../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",
3705
+ "../../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",
3701
3706
  "../../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",
3702
3707
  "../../project-templates/stand/advanced/shadow-dom/vite/README.md.eta": "<%~ include('stand-readme', it) %>\n",
3703
3708
  "../../project-templates/stand/advanced/shadow-dom/vite/config/dev-host.ts.eta": "<%~ include('stand-dev-host-vite', it) %>\n",
@@ -3771,7 +3776,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3771
3776
  "../../project-templates/stand/angular/esbuild/scripts/formidable.d.ts": "declare module 'formidable';\n",
3772
3777
  "../../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",
3773
3778
  "../../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",
3774
- "../../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",
3779
+ "../../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",
3775
3780
  "../../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",
3776
3781
  "../../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",
3777
3782
  "../../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",
@@ -3797,7 +3802,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
3797
3802
  "../../project-templates/stand/angular/webpack/scripts/hostDevServerHeaders.ts.eta": "<%~ include('stand-host-dev-server-webpack', it) %>\n",
3798
3803
  "../../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",
3799
3804
  "../../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",
3800
- "../../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",
3805
+ "../../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",
3801
3806
  "../../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",
3802
3807
  "../../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",
3803
3808
  "../../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",
@@ -4234,6 +4239,8 @@ function buildPluginEtaData(templateOptions) {
4234
4239
  const isTemplating = preset === "templating";
4235
4240
  const productApiName = String(packageConfig?.appName || "app").replace(/[^a-zA-Z0-9_$]/g, "") || "app";
4236
4241
  const releaseUsesUmd = pluginFormat === "umd";
4242
+ const releaseHostCompatGlobals = importsMode !== "esm";
4243
+ const devHostCompatGlobals = isLegacyWebpack;
4237
4244
  const targetLabel = formatPluginTargetTemplateLabel(t, target, advancedTarget);
4238
4245
  const pluginKeyLiteral = toLiteral(pluginKey);
4239
4246
  const importsModeLiteral = toLiteral(importsMode);
@@ -4282,6 +4289,8 @@ function buildPluginEtaData(templateOptions) {
4282
4289
  pluginFormatVite,
4283
4290
  productApiName,
4284
4291
  releaseUsesUmd,
4292
+ releaseHostCompatGlobals,
4293
+ devHostCompatGlobals,
4285
4294
  bundler,
4286
4295
  importsMode,
4287
4296
  pluginFormat,
package/package.json CHANGED
@@ -16,5 +16,5 @@
16
16
  "yargs": "^17.5.1"
17
17
  },
18
18
  "name": "useblocks-cli",
19
- "version": "1.1.85-dev.1"
19
+ "version": "1.1.85-dev.10"
20
20
  }