tempo-sdk 0.0.3 → 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/README.md ADDED
@@ -0,0 +1,272 @@
1
+ # tempo-sdk
2
+
3
+ Tempo's JSX-annotation plugins for Vite and Next.js. At build time, every JSX
4
+ element in your codebase gets `data-tempo-*` attributes that map the rendered
5
+ DOM back to the exact source-file location that produced it. Tempo's design
6
+ surface uses these attributes to navigate from a clicked element to its source.
7
+
8
+ This package ships two plugins from one workspace:
9
+
10
+ - **`tempo-sdk`** — Vite plugin (`tempoVitePlugin`)
11
+ - **`tempo-sdk/nextjs`** — Next.js plugin (`tempoNextjsPlugin`)
12
+
13
+ Both produce byte-identical `data-tempo-*` output, so downstream consumers
14
+ (`source-editor.ts`, `frame-preload.ts`) work the same regardless of which
15
+ framework the user's project is on.
16
+
17
+ ---
18
+
19
+ ## Next.js usage
20
+
21
+ ### 1. Install
22
+
23
+ In a workspace package:
24
+
25
+ ```jsonc
26
+ {
27
+ "dependencies": { "tempo-sdk": "workspace:*" }
28
+ }
29
+ ```
30
+
31
+ In an external project: `pnpm add tempo-sdk` (or your package manager's equivalent).
32
+
33
+ ### 2. Wrap `next.config`
34
+
35
+ CommonJS (`next.config.js`):
36
+
37
+ ```js
38
+ const tempoNextjsPlugin = require("tempo-sdk/nextjs");
39
+
40
+ module.exports = tempoNextjsPlugin()({
41
+ reactStrictMode: true,
42
+ // ...rest of your existing config
43
+ });
44
+ ```
45
+
46
+ ESM (`next.config.mjs` / `next.config.ts`):
47
+
48
+ ```ts
49
+ import tempoNextjsPlugin from "tempo-sdk/nextjs";
50
+
51
+ export default tempoNextjsPlugin()({
52
+ reactStrictMode: true,
53
+ });
54
+ ```
55
+
56
+ ### 3. Set the `TEMPO` env var when launching dev
57
+
58
+ ```bash
59
+ TEMPO=true next dev # Turbopack (Next.js 16+ default)
60
+ TEMPO=true next dev --webpack # Webpack mode
61
+ ```
62
+
63
+ Without `TEMPO` set, the plugin is a complete no-op. You can leave
64
+ `tempoNextjsPlugin()` in `next.config.js` permanently — there is zero overhead
65
+ in normal dev. Tempo's start script sets `TEMPO=true` automatically when
66
+ launching the project under Tempo.
67
+
68
+ ### 4. App Router — that's it
69
+
70
+ The loader auto-injects `<meta name="tempo-project-root">` into the first JSX
71
+ `<head>` it sees (typically `app/layout.tsx`). Every JSX element in your project
72
+ gets `data-tempo-filepath`, `data-tempo-position`, `data-tempo-modifiedts`, and
73
+ `data-tempo-supports-*` attributes baked into the SWC-compiled output.
74
+
75
+ Example rendered HTML:
76
+
77
+ ```html
78
+ <button
79
+ data-tempo-filepath="components/Button.tsx"
80
+ data-tempo-position="142"
81
+ data-tempo-modifiedts="1708900000000"
82
+ data-tempo-supports-children="true"
83
+ >
84
+ Click me
85
+ </button>
86
+
87
+ <head>
88
+ <meta name="tempo-project-root" content="/abs/path/to/project" />
89
+ </head>
90
+ ```
91
+
92
+ ### 5. Pages Router — one extra line in `_document.tsx`
93
+
94
+ `<Head>` from `next/document` is a **custom** React component (capital H), not
95
+ intrinsic JSX `<head>` (lowercase), so auto-inject doesn't fire there. Add the
96
+ project-root meta manually:
97
+
98
+ ```tsx
99
+ // pages/_document.tsx
100
+ import { Html, Head, Main, NextScript } from "next/document";
101
+ import { tempoProjectRoot } from "tempo-sdk/nextjs";
102
+
103
+ export default function Document() {
104
+ return (
105
+ <Html>
106
+ <Head>
107
+ <meta name="tempo-project-root" content={tempoProjectRoot()} />
108
+ </Head>
109
+ <body>
110
+ <Main />
111
+ <NextScript />
112
+ </body>
113
+ </Html>
114
+ );
115
+ }
116
+ ```
117
+
118
+ `tempoProjectRoot()` returns the same canonical root the loader uses for
119
+ `data-tempo-filepath`, so paths reconstruct correctly.
120
+
121
+ ### Options
122
+
123
+ All optional:
124
+
125
+ ```js
126
+ tempoNextjsPlugin({
127
+ autoInjectRootMeta: false, // disable head meta auto-inject
128
+ productionBuild: true, // run in `next build` too (rare)
129
+ computeAnnotatedPropsModule: "./tempo-strategy.js", // custom prop-computation
130
+ })(nextConfig);
131
+ ```
132
+
133
+ `computeAnnotatedPropsModule` is a path (not a function) because Turbopack
134
+ requires loader options to be JSON-serializable. The module's default export
135
+ must be a function `(info, filepath, modifiedtsMs) => Record<string, PropValue>`.
136
+
137
+ ### Composing with other wrappers (`@next/mdx`, etc.)
138
+
139
+ `tempoNextjsPlugin` follows the `@next/mdx` higher-order-config pattern, so it
140
+ composes naturally:
141
+
142
+ ```js
143
+ const tempoNextjsPlugin = require("tempo-sdk/nextjs");
144
+ const withMDX = require("@next/mdx")();
145
+
146
+ module.exports = tempoNextjsPlugin()(
147
+ withMDX({ reactStrictMode: true })
148
+ );
149
+ ```
150
+
151
+ `tempoNextjsPlugin` should be the **outermost** wrapper so its webpack/turbopack
152
+ chaining sees the inner wrappers' contributions.
153
+
154
+ ### Supported Next.js versions
155
+
156
+ | Next.js | Webpack | Turbopack | Notes |
157
+ |---|---|---|---|
158
+ | 16.x | `--webpack` flag | default | Validated end-to-end |
159
+ | 15.3 – 15.x | default | `--turbo` flag | Wrapper writes to `turbopack.*` |
160
+ | 13.0 – 15.2 | default | `--turbo` flag | Wrapper writes to `experimental.turbo.*` |
161
+ | 12.x | default | n/a | Webpack only; turbopack field omitted |
162
+ | < 12 | n/a | n/a | Out of scope |
163
+
164
+ The wrapper detects the version via `next/package.json` and writes to the
165
+ correct field automatically.
166
+
167
+ ---
168
+
169
+ ## Vite usage
170
+
171
+ ```ts
172
+ // vite.config.ts
173
+ import { defineConfig } from "vite";
174
+ import react from "@vitejs/plugin-react";
175
+ import { tempoVitePlugin } from "tempo-sdk";
176
+
177
+ export default defineConfig({
178
+ plugins: [tempoVitePlugin(), react()],
179
+ });
180
+ ```
181
+
182
+ Same `TEMPO` env-var gating, same `data-tempo-*` output as the Next.js plugin.
183
+ The Vite plugin additionally exposes an `/__tempo/errors` SSE endpoint for
184
+ streaming compile errors to the design surface — see `SPEC.md` for the full
185
+ design.
186
+
187
+ ---
188
+
189
+ ## How it works
190
+
191
+ The Next.js plugin is a webpack-compatible loader (`nextjs-loader.cjs`) plus a
192
+ higher-order config wrapper (`tempoNextjsPlugin`) that registers the loader for
193
+ both Webpack and Turbopack from a single user-facing entrypoint.
194
+
195
+ The flow per source file:
196
+
197
+ 1. Resource gating — `.tsx`/`.jsx` only, exclude `node_modules`, require
198
+ `process.env.TEMPO`.
199
+ 2. Read mtime via `fs.statSync`.
200
+ 3. Compute project-relative filepath via `path.relative(rootContext, …)`.
201
+ 4. Call `annotateFile` from `@modules/annotation` with a callback that returns
202
+ the `data-tempo-*` props for each JSX element. The walker visits every
203
+ `JSXElement`, fragments are skipped, and props are inserted as JSX
204
+ attribute strings at the end of each opening tag.
205
+ 5. If the file contains an intrinsic JSX `<head>`, splice
206
+ `<meta name="tempo-project-root" content="…" />` into the post-annotation
207
+ source. The injected meta does not itself carry `data-tempo-*` attrs (it has
208
+ no source location), which keeps every other element's `data-tempo-position`
209
+ pointing at the byte offset of `<` in the on-disk source file.
210
+ 6. Return the annotated source. Errors at any step cause the loader to return
211
+ the original source unchanged — `correct or untouched, always`.
212
+
213
+ The `tempoNextjsPlugin` wrapper:
214
+
215
+ - Adds an `enforce: "pre"` rule under `config.module.rules` for Webpack
216
+ (`/.(tsx|jsx)$/`).
217
+ - Adds a `*.{tsx,jsx}` rule under `nextConfig.turbopack.rules` for Turbopack
218
+ with `condition: { all: [{ not: "foreign" }, "development"] }` (excludes
219
+ node_modules / Next internals AND production builds).
220
+ - Chains an existing user-supplied `webpack(config, options)` function and
221
+ merges with any existing `turbopack.rules` so other plugins are preserved.
222
+ - No-ops entirely when `process.env.TEMPO` is not set.
223
+
224
+ See `SPEC_NEXTJS.md` for the complete design specification.
225
+
226
+ ---
227
+
228
+ ## Demo
229
+
230
+ ```bash
231
+ pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev # Turbopack on :3477
232
+ pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev:webpack # Webpack on :3478
233
+ ```
234
+
235
+ Then:
236
+
237
+ ```bash
238
+ curl -s localhost:3477/ | grep -oE 'data-tempo-filepath="[^"]+"' | sort -u
239
+ ```
240
+
241
+ Should print one line per source file rendered on the home page.
242
+
243
+ ---
244
+
245
+ ## Tests
246
+
247
+ ```bash
248
+ pnpm test # all 308 tests across both plugins
249
+ pnpm test:nextjs # 175 Next.js tests (~24s)
250
+ pnpm test:nextjs:unit # fast unit tests, no servers
251
+ pnpm test:nextjs:integration # live `next dev` against demo (Turbopack + Webpack)
252
+ pnpm test:nextjs:production # `next build` correctness (no annotations in prod)
253
+ ```
254
+
255
+ Test layers:
256
+
257
+ | File | Tests | Coverage |
258
+ |---|---|---|
259
+ | `nextjs-loader.test.ts` | 41 | Loader function — file filtering, default strategy, auto-inject, error handling |
260
+ | `nextjs-wrapper.test.ts` | 26 | `tempoNextjsPlugin` — webpack chaining, turbopack merging, version detection, options |
261
+ | `nextjs-fixtures.test.ts` | 40 | Project shapes — App/Pages Router, server/client components, all routing types |
262
+ | `nextjs-published.test.ts` | 14 | Built `dist/*.cjs` and `dist/*.js` — CJS callable, ESM imports, parity |
263
+ | `nextjs-production.test.ts` | 6 | `next build` produces zero `data-tempo-*` attributes |
264
+ | `nextjs-e2e-correctness.test.ts` | — | Live `next dev` against demo (both bundlers); every recorded `data-tempo-position` actually points at `<` in the on-disk source file |
265
+
266
+ ---
267
+
268
+ ## Related docs
269
+
270
+ - `SPEC.md` — Vite plugin specification
271
+ - `SPEC_NEXTJS.md` — Next.js plugin specification
272
+ - `SPEC_TSC.md` — TypeScript type-analyzer (used by both plugins for `data-tempo-supports-*`)
package/dist/index.d.ts CHANGED
@@ -15,6 +15,7 @@ type PropValue = string | number | boolean | null | undefined | ((...args: unkno
15
15
  interface ElementTypeSupport {
16
16
  supportsStyle: boolean;
17
17
  supportsClassName: boolean;
18
+ supportsChildren: boolean;
18
19
  }
19
20
  /** Position → type support for custom components only */
20
21
  type FileTypeInfo = Map<number, ElementTypeSupport>;
@@ -52,6 +53,11 @@ interface TempoRouteStoryboard {
52
53
  name?: string;
53
54
  layout: StoryboardLayout;
54
55
  }
56
+ interface TempoHtmlStoryboard {
57
+ filepath: string;
58
+ name?: string;
59
+ layout: StoryboardLayout;
60
+ }
55
61
 
56
62
  /** Error payload captured from Vite's HMR error events or console interception. */
57
63
  type TempoViteError = {
@@ -88,4 +94,4 @@ declare function tempoVitePlugin(options?: TempoAnnotateOptions): Plugin;
88
94
  /** @deprecated Use `tempoVitePlugin` instead. */
89
95
  declare const tempoAnnotate: typeof tempoVitePlugin;
90
96
 
91
- export { type ComputeAnnotatedProps, type ElementInfo, type ElementTypeSupport, type FileTypeInfo, type PropValue, type StoryboardLayout, type TempoAnnotateOptions, type TempoErrorServer, type TempoPage, type TempoRouteStoryboard, type TempoStoryboard, type TempoViteError, type TypeAnalyzer, createTypeAnalyzer, tempoAnnotate, tempoVitePlugin };
97
+ export { type ComputeAnnotatedProps, type ElementInfo, type ElementTypeSupport, type FileTypeInfo, type PropValue, type StoryboardLayout, type TempoAnnotateOptions, type TempoErrorServer, type TempoHtmlStoryboard, type TempoPage, type TempoRouteStoryboard, type TempoStoryboard, type TempoViteError, type TypeAnalyzer, createTypeAnalyzer, tempoAnnotate, tempoVitePlugin };
package/dist/index.js CHANGED
@@ -42,8 +42,27 @@ 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
+
45
63
  // ../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts
46
- import { parseSync, visitorKeys } from "oxc-parser";
64
+ import { parseSync } from "oxc-parser";
65
+ import visitorKeysDefault from "oxc-parser/src-js/generated/visit/keys.js";
47
66
 
48
67
  // ../../modules/annotation/annotate-file.ts
49
68
  function formatPropValue(value) {
@@ -506,6 +525,72 @@ function createTypeAnalyzer(root) {
506
525
  }
507
526
  return cssPropertiesType;
508
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
+ }
509
594
  return {
510
595
  analyzeFileTypes(filePath, source) {
511
596
  const canonicalFilePath = canonicalPath2(filePath);
@@ -529,6 +614,7 @@ function createTypeAnalyzer(root) {
529
614
  const attrsType = checker.getContextualType(node.attributes);
530
615
  let supportsStyle = false;
531
616
  let supportsClassName = false;
617
+ let supportsChildren = false;
532
618
  if (attrsType) {
533
619
  const classNameProp = attrsType.getProperty("className");
534
620
  if (classNameProp) {
@@ -540,14 +626,32 @@ function createTypeAnalyzer(root) {
540
626
  }
541
627
  const styleProp = attrsType.getProperty("style");
542
628
  if (styleProp && cssProps) {
543
- const propType = checker.getTypeOfSymbol(styleProp);
544
- supportsStyle = checker.isTypeAssignableTo(
545
- 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,
546
650
  propType
547
651
  );
548
652
  }
549
653
  }
550
- result.set(position, { supportsStyle, supportsClassName });
654
+ result.set(position, { supportsStyle, supportsClassName, supportsChildren });
551
655
  }
552
656
  ts2.forEachChild(node, visit);
553
657
  }
@@ -577,6 +681,22 @@ function hasRootMetaTag(html) {
577
681
  function isIntrinsicElement(tagName) {
578
682
  return tagName.length > 0 && tagName[0] === tagName[0].toLowerCase();
579
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
+ ]);
580
700
  function defaultComputeAnnotatedProps(info, filepath, modifiedtsMs) {
581
701
  return {
582
702
  "data-tempo-filepath": filepath,
@@ -782,13 +902,17 @@ function tempoVitePlugin(options = {}) {
782
902
  const result = annotateFile(source, cleanId, (info) => {
783
903
  const userProps = computeAnnotatedProps(info, filepath, modifiedtsMs);
784
904
  if (isIntrinsicElement(info.tagName)) {
785
- return userProps;
905
+ return {
906
+ ...userProps,
907
+ "data-tempo-supports-children": !HTML_VOID_ELEMENTS.has(info.tagName)
908
+ };
786
909
  }
787
910
  const support = typeInfo?.get(info.element.openingElement.start);
788
911
  return {
789
912
  ...userProps,
790
913
  "data-tempo-supports-style": support?.supportsStyle ?? false,
791
- "data-tempo-supports-classname": support?.supportsClassName ?? false
914
+ "data-tempo-supports-classname": support?.supportsClassName ?? false,
915
+ "data-tempo-supports-children": support?.supportsChildren ?? false
792
916
  };
793
917
  });
794
918
  if (result.elementsAnnotated === 0) {