mdorigin 0.5.2 → 0.5.3
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/dist/adapters/cloudflare.d.ts +31 -2
- package/dist/adapters/cloudflare.js +277 -17
- package/dist/cloudflare.js +10 -1
- package/dist/core/markdown.d.ts +23 -6
- package/dist/core/markdown.js +27 -2
- package/dist/core/request-handler.js +17 -17
- package/dist/core/site-config.js +2 -2
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { MdoPlugin } from '../core/extensions.js';
|
|
2
2
|
import type { ResolvedSiteConfig } from '../core/site-config.js';
|
|
3
|
-
import { type ExternalSearchBundleEntry, type SearchBundleEntry } from '../search.js';
|
|
3
|
+
import { type ExternalSearchBundleEntry, type SearchApi, type SearchBundleEntry } from '../search.js';
|
|
4
4
|
export interface TextCloudflareManifestEntry {
|
|
5
5
|
path: string;
|
|
6
6
|
kind: 'text';
|
|
@@ -32,6 +32,13 @@ export interface CloudflareManifest {
|
|
|
32
32
|
searchEntries?: SearchBundleEntry[];
|
|
33
33
|
externalSearchEntries?: ExternalSearchBundleEntry[];
|
|
34
34
|
runtime?: CloudflareBundleRuntimeConfig;
|
|
35
|
+
/**
|
|
36
|
+
* Build-time deploy version. Bundle content is immutable within one deploy,
|
|
37
|
+
* so this value doubles as a strong ETag and lets If-None-Match matches skip
|
|
38
|
+
* rendering entirely. A new deploy produces a new version and invalidates
|
|
39
|
+
* every cached response.
|
|
40
|
+
*/
|
|
41
|
+
deployVersion?: string;
|
|
35
42
|
}
|
|
36
43
|
export interface CloudflareAssetsBindingLike {
|
|
37
44
|
fetch(request: Request): Promise<Response>;
|
|
@@ -52,9 +59,31 @@ export interface CloudflareWorkerEnv {
|
|
|
52
59
|
[binding: string]: unknown;
|
|
53
60
|
}
|
|
54
61
|
export interface ExportedHandlerLike {
|
|
55
|
-
fetch(request: Request, env?: CloudflareWorkerEnv, ctx?:
|
|
62
|
+
fetch(request: Request, env?: CloudflareWorkerEnv, ctx?: CloudflareWorkerExecutionContextLike): Promise<Response>;
|
|
63
|
+
}
|
|
64
|
+
export interface CloudflareWorkerExecutionContextLike {
|
|
65
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
66
|
+
}
|
|
67
|
+
export interface CloudflareCacheLike {
|
|
68
|
+
match(request: Request): Promise<Response | undefined>;
|
|
69
|
+
put(request: Request, response: Response): Promise<void>;
|
|
56
70
|
}
|
|
57
71
|
export interface CreateCloudflareWorkerOptions {
|
|
58
72
|
plugins?: MdoPlugin[];
|
|
73
|
+
/**
|
|
74
|
+
* Per-colo L2 cache. Defaults to the runtime `caches.default` when the
|
|
75
|
+
* runtime exposes one. Pass `null` to disable L2 caching.
|
|
76
|
+
*/
|
|
77
|
+
cache?: CloudflareCacheLike | null;
|
|
78
|
+
/** Maximum isolate-memoized rendered responses. Defaults to 100. */
|
|
79
|
+
responseCacheLimit?: number;
|
|
80
|
+
/** Maximum isolate-memoized search results. Defaults to 100. */
|
|
81
|
+
searchCacheLimit?: number;
|
|
59
82
|
}
|
|
60
83
|
export declare function createCloudflareWorker(manifest: CloudflareManifest, options?: CreateCloudflareWorkerOptions): ExportedHandlerLike;
|
|
84
|
+
/**
|
|
85
|
+
* Memoizes deterministic search results per isolate. The search index is
|
|
86
|
+
* static within one deploy, so identical (query, options) calls return the
|
|
87
|
+
* same hits and repeated queries skip retrieval entirely.
|
|
88
|
+
*/
|
|
89
|
+
export declare function withSearchResultCache(api: SearchApi, limit: number): SearchApi;
|
|
@@ -2,6 +2,21 @@ import { MemoryContentStore } from '../core/content-store.js';
|
|
|
2
2
|
import { handleSiteRequest } from '../core/request-handler.js';
|
|
3
3
|
import { resolveRequest } from '../core/router.js';
|
|
4
4
|
import { createSearchApiFromBundle, createSearchApiFromExternalBundle, } from '../search.js';
|
|
5
|
+
const BROWSER_CACHE_CONTROL = 'public, max-age=120, stale-while-revalidate=604800';
|
|
6
|
+
const CDN_CACHE_CONTROL = 'max-age=86400';
|
|
7
|
+
const L2_CACHE_CONTROL = 'public, max-age=86400';
|
|
8
|
+
const L2_CACHE_KEY_ORIGIN = 'https://cache.mdorigin.internal';
|
|
9
|
+
const CACHE_DEBUG_HEADER = 'x-mdorigin-cache';
|
|
10
|
+
const RESPONSE_CACHE_LIMIT_DEFAULT = 100;
|
|
11
|
+
const SEARCH_CACHE_LIMIT_DEFAULT = 100;
|
|
12
|
+
const CACHEABLE_CONTENT_TYPE_PREFIXES = [
|
|
13
|
+
'text/html',
|
|
14
|
+
'text/markdown',
|
|
15
|
+
'application/xml',
|
|
16
|
+
'text/xml',
|
|
17
|
+
'application/rss+xml',
|
|
18
|
+
'application/atom+xml',
|
|
19
|
+
];
|
|
5
20
|
export function createCloudflareWorker(manifest, options = {}) {
|
|
6
21
|
const storeIndex = new MemoryContentStore(manifest.entries.map((entry) => {
|
|
7
22
|
if (entry.kind === 'text') {
|
|
@@ -26,22 +41,60 @@ export function createCloudflareWorker(manifest, options = {}) {
|
|
|
26
41
|
bytes: decodeBase64(entry.base64 ?? ''),
|
|
27
42
|
};
|
|
28
43
|
}));
|
|
44
|
+
const responseCache = new LruCache(options.responseCacheLimit ?? RESPONSE_CACHE_LIMIT_DEFAULT);
|
|
45
|
+
const searchCacheLimit = options.searchCacheLimit ?? SEARCH_CACHE_LIMIT_DEFAULT;
|
|
46
|
+
const cache = options.cache === undefined ? resolveDefaultCache() : options.cache ?? undefined;
|
|
29
47
|
const inlineSearchApi = manifest.searchEntries && manifest.searchEntries.length > 0
|
|
30
|
-
? createSearchApiFromBundle(manifest.searchEntries, manifest.siteConfig?.search)
|
|
48
|
+
? withSearchResultCache(createSearchApiFromBundle(manifest.searchEntries, manifest.siteConfig?.search), searchCacheLimit)
|
|
31
49
|
: undefined;
|
|
32
50
|
const externalSearchApis = new WeakMap();
|
|
33
51
|
let defaultExternalSearchApi;
|
|
34
52
|
return {
|
|
35
|
-
async fetch(request, env) {
|
|
53
|
+
async fetch(request, env, ctx) {
|
|
36
54
|
const url = new URL(request.url);
|
|
37
|
-
const externalSearchApi = getExternalSearchApi(manifest, env, externalSearchApis, defaultExternalSearchApi);
|
|
55
|
+
const externalSearchApi = getExternalSearchApi(manifest, env, externalSearchApis, defaultExternalSearchApi, searchCacheLimit);
|
|
38
56
|
if (env === undefined && externalSearchApi !== undefined) {
|
|
39
57
|
defaultExternalSearchApi = externalSearchApi;
|
|
40
58
|
}
|
|
41
|
-
const
|
|
59
|
+
const resolvedRequest = resolveRequest(url.pathname);
|
|
60
|
+
const directBinaryResponse = await tryServeExternalBinary(manifest, request, env, resolvedRequest);
|
|
42
61
|
if (directBinaryResponse !== null) {
|
|
43
62
|
return directBinaryResponse;
|
|
44
63
|
}
|
|
64
|
+
const etag = manifest.deployVersion === undefined
|
|
65
|
+
? undefined
|
|
66
|
+
: `"${manifest.deployVersion}"`;
|
|
67
|
+
if (etag !== undefined &&
|
|
68
|
+
isCacheableRequest(request, url) &&
|
|
69
|
+
requestMatchesEtag(request.headers.get('if-none-match'), etag)) {
|
|
70
|
+
return new Response(null, {
|
|
71
|
+
status: 304,
|
|
72
|
+
headers: {
|
|
73
|
+
etag,
|
|
74
|
+
'cache-control': BROWSER_CACHE_CONTROL,
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const cacheDebugEnabled = isCacheDebugEnabled(env);
|
|
79
|
+
const responseCacheKey = manifest.deployVersion !== undefined && isCacheableRequest(request, url)
|
|
80
|
+
? buildResponseCacheKey(manifest.deployVersion, resolvedRequest, request.headers.get('accept'), url.pathname)
|
|
81
|
+
: undefined;
|
|
82
|
+
if (responseCacheKey !== undefined) {
|
|
83
|
+
const memoized = responseCache.get(responseCacheKey);
|
|
84
|
+
if (memoized !== undefined) {
|
|
85
|
+
return toWorkerResponse(memoized, cacheDebugEnabled ? 'l1' : undefined);
|
|
86
|
+
}
|
|
87
|
+
if (cache !== undefined) {
|
|
88
|
+
const cached = await cache.match(toL2CacheRequest(responseCacheKey));
|
|
89
|
+
if (cached !== undefined) {
|
|
90
|
+
const entry = await cachedResponseFromL2(cached);
|
|
91
|
+
if (entry !== null) {
|
|
92
|
+
responseCache.set(responseCacheKey, entry);
|
|
93
|
+
return toWorkerResponse(entry, cacheDebugEnabled ? 'l2' : undefined);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
45
98
|
const store = new CloudflareManifestContentStore(manifest, storeIndex, request, env);
|
|
46
99
|
const siteResponse = await handleSiteRequest(store, url.pathname, {
|
|
47
100
|
draftMode: 'exclude',
|
|
@@ -72,31 +125,239 @@ export function createCloudflareWorker(manifest, options = {}) {
|
|
|
72
125
|
plugins: options.plugins,
|
|
73
126
|
});
|
|
74
127
|
const headers = new Headers(siteResponse.headers);
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
128
|
+
const cacheHeaders = collectResponseCacheHeaders(siteResponse, request, url, etag);
|
|
129
|
+
if (cacheHeaders !== undefined) {
|
|
130
|
+
for (const [name, value] of Object.entries(cacheHeaders)) {
|
|
131
|
+
headers.set(name, value);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const rendered = {
|
|
81
135
|
status: siteResponse.status,
|
|
82
|
-
headers,
|
|
83
|
-
|
|
136
|
+
headers: Object.fromEntries(headers.entries()),
|
|
137
|
+
body: siteResponse.body ?? '',
|
|
138
|
+
};
|
|
139
|
+
if (responseCacheKey !== undefined &&
|
|
140
|
+
siteResponse.status === 200 &&
|
|
141
|
+
isCacheableContentType(siteResponse.headers['content-type'])) {
|
|
142
|
+
responseCache.set(responseCacheKey, rendered);
|
|
143
|
+
if (cache !== undefined) {
|
|
144
|
+
const putPromise = cache.put(toL2CacheRequest(responseCacheKey), toL2CacheResponse(rendered));
|
|
145
|
+
if (ctx?.waitUntil !== undefined) {
|
|
146
|
+
ctx.waitUntil(putPromise);
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
await putPromise;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return toWorkerResponse(rendered, cacheDebugEnabled && responseCacheKey !== undefined ? 'miss' : undefined);
|
|
84
154
|
},
|
|
85
155
|
};
|
|
86
156
|
}
|
|
87
|
-
function
|
|
157
|
+
function isCacheableRequest(request, url) {
|
|
158
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
if (url.search !== '') {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
return url.pathname !== '/api' && !url.pathname.startsWith('/api/');
|
|
165
|
+
}
|
|
166
|
+
function isCacheableContentType(contentType) {
|
|
167
|
+
if (contentType === undefined) {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
const mediaType = contentType.split(';', 1)[0]?.trim().toLowerCase();
|
|
171
|
+
if (mediaType === undefined || mediaType === '') {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
return CACHEABLE_CONTENT_TYPE_PREFIXES.some((prefix) => mediaType === prefix || mediaType.startsWith(`${prefix}/`));
|
|
175
|
+
}
|
|
176
|
+
function requestMatchesEtag(ifNoneMatch, etag) {
|
|
177
|
+
if (ifNoneMatch === null || ifNoneMatch.trim() === '') {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
if (ifNoneMatch.trim() === '*') {
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
return ifNoneMatch.split(',').some((candidate) => {
|
|
184
|
+
const trimmed = candidate.trim();
|
|
185
|
+
const value = trimmed.startsWith('W/') ? trimmed.slice(2) : trimmed;
|
|
186
|
+
return value === etag;
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
function collectResponseCacheHeaders(siteResponse, request, url, etag) {
|
|
190
|
+
if (etag === undefined ||
|
|
191
|
+
siteResponse.status !== 200 ||
|
|
192
|
+
!isCacheableRequest(request, url) ||
|
|
193
|
+
!isCacheableContentType(siteResponse.headers['content-type'])) {
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
const cacheHeaders = {
|
|
197
|
+
etag,
|
|
198
|
+
'cache-control': BROWSER_CACHE_CONTROL,
|
|
199
|
+
};
|
|
200
|
+
const varyValues = siteResponse.headers['vary']
|
|
201
|
+
?.split(',')
|
|
202
|
+
.map((value) => value.trim().toLowerCase()) ?? [];
|
|
203
|
+
// The Cloudflare edge cache does not vary on Accept, so extensionless
|
|
204
|
+
// content-negotiated routes must stay out of the CDN cache. They still get
|
|
205
|
+
// ETag/304 handling and browser revalidation.
|
|
206
|
+
if (!varyValues.includes('accept')) {
|
|
207
|
+
cacheHeaders['cdn-cache-control'] = CDN_CACHE_CONTROL;
|
|
208
|
+
}
|
|
209
|
+
return cacheHeaders;
|
|
210
|
+
}
|
|
211
|
+
class LruCache {
|
|
212
|
+
limit;
|
|
213
|
+
entries = new Map();
|
|
214
|
+
constructor(limit) {
|
|
215
|
+
this.limit = limit;
|
|
216
|
+
}
|
|
217
|
+
get(key) {
|
|
218
|
+
const cached = this.entries.get(key);
|
|
219
|
+
if (cached === undefined) {
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
this.entries.delete(key);
|
|
223
|
+
this.entries.set(key, cached);
|
|
224
|
+
return cached;
|
|
225
|
+
}
|
|
226
|
+
set(key, value) {
|
|
227
|
+
if (this.limit <= 0) {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
this.entries.delete(key);
|
|
231
|
+
this.entries.set(key, value);
|
|
232
|
+
while (this.entries.size > this.limit) {
|
|
233
|
+
const oldest = this.entries.keys().next().value;
|
|
234
|
+
if (oldest === undefined) {
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
this.entries.delete(oldest);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Memoizes deterministic search results per isolate. The search index is
|
|
243
|
+
* static within one deploy, so identical (query, options) calls return the
|
|
244
|
+
* same hits and repeated queries skip retrieval entirely.
|
|
245
|
+
*/
|
|
246
|
+
export function withSearchResultCache(api, limit) {
|
|
247
|
+
if (limit <= 0) {
|
|
248
|
+
return api;
|
|
249
|
+
}
|
|
250
|
+
const cache = new LruCache(limit);
|
|
251
|
+
return {
|
|
252
|
+
async search(query, options) {
|
|
253
|
+
const key = JSON.stringify([query, options ?? null]);
|
|
254
|
+
const cached = cache.get(key);
|
|
255
|
+
if (cached !== undefined) {
|
|
256
|
+
return cached;
|
|
257
|
+
}
|
|
258
|
+
const hits = await api.search(query, options);
|
|
259
|
+
cache.set(key, hits);
|
|
260
|
+
return hits;
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
function resolveDefaultCache() {
|
|
265
|
+
const cachesRef = globalThis
|
|
266
|
+
.caches;
|
|
267
|
+
const defaultCache = cachesRef?.default;
|
|
268
|
+
if (defaultCache === undefined ||
|
|
269
|
+
typeof defaultCache.match !== 'function' ||
|
|
270
|
+
typeof defaultCache.put !== 'function') {
|
|
271
|
+
return undefined;
|
|
272
|
+
}
|
|
273
|
+
return defaultCache;
|
|
274
|
+
}
|
|
275
|
+
function isCacheDebugEnabled(env) {
|
|
276
|
+
const value = env?.MDORIGIN_CACHE_DEBUG;
|
|
277
|
+
return value === '1' || value === 'true';
|
|
278
|
+
}
|
|
279
|
+
function buildResponseCacheKey(deployVersion, resolved, acceptHeader, pathname) {
|
|
280
|
+
const variant = resolveCacheVariant(resolved, acceptHeader);
|
|
281
|
+
return `${deployVersion}/${variant}${pathname}`;
|
|
282
|
+
}
|
|
283
|
+
function resolveCacheVariant(resolved, acceptHeader) {
|
|
284
|
+
if (resolved.kind === 'markdown') {
|
|
285
|
+
return 'md';
|
|
286
|
+
}
|
|
287
|
+
if (resolved.kind === 'html' &&
|
|
288
|
+
!resolved.requestPath.endsWith('.html') &&
|
|
289
|
+
acceptsMarkdown(acceptHeader)) {
|
|
290
|
+
return 'md';
|
|
291
|
+
}
|
|
292
|
+
return 'html';
|
|
293
|
+
}
|
|
294
|
+
function acceptsMarkdown(acceptHeader) {
|
|
295
|
+
if (!acceptHeader) {
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
return acceptHeader
|
|
299
|
+
.split(',')
|
|
300
|
+
.map((part) => part.split(';', 1)[0]?.trim().toLowerCase())
|
|
301
|
+
.includes('text/markdown');
|
|
302
|
+
}
|
|
303
|
+
function toL2CacheRequest(cacheKey) {
|
|
304
|
+
return new Request(`${L2_CACHE_KEY_ORIGIN}/${cacheKey}`);
|
|
305
|
+
}
|
|
306
|
+
function toL2CacheResponse(entry) {
|
|
307
|
+
const headers = new Headers(entry.headers);
|
|
308
|
+
headers.set('cache-control', L2_CACHE_CONTROL);
|
|
309
|
+
return new Response(toResponseBody(entry), {
|
|
310
|
+
status: entry.status,
|
|
311
|
+
headers,
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
async function cachedResponseFromL2(cached) {
|
|
315
|
+
if (cached.status !== 200) {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
const headers = new Headers(cached.headers);
|
|
319
|
+
headers.set('cache-control', BROWSER_CACHE_CONTROL);
|
|
320
|
+
const headerEntries = {};
|
|
321
|
+
headers.forEach((value, name) => {
|
|
322
|
+
headerEntries[name] = value;
|
|
323
|
+
});
|
|
324
|
+
return {
|
|
325
|
+
status: cached.status,
|
|
326
|
+
headers: headerEntries,
|
|
327
|
+
body: new Uint8Array(await cached.arrayBuffer()),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
function toWorkerResponse(entry, cacheStatus) {
|
|
331
|
+
const headers = new Headers(entry.headers);
|
|
332
|
+
if (cacheStatus !== undefined) {
|
|
333
|
+
headers.set(CACHE_DEBUG_HEADER, cacheStatus);
|
|
334
|
+
}
|
|
335
|
+
return new Response(toResponseBody(entry), {
|
|
336
|
+
status: entry.status,
|
|
337
|
+
headers,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
function toResponseBody(entry) {
|
|
341
|
+
if (entry.body instanceof Uint8Array) {
|
|
342
|
+
return new Blob([Uint8Array.from(entry.body)], {
|
|
343
|
+
type: entry.headers['content-type'],
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
return entry.body;
|
|
347
|
+
}
|
|
348
|
+
function getExternalSearchApi(manifest, env, cache, defaultApi, searchCacheLimit) {
|
|
88
349
|
if (!manifest.externalSearchEntries || manifest.externalSearchEntries.length === 0) {
|
|
89
350
|
return undefined;
|
|
90
351
|
}
|
|
91
352
|
if (!env) {
|
|
92
353
|
return (defaultApi ??
|
|
93
|
-
createSearchApiFromExternalBundle(manifest.externalSearchEntries, async (entry) => loadExternalSearchEntryResponse(entry, undefined, manifest.runtime?.r2Binding), manifest.siteConfig?.search));
|
|
354
|
+
withSearchResultCache(createSearchApiFromExternalBundle(manifest.externalSearchEntries, async (entry) => loadExternalSearchEntryResponse(entry, undefined, manifest.runtime?.r2Binding), manifest.siteConfig?.search), searchCacheLimit));
|
|
94
355
|
}
|
|
95
356
|
const cached = cache.get(env);
|
|
96
357
|
if (cached) {
|
|
97
358
|
return cached;
|
|
98
359
|
}
|
|
99
|
-
const searchApi = createSearchApiFromExternalBundle(manifest.externalSearchEntries, async (entry) => loadExternalSearchEntryResponse(entry, env, manifest.runtime?.r2Binding), manifest.siteConfig?.search);
|
|
360
|
+
const searchApi = withSearchResultCache(createSearchApiFromExternalBundle(manifest.externalSearchEntries, async (entry) => loadExternalSearchEntryResponse(entry, env, manifest.runtime?.r2Binding), manifest.siteConfig?.search), searchCacheLimit);
|
|
100
361
|
cache.set(env, searchApi);
|
|
101
362
|
return searchApi;
|
|
102
363
|
}
|
|
@@ -162,8 +423,7 @@ async function loadExternalSearchEntryResponse(entry, env, r2Binding) {
|
|
|
162
423
|
headers,
|
|
163
424
|
});
|
|
164
425
|
}
|
|
165
|
-
async function tryServeExternalBinary(manifest, request, env) {
|
|
166
|
-
const resolved = resolveRequest(new URL(request.url).pathname);
|
|
426
|
+
async function tryServeExternalBinary(manifest, request, env, resolved) {
|
|
167
427
|
if (resolved.kind !== 'asset' || !resolved.sourcePath) {
|
|
168
428
|
return null;
|
|
169
429
|
}
|
package/dist/cloudflare.js
CHANGED
|
@@ -82,6 +82,13 @@ export async function writeCloudflareBundle(options) {
|
|
|
82
82
|
assetsMaxBytes,
|
|
83
83
|
r2Binding,
|
|
84
84
|
});
|
|
85
|
+
// Deploy version = hash of the manifest payload (all entries, config, and
|
|
86
|
+
// search bundle references). Workers use it as a strong ETag so content
|
|
87
|
+
// edits produce a new version and invalidate every cached response.
|
|
88
|
+
manifest.deployVersion = createHash('sha256')
|
|
89
|
+
.update(JSON.stringify(manifest))
|
|
90
|
+
.digest('hex')
|
|
91
|
+
.slice(0, 16);
|
|
85
92
|
const packageImport = options.packageImport ?? 'mdorigin/cloudflare-runtime';
|
|
86
93
|
const workerFile = path.join(outDir, 'worker.mjs');
|
|
87
94
|
const bundleFile = path.join(outDir, BUNDLE_FILE_NAME);
|
|
@@ -163,7 +170,9 @@ export async function initCloudflareProject(options) {
|
|
|
163
170
|
' "assets": {',
|
|
164
171
|
` "directory": ${JSON.stringify(toPosixPath(path.relative(projectDir, path.join(path.dirname(options.workerEntry), bundleMetadata.assetsDir))))},`,
|
|
165
172
|
` "binding": ${JSON.stringify(DEFAULT_ASSETS_BINDING)},`,
|
|
166
|
-
' "run_worker_first":
|
|
173
|
+
' "run_worker_first": false,',
|
|
174
|
+
' "html_handling": "none",',
|
|
175
|
+
' "not_found_handling": "none"',
|
|
167
176
|
' }',
|
|
168
177
|
].join('\n')
|
|
169
178
|
: '',
|
package/dist/core/markdown.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ContentEntry } from './content-store.js';
|
|
1
2
|
export interface ParsedDocumentMeta {
|
|
2
3
|
title?: string;
|
|
3
4
|
name?: string;
|
|
@@ -10,21 +11,37 @@ export interface ParsedDocumentMeta {
|
|
|
10
11
|
aliases?: string[];
|
|
11
12
|
[key: string]: unknown;
|
|
12
13
|
}
|
|
13
|
-
export interface ParsedDocument {
|
|
14
|
-
sourcePath: string;
|
|
15
|
-
body: string;
|
|
16
|
-
html: string;
|
|
17
|
-
meta: ParsedDocumentMeta;
|
|
18
|
-
}
|
|
19
14
|
export interface ManagedIndexEntry {
|
|
20
15
|
kind: 'directory' | 'article';
|
|
21
16
|
title: string;
|
|
22
17
|
href: string;
|
|
23
18
|
detail?: string;
|
|
24
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Parsed document without rendered HTML. Extracting frontmatter metadata is
|
|
22
|
+
* orders of magnitude cheaper than rendering markdown to HTML, so metadata
|
|
23
|
+
* consumers (listings, sitemaps, feeds, alias scans) use this shape.
|
|
24
|
+
*/
|
|
25
|
+
export interface ParsedDocumentLite {
|
|
26
|
+
sourcePath: string;
|
|
27
|
+
body: string;
|
|
28
|
+
meta: ParsedDocumentMeta;
|
|
29
|
+
}
|
|
30
|
+
export interface ParsedDocument extends ParsedDocumentLite {
|
|
31
|
+
html: string;
|
|
32
|
+
}
|
|
25
33
|
export declare function getDocumentTitle(meta: ParsedDocumentMeta, body: string, fallback: string): string;
|
|
26
34
|
export declare function getDocumentSummary(meta: ParsedDocumentMeta, body: string): string | undefined;
|
|
27
35
|
export declare function parseMarkdownDocument(sourcePath: string, markdown: string): Promise<ParsedDocument>;
|
|
36
|
+
export declare function parseDocumentMeta(sourcePath: string, markdown: string): ParsedDocumentLite;
|
|
37
|
+
/**
|
|
38
|
+
* Parse a store entry's frontmatter metadata, memoized by entry identity.
|
|
39
|
+
* Immutable in-memory stores return the same entry object per path, so
|
|
40
|
+
* repeated metadata reads (alias scans, listings, feeds) parse each document
|
|
41
|
+
* at most once per isolate. File-system stores return fresh entry objects,
|
|
42
|
+
* which naturally bypasses the cache after content edits.
|
|
43
|
+
*/
|
|
44
|
+
export declare function parseEntryDocumentMeta(entry: ContentEntry): ParsedDocumentLite;
|
|
28
45
|
export declare function renderMarkdown(markdown: string): Promise<string>;
|
|
29
46
|
export declare function rewriteMarkdownLinksInHtml(html: string): string;
|
|
30
47
|
export declare function stripManagedIndexBlock(markdown: string): string;
|
package/dist/core/markdown.js
CHANGED
|
@@ -14,15 +14,40 @@ export function getDocumentSummary(meta, body) {
|
|
|
14
14
|
extractFirstParagraph(body));
|
|
15
15
|
}
|
|
16
16
|
export async function parseMarkdownDocument(sourcePath, markdown) {
|
|
17
|
+
const { body, meta } = parseDocumentMeta(sourcePath, markdown);
|
|
18
|
+
const html = rewriteMarkdownLinksInHtml(await renderMarkdown(body));
|
|
19
|
+
return {
|
|
20
|
+
sourcePath,
|
|
21
|
+
body,
|
|
22
|
+
html,
|
|
23
|
+
meta,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export function parseDocumentMeta(sourcePath, markdown) {
|
|
17
27
|
const parsed = matter(markdown);
|
|
18
|
-
const html = rewriteMarkdownLinksInHtml(await renderMarkdown(parsed.content));
|
|
19
28
|
return {
|
|
20
29
|
sourcePath,
|
|
21
30
|
body: parsed.content,
|
|
22
|
-
html,
|
|
23
31
|
meta: normalizeMeta(parsed.data),
|
|
24
32
|
};
|
|
25
33
|
}
|
|
34
|
+
const entryDocumentMetaCache = new WeakMap();
|
|
35
|
+
/**
|
|
36
|
+
* Parse a store entry's frontmatter metadata, memoized by entry identity.
|
|
37
|
+
* Immutable in-memory stores return the same entry object per path, so
|
|
38
|
+
* repeated metadata reads (alias scans, listings, feeds) parse each document
|
|
39
|
+
* at most once per isolate. File-system stores return fresh entry objects,
|
|
40
|
+
* which naturally bypasses the cache after content edits.
|
|
41
|
+
*/
|
|
42
|
+
export function parseEntryDocumentMeta(entry) {
|
|
43
|
+
const cached = entryDocumentMetaCache.get(entry);
|
|
44
|
+
if (cached !== undefined) {
|
|
45
|
+
return cached;
|
|
46
|
+
}
|
|
47
|
+
const parsed = parseDocumentMeta(entry.path, entry.text ?? '');
|
|
48
|
+
entryDocumentMetaCache.set(entry, parsed);
|
|
49
|
+
return parsed;
|
|
50
|
+
}
|
|
26
51
|
export async function renderMarkdown(markdown) {
|
|
27
52
|
const output = await remark()
|
|
28
53
|
.use(remarkGfm)
|
|
@@ -2,7 +2,7 @@ import path from 'node:path';
|
|
|
2
2
|
import { isIgnoredContentName } from './content-store.js';
|
|
3
3
|
import { inferDirectoryContentType, resolveContentType, } from './content-type.js';
|
|
4
4
|
import { getDirectoryIndexCandidates } from './directory-index.js';
|
|
5
|
-
import { extractManagedIndexEntries, getDocumentSummary, getDocumentTitle as getParsedDocumentTitle, parseMarkdownDocument, stripManagedIndexBlock, stripManagedIndexLinks, stripMachineOnlyMarkdownComments, } from './markdown.js';
|
|
5
|
+
import { extractManagedIndexEntries, getDocumentSummary, getDocumentTitle as getParsedDocumentTitle, parseEntryDocumentMeta, parseMarkdownDocument, stripManagedIndexBlock, stripManagedIndexLinks, stripMachineOnlyMarkdownComments, } from './markdown.js';
|
|
6
6
|
import { ensureTrailingSlash, trimLeadingSlash } from './site-url.js';
|
|
7
7
|
import { applyIndexTransforms, renderFooterOverride, renderHeaderOverride, renderPageWithPlugins, transformHtmlWithPlugins, } from './extensions.js';
|
|
8
8
|
import { handleApiRoute } from './api.js';
|
|
@@ -82,7 +82,7 @@ export async function handleSiteRequest(store, pathname, options) {
|
|
|
82
82
|
return renderNotFoundForResolvedRequest(store, resolved, options, negotiatedMarkdown, requestLocale);
|
|
83
83
|
}
|
|
84
84
|
if (resolved.kind === 'markdown' || negotiatedMarkdown) {
|
|
85
|
-
const parsed =
|
|
85
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
86
86
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
87
87
|
return renderNotFoundForResolvedRequest(store, resolved, options, negotiatedMarkdown, requestLocale);
|
|
88
88
|
}
|
|
@@ -94,7 +94,7 @@ export async function handleSiteRequest(store, pathname, options) {
|
|
|
94
94
|
body: entry.text,
|
|
95
95
|
};
|
|
96
96
|
}
|
|
97
|
-
const parsed =
|
|
97
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
98
98
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
99
99
|
return renderNotFoundForResolvedRequest(store, resolved, options, negotiatedMarkdown, requestLocale);
|
|
100
100
|
}
|
|
@@ -114,9 +114,7 @@ export async function handleSiteRequest(store, pathname, options) {
|
|
|
114
114
|
return renderListingPostsFragment(listingEntries, listingFragmentRequest);
|
|
115
115
|
}
|
|
116
116
|
const documentBody = listingEntries.length > 0 ? stripManagedIndexBlock(renderedBody) : renderedBody;
|
|
117
|
-
const renderedParsed =
|
|
118
|
-
? parsed
|
|
119
|
-
: await parseMarkdownDocument(resolved.sourcePath, documentBody);
|
|
117
|
+
const renderedParsed = await parseMarkdownDocument(resolved.sourcePath, documentBody);
|
|
120
118
|
return renderStructuredPage({
|
|
121
119
|
requestPath: resolved.requestPath,
|
|
122
120
|
sourcePath: resolved.sourcePath,
|
|
@@ -488,7 +486,7 @@ async function hasPublishedContent(store, contentPath, draftMode) {
|
|
|
488
486
|
return false;
|
|
489
487
|
}
|
|
490
488
|
if (draftMode === 'exclude') {
|
|
491
|
-
const parsed =
|
|
489
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
492
490
|
if (parsed.meta.draft === true) {
|
|
493
491
|
return false;
|
|
494
492
|
}
|
|
@@ -658,7 +656,7 @@ async function collectSitemapEntries(store, directoryPath, options) {
|
|
|
658
656
|
if (document === null || document.kind !== 'text' || document.text === undefined) {
|
|
659
657
|
continue;
|
|
660
658
|
}
|
|
661
|
-
const parsed =
|
|
659
|
+
const parsed = parseEntryDocumentMeta(document);
|
|
662
660
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
663
661
|
continue;
|
|
664
662
|
}
|
|
@@ -706,7 +704,7 @@ async function collectRssFeedItems(store, directoryPath, options, excludedDirect
|
|
|
706
704
|
if (document === null || document.kind !== 'text' || document.text === undefined) {
|
|
707
705
|
continue;
|
|
708
706
|
}
|
|
709
|
-
const parsed =
|
|
707
|
+
const parsed = parseEntryDocumentMeta(document);
|
|
710
708
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
711
709
|
continue;
|
|
712
710
|
}
|
|
@@ -842,7 +840,7 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
|
|
|
842
840
|
if (entry === null || entry.kind !== 'text' || entry.text === undefined) {
|
|
843
841
|
continue;
|
|
844
842
|
}
|
|
845
|
-
const parsed =
|
|
843
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
846
844
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
847
845
|
return notFound();
|
|
848
846
|
}
|
|
@@ -864,9 +862,7 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
|
|
|
864
862
|
return renderListingPostsFragment(listingEntries, listingFragmentRequest);
|
|
865
863
|
}
|
|
866
864
|
const documentBody = listingEntries.length > 0 ? stripManagedIndexBlock(renderedBody) : renderedBody;
|
|
867
|
-
const renderedParsed =
|
|
868
|
-
? parsed
|
|
869
|
-
: await parseMarkdownDocument(candidatePath, documentBody);
|
|
865
|
+
const renderedParsed = await parseMarkdownDocument(candidatePath, documentBody);
|
|
870
866
|
return renderStructuredPage({
|
|
871
867
|
requestPath,
|
|
872
868
|
sourcePath: candidatePath,
|
|
@@ -880,6 +876,10 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
|
|
|
880
876
|
store,
|
|
881
877
|
requestLocale,
|
|
882
878
|
draftMode: options.draftMode,
|
|
879
|
+
// This branch only renders extensionless directory routes, which serve
|
|
880
|
+
// a raw markdown variant through Accept negotiation; the HTML variant
|
|
881
|
+
// must therefore declare Vary: Accept like every other negotiated route.
|
|
882
|
+
varyOnAccept: true,
|
|
883
883
|
});
|
|
884
884
|
}
|
|
885
885
|
return null;
|
|
@@ -900,7 +900,7 @@ async function tryServeAlternateDirectoryMarkdown(store, resolved, options, nego
|
|
|
900
900
|
if (entry === null || entry.kind !== 'text' || entry.text === undefined) {
|
|
901
901
|
continue;
|
|
902
902
|
}
|
|
903
|
-
const parsed =
|
|
903
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
904
904
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
905
905
|
return notFound();
|
|
906
906
|
}
|
|
@@ -931,7 +931,7 @@ async function tryRedirectAlternateDirectoryMarkdown(store, resolved, options) {
|
|
|
931
931
|
if (entry === null || entry.kind !== 'text' || entry.text === undefined) {
|
|
932
932
|
continue;
|
|
933
933
|
}
|
|
934
|
-
const parsed =
|
|
934
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
935
935
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
936
936
|
return null;
|
|
937
937
|
}
|
|
@@ -1011,7 +1011,7 @@ async function findAliasRedirectLocation(store, directoryPath, requestPath, opti
|
|
|
1011
1011
|
if (document === null || document.kind !== 'text' || document.text === undefined) {
|
|
1012
1012
|
continue;
|
|
1013
1013
|
}
|
|
1014
|
-
const parsed =
|
|
1014
|
+
const parsed = parseEntryDocumentMeta(document);
|
|
1015
1015
|
if (parsed.meta.draft === true && options.draftMode === 'exclude') {
|
|
1016
1016
|
continue;
|
|
1017
1017
|
}
|
|
@@ -1137,7 +1137,7 @@ async function resolveDirectoryNav(store, entry) {
|
|
|
1137
1137
|
if (contentEntry === null || contentEntry.kind !== 'text' || contentEntry.text === undefined) {
|
|
1138
1138
|
continue;
|
|
1139
1139
|
}
|
|
1140
|
-
const parsed =
|
|
1140
|
+
const parsed = parseEntryDocumentMeta(contentEntry);
|
|
1141
1141
|
const shape = await inspectDirectoryShape(store, entry.path);
|
|
1142
1142
|
return {
|
|
1143
1143
|
title: getParsedDocumentTitle(parsed.meta, parsed.body, entry.name),
|
package/dist/core/site-config.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
4
|
import { tsImport } from 'tsx/esm/api';
|
|
5
5
|
import { getDirectoryIndexCandidates } from './directory-index.js';
|
|
6
|
-
import {
|
|
6
|
+
import { parseEntryDocumentMeta } from './markdown.js';
|
|
7
7
|
import { DEFAULT_SITE_LOCALE, validateSiteMessages, } from '../i18n/messages.js';
|
|
8
8
|
export async function loadSiteConfig(options = {}) {
|
|
9
9
|
return (await loadUserSiteConfig(options)).siteConfig;
|
|
@@ -78,7 +78,7 @@ export async function applySiteConfigFrontmatterDefaults(store, siteConfig) {
|
|
|
78
78
|
if (entry === null || entry.kind !== 'text' || entry.text === undefined) {
|
|
79
79
|
continue;
|
|
80
80
|
}
|
|
81
|
-
const parsed =
|
|
81
|
+
const parsed = parseEntryDocumentMeta(entry);
|
|
82
82
|
return {
|
|
83
83
|
...siteConfig,
|
|
84
84
|
siteTitle: siteConfig.siteTitleConfigured
|