@krate/runtime 0.5.0-rc.17 → 0.5.0-rc.19

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.
@@ -99,8 +99,17 @@ export interface RobotsObject {
99
99
  noimageindex?: boolean;
100
100
  nocache?: boolean;
101
101
  notranslate?: boolean;
102
+ indexifembedded?: boolean;
103
+ nositelinksearchbox?: boolean;
104
+ unavailable_after?: string;
105
+ 'max-snippet'?: number;
106
+ 'max-image-preview'?: 'none' | 'standard' | 'large';
107
+ 'max-video-preview'?: number | string;
108
+ /** @deprecated Use 'max-snippet'. */
102
109
  maxSnippet?: number;
110
+ /** @deprecated Use 'max-image-preview'. */
103
111
  maxImagePreview?: 'none' | 'standard' | 'large';
112
+ /** @deprecated Use 'max-video-preview'. */
104
113
  maxVideoPreview?: number | string;
105
114
  googleBot?: string | RobotsObject;
106
115
  }
@@ -169,6 +178,8 @@ export type ResolvingViewport = Promise<Viewport>;
169
178
  export interface MetadataProps {
170
179
  params?: unknown;
171
180
  searchParams?: unknown;
181
+ /** The page's URL path (without query), which "./" URLs in the metadata resolve against. */
182
+ pathname?: string;
172
183
  }
173
184
  /** The resolved metadata of the parent segments, as generateMetadata's second argument. */
174
185
  export type ResolvingMetadata = Promise<Metadata>;
@@ -213,7 +224,7 @@ export declare function resolveMetadata(segments: MetadataSegment[], rawProps: M
213
224
  export declare function renderMetadataTags(md: Metadata, templates?: {
214
225
  openGraph?: string;
215
226
  twitter?: string;
216
- }): string;
227
+ }, pathname?: string): string;
217
228
  /**
218
229
  * The head markup of a chain for these props, or "" when the chain exports no
219
230
  * metadata. Errors from generateMetadata are logged and the segment skipped.
package/dist/metadata.js CHANGED
@@ -171,11 +171,29 @@ function toArray(v) {
171
171
  return [];
172
172
  return Array.isArray(v) ? v : [v];
173
173
  }
174
+ /** Resolves a "./..." URL against a page path, like path.posix.resolve(pathname, url). */
175
+ function joinPathname(pathname, rel) {
176
+ const out = [];
177
+ for (const seg of ((pathname || '/').split('?')[0].split('#')[0] + '/' + rel).split('/')) {
178
+ if (seg === '' || seg === '.')
179
+ continue;
180
+ if (seg === '..')
181
+ out.pop();
182
+ else
183
+ out.push(seg);
184
+ }
185
+ return '/' + out.join('/');
186
+ }
174
187
  /** Resolves a URL field against metadataBase (its path is a prefix). Absolute URLs stay as they are. */
175
- function resolveBaseJoin(value, base) {
188
+ function resolveBaseJoin(value, ctx) {
176
189
  if (value === null || value === undefined || value === '')
177
190
  return '';
178
- const s = String(value);
191
+ let s = String(value);
192
+ const base = ctx.base;
193
+ // As in Next.js, "./x" is relative to the page's path: on /blog/post,
194
+ // "./" is /blog/post and "./x" is /blog/post/x.
195
+ if (s.startsWith('./'))
196
+ s = joinPathname(ctx.pathname, s);
179
197
  if (!base || /^[a-z][a-z0-9+.-]*:/i.test(s) || s.startsWith('//'))
180
198
  return s;
181
199
  try {
@@ -220,28 +238,48 @@ function viewportString(v) {
220
238
  add('interactive-widget', v.interactiveWidget);
221
239
  return parts.join(', ');
222
240
  }
241
+ // Robots directives after index and follow, in the order Next.js prints them.
242
+ const ROBOTS_KEYS = [
243
+ 'noarchive',
244
+ 'nosnippet',
245
+ 'noimageindex',
246
+ 'nocache',
247
+ 'notranslate',
248
+ 'indexifembedded',
249
+ 'nositelinksearchbox',
250
+ 'unavailable_after',
251
+ 'max-video-preview',
252
+ 'max-image-preview',
253
+ 'max-snippet',
254
+ ];
255
+ // The camelCase spellings Krate accepted before the Next.js ones.
256
+ const ROBOTS_ALIASES = {
257
+ maxSnippet: 'max-snippet',
258
+ maxImagePreview: 'max-image-preview',
259
+ maxVideoPreview: 'max-video-preview',
260
+ };
223
261
  function robotsString(r) {
224
262
  if (typeof r === 'string')
225
263
  return r;
264
+ const o = { ...r };
265
+ for (const [alias, key] of Object.entries(ROBOTS_ALIASES))
266
+ if (o[key] === undefined && o[alias] !== undefined)
267
+ o[key] = o[alias];
226
268
  const out = [];
227
- out.push(r.index === false ? 'noindex' : 'index');
228
- out.push(r.follow === false ? 'nofollow' : 'follow');
229
- if (r.noarchive)
230
- out.push('noarchive');
231
- if (r.nosnippet)
232
- out.push('nosnippet');
233
- if (r.noimageindex)
234
- out.push('noimageindex');
235
- if (r.nocache)
236
- out.push('nocache');
237
- if (r.notranslate)
238
- out.push('notranslate');
239
- if (r.maxSnippet !== undefined)
240
- out.push(`max-snippet:${r.maxSnippet}`);
241
- if (r.maxImagePreview !== undefined)
242
- out.push(`max-image-preview:${r.maxImagePreview}`);
243
- if (r.maxVideoPreview !== undefined)
244
- out.push(`max-video-preview:${r.maxVideoPreview}`);
269
+ if (o.index)
270
+ out.push('index');
271
+ else if (typeof o.index === 'boolean')
272
+ out.push('noindex');
273
+ if (o.follow)
274
+ out.push('follow');
275
+ else if (typeof o.follow === 'boolean')
276
+ out.push('nofollow');
277
+ for (const key of ROBOTS_KEYS) {
278
+ const v = o[key];
279
+ if (v === undefined || v === null || v === false)
280
+ continue;
281
+ out.push(typeof v === 'boolean' ? key : `${key}:${v}`);
282
+ }
245
283
  return out.join(', ');
246
284
  }
247
285
  function imageList(images, base) {
@@ -261,8 +299,8 @@ function titleOf(t, template) {
261
299
  return t.absolute !== undefined ? t.absolute : t.default || '';
262
300
  }
263
301
  /** The <head> tags for resolved metadata, one per line. */
264
- export function renderMetadataTags(md, templates = {}) {
265
- const base = md.metadataBase ? String(md.metadataBase) : undefined;
302
+ export function renderMetadataTags(md, templates = {}, pathname) {
303
+ const base = { base: md.metadataBase ? String(md.metadataBase) : undefined, pathname };
266
304
  const tags = [];
267
305
  const push = (t) => {
268
306
  if (t)
@@ -474,7 +512,7 @@ export async function metadataHeadTags(segments, props, log) {
474
512
  const { metadata, templates, errors } = await resolveMetadata(segments, props);
475
513
  for (const e of errors)
476
514
  (log || defaultLog)(`generateMetadata${e.file ? ` in ${e.file}` : ''} failed; the page renders without its metadata`, e.error);
477
- return renderMetadataTags(metadata, templates);
515
+ return renderMetadataTags(metadata, templates, props.pathname);
478
516
  }
479
517
  function defaultLog(msg, err) {
480
518
  console.error(`[krate] ${msg}:`, err);
@@ -20,6 +20,17 @@ export declare function krateRouteStore(): {
20
20
  subscribe: (cb: () => void) => () => void;
21
21
  getSnapshot: () => RouteSnapshot;
22
22
  };
23
+ /**
24
+ * The current route as plain values (search without the "?"), readable anywhere (not a hook): in an
25
+ * effect, an event handler or outside any component. The object keeps its
26
+ * identity while the URL is unchanged. In Krate-compiled code the read is
27
+ * tracked, so a binding that reads it follows navigation.
28
+ */
29
+ export declare function krateCurrentRoute(): {
30
+ pathname: string;
31
+ search: string;
32
+ params: Record<string, string | string[]>;
33
+ };
23
34
  /** The params a route pattern matches in a pathname (see useParams). */
24
35
  export declare function krateMatchParams(route: string, pathname: string): Record<string, string | string[]>;
25
36
  /** The path segments below depth (see useSelectedLayoutSegments). */
@@ -109,6 +109,27 @@ export function krateRouteStore() {
109
109
  };
110
110
  return { subscribe, getSnapshot };
111
111
  }
112
+ let nowKey = '';
113
+ let nowVal = null;
114
+ /**
115
+ * The current route as plain values (search without the "?"), readable anywhere (not a hook): in an
116
+ * effect, an event handler or outside any component. The object keeps its
117
+ * identity while the URL is unchanged. In Krate-compiled code the read is
118
+ * tracked, so a binding that reads it follows navigation.
119
+ */
120
+ export function krateCurrentRoute() {
121
+ if (getRequestContext()) {
122
+ const params = serverNav.useParams();
123
+ return { pathname: serverNav.usePathname(), search: serverNav.useSearchParams().toString(), params };
124
+ }
125
+ const s = routeState()();
126
+ const key = s.pathname + '\0' + s.search + '\0' + s.route;
127
+ if (!nowVal || key !== nowKey) {
128
+ nowKey = key;
129
+ nowVal = { pathname: s.pathname, search: s.search.replace(/^\?/, ''), params: matchRouteParams(s.route, s.pathname) };
130
+ }
131
+ return nowVal;
132
+ }
112
133
  /** The params a route pattern matches in a pathname (see useParams). */
113
134
  export function krateMatchParams(route, pathname) {
114
135
  return matchRouteParams(route, pathname);
@@ -173,6 +173,13 @@ function build(c, options) {
173
173
  if (vnode.type === 'form' && isPlainAction(p.action)) {
174
174
  const box = { fn: p.action };
175
175
  p.action = undefined;
176
+ // Server render: the form posts to the action without JavaScript.
177
+ const post = box.fn.$$krateFormURL;
178
+ if (typeof post === 'string' && typeof document === 'undefined') {
179
+ p.action = post;
180
+ if (p.method == null)
181
+ p.method = 'post';
182
+ }
176
183
  withRef(vnode, (el) => { el.__krateForm = box; });
177
184
  p.children = createElement(FormScope, { box }, p.children);
178
185
  }
@@ -194,6 +201,27 @@ function build(c, options) {
194
201
  function requestFormReset(form) {
195
202
  form.reset();
196
203
  }
204
+ // A dispatch wrapping a server action also names the endpoint a form posts to
205
+ // without JavaScript, with the initial state as the leading argument (the
206
+ // compat form hook renders it during a server render).
207
+ function markNativePost(dispatch, action, initial, permalink) {
208
+ if (typeof action !== 'function' || typeof action.$$krateAction !== 'string' || typeof action.actionUrl !== 'string')
209
+ return;
210
+ if (Array.isArray(action.$$krateBound) && action.$$krateBound.length > 0)
211
+ return;
212
+ let first = 'null';
213
+ try {
214
+ first = JSON.stringify(initial === undefined ? null : initial) ?? 'null';
215
+ }
216
+ catch {
217
+ first = 'null';
218
+ }
219
+ let target = action.actionUrl + '?__krate_args=' + encodeURIComponent('[' + first + ']');
220
+ if (typeof permalink === 'string' && permalink.startsWith('/') && !permalink.startsWith('//')) {
221
+ target += '&__krate_return=' + encodeURIComponent(permalink);
222
+ }
223
+ Object.defineProperty(dispatch, '$$krateFormURL', { value: target });
224
+ }
197
225
  function useActionState(action, initialState, _permalink) {
198
226
  const [state, setState] = useState(initialState);
199
227
  const [pending, setPending] = useState(false);
@@ -235,6 +263,8 @@ function build(c, options) {
235
263
  }, []);
236
264
  if (failure)
237
265
  throw failure.error;
266
+ if (!dispatch.$$krateFormURL)
267
+ markNativePost(dispatch, action, initialState, _permalink);
238
268
  return [state, dispatch, pending];
239
269
  }
240
270
  function use(usable) {
@@ -12,7 +12,8 @@
12
12
  * `Element`, which React-typed props (`children: ReactNode`) reject.
13
13
  *
14
14
  * Importing this file makes `JSX.Element` also a `React.ReactElement`, so it is
15
- * assignable to `ReactNode` in both setups. Include it once, for example:
15
+ * assignable to `ReactNode` in both setups, and sets `JSX.ElementType` so
16
+ * components that return `ReactNode` are valid JSX tags. Include it once, for example:
16
17
  *
17
18
  * // src/krate-react.d.ts
18
19
  * import "@krate/runtime/react-types";
@@ -20,9 +21,23 @@
20
21
  * It needs @types/react; plain Krate apps should not import it.
21
22
  */
22
23
  declare global {
24
+ namespace Krate {
25
+ // React handlers, refs and HTML props use React's wider types; see jsx-types.
26
+ interface ReactCompat {
27
+ react: true;
28
+ }
29
+ }
30
+
23
31
  namespace JSX {
24
32
  // eslint-disable-next-line @typescript-eslint/no-empty-object-type
25
33
  interface Element extends React.ReactElement<any, any> {}
34
+
35
+ // React components may return any ReactNode (Suspense, icon libraries,
36
+ // Radix); TS 5.1+ reads this to validate a component's return type.
37
+ type ElementType =
38
+ | string
39
+ | ((props: any) => React.ReactNode | Promise<React.ReactNode>)
40
+ | (new (props: any) => React.Component<any, any>);
26
41
  }
27
42
  }
28
43
 
package/dist/server.js CHANGED
@@ -412,6 +412,16 @@ function styleString(value) {
412
412
  }
413
413
  return out.join(";");
414
414
  }
415
+ // The endpoint of a server action. Arguments fixed with .bind() travel sealed
416
+ // in the URL (see action-seal.ts), never in the clear. An inline action's URL
417
+ // already carries its sealed captures in __krate_args.
418
+ function actionEndpoint(action, name) {
419
+ const bound = action.$$krateBound;
420
+ if (!Array.isArray(bound) || bound.length === 0 || typeof action.$$krateAction !== 'string' || action.actionUrl.includes('__krate_args='))
421
+ return action.actionUrl;
422
+ const token = sealBoundArgs(action.$$krateAction, bound, name);
423
+ return action.actionUrl + (action.actionUrl.includes('?') ? '&' : '?') + '__krate_bound=' + encodeURIComponent(token);
424
+ }
415
425
  function setAttr(key, val) {
416
426
  if (key === "children" || key === "key" || key === "ref" || key === "dangerouslySetInnerHTML")
417
427
  return "";
@@ -421,10 +431,10 @@ function setAttr(key, val) {
421
431
  if (val === true)
422
432
  return ` ${name}`;
423
433
  if (name === "action" && isServerAction(val)) {
424
- return ` action="${escapeHTML(val.actionUrl)}" data-krate-action`;
434
+ return ` action="${escapeHTML(actionEndpoint(val, 'action'))}" data-krate-action`;
425
435
  }
426
436
  if (name === "formaction" && isServerAction(val)) {
427
- return ` formaction="${escapeHTML(val.actionUrl)}" formmethod="post" data-krate-action`;
437
+ return ` formaction="${escapeHTML(actionEndpoint(val, 'formAction'))}" formmethod="post" data-krate-action`;
428
438
  }
429
439
  // Client function actions run only after hydration; they have no HTML form.
430
440
  if (typeof val === "function")
@@ -581,6 +591,33 @@ function renderElement(el) {
581
591
  }
582
592
  // HTML element
583
593
  const tag = type;
594
+ if (hoistsHeadTag(tag, props)) {
595
+ const { precedence: _precedence, ...kept } = props;
596
+ return HEAD_OPEN + renderPlainElement({ ...el, props: kept }) + HEAD_CLOSE;
597
+ }
598
+ return renderPlainElement(el);
599
+ }
600
+ // Elements whose content is not part of the document body flow: a <meta> or
601
+ // <link> inside them stays where it is rendered.
602
+ const NON_HEAD_CONTEXT = new Set(["svg", "noscript", "template"]);
603
+ let nonHeadDepth = 0;
604
+ // hoistsHeadTag reports whether a <meta> or <link> rendered in a component
605
+ // belongs in the document head (React 19 metadata hoisting; the compiler does
606
+ // the same for static pages, see irtree.IsHoistableMetadata). The host moves
607
+ // the element between the head markers into <head> of the response.
608
+ function hoistsHeadTag(tag, props) {
609
+ if ((tag !== "meta" && tag !== "link") || nonHeadDepth > 0)
610
+ return false;
611
+ if (props.itemProp !== undefined || props.itemprop !== undefined)
612
+ return false;
613
+ if (tag === "link" && String(props.rel ?? "").toLowerCase().trim() === "stylesheet" && props.precedence === undefined) {
614
+ return false;
615
+ }
616
+ return true;
617
+ }
618
+ function renderPlainElement(el) {
619
+ const { type, props, children } = el;
620
+ const tag = type;
584
621
  const renderProps = tag === "form" && isServerAction(props.action) && props.method == null
585
622
  ? { ...props, method: "post" }
586
623
  : props;
@@ -591,11 +628,21 @@ function renderElement(el) {
591
628
  return `<${tag}${attrs}>`;
592
629
  }
593
630
  const dangerous = props.dangerouslySetInnerHTML;
594
- const inner = dangerous && typeof dangerous === "object" && typeof dangerous.__html === "string"
595
- ? dangerous.__html
596
- : tag === "script" || tag === "style"
597
- ? rawTextContent(tag, children)
598
- : children.map(renderNode).join("");
631
+ const nonHead = NON_HEAD_CONTEXT.has(tag);
632
+ if (nonHead)
633
+ nonHeadDepth++;
634
+ let inner;
635
+ try {
636
+ inner = dangerous && typeof dangerous === "object" && typeof dangerous.__html === "string"
637
+ ? dangerous.__html
638
+ : tag === "script" || tag === "style"
639
+ ? rawTextContent(tag, children)
640
+ : children.map(renderNode).join("");
641
+ }
642
+ finally {
643
+ if (nonHead)
644
+ nonHeadDepth--;
645
+ }
599
646
  return `<${tag}${attrs}>${inner}</${tag}>`;
600
647
  }
601
648
  // Streaming SSR via Suspense
@@ -1121,19 +1168,46 @@ export function Link(props) {
1121
1168
  return raw(`<a ${attrs.join(" ")}>${inner}</a>`);
1122
1169
  }
1123
1170
  Link.__krateEagerChildren = true;
1124
- // Image - renders an <img> tag (server stub; Go compiler handles full responsive output at build time).
1171
+ // Image - renders an <img> tag at request time. The Go compiler lowers an <Image> whose props are
1172
+ // known at build time to a responsive <picture>; a src that only exists at run time cannot be
1173
+ // optimised, so it becomes a plain <img> that keeps every other prop (class, style, data-*, ...).
1174
+ const IMAGE_ONLY_PROPS = new Set([
1175
+ "priority", "quality", "placeholder", "blurDataURL", "loader", "unoptimized", "fill", "layout",
1176
+ "objectFit", "objectPosition", "lazyBoundary", "lazyRoot", "onLoadingComplete", "children",
1177
+ ]);
1125
1178
  export function Image(props) {
1126
- const { src = "", alt = "", width, height } = props;
1127
- const attrs = [];
1128
- if (src)
1129
- attrs.push(`src="${escapeHTML(src)}"`);
1130
- if (alt)
1131
- attrs.push(`alt="${escapeHTML(alt)}"`);
1132
- if (width)
1133
- attrs.push(`width="${width}"`);
1134
- if (height)
1135
- attrs.push(`height="${height}"`);
1136
- return raw(`<img ${attrs.join(" ")} />`);
1179
+ const attrs = {};
1180
+ const { priority } = props;
1181
+ for (const [key, v] of Object.entries(props)) {
1182
+ if (v == null || v === false || typeof v === "function" || IMAGE_ONLY_PROPS.has(key))
1183
+ continue;
1184
+ if (key === "key" || key === "ref" || key === "dangerouslySetInnerHTML" || key.startsWith("on") || key.startsWith("__"))
1185
+ continue;
1186
+ const name = ATTR_ALIASES[key] || key;
1187
+ if (key === "style" && typeof v === "object") {
1188
+ const css = styleString(v);
1189
+ if (css)
1190
+ attrs.style = css;
1191
+ continue;
1192
+ }
1193
+ if (key === "src" && typeof v === "object" && typeof v.src === "string") {
1194
+ attrs.src = v.src;
1195
+ continue;
1196
+ }
1197
+ attrs[name] = v === true ? true : String(v);
1198
+ }
1199
+ if (priority) {
1200
+ if (attrs.fetchpriority === undefined)
1201
+ attrs.fetchpriority = "high";
1202
+ }
1203
+ else {
1204
+ if (attrs.loading === undefined)
1205
+ attrs.loading = "lazy";
1206
+ if (attrs.decoding === undefined)
1207
+ attrs.decoding = "async";
1208
+ }
1209
+ const out = Object.entries(attrs).map(([k, v]) => (v === true ? k : `${k}="${escapeHTML(v)}"`));
1210
+ return raw(`<img ${out.join(" ")} />`);
1137
1211
  }
1138
1212
  // Icon - renders an empty span placeholder (Go compiler handles SVG fetching at build time).
1139
1213
  export function Icon(_props) {
@@ -1146,8 +1220,8 @@ export function Icon(_props) {
1146
1220
  export function SyntaxHighlight(props) {
1147
1221
  const lang = props.lang || "";
1148
1222
  const code = props.children != null ? String(props.children) : "";
1149
- const lines = props.highlight || "";
1150
- const html = lang ? highlightCode(trimSpace(code), lang, lines || undefined) : null;
1223
+ const lines = props.highlight != null ? String(props.highlight) : undefined;
1224
+ const html = lang ? highlightCode(trimSpace(code), lang, lines) : null;
1151
1225
  if (html !== null) {
1152
1226
  const attr = lines ? ` data-highlight-lines="${escapeHTML(lines)}"` : "";
1153
1227
  return raw(`<pre class="chroma"${attr}><code class="language-${escapeHTML(lang)}">${html}</code></pre>`);
package/dist/ssr-core.js CHANGED
@@ -431,6 +431,13 @@ export function createSSRCore(opts) {
431
431
  });
432
432
  return thenable(makeProxy(), makeProxy);
433
433
  }
434
+ // The path of the request without its query, what "./" metadata URLs
435
+ // resolve against. A request with no url has only its route pattern.
436
+ function requestPathname(req) {
437
+ const raw = req.url || req.route || "/";
438
+ const path = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, "") : raw;
439
+ return path.split(/[?#]/)[0] || "/";
440
+ }
434
441
  function buildProps(req, tracker) {
435
442
  // Page-level data fetching (getStaticProps/getServerSideProps) has been
436
443
  // removed; per-request data is provided by server components (@server),
@@ -486,7 +493,7 @@ export function createSSRCore(opts) {
486
493
  // and cache scope: its fetches share the data cache with the
487
494
  // page's, and the tags it declares are recorded on the entry.
488
495
  const [head, body] = await Promise.all([
489
- metadataHeadTags(segments, { params: props.params ?? thenableRecord({}), searchParams: props.searchParams }),
496
+ metadataHeadTags(segments, { params: props.params ?? thenableRecord({}), searchParams: props.searchParams, pathname: requestPathname(req) }),
490
497
  renderToStringAsync(jsx(Component, props)),
491
498
  ]);
492
499
  return head ? HEAD_OPEN + head + HEAD_CLOSE + body : body;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.5.0-rc.17",
3
+ "version": "0.5.0-rc.19",
4
4
  "description": "Client-side runtime for Krate - signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",