@sdxc/kit 2026.10.16 → 2026.10.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +391 -20
- package/changelog.jsonl +1160 -1035
- package/config.schema.json +47 -1
- package/dist/author.d.ts +36 -0
- package/dist/author.js +107 -0
- package/dist/cli.js +12 -0
- package/dist/commands/create.js +9 -4
- package/dist/commands/deploy.d.ts +23 -0
- package/dist/commands/deploy.js +167 -0
- package/dist/commands/destroy.d.ts +22 -0
- package/dist/commands/destroy.js +92 -0
- package/dist/commands/doctor.d.ts +26 -0
- package/dist/commands/doctor.js +65 -0
- package/dist/commands/initializers.d.ts +16 -0
- package/dist/commands/initializers.js +23 -0
- package/dist/commands/make.d.ts +72 -6
- package/dist/commands/make.js +127 -19
- package/dist/commands/middleware.d.ts +16 -0
- package/dist/commands/middleware.js +21 -0
- package/dist/commands/models.d.ts +18 -0
- package/dist/commands/models.js +29 -0
- package/dist/commands/notes.d.ts +17 -0
- package/dist/commands/notes.js +27 -0
- package/dist/commands/routes.d.ts +25 -0
- package/dist/commands/routes.js +50 -0
- package/dist/commands/run.d.ts +18 -2
- package/dist/commands/run.js +35 -12
- package/dist/commands/scaffold.d.ts +29 -0
- package/dist/commands/scaffold.js +33 -0
- package/dist/commands/schedule.d.ts +16 -0
- package/dist/commands/schedule.js +21 -0
- package/dist/commands/stats.d.ts +16 -0
- package/dist/commands/stats.js +21 -0
- package/dist/commands/ui/update.d.ts +6 -3
- package/dist/commands/ui/update.js +24 -7
- package/dist/commands/upgrade.d.ts +3 -1
- package/dist/commands/upgrade.js +88 -23
- package/dist/config.d.ts +18 -0
- package/dist/config.js +28 -1
- package/dist/contract.d.ts +97 -3
- package/dist/contract.js +360 -26
- package/dist/create/templates.d.ts +8 -1
- package/dist/create/templates.js +26 -2
- package/dist/dependencies.d.ts +4 -1
- package/dist/dependencies.js +13 -1
- package/dist/deploy/plan.d.ts +49 -0
- package/dist/deploy/plan.js +68 -0
- package/dist/destroy.d.ts +40 -0
- package/dist/destroy.js +311 -0
- package/dist/doctor/check.d.ts +71 -0
- package/dist/doctor/check.js +53 -0
- package/dist/doctor/checks.d.ts +23 -0
- package/dist/doctor/checks.js +68 -0
- package/dist/doctor/define.d.ts +59 -0
- package/dist/doctor/define.js +16 -0
- package/dist/doctor/emails.d.ts +18 -0
- package/dist/doctor/emails.js +243 -0
- package/dist/doctor/env.d.ts +26 -0
- package/dist/doctor/env.js +88 -0
- package/dist/doctor/files.d.ts +14 -0
- package/dist/doctor/files.js +34 -0
- package/dist/doctor/fixture.d.ts +23 -0
- package/dist/doctor/fixture.js +46 -0
- package/dist/doctor/install.d.ts +17 -0
- package/dist/doctor/install.js +37 -0
- package/dist/doctor/installed.d.ts +11 -0
- package/dist/doctor/installed.js +79 -0
- package/dist/doctor/layout.d.ts +23 -0
- package/dist/doctor/layout.js +83 -0
- package/dist/doctor/migrations.d.ts +16 -0
- package/dist/doctor/migrations.js +96 -0
- package/dist/doctor/models.d.ts +13 -0
- package/dist/doctor/models.js +69 -0
- package/dist/doctor/pins.d.ts +15 -0
- package/dist/doctor/pins.js +79 -0
- package/dist/doctor/project.d.ts +58 -0
- package/dist/doctor/project.js +261 -0
- package/dist/doctor/remix.d.ts +14 -0
- package/dist/doctor/remix.js +44 -0
- package/dist/doctor/routes.d.ts +11 -0
- package/dist/doctor/routes.js +49 -0
- package/dist/doctor/typegen.d.ts +13 -0
- package/dist/doctor/typegen.js +57 -0
- package/dist/doctor/ui.d.ts +14 -0
- package/dist/doctor/ui.js +51 -0
- package/dist/init.d.ts +5 -3
- package/dist/init.js +15 -7
- package/dist/initializers.d.ts +25 -0
- package/dist/initializers.js +89 -0
- package/dist/lock.d.ts +2 -2
- package/dist/make/actions.d.ts +23 -0
- package/dist/make/actions.js +82 -0
- package/dist/make/declare.d.ts +32 -4
- package/dist/make/declare.js +405 -27
- package/dist/make/email.d.ts +23 -0
- package/dist/make/email.js +111 -0
- package/dist/make/from-fields.d.ts +30 -0
- package/dist/make/from-fields.js +162 -0
- package/dist/make/from-model.d.ts +39 -0
- package/dist/make/from-model.js +161 -0
- package/dist/make/generate.d.ts +16 -5
- package/dist/make/generate.js +43 -14
- package/dist/make/guard.d.ts +35 -0
- package/dist/make/guard.js +73 -0
- package/dist/make/imports.d.ts +6 -0
- package/dist/make/imports.js +19 -0
- package/dist/make/index.d.ts +47 -4
- package/dist/make/index.js +287 -25
- package/dist/make/kinds.d.ts +31 -3
- package/dist/make/kinds.js +82 -9
- package/dist/make/mount.d.ts +25 -0
- package/dist/make/mount.js +135 -0
- package/dist/make/schema-diff.d.ts +58 -0
- package/dist/make/schema-diff.js +609 -0
- package/dist/make/schema.d.ts +76 -0
- package/dist/make/schema.js +206 -0
- package/dist/make/stubs.d.ts +7 -5
- package/dist/make/stubs.js +16 -5
- package/dist/make/test.d.ts +43 -0
- package/dist/make/test.js +149 -0
- package/dist/make/trigger.d.ts +31 -0
- package/dist/make/trigger.js +163 -0
- package/dist/models.d.ts +42 -0
- package/dist/models.js +149 -0
- package/dist/notes.d.ts +28 -0
- package/dist/notes.js +66 -0
- package/dist/reference.d.ts +27 -0
- package/dist/reference.js +103 -0
- package/dist/releases.d.ts +9 -0
- package/dist/releases.js +29 -8
- package/dist/routes/chains.d.ts +34 -0
- package/dist/routes/chains.js +95 -0
- package/dist/routes/filter.d.ts +53 -0
- package/dist/routes/filter.js +147 -0
- package/dist/routes/format.d.ts +23 -0
- package/dist/routes/format.js +123 -0
- package/dist/routes/helpers.d.ts +21 -0
- package/dist/routes/helpers.js +165 -0
- package/dist/routes/index.d.ts +56 -0
- package/dist/routes/index.js +167 -0
- package/dist/routes/modules.d.ts +116 -0
- package/dist/routes/modules.js +235 -0
- package/dist/routes/parse.d.ts +161 -0
- package/dist/routes/parse.js +621 -0
- package/dist/routes/routers.d.ts +69 -0
- package/dist/routes/routers.js +327 -0
- package/dist/scaffold/fields.d.ts +129 -0
- package/dist/scaffold/fields.js +421 -0
- package/dist/scaffold/index.d.ts +37 -0
- package/dist/scaffold/index.js +613 -0
- package/dist/scaffold/render.d.ts +51 -0
- package/dist/scaffold/render.js +332 -0
- package/dist/schedule.d.ts +45 -0
- package/dist/schedule.js +124 -0
- package/dist/stats.d.ts +37 -0
- package/dist/stats.js +126 -0
- package/dist/testing.d.ts +12 -2
- package/dist/testing.js +22 -3
- package/dist/ui/commands.d.ts +10 -3
- package/dist/ui/commands.js +85 -15
- package/dist/ui/registry.d.ts +8 -8
- package/dist/upgrade/agents.d.ts +49 -0
- package/dist/upgrade/agents.js +110 -0
- package/dist/upgrade/changelog.d.ts +2 -2
- package/dist/upgrade/project.d.ts +4 -0
- package/dist/upgrade/project.js +11 -1
- package/dist/upgrade/prompt.d.ts +11 -0
- package/dist/upgrade/prompt.js +50 -7
- package/package.json +6 -4
- package/registry/ui/alert-dialog.json +2 -2
- package/registry/ui/attachment.json +2 -2
- package/registry/ui/calendar.json +2 -2
- package/registry/ui/color-picker.json +2 -2
- package/registry/ui/command.json +2 -2
- package/registry/ui/date-picker.json +2 -2
- package/registry/ui/date-range-picker.json +2 -2
- package/registry/ui/dialog.json +2 -2
- package/registry/ui/file-trigger.json +2 -2
- package/registry/ui/heading-scope.json +2 -2
- package/registry/ui/message-scroller.json +2 -2
- package/registry/ui/number-field.json +2 -2
- package/registry/ui/range-calendar.json +2 -2
- package/registry/ui/resizable.json +2 -2
- package/registry/ui/select.json +2 -2
- package/registry/ui/shared-element.json +2 -2
- package/stubs/command.stub +4 -0
- package/stubs/command.test.stub +3 -0
- package/stubs/controller.api.resource.stub +23 -0
- package/stubs/controller.api.stub +21 -0
- package/stubs/controller.api.test.stub +18 -0
- package/stubs/controller.form.stub +40 -10
- package/stubs/controller.form.test.stub +61 -0
- package/stubs/controller.resource.form.stub +67 -0
- package/stubs/controller.resource.stub +28 -0
- package/stubs/controller.stub +15 -8
- package/stubs/controller.test.stub +3 -0
- package/stubs/email.stub +15 -38
- package/stubs/email.test.stub +12 -7
- package/stubs/factory.stub +4 -1
- package/stubs/initializer.stub +2 -0
- package/stubs/initializer.test.stub +3 -0
- package/stubs/job.cron.stub +4 -0
- package/stubs/job.stub +4 -0
- package/stubs/job.test.stub +3 -0
- package/stubs/mcp.resource.stub +3 -0
- package/stubs/mcp.stub +3 -0
- package/stubs/mcp.test.stub +3 -0
- package/stubs/middleware.stub +6 -1
- package/stubs/middleware.test.stub +3 -0
- package/stubs/model.stub +12 -3
- package/stubs/model.test.stub +3 -0
- package/stubs/policy.test.stub +36 -7
- package/stubs/scaffold.api.create.stub +34 -0
- package/stubs/scaffold.api.create.test.stub +37 -0
- package/stubs/scaffold.api.destroy.stub +34 -0
- package/stubs/scaffold.api.destroy.test.stub +44 -0
- package/stubs/scaffold.api.index.stub +23 -0
- package/stubs/scaffold.api.index.test.stub +31 -0
- package/stubs/scaffold.api.show.stub +27 -0
- package/stubs/scaffold.api.show.test.stub +41 -0
- package/stubs/scaffold.api.update.stub +44 -0
- package/stubs/scaffold.api.update.test.stub +46 -0
- package/stubs/scaffold.command.create.stub +22 -0
- package/stubs/scaffold.command.create.test.stub +30 -0
- package/stubs/scaffold.command.delete.stub +20 -0
- package/stubs/scaffold.command.delete.test.stub +39 -0
- package/stubs/scaffold.command.list.stub +18 -0
- package/stubs/scaffold.command.list.test.stub +31 -0
- package/stubs/scaffold.command.show.stub +19 -0
- package/stubs/scaffold.command.show.test.stub +37 -0
- package/stubs/scaffold.controller.destroy.stub +35 -0
- package/stubs/scaffold.controller.destroy.test.stub +65 -0
- package/stubs/scaffold.controller.edit.stub +97 -0
- package/stubs/scaffold.controller.edit.test.stub +91 -0
- package/stubs/scaffold.controller.index.stub +55 -0
- package/stubs/scaffold.controller.index.test.stub +32 -0
- package/stubs/scaffold.controller.new.stub +70 -0
- package/stubs/scaffold.controller.new.test.stub +81 -0
- package/stubs/scaffold.controller.show.stub +59 -0
- package/stubs/scaffold.controller.show.test.stub +43 -0
- package/stubs/scaffold.factory.stub +16 -0
- package/stubs/scaffold.form.stub +75 -0
- package/stubs/scaffold.mcp.create.stub +24 -0
- package/stubs/scaffold.mcp.create.test.stub +36 -0
- package/stubs/scaffold.mcp.delete.stub +31 -0
- package/stubs/scaffold.mcp.delete.test.stub +43 -0
- package/stubs/scaffold.mcp.get.stub +21 -0
- package/stubs/scaffold.mcp.get.test.stub +31 -0
- package/stubs/scaffold.mcp.list.stub +23 -0
- package/stubs/scaffold.mcp.list.test.stub +25 -0
- package/stubs/scaffold.mcp.update.stub +37 -0
- package/stubs/scaffold.mcp.update.test.stub +40 -0
- package/stubs/scaffold.migration.stub +2 -0
- package/stubs/scaffold.model.stub +35 -0
- package/stubs/scaffold.model.test.stub +25 -0
- package/stubs/scaffold.test-database.stub +33 -0
- package/stubs/scaffold.test-mcp.stub +92 -0
- package/stubs/scaffold.validator.stub +18 -0
- package/stubs/scaffold.validator.test.stub +26 -0
- package/stubs/service.stub +4 -0
- package/stubs/service.test.stub +3 -0
- package/stubs/validator.stub +3 -0
- package/stubs/validator.test.stub +3 -0
- package/templates/app/.env.example +16 -0
- package/templates/app/AGENTS.md +163 -0
- package/templates/app/CLAUDE.md +1 -0
- package/templates/app/README.md +79 -37
- package/templates/app/app/commands/about.test.ts +1 -1
- package/templates/app/app/commands/console.test.ts +26 -0
- package/templates/app/app/commands/console.ts +19 -0
- package/templates/app/app/commands/db/console.ts +6 -0
- package/templates/app/app/commands/db/fresh.test.ts +57 -0
- package/templates/app/app/commands/db/fresh.ts +37 -0
- package/templates/app/app/commands/db/migrate.test.ts +46 -0
- package/templates/app/app/commands/db/migrate.ts +88 -0
- package/templates/app/app/commands/db/prepare.test.ts +39 -0
- package/templates/app/app/commands/db/prepare.ts +35 -0
- package/templates/app/app/commands/db/seed.test.ts +38 -0
- package/templates/app/app/commands/db/seed.ts +26 -0
- package/templates/app/app/commands/deploy.test.ts +34 -0
- package/templates/app/app/commands/deploy.ts +18 -0
- package/templates/app/app/commands/emails/preview.test.tsx +63 -0
- package/templates/app/app/commands/emails/preview.ts +24 -0
- package/templates/app/app/commands/index.ts +72 -1
- package/templates/app/app/commands/typegen.test.ts +17 -0
- package/templates/app/app/commands/typegen.ts +16 -0
- package/templates/app/app/emails/index.ts +10 -0
- package/templates/app/app/http/controllers/api/health.tsx +15 -0
- package/templates/app/app/http/controllers/api/not-found.tsx +16 -0
- package/templates/app/app/http/controllers/api/openapi.tsx +17 -0
- package/templates/app/app/http/controllers/home.tsx +21 -13
- package/templates/app/app/http/controllers/mcp.tsx +16 -0
- package/templates/app/app/http/controllers/not-found.tsx +23 -18
- package/templates/app/app/http/controllers/robots.test.ts +18 -0
- package/templates/app/app/http/controllers/robots.ts +24 -0
- package/templates/app/app/http/controllers/sitemap.test.ts +28 -0
- package/templates/app/app/http/controllers/sitemap.ts +25 -0
- package/templates/app/app/http/middleware/access.test.ts +43 -0
- package/templates/app/app/http/middleware/access.ts +41 -0
- package/templates/app/app/http/middleware/api.ts +19 -0
- package/templates/app/app/http/middleware/page.test.ts +43 -0
- package/templates/app/app/http/middleware/page.ts +51 -0
- package/templates/app/app/http/middleware/server-timing.test.ts +15 -0
- package/templates/app/app/http/middleware/server-timing.ts +42 -0
- package/templates/app/app/initializers/assets.ts +1 -1
- package/templates/app/app/initializers/captcha.ts +11 -0
- package/templates/app/app/initializers/cli.ts +68 -2
- package/templates/app/app/initializers/database.test.ts +18 -0
- package/templates/app/app/initializers/database.ts +18 -0
- package/templates/app/app/initializers/dispatcher.ts +26 -0
- package/templates/app/app/initializers/honeypot.ts +11 -0
- package/templates/app/app/initializers/i18n.test.ts +16 -0
- package/templates/app/app/initializers/i18n.ts +28 -0
- package/templates/app/app/initializers/local-database.test.ts +33 -0
- package/templates/app/app/initializers/local-database.ts +53 -0
- package/templates/app/app/initializers/mail-transport.test.ts +27 -0
- package/templates/app/app/initializers/mail-transport.ts +26 -0
- package/templates/app/app/initializers/mail.test.ts +27 -0
- package/templates/app/app/initializers/mail.ts +19 -0
- package/templates/app/app/initializers/mcp.ts +1 -1
- package/templates/app/app/initializers/openapi.ts +21 -0
- package/templates/app/app/initializers/router.test.ts +68 -0
- package/templates/app/app/initializers/router.tsx +81 -25
- package/templates/app/app/initializers/seo.ts +15 -0
- package/templates/app/app/initializers/session.test.ts +34 -0
- package/templates/app/app/initializers/session.ts +29 -0
- package/templates/app/app/initializers/spam.ts +10 -0
- package/templates/app/app/jobs/email.test.tsx +70 -0
- package/templates/app/app/jobs/email.ts +16 -0
- package/templates/app/app/jobs/index.ts +6 -2
- package/templates/app/app/models/index.ts +10 -0
- package/templates/app/app/policies/abilities.ts +13 -0
- package/templates/app/app/policies/policy.test.ts +15 -0
- package/templates/app/app/policies/policy.ts +30 -0
- package/templates/app/app/services/commands.ts +30 -0
- package/templates/app/app/services/migrations.test.ts +92 -0
- package/templates/app/app/services/migrations.ts +117 -0
- package/templates/app/app/test/cloudflare-workers.ts +25 -0
- package/templates/app/app/test/local-database.ts +67 -0
- package/templates/app/app/test/session.ts +28 -0
- package/templates/app/bootstrap/cli.ts +1 -1
- package/templates/app/bootstrap/console.ts +13 -0
- package/templates/app/bootstrap/worker.ts +4 -4
- package/templates/app/cloudflare.config.ts +30 -2
- package/templates/app/config/constants.ts +19 -0
- package/templates/app/config/problems.ts +24 -0
- package/templates/app/config/security-policy.ts +34 -0
- package/templates/app/config/security-txt.ts +28 -0
- package/templates/app/database/migrations/.gitkeep +0 -0
- package/templates/app/database/seed.ts +12 -0
- package/templates/app/package.json +37 -6
- package/templates/app/resources/layouts/document.tsx +28 -7
- package/templates/app/resources/locales/en.json +10 -0
- package/templates/app/routes/api.ts +29 -0
- package/templates/app/routes/web.ts +6 -4
- package/templates/app/vite.config.ts +4 -0
- package/stubs/policy.stub +0 -13
- package/templates/app/config/router-context.d.ts +0 -20
|
@@ -1,64 +1,120 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
3
|
-
* `routes/
|
|
4
|
-
* controller it reaches. `sdxc make controller` maps each new controller here.
|
|
2
|
+
* The router: the middleware every request runs through, and every route in `routes/web.ts`
|
|
3
|
+
* and `routes/api.ts` mapped onto its controller through `lazy()`, so a request imports only
|
|
4
|
+
* the controller it reaches. `sdxc make controller` maps each new controller here.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import type { RouterContext } from "remix/router";
|
|
8
8
|
|
|
9
|
-
import {
|
|
9
|
+
import { models } from "@sdxc/data-model/router";
|
|
10
|
+
import { database } from "@sdxc/database-middleware";
|
|
11
|
+
import getClientIP from "@sdxc/get-client-ip/middleware";
|
|
10
12
|
import { lazy } from "@sdxc/lazy-route";
|
|
11
13
|
import { log } from "@sdxc/logger/middleware";
|
|
14
|
+
import mailer from "@sdxc/mail/middleware";
|
|
15
|
+
import { previews } from "@sdxc/mail/previews";
|
|
16
|
+
import { noWWW } from "@sdxc/no-www-middleware";
|
|
17
|
+
import { addressKey, CloudflareAdapter } from "@sdxc/rate-limit";
|
|
18
|
+
import { rateLimit } from "@sdxc/rate-limit/middleware";
|
|
19
|
+
import { trace } from "@sdxc/trace-context/middleware";
|
|
20
|
+
import { trailingSlash } from "@sdxc/trailing-slash-middleware";
|
|
21
|
+
import { userAgent } from "@sdxc/user-agent/middleware";
|
|
22
|
+
import { wellKnown } from "@sdxc/well-known/middleware";
|
|
23
|
+
import { env } from "cloudflare:workers";
|
|
12
24
|
import { asyncContext } from "remix/middleware/async-context";
|
|
13
|
-
import { cop } from "remix/middleware/cop";
|
|
14
|
-
import { formData } from "remix/middleware/form-data";
|
|
15
|
-
import { render } from "remix/middleware/render";
|
|
16
25
|
import { createRouter } from "remix/router";
|
|
17
26
|
|
|
18
|
-
import
|
|
27
|
+
import serverTiming from "~/app/http/middleware/server-timing";
|
|
19
28
|
import { assetResolver } from "~/app/initializers/assets";
|
|
29
|
+
import { openDatabase } from "~/app/initializers/database";
|
|
30
|
+
import { SUPPORTED_LANGUAGES } from "~/app/initializers/i18n";
|
|
20
31
|
import { logger } from "~/app/initializers/logger";
|
|
21
|
-
import
|
|
32
|
+
import { mail } from "~/app/initializers/mail";
|
|
33
|
+
import { queue, transport } from "~/app/initializers/mail-transport";
|
|
34
|
+
import registry from "~/app/models";
|
|
35
|
+
import { MAIL_FROM } from "~/config/constants";
|
|
36
|
+
import problems from "~/config/problems";
|
|
37
|
+
import { securityTxtEntry } from "~/config/security-txt";
|
|
38
|
+
import apiRoutes from "~/routes/api";
|
|
39
|
+
import webRoutes from "~/routes/web";
|
|
22
40
|
|
|
23
|
-
/** The context a controller sees once the
|
|
41
|
+
/** The context a controller sees once the router's middleware has run. */
|
|
24
42
|
export type AppContext = RouterContext<ReturnType<typeof createWebRouter>>;
|
|
25
43
|
|
|
26
44
|
declare module "remix/router" {
|
|
27
|
-
/** Types `createAction` and `createController` with the context the
|
|
45
|
+
/** Types `createAction` and `createController` with the context the router's chain builds. */
|
|
28
46
|
interface RouterTypes {
|
|
29
47
|
context: AppContext;
|
|
30
48
|
}
|
|
31
49
|
}
|
|
32
50
|
|
|
33
51
|
/**
|
|
34
|
-
* Builds the router the Worker forwards each request to.
|
|
35
|
-
*
|
|
52
|
+
* Builds the router the Worker forwards each request to. Its middleware is what pages and
|
|
53
|
+
* endpoints both need, written inline so {@link AppContext} reads what each one publishes; a
|
|
54
|
+
* controller adds its contract's chain, `app/http/middleware/page.ts` or `api.ts`, itself.
|
|
55
|
+
* While developing, `/_emails` previews every mapped email in every supported language.
|
|
36
56
|
*/
|
|
37
57
|
export function createWebRouter() {
|
|
38
58
|
let router = createRouter({
|
|
39
59
|
middleware: [
|
|
40
60
|
asyncContext(),
|
|
41
61
|
log(logger),
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
62
|
+
trace(),
|
|
63
|
+
serverTiming(),
|
|
64
|
+
noWWW(),
|
|
65
|
+
trailingSlash(),
|
|
66
|
+
wellKnown({ "security.txt": securityTxtEntry }),
|
|
67
|
+
getClientIP(),
|
|
68
|
+
userAgent(),
|
|
69
|
+
rateLimit({
|
|
70
|
+
adapter: new CloudflareAdapter(env.RATE_LIMITER, { limit: 100, window: "1 minute" }),
|
|
71
|
+
prefix: "address",
|
|
72
|
+
key: (ctx) => addressKey(ctx.ip),
|
|
73
|
+
onLimit: () => problems.tooManyRequests(),
|
|
47
74
|
}),
|
|
48
|
-
|
|
75
|
+
database(openDatabase()),
|
|
76
|
+
models(registry, (ctx) => ({ db: ctx.db })),
|
|
77
|
+
previews(mail, {
|
|
78
|
+
locales: SUPPORTED_LANGUAGES,
|
|
79
|
+
enabled: import.meta.env.DEV,
|
|
80
|
+
stylesheets: () => assetResolver.getStylesheets("resources/layouts/document.tsx"),
|
|
81
|
+
}),
|
|
82
|
+
mailer({ transport, from: MAIL_FROM, mail, queue }),
|
|
49
83
|
],
|
|
50
|
-
defaultHandler: notFound,
|
|
51
84
|
});
|
|
52
85
|
|
|
53
86
|
router.map(
|
|
54
|
-
|
|
87
|
+
webRoutes.home,
|
|
55
88
|
lazy(() => import("~/app/http/controllers/home")),
|
|
56
89
|
);
|
|
57
90
|
router.map(
|
|
58
|
-
|
|
59
|
-
lazy(() =>
|
|
60
|
-
|
|
61
|
-
|
|
91
|
+
webRoutes.robots,
|
|
92
|
+
lazy(() => import("~/app/http/controllers/robots")),
|
|
93
|
+
);
|
|
94
|
+
router.map(
|
|
95
|
+
webRoutes.sitemap,
|
|
96
|
+
lazy(() => import("~/app/http/controllers/sitemap")),
|
|
97
|
+
);
|
|
98
|
+
router.map(
|
|
99
|
+
webRoutes.notFound,
|
|
100
|
+
lazy(() => import("~/app/http/controllers/not-found")),
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
router.map(
|
|
104
|
+
apiRoutes.api.health,
|
|
105
|
+
lazy(() => import("~/app/http/controllers/api/health")),
|
|
106
|
+
);
|
|
107
|
+
router.map(
|
|
108
|
+
apiRoutes.api.openapi,
|
|
109
|
+
lazy(() => import("~/app/http/controllers/api/openapi")),
|
|
110
|
+
);
|
|
111
|
+
router.map(
|
|
112
|
+
apiRoutes.api.notFound,
|
|
113
|
+
lazy(() => import("~/app/http/controllers/api/not-found")),
|
|
114
|
+
);
|
|
115
|
+
router.map(
|
|
116
|
+
apiRoutes.mcp,
|
|
117
|
+
lazy(() => import("~/app/http/controllers/mcp")),
|
|
62
118
|
);
|
|
63
119
|
|
|
64
120
|
return router;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The app's SEO instance: one configuration the document layout, the sitemap and robots.txt
|
|
3
|
+
* resolve URLs through, so every published link names `SITE_URL` whichever host served it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createSeo } from "@sdxc/seo";
|
|
7
|
+
|
|
8
|
+
import { SITE_DESCRIPTION, SITE_NAME, SITE_URL } from "~/config/constants";
|
|
9
|
+
|
|
10
|
+
/** Canonical URLs drop the trailing slash and tracking parameters, matching the router's redirects. */
|
|
11
|
+
export const seo = createSeo({
|
|
12
|
+
baseUrl: SITE_URL,
|
|
13
|
+
siteName: SITE_NAME,
|
|
14
|
+
defaultDescription: SITE_DESCRIPTION,
|
|
15
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session the page middleware loads, carried across requests by its cookie and kept in the
|
|
3
|
+
* in-memory KV store tests receive as the `SESSIONS` binding.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { session } from "remix/middleware/session";
|
|
7
|
+
import { createRouter } from "remix/router";
|
|
8
|
+
import { describe, expect, test } from "vitest";
|
|
9
|
+
|
|
10
|
+
import { sessionCookie, sessionStorage } from "~/app/initializers/session";
|
|
11
|
+
|
|
12
|
+
/** A router that counts each visitor's requests in their session. */
|
|
13
|
+
function createCounter() {
|
|
14
|
+
let router = createRouter({ middleware: [session(sessionCookie, sessionStorage)] });
|
|
15
|
+
router.get("/", (ctx) => {
|
|
16
|
+
let count = Number(ctx.session.get("count") ?? 0) + 1;
|
|
17
|
+
ctx.session.set("count", count);
|
|
18
|
+
return Response.json({ count });
|
|
19
|
+
});
|
|
20
|
+
return router;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe("session", () => {
|
|
24
|
+
test("keeps a value from one request to the next", async () => {
|
|
25
|
+
let router = createCounter();
|
|
26
|
+
|
|
27
|
+
let first = await router.fetch("https://example.com/");
|
|
28
|
+
let cookie = first.headers.get("set-cookie")?.split(";")[0] ?? "";
|
|
29
|
+
let second = await router.fetch(new Request("https://example.com/", { headers: { cookie } }));
|
|
30
|
+
|
|
31
|
+
expect(first.headers.get("set-cookie")).toContain("HttpOnly");
|
|
32
|
+
expect(await second.json()).toEqual({ count: 2 });
|
|
33
|
+
});
|
|
34
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The visitor's session: a signed, httpOnly cookie naming a record in the `SESSIONS` KV store.
|
|
3
|
+
* The page middleware loads it as `ctx.session` and saves it after the controller runs, so a
|
|
4
|
+
* page reads and writes values, flash messages included, without touching the cookie.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { KVSessionStorage } from "@sdxc/session-storage-kv";
|
|
8
|
+
import { env } from "cloudflare:workers";
|
|
9
|
+
import { createCookie } from "remix/cookie";
|
|
10
|
+
|
|
11
|
+
/** How long a session lasts after its last change, as both the cookie's and the record's lifetime. */
|
|
12
|
+
const SESSION_TTL_SECONDS = 60 * 60 * 24 * 30;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Signed with `SESSION_SECRET`; set it with `cf workers secrets update` before deploying.
|
|
16
|
+
* `Secure` follows the request's scheme, so the cookie also works over `http://localhost`.
|
|
17
|
+
*/
|
|
18
|
+
export const sessionCookie = createCookie("__session", {
|
|
19
|
+
path: "/",
|
|
20
|
+
httpOnly: true,
|
|
21
|
+
sameSite: "Lax",
|
|
22
|
+
maxAge: SESSION_TTL_SECONDS,
|
|
23
|
+
secrets: [env.SESSION_SECRET],
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** Session records, under `session:<id>` keys that expire with the cookie. */
|
|
27
|
+
export const sessionStorage = new KVSessionStorage(env.SESSIONS, {
|
|
28
|
+
ttlSeconds: SESSION_TTL_SECONDS,
|
|
29
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The spam filter a form's action scores submissions with, through `spam(spamFilter, …)` from
|
|
3
|
+
* `@sdxc/spam/middleware`: the local rules weigh links, markup and how fast the form came back,
|
|
4
|
+
* with no account or network call. Add reputation checks here as the app's forms attract them.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createSpamFilter, DEFAULT_RULES } from "@sdxc/spam";
|
|
8
|
+
|
|
9
|
+
/** Scores a submission as `ham`, `unsure` or `spam`, with every signal that fired. */
|
|
10
|
+
export const spamFilter = createSpamFilter({ checks: DEFAULT_RULES });
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The job that delivers queued email: it sends what `ctx.email.queue()` handed the queue, gives
|
|
3
|
+
* up on a delivery no retry can send, and asks for another try when the provider fails.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { NormalizedMessage, QueuedEmail, SentMessage, Transport } from "@sdxc/mail";
|
|
7
|
+
import type { Result } from "@sdxc/result";
|
|
8
|
+
|
|
9
|
+
import { createJobContext } from "@sdxc/jobs";
|
|
10
|
+
import { NonRetriable, Retry } from "@sdxc/jobs/errors";
|
|
11
|
+
import { createEmail, createMail, email, emails, Mailer, MailError } from "@sdxc/mail";
|
|
12
|
+
import { MemoryTransport } from "@sdxc/mail/memory";
|
|
13
|
+
import { CurrentMailer } from "@sdxc/mail/middleware/jobs";
|
|
14
|
+
import { failure } from "@sdxc/result";
|
|
15
|
+
import * as s from "remix/data-schema";
|
|
16
|
+
import { describe, expect, test } from "vitest";
|
|
17
|
+
|
|
18
|
+
import jobs from "~/app/jobs";
|
|
19
|
+
import handler from "~/app/jobs/email";
|
|
20
|
+
import { MAIL_FROM } from "~/config/constants";
|
|
21
|
+
|
|
22
|
+
/** An email declared for these tests alone. */
|
|
23
|
+
const EMAILS = emails({ greeting: email({ props: s.object({ name: s.string() }) }) });
|
|
24
|
+
|
|
25
|
+
/** A transport whose provider is down. */
|
|
26
|
+
class FailingTransport implements Transport {
|
|
27
|
+
async send(_message: NormalizedMessage): Promise<Result<SentMessage, MailError>> {
|
|
28
|
+
return failure(new MailError("The provider is down."));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Runs the job for `input` with a mailer over `transport` that sends the test email. */
|
|
33
|
+
async function run(input: QueuedEmail, transport: Transport) {
|
|
34
|
+
let mail = createMail();
|
|
35
|
+
mail.map(
|
|
36
|
+
EMAILS.greeting,
|
|
37
|
+
createEmail(EMAILS.greeting, {
|
|
38
|
+
subject: ({ name }) => `Hello, ${name}`,
|
|
39
|
+
body: (handle) => () => <p>Hello {handle.props.name}</p>,
|
|
40
|
+
}),
|
|
41
|
+
);
|
|
42
|
+
let ctx = createJobContext(jobs.email, { id: "message-1", attempts: 1, input });
|
|
43
|
+
ctx.set(CurrentMailer, new Mailer({ transport, from: MAIL_FROM, mail }), { property: "email" });
|
|
44
|
+
await handler(ctx);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
describe("email", () => {
|
|
48
|
+
test("sends the queued email", async () => {
|
|
49
|
+
let transport = new MemoryTransport();
|
|
50
|
+
|
|
51
|
+
await run({ email: "greeting", to: "ada@example.com", props: { name: "Ada" } }, transport);
|
|
52
|
+
|
|
53
|
+
expect(transport.last?.subject).toBe("Hello, Ada");
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("gives up on an email nothing maps", async () => {
|
|
57
|
+
let sent = run({ email: "missing", to: "ada@example.com", props: {} }, new MemoryTransport());
|
|
58
|
+
|
|
59
|
+
await expect(sent).rejects.toBeInstanceOf(NonRetriable);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("retries when the provider fails", async () => {
|
|
63
|
+
let sent = run(
|
|
64
|
+
{ email: "greeting", to: "ada@example.com", props: { name: "Ada" } },
|
|
65
|
+
new FailingTransport(),
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
await expect(sent).rejects.toBeInstanceOf(Retry);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delivers a queued email. A delivery no retry can send (an email nothing maps, props its
|
|
3
|
+
* schema refuses) ends here; any other failure, such as the provider being down, is retried.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createJobHandler } from "@sdxc/jobs";
|
|
7
|
+
import { EmailRefusedError } from "@sdxc/mail";
|
|
8
|
+
import { isFailure } from "@sdxc/result";
|
|
9
|
+
|
|
10
|
+
import jobs from "~/app/jobs";
|
|
11
|
+
|
|
12
|
+
export default createJobHandler(jobs.email, async (ctx) => {
|
|
13
|
+
let sent = await ctx.email.deliver(ctx.input);
|
|
14
|
+
if (isFailure(sent) && sent.error instanceof EmailRefusedError) ctx.exit(sent.error.message);
|
|
15
|
+
if (isFailure(sent)) ctx.retry({ cause: sent.error });
|
|
16
|
+
});
|
|
@@ -4,7 +4,11 @@
|
|
|
4
4
|
* a job without loading the handler that runs it.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import { jobs } from "@sdxc/jobs";
|
|
7
|
+
import { job, jobs } from "@sdxc/jobs";
|
|
8
|
+
import { EMAIL_DELIVERY } from "@sdxc/mail";
|
|
8
9
|
|
|
9
10
|
/** The app's jobs; `sdxc make job <name>` declares one here and maps its handler. */
|
|
10
|
-
export default jobs({
|
|
11
|
+
export default jobs({
|
|
12
|
+
/** Delivers what `ctx.email.queue()` handed the queue, for every declared email. */
|
|
13
|
+
email: job({ input: EMAIL_DELIVERY }),
|
|
14
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every model the app reads and writes through, by the name a handler reaches it under:
|
|
3
|
+
* `ctx.models.post` on a request, a job or a command, bound to that run's database. An entry
|
|
4
|
+
* imports its module on first use, so a request loads only the models it touches.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createModels } from "@sdxc/data-model";
|
|
8
|
+
|
|
9
|
+
/** The app's models; `sdxc make model <name>` registers one here. */
|
|
10
|
+
export default createModels({});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Everything a visitor can do in the app, named once so a page, an endpoint, a tool and a test
|
|
3
|
+
* all check the same ability. `sdxc make policy <resource>` adds a resource's abilities here, and
|
|
4
|
+
* importing the catalog does no work, so browser code reads it too.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { abilities } from "@sdxc/authz";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Each ability by its dot-joined keys, such as `post.update`. One declared with a `context` is
|
|
11
|
+
* checked against a record; one without is checked with nothing.
|
|
12
|
+
*/
|
|
13
|
+
export default abilities({});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The policy compiles, so every grant names an ability the catalog declares and every condition
|
|
3
|
+
* reads a fact or record it is given; `sdxc make policy` writes a test per resource beside it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { isSuccess } from "@sdxc/result";
|
|
7
|
+
import { describe, expect, test } from "vitest";
|
|
8
|
+
|
|
9
|
+
import policy from "~/app/policies/policy";
|
|
10
|
+
|
|
11
|
+
describe("policy", () => {
|
|
12
|
+
test("compiles", () => {
|
|
13
|
+
expect(isSuccess(policy.compile())).toBe(true);
|
|
14
|
+
});
|
|
15
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may do what. `everyone` lists what any visitor may do, signed in or not, and `member` what
|
|
3
|
+
* a signed-in visitor adds; `sdxc make policy` grants a resource's reads to everyone and its
|
|
4
|
+
* writes to members. A guard under `guards` refuses whatever role is held.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { definePolicy, fact } from "@sdxc/authz";
|
|
8
|
+
|
|
9
|
+
import abilities from "~/app/policies/abilities";
|
|
10
|
+
|
|
11
|
+
/** The signed-in visitor, as a condition reads it under `actor`; absent for a guest. */
|
|
12
|
+
export interface Actor {
|
|
13
|
+
id: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The app's policy, bound to each request by `app/http/middleware/access.ts`. */
|
|
17
|
+
const policy = definePolicy(abilities, {
|
|
18
|
+
facts: { actor: fact<Actor>({ optional: true }) },
|
|
19
|
+
everyone: [],
|
|
20
|
+
roles: { member: [] },
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
declare module "@sdxc/authz" {
|
|
24
|
+
/** Types `ctx.access` and every check against this policy's catalog and facts. */
|
|
25
|
+
interface AuthzTypes {
|
|
26
|
+
policy: typeof policy;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export default policy;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs one of the app's own commands from inside another, as typing it would, so a command
|
|
3
|
+
* composed of others (`db prepare`, `db fresh --seed`) behaves exactly like its parts.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { AnyCommandContext, CommandResult } from "@sdxc/cli";
|
|
7
|
+
|
|
8
|
+
import { exit, success } from "@sdxc/cli";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Runs `argv` on the app's command line with the calling run's streams, directory and
|
|
12
|
+
* environment, so its output lands where the caller's would. Its failure has been printed
|
|
13
|
+
* already, so the caller fails with the same exit code and no second message.
|
|
14
|
+
*
|
|
15
|
+
* @example let migrated = await runCommand(ctx, ["db", "migrate"]);
|
|
16
|
+
*/
|
|
17
|
+
export async function runCommand(
|
|
18
|
+
ctx: AnyCommandContext,
|
|
19
|
+
argv: readonly string[],
|
|
20
|
+
): Promise<CommandResult> {
|
|
21
|
+
let { cli } = await import("~/app/initializers/cli");
|
|
22
|
+
let code = await cli.run(argv, {
|
|
23
|
+
cwd: ctx.cwd,
|
|
24
|
+
env: ctx.env,
|
|
25
|
+
stdout: { write: ctx.stdout },
|
|
26
|
+
stderr: { write: ctx.stderr },
|
|
27
|
+
signal: ctx.signal,
|
|
28
|
+
});
|
|
29
|
+
return code === 0 ? success() : exit(code);
|
|
30
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The migration runner, on an in-memory SQLite database shaped like a local D1 copy.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { openDatabase } from "@sdxc/cloudflare-mocks/sqlite";
|
|
6
|
+
import { isFailure, unwrap } from "@sdxc/result";
|
|
7
|
+
import { describe, expect, test } from "vitest";
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
applyMigrations,
|
|
11
|
+
dropTables,
|
|
12
|
+
hasAppliedMigrations,
|
|
13
|
+
pendingMigrations,
|
|
14
|
+
} from "~/app/services/migrations";
|
|
15
|
+
|
|
16
|
+
/** Two migrations, given out of order to show the runner sorts them. */
|
|
17
|
+
const MIGRATIONS = [
|
|
18
|
+
{ name: "0002_AddTitle.sql", sql: "ALTER TABLE posts ADD COLUMN title TEXT;" },
|
|
19
|
+
{ name: "0001_CreatePosts.sql", sql: "CREATE TABLE posts (id TEXT PRIMARY KEY);" },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
describe("applyMigrations", () => {
|
|
23
|
+
test("applies each pending migration once, in name order", () => {
|
|
24
|
+
let database = openDatabase(":memory:");
|
|
25
|
+
|
|
26
|
+
let first = unwrap(applyMigrations(database, MIGRATIONS));
|
|
27
|
+
let second = unwrap(applyMigrations(database, MIGRATIONS));
|
|
28
|
+
|
|
29
|
+
expect(first).toEqual(["0001_CreatePosts.sql", "0002_AddTitle.sql"]);
|
|
30
|
+
expect(second).toEqual([]);
|
|
31
|
+
expect(database.query("SELECT name FROM d1_migrations ORDER BY id").all()).toEqual([
|
|
32
|
+
{ name: "0001_CreatePosts.sql" },
|
|
33
|
+
{ name: "0002_AddTitle.sql" },
|
|
34
|
+
]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("stops at a failing migration and leaves it unrecorded", () => {
|
|
38
|
+
let database = openDatabase(":memory:");
|
|
39
|
+
|
|
40
|
+
let result = applyMigrations(database, [
|
|
41
|
+
...MIGRATIONS,
|
|
42
|
+
{ name: "0003_Broken.sql", sql: "CREATE TABLE posts (id TEXT);" },
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
expect(isFailure(result) && result.error.message).toBe("0003_Broken.sql failed");
|
|
46
|
+
expect(database.query("SELECT count(*) AS applied FROM d1_migrations").all()).toEqual([
|
|
47
|
+
{ applied: 2 },
|
|
48
|
+
]);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe("pendingMigrations", () => {
|
|
53
|
+
test("lists what applyMigrations would run, and applies nothing", () => {
|
|
54
|
+
let database = openDatabase(":memory:");
|
|
55
|
+
unwrap(applyMigrations(database, MIGRATIONS.slice(1)));
|
|
56
|
+
|
|
57
|
+
let pending = pendingMigrations(database, MIGRATIONS);
|
|
58
|
+
|
|
59
|
+
expect(pending.map((migration) => migration.name)).toEqual(["0002_AddTitle.sql"]);
|
|
60
|
+
expect(database.query("SELECT count(*) AS applied FROM d1_migrations").all()).toEqual([
|
|
61
|
+
{ applied: 1 },
|
|
62
|
+
]);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe("dropTables", () => {
|
|
67
|
+
test("drops the migrations' tables and views, and the journal, so the chain runs again", () => {
|
|
68
|
+
let database = openDatabase(":memory:");
|
|
69
|
+
unwrap(applyMigrations(database, MIGRATIONS));
|
|
70
|
+
database.exec(
|
|
71
|
+
"CREATE TABLE comments (id INTEGER PRIMARY KEY AUTOINCREMENT, post_id TEXT REFERENCES posts (id)); CREATE VIEW titles AS SELECT title FROM posts;",
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
let dropped = unwrap(dropTables(database));
|
|
75
|
+
|
|
76
|
+
expect(dropped.toSorted()).toEqual(["comments", "d1_migrations", "posts"]);
|
|
77
|
+
expect(
|
|
78
|
+
database.query("SELECT name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'").all(),
|
|
79
|
+
).toEqual([]);
|
|
80
|
+
expect(unwrap(applyMigrations(database, MIGRATIONS))).toHaveLength(2);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
describe("hasAppliedMigrations", () => {
|
|
85
|
+
test("tells a new database from one a migration ran on", () => {
|
|
86
|
+
let database = openDatabase(":memory:");
|
|
87
|
+
let before = hasAppliedMigrations(database);
|
|
88
|
+
unwrap(applyMigrations(database, MIGRATIONS));
|
|
89
|
+
|
|
90
|
+
expect([before, hasAppliedMigrations(database)]).toEqual([false, true]);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Applies a chain of SQL migrations the way `cf d1 migrations apply` does: in name order, each
|
|
3
|
+
* once, recorded in the same `d1_migrations` table, so local and remote databases agree on
|
|
4
|
+
* what ran whichever tool applied it. `dropTables` empties a database for the chain to rerun.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
|
|
10
|
+
import type { Result } from "@sdxc/result";
|
|
11
|
+
|
|
12
|
+
import { failure, success } from "@sdxc/result";
|
|
13
|
+
|
|
14
|
+
/** The migration chain `sdxc make migration` writes into, relative to the project's root. */
|
|
15
|
+
export const MIGRATIONS_DIRECTORY = "database/migrations";
|
|
16
|
+
|
|
17
|
+
/** One migration file: its name, as `0001_CreatePosts.sql`, and its SQL. */
|
|
18
|
+
export interface Migration {
|
|
19
|
+
name: string;
|
|
20
|
+
sql: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The synchronous SQLite client a migration runs on; it runs several statements per call. */
|
|
24
|
+
export interface MigrationDatabase {
|
|
25
|
+
exec(sql: string): void;
|
|
26
|
+
query(sql: string): { all(): unknown[] };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Every `.sql` file in the chain under `root`, with its SQL. */
|
|
30
|
+
export async function readMigrations(root: string): Promise<Migration[]> {
|
|
31
|
+
let directory = join(root, MIGRATIONS_DIRECTORY);
|
|
32
|
+
let names = (await readdir(directory)).filter((name) => name.endsWith(".sql"));
|
|
33
|
+
return Promise.all(
|
|
34
|
+
names.map(async (name) => ({ name, sql: await readFile(join(directory, name), "utf8") })),
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The table D1 records applied migrations in, as Wrangler and `cf` create it. */
|
|
39
|
+
const JOURNAL = `CREATE TABLE IF NOT EXISTS "d1_migrations"(
|
|
40
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
|
+
name TEXT UNIQUE,
|
|
42
|
+
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
|
|
43
|
+
)`;
|
|
44
|
+
|
|
45
|
+
/** Whether any migration ran on the database, which tells a new database from one in use. */
|
|
46
|
+
export function hasAppliedMigrations(database: MigrationDatabase): boolean {
|
|
47
|
+
database.exec(JOURNAL);
|
|
48
|
+
return database.query("SELECT 1 FROM d1_migrations LIMIT 1").all().length > 0;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The migrations the journal lacks, in the order `applyMigrations` runs them. */
|
|
52
|
+
export function pendingMigrations(
|
|
53
|
+
database: MigrationDatabase,
|
|
54
|
+
migrations: readonly Migration[],
|
|
55
|
+
): Migration[] {
|
|
56
|
+
database.exec(JOURNAL);
|
|
57
|
+
let rows = database.query("SELECT name FROM d1_migrations").all() as { name: string }[];
|
|
58
|
+
let applied = new Set(rows.map((row) => row.name));
|
|
59
|
+
return [...migrations]
|
|
60
|
+
.filter((migration) => !applied.has(migration.name))
|
|
61
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Runs every migration the journal lacks, each in its own transaction with its journal row, so
|
|
66
|
+
* a failing migration leaves the database as the previous one left it.
|
|
67
|
+
*
|
|
68
|
+
* @returns The names applied, in order; a failure names the migration that stopped the run.
|
|
69
|
+
*/
|
|
70
|
+
export function applyMigrations(
|
|
71
|
+
database: MigrationDatabase,
|
|
72
|
+
migrations: readonly Migration[],
|
|
73
|
+
): Result<string[], Error> {
|
|
74
|
+
let names: string[] = [];
|
|
75
|
+
for (let migration of pendingMigrations(database, migrations)) {
|
|
76
|
+
try {
|
|
77
|
+
database.exec(
|
|
78
|
+
`BEGIN;\n${migration.sql}\n;INSERT INTO d1_migrations (name) VALUES ('${migration.name.replaceAll("'", "''")}');\nCOMMIT;`,
|
|
79
|
+
);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
database.exec("ROLLBACK");
|
|
82
|
+
return failure(new Error(`${migration.name} failed`, { cause: error }));
|
|
83
|
+
}
|
|
84
|
+
names.push(migration.name);
|
|
85
|
+
}
|
|
86
|
+
return success(names);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Tables SQLite and the local Workers runtime keep for themselves, which a reset leaves alone. */
|
|
90
|
+
const RESERVED_TABLE = /^(sqlite_|_cf_)/;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Drops every view and table the migrations made, `d1_migrations` included, so the next
|
|
94
|
+
* `applyMigrations` runs the whole chain on an empty database. Indexes and triggers go with
|
|
95
|
+
* their tables, and foreign keys are off meanwhile, so the drop order never matters.
|
|
96
|
+
*
|
|
97
|
+
* @returns The names of the tables dropped, views left out.
|
|
98
|
+
*/
|
|
99
|
+
export function dropTables(database: MigrationDatabase): Result<string[], Error> {
|
|
100
|
+
let rows = database
|
|
101
|
+
.query(
|
|
102
|
+
"SELECT type, name FROM sqlite_master WHERE type IN ('view', 'table') ORDER BY type DESC",
|
|
103
|
+
)
|
|
104
|
+
.all() as { type: "view" | "table"; name: string }[];
|
|
105
|
+
let dropped = rows.filter((row) => !RESERVED_TABLE.test(row.name));
|
|
106
|
+
let statements = dropped.map(
|
|
107
|
+
(row) => `DROP ${row.type.toUpperCase()} IF EXISTS "${row.name.replaceAll('"', '""')}";`,
|
|
108
|
+
);
|
|
109
|
+
try {
|
|
110
|
+
database.exec(
|
|
111
|
+
`PRAGMA foreign_keys = OFF;\n${statements.join("\n")}\nPRAGMA foreign_keys = ON;`,
|
|
112
|
+
);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
return failure(new Error("Dropping the tables failed", { cause: error }));
|
|
115
|
+
}
|
|
116
|
+
return success(dropped.filter((row) => row.type === "table").map((row) => row.name));
|
|
117
|
+
}
|