@rsc-kit/mcp 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/answers.d.ts +7 -0
  2. package/dist/answers.js +26 -0
  3. package/dist/answers.js.map +1 -1
  4. package/dist/bundleGuides.d.ts +22 -0
  5. package/dist/bundleGuides.js +130 -0
  6. package/dist/bundleGuides.js.map +1 -0
  7. package/dist/index.js +21 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/recipes.js +81 -6
  10. package/dist/recipes.js.map +1 -1
  11. package/dist/report.d.ts +11 -0
  12. package/dist/report.js +1 -1
  13. package/dist/report.js.map +1 -1
  14. package/guides/api-routes.md +168 -0
  15. package/guides/authorization.md +288 -0
  16. package/guides/caching.md +57 -0
  17. package/guides/connection.md +98 -0
  18. package/guides/edge-caching.md +159 -0
  19. package/guides/errors.md +109 -0
  20. package/guides/file-uploads.md +119 -0
  21. package/guides/fonts.md +117 -0
  22. package/guides/forms.md +528 -0
  23. package/guides/images.md +83 -0
  24. package/guides/index.json +162 -0
  25. package/guides/mcp.md +113 -0
  26. package/guides/metadata.md +289 -0
  27. package/guides/navigation.md +84 -0
  28. package/guides/no-javascript.md +39 -0
  29. package/guides/offline.md +215 -0
  30. package/guides/ppr.md +181 -0
  31. package/guides/pwa.md +260 -0
  32. package/guides/queries.md +340 -0
  33. package/guides/react-compiler.md +153 -0
  34. package/guides/redirects.md +143 -0
  35. package/guides/response-headers.md +66 -0
  36. package/guides/route-interception.md +206 -0
  37. package/guides/routing.md +458 -0
  38. package/guides/sections.md +74 -0
  39. package/guides/server-actions.md +444 -0
  40. package/guides/static-generation.md +347 -0
  41. package/guides/testing.md +158 -0
  42. package/guides/third-party-scripts.md +105 -0
  43. package/guides/typed-routes.md +139 -0
  44. package/guides/url-validation.md +143 -0
  45. package/guides/validation.md +175 -0
  46. package/guides/view-transitions.md +120 -0
  47. package/package.json +4 -3
package/dist/answers.d.ts CHANGED
@@ -19,3 +19,10 @@ export declare function explainRoute(report: BuildReport, url: string, builtAt:
19
19
  export declare function whatIsDynamic(report: BuildReport, builtAt: Date, now: number): string;
20
20
  /** The heaviest routes, for the question that follows the size column. */
21
21
  export declare function heaviestRoutes(report: BuildReport, builtAt: Date, now: number, top?: number): string;
22
+ /**
23
+ * The actions, and the one fact about each that nothing else states: whether
24
+ * anything checks who calls it. A bare "use server" export runs with no
25
+ * middleware; an agent adding a delete button needs to know that before it
26
+ * trusts the id it was handed.
27
+ */
28
+ export declare function actionLines(report: BuildReport): string[];
package/dist/answers.js CHANGED
@@ -33,6 +33,11 @@ export function listRoutes(report, builtAt, now) {
33
33
  `${report.routes.length} routes and ${report.apis.length} api routes ${asOf(builtAt, now)}`,
34
34
  '',
35
35
  ];
36
+ // First, before the table, because it changes what the table means: these
37
+ // rows are from a build that did not finish, and nothing below is deployed.
38
+ if (report.totals.failed > 0) {
39
+ lines.unshift(`THE LAST BUILD FAILED: ${report.totals.failed} route${report.totals.failed === 1 ? '' : 's'} refused. Each one's line below says what to change. Fix it and build again.`, '');
40
+ }
36
41
  for (const route of report.routes) {
37
42
  const size = route.clientJs === null ? '' : ` ${kb(route.clientJs)}`;
38
43
  lines.push(`${route.url}${size} — ${MEANING[route.type] ?? route.type}`);
@@ -49,6 +54,7 @@ export function listRoutes(report, builtAt, now) {
49
54
  }
50
55
  lines.push('', `${report.totals.static} static, ${report.totals.partial} partial prerender, ${report.totals.dynamic} dynamic` +
51
56
  (report.totals.failed ? `, ${report.totals.failed} failed` : ''));
57
+ lines.push('', ...actionLines(report));
52
58
  return lines.join('\n');
53
59
  }
54
60
  function isPage(route) {
@@ -121,4 +127,24 @@ export function heaviestRoutes(report, builtAt, now, top = 10) {
121
127
  'which every route pays for.',
122
128
  ].join('\n');
123
129
  }
130
+ /**
131
+ * The actions, and the one fact about each that nothing else states: whether
132
+ * anything checks who calls it. A bare "use server" export runs with no
133
+ * middleware; an agent adding a delete button needs to know that before it
134
+ * trusts the id it was handed.
135
+ */
136
+ export function actionLines(report) {
137
+ const actions = report.actions;
138
+ if (!actions)
139
+ return ['actions: not audited by this build (older @rsc-kit/core)'];
140
+ if (actions.length === 0)
141
+ return ['actions: none'];
142
+ const bare = actions.filter((a) => !a.client);
143
+ const lines = [`actions: ${actions.length}, ${actions.length - bare.length} built from an action client`];
144
+ if (bare.length > 0) {
145
+ lines.push(`${bare.length} run NO middleware — nothing checks who calls them: ` +
146
+ bare.map((a) => `${a.name}${a.query ? ' (query)' : ''} in ${a.file}`).join(', '), 'Fine for a public action. For anything else, build it from an action client so the check cannot be forgotten — how_to({ topic: "action-client" }).');
147
+ }
148
+ return lines;
149
+ }
124
150
  //# sourceMappingURL=answers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"answers.js","sourceRoot":"","sources":["../src/answers.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,6EAA6E;AAC7E,4EAA4E;AAC5E,yBAAyB;AAGzB,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE/C,MAAM,EAAE,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,GAAG,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAA;AAE3G,MAAM,GAAG,GAAG,CAAC,OAAa,EAAE,GAAW,EAAU,EAAE;IACjD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,GAAG,MAAM,CAAC,CAAA;IAE9D,IAAI,OAAO,GAAG,CAAC;QAAE,OAAO,UAAU,CAAA;IAClC,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,OAAO,UAAU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AAC,CAAC,QAAQ,KAAK,IAAI,CAAC;SAClC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,CAAC,CAAA;IAExD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,0CAA0C,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,GAAG,CAAA;IACxE,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAA;IAE1D,OAAO;QACL,mBAAmB,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,GAAG;QACxC,EAAE;QACF,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC;QACvE,EAAE;QACF,4BAA4B,EAAE,CAAC,QAAQ,CAAC,qCAAqC;QAC7E,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,2DAA2D;QACvG,6BAA6B;KAC9B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AACd,CAAC","sourcesContent":["// The answers, as text, with no protocol in them.\n//\n// Separated from the server so they can be tested by calling them, and so the\n// wording is reviewable in one place. An agent reads these as prose and acts on\n// them, so a vague sentence here becomes a wrong edit somewhere else — \"this\n// route is dynamic\" invites a fix, \"this route reads cookies, which is why\"\n// invites the right one.\n\nimport type { BuildReport, ReportedApiRoute, ReportedRoute } from './report.js'\nimport { MEANING, routeFor } from './report.js'\n\nconst kb = (bytes: number) => `${bytes < 10_000 ? (bytes / 1000).toFixed(1) : Math.round(bytes / 1000)} kB`\n\nconst age = (builtAt: Date, now: number): string => {\n const minutes = Math.round((now - builtAt.getTime()) / 60_000)\n\n if (minutes < 1) return 'just now'\n if (minutes < 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`\n\n const hours = Math.round(minutes / 60)\n\n if (hours < 24) return `${hours} hour${hours === 1 ? '' : 's'} ago`\n\n return `${Math.round(hours / 24)} days ago`\n}\n\n/**\n * Every answer says how old it is.\n *\n * The one way this server misleads is by being confidently stale: it reports\n * the last build, and the file on disk may have changed since. Saying so on\n * every answer is cheaper than being wrong once.\n */\nexport function asOf(builtAt: Date, now: number): string {\n return `(from the last build, ${age(builtAt, now)})`\n}\n\nexport function listRoutes(report: BuildReport, builtAt: Date, now: number): string {\n const lines = [\n `${report.routes.length} routes and ${report.apis.length} api routes ${asOf(builtAt, now)}`,\n '',\n ]\n\n for (const route of report.routes) {\n const size = route.clientJs === null ? '' : ` ${kb(route.clientJs)}`\n\n lines.push(`${route.url}${size} — ${MEANING[route.type] ?? route.type}`)\n\n if (route.reason) lines.push(` ${route.reason}`)\n }\n\n if (report.apis.length) {\n lines.push('', 'api routes:')\n\n for (const api of report.apis) {\n lines.push(`${api.url} — ${MEANING[api.type] ?? api.type}`)\n\n if (api.reason) lines.push(` ${api.reason}`)\n }\n }\n\n lines.push(\n '',\n `${report.totals.static} static, ${report.totals.partial} partial prerender, ${report.totals.dynamic} dynamic` +\n (report.totals.failed ? `, ${report.totals.failed} failed` : ''),\n )\n\n return lines.join('\\n')\n}\n\nfunction isPage(route: ReportedRoute | ReportedApiRoute): route is ReportedRoute {\n return 'component' in route\n}\n\nexport function explainRoute(\n report: BuildReport,\n url: string,\n builtAt: Date,\n now: number,\n): string {\n const route = routeFor(report, url)\n\n if (!route) {\n // The urls, not just \"not found\": the caller has a url that does not exist,\n // and the most useful next thing is the ones that do.\n return (\n `No route for ${url} ${asOf(builtAt, now)}.\\n\\n` +\n 'Known urls:\\n' +\n [...report.routes, ...report.apis].map((r) => ` ${r.url}`).join('\\n')\n )\n }\n\n const lines = [`${route.url} — ${MEANING[route.type] ?? route.type} ${asOf(builtAt, now)}`]\n\n if (isPage(route)) {\n lines.push(`Rendered by ${route.component}.`)\n\n if (route.clientJs !== null) {\n lines.push(`Ships ${kb(route.clientJs)} of javascript, gzipped.`)\n }\n }\n\n if (route.reason) lines.push('', `Why it is not stored whole: ${route.reason}`)\n\n if (isPage(route) && route.warning) lines.push('', `Warning: ${route.warning}`)\n\n if (route.type === 'frozen') {\n lines.push(\n '',\n 'Nothing to fix. It is rendered once at build time and served as a file.',\n )\n }\n\n return lines.join('\\n')\n}\n\n/**\n * The routes that are not stored, and why.\n *\n * The question behind most of the others — someone asking \"why is my site\n * slow\" wants this list, not the whole table. Routes that are fine are left\n * out entirely rather than listed and dismissed.\n */\nexport function whatIsDynamic(report: BuildReport, builtAt: Date, now: number): string {\n const pages = report.routes.filter((r) => r.type !== 'frozen')\n const apis = report.apis.filter((a) => a.type !== 'frozen')\n\n if (pages.length === 0 && apis.length === 0) {\n return `Every route is stored at build time ${asOf(builtAt, now)}. Nothing renders per request.`\n }\n\n const lines = [\n `${pages.length + apis.length} of ${report.routes.length + report.apis.length} routes render per request ${asOf(builtAt, now)}:`,\n '',\n ]\n\n for (const route of [...pages, ...apis]) {\n lines.push(`${route.url} — ${route.reason ?? MEANING[route.type] ?? route.type}`)\n }\n\n lines.push(\n '',\n 'Reading the request is what makes a route dynamic: cookies(), headers(), searchParams(),',\n 'or connection() said deliberately. That is usually correct — a page whose content depends',\n 'on who is asking cannot be one stored file. Change it only if the read was accidental.',\n )\n\n return lines.join('\\n')\n}\n\n/** The heaviest routes, for the question that follows the size column. */\nexport function heaviestRoutes(report: BuildReport, builtAt: Date, now: number, top = 10): string {\n const weighed = report.routes\n .filter((r) => r.clientJs !== null)\n .sort((a, b) => (b.clientJs ?? 0) - (a.clientJs ?? 0))\n\n if (weighed.length === 0) {\n return `No route shipped measurable javascript ${asOf(builtAt, now)}.`\n }\n\n const lightest = weighed[weighed.length - 1].clientJs ?? 0\n\n return [\n `Heaviest routes ${asOf(builtAt, now)}:`,\n '',\n ...weighed.slice(0, top).map((r) => `${kb(r.clientJs ?? 0)} ${r.url}`),\n '',\n `The lightest route ships ${kb(lightest)}, so the difference between them is`,\n `${kb((weighed[0].clientJs ?? 0) - lightest)} of client components — most of the rest is React itself,`,\n 'which every route pays for.',\n ].join('\\n')\n}\n"]}
1
+ {"version":3,"file":"answers.js","sourceRoot":"","sources":["../src/answers.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,6EAA6E;AAC7E,4EAA4E;AAC5E,yBAAyB;AAGzB,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE/C,MAAM,EAAE,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,GAAG,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAA;AAE3G,MAAM,GAAG,GAAG,CAAC,OAAa,EAAE,GAAW,EAAU,EAAE;IACjD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,GAAG,MAAM,CAAC,CAAA;IAE9D,IAAI,OAAO,GAAG,CAAC;QAAE,OAAO,UAAU,CAAA;IAClC,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,OAAO,UAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,MAAM,CAAA;IAE3E,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAA;IAEtC,IA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;IAC7C,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAA;IAE9B,IAAI,CAAC,OAAO;QAAE,OAAO,CAAC,0DAA0D,CAAC,CAAA;IACjF,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,CAAC,eAAe,CAAC,CAAA;IAElD,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;IAC7C,MAAM,KAAK,GAAG,CAAC,YAAY,OAAO,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,8BAA8B,CAAC,CAAA;IAEzG,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,KAAK,CAAC,IAAI,CACR,GAAG,IAAI,CAAC,MAAM,sDAAsD;YAClE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAClF,oJAAoJ,CACrJ,CAAA;IACH,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["// The answers, as text, with no protocol in them.\n//\n// Separated from the server so they can be tested by calling them, and so the\n// wording is reviewable in one place. An agent reads these as prose and acts on\n// them, so a vague sentence here becomes a wrong edit somewhere else — \"this\n// route is dynamic\" invites a fix, \"this route reads cookies, which is why\"\n// invites the right one.\n\nimport type { BuildReport, ReportedApiRoute, ReportedRoute } from './report.js'\nimport { MEANING, routeFor } from './report.js'\n\nconst kb = (bytes: number) => `${bytes < 10_000 ? (bytes / 1000).toFixed(1) : Math.round(bytes / 1000)} kB`\n\nconst age = (builtAt: Date, now: number): string => {\n const minutes = Math.round((now - builtAt.getTime()) / 60_000)\n\n if (minutes < 1) return 'just now'\n if (minutes < 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`\n\n const hours = Math.round(minutes / 60)\n\n if (hours < 24) return `${hours} hour${hours === 1 ? '' : 's'} ago`\n\n return `${Math.round(hours / 24)} days ago`\n}\n\n/**\n * Every answer says how old it is.\n *\n * The one way this server misleads is by being confidently stale: it reports\n * the last build, and the file on disk may have changed since. Saying so on\n * every answer is cheaper than being wrong once.\n */\nexport function asOf(builtAt: Date, now: number): string {\n return `(from the last build, ${age(builtAt, now)})`\n}\n\nexport function listRoutes(report: BuildReport, builtAt: Date, now: number): string {\n const lines = [\n `${report.routes.length} routes and ${report.apis.length} api routes ${asOf(builtAt, now)}`,\n '',\n ]\n\n // First, before the table, because it changes what the table means: these\n // rows are from a build that did not finish, and nothing below is deployed.\n if (report.totals.failed > 0) {\n lines.unshift(\n `THE LAST BUILD FAILED: ${report.totals.failed} route${report.totals.failed === 1 ? '' : 's'} refused. Each one's line below says what to change. Fix it and build again.`,\n '',\n )\n }\n\n for (const route of report.routes) {\n const size = route.clientJs === null ? '' : ` ${kb(route.clientJs)}`\n\n lines.push(`${route.url}${size} — ${MEANING[route.type] ?? route.type}`)\n\n if (route.reason) lines.push(` ${route.reason}`)\n }\n\n if (report.apis.length) {\n lines.push('', 'api routes:')\n\n for (const api of report.apis) {\n lines.push(`${api.url} — ${MEANING[api.type] ?? api.type}`)\n\n if (api.reason) lines.push(` ${api.reason}`)\n }\n }\n\n lines.push(\n '',\n `${report.totals.static} static, ${report.totals.partial} partial prerender, ${report.totals.dynamic} dynamic` +\n (report.totals.failed ? `, ${report.totals.failed} failed` : ''),\n )\n\n lines.push('', ...actionLines(report))\n\n return lines.join('\\n')\n}\n\nfunction isPage(route: ReportedRoute | ReportedApiRoute): route is ReportedRoute {\n return 'component' in route\n}\n\nexport function explainRoute(\n report: BuildReport,\n url: string,\n builtAt: Date,\n now: number,\n): string {\n const route = routeFor(report, url)\n\n if (!route) {\n // The urls, not just \"not found\": the caller has a url that does not exist,\n // and the most useful next thing is the ones that do.\n return (\n `No route for ${url} ${asOf(builtAt, now)}.\\n\\n` +\n 'Known urls:\\n' +\n [...report.routes, ...report.apis].map((r) => ` ${r.url}`).join('\\n')\n )\n }\n\n const lines = [`${route.url} — ${MEANING[route.type] ?? route.type} ${asOf(builtAt, now)}`]\n\n if (isPage(route)) {\n lines.push(`Rendered by ${route.component}.`)\n\n if (route.clientJs !== null) {\n lines.push(`Ships ${kb(route.clientJs)} of javascript, gzipped.`)\n }\n }\n\n if (route.reason) lines.push('', `Why it is not stored whole: ${route.reason}`)\n\n if (isPage(route) && route.warning) lines.push('', `Warning: ${route.warning}`)\n\n if (route.type === 'frozen') {\n lines.push(\n '',\n 'Nothing to fix. It is rendered once at build time and served as a file.',\n )\n }\n\n return lines.join('\\n')\n}\n\n/**\n * The routes that are not stored, and why.\n *\n * The question behind most of the others — someone asking \"why is my site\n * slow\" wants this list, not the whole table. Routes that are fine are left\n * out entirely rather than listed and dismissed.\n */\nexport function whatIsDynamic(report: BuildReport, builtAt: Date, now: number): string {\n const pages = report.routes.filter((r) => r.type !== 'frozen')\n const apis = report.apis.filter((a) => a.type !== 'frozen')\n\n if (pages.length === 0 && apis.length === 0) {\n return `Every route is stored at build time ${asOf(builtAt, now)}. Nothing renders per request.`\n }\n\n const lines = [\n `${pages.length + apis.length} of ${report.routes.length + report.apis.length} routes render per request ${asOf(builtAt, now)}:`,\n '',\n ]\n\n for (const route of [...pages, ...apis]) {\n lines.push(`${route.url} — ${route.reason ?? MEANING[route.type] ?? route.type}`)\n }\n\n lines.push(\n '',\n 'Reading the request is what makes a route dynamic: cookies(), headers(), searchParams(),',\n 'or connection() said deliberately. That is usually correct — a page whose content depends',\n 'on who is asking cannot be one stored file. Change it only if the read was accidental.',\n )\n\n return lines.join('\\n')\n}\n\n/** The heaviest routes, for the question that follows the size column. */\nexport function heaviestRoutes(report: BuildReport, builtAt: Date, now: number, top = 10): string {\n const weighed = report.routes\n .filter((r) => r.clientJs !== null)\n .sort((a, b) => (b.clientJs ?? 0) - (a.clientJs ?? 0))\n\n if (weighed.length === 0) {\n return `No route shipped measurable javascript ${asOf(builtAt, now)}.`\n }\n\n const lightest = weighed[weighed.length - 1].clientJs ?? 0\n\n return [\n `Heaviest routes ${asOf(builtAt, now)}:`,\n '',\n ...weighed.slice(0, top).map((r) => `${kb(r.clientJs ?? 0)} ${r.url}`),\n '',\n `The lightest route ships ${kb(lightest)}, so the difference between them is`,\n `${kb((weighed[0].clientJs ?? 0) - lightest)} of client components — most of the rest is React itself,`,\n 'which every route pays for.',\n ].join('\\n')\n}\n\n/**\n * The actions, and the one fact about each that nothing else states: whether\n * anything checks who calls it. A bare \"use server\" export runs with no\n * middleware; an agent adding a delete button needs to know that before it\n * trusts the id it was handed.\n */\nexport function actionLines(report: BuildReport): string[] {\n const actions = report.actions\n\n if (!actions) return ['actions: not audited by this build (older @rsc-kit/core)']\n if (actions.length === 0) return ['actions: none']\n\n const bare = actions.filter((a) => !a.client)\n const lines = [`actions: ${actions.length}, ${actions.length - bare.length} built from an action client`]\n\n if (bare.length > 0) {\n lines.push(\n `${bare.length} run NO middleware — nothing checks who calls them: ` +\n bare.map((a) => `${a.name}${a.query ? ' (query)' : ''} in ${a.file}`).join(', '),\n 'Fine for a public action. For anything else, build it from an action client so the check cannot be forgotten — how_to({ topic: \"action-client\" }).',\n )\n }\n\n return lines\n}\n"]}
@@ -0,0 +1,22 @@
1
+ export interface GuideEntry {
2
+ slug: string;
3
+ title: string;
4
+ description: string;
5
+ }
6
+ /** One guide's MDX as markdown, with the samples it names inlined. */
7
+ export declare function toMarkdown(mdx: string, repoRoot: string): {
8
+ entry: Omit<GuideEntry, 'slug'>;
9
+ body: string;
10
+ };
11
+ /** Every guide under `from`, written as markdown into `into`, with an index. */
12
+ export declare function bundleGuides(from: string, into: string, repoRoot: string): GuideEntry[];
13
+ /** Where the bundled guides are, beside dist — or nowhere, before a build. */
14
+ export declare function guidesDir(): string | null;
15
+ export declare function listGuides(): string;
16
+ export declare function readGuide(slug: string): string;
17
+ /**
18
+ * Lines matching a phrase across every bundled guide, with the guide and a
19
+ * little context. A grep, deliberately - the guides are 250 KB and an agent
20
+ * asking "where is fieldErrors mentioned" wants the lines, not a ranking.
21
+ */
22
+ export declare function searchGuides(phrase: string, limit?: number): string;
@@ -0,0 +1,130 @@
1
+ // The guides, as files an agent can read without leaving its editor.
2
+ //
3
+ // how_to answers are short and opinionated, and they are copies — of the
4
+ // guides at rsc-kit.dev, by hand, which is how a recipe once said <Form> worked
5
+ // without javascript when it did not yet. The guides are the source. This
6
+ // bundles them into the package at build time so read_guide answers with the
7
+ // same text the site shows, and a recipe can point at the full version instead
8
+ // of restating it.
9
+ //
10
+ // MDX to markdown is three edits: the frontmatter becomes a heading, the
11
+ // component imports go, and <CodeFromFile> becomes the code it names — cut the
12
+ // same way the site cuts it, region and all.
13
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { basename, extname, join } from 'node:path';
15
+ const FRONTMATTER = /^---\n([\s\S]*?)\n---\n/;
16
+ const COMPONENT_IMPORT = /^import .* from ["']@\/components\/.*["'];?\n/gm;
17
+ const CODE_FROM_FILE = /<CodeFromFile\s+([^>]*?)\/>/g;
18
+ function attribute(attrs, name) {
19
+ return new RegExp(`${name}="([^"]*)"`).exec(attrs)?.[1];
20
+ }
21
+ function frontmatterField(block, name) {
22
+ const match = new RegExp(`^${name}:\\s*(.*)$`, 'm').exec(block);
23
+ return (match?.[1] ?? '').trim().replace(/^["'](.*)["']$/, '$1');
24
+ }
25
+ /** The lines between `#region <name>` and its `#endregion`, dedented. */
26
+ function region(source, name, file) {
27
+ const lines = source.split('\n');
28
+ const start = lines.findIndex((line) => new RegExp(`#region\\s+${name}\\b`).test(line));
29
+ if (start === -1)
30
+ throw new Error(`No region "${name}" in ${file}`);
31
+ const end = lines.findIndex((line, i) => i > start && /#endregion\b/.test(line));
32
+ if (end === -1)
33
+ throw new Error(`Region "${name}" in ${file} is never closed`);
34
+ const body = lines.slice(start + 1, end).filter((line) => !/#(region|endregion)\b/.test(line));
35
+ const indent = Math.min(...body.filter((l) => l.trim()).map((l) => /^\s*/.exec(l)[0].length));
36
+ return body.map((line) => line.slice(indent)).join('\n');
37
+ }
38
+ /** One guide's MDX as markdown, with the samples it names inlined. */
39
+ export function toMarkdown(mdx, repoRoot) {
40
+ const fm = FRONTMATTER.exec(mdx);
41
+ const title = fm ? frontmatterField(fm[1], 'title') : '';
42
+ const description = fm ? frontmatterField(fm[1], 'description') : '';
43
+ let body = mdx.replace(FRONTMATTER, '').replace(COMPONENT_IMPORT, '');
44
+ body = body.replace(CODE_FROM_FILE, (_, attrs) => {
45
+ const file = attribute(attrs, 'file');
46
+ const source = readFileSync(join(repoRoot, file), 'utf-8');
47
+ const name = attribute(attrs, 'region');
48
+ const code = name ? region(source, name, file) : source.trimEnd();
49
+ const lang = attribute(attrs, 'lang') ?? extname(file).slice(1);
50
+ const heading = attribute(attrs, 'title') ?? file;
51
+ return `\`\`\`${lang} title="${heading}"\n${code}\n\`\`\``;
52
+ });
53
+ return {
54
+ entry: { title, description },
55
+ body: `# ${title}\n\n${description ? `> ${description}\n\n` : ''}${body.trim()}\n`,
56
+ };
57
+ }
58
+ /** Every guide under `from`, written as markdown into `into`, with an index. */
59
+ export function bundleGuides(from, into, repoRoot) {
60
+ rmSync(into, { recursive: true, force: true });
61
+ mkdirSync(into, { recursive: true });
62
+ const index = [];
63
+ for (const file of readdirSync(from).filter((f) => f.endsWith('.mdx')).sort()) {
64
+ const slug = basename(file, '.mdx');
65
+ const { entry, body } = toMarkdown(readFileSync(join(from, file), 'utf-8'), repoRoot);
66
+ writeFileSync(join(into, `${slug}.md`), body);
67
+ index.push({ slug, ...entry });
68
+ }
69
+ writeFileSync(join(into, 'index.json'), JSON.stringify(index, null, 2) + '\n');
70
+ return index;
71
+ }
72
+ /** Where the bundled guides are, beside dist — or nowhere, before a build. */
73
+ export function guidesDir() {
74
+ const dir = new URL('../guides/', import.meta.url).pathname;
75
+ return existsSync(join(dir, 'index.json')) ? dir : null;
76
+ }
77
+ export function listGuides() {
78
+ const dir = guidesDir();
79
+ if (!dir)
80
+ return 'No guides are bundled in this install. They are at https://rsc-kit.dev.';
81
+ const index = JSON.parse(readFileSync(join(dir, 'index.json'), 'utf-8'));
82
+ const width = Math.max(...index.map((g) => g.slug.length));
83
+ return [
84
+ 'The guides, as published. Read one with read_guide({ slug }).',
85
+ '',
86
+ ...index.map((g) => `${g.slug.padEnd(width)} ${g.description || g.title}`),
87
+ ].join('\n');
88
+ }
89
+ export function readGuide(slug) {
90
+ const dir = guidesDir();
91
+ if (!dir)
92
+ return `No guides are bundled in this install. This one is at https://rsc-kit.dev/guides/${slug}.`;
93
+ const file = join(dir, `${basename(slug)}.md`);
94
+ if (!existsSync(file))
95
+ return `No guide called "${slug}". list_guides has the names.`;
96
+ return readFileSync(file, 'utf-8');
97
+ }
98
+ /**
99
+ * Lines matching a phrase across every bundled guide, with the guide and a
100
+ * little context. A grep, deliberately - the guides are 250 KB and an agent
101
+ * asking "where is fieldErrors mentioned" wants the lines, not a ranking.
102
+ */
103
+ export function searchGuides(phrase, limit = 40) {
104
+ const dir = guidesDir();
105
+ if (!dir)
106
+ return 'No guides are bundled in this install. Search https://rsc-kit.dev instead.';
107
+ const needle = phrase.trim().toLowerCase();
108
+ if (!needle)
109
+ return 'Give a word or phrase to search for.';
110
+ const index = JSON.parse(readFileSync(join(dir, 'index.json'), 'utf-8'));
111
+ const hits = [];
112
+ for (const { slug } of index) {
113
+ const lines = readFileSync(join(dir, `${slug}.md`), 'utf-8').split('\n');
114
+ for (let i = 0; i < lines.length && hits.length < limit; i++) {
115
+ if (!lines[i].toLowerCase().includes(needle))
116
+ continue;
117
+ hits.push(`${slug}:${i + 1} ${lines[i].trim()}`);
118
+ }
119
+ if (hits.length >= limit)
120
+ break;
121
+ }
122
+ if (hits.length === 0)
123
+ return `Nothing in the guides mentions "${phrase}".`;
124
+ return [
125
+ `${hits.length}${hits.length === limit ? '+' : ''} lines mention "${phrase}". Read a guide with read_guide({ slug }).`,
126
+ '',
127
+ ...hits,
128
+ ].join('\n');
129
+ }
130
+ //# sourceMappingURL=bundleGuides.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundleGuides.js","sourceRoot":"","sources":["../src/bundleGuides.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,EAAE;AACF,yEAAyE;AACzE,gFAAgF;AAChF,0EAA0E;AAC1E,6EAA6E;AAC7E,+EAA+E;AAC/E,mBAAmB;AACnB,EAAE;AACF,yEAAyE;AACzE,+EAA+E;AAC/E,6CAA6C;AAE7C,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACjG,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAQnD,MAAM,WAAW,GAAG,yBAAyB,CAAA;AAC7C,MAAM,gBAAgB,GAAG,iDAAiD,CAAA;AAC1E,MAAM,cAAc,GAAG,8BAA8B,CAAA;AAErD,SAAS,SAAS,CAAC,KAAa,EAAE,IAAY;IAC5C,OAAO,IAAI,MAAM,CAAC,GAAG,IAAI,YAAY,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;AACzD,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa,EAAE,IAAY;IACnD,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,IAAI,IAAI,YAAY,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAE/D,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAA;AAClE,CAAC;AAED,yEAAyE;AACzE,SAAS,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E,CAAC,IAAI,EAAE,EAAE,CAAC,CAAA;QACpD,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,IAAI,KAAK;YAAE,MAAK;IACjC,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,mCAAmC,MAAM,IAAI,CAAA;IAE3E,OAAO;QACL,GAAG,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,mBAAmB,MAAM,4CAA4C;QACtH,EAAE;QACF,GAAG,IAAI;KACR,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AACd,CAAC","sourcesContent":["// The guides, as files an agent can read without leaving its editor.\n//\n// how_to answers are short and opinionated, and they are copies — of the\n// guides at rsc-kit.dev, by hand, which is how a recipe once said <Form> worked\n// without javascript when it did not yet. The guides are the source. This\n// bundles them into the package at build time so read_guide answers with the\n// same text the site shows, and a recipe can point at the full version instead\n// of restating it.\n//\n// MDX to markdown is three edits: the frontmatter becomes a heading, the\n// component imports go, and <CodeFromFile> becomes the code it names — cut the\n// same way the site cuts it, region and all.\n\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'\nimport { basename, extname, join } from 'node:path'\n\nexport interface GuideEntry {\n slug: string\n title: string\n description: string\n}\n\nconst FRONTMATTER = /^---\\n([\\s\\S]*?)\\n---\\n/\nconst COMPONENT_IMPORT = /^import .* from [\"']@\\/components\\/.*[\"'];?\\n/gm\nconst CODE_FROM_FILE = /<CodeFromFile\\s+([^>]*?)\\/>/g\n\nfunction attribute(attrs: string, name: string): string | undefined {\n return new RegExp(`${name}=\"([^\"]*)\"`).exec(attrs)?.[1]\n}\n\nfunction frontmatterField(block: string, name: string): string {\n const match = new RegExp(`^${name}:\\\\s*(.*)$`, 'm').exec(block)\n\n return (match?.[1] ?? '').trim().replace(/^[\"'](.*)[\"']$/, '$1')\n}\n\n/** The lines between `#region <name>` and its `#endregion`, dedented. */\nfunction region(source: string, name: string, file: string): string {\n const lines = source.split('\\n')\n const start = lines.findIndex((line) => new RegExp(`#region\\\\s+${name}\\\\b`).test(line))\n\n if (start === -1) throw new Error(`No region \"${name}\" in ${file}`)\n\n const end = lines.findIndex((line, i) => i > start && /#endregion\\b/.test(line))\n\n if (end === -1) throw new Error(`Region \"${name}\" in ${file} is never closed`)\n\n const body = lines.slice(start + 1, end).filter((line) => !/#(region|endregion)\\b/.test(line))\n const indent = Math.min(...body.filter((l) => l.trim()).map((l) => /^\\s*/.exec(l)![0].length))\n\n return body.map((line) => line.slice(indent)).join('\\n')\n}\n\n/** One guide's MDX as markdown, with the samples it names inlined. */\nexport function toMarkdown(mdx: string, repoRoot: string): { entry: Omit<GuideEntry, 'slug'>; body: string } {\n const fm = FRONTMATTER.exec(mdx)\n const title = fm ? frontmatterField(fm[1]!, 'title') : ''\n const description = fm ? frontmatterField(fm[1]!, 'description') : ''\n\n let body = mdx.replace(FRONTMATTER, '').replace(COMPONENT_IMPORT, '')\n\n body = body.replace(CODE_FROM_FILE, (_, attrs: string) => {\n const file = attribute(attrs, 'file')!\n const source = readFileSync(join(repoRoot, file), 'utf-8')\n const name = attribute(attrs, 'region')\n const code = name ? region(source, name, file) : source.trimEnd()\n const lang = attribute(attrs, 'lang') ?? extname(file).slice(1)\n const heading = attribute(attrs, 'title') ?? file\n\n return `\\`\\`\\`${lang} title=\"${heading}\"\\n${code}\\n\\`\\`\\``\n })\n\n return {\n entry: { title, description },\n body: `# ${title}\\n\\n${description ? `> ${description}\\n\\n` : ''}${body.trim()}\\n`,\n }\n}\n\n/** Every guide under `from`, written as markdown into `into`, with an index. */\nexport function bundleGuides(from: string, into: string, repoRoot: string): GuideEntry[] {\n rmSync(into, { recursive: true, force: true })\n mkdirSync(into, { recursive: true })\n\n const index: GuideEntry[] = []\n\n for (const file of readdirSync(from).filter((f) => f.endsWith('.mdx')).sort()) {\n const slug = basename(file, '.mdx')\n const { entry, body } = toMarkdown(readFileSync(join(from, file), 'utf-8'), repoRoot)\n\n writeFileSync(join(into, `${slug}.md`), body)\n index.push({ slug, ...entry })\n }\n\n writeFileSync(join(into, 'index.json'), JSON.stringify(index, null, 2) + '\\n')\n\n return index\n}\n\n/** Where the bundled guides are, beside dist — or nowhere, before a build. */\nexport function guidesDir(): string | null {\n const dir = new URL('../guides/', import.meta.url).pathname\n\n return existsSync(join(dir, 'index.json')) ? dir : null\n}\n\nexport function listGuides(): string {\n const dir = guidesDir()\n\n if (!dir) return 'No guides are bundled in this install. They are at https://rsc-kit.dev.'\n\n const index = JSON.parse(readFileSync(join(dir, 'index.json'), 'utf-8')) as GuideEntry[]\n const width = Math.max(...index.map((g) => g.slug.length))\n\n return [\n 'The guides, as published. Read one with read_guide({ slug }).',\n '',\n ...index.map((g) => `${g.slug.padEnd(width)} ${g.description || g.title}`),\n ].join('\\n')\n}\n\nexport function readGuide(slug: string): string {\n const dir = guidesDir()\n\n if (!dir) return `No guides are bundled in this install. This one is at https://rsc-kit.dev/guides/${slug}.`\n\n const file = join(dir, `${basename(slug)}.md`)\n\n if (!existsSync(file)) return `No guide called \"${slug}\". list_guides has the names.`\n\n return readFileSync(file, 'utf-8')\n}\n\n/**\n * Lines matching a phrase across every bundled guide, with the guide and a\n * little context. A grep, deliberately - the guides are 250 KB and an agent\n * asking \"where is fieldErrors mentioned\" wants the lines, not a ranking.\n */\nexport function searchGuides(phrase: string, limit = 40): string {\n const dir = guidesDir()\n\n if (!dir) return 'No guides are bundled in this install. Search https://rsc-kit.dev instead.'\n\n const needle = phrase.trim().toLowerCase()\n\n if (!needle) return 'Give a word or phrase to search for.'\n\n const index = JSON.parse(readFileSync(join(dir, 'index.json'), 'utf-8')) as GuideEntry[]\n const hits: string[] = []\n\n for (const { slug } of index) {\n const lines = readFileSync(join(dir, `${slug}.md`), 'utf-8').split('\\n')\n\n for (let i = 0; i < lines.length && hits.length < limit; i++) {\n if (!lines[i]!.toLowerCase().includes(needle)) continue\n\n hits.push(`${slug}:${i + 1} ${lines[i]!.trim()}`)\n }\n\n if (hits.length >= limit) break\n }\n\n if (hits.length === 0) return `Nothing in the guides mentions \"${phrase}\".`\n\n return [\n `${hits.length}${hits.length === limit ? '+' : ''} lines mention \"${phrase}\". Read a guide with read_guide({ slug }).`,\n '',\n ...hits,\n ].join('\\n')\n}\n"]}
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ import { z } from 'zod';
26
26
  import { explainRoute, heaviestRoutes, listRoutes, whatIsDynamic } from './answers.js';
27
27
  import { NoReport, loadReport } from './report.js';
28
28
  import { howTo, listTopics } from './recipes.js';
29
+ import { listGuides, readGuide, searchGuides } from './bundleGuides.js';
29
30
  /** The project to read, from the argument or the working directory. */
30
31
  const root = process.argv[2] ?? process.cwd();
31
32
  /**
@@ -46,6 +47,8 @@ const read = () => loadReport(root);
46
47
  */
47
48
  const URL_ARG = { url: z.string().describe('The url, e.g. /orders or /posts/hello') };
48
49
  const TOPIC_ARG = { topic: z.string().describe('One of the topics from list_topics, e.g. forms or validation') };
50
+ const SLUG_ARG = { slug: z.string().describe('One of the slugs from list_guides, e.g. forms or server-actions') };
51
+ const PHRASE_ARG = { phrase: z.string().describe('A word or phrase, e.g. fieldErrors or metadataBase') };
49
52
  const text = (body) => ({ content: [{ type: 'text', text: body }] });
50
53
  /** A missing report is an answer, not a crash: it says to run a build. */
51
54
  const answering = (produce) => {
@@ -94,7 +97,7 @@ server.registerTool('heaviest_routes', {
94
97
  }));
95
98
  server.registerTool('how_to', {
96
99
  title: 'How to build it',
97
- description: 'How to do something in an rsc-kit app — forms, prefetching, validation, the action client, data loading with TanStack Query or SWR, Suspense boundaries, offline, PWA, api routes, authorization, and why a page is dynamic. Read this BEFORE writing the code: the patterns here differ from Next and plain React in ways that compile either way.',
100
+ description: 'How to do something in an rsc-kit app — forms, prefetching, validation, the action client, data loading with TanStack Query or SWR, Suspense boundaries, offline, PWA, api routes, authorization, and why a page is dynamic. Read this BEFORE writing the code: the patterns here differ from Next and plain React in ways that compile either way. The short answer; read_guide has the full one.',
98
101
  inputSchema: TOPIC_ARG,
99
102
  annotations: { readOnlyHint: true },
100
103
  }, (async ({ topic }) => text(howTo(topic))));
@@ -103,5 +106,22 @@ server.registerTool('list_topics', {
103
106
  description: 'Every topic how_to knows about, one line each.',
104
107
  annotations: { readOnlyHint: true },
105
108
  }, async () => text(listTopics()));
109
+ server.registerTool('list_guides', {
110
+ title: 'The guides',
111
+ description: 'Every guide from rsc-kit.dev, bundled with this server — the full text behind how_to, one line each.',
112
+ annotations: { readOnlyHint: true },
113
+ }, async () => text(listGuides()));
114
+ server.registerTool('read_guide', {
115
+ title: 'Read a guide',
116
+ description: 'The complete guide for one topic, as published at rsc-kit.dev — routing, forms, server-actions, validation, metadata, testing, deployment and the rest. Use it when how_to is not enough or names something it does not explain.',
117
+ inputSchema: SLUG_ARG,
118
+ annotations: { readOnlyHint: true },
119
+ }, (async ({ slug }) => text(readGuide(slug))));
120
+ server.registerTool('search_guides', {
121
+ title: 'Search the guides',
122
+ description: 'Every line in the guides that mentions a word or phrase, with the guide it is in. Use it to find which guide covers something before reading it.',
123
+ inputSchema: PHRASE_ARG,
124
+ annotations: { readOnlyHint: true },
125
+ }, (async ({ phrase }) => text(searchGuides(phrase))));
106
126
  await server.connect(new StdioServerTransport());
107
127
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,oDAAoD;AACpD,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,yEAAyE;AACzE,mCAAmC;AACnC,EAAE;AACF,iDAAiD;AACjD,+BAA+B;AAC/B,kCAAkC;AAClC,yCAAyC;AACzC,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,gFAAgF;AAChF,8EAA8E;AAC9E,kEAAkE;AAClE,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,2EAA2E;AAE3E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AE,CAAA;IAElC,OAAO,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;AACnD,CAAC,CAAC,CACL,CAAA;AAED,MAAM,CAAC,YAAY,CACjB,iBAAiB,EACjB;IACE,KAAK,EAAE,iBAAiB;IACxB,WAAW,EAAE,+EAA+E;IAC5F,WAAW,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE;CACpC,EACD,KAAK,IAAI,EAAE,CACT,SAAS,CAAC,GAAG,EAAE;IACb,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,CAAA;IAElC,OAAO,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;AACpD,CAAC,CAAC,CACL,CAAA;AAED,MAAM,CAAC,YAAY,CACjB,QAAQ,EACR;IACE,KAAK,EAAE,iBAAiB;IACxB,WAAW,EACT,qVAAqV;IACvV,WAAW,EAAE,SAAS;IACtB,WAAW,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE;CACpC,EACD,CAAC,KAAK,EAAE,EAAE,KAAK,EAAqB,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAU,CACtE,CAAA;AAED,MAAM,CAAC,YAAY,CACjB,aAAa,EACb;IACE,KAAK,EAAE,8BAA8B;IACrC,WAAW,EAAE,gDAAgD;IAC7D,WAAW,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE;CACpC,EACD,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,CAC/B,CAAA;AAED,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAA","sourcesContent":["#!/usr/bin/env node\n// An MCP server over what an rsc-kit build decided.\n//\n// claude mcp add rsc-kit -- npx -y @rsc-kit/mcp\n//\n// Four questions, all answered from `build-report.json` and none of them\n// requiring the app to be running:\n//\n// what routes exist, and what happened to each\n// why is this one not stored\n// which ones render per request\n// which ones cost the browser the most\n//\n// Why a server rather than letting an agent read the file: the file is JSON\n// with a `type` field whose values mean nothing without the documentation, and\n// an agent reading it guesses — \"shell\" invites being treated as a failure when\n// it is the normal, correct outcome for a page with data in it. These answers\n// say what each state means, in the same words the build printed.\n//\n// Everything is read-only. There is no tool here that edits, builds or deploys,\n// deliberately: an agent already has a shell for those, and a server that can\n// change the project is one that can change it while answering a question.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { explainRoute, heaviestRoutes, listRoutes, whatIsDynamic } from './answers.js'\nimport { NoReport, loadReport } from './report.js'\nimport { howTo, listTopics } from './recipes.js'\n\n/** The project to read, from the argument or the working directory. */\nconst root = process.argv[2] ?? process.cwd()\n\n/**\n * Loaded per call, never cached.\n *\n * A build happens while this server is running — that is the normal case, not\n * the exception — and an answer from the build before it is worse than a slow\n * one. The file is small and this is not a hot path.\n */\nconst read = () => loadReport(root)\n\n/**\n * Declared once, outside the call.\n *\n * Inline, TypeScript walks the sdk's tool generics against the zod shape and\n * gives up with \"type instantiation is excessively deep\" — a compiler limit\n * rather than anything wrong with the schema. A named const with the handler's\n * argument annotated stops the inference chain before it gets there.\n */\nconst URL_ARG = { url: z.string().describe('The url, e.g. /orders or /posts/hello') }\nconst TOPIC_ARG = { topic: z.string().describe('One of the topics from list_topics, e.g. forms or validation') }\n\nconst text = (body: string) => ({ content: [{ type: 'text' as const, text: body }] })\n\n/** A missing report is an answer, not a crash: it says to run a build. */\nconst answering = (produce: () => string) => {\n try {\n return text(produce())\n } catch (error) {\n if (error instanceof NoReport) return text(error.message)\n\n throw error\n }\n}\n\n/**\n * The registration surface, named rather than inferred.\n *\n * `registerTool` is generic over the zod shape, and TypeScript walks those\n * generics until it gives up — \"type instantiation is excessively deep\", which\n * is a compiler limit rather than anything wrong with the schema. Describing\n * the one method used, with the argument type written out, stops the inference\n * before it gets there and costs nothing: the schemas below are still real zod\n * and still validate at runtime.\n */\ninterface Registrar {\n registerTool(\n name: string,\n config: {\n title?: string\n description?: string\n inputSchema?: Record<string, unknown>\n annotations?: { readOnlyHint?: boolean }\n },\n handler: (args: never) => Promise<{ content: { type: 'text'; text: string }[] }>,\n ): unknown\n connect(transport: StdioServerTransport): Promise<void>\n}\n\nconst server = new McpServer({ name: 'rsc-kit', version: '0.1.0' }) as unknown as Registrar\n\nserver.registerTool(\n 'list_routes',\n {\n title: 'List routes',\n description:\n 'Every route in this rsc-kit app, what the build did with each one, and how much javascript it ships. Start here when you need to know what exists.',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return listRoutes(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'explain_route',\n {\n title: 'Explain a route',\n description:\n 'Why one url is stored at build time or rendered per request, what renders it, and what it costs the browser. Use this before changing a page to make it faster — the reason is recorded, not guessed.',\n inputSchema: URL_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ url }: { url: string }) =>\n answering(() => {\n const { report, builtAt } = read()\n\n return explainRoute(report, url, builtAt, Date.now())\n })) as never,\n)\n\nserver.registerTool(\n 'what_is_dynamic',\n {\n title: 'What renders per request',\n description:\n 'The routes that render per request rather than being stored, each with the reason. This is the answer to \"why is this site not static\".',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return whatIsDynamic(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'heaviest_routes',\n {\n title: 'Heaviest routes',\n description: 'The routes that make the browser download the most javascript, largest first.',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return heaviestRoutes(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'how_to',\n {\n title: 'How to build it',\n description:\n 'How to do something in an rsc-kit app — forms, prefetching, validation, the action client, data loading with TanStack Query or SWR, Suspense boundaries, offline, PWA, api routes, authorization, and why a page is dynamic. Read this BEFORE writing the code: the patterns here differ from Next and plain React in ways that compile either way.',\n inputSchema: TOPIC_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ topic }: { topic: string }) => text(howTo(topic))) as never,\n)\n\nserver.registerTool(\n 'list_topics',\n {\n title: 'What this server can explain',\n description: 'Every topic how_to knows about, one line each.',\n annotations: { readOnlyHint: true },\n },\n async () => text(listTopics()),\n)\n\nawait server.connect(new StdioServerTransport())\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,oDAAoD;AACpD,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,yEAAyE;AACzE,mCAAmC;AACnC,EAAE;AACF,iDAAiD;AACjD,+BAA+B;AAC/B,kCAAkC;AAClC,yCAAyC;AACzC,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,gFAAgF;AAChF,8EAA8E;AAC9E,kEAAkE;AAClE,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,2EAA2E;AAE3E,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAA;AAChF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AACtF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAChD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEvE,uEAAuE;AACvE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,CAAA;AAE7C;;;;;;G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AAC,CAAC,CAAU,CACvE,CAAA;AAED,MAAM,CAAC,YAAY,CACjB,eAAe,EACf;IACE,KAAK,EAAE,mBAAmB;IAC1B,WAAW,EAAE,kJAAkJ;IAC/J,WAAW,EAAE,UAAU;IACvB,WAAW,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE;CACpC,EACD,CAAC,KAAK,EAAE,EAAE,MAAM,EAAsB,EAAE,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAU,CAChF,CAAA;AAED,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAA","sourcesContent":["#!/usr/bin/env node\n// An MCP server over what an rsc-kit build decided.\n//\n// claude mcp add rsc-kit -- npx -y @rsc-kit/mcp\n//\n// Four questions, all answered from `build-report.json` and none of them\n// requiring the app to be running:\n//\n// what routes exist, and what happened to each\n// why is this one not stored\n// which ones render per request\n// which ones cost the browser the most\n//\n// Why a server rather than letting an agent read the file: the file is JSON\n// with a `type` field whose values mean nothing without the documentation, and\n// an agent reading it guesses — \"shell\" invites being treated as a failure when\n// it is the normal, correct outcome for a page with data in it. These answers\n// say what each state means, in the same words the build printed.\n//\n// Everything is read-only. There is no tool here that edits, builds or deploys,\n// deliberately: an agent already has a shell for those, and a server that can\n// change the project is one that can change it while answering a question.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { explainRoute, heaviestRoutes, listRoutes, whatIsDynamic } from './answers.js'\nimport { NoReport, loadReport } from './report.js'\nimport { howTo, listTopics } from './recipes.js'\nimport { listGuides, readGuide, searchGuides } from './bundleGuides.js'\n\n/** The project to read, from the argument or the working directory. */\nconst root = process.argv[2] ?? process.cwd()\n\n/**\n * Loaded per call, never cached.\n *\n * A build happens while this server is running — that is the normal case, not\n * the exception — and an answer from the build before it is worse than a slow\n * one. The file is small and this is not a hot path.\n */\nconst read = () => loadReport(root)\n\n/**\n * Declared once, outside the call.\n *\n * Inline, TypeScript walks the sdk's tool generics against the zod shape and\n * gives up with \"type instantiation is excessively deep\" — a compiler limit\n * rather than anything wrong with the schema. A named const with the handler's\n * argument annotated stops the inference chain before it gets there.\n */\nconst URL_ARG = { url: z.string().describe('The url, e.g. /orders or /posts/hello') }\nconst TOPIC_ARG = { topic: z.string().describe('One of the topics from list_topics, e.g. forms or validation') }\nconst SLUG_ARG = { slug: z.string().describe('One of the slugs from list_guides, e.g. forms or server-actions') }\nconst PHRASE_ARG = { phrase: z.string().describe('A word or phrase, e.g. fieldErrors or metadataBase') }\n\nconst text = (body: string) => ({ content: [{ type: 'text' as const, text: body }] })\n\n/** A missing report is an answer, not a crash: it says to run a build. */\nconst answering = (produce: () => string) => {\n try {\n return text(produce())\n } catch (error) {\n if (error instanceof NoReport) return text(error.message)\n\n throw error\n }\n}\n\n/**\n * The registration surface, named rather than inferred.\n *\n * `registerTool` is generic over the zod shape, and TypeScript walks those\n * generics until it gives up — \"type instantiation is excessively deep\", which\n * is a compiler limit rather than anything wrong with the schema. Describing\n * the one method used, with the argument type written out, stops the inference\n * before it gets there and costs nothing: the schemas below are still real zod\n * and still validate at runtime.\n */\ninterface Registrar {\n registerTool(\n name: string,\n config: {\n title?: string\n description?: string\n inputSchema?: Record<string, unknown>\n annotations?: { readOnlyHint?: boolean }\n },\n handler: (args: never) => Promise<{ content: { type: 'text'; text: string }[] }>,\n ): unknown\n connect(transport: StdioServerTransport): Promise<void>\n}\n\nconst server = new McpServer({ name: 'rsc-kit', version: '0.1.0' }) as unknown as Registrar\n\nserver.registerTool(\n 'list_routes',\n {\n title: 'List routes',\n description:\n 'Every route in this rsc-kit app, what the build did with each one, and how much javascript it ships. Start here when you need to know what exists.',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return listRoutes(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'explain_route',\n {\n title: 'Explain a route',\n description:\n 'Why one url is stored at build time or rendered per request, what renders it, and what it costs the browser. Use this before changing a page to make it faster — the reason is recorded, not guessed.',\n inputSchema: URL_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ url }: { url: string }) =>\n answering(() => {\n const { report, builtAt } = read()\n\n return explainRoute(report, url, builtAt, Date.now())\n })) as never,\n)\n\nserver.registerTool(\n 'what_is_dynamic',\n {\n title: 'What renders per request',\n description:\n 'The routes that render per request rather than being stored, each with the reason. This is the answer to \"why is this site not static\".',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return whatIsDynamic(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'heaviest_routes',\n {\n title: 'Heaviest routes',\n description: 'The routes that make the browser download the most javascript, largest first.',\n annotations: { readOnlyHint: true },\n },\n async () =>\n answering(() => {\n const { report, builtAt } = read()\n\n return heaviestRoutes(report, builtAt, Date.now())\n }),\n)\n\nserver.registerTool(\n 'how_to',\n {\n title: 'How to build it',\n description:\n 'How to do something in an rsc-kit app — forms, prefetching, validation, the action client, data loading with TanStack Query or SWR, Suspense boundaries, offline, PWA, api routes, authorization, and why a page is dynamic. Read this BEFORE writing the code: the patterns here differ from Next and plain React in ways that compile either way. The short answer; read_guide has the full one.',\n inputSchema: TOPIC_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ topic }: { topic: string }) => text(howTo(topic))) as never,\n)\n\nserver.registerTool(\n 'list_topics',\n {\n title: 'What this server can explain',\n description: 'Every topic how_to knows about, one line each.',\n annotations: { readOnlyHint: true },\n },\n async () => text(listTopics()),\n)\n\nserver.registerTool(\n 'list_guides',\n {\n title: 'The guides',\n description: 'Every guide from rsc-kit.dev, bundled with this server — the full text behind how_to, one line each.',\n annotations: { readOnlyHint: true },\n },\n async () => text(listGuides()),\n)\n\nserver.registerTool(\n 'read_guide',\n {\n title: 'Read a guide',\n description:\n 'The complete guide for one topic, as published at rsc-kit.dev — routing, forms, server-actions, validation, metadata, testing, deployment and the rest. Use it when how_to is not enough or names something it does not explain.',\n inputSchema: SLUG_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ slug }: { slug: string }) => text(readGuide(slug))) as never,\n)\n\nserver.registerTool(\n 'search_guides',\n {\n title: 'Search the guides',\n description: 'Every line in the guides that mentions a word or phrase, with the guide it is in. Use it to find which guide covers something before reading it.',\n inputSchema: PHRASE_ARG,\n annotations: { readOnlyHint: true },\n },\n (async ({ phrase }: { phrase: string }) => text(searchGuides(phrase))) as never,\n)\n\nawait server.connect(new StdioServerTransport())\n"]}
package/dist/recipes.js CHANGED
@@ -214,6 +214,18 @@ export const searchParams = z.object({ page: z.coerce.number().int().min(1).defa
214
214
  Values arrive parsed and typed — \`?page=3\` is the number 3, a missing one is
215
215
  the default. Never hand-parse \`Number(searchParams.get('page'))\`.
216
216
 
217
+ The same schema types every LINK to that page. Write search params as an
218
+ object, never as a string:
219
+
220
+ \`\`\`tsx
221
+ <Link href="/search" search={{ q: 'shoes', page: 2 }}>…</Link> // typed by the page's schema
222
+ visit(href('/search', { q: 'shoes' })) // same check, as a string
223
+ \`\`\`
224
+
225
+ A key the page never reads, or a number written as text, does not compile;
226
+ a key the page requires is required on the link. A page with no schema takes
227
+ any scalars. Do NOT build \`?q=\${q}\` by hand when the page has a schema.
228
+
217
229
  **Api route bodies** the same way:
218
230
 
219
231
  \`\`\`ts
@@ -267,14 +279,20 @@ schema does not have is a compile error:
267
279
 
268
280
  \`\`\`ts
269
281
  .handler(async ({ input, fieldErrors }) => {
270
- if (!account) fieldErrors({ email: 'Account not found' })
282
+ if (!account) return fieldErrors({ email: 'Account not found' })
271
283
  })
272
284
  \`\`\`
273
285
 
274
- It throws, so nothing after it runs. It lands in validationErrors on that
275
- field, the same place a schema refusal does. This is next-safe-action's
276
- returnValidationErrors with no schema argument, no _errors nesting and no
277
- return to forget.
286
+ WRITE return fieldErrors(...). It throws either way, but TypeScript cannot see
287
+ a never-return through a destructured argument, so without the return the
288
+ value you checked stays possibly-undefined on the next line. It lands in
289
+ validationErrors on that field, the same place a schema refusal does. This is
290
+ next-safe-action's returnValidationErrors with no schema argument and no
291
+ _errors nesting.
292
+
293
+ A plain "use server" function with no action client imports the same thing,
294
+ untyped, from '@rsc-kit/core/action' - the engine converts the throw into the
295
+ returned { validationErrors } on the way out. Same rule: return fieldErrors(...).
278
296
 
279
297
  The point is not convenience. An action cannot be added without the check,
280
298
  because there is no other constructor to reach for.
@@ -666,6 +684,39 @@ import fraunces from '@fontsource-variable/fraunces/files/fraunces-latin-full-no
666
684
  needs; preloading all of them defeats the subsetting.
667
685
 
668
686
  Do NOT reach for next/font, @next/font or a Google Fonts link tag.`,
687
+ },
688
+ {
689
+ topic: 'images',
690
+ summary: 'Responsive images with no optimizer - unpic for a CDN, imagetools for files in the repo',
691
+ body: `There is NO image component and NO image server. Do not add next/image or
692
+ write an optimizer route. next/image is a srcset-writing component plus a
693
+ resize-on-request process; the first is a library, the second belongs to the
694
+ CDN.
695
+
696
+ An image on a CDN (Cloudinary, imgix, Cloudflare Images, Bunny, Vercel,
697
+ Netlify, ...): @unpic/react. Plain component, works in a server component,
698
+ ships no javascript, detects the CDN from the url:
699
+
700
+ \`\`\`tsx
701
+ import { Image } from '@unpic/react'
702
+
703
+ <Image src="https://res.cloudinary.com/demo/image/upload/sample.jpg" layout="constrained" width={800} height={600} alt="..." />
704
+ \`\`\`
705
+
706
+ A file in the repo, a handful of them: vite-imagetools, resized ONCE at build
707
+ time. Add imagetools() to the vite plugins, then:
708
+
709
+ \`\`\`tsx
710
+ import hero from '../hero.png?w=400;800;1200&format=webp&as=srcset'
711
+ import heroSrc from '../hero.png?w=800&format=webp'
712
+
713
+ <img srcSet={hero} src={heroSrc} sizes="(min-width: 800px) 800px, 100vw" width={800} height={600} alt="..." />
714
+ \`\`\`
715
+
716
+ Hundreds of files in the repo: that is a CDN's job; move them and use unpic.
717
+ An icon or a logo: a plain <img>, or inline the svg.
718
+
719
+ Full guide: read_guide({ slug: 'images' }).`,
669
720
  },
670
721
  {
671
722
  topic: 'scripts',
@@ -736,7 +787,31 @@ the rest do not. This is where a guard that never ran or a 404 that came back
736
787
 
737
788
  **What still needs a browser:** a server action called OVER THE WIRE (the id is
738
789
  React's and private), hydration, navigation. Playwright against vite preview.
739
- That limit is narrower than Next's: the action's logic is a unit test here.`,
790
+ That limit is narrower than Next's: the action's logic is a unit test here.
791
+
792
+ **What to write when you add something.** Before running check, not after:
793
+
794
+ - A guarded route (middleware.ts, or a page reading the session): a stranger
795
+ is turned away, and someone signed in gets 200.
796
+ \`\`\`ts
797
+ expect((await app.fetch('/admin', { redirect: 'manual' })).status).toBe(302)
798
+ expect((await app.fetch('/admin', { headers: { Cookie: 'session=ada' } })).status).toBe(200)
799
+ \`\`\`
800
+ - An action: its refusal, by calling it. Bad input answers validationErrors;
801
+ a stranger answers serverError (or throws ServerAuthenticationError if you
802
+ built it without the client).
803
+ \`\`\`ts
804
+ expect((await createPost({ title: '' })).validationErrors).toBeDefined()
805
+ \`\`\`
806
+ - An action that takes an id: someone else's id is refused. This is the IDOR
807
+ test and the one most often missing.
808
+ - A query: the shape of its answer, and what a filter changes.
809
+ - An api route: status, content-type, and the 4xx it answers to a bad body.
810
+ - A page that should stay static: assert on the build report - no test, a CI
811
+ check that build-report.json still says frozen for it.
812
+
813
+ Do NOT start a dev server, spawn a process or pick a port in a test. Do NOT
814
+ add a second runner. The one in tests/ goes through the real build already.`,
740
815
  },
741
816
  ];
742
817
  /** Every topic, with one line each — what a caller reads before choosing. */