useblocks-cli 1.3.2 → 1.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +56 -45
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -186,7 +186,7 @@ var DEFAULT_UI_TEXT = {
|
|
|
186
186
|
requiredProjectName: "Project name is required.",
|
|
187
187
|
requiredAppName: "Application id is required (--app or REACT_APP_NAME).",
|
|
188
188
|
invalidKind: (kind, choices) => `Project kind ${kind} is not supported. Use one of: ${choices}.`,
|
|
189
|
-
invalidPreset: "Choose a preset: minimal, advanced, or
|
|
189
|
+
invalidPreset: "Choose a preset: minimal, advanced, templating, or shell.",
|
|
190
190
|
presetLocalOnly: (preset) => `Preset ${preset} is available only in local CLI mode (--local-test).`,
|
|
191
191
|
invalidBundler: "Choose a bundler: vite or webpack.",
|
|
192
192
|
requiredStandMode: "Choose a demo stand scenario.",
|
|
@@ -207,6 +207,7 @@ var DEFAULT_UI_TEXT = {
|
|
|
207
207
|
promptPresetMinimal: "Plugin scaffold (basic classes and API)",
|
|
208
208
|
promptPresetAdvanced: "Extended example (product cards)",
|
|
209
209
|
promptPresetTemplating: "Templating plugin: Twig matcher + JSON panel",
|
|
210
|
+
promptPresetShell: "Editor shell plugin: toolbar button, sidebar panel, dialog, commands",
|
|
210
211
|
promptProjectName: "Project name",
|
|
211
212
|
promptProjectNameValidate: "Enter a project name",
|
|
212
213
|
promptBundler: "Which bundler do you want to use?",
|
|
@@ -245,7 +246,7 @@ var DEFAULT_UI_TEXT = {
|
|
|
245
246
|
helpApp: "Application id (REACT_APP_NAME), same as in the monorepo",
|
|
246
247
|
promptAppName: "Application id (REACT_APP_NAME)",
|
|
247
248
|
promptAppNameValidate: "Enter an application id",
|
|
248
|
-
helpPreset: "Template preset: minimal, advanced, or
|
|
249
|
+
helpPreset: "Template preset: minimal, advanced, templating, or shell",
|
|
249
250
|
helpBundler: "Template bundler",
|
|
250
251
|
helpKind: "Top-level CLI mode: plugin or demo-stand",
|
|
251
252
|
helpTarget: "Plugin delivery target: ESM module, browser bundle, or advanced",
|
|
@@ -402,9 +403,9 @@ var DEFAULT_EXTENSIONS_API_PACKAGE = "useblocks-extensions-api";
|
|
|
402
403
|
var DEFAULT_EXTENSIONS_REACT_PACKAGE = "useblocks-extensions-react";
|
|
403
404
|
var DEFAULT_EXTENSIONS_SANDBOX_PACKAGE = "useblocks-extensions-sandbox";
|
|
404
405
|
var DEFAULT_CLI_PACKAGE = "useblocks-cli";
|
|
405
|
-
var DEFAULT_VERSION = "1.3.
|
|
406
|
-
var DEFAULT_UI_KIT_VERSION = "1.3.
|
|
407
|
-
var DEFAULT_CLI_VERSION = "1.3.
|
|
406
|
+
var DEFAULT_VERSION = "1.3.4";
|
|
407
|
+
var DEFAULT_UI_KIT_VERSION = "1.3.4";
|
|
408
|
+
var DEFAULT_CLI_VERSION = "1.3.4";
|
|
408
409
|
var DEFAULT_OPENAPI_BASE_URL = "https://app.useblocks.io/api";
|
|
409
410
|
var DEFAULT_CDN_URL = "https://cdn.useblocks.io";
|
|
410
411
|
var DEFAULT_BACKEND_DOMAIN = "api.useblocks.io";
|
|
@@ -635,11 +636,13 @@ var IMPORTS_BY_BUNDLER = {
|
|
|
635
636
|
};
|
|
636
637
|
var PLUGIN_FORMAT_CHOICES = ["esm", "umd"];
|
|
637
638
|
var ADVANCED_TARGET_CHOICES = ["async-globals", "legacy-async-globals"];
|
|
638
|
-
|
|
639
|
+
/** LOCAL_ONLY_PRESET_CHOICES — внутренние шаблоны: их видит только локальный запуск CLI из репозитория. */
|
|
640
|
+
var LOCAL_ONLY_PRESET_CHOICES = ["shell"];
|
|
639
641
|
var PRESET_CHOICES = [
|
|
640
642
|
"minimal",
|
|
641
643
|
"advanced",
|
|
642
|
-
"templating"
|
|
644
|
+
"templating",
|
|
645
|
+
"shell"
|
|
643
646
|
];
|
|
644
647
|
var KIND_CHOICES = [
|
|
645
648
|
"plugin",
|
|
@@ -675,6 +678,15 @@ function getVisibleAdvancedProfileChoices(options = {}) {
|
|
|
675
678
|
});
|
|
676
679
|
}
|
|
677
680
|
//#endregion
|
|
681
|
+
//#region lib/cli/presetVisibility.ts
|
|
682
|
+
/** getVisiblePresetChoices — шаблоны плагина, которые видит этот запуск CLI: внутренние — только локальный. */
|
|
683
|
+
function getVisiblePresetChoices(options = {}) {
|
|
684
|
+
return PRESET_CHOICES.filter((value) => {
|
|
685
|
+
if (!LOCAL_ONLY_PRESET_CHOICES.includes(value)) return true;
|
|
686
|
+
return Boolean(options.localTest);
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
//#endregion
|
|
678
690
|
//#region lib/cli/suggestProjectName.ts
|
|
679
691
|
function getTemplateSlug(options) {
|
|
680
692
|
if (options.kind === "demo-stand") {
|
|
@@ -781,12 +793,6 @@ function isResourceProxyAuth(value) {
|
|
|
781
793
|
function isPreset(value) {
|
|
782
794
|
return PRESET_CHOICES.includes(value);
|
|
783
795
|
}
|
|
784
|
-
function getVisiblePresetChoices(options = {}) {
|
|
785
|
-
return PRESET_CHOICES.filter((value) => {
|
|
786
|
-
if (!LOCAL_ONLY_PRESET_CHOICES.includes(value)) return true;
|
|
787
|
-
return Boolean(options.localTest);
|
|
788
|
-
});
|
|
789
|
-
}
|
|
790
796
|
function isPluginTarget(value, bundler) {
|
|
791
797
|
return TARGETS_BY_BUNDLER[bundler].includes(value);
|
|
792
798
|
}
|
|
@@ -978,7 +984,7 @@ function getResourceProxyAuthChoices(messages) {
|
|
|
978
984
|
}
|
|
979
985
|
function getPresetChoicesForOptions(messages, options = {}) {
|
|
980
986
|
return getVisiblePresetChoices(options).map((value) => ({
|
|
981
|
-
title: value === "advanced" ? messages.promptPresetAdvanced : value === "templating" ? messages.promptPresetTemplating : messages.promptPresetMinimal,
|
|
987
|
+
title: value === "advanced" ? messages.promptPresetAdvanced : value === "templating" ? messages.promptPresetTemplating : value === "shell" ? messages.promptPresetShell : messages.promptPresetMinimal,
|
|
982
988
|
value
|
|
983
989
|
}));
|
|
984
990
|
}
|
|
@@ -1623,7 +1629,7 @@ var ROOT_PKG = {
|
|
|
1623
1629
|
"type-check:tsc": "tsc -p src/tsconfig.json --noEmit",
|
|
1624
1630
|
"type-check:watch": "tsc -p src/tsconfig.json --noEmit --watch",
|
|
1625
1631
|
"lint:types": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsc --noEmit && tsc -p build-tools/tsconfig.tooling.json",
|
|
1626
|
-
"test:typecheck": "npm run lint:types && tsc -p iframe/tsconfig.json --noEmit && tsc -p iframe/tsconfig.host-tests.json --noEmit && tsc -p packages/po/tsconfig.json --noEmit && tsc -p packages/extensions-core/contract/tsconfig.json && tsc -p plugin-examples/tsconfig.json",
|
|
1632
|
+
"test:typecheck": "npm run lint:types && tsc -p iframe/tsconfig.json --noEmit && tsc -p iframe/tsconfig.host-tests.json --noEmit && tsc -p packages/po/tsconfig.json --noEmit && tsc -p packages/extensions-core/contract/tsconfig.json && tsc -p plugin-examples/tsconfig.json && tsc -p src/extensions/api/tsconfig.json && tsc -p src/extensions/api/tsconfig.public.json",
|
|
1627
1633
|
"type-check:tooling": "tsc -p build-tools/tsconfig.tooling.json",
|
|
1628
1634
|
"diag:measure": "tsx build-tools/scripts/diagnostics/measure.ts",
|
|
1629
1635
|
"lint:new": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsx build-tools/scripts/lint/diffAwareLint.ts",
|
|
@@ -3482,14 +3488,14 @@ function resolvePluginBundlerLayerDir(bundler, rootPrefix = TEMPLATE_ROOT) {
|
|
|
3482
3488
|
return joinTemplatePath(rootPrefix, "plugin", `bundler-${bundler}`);
|
|
3483
3489
|
}
|
|
3484
3490
|
/**
|
|
3485
|
-
* Слои для plugin: shared-base → preset (minimal|advanced|templating) → bundler (vite|webpack).
|
|
3491
|
+
* Слои для plugin: shared-base → preset (minimal|advanced|templating|shell) → bundler (vite|webpack).
|
|
3486
3492
|
*/
|
|
3487
3493
|
function getPluginEtaLayerRoots(templateOptions, rootPrefix = TEMPLATE_ROOT) {
|
|
3488
3494
|
const runtimeMessages = getRuntimeCliMessages();
|
|
3489
3495
|
if (isDemoStandKind(templateOptions.kind)) return null;
|
|
3490
3496
|
if ((templateOptions.kind || "plugin") !== "plugin") return null;
|
|
3491
3497
|
const { preset, bundler, packageManager } = templateOptions;
|
|
3492
|
-
if (preset !== "minimal" && preset !== "advanced" && preset !== "templating") throw new Error(runtimeMessages.templateEngineUnsupportedPluginPreset(preset));
|
|
3498
|
+
if (preset !== "minimal" && preset !== "advanced" && preset !== "templating" && preset !== "shell") throw new Error(runtimeMessages.templateEngineUnsupportedPluginPreset(preset));
|
|
3493
3499
|
if (bundler !== "vite" && bundler !== "webpack") throw new Error(runtimeMessages.templateEngineUnsupportedPluginBundler(bundler));
|
|
3494
3500
|
return [
|
|
3495
3501
|
resolvePluginSharedBaseDir(rootPrefix),
|
|
@@ -3568,26 +3574,31 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3568
3574
|
"../../project-templates/plugin/shared-base/src/public-types.d.ts.eta": "<%~ include('plugin-public-types', it) %>\n",
|
|
3569
3575
|
"../../project-templates/plugin/shared-base/src/sandbox/index.ts.eta": "<% if (it.isMinimal) { %><%~ include('plugin-sandbox-minimal', it) %><% } else { %><%~ include('plugin-sandbox-advanced', it) %><% } %>\n",
|
|
3570
3576
|
"../../project-templates/plugin/shared-base/src/types.d.ts.eta": "<%~ include('plugin-types-dts', it) %>\n",
|
|
3571
|
-
"../../project-templates/plugin/shared-base/tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Bundler\",\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"
|
|
3572
|
-
"../../project-templates/plugin/
|
|
3577
|
+
"../../project-templates/plugin/shared-base/tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Bundler\",\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"types\": []\n },\n \"include\": [\"src/**/*\", \"src/types.d.ts\"]\n}\n",
|
|
3578
|
+
"../../project-templates/plugin/shell/src/app/__PLUGIN_CLASS_NAME__.tsx.eta": "<% const ns = it.pluginKey.charAt(0).toLowerCase() + it.pluginKey.slice(1); %>import {\n defineCommand,\n defineView,\n err,\n pluginRegistry,\n type CommandsOf,\n type IDisposable,\n type ViewsOf,\n} from '<%= it.packageConfig.extensionsApiPackageName %>';\nimport { BarChart03Icon, SendOutlined, SettingOutlined } from '<%= it.packageConfig.uiKitPackageName %>/icons';\nimport type { IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\nimport { Dialog } from './ui/Dialog';\nimport { Panel } from './ui/Panel';\n\n/**\n * commands are the commands of the plugin: menus, other plugins and the agent can run them too. Their types come\n * from the handlers; the commands are made per plugin instance, because the handlers use its state.\n */\nexport const commands = (plugin: <%= it.pluginClassName %>) => ({\n '<%= ns %>.measure': defineCommand({\n title: 'Measure document',\n description: 'Reads the open document and returns the size of its HTML.',\n icon: SendOutlined,\n agent: true,\n when: { documentOpen: true },\n run: async (_args, context) => {\n const snapshot = await context.run('document.getSnapshot');\n if (!snapshot.ok) {\n return snapshot;\n }\n const length = snapshot.value.content.length;\n // A toolbar button has no place of its own for the result, so the command reports it over the canvas.\n plugin.report(`HTML size: ${length}`);\n return { length };\n },\n }),\n '<%= ns %>.configure': defineCommand({\n title: 'Configure plugin',\n description: 'Asks the user for a label in a dialog and keeps it for this editor.',\n icon: SettingOutlined,\n run: async () => {\n const answer = await plugin.editor.use('Ui').open('<%= ns %>.dialog', { label: plugin.label });\n if (!answer.ok) {\n return answer.error.code === 'cancelled' ? err('aborted') : err('internal', answer.error.message);\n }\n plugin.label = answer.value.label;\n },\n }),\n});\n\n/** views are the places the plugin occupies in the editor: a sidebar panel and a dialog. */\nexport const views = {\n '<%= ns %>.panel': defineView({ location: 'sidebar', title: '<%= it.pluginClassName %>', icon: BarChart03Icon }),\n // A dialog names its input and output as type arguments.\n '<%= ns %>.dialog': defineView<{ label: string }, { label: string }>({ location: 'dialog', title: 'Configure plugin' }),\n};\n\ndeclare module '<%= it.packageConfig.extensionsApiPackageName %>' {\n interface CommandMap extends CommandsOf<ReturnType<typeof commands>> {}\n interface ViewMap extends ViewsOf<typeof views> {}\n}\n\n/** <%= it.pluginClassName %> adds a toolbar button, a sidebar panel and a dialog. */\nexport class <%= it.pluginClassName %> implements IPlugin {\n label = '<%= it.pluginClassName %>';\n /** notice is the last result shown over the canvas; a new measure replaces it. */\n private notice: IDisposable | undefined;\n\n constructor(readonly editor: Instance) {}\n\n init() {\n const ui = this.editor.use('Ui');\n\n this.editor.use('Commands').register(commands(this));\n\n ui.addViews(views, {\n '<%= ns %>.panel': Panel,\n '<%= ns %>.dialog': Dialog,\n });\n\n ui.addItem({ location: 'toolbar', command: '<%= ns %>.measure' });\n ui.addItem({ location: 'menu:document', command: '<%= ns %>.configure' });\n }\n\n /** report shows a result over the canvas in place of the previous one. */\n report(title: string) {\n this.notice?.dispose();\n this.notice = this.editor.use('Ui').addItem({ location: 'notices', severity: 'info', title });\n }\n\n dispose() {\n this.notice?.dispose();\n }\n}\n\npluginRegistry.add(<%~ it.pluginKeyLiteral %>, <%= it.pluginClassName %>);\n",
|
|
3579
|
+
"../../project-templates/plugin/shell/src/app/ui/Dialog.tsx.eta": "<% const ns = it.pluginKey.charAt(0).toLowerCase() + it.pluginKey.slice(1); %>import { useCallback, useState, type ChangeEvent, type FormEvent } from 'react';\nimport type { ViewProps } from '<%= it.packageConfig.extensionsReactPackageName %>';\nimport { Button, Flex, Input } from '<%= it.packageConfig.uiKitPackageName %>';\n\n/** Dialog asks for a label and closes with it as the dialog result. */\nexport function Dialog({ context }: ViewProps<'<%= ns %>.dialog'>) {\n const [label, setLabel] = useState(context.input.label);\n\n const onSubmit = useCallback(\n (event: FormEvent) => {\n event.preventDefault();\n context.close({ label });\n },\n [context, label],\n );\n const onChange = useCallback((event: ChangeEvent<HTMLInputElement>) => setLabel(event.target.value), []);\n\n return (\n <form onSubmit={onSubmit}>\n <Flex gap={8}>\n <Input value={label} onChange={onChange} autoFocus />\n <Button type=\"primary\" htmlType=\"submit\">\n Save\n </Button>\n </Flex>\n </form>\n );\n}\n",
|
|
3580
|
+
"../../project-templates/plugin/shell/src/app/ui/Panel.tsx.eta": "<% const ns = it.pluginKey.charAt(0).toLowerCase() + it.pluginKey.slice(1); %>import { useCallback, useState } from 'react';\nimport { useCommand, useEditor, type ViewProps } from '<%= it.packageConfig.extensionsReactPackageName %>';\nimport { Button, Card, Flex, PanelForm, Text } from '<%= it.packageConfig.uiKitPackageName %>';\n\n/** Panel shows the size of the open document and lets the user name the report in the plugin's dialog. */\nexport function Panel(_props: ViewProps<'<%= ns %>.panel'>) {\n const measure = useCommand('<%= ns %>.measure');\n const ui = useEditor().use('Ui');\n const [length, setLength] = useState<number>();\n const [label, setLabel] = useState('Report');\n\n const onMeasure = useCallback(() => {\n void measure().then((result) => {\n if (result.ok) {\n setLength(result.value.length);\n }\n });\n }, [measure]);\n\n // A view opens another view through the editor and gets its output back; a command alone cannot do that.\n const onRename = useCallback(() => {\n void ui.open('<%= ns %>.dialog', { label }).then((answer) => {\n if (answer.ok) {\n setLabel(answer.value.label);\n }\n });\n }, [ui, label]);\n\n // PanelForm is the frame of the editor's own panels: a header with a divider and a padded body.\n return (\n <PanelForm>\n <PanelForm.Header title=\"<%= it.pluginClassName %>\" />\n <PanelForm.Body>\n <Flex vertical gap={12}>\n <Flex gap={8}>\n <Button type=\"primary\" onClick={onMeasure} loading={measure.running}>\n Measure\n </Button>\n <Button onClick={onRename}>Rename</Button>\n </Flex>\n {length !== undefined && (\n <Card size=\"small\">\n <Text>\n {label}: HTML size {length}\n </Text>\n </Card>\n )}\n </Flex>\n </PanelForm.Body>\n </PanelForm>\n );\n}\n",
|
|
3581
|
+
"../../project-templates/plugin/shell/src/dev/hostApp.tsx.eta": "<%~ include('plugin-dev-host-app-minimal', it) %>\n",
|
|
3582
|
+
"../../project-templates/plugin/shell/src/sandbox/index.ts.eta": "<%~ include('plugin-sandbox-minimal', it) %>\n",
|
|
3583
|
+
"../../project-templates/plugin/templating/src/app/__PLUGIN_CLASS_NAME__.tsx.eta": "import { pluginRegistry, createComponentIdentifier, type SettingsPanelApi } 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?: SettingsPanelApi;\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: SettingsPanelApi | undefined) {\n if (!settingsPanel) {\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: PreviewTemplateData) => {\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",
|
|
3573
3584
|
"../../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",
|
|
3574
|
-
"../../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
|
|
3575
|
-
"../../project-templates/plugin/templating/src/dev/hostApp.tsx.eta": "
|
|
3576
|
-
"../../project-templates/plugin/templating/src/interfaces/index.ts.eta": "
|
|
3577
|
-
"../../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",
|
|
3585
|
+
"../../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 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",
|
|
3586
|
+
"../../project-templates/plugin/templating/src/dev/hostApp.tsx.eta": "import { 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) %>\n/**\n * renderHostApp mounts the editor on the development page. Plain DOM on purpose: the editor brings its own React,\n * and a second one on the page would only add weight.\n */\nexport function renderHostApp(options: HostAppOptions): void {\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n const errorElement = rootElement.appendChild(document.createElement('div'));\n errorElement.style.cssText = 'margin: 12px 0; color: #b42318; font-size: 14px';\n errorElement.hidden = true;\n\n // The editor fills its container: without a definite height the side panels shrink to their content.\n const mountElement = rootElement.appendChild(document.createElement('div'));\n mountElement.id = 'editor-root';\n mountElement.style.height = '100vh';\n\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-templating',\n mountLabel: '#editor-root',\n } as const;\n\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: options.plugins,\n } satisfies ExportedApi.Options;\n\n init(initOptions).then(\n () => reportEditorReady(smokeMeta, mountElement),\n (error: unknown) => {\n errorElement.textContent = `Editor failed to initialize: ${reportEditorInitError(smokeMeta, error, mountElement)}`;\n errorElement.hidden = false;\n },\n );\n}\n",
|
|
3587
|
+
"../../project-templates/plugin/templating/src/interfaces/index.ts.eta": "import type { Identifier } from '<%= it.packageConfig.extensionsApiPackageName %>';\n\nexport 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';\n// Message ids carry the payload type: MessageService checks what is sent and received under each id.\nexport const TEMPLATE_DATA_MESSAGE = 'templating:preview-data' as Identifier<PreviewTemplateData>;\nexport const OPEN_TEMPLATE_DATA_PANEL_MESSAGE = 'templating:open-panel' as Identifier<void>;\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",
|
|
3588
|
+
"../../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 const start = match.index;\n if (!validStartPositions.has(start) && !ranges.some((range) => start >= range.start && start < range.end)) {\n ranges.push({ start, 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 const start = match.index;\n if (!ranges.some((range) => start >= range.start && start < range.end)) {\n ranges.push({ start, 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",
|
|
3578
3589
|
"../../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",
|
|
3579
3590
|
"../../project-templates/shared/comments/plugin-host-comments.ru.ts": "export const pluginHostComments = {\n devHostMode: 'Source-режим host-приложения: плагин грузится из исходников, а dev-хелперы остаются включены.',\n releasePackages: 'Здесь пакеты редактора/runtime остаются внешними, чтобы release host работал по тому же DI/runtime-контракту, что и собранный плагин.',\n releaseOptimizeDeps: 'Не даём Vite предсобирать эти пакеты, иначе host может вычислить свою копию runtime и задвоить синглтоны.',\n releaseAlias: 'Для release smoke-test подменяем источник плагина на собранный bundle из dist/.',\n apiProxy: 'Проксируем локальные /api-запросы в целевой backend и сохраняем ожидаемый origin-заголовок.',\n releaseEntry: 'Entry для release smoke-test: поднимаем host поверх собранных артефактов из dist/.',\n} as const;\n",
|
|
3580
3591
|
"../../project-templates/shared/comments/plugin-host-comments.ts": "import { getEmbeddedUiLanguage } from '../../../lib/config';\nimport { pluginHostComments as pluginHostCommentsEn } from './plugin-host-comments.en';\nimport { pluginHostComments as pluginHostCommentsRu } from './plugin-host-comments.ru';\n\nconst COMMENTS_BY_LOCALE = {\n en: pluginHostCommentsEn,\n ru: pluginHostCommentsRu,\n} as const;\n\nexport const pluginHostComments = COMMENTS_BY_LOCALE[getEmbeddedUiLanguage()];\n",
|
|
3581
3592
|
"../../project-templates/shared/partials/editor-init-smoke-helpers.eta": "const SMOKE_QUERY_PARAM = '__smoke';\nconst SMOKE_READY_DOM_ATTR = 'data-ub-smoke-ready';\n\ntype EditorSmokeMeta = {\n hostKind: 'plugin-host' | 'stand-host';\n variant: string;\n mountLabel: string;\n};\n\ndeclare global {\n interface Window {\n /** Playwright smoke: prefer polling this over console.log parsing. */\n __UB_SMOKE_READY__?: boolean;\n __UB_SMOKE_META__?: EditorSmokeMeta;\n }\n}\n\nfunction isSmokeMode(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n return new URLSearchParams(window.location.search).get(SMOKE_QUERY_PARAM) === '1';\n}\n\nfunction formatEditorInitError(error: unknown): string {\n if (error instanceof Error && error.message) {\n return error.message;\n }\n\n if (typeof error === 'string' && error.trim()) {\n return error.trim();\n }\n\n return 'Unknown editor initialization error.';\n}\n\nfunction reportEditorReady(meta: EditorSmokeMeta, mountElement?: Element | null): void {\n if (!isSmokeMode()) {\n return;\n }\n\n window.__UB_SMOKE_READY__ = true;\n window.__UB_SMOKE_META__ = meta;\n document.documentElement.setAttribute(SMOKE_READY_DOM_ATTR, '1');\n document.dispatchEvent(new CustomEvent('ub-smoke-ready', { detail: meta }));\n console.info('[ub-smoke-ready]', meta, mountElement ?? null);\n}\n\nfunction reportEditorInitError(meta: EditorSmokeMeta, error: unknown, mountElement?: Element | null): string {\n const message = formatEditorInitError(error);\n\n if (isSmokeMode()) {\n console.error('[ub-smoke-error]', { ...meta, message }, mountElement ?? null);\n } else {\n console.error('[editor-host] Editor initialization failed', error);\n }\n\n return message;\n}\n",
|
|
3582
3593
|
"../../project-templates/shared/partials/editor-init-smoke.eta": "<% if (it.includeSmokeHelpers) { %>\n<%~ include('editor-init-smoke-helpers', it) %>\n<% } else { %>\nfunction formatEditorInitError(error: unknown): string {\n if (error instanceof Error && error.message) {\n return error.message;\n }\n\n if (typeof error === 'string' && error.trim()) {\n return error.trim();\n }\n\n return 'Unknown editor initialization error.';\n}\n\nfunction reportEditorReady(_meta: unknown, _mountElement?: Element | null): void {}\n\nfunction reportEditorInitError(_meta: unknown, error: unknown, _mountElement?: Element | null): string {\n const message = formatEditorInitError(error);\n console.error('[editor-host] Editor initialization failed', error);\n return message;\n}\n<% } %>\n",
|
|
3583
|
-
"../../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",
|
|
3594
|
+
"../../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 // The editor creates an email shown without an id on its own; only a save the user asked for gets the modal.\n if (event.source === 'AUTOSAVE') {\n return;\n }\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",
|
|
3584
3595
|
"../../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",
|
|
3585
3596
|
"../../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",
|
|
3586
|
-
"../../project-templates/shared/partials/plugin-dev-host-app-advanced.eta": "
|
|
3587
|
-
"../../project-templates/shared/partials/plugin-dev-host-app-minimal.eta": "
|
|
3597
|
+
"../../project-templates/shared/partials/plugin-dev-host-app-advanced.eta": "import { 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) %>\n/**\n * renderHostApp mounts the editor on the development page. Plain DOM on purpose: the editor brings its own React,\n * and a second one on the page would only add weight.\n */\nexport function renderHostApp(options: HostAppOptions): void {\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n const errorElement = rootElement.appendChild(document.createElement('div'));\n errorElement.style.cssText = 'margin-bottom: 12px; color: #b42318; font-size: 14px';\n errorElement.hidden = true;\n\n // The editor fills its container: without a definite height the side panels shrink to their content.\n const mountElement = rootElement.appendChild(document.createElement('div'));\n mountElement.id = 'editor-root';\n mountElement.style.height = '100vh';\n\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-advanced',\n mountLabel: '#editor-root',\n } as const;\n\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: createDemoEmailHtml(),\n },\n },\n config: editorConfig,\n plugins: options.plugins,\n } satisfies ExportedApi.Options;\n\n init(initOptions).then(\n () => reportEditorReady(smokeMeta, mountElement),\n (error: unknown) => {\n errorElement.textContent = `Editor failed to initialize: ${reportEditorInitError(smokeMeta, error, mountElement)}`;\n errorElement.hidden = false;\n },\n );\n}\n",
|
|
3598
|
+
"../../project-templates/shared/partials/plugin-dev-host-app-minimal.eta": "import { 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) %>\n/**\n * renderHostApp mounts the editor on the development page. Plain DOM on purpose: the editor brings its own React,\n * and a second one on the page would only add weight.\n */\nexport function renderHostApp(options: HostAppOptions): void {\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n const errorElement = rootElement.appendChild(document.createElement('div'));\n errorElement.style.cssText = 'margin-bottom: 12px; color: #b42318; font-size: 14px';\n errorElement.hidden = true;\n\n // The editor fills its container: without a definite height the side panels shrink to their content.\n const mountElement = rootElement.appendChild(document.createElement('div'));\n mountElement.id = 'editor-root';\n mountElement.style.height = '100vh';\n\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-minimal',\n mountLabel: '#editor-root',\n } as const;\n\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: options.plugins,\n } satisfies ExportedApi.Options;\n\n init(initOptions).then(\n () => reportEditorReady(smokeMeta, mountElement),\n (error: unknown) => {\n errorElement.textContent = `Editor failed to initialize: ${reportEditorInitError(smokeMeta, error, mountElement)}`;\n errorElement.hidden = false;\n },\n );\n}\n",
|
|
3588
3599
|
"../../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",
|
|
3589
|
-
"../../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
|
|
3590
|
-
"../../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",
|
|
3600
|
+
"../../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 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 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",
|
|
3601
|
+
"../../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 // The bundle appears only after `npm run build` and ships no declarations; its shape is asserted right here.\n // @ts-ignore\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",
|
|
3591
3602
|
"../../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",
|
|
3592
3603
|
"../../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",
|
|
3593
3604
|
"../../project-templates/shared/partials/plugin-index-ts.eta": "import { <%= it.pluginClassName %> } from './app/<%= it.pluginClassName %>';\n\nexport default <%= it.pluginClassName %>;\n",
|
|
@@ -3598,10 +3609,10 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3598
3609
|
"../../project-templates/shared/partials/plugin-sandbox-advanced.eta": "import { App, MessageService, SyncService } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport type { IPlugin } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport {\n Activate_Product_Settings,\n Change_Product_Settings,\n Group,\n VisualSettings,\n} from '../interfaces';\n\nimport groupCardTemplate from '../common/templates/group-card.html?raw';\nimport emptyGroupTemplate from '../common/templates/empty-group.html?raw';\n\n/** SSOT: same CSS as plugin-app-advanced (`plugin/assets/advanced/product-card.css` via Eta). */\nconst PRODUCT_CARD_CSS = <%~ it.productCardCssLiteral %>;\n\ntype Disposable = { dispose(): void };\n\nclass ProductCardSandbox implements IPlugin {\n private _messageService!: MessageService;\n private _syncService?: SyncService;\n private _activeAtom: HTMLElement | null = null;\n private readonly _disposables: Disposable[] = [];\n\n private _hasExtensionStyles(): boolean {\n return Boolean(document.querySelector('style[data-extension=\"product-card-styles\"]'));\n }\n\n private _injectStylesFallback() {\n if (this._hasExtensionStyles()) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute('data-extension', 'product-card-styles');\n style.textContent = PRODUCT_CARD_CSS;\n document.head.appendChild(style);\n }\n\n private async _ensureStyles() {\n for (let attempt = 0; attempt < 40; attempt += 1) {\n if (this._hasExtensionStyles()) {\n return;\n }\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n this._injectStylesFallback();\n }\n\n private _fillTemplate(template: string, data: Record<string, string>): string {\n return template.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_, key) => data[key] || '');\n }\n\n private _onClick = (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n const atom = target.closest('.product-atom') as HTMLElement | null;\n if (!atom) return;\n this._activeAtom = atom;\n const groupId = this._getGroupId(atom);\n const settings = this._extractVisualSettings(atom);\n this._messageService.send(Activate_Product_Settings, { groupId, visualSettings: settings });\n e.preventDefault();\n };\n\n private _onChangeSettings = ({\n group,\n visualSettings,\n }: {\n group?: Group;\n visualSettings: VisualSettings;\n }) => {\n if (!this._activeAtom) return;\n if (this._getGroupId(this._activeAtom) !== group?.id) {\n this._renderGroupCard(this._activeAtom, group);\n const groupId = this._getGroupId(this._activeAtom);\n const settings = this._extractVisualSettings(this._activeAtom);\n this._messageService.send(Activate_Product_Settings, {\n groupId,\n visualSettings: settings,\n });\n }\n setTimeout(() => {\n this._applyVisualSettings(this._activeAtom!, visualSettings);\n }, 0);\n };\n\n private _renderGroupCard(containerAtom: HTMLElement, group?: Group) {\n const container = containerAtom.querySelector('.groups-container') as HTMLElement;\n if (!container) return;\n const html = group\n ? this._fillTemplate(groupCardTemplate, {\n groupId: group.id,\n imageUrl: group.image_url,\n name: group.name,\n price: String(group.price),\n count: String(group.count),\n })\n : emptyGroupTemplate;\n container.innerHTML = html;\n this._syncService?.commit();\n }\n\n private _applyVisualSettings(atom: HTMLElement, settings: VisualSettings) {\n const card = atom.querySelector('.group-container') as HTMLElement | null;\n if (!card) return;\n const button = card.querySelector('.button-buy') as HTMLElement | null;\n if (settings.blockBorder !== undefined) {\n card.style.border = settings.blockBorder + 'px solid #ccc';\n }\n if (settings.blockPadding !== undefined) {\n card.style.padding = settings.blockPadding + 'px';\n }\n if (settings.cardBackgroundColor) card.style.backgroundColor = settings.cardBackgroundColor;\n if (settings.cardTextColor && button) button.style.color = settings.cardTextColor;\n if (settings.cardTextAlign) card.style.textAlign = settings.cardTextAlign;\n if (button) {\n if (settings.cardButtonColor) button.style.backgroundColor = settings.cardButtonColor;\n if (settings.cardButtonText) button.textContent = settings.cardButtonText;\n }\n this._syncService?.commit();\n }\n\n private _extractVisualSettings(atom: HTMLElement): VisualSettings {\n const card = atom.querySelector('.group-container') as HTMLElement | null;\n const button = card?.querySelector('.button-buy') as HTMLElement | null;\n const cardStyle = card && getComputedStyle(card);\n const buttonStyle = button && getComputedStyle(button);\n return {\n blockBorder: cardStyle?.border ? parseInt(cardStyle.border, 10) : 0,\n blockPadding: cardStyle?.padding ? parseInt(cardStyle.padding, 10) : 0,\n cardBackgroundColor: cardStyle?.backgroundColor || undefined,\n cardTextColor: buttonStyle?.color || cardStyle?.color || undefined,\n cardTextAlign: (cardStyle?.textAlign as VisualSettings['cardTextAlign']) || 'left',\n cardButtonText: button?.textContent || '',\n cardButtonColor: buttonStyle?.backgroundColor || undefined,\n };\n }\n\n private _getGroupId(atom: HTMLElement): string | undefined {\n const container = atom.querySelector('.group-container');\n return container?.getAttribute('data-group-id') || undefined;\n }\n\n init() {\n this._messageService = App.use('MessageService');\n this._syncService = App.use('SyncService');\n void this._ensureStyles();\n // Click on .product-atom in the email → tell app to open the settings panel.\n document.addEventListener('mousedown', this._onClick, true);\n this._disposables.push(\n this._messageService.addListener(Change_Product_Settings, this._onChangeSettings),\n );\n }\n\n dispose() {\n document.removeEventListener('mousedown', this._onClick, true);\n while (this._disposables.length > 0) {\n this._disposables.pop()?.dispose();\n }\n }\n}\n\nApp.use(ProductCardSandbox);\n",
|
|
3599
3610
|
"../../project-templates/shared/partials/plugin-sandbox-minimal.eta": "import { App } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport type { IPlugin } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\n\nclass <%= it.pluginClassName %>Sandbox implements IPlugin {}\n\nApp.use(<%= it.pluginClassName %>Sandbox);\n",
|
|
3600
3611
|
"../../project-templates/shared/partials/plugin-types-dts.eta": "declare module '*.html?raw' {\n const content: string;\n export default content;\n}\n\ndeclare module '*.css?raw' {\n const content: string;\n export default content;\n}\n",
|
|
3601
|
-
"../../project-templates/shared/partials/plugin-vite-dev-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\
|
|
3612
|
+
"../../project-templates/shared/partials/plugin-vite-dev-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\n<% if (!it.isMinimal) { %>import react from '@vitejs/plugin-react';\n<% } %>import VitePlugin from '<%= it.packageConfig.packageName %>/vite';\nimport PluginDev from '<%= it.packageConfig.packageName %>/vite/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n // <%= it.commentDevHostMode %>\n plugins: [\n PluginDev({ externals: false }),\n<% if (!it.isMinimal) { %> react(),\n<% } %> VitePlugin(),\n ],\n optimizeDeps: {\n entries: ['index.html'],\n },\n server: {\n port: devPort,\n strictPort: true,\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n rewrite: (path) => path.replace(/^\\/api/, '') || '/',\n configure: (proxy) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3602
3613
|
"../../project-templates/shared/partials/plugin-vite-index-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> <%= it.indexHtmlTitleSuffix %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"<%= it.pluginViteIndexScriptSrc %>\"><\/script>\n </body>\n</html>\n",
|
|
3603
3614
|
"../../project-templates/shared/partials/plugin-vite-plugin-build.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport PluginDev from '<%= it.packageConfig.packageName %>/vite/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst pluginDevExternals = <%~ it.importsModeLiteral %>;\n\nconst config = defineConfig({\n root: projectRoot,\n plugins: [\n PluginDev({ externals: pluginDevExternals }),\n ],\n build: {\n sourcemap: true,\n minify: true,\n outDir: 'dist',\n emptyOutDir: false,\n lib: {\n entry: path.resolve(projectRoot, 'src/index.ts'),\n formats: ['<%= it.pluginFormatVite %>'],\n name: '<%= it.pluginClassName %>',\n fileName: () => 'index.js',\n },\n },\n}) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3604
|
-
"../../project-templates/shared/partials/plugin-vite-release-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\
|
|
3615
|
+
"../../project-templates/shared/partials/plugin-vite-release-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\n<% if (!it.isMinimal) { %>import react from '@vitejs/plugin-react';\n<% } %>import VitePlugin from '<%= it.packageConfig.packageName %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\n/**\n * Proxy shared by the dev server and the preview server: the production host serves built assets,\n * but still talks to the same API.\n */\nconst apiProxy = {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n rewrite: (path) => path.replace(/^\\/api/, '') || '/',\n configure: (proxy: any) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq: any) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n};\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n plugins: [\n<% if (!it.isMinimal) { %> react(),\n<% } %> VitePlugin(),\n ],\n /**\n * Production host: `build` + `preview` instead of the dev server.\n *\n * The dev server hands every dependency to vite's optimizer, which bundles each one whole and on\n * purpose does not shake it. Weights seen there say nothing about the delivered result — only a\n * built host does.\n */\n build: {\n outDir: 'dist-host',\n emptyOutDir: true,\n rollupOptions: {\n input: path.resolve(projectRoot, 'release.html'),\n },\n },\n preview: {\n port: devPort,\n strictPort: true,\n open: '/release.html',\n proxy: apiProxy,\n },\n server: {\n port: devPort,\n strictPort: true,\n open: '/release.html',\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: apiProxy,\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3605
3616
|
"../../project-templates/shared/partials/plugin-vite-release-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> release host</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/dev-release.tsx\"><\/script>\n </body>\n</html>\n",
|
|
3606
3617
|
"../../project-templates/shared/partials/plugin-vite-sandbox-build.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = defineConfig(({ mode }) => ({\n root: projectRoot,\n build: {\n sourcemap: true,\n minify: mode === 'production',\n outDir: mode === 'development' ? 'public' : 'dist',\n emptyOutDir: false,\n lib: {\n entry: path.resolve(projectRoot, 'src/sandbox/index.ts'),\n formats: ['iife'],\n name: '<%= it.pluginClassName %>Sandbox',\n fileName: () => 'sandbox.js',\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3607
3618
|
"../../project-templates/shared/partials/plugin-webpack-dev-host-legacy.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n\n\n<%~ include('plugin-wp-legacy-externals', it) %>\n\n\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n externals: getExternals(),\n\n // <%= it.commentDevHostMode %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
|
|
@@ -3618,7 +3629,6 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3618
3629
|
"../../project-templates/shared/partials/plugin-wp-modern-module.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Configuration } from 'webpack';\nimport PluginDev from '<%= it.packageConfig.packageName %>/webpack/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst pluginDevExternals = <%~ it.importsModeLiteral %>;\n\nconst config = {\n entry: path.resolve(projectRoot, 'src/index.ts'),\n devtool: 'source-map',\n mode: 'production',\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n plugins: [\n new PluginDev({ externals: pluginDevExternals }),\n ],\n optimization: {\n minimize: true,\n },\n experiments: { outputModule: true },\n output: {\n filename: 'index.js',\n path: path.resolve(projectRoot, 'dist'),\n clean: false,\n module: true,\n library: {\n type: 'module',\n },\n },\n} satisfies Configuration;\n\nexport default config;\n",
|
|
3619
3630
|
"../../project-templates/shared/partials/plugin-wp-modern-umd.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Configuration } from 'webpack';\nimport PluginDev from '<%= it.packageConfig.packageName %>/webpack/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst pluginDevExternals = <%~ it.importsModeLiteral %>;\n\nconst config = {\n entry: path.resolve(projectRoot, 'src/index.ts'),\n devtool: 'source-map',\n mode: 'production',\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n plugins: [\n new PluginDev({ externals: pluginDevExternals }),\n ],\n optimization: {\n minimize: true,\n },\n experiments: {},\n output: {\n filename: 'index.js',\n path: path.resolve(projectRoot, 'dist'),\n clean: false,\n library: {\n name: '<%= it.pluginClassName %>',\n type: 'umd',\n export: 'default',\n },\n globalObject: 'this',\n umdNamedDefine: true,\n },\n} satisfies Configuration;\n\nexport default config;\n",
|
|
3620
3631
|
"../../project-templates/shared/partials/stand-angular-production-optimization.eta": "\"optimization\": {\n \"scripts\": true,\n \"styles\": {\n \"minify\": true,\n \"inlineCritical\": false\n },\n \"fonts\": true\n},\n",
|
|
3621
|
-
"../../project-templates/shared/partials/stand-demo-email-id.eta": "function 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",
|
|
3622
3632
|
"../../project-templates/shared/partials/stand-dev-email-resource-proxy.eta": "<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title><%= it.devEmailTitle %></title>\n</head>\n<body style=\"margin:0;padding:0;background:#f8f8f8;\">\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"background:#f8f8f8;\">\n <tr>\n <td align=\"center\" style=\"padding:40px 20px;\">\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"660\" style=\"max-width:660px;width:100%;background:#ffffff;\">\n <tr>\n <td style=\"padding:30px 40px 20px;\">\n <img src=\"<%= it.standCdnUrl %>/YOUR_CDN_SAMPLE_PROJECT_ID/240122_4213_7sMGu9U.png\" width=\"100\" alt=\"\" style=\"display:block;width:100%;max-width:100px;border:0;\">\n </td>\n </tr>\n <tr>\n <td style=\"padding:30px 40px 40px;\">\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n <tr>\n <td width=\"291\" valign=\"bottom\">\n <img src=\"<%= it.standCdnUrl %>/YOUR_CDN_SAMPLE_PROJECT_ID/240112_4213_jmuAvfh.png\" width=\"291\" alt=\"\" style=\"display:block;width:100%;max-width:291px;border-radius:6px;border:0;\">\n </td>\n <td width=\"10\"></td>\n <td width=\"135\" valign=\"bottom\">\n <img src=\"<%= it.standCdnUrl %>/YOUR_CDN_SAMPLE_PROJECT_ID/240112_4213_34n4skn.png\" width=\"135\" alt=\"\" style=\"display:block;width:100%;max-width:135px;border-radius:6px;border:0;\">\n </td>\n <td width=\"10\"></td>\n <td width=\"134\" valign=\"bottom\">\n <img src=\"<%= it.standCdnUrl %>/YOUR_CDN_SAMPLE_PROJECT_ID/240112_4213_1BW0VnL.png\" width=\"134\" alt=\"\" style=\"display:block;width:100%;max-width:134px;border-radius:6px;border:0;\">\n </td>\n </tr>\n </table>\n </td>\n </tr>\n <tr>\n <td style=\"padding:0 40px 30px;\">\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n <tr>\n <td width=\"50%\" valign=\"top\" style=\"padding-right:10px;font-family:Arial,sans-serif;font-size:12px;line-height:16px;color:#4a5565;\">\n directHosts (placehold.co)\n </td>\n <td width=\"50%\" valign=\"top\" style=\"padding-left:10px;font-family:Arial,sans-serif;font-size:12px;line-height:16px;color:#4a5565;\">\n via proxy (dummyimage.com)\n </td>\n </tr>\n <tr>\n <td width=\"50%\" valign=\"top\" style=\"padding:8px 10px 0 0;\">\n <img src=\"<%= it.resourceProxyDemoDirectUrl %>\" width=\"200\" alt=\"directHosts demo (placehold.co)\" style=\"display:block;width:100%;max-width:200px;border:0;\">\n </td>\n <td width=\"50%\" valign=\"top\" style=\"padding:8px 0 0 10px;\">\n <img src=\"<%= it.resourceProxyDemoProxyUrl %>\" width=\"200\" alt=\"proxy demo (dummyimage.com)\" style=\"display:block;width:100%;max-width:200px;border:0;\">\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n</body>\n</html>\n",
|
|
3623
3633
|
"../../project-templates/shared/partials/stand-dev-email.eta": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <meta name=\"x-apple-disable-message-reformatting\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title><%= it.devEmailTitle %></title>\n <style type=\"text/css\">\n html {\n -webkit-text-size-adjust: none;\n -ms-text-size-adjust: none;\n }\n </style>\n <style em=\"styles\">\n@media only screen and (max-device-width:660px),only screen and (max-width:660px) {\n .em-narrow-table {\n width: 100%!important;\n max-width: 660px!important;\n min-width: 320px!important;\n }\n}\n</style>\n <!--[if gte mso 9]>\n <xml>\n <o:OfficeDocumentSettings>\n <o:AllowPNG></o:AllowPNG>\n <o:PixelsPerInch>96</o:PixelsPerInch>\n </o:OfficeDocumentSettings>\n </xml>\n <![endif]-->\n</head>\n<body style=\"margin: 0; padding: 0; background-color: #F8F8F8;\">\n <span class=\"preheader\" style=\"display: none !important; visibility: hidden; opacity: 0; color: #F8F8F8; height: 0; width: 0; font-size: 1px;\"> </span>\n <!--[if !mso]><!-->\n <div style=\"font-size:0px;color:transparent;opacity:0;\">\n ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n </div>\n <!--<![endif]-->\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"font-size: 1px; line-height: normal;\"\n bgcolor=\"#F8F8F8\">\n <tr em=\"group\">\n <td align=\"center\">\n <!--[if (gte mso 9)|(IE)]>\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"660\"><tr><td>\n <![endif]-->\n <table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" border=\"0\" style=\"max-width: 660px; min-width: 660px; width: 660px;\" class=\"em-narrow-table\"></table>\n <!--[if (gte mso 9)|(IE)]>\n </td></tr></table>\n <![endif]-->\n </td>\n </tr>\n </table>\n</body>\n</html>\n",
|
|
3624
3634
|
"../../project-templates/shared/partials/stand-dev-host-vite-memory.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport VitePlugin from '<%~ it.standVitePluginPackage %>/vite';\nimport { createMemoryUsageStandConfig } from './lib/createMemoryUsageStandConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createMemoryUsageStandConfig({\n projectRoot,\n vitePlugin: VitePlugin,\n closedLoop: <%= it.standClosedLoop %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n});\n",
|
|
@@ -3634,15 +3644,15 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3634
3644
|
"../../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",
|
|
3635
3645
|
"../../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",
|
|
3636
3646
|
"../../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",
|
|
3637
|
-
"../../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) %>\
|
|
3647
|
+
"../../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) %>\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 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",
|
|
3638
3648
|
"../../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",
|
|
3639
|
-
"../../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) %>\
|
|
3640
|
-
"../../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) %>\
|
|
3641
|
-
"../../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) %>\
|
|
3642
|
-
"../../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) %>\
|
|
3649
|
+
"../../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) %>\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 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",
|
|
3650
|
+
"../../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) %>\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 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",
|
|
3651
|
+
"../../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) %>\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 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",
|
|
3652
|
+
"../../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) %>\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 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",
|
|
3643
3653
|
"../../project-templates/shared/partials/stand-host-resource-proxy.eta": "<%~ include('stand-host-resource-proxy-body', it) %>\n",
|
|
3644
|
-
"../../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) %>\
|
|
3645
|
-
"../../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) %>\
|
|
3654
|
+
"../../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) %>\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 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",
|
|
3655
|
+
"../../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) %>\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 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",
|
|
3646
3656
|
"../../project-templates/shared/partials/stand-package-json.eta": "<%~ JSON.stringify(it.standPackageJson, null, 2) + '\\n' %>\n",
|
|
3647
3657
|
"../../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",
|
|
3648
3658
|
"../../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",
|
|
@@ -3660,14 +3670,14 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3660
3670
|
"../../project-templates/shared/stand-vite-base/config/lib/standProductionBuild.ts": "import type { BuildOptions } from 'vite';\n\n/** Production build defaults for demo stands (`vite build` / `vite preview`). */\nexport const STAND_VITE_PRODUCTION_BUILD = {\n minify: 'esbuild',\n cssMinify: true,\n sourcemap: false,\n} satisfies BuildOptions;\n",
|
|
3661
3671
|
"../../project-templates/shared/stand-vite-base/scripts/devStorageMiddleware.ts.eta": "<%~ include('stand-dev-storage-middleware', it) %>\n",
|
|
3662
3672
|
"../../project-templates/shared/stand-vite-base/src/types.d.ts": "declare module '*.html?raw' {\n const content: string;\n export default content;\n}\n",
|
|
3663
|
-
"../../project-templates/shared/stand-vite-base/tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Bundler\",\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"
|
|
3673
|
+
"../../project-templates/shared/stand-vite-base/tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Bundler\",\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"types\": []\n },\n \"include\": [\"src/**/*\"]\n}\n",
|
|
3664
3674
|
"../../project-templates/shared/stand-webpack-base/config/lib/createWebpackStandConfig.ts": "import path from 'node:path';\nimport type { ClientRequest } from 'node:http';\nimport type { Configuration, WebpackPluginInstance } from 'webpack';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { mergeHostEditorDevServer } from '../../scripts/hostDevServerHeaders.ts';\nimport { createUmdServeMiddleware } from './umdServeMiddleware.ts';\n\ninterface UmdServeOptions {\n packageRoot: string;\n publicPath: string;\n}\n\ninterface ProxyRule {\n context: string[];\n target: string;\n secure: boolean;\n changeOrigin: boolean;\n onProxyReq?: (proxyRequest: ClientRequest) => void;\n}\n\ninterface CreateWebpackStandConfigOptions {\n projectRoot: string;\n plugins: WebpackPluginInstance[];\n outputPublicPath: string;\n staticDirectory: string;\n open: string;\n proxy?: ProxyRule[];\n umd?: UmdServeOptions | null;\n}\n\nexport function createWebpackStandConfig(\n options: CreateWebpackStandConfigOptions,\n): (env: unknown, argv: { mode?: string }) => Configuration {\n const {\n projectRoot,\n plugins,\n outputPublicPath,\n staticDirectory,\n open,\n proxy,\n umd,\n } = options;\n\n const umdMiddleware = umd ? createUmdServeMiddleware(umd) : null;\n\n return (_env, argv) => {\n const isProd = argv.mode === 'production';\n\n const devServerConfig = mergeHostEditorDevServer({\n devServer: {\n static: {\n directory: staticDirectory,\n publicPath: outputPublicPath,\n },\n devMiddleware: { publicPath: outputPublicPath },\n open,\n port: 'auto',\n hot: false,\n liveReload: true,\n setupMiddlewares: (middlewares, devServer) => {\n if (open && open !== '/') {\n devServer.app?.use((req, res, next) => {\n if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {\n res.redirect(open);\n return;\n }\n next();\n });\n }\n devServer.app?.use(devStorageMiddleware());\n if (umdMiddleware) {\n devServer.app?.use(umdMiddleware);\n }\n return middlewares;\n },\n ...(proxy && proxy.length > 0 ? { proxy } : {}),\n },\n }).devServer!;\n\n return {\n mode: isProd ? 'production' : 'development',\n devtool: isProd ? false : 'eval-source-map',\n optimization: isProd\n ? {\n minimize: true,\n concatenateModules: true,\n moduleIds: 'deterministic',\n }\n : undefined,\n entry: path.resolve(projectRoot, 'src/index.tsx'),\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n plugins,\n output: {\n filename: 'dev.js',\n path: path.resolve(projectRoot, 'dev-build'),\n publicPath: outputPublicPath,\n },\n devServer: devServerConfig,\n };\n };\n}\n",
|
|
3665
3675
|
"../../project-templates/shared/stand-webpack-base/config/lib/umdServeMiddleware.ts": "import fs from 'node:fs';\nimport path from 'node:path';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\ninterface UmdServeOptions {\n packageRoot: string;\n publicPath: string;\n}\n\nconst MIME_TYPES = {\n '.css': 'text/css; charset=utf-8',\n '.js': 'application/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.html': 'text/html; charset=utf-8',\n '.map': '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 '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n} as const satisfies Record<string, string>;\n\nexport function createUmdServeMiddleware(options: UmdServeOptions) {\n const { packageRoot, publicPath } = options;\n\n return (req: IncomingMessage, res: ServerResponse, next: () => void): void => {\n if (!req.url || (req.method !== 'GET' && req.method !== 'HEAD')) {\n next();\n return;\n }\n\n const requestPath = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);\n if (!requestPath.startsWith(publicPath)) {\n next();\n return;\n }\n\n const relativePath = requestPath.slice(publicPath.length);\n if (!relativePath || relativePath.endsWith('/')) {\n next();\n return;\n }\n\n const absolutePath = path.resolve(packageRoot, relativePath);\n const relativeFromRoot = path.relative(packageRoot, absolutePath);\n if (relativeFromRoot.startsWith('..') || path.isAbsolute(relativeFromRoot)) {\n res.statusCode = 403;\n res.end('Forbidden');\n return;\n }\n\n if (!fs.existsSync(absolutePath) || !fs.statSync(absolutePath).isFile()) {\n next();\n return;\n }\n\n const contentType = MIME_TYPES[path.extname(absolutePath).toLowerCase() as keyof typeof MIME_TYPES];\n if (contentType) {\n res.setHeader('Content-Type', contentType);\n }\n\n res.end(fs.readFileSync(absolutePath));\n };\n}\n",
|
|
3666
3676
|
"../../project-templates/shared/stand-webpack-base/scripts/devStorageMiddleware.ts.eta": "<%~ include('stand-dev-storage-middleware', it) %>\n",
|
|
3667
3677
|
"../../project-templates/shared/stand-webpack-base/scripts/hostDevServerHeaders.ts.eta": "<%~ include('stand-host-dev-server-webpack', it) %>\n",
|
|
3668
3678
|
"../../project-templates/shared/stand-webpack-base/scripts/prepareDist.cjs": "#!/usr/bin/env node\n/**\n * Merges webpack stand production artifacts into `dist/` for static serving.\n *\n * Dev server combines `public/` (HTML shell) and `dev-build/` (bundle + product assets).\n * `npm run build` only writes to `dev-build/` — this script assembles a single `dist/` tree\n * for `npm run serve:dist` (`serve` package; `serve.json` is copied into `dist/` below).\n */\nconst fs = require('node:fs');\nconst path = require('node:path');\n\nconst projectRoot = path.resolve(__dirname, '..');\nconst publicDir = path.join(projectRoot, 'public');\nconst devBuildDir = path.join(projectRoot, 'dev-build');\nconst distDir = path.join(projectRoot, 'dist');\n\nfunction copyRecursive(source, destination) {\n const stat = fs.statSync(source);\n if (stat.isDirectory()) {\n fs.mkdirSync(destination, { recursive: true });\n for (const entry of fs.readdirSync(source, { withFileTypes: true })) {\n copyRecursive(path.join(source, entry.name), path.join(destination, entry.name));\n }\n return;\n }\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n fs.copyFileSync(source, destination);\n}\n\nfunction copyProductAssetDirs(sourceRoot, destinationRoot) {\n for (const entry of fs.readdirSync(sourceRoot, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n copyRecursive(path.join(sourceRoot, entry.name), path.join(destinationRoot, entry.name));\n }\n}\n\nfunction copyDevBundleBesideNestedIndexes(rootDir, devBundle) {\n const queue = [rootDir];\n while (queue.length > 0) {\n const dir = queue.shift();\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n queue.push(fullPath);\n continue;\n }\n if (entry.name !== 'index.html') continue;\n if (dir === rootDir) continue;\n const nestedBundle = path.join(dir, 'dev.js');\n if (!fs.existsSync(nestedBundle)) {\n fs.copyFileSync(devBundle, nestedBundle);\n }\n }\n }\n}\n\nfunction main() {\n const devBundle = path.join(devBuildDir, 'dev.js');\n if (!fs.existsSync(devBundle)) {\n console.error('[prepareDist] Missing dev-build/dev.js — run `npm run build` first.');\n process.exit(1);\n }\n\n fs.rmSync(distDir, { recursive: true, force: true });\n fs.mkdirSync(distDir, { recursive: true });\n\n if (fs.existsSync(publicDir)) {\n copyRecursive(publicDir, distDir);\n }\n\n fs.copyFileSync(devBundle, path.join(distDir, 'dev.js'));\n copyDevBundleBesideNestedIndexes(distDir, devBundle);\n copyProductAssetDirs(devBuildDir, distDir);\n\n const serveConfig = path.join(projectRoot, 'serve.json');\n if (fs.existsSync(serveConfig)) {\n fs.copyFileSync(serveConfig, path.join(distDir, 'serve.json'));\n }\n\n console.log(`[prepareDist] Ready: ${distDir}`);\n}\n\nmain();\n",
|
|
3669
3679
|
"../../project-templates/shared/stand-webpack-base/src/types.d.ts": "declare module '*.html?raw' {\n const content: string;\n export default content;\n}\n",
|
|
3670
|
-
"../../project-templates/shared/stand-webpack-base/tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Bundler\",\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"
|
|
3680
|
+
"../../project-templates/shared/stand-webpack-base/tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Bundler\",\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"types\": []\n },\n \"include\": [\"src/**/*\"]\n}\n",
|
|
3671
3681
|
"../../project-templates/stand/advanced/memory-usage/vite/README.md.eta": "<%~ include('stand-readme', it) %>\n",
|
|
3672
3682
|
"../../project-templates/stand/advanced/memory-usage/vite/config/dev-host.ts.eta": "<%~ include('stand-dev-host-vite-memory', it) %>\n",
|
|
3673
3683
|
"../../project-templates/stand/advanced/memory-usage/vite/config/lib/createMemoryUsageStandConfig.ts": "import path from 'node:path';\nimport react from '@vitejs/plugin-react';\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 { ViteImageOptimizer } from 'vite-plugin-image-optimizer';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_PREVIEW_HEADERS, STAND_PREVIEW_PORT } from './standPreviewSettings.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\n\ninterface CreateMemoryUsageStandConfigOptions {\n projectRoot: string;\n vitePlugin: () => PluginOption[];\n closedLoop?: boolean;\n apiBaseUrl: string;\n apiOrigin: string;\n}\n\nexport function createMemoryUsageStandConfig(options: CreateMemoryUsageStandConfigOptions): UserConfigExport {\n const {\n projectRoot,\n vitePlugin,\n closedLoop,\n apiBaseUrl,\n apiOrigin,\n } = options;\n\n return defineConfig(() => {\n const apiProxy = closedLoop\n ? undefined\n : createStandApiProxyOptions(apiBaseUrl, apiOrigin);\n\n return {\n root: projectRoot,\n plugins: [\n react(),\n ...vitePlugin(),\n ViteImageOptimizer(),\n cssInjectedByJsPlugin({\n injectCode: (content) => `\n if (document) {\n const style = document.createElement('style');\n style.setAttribute('data-mf-app', 'memory-usage-test');\n style.innerHTML = ${content};\n document.body.append(style);\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 },\n server: {\n port: 3000,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n outDir: './dist/profile-a',\n rollupOptions: {\n output: {\n entryFileNames: `[name]${uuid()}.js`,\n chunkFileNames: `[name]${uuid()}.js`,\n assetFileNames: `[name]${uuid()}.[ext]`,\n },\n },\n },\n preview: {\n port: STAND_PREVIEW_PORT,\n headers: STAND_PREVIEW_HEADERS,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n };\n });\n}\n",
|
|
@@ -3698,7 +3708,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3698
3708
|
"../../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",
|
|
3699
3709
|
"../../project-templates/stand/advanced/module-federation/vite/src/dev/storageProvider.ts.eta": "<%~ include('stand-storage-provider', it) %>\n",
|
|
3700
3710
|
"../../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",
|
|
3701
|
-
"../../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) %>\
|
|
3711
|
+
"../../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) %>\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 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",
|
|
3702
3712
|
"../../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",
|
|
3703
3713
|
"../../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",
|
|
3704
3714
|
"../../project-templates/stand/advanced/shadow-dom/vite/README.md.eta": "<%~ include('stand-readme', it) %>\n",
|
|
@@ -3777,7 +3787,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3777
3787
|
"../../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",
|
|
3778
3788
|
"../../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",
|
|
3779
3789
|
"../../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",
|
|
3780
|
-
"../../project-templates/stand/angular/esbuild/src/app/editor-host.ts.eta": "import baseEmailHtml from '../dev/email.html?raw';\nimport { editorConfig } from '../dev/editorConfig';\nimport { getAuthToken } from '../dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from '../dev/storageProvider';\nimport { snapshotPublicPathDiagnostics } from '../../scripts/publicPathDiagnostics';\n\n
|
|
3790
|
+
"../../project-templates/stand/angular/esbuild/src/app/editor-host.ts.eta": "import baseEmailHtml from '../dev/email.html?raw';\nimport { editorConfig } from '../dev/editorConfig';\nimport { getAuthToken } from '../dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from '../dev/storageProvider';\nimport { snapshotPublicPathDiagnostics } from '../../scripts/publicPathDiagnostics';\n\n\ntype EmailmakerModule = typeof import('<%~ it.packageName %>');\ntype EditorInstance = Awaited<ReturnType<EmailmakerModule['init']>>;\n\nlet editorInstance: EditorInstance | null = null;\n\nasync function loadEmailmakerModule(): Promise<EmailmakerModule> {\n return import('<%~ it.packageName %>');\n}\n\nfunction formatInitError(error: unknown): string {\n if (error instanceof Error && error.message) {\n return error.message;\n }\n if (typeof error === 'string' && error.trim()) {\n return error.trim();\n }\n return 'Editor initialization failed.';\n}\n\nexport async function initOAuthEditor(): Promise<EditorInstance> {\n if (editorInstance) {\n return editorInstance;\n }\n\n snapshotPublicPathDiagnostics('before-emailmaker-import');\n const <%= it.standProductApiName %> = await loadEmailmakerModule();\n snapshotPublicPathDiagnostics('after-emailmaker-import');\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n\n editorInstance = instance;\n return instance;\n } catch (error) {\n const message = formatInitError(error);\n console.error('[editor-host] Editor initialization failed', error);\n throw new Error(message);\n }\n}\n",
|
|
3781
3791
|
"../../project-templates/stand/angular/esbuild/src/dev/editorConfig.ts.eta": "<%~ include('stand-editor-config', it) %>\n",
|
|
3782
3792
|
"../../project-templates/stand/angular/esbuild/src/dev/email.html.eta": "<%~ include('stand-dev-email', it) %>\n",
|
|
3783
3793
|
"../../project-templates/stand/angular/esbuild/src/dev/getAuthToken.ts.eta": "<%~ include('stand-get-auth-token', it) %>\n",
|
|
@@ -3803,7 +3813,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3803
3813
|
"../../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",
|
|
3804
3814
|
"../../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",
|
|
3805
3815
|
"../../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",
|
|
3806
|
-
"../../project-templates/stand/angular/webpack/src/app/editor-host.ts.eta": "import baseEmailHtml from '../dev/email.html?raw';\nimport { editorConfig } from '../dev/editorConfig';\nimport { getAuthToken } from '../dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from '../dev/storageProvider';\nimport { snapshotPublicPathDiagnostics } from '../../scripts/publicPathDiagnostics';\n\n<%~ include('
|
|
3816
|
+
"../../project-templates/stand/angular/webpack/src/app/editor-host.ts.eta": "import baseEmailHtml from '../dev/email.html?raw';\nimport { editorConfig } from '../dev/editorConfig';\nimport { getAuthToken } from '../dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from '../dev/storageProvider';\nimport { snapshotPublicPathDiagnostics } from '../../scripts/publicPathDiagnostics';\n\n<%~ include('editor-init-smoke', it) %>\n\ntype EmailmakerModule = typeof import('<%~ it.packageName %>');\ntype EditorInstance = Awaited<ReturnType<EmailmakerModule['init']>>;\n\nlet editorInstance: EditorInstance | null = null;\n\nconst smokeMeta = {\n hostKind: 'stand-host' as const,\n variant: 'stand-angular',\n mountLabel: '#editor-root',\n};\n\nasync function loadEmailmakerModule(): Promise<EmailmakerModule> {\n return import('<%~ it.packageName %>');\n}\n\nfunction formatInitError(error: unknown): string {\n if (error instanceof Error && error.message) {\n return error.message;\n }\n if (typeof error === 'string' && error.trim()) {\n return error.trim();\n }\n return 'Editor initialization failed.';\n}\n\nexport async function initOAuthEditor(): Promise<EditorInstance> {\n if (editorInstance) {\n return editorInstance;\n }\n\n const mountElement = document.getElementById('editor-root');\n snapshotPublicPathDiagnostics('before-emailmaker-import');\n const <%= it.standProductApiName %> = await loadEmailmakerModule();\n snapshotPublicPathDiagnostics('after-emailmaker-import');\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n\n editorInstance = instance;\n reportEditorReady(smokeMeta, mountElement);\n return instance;\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement) ?? formatInitError(error);\n throw new Error(message);\n }\n}\n",
|
|
3807
3817
|
"../../project-templates/stand/angular/webpack/src/dev/editorConfig.ts.eta": "<%~ include('stand-editor-config', it) %>\n",
|
|
3808
3818
|
"../../project-templates/stand/angular/webpack/src/dev/email.html.eta": "<%~ include('stand-dev-email', it) %>\n",
|
|
3809
3819
|
"../../project-templates/stand/angular/webpack/src/dev/getAuthToken.ts.eta": "<%~ include('stand-get-auth-token', it) %>\n",
|
|
@@ -4031,17 +4041,18 @@ function buildPluginPackageJsonData(options) {
|
|
|
4031
4041
|
localPublishedNames,
|
|
4032
4042
|
packageConfig
|
|
4033
4043
|
}) : void 0;
|
|
4044
|
+
const usesReact = includesUiPreset || isLegacyWebpack;
|
|
4034
4045
|
const devDependencies = {
|
|
4035
4046
|
typescript: String(packageConfig.versions.typescript),
|
|
4036
4047
|
tsx: packageConfig.versions.tsx,
|
|
4037
|
-
...LEGACY_REACT_DEPENDENCIES
|
|
4048
|
+
...usesReact ? LEGACY_REACT_DEPENDENCIES : {}
|
|
4038
4049
|
};
|
|
4039
4050
|
if (includesUiPreset || isLegacyWebpack)
|
|
4040
4051
|
/** Independent ui-kit npm for authoring; PluginDev externalizes to host main subpath in prod. */
|
|
4041
4052
|
devDependencies[uiKitKey] = String(uiKitVersion);
|
|
4042
4053
|
if (bundler === "vite") {
|
|
4043
4054
|
devDependencies.vite = packageConfig.versions.vite;
|
|
4044
|
-
devDependencies["@vitejs/plugin-react"] = packageConfig.versions.viteReactPlugin;
|
|
4055
|
+
if (usesReact) devDependencies["@vitejs/plugin-react"] = packageConfig.versions.viteReactPlugin;
|
|
4045
4056
|
} else {
|
|
4046
4057
|
devDependencies.webpack = packageConfig.versions.webpack;
|
|
4047
4058
|
devDependencies["webpack-cli"] = packageConfig.versions.webpackCli;
|
package/package.json
CHANGED