tempo-sdk 0.0.2 → 0.0.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 CHANGED
@@ -3,7 +3,7 @@ import { realpathSync as realpathSync3, statSync as statSync2 } from "fs";
3
3
  import { relative } from "path";
4
4
 
5
5
  // ../../modules/annotation/annotate-file.ts
6
- import { parseSync } from "oxc-parser";
6
+ import { parseSync as parseSync2 } from "oxc-parser";
7
7
 
8
8
  // ../../modules/file-parser/utils.ts
9
9
  function getTagName(name) {
@@ -42,6 +42,28 @@ function walk(node, callbacks) {
42
42
  }
43
43
  }
44
44
 
45
+ // ../../modules/file-parser/scope-analyzer/types.ts
46
+ var ScopeFlags = {
47
+ Top: 1 << 0,
48
+ Function: 1 << 1,
49
+ Block: 1 << 2,
50
+ Catch: 1 << 3,
51
+ Class: 1 << 4,
52
+ For: 1 << 5,
53
+ Switch: 1 << 6,
54
+ Module: 1 << 7,
55
+ StrictMode: 1 << 8,
56
+ ClassStaticBlock: 1 << 9,
57
+ TsModuleBlock: 1 << 10,
58
+ TsConditional: 1 << 11,
59
+ Type: 1 << 12,
60
+ Enum: 1 << 13
61
+ };
62
+
63
+ // ../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts
64
+ import { parseSync } from "oxc-parser";
65
+ import visitorKeysDefault from "oxc-parser/src-js/generated/visit/keys.js";
66
+
45
67
  // ../../modules/annotation/annotate-file.ts
46
68
  function formatPropValue(value) {
47
69
  if (value === void 0) return null;
@@ -57,7 +79,7 @@ function formatProps(props) {
57
79
  }
58
80
  var FRAGMENT_TAG_NAMES = /* @__PURE__ */ new Set(["Fragment", "React.Fragment"]);
59
81
  function annotateFile(source, filename, computeAnnotatedProps) {
60
- const parseResult = parseSync(filename, source);
82
+ const parseResult = parseSync2(filename, source);
61
83
  const insertions = [];
62
84
  walk(parseResult.program, {
63
85
  JSXElement(node) {
@@ -86,11 +108,7 @@ function annotateFile(source, filename, computeAnnotatedProps) {
86
108
  lastPos = position;
87
109
  }
88
110
  chunks.push(source.slice(lastPos));
89
- return {
90
- annotatedSource: chunks.join(""),
91
- elementsAnnotated: insertions.length,
92
- parseResult
93
- };
111
+ return { annotatedSource: chunks.join(""), elementsAnnotated: insertions.length, parseResult };
94
112
  }
95
113
 
96
114
  // index.ts
@@ -445,17 +463,40 @@ function createTypeAnalyzer(root) {
445
463
  function resolveCSSPropertiesType(checker, sourceFile) {
446
464
  if (cssPropertiesType !== void 0) return cssPropertiesType;
447
465
  try {
448
- const jsxNs = checker.resolveName(
466
+ let jsxNs = checker.resolveName(
449
467
  "JSX",
450
468
  sourceFile,
451
469
  ts2.SymbolFlags.Namespace,
452
470
  false
453
471
  );
472
+ if (!jsxNs) {
473
+ const program = workspaceService.getProgram();
474
+ const compilerOptions = program?.getCompilerOptions();
475
+ const jsxImportSource = compilerOptions?.jsxImportSource ?? "react";
476
+ const resolved = ts2.resolveModuleName(
477
+ `${jsxImportSource}/jsx-runtime`,
478
+ sourceFile.fileName,
479
+ compilerOptions,
480
+ ts2.sys
481
+ );
482
+ if (resolved.resolvedModule) {
483
+ const runtimeFile = program?.getSourceFile(
484
+ resolved.resolvedModule.resolvedFileName
485
+ );
486
+ if (runtimeFile) {
487
+ const runtimeSymbol = checker.getSymbolAtLocation(runtimeFile);
488
+ if (runtimeSymbol) {
489
+ const exports = checker.getExportsOfModule(runtimeSymbol);
490
+ jsxNs = exports.find((s) => s.name === "JSX");
491
+ }
492
+ }
493
+ }
494
+ }
454
495
  if (!jsxNs) {
455
496
  cssPropertiesType = null;
456
497
  return null;
457
498
  }
458
- const intrinsicSym = checker.getExportsOfModule(jsxNs).find((s) => s.name === "IntrinsicElements");
499
+ const intrinsicSym = checker.getExportsOfModule(jsxNs).find((s) => s.name === "IntrinsicElements") ?? checker.getDeclaredTypeOfSymbol(jsxNs).getProperty("IntrinsicElements");
459
500
  if (!intrinsicSym) {
460
501
  cssPropertiesType = null;
461
502
  return null;
@@ -484,6 +525,72 @@ function createTypeAnalyzer(root) {
484
525
  }
485
526
  return cssPropertiesType;
486
527
  }
528
+ let reactNodeType;
529
+ function resolveReactNodeType(checker, sourceFile) {
530
+ if (reactNodeType !== void 0) return reactNodeType;
531
+ try {
532
+ let jsxNs = checker.resolveName(
533
+ "JSX",
534
+ sourceFile,
535
+ ts2.SymbolFlags.Namespace,
536
+ false
537
+ );
538
+ if (!jsxNs) {
539
+ const program = workspaceService.getProgram();
540
+ const compilerOptions = program?.getCompilerOptions();
541
+ const jsxImportSource = compilerOptions?.jsxImportSource ?? "react";
542
+ const resolved = ts2.resolveModuleName(
543
+ `${jsxImportSource}/jsx-runtime`,
544
+ sourceFile.fileName,
545
+ compilerOptions,
546
+ ts2.sys
547
+ );
548
+ if (resolved.resolvedModule) {
549
+ const runtimeFile = program?.getSourceFile(
550
+ resolved.resolvedModule.resolvedFileName
551
+ );
552
+ if (runtimeFile) {
553
+ const runtimeSymbol = checker.getSymbolAtLocation(runtimeFile);
554
+ if (runtimeSymbol) {
555
+ const exports = checker.getExportsOfModule(runtimeSymbol);
556
+ jsxNs = exports.find((s) => s.name === "JSX");
557
+ }
558
+ }
559
+ }
560
+ }
561
+ if (!jsxNs) {
562
+ reactNodeType = null;
563
+ return null;
564
+ }
565
+ const intrinsicSym = checker.getExportsOfModule(jsxNs).find((s) => s.name === "IntrinsicElements") ?? checker.getDeclaredTypeOfSymbol(jsxNs).getProperty("IntrinsicElements");
566
+ if (!intrinsicSym) {
567
+ reactNodeType = null;
568
+ return null;
569
+ }
570
+ const divSym = checker.getDeclaredTypeOfSymbol(intrinsicSym).getProperty("div");
571
+ if (!divSym) {
572
+ reactNodeType = null;
573
+ return null;
574
+ }
575
+ const childrenSym = checker.getTypeOfSymbol(divSym).getProperty("children");
576
+ if (!childrenSym) {
577
+ reactNodeType = null;
578
+ return null;
579
+ }
580
+ const childrenType = checker.getTypeOfSymbol(childrenSym);
581
+ if (childrenType.isUnion()) {
582
+ const nonUndefined = childrenType.types.find(
583
+ (t) => !(t.flags & ts2.TypeFlags.Undefined)
584
+ );
585
+ reactNodeType = nonUndefined ?? null;
586
+ } else {
587
+ reactNodeType = childrenType;
588
+ }
589
+ } catch {
590
+ reactNodeType = null;
591
+ }
592
+ return reactNodeType;
593
+ }
487
594
  return {
488
595
  analyzeFileTypes(filePath, source) {
489
596
  const canonicalFilePath = canonicalPath2(filePath);
@@ -507,6 +614,7 @@ function createTypeAnalyzer(root) {
507
614
  const attrsType = checker.getContextualType(node.attributes);
508
615
  let supportsStyle = false;
509
616
  let supportsClassName = false;
617
+ let supportsChildren = false;
510
618
  if (attrsType) {
511
619
  const classNameProp = attrsType.getProperty("className");
512
620
  if (classNameProp) {
@@ -518,14 +626,32 @@ function createTypeAnalyzer(root) {
518
626
  }
519
627
  const styleProp = attrsType.getProperty("style");
520
628
  if (styleProp && cssProps) {
521
- const propType = checker.getTypeOfSymbol(styleProp);
522
- supportsStyle = checker.isTypeAssignableTo(
523
- cssProps,
629
+ let propType = checker.getTypeOfSymbol(styleProp);
630
+ if (propType.isUnion()) {
631
+ const nonUndefined = propType.types.find(
632
+ (t) => !(t.flags & ts2.TypeFlags.Undefined)
633
+ );
634
+ if (nonUndefined) propType = nonUndefined;
635
+ }
636
+ supportsStyle = checker.isTypeAssignableTo(cssProps, propType);
637
+ }
638
+ const reactNode = resolveReactNodeType(checker, sourceFile);
639
+ const childrenProp = attrsType.getProperty("children");
640
+ if (childrenProp && reactNode) {
641
+ let propType = checker.getTypeOfSymbol(childrenProp);
642
+ if (propType.isUnion()) {
643
+ const nonUndefined = propType.types.find(
644
+ (t) => !(t.flags & ts2.TypeFlags.Undefined)
645
+ );
646
+ if (nonUndefined) propType = nonUndefined;
647
+ }
648
+ supportsChildren = checker.isTypeAssignableTo(
649
+ reactNode,
524
650
  propType
525
651
  );
526
652
  }
527
653
  }
528
- result.set(position, { supportsStyle, supportsClassName });
654
+ result.set(position, { supportsStyle, supportsClassName, supportsChildren });
529
655
  }
530
656
  ts2.forEachChild(node, visit);
531
657
  }
@@ -555,6 +681,22 @@ function hasRootMetaTag(html) {
555
681
  function isIntrinsicElement(tagName) {
556
682
  return tagName.length > 0 && tagName[0] === tagName[0].toLowerCase();
557
683
  }
684
+ var HTML_VOID_ELEMENTS = /* @__PURE__ */ new Set([
685
+ "area",
686
+ "base",
687
+ "br",
688
+ "col",
689
+ "embed",
690
+ "hr",
691
+ "img",
692
+ "input",
693
+ "link",
694
+ "meta",
695
+ "param",
696
+ "source",
697
+ "track",
698
+ "wbr"
699
+ ]);
558
700
  function defaultComputeAnnotatedProps(info, filepath, modifiedtsMs) {
559
701
  return {
560
702
  "data-tempo-filepath": filepath,
@@ -562,7 +704,109 @@ function defaultComputeAnnotatedProps(info, filepath, modifiedtsMs) {
562
704
  "data-tempo-modifiedts": modifiedtsMs
563
705
  };
564
706
  }
565
- function tempoAnnotate(options = {}) {
707
+ function createErrorServer() {
708
+ const errorsByFile = /* @__PURE__ */ new Map();
709
+ function getMostRecentError() {
710
+ if (errorsByFile.size === 0) return null;
711
+ let latest = null;
712
+ for (const err of errorsByFile.values()) latest = err;
713
+ return latest;
714
+ }
715
+ function broadcastCurrentState() {
716
+ const data = JSON.stringify(server.currentError);
717
+ for (const client of server.clients) {
718
+ client.write(`data: ${data}
719
+
720
+ `);
721
+ }
722
+ }
723
+ const server = {
724
+ get currentError() {
725
+ return getMostRecentError();
726
+ },
727
+ clients: /* @__PURE__ */ new Set(),
728
+ setError(error) {
729
+ const key = error.file ?? error.loc?.file ?? "unknown";
730
+ errorsByFile.delete(key);
731
+ errorsByFile.set(key, error);
732
+ broadcastCurrentState();
733
+ },
734
+ clearErrorForModules(updatedPaths) {
735
+ if (errorsByFile.size === 0) return;
736
+ let changed = false;
737
+ for (const errorKey of [...errorsByFile.keys()]) {
738
+ if (errorKey === "unknown" || updatedPaths.some(
739
+ (p) => errorKey.endsWith(p) || p.endsWith(errorKey)
740
+ )) {
741
+ errorsByFile.delete(errorKey);
742
+ changed = true;
743
+ }
744
+ }
745
+ if (changed) broadcastCurrentState();
746
+ },
747
+ clearAll() {
748
+ errorsByFile.clear();
749
+ broadcastCurrentState();
750
+ }
751
+ };
752
+ return server;
753
+ }
754
+ function readBody(req) {
755
+ return new Promise((resolve, reject) => {
756
+ const chunks = [];
757
+ req.on("data", (chunk) => chunks.push(chunk));
758
+ req.on("end", () => resolve(Buffer.concat(chunks).toString()));
759
+ req.on("error", reject);
760
+ });
761
+ }
762
+ function handleErrorMiddleware(errorServer, req, res, next) {
763
+ const url = req.url;
764
+ if (!url?.startsWith("/__tempo/")) return next();
765
+ if (url === "/__tempo/report-error" && req.method === "POST") {
766
+ readBody(req).then((body) => {
767
+ try {
768
+ errorServer.setError(JSON.parse(body));
769
+ } catch {
770
+ }
771
+ res.statusCode = 200;
772
+ res.end("ok");
773
+ });
774
+ return;
775
+ }
776
+ if (url === "/__tempo/report-clear" && req.method === "POST") {
777
+ errorServer.clearAll();
778
+ res.statusCode = 200;
779
+ res.end("ok");
780
+ return;
781
+ }
782
+ if (url === "/__tempo/errors" && req.method === "OPTIONS") {
783
+ res.writeHead(204, {
784
+ "Access-Control-Allow-Origin": "*",
785
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
786
+ "Access-Control-Allow-Headers": "*"
787
+ });
788
+ res.end();
789
+ return;
790
+ }
791
+ if (url === "/__tempo/errors" && req.method === "GET") {
792
+ res.writeHead(200, {
793
+ "Content-Type": "text/event-stream",
794
+ "Cache-Control": "no-cache",
795
+ Connection: "keep-alive",
796
+ "Access-Control-Allow-Origin": "*"
797
+ });
798
+ res.write(`data: ${JSON.stringify(errorServer.currentError)}
799
+
800
+ `);
801
+ errorServer.clients.add(res);
802
+ req.on("close", () => {
803
+ errorServer.clients.delete(res);
804
+ });
805
+ return;
806
+ }
807
+ next();
808
+ }
809
+ function tempoVitePlugin(options = {}) {
566
810
  const enabled = !!process.env.TEMPO;
567
811
  const include = options.include === void 0 ? DEFAULT_INCLUDE : options.include;
568
812
  const exclude = options.exclude === void 0 ? DEFAULT_EXCLUDE : options.exclude;
@@ -571,9 +815,12 @@ function tempoAnnotate(options = {}) {
571
815
  let canonicalRoot = process.cwd();
572
816
  let command = "serve";
573
817
  let typeAnalyzer = null;
818
+ const errorServer = createErrorServer();
574
819
  return {
575
820
  name: "tempo-annotate",
576
821
  enforce: "pre",
822
+ // Expose error server for testing
823
+ _tempoErrorServer: errorServer,
577
824
  configResolved(resolvedConfig) {
578
825
  if (!enabled) return;
579
826
  command = resolvedConfig.command;
@@ -582,6 +829,43 @@ function tempoAnnotate(options = {}) {
582
829
  typeAnalyzer = createTypeAnalyzer(canonicalRoot);
583
830
  }
584
831
  },
832
+ configureServer(server) {
833
+ if (!enabled) return;
834
+ server.middlewares.use((req, res, next) => {
835
+ handleErrorMiddleware(errorServer, req, res, next);
836
+ });
837
+ const interceptHmrSend = (target) => {
838
+ const orig = target.send.bind(target);
839
+ target.send = ((...args) => {
840
+ const payload = args[0];
841
+ if (typeof payload === "object" && payload !== null && "type" in payload) {
842
+ const typed = payload;
843
+ if (typed.type === "error") {
844
+ const err = typed.err;
845
+ errorServer.setError({
846
+ type: "compile",
847
+ message: err?.message ?? "Unknown error",
848
+ stack: err?.stack,
849
+ file: err?.id ?? err?.loc?.file,
850
+ frame: err?.frame,
851
+ plugin: err?.plugin,
852
+ loc: err?.loc
853
+ });
854
+ } else if (typed.type === "update") {
855
+ const updates = typed.updates;
856
+ const paths = updates?.map((u) => u.path).filter((p) => typeof p === "string") ?? [];
857
+ errorServer.clearErrorForModules(paths);
858
+ }
859
+ }
860
+ return orig(...args);
861
+ });
862
+ };
863
+ interceptHmrSend(server.ws);
864
+ const clientHot = server.environments?.client?.hot;
865
+ if (clientHot && clientHot !== server.ws) {
866
+ interceptHmrSend(clientHot);
867
+ }
868
+ },
585
869
  transformIndexHtml(html) {
586
870
  if (!enabled || command !== "serve") {
587
871
  return;
@@ -618,13 +902,17 @@ function tempoAnnotate(options = {}) {
618
902
  const result = annotateFile(source, cleanId, (info) => {
619
903
  const userProps = computeAnnotatedProps(info, filepath, modifiedtsMs);
620
904
  if (isIntrinsicElement(info.tagName)) {
621
- return userProps;
905
+ return {
906
+ ...userProps,
907
+ "data-tempo-supports-children": !HTML_VOID_ELEMENTS.has(info.tagName)
908
+ };
622
909
  }
623
910
  const support = typeInfo?.get(info.element.openingElement.start);
624
911
  return {
625
912
  ...userProps,
626
913
  "data-tempo-supports-style": support?.supportsStyle ?? false,
627
- "data-tempo-supports-classname": support?.supportsClassName ?? false
914
+ "data-tempo-supports-classname": support?.supportsClassName ?? false,
915
+ "data-tempo-supports-children": support?.supportsChildren ?? false
628
916
  };
629
917
  });
630
918
  if (result.elementsAnnotated === 0) {
@@ -640,8 +928,10 @@ function tempoAnnotate(options = {}) {
640
928
  }
641
929
  };
642
930
  }
931
+ var tempoAnnotate = tempoVitePlugin;
643
932
  export {
644
933
  createTypeAnalyzer,
645
- tempoAnnotate
934
+ tempoAnnotate,
935
+ tempoVitePlugin
646
936
  };
647
937
  //# sourceMappingURL=index.js.map