@timber-js/app 0.2.0-alpha.214 → 0.2.0-alpha.216
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/_chunks/als-registry-BZqHCtq-.js.map +1 -1
- package/dist/_chunks/{chains-CjK1Eu6a.js → chains-YKZ8WpIW.js} +2 -2
- package/dist/_chunks/{chains-CjK1Eu6a.js.map → chains-YKZ8WpIW.js.map} +1 -1
- package/dist/_chunks/{classify-GAdt6aiA.js → classify-2Yp3xJY1.js} +3 -3
- package/dist/_chunks/{classify-GAdt6aiA.js.map → classify-2Yp3xJY1.js.map} +1 -1
- package/dist/_chunks/{cli-check-DOzjlycg.js → cli-check-D2WtbNqo.js} +3 -3
- package/dist/_chunks/{cli-check-DOzjlycg.js.map → cli-check-D2WtbNqo.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-B9wDaQvW.js → cli-schema-sync-CySLKrO3.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-B9wDaQvW.js.map → cli-schema-sync-CySLKrO3.js.map} +1 -1
- package/dist/_chunks/{client-dep-entries-DyDqXOF9.js → client-dep-entries-BOkpKjj1.js} +47 -3
- package/dist/_chunks/client-dep-entries-BOkpKjj1.js.map +1 -0
- package/dist/_chunks/{convention-lint-B3QEGJX7.js → convention-lint-ByKJ6aqD.js} +2 -2
- package/dist/_chunks/{convention-lint-B3QEGJX7.js.map → convention-lint-ByKJ6aqD.js.map} +1 -1
- package/dist/_chunks/{dev-server-_9L4KWC-.js → dev-server-B8zsT-ee.js} +4 -4
- package/dist/_chunks/{dev-server-_9L4KWC-.js.map → dev-server-B8zsT-ee.js.map} +1 -1
- package/dist/_chunks/{live-graph-Cd3YHvrH.js → live-graph-BhtrZpRd.js} +4 -4
- package/dist/_chunks/{live-graph-Cd3YHvrH.js.map → live-graph-BhtrZpRd.js.map} +1 -1
- package/dist/_chunks/{metadata-routes-DSDjM_hJ.js → metadata-routes-B3XJNyIH.js} +1 -2
- package/dist/_chunks/metadata-routes-B3XJNyIH.js.map +1 -0
- package/dist/_chunks/{poison-scan-BnJjBOkn.js → poison-scan-C4FgMxFl.js} +2 -2
- package/dist/_chunks/{poison-scan-BnJjBOkn.js.map → poison-scan-C4FgMxFl.js.map} +1 -1
- package/dist/_chunks/{scanner-CKAT5gRx.js → scanner-Cb3fSjAC.js} +4 -4
- package/dist/_chunks/{scanner-CKAT5gRx.js.map → scanner-Cb3fSjAC.js.map} +1 -1
- package/dist/_chunks/{walkers-DwCXEyRu.js → walkers-Ber9bamD.js} +3 -3
- package/dist/_chunks/{walkers-DwCXEyRu.js.map → walkers-Ber9bamD.js.map} +1 -1
- package/dist/adapters/types.d.ts +3 -1
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/analyze/crawl-entry.js +3 -3
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cli.d.ts +5 -5
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +15 -14
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +28 -53
- package/dist/index.js.map +1 -1
- package/dist/plugins/client-dep-entries.d.ts +36 -0
- package/dist/plugins/client-dep-entries.d.ts.map +1 -1
- package/dist/routing/index.js +2 -2
- package/dist/server/als-registry.d.ts +2 -0
- package/dist/server/als-registry.d.ts.map +1 -1
- package/dist/server/internal.js +2 -2
- package/dist/server/internal.js.map +1 -1
- package/dist/server/metadata-collector.d.ts +2 -0
- package/dist/server/metadata-collector.d.ts.map +1 -1
- package/dist/server/metadata-route-links.d.ts +70 -0
- package/dist/server/metadata-route-links.d.ts.map +1 -0
- package/dist/server/metadata-routes.d.ts +0 -24
- package/dist/server/metadata-routes.d.ts.map +1 -1
- package/dist/server/port-resolution.d.ts +3 -12
- package/dist/server/port-resolution.d.ts.map +1 -1
- package/dist/server/route-element-builder.d.ts.map +1 -1
- package/dist/server/route-matcher.d.ts +7 -0
- package/dist/server/route-matcher.d.ts.map +1 -1
- package/docs/api/36-cli.mdx +8 -4
- package/docs/learn/13-deploying.mdx +2 -0
- package/package.json +1 -1
- package/src/adapters/types.ts +3 -1
- package/src/cli.ts +18 -16
- package/src/index.ts +48 -71
- package/src/plugins/client-dep-entries.ts +46 -0
- package/src/server/als-registry.ts +2 -0
- package/src/server/metadata-collector.ts +15 -17
- package/src/server/metadata-route-links.ts +200 -0
- package/src/server/metadata-routes.ts +0 -106
- package/src/server/port-resolution.ts +6 -16
- package/src/server/route-element-builder.ts +1 -0
- package/src/server/route-matcher.ts +2 -2
- package/dist/_chunks/client-dep-entries-DyDqXOF9.js.map +0 -1
- package/dist/_chunks/metadata-routes-DSDjM_hJ.js.map +0 -1
|
@@ -27,12 +27,13 @@ import { createElement, Fragment } from 'react';
|
|
|
27
27
|
import type { ReactNode } from 'react';
|
|
28
28
|
|
|
29
29
|
import { requestContextAls } from './als-registry.ts';
|
|
30
|
+
import type { RequestContextStore } from './als-registry.ts';
|
|
30
31
|
import type { Metadata } from './types.ts';
|
|
31
32
|
import type { ManifestSegmentNode } from './route-matcher.ts';
|
|
32
33
|
import { withSpan } from './tracing.ts';
|
|
33
34
|
import { resolveMetadata, renderMetadataToElements, headElementsToReact } from './metadata.ts';
|
|
34
35
|
import type { SegmentMetadataEntry } from './metadata.ts';
|
|
35
|
-
import {
|
|
36
|
+
import { findDeclaredImageOwners, linkMetadataRoutes } from './metadata-route-links.ts';
|
|
36
37
|
|
|
37
38
|
// ─── Request-scoped metadata entry store ────────────────────────────────
|
|
38
39
|
|
|
@@ -41,16 +42,13 @@ import { collectMetadataRouteHeadElements } from './metadata-routes.ts';
|
|
|
41
42
|
* concurrent resolution (TIM-1367). Dynamic metadata pushes a promise;
|
|
42
43
|
* static metadata pushes the resolved object directly.
|
|
43
44
|
*/
|
|
44
|
-
|
|
45
|
-
metadata: Metadata | Promise<Metadata | null>;
|
|
46
|
-
isPage: boolean;
|
|
47
|
-
}
|
|
45
|
+
type DeferredMetadataEntry = NonNullable<RequestContextStore['_metadataEntries']>[number];
|
|
48
46
|
|
|
49
47
|
function getDeferredMetadataEntries(): DeferredMetadataEntry[] {
|
|
50
48
|
const store = requestContextAls.getStore();
|
|
51
49
|
if (!store) return [];
|
|
52
50
|
store._metadataEntries ??= [];
|
|
53
|
-
return store._metadataEntries
|
|
51
|
+
return store._metadataEntries;
|
|
54
52
|
}
|
|
55
53
|
|
|
56
54
|
// ─── MetadataSettle ─────────────────────────────────────────────────────
|
|
@@ -76,6 +74,8 @@ export interface MetadataCollectorProps {
|
|
|
76
74
|
metadataExport: Metadata | (() => Promise<Metadata>);
|
|
77
75
|
segmentName: string;
|
|
78
76
|
isPage: boolean;
|
|
77
|
+
/** Index of the owning segment in the route chain. */
|
|
78
|
+
segmentIndex: number;
|
|
79
79
|
children: ReactNode;
|
|
80
80
|
}
|
|
81
81
|
|
|
@@ -92,7 +92,7 @@ export interface MetadataCollectorProps {
|
|
|
92
92
|
* awaits the promise for error ownership.
|
|
93
93
|
*/
|
|
94
94
|
export function MetadataCollector(props: MetadataCollectorProps): ReactNode {
|
|
95
|
-
const { metadataExport, segmentName, isPage, children } = props;
|
|
95
|
+
const { metadataExport, segmentName, isPage, segmentIndex, children } = props;
|
|
96
96
|
|
|
97
97
|
if (typeof metadataExport === 'function') {
|
|
98
98
|
const promise = withSpan('timber.metadata', { 'timber.segment': segmentName }, () =>
|
|
@@ -103,12 +103,12 @@ export function MetadataCollector(props: MetadataCollectorProps): ReactNode {
|
|
|
103
103
|
// Node's unhandledRejection before they do.
|
|
104
104
|
promise.catch(() => {});
|
|
105
105
|
|
|
106
|
-
getDeferredMetadataEntries().push({ metadata: promise, isPage });
|
|
106
|
+
getDeferredMetadataEntries().push({ metadata: promise, isPage, segmentIndex });
|
|
107
107
|
|
|
108
108
|
return createElement(Fragment, null, children, createElement(MetadataSettle, { promise }));
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
-
getDeferredMetadataEntries().push({ metadata: metadataExport, isPage });
|
|
111
|
+
getDeferredMetadataEntries().push({ metadata: metadataExport, isPage, segmentIndex });
|
|
112
112
|
return children;
|
|
113
113
|
}
|
|
114
114
|
|
|
@@ -152,26 +152,24 @@ export async function MetadataHead(props: MetadataHeadProps): Promise<ReactNode>
|
|
|
152
152
|
e.metadata instanceof Promise ? e.metadata : Promise.resolve(e.metadata)
|
|
153
153
|
)
|
|
154
154
|
);
|
|
155
|
-
const entries: SegmentMetadataEntry[] = [];
|
|
155
|
+
const entries: (SegmentMetadataEntry & { segmentIndex: number })[] = [];
|
|
156
156
|
for (let i = 0; i < settled.length; i++) {
|
|
157
157
|
const s = settled[i];
|
|
158
158
|
if (s.status === 'fulfilled' && s.value) {
|
|
159
|
-
|
|
159
|
+
const { isPage, segmentIndex } = deferredEntries[i];
|
|
160
|
+
entries.push({ metadata: s.value, isPage, segmentIndex });
|
|
160
161
|
}
|
|
161
162
|
}
|
|
162
163
|
|
|
163
164
|
const resolved = resolveMetadata(entries);
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
const autoLinked = collectMetadataRouteHeadElements(
|
|
165
|
+
const { metadata, elements } = linkMetadataRoutes(
|
|
167
166
|
segments,
|
|
168
|
-
Infinity,
|
|
169
167
|
resolved,
|
|
168
|
+
findDeclaredImageOwners(entries, resolved),
|
|
170
169
|
new URL(requestUrl),
|
|
171
170
|
rawSegmentParams,
|
|
172
171
|
metadataRouteHashes
|
|
173
172
|
);
|
|
174
|
-
headElements.push(...autoLinked);
|
|
175
173
|
|
|
176
|
-
return headElementsToReact(
|
|
174
|
+
return headElementsToReact([...renderMetadataToElements(metadata), ...elements]);
|
|
177
175
|
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-linking: turn the metadata route files in a page's segment chain into
|
|
3
|
+
* the <link>/<meta> tags its <head> carries, and decide precedence between
|
|
4
|
+
* those files and the metadata the app declares.
|
|
5
|
+
*
|
|
6
|
+
* Every link must name a file the metadata route matcher actually serves at
|
|
7
|
+
* that URL, so the OG winner is chosen by asking the matcher rather than by
|
|
8
|
+
* modelling its precedence here.
|
|
9
|
+
*
|
|
10
|
+
* See design/16-metadata.md §"Auto-Linking".
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import type { HeadElement } from './metadata.ts';
|
|
15
|
+
import type { Metadata } from './types.ts';
|
|
16
|
+
import { matchMetadataRoute, type ManifestSegmentNode } from './route-matcher.ts';
|
|
17
|
+
import { extractUrlParts } from './chain-url-parts.ts';
|
|
18
|
+
import {
|
|
19
|
+
METADATA_ROUTE_CONVENTIONS,
|
|
20
|
+
getMetadataRouteAutoLink,
|
|
21
|
+
resolveServePathForFile,
|
|
22
|
+
type MetadataRouteType,
|
|
23
|
+
} from './metadata-routes.ts';
|
|
24
|
+
|
|
25
|
+
// In dev mode, use a per-startup nonce for metadata route cache busting
|
|
26
|
+
// instead of per-file content hashes (avoids rehashing on every request).
|
|
27
|
+
let _devNonce: string | undefined;
|
|
28
|
+
function getDevNonce(): string {
|
|
29
|
+
_devNonce ??= randomUUID().slice(0, 8);
|
|
30
|
+
return _devNonce;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Segment index whose metadata export supplied the resolved `openGraph.images`
|
|
35
|
+
* and `twitter.images`, or -1 when none did. A file-based `opengraph-image`
|
|
36
|
+
* replaces declared images only from a deeper segment.
|
|
37
|
+
*/
|
|
38
|
+
export interface DeclaredImageOwners {
|
|
39
|
+
openGraph: number;
|
|
40
|
+
twitter: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Find which segment's export supplied the resolved `openGraph.images` and
|
|
45
|
+
* `twitter.images`: the deepest entry whose images are the resolved value.
|
|
46
|
+
* Read off the merge result rather than re-deriving `resolveMetadata`'s merge
|
|
47
|
+
* rule, so the two cannot drift.
|
|
48
|
+
*/
|
|
49
|
+
export function findDeclaredImageOwners(
|
|
50
|
+
entries: { metadata: Metadata; segmentIndex: number }[],
|
|
51
|
+
resolved: Metadata
|
|
52
|
+
): DeclaredImageOwners {
|
|
53
|
+
const owners: DeclaredImageOwners = { openGraph: -1, twitter: -1 };
|
|
54
|
+
const ogImages = resolved.openGraph?.images;
|
|
55
|
+
const twitterImages = resolved.twitter?.images;
|
|
56
|
+
for (const { metadata, segmentIndex } of entries) {
|
|
57
|
+
if (ogImages && metadata.openGraph?.images === ogImages) owners.openGraph = segmentIndex;
|
|
58
|
+
if (twitterImages && metadata.twitter?.images === twitterImages) owners.twitter = segmentIndex;
|
|
59
|
+
}
|
|
60
|
+
return owners;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Auto-linked head elements, and the declared metadata they leave in force. */
|
|
64
|
+
export interface MetadataRouteLinks {
|
|
65
|
+
/** `resolvedMetadata` minus any declared images a deeper file replaced. */
|
|
66
|
+
metadata: Metadata;
|
|
67
|
+
elements: HeadElement[];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Link metadata route files in the segment chain into the page's head.
|
|
72
|
+
*
|
|
73
|
+
* Walks each segment's metadataRoutes, resolves serve paths and URLs, and
|
|
74
|
+
* emits HeadElement descriptors for <link> and <meta> tags that React Float
|
|
75
|
+
* hoists into <head>.
|
|
76
|
+
*
|
|
77
|
+
* A metadata file is served under the URL of the segment that owns it, not
|
|
78
|
+
* under every descendant URL: a root `app/icon.tsx` rendered on `/map` links
|
|
79
|
+
* `/icon.png`, and `app/posts/[id]/opengraph-image.tsx` on `/posts/42/comments`
|
|
80
|
+
* links `/posts/42/opengraph-image.png`. The owner's prefix is the URL parts
|
|
81
|
+
* the chain has consumed through that segment (`extractUrlParts`, the same
|
|
82
|
+
* walk slot matching uses), filled with the request's raw param values — the
|
|
83
|
+
* parts the metadata route matcher walks back to the same owner.
|
|
84
|
+
*
|
|
85
|
+
* Segments at or below an intercepting segment are skipped: the metadata
|
|
86
|
+
* matcher only walks the canonical tree, so nothing serves their files.
|
|
87
|
+
*
|
|
88
|
+
* Precedence, so no tag is ever emitted twice:
|
|
89
|
+
* - Icon and apple-icon files link from every segment, root to leaf, unless
|
|
90
|
+
* the metadata declares `icons.icon` / `icons.apple`. A declared manifest
|
|
91
|
+
* likewise replaces `app/manifest.*`.
|
|
92
|
+
* - Only the deepest served `opengraph-image` links. It replaces declared
|
|
93
|
+
* `openGraph.images` / `twitter.images` from a shallower segment (those are
|
|
94
|
+
* dropped from the returned metadata) and yields to images declared at its
|
|
95
|
+
* own segment or deeper.
|
|
96
|
+
*
|
|
97
|
+
* See design/16-metadata.md §"Auto-Linking"
|
|
98
|
+
*/
|
|
99
|
+
export function linkMetadataRoutes(
|
|
100
|
+
segments: ManifestSegmentNode[],
|
|
101
|
+
resolvedMetadata: Metadata,
|
|
102
|
+
declaredImages: DeclaredImageOwners,
|
|
103
|
+
requestUrl: URL,
|
|
104
|
+
rawSegmentParams: Record<string, string | string[]>,
|
|
105
|
+
metadataRouteHashes?: Record<string, string>
|
|
106
|
+
): MetadataRouteLinks {
|
|
107
|
+
const elements: HeadElement[] = [];
|
|
108
|
+
// In dev mode, use the request origin so OG URLs resolve to localhost.
|
|
109
|
+
// In production, use metadataBase (the canonical domain).
|
|
110
|
+
const ogBase =
|
|
111
|
+
process.env.NODE_ENV !== 'production'
|
|
112
|
+
? new URL(requestUrl.origin)
|
|
113
|
+
: resolvedMetadata.metadataBase;
|
|
114
|
+
|
|
115
|
+
const interceptingIndex = segments.findIndex((s) => s.segmentType === 'intercepting');
|
|
116
|
+
const servedDepth = interceptingIndex === -1 ? segments.length : interceptingIndex;
|
|
117
|
+
|
|
118
|
+
// The canonical (decoded) URL parts each served segment owns.
|
|
119
|
+
const ownerParts = segments
|
|
120
|
+
.slice(0, servedDepth)
|
|
121
|
+
.map((_, si) => extractUrlParts(segments.slice(0, si + 1), rawSegmentParams));
|
|
122
|
+
|
|
123
|
+
// The OG winner is the deepest segment whose link the metadata matcher
|
|
124
|
+
// resolves back to that segment's own file. Several segments can share one
|
|
125
|
+
// URL — a group or a zero-length [[...slug]] adds no part, and sibling
|
|
126
|
+
// groups off the chain own the same root URL — and only one file is served
|
|
127
|
+
// there, so asking the matcher is the one way the link and its cache-bust
|
|
128
|
+
// hash cannot name a different image than the URL returns.
|
|
129
|
+
let ogFileIndex = -1;
|
|
130
|
+
for (let si = servedDepth - 1; si >= 0 && ogFileIndex === -1; si--) {
|
|
131
|
+
for (const [baseName, file] of Object.entries(segments[si].metadataRoutes ?? {})) {
|
|
132
|
+
if (METADATA_ROUTE_CONVENTIONS[baseName]?.type !== 'opengraph-image') continue;
|
|
133
|
+
const path = ['', ...ownerParts[si], resolveServePathForFile(baseName, file.filePath)].join(
|
|
134
|
+
'/'
|
|
135
|
+
);
|
|
136
|
+
if (matchMetadataRoute(segments[0], path)?.file === file) ogFileIndex = si;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const linkOgImage = ogFileIndex > declaredImages.openGraph;
|
|
140
|
+
const linkTwitterImage = linkOgImage && ogFileIndex > declaredImages.twitter;
|
|
141
|
+
const declaredTypes = new Set<MetadataRouteType>();
|
|
142
|
+
if (resolvedMetadata.icons?.icon) declaredTypes.add('icon');
|
|
143
|
+
if (resolvedMetadata.icons?.apple) declaredTypes.add('apple-icon');
|
|
144
|
+
if (resolvedMetadata.manifest) declaredTypes.add('manifest');
|
|
145
|
+
|
|
146
|
+
for (let si = 0; si < servedDepth; si++) {
|
|
147
|
+
const segment = segments[si];
|
|
148
|
+
if (!segment.metadataRoutes) continue;
|
|
149
|
+
// Encode each part so the href canonicalizes back to the pathname the
|
|
150
|
+
// matcher resolves to this owner.
|
|
151
|
+
const segmentPrefix = ownerParts[si].map((part) => `/${encodeURIComponent(part)}`).join('');
|
|
152
|
+
for (const baseName of Object.keys(segment.metadataRoutes)) {
|
|
153
|
+
const convention = METADATA_ROUTE_CONVENTIONS[baseName];
|
|
154
|
+
if (!convention) continue;
|
|
155
|
+
if (!convention.nestable && segment.urlPath !== '/') continue;
|
|
156
|
+
if (declaredTypes.has(convention.type)) continue;
|
|
157
|
+
if (convention.type === 'opengraph-image' && (!linkOgImage || si !== ogFileIndex)) {
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
const metaFile = segment.metadataRoutes[baseName];
|
|
161
|
+
const fileServePath = metaFile?.filePath
|
|
162
|
+
? resolveServePathForFile(baseName, metaFile.filePath)
|
|
163
|
+
: convention.serveExtension
|
|
164
|
+
? `${convention.servePath}.${convention.serveExtension}`
|
|
165
|
+
: convention.servePath;
|
|
166
|
+
let href = `${segmentPrefix}/${fileServePath}`;
|
|
167
|
+
if (convention.type === 'opengraph-image') {
|
|
168
|
+
const fileHash = metaFile?.filePath ? metadataRouteHashes?.[metaFile.filePath] : undefined;
|
|
169
|
+
const cacheBust = fileHash ?? getDevNonce();
|
|
170
|
+
href = `${href}?${cacheBust}`;
|
|
171
|
+
}
|
|
172
|
+
if (ogBase && convention.type === 'opengraph-image') {
|
|
173
|
+
href = new URL(href, ogBase).toString();
|
|
174
|
+
}
|
|
175
|
+
for (const autoLink of getMetadataRouteAutoLink(convention.type, href)) {
|
|
176
|
+
if (autoLink.tag === 'link') {
|
|
177
|
+
const attrs: Record<string, string> = { rel: autoLink.rel, href: autoLink.href };
|
|
178
|
+
if (autoLink.type) attrs.type = autoLink.type;
|
|
179
|
+
elements.push({ tag: 'link', attrs });
|
|
180
|
+
} else {
|
|
181
|
+
if (autoLink.name === 'twitter:image' && !linkTwitterImage) continue;
|
|
182
|
+
const attrs: Record<string, string> = { content: autoLink.content };
|
|
183
|
+
if (autoLink.property) attrs.property = autoLink.property;
|
|
184
|
+
if (autoLink.name) attrs.name = autoLink.name;
|
|
185
|
+
elements.push({ tag: 'meta', attrs });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// The linked file replaces images declared by a shallower segment.
|
|
192
|
+
const metadata = { ...resolvedMetadata };
|
|
193
|
+
if (linkOgImage && metadata.openGraph?.images) {
|
|
194
|
+
metadata.openGraph = { ...metadata.openGraph, images: undefined };
|
|
195
|
+
}
|
|
196
|
+
if (linkTwitterImage && metadata.twitter?.images) {
|
|
197
|
+
metadata.twitter = { ...metadata.twitter, images: undefined };
|
|
198
|
+
}
|
|
199
|
+
return { metadata, elements };
|
|
200
|
+
}
|
|
@@ -10,11 +10,9 @@
|
|
|
10
10
|
* See design/16-metadata.md §"Metadata Routes"
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import { randomUUID } from 'node:crypto';
|
|
14
13
|
import type { HeadElement } from './metadata.ts';
|
|
15
14
|
import type { Metadata } from './types.ts';
|
|
16
15
|
import type { ManifestSegmentNode } from './route-matcher.ts';
|
|
17
|
-
import { extractUrlParts } from './chain-url-parts.ts';
|
|
18
16
|
|
|
19
17
|
// ─── Types ───────────────────────────────────────────────────────────────────
|
|
20
18
|
|
|
@@ -340,107 +338,3 @@ export function getMetadataRouteAutoLink(type: MetadataRouteType, href: string):
|
|
|
340
338
|
return [];
|
|
341
339
|
}
|
|
342
340
|
}
|
|
343
|
-
|
|
344
|
-
// ─── Auto-Linking ──────────────────────────────────────────────────────────
|
|
345
|
-
|
|
346
|
-
// In dev mode, use a per-startup nonce for metadata route cache busting
|
|
347
|
-
// instead of per-file content hashes (avoids rehashing on every request).
|
|
348
|
-
let _devNonce: string | undefined;
|
|
349
|
-
function getDevNonce(): string {
|
|
350
|
-
_devNonce ??= randomUUID().slice(0, 8);
|
|
351
|
-
return _devNonce;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* Collect auto-linked head elements from metadata route files in the segment chain.
|
|
356
|
-
*
|
|
357
|
-
* Walks each segment's metadataRoutes, resolves serve paths and URLs, and
|
|
358
|
-
* emits HeadElement descriptors for <link> and <meta> tags that React Float
|
|
359
|
-
* hoists into <head>.
|
|
360
|
-
*
|
|
361
|
-
* A metadata file is served under the URL of the segment that owns it, not
|
|
362
|
-
* under every descendant URL: a root `app/icon.tsx` rendered on `/map` links
|
|
363
|
-
* `/icon.png`, and `app/posts/[id]/opengraph-image.tsx` on `/posts/42/comments`
|
|
364
|
-
* links `/posts/42/opengraph-image.png`. The owner's prefix is the URL parts
|
|
365
|
-
* the chain has consumed through that segment (`extractUrlParts`, the same
|
|
366
|
-
* walk slot matching uses), filled with the request's raw param values — the
|
|
367
|
-
* parts the metadata route matcher walks back to the same owner.
|
|
368
|
-
*
|
|
369
|
-
* Segments at or below an intercepting segment are skipped: the metadata
|
|
370
|
-
* matcher only walks the canonical tree, so nothing serves their files.
|
|
371
|
-
*
|
|
372
|
-
* See design/16-metadata.md §"Auto-Linking"
|
|
373
|
-
*/
|
|
374
|
-
export function collectMetadataRouteHeadElements(
|
|
375
|
-
segments: ManifestSegmentNode[],
|
|
376
|
-
firstDeniedIndex: number,
|
|
377
|
-
resolvedMetadata: Metadata,
|
|
378
|
-
requestUrl: URL,
|
|
379
|
-
rawSegmentParams: Record<string, string | string[]>,
|
|
380
|
-
metadataRouteHashes?: Record<string, string>
|
|
381
|
-
): HeadElement[] {
|
|
382
|
-
const elements: HeadElement[] = [];
|
|
383
|
-
const hasUserOgImage = Boolean(resolvedMetadata.openGraph?.images);
|
|
384
|
-
const hasUserTwitterImage = Boolean(resolvedMetadata.twitter?.images);
|
|
385
|
-
// In dev mode, use the request origin so OG URLs resolve to localhost.
|
|
386
|
-
// In production, use metadataBase (the canonical domain).
|
|
387
|
-
const ogBase =
|
|
388
|
-
process.env.NODE_ENV !== 'production'
|
|
389
|
-
? new URL(requestUrl.origin)
|
|
390
|
-
: resolvedMetadata.metadataBase;
|
|
391
|
-
|
|
392
|
-
const interceptingIndex = segments.findIndex((s) => s.segmentType === 'intercepting');
|
|
393
|
-
const servedDepth = interceptingIndex === -1 ? segments.length : interceptingIndex;
|
|
394
|
-
|
|
395
|
-
for (let si = 0; si < servedDepth; si++) {
|
|
396
|
-
const segment = segments[si];
|
|
397
|
-
if (!segment.metadataRoutes) continue;
|
|
398
|
-
if (si >= firstDeniedIndex) continue;
|
|
399
|
-
// Params are canonical (decoded) values; encode each part so the href
|
|
400
|
-
// canonicalizes back to the pathname the matcher resolves to this owner.
|
|
401
|
-
const segmentPrefix = extractUrlParts(segments.slice(0, si + 1), rawSegmentParams)
|
|
402
|
-
.map((part) => `/${encodeURIComponent(part)}`)
|
|
403
|
-
.join('');
|
|
404
|
-
for (const baseName of Object.keys(segment.metadataRoutes)) {
|
|
405
|
-
const convention = METADATA_ROUTE_CONVENTIONS[baseName];
|
|
406
|
-
if (!convention) continue;
|
|
407
|
-
if (!convention.nestable && segment.urlPath !== '/') continue;
|
|
408
|
-
if (convention.type === 'opengraph-image' && hasUserOgImage) continue;
|
|
409
|
-
const metaFile = segment.metadataRoutes[baseName];
|
|
410
|
-
const fileServePath = metaFile?.filePath
|
|
411
|
-
? resolveServePathForFile(baseName, metaFile.filePath)
|
|
412
|
-
: convention.serveExtension
|
|
413
|
-
? `${convention.servePath}.${convention.serveExtension}`
|
|
414
|
-
: convention.servePath;
|
|
415
|
-
let href = `${segmentPrefix}/${fileServePath}`;
|
|
416
|
-
if (convention.type === 'opengraph-image') {
|
|
417
|
-
const fileHash = metaFile?.filePath ? metadataRouteHashes?.[metaFile.filePath] : undefined;
|
|
418
|
-
const cacheBust = fileHash ?? getDevNonce();
|
|
419
|
-
href = `${href}?${cacheBust}`;
|
|
420
|
-
}
|
|
421
|
-
if (ogBase && convention.type === 'opengraph-image') {
|
|
422
|
-
href = new URL(href, ogBase).toString();
|
|
423
|
-
}
|
|
424
|
-
for (const autoLink of getMetadataRouteAutoLink(convention.type, href)) {
|
|
425
|
-
if (
|
|
426
|
-
hasUserTwitterImage &&
|
|
427
|
-
autoLink.tag === 'meta' &&
|
|
428
|
-
'name' in autoLink &&
|
|
429
|
-
autoLink.name === 'twitter:image'
|
|
430
|
-
)
|
|
431
|
-
continue;
|
|
432
|
-
if (autoLink.tag === 'link') {
|
|
433
|
-
const attrs: Record<string, string> = { rel: autoLink.rel, href: autoLink.href };
|
|
434
|
-
if (autoLink.type) attrs.type = autoLink.type;
|
|
435
|
-
elements.push({ tag: 'link', attrs });
|
|
436
|
-
} else {
|
|
437
|
-
const attrs: Record<string, string> = { content: autoLink.content };
|
|
438
|
-
if (autoLink.property) attrs.property = autoLink.property;
|
|
439
|
-
if (autoLink.name) attrs.name = autoLink.name;
|
|
440
|
-
elements.push({ tag: 'meta', attrs });
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
return elements;
|
|
446
|
-
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/** Port input precedence for dev
|
|
1
|
+
/** Port input precedence for dev. Vite owns binding and restart reuse. */
|
|
2
2
|
|
|
3
|
-
/** Default port used by `timber dev
|
|
3
|
+
/** Default port used by `timber dev`. */
|
|
4
4
|
export const DEFAULT_PORT = 3000;
|
|
5
5
|
|
|
6
6
|
// ── Pure resolution ────────────────────────────────────────────────────
|
|
@@ -18,36 +18,26 @@ export interface ResolvePortInput {
|
|
|
18
18
|
defaultPort?: number;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
export interface ResolvedPortInput {
|
|
22
|
-
/** Port to start binding from. */
|
|
23
|
-
port: number;
|
|
24
|
-
/**
|
|
25
|
-
* `true` if the port came from an explicit user override (config or
|
|
26
|
-
* env). Preview uses this to default to strict port binding.
|
|
27
|
-
*/
|
|
28
|
-
explicit: boolean;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
21
|
/**
|
|
32
22
|
* Pure: compute the starting port from config / env / defaults.
|
|
33
23
|
*
|
|
34
24
|
* Performs no I/O.
|
|
35
25
|
*/
|
|
36
|
-
export function resolveStartPort(input: ResolvePortInput):
|
|
26
|
+
export function resolveStartPort(input: ResolvePortInput): number {
|
|
37
27
|
const defaultPort = input.defaultPort ?? DEFAULT_PORT;
|
|
38
28
|
|
|
39
29
|
// `configPort` wins over `envPort`. This matches Vite's behavior:
|
|
40
30
|
// `vite --port 4000` overrides `PORT=5000` in the environment.
|
|
41
31
|
if (typeof input.configPort === 'number' && Number.isFinite(input.configPort)) {
|
|
42
|
-
return
|
|
32
|
+
return input.configPort;
|
|
43
33
|
}
|
|
44
34
|
|
|
45
35
|
if (input.envPort != null && input.envPort !== '') {
|
|
46
36
|
const parsed = Number(input.envPort);
|
|
47
37
|
if (Number.isFinite(parsed) && parsed > 0) {
|
|
48
|
-
return
|
|
38
|
+
return parsed;
|
|
49
39
|
}
|
|
50
40
|
}
|
|
51
41
|
|
|
52
|
-
return
|
|
42
|
+
return defaultPort;
|
|
53
43
|
}
|
|
@@ -186,7 +186,7 @@ for (const [baseName, convention] of Object.entries(METADATA_ROUTE_CONVENTIONS))
|
|
|
186
186
|
export function createMetadataRouteMatcher(
|
|
187
187
|
manifest: ManifestRoot
|
|
188
188
|
): (pathname: string) => MetadataRouteMatch | null {
|
|
189
|
-
return (pathname: string) =>
|
|
189
|
+
return (pathname: string) => matchMetadataRoute(manifest.root, pathname);
|
|
190
190
|
}
|
|
191
191
|
|
|
192
192
|
/**
|
|
@@ -195,7 +195,7 @@ export function createMetadataRouteMatcher(
|
|
|
195
195
|
* Checks if the last URL part is a known metadata route serve path,
|
|
196
196
|
* then walks the tree to find the segment that owns the route.
|
|
197
197
|
*/
|
|
198
|
-
function
|
|
198
|
+
export function matchMetadataRoute(
|
|
199
199
|
root: ManifestSegmentNode,
|
|
200
200
|
pathname: string
|
|
201
201
|
): MetadataRouteMatch | null {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-dep-entries-DyDqXOF9.js","names":[],"sources":["../../src/plugins/client-dep-entries.ts"],"sourcesContent":["/**\n * client-dep-entries — seed the client dep optimizer's startup scan with\n * the app's `'use client'` modules.\n *\n * Vite's dev optimizer discovers bare imports by crawling from its\n * entries before the first request. With no `optimizeDeps.entries`, the\n * client environment crawls its build input — timber's browser entry —\n * and nothing more: every `'use client'` module is reached only through\n * the RSC payload at runtime, never through a static import the crawl\n * can follow. A package imported only from client components is then\n * found on the first browser request, re-optimized mid-load, and the\n * page full-reloads (\"optimized dependencies changed. reloading\"). That\n * reload can leave react and react-dom from two optimizer runs in the\n * browser (duplicate React → \"Invalid hook call\").\n *\n * Listing the `'use client'` files as entries lets the startup crawl see\n * those imports. Setting `entries` replaces the build-input default, so\n * the browser entry is listed too. Files that gain the directive after\n * startup still fall back to Vite's late discovery.\n *\n * Design docs: 21-dev-server.md §\"Client Dependency Pre-Bundling\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { sep } from 'node:path';\nimport { detectDirective, PARSEABLE_EXTENSIONS } from '../analyze/classify.ts';\nimport { normalizeSlashes, scanProjectSourceFiles } from '../analyze/scan.ts';\n\n/**\n * Every project source file under `root` whose directive prologue holds\n * `'use client'`. Uses the same walker as `timber graph` (node_modules,\n * root-level dot dirs and build outputs skipped) and the same AST\n * directive check the RSC plugin applies. Files under `excludeDir` (the\n * build output) are skipped.\n */\nexport async function findUseClientFiles(root: string, excludeDir?: string): Promise<string[]> {\n const files: string[] = [];\n // An unreadable directory only means its client deps are discovered\n // late, through Vite's normal fallback — never fatal for dev startup.\n await scanProjectSourceFiles(root, files, () => {}, 0, PARSEABLE_EXTENSIONS);\n const excludePrefix = excludeDir ? excludeDir + sep : undefined;\n const candidates = excludePrefix ? files.filter((f) => !f.startsWith(excludePrefix)) : files;\n\n const matches = await Promise.all(\n candidates.map(async (file) => {\n const code = await readFile(file, 'utf8').catch(() => null);\n // Cheap text gate before parsing: a directive is a literal\n // without escapes, so a file lacking the text cannot carry it.\n if (code === null || !code.includes('use client')) return null;\n return detectDirective(code, file) === 'use client' ? file : null;\n })\n );\n return matches.filter((file): file is string => file !== null);\n}\n\n/**\n * Escape a path for use as an `optimizeDeps.entries` pattern. Vite globs\n * entries, and route directories are full of glob syntax: `(group)`,\n * `[slug]`, `[[...catchAll]]`, `@slot`. Slashes are normalized first, so\n * the only backslashes left are literal (POSIX) ones, which are escaped\n * too.\n */\nexport function escapeGlobPath(path: string): string {\n return normalizeSlashes(path).replace(/[\\\\()[\\]{}*?|!+@]/g, '\\\\$&');\n}\n\n/**\n * The client environment's `optimizeDeps.entries`: timber's browser\n * entry plus every `'use client'` file in the project.\n */\nexport async function clientOptimizeDepsEntries(\n root: string,\n browserEntryFile: string,\n buildDir: string\n): Promise<string[]> {\n const clientFiles = await findUseClientFiles(root, buildDir);\n return [browserEntryFile, ...clientFiles].map(escapeGlobPath);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,mBAAmB,MAAc,YAAwC;CAC7F,MAAM,QAAkB,CAAC;CAGzB,MAAM,uBAAuB,MAAM,aAAa,CAAC,GAAG,GAAG,oBAAoB;CAC3E,MAAM,gBAAgB,aAAa,aAAa,MAAM,KAAA;CACtD,MAAM,aAAa,gBAAgB,MAAM,QAAQ,MAAM,CAAC,EAAE,WAAW,aAAa,CAAC,IAAI;CAWvF,QAAO,MATe,QAAQ,IAC5B,WAAW,IAAI,OAAO,SAAS;EAC7B,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM,CAAC,CAAC,YAAY,IAAI;EAG1D,IAAI,SAAS,QAAQ,CAAC,KAAK,SAAS,YAAY,GAAG,OAAO;EAC1D,OAAO,gBAAgB,MAAM,IAAI,MAAM,eAAe,OAAO;CAC/D,CAAC,CACH,EAAA,CACe,QAAQ,SAAyB,SAAS,IAAI;AAC/D;;;;;;;;AASA,SAAgB,eAAe,MAAsB;CACnD,OAAO,iBAAiB,IAAI,CAAC,CAAC,QAAQ,sBAAsB,MAAM;AACpE;;;;;AAMA,eAAsB,0BACpB,MACA,kBACA,UACmB;CAEnB,OAAO,CAAC,kBAAkB,GAAG,MADH,mBAAmB,MAAM,QAAQ,CACnB,CAAC,CAAC,IAAI,cAAc;AAC9D"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"metadata-routes-DSDjM_hJ.js","names":[],"sources":["../../src/server/metadata-routes.ts"],"sourcesContent":["/**\n * Metadata route classification for timber.js.\n *\n * Metadata routes are file-based endpoints that generate well-known URLs for\n * crawlers and browsers (sitemap.xml, robots.txt, OG images, etc.).\n *\n * These routes run through proxy.ts but NOT through middleware.ts or access.ts —\n * they are public endpoints by nature.\n *\n * See design/16-metadata.md §\"Metadata Routes\"\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { HeadElement } from './metadata.ts';\nimport type { Metadata } from './types.ts';\nimport type { ManifestSegmentNode } from './route-matcher.ts';\nimport { extractUrlParts } from './chain-url-parts.ts';\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Classification of a metadata route file. */\nexport interface MetadataRouteInfo {\n /** The metadata route type. */\n type: MetadataRouteType;\n /** The content type to serve this route with. */\n contentType: string;\n /** Whether this route can appear in nested segments (not just app root). */\n nestable: boolean;\n}\n\nexport type MetadataRouteType =\n | 'sitemap'\n | 'robots'\n | 'manifest'\n | 'favicon'\n | 'icon'\n | 'opengraph-image'\n | 'apple-icon';\n\n// ─── Convention Table ────────────────────────────────────────────────────────\n\n/**\n * All recognized metadata route file conventions.\n *\n * Each entry maps a base file name (without extension) to its route info.\n * The extensions determine whether the file is static or dynamic.\n *\n * Static extensions: .xml, .txt, .json, .png, .jpg, .ico, .svg\n * Dynamic extensions: .ts, .tsx\n */\nexport const METADATA_ROUTE_CONVENTIONS: Record<\n string,\n {\n type: MetadataRouteType;\n contentType: string;\n nestable: boolean;\n staticExtensions: string[];\n dynamicExtensions: string[];\n /**\n * The URL path basename this file serves at (relative to segment).\n * For image routes, the full serve path includes an extension via\n * `resolveServePathForFile()`.\n */\n servePath: string;\n /**\n * When set, image routes append `.{serveExtension}` to the serve path.\n * Dynamic handlers (`.ts`/`.tsx`) use this as the default. Static files\n * use their own extension instead. Non-image routes leave this undefined.\n */\n serveExtension?: string;\n }\n> = {\n 'sitemap': {\n type: 'sitemap',\n contentType: 'application/xml',\n nestable: true,\n staticExtensions: ['xml'],\n dynamicExtensions: ['ts'],\n servePath: 'sitemap.xml',\n },\n 'robots': {\n type: 'robots',\n contentType: 'text/plain',\n nestable: false,\n staticExtensions: ['txt'],\n dynamicExtensions: ['ts'],\n servePath: 'robots.txt',\n },\n 'manifest': {\n type: 'manifest',\n contentType: 'application/manifest+json',\n nestable: false,\n staticExtensions: ['json'],\n dynamicExtensions: ['ts'],\n servePath: 'manifest.webmanifest',\n },\n 'favicon': {\n type: 'favicon',\n contentType: 'image/x-icon',\n nestable: false,\n staticExtensions: ['ico'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'favicon.ico',\n },\n 'icon': {\n type: 'icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg', 'svg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'icon',\n serveExtension: 'png',\n },\n 'opengraph-image': {\n type: 'opengraph-image',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'opengraph-image',\n serveExtension: 'png',\n },\n\n 'apple-icon': {\n type: 'apple-icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'apple-icon',\n serveExtension: 'png',\n },\n};\n\n// ─── MIME Type Resolution ─────────────────────────────────────────────────────\n\n/**\n * Map of file extensions to MIME types for static metadata route files.\n * Used to resolve the generic `image/*` content type for static image files.\n */\nconst EXTENSION_MIME_TYPES: Record<string, string> = {\n xml: 'application/xml',\n txt: 'text/plain',\n json: 'application/json',\n ico: 'image/x-icon',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n svg: 'image/svg+xml',\n webp: 'image/webp',\n};\n\n/**\n * Resolve the concrete MIME type for a static metadata route file.\n *\n * For generic content types like `image/*`, this resolves to the actual\n * MIME type based on the file extension (e.g. `image/png` for `.png`).\n *\n * @param conventionContentType - The content type from the convention table (may be generic like `image/*`)\n * @param extension - The file extension without leading dot (e.g. \"png\", \"xml\")\n * @returns The resolved MIME type\n */\nexport function resolveStaticContentType(conventionContentType: string, extension: string): string {\n if (conventionContentType.includes('*')) {\n return EXTENSION_MIME_TYPES[extension] ?? 'application/octet-stream';\n }\n return conventionContentType;\n}\n\n/**\n * Check if a file extension represents a static (non-code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"xml\", \"png\", \"ts\")\n * @returns true if this is a static file, false if dynamic or unrecognized\n */\nexport function isStaticMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.staticExtensions.includes(extension);\n}\n\n/**\n * Check if a file extension represents a dynamic (code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"ts\", \"tsx\")\n * @returns true if this is a dynamic file, false if static or unrecognized\n */\nexport function isDynamicMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.dynamicExtensions.includes(extension);\n}\n\n// ─── Classification ──────────────────────────────────────────────────────────\n\n/**\n * Classify a file name as a metadata route, or return null if it's not one.\n *\n * @param fileName - The full file name including extension (e.g. \"sitemap.xml\", \"icon.tsx\")\n * @returns Classification info, or null if not a metadata route\n */\nexport function classifyMetadataRoute(fileName: string): MetadataRouteInfo | null {\n const dotIndex = fileName.lastIndexOf('.');\n if (dotIndex === -1) return null;\n\n const baseName = fileName.slice(0, dotIndex);\n const ext = fileName.slice(dotIndex + 1);\n\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return null;\n\n const isStatic = convention.staticExtensions.includes(ext);\n const isDynamic = convention.dynamicExtensions.includes(ext);\n\n if (!isStatic && !isDynamic) return null;\n\n return {\n type: convention.type,\n contentType: convention.contentType,\n nestable: convention.nestable,\n };\n}\n\n/**\n * Resolve the serve path for a metadata route file.\n *\n * For image routes (icon, opengraph-image, apple-icon), the serve path includes\n * a file extension so CDNs cache correctly:\n * - Dynamic handlers (.ts/.tsx) use the convention's `serveExtension` (default: .png)\n * - Static files use their own extension (e.g., icon.svg → icon.svg)\n *\n * Non-image routes return the convention's `servePath` as-is (already includes\n * extension: sitemap.xml, robots.txt, etc.).\n */\nexport function resolveServePathForFile(baseName: string, filePath: string): string {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return baseName;\n\n if (!convention.serveExtension) return convention.servePath;\n\n const ext = filePath.slice(filePath.lastIndexOf('.') + 1);\n if (convention.staticExtensions.includes(ext)) {\n return `${convention.servePath}.${ext}`;\n }\n return `${convention.servePath}.${convention.serveExtension}`;\n}\n\n/**\n * Get the default serve path for a metadata route type (using default extension\n * for image routes). Used for auto-link generation when only the type is known.\n */\nexport function getMetadataRouteServePath(type: MetadataRouteType): string {\n for (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.type === type) {\n if (convention.serveExtension) {\n return `${convention.servePath}.${convention.serveExtension}`;\n }\n return convention.servePath;\n }\n }\n throw new Error(`[timber] Unknown metadata route type: ${type}`);\n}\n\n/**\n * All possible serve path segments for metadata routes (includes extension\n * variants for image routes).\n */\nconst METADATA_SERVE_PATHS = new Set<string>();\nfor (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.serveExtension) {\n for (const ext of [...convention.staticExtensions, convention.serveExtension]) {\n METADATA_SERVE_PATHS.add(`${convention.servePath}.${ext}`);\n }\n } else {\n METADATA_SERVE_PATHS.add(convention.servePath);\n }\n}\n\nexport function isMetadataRouteServePath(pathname: string): boolean {\n let lastSegment = pathname.slice(pathname.lastIndexOf('/') + 1);\n const qIdx = lastSegment.indexOf('?');\n let query = '';\n if (qIdx !== -1) {\n query = lastSegment.slice(qIdx + 1);\n lastSegment = lastSegment.slice(0, qIdx);\n }\n if (!METADATA_SERVE_PATHS.has(lastSegment)) return false;\n // Vite module requests (e.g., /src/icon.svg?import) use special query params.\n // These are source assets, not metadata routes.\n if (/(?:^|&)(?:import|url|raw|worker|inline)(?:&|$)/.test(query)) return false;\n return true;\n}\n\n/** A <link> auto-link tag. */\nexport interface AutoLinkLink {\n tag: 'link';\n rel: string;\n href: string;\n type?: string;\n}\n\n/** A <meta> auto-link tag. */\nexport interface AutoLinkMeta {\n tag: 'meta';\n property?: string;\n name?: string;\n content: string;\n}\n\nexport type AutoLinkTag = AutoLinkLink | AutoLinkMeta;\n\n/**\n * Get the auto-link tags to inject into <head> for metadata route files\n * discovered in a segment.\n *\n * Returns link tags for icon/apple-icon/manifest, and meta tags for\n * opengraph-image (emits both og:image and twitter:image). Returns null\n * for types that don't auto-link (favicon, sitemap, robots).\n *\n * @param type - The metadata route type\n * @param href - The resolved URL path to the metadata route\n * @returns Tag descriptor(s) for the <head>, or null if no auto-link\n */\nexport function getMetadataRouteAutoLink(type: MetadataRouteType, href: string): AutoLinkTag[] {\n switch (type) {\n case 'icon':\n return [{ tag: 'link', rel: 'icon', href }];\n case 'apple-icon':\n return [{ tag: 'link', rel: 'apple-touch-icon', href }];\n case 'manifest':\n return [{ tag: 'link', rel: 'manifest', href }];\n case 'opengraph-image':\n return [\n { tag: 'meta', property: 'og:image', content: href },\n { tag: 'meta', name: 'twitter:image', content: href },\n ];\n default:\n return [];\n }\n}\n\n// ─── Auto-Linking ──────────────────────────────────────────────────────────\n\n// In dev mode, use a per-startup nonce for metadata route cache busting\n// instead of per-file content hashes (avoids rehashing on every request).\nlet _devNonce: string | undefined;\nfunction getDevNonce(): string {\n _devNonce ??= randomUUID().slice(0, 8);\n return _devNonce;\n}\n\n/**\n * Collect auto-linked head elements from metadata route files in the segment chain.\n *\n * Walks each segment's metadataRoutes, resolves serve paths and URLs, and\n * emits HeadElement descriptors for <link> and <meta> tags that React Float\n * hoists into <head>.\n *\n * A metadata file is served under the URL of the segment that owns it, not\n * under every descendant URL: a root `app/icon.tsx` rendered on `/map` links\n * `/icon.png`, and `app/posts/[id]/opengraph-image.tsx` on `/posts/42/comments`\n * links `/posts/42/opengraph-image.png`. The owner's prefix is the URL parts\n * the chain has consumed through that segment (`extractUrlParts`, the same\n * walk slot matching uses), filled with the request's raw param values — the\n * parts the metadata route matcher walks back to the same owner.\n *\n * Segments at or below an intercepting segment are skipped: the metadata\n * matcher only walks the canonical tree, so nothing serves their files.\n *\n * See design/16-metadata.md §\"Auto-Linking\"\n */\nexport function collectMetadataRouteHeadElements(\n segments: ManifestSegmentNode[],\n firstDeniedIndex: number,\n resolvedMetadata: Metadata,\n requestUrl: URL,\n rawSegmentParams: Record<string, string | string[]>,\n metadataRouteHashes?: Record<string, string>\n): HeadElement[] {\n const elements: HeadElement[] = [];\n const hasUserOgImage = Boolean(resolvedMetadata.openGraph?.images);\n const hasUserTwitterImage = Boolean(resolvedMetadata.twitter?.images);\n // In dev mode, use the request origin so OG URLs resolve to localhost.\n // In production, use metadataBase (the canonical domain).\n const ogBase =\n process.env.NODE_ENV !== 'production'\n ? new URL(requestUrl.origin)\n : resolvedMetadata.metadataBase;\n\n const interceptingIndex = segments.findIndex((s) => s.segmentType === 'intercepting');\n const servedDepth = interceptingIndex === -1 ? segments.length : interceptingIndex;\n\n for (let si = 0; si < servedDepth; si++) {\n const segment = segments[si];\n if (!segment.metadataRoutes) continue;\n if (si >= firstDeniedIndex) continue;\n // Params are canonical (decoded) values; encode each part so the href\n // canonicalizes back to the pathname the matcher resolves to this owner.\n const segmentPrefix = extractUrlParts(segments.slice(0, si + 1), rawSegmentParams)\n .map((part) => `/${encodeURIComponent(part)}`)\n .join('');\n for (const baseName of Object.keys(segment.metadataRoutes)) {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) continue;\n if (!convention.nestable && segment.urlPath !== '/') continue;\n if (convention.type === 'opengraph-image' && hasUserOgImage) continue;\n const metaFile = segment.metadataRoutes[baseName];\n const fileServePath = metaFile?.filePath\n ? resolveServePathForFile(baseName, metaFile.filePath)\n : convention.serveExtension\n ? `${convention.servePath}.${convention.serveExtension}`\n : convention.servePath;\n let href = `${segmentPrefix}/${fileServePath}`;\n if (convention.type === 'opengraph-image') {\n const fileHash = metaFile?.filePath ? metadataRouteHashes?.[metaFile.filePath] : undefined;\n const cacheBust = fileHash ?? getDevNonce();\n href = `${href}?${cacheBust}`;\n }\n if (ogBase && convention.type === 'opengraph-image') {\n href = new URL(href, ogBase).toString();\n }\n for (const autoLink of getMetadataRouteAutoLink(convention.type, href)) {\n if (\n hasUserTwitterImage &&\n autoLink.tag === 'meta' &&\n 'name' in autoLink &&\n autoLink.name === 'twitter:image'\n )\n continue;\n if (autoLink.tag === 'link') {\n const attrs: Record<string, string> = { rel: autoLink.rel, href: autoLink.href };\n if (autoLink.type) attrs.type = autoLink.type;\n elements.push({ tag: 'link', attrs });\n } else {\n const attrs: Record<string, string> = { content: autoLink.content };\n if (autoLink.property) attrs.property = autoLink.property;\n if (autoLink.name) attrs.name = autoLink.name;\n elements.push({ tag: 'meta', attrs });\n }\n }\n }\n }\n return elements;\n}\n"],"mappings":"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"}
|