@fierst/c7t 0.0.0-stage → 1.0.0-beta.1
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 +337 -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 +122 -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
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
import { ErrorBoundary, _comp, _setReceiptResolver, _setStepCacheResolver, _slot, _tpl, createContext, mountComponent, provide, useContext } from "@fierst/blokd";
|
|
2
|
+
// src/receipts.ts
|
|
3
|
+
function escapeScriptJson(value) {
|
|
4
|
+
return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
|
|
5
|
+
}
|
|
6
|
+
function nonceAttr(nonce) {
|
|
7
|
+
if (nonce === void 0) return "";
|
|
8
|
+
return ` nonce="${nonce.replace(/&/g, "&").replace(/"/g, """)}"`;
|
|
9
|
+
}
|
|
10
|
+
function stableArgsKey(args) {
|
|
11
|
+
try {
|
|
12
|
+
return JSON.stringify(args, (_k, val) => {
|
|
13
|
+
if (val && typeof val === "object" && !Array.isArray(val) && !(val instanceof Date)) {
|
|
14
|
+
const sorted = {};
|
|
15
|
+
for (const key of Object.keys(val).sort()) sorted[key] = val[key];
|
|
16
|
+
return sorted;
|
|
17
|
+
}
|
|
18
|
+
return val;
|
|
19
|
+
});
|
|
20
|
+
} catch {
|
|
21
|
+
return String(Math.random());
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const RESERVED_KEYS = /* @__PURE__ */ new Set([
|
|
25
|
+
"$undef",
|
|
26
|
+
"$date",
|
|
27
|
+
"$query",
|
|
28
|
+
"$ref"
|
|
29
|
+
]);
|
|
30
|
+
/**
|
|
31
|
+
* Create a per-request SSR ReceiptCollector that:
|
|
32
|
+
* 1. Memoizes identical `(id, args)` step executions across the SSR component tree.
|
|
33
|
+
* 2. Deduplicates repeated objects/arrays across components into a compact `$ref` pool.
|
|
34
|
+
* 3. Emits both initial shell `<script>` and out-of-order streaming `<script>` receipt chunks.
|
|
35
|
+
*/
|
|
36
|
+
function createReceiptCollector() {
|
|
37
|
+
let nextReceiptNum = 0;
|
|
38
|
+
const pool = [];
|
|
39
|
+
let flushedPoolCursor = 0;
|
|
40
|
+
const objToPoolIdx = /* @__PURE__ */ new Map();
|
|
41
|
+
const jsonToPoolIdx = /* @__PURE__ */ new Map();
|
|
42
|
+
const receipts = {};
|
|
43
|
+
const flushedReceipts = /* @__PURE__ */ new Set();
|
|
44
|
+
const memoCache = /* @__PURE__ */ new Map();
|
|
45
|
+
function encodeRaw(val, topLevelStep = false) {
|
|
46
|
+
if (val === void 0) return { $undef: 1 };
|
|
47
|
+
if (val === null || typeof val === "boolean" || typeof val === "string") return val;
|
|
48
|
+
if (typeof val === "number") return Number.isFinite(val) ? val : null;
|
|
49
|
+
if (val instanceof Date) return { $date: val.toISOString() };
|
|
50
|
+
if (val instanceof URLSearchParams) return { $query: val.toString() };
|
|
51
|
+
if (typeof val === "object") {
|
|
52
|
+
const existingIdx = objToPoolIdx.get(val);
|
|
53
|
+
if (existingIdx !== void 0) return { $ref: existingIdx };
|
|
54
|
+
let encoded;
|
|
55
|
+
if (Array.isArray(val)) encoded = val.map((item) => encodeRaw(item, false));
|
|
56
|
+
else {
|
|
57
|
+
const out = {};
|
|
58
|
+
for (const [k, v] of Object.entries(val)) {
|
|
59
|
+
const safeKey = RESERVED_KEYS.has(k) ? `$lit:${k}` : k;
|
|
60
|
+
out[safeKey] = encodeRaw(v, false);
|
|
61
|
+
}
|
|
62
|
+
encoded = out;
|
|
63
|
+
}
|
|
64
|
+
const serialized = JSON.stringify(encoded);
|
|
65
|
+
const structuralMatch = jsonToPoolIdx.get(serialized);
|
|
66
|
+
if (structuralMatch !== void 0) {
|
|
67
|
+
objToPoolIdx.set(val, structuralMatch);
|
|
68
|
+
return { $ref: structuralMatch };
|
|
69
|
+
}
|
|
70
|
+
if (topLevelStep || serialized.length >= 32) {
|
|
71
|
+
const idx = pool.length;
|
|
72
|
+
pool.push(encoded);
|
|
73
|
+
objToPoolIdx.set(val, idx);
|
|
74
|
+
jsonToPoolIdx.set(serialized, idx);
|
|
75
|
+
return { $ref: idx };
|
|
76
|
+
}
|
|
77
|
+
return encoded;
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
function encodeEntry(entry) {
|
|
82
|
+
const s = entry.steps.map((step) => {
|
|
83
|
+
if ("error" in step && step.error !== void 0) return {
|
|
84
|
+
i: step.id,
|
|
85
|
+
e: encodeRaw(step.error, false)
|
|
86
|
+
};
|
|
87
|
+
return {
|
|
88
|
+
i: step.id,
|
|
89
|
+
v: encodeRaw(step.value, true)
|
|
90
|
+
};
|
|
91
|
+
});
|
|
92
|
+
return entry.skipYields ? {
|
|
93
|
+
s,
|
|
94
|
+
y: entry.skipYields
|
|
95
|
+
} : { s };
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
record(entry) {
|
|
99
|
+
const rid = `r${nextReceiptNum++}`;
|
|
100
|
+
receipts[rid] = encodeEntry(entry);
|
|
101
|
+
return rid;
|
|
102
|
+
},
|
|
103
|
+
memoize(id, args, run) {
|
|
104
|
+
const key = `${id}::${stableArgsKey(args)}`;
|
|
105
|
+
if (memoCache.has(key)) return memoCache.get(key);
|
|
106
|
+
const res = run();
|
|
107
|
+
if (res && typeof res.then === "function") {
|
|
108
|
+
const tracked = Promise.resolve(res).catch((err) => {
|
|
109
|
+
memoCache.delete(key);
|
|
110
|
+
throw err;
|
|
111
|
+
});
|
|
112
|
+
memoCache.set(key, tracked);
|
|
113
|
+
return tracked;
|
|
114
|
+
}
|
|
115
|
+
memoCache.set(key, res);
|
|
116
|
+
return res;
|
|
117
|
+
},
|
|
118
|
+
emitInitialScript(nonce) {
|
|
119
|
+
const initialR = {};
|
|
120
|
+
let count = 0;
|
|
121
|
+
for (const [rid, entry] of Object.entries(receipts)) {
|
|
122
|
+
initialR[rid] = entry;
|
|
123
|
+
flushedReceipts.add(rid);
|
|
124
|
+
count++;
|
|
125
|
+
}
|
|
126
|
+
const initialPool = pool.slice(0);
|
|
127
|
+
flushedPoolCursor = pool.length;
|
|
128
|
+
if (count === 0 && initialPool.length === 0) return "";
|
|
129
|
+
const payload = {
|
|
130
|
+
p: initialPool,
|
|
131
|
+
r: initialR
|
|
132
|
+
};
|
|
133
|
+
return `<script id="__C7T_RECEIPTS__"${nonceAttr(nonce)}>window.__C7T_R=${escapeScriptJson(payload)};<\/script>`;
|
|
134
|
+
},
|
|
135
|
+
emitStreamScript(rid, entry, nonce) {
|
|
136
|
+
if (!(rid in receipts)) receipts[rid] = encodeEntry(entry);
|
|
137
|
+
const encodedEntry = receipts[rid];
|
|
138
|
+
flushedReceipts.add(rid);
|
|
139
|
+
const newPoolSlice = pool.slice(flushedPoolCursor);
|
|
140
|
+
const startIdx = flushedPoolCursor;
|
|
141
|
+
flushedPoolCursor = pool.length;
|
|
142
|
+
let poolAssignJs = "";
|
|
143
|
+
for (let i = 0; i < newPoolSlice.length; i++) poolAssignJs += `s.p[${startIdx + i}]=${escapeScriptJson(newPoolSlice[i])};`;
|
|
144
|
+
return `<script${nonceAttr(nonce)}>(function(w){var s=w.__C7T_R||(w.__C7T_R={p:[],r:{}});${poolAssignJs}s.r[${escapeScriptJson(rid)}]=${escapeScriptJson(encodedEntry)};var c=document.currentScript;if(c)c.remove();})(window)<\/script>`;
|
|
145
|
+
},
|
|
146
|
+
getSnapshot() {
|
|
147
|
+
return {
|
|
148
|
+
p: [...pool],
|
|
149
|
+
r: { ...receipts }
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Decode an `EncodedReceiptStore` entry synchronously in 0 microtasks.
|
|
156
|
+
* Preserves shared reference identity across `$ref` pool pointers!
|
|
157
|
+
*/
|
|
158
|
+
function createReceiptDecoder(getStore) {
|
|
159
|
+
const decodedPool = /* @__PURE__ */ new Map();
|
|
160
|
+
function resolveStore() {
|
|
161
|
+
if (getStore) return getStore();
|
|
162
|
+
if (typeof window !== "undefined") return window.__C7T_R;
|
|
163
|
+
}
|
|
164
|
+
function decodeVal(val, pool) {
|
|
165
|
+
if (val === null || typeof val !== "object") return val;
|
|
166
|
+
if (Array.isArray(val)) return val.map((item) => decodeVal(item, pool));
|
|
167
|
+
if ("$undef" in val && val.$undef === 1 && Object.keys(val).length === 1) return void 0;
|
|
168
|
+
if ("$date" in val && typeof val.$date === "string" && Object.keys(val).length === 1) return new Date(val.$date);
|
|
169
|
+
if ("$query" in val && typeof val.$query === "string" && Object.keys(val).length === 1) return new URLSearchParams(val.$query);
|
|
170
|
+
if ("$ref" in val && typeof val.$ref === "number" && Object.keys(val).length === 1) {
|
|
171
|
+
const idx = val.$ref;
|
|
172
|
+
if (decodedPool.has(idx)) return decodedPool.get(idx);
|
|
173
|
+
const decoded = decodeVal(pool[idx], pool);
|
|
174
|
+
decodedPool.set(idx, decoded);
|
|
175
|
+
return decoded;
|
|
176
|
+
}
|
|
177
|
+
const out = {};
|
|
178
|
+
for (const [k, v] of Object.entries(val)) {
|
|
179
|
+
const realKey = k.startsWith("$lit:") ? k.slice(5) : k;
|
|
180
|
+
out[realKey] = decodeVal(v, pool);
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
return function resolveIslandReceipt(el) {
|
|
185
|
+
const rid = el.getAttribute("data-blokd-rid");
|
|
186
|
+
if (!rid) return void 0;
|
|
187
|
+
const store = resolveStore();
|
|
188
|
+
if (!store || !store.r || !(rid in store.r)) return void 0;
|
|
189
|
+
const rawEntry = store.r[rid];
|
|
190
|
+
delete store.r[rid];
|
|
191
|
+
const steps = rawEntry.s.map((s) => {
|
|
192
|
+
if ("e" in s) return {
|
|
193
|
+
id: s.i,
|
|
194
|
+
error: decodeVal(s.e, store.p)
|
|
195
|
+
};
|
|
196
|
+
return {
|
|
197
|
+
id: s.i,
|
|
198
|
+
value: decodeVal(s.v, store.p)
|
|
199
|
+
};
|
|
200
|
+
});
|
|
201
|
+
return rawEntry.y ? {
|
|
202
|
+
steps,
|
|
203
|
+
skipYields: rawEntry.y
|
|
204
|
+
} : { steps };
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
/** Install the global 0-tick receipt resolver into `@fierst/blokd` on the client. */
|
|
208
|
+
function installReceiptResolver(getStore) {
|
|
209
|
+
const resolver = createReceiptDecoder(getStore);
|
|
210
|
+
_setReceiptResolver(resolver);
|
|
211
|
+
return () => _setReceiptResolver(null);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Decode all recorded steps inside a static `__c7t.json` sidecar store and activate
|
|
215
|
+
* synchronous 0-tick step resolution while `fn()` mounts a prerendered SSG route on the client.
|
|
216
|
+
*/
|
|
217
|
+
function runWithStaticReceiptSidecar(store, fn) {
|
|
218
|
+
if (!store || !store.r || Object.keys(store.r).length === 0) return fn();
|
|
219
|
+
const clone = {
|
|
220
|
+
p: store.p,
|
|
221
|
+
r: { ...store.r }
|
|
222
|
+
};
|
|
223
|
+
const decoder = createReceiptDecoder(() => clone);
|
|
224
|
+
const queuesByStepId = /* @__PURE__ */ new Map();
|
|
225
|
+
for (const rid of Object.keys(clone.r)) {
|
|
226
|
+
const decoded = decoder({ getAttribute: (attr) => attr === "data-blokd-rid" ? rid : null });
|
|
227
|
+
if (!decoded) continue;
|
|
228
|
+
for (const step of decoded.steps) {
|
|
229
|
+
let q = queuesByStepId.get(step.id);
|
|
230
|
+
if (!q) {
|
|
231
|
+
q = [];
|
|
232
|
+
queuesByStepId.set(step.id, q);
|
|
233
|
+
}
|
|
234
|
+
q.push(step);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
_setStepCacheResolver((id) => {
|
|
238
|
+
const q = queuesByStepId.get(id);
|
|
239
|
+
if (!q || q.length === 0) return void 0;
|
|
240
|
+
const step = q.shift();
|
|
241
|
+
if ("error" in step && step.error !== void 0) return {
|
|
242
|
+
hit: true,
|
|
243
|
+
error: step.error
|
|
244
|
+
};
|
|
245
|
+
return {
|
|
246
|
+
hit: true,
|
|
247
|
+
value: step.value
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
try {
|
|
251
|
+
return fn();
|
|
252
|
+
} finally {
|
|
253
|
+
_setStepCacheResolver(null);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// src/router.ts
|
|
257
|
+
const c7tRouteContext = createContext({
|
|
258
|
+
pathname: "/",
|
|
259
|
+
search: new URLSearchParams(),
|
|
260
|
+
params: {}
|
|
261
|
+
});
|
|
262
|
+
function useRoute() {
|
|
263
|
+
return useContext(c7tRouteContext);
|
|
264
|
+
}
|
|
265
|
+
function normalizeRouteFile(file) {
|
|
266
|
+
return file.replace(/\\/g, "/").replace(/^\/+/, "").replace(/^src\/routes\//, "").replace(/^routes\//, "").replace(/\.(tsx|ts|jsx|js)$/, "");
|
|
267
|
+
}
|
|
268
|
+
function compilePattern(segments) {
|
|
269
|
+
if (segments.length === 0) return {
|
|
270
|
+
pattern: "/",
|
|
271
|
+
regex: /^\/$/,
|
|
272
|
+
paramNames: [],
|
|
273
|
+
score: 1e3
|
|
274
|
+
};
|
|
275
|
+
const paramNames = [];
|
|
276
|
+
let score = 0;
|
|
277
|
+
const regexParts = [];
|
|
278
|
+
const patternParts = [];
|
|
279
|
+
for (const seg of segments) {
|
|
280
|
+
const catchAll = /^\[\.\.\.([A-Za-z_]\w*)\]$/.exec(seg);
|
|
281
|
+
if (catchAll) {
|
|
282
|
+
paramNames.push(catchAll[1]);
|
|
283
|
+
regexParts.push("(.*)");
|
|
284
|
+
patternParts.push(`*`);
|
|
285
|
+
score += 1;
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
const dynamic = /^\[([A-Za-z_]\w*)\]$/.exec(seg) ?? /^:([A-Za-z_]\w*)$/.exec(seg);
|
|
289
|
+
if (dynamic) {
|
|
290
|
+
paramNames.push(dynamic[1]);
|
|
291
|
+
regexParts.push("([^/]+)");
|
|
292
|
+
patternParts.push(`:${dynamic[1]}`);
|
|
293
|
+
score += 10;
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
const escaped = seg.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
|
|
297
|
+
regexParts.push(escaped);
|
|
298
|
+
patternParts.push(seg);
|
|
299
|
+
score += 100;
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
pattern: "/" + patternParts.join("/"),
|
|
303
|
+
regex: new RegExp(`^/${regexParts.join("/")}/?$`),
|
|
304
|
+
paramNames,
|
|
305
|
+
score
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function isGroupSegment(seg) {
|
|
309
|
+
return /^\([^/]+\)$/.test(seg);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Extract convention-based root `404.tsx` (`_404.tsx`), `error.tsx` (`_error.tsx`), and `layout.tsx`
|
|
313
|
+
* components from route module entries.
|
|
314
|
+
*/
|
|
315
|
+
function extractSpecialRoutes(entries) {
|
|
316
|
+
let notFound;
|
|
317
|
+
let error;
|
|
318
|
+
let rootLayout;
|
|
319
|
+
for (const entry of entries) {
|
|
320
|
+
if (!entry.component) continue;
|
|
321
|
+
const clean = normalizeRouteFile(entry.file);
|
|
322
|
+
if (clean === "404" || clean === "_404") notFound = entry.component;
|
|
323
|
+
else if (clean === "error" || clean === "_error") error = entry.component;
|
|
324
|
+
else if (clean === "layout" || clean === "_layout") rootLayout = entry.component;
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
notFound,
|
|
328
|
+
error,
|
|
329
|
+
rootLayout
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Compile a list of route module entries (`layout.tsx`, `(group)/layout.tsx`, `index.tsx`, `projects/[id].tsx`, `[...all].tsx`)
|
|
334
|
+
* into a specificity-ordered nested route table.
|
|
335
|
+
*/
|
|
336
|
+
function buildRoutes(entries, defaults = {}) {
|
|
337
|
+
const layoutMap = /* @__PURE__ */ new Map();
|
|
338
|
+
const pageEntries = [];
|
|
339
|
+
for (const entry of entries) {
|
|
340
|
+
if (!entry.component) continue;
|
|
341
|
+
const clean = normalizeRouteFile(entry.file);
|
|
342
|
+
if (clean === "404" || clean === "_404" || clean === "error" || clean === "_error") continue;
|
|
343
|
+
const parts = clean.split("/").filter(Boolean);
|
|
344
|
+
const base = parts.at(-1) ?? "";
|
|
345
|
+
const dirParts = parts.slice(0, -1);
|
|
346
|
+
if (base === "layout" || base === "_layout") {
|
|
347
|
+
const prefix = dirParts.length === 0 ? "/" : "/" + dirParts.join("/");
|
|
348
|
+
layoutMap.set(prefix, {
|
|
349
|
+
id: `layout:${prefix}`,
|
|
350
|
+
prefix,
|
|
351
|
+
component: entry.component,
|
|
352
|
+
load: entry.load,
|
|
353
|
+
prerender: entry.prerender !== void 0 ? Boolean(entry.prerender) : void 0,
|
|
354
|
+
csr: entry.csr
|
|
355
|
+
});
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const routeSegments = (base === "index" ? dirParts : [...dirParts, base]).filter((seg) => !isGroupSegment(seg));
|
|
359
|
+
pageEntries.push({
|
|
360
|
+
cleanPath: clean,
|
|
361
|
+
dirParts,
|
|
362
|
+
routeSegments,
|
|
363
|
+
entry
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
const seenStaticOrShapePatterns = /* @__PURE__ */ new Map();
|
|
367
|
+
const compiled = pageEntries.map(({ cleanPath, dirParts, routeSegments, entry }) => {
|
|
368
|
+
const { pattern, regex, paramNames, score } = compilePattern(routeSegments);
|
|
369
|
+
const canonicalShape = routeSegments.map((s) => s.startsWith("[...") ? "*" : s.startsWith("[") || s.startsWith(":") ? ":param" : s).join("/");
|
|
370
|
+
const conflictFile = seenStaticOrShapePatterns.get(canonicalShape);
|
|
371
|
+
if (conflictFile !== void 0) throw new Error(`[c7t] Ambiguous duplicate route pattern "${pattern}" defined by both "${conflictFile}" and "${entry.file}".`);
|
|
372
|
+
seenStaticOrShapePatterns.set(canonicalShape, entry.file);
|
|
373
|
+
const layouts = [];
|
|
374
|
+
const rootLayout = layoutMap.get("/");
|
|
375
|
+
if (rootLayout) layouts.push(rootLayout);
|
|
376
|
+
let accum = "";
|
|
377
|
+
for (const part of dirParts) {
|
|
378
|
+
accum += "/" + part;
|
|
379
|
+
const l = layoutMap.get(accum);
|
|
380
|
+
if (l) layouts.push(l);
|
|
381
|
+
}
|
|
382
|
+
let resolvedPrerender = defaults.prerender ?? false;
|
|
383
|
+
let resolvedCsr = defaults.csr ?? "auto";
|
|
384
|
+
for (const l of layouts) {
|
|
385
|
+
if (l.prerender !== void 0) resolvedPrerender = l.prerender;
|
|
386
|
+
if (l.csr !== void 0) resolvedCsr = l.csr;
|
|
387
|
+
}
|
|
388
|
+
if (entry.prerender !== void 0) resolvedPrerender = Boolean(entry.prerender);
|
|
389
|
+
if (entry.csr !== void 0) resolvedCsr = entry.csr;
|
|
390
|
+
return {
|
|
391
|
+
id: `page:${cleanPath}`,
|
|
392
|
+
pattern,
|
|
393
|
+
regex,
|
|
394
|
+
paramNames,
|
|
395
|
+
score,
|
|
396
|
+
layouts,
|
|
397
|
+
page: entry.component,
|
|
398
|
+
pageLoad: entry.load,
|
|
399
|
+
prerender: resolvedPrerender,
|
|
400
|
+
csr: resolvedCsr
|
|
401
|
+
};
|
|
402
|
+
});
|
|
403
|
+
compiled.sort((a, b) => b.score - a.score || a.pattern.localeCompare(b.pattern));
|
|
404
|
+
return compiled;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Compile file-system HTTP endpoint entries (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`)
|
|
408
|
+
* into specificity-ordered Hono route definitions.
|
|
409
|
+
*/
|
|
410
|
+
function buildApiRoutes(entries) {
|
|
411
|
+
const apiRoutes = [];
|
|
412
|
+
for (const entry of entries) {
|
|
413
|
+
if (!entry.handlers) continue;
|
|
414
|
+
const activeHandlers = {};
|
|
415
|
+
let count = 0;
|
|
416
|
+
for (const method of [
|
|
417
|
+
"GET",
|
|
418
|
+
"POST",
|
|
419
|
+
"PUT",
|
|
420
|
+
"PATCH",
|
|
421
|
+
"DELETE",
|
|
422
|
+
"HEAD",
|
|
423
|
+
"OPTIONS"
|
|
424
|
+
]) if (typeof entry.handlers[method] === "function") {
|
|
425
|
+
activeHandlers[method] = entry.handlers[method];
|
|
426
|
+
count++;
|
|
427
|
+
}
|
|
428
|
+
if (count === 0) continue;
|
|
429
|
+
const clean = normalizeRouteFile(entry.file);
|
|
430
|
+
const parts = clean.split("/").filter(Boolean);
|
|
431
|
+
const base = parts.at(-1) ?? "";
|
|
432
|
+
if (base === "layout" || base === "_layout") continue;
|
|
433
|
+
const dirParts = parts.slice(0, -1);
|
|
434
|
+
const { pattern, score } = compilePattern((base === "index" ? dirParts : [...dirParts, base]).filter((seg) => !isGroupSegment(seg)));
|
|
435
|
+
apiRoutes.push({
|
|
436
|
+
id: `api:${clean}`,
|
|
437
|
+
honoPath: pattern,
|
|
438
|
+
score,
|
|
439
|
+
prerender: entry.prerender !== void 0 ? Boolean(entry.prerender) : void 0,
|
|
440
|
+
handlers: activeHandlers
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
apiRoutes.sort((a, b) => b.score - a.score || a.honoPath.localeCompare(b.honoPath));
|
|
444
|
+
return apiRoutes;
|
|
445
|
+
}
|
|
446
|
+
function decodeParam(raw) {
|
|
447
|
+
try {
|
|
448
|
+
return decodeURIComponent(raw);
|
|
449
|
+
} catch {
|
|
450
|
+
return raw;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
function matchNestedRoutes(routes, urlStr) {
|
|
454
|
+
const parsed = new URL(urlStr, "http://c7t.local");
|
|
455
|
+
const pathname = parsed.pathname || "/";
|
|
456
|
+
for (const route of routes) {
|
|
457
|
+
const m = pathname.match(route.regex);
|
|
458
|
+
if (!m) continue;
|
|
459
|
+
const params = {};
|
|
460
|
+
for (let i = 0; i < route.paramNames.length; i++) params[route.paramNames[i]] = decodeParam(m[i + 1] ?? "");
|
|
461
|
+
const stack = [...route.layouts.map((l) => ({
|
|
462
|
+
kind: "layout",
|
|
463
|
+
id: l.id,
|
|
464
|
+
instanceKey: l.id,
|
|
465
|
+
component: l.component
|
|
466
|
+
})), {
|
|
467
|
+
kind: "page",
|
|
468
|
+
id: route.id,
|
|
469
|
+
instanceKey: `${route.id}::${pathname}${parsed.search}`,
|
|
470
|
+
component: route.page
|
|
471
|
+
}];
|
|
472
|
+
return {
|
|
473
|
+
route,
|
|
474
|
+
pathname,
|
|
475
|
+
search: parsed.searchParams,
|
|
476
|
+
params,
|
|
477
|
+
stack,
|
|
478
|
+
prerender: route.prerender,
|
|
479
|
+
csr: route.csr
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
return null;
|
|
483
|
+
}
|
|
484
|
+
const outletSsrTpl = _tpl("<c7t-outlet data-blokd-a0><!--blokd:1--></c7t-outlet>", [{
|
|
485
|
+
kind: "attr",
|
|
486
|
+
name: "data-c7t-depth",
|
|
487
|
+
path: [0]
|
|
488
|
+
}, {
|
|
489
|
+
kind: "node",
|
|
490
|
+
path: [0, 0]
|
|
491
|
+
}]);
|
|
492
|
+
const outletClaimTpl = _tpl("<c7t-outlet data-blokd-a0></c7t-outlet>", [{
|
|
493
|
+
kind: "attr",
|
|
494
|
+
name: "data-c7t-depth",
|
|
495
|
+
path: [0]
|
|
496
|
+
}]);
|
|
497
|
+
function Outlet(props) {
|
|
498
|
+
if (props.children !== void 0) return _slot(outletSsrTpl, [String(props.depth), props.children]);
|
|
499
|
+
return _slot(outletClaimTpl, [String(props.depth)]);
|
|
500
|
+
}
|
|
501
|
+
Outlet.__blokdBoundary = true;
|
|
502
|
+
Outlet.__blokdOwnerSrc = "@fierst/c7t/router#Outlet";
|
|
503
|
+
function RouteContextBridge(props) {
|
|
504
|
+
provide(c7tRouteContext, props.info);
|
|
505
|
+
return props.children;
|
|
506
|
+
}
|
|
507
|
+
/** Build the nested SSR or client VDOM tree from `depth` downward. */
|
|
508
|
+
function buildMatchedRouteView(match, startDepth = 0, errorComponent) {
|
|
509
|
+
function buildAt(depth) {
|
|
510
|
+
const seg = match.stack[depth];
|
|
511
|
+
if (!seg) return null;
|
|
512
|
+
const isLast = depth === match.stack.length - 1;
|
|
513
|
+
const routeProps = {
|
|
514
|
+
params: match.params,
|
|
515
|
+
search: match.search,
|
|
516
|
+
pathname: match.pathname,
|
|
517
|
+
...isLast ? {} : { children: _comp(Outlet, {
|
|
518
|
+
depth,
|
|
519
|
+
children: buildAt(depth + 1)
|
|
520
|
+
}) }
|
|
521
|
+
};
|
|
522
|
+
return _comp(seg.component, routeProps, seg.instanceKey);
|
|
523
|
+
}
|
|
524
|
+
const info = {
|
|
525
|
+
pathname: match.pathname,
|
|
526
|
+
search: match.search,
|
|
527
|
+
params: match.params
|
|
528
|
+
};
|
|
529
|
+
const branch = buildAt(startDepth);
|
|
530
|
+
const guarded = errorComponent ? _comp(ErrorBoundary, {
|
|
531
|
+
fallback: (err, reset) => _comp(errorComponent, {
|
|
532
|
+
error: err,
|
|
533
|
+
reset
|
|
534
|
+
}),
|
|
535
|
+
children: branch
|
|
536
|
+
}) : branch;
|
|
537
|
+
return _comp(RouteContextBridge, {
|
|
538
|
+
info,
|
|
539
|
+
children: guarded
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
let activeNavigator = null;
|
|
543
|
+
async function navigate(to, opts = {}) {
|
|
544
|
+
if (activeNavigator) {
|
|
545
|
+
await activeNavigator(to, opts);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (typeof window !== "undefined") {
|
|
549
|
+
if (opts.replace) window.location.replace(to);
|
|
550
|
+
else window.location.assign(to);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function toSidecarUrl(pathname) {
|
|
554
|
+
const clean = pathname.split("?")[0].split("#")[0] || "/";
|
|
555
|
+
return clean === "/" ? "/__c7t.json" : `${clean.replace(/\/+$/, "")}/__c7t.json`;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Install client-side nested layout navigation with hover preloading and SSG `__c7t.json` sidecar support.
|
|
559
|
+
* Keeps unchanged parent layouts (`RootLayout`) mounted with local `let` & `Context` state intact,
|
|
560
|
+
* while tearing down outgoing child route generators (`finally` + `AbortSignal`) and mounting the new leaf.
|
|
561
|
+
*/
|
|
562
|
+
function installClientRouter(options) {
|
|
563
|
+
const { routes, transitions = true } = options;
|
|
564
|
+
const fetcher = options.fetch ?? (typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : null);
|
|
565
|
+
const rootEl = options.rootElement ?? (typeof document !== "undefined" ? document.getElementById("app") ?? document.body : null);
|
|
566
|
+
if (!rootEl) return () => {};
|
|
567
|
+
let currentMatch = matchNestedRoutes(routes, options.initialUrl ?? (typeof window !== "undefined" ? window.location.pathname + window.location.search : "/"));
|
|
568
|
+
const dynamicHandles = /* @__PURE__ */ new Map();
|
|
569
|
+
const preloadedRoutes = /* @__PURE__ */ new Set();
|
|
570
|
+
const sidecarCache = /* @__PURE__ */ new Map();
|
|
571
|
+
const ac = new AbortController();
|
|
572
|
+
function fetchSidecar(pathname) {
|
|
573
|
+
const url = toSidecarUrl(pathname);
|
|
574
|
+
let cached = sidecarCache.get(url);
|
|
575
|
+
if (!cached) {
|
|
576
|
+
cached = fetcher ? fetcher(url, { headers: { Accept: "application/json" } }).then((res) => res.ok ? res.json() : null).catch(() => null) : Promise.resolve(null);
|
|
577
|
+
sidecarCache.set(url, cached);
|
|
578
|
+
}
|
|
579
|
+
return cached;
|
|
580
|
+
}
|
|
581
|
+
function preloadHref(href) {
|
|
582
|
+
const matched = matchNestedRoutes(routes, href);
|
|
583
|
+
if (!matched) return;
|
|
584
|
+
if (!preloadedRoutes.has(matched.route.id)) {
|
|
585
|
+
preloadedRoutes.add(matched.route.id);
|
|
586
|
+
matched.route.pageLoad?.();
|
|
587
|
+
for (const layout of matched.route.layouts) layout.load?.();
|
|
588
|
+
}
|
|
589
|
+
if (matched.prerender) fetchSidecar(matched.pathname);
|
|
590
|
+
}
|
|
591
|
+
function disposeFromDepth(depth) {
|
|
592
|
+
for (const [d, handle] of Array.from(dynamicHandles.entries())) if (d >= depth) {
|
|
593
|
+
dynamicHandles.delete(d);
|
|
594
|
+
handle.dispose();
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
async function applyNavigation(nextUrl, useTransition) {
|
|
598
|
+
const nextMatch = matchNestedRoutes(routes, nextUrl);
|
|
599
|
+
if (!nextMatch) return;
|
|
600
|
+
let divergeDepth = 0;
|
|
601
|
+
if (currentMatch) {
|
|
602
|
+
const minLen = Math.min(currentMatch.stack.length, nextMatch.stack.length);
|
|
603
|
+
while (divergeDepth < minLen && currentMatch.stack[divergeDepth].instanceKey === nextMatch.stack[divergeDepth].instanceKey) divergeDepth++;
|
|
604
|
+
if (divergeDepth === currentMatch.stack.length && divergeDepth === nextMatch.stack.length) {
|
|
605
|
+
options.onNavigate?.();
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
const sidecarStore = nextMatch.prerender ? await fetchSidecar(nextMatch.pathname) : null;
|
|
610
|
+
if (divergeDepth > 0) {
|
|
611
|
+
const dormantAncestor = rootEl.querySelector(`c7t-outlet[data-c7t-depth="${divergeDepth - 1}"]`)?.closest?.("[data-blokd-src]");
|
|
612
|
+
if (dormantAncestor && !dormantAncestor.__blokdCtx && options.wakeIsland) await options.wakeIsland(dormantAncestor);
|
|
613
|
+
}
|
|
614
|
+
const commit = () => {
|
|
615
|
+
disposeFromDepth(divergeDepth);
|
|
616
|
+
const container = divergeDepth === 0 ? rootEl : rootEl.querySelector(`c7t-outlet[data-c7t-depth="${divergeDepth - 1}"]`);
|
|
617
|
+
if (!container) return;
|
|
618
|
+
const parentCtx = (container.closest?.("[data-blokd-src]"))?.__blokdCtx ?? null;
|
|
619
|
+
container.innerHTML = "";
|
|
620
|
+
const subView = buildMatchedRouteView(nextMatch, divergeDepth, options.errorComponent);
|
|
621
|
+
const handle = runWithStaticReceiptSidecar(sidecarStore, () => mountComponent(() => subView, {}, container, null, void 0, void 0, nextMatch.stack[divergeDepth].instanceKey, parentCtx));
|
|
622
|
+
dynamicHandles.set(divergeDepth, handle);
|
|
623
|
+
currentMatch = nextMatch;
|
|
624
|
+
options.onNavigate?.();
|
|
625
|
+
};
|
|
626
|
+
if (useTransition && typeof document !== "undefined" && typeof document.startViewTransition === "function") await document.startViewTransition(commit).finished.catch(() => {});
|
|
627
|
+
else commit();
|
|
628
|
+
}
|
|
629
|
+
activeNavigator = async (to, navOpts = {}) => {
|
|
630
|
+
if (typeof window !== "undefined") {
|
|
631
|
+
const parsed = new URL(to, window.location.origin);
|
|
632
|
+
const nextUrl = parsed.pathname + parsed.search;
|
|
633
|
+
if (window.location.pathname + window.location.search !== nextUrl && window.location.protocol !== "about:") try {
|
|
634
|
+
if (navOpts.replace) window.history.replaceState(null, "", nextUrl);
|
|
635
|
+
else window.history.pushState(null, "", nextUrl);
|
|
636
|
+
} catch {}
|
|
637
|
+
await applyNavigation(nextUrl, navOpts.transition ?? transitions);
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
if (typeof window !== "undefined") {
|
|
641
|
+
const onPop = () => {
|
|
642
|
+
applyNavigation(window.location.pathname + window.location.search, transitions);
|
|
643
|
+
};
|
|
644
|
+
const onHoverOrFocus = (e) => {
|
|
645
|
+
const target = e.target;
|
|
646
|
+
const a = (target instanceof Element ? target : null)?.closest?.("a[href]");
|
|
647
|
+
if (!a || a.target || a.hasAttribute("download") || a.hasAttribute("data-c7t-reload")) return;
|
|
648
|
+
if (a.getAttribute("data-c7t-preload") === "off") return;
|
|
649
|
+
const href = a.getAttribute("href");
|
|
650
|
+
if (!href || !href.startsWith("/") || href.startsWith("//")) return;
|
|
651
|
+
preloadHref(href);
|
|
652
|
+
};
|
|
653
|
+
const onClick = (e) => {
|
|
654
|
+
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
|
655
|
+
const a = e.target?.closest?.("a[href]");
|
|
656
|
+
if (!a || a.target || a.hasAttribute("download") || a.hasAttribute("data-c7t-reload")) return;
|
|
657
|
+
const href = a.getAttribute("href");
|
|
658
|
+
if (!href || !href.startsWith("/") || href.startsWith("//")) return;
|
|
659
|
+
if (!matchNestedRoutes(routes, href)) return;
|
|
660
|
+
e.preventDefault();
|
|
661
|
+
activeNavigator(href, { transition: transitions });
|
|
662
|
+
};
|
|
663
|
+
window.addEventListener("popstate", onPop, { signal: ac.signal });
|
|
664
|
+
rootEl.ownerDocument.addEventListener("pointerenter", onHoverOrFocus, {
|
|
665
|
+
capture: true,
|
|
666
|
+
signal: ac.signal
|
|
667
|
+
});
|
|
668
|
+
rootEl.ownerDocument.addEventListener("focusin", onHoverOrFocus, {
|
|
669
|
+
capture: true,
|
|
670
|
+
signal: ac.signal
|
|
671
|
+
});
|
|
672
|
+
rootEl.ownerDocument.addEventListener("click", onClick, { signal: ac.signal });
|
|
673
|
+
}
|
|
674
|
+
return () => {
|
|
675
|
+
ac.abort();
|
|
676
|
+
disposeFromDepth(0);
|
|
677
|
+
activeNavigator = null;
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
export { c7tRouteContext as a, matchNestedRoutes as c, createReceiptCollector as d, installReceiptResolver as f, buildRoutes as i, navigate as l, buildApiRoutes as n, extractSpecialRoutes as o, buildMatchedRouteView as r, installClientRouter as s, Outlet as t, useRoute as u };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { C as matchNestedRoutes, S as installClientRouter, T as useRoute, _ as buildApiRoutes, a as CompiledApiRoute, b as c7tRouteContext, c as ExtractRouteParams, d as MatchedSegment, f as NestedRouteMatch, g as SpecialRoutes, h as RouteProps, i as ClientRouterOptions, l as HttpMethod, m as RouteModuleEntry, n as BuildRoutesOptions, o as CompiledRoute, p as Outlet, r as C7tRouteInfo, s as CsrMode, t as ApiRouteHandler, u as LayoutEntry, v as buildMatchedRouteView, w as navigate, x as extractSpecialRoutes, y as buildRoutes } from "./router-19ZZ3woS.mjs";
|
|
2
|
+
export { ApiRouteHandler, BuildRoutesOptions, C7tRouteInfo, ClientRouterOptions, CompiledApiRoute, CompiledRoute, CsrMode, ExtractRouteParams, HttpMethod, LayoutEntry, MatchedSegment, NestedRouteMatch, Outlet, RouteModuleEntry, RouteProps, SpecialRoutes, buildApiRoutes, buildMatchedRouteView, buildRoutes, c7tRouteContext, extractSpecialRoutes, installClientRouter, matchNestedRoutes, navigate, useRoute };
|
package/dist/router.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as Outlet, n as buildApiRoutes, r as buildMatchedRouteView, i as buildRoutes, a as c7tRouteContext, o as extractSpecialRoutes, s as installClientRouter, c as matchNestedRoutes, l as navigate, u as useRoute } from "./router-B50LekA_.mjs";
|