@base44-preview/vite-plugin 1.0.35-pr.118.22dbd5b → 1.0.37-pr.121.9ef7c71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +16 -5
  2. package/dist/build-status-plugin.d.ts.map +1 -1
  3. package/dist/build-status-plugin.js +40 -0
  4. package/dist/build-status-plugin.js.map +1 -1
  5. package/dist/bundled-dev.d.ts +10 -0
  6. package/dist/bundled-dev.d.ts.map +1 -0
  7. package/dist/bundled-dev.js +14 -0
  8. package/dist/bundled-dev.js.map +1 -0
  9. package/dist/error-overlay-plugin.d.ts.map +1 -1
  10. package/dist/error-overlay-plugin.js +4 -0
  11. package/dist/error-overlay-plugin.js.map +1 -1
  12. package/dist/html-injections-plugin.d.ts +11 -2
  13. package/dist/html-injections-plugin.d.ts.map +1 -1
  14. package/dist/html-injections-plugin.js +145 -59
  15. package/dist/html-injections-plugin.js.map +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/index.js.map +1 -1
  18. package/dist/injections/sandbox-build-error-notifier.d.ts +6 -0
  19. package/dist/injections/sandbox-build-error-notifier.d.ts.map +1 -0
  20. package/dist/injections/sandbox-build-error-notifier.js +26 -0
  21. package/dist/injections/sandbox-build-error-notifier.js.map +1 -0
  22. package/dist/injections/sandbox-hmr-socket-relay.d.ts +7 -0
  23. package/dist/injections/sandbox-hmr-socket-relay.d.ts.map +1 -0
  24. package/dist/injections/sandbox-hmr-socket-relay.js +28 -0
  25. package/dist/injections/sandbox-hmr-socket-relay.js.map +1 -0
  26. package/dist/injections/visual-edit-agent.d.ts.map +1 -1
  27. package/dist/injections/visual-edit-agent.js +14 -4
  28. package/dist/injections/visual-edit-agent.js.map +1 -1
  29. package/dist/statics/index.mjs +7 -7
  30. package/dist/statics/index.mjs.map +1 -1
  31. package/package.json +1 -1
  32. package/src/build-status-plugin.ts +43 -1
  33. package/src/bundled-dev.ts +13 -0
  34. package/src/error-overlay-plugin.ts +5 -0
  35. package/src/html-injections-plugin.ts +164 -71
  36. package/src/index.ts +1 -1
  37. package/src/injections/sandbox-build-error-notifier.ts +36 -0
  38. package/src/injections/sandbox-hmr-socket-relay.ts +37 -0
  39. package/src/injections/visual-edit-agent.ts +15 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/vite-plugin",
3
- "version": "1.0.35-pr.118.22dbd5b",
3
+ "version": "1.0.37-pr.121.9ef7c71",
4
4
  "description": "The Vite plugin for base44 based applications",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,5 +1,6 @@
1
- import type { Connect, Plugin, ViteDevServer } from "vite";
1
+ import type { Connect, Logger, Plugin, ViteDevServer } from "vite";
2
2
  import type { ServerResponse } from "http";
3
+ import { isBundledDev } from "./bundled-dev.js";
3
4
 
4
5
  /**
5
6
  * Opt-in, loopback-gated dev-server endpoint that reports the last
@@ -36,6 +37,18 @@ const MAX_FRAME = 2000;
36
37
 
37
38
  type SendChannel = { send: (...args: unknown[]) => void };
38
39
 
40
+ const PATCHED = Symbol.for("base44.buildStatus.loggerPatched");
41
+ type PatchableLogger = Omit<Logger, "error"> & {
42
+ error: Logger["error"] & { [PATCHED]?: boolean };
43
+ };
44
+
45
+ // Plugin hooks run once per environment in bundled dev; only the client's
46
+ // build is the preview. Older Vite has no `this.environment`.
47
+ function isClientEnvironment(ctx: unknown): boolean {
48
+ const name = (ctx as { environment?: { name?: string } } | undefined)?.environment?.name;
49
+ return name === undefined || name === "client";
50
+ }
51
+
39
52
  const LOOPBACK_ADDRESSES = new Set([
40
53
  "127.0.0.1",
41
54
  "::1",
@@ -122,12 +135,41 @@ export function scrub(err: unknown): Record<string, unknown> | null {
122
135
 
123
136
  export function buildStatusPlugin(): Plugin {
124
137
  let lastError: unknown = null;
138
+ let bundled = false;
125
139
 
126
140
  return {
127
141
  name: "base44-build-status",
128
142
  apply: "serve",
143
+ configResolved(config) {
144
+ bundled = isBundledDev(config);
145
+ },
146
+ // Bundled dev runs the rolldown build hooks on every rebuild of the client
147
+ // environment; a build that reaches generateBundle superseded whatever error
148
+ // was recorded before. Other environments' builds say nothing about the preview.
149
+ buildEnd(error) {
150
+ if (bundled && error && isClientEnvironment(this)) lastError = error;
151
+ },
152
+ generateBundle() {
153
+ if (bundled && isClientEnvironment(this)) lastError = null;
154
+ },
129
155
  configureServer(server: ViteDevServer) {
130
156
  try {
157
+ if (bundled) {
158
+ // Bundled dev reports build failures through the environment logger
159
+ // (`{ error }` option) and per-client sends, never the broadcast
160
+ // channel patched below. Any logged `{ error }` counts until the next
161
+ // successful build: the fail-safe direction for a health endpoint.
162
+ const logger = server.environments.client.logger as PatchableLogger;
163
+ if (!logger.error[PATCHED]) {
164
+ const origError = logger.error.bind(logger);
165
+ const patched: PatchableLogger["error"] = (msg, options) => {
166
+ if (options?.error) lastError = options.error;
167
+ return origError(msg, options);
168
+ };
169
+ patched[PATCHED] = true;
170
+ logger.error = patched;
171
+ }
172
+ }
131
173
  // Observe the HMR channel: an `error` payload records the last
132
174
  // error; a successful `update` / `full-reload` clears it.
133
175
  const ch = (server.hot ?? server.ws) as unknown as SendChannel | undefined;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Vite 8's experimental full-bundle dev mode (`experimental.bundledDev`) serves
3
+ * the client from an in-memory rolldown build. It mounts neither the transform
4
+ * nor the static middlewares, so raw `/node_modules/...` and `/@vite/client`
5
+ * URLs stop resolving, and build errors surface through the environment logger
6
+ * instead of the websocket broadcast. Plugins that assume the middleware-based
7
+ * dev server branch on this.
8
+ */
9
+ export function isBundledDev(config: unknown): boolean {
10
+ const experimental = (config as { experimental?: { bundledDev?: unknown } } | undefined)
11
+ ?.experimental;
12
+ return Boolean(experimental?.bundledDev);
13
+ }
@@ -1,5 +1,6 @@
1
1
  import { errorOverlayCode } from "./ErrorOverlay.js";
2
2
  import type { Plugin } from "vite";
3
+ import { isBundledDev } from "./bundled-dev.js";
3
4
 
4
5
  // Vite <=6 emits `class ErrorOverlay extends HTMLElement`, Vite >=7
5
6
  // `var ErrorOverlay = class extends HTMLElement`. This is Vite's bundled output,
@@ -12,6 +13,10 @@ export function errorOverlayPlugin() {
12
13
  return {
13
14
  name: "error-overlay",
14
15
  apply: (config) => config.mode === "development",
16
+ // Bundled dev never serves client.mjs, so the swap below cannot run. Turn
17
+ // Vite's overlay off and let sandbox-build-error-notifier forward the error.
18
+ config: (config) =>
19
+ isBundledDev(config) ? { server: { hmr: { overlay: false } } } : null,
15
20
  transform(code, id, opts = {}) {
16
21
  if (opts?.ssr) return;
17
22
 
@@ -1,5 +1,10 @@
1
- import type { Plugin, HtmlTagDescriptor } from "vite";
1
+ import { createReadStream, existsSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { ServerResponse } from "node:http";
5
+ import type { Connect, Plugin, HtmlTagDescriptor, ViteDevServer } from "vite";
2
6
  import { loadEnv } from "vite";
7
+ import { isBundledDev } from "./bundled-dev.js";
3
8
 
4
9
  type Injection = {
5
10
  /** Script src path for dev mode (served from node_modules) */
@@ -8,6 +13,8 @@ type Injection = {
8
13
  mode: "dev" | "production";
9
14
  /** Inline content for production builds (src paths don't work in built output) */
10
15
  inlineContent?: string;
16
+ /** Dev injections that only make sense when the client is bundled. */
17
+ bundledOnly?: boolean;
11
18
  };
12
19
 
13
20
  const ANALYTICS_TRACKER_SCRIPT = `
@@ -43,27 +50,41 @@ if (window.self === window.top) {
43
50
  }
44
51
  `;
45
52
 
53
+ const DIST_URL_PREFIX = "/node_modules/@base44/vite-plugin/dist";
54
+
46
55
  const INJECTIONS: Record<string, Injection> = {
47
56
  unhandledErrors: {
48
- src: "/node_modules/@base44/vite-plugin/dist/injections/unhandled-errors-handlers.js",
57
+ src: `${DIST_URL_PREFIX}/injections/unhandled-errors-handlers.js`,
49
58
  injectTo: "head",
50
59
  mode: "dev",
51
60
  },
52
61
  sandboxMount: {
53
- src: "/node_modules/@base44/vite-plugin/dist/injections/sandbox-mount-observer.js",
62
+ src: `${DIST_URL_PREFIX}/injections/sandbox-mount-observer.js`,
54
63
  injectTo: "body",
55
64
  mode: "dev",
56
65
  },
57
66
  hmrNotifier: {
58
- src: "/node_modules/@base44/vite-plugin/dist/injections/sandbox-hmr-notifier.js",
67
+ src: `${DIST_URL_PREFIX}/injections/sandbox-hmr-notifier.js`,
59
68
  injectTo: "head",
60
69
  mode: "dev",
61
70
  },
62
71
  navigationNotifier: {
63
- src: "/node_modules/@base44/vite-plugin/dist/injections/navigation-notifier.js",
72
+ src: `${DIST_URL_PREFIX}/injections/navigation-notifier.js`,
64
73
  injectTo: "head",
65
74
  mode: "dev",
66
75
  },
76
+ buildErrorNotifier: {
77
+ src: `${DIST_URL_PREFIX}/injections/sandbox-build-error-notifier.js`,
78
+ injectTo: "head",
79
+ mode: "dev",
80
+ bundledOnly: true,
81
+ },
82
+ hmrSocketRelay: {
83
+ src: `${DIST_URL_PREFIX}/injections/sandbox-hmr-socket-relay.js`,
84
+ injectTo: "head",
85
+ mode: "dev",
86
+ bundledOnly: true,
87
+ },
67
88
  analyticsTracker: {
68
89
  injectTo: "head",
69
90
  mode: "production",
@@ -71,6 +92,49 @@ const INJECTIONS: Record<string, Injection> = {
71
92
  },
72
93
  };
73
94
 
95
+ const CONTENT_TYPES: Record<string, string> = {
96
+ ".js": "text/javascript",
97
+ ".mjs": "text/javascript",
98
+ ".map": "application/json",
99
+ };
100
+
101
+ /** This file lives in dist/ once built, so its directory is the served root. */
102
+ export const PLUGIN_DIST_DIR = path.dirname(fileURLToPath(import.meta.url));
103
+
104
+ /**
105
+ * Bundled dev mounts no static/transform middleware, so the visual-edit agent's
106
+ * dynamic `import()` of dist/statics/index.mjs would fall through to the SPA
107
+ * fallback and receive index.html. Serve the plugin's own dist tree instead.
108
+ */
109
+ export function serveDistMiddleware(distDir: string) {
110
+ return (req: Connect.IncomingMessage, res: ServerResponse, next: Connect.NextFunction) => {
111
+ const url = (req.url ?? "").split("?")[0] ?? "";
112
+ if (!url.startsWith(`${DIST_URL_PREFIX}/`)) return next();
113
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
114
+ let relative: string;
115
+ try {
116
+ relative = decodeURIComponent(url.slice(DIST_URL_PREFIX.length + 1));
117
+ } catch {
118
+ return next();
119
+ }
120
+ const filePath = path.resolve(distDir, relative);
121
+ const type = CONTENT_TYPES[path.extname(filePath)];
122
+ if (
123
+ !type ||
124
+ !filePath.startsWith(distDir + path.sep) ||
125
+ !existsSync(filePath) ||
126
+ !statSync(filePath).isFile()
127
+ ) {
128
+ return next();
129
+ }
130
+ res.statusCode = 200;
131
+ res.setHeader("Content-Type", type);
132
+ res.setHeader("Cache-Control", "no-store");
133
+ // Headers are already out, so a read failure can only end the response.
134
+ createReadStream(filePath).on("error", () => res.end()).pipe(res);
135
+ };
136
+ }
137
+
74
138
  export function htmlInjectionsPlugin({
75
139
  hmrNotifier,
76
140
  navigationNotifier,
@@ -81,88 +145,117 @@ export function htmlInjectionsPlugin({
81
145
  navigationNotifier: boolean;
82
146
  visualEditAgent: boolean;
83
147
  analyticsTracker: boolean;
84
- }) {
148
+ }): Plugin[] {
85
149
  const enabledInjections: Record<string, boolean> = {
86
150
  unhandledErrors: true,
87
151
  sandboxMount: true,
88
152
  hmrNotifier,
89
153
  navigationNotifier,
154
+ buildErrorNotifier: true,
155
+ hmrSocketRelay: true,
90
156
  analyticsTracker,
91
157
  };
92
158
 
93
159
  let resolvedEnv: Record<string, string> = {};
160
+ let isServe = false;
161
+ let bundled = false;
162
+
163
+ const tagsFor = (mode: "dev" | "production"): HtmlTagDescriptor[] =>
164
+ Object.entries(INJECTIONS)
165
+ .filter(
166
+ ([key, injection]) =>
167
+ enabledInjections[key] &&
168
+ injection.mode === mode &&
169
+ (!injection.bundledOnly || bundled)
170
+ )
171
+ .map(([, injection]): HtmlTagDescriptor => {
172
+ if (injection.inlineContent) {
173
+ // Vite doesn't replace import.meta.env inside injected inline scripts.
174
+ const content = injection.inlineContent.replace(
175
+ /import\.meta\.env\.(\w+)/g,
176
+ (_, envKey) => JSON.stringify(resolvedEnv[envKey] ?? "")
177
+ );
178
+ return {
179
+ tag: "script",
180
+ attrs: { type: "module" },
181
+ children: content,
182
+ injectTo: injection.injectTo,
183
+ };
184
+ }
185
+ return {
186
+ tag: "script",
187
+ attrs: { src: injection.src, type: "module" },
188
+ injectTo: injection.injectTo,
189
+ };
190
+ });
191
+
192
+ const visualEditAgentTag = (): HtmlTagDescriptor => ({
193
+ tag: "script",
194
+ attrs: { type: "module" },
195
+ children: [
196
+ `if (window.self !== window.top) {`,
197
+ ` const mode = new URLSearchParams(location.search).get("sandbox-bridge");`,
198
+ ` const url = mode === "local"`,
199
+ ` ? "https://localhost:3201/index.mjs"`,
200
+ ` : "${DIST_URL_PREFIX}/statics/index.mjs";`,
201
+ ` import(url)`,
202
+ ` .then(mod => {`,
203
+ ` if (typeof mod.setupVisualEditAgent === "function") mod.setupVisualEditAgent();`,
204
+ ` })`,
205
+ ` .catch(e => console.error("[visual-edit-agent] Failed to load:", e));`,
206
+ `}`,
207
+ ].join("\n"),
208
+ injectTo: "body",
209
+ });
210
+
211
+ const devTags = () => {
212
+ const tags = tagsFor("dev");
213
+ if (visualEditAgent) tags.push(visualEditAgentTag());
214
+ return tags;
215
+ };
94
216
 
95
- return {
217
+ const dev: Plugin = {
96
218
  name: "html-injections",
97
219
  configResolved(config) {
98
- // Capture env vars for use in transformIndexHtml
99
- // loadEnv gets all env vars including VITE_ prefixed ones
100
220
  resolvedEnv = loadEnv(config.mode, config.root, "");
221
+ // `ctx.server` is absent in bundled dev, where the HTML runs through the
222
+ // build-shaped transform; the command is the only reliable dev signal.
223
+ isServe = config.command === "serve";
224
+ bundled = isBundledDev(config);
225
+ },
226
+ configureServer(server: ViteDevServer) {
227
+ if (!bundled) return;
228
+ server.middlewares.use(serveDistMiddleware(PLUGIN_DIST_DIR));
101
229
  },
102
230
  transformIndexHtml: {
103
- handler(_html, ctx) {
104
- const currentMode = ctx.server ? "dev" : "production";
105
-
106
- const tags = Object.entries(INJECTIONS)
107
- .filter(
108
- ([key, injection]) =>
109
- enabledInjections[key] && injection.mode === currentMode
110
- )
111
- .map(([, injection]): HtmlTagDescriptor => {
112
- // Production injections use inline content (src paths don't work in built output)
113
- if (injection.inlineContent) {
114
- // Replace import.meta.env references with actual values
115
- // Vite doesn't replace these in inline script content
116
- let content = injection.inlineContent;
117
- content = content.replace(
118
- /import\.meta\.env\.(\w+)/g,
119
- (_, envKey) => JSON.stringify(resolvedEnv[envKey] ?? "")
120
- );
121
-
122
- return {
123
- tag: "script",
124
- attrs: { type: "module" },
125
- children: content,
126
- injectTo: injection.injectTo,
127
- };
128
- }
129
- // Dev injections use src path (served from node_modules)
130
- return {
131
- tag: "script",
132
- attrs: {
133
- src: injection.src,
134
- type: "module",
135
- },
136
- injectTo: injection.injectTo,
137
- };
138
- });
139
-
140
- // Visual edit agent — loaded via dynamic import to support
141
- // local dev iteration with ?sandbox-bridge=local
142
- if (currentMode === "dev" && visualEditAgent) {
143
- const dist = "/node_modules/@base44/vite-plugin/dist";
144
- tags.push({
145
- tag: "script",
146
- attrs: { type: "module" },
147
- children: [
148
- `if (window.self !== window.top) {`,
149
- ` const mode = new URLSearchParams(location.search).get("sandbox-bridge");`,
150
- ` const url = mode === "local"`,
151
- ` ? "https://localhost:3201/index.mjs"`,
152
- ` : "${dist}/statics/index.mjs";`,
153
- ` import(url)`,
154
- ` .then(mod => {`,
155
- ` if (typeof mod.setupVisualEditAgent === "function") mod.setupVisualEditAgent();`,
156
- ` })`,
157
- ` .catch(e => console.error("[visual-edit-agent] Failed to load:", e));`,
158
- `}`,
159
- ].join("\n"),
160
- injectTo: "body",
161
- });
162
- }
231
+ handler() {
232
+ return isServe && !bundled ? devTags() : [];
233
+ },
234
+ },
235
+ };
163
236
 
164
- return tags;
237
+ // Pre-order tags are part of the HTML entry, so bundled dev folds them into
238
+ // the bundle (with `import.meta.hot`) instead of leaving raw node_modules URLs
239
+ // that nothing serves. Kept separate so the middleware-based dev server keeps
240
+ // injecting after its own HTML processing, exactly as before.
241
+ const devBundled: Plugin = {
242
+ name: "html-injections-bundled",
243
+ transformIndexHtml: {
244
+ order: "pre",
245
+ handler() {
246
+ return isServe && bundled ? devTags() : [];
165
247
  },
166
248
  },
167
- } as Plugin;
249
+ };
250
+
251
+ const production: Plugin = {
252
+ name: "html-injections-production",
253
+ transformIndexHtml: {
254
+ handler() {
255
+ return isServe ? [] : tagsFor("production");
256
+ },
257
+ },
258
+ };
259
+
260
+ return [dev, devBundled, production];
168
261
  }
package/src/index.ts CHANGED
@@ -280,7 +280,7 @@ export default function vitePlugin(
280
280
  ]
281
281
  : []),
282
282
  // HTML injections - handles both dev (sandbox) and production injections
283
- htmlInjectionsPlugin({ hmrNotifier, navigationNotifier, visualEditAgent, analyticsTracker }),
283
+ ...htmlInjectionsPlugin({ hmrNotifier, navigationNotifier, visualEditAgent, analyticsTracker }),
284
284
  // Opt-in, loopback-gated dev-server build-status endpoint. Gated here on
285
285
  // the BASE44_BUILD_STATUS_ENABLED env var so the generated app's
286
286
  // vite.config.js doesn't need to change and the sub-plugin isn't even
@@ -0,0 +1,36 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ // Bundled dev mode keeps Vite's own client, so the ErrorOverlay swap in
4
+ // error-overlay-plugin never runs. The overlay is disabled server-side instead
5
+ // and build errors are forwarded here in the same `app_error` shape.
6
+
7
+ type BuildErrorPayload = { err?: Record<string, unknown> } | undefined;
8
+
9
+ export function reportBuildError(payload: BuildErrorPayload, win: Window = window) {
10
+ const err = payload?.err ?? {};
11
+ const message = typeof err.message === "string" ? err.message : "Build error";
12
+ const stack = typeof err.stack === "string" ? err.stack : undefined;
13
+ const loc = err.loc as { file?: string; line?: number; column?: number } | undefined;
14
+ const file = loc?.file ?? (typeof err.id === "string" ? err.id : undefined);
15
+ const where = file && loc?.line != null ? `${file}:${loc.line}:${loc.column ?? 0}` : file;
16
+ const details = [where, typeof err.frame === "string" ? err.frame : undefined, stack]
17
+ .filter(Boolean)
18
+ .join("\n");
19
+ win.parent?.postMessage(
20
+ {
21
+ type: "app_error",
22
+ error: {
23
+ title: message,
24
+ details: details || undefined,
25
+ componentName: undefined,
26
+ originalError: { message, stack, plugin: err.plugin, id: err.id, loc },
27
+ stack,
28
+ },
29
+ },
30
+ "*"
31
+ );
32
+ }
33
+
34
+ if (import.meta.hot) {
35
+ import.meta.hot.on("vite:error", (payload) => reportBuildError(payload as BuildErrorPayload));
36
+ }
@@ -0,0 +1,37 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ // The preview proxy's bridge watches the HMR socket by importing /@vite/client,
4
+ // which bundled dev mode does not serve. This module ships inside the bundle and
5
+ // reports the same events; the bridge skips its own attach when it sees the flag.
6
+
7
+ type HotEvents = {
8
+ on: (event: string, cb: (payload?: unknown) => unknown) => void;
9
+ };
10
+
11
+ // Query param the editor adds to the preview URL when it can swap in a fresh
12
+ // iframe on a full reload (mirrors builder_bridge_inject.py in base44-dev/apper).
13
+ export const PREVIEW_FE_VERSION_PARAM = "previewFE_version";
14
+
15
+ export function attachHmrSocketRelay(hot: HotEvents, win: Window = window) {
16
+ (win as unknown as Record<string, unknown>).__base44_bundled_dev__ = true;
17
+ if (win.self === win.top) return;
18
+ const previewFEVersion =
19
+ Number(new URLSearchParams(win.location.search).get(PREVIEW_FE_VERSION_PARAM)) || 0;
20
+ hot.on("vite:ws:connect", () => {
21
+ win.parent?.postMessage({ type: "SANDBOX_WS_CONNECT" }, "*");
22
+ });
23
+ hot.on("vite:ws:disconnect", () => {
24
+ win.parent?.postMessage({ type: "SANDBOX_WS_DISCONNECT" }, "*");
25
+ });
26
+ // Vite's bundled client awaits `vite:beforeFullReload` listeners before it
27
+ // reloads (verified against vite 8.2 bundledDevClient), so a never-settling
28
+ // promise holds the reload and lets the editor swap in a fresh iframe instead.
29
+ hot.on("vite:beforeFullReload", () => {
30
+ win.parent?.postMessage({ type: "sandbox:beforeFullReload" }, "*");
31
+ return previewFEVersion > 0 ? new Promise<void>(() => {}) : undefined;
32
+ });
33
+ }
34
+
35
+ // The socket opens asynchronously, after the whole bundle has evaluated, so the
36
+ // listeners above are always registered before the first connect event.
37
+ if (import.meta.hot) attachHmrSocketRelay(import.meta.hot);
@@ -181,7 +181,7 @@ export function setupVisualEditAgent() {
181
181
  };
182
182
 
183
183
  // Select an element: create overlays, update state, notify parent
184
- const selectElement = (element: Element): HTMLDivElement | undefined => {
184
+ const selectElement = (element: Element, notifyParent = true): HTMLDivElement | undefined => {
185
185
  const visualSelectorId = getElementSelectorId(element);
186
186
 
187
187
  clearSelectedOverlays();
@@ -197,7 +197,7 @@ export function setupVisualEditAgent() {
197
197
  selectedElementId = visualSelectorId || null;
198
198
  selectedElement = element;
199
199
  clearHoverOverlays();
200
- notifyElementSelected(element);
200
+ if (notifyParent) notifyElementSelected(element);
201
201
 
202
202
  return selectedOverlays[0];
203
203
  };
@@ -381,9 +381,20 @@ export function setupVisualEditAgent() {
381
381
  // Reposition overlays after attribute change (e.g. image src swap can affect layout)
382
382
  setTimeout(() => {
383
383
  if (selectedElementId === visualSelectorId) {
384
+ const currentElements = findElementsById(visualSelectorId);
385
+ if (selectedElement && !selectedElement.isConnected) {
386
+ const selectedIndex = (selectedElement as HTMLElement).dataset.arrIndex;
387
+ const replacement = currentElements.find(
388
+ (element) => (element as HTMLElement).dataset.arrIndex === selectedIndex
389
+ );
390
+ if (replacement) {
391
+ const overlay = selectElement(replacement, false);
392
+ layerController.attachToOverlay(overlay, replacement);
393
+ }
394
+ }
384
395
  selectedOverlays.forEach((overlay, index) => {
385
- if (index < elements.length) {
386
- positionOverlay(overlay, elements[index]!);
396
+ if (index < currentElements.length) {
397
+ positionOverlay(overlay, currentElements[index]!);
387
398
  }
388
399
  });
389
400
  }