tempo-sdk 0.0.99 → 0.0.102

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 (170) hide show
  1. package/README.md +3 -403
  2. package/dist/assets/editor.d.ts +43 -65
  3. package/dist/assets/editor.js +1 -573
  4. package/dist/assets/index.d.ts +11 -61
  5. package/dist/assets/index.js +1 -338
  6. package/dist/assets/parser.d.ts +68 -78
  7. package/dist/assets/parser.js +1 -33
  8. package/dist/astro/asset-preview-client.d.ts +3 -2
  9. package/dist/astro/asset-preview-client.js +1 -93
  10. package/dist/astro/controls.d.ts +1 -3
  11. package/dist/astro/controls.js +1 -7
  12. package/dist/astro/document-client.d.ts +5 -6
  13. package/dist/astro/document-client.js +1 -78
  14. package/dist/astro/runtime.d.ts +23 -11
  15. package/dist/astro/runtime.js +1 -86
  16. package/dist/astro.d.ts +19 -13
  17. package/dist/astro.js +1 -818
  18. package/dist/canvas/astro-contract.d.ts +0 -3
  19. package/dist/canvas/astro-contract.js +1 -9
  20. package/dist/canvas/astro.d.ts +3 -4
  21. package/dist/canvas/astro.js +1 -42
  22. package/dist/canvas/editor.d.ts +187 -183
  23. package/dist/canvas/editor.js +1 -1094
  24. package/dist/canvas/flutter-preview.d.ts +0 -1
  25. package/dist/canvas/flutter-preview.js +1 -9
  26. package/dist/canvas/index.d.ts +46 -100
  27. package/dist/canvas/index.js +1 -3926
  28. package/dist/canvas/interact-projection.d.ts +7 -5
  29. package/dist/canvas/interact-projection.js +1 -12
  30. package/dist/canvas/parser.d.ts +10 -303
  31. package/dist/canvas/parser.js +1 -30
  32. package/dist/canvas/svelte.d.ts +6 -7
  33. package/dist/canvas/svelte.js +1 -91
  34. package/dist/canvas/vue.d.ts +9 -49
  35. package/dist/canvas/vue.js +1 -264
  36. package/dist/chunk-CXCUJCXD.js +1 -0
  37. package/dist/chunk-FH6TMWFA.js +1 -0
  38. package/dist/chunk-FL7FSJSL.js +1 -0
  39. package/dist/chunk-GQIOB5SV.js +1 -0
  40. package/dist/chunk-HBQ7FFH7.js +1 -0
  41. package/dist/chunk-JRJOWLCN.js +1 -0
  42. package/dist/chunk-LJCBFTMP.js +1 -0
  43. package/dist/chunk-M3GN2KUH.js +1 -0
  44. package/dist/chunk-MPIHFFML.js +1 -0
  45. package/dist/chunk-T5TY3U2H.js +1 -0
  46. package/dist/chunk-XO2BSHWM.js +1 -0
  47. package/dist/chunk-XUSV3KOD.js +1 -0
  48. package/dist/chunk-ZXBMP6RV.js +1 -0
  49. package/dist/{controls-uCaQ3CNX.d.ts → controls-DKslABtM.d.ts} +0 -3
  50. package/dist/expo/plugin.cjs +1 -1928
  51. package/dist/expo/plugin.js +1 -8
  52. package/dist/expo-babel-plugin.cjs +1 -1928
  53. package/dist/expo-babel-plugin.d.cts +46 -40
  54. package/dist/expo-babel-plugin.d.ts +46 -40
  55. package/dist/expo-babel-plugin.js +1 -8
  56. package/dist/flutter-preview-path.d.ts +23 -7
  57. package/dist/flutter-preview-path.js +1 -16
  58. package/dist/index.d.ts +33 -45
  59. package/dist/index.js +1 -20
  60. package/dist/nextjs/plugin.cjs +1 -413
  61. package/dist/nextjs/plugin.js +1 -7
  62. package/dist/nextjs-loader.cjs +1 -2277
  63. package/dist/nextjs.cjs +1 -484
  64. package/dist/nextjs.d.cts +2 -58
  65. package/dist/nextjs.d.ts +2 -58
  66. package/dist/nextjs.js +1 -17
  67. package/dist/nuxt/runtime/identity.d.ts +2 -4
  68. package/dist/nuxt/runtime/identity.js +1 -18
  69. package/dist/nuxt.d.ts +31 -92
  70. package/dist/nuxt.js +1 -5854
  71. package/dist/{page-DwLnOM5d.d.ts → page-Bc8PekIX.d.ts} +1 -5
  72. package/dist/parser.d-MO5ciJ5n.d.ts +236 -0
  73. package/dist/{storyboard-CMJVBSXn.d.ts → storyboard.contract.d-UQ4MUYN5.d.ts} +3 -25
  74. package/dist/svelte.d.ts +8 -18
  75. package/dist/svelte.js +1 -917
  76. package/dist/types-CfUgM2w4.d.ts +57 -0
  77. package/dist/v1-client-compat-n0E0XxuX.d.ts +5 -0
  78. package/dist/vue.d.ts +17 -58
  79. package/dist/vue.js +1 -1501
  80. package/package.json +12 -62
  81. package/dist/assets/editor.js.map +0 -1
  82. package/dist/assets/index.js.map +0 -1
  83. package/dist/assets/parser.js.map +0 -1
  84. package/dist/astro/asset-preview-client.js.map +0 -1
  85. package/dist/astro/controls.js.map +0 -1
  86. package/dist/astro/document-client.js.map +0 -1
  87. package/dist/astro/runtime.js.map +0 -1
  88. package/dist/astro.js.map +0 -1
  89. package/dist/canvas/astro-contract.js.map +0 -1
  90. package/dist/canvas/astro.js.map +0 -1
  91. package/dist/canvas/editor.js.map +0 -1
  92. package/dist/canvas/flutter-preview.js.map +0 -1
  93. package/dist/canvas/index.js.map +0 -1
  94. package/dist/canvas/interact-projection.js.map +0 -1
  95. package/dist/canvas/parser.js.map +0 -1
  96. package/dist/canvas/svelte.js.map +0 -1
  97. package/dist/canvas/vue.js.map +0 -1
  98. package/dist/chunk-27WT3XUG.js +0 -455
  99. package/dist/chunk-27WT3XUG.js.map +0 -1
  100. package/dist/chunk-5HIIF354.js +0 -67
  101. package/dist/chunk-5HIIF354.js.map +0 -1
  102. package/dist/chunk-65B52AR7.js +0 -11
  103. package/dist/chunk-65B52AR7.js.map +0 -1
  104. package/dist/chunk-6HYKKP5N.js +0 -2658
  105. package/dist/chunk-6HYKKP5N.js.map +0 -1
  106. package/dist/chunk-6SOP4XU6.js +0 -1891
  107. package/dist/chunk-6SOP4XU6.js.map +0 -1
  108. package/dist/chunk-AFXE462X.js +0 -1253
  109. package/dist/chunk-AFXE462X.js.map +0 -1
  110. package/dist/chunk-BQPKOVI5.js +0 -115
  111. package/dist/chunk-BQPKOVI5.js.map +0 -1
  112. package/dist/chunk-CYDF4LYJ.js +0 -342
  113. package/dist/chunk-CYDF4LYJ.js.map +0 -1
  114. package/dist/chunk-CYQE3TLC.js +0 -37
  115. package/dist/chunk-CYQE3TLC.js.map +0 -1
  116. package/dist/chunk-DI2ZFAWL.js +0 -14
  117. package/dist/chunk-DI2ZFAWL.js.map +0 -1
  118. package/dist/chunk-EGRHWZRV.js +0 -1
  119. package/dist/chunk-EGRHWZRV.js.map +0 -1
  120. package/dist/chunk-FGWGY3G3.js +0 -157
  121. package/dist/chunk-FGWGY3G3.js.map +0 -1
  122. package/dist/chunk-HOBTDB6G.js +0 -112
  123. package/dist/chunk-HOBTDB6G.js.map +0 -1
  124. package/dist/chunk-I7VF4ZOV.js +0 -630
  125. package/dist/chunk-I7VF4ZOV.js.map +0 -1
  126. package/dist/chunk-JVVHU3A7.js +0 -1077
  127. package/dist/chunk-JVVHU3A7.js.map +0 -1
  128. package/dist/chunk-MIXQVPDH.js +0 -8606
  129. package/dist/chunk-MIXQVPDH.js.map +0 -1
  130. package/dist/chunk-MU7S7NU7.js +0 -183
  131. package/dist/chunk-MU7S7NU7.js.map +0 -1
  132. package/dist/chunk-OX2YKYSL.js +0 -13
  133. package/dist/chunk-OX2YKYSL.js.map +0 -1
  134. package/dist/chunk-PYAJHLXO.js +0 -903
  135. package/dist/chunk-PYAJHLXO.js.map +0 -1
  136. package/dist/chunk-SGN7BDRE.js +0 -16
  137. package/dist/chunk-SGN7BDRE.js.map +0 -1
  138. package/dist/chunk-SGTGDLOX.js +0 -285
  139. package/dist/chunk-SGTGDLOX.js.map +0 -1
  140. package/dist/chunk-T364NBR3.js +0 -1440
  141. package/dist/chunk-T364NBR3.js.map +0 -1
  142. package/dist/chunk-U66QI3EN.js +0 -1524
  143. package/dist/chunk-U66QI3EN.js.map +0 -1
  144. package/dist/chunk-WTXOWQ7N.js +0 -47
  145. package/dist/chunk-WTXOWQ7N.js.map +0 -1
  146. package/dist/chunk-X5DJKVBT.js +0 -1308
  147. package/dist/chunk-X5DJKVBT.js.map +0 -1
  148. package/dist/chunk-ZT7HJ6YU.js +0 -38
  149. package/dist/chunk-ZT7HJ6YU.js.map +0 -1
  150. package/dist/chunk-ZW26VZHX.js +0 -3169
  151. package/dist/chunk-ZW26VZHX.js.map +0 -1
  152. package/dist/controls-reader-5MFHYBZZ.js +0 -192
  153. package/dist/controls-reader-5MFHYBZZ.js.map +0 -1
  154. package/dist/expo/plugin.cjs.map +0 -1
  155. package/dist/expo/plugin.js.map +0 -1
  156. package/dist/expo-babel-plugin.cjs.map +0 -1
  157. package/dist/expo-babel-plugin.js.map +0 -1
  158. package/dist/flutter-preview-path.js.map +0 -1
  159. package/dist/index.js.map +0 -1
  160. package/dist/nextjs/plugin.cjs.map +0 -1
  161. package/dist/nextjs/plugin.js.map +0 -1
  162. package/dist/nextjs-loader.cjs.map +0 -1
  163. package/dist/nextjs.cjs.map +0 -1
  164. package/dist/nextjs.js.map +0 -1
  165. package/dist/nuxt/runtime/identity.js.map +0 -1
  166. package/dist/nuxt.js.map +0 -1
  167. package/dist/svelte.js.map +0 -1
  168. package/dist/types-C8OIU-kc.d.ts +0 -106
  169. package/dist/v1-client-compat-qxaXEDm_.d.ts +0 -23
  170. package/dist/vue.js.map +0 -1
@@ -1,2277 +1 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // nextjs-loader.ts
31
- var nextjs_loader_exports = {};
32
- __export(nextjs_loader_exports, {
33
- _resetLoaderState: () => _resetLoaderState,
34
- default: () => nextjs_loader_default,
35
- injectRootMetaIntoAnnotatedSource: () => injectRootMetaIntoAnnotatedSource,
36
- injectRootMetaIntoSource: () => injectRootMetaIntoSource,
37
- nextjsLoader: () => nextjsLoader
38
- });
39
- module.exports = __toCommonJS(nextjs_loader_exports);
40
-
41
- // canvas-component-reference.ts
42
- var import_node_fs2 = require("fs");
43
- var import_node_path2 = require("path");
44
-
45
- // canvas/flutter-preview.ts
46
- function parseFlutterPreview(value) {
47
- const prefix = `preview ${JSON.stringify(value)}`;
48
- if (value.includes("\\"))
49
- return {
50
- error: `${prefix} uses a backslash; use "/" (paths in canvases are POSIX).`
51
- };
52
- const hash = value.lastIndexOf("#");
53
- if (hash < 0)
54
- return {
55
- error: `${prefix} needs "#<function>" after the file, e.g. "../../lib/cards.dart#productCard".`
56
- };
57
- const file = value.slice(0, hash);
58
- const functionName = value.slice(hash + 1);
59
- if (!file.startsWith("./") && !file.startsWith("../"))
60
- return {
61
- error: file.startsWith("lib/") ? `${prefix} is no longer relative to a Flutter app folder; write the path from this canvas file, starting with "./" or "../".` : `${prefix} must be a path relative to this canvas file and start with "./" or "../", like a relative import.`
62
- };
63
- if (!file.endsWith(".dart"))
64
- return { error: `${prefix} must name a .dart file.` };
65
- if (/[?#]/.test(file) || file.includes("//"))
66
- return {
67
- error: `${prefix} must not contain "?", "#", or empty path segments.`
68
- };
69
- if (!/^[A-Za-z$][A-Za-z0-9_$]*$/.test(functionName))
70
- return {
71
- error: `${prefix}: ${JSON.stringify(functionName)} is not a public Dart function name.`
72
- };
73
- return { file, functionName };
74
- }
75
- var FLUTTER_PREVIEW_KEY_ATTRIBUTE = "data-tempo-flutter-preview-key";
76
-
77
- // flutter-preview-path.ts
78
- var import_node_fs = require("fs");
79
- var import_node_path = __toESM(require("path"), 1);
80
- function canonicalPathAllowMissing(file) {
81
- const absolute = import_node_path.default.resolve(file);
82
- try {
83
- return import_node_fs.realpathSync.native(absolute);
84
- } catch (error) {
85
- const code = error.code;
86
- if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
87
- let isLink = false;
88
- try {
89
- isLink = (0, import_node_fs.lstatSync)(absolute).isSymbolicLink();
90
- } catch (statError) {
91
- if (statError.code !== "ENOENT" && statError.code !== "ENOTDIR")
92
- throw statError;
93
- }
94
- if (isLink) throw error;
95
- const parent = import_node_path.default.dirname(absolute);
96
- if (parent === absolute) throw error;
97
- return import_node_path.default.join(
98
- canonicalPathAllowMissing(parent),
99
- import_node_path.default.basename(absolute)
100
- );
101
- }
102
- }
103
- function flutterPreviewKey(hostRoot, file, functionName) {
104
- return `${import_node_path.default.relative(canonicalPathAllowMissing(hostRoot), canonicalPathAllowMissing(file)).split(import_node_path.default.sep).join("/")}#${functionName}`;
105
- }
106
-
107
- // canvas/parser.ts
108
- var import_oxc_parser = require("oxc-parser");
109
-
110
- // canvas/storyboard-components.ts
111
- var STORYBOARD_SDK_COMPONENT_ROWS = {
112
- Storyboard: {
113
- importSource: "tempo-sdk/canvas",
114
- kind: "component",
115
- requiresComponentProp: true,
116
- allowsVrt: true,
117
- componentFileExtension: ".tsx"
118
- },
119
- SvelteStoryboard: {
120
- importSource: "tempo-sdk/canvas/svelte",
121
- kind: "component",
122
- uiFramework: "svelte",
123
- requiresComponentProp: true,
124
- allowsVrt: true,
125
- componentFileExtension: ".svelte"
126
- },
127
- VueStoryboard: {
128
- importSource: "tempo-sdk/canvas/vue",
129
- kind: "component",
130
- uiFramework: "vue",
131
- requiresComponentProp: true,
132
- allowsVrt: true,
133
- componentFileExtension: ".vue"
134
- },
135
- AstroStoryboard: {
136
- importSource: "tempo-sdk/canvas/astro",
137
- kind: "component",
138
- uiFramework: "astro",
139
- requiresComponentProp: true,
140
- allowsVrt: true,
141
- componentFileExtension: ".astro",
142
- componentImportQuery: "?tempo-component"
143
- },
144
- FlutterStoryboard: {
145
- importSource: "tempo-sdk/canvas",
146
- kind: "component",
147
- requiresComponentProp: false,
148
- allowsVrt: true
149
- },
150
- RouteStoryboard: {
151
- importSource: "tempo-sdk/canvas",
152
- kind: "route",
153
- requiresComponentProp: false,
154
- allowsVrt: false
155
- },
156
- HtmlStoryboard: {
157
- importSource: "tempo-sdk/canvas",
158
- kind: "html",
159
- requiresComponentProp: false,
160
- allowsVrt: true
161
- },
162
- LegacyStoryboardV1: {
163
- importSource: "tempo-sdk/canvas",
164
- kind: "component",
165
- requiresComponentProp: false,
166
- allowsVrt: false
167
- }
168
- };
169
- var STORYBOARD_SDK_COMPONENTS = STORYBOARD_SDK_COMPONENT_ROWS;
170
- var STORYBOARD_SDK_COMPONENT_NAMES = Object.keys(
171
- STORYBOARD_SDK_COMPONENTS
172
- );
173
-
174
- // canvas/parser.ts
175
- var SDK_IMPORT_SOURCES = /* @__PURE__ */ new Set([
176
- "tempo-sdk/canvas",
177
- ...STORYBOARD_SDK_COMPONENT_NAMES.map(
178
- (component) => STORYBOARD_SDK_COMPONENTS[component].importSource
179
- )
180
- ]);
181
- var SDK_COMPONENTS = /* @__PURE__ */ new Set([
182
- "Canvas",
183
- ...STORYBOARD_SDK_COMPONENT_NAMES
184
- ]);
185
- var CANVAS_CHILDREN_ERROR = `<Canvas> children must be ${formatAlternatives(
186
- STORYBOARD_SDK_COMPONENT_NAMES.map((component) => `<${component}>`)
187
- )} declarations`;
188
- var SDK_CANVAS_VALUE_EXPORTS = /* @__PURE__ */ new Set([
189
- "Canvas",
190
- "CanvasContext",
191
- "getCanvasStoryboardRenderId",
192
- "CanvasHost",
193
- "buildRenderContentFiberSelector",
194
- "buildRenderContentSelector",
195
- "buildRenderSelector",
196
- "captureStoryboardCombined",
197
- "captureStoryboardHtml",
198
- "captureStoryboardImage",
199
- "stripRenderContentWrapperAttributes",
200
- "stripRenderContentWrapperFromCombinedCapture",
201
- "watchStoryboardCombined",
202
- "getCanvasHostRuntime",
203
- "getOptionalCanvasHostRuntime",
204
- "useActiveState",
205
- "FlutterStoryboard",
206
- "HtmlStoryboard",
207
- "LegacyStoryboardV1",
208
- "RouteStoryboard",
209
- "Storyboard",
210
- "StoryboardSlot"
211
- ]);
212
- var DEFAULT_LAYOUT = {
213
- x: 0,
214
- y: 0
215
- };
216
- var DEFAULT_VIEWPORT_LAYOUT = {
217
- ...DEFAULT_LAYOUT,
218
- width: 600,
219
- height: 400
220
- };
221
- var NO_CANVAS_DECLARATION_ERROR = "No <Canvas> declaration found in canvas file";
222
- function parseCanvasFile(filePath, source) {
223
- const errors = [];
224
- let program;
225
- try {
226
- const result = (0, import_oxc_parser.parseSync)(filePath, source);
227
- program = result.program;
228
- for (const error of result.errors ?? []) {
229
- errors.push({
230
- message: error.message ?? "Unable to parse canvas source",
231
- span: toSpan(error) ?? toSpan(error?.labels?.[0]),
232
- kind: "structural"
233
- });
234
- }
235
- } catch (error) {
236
- return {
237
- filePath,
238
- pageName: fallbackPageName(filePath),
239
- imports: [],
240
- misimportedSdkCanvasImports: [],
241
- storyboards: [],
242
- errors: [
243
- {
244
- message: error instanceof Error ? error.message : "Unable to parse canvas source",
245
- kind: "structural"
246
- }
247
- ]
248
- };
249
- }
250
- const imports = readImports(program);
251
- const misimportedSdkCanvasImports = readMisimportedSdkCanvasImports(program);
252
- const { legacyObjects, stringBindings: objectStringBindings } = readObjectExpressionBindings(program, imports, source);
253
- let canvasElement = null;
254
- const allStoryboardElements = [];
255
- walk(program, (node) => {
256
- if (node.type !== "JSXElement") return;
257
- const component = resolveSdkComponent(node.openingElement?.name, imports);
258
- const namespaceMisimport = resolveMisimportedNamespaceSdkComponent(
259
- node.openingElement?.name,
260
- imports,
261
- misimportedSdkCanvasImports
262
- );
263
- if (namespaceMisimport) {
264
- misimportedSdkCanvasImports.add(namespaceMisimport);
265
- }
266
- if (component === "Canvas") {
267
- if (!canvasElement) {
268
- canvasElement = node;
269
- } else {
270
- errors.push({
271
- message: "Canvas file must declare exactly one <Canvas> element",
272
- span: toSpan(node),
273
- kind: "structural"
274
- });
275
- }
276
- return;
277
- }
278
- if (isStoryboardSdkComponent(component)) {
279
- allStoryboardElements.push({ element: node, component });
280
- }
281
- });
282
- const directStoryboardElements = canvasElement ? readDirectCanvasStoryboardElements(canvasElement, imports) : [];
283
- const directStoryboardElementSet = new Set(
284
- directStoryboardElements.map((item) => item.element)
285
- );
286
- const storyboards = directStoryboardElements.map(
287
- (item) => readStoryboard(
288
- item.element,
289
- item.component,
290
- imports,
291
- legacyObjects,
292
- source,
293
- errors
294
- )
295
- );
296
- for (const item of allStoryboardElements) {
297
- if (directStoryboardElementSet.has(item.element)) continue;
298
- errors.push({
299
- message: `<${item.component}> declarations must be direct children of the <Canvas> element`,
300
- span: toSpan(item.element),
301
- kind: "structural"
302
- });
303
- }
304
- reportDuplicateStoryboardIds(storyboards, errors);
305
- if (!canvasElement) {
306
- if (misimportedSdkCanvasImports.all.length > 0) {
307
- for (const entry of misimportedSdkCanvasImports.all) {
308
- errors.push({
309
- message: misimportedSdkCanvasImportMessage(entry),
310
- span: entry.sourceSpan,
311
- kind: "structural"
312
- });
313
- }
314
- } else {
315
- errors.push({
316
- message: NO_CANVAS_DECLARATION_ERROR,
317
- kind: "structural"
318
- });
319
- }
320
- } else {
321
- errors.push(...validateCanvasChildren(canvasElement, imports));
322
- }
323
- const openingElement = canvasElement?.openingElement;
324
- const name = readResolvableStringAttribute(
325
- openingElement,
326
- "name",
327
- objectStringBindings
328
- );
329
- const path2 = readStringAttribute(openingElement, "path");
330
- const backgroundColor = readResolvableStringAttribute(
331
- openingElement,
332
- "backgroundColor",
333
- objectStringBindings
334
- ) ?? readResolvableStringAttribute(
335
- openingElement,
336
- "background",
337
- objectStringBindings
338
- );
339
- if (openingElement && !name) {
340
- errors.push({
341
- message: '<Canvas> must include a literal "name" prop',
342
- span: toSpan(openingElement),
343
- kind: "degraded"
344
- });
345
- }
346
- return {
347
- filePath,
348
- canvasPath: path2?.value,
349
- pageName: name?.value ?? fallbackPageName(filePath),
350
- backgroundColor: backgroundColor?.value,
351
- canvasElementSpan: toSpan(canvasElement),
352
- canvasOpeningElementSpan: toSpan(openingElement),
353
- canvasChildrenInsertionOffset: typeof canvasElement?.closingElement?.start === "number" ? canvasElement.closingElement.start : void 0,
354
- nameSpan: name?.valueSpan,
355
- nameAttributeSpan: name?.attributeSpan,
356
- pathSpan: path2?.valueSpan,
357
- pathAttributeSpan: path2?.attributeSpan,
358
- backgroundColorSpan: backgroundColor?.valueSpan,
359
- backgroundColorAttributeSpan: backgroundColor?.attributeSpan,
360
- imports: imports.all,
361
- misimportedSdkCanvasImports: misimportedSdkCanvasImports.all,
362
- storyboards,
363
- errors
364
- };
365
- }
366
- function misimportedSdkCanvasImportMessage(entry) {
367
- return `Tempo canvas components must be imported from "tempo-sdk/canvas" \u2014 found import of ${entry.importedNames.join(", ")} from "${entry.source}"`;
368
- }
369
- function readMisimportedSdkCanvasImports(program) {
370
- const all = [];
371
- const byDeclarationKey = /* @__PURE__ */ new Map();
372
- const namespaceCandidatesByLocalName = /* @__PURE__ */ new Map();
373
- const add = (entry) => {
374
- const key = spanKey(entry.sourceSpan);
375
- if (byDeclarationKey.has(key)) return;
376
- byDeclarationKey.set(key, entry);
377
- all.push(entry);
378
- };
379
- for (const statement of program?.body ?? []) {
380
- if (statement?.type !== "ImportDeclaration" || typeof statement.source?.value !== "string" || !isWrongTempoSdkCanvasImportSource(statement.source.value) || statement.importKind === "type") {
381
- continue;
382
- }
383
- const source = statement.source.value;
384
- const sourceSpan = toSpan(statement.source);
385
- if (!sourceSpan) continue;
386
- const valueSpecifiers = (statement.specifiers ?? []).filter(
387
- (specifier) => specifier?.importKind !== "type"
388
- );
389
- const importedNames = valueSpecifiers.map(readImportedName);
390
- const entry = {
391
- source,
392
- sourceSpan,
393
- importedNames,
394
- rewritable: valueSpecifiers.length > 0 && valueSpecifiers.every(
395
- (specifier) => specifier?.type === "ImportSpecifier" && SDK_CANVAS_VALUE_EXPORTS.has(readImportedName(specifier))
396
- )
397
- };
398
- const hasMisimportedNamedSdkComponent = valueSpecifiers.some(
399
- (specifier) => specifier?.type === "ImportSpecifier" && SDK_COMPONENTS.has(readImportedName(specifier))
400
- );
401
- if (hasMisimportedNamedSdkComponent) {
402
- add(entry);
403
- }
404
- for (const specifier of valueSpecifiers) {
405
- if (specifier?.type !== "ImportNamespaceSpecifier") continue;
406
- const localName = specifier.local?.name;
407
- if (typeof localName === "string") {
408
- namespaceCandidatesByLocalName.set(localName, entry);
409
- }
410
- }
411
- }
412
- return { all, byDeclarationKey, namespaceCandidatesByLocalName, add };
413
- }
414
- function readImports(program) {
415
- const all = [];
416
- const byLocalName = /* @__PURE__ */ new Map();
417
- const sdkLocalNames = /* @__PURE__ */ new Map();
418
- const sdkNamespaces = /* @__PURE__ */ new Set();
419
- for (const statement of program?.body ?? []) {
420
- if (statement?.type !== "ImportDeclaration" || typeof statement.source?.value !== "string") {
421
- continue;
422
- }
423
- const source = statement.source.value;
424
- const isSdkImport = isSdkImportSource(source);
425
- for (const specifier of statement.specifiers ?? []) {
426
- const localName = specifier.local?.name;
427
- if (typeof localName !== "string") continue;
428
- const importedName = readImportedName(specifier);
429
- const imported = {
430
- localName,
431
- source,
432
- importedName,
433
- kind: readImportKind(specifier),
434
- importKind: specifier.importKind === "type" ? "type" : "value",
435
- span: toSpan(specifier) ?? toSpan(statement) ?? { start: 0, end: 0 },
436
- declarationSpan: toSpan(statement) ?? { start: 0, end: 0 },
437
- specifierCount: statement.specifiers?.length ?? 0,
438
- namedSpecifierCount: (statement.specifiers ?? []).filter(
439
- (item) => item?.type === "ImportSpecifier"
440
- ).length,
441
- hasDefaultSpecifier: (statement.specifiers ?? []).some(
442
- (item) => item?.type === "ImportDefaultSpecifier"
443
- ),
444
- hasNamespaceSpecifier: (statement.specifiers ?? []).some(
445
- (item) => item?.type === "ImportNamespaceSpecifier"
446
- )
447
- };
448
- all.push(imported);
449
- byLocalName.set(localName, imported);
450
- if (!isSdkImport) continue;
451
- if (specifier.type === "ImportNamespaceSpecifier") {
452
- sdkNamespaces.add(localName);
453
- continue;
454
- }
455
- if (SDK_COMPONENTS.has(importedName)) {
456
- sdkLocalNames.set(localName, importedName);
457
- }
458
- }
459
- }
460
- return { all, byLocalName, sdkLocalNames, sdkNamespaces };
461
- }
462
- function readObjectExpressionBindings(program, imports, source) {
463
- const legacyObjects = /* @__PURE__ */ new Map();
464
- const stringBindings = /* @__PURE__ */ new Map();
465
- for (const node of readTopLevelVariableDeclarators(program)) {
466
- if (node.id?.type !== "Identifier") {
467
- continue;
468
- }
469
- const objectExpression = unwrapTsExpression(node.init);
470
- if (objectExpression?.type !== "ObjectExpression") continue;
471
- const bindingName = node.id.name;
472
- legacyObjects.set(
473
- bindingName,
474
- readLegacyStoryboardObject(
475
- bindingName,
476
- objectExpression,
477
- imports,
478
- source
479
- )
480
- );
481
- const stringProperties = readObjectStringProperties(objectExpression);
482
- if (stringProperties.size > 0) {
483
- stringBindings.set(bindingName, stringProperties);
484
- }
485
- }
486
- return { legacyObjects, stringBindings };
487
- }
488
- function readTopLevelVariableDeclarators(program) {
489
- const declarators = [];
490
- for (const statement of program?.body ?? []) {
491
- const declaration = statement?.type === "VariableDeclaration" ? statement : statement?.type === "ExportNamedDeclaration" && statement.declaration?.type === "VariableDeclaration" ? statement.declaration : null;
492
- if (!declaration) continue;
493
- declarators.push(...declaration.declarations ?? []);
494
- }
495
- return declarators;
496
- }
497
- function readLegacyStoryboardObject(bindingName, objectExpression, imports, source) {
498
- const errors = [];
499
- const nameProperty = getObjectProperty(objectExpression, "name");
500
- const name = nameProperty ? readStringLiteralValue(nameProperty.value) : null;
501
- const layoutProperty = getObjectProperty(objectExpression, "layout");
502
- const layout = layoutProperty ? readLayoutExpression(layoutProperty.value, "LegacyStoryboardV1") : {
503
- value: DEFAULT_LAYOUT,
504
- errors: [
505
- {
506
- message: '<LegacyStoryboardV1> storyboard object must include a literal "layout" object',
507
- span: toSpan(objectExpression),
508
- kind: "degraded"
509
- }
510
- ]
511
- };
512
- const renderProperty = getObjectProperty(objectExpression, "render");
513
- const component = readRenderComponentReference(
514
- renderProperty?.value,
515
- imports,
516
- source
517
- );
518
- if (nameProperty && !name) {
519
- errors.push({
520
- message: "<LegacyStoryboardV1> storyboard.name must be a string literal when set",
521
- span: toSpan(nameProperty),
522
- kind: "degraded"
523
- });
524
- }
525
- errors.push(...layout.errors);
526
- return {
527
- bindingName,
528
- displayName: name?.value,
529
- component: component ?? void 0,
530
- objectSpan: toSpan(objectExpression),
531
- objectClose: readLayoutClose(objectExpression),
532
- nameSpan: name?.span,
533
- namePropertySpan: toSpan(nameProperty),
534
- layoutPropertySpan: toSpan(layoutProperty),
535
- layout: layout.value,
536
- layoutSpans: layout.spans,
537
- errors
538
- };
539
- }
540
- function readObjectStringProperties(objectExpression) {
541
- const properties = /* @__PURE__ */ new Map();
542
- for (const property of objectExpression.properties ?? []) {
543
- if (property?.type !== "Property" || property.computed) continue;
544
- const propertyName = readPropertyKeyName(property.key);
545
- const value = readStringLiteralValue(property.value);
546
- if (!propertyName || !value) continue;
547
- properties.set(propertyName, value);
548
- }
549
- return properties;
550
- }
551
- function readStoryboard(element, component, imports, legacyObjects, source, globalErrors) {
552
- const openingElement = element.openingElement;
553
- const errors = [];
554
- const id = readStringAttribute(openingElement, "id");
555
- const name = readStringAttribute(openingElement, "name");
556
- const legacyReference = component === "LegacyStoryboardV1" ? readExpressionReference(openingElement, "storyboard", source) : void 0;
557
- const legacyObject = legacyReference?.expression && isIdentifierExpression(legacyReference.expression) ? legacyObjects.get(legacyReference.expression) : void 0;
558
- const layout = component === "LegacyStoryboardV1" ? {
559
- value: legacyObject?.layout ?? DEFAULT_LAYOUT,
560
- spans: legacyObject?.layoutSpans,
561
- attributeSpan: void 0,
562
- errors: legacyObject?.errors ?? (legacyReference ? [
563
- {
564
- message: "<LegacyStoryboardV1> storyboard prop must reference a same-file object literal",
565
- span: legacyReference.span,
566
- kind: "degraded"
567
- }
568
- ] : [
569
- {
570
- message: '<LegacyStoryboardV1> must include a "storyboard" expression prop',
571
- span: toSpan(openingElement),
572
- kind: "degraded"
573
- }
574
- ])
575
- } : readLayout(openingElement, component);
576
- const spec = STORYBOARD_SDK_COMPONENTS[component];
577
- if (!id) {
578
- errors.push({
579
- message: `<${component}> must include a literal "id" prop`,
580
- span: toSpan(openingElement),
581
- kind: "structural"
582
- });
583
- }
584
- if (layout.errors.length > 0) {
585
- errors.push(...layout.errors);
586
- }
587
- const storyboard = {
588
- storyboardKey: id?.value ?? "",
589
- displayName: name?.value ?? legacyObject?.displayName,
590
- kind: spec.kind,
591
- ...spec.uiFramework ? { componentFramework: spec.uiFramework } : {},
592
- ...spec.uiFramework === "svelte" ? { uiFramework: spec.uiFramework } : spec.uiFramework === "astro" ? { runtimeFramework: spec.uiFramework } : {},
593
- layout: layout.value,
594
- editable: Boolean(id) && layout.errors.length === 0,
595
- jsxElementSpan: toSpan(element) ?? { start: 0, end: 0 },
596
- openingElementSpan: toSpan(openingElement),
597
- idSpan: id?.valueSpan,
598
- idAttributeSpan: id?.attributeSpan,
599
- nameSpan: name?.valueSpan ?? legacyObject?.nameSpan,
600
- nameAttributeSpan: name?.attributeSpan ?? legacyObject?.namePropertySpan,
601
- layoutAttributeSpan: layout.attributeSpan,
602
- layoutSpans: layout.spans,
603
- props: readExpressionReference(openingElement, "props", source),
604
- component: legacyObject?.component,
605
- legacyV1: legacyReference ? {
606
- storyboard: legacyReference,
607
- objectName: legacyObject?.bindingName,
608
- objectSpan: legacyObject?.objectSpan,
609
- objectClose: legacyObject?.objectClose,
610
- namePropertySpan: legacyObject?.namePropertySpan,
611
- layoutPropertySpan: legacyObject?.layoutPropertySpan
612
- } : void 0,
613
- errors
614
- };
615
- if (spec.requiresComponentProp) {
616
- const componentReference = readComponentReference(
617
- openingElement,
618
- imports,
619
- source
620
- );
621
- if (componentReference) {
622
- storyboard.component = componentReference;
623
- } else {
624
- errors.push({
625
- message: `<${component}> must include a "component" expression prop`,
626
- span: toSpan(openingElement),
627
- kind: "degraded"
628
- });
629
- }
630
- }
631
- if (spec.allowsVrt) {
632
- const vrt = readVrt(openingElement, errors);
633
- if (vrt) {
634
- if (vrt.value) {
635
- storyboard.vrt = vrt.value;
636
- }
637
- storyboard.vrtAttributeSpan = vrt.attributeSpan;
638
- }
639
- }
640
- if (component === "RouteStoryboard") {
641
- const route = readStringAttribute(openingElement, "route");
642
- if (route) {
643
- storyboard.route = route.value;
644
- storyboard.routeSpan = route.valueSpan;
645
- storyboard.routeAttributeSpan = route.attributeSpan;
646
- } else {
647
- errors.push({
648
- message: '<RouteStoryboard> must include a literal "route" prop',
649
- span: toSpan(openingElement),
650
- kind: "degraded"
651
- });
652
- }
653
- }
654
- if (component === "HtmlStoryboard") {
655
- const filepath = readStringAttribute(openingElement, "filepath");
656
- const src = readStringAttribute(openingElement, "src");
657
- storyboard.filepath = filepath?.value.trim() ? filepath.value : void 0;
658
- storyboard.filepathSpan = filepath?.valueSpan;
659
- storyboard.filepathAttributeSpan = filepath?.attributeSpan;
660
- storyboard.src = src?.value;
661
- storyboard.srcSpan = src?.valueSpan;
662
- storyboard.srcAttributeSpan = src?.attributeSpan;
663
- if (!filepath?.value.trim() && !src?.value.trim()) {
664
- errors.push({
665
- message: '<HtmlStoryboard> must include a literal "filepath" or "src" prop',
666
- span: toSpan(openingElement),
667
- kind: "degraded"
668
- });
669
- }
670
- }
671
- if (component === "FlutterStoryboard") {
672
- const preview = readStringAttribute(openingElement, "preview");
673
- if (preview?.value.trim()) {
674
- storyboard.preview = preview.value;
675
- storyboard.previewSpan = preview.valueSpan;
676
- storyboard.previewAttributeSpan = preview.attributeSpan;
677
- const parsedPreview = parseFlutterPreview(preview.value);
678
- if ("error" in parsedPreview)
679
- errors.push({
680
- message: `flutter_preview_invalid: ${parsedPreview.error}`,
681
- span: preview.valueSpan,
682
- kind: "structural"
683
- });
684
- } else {
685
- errors.push({
686
- message: '<FlutterStoryboard> must include a literal "preview" prop naming a Flutter @Preview function, e.g. preview="../../lib/cards.dart#productCard"',
687
- span: toSpan(getAttribute(openingElement, "preview") ?? openingElement),
688
- kind: "structural"
689
- });
690
- }
691
- }
692
- globalErrors.push(...errors);
693
- return storyboard;
694
- }
695
- function readDirectCanvasStoryboardElements(canvasElement, imports) {
696
- const elements = [];
697
- for (const child of canvasElement.children ?? []) {
698
- if (child?.type !== "JSXElement") continue;
699
- const component = resolveSdkComponent(child.openingElement?.name, imports);
700
- if (isStoryboardSdkComponent(component)) {
701
- elements.push({ element: child, component });
702
- }
703
- }
704
- return elements;
705
- }
706
- function reportDuplicateStoryboardIds(storyboards, errors) {
707
- const byId = /* @__PURE__ */ new Map();
708
- for (const storyboard of storyboards) {
709
- if (!storyboard.storyboardKey) continue;
710
- const matching = byId.get(storyboard.storyboardKey);
711
- if (matching) {
712
- matching.push(storyboard);
713
- } else {
714
- byId.set(storyboard.storyboardKey, [storyboard]);
715
- }
716
- }
717
- for (const [storyboardKey, matching] of byId) {
718
- if (matching.length < 2) continue;
719
- errors.push({
720
- message: `Duplicate storyboard id "${storyboardKey}" (${matching.length} declarations) \u2014 storyboard ids must be unique`,
721
- span: matching[1]?.jsxElementSpan,
722
- kind: "structural"
723
- });
724
- }
725
- }
726
- function validateCanvasChildren(canvasElement, imports) {
727
- const errors = [];
728
- for (const child of canvasElement.children ?? []) {
729
- if (!child) continue;
730
- if (child.type === "JSXText") {
731
- if (typeof child.value === "string" && child.value.trim() === "") {
732
- continue;
733
- }
734
- }
735
- if (child.type === "JSXExpressionContainer") {
736
- if (child.expression?.type === "JSXEmptyExpression") {
737
- continue;
738
- }
739
- errors.push({
740
- message: "<Canvas> children must be static storyboard declarations, not expressions",
741
- span: toSpan(child),
742
- kind: "structural"
743
- });
744
- continue;
745
- }
746
- if (child.type === "JSXElement") {
747
- const component = resolveSdkComponent(
748
- child.openingElement?.name,
749
- imports
750
- );
751
- if (isStoryboardSdkComponent(component)) continue;
752
- const newerComponent = resolveNewerSdkStoryboardComponent(
753
- child.openingElement?.name,
754
- imports
755
- );
756
- if (newerComponent) {
757
- errors.push(newerSdkStoryboardError(child, newerComponent));
758
- continue;
759
- }
760
- }
761
- errors.push({
762
- message: CANVAS_CHILDREN_ERROR,
763
- span: toSpan(child),
764
- kind: "structural"
765
- });
766
- }
767
- return errors;
768
- }
769
- var SDK_CANVAS_SUBPATH = /(^|\/)tempo-sdk\/canvas(\/[^/]+)?$/;
770
- function resolveNewerSdkStoryboardComponent(nameNode, imports) {
771
- let importedName;
772
- let source;
773
- if (nameNode?.type === "JSXIdentifier") {
774
- const imported = imports.byLocalName.get(nameNode.name);
775
- if (imported?.kind !== "named") return null;
776
- importedName = imported.importedName;
777
- source = imported.source;
778
- } else if (nameNode?.type === "JSXMemberExpression" && nameNode.object?.type === "JSXIdentifier" && nameNode.property?.type === "JSXIdentifier") {
779
- const imported = imports.byLocalName.get(nameNode.object.name);
780
- if (imported?.kind !== "namespace") return null;
781
- importedName = nameNode.property.name;
782
- source = imported.source;
783
- } else {
784
- return null;
785
- }
786
- const fromSdkCanvas = SDK_CANVAS_SUBPATH.test(source);
787
- const namesStoryboard = importedName.endsWith("Storyboard");
788
- return fromSdkCanvas && namesStoryboard ? importedName : null;
789
- }
790
- function newerSdkStoryboardError(element, component) {
791
- const openingElement = element.openingElement;
792
- const storyboardKey = readStringAttribute(openingElement, "id")?.value;
793
- const vrt = readVrt(openingElement, [])?.value != null;
794
- const named = storyboardKey ? ` id="${storyboardKey}"` : "";
795
- return {
796
- message: `<${component}${named}> is a storyboard from a newer tempo-sdk than this reader supports`,
797
- span: toSpan(element),
798
- kind: "structural",
799
- newerSdkStoryboard: {
800
- component,
801
- ...storyboardKey ? { storyboardKey } : {},
802
- vrt
803
- }
804
- };
805
- }
806
- function readVrt(openingElement, errors) {
807
- const attribute = getAttribute(openingElement, "vrt");
808
- if (!attribute) return null;
809
- const attributeSpan = toSpan(attribute);
810
- if (attribute.value == null) {
811
- return { value: {}, attributeSpan };
812
- }
813
- const expression = unwrapTsExpression(
814
- unwrapAttributeExpression(attribute.value)
815
- );
816
- if (expression?.type === "Literal" && expression.value === true) {
817
- return { value: {}, attributeSpan };
818
- }
819
- if (expression?.type === "Literal" && expression.value === false) {
820
- return { value: null, attributeSpan };
821
- }
822
- if (expression?.type !== "ObjectExpression") {
823
- errors.push({
824
- message: "<Storyboard> vrt must be a boolean literal or an object literal ({ threshold?, skip?, ignore? })",
825
- span: toSpan(expression) ?? attributeSpan,
826
- kind: "degraded"
827
- });
828
- return { value: null, attributeSpan };
829
- }
830
- const value = {};
831
- for (const property of expression.properties ?? []) {
832
- if (property?.type !== "Property" || property.computed) {
833
- errors.push({
834
- message: "<Storyboard> vrt must contain only literal properties",
835
- span: toSpan(property ?? expression),
836
- kind: "degraded"
837
- });
838
- continue;
839
- }
840
- const key = readPropertyKeyName(property.key);
841
- if (key === "threshold") {
842
- const threshold = readNumberLiteral(property.value);
843
- if (threshold && threshold.value >= 0 && threshold.value <= 0.5) {
844
- value.threshold = threshold.value;
845
- } else {
846
- errors.push({
847
- message: "<Storyboard> vrt.threshold must be a number literal between 0 and 0.5",
848
- span: toSpan(property),
849
- kind: "degraded"
850
- });
851
- }
852
- continue;
853
- }
854
- if (key === "skip") {
855
- if (property.value?.type === "Literal" && typeof property.value.value === "boolean") {
856
- if (property.value.value) value.skip = true;
857
- } else {
858
- errors.push({
859
- message: "<Storyboard> vrt.skip must be a boolean literal",
860
- span: toSpan(property),
861
- kind: "degraded"
862
- });
863
- }
864
- continue;
865
- }
866
- if (key === "ignore") {
867
- const regions = readVrtIgnoreRegions(property.value, errors);
868
- if (regions) value.ignore = regions;
869
- continue;
870
- }
871
- errors.push({
872
- message: `<Storyboard> vrt has unknown property "${key ?? "?"}" \u2014 expected threshold, skip, or ignore`,
873
- span: toSpan(property),
874
- kind: "degraded"
875
- });
876
- }
877
- return { value, attributeSpan };
878
- }
879
- function readVrtIgnoreRegions(node, errors) {
880
- if (node?.type !== "ArrayExpression") {
881
- errors.push({
882
- message: "<Storyboard> vrt.ignore must be an array of { x, y, w, h } literals",
883
- span: toSpan(node),
884
- kind: "degraded"
885
- });
886
- return null;
887
- }
888
- const regions = [];
889
- for (const element of node.elements ?? []) {
890
- const region = {};
891
- for (const key of ["x", "y", "w", "h"]) {
892
- const property = getObjectProperty(element, key);
893
- const number = property ? readNumberLiteral(property.value) : null;
894
- if (number) region[key] = number.value;
895
- }
896
- if (region.x === void 0 || region.y === void 0 || region.w === void 0 || region.h === void 0) {
897
- errors.push({
898
- message: "<Storyboard> vrt.ignore regions must be { x, y, w, h } number literals",
899
- span: toSpan(element) ?? toSpan(node),
900
- kind: "degraded"
901
- });
902
- return null;
903
- }
904
- regions.push(region);
905
- }
906
- return regions;
907
- }
908
- function readComponentReference(openingElement, imports, source) {
909
- const attribute = getAttribute(openingElement, "component");
910
- const expression = unwrapAttributeExpression(attribute?.value);
911
- const span = toSpan(expression);
912
- if (!expression || !span) return null;
913
- const localName = expression.type === "Identifier" ? expression.name : expression.type === "MemberExpression" && expression.object?.type === "Identifier" ? expression.object.name : void 0;
914
- return {
915
- expression: source.slice(span.start, span.end),
916
- span,
917
- attributeSpan: toSpan(attribute),
918
- localName,
919
- import: localName ? imports.byLocalName.get(localName) : void 0
920
- };
921
- }
922
- function readRenderComponentReference(renderValue, imports, source) {
923
- if (renderValue?.type !== "ArrowFunctionExpression") return null;
924
- const body = unwrapTsExpression(renderValue.body);
925
- if (body?.type !== "JSXElement") return null;
926
- const name = body.openingElement?.name;
927
- if (name?.type !== "JSXIdentifier") return null;
928
- const span = toSpan(name);
929
- if (!span || typeof name.name !== "string") return null;
930
- return {
931
- expression: source.slice(span.start, span.end),
932
- span,
933
- localName: name.name,
934
- import: imports.byLocalName.get(name.name)
935
- };
936
- }
937
- function readExpressionReference(openingElement, name, source) {
938
- const attribute = getAttribute(openingElement, name);
939
- const expression = unwrapAttributeExpression(attribute?.value);
940
- const span = toSpan(expression);
941
- if (!expression || !span) return void 0;
942
- return {
943
- expression: source.slice(span.start, span.end),
944
- span,
945
- attributeSpan: toSpan(attribute)
946
- };
947
- }
948
- function isIdentifierExpression(expression) {
949
- return /^[A-Za-z_$][\w$]*$/.test(expression);
950
- }
951
- function readLayout(openingElement, componentName) {
952
- const isViewport = requiresFixedLayoutSize(componentName);
953
- const attribute = getAttribute(openingElement, "layout");
954
- const expression = unwrapAttributeExpression(attribute?.value);
955
- if (!expression) {
956
- return {
957
- value: isViewport ? DEFAULT_VIEWPORT_LAYOUT : DEFAULT_LAYOUT,
958
- attributeSpan: toSpan(attribute),
959
- errors: [
960
- {
961
- message: `<${componentName}> must include a literal "layout" object prop`,
962
- span: toSpan(openingElement),
963
- kind: "degraded"
964
- }
965
- ]
966
- };
967
- }
968
- const layout = readLayoutExpression(expression, componentName);
969
- return {
970
- ...layout,
971
- attributeSpan: toSpan(attribute)
972
- };
973
- }
974
- function readLayoutExpression(expression, componentName) {
975
- const errors = [];
976
- const isViewport = requiresFixedLayoutSize(componentName);
977
- if (expression.type !== "ObjectExpression") {
978
- return {
979
- value: isViewport ? DEFAULT_VIEWPORT_LAYOUT : DEFAULT_LAYOUT,
980
- spans: { layoutClose: readLayoutClose(expression) },
981
- errors: [
982
- {
983
- message: `<${componentName}> layout must be an object literal`,
984
- span: toSpan(expression),
985
- kind: "degraded"
986
- }
987
- ]
988
- };
989
- }
990
- const spans = {
991
- layoutClose: readLayoutClose(expression)
992
- };
993
- const layout = { ...DEFAULT_LAYOUT };
994
- const width = getObjectProperty(expression, "width");
995
- const height = getObjectProperty(expression, "height");
996
- const legacySizing = getObjectProperty(expression, "intrinsicSizing");
997
- const legacyResponsiveFlag = legacySizing?.value?.value === "root-element";
998
- const hasBothSizes = Boolean(width && height);
999
- const readSize = isViewport || hasBothSizes && !legacyResponsiveFlag;
1000
- const incompleteSize = !isViewport && Boolean(width) !== Boolean(height);
1001
- if (incompleteSize) {
1002
- errors.push({
1003
- message: "layout.width and layout.height must be set together",
1004
- span: toSpan(expression),
1005
- kind: "degraded"
1006
- });
1007
- }
1008
- const size = readSize ? {
1009
- width: width ? readNumberLiteral(width.value) : null,
1010
- height: height ? readNumberLiteral(height.value) : null
1011
- } : null;
1012
- const keys = readSize ? ["x", "y", "width", "height"] : ["x", "y"];
1013
- for (const key of keys) {
1014
- const property = key === "width" ? width : key === "height" ? height : getObjectProperty(expression, key);
1015
- const value = key === "width" || key === "height" ? size?.[key] : property ? readNumberLiteral(property.value) : null;
1016
- const keepValue = key === "x" || key === "y" || isViewport || Boolean(size?.width && size.height);
1017
- if (!value) {
1018
- errors.push({
1019
- message: `<${componentName}> layout.${key} must be a number literal`,
1020
- span: toSpan(property ?? expression),
1021
- kind: "degraded"
1022
- });
1023
- continue;
1024
- }
1025
- if (!keepValue) continue;
1026
- layout[key] = value.value;
1027
- spans[key] = value.span;
1028
- }
1029
- const zIndex = getObjectProperty(expression, "zIndex");
1030
- if (zIndex) {
1031
- const value = readNumberLiteral(zIndex.value);
1032
- if (value) {
1033
- layout.zIndex = value.value;
1034
- spans.zIndex = value.span;
1035
- } else {
1036
- errors.push({
1037
- message: `<${componentName}> layout.zIndex must be a number literal`,
1038
- span: toSpan(zIndex),
1039
- kind: "degraded"
1040
- });
1041
- }
1042
- }
1043
- const invalidLegacyFlag = legacySizing && (legacySizing.value?.type !== "Literal" || !legacyResponsiveFlag);
1044
- if (invalidLegacyFlag) {
1045
- errors.push({
1046
- message: `<${componentName}> layout.intrinsicSizing must be "root-element" when set`,
1047
- span: toSpan(legacySizing),
1048
- kind: "degraded"
1049
- });
1050
- }
1051
- return { value: layout, spans, errors };
1052
- }
1053
- function readStringLiteralValue(node) {
1054
- return node?.type === "Literal" && typeof node.value === "string" ? { value: node.value, span: toSpan(node) ?? { start: 0, end: 0 } } : null;
1055
- }
1056
- function unwrapTsExpression(node) {
1057
- let current = node;
1058
- while (current?.type === "TSSatisfiesExpression" || current?.type === "TSAsExpression" || current?.type === "TSNonNullExpression" || current?.type === "ParenthesizedExpression") {
1059
- current = current.expression;
1060
- }
1061
- return current;
1062
- }
1063
- function readResolvableStringAttribute(openingElement, name, bindings) {
1064
- const literal = readStringAttribute(openingElement, name);
1065
- if (literal) return literal;
1066
- const attribute = getAttribute(openingElement, name);
1067
- const expression = unwrapAttributeExpression(attribute?.value);
1068
- const expressionSpan = toSpan(expression);
1069
- const attributeSpan = toSpan(attribute);
1070
- if (!expression || !expressionSpan || !attributeSpan) return null;
1071
- const resolved = resolveStringMemberExpression(expression, bindings);
1072
- return resolved ? {
1073
- value: resolved.value,
1074
- valueSpan: expressionSpan,
1075
- attributeSpan
1076
- } : null;
1077
- }
1078
- function resolveStringMemberExpression(expression, bindings) {
1079
- if (expression?.type !== "MemberExpression") return null;
1080
- if (expression.object?.type !== "Identifier") return null;
1081
- const propertyName = readPropertyKeyName(expression.property);
1082
- if (!propertyName) return null;
1083
- return bindings.get(expression.object.name)?.get(propertyName) ?? null;
1084
- }
1085
- function readStringAttribute(openingElement, name) {
1086
- const attribute = getAttribute(openingElement, name);
1087
- if (!attribute) return null;
1088
- const value = attribute.value;
1089
- if (value?.type === "Literal" && typeof value.value === "string") {
1090
- return {
1091
- value: value.value,
1092
- valueSpan: toSpan(value) ?? toSpan(attribute) ?? { start: 0, end: 0 },
1093
- attributeSpan: toSpan(attribute) ?? { start: 0, end: 0 }
1094
- };
1095
- }
1096
- const expression = unwrapTsExpression(unwrapAttributeExpression(value));
1097
- const fixed = expression?.type === "Literal" && typeof expression.value === "string" ? expression.value : expression?.type === "TemplateLiteral" && (expression.expressions?.length ?? 0) === 0 && expression.quasis?.length === 1 && typeof expression.quasis[0]?.value?.cooked === "string" ? expression.quasis[0].value.cooked : null;
1098
- if (fixed !== null) {
1099
- return {
1100
- value: fixed,
1101
- valueSpan: toSpan(expression) ?? toSpan(attribute) ?? { start: 0, end: 0 },
1102
- attributeSpan: toSpan(attribute) ?? { start: 0, end: 0 }
1103
- };
1104
- }
1105
- return null;
1106
- }
1107
- function getAttribute(openingElement, name) {
1108
- for (const attribute of openingElement?.attributes ?? []) {
1109
- if (attribute?.type === "JSXAttribute" && attribute.name?.type === "JSXIdentifier" && attribute.name.name === name) {
1110
- return attribute;
1111
- }
1112
- }
1113
- return null;
1114
- }
1115
- function unwrapAttributeExpression(value) {
1116
- if (!value) return null;
1117
- if (value.type === "JSXExpressionContainer") {
1118
- return value.expression;
1119
- }
1120
- return value;
1121
- }
1122
- function readPropertyKeyName(key) {
1123
- if (key?.type === "Identifier") return key.name;
1124
- if (key?.type === "Literal" && typeof key.value === "string") {
1125
- return key.value;
1126
- }
1127
- return null;
1128
- }
1129
- function getObjectProperty(objectExpression, name) {
1130
- if (objectExpression?.type !== "ObjectExpression") return null;
1131
- for (const property of objectExpression.properties ?? []) {
1132
- if (property?.type !== "Property" || property.computed) continue;
1133
- const propertyName = readPropertyKeyName(property.key);
1134
- if (propertyName === name) return property;
1135
- }
1136
- return null;
1137
- }
1138
- function readNumberLiteral(node) {
1139
- if (node?.type === "Literal" && typeof node.value === "number" && Number.isFinite(node.value)) {
1140
- return { value: node.value, span: toSpan(node) ?? { start: 0, end: 0 } };
1141
- }
1142
- if (node?.type === "UnaryExpression" && node.operator === "-" && node.argument?.type === "Literal" && typeof node.argument.value === "number" && Number.isFinite(node.argument.value)) {
1143
- return {
1144
- value: -node.argument.value,
1145
- span: toSpan(node) ?? { start: 0, end: 0 }
1146
- };
1147
- }
1148
- return null;
1149
- }
1150
- function resolveSdkComponent(nameNode, imports) {
1151
- if (nameNode?.type === "JSXIdentifier") {
1152
- return imports.sdkLocalNames.get(nameNode.name) ?? null;
1153
- }
1154
- if (nameNode?.type === "JSXMemberExpression" && nameNode.object?.type === "JSXIdentifier" && nameNode.property?.type === "JSXIdentifier" && imports.sdkNamespaces.has(nameNode.object.name) && SDK_COMPONENTS.has(nameNode.property.name)) {
1155
- return nameNode.property.name;
1156
- }
1157
- return null;
1158
- }
1159
- function resolveMisimportedNamespaceSdkComponent(nameNode, imports, misimportedSdkCanvasImports) {
1160
- if (nameNode?.type !== "JSXMemberExpression" || nameNode.object?.type !== "JSXIdentifier" || nameNode.property?.type !== "JSXIdentifier" || !SDK_COMPONENTS.has(nameNode.property.name)) {
1161
- return null;
1162
- }
1163
- const imported = imports.byLocalName.get(nameNode.object.name);
1164
- if (imported?.kind !== "namespace" || !isWrongTempoSdkCanvasImportSource(imported.source)) {
1165
- return null;
1166
- }
1167
- return misimportedSdkCanvasImports.namespaceCandidatesByLocalName.get(
1168
- nameNode.object.name
1169
- ) ?? null;
1170
- }
1171
- function isStoryboardSdkComponent(component) {
1172
- return component !== null && component !== "Canvas";
1173
- }
1174
- function formatAlternatives(items) {
1175
- if (items.length <= 1) return items.join("");
1176
- return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
1177
- }
1178
- function requiresFixedLayoutSize(componentName) {
1179
- return componentName === "RouteStoryboard" || componentName === "HtmlStoryboard" || componentName === "FlutterStoryboard";
1180
- }
1181
- function readImportedName(specifier) {
1182
- if (specifier.type === "ImportDefaultSpecifier") return "default";
1183
- if (specifier.type === "ImportNamespaceSpecifier") return "*";
1184
- return specifier.imported?.name ?? specifier.local?.name ?? "unknown";
1185
- }
1186
- function readImportKind(specifier) {
1187
- if (specifier.type === "ImportDefaultSpecifier") return "default";
1188
- if (specifier.type === "ImportNamespaceSpecifier") return "namespace";
1189
- return "named";
1190
- }
1191
- function isSdkImportSource(source) {
1192
- for (const sdkSource of SDK_IMPORT_SOURCES) {
1193
- if (source === sdkSource || source.endsWith(`/${sdkSource}`)) return true;
1194
- }
1195
- return false;
1196
- }
1197
- function isWrongTempoSdkCanvasImportSource(source) {
1198
- return (source === "tempo-sdk" || source.startsWith("tempo-sdk/")) && !isSdkImportSource(source);
1199
- }
1200
- function spanKey(span) {
1201
- return `${span.start}:${span.end}`;
1202
- }
1203
- function readLayoutClose(node) {
1204
- return typeof node?.end === "number" && Number.isFinite(node.end) ? node.end - 1 : void 0;
1205
- }
1206
- function fallbackPageName(filePath) {
1207
- const normalized = filePath.replace(/\\/g, "/");
1208
- const segments = normalized.split("/").filter(Boolean);
1209
- const fileName = segments.length > 0 ? segments[segments.length - 1] : filePath;
1210
- const parentName = segments.length > 1 ? segments[segments.length - 2] : fileName;
1211
- const baseName = /^index\.canvas\.[tj]sx?$/.test(fileName) ? parentName : fileName.replace(/\.canvas\.[tj]sx?$/, "");
1212
- return baseName.split(/[-_\s]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
1213
- }
1214
- function toSpan(node) {
1215
- return typeof node?.start === "number" && Number.isFinite(node.start) && typeof node?.end === "number" && Number.isFinite(node.end) ? { start: node.start, end: node.end } : void 0;
1216
- }
1217
- function walk(node, visitor, seen = /* @__PURE__ */ new Set()) {
1218
- if (!node || typeof node !== "object" || seen.has(node)) return;
1219
- seen.add(node);
1220
- visitor(node);
1221
- for (const value of Object.values(node)) {
1222
- if (!value) continue;
1223
- if (Array.isArray(value)) {
1224
- for (const item of value) {
1225
- walk(item, visitor, seen);
1226
- }
1227
- } else if (typeof value === "object") {
1228
- walk(value, visitor, seen);
1229
- }
1230
- }
1231
- }
1232
-
1233
- // canvas-component-reference.ts
1234
- var COMPONENT_REFERENCE_ATTRIBUTE = "data-tempo-component-reference";
1235
- function moduleIdentity(file, specifier, resolved) {
1236
- const resolvedId = resolved?.get(specifier);
1237
- const bundled = resolvedId?.startsWith("\0tempo:astro-component:") ? decodeURIComponent(
1238
- resolvedId.slice("\0tempo:astro-component:".length, -3)
1239
- ) : resolvedId;
1240
- const target = bundled === void 0 ? specifier : bundled.replace(/\bt=\d{13}&?\b/, "").replace(/[?&]$/, "");
1241
- if (target.startsWith("\0")) return target;
1242
- const suffixAt = target.search(/[?#]/);
1243
- let path2 = (suffixAt < 0 ? target : target.slice(0, suffixAt)).replace(
1244
- /\\/g,
1245
- "/"
1246
- );
1247
- const suffix = suffixAt < 0 || target.endsWith(".astro?tempo-component") ? "" : target.slice(suffixAt);
1248
- if (bundled === void 0 && path2.startsWith("."))
1249
- path2 = (0, import_node_path2.resolve)((0, import_node_path2.dirname)(file), path2);
1250
- if (!(0, import_node_path2.isAbsolute)(path2) && !/^[A-Za-z]:\//.test(path2)) return target;
1251
- if (bundled !== void 0) {
1252
- try {
1253
- path2 = import_node_fs2.realpathSync.native(path2);
1254
- } catch {
1255
- }
1256
- }
1257
- return (0, import_node_path2.normalize)(path2).replace(/\\/g, "/") + suffix;
1258
- }
1259
- function canvasComponentAnnotations(file, source, resolved, hostRoot) {
1260
- const result = /* @__PURE__ */ new Map();
1261
- if (!source.includes("tempo-sdk/canvas")) return result;
1262
- const parsed = parseCanvasFile(file, source);
1263
- for (const board of parsed.storyboards) {
1264
- if (board.kind !== "component" || board.openingElementSpan === void 0)
1265
- continue;
1266
- const flutterPreview = board.preview ? parseFlutterPreview(board.preview) : null;
1267
- if (flutterPreview && !("error" in flutterPreview) && hostRoot) {
1268
- let key;
1269
- try {
1270
- const absolute = (0, import_node_path2.resolve)(
1271
- (0, import_node_path2.dirname)(canonicalPathAllowMissing(file)),
1272
- flutterPreview.file
1273
- );
1274
- key = flutterPreviewKey(
1275
- hostRoot,
1276
- absolute,
1277
- flutterPreview.functionName
1278
- );
1279
- } catch {
1280
- continue;
1281
- }
1282
- result.set(board.openingElementSpan.start, {
1283
- [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: key,
1284
- [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([
1285
- "flutter",
1286
- key.slice(0, key.lastIndexOf("#")),
1287
- flutterPreview.functionName
1288
- ]),
1289
- "data-tempo-external-component": "true"
1290
- });
1291
- continue;
1292
- }
1293
- const ref = board.component;
1294
- if (!ref?.localName) continue;
1295
- const member = ref.expression.match(
1296
- /^\s*([$\w]+)(?:\s*\.\s*([$\w]+))?\s*$/
1297
- );
1298
- if (!member) continue;
1299
- let name;
1300
- if (ref.import) {
1301
- if (ref.import.kind === "namespace") {
1302
- if (!member[2]) continue;
1303
- name = member[2];
1304
- } else {
1305
- if (member[2]) continue;
1306
- name = ref.import.importedName;
1307
- }
1308
- } else {
1309
- if (member[2]) continue;
1310
- name = ref.localName;
1311
- }
1312
- const specifier = ref.import?.source.replace(/\\/g, "/").replace(/[?#].*/, "");
1313
- const canvasDir = import_node_path2.posix.dirname(file.replace(/\\/g, "/"));
1314
- const external = specifier !== void 0 && (!specifier.startsWith(".") || !import_node_path2.posix.join(canvasDir, specifier).startsWith(`${canvasDir}/`));
1315
- result.set(board.openingElementSpan.start, {
1316
- [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([
1317
- ref.import ? "import" : "local",
1318
- moduleIdentity(file, ref.import?.source ?? file, resolved),
1319
- name
1320
- ]),
1321
- ...external ? { "data-tempo-external-component": "true" } : {}
1322
- });
1323
- }
1324
- return result;
1325
- }
1326
-
1327
- // nextjs-loader.ts
1328
- var import_node_fs6 = require("fs");
1329
- var import_node_module = require("module");
1330
- var import_node_path6 = require("path");
1331
-
1332
- // ../../modules/annotation/annotate-file.ts
1333
- var import_oxc_parser3 = require("oxc-parser");
1334
-
1335
- // ../../modules/file-parser/utils.ts
1336
- function getTagName(name) {
1337
- switch (name.type) {
1338
- case "JSXIdentifier":
1339
- return name.name;
1340
- case "JSXNamespacedName":
1341
- return `${name.namespace.name}:${name.name.name}`;
1342
- case "JSXMemberExpression":
1343
- return getJSXMemberExpressionName(name);
1344
- }
1345
- }
1346
- function getJSXMemberExpressionName(node) {
1347
- const object = node.object.type === "JSXIdentifier" ? node.object.name : getJSXMemberExpressionName(node.object);
1348
- return `${object}.${node.property.name}`;
1349
- }
1350
-
1351
- // ../../modules/file-parser/walk.ts
1352
- var import_keys = __toESM(require("oxc-parser/src-js/generated/visit/keys.js"), 1);
1353
- var importedKeys = import_keys.default;
1354
- var visitorKeys = importedKeys.default ?? importedKeys;
1355
- function walk2(node, callbacks, parent = null) {
1356
- if (node === null || node === void 0 || typeof node !== "object") return;
1357
- if (Array.isArray(node)) {
1358
- for (const child of node) {
1359
- walk2(child, callbacks, parent);
1360
- }
1361
- return;
1362
- }
1363
- const record = node;
1364
- const type = record.type;
1365
- if (typeof type === "string" && type in callbacks) {
1366
- callbacks[type](node, parent);
1367
- }
1368
- const enclosing = typeof type === "string" ? node : parent;
1369
- for (const value of Object.values(record)) {
1370
- if (value !== null && typeof value === "object") {
1371
- walk2(value, callbacks, enclosing);
1372
- }
1373
- }
1374
- }
1375
-
1376
- // ../../modules/file-parser/scope-analyzer/types.ts
1377
- var ScopeFlags = {
1378
- Top: 1 << 0,
1379
- Function: 1 << 1,
1380
- Block: 1 << 2,
1381
- Catch: 1 << 3,
1382
- Class: 1 << 4,
1383
- For: 1 << 5,
1384
- Switch: 1 << 6,
1385
- Module: 1 << 7,
1386
- StrictMode: 1 << 8,
1387
- ClassStaticBlock: 1 << 9,
1388
- TsModuleBlock: 1 << 10,
1389
- TsConditional: 1 << 11,
1390
- Type: 1 << 12,
1391
- Enum: 1 << 13
1392
- };
1393
-
1394
- // ../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts
1395
- var import_oxc_parser2 = require("oxc-parser");
1396
-
1397
- // ../../modules/annotation/literal-expression.ts
1398
- function unwrapLiteralExpression(node) {
1399
- let current = node;
1400
- while ([
1401
- "ParenthesizedExpression",
1402
- "TSAsExpression",
1403
- "TSSatisfiesExpression",
1404
- "TSTypeAssertion",
1405
- "TSNonNullExpression",
1406
- "TSInstantiationExpression"
1407
- ].includes(current.type)) {
1408
- const expression = current.expression;
1409
- if (!expression) break;
1410
- current = expression;
1411
- }
1412
- return current;
1413
- }
1414
- function readLiteralExpression(node) {
1415
- const value = unwrapLiteralExpression(node);
1416
- if (["Literal", "StringLiteral", "NumericLiteral", "BooleanLiteral"].includes(
1417
- value.type
1418
- )) {
1419
- if (typeof value.value === "string" || typeof value.value === "boolean")
1420
- return value.value;
1421
- if (typeof value.value === "number" && Number.isFinite(value.value))
1422
- return value.value;
1423
- }
1424
- if (value.type === "TemplateLiteral") {
1425
- const expressions = value.expressions;
1426
- const quasis = value.quasis;
1427
- if (expressions.length === 0 && quasis.length === 1 && typeof quasis[0]?.value.cooked === "string")
1428
- return quasis[0].value.cooked;
1429
- }
1430
- if (value.type === "UnaryExpression" && (value.operator === "-" || value.operator === "+")) {
1431
- const argument = readLiteralExpression(value.argument);
1432
- if (typeof argument === "number")
1433
- return value.operator === "-" ? -argument : argument;
1434
- }
1435
- if (value.type === "BinaryExpression" && ["+", "-", "*", "/"].includes(value.operator)) {
1436
- const left = readLiteralExpression(value.left);
1437
- const right = readLiteralExpression(value.right);
1438
- if (typeof left !== "number" || typeof right !== "number") return null;
1439
- const result = value.operator === "+" ? left + right : value.operator === "-" ? left - right : value.operator === "*" ? left * right : left / right;
1440
- return Number.isFinite(result) ? result : null;
1441
- }
1442
- return null;
1443
- }
1444
- function literalJsxChild(node) {
1445
- if (node.type !== "JSXExpressionContainer") return null;
1446
- const root = unwrapLiteralExpression(
1447
- node.expression
1448
- );
1449
- return root.type === "JSXElement" ? root : null;
1450
- }
1451
- function literalPropertyName(key, computed = false) {
1452
- if (!computed && key.type === "Identifier")
1453
- return typeof key.name === "string" ? key.name : null;
1454
- const value = readLiteralExpression(key);
1455
- return typeof value === "string" || typeof value === "number" ? String(value) : null;
1456
- }
1457
-
1458
- // ../../modules/annotation/annotate-file.ts
1459
- function formatPropValue(value) {
1460
- if (value === void 0) return null;
1461
- if (typeof value === "function") return value.toString();
1462
- return JSON.stringify(value);
1463
- }
1464
- function formatProps(props) {
1465
- return Object.entries(props).map(([key, value]) => {
1466
- const formatted = formatPropValue(value);
1467
- if (formatted === null) return null;
1468
- return ` ${key}={${formatted}}`;
1469
- }).filter((s) => s !== null).join("");
1470
- }
1471
- function getExistingAttributeNames(element) {
1472
- const names = /* @__PURE__ */ new Set();
1473
- for (const attr of element.openingElement.attributes ?? []) {
1474
- if (attr.type !== "JSXAttribute") continue;
1475
- names.add(getTagName(attr.name));
1476
- }
1477
- return names;
1478
- }
1479
- function removeExistingProps(props, existingNames) {
1480
- return Object.fromEntries(
1481
- Object.entries(props).filter(([key]) => !existingNames.has(key))
1482
- );
1483
- }
1484
- var FRAGMENT_TAG_NAMES = /* @__PURE__ */ new Set(["Fragment", "React.Fragment"]);
1485
- function annotateFile(source, filename, computeAnnotatedProps) {
1486
- const parseResult = (0, import_oxc_parser3.parseSync)(filename, source);
1487
- const insertions = [];
1488
- const staticChildren = /* @__PURE__ */ new WeakSet();
1489
- const noteChildren = (node) => {
1490
- for (const child of node.children) {
1491
- const literal = literalJsxChild(child);
1492
- if (literal) staticChildren.add(literal);
1493
- }
1494
- };
1495
- walk2(parseResult.program, {
1496
- JSXFragment(node) {
1497
- noteChildren(node);
1498
- },
1499
- JSXElement(node, parent) {
1500
- const element = node;
1501
- noteChildren(element);
1502
- const tagName = getTagName(element.openingElement.name);
1503
- if (FRAGMENT_TAG_NAMES.has(tagName)) return;
1504
- const parentType = parent?.type ?? null;
1505
- const props = removeExistingProps(
1506
- computeAnnotatedProps({
1507
- element,
1508
- tagName,
1509
- parentType,
1510
- ...staticChildren.has(element) ? { isStaticJsxChild: true } : {}
1511
- }),
1512
- getExistingAttributeNames(element)
1513
- );
1514
- if (Object.keys(props).length === 0) return;
1515
- const openingElement = element.openingElement;
1516
- let insertPos = openingElement.end - 1;
1517
- if (openingElement.selfClosing) {
1518
- insertPos--;
1519
- while (insertPos > openingElement.start && /\s/.test(source[insertPos - 1])) {
1520
- insertPos--;
1521
- }
1522
- }
1523
- insertions.push({ position: insertPos, text: formatProps(props) });
1524
- }
1525
- });
1526
- insertions.sort((a, b) => a.position - b.position);
1527
- const chunks = [];
1528
- let lastPos = 0;
1529
- for (const { position, text } of insertions) {
1530
- chunks.push(source.slice(lastPos, position));
1531
- chunks.push(text);
1532
- lastPos = position;
1533
- }
1534
- chunks.push(source.slice(lastPos));
1535
- return {
1536
- annotatedSource: chunks.join(""),
1537
- elementsAnnotated: insertions.length,
1538
- parseResult
1539
- };
1540
- }
1541
-
1542
- // ../../modules/annotation/expression-facts.ts
1543
- var EXPRESSION_FACTS_ATTRIBUTE = "data-tempo-expr";
1544
- var DYNAMIC_SLOT_FACT = "#slot";
1545
- function expressionFacts(element, parentType, isStaticJsxChild = false) {
1546
- const opening = element.openingElement;
1547
- const attributes = opening.attributes;
1548
- const facts = [];
1549
- if (!isStaticJsxChild && parentType !== "JSXElement" && parentType !== "JSXFragment")
1550
- facts.push(DYNAMIC_SLOT_FACT);
1551
- const last = /* @__PURE__ */ new Map();
1552
- attributes.forEach((attribute, index) => {
1553
- const name = attributeName(attribute);
1554
- if (name !== null) last.set(name, index);
1555
- });
1556
- let lastSpread = -1;
1557
- attributes.forEach((attribute, index) => {
1558
- if (attribute.type === "JSXSpreadAttribute") lastSpread = index;
1559
- });
1560
- for (const [name, index] of last) {
1561
- if (unstamped(name)) continue;
1562
- const overridden = index < lastSpread;
1563
- const value = attributes[index].value;
1564
- if (value === null) continue;
1565
- if (name === "style" && !overridden) {
1566
- facts.push(...styleFacts(value));
1567
- continue;
1568
- }
1569
- if (overridden) facts.push(name);
1570
- else if (name === "className" && isClassHelperCall(value)) continue;
1571
- else if (!isLiteralValue(value)) facts.push(name);
1572
- }
1573
- if (facts.length > 0) return facts.join(" ");
1574
- return lastSpread >= 0 ? "" : void 0;
1575
- }
1576
- function attributeName(attribute) {
1577
- if (attribute.type !== "JSXAttribute") return null;
1578
- const name = attribute.name;
1579
- if (name.type === "JSXIdentifier") return name.name;
1580
- if (name.type === "JSXNamespacedName") {
1581
- const namespace = name.namespace.name;
1582
- return `${namespace}:${name.name.name}`;
1583
- }
1584
- return null;
1585
- }
1586
- function unstamped(name) {
1587
- return name === "key" || name.startsWith("data-tempo-");
1588
- }
1589
- function styleFacts(value) {
1590
- const expression = value.type === "JSXExpressionContainer" ? unwrap(value.expression) : value;
1591
- if (expression.type !== "ObjectExpression") return ["style"];
1592
- const properties = expression.properties;
1593
- const last = /* @__PURE__ */ new Map();
1594
- properties.forEach((property, index) => {
1595
- const key = styleKey(property);
1596
- if (key !== null) last.set(key, index);
1597
- });
1598
- const facts = [];
1599
- for (const [key, index] of last) {
1600
- const property = properties[index];
1601
- const overridden = properties.slice(index + 1).some(
1602
- (later) => later.type === "SpreadElement" || later.computed && styleKey(later) === null
1603
- );
1604
- const literal = property.type !== "ObjectMethod" && !property.shorthand && isLiteral(property.value);
1605
- if (overridden || !literal) facts.push(`style.${key}`);
1606
- }
1607
- return facts;
1608
- }
1609
- function styleKey(property) {
1610
- const isProperty = property.type === "Property" || property.type === "ObjectProperty" || property.type === "ObjectMethod";
1611
- if (!isProperty) return null;
1612
- return literalPropertyName(property.key, Boolean(property.computed));
1613
- }
1614
- function isLiteralValue(value) {
1615
- if (value.type === "Literal" || value.type === "StringLiteral") return true;
1616
- if (value.type !== "JSXExpressionContainer") return false;
1617
- return isLiteral(value.expression);
1618
- }
1619
- var CLASS_HELPERS = /* @__PURE__ */ new Set(["cn", "clsx", "twMerge", "cx", "classNames"]);
1620
- function isClassHelperCall(value) {
1621
- if (value.type !== "JSXExpressionContainer") return false;
1622
- const call = value.expression;
1623
- if (call.type !== "CallExpression") return false;
1624
- const callee = call.callee;
1625
- if (callee.type !== "Identifier" || !CLASS_HELPERS.has(callee.name))
1626
- return false;
1627
- return call.arguments.every(
1628
- (argument) => (argument.type === "Literal" || argument.type === "StringLiteral") && typeof argument.value === "string" || argument.type === "TemplateLiteral" && argument.expressions.length === 0
1629
- );
1630
- }
1631
- function isLiteral(node) {
1632
- return readLiteralExpression(node) !== null;
1633
- }
1634
- function unwrap(node) {
1635
- return unwrapLiteralExpression(node);
1636
- }
1637
-
1638
- // ../../modules/annotation/source-version.ts
1639
- function sourceVersionHash(content) {
1640
- let djb2 = 5381;
1641
- let sdbm = 0;
1642
- for (let i = 0; i < content.length; i++) {
1643
- const c = content.charCodeAt(i);
1644
- djb2 = (djb2 << 5) + djb2 ^ c;
1645
- sdbm = c + (sdbm << 6) + (sdbm << 16) - sdbm | 0;
1646
- }
1647
- return toHex8(djb2) + toHex8(sdbm);
1648
- }
1649
- function toHex8(n) {
1650
- return (n >>> 0).toString(16).padStart(8, "0");
1651
- }
1652
-
1653
- // nextjs-loader.ts
1654
- var import_oxc_parser4 = require("oxc-parser");
1655
-
1656
- // annotation-strategy.ts
1657
- var import_node_fs3 = require("fs");
1658
- var import_node_path3 = require("path");
1659
- var HTML_VOID_ELEMENTS = /* @__PURE__ */ new Set([
1660
- "area",
1661
- "base",
1662
- "br",
1663
- "col",
1664
- "embed",
1665
- "hr",
1666
- "img",
1667
- "input",
1668
- "link",
1669
- "meta",
1670
- "param",
1671
- "source",
1672
- "track",
1673
- "wbr"
1674
- ]);
1675
- function isIntrinsicElement(tagName) {
1676
- return tagName.length > 0 && tagName[0] === tagName[0].toLowerCase();
1677
- }
1678
- function hasJsxAttribute(info, attrName) {
1679
- for (const attr of info.element.openingElement.attributes) {
1680
- const name = attr.name;
1681
- if (name?.name === attrName) return true;
1682
- }
1683
- return false;
1684
- }
1685
- function defaultComputeAnnotatedProps(info, filepath, modifiedtsMs, sourceVersion) {
1686
- return {
1687
- "data-tempo-filepath": filepath,
1688
- "data-tempo-position": info.element.openingElement.start,
1689
- // Runtime display names can differ from the JSX used at this callsite
1690
- // (imports, member expressions, memo and forwardRef wrappers).
1691
- "data-tempo-source-tag": info.tagName,
1692
- "data-tempo-modifiedts": modifiedtsMs,
1693
- // Content-hash identity of the file this element was annotated from. The
1694
- // canvas reconcile loop equality-compares it against the write pipeline's
1695
- // computed version to decide whether a capture reflects a given edit.
1696
- "data-tempo-source-version": sourceVersion
1697
- };
1698
- }
1699
- function appendModuleVersionRecord(source, filepath, modifiedtsMs, sourceVersion) {
1700
- const record = JSON.stringify({
1701
- file: filepath,
1702
- modifiedTs: modifiedtsMs,
1703
- sourceVersion
1704
- });
1705
- return `${source}
1706
- ;typeof window !== "undefined" && (globalThis.__TEMPO_MODULE_VERSIONS__ || (globalThis.__TEMPO_MODULE_VERSIONS__ = [])).push(${record});
1707
- `;
1708
- }
1709
- function computeTempoAnnotatedProps(params) {
1710
- const {
1711
- info,
1712
- filepath,
1713
- modifiedtsMs,
1714
- sourceVersion,
1715
- computeAnnotatedProps,
1716
- elementSupportOverrides
1717
- } = params;
1718
- const userProps = {
1719
- ...computeAnnotatedProps ? computeAnnotatedProps(info, filepath, modifiedtsMs, sourceVersion) : defaultComputeAnnotatedProps(
1720
- info,
1721
- filepath,
1722
- modifiedtsMs,
1723
- sourceVersion
1724
- ),
1725
- // Only a caller that knows the parent can say whether the slot is a JSX
1726
- // child; without it every element would read as a dynamic slot.
1727
- ...info.parentType !== void 0 && !hasJsxAttribute(info, EXPRESSION_FACTS_ATTRIBUTE) ? {
1728
- [EXPRESSION_FACTS_ATTRIBUTE]: expressionFacts(
1729
- info.element,
1730
- info.parentType,
1731
- info.isStaticJsxChild
1732
- )
1733
- } : {}
1734
- };
1735
- if (isIntrinsicElement(info.tagName)) {
1736
- return {
1737
- ...userProps,
1738
- "data-tempo-supports-children": hasJsxAttribute(
1739
- info,
1740
- "data-tempo-supports-children"
1741
- ) ? void 0 : !HTML_VOID_ELEMENTS.has(info.tagName)
1742
- };
1743
- }
1744
- const override = elementSupportOverrides?.get(info.tagName);
1745
- if (override) {
1746
- return {
1747
- ...userProps,
1748
- "data-tempo-supports-children": hasJsxAttribute(
1749
- info,
1750
- "data-tempo-supports-children"
1751
- ) ? void 0 : override.supportsChildren
1752
- };
1753
- }
1754
- return userProps;
1755
- }
1756
-
1757
- // host-identity.ts
1758
- var import_node_fs4 = require("fs");
1759
- var import_node_path4 = require("path");
1760
-
1761
- // package.json
1762
- var package_default = {
1763
- name: "tempo-sdk",
1764
- version: "0.0.99",
1765
- publishConfig: {
1766
- tag: "sdk-v2-latest"
1767
- },
1768
- type: "module",
1769
- description: "Tempo SDK \u2014 Vite, Next.js, Nuxt, Expo, Svelte, Vue and Astro canvas integration, source annotations and storyboard types",
1770
- repository: {
1771
- type: "git",
1772
- url: "git+https://github.com/TempoLabsAI/tempo-monorepo.git",
1773
- directory: "tempo-modules/tempo-sdk"
1774
- },
1775
- exports: {
1776
- "./astro/controls": {
1777
- types: "./dist/astro/controls.d.ts",
1778
- import: "./dist/astro/controls.js",
1779
- default: "./dist/astro/controls.js"
1780
- },
1781
- "./astro": {
1782
- types: "./dist/astro.d.ts",
1783
- import: "./dist/astro.js"
1784
- },
1785
- "./astro/client": {
1786
- types: "./astro/client.d.ts"
1787
- },
1788
- "./canvas/astro": {
1789
- types: "./dist/canvas/astro.d.ts",
1790
- import: "./dist/canvas/astro.js"
1791
- },
1792
- "./canvas/astro-contract": {
1793
- types: "./dist/canvas/astro-contract.d.ts",
1794
- import: "./dist/canvas/astro-contract.js"
1795
- },
1796
- ".": {
1797
- types: "./dist/index.d.ts",
1798
- import: "./dist/index.js"
1799
- },
1800
- "./canvas": {
1801
- types: "./dist/canvas/index.d.ts",
1802
- import: "./dist/canvas/index.js"
1803
- },
1804
- "./canvas/svelte": {
1805
- types: "./dist/canvas/svelte.d.ts",
1806
- import: "./dist/canvas/svelte.js"
1807
- },
1808
- "./canvas/vue": {
1809
- types: "./dist/canvas/vue.d.ts",
1810
- import: "./dist/canvas/vue.js"
1811
- },
1812
- "./canvas/interact-projection": {
1813
- types: "./dist/canvas/interact-projection.d.ts",
1814
- import: "./dist/canvas/interact-projection.js"
1815
- },
1816
- "./canvas/parser": {
1817
- types: "./dist/canvas/parser.d.ts",
1818
- import: "./dist/canvas/parser.js"
1819
- },
1820
- "./canvas/editor": {
1821
- types: "./dist/canvas/editor.d.ts",
1822
- import: "./dist/canvas/editor.js"
1823
- },
1824
- "./assets": {
1825
- types: "./dist/assets/index.d.ts",
1826
- import: "./dist/assets/index.js"
1827
- },
1828
- "./assets/parser": {
1829
- types: "./dist/assets/parser.d.ts",
1830
- import: "./dist/assets/parser.js"
1831
- },
1832
- "./assets/editor": {
1833
- types: "./dist/assets/editor.d.ts",
1834
- import: "./dist/assets/editor.js"
1835
- },
1836
- "./nextjs": {
1837
- types: "./dist/nextjs.d.ts",
1838
- import: "./dist/nextjs.js",
1839
- require: "./dist/nextjs.cjs"
1840
- },
1841
- "./nextjs/plugin": {
1842
- types: "./dist/nextjs/plugin.d.ts",
1843
- import: "./dist/nextjs/plugin.js"
1844
- },
1845
- "./nuxt": {
1846
- types: "./dist/nuxt.d.ts",
1847
- import: "./dist/nuxt.js"
1848
- },
1849
- "./expo": {
1850
- types: "./dist/expo-babel-plugin.d.ts",
1851
- import: "./dist/expo-babel-plugin.js",
1852
- require: "./dist/expo-babel-plugin.cjs"
1853
- },
1854
- "./expo/plugin": {
1855
- types: "./dist/expo/plugin.d.ts",
1856
- import: "./dist/expo/plugin.js",
1857
- require: "./dist/expo/plugin.cjs"
1858
- },
1859
- "./svelte": {
1860
- types: "./dist/svelte.d.ts",
1861
- import: "./dist/svelte.js"
1862
- },
1863
- "./vue": {
1864
- types: "./dist/vue.d.ts",
1865
- import: "./dist/vue.js"
1866
- },
1867
- "./astro/asset-preview-client": {
1868
- types: "./dist/astro/asset-preview-client.d.ts",
1869
- import: "./dist/astro/asset-preview-client.js"
1870
- },
1871
- "./flutter-preview-path": {
1872
- types: "./dist/flutter-preview-path.d.ts",
1873
- import: "./dist/flutter-preview-path.js"
1874
- },
1875
- "./canvas/flutter-preview": {
1876
- types: "./dist/canvas/flutter-preview.d.ts",
1877
- import: "./dist/canvas/flutter-preview.js"
1878
- }
1879
- },
1880
- files: [
1881
- "dist",
1882
- "astro/client.d.ts"
1883
- ],
1884
- scripts: {
1885
- clean: "rm -rf dist",
1886
- build: "pnpm run clean && tsup",
1887
- "build:if-missing": "test -f dist/index.js || pnpm run build",
1888
- prepare: "pnpm run build",
1889
- prepublishOnly: "pnpm build",
1890
- demo: "TEMPO=true pnpm --filter @tempo-modules/vite-annotate-plugin-demo dev",
1891
- "demo:nextjs": "TEMPO=true pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev",
1892
- "demo:nuxt": "pnpm --filter @tempo-modules/tempo-sdk-nuxt-demo dev",
1893
- test: "vitest run",
1894
- "test:browser": "vitest run canvas-dependency-scan-browser.test.ts pruned-module-deletion-browser.test.ts asset-live-preview-browser.test.ts asset-popover-lifecycle-browser.test.ts component-controls-browser.test.ts canvas-controls-browser.test.ts canvas-capture-determinism-browser.test.ts flutter-storyboard-browser.test.ts canvas-host-vite-e2e.test.ts canvas-host-packed-sdk-e2e.test.ts error-tracking-e2e.test.ts astro-integration.test.ts astro-storyboard-routing.test.ts astro-react-integration.test.ts astro-descriptor-browser.test.ts astro-packed.test.ts",
1895
- "test:watch": "vitest",
1896
- "test:nextjs:unit": "vitest run nextjs-loader.test.ts nextjs-wrapper.test.ts nextjs-fixtures.test.ts nextjs-published.test.ts",
1897
- "test:nextjs:integration": "vitest run nextjs-e2e-correctness.test.ts",
1898
- "test:nextjs:production": "vitest run nextjs-production.test.ts",
1899
- "test:nextjs": "vitest run nextjs-loader.test.ts nextjs-wrapper.test.ts nextjs-fixtures.test.ts nextjs-published.test.ts nextjs-e2e-correctness.test.ts nextjs-production.test.ts"
1900
- },
1901
- dependencies: {
1902
- "@rollup/pluginutils": "^5.1.0",
1903
- "oxc-parser": "^0.110.0"
1904
- },
1905
- optionalDependencies: {
1906
- "@astrojs/compiler-rs": "0.5.1"
1907
- },
1908
- peerDependencies: {
1909
- astro: "^7.0.0",
1910
- "@babel/core": "^7.0.0",
1911
- h3: "^1.12.0",
1912
- next: "^13 || ^14 || ^15 || ^16",
1913
- nuxt: "^3.18.0 || ^4.0.0",
1914
- react: "^18 || ^19",
1915
- svelte: "^5.0.0",
1916
- vite: "^5 || ^6 || ^7 || ^8",
1917
- vue: "^3.3.0"
1918
- },
1919
- peerDependenciesMeta: {
1920
- astro: {
1921
- optional: true
1922
- },
1923
- react: {
1924
- optional: true
1925
- },
1926
- "@babel/core": {
1927
- optional: true
1928
- },
1929
- h3: {
1930
- optional: true
1931
- },
1932
- next: {
1933
- optional: true
1934
- },
1935
- nuxt: {
1936
- optional: true
1937
- },
1938
- svelte: {
1939
- optional: true
1940
- },
1941
- vite: {
1942
- optional: true
1943
- },
1944
- vue: {
1945
- optional: true
1946
- }
1947
- },
1948
- devDependencies: {
1949
- "@astrojs/react": "7.0.1",
1950
- "@babel/core": "^7.29.0",
1951
- "@babel/types": "^7.29.0",
1952
- "@modules/annotation": "workspace:*",
1953
- "@modules/astro-editor": "workspace:*",
1954
- "@modules/file-parser": "workspace:*",
1955
- "@modules/frame-pool": "workspace:*",
1956
- "@modules/iframe-projection": "workspace:*",
1957
- "@modules/svelte-editor": "workspace:*",
1958
- "@modules/vue-editor": "workspace:*",
1959
- "@nuxt/kit": "^4.6.2",
1960
- "@types/babel__core": "^7.20.5",
1961
- "@types/node": "^25.0.8",
1962
- "@types/react": "catalog:",
1963
- "@types/react-dom": "catalog:",
1964
- "@vitejs/plugin-react": "catalog:",
1965
- "@vitejs/plugin-vue": "6.0.10",
1966
- astro: "7.3.8",
1967
- h3: "^1.15.11",
1968
- "magic-string": "^0.30.21",
1969
- nuxt: "^4.6.2",
1970
- playwright: "^1.58.2",
1971
- "react-dom": "catalog:",
1972
- "react-dom18": "npm:react-dom@18.3.1",
1973
- react18: "npm:react@18.3.1",
1974
- svelte: "5.56.9",
1975
- tsup: "^8.5.1",
1976
- typescript: "catalog:",
1977
- vite: "catalog:",
1978
- vitest: "catalog:",
1979
- vue: "3.5.44"
1980
- }
1981
- };
1982
-
1983
- // release-channel.ts
1984
- var TEMPO_SDK_CHANNEL = package_default.publishConfig.tag;
1985
- function sdkChannelGeneration(channel) {
1986
- if (typeof channel !== "string") return null;
1987
- const match = /^sdk-v([1-9]\d*)-latest$/.exec(channel);
1988
- return match ? Number(match[1]) : null;
1989
- }
1990
- if (sdkChannelGeneration(TEMPO_SDK_CHANNEL) === null) {
1991
- throw new Error("tempo-sdk publishConfig.tag must be sdk-v<N>-latest");
1992
- }
1993
-
1994
- // host-identity.ts
1995
- var TEMPO_WORKSPACE_NONCE_ENV = "TEMPO_WORKSPACE_NONCE";
1996
- var TEMPO_WORKSPACE_NONCE_META_NAME = "tempo-workspace-nonce";
1997
- var WORKSPACE_NONCE_RELATIVE_PATH = ".tempo/workspace-nonce";
1998
- var MAX_WORKSPACE_NONCE_LENGTH = 128;
1999
- function normalizeWorkspaceNonce(value) {
2000
- const nonce = value?.trim() ?? "";
2001
- return nonce.length > 0 && nonce.length <= MAX_WORKSPACE_NONCE_LENGTH ? nonce : "";
2002
- }
2003
- function readTempoWorkspaceNonce(root = process.cwd()) {
2004
- const fromEnvironment = normalizeWorkspaceNonce(
2005
- process.env[TEMPO_WORKSPACE_NONCE_ENV]
2006
- );
2007
- if (fromEnvironment) return fromEnvironment;
2008
- try {
2009
- return normalizeWorkspaceNonce(
2010
- (0, import_node_fs4.readFileSync)((0, import_node_path4.resolve)(root, WORKSPACE_NONCE_RELATIVE_PATH), "utf-8")
2011
- );
2012
- } catch {
2013
- return "";
2014
- }
2015
- }
2016
-
2017
- // sdk-package-files.ts
2018
- var import_node_fs5 = require("fs");
2019
- var import_node_path5 = require("path");
2020
- var SDK_PACKAGE_NAME = "tempo-sdk";
2021
- var SDK_NODE_MODULES_SEGMENT = `/node_modules/${SDK_PACKAGE_NAME}/`;
2022
- function createSdkFileMatcher() {
2023
- const ownerIsSdkByDirectory = /* @__PURE__ */ new Map();
2024
- const nearestPackageIsSdk = (startDirectory) => {
2025
- const visited = [];
2026
- let directory = startDirectory;
2027
- let isSdk = false;
2028
- while (true) {
2029
- const cached = ownerIsSdkByDirectory.get(directory);
2030
- if (cached !== void 0) {
2031
- isSdk = cached;
2032
- break;
2033
- }
2034
- visited.push(directory);
2035
- const manifest = readPackageManifest(directory);
2036
- if (manifest !== void 0) {
2037
- isSdk = manifest?.name === SDK_PACKAGE_NAME;
2038
- break;
2039
- }
2040
- const parent = (0, import_node_path5.dirname)(directory);
2041
- if (parent === directory) break;
2042
- directory = parent;
2043
- }
2044
- for (const entry of visited) ownerIsSdkByDirectory.set(entry, isSdk);
2045
- return isSdk;
2046
- };
2047
- return (file) => {
2048
- if (file.replace(/\\/g, "/").includes(SDK_NODE_MODULES_SEGMENT)) {
2049
- return true;
2050
- }
2051
- let realFile = file;
2052
- try {
2053
- realFile = import_node_fs5.realpathSync.native(file);
2054
- } catch {
2055
- }
2056
- return nearestPackageIsSdk((0, import_node_path5.dirname)(realFile));
2057
- };
2058
- }
2059
- function readPackageManifest(directory) {
2060
- let text;
2061
- try {
2062
- text = (0, import_node_fs5.readFileSync)((0, import_node_path5.join)(directory, "package.json"), "utf8");
2063
- } catch {
2064
- return void 0;
2065
- }
2066
- try {
2067
- const manifest = JSON.parse(text);
2068
- return manifest && typeof manifest === "object" ? manifest : null;
2069
- } catch {
2070
- return null;
2071
- }
2072
- }
2073
-
2074
- // nextjs-loader.ts
2075
- var ROOT_META_NAME = "tempo-project-root";
2076
- var cachedCanonicalRoot = null;
2077
- var cachedUserComputeProps;
2078
- var cachedComputeModulePath = null;
2079
- var isSdkFile = createSdkFileMatcher();
2080
- function _resetLoaderState() {
2081
- cachedCanonicalRoot = null;
2082
- cachedUserComputeProps = void 0;
2083
- cachedComputeModulePath = null;
2084
- }
2085
- function stripQueryAndHash(path2) {
2086
- const queryIdx = path2.indexOf("?");
2087
- const hashIdx = path2.indexOf("#");
2088
- let end = path2.length;
2089
- if (queryIdx !== -1) end = Math.min(end, queryIdx);
2090
- if (hashIdx !== -1) end = Math.min(end, hashIdx);
2091
- return path2.slice(0, end);
2092
- }
2093
- function resolveCanonicalRoot(rootContext) {
2094
- try {
2095
- return import_node_fs6.realpathSync.native(rootContext);
2096
- } catch {
2097
- return rootContext;
2098
- }
2099
- }
2100
- function isInNodeModules(path2) {
2101
- return path2.includes(`${import_node_path6.sep}node_modules${import_node_path6.sep}`);
2102
- }
2103
- function findFirstJSXElement(program, tagName) {
2104
- let result = null;
2105
- walk2(program, {
2106
- JSXElement(node) {
2107
- if (result) return;
2108
- const element = node;
2109
- if (getTagName(element.openingElement.name) === tagName) {
2110
- result = element;
2111
- }
2112
- }
2113
- });
2114
- return result;
2115
- }
2116
- function hasNamedMetaChild(headElement, metaName) {
2117
- for (const child of headElement.children ?? []) {
2118
- if (child.type !== "JSXElement") continue;
2119
- const childTag = getTagName(child.openingElement.name);
2120
- if (childTag !== "meta") continue;
2121
- for (const attr of child.openingElement.attributes ?? []) {
2122
- if (attr.type !== "JSXAttribute") continue;
2123
- if (getTagName(attr.name) !== "name") continue;
2124
- const value = attr.value;
2125
- if (value && value.type === "Literal" && value.value === metaName) {
2126
- return true;
2127
- }
2128
- }
2129
- }
2130
- return false;
2131
- }
2132
- function injectFirstChildMarkup(source, element, childMarkup) {
2133
- const opening = element.openingElement;
2134
- if (!opening.selfClosing) {
2135
- const insertPos = opening.end;
2136
- return source.slice(0, insertPos) + childMarkup + source.slice(insertPos);
2137
- }
2138
- const tagName = getTagName(opening.name);
2139
- const reopened = source.slice(opening.start, opening.end).replace(/\s*\/>$/, ">");
2140
- return source.slice(0, opening.start) + `${reopened}${childMarkup}</${tagName}>` + source.slice(opening.end);
2141
- }
2142
- function injectRootMetaIntoSource(source, filename, root) {
2143
- let parseResult;
2144
- try {
2145
- parseResult = (0, import_oxc_parser4.parseSync)(filename, source);
2146
- } catch {
2147
- return source;
2148
- }
2149
- const workspaceNonce = readTempoWorkspaceNonce(root);
2150
- const rootMetaTag = `<meta name="${ROOT_META_NAME}" content={${JSON.stringify(root)}} />`;
2151
- const nonceMetaTag = workspaceNonce ? `<meta name="${TEMPO_WORKSPACE_NONCE_META_NAME}" content={${JSON.stringify(workspaceNonce)}} />` : "";
2152
- const headElement = findFirstJSXElement(parseResult.program, "head");
2153
- if (headElement) {
2154
- const missingRoot = !hasNamedMetaChild(headElement, ROOT_META_NAME);
2155
- const missingNonce = nonceMetaTag.length > 0 && !hasNamedMetaChild(headElement, TEMPO_WORKSPACE_NONCE_META_NAME);
2156
- if (!missingRoot && !missingNonce) return source;
2157
- return injectFirstChildMarkup(
2158
- source,
2159
- headElement,
2160
- `${missingRoot ? rootMetaTag : ""}${missingNonce ? nonceMetaTag : ""}`
2161
- );
2162
- }
2163
- const htmlElement = findFirstJSXElement(parseResult.program, "html");
2164
- if (htmlElement) {
2165
- return injectFirstChildMarkup(
2166
- source,
2167
- htmlElement,
2168
- `<head>${rootMetaTag}${nonceMetaTag}</head>`
2169
- );
2170
- }
2171
- return source;
2172
- }
2173
- function injectRootMetaIntoAnnotatedSource(annotatedSource, filename, root) {
2174
- return injectRootMetaIntoSource(annotatedSource, filename, root);
2175
- }
2176
- function loadUserComputeProps(modulePath, canonicalRoot) {
2177
- const resolved = (0, import_node_path6.resolve)(canonicalRoot, modulePath);
2178
- const requireFromRoot = (0, import_node_module.createRequire)(`${canonicalRoot}/__tempo_loader__.js`);
2179
- const mod = requireFromRoot(resolved);
2180
- const fn = mod && (mod.default ?? mod);
2181
- if (typeof fn !== "function") {
2182
- return null;
2183
- }
2184
- return fn;
2185
- }
2186
- function diskTextOf(cleanPath, source) {
2187
- try {
2188
- const raw = (0, import_node_fs6.readFileSync)(cleanPath, "utf8");
2189
- if (raw.charCodeAt(0) === 65279 && raw.slice(1) === source) return raw;
2190
- } catch {
2191
- }
2192
- return source;
2193
- }
2194
- function readOptions() {
2195
- if (typeof this.getOptions === "function") {
2196
- return this.getOptions() ?? {};
2197
- }
2198
- if (typeof this.query === "string") {
2199
- return {};
2200
- }
2201
- return this.query ?? {};
2202
- }
2203
- function nextjsLoader(source) {
2204
- this.cacheable?.(true);
2205
- if (!process.env.TEMPO) return source;
2206
- const cleanPath = stripQueryAndHash(this.resourcePath ?? "");
2207
- if (!/\.(tsx|jsx)$/.test(cleanPath)) return source;
2208
- if (isInNodeModules(cleanPath) || isSdkFile(cleanPath)) return source;
2209
- const options = readOptions.call(this);
2210
- try {
2211
- if (cachedCanonicalRoot === null) {
2212
- cachedCanonicalRoot = resolveCanonicalRoot(this.rootContext);
2213
- }
2214
- const canonicalRoot = cachedCanonicalRoot;
2215
- const userModule = options.computeAnnotatedPropsModule;
2216
- if (userModule && userModule !== cachedComputeModulePath) {
2217
- try {
2218
- cachedUserComputeProps = loadUserComputeProps(
2219
- userModule,
2220
- canonicalRoot
2221
- );
2222
- } catch {
2223
- cachedUserComputeProps = null;
2224
- }
2225
- cachedComputeModulePath = userModule;
2226
- } else if (cachedUserComputeProps === void 0) {
2227
- cachedUserComputeProps = null;
2228
- }
2229
- const userComputeProps = cachedUserComputeProps;
2230
- const filepath = (0, import_node_path6.relative)(canonicalRoot, cleanPath);
2231
- const modifiedtsMs = Math.trunc((0, import_node_fs6.statSync)(cleanPath).mtimeMs);
2232
- const text = diskTextOf(cleanPath, source);
2233
- const sourceVersion = sourceVersionHash(text);
2234
- const componentReferences = canvasComponentAnnotations(
2235
- cleanPath,
2236
- text,
2237
- void 0,
2238
- canonicalRoot
2239
- );
2240
- const annotated = annotateFile(text, cleanPath, (info) => ({
2241
- ...componentReferences.get(info.element.openingElement.start),
2242
- ...computeTempoAnnotatedProps({
2243
- info,
2244
- filepath,
2245
- modifiedtsMs,
2246
- sourceVersion,
2247
- computeAnnotatedProps: userComputeProps ?? void 0
2248
- })
2249
- }));
2250
- let finalSource = annotated.annotatedSource;
2251
- if (options.autoInjectRootMeta !== false) {
2252
- finalSource = injectRootMetaIntoAnnotatedSource(
2253
- finalSource,
2254
- cleanPath,
2255
- canonicalRoot
2256
- );
2257
- }
2258
- if (annotated.parseResult.errors.length > 0) return source;
2259
- return appendModuleVersionRecord(
2260
- finalSource,
2261
- filepath,
2262
- modifiedtsMs,
2263
- sourceVersion
2264
- );
2265
- } catch {
2266
- return source;
2267
- }
2268
- }
2269
- var nextjs_loader_default = nextjsLoader;
2270
- // Annotate the CommonJS export names for ESM import in node:
2271
- 0 && (module.exports = {
2272
- _resetLoaderState,
2273
- injectRootMetaIntoAnnotatedSource,
2274
- injectRootMetaIntoSource,
2275
- nextjsLoader
2276
- });
2277
- //# sourceMappingURL=nextjs-loader.cjs.map
1
+ "use strict";var R=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var i=(t,e)=>R(t,"name",{value:e,configurable:!0});var D=(t,e)=>{for(var o in e)R(t,o,{get:e[o],enumerable:!0})},rt=(t,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ot(e))!nt.call(t,r)&&r!==o&&R(t,r,{get:()=>e[r],enumerable:!(s=et(e,r))||s.enumerable});return t};var st=t=>rt(R({},"__esModule",{value:!0}),t);var xt={};D(xt,{_resetLoaderState:()=>ht,default:()=>Rt,injectRootMetaIntoAnnotatedSource:()=>yt,injectRootMetaIntoSource:()=>Tt,nextjsLoader:()=>Z});module.exports=st(xt);var g=require("path");var I=require("crypto"),m=require("fs"),l=require("module"),n=require("path"),f=require("url");var N={};D(N,{TEMPO_HOST_IDENTITY_CAPABILITY_HEADER:()=>ct,TEMPO_HOST_IDENTITY_CONTRACT_VERSION:()=>V,TEMPO_HOST_IDENTITY_ENDPOINT:()=>at,TEMPO_VUE_ANNOTATION_PLUGIN_NAME:()=>dt,TEMPO_WORKSPACE_NONCE_ENV:()=>B,TEMPO_WORKSPACE_NONCE_META_NAME:()=>ut,createTempoHostIdentity:()=>ft,readTempoWorkspaceNonce:()=>J});var U=require("fs"),q=require("path");var L={version:"0.0.102"};var W="latest";var at="/__tempo/identity",ct="x-tempo-host-identity",V=1,B="TEMPO_WORKSPACE_NONCE",ut="tempo-workspace-nonce",pt=".tempo/workspace-nonce",mt=128,dt="tempo-vue-source-annotation";function K(t){let e=t?.trim()??"";return e.length>0&&e.length<=mt?e:""}i(K,"normalizeWorkspaceNonce");function J(t=process.cwd()){let e=K(process.env[B]);if(e)return e;try{return K((0,U.readFileSync)((0,q.resolve)(t,pt),"utf-8"))}catch{return""}}i(J,"readTempoWorkspaceNonce");function ft(t,e={}){return{tempoHost:!0,contractVersion:V,workspaceNonce:J(e.root),sdkVersion:L.version,sdkChannel:W,tempoRuntimeContract:1,pluginActive:e.pluginActive??!!process.env.TEMPO,framework:t,...e.capabilities?{capabilities:e.capabilities}:{}}}i(ft,"createTempoHostIdentity");var z={};var b=1,E="TEMPO_SDK_RUNTIME_PATH",S=typeof z.url=="string"?z.url:(0,f.pathToFileURL)(__filename).href,A=(0,l.createRequire)(S),G=new Map,x=new Map,Y=new Map,O;function lt(t){if(!O){let o=(0,n.dirname)((0,f.fileURLToPath)(S));for(;;){try{if(JSON.parse((0,m.readFileSync)((0,n.resolve)(o,"package.json"),"utf8")).name==="tempo-sdk"){O=o;break}}catch{}let s=(0,n.dirname)(o);if(o===s)throw c("the SDK package directory could not be found");o=s}}let e=(0,f.fileURLToPath)(S).endsWith(".ts");return(0,f.pathToFileURL)((0,n.resolve)(O,e?t:`dist/${t.replace(/\.tsx?$/,".js")}`)).href}i(lt,"sdkModuleUrl");function c(t){return new Error(`Tempo SDK runtime unavailable: ${t}. Start this project with an updated Tempo host, or provision its matching runtime and set ${E}.`)}i(c,"runtimeError");function X(){let t=process.env[E];if(!t||!(0,n.isAbsolute)(t))throw c("an absolute runtime directory was not supplied");let e=(0,n.resolve)(t),o;try{o=JSON.parse((0,m.readFileSync)((0,n.resolve)(e,"runtime.json"),"utf8"))}catch{throw c("runtime.json could not be read")}if(o?.tempoRuntimeContract!==b)throw c(`contract ${o?.tempoRuntimeContract} does not match ${b}`);return{root:e,manifest:o}}i(X,"readRuntimeManifest");function w(t,e,o){if(!o||typeof o.file!="string"||!/^[a-f0-9]{64}$/.test(o.sha256))throw c(`the ${e} entry is missing or invalid`);let s=(0,n.resolve)(t,o.file),r=(0,n.relative)(t,s);if((0,n.isAbsolute)(r)||r===".."||r.startsWith(`..${n.sep}`))throw c(`the ${e} entry escapes its runtime directory`);let u;try{let p=(0,n.relative)((0,m.realpathSync)(t),(0,m.realpathSync)(s));if((0,n.isAbsolute)(p)||p===".."||p.startsWith(`..${n.sep}`))throw c(`the ${e} entry escapes its runtime directory`);u=(0,m.readFileSync)(s)}catch{throw c(`the ${e} artifact could not be read`)}if((0,I.createHash)("sha256").update(u).digest("hex")!==o.sha256)throw c(`the ${e} artifact failed its integrity check`);return s}i(w,"verifyArtifact");function Q(t){let e=process.env[E];if(!e||!(0,n.isAbsolute)(e))throw c("an absolute runtime directory was not supplied");let o=(0,n.resolve)(e),s=`${o}\0${t}`,r=Y.get(s);if(r)return r;let{manifest:u}=X(),p=u.node?.[t],T=w(o,t,p),d=u.browser,y=d&&w(o,"browser",d),h={sha256:d?(0,I.createHash)("sha256").update(p.sha256).update(d.sha256).digest("hex"):p.sha256,dependencies:[(0,n.resolve)(o,"runtime.json"),T,...y?[y]:[]]};return Y.set(s,h),h}i(Q,"nodeRuntimeIdentity");function C(t){if(typeof t=="string")return t;if(Array.isArray(t)){for(let e of t){let o=C(e);if(o)return o}return}if(!(!t||typeof t!="object"))for(let[e,o]of Object.entries(t)){if(!(["node","import","default"].includes(e)||e==="module-sync"&&process.features.require_module))continue;let r=C(o);if(r)return r}}i(C,"importExportTarget");function gt(t,e){if((0,l.isBuiltin)(t))return t;let o=e.resolve(`${t}/package.json`),s=JSON.parse((0,m.readFileSync)(o,"utf8")),r=s.exports,u=r===void 0?s.module??s.main:C(r?.["."]??r);if(typeof u!="string")throw c(`${t} has no supported Node import entry`);return(0,f.pathToFileURL)((0,n.resolve)((0,n.dirname)(o),u)).href}i(gt,"resolveProjectImport");function j(t,e=process.cwd(),o={}){let s=process.env[E];if(!s||!(0,n.isAbsolute)(s))throw c("an absolute runtime directory was not supplied");let r=(0,n.resolve)(s),u=(0,n.resolve)(e),p=`${r}\0${u}\0${t}`;if(x.has(p))return x.get(p);let{manifest:T}=X(),d=T.node?.[t],y=w(r,t,d);A(w(r,"serverBrowser",T.serverBrowser));let h=`${r}\0${u}\0${d.file}`,M=G.get(h);if(M){let a=M.getEntry(t);return x.set(p,a),a}let k=A(y);if(k.tempoRuntimeContract!==b||typeof k.createRuntime!="function")throw c(`the ${t} factory has an incompatible contract`);let P=(0,l.createRequire)((0,n.resolve)(u,"package.json")),v=i(a=>(0,l.isBuiltin)(a)||a==="oxc-parser"||a.startsWith("oxc-parser/")||a.startsWith("@astrojs/compiler-")?A:P,"from"),$=Object.assign(a=>a==="@tempo-sdk-public/host-identity"?N:Object.hasOwn(o,a)?o[a]:v(a)(a),P,{resolve:i((a,tt)=>v(a).resolve(a,tt),"resolve")}),H=k.createRuntime({require:$,projectRoot:u,import:i(a=>import(gt(a,$)),"import"),sdkModuleUrl:lt});G.set(h,H);let F=H.getEntry(t);return x.set(p,F),F}i(j,"getNodeRuntime");function _(t,e){let o=i(function(...s){let r=j(t)[e];if(typeof r!="function")throw c(`${t}.${e} is missing`);return Reflect.apply(r,this,s)},"delegate");return Object.defineProperty(o,"name",{value:e}),o}i(_,"nodeRuntimeFunction");var ht=_("nextjs-loader","_resetLoaderState"),Tt=_("nextjs-loader","injectRootMetaIntoSource"),yt=_("nextjs-loader","injectRootMetaIntoAnnotatedSource"),Z=i(function(t){if(!process.env.TEMPO)return this.cacheable?.(!0),t;for(let e of Q("nextjs-loader").dependencies){let o=(0,g.relative)(this.rootContext,e);(0,g.isAbsolute)(o)||o===".."||o.startsWith(`..${g.sep}`)||this.addDependency?.(e)}return j("nextjs-loader",this.rootContext).nextjsLoader.call(this,t)},"nextjsLoader"),Rt=Z;0&&(module.exports={_resetLoaderState,injectRootMetaIntoAnnotatedSource,injectRootMetaIntoSource,nextjsLoader});