@sdxc/kit 2026.10.24 → 2026.10.26

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 (82) hide show
  1. package/README.md +28 -15
  2. package/changelog.jsonl +125 -4
  3. package/dist/architecture/graph.d.ts +16 -3
  4. package/dist/architecture/graph.js +37 -19
  5. package/dist/architecture/layers.d.ts +10 -3
  6. package/dist/architecture/layers.js +38 -9
  7. package/dist/commands/destroy.d.ts +1 -1
  8. package/dist/commands/make.d.ts +5 -5
  9. package/dist/commands/make.js +11 -8
  10. package/dist/commands/scaffold.d.ts +1 -1
  11. package/dist/contract.d.ts +3 -3
  12. package/dist/doctor/checks.d.ts +2 -2
  13. package/dist/doctor/checks.js +14 -2
  14. package/dist/doctor/constant-names.d.ts +17 -0
  15. package/dist/doctor/constant-names.js +106 -0
  16. package/dist/doctor/dependencies.d.ts +3 -3
  17. package/dist/doctor/dependencies.js +3 -3
  18. package/dist/doctor/fan-out.d.ts +3 -2
  19. package/dist/doctor/fan-out.js +4 -3
  20. package/dist/doctor/fetch-param.d.ts +15 -0
  21. package/dist/doctor/fetch-param.js +37 -0
  22. package/dist/doctor/files.d.ts +2 -0
  23. package/dist/doctor/files.js +4 -0
  24. package/dist/doctor/local-const.d.ts +15 -0
  25. package/dist/doctor/local-const.js +54 -0
  26. package/dist/doctor/logger.d.ts +15 -0
  27. package/dist/doctor/logger.js +41 -0
  28. package/dist/doctor/orphans.d.ts +3 -3
  29. package/dist/doctor/orphans.js +33 -7
  30. package/dist/doctor/process-env.d.ts +15 -0
  31. package/dist/doctor/process-env.js +39 -0
  32. package/dist/doctor/project.js +17 -13
  33. package/dist/doctor/result-throws.d.ts +5 -4
  34. package/dist/doctor/result-throws.js +6 -5
  35. package/dist/doctor/source-rule.d.ts +35 -0
  36. package/dist/doctor/source-rule.js +52 -0
  37. package/dist/doctor/stack-imports.d.ts +15 -0
  38. package/dist/doctor/stack-imports.js +60 -0
  39. package/dist/doctor/syntax.d.ts +31 -0
  40. package/dist/doctor/syntax.js +56 -0
  41. package/dist/make/binding.d.ts +13 -8
  42. package/dist/make/binding.js +96 -64
  43. package/dist/make/from-model.js +2 -7
  44. package/dist/make/index.js +2 -7
  45. package/dist/package-manager.d.ts +6 -0
  46. package/dist/package-manager.js +25 -2
  47. package/dist/scaffold/index.js +25 -19
  48. package/dist/ui/commands.js +2 -5
  49. package/dist/ui/registry.d.ts +2 -2
  50. package/dist/ui/registry.js +1 -1
  51. package/dist/upgrade/changelog.d.ts +2 -0
  52. package/dist/upgrade/changelog.js +2 -0
  53. package/dist/upgrade/project.d.ts +2 -2
  54. package/dist/upgrade/prompt.d.ts +3 -2
  55. package/dist/upgrade/prompt.js +43 -2
  56. package/package.json +5 -5
  57. package/registry/ui/youtube-embed.json +3 -3
  58. package/stubs/scaffold.test-mcp.stub +5 -1
  59. package/templates/app/AGENTS.md +3 -1
  60. package/templates/app/app/commands/db/fresh.ts +20 -13
  61. package/templates/app/app/commands/db/migrate.ts +42 -32
  62. package/templates/app/app/http/controllers/api/openapi.test.ts +29 -0
  63. package/templates/app/app/http/controllers/api/openapi.tsx +8 -2
  64. package/templates/app/app/http/controllers/health.test.ts +35 -0
  65. package/templates/app/app/http/controllers/health.ts +16 -0
  66. package/templates/app/app/http/controllers/mcp.test.ts +16 -0
  67. package/templates/app/app/http/middleware/access.ts +6 -3
  68. package/templates/app/app/http/middleware/page.ts +3 -4
  69. package/templates/app/app/http/middleware/server-timing.test.ts +1 -1
  70. package/templates/app/app/initializers/database.test.ts +6 -1
  71. package/templates/app/app/initializers/health.ts +17 -0
  72. package/templates/app/app/initializers/openapi.ts +5 -4
  73. package/templates/app/app/initializers/router.test.ts +1 -1
  74. package/templates/app/app/initializers/router.tsx +5 -6
  75. package/templates/app/app/test/cloudflare-workers.test.ts +27 -0
  76. package/templates/app/app/test/cloudflare-workers.ts +17 -4
  77. package/templates/app/app/test/database.ts +33 -0
  78. package/templates/app/app/test/mcp.ts +96 -0
  79. package/templates/app/package.json +1 -0
  80. package/templates/app/resources/layouts/document.tsx +2 -3
  81. package/templates/app/routes/api.ts +17 -7
  82. package/templates/app/app/http/controllers/api/health.tsx +0 -15
@@ -15,12 +15,12 @@ import { missingDependencies } from "../dependencies.js";
15
15
  import { unifiedDiff } from "../diff.js";
16
16
  import { formatFiles } from "../format.js";
17
17
  import { declare, declaresAbilities } from "../make/declare.js";
18
+ import { ensureImport } from "../make/imports.js";
18
19
  import { SCAFFOLD_PIECES } from "../make/kinds.js";
19
20
  import { chainFolder, nextMigrationFile } from "../make/migrations.js";
20
21
  import { parseName } from "../make/names.js";
21
22
  import { loadStub, renderStub } from "../make/stubs.js";
22
- import { lockFileAtOrAbove, packageManager } from "../package-manager.js";
23
- import { readManifest } from "../upgrade/project.js";
23
+ import { projectPackageManager } from "../package-manager.js";
24
24
  import { parseFields, pluralize } from "./fields.js";
25
25
  import { apiOperationNames, apiOperations, flagProperties, jsonProperties, localeBlock, placeholders, } from "./render.js";
26
26
  /** The endpoints `--api` writes, in the order the contract declares them. */
@@ -147,11 +147,7 @@ export async function scaffold(ctx, project, packageRoot, input) {
147
147
  ctx.stdout(`Edited ${edit.path}\n`);
148
148
  }
149
149
  if (dependencies.data !== null) {
150
- let read = await readManifest(root);
151
- let manager = await packageManager({
152
- declared: isFailure(read) ? undefined : read.data.manifest.packageManager,
153
- findLockFile: lockFileAtOrAbove(root),
154
- });
150
+ let manager = await projectPackageManager(root);
155
151
  let added = dependencies.data.added.map(({ name, version }) => `${name}@${version}`);
156
152
  ctx.stdout(`Added ${added.join(", ")} to package.json; run ${manager.install.join(" ")}\n`);
157
153
  }
@@ -500,8 +496,8 @@ async function stageDeclarations(root, requests, planned) {
500
496
  /**
501
497
  * `edits` with the resource's OpenAPI operations appended to `routes/api.ts`, after the routes
502
498
  * the staged declarations added, and added to the document `app/initializers/openapi.ts` builds.
503
- * A file laid out otherwise, such as one with no `@sdxc/json-schema` import, gets the code
504
- * printed for the user to place instead.
499
+ * A contract missing `@sdxc/json-schema` gets the import; one laid out otherwise, with no
500
+ * `defineOperation` or default export, gets the code printed for the user to place instead.
505
501
  */
506
502
  async function operationEdits(root, resource, edits) {
507
503
  let result = [...edits];
@@ -528,18 +524,18 @@ async function operationEdits(root, resource, edits) {
528
524
  let contract = `routes/${API_CONTRACT}.ts`;
529
525
  let names = apiOperationNames(resource);
530
526
  let source = await current(contract);
531
- let locals = source === null ? null : operationLocals(source);
532
- let code = apiOperations(resource, locals ?? { s: "s", defineOperation: "defineOperation", routes: "ROUTES" });
533
- if (source === null || locals === null) {
527
+ let operations = source === null ? null : operationLocals(contract, source);
528
+ let code = apiOperations(resource, operations?.locals ?? { s: "s", defineOperation: "defineOperation", routes: "ROUTES" });
529
+ if (operations === null) {
534
530
  manual.push({
535
531
  path: contract,
536
- reason: `${contract} does not import @sdxc/json-schema, defineOperation and a default export the operations can use`,
532
+ reason: `${contract} does not import defineOperation and a default export the operations can use`,
537
533
  instructions: `At the end of ${contract}:
538
534
  ${code}`,
539
535
  });
540
536
  }
541
537
  else {
542
- await write(contract, `${source.trimEnd()}
538
+ await write(contract, `${operations.source.trimEnd()}
543
539
 
544
540
  ${code}
545
541
  `);
@@ -560,16 +556,26 @@ ${code}
560
556
  }
561
557
  /**
562
558
  * The names `source` imports `@sdxc/json-schema`'s namespace, `defineOperation` and its own
563
- * default export under, or `null` when it lacks one of them.
559
+ * default export under, with `source` importing the namespace as `s` when it lacked it, or
560
+ * `null` when it lacks `defineOperation` or the default export.
564
561
  */
565
- function operationLocals(source) {
566
- let s = /import \* as (\w+) from "@sdxc\/json-schema";/.exec(source)?.[1];
562
+ function operationLocals(filename, source) {
567
563
  let imported = /import \{([^}]*)\} from "@sdxc\/openapi";/.exec(source)?.[1] ?? "";
568
564
  let defineOperation = /\bdefineOperation(?:\s+as\s+(\w+))?\b/.exec(imported);
569
565
  let routes = /export default (\w+);/.exec(source)?.[1];
570
- if (s === undefined || defineOperation === null || routes === undefined)
566
+ if (defineOperation === null || routes === undefined)
567
+ return null;
568
+ let schema = ensureImport(filename, source, { kind: "namespace" }, (specifier) => specifier === "@sdxc/json-schema", "@sdxc/json-schema", "s");
569
+ if (isFailure(schema))
571
570
  return null;
572
- return { s, defineOperation: defineOperation[1] ?? "defineOperation", routes };
571
+ return {
572
+ source: schema.data.source,
573
+ locals: {
574
+ s: schema.data.local,
575
+ defineOperation: defineOperation[1] ?? "defineOperation",
576
+ routes,
577
+ },
578
+ };
573
579
  }
574
580
  /**
575
581
  * `source` with `names` imported from the API contract and passed to its document's `.add(…)`,
@@ -15,7 +15,7 @@ import { missingDependencies } from "../dependencies.js";
15
15
  import { unifiedDiff } from "../diff.js";
16
16
  import { formatFiles } from "../format.js";
17
17
  import { readLock, removeUIEntry, renderLock, setUIEntry, uiEntries, uiEntry, writeLock, } from "../lock.js";
18
- import { lockFileAtOrAbove, packageManager } from "../package-manager.js";
18
+ import { projectPackageManager } from "../package-manager.js";
19
19
  import { copyPath, pointAtCopies, pointBack, projectSources, readProjectFile } from "./imports.js";
20
20
  import { readLayout } from "./layout.js";
21
21
  import { readRegistry, withDependencies } from "./registry.js";
@@ -343,10 +343,7 @@ async function listImportedPackages(root, plan) {
343
343
  if (edit.data === null)
344
344
  return success(undefined);
345
345
  plan.files.set(edit.data.path, { before: edit.data.before, after: edit.data.after });
346
- let manager = await packageManager({
347
- declared: undefined,
348
- findLockFile: lockFileAtOrAbove(root),
349
- });
346
+ let manager = await projectPackageManager(root);
350
347
  let added = edit.data.added.map(({ name, version }) => `${name}@${version}`).join(", ");
351
348
  plan.report.push(`Added ${added} to package.json; run ${manager.install.join(" ")}`);
352
349
  return success(undefined);
@@ -18,11 +18,11 @@ export declare const REGISTRY_ENTRY: s.Schema<{
18
18
  path: string;
19
19
  content: string;
20
20
  };
21
- exports: string[];
22
21
  test: {
23
22
  path: string;
24
23
  content: string;
25
24
  } | null;
25
+ exports: string[];
26
26
  changedIn: string;
27
27
  }, {
28
28
  name: string;
@@ -31,11 +31,11 @@ export declare const REGISTRY_ENTRY: s.Schema<{
31
31
  path: string;
32
32
  content: string;
33
33
  };
34
- exports: string[];
35
34
  test: {
36
35
  path: string;
37
36
  content: string;
38
37
  } | null;
38
+ exports: string[];
39
39
  changedIn: string;
40
40
  }>;
41
41
  /** A component as the installed release ships it. */
@@ -15,7 +15,7 @@ import { failure, isFailure, success, wrap } from "@sdxc/result";
15
15
  export const REGISTRY_DIR = "registry/ui";
16
16
  /** A file the registry ships, named as its copy is named in the app: one path segment. */
17
17
  const REGISTRY_FILE = s.object({
18
- path: s.string().pipe(checks.pattern(/^[a-z0-9][a-z0-9-]*(?:\.test)?\.tsx?$/)),
18
+ path: s.string().pipe(checks.pattern(/^[a-z0-9][a-z0-9-]*(?:(?:\.browser)?\.test)?\.tsx?$/)),
19
19
  content: s.string(),
20
20
  });
21
21
  /** One `registry/ui/<name>.json`. */
@@ -18,6 +18,7 @@ declare const ENTRY_SCHEMA: s.Schema<{
18
18
  release: string;
19
19
  package: string;
20
20
  breaking: boolean;
21
+ correctedIn?: string | undefined;
21
22
  }, {
22
23
  type: string;
23
24
  title: string;
@@ -25,6 +26,7 @@ declare const ENTRY_SCHEMA: s.Schema<{
25
26
  release: string;
26
27
  package: string;
27
28
  breaking: boolean;
29
+ correctedIn?: string | undefined;
28
30
  }>;
29
31
  /** One commit's note as it applies to one package in one release. */
30
32
  export type ChangelogEntry = s.InferOutput<typeof ENTRY_SCHEMA>;
@@ -22,6 +22,8 @@ const ENTRY_SCHEMA = s.object({
22
22
  breaking: s.boolean(),
23
23
  title: s.string(),
24
24
  body: s.string(),
25
+ /** The release whose `Release-Note-For` correction replaced `body`; absent on an uncorrected note. */
26
+ correctedIn: s.optional(s.string()),
25
27
  });
26
28
  /**
27
29
  * Every entry of the changelog in the `@sdxc/kit` package at `packageRoot`. A missing file, a line
@@ -12,15 +12,15 @@ declare const MANIFEST_SCHEMA: s.Schema<{
12
12
  name?: string | undefined;
13
13
  dependencies?: Record<string, string> | undefined;
14
14
  devDependencies?: Record<string, string> | undefined;
15
- optionalDependencies?: Record<string, string> | undefined;
16
15
  packageManager?: string | undefined;
16
+ optionalDependencies?: Record<string, string> | undefined;
17
17
  scripts?: Record<string, string> | undefined;
18
18
  }, {
19
19
  name?: string | undefined;
20
20
  dependencies?: Record<string, string> | undefined;
21
21
  devDependencies?: Record<string, string> | undefined;
22
- optionalDependencies?: Record<string, string> | undefined;
23
22
  packageManager?: string | undefined;
23
+ optionalDependencies?: Record<string, string> | undefined;
24
24
  scripts?: Record<string, string> | undefined;
25
25
  }>;
26
26
  /** The project's `package.json` fields the upgrade reads. */
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The prompt `sdxc upgrade` hands an AI agent: the release notes of the packages the project
3
- * imports, for every release it moved across, breaking changes first, with the components to
4
- * refresh, the commands that verify the edit, and where each package is documented.
3
+ * imports, for every release it moved across, breaking changes first, then the corrections those
4
+ * releases made to notes it already had, the components to refresh, the commands that verify the
5
+ * edit, and where each package is documented.
5
6
  *
6
7
  * @author [Sergio Xalambrí](https://sergiodxa.com)
7
8
  * @copyright Sergio Xalambrí 2026
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The prompt `sdxc upgrade` hands an AI agent: the release notes of the packages the project
3
- * imports, for every release it moved across, breaking changes first, with the components to
4
- * refresh, the commands that verify the edit, and where each package is documented.
3
+ * imports, for every release it moved across, breaking changes first, then the corrections those
4
+ * releases made to notes it already had, the components to refresh, the commands that verify the
5
+ * edit, and where each package is documented.
5
6
  *
6
7
  * @author [Sergio Xalambrí](https://sergiodxa.com)
7
8
  * @copyright Sergio Xalambrí 2026
@@ -44,6 +45,7 @@ export function renderPrompt(input) {
44
45
  let breaking = relevant.filter((entry) => entry.breaking);
45
46
  let features = relevant.filter((entry) => !entry.breaking && entry.type === "feat");
46
47
  let fixes = relevant.filter((entry) => !entry.breaking && FIX_TYPES.has(entry.type));
48
+ let corrected = correctedEntries(input);
47
49
  let sections = [
48
50
  [
49
51
  from === input.to
@@ -68,6 +70,8 @@ export function renderPrompt(input) {
68
70
  sections.push(entrySection("Features", features));
69
71
  if (fixes.length > 0)
70
72
  sections.push(entrySection("Fixes", fixes));
73
+ if (corrected.length > 0)
74
+ sections.push(correctedSection(corrected));
71
75
  let older = olderReleases(input);
72
76
  if (older !== null)
73
77
  sections.push(older);
@@ -246,6 +250,43 @@ function earliestStart(input) {
246
250
  }
247
251
  return earliest;
248
252
  }
253
+ /**
254
+ * The imported packages' notes from releases the project already had whose correction shipped
255
+ * in a release it moves across, so a changed migration step reaches a project past the original.
256
+ * Notes the prompt leaves to the GitHub Releases stay left out once corrected.
257
+ */
258
+ function correctedEntries(input) {
259
+ let imported = new Set(input.packages);
260
+ let since = input.since ?? new Map();
261
+ return input.entries
262
+ .filter((entry) => {
263
+ let start = since.get(entry.package) ?? input.from;
264
+ return (entry.correctedIn !== undefined &&
265
+ imported.has(entry.package) &&
266
+ (entry.breaking || entry.type === "feat" || FIX_TYPES.has(entry.type)) &&
267
+ compare(entry.release, start) <= 0 &&
268
+ compare(entry.correctedIn, start) > 0 &&
269
+ compare(entry.correctedIn, input.to) <= 0);
270
+ })
271
+ .sort((a, b) => compare(a.release, b.release) || compareText(a.package, b.package));
272
+ }
273
+ /** The corrected notes, each naming the release it shipped in and the one that corrected it. */
274
+ function correctedSection(entries) {
275
+ let blocks = entries.map((entry) => {
276
+ let lines = [
277
+ `### ${entry.package}: ${entry.title}`,
278
+ `Released in ${entry.release}, corrected in ${entry.correctedIn}.`,
279
+ ];
280
+ if (entry.body.trim() !== "")
281
+ lines.push(entry.body.trim());
282
+ return lines.join("\n\n");
283
+ });
284
+ return [
285
+ "## Corrected notes",
286
+ "These notes shipped in releases this project already had, and a later release replaced them. Check the code against each corrected note, and apply any migration step the original note left out or got wrong.",
287
+ ...blocks,
288
+ ].join("\n\n");
289
+ }
249
290
  /** A heading and each entry under its own sub-heading with its full body. */
250
291
  function entrySection(heading, entries) {
251
292
  let blocks = entries.map((entry) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdxc/kit",
3
- "version": "2026.10.24",
3
+ "version": "2026.10.26",
4
4
  "description": "The sdxc command line: start a Remix v3 app, generate its files, copy UI components into it and upgrade it",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -16,12 +16,12 @@
16
16
  "dependencies": {
17
17
  "@sdxc/cli": "2026.10.24",
18
18
  "@sdxc/codemod": "2026.10.23",
19
- "@sdxc/cron": "2026.10.23",
20
- "@sdxc/diagram": "2026.10.24",
19
+ "@sdxc/cron": "2026.10.25",
20
+ "@sdxc/diagram": "2026.10.26",
21
21
  "@sdxc/iife": "2026.10.23",
22
22
  "@sdxc/json-schema": "2026.10.24",
23
23
  "@sdxc/jsonc": "2026.10.16",
24
- "@sdxc/jsonl": "2026.10.16",
24
+ "@sdxc/jsonl": "2026.10.25",
25
25
  "@sdxc/result": "2026.10.13",
26
26
  "@sdxc/semver": "2026.10.13",
27
27
  "oxc-parser": "^0.154.0"
@@ -29,7 +29,7 @@
29
29
  "peerDependencies": {
30
30
  "remix": "3.1.0"
31
31
  },
32
- "gitHead": "f9db0f8f1f51a256e74b94b0f4b1db4be9880370",
32
+ "gitHead": "ff18988bd00de6200766dbc77367257277979566",
33
33
  "publishConfig": {
34
34
  "access": "public"
35
35
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "youtube-embed",
3
- "changedIn": "2026.10.14",
3
+ "changedIn": "2026.10.25",
4
4
  "dependencies": [],
5
5
  "exports": [
6
6
  "YouTubeEmbed"
@@ -10,7 +10,7 @@
10
10
  "content": "/**\n * A YouTube player sized to its container: a 16:9 `<iframe>` served from YouTube's\n * privacy-enhanced host, so a visitor receives no YouTube cookies until they press play,\n * and lazy-loaded so a video below the fold costs nothing until it scrolls into view.\n *\n * @author [Sergio Xalambrí](https://sergiodxa.com)\n * @copyright Sergio Xalambrí 2026\n */\n\nimport type { Handle, Props as TagProps } from \"remix/component\";\n\nimport { border } from \"@sdxc/u/color\";\nimport { rounded } from \"@sdxc/u/effects\";\nimport { block } from \"@sdxc/u/layout\";\nimport { aspect, is } from \"@sdxc/u/size\";\n\n/** The host every player loads from; a page's `frame-src` has to allow it. */\nconst EMBED_ORIGIN = \"https://www.youtube-nocookie.com\";\n\n/** Loading strategy {@link YouTubeEmbed} falls back to when `loading` is omitted. */\nconst DEFAULT_LOADING: YouTubeEmbed.Props[\"loading\"] = \"lazy\";\n\n/** The player features YouTube asks an embedding page to delegate. */\nconst ALLOWED_FEATURES =\n\t\"accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\";\n\n/**\n * Prop types for {@link YouTubeEmbed}.\n */\nexport namespace YouTubeEmbed {\n\t/**\n\t * Props accepted by {@link YouTubeEmbed}.\n\t */\n\texport interface Props extends Omit<\n\t\tTagProps<\"iframe\">,\n\t\t\"src\" | \"title\" | \"allow\" | \"referrerpolicy\" | \"referrerPolicy\"\n\t> {\n\t\t/** The eleven-character id from the video's `watch?v=` or `youtu.be/` URL. */\n\t\tvideoId: string;\n\t\t/** Seconds into the video the player starts at; zero or less starts at the beginning. */\n\t\tstart?: number;\n\t\t/** The frame's accessible name, announced before a reader enters the player. */\n\t\ttitle: string;\n\t}\n}\n\n/**\n * Renders the player filling its container's inline axis at 16:9. The frame always sends\n * the embedding page's origin as referrer, without which YouTube refuses to play.\n *\n * @param handle Runtime handle carrying the host `<iframe>`'s props.\n * @returns The render function producing the player's markup.\n * @example <YouTubeEmbed videoId=\"dQw4w9WgXcQ\" title={t(\"video.title\")} />\n * @example <YouTubeEmbed videoId=\"dQw4w9WgXcQ\" start={90} title={t(\"video.title\")} />\n */\nexport function YouTubeEmbed(handle: Handle<YouTubeEmbed.Props>) {\n\treturn () => {\n\t\tlet { videoId, start, title, loading, mix, ...rest } = handle.props;\n\t\tlet src = new URL(`/embed/${encodeURIComponent(videoId)}`, EMBED_ORIGIN);\n\t\tif (start !== undefined && start >= 1) src.searchParams.set(\"start\", String(Math.floor(start)));\n\n\t\treturn (\n\t\t\t<iframe\n\t\t\t\t{...rest}\n\t\t\t\tdata-slot=\"youtube-embed\"\n\t\t\t\tsrc={src.href}\n\t\t\t\ttitle={title}\n\t\t\t\tloading={loading ?? DEFAULT_LOADING}\n\t\t\t\treferrerpolicy=\"strict-origin-when-cross-origin\"\n\t\t\t\tallow={ALLOWED_FEATURES}\n\t\t\t\tallowFullScreen\n\t\t\t\tmix={[block(), is(\"full\"), aspect(\"video\"), border(\"none\"), rounded(\"lg\"), mix]}\n\t\t\t/>\n\t\t);\n\t};\n}\n"
11
11
  },
12
12
  "test": {
13
- "path": "youtube-embed.test.tsx",
14
- "content": "// @vitest-environment happy-dom\n\n/**\n * Tests the player's frame: the privacy-enhanced embed URL with its start time, the\n * consumer's accessible name, and the attributes YouTube needs before it plays.\n *\n * @author [Sergio Xalambrí](https://sergiodxa.com)\n * @copyright Sergio Xalambrí 2026\n */\n\nimport type { RemixNode } from \"remix/component\";\n\nimport { renderToString } from \"remix/component/server\";\nimport { describe, expect, test } from \"vitest\";\n\nimport { YouTubeEmbed } from \"@sdxc/ui/youtube-embed\";\n\n/** The rendered `<iframe>`, parsed so a test reads attributes rather than matching strings. */\nasync function renderFrame(node: RemixNode) {\n\tlet template = document.createElement(\"template\");\n\ttemplate.innerHTML = await renderToString(node);\n\tlet frame = template.content.querySelector(\"iframe\");\n\tif (!frame) throw new Error(\"The player rendered no iframe\");\n\treturn frame;\n}\n\ndescribe(\"YouTubeEmbed\", () => {\n\ttest(\"loads the video from the privacy-enhanced host under the consumer's title\", async () => {\n\t\tlet frame = await renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" title=\"The Remix Way\" />);\n\n\t\texpect(frame.getAttribute(\"src\")).toBe(\"https://www.youtube-nocookie.com/embed/o07u1oKE6VA\");\n\t\texpect(frame.getAttribute(\"title\")).toBe(\"The Remix Way\");\n\t\texpect(frame.getAttribute(\"data-slot\")).toBe(\"youtube-embed\");\n\t});\n\n\ttest(\"starts at whole seconds, and at the beginning for a start below one\", async () => {\n\t\tlet later = await renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" start={905.6} title=\"\" />);\n\t\tlet zero = await renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" start={0} title=\"\" />);\n\n\t\texpect(later.getAttribute(\"src\")).toBe(\n\t\t\t\"https://www.youtube-nocookie.com/embed/o07u1oKE6VA?start=905\",\n\t\t);\n\t\texpect(zero.getAttribute(\"src\")).toBe(\"https://www.youtube-nocookie.com/embed/o07u1oKE6VA\");\n\t});\n\n\ttest(\"sends the page's origin as referrer, which YouTube requires to play\", async () => {\n\t\tlet frame = await renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" title=\"\" />);\n\n\t\texpect(frame.getAttribute(\"referrerpolicy\")).toBe(\"strict-origin-when-cross-origin\");\n\t\texpect(frame.hasAttribute(\"allowfullscreen\")).toBe(true);\n\t});\n\n\ttest(\"loads lazily unless the consumer asks for an eager player\", async () => {\n\t\tlet lazy = await renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" title=\"\" />);\n\t\tlet eager = await renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" title=\"\" loading=\"eager\" />);\n\n\t\texpect(lazy.getAttribute(\"loading\")).toBe(\"lazy\");\n\t\texpect(eager.getAttribute(\"loading\")).toBe(\"eager\");\n\t});\n});\n"
13
+ "path": "youtube-embed.browser.test.tsx",
14
+ "content": "/**\n * Tests the player's frame: the privacy-enhanced embed URL with its start time, the\n * consumer's accessible name, and the attributes YouTube needs before it plays.\n *\n * @author [Sergio Xalambrí](https://sergiodxa.com)\n * @copyright Sergio Xalambrí 2026\n */\n\nimport type { RemixNode } from \"remix/component\";\n\nimport { render } from \"remix/component/test\";\nimport { describe, expect, test } from \"vitest\";\n\nimport { YouTubeEmbed } from \"@sdxc/ui/youtube-embed\";\n\n/**\n * The player's `<iframe>`, mounted into a container outside the document: a detached frame\n * keeps its attributes and loads nothing, so no test reaches YouTube.\n */\nfunction renderFrame(node: RemixNode): HTMLIFrameElement {\n\tlet frame = render(node, { container: document.createElement(\"div\") }).container.querySelector(\n\t\t\"iframe\",\n\t);\n\tif (!frame) throw new Error(\"The player rendered no iframe\");\n\treturn frame;\n}\n\ndescribe(\"YouTubeEmbed\", () => {\n\ttest(\"loads the video from the privacy-enhanced host under the consumer's title\", () => {\n\t\tlet frame = renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" title=\"The Remix Way\" />);\n\n\t\texpect(frame.getAttribute(\"src\")).toBe(\"https://www.youtube-nocookie.com/embed/o07u1oKE6VA\");\n\t\texpect(frame.getAttribute(\"title\")).toBe(\"The Remix Way\");\n\t\texpect(frame.getAttribute(\"data-slot\")).toBe(\"youtube-embed\");\n\t});\n\n\ttest(\"starts at whole seconds, and at the beginning for a start below one\", () => {\n\t\tlet later = renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" start={905.6} title=\"\" />);\n\t\tlet zero = renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" start={0} title=\"\" />);\n\n\t\texpect(later.getAttribute(\"src\")).toBe(\n\t\t\t\"https://www.youtube-nocookie.com/embed/o07u1oKE6VA?start=905\",\n\t\t);\n\t\texpect(zero.getAttribute(\"src\")).toBe(\"https://www.youtube-nocookie.com/embed/o07u1oKE6VA\");\n\t});\n\n\ttest(\"sends the page's origin as referrer, which YouTube requires to play\", () => {\n\t\tlet frame = renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" title=\"\" />);\n\n\t\texpect(frame.getAttribute(\"referrerpolicy\")).toBe(\"strict-origin-when-cross-origin\");\n\t\texpect(frame.hasAttribute(\"allowfullscreen\")).toBe(true);\n\t});\n\n\ttest(\"loads lazily unless the consumer asks for an eager player\", () => {\n\t\tlet lazy = renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" title=\"\" />);\n\t\tlet eager = renderFrame(<YouTubeEmbed videoId=\"o07u1oKE6VA\" title=\"\" loading=\"eager\" />);\n\n\t\texpect(lazy.getAttribute(\"loading\")).toBe(\"lazy\");\n\t\texpect(eager.getAttribute(\"loading\")).toBe(\"eager\");\n\t});\n});\n"
15
15
  }
16
16
  }
@@ -86,7 +86,11 @@ export async function callTool(
86
86
  }),
87
87
  }),
88
88
  );
89
- let body = (await response.json()) as CallResponse;
89
+ return readCall((await response.json()) as CallResponse);
90
+ }
91
+
92
+ /** What a `tools/call` response says, with a protocol error read as the call's failure. */
93
+ function readCall(body: CallResponse): ToolCall {
90
94
  if (body.error !== undefined) return { text: body.error.message ?? "", isError: true };
91
95
  return { text: body.result?.content?.[0]?.text ?? "", isError: body.result?.isError === true };
92
96
  }
@@ -155,7 +155,9 @@ bun run test # every test, under Vitest
155
155
  ### Testing
156
156
 
157
157
  - Write tests with Vitest, in a `*.test.ts` file beside the module.
158
- - Back database tests with the in-memory D1 from `@sdxc/cloudflare-mocks/sqlite`.
158
+ - Back database tests with the in-memory D1 from `@sdxc/cloudflare-mocks/sqlite`: `migrate()` and
159
+ `factories()` from `app/test/database.ts` apply the migrations and seed rows through the models.
160
+ - Call MCP tools in tests with `callTool()` from `app/test/mcp.ts`, through the app's router.
159
161
  - Mock outbound HTTP with MSW (`setupServer` from `msw/node`).
160
162
  - Add a regression test with every bug fix, one that fails without the fix.
161
163
 
@@ -4,15 +4,33 @@
4
4
  * on the empty tables.
5
5
  */
6
6
 
7
+ import type { AnyCommandContext, CommandResult } from "@sdxc/cli";
8
+
7
9
  import { createCommand, failure, success } from "@sdxc/cli";
8
10
  import { openDatabase } from "@sdxc/cloudflare-mocks/sqlite";
9
11
  import { isFailure } from "@sdxc/result";
10
12
 
13
+ import type { MigrationDatabase } from "~/app/services/migrations";
14
+
11
15
  import commandset from "~/app/commands";
12
16
  import { LOCAL_DATABASE_FILE, PROJECT_ROOT } from "~/app/initializers/local-database";
13
17
  import { runCommand } from "~/app/services/commands";
14
18
  import { applyMigrations, dropTables, readMigrations } from "~/app/services/migrations";
15
19
 
20
+ /** Empties `database` and applies the chain to it, printing each table dropped and migration applied. */
21
+ async function rebuild(
22
+ ctx: AnyCommandContext,
23
+ database: MigrationDatabase,
24
+ ): Promise<CommandResult> {
25
+ let dropped = dropTables(database);
26
+ if (isFailure(dropped)) return dropped;
27
+ ctx.stdout(`Dropped ${dropped.data.length} ${dropped.data.length === 1 ? "table" : "tables"}\n`);
28
+ let applied = applyMigrations(database, await readMigrations(PROJECT_ROOT));
29
+ if (isFailure(applied)) return applied;
30
+ ctx.stdout(applied.data.map((name) => `Applied ${name}\n`).join(""));
31
+ return success();
32
+ }
33
+
16
34
  /** Refuses `--remote`: emptying production has no undo. */
17
35
  export default createCommand(commandset.db.fresh, async (ctx) => {
18
36
  if (ctx.flags.remote) {
@@ -20,18 +38,7 @@ export default createCommand(commandset.db.fresh, async (ctx) => {
20
38
  }
21
39
 
22
40
  let database = openDatabase(LOCAL_DATABASE_FILE);
23
- try {
24
- let dropped = dropTables(database);
25
- if (isFailure(dropped)) return dropped;
26
- ctx.stdout(
27
- `Dropped ${dropped.data.length} ${dropped.data.length === 1 ? "table" : "tables"}\n`,
28
- );
29
- let applied = applyMigrations(database, await readMigrations(PROJECT_ROOT));
30
- if (isFailure(applied)) return applied;
31
- ctx.stdout(applied.data.map((name) => `Applied ${name}\n`).join(""));
32
- } finally {
33
- database.close();
34
- }
35
-
41
+ let rebuilt = await rebuild(ctx, database).finally(() => database.close());
42
+ if (isFailure(rebuilt)) return rebuilt;
36
43
  return ctx.flags.seed ? runCommand(ctx, ["db", "seed"]) : success();
37
44
  });
@@ -4,7 +4,7 @@
4
4
  * against the production database. Safe to run twice: an applied migration is skipped.
5
5
  */
6
6
 
7
- import type { AnyCommandContext } from "@sdxc/cli";
7
+ import type { AnyCommandContext, CommandResult } from "@sdxc/cli";
8
8
  import type { Result } from "@sdxc/result";
9
9
 
10
10
  import { createCommand, success } from "@sdxc/cli";
@@ -28,6 +28,14 @@ const REMOTE_PENDING = s.array(s.object({ Name: s.string() }));
28
28
  // oxlint-disable-next-line no-control-regex -- matching the ESC that starts a color sequence
29
29
  const ANSI = /\u001B\[[0-9;]*m/g;
30
30
 
31
+ /** The migration names `cf d1 migrations list` printed as JSON, or `null` for any other output. */
32
+ function listedNames(printed: string): string[] | null {
33
+ let json = wrap(() => JSON.parse(printed.replace(ANSI, "")) as unknown);
34
+ if (isFailure(json)) return null;
35
+ let parsed = s.parseSafe(REMOTE_PENDING, json.data);
36
+ return parsed.success ? parsed.value.map((row) => row.Name) : null;
37
+ }
38
+
31
39
  /** The migrations the production database lacks, as `cf d1 migrations list` reports them. */
32
40
  async function remotePending(ctx: AnyCommandContext): Promise<Result<string[], Error>> {
33
41
  let listed = await ctx.exec(
@@ -35,43 +43,35 @@ async function remotePending(ctx: AnyCommandContext): Promise<Result<string[], E
35
43
  { cwd: PROJECT_ROOT, stdio: "collect" },
36
44
  );
37
45
  if (isFailure(listed)) return listed;
38
- let printed = listed.data.stdout;
39
- let json = wrap(() => JSON.parse(printed.replace(ANSI, "")) as unknown);
40
- let parsed = isFailure(json) ? undefined : s.parseSafe(REMOTE_PENDING, json.data);
41
- if (parsed === undefined || !parsed.success) {
42
- return failure(new Error(`cf d1 migrations list printed ${printed.trim()}`));
43
- }
44
- return success(parsed.value.map((row) => row.Name));
46
+ let names = listedNames(listed.data.stdout);
47
+ return names === null
48
+ ? failure(new Error(`cf d1 migrations list printed ${listed.data.stdout.trim()}`))
49
+ : success(names);
45
50
  }
46
51
 
47
- /**
48
- * With `--pending`, prints one migration name per line and applies nothing; an up-to-date
49
- * database prints nothing. `sdxc deploy` reads that list to show what production will run.
50
- */
51
- export default createCommand(commandset.db.migrate, async (ctx) => {
52
- if (ctx.flags.remote) {
53
- if (ctx.flags.pending) {
54
- let pending = await remotePending(ctx);
55
- if (isFailure(pending)) return pending;
56
- ctx.stdout(pending.data.map((name) => `${name}\n`).join(""));
57
- return success();
58
- }
59
- let applied = await ctx.exec(
60
- ["cf", "d1", "migrations", "apply", DATABASE_ID, "--dir", MIGRATIONS_DIRECTORY],
61
- { cwd: PROJECT_ROOT },
62
- );
63
- return isFailure(applied) ? applied : success();
52
+ /** Applies, or with `pending` lists, the migrations the production database lacks, through `cf`. */
53
+ async function migrateRemote(ctx: AnyCommandContext, pending: boolean): Promise<CommandResult> {
54
+ if (pending) {
55
+ let names = await remotePending(ctx);
56
+ if (isFailure(names)) return names;
57
+ ctx.stdout(names.data.map((name) => `${name}\n`).join(""));
58
+ return success();
64
59
  }
60
+ let applied = await ctx.exec(
61
+ ["cf", "d1", "migrations", "apply", DATABASE_ID, "--dir", MIGRATIONS_DIRECTORY],
62
+ { cwd: PROJECT_ROOT },
63
+ );
64
+ return isFailure(applied) ? applied : success();
65
+ }
65
66
 
67
+ /** Applies, or with `pending` lists, the migrations the local SQLite file lacks. */
68
+ async function migrateLocal(ctx: AnyCommandContext, pending: boolean): Promise<CommandResult> {
66
69
  let database = openDatabase(LOCAL_DATABASE_FILE);
67
70
  try {
68
71
  let migrations = await readMigrations(PROJECT_ROOT);
69
- if (ctx.flags.pending) {
70
- ctx.stdout(
71
- pendingMigrations(database, migrations)
72
- .map((migration) => `${migration.name}\n`)
73
- .join(""),
74
- );
72
+ if (pending) {
73
+ let names = pendingMigrations(database, migrations).map((migration) => migration.name);
74
+ ctx.stdout(names.map((name) => `${name}\n`).join(""));
75
75
  return success();
76
76
  }
77
77
  let applied = applyMigrations(database, migrations);
@@ -85,4 +85,14 @@ export default createCommand(commandset.db.migrate, async (ctx) => {
85
85
  } finally {
86
86
  database.close();
87
87
  }
88
- });
88
+ }
89
+
90
+ /**
91
+ * With `--pending`, prints one migration name per line and applies nothing; an up-to-date
92
+ * database prints nothing. `sdxc deploy` reads that list to show what production will run.
93
+ */
94
+ export default createCommand(commandset.db.migrate, (ctx) =>
95
+ ctx.flags.remote
96
+ ? migrateRemote(ctx, ctx.flags.pending === true)
97
+ : migrateLocal(ctx, ctx.flags.pending === true),
98
+ );
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `/api/openapi.json`, fetched through the app's router: one document naming the published
3
+ * origin, which a client revalidates by its `ETag`.
4
+ */
5
+
6
+ import { describe, expect, test } from "vitest";
7
+
8
+ import { createWebRouter } from "~/app/initializers/router";
9
+ import { SITE_URL } from "~/config/constants";
10
+
11
+ describe("openapi", () => {
12
+ test("names SITE_URL as the server whatever origin the request reached", async () => {
13
+ let response = await createWebRouter().fetch("http://localhost:5173/api/openapi.json");
14
+
15
+ let document = (await response.json()) as { servers: Array<{ url: string }> };
16
+ expect(document.servers).toEqual([{ url: SITE_URL }]);
17
+ });
18
+
19
+ test("answers a request carrying the document's ETag with 304", async () => {
20
+ let router = createWebRouter();
21
+ let first = await router.fetch("https://example.com/api/openapi.json");
22
+
23
+ let second = await router.fetch("https://example.com/api/openapi.json", {
24
+ headers: { "If-None-Match": first.headers.get("ETag") ?? "" },
25
+ });
26
+
27
+ expect(second.status).toBe(304);
28
+ });
29
+ });
@@ -10,8 +10,14 @@ import api from "~/app/http/middleware/api";
10
10
  import { createApiDocument } from "~/app/initializers/openapi";
11
11
  import routes from "~/routes/api";
12
12
 
13
+ /**
14
+ * Builds the document on the first request and serves that build, with its `ETag`, to every
15
+ * later one for the life of the Worker.
16
+ */
17
+ const serveDocument = openapiHandler(() => createApiDocument().build());
18
+
13
19
  export default createAction(routes.api.openapi, {
14
20
  middleware: api,
15
- /** GET /api/openapi.json, naming the origin the request reached as the API's server. */
16
- handler: (ctx) => openapiHandler(() => createApiDocument(ctx.url.origin).build())(ctx),
21
+ /** GET /api/openapi.json, as JSON or YAML by `Accept` or `?format=`. */
22
+ handler: (ctx) => serveDocument(ctx),
17
23
  });
@@ -0,0 +1,35 @@
1
+ /**
2
+ * `/health`, fetched through the app's router, and the operation the OpenAPI document publishes
3
+ * for it.
4
+ */
5
+
6
+ import { describe, expect, test } from "vitest";
7
+
8
+ import { createWebRouter } from "~/app/initializers/router";
9
+
10
+ import manifest from "../../../package.json" with { type: "json" };
11
+
12
+ describe("health", () => {
13
+ test("reports the database as passing in the application/health+json format", async () => {
14
+ let response = await createWebRouter().fetch("https://example.com/health");
15
+
16
+ expect(response.status).toBe(200);
17
+ expect(response.headers.get("content-type")).toBe("application/health+json");
18
+ expect(await response.json()).toMatchObject({
19
+ status: "pass",
20
+ serviceId: manifest.name,
21
+ checks: { "database:responseTime": [{ componentType: "datastore", status: "pass" }] },
22
+ });
23
+ });
24
+
25
+ test("is documented with the report's schema for both statuses", async () => {
26
+ let response = await createWebRouter().fetch("https://example.com/api/openapi.json");
27
+
28
+ let document = (await response.json()) as {
29
+ paths: Record<string, { get: { responses: Record<string, { content: object }> } }>;
30
+ };
31
+ let responses = document.paths["/health"]?.get.responses;
32
+ expect(Object.keys(responses?.["200"]?.content ?? {})).toEqual(["application/health+json"]);
33
+ expect(Object.keys(responses?.["503"]?.content ?? {})).toEqual(["application/health+json"]);
34
+ });
35
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The health check: every dependency the app reads, probed on each request, so a monitor tells
3
+ * a deploy that serves from one whose database is unreachable.
4
+ */
5
+
6
+ import { createAction } from "remix/router";
7
+
8
+ import api from "~/app/http/middleware/api";
9
+ import { health } from "~/app/initializers/health";
10
+ import routes from "~/routes/api";
11
+
12
+ export default createAction(routes.health, {
13
+ middleware: api,
14
+ /** GET /health, `200` while every critical probe passes and `503` once one fails. */
15
+ handler: (ctx) => health.respond(ctx),
16
+ });