@bgub/fig-tanstack-start 0.0.0-tegami-trusted-publish-setup → 0.1.0-alpha.2

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 (42) hide show
  1. package/CHANGELOG.md +225 -0
  2. package/LICENSE +21 -0
  3. package/README.md +280 -3
  4. package/dist/client-B2okTbp3.js +29 -0
  5. package/dist/client-B2okTbp3.js.map +1 -0
  6. package/dist/client.d.ts +13 -0
  7. package/dist/client.js +2 -0
  8. package/dist/data.d.ts +14 -0
  9. package/dist/data.js +34 -0
  10. package/dist/data.js.map +1 -0
  11. package/dist/default-entry/client.d.ts +1 -0
  12. package/dist/default-entry/client.js +7 -0
  13. package/dist/default-entry/client.js.map +1 -0
  14. package/dist/default-entry/server.d.ts +4 -0
  15. package/dist/default-entry/server.js +6 -0
  16. package/dist/default-entry/server.js.map +1 -0
  17. package/dist/default-entry/start.d.ts +4 -0
  18. package/dist/default-entry/start.js +6 -0
  19. package/dist/default-entry/start.js.map +1 -0
  20. package/dist/payload-assets-eHfSAMbN.js +14 -0
  21. package/dist/payload-assets-eHfSAMbN.js.map +1 -0
  22. package/dist/payload-internal-CZhfVhwH.js +168 -0
  23. package/dist/payload-internal-CZhfVhwH.js.map +1 -0
  24. package/dist/payload.d.ts +19 -0
  25. package/dist/payload.js +38 -0
  26. package/dist/payload.js.map +1 -0
  27. package/dist/plugin/vite.d.ts +6 -0
  28. package/dist/plugin/vite.js +857 -0
  29. package/dist/plugin/vite.js.map +1 -0
  30. package/dist/server.d.ts +20 -0
  31. package/dist/server.js +111 -0
  32. package/dist/server.js.map +1 -0
  33. package/dist/start-context-DZ2gsb5m.js +12 -0
  34. package/dist/start-context-DZ2gsb5m.js.map +1 -0
  35. package/dist/storage-context.d.ts +9 -0
  36. package/dist/storage-context.js +21 -0
  37. package/dist/storage-context.js.map +1 -0
  38. package/dist/store-CibAGqiI.js +13 -0
  39. package/dist/store-CibAGqiI.js.map +1 -0
  40. package/dist/transport-DKcSG44e.js +33 -0
  41. package/dist/transport-DKcSG44e.js.map +1 -0
  42. package/package.json +90 -3
@@ -0,0 +1,857 @@
1
+ import { n as payloadStylesheetsSymbolKey } from "../payload-assets-eHfSAMbN.js";
2
+ import { START_ENVIRONMENT_NAMES, tanStackStartVite } from "@tanstack/start-plugin-core/vite";
3
+ import { figRefresh } from "@bgub/fig-vite";
4
+ import { fileURLToPath } from "node:url";
5
+ import { Buffer as Buffer$1 } from "node:buffer";
6
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
7
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import * as babel from "@babel/core";
9
+ import presetTypescript from "@babel/preset-typescript";
10
+ //#region src/plugin/module-ids.ts
11
+ const payloadManifestDefinitionQuery = "fig-payload-manifest";
12
+ const payloadModuleQuery = "fig-payload-module";
13
+ const payloadReferenceQuery = "fig-payload-reference";
14
+ function cleanModuleId(id) {
15
+ const query = id.indexOf("?");
16
+ return query === -1 ? id : id.slice(0, query);
17
+ }
18
+ function moduleQueryValue(id, name) {
19
+ const query = id.indexOf("?");
20
+ if (query === -1) return void 0;
21
+ const hash = id.indexOf("#", query);
22
+ return new URLSearchParams(id.slice(query + 1, hash === -1 ? void 0 : hash)).get(name) ?? void 0;
23
+ }
24
+ function hasModuleQuery(id, name) {
25
+ return moduleQueryValue(id, name) !== void 0;
26
+ }
27
+ function withModuleQuery(source, name, value) {
28
+ const hash = source.indexOf("#");
29
+ const suffix = hash === -1 ? "" : source.slice(hash);
30
+ const path = hash === -1 ? source : source.slice(0, hash);
31
+ return `${path}${path.includes("?") ? "&" : "?"}${name}=${encodeURIComponent(value)}${suffix}`;
32
+ }
33
+ function encodeOpaqueId(id) {
34
+ return Buffer$1.from(id).toString("base64url");
35
+ }
36
+ function decodeOpaqueId(id) {
37
+ return Buffer$1.from(id, "base64url").toString();
38
+ }
39
+ function toViteModulePath(root, moduleId) {
40
+ const clean = cleanModuleId(moduleId);
41
+ const path = isAbsolute(clean) ? relative(root, clean) : clean;
42
+ const normalized = normalizePath(path);
43
+ return isAbsolute(path) || normalized.startsWith("../") ? toViteFsPath(clean) : `/${normalized.replace(/^\/+/, "")}`;
44
+ }
45
+ function toViteFsPath(path) {
46
+ return `/@fs/${normalizePath(path).replace(/^\/+/, "")}`;
47
+ }
48
+ function normalizePath(path) {
49
+ return path.split(sep).join("/").replaceAll("\\", "/");
50
+ }
51
+ //#endregion
52
+ //#region src/plugin/compatibility-profile.ts
53
+ const tanStackCompatibilityProfile = {
54
+ id: "tanstack-start-core-1.171",
55
+ framework: "solid",
56
+ packages: {
57
+ figRouter: "@bgub/fig-tanstack-router",
58
+ figStart: "@bgub/fig-tanstack-start",
59
+ frameworkRouter: "@tanstack/solid-router",
60
+ frameworkStart: "@tanstack/solid-start",
61
+ startClient: "@tanstack/start-client-core",
62
+ startServer: "@tanstack/start-server-core"
63
+ },
64
+ versions: {
65
+ routerCore: "1.171.15",
66
+ startClientCore: "1.170.14",
67
+ startPluginCore: "1.171.22",
68
+ startServerCore: "1.169.17"
69
+ }
70
+ };
71
+ function createCompilerRpcModules(resolveDependency) {
72
+ const { frameworkStart, startClient, startServer } = tanStackCompatibilityProfile.packages;
73
+ return [
74
+ {
75
+ source: `${frameworkStart}/client-rpc`,
76
+ id: "\0fig-tanstack-start:client-rpc",
77
+ code: `export { createClientRpc } from "${startClient}/client-rpc";`
78
+ },
79
+ {
80
+ source: `${frameworkStart}/server-rpc`,
81
+ id: "\0fig-tanstack-start:server-rpc",
82
+ code: `export { createServerRpc } from ${JSON.stringify(resolveDependency(`${startServer}/createServerRpc`))};`
83
+ },
84
+ {
85
+ source: `${frameworkStart}/ssr-rpc`,
86
+ id: "\0fig-tanstack-start:ssr-rpc",
87
+ code: `export { createSsrRpc } from ${JSON.stringify(resolveDependency(`${startServer}/createSsrRpc`))};`
88
+ }
89
+ ];
90
+ }
91
+ function createDefaultServerEntry() {
92
+ const { figStart } = tanStackCompatibilityProfile.packages;
93
+ return [
94
+ `import { createFigStartHandler } from ${JSON.stringify(`${figStart}/server`)};`,
95
+ "const fetch = createFigStartHandler();",
96
+ "export default { fetch };"
97
+ ].join("\n");
98
+ }
99
+ function rewriteFrameworkImports(code) {
100
+ const { figStart, frameworkStart } = tanStackCompatibilityProfile.packages;
101
+ return code.replace(new RegExp(`\\b(from|import)\\s*(\\(\\s*)?(["'])${escapeRegExp(figStart)}\\3`, "g"), (_match, keyword, parenthesis, quote) => `${keyword}${parenthesis === void 0 ? " " : parenthesis}${quote}${frameworkStart}${quote}`);
102
+ }
103
+ function incompatibleRuntimeModules(moduleIds) {
104
+ const { frameworkRouter, frameworkStart } = tanStackCompatibilityProfile.packages;
105
+ const forbiddenPackages = [frameworkRouter, frameworkStart];
106
+ return [...moduleIds].filter((id) => {
107
+ const normalized = id.replaceAll("\\", "/");
108
+ return forbiddenPackages.some((packageName) => normalized.includes(`/node_modules/${packageName}/`));
109
+ });
110
+ }
111
+ function escapeRegExp(value) {
112
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
113
+ }
114
+ //#endregion
115
+ //#region src/plugin/compatibility-vite.ts
116
+ const { figRouter: figRouterPackage, figStart: figTanStackStartPackage, frameworkRouter: tanstackRouterPackage, frameworkStart: tanstackStartPackage, startClient: tanstackStartClientPackage } = tanStackCompatibilityProfile.packages;
117
+ const resolveDependency = (id) => fileURLToPath(import.meta.resolve(id));
118
+ const tanstackStartClientModules = [
119
+ tanstackStartClientPackage,
120
+ `${tanstackStartClientPackage}/client`,
121
+ `${tanstackStartClientPackage}/client-rpc`
122
+ ];
123
+ const tanstackStartClientAliases = tanstackStartClientModules.map((id) => ({
124
+ find: new RegExp(`^${id}$`),
125
+ replacement: resolveDependency(id)
126
+ }));
127
+ const optimizedClientModules = ["@tanstack/router-core/ssr/client"];
128
+ const applicationEntryIds = /* @__PURE__ */ new Set(["#tanstack-router-entry", "#tanstack-start-entry"]);
129
+ const storageContextPath = fileURLToPath(new URL("../storage-context.js", import.meta.url));
130
+ const defaultEntryPaths = {
131
+ client: fileURLToPath(new URL("../default-entry/client.js", import.meta.url)),
132
+ server: fileURLToPath(new URL("../default-entry/server.js", import.meta.url)),
133
+ start: fileURLToPath(new URL("../default-entry/start.js", import.meta.url))
134
+ };
135
+ const compilerRpcModules = createCompilerRpcModules(resolveDependency);
136
+ function startCompatibilityPlugin() {
137
+ const applicationEntryUrls = /* @__PURE__ */ new Map();
138
+ const optimizerApplicationEntries = {
139
+ name: "fig-tanstack-start:optimizer-application-entries",
140
+ resolveId(source) {
141
+ const id = applicationEntryUrls.get(source);
142
+ return id === void 0 ? null : {
143
+ external: true,
144
+ id
145
+ };
146
+ }
147
+ };
148
+ return {
149
+ name: "fig-tanstack-start:compatibility",
150
+ enforce: "pre",
151
+ config() {
152
+ return { resolve: {
153
+ alias: [
154
+ ...tanstackStartClientAliases,
155
+ {
156
+ find: /^@tanstack\/start-storage-context$/,
157
+ replacement: storageContextPath
158
+ },
159
+ {
160
+ find: new RegExp(`^${tanstackRouterPackage}$`),
161
+ replacement: figRouterPackage
162
+ },
163
+ {
164
+ find: new RegExp(`^${tanstackStartPackage}$`),
165
+ replacement: figTanStackStartPackage
166
+ }
167
+ ],
168
+ dedupe: [figTanStackStartPackage, figRouterPackage]
169
+ } };
170
+ },
171
+ configEnvironment(environmentName, environment) {
172
+ if (environmentName !== START_ENVIRONMENT_NAMES.client) return void 0;
173
+ const optimizerPlugins = environment.optimizeDeps?.rolldownOptions?.plugins;
174
+ return { optimizeDeps: {
175
+ include: [...environment.optimizeDeps?.include ?? [], ...optimizedClientModules],
176
+ exclude: [
177
+ ...environment.optimizeDeps?.exclude ?? [],
178
+ ...tanstackStartClientModules,
179
+ figTanStackStartPackage,
180
+ figRouterPackage
181
+ ],
182
+ rolldownOptions: {
183
+ ...environment.optimizeDeps?.rolldownOptions,
184
+ plugins: [...optimizerPlugins === void 0 ? [] : [optimizerPlugins], optimizerApplicationEntries]
185
+ }
186
+ } };
187
+ },
188
+ configResolved(config) {
189
+ for (const alias of config.resolve.alias) if (typeof alias.find === "string" && applicationEntryIds.has(alias.find)) applicationEntryUrls.set(alias.find, toViteFsPath(alias.replacement));
190
+ },
191
+ generateBundle(_options, bundle) {
192
+ if (this.environment.name !== START_ENVIRONMENT_NAMES.client) return;
193
+ const incompatible = incompatibleRuntimeModules(Object.values(bundle).flatMap((output) => output.type === "chunk" ? Object.entries(output.modules).flatMap(([id, module]) => module.renderedLength === 0 ? [] : [id]) : []));
194
+ if (incompatible.length === 0) return;
195
+ throw new Error(`${tanStackCompatibilityProfile.id} resolved compatibility-only Solid modules into the client runtime:\n${incompatible.join("\n")}`);
196
+ },
197
+ resolveId(source) {
198
+ return compilerRpcModules.find((module) => module.source === source)?.id;
199
+ },
200
+ load(id) {
201
+ const rpcModule = compilerRpcModules.find((module) => module.id === id);
202
+ if (rpcModule !== void 0) return rpcModule.code;
203
+ if (id === defaultEntryPaths.server) return createDefaultServerEntry();
204
+ },
205
+ transform(code) {
206
+ const rewritten = rewriteFrameworkImports(code);
207
+ return rewritten === code ? null : {
208
+ code: rewritten,
209
+ map: null
210
+ };
211
+ }
212
+ };
213
+ }
214
+ //#endregion
215
+ //#region src/plugin/compiler-options.ts
216
+ const payloadPackageId = "@bgub/fig-tanstack-start/payload";
217
+ const serverPackageId = "@bgub/fig-tanstack-start/server";
218
+ const sourceModuleExtensions = [
219
+ "js",
220
+ "jsx",
221
+ "ts",
222
+ "tsx",
223
+ "cjs",
224
+ "mjs",
225
+ "cts",
226
+ "mts"
227
+ ];
228
+ const sourceModulePattern = new RegExp(`\\.(?:${sourceModuleExtensions.join("|")})$`);
229
+ function babelOptions(filename) {
230
+ return {
231
+ babelrc: false,
232
+ configFile: false,
233
+ filename,
234
+ presets: [[presetTypescript, {
235
+ ignoreExtensions: true,
236
+ onlyRemoveTypeImports: true
237
+ }]],
238
+ parserOpts: { plugins: filename.endsWith("x") ? ["jsx"] : [] }
239
+ };
240
+ }
241
+ function isSourceModule(id) {
242
+ return sourceModulePattern.test(id);
243
+ }
244
+ function isComponentName(name) {
245
+ const first = name.codePointAt(0);
246
+ return first !== void 0 && first >= 65 && first <= 90;
247
+ }
248
+ function isImportedBinding(path, localName, importedName, source) {
249
+ const binding = path.scope.getBinding(localName);
250
+ if (!binding?.path.isImportSpecifier()) return false;
251
+ const imported = binding.path.node.imported;
252
+ return (imported.type === "Identifier" ? imported.name : imported.value) === importedName && binding.path.parentPath.isImportDeclaration() && binding.path.parentPath.node.source.value === source;
253
+ }
254
+ const resolvedPayloadManifestId = `\0virtual:fig-tanstack-start/payload-manifest`;
255
+ function isomorphicReferenceId(root, moduleId, exportName) {
256
+ return `${toViteModulePath(root, moduleId)}#${exportName}`;
257
+ }
258
+ function payloadManifestDefinitionCode(references) {
259
+ return `export const references = {${references.map((reference) => {
260
+ const moduleId = withModuleQuery(reference.resolvedModuleId, payloadReferenceQuery, encodeOpaqueId(reference.referenceId));
261
+ return `${JSON.stringify(reference.referenceId)}: {
262
+ load: () => import(${JSON.stringify(moduleId)}).then((module) => module[${JSON.stringify(reference.importedName)}]),
263
+ stylesheets: ${JSON.stringify(reference.developmentStylesheetHrefs)},
264
+ }`;
265
+ }).join(",\n")}};`;
266
+ }
267
+ function payloadManifestRuntimeCode(clientStylesheets) {
268
+ const assets = JSON.stringify(Object.fromEntries(clientStylesheets));
269
+ return `import { stylesheet } from "@bgub/fig";
270
+ import { createPayloadClientReferenceResolver } from "@bgub/fig/payload";
271
+
272
+ const definitions = import.meta.glob([
273
+ "/**/*.{${sourceModuleExtensions.join(",")}}",
274
+ "!/**/*.d.ts",
275
+ "!/**/*.test.*",
276
+ "!/**/*.spec.*",
277
+ "!/**/__tests__/**",
278
+ "!/**/dist/**",
279
+ "!/**/node_modules/**",
280
+ ], {
281
+ eager: true,
282
+ import: "references",
283
+ query: "?${payloadManifestDefinitionQuery}",
284
+ });
285
+ const references = Object.assign({}, ...Object.values(definitions));
286
+ const clientStylesheets = ${assets};
287
+
288
+ export const resolveIsomorphicReference = createPayloadClientReferenceResolver(
289
+ (reference) => references[reference.id]?.load(),
290
+ );
291
+
292
+ export function compiledIsomorphicReferenceAssets({ id }) {
293
+ const hrefs = clientStylesheets[id] ?? references[id]?.stylesheets ?? [];
294
+ return hrefs.map((href) => stylesheet(href, { precedence: "isomorphic" }));
295
+ }`;
296
+ }
297
+ function payloadReferenceIds(moduleIds) {
298
+ const ids = /* @__PURE__ */ new Set();
299
+ for (const moduleId of moduleIds) {
300
+ const id = moduleQueryValue(moduleId, payloadReferenceQuery);
301
+ if (id !== void 0) ids.add(decodeOpaqueId(id));
302
+ }
303
+ return [...ids];
304
+ }
305
+ //#endregion
306
+ //#region src/plugin/isomorphic-compiler.ts
307
+ function isomorphicBoundaryAnalysisPlugin(imports) {
308
+ return () => ({
309
+ name: "fig-tanstack-start-isomorphic-boundary-analysis",
310
+ visitor: { Program(path) {
311
+ const seen = /* @__PURE__ */ new Set();
312
+ path.traverse({ JSXOpeningElement(elementPath) {
313
+ if (elementPath.node.name.type !== "JSXIdentifier" || !isIsomorphicBoundary(elementPath, elementPath.node.name.name)) return;
314
+ const component = isomorphicComponentAttribute(elementPath);
315
+ const imported = importedComponent(elementPath, component.node.name);
316
+ const key = `${imported.source}\0${imported.importedName}\0${component.node.name}`;
317
+ if (seen.has(key)) return;
318
+ seen.add(key);
319
+ imports.push({
320
+ ...imported,
321
+ localName: component.node.name
322
+ });
323
+ } });
324
+ } }
325
+ });
326
+ }
327
+ function rewriteIsomorphicBoundaries(path, t, references) {
328
+ if (references.length === 0) return void 0;
329
+ const byLocalName = new Map(references.map((reference) => [reference.localName, reference]));
330
+ const createReference = path.scope.generateUidIdentifier("createIsomorphicReference");
331
+ let count = 0;
332
+ path.traverse({ JSXOpeningElement(elementPath) {
333
+ if (elementPath.node.name.type !== "JSXIdentifier" || !isIsomorphicBoundary(elementPath, elementPath.node.name.name)) return;
334
+ const component = isomorphicComponentAttribute(elementPath);
335
+ const reference = byLocalName.get(component.node.name);
336
+ if (reference === void 0) return;
337
+ component.replaceWith(t.callExpression(t.cloneNode(createReference), [t.stringLiteral(reference.referenceId)]));
338
+ count += 1;
339
+ } });
340
+ if (count === 0) return void 0;
341
+ path.scope.crawl();
342
+ for (const localName of byLocalName.keys()) {
343
+ const binding = path.scope.getBinding(localName);
344
+ if (binding?.referenced || !binding?.path.isImportSpecifier() && !binding?.path.isImportDefaultSpecifier()) continue;
345
+ const declaration = binding.path.parentPath;
346
+ binding.path.remove();
347
+ if (declaration.isImportDeclaration() && declaration.node.specifiers.length === 0) declaration.remove();
348
+ }
349
+ return createReference;
350
+ }
351
+ function isIsomorphicBoundary(path, localName) {
352
+ return isImportedBinding(path, localName, "Isomorphic", payloadPackageId);
353
+ }
354
+ function isomorphicComponentAttribute(path) {
355
+ const attribute = path.get("attributes").find((candidate) => candidate.isJSXAttribute() && candidate.node.name.type === "JSXIdentifier" && candidate.node.name.name === "component");
356
+ if (attribute === void 0 || !attribute.isJSXAttribute()) throw path.buildCodeFrameError("Isomorphic requires a component prop containing a statically imported component.");
357
+ const value = attribute.get("value");
358
+ if (!value.isJSXExpressionContainer()) throw attribute.buildCodeFrameError("Isomorphic component must be a statically imported component identifier.");
359
+ const expression = value.get("expression");
360
+ if (Array.isArray(expression) || !expression.isIdentifier()) throw value.buildCodeFrameError("Isomorphic component must be a statically imported component identifier.");
361
+ return expression;
362
+ }
363
+ function importedComponent(path, localName) {
364
+ const binding = path.scope.getBinding(localName);
365
+ if (binding === void 0 || !binding.path.isImportSpecifier() && !binding.path.isImportDefaultSpecifier() || !binding.path.parentPath.isImportDeclaration()) throw path.buildCodeFrameError("Isomorphic component must be a statically imported component identifier.");
366
+ return {
367
+ importedName: binding.path.isImportDefaultSpecifier() ? "default" : binding.path.node.imported.type === "Identifier" ? binding.path.node.imported.name : binding.path.node.imported.value,
368
+ source: binding.path.parentPath.node.source.value
369
+ };
370
+ }
371
+ //#endregion
372
+ //#region src/plugin/payload-stylesheet-compiler.ts
373
+ function stylesheetImportAnalysisPlugin(stylesheets) {
374
+ return () => ({
375
+ name: "fig-tanstack-start-stylesheet-import-analysis",
376
+ visitor: { ImportDeclaration(path) {
377
+ const source = path.node.source.value;
378
+ if (isStylesheetSpecifier(source)) stylesheets.push(source);
379
+ } }
380
+ });
381
+ }
382
+ function rewriteStylesheetImports(path, t) {
383
+ const hrefs = [];
384
+ for (const statement of path.get("body")) {
385
+ if (!statement.isImportDeclaration()) continue;
386
+ const source = statement.node.source.value;
387
+ if (!isStylesheetSpecifier(source)) continue;
388
+ const existingUrl = hasUrlQuery(source);
389
+ const defaultSpecifier = statement.node.specifiers.find((specifier) => t.isImportDefaultSpecifier(specifier));
390
+ if (existingUrl && defaultSpecifier !== void 0) {
391
+ hrefs.push(defaultSpecifier.local);
392
+ continue;
393
+ }
394
+ const local = path.scope.generateUidIdentifier("figPayloadStylesheet");
395
+ if (statement.node.specifiers.length === 0) {
396
+ statement.node.source = t.stringLiteral(withUrlQuery(source));
397
+ statement.node.specifiers.push(t.importDefaultSpecifier(local));
398
+ } else statement.insertAfter(t.importDeclaration([t.importDefaultSpecifier(local)], t.stringLiteral(withUrlQuery(source))));
399
+ hrefs.push(local);
400
+ }
401
+ return hrefs;
402
+ }
403
+ function collectComponentNames(path, t) {
404
+ const names = /* @__PURE__ */ new Set();
405
+ for (const statement of path.get("body")) {
406
+ const declaration = statement.isExportNamedDeclaration() || statement.isExportDefaultDeclaration() ? statement.get("declaration") : statement;
407
+ if (Array.isArray(declaration)) continue;
408
+ if (declaration.isFunctionDeclaration()) {
409
+ const name = declaration.node.id?.name;
410
+ if (name !== void 0 && isComponentName(name)) names.add(name);
411
+ continue;
412
+ }
413
+ if (!declaration.isVariableDeclaration()) continue;
414
+ for (const declarator of declaration.node.declarations) if (t.isIdentifier(declarator.id) && isComponentName(declarator.id.name) && (t.isArrowFunctionExpression(declarator.init) || t.isFunctionExpression(declarator.init))) names.add(declarator.id.name);
415
+ }
416
+ return [...names];
417
+ }
418
+ function isStylesheetSpecifier(source) {
419
+ const path = cleanModuleId(source);
420
+ return /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)$/.test(path);
421
+ }
422
+ function hasUrlQuery(source) {
423
+ return hasModuleQuery(source, "url");
424
+ }
425
+ function withUrlQuery(source) {
426
+ if (hasUrlQuery(source)) return source;
427
+ return `${source}${source.includes("?") ? "&" : "?"}url`;
428
+ }
429
+ //#endregion
430
+ //#region src/plugin/payload-compiler.ts
431
+ const payloadRuntimeId = "virtual:fig-tanstack-start/payload-runtime";
432
+ const resolvedPayloadRuntimeId = `\0${payloadRuntimeId}`;
433
+ const figRuntimePackageIds = [
434
+ "@bgub/fig",
435
+ "@bgub/fig-devtools",
436
+ "@bgub/fig-dom",
437
+ "@bgub/fig-reconciler",
438
+ "@bgub/fig-refresh",
439
+ "@bgub/fig-server",
440
+ "@bgub/fig-tanstack-router",
441
+ "@bgub/fig-tanstack-start",
442
+ "@bgub/fig-vite"
443
+ ];
444
+ async function analyzeStylesheetImports(code, id) {
445
+ const clean = cleanModuleId(id);
446
+ if (!isSourceModule(clean)) return [];
447
+ const stylesheets = [];
448
+ await babel.transformAsync(code, {
449
+ ...babelOptions(clean),
450
+ plugins: [stylesheetImportAnalysisPlugin(stylesheets)]
451
+ });
452
+ return stylesheets;
453
+ }
454
+ async function analyzeIsomorphicBoundaries(code, id) {
455
+ const clean = cleanModuleId(id);
456
+ if (!isSourceModule(clean) || !code.includes("Isomorphic")) return [];
457
+ const imports = [];
458
+ await babel.transformAsync(code, {
459
+ ...babelOptions(clean),
460
+ plugins: [isomorphicBoundaryAnalysisPlugin(imports)]
461
+ });
462
+ return imports;
463
+ }
464
+ function mayBePayloadModule(code, id) {
465
+ return isSourceModule(cleanModuleId(id)) && (hasModuleQuery(id, "fig-payload-module") || code.includes("renderPayloadResponse"));
466
+ }
467
+ async function transformPayloadModule(code, id, isomorphicImports = []) {
468
+ if (!mayBePayloadModule(code, id)) return null;
469
+ const state = { changed: false };
470
+ const result = await babel.transformAsync(code, {
471
+ ...babelOptions(cleanModuleId(id)),
472
+ sourceMaps: true,
473
+ plugins: [payloadBabelPlugin(isomorphicImports, hasModuleQuery(id, payloadModuleQuery), state)]
474
+ });
475
+ if (!state.changed || result?.code == null) return null;
476
+ return {
477
+ code: result.code,
478
+ map: result.map == null ? null : JSON.stringify(result.map)
479
+ };
480
+ }
481
+ function payloadRuntimeCode() {
482
+ return `import { clientReference } from "@bgub/fig";
483
+ const stylesheetKey = Symbol.for(${JSON.stringify(payloadStylesheetsSymbolKey)});
484
+ export function createIsomorphicReference(id) {
485
+ return clientReference({ id });
486
+ }
487
+ export function registerPayloadStylesheets(components, hrefs) {
488
+ for (const component of components) {
489
+ if (typeof component === "function") {
490
+ Object.defineProperty(component, stylesheetKey, { configurable: true, value: hrefs });
491
+ }
492
+ }
493
+ }`;
494
+ }
495
+ function payloadBabelPlugin(isomorphicImports, compiledPayloadModule, state) {
496
+ return (api) => {
497
+ const t = api.types;
498
+ return {
499
+ name: "fig-tanstack-start-payload",
500
+ visitor: { Program: { exit(path) {
501
+ if (!compiledPayloadModule && !callsRenderPayloadResponse(path)) return;
502
+ const components = collectComponentNames(path, t);
503
+ const hrefs = components.length === 0 ? [] : rewriteStylesheetImports(path, t);
504
+ const createReference = rewriteIsomorphicBoundaries(path, t, isomorphicImports);
505
+ if (rewritePayloadComponentImports(path) > 0) state.changed = true;
506
+ const runtimeSpecifiers = [];
507
+ if (createReference !== void 0) runtimeSpecifiers.push(t.importSpecifier(createReference, t.identifier("createIsomorphicReference")));
508
+ let registerStylesheets;
509
+ if (hrefs.length > 0) {
510
+ registerStylesheets = path.scope.generateUidIdentifier("registerPayloadStylesheets");
511
+ runtimeSpecifiers.push(t.importSpecifier(registerStylesheets, t.identifier("registerPayloadStylesheets")));
512
+ }
513
+ if (runtimeSpecifiers.length === 0) return;
514
+ state.changed = true;
515
+ path.node.body.unshift(t.importDeclaration(runtimeSpecifiers, t.stringLiteral(payloadRuntimeId)));
516
+ if (registerStylesheets !== void 0) path.node.body.push(t.expressionStatement(t.callExpression(registerStylesheets, [t.arrayExpression(components.map((name) => t.identifier(name))), t.arrayExpression(hrefs)])));
517
+ } } }
518
+ };
519
+ };
520
+ }
521
+ function callsRenderPayloadResponse(path) {
522
+ let found = false;
523
+ path.traverse({ CallExpression(callPath) {
524
+ if (callPath.node.callee.type === "Identifier" && isImportedBinding(callPath, callPath.node.callee.name, "renderPayloadResponse", "@bgub/fig-tanstack-start/server")) {
525
+ found = true;
526
+ callPath.stop();
527
+ }
528
+ } });
529
+ return found;
530
+ }
531
+ function rewritePayloadComponentImports(path) {
532
+ const componentBindings = /* @__PURE__ */ new Set();
533
+ path.traverse({
534
+ JSXOpeningElement(elementPath) {
535
+ if (elementPath.node.name.type === "JSXNamespacedName") return;
536
+ const name = rootJsxIdentifier(elementPath.node.name);
537
+ if (name !== void 0) componentBindings.add(name);
538
+ },
539
+ CallExpression(callPath) {
540
+ if (callPath.node.callee.type !== "Identifier" || !isImportedBinding(callPath, callPath.node.callee.name, "createElement", "@bgub/fig")) return;
541
+ const [type] = callPath.node.arguments;
542
+ if (type?.type === "Identifier" && isComponentName(type.name)) componentBindings.add(type.name);
543
+ }
544
+ });
545
+ let count = 0;
546
+ for (const statement of path.get("body")) {
547
+ if (!statement.isImportDeclaration()) continue;
548
+ const source = statement.node.source.value;
549
+ if (statement.node.importKind === "type" || isStylesheetSpecifier(source) || isFigRuntimeSpecifier(source) || hasModuleQuery(source, "fig-payload-module") || !statement.node.specifiers.some((specifier) => !("importKind" in specifier && specifier.importKind === "type") && componentBindings.has(specifier.local.name))) continue;
550
+ statement.node.source.value = withModuleQuery(source, payloadModuleQuery, "1");
551
+ count += 1;
552
+ }
553
+ return count;
554
+ }
555
+ function isFigRuntimeSpecifier(source) {
556
+ return figRuntimePackageIds.some((packageId) => source === packageId || source.startsWith(`${packageId}/`));
557
+ }
558
+ function rootJsxIdentifier(name) {
559
+ let current = name;
560
+ while (current.type === "JSXMemberExpression") current = current.object;
561
+ return current.type === "JSXIdentifier" && isComponentName(current.name) ? current.name : void 0;
562
+ }
563
+ //#endregion
564
+ //#region src/plugin/server-payload-compiler.ts
565
+ const compiledServerPayloadMarkerKey = "fig.tanstack-start.compiled-server-payload";
566
+ async function transformServerPayloadDefinitions(code, id) {
567
+ const clean = cleanModuleId(id);
568
+ if (!isSourceModule(clean) || !code.includes("serverPayload")) return null;
569
+ const state = { transformed: false };
570
+ const result = await babel.transformAsync(code, {
571
+ ...babelOptions(clean),
572
+ sourceMaps: true,
573
+ plugins: [serverPayloadBabelPlugin(state)]
574
+ });
575
+ if (!state.transformed || result?.code == null) return null;
576
+ return {
577
+ code: result.code,
578
+ map: result.map == null ? null : JSON.stringify(result.map)
579
+ };
580
+ }
581
+ function serverPayloadBabelPlugin(state) {
582
+ return (api) => {
583
+ const t = api.types;
584
+ let createElement;
585
+ let createServerFn;
586
+ let renderPayloadResponse;
587
+ return {
588
+ name: "fig-tanstack-start-server-payload",
589
+ visitor: {
590
+ Program: {
591
+ enter(path) {
592
+ createElement = path.scope.generateUidIdentifier("createElement");
593
+ createServerFn = path.scope.generateUidIdentifier("createServerFn");
594
+ renderPayloadResponse = path.scope.generateUidIdentifier("renderPayloadResponse");
595
+ },
596
+ exit(path) {
597
+ if (!state.transformed) return;
598
+ path.node.body.unshift(t.importDeclaration([t.importSpecifier(createElement, t.identifier("createElement"))], t.stringLiteral("@bgub/fig")));
599
+ path.node.body.unshift(t.importDeclaration([t.importSpecifier(renderPayloadResponse, t.identifier("renderPayloadResponse"))], t.stringLiteral(serverPackageId)));
600
+ path.node.body.unshift(t.importDeclaration([t.importSpecifier(createServerFn, t.identifier("createServerFn"))], t.stringLiteral(tanStackCompatibilityProfile.packages.frameworkStart)));
601
+ }
602
+ },
603
+ CallExpression(path) {
604
+ if (path.node.callee.type !== "Identifier" || !isImportedBinding(path, path.node.callee.name, "serverPayload", "@bgub/fig-tanstack-start/payload")) return;
605
+ transformServerPayloadCall(path, t, createElement, createServerFn, renderPayloadResponse);
606
+ state.transformed = true;
607
+ }
608
+ }
609
+ };
610
+ };
611
+ }
612
+ function transformServerPayloadCall(path, t, createElement, createServerFn, renderPayloadResponse) {
613
+ const [render, ...extra] = path.node.arguments;
614
+ if (render === void 0 || render.type === "SpreadElement" || render.type === "ArgumentPlaceholder" || extra.length > 0) throw path.buildCodeFrameError("serverPayload requires exactly one server component or render callback.");
615
+ if (!isRenderExpression(render)) throw path.buildCodeFrameError("serverPayload requires a component reference or inline render callback.");
616
+ const statement = path.getStatementParent();
617
+ if (path.getFunctionParent() !== null || statement === null || !statement.parentPath.isProgram()) throw path.buildCodeFrameError("serverPayload must be declared in a top-level statement.");
618
+ const declarator = path.findParent((candidate) => candidate.isVariableDeclarator());
619
+ const requestName = declarator?.isVariableDeclarator() && declarator.node.id.type === "Identifier" ? `${declarator.node.id.name}Request` : "payloadRequest";
620
+ const request = statement.scope.generateUidIdentifier(requestName);
621
+ const data = statement.scope.generateUidIdentifier("data");
622
+ const input = statement.scope.generateUidIdentifier("input");
623
+ const signal = statement.scope.generateUidIdentifier("signal");
624
+ const serverFn = t.callExpression(t.memberExpression(t.callExpression(createServerFn, []), t.identifier("handler")), [t.arrowFunctionExpression([t.objectPattern([t.objectProperty(t.identifier("data"), data, false, false)])], t.callExpression(renderPayloadResponse, [t.callExpression(createElement, [render, data])]))]);
625
+ statement.insertBefore(t.variableDeclaration("const", [t.variableDeclarator(request, serverFn)]));
626
+ const proxy = t.arrowFunctionExpression([input, t.objectPattern([t.objectProperty(t.identifier("signal"), signal, false, false)])], t.callExpression(request, [t.objectExpression([t.objectProperty(t.identifier("data"), input, false, false), t.objectProperty(t.identifier("signal"), signal, false, false)])]));
627
+ path.node.arguments = [t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("assign")), [proxy, t.objectExpression([t.objectProperty(t.callExpression(t.memberExpression(t.identifier("Symbol"), t.identifier("for")), [t.stringLiteral(compiledServerPayloadMarkerKey)]), t.booleanLiteral(true), true)])])];
628
+ }
629
+ function isRenderExpression(value) {
630
+ return value.type === "ArrowFunctionExpression" || value.type === "FunctionExpression" && !value.generator || value.type === "Identifier" || value.type === "MemberExpression";
631
+ }
632
+ //#endregion
633
+ //#region src/plugin/public-assets.ts
634
+ async function writePublicAsset(path, source) {
635
+ const bytes = Buffer.from(source);
636
+ let existing;
637
+ try {
638
+ existing = await readFile(path);
639
+ } catch (error) {
640
+ if (!isMissingFile(error)) throw error;
641
+ }
642
+ if (existing !== void 0) {
643
+ if (existing.equals(bytes)) return;
644
+ throw new Error(`TanStack Start server asset ${JSON.stringify(path)} conflicts with a different client asset at the same public path. Use content-hashed or separately namespaced asset file names.`);
645
+ }
646
+ await mkdir(dirname(path), { recursive: true });
647
+ await writeFile(path, bytes);
648
+ }
649
+ function isMissingFile(error) {
650
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
651
+ }
652
+ //#endregion
653
+ //#region src/plugin/payload-vite.ts
654
+ const payloadManifestDefinitionPrefix = "\0fig-tanstack-start:payload-manifest-definition:";
655
+ function serverPayloadPlugin() {
656
+ return {
657
+ name: "fig-tanstack-start:server-payload",
658
+ enforce: "pre",
659
+ transform: transformServerPayloadDefinitions
660
+ };
661
+ }
662
+ function payloadPlugin() {
663
+ let root = process.cwd();
664
+ let base = "/";
665
+ let clientOutDir;
666
+ let serverAssetsPrefix = "assets/";
667
+ const clientStylesheets = /* @__PURE__ */ new Map();
668
+ const definitionInputs = /* @__PURE__ */ new Map();
669
+ return {
670
+ name: "fig-tanstack-start:payload",
671
+ enforce: "pre",
672
+ configEnvironment(environmentName) {
673
+ if (environmentName === START_ENVIRONMENT_NAMES.server) return { build: { emitAssets: true } };
674
+ },
675
+ configResolved(config) {
676
+ root = config.root;
677
+ base = config.base;
678
+ const outDir = config.environments[START_ENVIRONMENT_NAMES.client]?.build.outDir;
679
+ if (outDir !== void 0) clientOutDir = resolve(config.root, outDir);
680
+ const assetsDir = config.environments[START_ENVIRONMENT_NAMES.server]?.build.assetsDir;
681
+ if (assetsDir !== void 0) {
682
+ const normalized = assetsDir.replace(/\/+$/, "");
683
+ serverAssetsPrefix = normalized === "" ? "" : `${normalized}/`;
684
+ }
685
+ },
686
+ async writeBundle(_options, bundle) {
687
+ if (this.environment.name !== START_ENVIRONMENT_NAMES.server || clientOutDir === void 0) return;
688
+ const publicOutDir = clientOutDir;
689
+ await Promise.all(Object.values(bundle).map(async (output) => {
690
+ if (output.type !== "asset" || !output.fileName.startsWith(serverAssetsPrefix) || output.fileName.endsWith(".map")) return;
691
+ await writePublicAsset(resolve(publicOutDir, output.fileName), output.source);
692
+ }));
693
+ },
694
+ generateBundle(_options, bundle) {
695
+ if (this.environment.name !== START_ENVIRONMENT_NAMES.client) return;
696
+ collectClientStylesheets(bundle, clientStylesheets, base);
697
+ },
698
+ async resolveId(source, importer) {
699
+ if (source === "virtual:fig-tanstack-start/payload-runtime") return resolvedPayloadRuntimeId;
700
+ if (source === "virtual:fig-tanstack-start/payload-manifest") return resolvedPayloadManifestId;
701
+ if (hasModuleQuery(source, "fig-payload-module")) {
702
+ const resolved = await this.resolve(cleanModuleId(source), importer, { skipSelf: true });
703
+ return resolved === null ? null : withModuleQuery(cleanModuleId(resolved.id), payloadModuleQuery, "1");
704
+ }
705
+ if (!hasModuleQuery(source, "fig-payload-manifest")) return;
706
+ const resolved = await this.resolve(cleanModuleId(source), importer, { skipSelf: true });
707
+ if (resolved === null) return null;
708
+ return definitionModuleId(cleanModuleId(resolved.id));
709
+ },
710
+ async load(id) {
711
+ if (id === resolvedPayloadRuntimeId) return payloadRuntimeCode();
712
+ if (id === resolvedPayloadManifestId) return payloadManifestRuntimeCode(clientStylesheets);
713
+ if (!id.startsWith(payloadManifestDefinitionPrefix)) return void 0;
714
+ const sourceId = decodeOpaqueId(id.slice(48));
715
+ const code = rewriteFrameworkImports(await readFile(sourceId, "utf8"));
716
+ const stylesheetSources = /* @__PURE__ */ new Map();
717
+ const references = await collectPayloadReferences(sourceId, code, (source, importer) => this.resolve(source, importer, { skipSelf: true }), root, stylesheetSources);
718
+ if (references.length > 0) {
719
+ this.addWatchFile(sourceId);
720
+ definitionInputs.set(sourceId, {
721
+ boundaries: boundaryFingerprint(references),
722
+ stylesheetSources
723
+ });
724
+ } else definitionInputs.delete(sourceId);
725
+ return payloadManifestDefinitionCode(references);
726
+ },
727
+ async hotUpdate({ file, modules, read }) {
728
+ const { moduleGraph } = this.environment;
729
+ const invalidated = /* @__PURE__ */ new Set();
730
+ let content;
731
+ const readContent = async () => content ??= await read();
732
+ const definition = moduleGraph.getModuleById(definitionModuleId(file));
733
+ if (definition !== void 0) {
734
+ let changed;
735
+ try {
736
+ const boundaries = boundaryFingerprint(await analyzeIsomorphicBoundaries(rewriteFrameworkImports(await readContent()), file));
737
+ changed = (definitionInputs.get(file)?.boundaries ?? emptyBoundaryFingerprint) !== boundaries;
738
+ } catch {
739
+ changed = true;
740
+ }
741
+ if (changed) invalidated.add(definition);
742
+ }
743
+ const dependents = [...definitionInputs].filter(([, inputs]) => inputs.stylesheetSources.has(file));
744
+ if (dependents.length > 0) {
745
+ let sources;
746
+ try {
747
+ sources = stylesheetSourceFingerprint(await analyzeStylesheetImports(await readContent(), file));
748
+ } catch {
749
+ sources = void 0;
750
+ }
751
+ for (const [sourceId, inputs] of dependents) {
752
+ if (inputs.stylesheetSources.get(file) === sources) continue;
753
+ const dependent = moduleGraph.getModuleById(definitionModuleId(sourceId));
754
+ if (dependent !== void 0) invalidated.add(dependent);
755
+ }
756
+ }
757
+ if (invalidated.size === 0) return void 0;
758
+ return [...modules, ...invalidated];
759
+ },
760
+ async transform(code, id) {
761
+ if (this.environment.name !== START_ENVIRONMENT_NAMES.server || !mayBePayloadModule(code, id)) return null;
762
+ return transformPayloadModule(code, id, await collectPayloadReferences(id, code, (source, importer) => this.resolve(source, importer, { skipSelf: true }), root));
763
+ }
764
+ };
765
+ }
766
+ function definitionModuleId(sourceId) {
767
+ return `${payloadManifestDefinitionPrefix}${encodeOpaqueId(sourceId)}`;
768
+ }
769
+ function boundaryFingerprint(imports) {
770
+ return JSON.stringify(imports.map(({ importedName, localName, source }) => [
771
+ source,
772
+ importedName,
773
+ localName
774
+ ]));
775
+ }
776
+ const emptyBoundaryFingerprint = boundaryFingerprint([]);
777
+ function stylesheetSourceFingerprint(sources) {
778
+ return JSON.stringify(sources);
779
+ }
780
+ async function collectPayloadReferences(id, code, resolveModule, root, stylesheetSources) {
781
+ const importerId = cleanModuleId(id);
782
+ const imports = await analyzeIsomorphicBoundaries(code, id);
783
+ return Promise.all(imports.map(async (imported) => {
784
+ const resolved = await resolveModule(imported.source, importerId);
785
+ if (resolved === null) throw new Error(`Cannot resolve Isomorphic component import ${JSON.stringify(imported.source)} from ${importerId}.`);
786
+ const moduleId = cleanModuleId(resolved.id);
787
+ const referenceId = isomorphicReferenceId(root, moduleId, imported.importedName);
788
+ let hrefs = [];
789
+ if (stylesheetSources !== void 0) {
790
+ const stylesheets = await moduleStylesheets(moduleId, root, resolveModule);
791
+ hrefs = stylesheets.hrefs;
792
+ stylesheetSources.set(moduleId, stylesheetSourceFingerprint(stylesheets.sources));
793
+ }
794
+ return {
795
+ ...imported,
796
+ referenceId,
797
+ resolvedModuleId: moduleId,
798
+ developmentStylesheetHrefs: hrefs
799
+ };
800
+ }));
801
+ }
802
+ async function moduleStylesheets(moduleId, root, resolveModule) {
803
+ if (!isAbsolute(moduleId)) return {
804
+ hrefs: [],
805
+ sources: []
806
+ };
807
+ let code;
808
+ try {
809
+ code = await readFile(moduleId, "utf8");
810
+ } catch {
811
+ return {
812
+ hrefs: [],
813
+ sources: []
814
+ };
815
+ }
816
+ const sources = await analyzeStylesheetImports(code, moduleId);
817
+ return {
818
+ hrefs: (await Promise.all(sources.map(async (source) => {
819
+ const resolved = await resolveModule(source, moduleId);
820
+ return resolved === null ? void 0 : toViteModulePath(root, cleanModuleId(resolved.id));
821
+ }))).filter((href) => href !== void 0),
822
+ sources
823
+ };
824
+ }
825
+ function collectClientStylesheets(bundle, clientStylesheets, base) {
826
+ clientStylesheets.clear();
827
+ for (const output of Object.values(bundle)) {
828
+ if (output.type !== "chunk") continue;
829
+ const referenceIds = payloadReferenceIds(Object.keys(output.modules));
830
+ for (const referenceId of referenceIds) {
831
+ const stylesheets = new Set(clientStylesheets.get(referenceId));
832
+ for (const file of output.viteMetadata?.importedCss ?? []) stylesheets.add(`${base.replace(/\/$/, "")}/${file}`);
833
+ clientStylesheets.set(referenceId, [...stylesheets]);
834
+ }
835
+ }
836
+ }
837
+ //#endregion
838
+ //#region src/plugin/vite.ts
839
+ function tanstackStart(options) {
840
+ return [
841
+ startCompatibilityPlugin(),
842
+ serverPayloadPlugin(),
843
+ payloadPlugin(),
844
+ tanStackStartVite({
845
+ defaultEntryPaths,
846
+ framework: tanStackCompatibilityProfile.framework,
847
+ providerEnvironmentName: START_ENVIRONMENT_NAMES.server,
848
+ ssrIsProvider: true,
849
+ ssrResolverStrategy: { type: "default" }
850
+ }, options),
851
+ figRefresh()
852
+ ];
853
+ }
854
+ //#endregion
855
+ export { tanstackStart };
856
+
857
+ //# sourceMappingURL=vite.js.map