tempo-sdk 0.0.20 → 0.0.22

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.
@@ -0,0 +1,19 @@
1
+ // ../../modules/iframe-projection/combined/projection-pending.ts
2
+ var PROJECTION_PENDING_ATTRIBUTE = "data-tempo-projection-pending";
3
+ function isProjectionPendingOnly(rootElement) {
4
+ const children = rootElement.children;
5
+ if (children.length === 0) return false;
6
+ for (let index = 0; index < children.length; index += 1) {
7
+ const child = children[index];
8
+ if (!child || !child.hasAttribute(PROJECTION_PENDING_ATTRIBUTE)) {
9
+ return false;
10
+ }
11
+ }
12
+ return true;
13
+ }
14
+
15
+ export {
16
+ PROJECTION_PENDING_ATTRIBUTE,
17
+ isProjectionPendingOnly
18
+ };
19
+ //# sourceMappingURL=chunk-ZT2REPH4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../modules/iframe-projection/combined/projection-pending.ts"],"sourcesContent":["/**\n * The pending-marker contract, shared between the source app and the producer.\n *\n * A Tempo-owned Suspense boundary renders a single hidden marker element as its\n * fallback instead of `null`. That turns \"this subtree is briefly empty because\n * content is loading\" — which is indistinguishable from \"this subtree is now\n * genuinely empty\" once it reaches the DOM — into something the producer can\n * recognise without inspecting React internals.\n *\n * This file is imported directly by tempo-sdk and bundled into it, so it must\n * stay dependency-free: no imports, no DOM globals beyond the element passed in.\n */\n\n/** Marks an element as a Tempo Suspense boundary's pending placeholder. */\nexport const PROJECTION_PENDING_ATTRIBUTE = \"data-tempo-projection-pending\";\n\n/**\n * Is this root showing a pending marker and nothing else?\n *\n * The rule is deliberately strict — marker-ONLY. A root that still holds real\n * content alongside a marker is a partially-loaded tree, and partial content is\n * exactly what the mirror should show; only a root whose entire visible output\n * is placeholder has nothing worth publishing. An empty root is likewise not\n * pending: emptiness with no marker is a real state (a conditional unmount, a\n * foreign boundary with `fallback={null}`) and stays a real change.\n */\nexport function isProjectionPendingOnly(rootElement: Element): boolean {\n const children = rootElement.children;\n if (children.length === 0) return false;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (!child || !child.hasAttribute(PROJECTION_PENDING_ATTRIBUTE)) {\n return false;\n }\n }\n return true;\n}\n"],"mappings":";AAcO,IAAM,+BAA+B;AAYrC,SAAS,wBAAwB,aAA+B;AACrE,QAAM,WAAW,YAAY;AAC7B,MAAI,SAAS,WAAW,EAAG,QAAO;AAClC,WAAS,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS,GAAG;AACvD,UAAM,QAAQ,SAAS,KAAK;AAC5B,QAAI,CAAC,SAAS,CAAC,MAAM,aAAa,4BAA4B,GAAG;AAC/D,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { ServerResponse, IncomingMessage } from 'node:http';
2
2
  import { FilterPattern } from '@rollup/pluginutils';
3
3
  import { Plugin } from 'vite';
4
4
  import { JSXElement } from 'oxc-parser';
5
- export { S as StoryboardLayout, T as TempoCanvasConfig, a as TempoHtmlStoryboard, b as TempoPage, c as TempoRouteStoryboard, d as TempoStoryboard } from './page-xi1aI5a7.js';
5
+ export { S as StoryboardLayout, T as TempoCanvasConfig, a as TempoHtmlStoryboard, b as TempoPage, c as TempoRouteStoryboard, d as TempoStoryboard } from './page-BUbHO0BI.js';
6
6
  import 'react';
7
7
 
8
8
  interface ElementInfo {
@@ -41,6 +41,9 @@ type SseClient = ServerResponse<IncomingMessage>;
41
41
  interface TempoErrorServer {
42
42
  /** The error currently broadcast to SSE clients (most recent across all modules). */
43
43
  readonly currentError: TempoViteError | null;
44
+ /** Files with active compile errors. Failed transforms may not be present in
45
+ * Vite's module graph, so recovery code must track them explicitly. */
46
+ readonly errorFiles: readonly string[];
44
47
  clients: Set<SseClient>;
45
48
  setError(error: TempoViteError): void;
46
49
  /** Clear errors for exact module aliases present in the HMR update. Pathless
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  watch as watchFileSystem
11
11
  } from "fs";
12
12
  import { createRequire } from "module";
13
- import { dirname, join, relative as relative2, resolve } from "path";
13
+ import { dirname, isAbsolute, join, relative as relative2, resolve } from "path";
14
14
  import { createFilter } from "@rollup/pluginutils";
15
15
 
16
16
  // ../../modules/annotation/annotate-file.ts
@@ -225,9 +225,17 @@ function computeTempoAnnotatedProps(params) {
225
225
  return userProps;
226
226
  }
227
227
 
228
+ // canvas-host-registration-contract.ts
229
+ var CANVAS_HOST_REGISTRATION_ENDPOINT = "/__tempo/canvas-host-registration";
230
+ var CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER = "x-tempo-canvas-host-registration";
231
+ function normalizeCanvasRegistrationPath(canvasPath) {
232
+ return canvasPath.trim().replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
233
+ }
234
+
228
235
  // default-export-identity.ts
229
236
  var FUNCTION_DEFAULT_RE = /^(?:async\s+)?function(?:\s*\*)?(?:\s+([A-Za-z_$][\w$]*))?\s*\(/;
230
237
  var CLASS_DEFAULT_RE = /^(?:abstract\s+)?class(?:\s+([A-Za-z_$][\w$]*))?(?=[\s{])/;
238
+ var ARROW_DEFAULT_RE = /^(?:async\s+)?(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>/;
231
239
  var IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\w$]*)[ \t]*(?:;|\r?\n|$)/;
232
240
  function readDefaultExportIdentity(source) {
233
241
  const start = /\bexport\s+default\s+/.exec(source);
@@ -237,12 +245,15 @@ function readDefaultExportIdentity(source) {
237
245
  if (fn) return { kind: "function", name: fn[1] ?? null };
238
246
  const cls = CLASS_DEFAULT_RE.exec(tail);
239
247
  if (cls) return { kind: "class", name: cls[1] ?? null };
248
+ if (ARROW_DEFAULT_RE.test(tail)) return { kind: "function", name: null };
240
249
  const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);
241
250
  if (identifier) return { kind: "identifier", name: identifier[1] };
242
251
  return null;
243
252
  }
244
253
  function isDefaultExportIdentityRewrite(before, after) {
245
- if (!before || !after) return false;
254
+ if (!before) return false;
255
+ if (before.name === null) return true;
256
+ if (!after) return false;
246
257
  if (before.name === after.name) return false;
247
258
  return isComponentShaped(before) && isComponentShaped(after);
248
259
  }
@@ -250,33 +261,99 @@ function isComponentShaped(identity) {
250
261
  return identity.name === null || /^[A-Z]/.test(identity.name);
251
262
  }
252
263
 
264
+ // hmr-generation-fence.ts
265
+ function generationIdentity(update) {
266
+ const type = typeof update.type === "string" ? update.type : null;
267
+ const acceptedPath = typeof update.acceptedPath === "string" ? update.acceptedPath : typeof update.path === "string" ? update.path : null;
268
+ if (!type || !acceptedPath) return null;
269
+ return `${type}\0${acceptedPath}`;
270
+ }
271
+ function createHmrGenerationFence() {
272
+ const newestTimestampByIdentity = /* @__PURE__ */ new Map();
273
+ return {
274
+ filter(updates) {
275
+ const accepted = [];
276
+ for (const update of updates) {
277
+ const identity = generationIdentity(update);
278
+ const timestamp = update.timestamp;
279
+ if (identity === null || typeof timestamp !== "number" || !Number.isFinite(timestamp)) {
280
+ accepted.push(update);
281
+ continue;
282
+ }
283
+ const newestTimestamp = newestTimestampByIdentity.get(identity);
284
+ if (newestTimestamp !== void 0 && timestamp < newestTimestamp) {
285
+ continue;
286
+ }
287
+ if (newestTimestamp === void 0 || timestamp > newestTimestamp) {
288
+ newestTimestampByIdentity.set(identity, timestamp);
289
+ }
290
+ accepted.push(update);
291
+ }
292
+ return accepted;
293
+ },
294
+ clear() {
295
+ newestTimestampByIdentity.clear();
296
+ }
297
+ };
298
+ }
299
+
253
300
  // missed-change-sweep.ts
254
301
  var MISSED_CHANGE_WATCHER_GRACE_MS = 1e3;
302
+ var MISSED_CHANGE_MAX_EMITS_PER_REVISION = 3;
255
303
  function createMissedChangeSweep(args) {
256
304
  const now = args.now ?? Date.now;
257
305
  const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;
306
+ const maxEmits = args.maxEmitsPerRevision ?? MISSED_CHANGE_MAX_EMITS_PER_REVISION;
258
307
  const lastSeenMtimeMs = /* @__PURE__ */ new Map();
308
+ const pending = /* @__PURE__ */ new Map();
259
309
  return {
260
310
  async sweep() {
261
311
  const emitted = [];
262
312
  for (const [file, modules] of args.listServedFiles()) {
263
313
  const mtimeMs = await args.statMtimeMs(file);
264
- if (mtimeMs === null) continue;
265
- const previous = lastSeenMtimeMs.get(file);
266
- if (previous === void 0 || mtimeMs <= previous) {
267
- lastSeenMtimeMs.set(file, mtimeMs);
314
+ if (mtimeMs === null) {
315
+ pending.delete(file);
268
316
  continue;
269
317
  }
270
- if (now() - mtimeMs < graceMs) continue;
271
- lastSeenMtimeMs.set(file, mtimeMs);
272
- let viteAlreadySawIt = false;
273
- for (const module of modules) {
274
- if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {
275
- viteAlreadySawIt = true;
276
- break;
318
+ let previous = lastSeenMtimeMs.get(file);
319
+ if (previous === void 0) {
320
+ const coveredMtimeMs = args.lastHotUpdateMtimeMs?.(file);
321
+ if (coveredMtimeMs === void 0 || coveredMtimeMs >= mtimeMs) {
322
+ lastSeenMtimeMs.set(file, mtimeMs);
323
+ continue;
277
324
  }
325
+ previous = coveredMtimeMs;
326
+ lastSeenMtimeMs.set(file, coveredMtimeMs);
278
327
  }
279
- if (viteAlreadySawIt) continue;
328
+ if (mtimeMs > previous) {
329
+ if (now() - mtimeMs < graceMs) continue;
330
+ lastSeenMtimeMs.set(file, mtimeMs);
331
+ } else if (mtimeMs < previous) {
332
+ lastSeenMtimeMs.set(file, mtimeMs);
333
+ }
334
+ const entry = pending.get(file);
335
+ if (mtimeMs <= previous && entry === void 0) continue;
336
+ const hotUpdateMtimeMs = args.lastHotUpdateMtimeMs?.(file);
337
+ let delivered;
338
+ if (hotUpdateMtimeMs !== void 0) {
339
+ delivered = hotUpdateMtimeMs >= mtimeMs;
340
+ } else {
341
+ delivered = false;
342
+ for (const module of modules) {
343
+ if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {
344
+ delivered = true;
345
+ break;
346
+ }
347
+ }
348
+ }
349
+ if (delivered) {
350
+ pending.delete(file);
351
+ continue;
352
+ }
353
+ const revision = entry !== void 0 && entry.mtimeMs === mtimeMs ? entry : { mtimeMs, emits: 0 };
354
+ pending.set(file, revision);
355
+ if (revision.emits >= maxEmits) continue;
356
+ revision.emits += 1;
280
357
  args.emitChange(file);
281
358
  emitted.push(file);
282
359
  }
@@ -285,6 +362,43 @@ function createMissedChangeSweep(args) {
285
362
  };
286
363
  }
287
364
 
365
+ // rapid-hot-update-replay.ts
366
+ var RAPID_HOT_UPDATE_QUIET_MS = 100;
367
+ function createRapidHotUpdateReplay(options) {
368
+ const quietMs = options?.quietMs ?? RAPID_HOT_UPDATE_QUIET_MS;
369
+ const schedule = options?.schedule ?? setTimeout;
370
+ const cancel = options?.cancel ?? clearTimeout;
371
+ const bursts = /* @__PURE__ */ new Map();
372
+ return {
373
+ observe(file, replay) {
374
+ const previous = bursts.get(file);
375
+ if (previous?.timer) cancel(previous.timer);
376
+ const burst = {
377
+ eventCount: (previous?.eventCount ?? 0) + 1,
378
+ replay
379
+ };
380
+ burst.timer = schedule(() => {
381
+ if (bursts.get(file) !== burst) return;
382
+ bursts.delete(file);
383
+ if (burst.eventCount < 2) return;
384
+ const replayAllowance = { eventCount: -1, replay: burst.replay };
385
+ replayAllowance.timer = schedule(() => {
386
+ if (bursts.get(file) === replayAllowance) bursts.delete(file);
387
+ }, quietMs);
388
+ bursts.set(file, replayAllowance);
389
+ burst.replay();
390
+ }, quietMs);
391
+ bursts.set(file, burst);
392
+ },
393
+ clear() {
394
+ for (const burst of bursts.values()) {
395
+ if (burst.timer) cancel(burst.timer);
396
+ }
397
+ bursts.clear();
398
+ }
399
+ };
400
+ }
401
+
288
402
  // index.ts
289
403
  var DEFAULT_INCLUDE = ["**/*.tsx", "**/*.jsx"];
290
404
  var DEFAULT_EXCLUDE = ["**/node_modules/**"];
@@ -328,6 +442,9 @@ var INTERACT_PROJECTION_BOOTSTRAP = `
328
442
  function cleanModuleId(id) {
329
443
  return id.replace(/[?#].*$/, "");
330
444
  }
445
+ function fsPathFromModuleId(id) {
446
+ return cleanModuleId(id).replace(/^\/@fs\//, "/");
447
+ }
331
448
  function isCanvasHostRequest(requestPath) {
332
449
  const url = new URL(requestPath, "http://tempo.local");
333
450
  return url.pathname.replace(/\/+$/, "") === "/tempo-host";
@@ -362,7 +479,7 @@ function barePackageName(specifier) {
362
479
  return packageName && /^@?[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(packageName) ? packageName : void 0;
363
480
  }
364
481
  function resolvedIdMatchesFile(id, file) {
365
- const resolvedFile = cleanModuleId(id).replace(/^\/@fs\//, "/");
482
+ const resolvedFile = fsPathFromModuleId(id);
366
483
  try {
367
484
  return realpathSync2.native(resolvedFile) === realpathSync2.native(file);
368
485
  } catch {
@@ -386,7 +503,10 @@ function hasRootMetaTag(html) {
386
503
  function hasSourceIdentityRootMetaTag(html) {
387
504
  return /<meta[^>]+name=["']tempo-source-identity-root["'][^>]*>/i.test(html);
388
505
  }
389
- function createErrorServer() {
506
+ function isSameError(left, right) {
507
+ return left.type === right.type && left.message === right.message && left.loc?.line === right.loc?.line && left.loc?.column === right.loc?.column;
508
+ }
509
+ function createErrorServer(onErrorFile) {
390
510
  const errorsByFile = /* @__PURE__ */ new Map();
391
511
  function getMostRecentError() {
392
512
  if (errorsByFile.size === 0) return null;
@@ -406,9 +526,15 @@ function createErrorServer() {
406
526
  get currentError() {
407
527
  return getMostRecentError();
408
528
  },
529
+ get errorFiles() {
530
+ return [...errorsByFile.keys()].filter((file) => file !== "unknown");
531
+ },
409
532
  clients: /* @__PURE__ */ new Set(),
410
533
  setError(error) {
411
534
  const key = error.file ?? error.loc?.file ?? "unknown";
535
+ const recorded = errorsByFile.get(key);
536
+ if (recorded && isSameError(recorded, error)) return;
537
+ if (key !== "unknown" && !recorded) onErrorFile?.(key);
412
538
  errorsByFile.delete(key);
413
539
  errorsByFile.set(key, error);
414
540
  broadcastCurrentState();
@@ -439,9 +565,102 @@ function readBody(req) {
439
565
  req.on("error", reject);
440
566
  });
441
567
  }
442
- function handleTempoMiddleware(errorServer, req, res, next) {
568
+ var CANVAS_HOST_WRAPPER_URL = "/.tempo/tempo-host";
569
+ function readGeneratedCanvasPaths(source) {
570
+ const paths = /* @__PURE__ */ new Set();
571
+ const canvasPathPattern = /\bcanvasPath:\s*("(?:\\.|[^"\\])*")/g;
572
+ for (const match of source.matchAll(canvasPathPattern)) {
573
+ try {
574
+ const parsed = JSON.parse(match[1] ?? "");
575
+ if (typeof parsed !== "string") continue;
576
+ const normalized = normalizeCanvasRegistrationPath(parsed);
577
+ if (normalized) paths.add(normalized);
578
+ } catch {
579
+ }
580
+ }
581
+ return [...paths];
582
+ }
583
+ async function synchronizeCanvasHostRegistrationTransform(server, canvasPath) {
584
+ const wrapperPath = resolve(server.config.root, ".tempo", "tempo-host.tsx");
585
+ let wrapperSource;
586
+ try {
587
+ wrapperSource = readFileSync(wrapperPath, "utf8");
588
+ } catch (error) {
589
+ throw new Error(
590
+ `Canvas host wrapper is unavailable at ${wrapperPath}: ${error instanceof Error ? error.message : String(error)}`
591
+ );
592
+ }
593
+ const registeredCanvasPaths = readGeneratedCanvasPaths(wrapperSource);
594
+ if (!registeredCanvasPaths.includes(canvasPath)) {
595
+ throw Object.assign(
596
+ new Error(
597
+ `Generated canvas host wrapper does not contain ${JSON.stringify(
598
+ canvasPath
599
+ )}`
600
+ ),
601
+ { statusCode: 409 }
602
+ );
603
+ }
604
+ const canonicalWrapperPath = realpathSync2(wrapperPath);
605
+ await retransformCanvasHostWrapper(
606
+ server.environments?.client ?? server,
607
+ canonicalWrapperPath,
608
+ wrapperPath
609
+ );
610
+ }
611
+ async function retransformCanvasHostWrapper(transformer, canonicalWrapperPath, wrapperPath) {
612
+ const modules = transformer.moduleGraph.getModulesByFile(canonicalWrapperPath) ?? transformer.moduleGraph.getModulesByFile(wrapperPath);
613
+ for (const module of modules ?? []) {
614
+ transformer.moduleGraph.invalidateModule(module);
615
+ }
616
+ const result = await transformer.transformRequest(CANVAS_HOST_WRAPPER_URL);
617
+ if (!result) {
618
+ throw new Error(
619
+ `Vite did not transform ${CANVAS_HOST_WRAPPER_URL} after registration`
620
+ );
621
+ }
622
+ }
623
+ function writeCanvasRegistrationResponseHeaders(res) {
624
+ res.setHeader("Access-Control-Allow-Origin", "*");
625
+ res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, "1");
626
+ }
627
+ function handleTempoMiddleware(errorServer, viteServer, req, res, next) {
443
628
  const url = req.url;
444
629
  if (!url?.startsWith("/__tempo/")) return next();
630
+ if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === "OPTIONS") {
631
+ writeCanvasRegistrationResponseHeaders(res);
632
+ res.writeHead(204, {
633
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
634
+ "Access-Control-Allow-Headers": "content-type"
635
+ });
636
+ res.end();
637
+ return;
638
+ }
639
+ if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === "POST") {
640
+ writeCanvasRegistrationResponseHeaders(res);
641
+ void readBody(req).then(async (body) => {
642
+ const parsed = JSON.parse(body);
643
+ const canvasPath = typeof parsed.canvasPath === "string" ? normalizeCanvasRegistrationPath(parsed.canvasPath) : "";
644
+ if (!canvasPath) {
645
+ throw Object.assign(
646
+ new Error("canvasPath must be a non-empty string"),
647
+ { statusCode: 400 }
648
+ );
649
+ }
650
+ await synchronizeCanvasHostRegistrationTransform(
651
+ viteServer,
652
+ canvasPath
653
+ );
654
+ res.statusCode = 200;
655
+ res.setHeader("Content-Type", "application/json");
656
+ res.end(JSON.stringify({ canvasPath }));
657
+ }).catch((error) => {
658
+ res.statusCode = typeof error === "object" && error !== null && "statusCode" in error && typeof error.statusCode === "number" ? error.statusCode : 500;
659
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
660
+ res.end(error instanceof Error ? error.message : String(error));
661
+ });
662
+ return;
663
+ }
445
664
  if (url === "/__tempo/report-error" && req.method === "POST") {
446
665
  readBody(req).then((body) => {
447
666
  try {
@@ -487,9 +706,21 @@ function handleTempoMiddleware(errorServer, req, res, next) {
487
706
  next();
488
707
  }
489
708
  var MISSED_CHANGE_SWEEP_INTERVAL_MS = 3e3;
490
- function installMissedChangeSweep(server) {
709
+ var COMPILE_ERROR_POLL_MAX_INTERVAL_MS = 3e4;
710
+ function installMissedChangeSweep(server, listErrorFiles, lastHotUpdateMtimeMs, pollCompileErrorRecovery) {
491
711
  const sweep = createMissedChangeSweep({
492
- listServedFiles: () => (server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map()).entries(),
712
+ listServedFiles: () => {
713
+ const files = new Map(
714
+ server.moduleGraph?.fileToModulesMap ?? /* @__PURE__ */ new Map()
715
+ );
716
+ const errorFiles = listErrorFiles();
717
+ for (const errorFile of errorFiles) {
718
+ const cleanFile = fsPathFromModuleId(errorFile);
719
+ const file = isAbsolute(cleanFile) ? cleanFile : resolve(server.config.root, cleanFile);
720
+ if (!files.has(file)) files.set(file, []);
721
+ }
722
+ return files.entries();
723
+ },
493
724
  statMtimeMs: async (file) => {
494
725
  try {
495
726
  return statSync2(file).mtimeMs;
@@ -503,15 +734,16 @@ function installMissedChangeSweep(server) {
503
734
  { timestamp: true }
504
735
  );
505
736
  server.watcher?.emit?.("change", file);
506
- }
737
+ },
738
+ lastHotUpdateMtimeMs
507
739
  });
508
- let sweeping = false;
740
+ let passRunning = false;
509
741
  const timer = setInterval(() => {
510
- if (sweeping) return;
511
- sweeping = true;
512
- void sweep.sweep().catch(() => {
742
+ if (passRunning) return;
743
+ passRunning = true;
744
+ void sweep.sweep().then(() => pollCompileErrorRecovery()).catch(() => {
513
745
  }).finally(() => {
514
- sweeping = false;
746
+ passRunning = false;
515
747
  });
516
748
  }, MISSED_CHANGE_SWEEP_INTERVAL_MS);
517
749
  timer.unref?.();
@@ -525,7 +757,9 @@ function tempoVitePlugin(options = {}) {
525
757
  let canonicalRoot = process.cwd();
526
758
  let sourceIdentityRoot = canonicalRoot;
527
759
  let command = "serve";
528
- const errorServer = createErrorServer();
760
+ const errorServer = createErrorServer(
761
+ (file) => pinErroneousRevisionCoverage(file)
762
+ );
529
763
  const unresolvedImports = /* @__PURE__ */ new Map();
530
764
  let devServer;
531
765
  const unresolvedImportWatchers = /* @__PURE__ */ new Map();
@@ -534,9 +768,77 @@ function tempoVitePlugin(options = {}) {
534
768
  let rerunUnresolvedImportResolution = false;
535
769
  let unresolvedImportWatchRearmTimer = null;
536
770
  const processedUpdatePayloads = /* @__PURE__ */ new WeakSet();
771
+ const hmrGenerationFence = createHmrGenerationFence();
772
+ const rapidHotUpdateReplay = createRapidHotUpdateReplay();
773
+ const hotUpdateMtimesMs = /* @__PURE__ */ new Map();
774
+ const normalizedFileKey = (file) => file.replace(/\\/g, "/");
775
+ const recordHotUpdateCoverage = (file) => {
776
+ const cleanFile = fsPathFromModuleId(file);
777
+ const key = normalizedFileKey(cleanFile);
778
+ try {
779
+ hotUpdateMtimesMs.set(key, statSync2(cleanFile).mtimeMs);
780
+ } catch {
781
+ hotUpdateMtimesMs.delete(key);
782
+ }
783
+ };
784
+ const pinErroneousRevisionCoverage = (file) => {
785
+ recordHotUpdateCoverage(file);
786
+ };
787
+ const hasActiveCompileError = (file) => errorServer.errorFiles.some((errorFile) => moduleIdsMatch(errorFile, file));
788
+ const recoverActiveCompileError = async (server, file) => {
789
+ if (!hasActiveCompileError(file)) return false;
790
+ const cleanFile = fsPathFromModuleId(file);
791
+ const requestId = `/@fs/${cleanFile.replace(/^\/+/, "")}`;
792
+ const clientEnvironment = server.environments?.client;
793
+ try {
794
+ const result = clientEnvironment ? await clientEnvironment.transformRequest(requestId) : await server.transformRequest(requestId);
795
+ if (!result) return false;
796
+ } catch {
797
+ return false;
798
+ }
799
+ errorServer.clearErrorForModules([file, cleanFile, requestId]);
800
+ server.config.logger.info(
801
+ `[tempo] recovered compile-error module after validated transform: ${cleanFile}`,
802
+ { timestamp: true }
803
+ );
804
+ (clientEnvironment?.hot ?? server.ws).send({
805
+ type: "full-reload",
806
+ path: "*"
807
+ });
808
+ return true;
809
+ };
810
+ const compileErrorPollSchedule = /* @__PURE__ */ new Map();
811
+ const pollCompileErrorRecovery = async (server) => {
812
+ const activeFiles = new Map(
813
+ errorServer.errorFiles.map((file) => [
814
+ normalizedFileKey(fsPathFromModuleId(file)),
815
+ file
816
+ ])
817
+ );
818
+ for (const key of [...compileErrorPollSchedule.keys()]) {
819
+ if (!activeFiles.has(key)) compileErrorPollSchedule.delete(key);
820
+ }
821
+ const nowMs = Date.now();
822
+ for (const [key, file] of activeFiles) {
823
+ const schedule = compileErrorPollSchedule.get(key);
824
+ if (schedule && nowMs < schedule.nextAttemptAtMs) continue;
825
+ if (await recoverActiveCompileError(server, file)) {
826
+ compileErrorPollSchedule.delete(key);
827
+ continue;
828
+ }
829
+ const intervalMs = schedule?.intervalMs ?? MISSED_CHANGE_SWEEP_INTERVAL_MS;
830
+ compileErrorPollSchedule.set(key, {
831
+ nextAttemptAtMs: nowMs + intervalMs,
832
+ intervalMs: Math.min(
833
+ intervalMs * 2,
834
+ COMPILE_ERROR_POLL_MAX_INTERVAL_MS
835
+ )
836
+ });
837
+ }
838
+ };
537
839
  const defaultExportIdentityByFile = /* @__PURE__ */ new Map();
538
840
  const canonicalIdentityKey = (idOrFile) => {
539
- const file = cleanModuleId(idOrFile).replace(/^\/@fs\//, "/");
841
+ const file = fsPathFromModuleId(idOrFile);
540
842
  try {
541
843
  return realpathSync2.native(file);
542
844
  } catch {
@@ -823,6 +1125,12 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
823
1125
  },
824
1126
  // Expose error server for testing
825
1127
  _tempoErrorServer: errorServer,
1128
+ // Test seam pinning the exact evidence the missed-change sweep reads.
1129
+ _tempoHotUpdateState: {
1130
+ lastHotUpdateMtimeMs(file) {
1131
+ return hotUpdateMtimesMs.get(normalizedFileKey(file));
1132
+ }
1133
+ },
826
1134
  _tempoUnresolvedImportState: {
827
1135
  get size() {
828
1136
  return unresolvedImports.size;
@@ -874,9 +1182,14 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
874
1182
  server.watcher?.once?.("close", closeUnresolvedImportWatchers);
875
1183
  server.httpServer?.once("close", closeUnresolvedImportWatchers);
876
1184
  server.middlewares.use((req, res, next) => {
877
- handleTempoMiddleware(errorServer, req, res, next);
1185
+ handleTempoMiddleware(errorServer, server, req, res, next);
878
1186
  });
879
- installMissedChangeSweep(server);
1187
+ installMissedChangeSweep(
1188
+ server,
1189
+ () => errorServer.errorFiles,
1190
+ (file) => hotUpdateMtimesMs.get(normalizedFileKey(file)),
1191
+ () => pollCompileErrorRecovery(server)
1192
+ );
880
1193
  const interceptHmrSend = (target) => {
881
1194
  const orig = target.send.bind(target);
882
1195
  target.send = ((...args) => {
@@ -896,31 +1209,58 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
896
1209
  });
897
1210
  } else if (typed.type === "update" && !processedUpdatePayloads.has(payload)) {
898
1211
  processedUpdatePayloads.add(payload);
899
- const updates = typed.updates;
900
- const paths = updates?.map((u) => u.path).filter((p) => typeof p === "string") ?? [];
1212
+ const updatePayload = typed;
1213
+ const updates = updatePayload.updates;
1214
+ const acceptedUpdates = updates ? hmrGenerationFence.filter(updates) : void 0;
1215
+ if (updates && acceptedUpdates && acceptedUpdates.length !== updates.length) {
1216
+ updatePayload.updates = acceptedUpdates;
1217
+ }
1218
+ const paths = acceptedUpdates?.map((u) => u.path).filter((p) => typeof p === "string") ?? [];
901
1219
  errorServer.clearErrorForModules(paths);
1220
+ if (updates && updates.length > 0 && acceptedUpdates?.length === 0) {
1221
+ return;
1222
+ }
902
1223
  }
903
1224
  }
904
1225
  return orig(...args);
905
1226
  });
906
1227
  };
907
1228
  interceptHmrSend(server.ws);
908
- const clientHot = server.environments?.client?.hot;
909
- if (clientHot && clientHot !== server.ws) {
910
- interceptHmrSend(clientHot);
911
- }
1229
+ return () => {
1230
+ const clientHot = server.environments?.client?.hot;
1231
+ if (clientHot && clientHot !== server.ws) {
1232
+ interceptHmrSend(clientHot);
1233
+ }
1234
+ };
912
1235
  },
913
1236
  closeBundle() {
914
1237
  devServer = void 0;
1238
+ rapidHotUpdateReplay.clear();
1239
+ hmrGenerationFence.clear();
1240
+ hotUpdateMtimesMs.clear();
1241
+ compileErrorPollSchedule.clear();
915
1242
  closeUnresolvedImportWatchers();
916
1243
  },
917
1244
  hotUpdate: {
918
1245
  order: "post",
919
- handler(context) {
920
- if (this.environment.name !== "client") return;
1246
+ async handler(context) {
1247
+ if (!enabled || this.environment.config.consumer !== "client") return;
1248
+ recordHotUpdateCoverage(context.file);
1249
+ if (context.type === "update" && context.modules.length > 0) {
1250
+ rapidHotUpdateReplay.observe(context.file, () => {
1251
+ context.server.config.logger.info(
1252
+ `[tempo] replaying settled rapid watcher change: ${context.file}`,
1253
+ { timestamp: true }
1254
+ );
1255
+ context.server.watcher.emit("change", context.file);
1256
+ });
1257
+ }
921
1258
  if (context.type !== "create") {
922
1259
  forgetUnresolvedImportsFrom(context.file);
923
1260
  }
1261
+ if (context.type === "update" && hasActiveCompileError(context.file) && await recoverActiveCompileError(context.server, context.file)) {
1262
+ return [];
1263
+ }
924
1264
  if (context.type === "delete") {
925
1265
  defaultExportIdentityByFile.delete(
926
1266
  canonicalIdentityKey(context.file)
@@ -935,8 +1275,22 @@ if (import.meta.hot) import.meta.hot.dispose(() => {
935
1275
  // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.
936
1276
  handleHotUpdate: {
937
1277
  order: "post",
938
- handler(context) {
1278
+ async handler(context) {
1279
+ if (!enabled) return;
1280
+ recordHotUpdateCoverage(context.file);
1281
+ if (context.modules.length > 0) {
1282
+ rapidHotUpdateReplay.observe(context.file, () => {
1283
+ context.server.config.logger.info(
1284
+ `[tempo] replaying settled rapid watcher change: ${context.file}`,
1285
+ { timestamp: true }
1286
+ );
1287
+ context.server.watcher.emit("change", context.file);
1288
+ });
1289
+ }
939
1290
  forgetUnresolvedImportsFrom(context.file);
1291
+ if (hasActiveCompileError(context.file) && await recoverActiveCompileError(context.server, context.file)) {
1292
+ return [];
1293
+ }
940
1294
  if (repairDefaultExportIdentityRewrite(context.file)) {
941
1295
  return [];
942
1296
  }