@fierst/c7t 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/bin/c7t.d.mts +1 -0
- package/bin/c7t.mjs +107 -0
- package/bin/create.d.mts +9 -0
- package/bin/create.mjs +344 -0
- package/dist/adapters/bun.d.mts +40 -0
- package/dist/adapters/bun.mjs +114 -0
- package/dist/adapters/cloudflare.d.mts +29 -0
- package/dist/adapters/cloudflare.mjs +28 -0
- package/dist/adapters/node.d.mts +31 -0
- package/dist/adapters/node.mjs +139 -0
- package/dist/adapters/static.d.mts +34 -0
- package/dist/adapters/static.mjs +53 -0
- package/dist/adapters/vercel.d.mts +40 -0
- package/dist/adapters/vercel.mjs +79 -0
- package/dist/client.d.mts +78 -0
- package/dist/client.mjs +181 -0
- package/dist/head-CUiNFY7Q.mjs +142 -0
- package/dist/index.d.mts +77 -0
- package/dist/index.mjs +25 -0
- package/dist/multipart-CwqTb3AQ.mjs +72 -0
- package/dist/protocol-B6QOAMGj.d.mts +115 -0
- package/dist/protocol-CZANZJ5x.mjs +126 -0
- package/dist/router-19ZZ3woS.d.mts +148 -0
- package/dist/router-B50LekA_.mjs +680 -0
- package/dist/router.d.mts +2 -0
- package/dist/router.mjs +1 -0
- package/dist/search-params-C03mU47i.mjs +79 -0
- package/dist/server.d.mts +146 -0
- package/dist/server.mjs +850 -0
- package/dist/ssg-DFBgqaob.d.mts +40 -0
- package/dist/ssg.d.mts +2 -0
- package/dist/ssg.mjs +179 -0
- package/dist/vite.d.mts +95 -0
- package/dist/vite.mjs +920 -0
- package/docs/README.md +26 -0
- package/docs/guides/01-getting-started.md +164 -0
- package/docs/guides/02-data-fetching-and-mutations.md +258 -0
- package/docs/guides/03-streaming-and-workflows.md +198 -0
- package/docs/guides/04-routing-layouts-and-state.md +236 -0
- package/docs/guides/05-auth-sessions-and-security.md +179 -0
- package/docs/guides/06-ssg-and-deployment.md +247 -0
- package/docs/guides/07-databases-and-drizzle.md +200 -0
- package/docs/reference.md +112 -0
- package/llms.txt +1627 -0
- package/package.json +121 -4
- package/template/gitignore +11 -0
- package/template/package.json +22 -0
- package/template/src/routes/404.tsx +16 -0
- package/template/src/routes/about.tsx +22 -0
- package/template/src/routes/index.tsx +41 -0
- package/template/src/routes/layout.tsx +14 -0
- package/template/src/styles.css +39 -0
- package/template/tsconfig.json +18 -0
- package/template/vite.config.ts +16 -0
package/dist/vite.mjs
ADDED
|
@@ -0,0 +1,920 @@
|
|
|
1
|
+
import { buildStaticSite } from "./adapters/static.mjs";
|
|
2
|
+
import { buildVercelOutput } from "./adapters/vercel.mjs";
|
|
3
|
+
import { prerenderApp } from "./ssg.mjs";
|
|
4
|
+
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { join, relative, resolve } from "node:path";
|
|
6
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { parseSync, visitorKeys } from "oxc-parser";
|
|
9
|
+
import blokd from "@fierst/blokd/vite";
|
|
10
|
+
import { pathToFileURL } from "node:url";
|
|
11
|
+
// src/build.ts
|
|
12
|
+
async function loadViteApi() {
|
|
13
|
+
const vitePlusSpecifier = "vite-plus";
|
|
14
|
+
try {
|
|
15
|
+
return await import(
|
|
16
|
+
/* @vite-ignore */
|
|
17
|
+
vitePlusSpecifier
|
|
18
|
+
);
|
|
19
|
+
} catch {
|
|
20
|
+
return await import(
|
|
21
|
+
/* @vite-ignore */
|
|
22
|
+
"vite"
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function normalizeAdapter(input) {
|
|
27
|
+
if (!input) return {
|
|
28
|
+
name: "node",
|
|
29
|
+
options: {}
|
|
30
|
+
};
|
|
31
|
+
if (typeof input === "string") return {
|
|
32
|
+
name: input,
|
|
33
|
+
options: {}
|
|
34
|
+
};
|
|
35
|
+
return {
|
|
36
|
+
name: input.name,
|
|
37
|
+
options: input.options ?? {}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Execute the full 3-stage `c7t` production build:
|
|
42
|
+
* 1. Client asset + island bundle (`dist/client` + `c7t-manifest.json` + hashed CSS)
|
|
43
|
+
* 2. Self-contained SSR & RPC bundle (`dist/server/entry.mjs` with inline manifest + zero-FOUC `<link>` styles)
|
|
44
|
+
* 3. Hybrid/Static prerendering (`__c7t.json` sidecars) + target adapter output (`node`, `cloudflare`, `vercel`, `bun`, `static`)
|
|
45
|
+
*/
|
|
46
|
+
async function buildApp(options = {}) {
|
|
47
|
+
const absRoot = resolve(options.root ?? process.cwd());
|
|
48
|
+
const logLevel = options.logLevel ?? "info";
|
|
49
|
+
const vite = await loadViteApi();
|
|
50
|
+
const pluginOpts = ((await vite.resolveConfig({
|
|
51
|
+
root: absRoot,
|
|
52
|
+
logLevel: "silent"
|
|
53
|
+
}, "build"))?.plugins ?? []).find((p) => p?.name === "c7t:compiler")?.__c7tOptions ?? {};
|
|
54
|
+
const { name: adapterName, options: adapterOpts } = normalizeAdapter(options.adapter ?? pluginOpts.adapter);
|
|
55
|
+
const prerenderOption = options.prerender ?? pluginOpts.prerender ?? "marked";
|
|
56
|
+
const absClientDir = join(absRoot, "dist", "client");
|
|
57
|
+
const absServerDir = join(absRoot, "dist", "server");
|
|
58
|
+
await vite.build({
|
|
59
|
+
root: absRoot,
|
|
60
|
+
logLevel,
|
|
61
|
+
build: {
|
|
62
|
+
outDir: "dist/client",
|
|
63
|
+
emptyOutDir: true,
|
|
64
|
+
ssr: false,
|
|
65
|
+
rollupOptions: { input: "virtual:c7t/client-entry" }
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
const manifestFile = join(absClientDir, "c7t-manifest.json");
|
|
69
|
+
let manifestPayload = {
|
|
70
|
+
manifest: {},
|
|
71
|
+
styles: []
|
|
72
|
+
};
|
|
73
|
+
if (existsSync(manifestFile)) manifestPayload = JSON.parse(readFileSync(manifestFile, "utf-8"));
|
|
74
|
+
_setActiveSsrBuildContext({
|
|
75
|
+
manifest: manifestPayload.manifest,
|
|
76
|
+
styles: manifestPayload.styles,
|
|
77
|
+
adapterName
|
|
78
|
+
});
|
|
79
|
+
try {
|
|
80
|
+
await vite.build({
|
|
81
|
+
root: absRoot,
|
|
82
|
+
logLevel,
|
|
83
|
+
ssr: { noExternal: [/^@fierst\//, "hono"] },
|
|
84
|
+
build: {
|
|
85
|
+
outDir: "dist/server",
|
|
86
|
+
emptyOutDir: true,
|
|
87
|
+
ssr: true,
|
|
88
|
+
rollupOptions: {
|
|
89
|
+
input: "virtual:c7t/ssr-entry",
|
|
90
|
+
output: {
|
|
91
|
+
format: "es",
|
|
92
|
+
entryFileNames: "entry.mjs"
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
} finally {
|
|
98
|
+
_setActiveSsrBuildContext(null);
|
|
99
|
+
}
|
|
100
|
+
const serverEntryPath = join(absServerDir, "entry.mjs");
|
|
101
|
+
let prerendered = null;
|
|
102
|
+
let entryFile = serverEntryPath;
|
|
103
|
+
const prevNodeEnv = process.env.NODE_ENV;
|
|
104
|
+
process.env.NODE_ENV = "production";
|
|
105
|
+
try {
|
|
106
|
+
const ssrMod = await import(
|
|
107
|
+
/* @vite-ignore */
|
|
108
|
+
`${pathToFileURL(serverEntryPath).href}?t=${Date.now()}`
|
|
109
|
+
);
|
|
110
|
+
const app = ssrMod.app ?? ssrMod.default;
|
|
111
|
+
const routeEntries = Array.isArray(ssrMod.routeEntries) ? ssrMod.routeEntries : [];
|
|
112
|
+
if (adapterName === "static") {
|
|
113
|
+
const staticOutDir = adapterOpts.outDir ? resolve(absRoot, adapterOpts.outDir) : absClientDir;
|
|
114
|
+
prerendered = await buildStaticSite({
|
|
115
|
+
app,
|
|
116
|
+
routes: routeEntries,
|
|
117
|
+
...adapterOpts,
|
|
118
|
+
outDir: staticOutDir
|
|
119
|
+
});
|
|
120
|
+
await rm(absServerDir, {
|
|
121
|
+
recursive: true,
|
|
122
|
+
force: true
|
|
123
|
+
});
|
|
124
|
+
return {
|
|
125
|
+
adapter: "static",
|
|
126
|
+
clientDir: staticOutDir,
|
|
127
|
+
serverDir: null,
|
|
128
|
+
entryFile: null,
|
|
129
|
+
manifest: manifestPayload.manifest,
|
|
130
|
+
styles: manifestPayload.styles,
|
|
131
|
+
prerendered
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
if (prerenderOption !== false && app && routeEntries.length > 0) {
|
|
135
|
+
const prerenderAll = prerenderOption === true || prerenderOption === "all";
|
|
136
|
+
const hasMarkedRoutes = routeEntries.some((r) => Boolean(r.prerender));
|
|
137
|
+
if (prerenderAll || hasMarkedRoutes) prerendered = await prerenderApp({
|
|
138
|
+
app,
|
|
139
|
+
routes: routeEntries,
|
|
140
|
+
outDir: absClientDir,
|
|
141
|
+
mode: prerenderAll ? "all" : "marked"
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
} finally {
|
|
145
|
+
if (prevNodeEnv === void 0) delete process.env.NODE_ENV;
|
|
146
|
+
else process.env.NODE_ENV = prevNodeEnv;
|
|
147
|
+
}
|
|
148
|
+
if (adapterName === "node") {
|
|
149
|
+
const startPath = join(absServerDir, "start.mjs");
|
|
150
|
+
const startSource = `import { fileURLToPath } from "node:url";
|
|
151
|
+
import { app, serveNode } from "./entry.mjs";
|
|
152
|
+
|
|
153
|
+
process.env.NODE_ENV ??= "production";
|
|
154
|
+
const clientDir = fileURLToPath(new URL("../client", import.meta.url));
|
|
155
|
+
const port = Number(process.env.PORT) || ${Number(adapterOpts.port) || 3e3};\nconst hostname = process.env.HOST || ${JSON.stringify(adapterOpts.hostname ?? "0.0.0.0")};\n\nexport const server = serveNode(app, {\n port,\n hostname,\n clientDir,\n onListen: ({ port: activePort }) => {\n console.log(\`[c7t] Production server listening on http://localhost:\${activePort}\`);\n },\n});\n`;
|
|
156
|
+
await writeFile(startPath, startSource, "utf-8");
|
|
157
|
+
entryFile = startPath;
|
|
158
|
+
} else if (adapterName === "bun") {
|
|
159
|
+
const startPath = join(absServerDir, "start.bun.mjs");
|
|
160
|
+
const startSource = `import { fileURLToPath } from "node:url";
|
|
161
|
+
import { app, serveBun } from "./entry.mjs";
|
|
162
|
+
|
|
163
|
+
process.env.NODE_ENV ??= "production";
|
|
164
|
+
const clientDir = fileURLToPath(new URL("../client", import.meta.url));
|
|
165
|
+
const port = Number(process.env.PORT) || ${Number(adapterOpts.port) || 3e3};\nconst hostname = process.env.HOST || ${JSON.stringify(adapterOpts.hostname ?? "0.0.0.0")};\n\nexport default serveBun(app, {\n port,\n hostname,\n clientDir,\n onListen: ({ port: activePort }) => {\n console.log(\`[c7t] Bun production server listening on http://localhost:\${activePort}\`);\n },\n});\n`;
|
|
166
|
+
await writeFile(startPath, startSource, "utf-8");
|
|
167
|
+
entryFile = startPath;
|
|
168
|
+
} else if (adapterName === "cloudflare") {
|
|
169
|
+
const workerPath = join(absRoot, "dist", "worker.mjs");
|
|
170
|
+
await mkdir(join(absRoot, "dist"), { recursive: true });
|
|
171
|
+
const assetsBinding = adapterOpts.assetsBinding ?? "ASSETS";
|
|
172
|
+
const workerSource = `import { app, cloudflareAdapter } from "./server/entry.mjs";\nexport default cloudflareAdapter(app, { assetsBinding: ${JSON.stringify(assetsBinding)} });\n`;
|
|
173
|
+
await writeFile(workerPath, workerSource, "utf-8");
|
|
174
|
+
entryFile = workerPath;
|
|
175
|
+
} else if (adapterName === "vercel") {
|
|
176
|
+
const vercelResult = await buildVercelOutput({
|
|
177
|
+
rootDir: absRoot,
|
|
178
|
+
clientDir: "dist/client",
|
|
179
|
+
serverDir: "dist/server",
|
|
180
|
+
serverEntry: "entry.mjs",
|
|
181
|
+
...adapterOpts
|
|
182
|
+
});
|
|
183
|
+
entryFile = join(vercelResult.functionDir, "index.mjs");
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
adapter: adapterName,
|
|
187
|
+
clientDir: absClientDir,
|
|
188
|
+
serverDir: absServerDir,
|
|
189
|
+
entryFile,
|
|
190
|
+
manifest: manifestPayload.manifest,
|
|
191
|
+
styles: manifestPayload.styles,
|
|
192
|
+
prerendered
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
// src/vite.ts
|
|
196
|
+
function computeRpcId(moduleUrl, exportName, index, hashIds = false) {
|
|
197
|
+
const raw = `${moduleUrl.replace(/\\/g, "/")}#${exportName}`;
|
|
198
|
+
if (!hashIds) return raw;
|
|
199
|
+
return `c7t_${createHash("sha256").update(`${raw}#${index}`).digest("hex").slice(0, 12)}`;
|
|
200
|
+
}
|
|
201
|
+
function isServerModulePath(cleanId) {
|
|
202
|
+
return /\.server\.(ts|tsx|js|jsx|mts|mjs)$/.test(cleanId);
|
|
203
|
+
}
|
|
204
|
+
function parseProgram(code, filename) {
|
|
205
|
+
const lang = filename.endsWith(".tsx") ? "tsx" : filename.endsWith(".jsx") ? "jsx" : filename.endsWith(".ts") || filename.endsWith(".mts") ? "ts" : "js";
|
|
206
|
+
const parsed = parseSync(filename, code, { lang });
|
|
207
|
+
if (parsed.errors.length > 0) throw new SyntaxError(parsed.errors[0].codeframe ?? parsed.errors[0].message);
|
|
208
|
+
return parsed.program;
|
|
209
|
+
}
|
|
210
|
+
function unwrapExpr(node) {
|
|
211
|
+
let cur = node ?? null;
|
|
212
|
+
while (cur && (cur.type === "ParenthesizedExpression" || cur.type === "TSAsExpression" || cur.type === "TSSatisfiesExpression" || cur.type === "TSNonNullExpression")) cur = cur.expression ?? null;
|
|
213
|
+
return cur;
|
|
214
|
+
}
|
|
215
|
+
function isGeneratorFnNode(node) {
|
|
216
|
+
const target = unwrapExpr(node);
|
|
217
|
+
if (!target) return false;
|
|
218
|
+
return (target.type === "FunctionExpression" || target.type === "FunctionDeclaration") && Boolean(target.generator);
|
|
219
|
+
}
|
|
220
|
+
function applyEdits(source, edits) {
|
|
221
|
+
if (edits.length === 0) return source;
|
|
222
|
+
const sorted = [...edits].sort((a, b) => a.start - b.start || a.end - b.end);
|
|
223
|
+
let out = "";
|
|
224
|
+
let cursor = 0;
|
|
225
|
+
for (const edit of sorted) {
|
|
226
|
+
if (edit.start < cursor) continue;
|
|
227
|
+
out += source.slice(cursor, edit.start) + edit.replacement;
|
|
228
|
+
cursor = edit.end;
|
|
229
|
+
}
|
|
230
|
+
out += source.slice(cursor);
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Compile a `*.server.ts` module or a `.tsx`/`.ts` module containing colocated `server(...)` calls.
|
|
235
|
+
* Returns `null` if no transformation is required.
|
|
236
|
+
*/
|
|
237
|
+
function compileC7tModule(code, options) {
|
|
238
|
+
const cleanUrl = options.moduleUrl.split("?")[0].replace(/\\/g, "/");
|
|
239
|
+
const isServerFile = isServerModulePath(cleanUrl);
|
|
240
|
+
const hashIds = options.hashIds ?? false;
|
|
241
|
+
if (!isServerFile && !code.includes("server") && !code.includes("@fierst/c7t/server") && !code.includes("prerender")) return null;
|
|
242
|
+
const program = parseProgram(code, cleanUrl);
|
|
243
|
+
if (isServerFile) {
|
|
244
|
+
const rpcs = [];
|
|
245
|
+
const serverEdits = [];
|
|
246
|
+
const serverFooterRegistrations = [];
|
|
247
|
+
const serverHelperLocals = /* @__PURE__ */ new Set();
|
|
248
|
+
for (const stmt of program.body) {
|
|
249
|
+
if (stmt.type !== "ImportDeclaration") continue;
|
|
250
|
+
const src = stmt.source.value;
|
|
251
|
+
if (src === "@fierst/c7t" || src === "@fierst/c7t/server") {
|
|
252
|
+
for (const spec of stmt.specifiers) if (spec.type === "ImportSpecifier" && spec.imported.type === "Identifier" && spec.imported.name === "server") serverHelperLocals.add(spec.local.name);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
let idx = 0;
|
|
256
|
+
for (const stmt of program.body) {
|
|
257
|
+
if (stmt.type !== "ExportNamedDeclaration" || stmt.exportKind === "type") continue;
|
|
258
|
+
const decl = stmt.declaration;
|
|
259
|
+
if (decl?.type === "FunctionDeclaration" && decl.id) {
|
|
260
|
+
const exportName = decl.id.name;
|
|
261
|
+
const id = computeRpcId(cleanUrl, exportName, idx++, hashIds);
|
|
262
|
+
const isStream = Boolean(decl.generator);
|
|
263
|
+
rpcs.push({
|
|
264
|
+
name: exportName,
|
|
265
|
+
id,
|
|
266
|
+
isStream
|
|
267
|
+
});
|
|
268
|
+
if (options.ssr) {
|
|
269
|
+
const internalName = `__c7t_orig_${exportName}`;
|
|
270
|
+
serverEdits.push({
|
|
271
|
+
start: stmt.start,
|
|
272
|
+
end: decl.start,
|
|
273
|
+
replacement: ""
|
|
274
|
+
});
|
|
275
|
+
serverEdits.push({
|
|
276
|
+
start: decl.id.start,
|
|
277
|
+
end: decl.id.end,
|
|
278
|
+
replacement: internalName
|
|
279
|
+
});
|
|
280
|
+
serverFooterRegistrations.push(`export const ${exportName} = __c7tReg(${JSON.stringify(id)}, ${internalName});`);
|
|
281
|
+
}
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (decl?.type === "VariableDeclaration") for (const item of decl.declarations) {
|
|
285
|
+
if (item.id.type !== "Identifier" || !item.init) continue;
|
|
286
|
+
const exportName = item.id.name;
|
|
287
|
+
const init = unwrapExpr(item.init);
|
|
288
|
+
if (!init) continue;
|
|
289
|
+
if (init.type === "CallExpression" && init.callee.type === "Identifier" && serverHelperLocals.has(init.callee.name)) {
|
|
290
|
+
const isStream = isGeneratorFnNode(init.arguments.at(-1));
|
|
291
|
+
const id = computeRpcId(cleanUrl, exportName, idx++, hashIds);
|
|
292
|
+
rpcs.push({
|
|
293
|
+
name: exportName,
|
|
294
|
+
id,
|
|
295
|
+
isStream
|
|
296
|
+
});
|
|
297
|
+
if (options.ssr && init.arguments.length > 0) {
|
|
298
|
+
const firstArg = init.arguments[0];
|
|
299
|
+
serverEdits.push({
|
|
300
|
+
start: init.start,
|
|
301
|
+
end: firstArg.start,
|
|
302
|
+
replacement: `__c7tReg(${JSON.stringify(id)}, `
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
} else if (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression") {
|
|
306
|
+
const isStream = Boolean(init.generator);
|
|
307
|
+
const id = computeRpcId(cleanUrl, exportName, idx++, hashIds);
|
|
308
|
+
rpcs.push({
|
|
309
|
+
name: exportName,
|
|
310
|
+
id,
|
|
311
|
+
isStream
|
|
312
|
+
});
|
|
313
|
+
if (options.ssr) serverEdits.push({
|
|
314
|
+
start: item.init.start,
|
|
315
|
+
end: item.init.end,
|
|
316
|
+
replacement: `__c7tReg(${JSON.stringify(id)}, ${code.slice(item.init.start, item.init.end)})`
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (!options.ssr) {
|
|
322
|
+
const lines = [];
|
|
323
|
+
const needRpc = rpcs.some((r) => !r.isStream);
|
|
324
|
+
const needStream = rpcs.some((r) => r.isStream);
|
|
325
|
+
const specifiers = [];
|
|
326
|
+
if (needRpc) specifiers.push("createRpcStub as __c7tRpc");
|
|
327
|
+
if (needStream) specifiers.push("createStreamStub as __c7tStream");
|
|
328
|
+
if (specifiers.length > 0) lines.push(`import { ${specifiers.join(", ")} } from '@fierst/c7t/client';`);
|
|
329
|
+
for (const rpc of rpcs) {
|
|
330
|
+
const helper = rpc.isStream ? "__c7tStream" : "__c7tRpc";
|
|
331
|
+
lines.push(`export const ${rpc.name} = ${helper}(${JSON.stringify(rpc.id)});`);
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
code: lines.join("\n") + "\n",
|
|
335
|
+
rpcs
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
if (rpcs.length === 0) return null;
|
|
339
|
+
return {
|
|
340
|
+
code: `import { registerServerFn as __c7tReg } from '@fierst/c7t/server';\n` + applyEdits(code, serverEdits) + (serverFooterRegistrations.length > 0 ? "\n" + serverFooterRegistrations.join("\n") + "\n" : ""),
|
|
341
|
+
rpcs
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
const serverLocalNames = /* @__PURE__ */ new Set();
|
|
345
|
+
let hasServerSubpathImport = false;
|
|
346
|
+
for (const stmt of program.body) {
|
|
347
|
+
if (stmt.type !== "ImportDeclaration" || stmt.importKind === "type") continue;
|
|
348
|
+
const src = stmt.source.value;
|
|
349
|
+
if (src === "@fierst/c7t/server") hasServerSubpathImport = true;
|
|
350
|
+
if (src === "@fierst/c7t" || src === "@fierst/c7t/server") {
|
|
351
|
+
for (const spec of stmt.specifiers) if (spec.type === "ImportSpecifier" && spec.importKind !== "type" && spec.imported.type === "Identifier" && spec.imported.name === "server") serverLocalNames.add(spec.local.name);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const prerenderFnEdits = [];
|
|
355
|
+
const prerenderStrippedRanges = [];
|
|
356
|
+
if (!options.ssr) for (const stmt of program.body) {
|
|
357
|
+
if (stmt.type !== "ExportNamedDeclaration" || stmt.exportKind === "type") continue;
|
|
358
|
+
const decl = stmt.declaration;
|
|
359
|
+
if (decl?.type === "FunctionDeclaration" && decl.id?.name === "prerender") {
|
|
360
|
+
prerenderFnEdits.push({
|
|
361
|
+
start: stmt.start,
|
|
362
|
+
end: stmt.end,
|
|
363
|
+
replacement: "export const prerender = true;"
|
|
364
|
+
});
|
|
365
|
+
prerenderStrippedRanges.push([stmt.start, stmt.end]);
|
|
366
|
+
} else if (decl?.type === "VariableDeclaration") {
|
|
367
|
+
for (const item of decl.declarations) if (item.id.type === "Identifier" && item.id.name === "prerender" && item.init) {
|
|
368
|
+
const unwrapped = unwrapExpr(item.init);
|
|
369
|
+
if (unwrapped?.type === "ArrowFunctionExpression" || unwrapped?.type === "FunctionExpression") {
|
|
370
|
+
prerenderFnEdits.push({
|
|
371
|
+
start: item.init.start,
|
|
372
|
+
end: item.init.end,
|
|
373
|
+
replacement: "true"
|
|
374
|
+
});
|
|
375
|
+
prerenderStrippedRanges.push([item.init.start, item.init.end]);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (serverLocalNames.size === 0 && prerenderFnEdits.length === 0 && (!hasServerSubpathImport || options.ssr)) return null;
|
|
381
|
+
const colocatedCalls = [];
|
|
382
|
+
let callIndex = 0;
|
|
383
|
+
function findCalls(node, assignedName) {
|
|
384
|
+
if (!node?.type || node.type.startsWith("TS")) return;
|
|
385
|
+
if (node.type === "CallExpression" && node.callee.type === "Identifier" && serverLocalNames.has(node.callee.name) && node.arguments.length >= 1) {
|
|
386
|
+
const name = assignedName ?? `anon_${callIndex}`;
|
|
387
|
+
const isStream = isGeneratorFnNode(node.arguments.at(-1));
|
|
388
|
+
const id = computeRpcId(cleanUrl, name, callIndex++, hashIds);
|
|
389
|
+
colocatedCalls.push({
|
|
390
|
+
callNode: node,
|
|
391
|
+
name,
|
|
392
|
+
id,
|
|
393
|
+
isStream
|
|
394
|
+
});
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
|
|
398
|
+
findCalls(node.init, node.id.name);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
const fields = node;
|
|
402
|
+
for (const key of visitorKeys[node.type] ?? []) {
|
|
403
|
+
const field = fields[key];
|
|
404
|
+
if (Array.isArray(field)) {
|
|
405
|
+
for (const item of field) if (item?.type) findCalls(item);
|
|
406
|
+
} else if (field?.type) findCalls(field);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
findCalls(program);
|
|
410
|
+
if (colocatedCalls.length === 0 && prerenderFnEdits.length === 0) {
|
|
411
|
+
if (!options.ssr && hasServerSubpathImport) throw new Error(`[c7t] "${cleanUrl}" imports server-only module "@fierst/c7t/server" in client code outside a server(...) block.`);
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
const rpcs = colocatedCalls.map((c) => ({
|
|
415
|
+
name: c.name,
|
|
416
|
+
id: c.id,
|
|
417
|
+
isStream: c.isStream
|
|
418
|
+
}));
|
|
419
|
+
if (options.ssr) {
|
|
420
|
+
if (colocatedCalls.length === 0) return null;
|
|
421
|
+
return {
|
|
422
|
+
code: `import { registerServerFn as __c7tReg } from '@fierst/c7t/server';\n` + applyEdits(code, colocatedCalls.map((c) => {
|
|
423
|
+
const firstArg = c.callNode.arguments[0];
|
|
424
|
+
return {
|
|
425
|
+
start: c.callNode.start,
|
|
426
|
+
end: firstArg.start,
|
|
427
|
+
replacement: `__c7tReg(${JSON.stringify(c.id)}, `
|
|
428
|
+
};
|
|
429
|
+
})),
|
|
430
|
+
rpcs
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
const strippedRanges = [...colocatedCalls.map((c) => [c.callNode.start, c.callNode.end]), ...prerenderStrippedRanges];
|
|
434
|
+
const isInsideStripped = (pos) => strippedRanges.some(([s, e]) => pos >= s && pos < e);
|
|
435
|
+
const usedRuntimeIds = /* @__PURE__ */ new Set();
|
|
436
|
+
function collectUsedIds(node, parent, propKey) {
|
|
437
|
+
if (!node?.type) return;
|
|
438
|
+
if (isInsideStripped(node.start)) return;
|
|
439
|
+
if (node.type === "ImportDeclaration") return;
|
|
440
|
+
if (node.type.startsWith("TS")) return;
|
|
441
|
+
if (node.type === "Identifier") {
|
|
442
|
+
if (parent?.type === "MemberExpression" && propKey === "property" && !parent.computed) return;
|
|
443
|
+
if (parent?.type === "Property" && propKey === "key" && !parent.computed && !parent.shorthand) return;
|
|
444
|
+
if ((parent?.type === "FunctionDeclaration" || parent?.type === "FunctionExpression" || parent?.type === "ClassDeclaration") && propKey === "id") return;
|
|
445
|
+
if (parent?.type === "JSXAttribute" || parent?.type === "JSXOpeningElement" || parent?.type === "JSXClosingElement") {
|
|
446
|
+
if (propKey === "name" && /^[a-z]/.test(node.name)) return;
|
|
447
|
+
}
|
|
448
|
+
usedRuntimeIds.add(node.name);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (node.type === "JSXIdentifier") {
|
|
452
|
+
if (/^[A-Z]/.test(node.name)) usedRuntimeIds.add(node.name);
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
const fields = node;
|
|
456
|
+
for (const key of visitorKeys[node.type] ?? []) {
|
|
457
|
+
const field = fields[key];
|
|
458
|
+
if (Array.isArray(field)) {
|
|
459
|
+
for (const item of field) if (item?.type) collectUsedIds(item, node, key);
|
|
460
|
+
} else if (field?.type) collectUsedIds(field, node, key);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
collectUsedIds(program);
|
|
464
|
+
const edits = [...colocatedCalls.map((c) => ({
|
|
465
|
+
start: c.callNode.start,
|
|
466
|
+
end: c.callNode.end,
|
|
467
|
+
replacement: `${c.isStream ? "__c7tStream" : "__c7tRpc"}(${JSON.stringify(c.id)})`
|
|
468
|
+
})), ...prerenderFnEdits];
|
|
469
|
+
for (const stmt of program.body) {
|
|
470
|
+
if (stmt.type !== "ImportDeclaration" || stmt.importKind === "type") continue;
|
|
471
|
+
if (stmt.specifiers.length === 0) continue;
|
|
472
|
+
const keptSpecs = stmt.specifiers.filter((spec) => {
|
|
473
|
+
if (spec.exportKind === "type" || spec.importKind === "type") return true;
|
|
474
|
+
return usedRuntimeIds.has(spec.local.name);
|
|
475
|
+
});
|
|
476
|
+
if (stmt.source.value === "@fierst/c7t/server") {
|
|
477
|
+
const runtimeKept = keptSpecs.filter((s) => s.importKind !== "type");
|
|
478
|
+
if (runtimeKept.length > 0) {
|
|
479
|
+
const leaked = runtimeKept.map((s) => s.local.name).join(", ");
|
|
480
|
+
throw new Error(`[c7t] "${cleanUrl}" references server-only import(s) (${leaked}) from "@fierst/c7t/server" in client code outside server(...).`);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
if (keptSpecs.length === 0) {
|
|
484
|
+
let end = stmt.end;
|
|
485
|
+
if (code[end] === "\r") end++;
|
|
486
|
+
if (code[end] === "\n") end++;
|
|
487
|
+
edits.push({
|
|
488
|
+
start: stmt.start,
|
|
489
|
+
end,
|
|
490
|
+
replacement: ""
|
|
491
|
+
});
|
|
492
|
+
} else if (keptSpecs.length < stmt.specifiers.length) {
|
|
493
|
+
const defaultSpec = keptSpecs.find((s) => s.type === "ImportDefaultSpecifier");
|
|
494
|
+
const nsSpec = keptSpecs.find((s) => s.type === "ImportNamespaceSpecifier");
|
|
495
|
+
const namedSpecs = keptSpecs.filter((s) => s.type === "ImportSpecifier");
|
|
496
|
+
const parts = [];
|
|
497
|
+
if (defaultSpec) parts.push(defaultSpec.local.name);
|
|
498
|
+
if (nsSpec) parts.push(`* as ${nsSpec.local.name}`);
|
|
499
|
+
if (namedSpecs.length > 0) {
|
|
500
|
+
const namedStr = namedSpecs.map((s) => code.slice(s.start, s.end)).join(", ");
|
|
501
|
+
parts.push(`{ ${namedStr} }`);
|
|
502
|
+
}
|
|
503
|
+
edits.push({
|
|
504
|
+
start: stmt.start,
|
|
505
|
+
end: stmt.end,
|
|
506
|
+
replacement: `import ${parts.join(", ")} from ${code.slice(stmt.source.start, stmt.source.end)};`
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
const needRpc = colocatedCalls.some((c) => !c.isStream);
|
|
511
|
+
const needStream = colocatedCalls.some((c) => c.isStream);
|
|
512
|
+
const clientSpecs = [];
|
|
513
|
+
if (needRpc) clientSpecs.push("createRpcStub as __c7tRpc");
|
|
514
|
+
if (needStream) clientSpecs.push("createStreamStub as __c7tStream");
|
|
515
|
+
return {
|
|
516
|
+
code: (clientSpecs.length > 0 ? `import { ${clientSpecs.join(", ")} } from '@fierst/c7t/client';\n` : "") + applyEdits(code, edits),
|
|
517
|
+
rpcs
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
let activeSsrBuildCtx = null;
|
|
521
|
+
/** @internal Used by `buildApp()` to pass Stage 1 client manifest & adapter target into Stage 2 SSR build. */
|
|
522
|
+
function _setActiveSsrBuildContext(ctx) {
|
|
523
|
+
activeSsrBuildCtx = ctx;
|
|
524
|
+
}
|
|
525
|
+
const HTTP_METHODS = /* @__PURE__ */ new Set([
|
|
526
|
+
"GET",
|
|
527
|
+
"POST",
|
|
528
|
+
"PUT",
|
|
529
|
+
"PATCH",
|
|
530
|
+
"DELETE",
|
|
531
|
+
"HEAD",
|
|
532
|
+
"OPTIONS"
|
|
533
|
+
]);
|
|
534
|
+
function inspectRouteModuleExports(fullPath) {
|
|
535
|
+
try {
|
|
536
|
+
const prog = parseProgram(readFileSync(fullPath, "utf-8"), fullPath);
|
|
537
|
+
let hasDefault = false;
|
|
538
|
+
let hasPrerender = false;
|
|
539
|
+
let hasCsr = false;
|
|
540
|
+
const httpMethods = [];
|
|
541
|
+
for (const stmt of prog.body) {
|
|
542
|
+
if (stmt.type === "ExportDefaultDeclaration") {
|
|
543
|
+
hasDefault = true;
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
if (stmt.type !== "ExportNamedDeclaration" || stmt.exportKind === "type") continue;
|
|
547
|
+
const decl = stmt.declaration;
|
|
548
|
+
if (decl?.type === "FunctionDeclaration" && decl.id) {
|
|
549
|
+
const name = decl.id.name;
|
|
550
|
+
if (HTTP_METHODS.has(name)) httpMethods.push(name);
|
|
551
|
+
if (name === "prerender") hasPrerender = true;
|
|
552
|
+
} else if (decl?.type === "VariableDeclaration") {
|
|
553
|
+
for (const d of decl.declarations) if (d.id.type === "Identifier") {
|
|
554
|
+
const name = d.id.name;
|
|
555
|
+
if (HTTP_METHODS.has(name)) httpMethods.push(name);
|
|
556
|
+
if (name === "prerender") hasPrerender = true;
|
|
557
|
+
if (name === "csr") hasCsr = true;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
for (const spec of stmt.specifiers) {
|
|
561
|
+
if (spec.exportKind === "type") continue;
|
|
562
|
+
const exported = spec.exported.type === "Identifier" ? spec.exported.name : spec.exported.value;
|
|
563
|
+
if (exported === "default") hasDefault = true;
|
|
564
|
+
if (HTTP_METHODS.has(exported)) httpMethods.push(exported);
|
|
565
|
+
if (exported === "prerender") hasPrerender = true;
|
|
566
|
+
if (exported === "csr") hasCsr = true;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return {
|
|
570
|
+
hasDefault,
|
|
571
|
+
httpMethods,
|
|
572
|
+
hasPrerender,
|
|
573
|
+
hasCsr
|
|
574
|
+
};
|
|
575
|
+
} catch {
|
|
576
|
+
return {
|
|
577
|
+
hasDefault: true,
|
|
578
|
+
httpMethods: [],
|
|
579
|
+
hasPrerender: false,
|
|
580
|
+
hasCsr: false
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
function scanRouteFiles(absRoutesDir) {
|
|
585
|
+
if (!existsSync(absRoutesDir)) return [];
|
|
586
|
+
const results = [];
|
|
587
|
+
function walk(dir) {
|
|
588
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
589
|
+
const full = join(dir, entry.name);
|
|
590
|
+
if (entry.isDirectory()) walk(full);
|
|
591
|
+
else if (/\.(tsx|ts|jsx|js)$/.test(entry.name) && !entry.name.endsWith(".d.ts") && !isServerModulePath(entry.name) && !entry.name.includes(".test.")) results.push(full);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
walk(absRoutesDir);
|
|
595
|
+
results.sort();
|
|
596
|
+
return results;
|
|
597
|
+
}
|
|
598
|
+
function importsCreateServerFromC7t(code, cleanId) {
|
|
599
|
+
if (!code.includes("createServer") || !code.includes("@fierst/c7t/server")) return false;
|
|
600
|
+
try {
|
|
601
|
+
const program = parseProgram(code, cleanId);
|
|
602
|
+
for (const stmt of program.body) if (stmt.type === "ImportDeclaration" && stmt.importKind !== "type" && stmt.source.value === "@fierst/c7t/server") {
|
|
603
|
+
for (const spec of stmt.specifiers) if (spec.type === "ImportSpecifier" && spec.importKind !== "type" && spec.imported.type === "Identifier" && spec.imported.name === "createServer") return true;
|
|
604
|
+
}
|
|
605
|
+
} catch {
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
function shouldBypassDevSsr(urlPath) {
|
|
611
|
+
if (urlPath.startsWith("/@") || urlPath.startsWith("/__vitest") || urlPath.startsWith("/node_modules/")) return true;
|
|
612
|
+
const clean = urlPath.split("?")[0];
|
|
613
|
+
return /\.(js|mjs|ts|tsx|jsx|css|json|map|svg|png|jpg|jpeg|gif|webp|ico|woff|woff2)$/.test(clean);
|
|
614
|
+
}
|
|
615
|
+
function collectDevStylesFromGraph(viteServer) {
|
|
616
|
+
const styles = [];
|
|
617
|
+
const idMap = viteServer?.moduleGraph?.idToModuleMap;
|
|
618
|
+
if (!idMap) return styles;
|
|
619
|
+
const seen = /* @__PURE__ */ new Set();
|
|
620
|
+
for (const mod of idMap.values()) {
|
|
621
|
+
const url = mod?.url;
|
|
622
|
+
if (!url || typeof url !== "string") continue;
|
|
623
|
+
if (!url.split("?")[0].endsWith(".css")) continue;
|
|
624
|
+
const directHref = url.includes("?") ? `${url}&direct` : `${url}?direct`;
|
|
625
|
+
if (seen.has(directHref)) continue;
|
|
626
|
+
seen.add(directHref);
|
|
627
|
+
styles.push(directHref);
|
|
628
|
+
}
|
|
629
|
+
return styles;
|
|
630
|
+
}
|
|
631
|
+
function c7t(options = {}) {
|
|
632
|
+
const routesDirRel = options.routesDir ?? "src/routes";
|
|
633
|
+
const virtualRoutesId = "virtual:c7t/routes";
|
|
634
|
+
const resolvedVirtualRoutesId = "\0" + virtualRoutesId;
|
|
635
|
+
const virtualClientEntryId = "virtual:c7t/client-entry";
|
|
636
|
+
const resolvedVirtualClientEntryId = "\0" + virtualClientEntryId;
|
|
637
|
+
const virtualIslandsEntryId = "virtual:c7t/islands-entry";
|
|
638
|
+
const resolvedVirtualIslandsEntryId = "\0" + virtualIslandsEntryId;
|
|
639
|
+
const virtualDefaultServerId = "virtual:c7t/default-server";
|
|
640
|
+
const resolvedVirtualDefaultServerId = "\0" + virtualDefaultServerId;
|
|
641
|
+
const virtualSsrEntryId = "virtual:c7t/ssr-entry";
|
|
642
|
+
const resolvedVirtualSsrEntryId = "\0" + virtualSsrEntryId;
|
|
643
|
+
const devClientRevivalUrl = `/@id/__x00__${virtualClientEntryId}`;
|
|
644
|
+
const devIslandsRevivalUrl = `/@id/__x00__${virtualIslandsEntryId}`;
|
|
645
|
+
let rootDir = "";
|
|
646
|
+
let base = "/";
|
|
647
|
+
let isBuild = false;
|
|
648
|
+
let isSsrBuild = false;
|
|
649
|
+
const clientChunkRefs = /* @__PURE__ */ new Map();
|
|
650
|
+
function toRelUrl(absId) {
|
|
651
|
+
const norm = absId.replace(/\\/g, "/");
|
|
652
|
+
if (rootDir && norm.startsWith(rootDir)) {
|
|
653
|
+
const rel = norm.slice(rootDir.length);
|
|
654
|
+
return rel.startsWith("/") ? rel : "/" + rel;
|
|
655
|
+
}
|
|
656
|
+
return norm;
|
|
657
|
+
}
|
|
658
|
+
function resolveServerEntryPath() {
|
|
659
|
+
if (options.serverEntry) return options.serverEntry.startsWith("/") ? options.serverEntry : "/" + options.serverEntry;
|
|
660
|
+
const baseDir = rootDir || process.cwd();
|
|
661
|
+
for (const candidate of [
|
|
662
|
+
"src/server.ts",
|
|
663
|
+
"src/server.tsx",
|
|
664
|
+
"src/app.ts"
|
|
665
|
+
]) if (existsSync(join(baseDir, candidate))) return "/" + candidate;
|
|
666
|
+
if (existsSync(join(baseDir, routesDirRel))) return virtualDefaultServerId;
|
|
667
|
+
return null;
|
|
668
|
+
}
|
|
669
|
+
function resolveProdBuildAssets() {
|
|
670
|
+
if (activeSsrBuildCtx) return {
|
|
671
|
+
manifest: activeSsrBuildCtx.manifest,
|
|
672
|
+
styles: activeSsrBuildCtx.styles
|
|
673
|
+
};
|
|
674
|
+
if (isBuild) {
|
|
675
|
+
const diskPath = join(rootDir || process.cwd(), "dist", "client", "c7t-manifest.json");
|
|
676
|
+
if (existsSync(diskPath)) try {
|
|
677
|
+
const parsed = JSON.parse(readFileSync(diskPath, "utf-8"));
|
|
678
|
+
return {
|
|
679
|
+
manifest: parsed.manifest ?? null,
|
|
680
|
+
styles: parsed.styles ?? []
|
|
681
|
+
};
|
|
682
|
+
} catch {}
|
|
683
|
+
}
|
|
684
|
+
return {
|
|
685
|
+
manifest: null,
|
|
686
|
+
styles: []
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
function resolveConfiguredAdapterName() {
|
|
690
|
+
if (activeSsrBuildCtx) return activeSsrBuildCtx.adapterName;
|
|
691
|
+
if (!options.adapter) return "node";
|
|
692
|
+
return typeof options.adapter === "string" ? options.adapter : options.adapter.name;
|
|
693
|
+
}
|
|
694
|
+
function resolveRouteDefaults() {
|
|
695
|
+
const adapterName = resolveConfiguredAdapterName();
|
|
696
|
+
const prerenderDefault = options.prerender === true || options.prerender === "all" || adapterName === "static" ? true : void 0;
|
|
697
|
+
const out = {};
|
|
698
|
+
if (prerenderDefault !== void 0) out.prerender = prerenderDefault;
|
|
699
|
+
if (options.csr !== void 0) out.csr = options.csr;
|
|
700
|
+
return out;
|
|
701
|
+
}
|
|
702
|
+
return [
|
|
703
|
+
{
|
|
704
|
+
name: "c7t:compiler",
|
|
705
|
+
enforce: "pre",
|
|
706
|
+
__c7tOptions: options,
|
|
707
|
+
config(userConfig, env) {
|
|
708
|
+
const patch = { resolve: { dedupe: ["@fierst/blokd", "@fierst/c7t"] } };
|
|
709
|
+
if (env.command === "build" && !env.isSsrBuild && !userConfig.build?.ssr) {
|
|
710
|
+
const cfgRoot = userConfig.root ?? process.cwd();
|
|
711
|
+
const hasInput = Boolean(userConfig.build?.rollupOptions?.input);
|
|
712
|
+
const hasIndexHtml = existsSync(join(cfgRoot, "index.html"));
|
|
713
|
+
if (!hasInput && !hasIndexHtml) patch.build = { rollupOptions: { input: virtualClientEntryId } };
|
|
714
|
+
}
|
|
715
|
+
return patch;
|
|
716
|
+
},
|
|
717
|
+
configResolved(config) {
|
|
718
|
+
rootDir = (config.root ?? process.cwd()).replace(/\\/g, "/").replace(/\/$/, "");
|
|
719
|
+
base = config.base ?? "/";
|
|
720
|
+
isBuild = config.command === "build";
|
|
721
|
+
isSsrBuild = Boolean(config.build?.ssr);
|
|
722
|
+
},
|
|
723
|
+
resolveId(id) {
|
|
724
|
+
if (id === virtualRoutesId) return resolvedVirtualRoutesId;
|
|
725
|
+
if (id === virtualClientEntryId) return resolvedVirtualClientEntryId;
|
|
726
|
+
if (id === virtualIslandsEntryId) return resolvedVirtualIslandsEntryId;
|
|
727
|
+
if (id === virtualDefaultServerId) return resolvedVirtualDefaultServerId;
|
|
728
|
+
if (id === virtualSsrEntryId) return resolvedVirtualSsrEntryId;
|
|
729
|
+
},
|
|
730
|
+
load(id, loadOpts) {
|
|
731
|
+
if (id === resolvedVirtualClientEntryId) return `import { routes, specialRoutes } from ${JSON.stringify(virtualRoutesId)};\nimport { installC7t } from '@fierst/c7t/client';\nexport function installRevival(runtimeUrl) {\n return installC7t({ runtimeUrl, routes, errorComponent: specialRoutes.error });\n}\n`;
|
|
732
|
+
if (id === resolvedVirtualIslandsEntryId) return "import { installReceiptResolver } from '@fierst/c7t/client';\nimport { installRevival as installBlokdRevival } from '@fierst/blokd/revive';\nexport function installRevival(runtimeUrl) {\n const disposeReceipts = installReceiptResolver();\n const disposeRevival = installBlokdRevival(runtimeUrl);\n return () => {\n disposeRevival();\n disposeReceipts();\n };\n}\n";
|
|
733
|
+
if (id === resolvedVirtualDefaultServerId) {
|
|
734
|
+
const { manifest: prodManifest, styles: prodStyles } = isBuild ? resolveProdBuildAssets() : {
|
|
735
|
+
manifest: null,
|
|
736
|
+
styles: []
|
|
737
|
+
};
|
|
738
|
+
const revivalUrl = isBuild ? null : devClientRevivalUrl;
|
|
739
|
+
const islandsUrl = isBuild ? null : devIslandsRevivalUrl;
|
|
740
|
+
const routeDefaults = resolveRouteDefaults();
|
|
741
|
+
return `import { routeEntries } from ${JSON.stringify(virtualRoutesId)};\nimport { _setDefaultRoutes, createServer } from '@fierst/c7t/server';\n_setDefaultRoutes(routeEntries, ${JSON.stringify(revivalUrl)}, ${JSON.stringify(prodManifest)}, ${JSON.stringify(prodStyles)}, ${JSON.stringify(routeDefaults)}, ${JSON.stringify(islandsUrl)});\nexport { routeEntries };\nexport default createServer({ routes: routeEntries });\n`;
|
|
742
|
+
}
|
|
743
|
+
if (id === resolvedVirtualSsrEntryId) {
|
|
744
|
+
const target = resolveServerEntryPath() ?? virtualDefaultServerId;
|
|
745
|
+
const adapterName = resolveConfiguredAdapterName();
|
|
746
|
+
const adapterExport = adapterName === "node" ? `export { serveNode, createNodeHandler } from '@fierst/c7t/node';\n` : adapterName === "bun" ? `export { serveBun, createBunFetchHandler } from '@fierst/c7t/bun';\n` : adapterName === "cloudflare" ? `export { cloudflareAdapter } from '@fierst/c7t/cloudflare';\n` : "";
|
|
747
|
+
return `import app from ${JSON.stringify(target)};\nimport { routeEntries } from ${JSON.stringify(virtualRoutesId)};\n` + adapterExport + "export { app, routeEntries };\nexport default app;\n";
|
|
748
|
+
}
|
|
749
|
+
if (id !== resolvedVirtualRoutesId) return null;
|
|
750
|
+
const isSsrLoad = Boolean(loadOpts?.ssr);
|
|
751
|
+
const absRoutes = join(rootDir || process.cwd(), routesDirRel);
|
|
752
|
+
const files = scanRouteFiles(absRoutes);
|
|
753
|
+
const imports = [];
|
|
754
|
+
const entries = [];
|
|
755
|
+
let modIdx = 0;
|
|
756
|
+
for (const fullPath of files) {
|
|
757
|
+
const meta = inspectRouteModuleExports(fullPath);
|
|
758
|
+
if (!isSsrLoad && !meta.hasDefault) continue;
|
|
759
|
+
const i = modIdx++;
|
|
760
|
+
const relFromRoutes = relative(absRoutes, fullPath).replace(/\\/g, "/");
|
|
761
|
+
const viteUrl = toRelUrl(fullPath);
|
|
762
|
+
imports.push(`import * as _r${i} from ${JSON.stringify(viteUrl)};`);
|
|
763
|
+
const propParts = [`file: ${JSON.stringify(relFromRoutes)}`];
|
|
764
|
+
if (meta.hasDefault) {
|
|
765
|
+
propParts.push(`component: _r${i}.default`);
|
|
766
|
+
propParts.push(`load: () => Promise.resolve(_r${i})`);
|
|
767
|
+
}
|
|
768
|
+
if (meta.hasPrerender) propParts.push(isSsrLoad ? `prerender: _r${i}.prerender` : `prerender: Boolean(_r${i}.prerender)`);
|
|
769
|
+
if (meta.hasCsr) propParts.push(`csr: _r${i}.csr`);
|
|
770
|
+
if (isSsrLoad && meta.httpMethods.length > 0) {
|
|
771
|
+
const methodList = meta.httpMethods.map((m) => `${m}: _r${i}.${m}`).join(", ");
|
|
772
|
+
propParts.push(`handlers: { ${methodList} }`);
|
|
773
|
+
}
|
|
774
|
+
entries.push(` { ${propParts.join(", ")} }`);
|
|
775
|
+
}
|
|
776
|
+
const routeDefaults = resolveRouteDefaults();
|
|
777
|
+
return `import { buildRoutes, extractSpecialRoutes } from '@fierst/c7t/router';\n` + imports.join("\n") + `\nexport const routeEntries = [\n${entries.join(",\n")}\n];\nexport const routes = buildRoutes(routeEntries, ${JSON.stringify(routeDefaults)});\nexport const specialRoutes = extractSpecialRoutes(routeEntries);\nexport default routes;\n`;
|
|
778
|
+
},
|
|
779
|
+
transform(code, id, transformOpts) {
|
|
780
|
+
const cleanId = id.split("?")[0].replace(/\\/g, "/");
|
|
781
|
+
if (cleanId.includes("/node_modules/") || cleanId.startsWith("\0")) return null;
|
|
782
|
+
if (!/\.(tsx|ts|jsx|js|mts|mjs)$/.test(cleanId) || cleanId.endsWith(".d.ts")) return null;
|
|
783
|
+
const ssr = Boolean(transformOpts?.ssr);
|
|
784
|
+
let workingCode = code;
|
|
785
|
+
let autoWiredRoutes = false;
|
|
786
|
+
const isTestFile = /\.(test|spec)\.(ts|tsx|js|jsx)$/.test(cleanId);
|
|
787
|
+
if (ssr && !isTestFile && importsCreateServerFromC7t(workingCode, cleanId) && existsSync(join(rootDir || process.cwd(), routesDirRel))) {
|
|
788
|
+
const revivalTarget = isBuild ? null : devClientRevivalUrl;
|
|
789
|
+
const islandsTarget = isBuild ? null : devIslandsRevivalUrl;
|
|
790
|
+
const routeDefaults = resolveRouteDefaults();
|
|
791
|
+
const { manifest: prodManifest, styles: prodStyles } = isBuild ? resolveProdBuildAssets() : {
|
|
792
|
+
manifest: null,
|
|
793
|
+
styles: []
|
|
794
|
+
};
|
|
795
|
+
workingCode = `import { routeEntries as __c7tAutoRoutes } from ${JSON.stringify(virtualRoutesId)};\nimport { _setDefaultRoutes as __c7tSetDefaultRoutes } from '@fierst/c7t/server';\n__c7tSetDefaultRoutes(__c7tAutoRoutes, ${JSON.stringify(revivalTarget)}, ${JSON.stringify(prodManifest)}, ${JSON.stringify(prodStyles)}, ${JSON.stringify(routeDefaults)}, ${JSON.stringify(islandsTarget)});\n` + workingCode;
|
|
796
|
+
autoWiredRoutes = true;
|
|
797
|
+
}
|
|
798
|
+
const result = compileC7tModule(workingCode, {
|
|
799
|
+
moduleUrl: toRelUrl(cleanId),
|
|
800
|
+
ssr,
|
|
801
|
+
hashIds: options.hashIds ?? isBuild
|
|
802
|
+
});
|
|
803
|
+
if (!result) return autoWiredRoutes ? {
|
|
804
|
+
code: workingCode,
|
|
805
|
+
map: null
|
|
806
|
+
} : null;
|
|
807
|
+
return {
|
|
808
|
+
code: result.code,
|
|
809
|
+
map: null
|
|
810
|
+
};
|
|
811
|
+
},
|
|
812
|
+
configureServer(viteServer) {
|
|
813
|
+
if (!options.serverEntry && viteServer.config?.mode === "test") return;
|
|
814
|
+
return () => {
|
|
815
|
+
viteServer.middlewares.use(async (nodeReq, nodeRes, next) => {
|
|
816
|
+
const rawUrl = nodeReq.url || "/";
|
|
817
|
+
if (!rawUrl.startsWith("/_c7t/") && shouldBypassDevSsr(rawUrl)) return next();
|
|
818
|
+
const targetEntry = resolveServerEntryPath();
|
|
819
|
+
if (!targetEntry) return next();
|
|
820
|
+
try {
|
|
821
|
+
const app = (await viteServer.ssrLoadModule(targetEntry)).default;
|
|
822
|
+
if (!app || typeof app.fetch !== "function") return next();
|
|
823
|
+
const url = `${nodeReq.socket?.encrypted ? "https" : "http"}://${nodeReq.headers.host || "localhost"}${nodeReq.url || "/"}`;
|
|
824
|
+
const method = nodeReq.method || "GET";
|
|
825
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
826
|
+
const abortController = new AbortController();
|
|
827
|
+
nodeRes.on("close", () => {
|
|
828
|
+
if (!nodeRes.writableEnded) abortController.abort();
|
|
829
|
+
});
|
|
830
|
+
const reqHeaders = new Headers(nodeReq.headers);
|
|
831
|
+
const devStyles = collectDevStylesFromGraph(viteServer);
|
|
832
|
+
if (devStyles.length > 0) reqHeaders.set("x-c7t-dev-styles", JSON.stringify(devStyles));
|
|
833
|
+
const webReq = new Request(url, {
|
|
834
|
+
method,
|
|
835
|
+
headers: reqHeaders,
|
|
836
|
+
body: hasBody ? nodeReq : void 0,
|
|
837
|
+
signal: abortController.signal,
|
|
838
|
+
...hasBody ? { duplex: "half" } : {}
|
|
839
|
+
});
|
|
840
|
+
const webRes = await app.fetch(webReq);
|
|
841
|
+
nodeRes.statusCode = webRes.status;
|
|
842
|
+
webRes.headers.forEach((v, k) => {
|
|
843
|
+
if (k.toLowerCase() === "set-cookie") return;
|
|
844
|
+
nodeRes.setHeader(k, v);
|
|
845
|
+
});
|
|
846
|
+
const setCookies = typeof webRes.headers.getSetCookie === "function" ? webRes.headers.getSetCookie() : [];
|
|
847
|
+
if (setCookies.length > 0) nodeRes.setHeader("Set-Cookie", setCookies);
|
|
848
|
+
if (!webRes.body) {
|
|
849
|
+
nodeRes.end();
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
const reader = webRes.body.getReader();
|
|
853
|
+
nodeRes.on("close", () => {
|
|
854
|
+
if (!nodeRes.writableEnded) reader.cancel();
|
|
855
|
+
});
|
|
856
|
+
while (true) {
|
|
857
|
+
const { done, value } = await reader.read();
|
|
858
|
+
if (done) break;
|
|
859
|
+
nodeRes.write(value);
|
|
860
|
+
}
|
|
861
|
+
nodeRes.end();
|
|
862
|
+
} catch (err) {
|
|
863
|
+
viteServer.ssrFixStacktrace?.(err);
|
|
864
|
+
next(err);
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
},
|
|
870
|
+
blokd(options.blokd),
|
|
871
|
+
{
|
|
872
|
+
name: "c7t:manifest",
|
|
873
|
+
enforce: "post",
|
|
874
|
+
buildStart() {
|
|
875
|
+
clientChunkRefs.clear();
|
|
876
|
+
if (!isBuild || isSsrBuild || typeof this?.emitFile !== "function") return;
|
|
877
|
+
clientChunkRefs.set("@fierst/c7t/client-entry", this.emitFile({
|
|
878
|
+
type: "chunk",
|
|
879
|
+
id: virtualClientEntryId,
|
|
880
|
+
preserveSignature: "allow-extension"
|
|
881
|
+
}));
|
|
882
|
+
clientChunkRefs.set("@fierst/c7t/islands-entry", this.emitFile({
|
|
883
|
+
type: "chunk",
|
|
884
|
+
id: virtualIslandsEntryId,
|
|
885
|
+
preserveSignature: "allow-extension"
|
|
886
|
+
}));
|
|
887
|
+
clientChunkRefs.set("@fierst/c7t/router", this.emitFile({
|
|
888
|
+
type: "chunk",
|
|
889
|
+
id: "@fierst/c7t/router",
|
|
890
|
+
preserveSignature: "allow-extension"
|
|
891
|
+
}));
|
|
892
|
+
},
|
|
893
|
+
generateBundle(_outputOptions, bundle) {
|
|
894
|
+
if (!isBuild || isSsrBuild || typeof this?.emitFile !== "function") return;
|
|
895
|
+
const cleanBase = base.endsWith("/") ? base : base + "/";
|
|
896
|
+
const blokdAsset = bundle[options.blokd?.manifestFile ?? "blokd-manifest.json"];
|
|
897
|
+
let manifest = {};
|
|
898
|
+
if (blokdAsset && blokdAsset.type === "asset" && typeof blokdAsset.source === "string") try {
|
|
899
|
+
manifest = JSON.parse(blokdAsset.source);
|
|
900
|
+
} catch {
|
|
901
|
+
manifest = {};
|
|
902
|
+
}
|
|
903
|
+
for (const [specifier, ref] of clientChunkRefs) manifest[specifier] = cleanBase + this.getFileName(ref);
|
|
904
|
+
const styles = [];
|
|
905
|
+
for (const item of Object.values(bundle)) if (item.type === "asset" && typeof item.fileName === "string" && item.fileName.endsWith(".css")) styles.push(`${cleanBase}${item.fileName}`);
|
|
906
|
+
if (blokdAsset && blokdAsset.type === "asset") blokdAsset.source = JSON.stringify(manifest, null, 2) + "\n";
|
|
907
|
+
const payload = {
|
|
908
|
+
manifest,
|
|
909
|
+
styles
|
|
910
|
+
};
|
|
911
|
+
this.emitFile({
|
|
912
|
+
type: "asset",
|
|
913
|
+
fileName: "c7t-manifest.json",
|
|
914
|
+
source: JSON.stringify(payload, null, 2) + "\n"
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
];
|
|
919
|
+
}
|
|
920
|
+
export { _setActiveSsrBuildContext, buildApp, c7t, c7t as default, compileC7tModule, computeRpcId };
|