emdash 0.40.0 → 0.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/route-utils.mjs +6 -6
- package/dist/api/schemas/index.d.mts +1 -1
- package/dist/{api-cFFZpyS0.mjs → api-CuyNEHZG.mjs} +3 -3
- package/dist/{api-cFFZpyS0.mjs.map → api-CuyNEHZG.mjs.map} +1 -1
- package/dist/{apply-CoT603H3.mjs → apply-npY1TAhG.mjs} +237 -34
- package/dist/apply-npY1TAhG.mjs.map +1 -0
- package/dist/astro/index.d.mts +3 -3
- package/dist/astro/index.mjs +9 -9
- package/dist/astro/index.mjs.map +1 -1
- package/dist/astro/middleware/auth.d.mts +3 -3
- package/dist/astro/middleware/redirect.mjs +1 -1
- package/dist/astro/middleware.d.mts +3 -3
- package/dist/astro/middleware.d.mts.map +1 -1
- package/dist/astro/middleware.mjs +19 -18
- package/dist/astro/middleware.mjs.map +1 -1
- package/dist/astro/routes/api/admin/media-usage/progress.mjs +2 -2
- package/dist/astro/routes/api/admin/media-usage/repair.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +8 -8
- package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +8 -8
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +8 -8
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +11 -11
- package/dist/astro/routes/api/admin/plugins/index.mjs +8 -8
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +8 -8
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +11 -11
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +8 -8
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +8 -8
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +12 -12
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs +9 -9
- package/dist/astro/routes/api/admin/plugins/registry/verify.mjs +9 -9
- package/dist/astro/routes/api/admin/plugins/updates.mjs +8 -8
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +8 -8
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +8 -8
- package/dist/astro/routes/api/admin/transfer/approvals/_id_/approve.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/approvals/_id_/deny.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/approvals/index.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/capabilities.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/exports/_id_/advance.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/exports/_id_/archive.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/exports/_id_/files/_...path_.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/exports/_id_/index.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/exports/_id_/manifest.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/exports/index.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/abandon.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/advance.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/analyze.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/cancel.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/execute.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/files/_...path_.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/index.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/missing.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/plan.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/_id_/receipt.mjs +3 -3
- package/dist/astro/routes/api/admin/transfer/imports/index.mjs +3 -3
- package/dist/astro/routes/api/dashboard.mjs +2 -2
- package/dist/astro/routes/api/health.mjs +1 -1
- package/dist/astro/routes/api/import/probe.mjs +3 -3
- package/dist/astro/routes/api/import/wordpress/execute.d.mts +3 -3
- package/dist/astro/routes/api/import/wordpress/media.d.mts +3 -3
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +3 -3
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +3 -3
- package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +3 -3
- package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +3 -3
- package/dist/astro/routes/api/manifest.mjs +1 -1
- package/dist/astro/routes/api/mcp.mjs +13 -33
- package/dist/astro/routes/api/mcp.mjs.map +1 -1
- package/dist/astro/routes/api/media/_id_/confirm.mjs +1 -1
- package/dist/astro/routes/api/media/_id_/upload.mjs +1 -1
- package/dist/astro/routes/api/media/_id_/usage.mjs +2 -2
- package/dist/astro/routes/api/media/_id_.mjs +2 -2
- package/dist/astro/routes/api/media/asset/_id_/_filename_.mjs +1 -1
- package/dist/astro/routes/api/media/upload-url.mjs +1 -1
- package/dist/astro/routes/api/media.mjs +2 -2
- package/dist/astro/routes/api/redirects/404s/index.mjs +2 -2
- package/dist/astro/routes/api/redirects/404s/summary.mjs +2 -2
- package/dist/astro/routes/api/redirects/_id_.mjs +2 -2
- package/dist/astro/routes/api/redirects/index.mjs +2 -2
- package/dist/astro/routes/api/schema/block-types/_slug_/index.mjs +8 -8
- package/dist/astro/routes/api/schema/block-types/_slug_/versions/_version_/activate.mjs +8 -8
- package/dist/astro/routes/api/schema/block-types/index.mjs +8 -8
- package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +8 -8
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +8 -8
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +8 -8
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +8 -8
- package/dist/astro/routes/api/schema/collections/index.mjs +8 -8
- package/dist/astro/routes/api/schema/collections/reorder.mjs +8 -8
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs +8 -8
- package/dist/astro/routes/api/schema/orphans/index.mjs +8 -8
- package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +2 -2
- package/dist/astro/routes/api/settings/backups/archives/index.mjs +2 -2
- package/dist/astro/routes/api/settings/backups/export.mjs +2 -2
- package/dist/astro/routes/api/settings/backups/index.mjs +2 -2
- package/dist/astro/routes/api/settings.mjs +3 -3
- package/dist/astro/routes/api/setup/dev-bypass.mjs +4 -4
- package/dist/astro/routes/api/setup/index.d.mts.map +1 -1
- package/dist/astro/routes/api/setup/index.mjs +35 -10
- package/dist/astro/routes/api/setup/index.mjs.map +1 -1
- package/dist/astro/routes/api/snapshot.mjs +2 -2
- package/dist/astro/routes/api/snapshot.mjs.map +1 -1
- package/dist/astro/routes/robots.txt.mjs +2 -2
- package/dist/astro/routes/sitemap-_collection_.xml.mjs +2 -2
- package/dist/astro/routes/sitemap.xml.mjs +2 -2
- package/dist/astro/types.d.mts +7 -3
- package/dist/astro/types.d.mts.map +1 -1
- package/dist/{backup-CBu0LrXf.mjs → backup-BQRj3afm.mjs} +3 -3
- package/dist/{backup-CBu0LrXf.mjs.map → backup-BQRj3afm.mjs.map} +1 -1
- package/dist/cli/index.mjs +6 -6
- package/dist/client/index.d.mts +14 -14
- package/dist/{config-5ii2haYu.d.mts → config-BjEm_3xL.d.mts} +25 -16
- package/dist/config-BjEm_3xL.d.mts.map +1 -0
- package/dist/{context-BeGccdUX.mjs → context-BV_7t-Ua.mjs} +6 -6
- package/dist/{context-BeGccdUX.mjs.map → context-BV_7t-Ua.mjs.map} +1 -1
- package/dist/{dashboard-DjrB-xxZ.mjs → dashboard-BP-iJqpd.mjs} +2 -2
- package/dist/{dashboard-DjrB-xxZ.mjs.map → dashboard-BP-iJqpd.mjs.map} +1 -1
- package/dist/db/libsql-migrations.mjs +2 -2
- package/dist/db/postgres-migrations.mjs +2 -2
- package/dist/db/sqlite-migrations.mjs +2 -2
- package/dist/{direct-executor-BmuFJJZV.mjs → direct-executor-D2lNadwo.mjs} +2 -2
- package/dist/{direct-executor-BmuFJJZV.mjs.map → direct-executor-D2lNadwo.mjs.map} +1 -1
- package/dist/{emdash-runtime-DAjghyEG.mjs → emdash-runtime-CtfnZmPi.mjs} +56 -56
- package/dist/emdash-runtime-CtfnZmPi.mjs.map +1 -0
- package/dist/{entry-lock-DVhCt49A.d.mts → entry-lock-Cf5OoIgN.d.mts} +18 -18
- package/dist/{entry-lock-DVhCt49A.d.mts.map → entry-lock-Cf5OoIgN.d.mts.map} +1 -1
- package/dist/{hreflang-DMFBL2eb.mjs → hreflang-CbVI4paR.mjs} +2 -2
- package/dist/{hreflang-DMFBL2eb.mjs.map → hreflang-CbVI4paR.mjs.map} +1 -1
- package/dist/{identity-IyNWwXr6.mjs → identity-Be5kzutJ.mjs} +2 -2
- package/dist/{identity-IyNWwXr6.mjs.map → identity-Be5kzutJ.mjs.map} +1 -1
- package/dist/{import-C3JZplWq.mjs → import-YzfKCaco.mjs} +2 -2
- package/dist/{import-C3JZplWq.mjs.map → import-YzfKCaco.mjs.map} +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +16 -16
- package/dist/{manifest-builder-B8zR-73J.mjs → manifest-builder-BmSAOOEF.mjs} +2 -2
- package/dist/{manifest-builder-B8zR-73J.mjs.map → manifest-builder-BmSAOOEF.mjs.map} +1 -1
- package/dist/media/local-runtime.d.mts +3 -3
- package/dist/media/local-runtime.mjs +3 -3
- package/dist/{media-Qp5S3eH3.mjs → media-CPXTbb1R.mjs} +20 -2
- package/dist/media-CPXTbb1R.mjs.map +1 -0
- package/dist/{media-h7tOiDLj.mjs → media-JXRWDhw3.mjs} +77 -4
- package/dist/media-JXRWDhw3.mjs.map +1 -0
- package/dist/{media-usage-My-Vi-ex.mjs → media-usage-De-zeR9E.mjs} +2 -2
- package/dist/{media-usage-My-Vi-ex.mjs.map → media-usage-De-zeR9E.mjs.map} +1 -1
- package/dist/{menus-TsSGmSR4.mjs → menus-Cm68rsAq.mjs} +4 -4
- package/dist/{menus-TsSGmSR4.mjs.map → menus-Cm68rsAq.mjs.map} +1 -1
- package/dist/migrations/index.mjs +2 -2
- package/dist/page/index.mjs +2 -2
- package/dist/plugin-test-runtime.d.mts +3 -3
- package/dist/plugin-test-runtime.mjs +18 -18
- package/dist/plugin-utils.d.mts +3 -3
- package/dist/plugins/adapt-sandbox-entry.d.mts +3 -3
- package/dist/plugins/host.d.mts +1 -1
- package/dist/plugins/host.mjs +6 -6
- package/dist/{redirect-iJf5fltD.mjs → redirect-B29UjdUn.mjs} +10 -14
- package/dist/redirect-B29UjdUn.mjs.map +1 -0
- package/dist/{redirects-CYu1u1aK.mjs → redirects-Ca2MPfEG.mjs} +2 -2
- package/dist/{redirects-CYu1u1aK.mjs.map → redirects-Ca2MPfEG.mjs.map} +1 -1
- package/dist/{routes-CUsM40Cc.mjs → routes-vrR95WR6.mjs} +2 -2
- package/dist/{routes-CUsM40Cc.mjs.map → routes-vrR95WR6.mjs.map} +1 -1
- package/dist/runtime.d.mts +3 -3
- package/dist/seed/index.mjs +4 -4
- package/dist/seo/index.mjs +3 -3
- package/dist/{settings-CgjRWGW9.mjs → settings-B4vDl1fK.mjs} +2 -2
- package/dist/{settings-CgjRWGW9.mjs.map → settings-B4vDl1fK.mjs.map} +1 -1
- package/dist/{settings-2xNYr90o.mjs → settings-Dyj6v8C4.mjs} +2 -2
- package/dist/{settings-2xNYr90o.mjs.map → settings-Dyj6v8C4.mjs.map} +1 -1
- package/dist/{snapshot-CugwUqKQ.mjs → snapshot-PawoX-WG.mjs} +180 -3
- package/dist/snapshot-PawoX-WG.mjs.map +1 -0
- package/dist/{storage-query-Bdv7A62k.d.mts → storage-query-FXJH5pI8.d.mts} +6 -1
- package/dist/storage-query-FXJH5pI8.d.mts.map +1 -0
- package/dist/{transfer-BhUCrgDc.mjs → transfer-DgeCvHnj.mjs} +4 -4
- package/dist/{transfer-BhUCrgDc.mjs.map → transfer-DgeCvHnj.mjs.map} +1 -1
- package/dist/validate-CM79QXYE.d.mts.map +1 -1
- package/dist/version-DXsxRrob.mjs +7 -0
- package/dist/{version-DUQDHgrf.mjs.map → version-DXsxRrob.mjs.map} +1 -1
- package/package.json +5 -5
- package/src/api/handlers/index.ts +1 -0
- package/src/api/handlers/media-upload.ts +17 -71
- package/src/api/handlers/media.ts +97 -3
- package/src/api/handlers/snapshot.ts +257 -3
- package/src/astro/integration/vite-config.ts +10 -4
- package/src/astro/middleware.ts +1 -0
- package/src/astro/routes/api/setup/index.ts +66 -23
- package/src/astro/routes/api/snapshot.ts +2 -1
- package/src/astro/types.ts +5 -0
- package/src/cleanup.ts +10 -0
- package/src/components/Columns.astro +3 -1
- package/src/components/Cover.astro +3 -1
- package/src/database/repositories/media.ts +40 -1
- package/src/database/repositories/redirect.ts +17 -34
- package/src/emdash-runtime.ts +28 -0
- package/src/index.ts +1 -0
- package/src/mcp/server.ts +13 -48
- package/src/seed/apply.ts +322 -41
- package/dist/apply-CoT603H3.mjs.map +0 -1
- package/dist/config-5ii2haYu.d.mts.map +0 -1
- package/dist/emdash-runtime-DAjghyEG.mjs.map +0 -1
- package/dist/media-Qp5S3eH3.mjs.map +0 -1
- package/dist/media-h7tOiDLj.mjs.map +0 -1
- package/dist/redirect-iJf5fltD.mjs.map +0 -1
- package/dist/snapshot-CugwUqKQ.mjs.map +0 -1
- package/dist/storage-query-Bdv7A62k.d.mts.map +0 -1
- package/dist/version-DUQDHgrf.mjs +0 -7
|
@@ -2,7 +2,7 @@ import "../runner-1y4J9fJB.mjs";
|
|
|
2
2
|
import "../dialect-helpers-7_IqPdh9.mjs";
|
|
3
3
|
import "../config-CvmjJcVw.mjs";
|
|
4
4
|
import "../datetime-normalization-PeiEdcRY.mjs";
|
|
5
|
-
import { n as fingerprintMigrationSet, r as getCoreMigrationIdentity, t as createCoreMigrationIdentity } from "../identity-
|
|
6
|
-
import { t as createDirectMigrationExecutor } from "../direct-executor-
|
|
5
|
+
import { n as fingerprintMigrationSet, r as getCoreMigrationIdentity, t as createCoreMigrationIdentity } from "../identity-Be5kzutJ.mjs";
|
|
6
|
+
import { t as createDirectMigrationExecutor } from "../direct-executor-D2lNadwo.mjs";
|
|
7
7
|
|
|
8
8
|
export { createCoreMigrationIdentity, createDirectMigrationExecutor, fingerprintMigrationSet, getCoreMigrationIdentity };
|
package/dist/page/index.mjs
CHANGED
|
@@ -6,10 +6,10 @@ import "../base64-DvnNgP7e.mjs";
|
|
|
6
6
|
import "../secrets-CIi0nFiR.mjs";
|
|
7
7
|
import "../object-cache-CqWNY5uP.mjs";
|
|
8
8
|
import "../types-BkUg2yHx.mjs";
|
|
9
|
-
import "../media-
|
|
9
|
+
import "../media-CPXTbb1R.mjs";
|
|
10
10
|
import "../request-cache-DzLYKm_x.mjs";
|
|
11
11
|
import "../loader-BzqeR1ZN.mjs";
|
|
12
|
-
import "../settings-
|
|
12
|
+
import "../settings-B4vDl1fK.mjs";
|
|
13
13
|
|
|
14
14
|
//#region src/page/context.ts
|
|
15
15
|
function isAstroInput(input) {
|
|
@@ -3,10 +3,10 @@ import "./parse-CVgO-Qai.mjs";
|
|
|
3
3
|
import { t as Database } from "./types-B7Lmsh1E.mjs";
|
|
4
4
|
import { Kt as PluginEditorDraftFieldSelector, Nn as UserInfo } from "./types-Cr-Kg-3D.mjs";
|
|
5
5
|
import "./options-SQCHQCPH.mjs";
|
|
6
|
-
import "./entry-lock-
|
|
7
|
-
import {
|
|
6
|
+
import "./entry-lock-Cf5OoIgN.mjs";
|
|
7
|
+
import { Li as RedirectRepository, cr as EmDashRuntime, dr as RuntimeDependencies, gr as PluginContentCacheInvalidator, lr as PluginEditorExtensionDispatch, or as handlePluginSettingsGet, sr as handlePluginSettingsUpdate, zi as TaxonomyRepository } from "./config-BjEm_3xL.mjs";
|
|
8
8
|
import "./runner-D5_LzKXI.mjs";
|
|
9
|
-
import "./storage-query-
|
|
9
|
+
import "./storage-query-FXJH5pI8.mjs";
|
|
10
10
|
import { T as BylineRepository } from "./index-D-hdtLe8.mjs";
|
|
11
11
|
import { o as setI18nConfig, r as getI18nConfig } from "./config-Py43JK9r.mjs";
|
|
12
12
|
import "./types-Cd-O03VG.mjs";
|
|
@@ -2,7 +2,7 @@ import "./runner-1y4J9fJB.mjs";
|
|
|
2
2
|
import "./dialect-helpers-7_IqPdh9.mjs";
|
|
3
3
|
import { c as setI18nConfig, r as getI18nConfig } from "./config-CvmjJcVw.mjs";
|
|
4
4
|
import "./datetime-normalization-PeiEdcRY.mjs";
|
|
5
|
-
import "./menus-
|
|
5
|
+
import "./menus-Cm68rsAq.mjs";
|
|
6
6
|
import "./after-PcEvMY_6.mjs";
|
|
7
7
|
import "./options-DhrI7eMv.mjs";
|
|
8
8
|
import "./base64-DvnNgP7e.mjs";
|
|
@@ -11,15 +11,15 @@ import "./content-DFaIEDj9.mjs";
|
|
|
11
11
|
import "./object-cache-CqWNY5uP.mjs";
|
|
12
12
|
import "./slugify-T5GHH42D.mjs";
|
|
13
13
|
import "./types-BkUg2yHx.mjs";
|
|
14
|
-
import "./media-
|
|
14
|
+
import "./media-CPXTbb1R.mjs";
|
|
15
15
|
import "./user-DDSL-sGw.mjs";
|
|
16
16
|
import { t as TaxonomyRepository } from "./taxonomy-C3Fu1YeH.mjs";
|
|
17
17
|
import "./comment-CrBl22OF.mjs";
|
|
18
18
|
import "./audit-RfCugiSB.mjs";
|
|
19
|
-
import "./context-
|
|
19
|
+
import "./context-BV_7t-Ua.mjs";
|
|
20
20
|
import "./menus-ITeAbcIF.mjs";
|
|
21
21
|
import "./resolve-2WbQsCvT.mjs";
|
|
22
|
-
import { t as RedirectRepository } from "./redirect-
|
|
22
|
+
import { t as RedirectRepository } from "./redirect-B29UjdUn.mjs";
|
|
23
23
|
import "./request-cache-DzLYKm_x.mjs";
|
|
24
24
|
import "./byline-registry-gnKscbQX.mjs";
|
|
25
25
|
import "./field-defs-cache-HIgBbqZZ.mjs";
|
|
@@ -34,7 +34,7 @@ import "./fts-manager-S-K0laoS.mjs";
|
|
|
34
34
|
import { p as saveTaxonomyStructure } from "./loader-BzqeR1ZN.mjs";
|
|
35
35
|
import "./collection-slugs-cache-CjGk__zp.mjs";
|
|
36
36
|
import "./taxonomies-C1IwNe8Q.mjs";
|
|
37
|
-
import { _ as handlePluginSettingsGet, v as handlePluginSettingsUpdate } from "./api-
|
|
37
|
+
import { _ as handlePluginSettingsGet, v as handlePluginSettingsUpdate } from "./api-CuyNEHZG.mjs";
|
|
38
38
|
import "./capture-triggers-kJyl_yyM.mjs";
|
|
39
39
|
import "./activation-LOkDM5WT.mjs";
|
|
40
40
|
import "./block-type-registry-DUI_3KxT.mjs";
|
|
@@ -44,14 +44,14 @@ import "./canonical-YhEQezjg.mjs";
|
|
|
44
44
|
import "./digest-BarSh-pN.mjs";
|
|
45
45
|
import "./hash-SDAW6zC-.mjs";
|
|
46
46
|
import "./zod-generator-D6uE4WiS.mjs";
|
|
47
|
-
import "./dashboard-
|
|
47
|
+
import "./dashboard-BP-iJqpd.mjs";
|
|
48
48
|
import "./block-values-C_VIPr5t.mjs";
|
|
49
|
-
import "./media-
|
|
49
|
+
import "./media-JXRWDhw3.mjs";
|
|
50
50
|
import "./media-folders-BE0oo2eX.mjs";
|
|
51
51
|
import "./media-usage-work-C2OZLCAd.mjs";
|
|
52
52
|
import "./content-repair-Q8IUrpLL.mjs";
|
|
53
53
|
import "./collection-deletion-processor-Br6rxs3u.mjs";
|
|
54
|
-
import "./media-usage-
|
|
54
|
+
import "./media-usage-De-zeR9E.mjs";
|
|
55
55
|
import "./settings-DYidIB26.mjs";
|
|
56
56
|
import "./site-settings-DOgRUoFX.mjs";
|
|
57
57
|
import "./errors-BF0_LFhW.mjs";
|
|
@@ -62,9 +62,9 @@ import "./schema-BABiRdsH.mjs";
|
|
|
62
62
|
import "./schema-Du3MzCG0.mjs";
|
|
63
63
|
import "./block-types-BmZmLmAD.mjs";
|
|
64
64
|
import "./seo-CZT2oLtT.mjs";
|
|
65
|
-
import "./settings-
|
|
65
|
+
import "./settings-B4vDl1fK.mjs";
|
|
66
66
|
import "./sections-Ddptx_o9.mjs";
|
|
67
|
-
import "./settings-
|
|
67
|
+
import "./settings-Dyj6v8C4.mjs";
|
|
68
68
|
import "./taxonomies-C_XMoRcX.mjs";
|
|
69
69
|
import "./manifest-schema-CY3zng_M.mjs";
|
|
70
70
|
import "./artifact-fetch-DZMOGZ3-.mjs";
|
|
@@ -80,20 +80,20 @@ import "./comments-fHZ8ON9O.mjs";
|
|
|
80
80
|
import "./relations-CK9CYUyr.mjs";
|
|
81
81
|
import "./menus-BM7BPLOb.mjs";
|
|
82
82
|
import "./status-DZKIG4a9.mjs";
|
|
83
|
-
import "./apply-
|
|
83
|
+
import "./apply-npY1TAhG.mjs";
|
|
84
84
|
import "./query-B48peoRT.mjs";
|
|
85
|
-
import "./import-
|
|
86
|
-
import "./redirects-
|
|
85
|
+
import "./import-YzfKCaco.mjs";
|
|
86
|
+
import "./redirects-Ca2MPfEG.mjs";
|
|
87
87
|
import "./ssrf-DpBH7aOt.mjs";
|
|
88
88
|
import "./cron-7DCJwPXq.mjs";
|
|
89
89
|
import "./email-console-bJn3ctqA.mjs";
|
|
90
90
|
import "./fence-CMDXJYc_.mjs";
|
|
91
91
|
import "./route-wire--1hLuACz.mjs";
|
|
92
|
-
import "./routes-
|
|
92
|
+
import "./routes-vrR95WR6.mjs";
|
|
93
93
|
import "./utils-DdhmO9w9.mjs";
|
|
94
94
|
import "./tokens-u78jETkX.mjs";
|
|
95
95
|
import "./preview-CIUcPYr6.mjs";
|
|
96
|
-
import "./hreflang-
|
|
96
|
+
import "./hreflang-CbVI4paR.mjs";
|
|
97
97
|
import "./comment-reaction-JEQ2Fpd8.mjs";
|
|
98
98
|
import "./bylines-BPwJqoYH.mjs";
|
|
99
99
|
import "./widgets-WdV72brA.mjs";
|
|
@@ -101,11 +101,11 @@ import "./validate-CHosPEhs.mjs";
|
|
|
101
101
|
import "./load-XgJiE6_3.mjs";
|
|
102
102
|
import "./search-Bt1PL1jf.mjs";
|
|
103
103
|
import "./policy-CUvwAARc.mjs";
|
|
104
|
-
import { n as EmDashRuntime } from "./emdash-runtime-
|
|
104
|
+
import { n as EmDashRuntime } from "./emdash-runtime-CtfnZmPi.mjs";
|
|
105
105
|
import "./site-url-BU_bbxwj.mjs";
|
|
106
106
|
import "./public-submission-BFBUrqst.mjs";
|
|
107
|
-
import "./snapshot-
|
|
108
|
-
import "./backup-
|
|
107
|
+
import "./snapshot-PawoX-WG.mjs";
|
|
108
|
+
import "./backup-BQRj3afm.mjs";
|
|
109
109
|
import "./comments-2ah9du9y.mjs";
|
|
110
110
|
import "./rate-limit-BZ6nybgc.mjs";
|
|
111
111
|
import "./service-DuykXPyW.mjs";
|
package/dist/plugin-utils.d.mts
CHANGED
|
@@ -2,10 +2,10 @@ import "./parse-CVgO-Qai.mjs";
|
|
|
2
2
|
import "./types-B7Lmsh1E.mjs";
|
|
3
3
|
import "./types-Cr-Kg-3D.mjs";
|
|
4
4
|
import "./options-SQCHQCPH.mjs";
|
|
5
|
-
import "./entry-lock-
|
|
6
|
-
import "./config-
|
|
5
|
+
import "./entry-lock-Cf5OoIgN.mjs";
|
|
6
|
+
import "./config-BjEm_3xL.mjs";
|
|
7
7
|
import "./runner-D5_LzKXI.mjs";
|
|
8
|
-
import "./storage-query-
|
|
8
|
+
import "./storage-query-FXJH5pI8.mjs";
|
|
9
9
|
import "./index-D-hdtLe8.mjs";
|
|
10
10
|
import "./types-Cd-O03VG.mjs";
|
|
11
11
|
import "./hreflang-D5uNnsGJ.mjs";
|
|
@@ -2,10 +2,10 @@ import "../parse-CVgO-Qai.mjs";
|
|
|
2
2
|
import "../types-B7Lmsh1E.mjs";
|
|
3
3
|
import { pn as ResolvedPlugin } from "../types-Cr-Kg-3D.mjs";
|
|
4
4
|
import "../options-SQCHQCPH.mjs";
|
|
5
|
-
import "../entry-lock-
|
|
6
|
-
import { xr as PluginDescriptor } from "../config-
|
|
5
|
+
import "../entry-lock-Cf5OoIgN.mjs";
|
|
6
|
+
import { xr as PluginDescriptor } from "../config-BjEm_3xL.mjs";
|
|
7
7
|
import "../runner-D5_LzKXI.mjs";
|
|
8
|
-
import "../storage-query-
|
|
8
|
+
import "../storage-query-FXJH5pI8.mjs";
|
|
9
9
|
import "../index-D-hdtLe8.mjs";
|
|
10
10
|
import { SandboxedPlugin } from "../plugin-types.mjs";
|
|
11
11
|
import "../types-Cd-O03VG.mjs";
|
package/dist/plugins/host.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "../types-B7Lmsh1E.mjs";
|
|
2
2
|
import { Ct as MediaMetadataPatch, Ft as PaginatedResult, L as ContentItem, R as ContentListOptions, St as MediaItem, _n as SettingField, xt as MediaBytes } from "../types-Cr-Kg-3D.mjs";
|
|
3
3
|
import { t as OptionsRepository } from "../options-SQCHQCPH.mjs";
|
|
4
|
-
import { D as getSandboxRouteErrorDetails, F as createMediaAccess, H as createSettingsAccess, I as createRedirectAccess, L as createSchemaAccess, M as createCommentAccess, T as createSandboxRouteError, X as PluginStorageRepository, a as readPluginMediaBytes, c as CronAccessImpl, i as parsePluginMediaMetadataPatch, j as RedirectAccessError, rt as resolvePluginEncryptionKeys, s as updatePluginMediaMetadata, t as StorageSerializationError, tt as ContentRepository, z as createContentAccess } from "../storage-query-
|
|
4
|
+
import { D as getSandboxRouteErrorDetails, F as createMediaAccess, H as createSettingsAccess, I as createRedirectAccess, L as createSchemaAccess, M as createCommentAccess, T as createSandboxRouteError, X as PluginStorageRepository, a as readPluginMediaBytes, c as CronAccessImpl, i as parsePluginMediaMetadataPatch, j as RedirectAccessError, rt as resolvePluginEncryptionKeys, s as updatePluginMediaMetadata, t as StorageSerializationError, tt as ContentRepository, z as createContentAccess } from "../storage-query-FXJH5pI8.mjs";
|
|
5
5
|
import { a as resolveContentCreateLocale } from "../config-Py43JK9r.mjs";
|
|
6
6
|
import { ulid } from "ulidx";
|
|
7
7
|
export { type ContentItem, type ContentListOptions, ContentRepository, CronAccessImpl, type MediaBytes, type MediaItem, type MediaMetadataPatch, OptionsRepository, type PaginatedResult, PluginStorageRepository, RedirectAccessError, type SettingField, StorageSerializationError, createCommentAccess, createContentAccess, createMediaAccess, createRedirectAccess, createSandboxRouteError, createSchemaAccess, createSettingsAccess, getSandboxRouteErrorDetails, parsePluginMediaMetadataPatch, readPluginMediaBytes, resolveContentCreateLocale, resolvePluginEncryptionKeys, ulid, updatePluginMediaMetadata };
|
package/dist/plugins/host.mjs
CHANGED
|
@@ -9,13 +9,13 @@ import { t as ContentRepository } from "../content-DFaIEDj9.mjs";
|
|
|
9
9
|
import "../object-cache-CqWNY5uP.mjs";
|
|
10
10
|
import "../slugify-T5GHH42D.mjs";
|
|
11
11
|
import "../types-BkUg2yHx.mjs";
|
|
12
|
-
import "../media-
|
|
12
|
+
import "../media-CPXTbb1R.mjs";
|
|
13
13
|
import "../user-DDSL-sGw.mjs";
|
|
14
14
|
import "../taxonomy-C3Fu1YeH.mjs";
|
|
15
15
|
import "../comment-CrBl22OF.mjs";
|
|
16
|
-
import { S as StorageSerializationError, _ as readPluginMediaBytes, b as createContentAccess, c as createSchemaAccess, g as parsePluginMediaMetadataPatch, n as RedirectAccessError, o as createMediaAccess, r as createCommentAccess, s as createRedirectAccess, x as PluginStorageRepository, y as updatePluginMediaMetadata } from "../context-
|
|
16
|
+
import { S as StorageSerializationError, _ as readPluginMediaBytes, b as createContentAccess, c as createSchemaAccess, g as parsePluginMediaMetadataPatch, n as RedirectAccessError, o as createMediaAccess, r as createCommentAccess, s as createRedirectAccess, x as PluginStorageRepository, y as updatePluginMediaMetadata } from "../context-BV_7t-Ua.mjs";
|
|
17
17
|
import "../resolve-2WbQsCvT.mjs";
|
|
18
|
-
import "../redirect-
|
|
18
|
+
import "../redirect-B29UjdUn.mjs";
|
|
19
19
|
import "../request-cache-DzLYKm_x.mjs";
|
|
20
20
|
import "../dist-BNwANFJR.mjs";
|
|
21
21
|
import "../enrich-Dl3kZ-lP.mjs";
|
|
@@ -35,17 +35,17 @@ import "../canonical-YhEQezjg.mjs";
|
|
|
35
35
|
import "../digest-BarSh-pN.mjs";
|
|
36
36
|
import "../hash-SDAW6zC-.mjs";
|
|
37
37
|
import "../zod-generator-D6uE4WiS.mjs";
|
|
38
|
-
import "../media-
|
|
38
|
+
import "../media-JXRWDhw3.mjs";
|
|
39
39
|
import "../settings-DYidIB26.mjs";
|
|
40
40
|
import "../site-settings-DOgRUoFX.mjs";
|
|
41
|
-
import { u as createSettingsAccess } from "../settings-
|
|
41
|
+
import { u as createSettingsAccess } from "../settings-B4vDl1fK.mjs";
|
|
42
42
|
import "../taxonomies-C_XMoRcX.mjs";
|
|
43
43
|
import { i as getSandboxRouteErrorDetails, n as createSandboxRouteError } from "../types-D7HUsguf.mjs";
|
|
44
44
|
import "../ssrf-CJUnJymJ.mjs";
|
|
45
45
|
import "../redirects-Cv9apQKj.mjs";
|
|
46
46
|
import "../media-Pu1L6xir.mjs";
|
|
47
47
|
import "../status-DZKIG4a9.mjs";
|
|
48
|
-
import "../redirects-
|
|
48
|
+
import "../redirects-Ca2MPfEG.mjs";
|
|
49
49
|
import "../ssrf-DpBH7aOt.mjs";
|
|
50
50
|
import { t as CronAccessImpl } from "../cron-7DCJwPXq.mjs";
|
|
51
51
|
import { ulid } from "ulidx";
|
|
@@ -7,9 +7,9 @@ import { ulid } from "ulidx";
|
|
|
7
7
|
|
|
8
8
|
//#region src/database/repositories/redirect.ts
|
|
9
9
|
/**
|
|
10
|
-
* Hard cap on rows stored in `_emdash_404_log`.
|
|
11
|
-
* rows
|
|
12
|
-
*
|
|
10
|
+
* Hard cap on rows stored in `_emdash_404_log`. Scheduled maintenance evicts
|
|
11
|
+
* the oldest rows by `last_seen_at` without adding a read-amplifying count to
|
|
12
|
+
* the anonymous request path.
|
|
13
13
|
*/
|
|
14
14
|
const MAX_404_LOG_ROWS = 1e4;
|
|
15
15
|
/** Max stored length for the `Referer` header — truncated on insert. */
|
|
@@ -314,7 +314,7 @@ var RedirectRepository = class RedirectRepository {
|
|
|
314
314
|
const userAgent = truncateOrNull(entry.userAgent, USER_AGENT_MAX_LENGTH);
|
|
315
315
|
const ip = entry.ip ?? null;
|
|
316
316
|
const id = ulid();
|
|
317
|
-
|
|
317
|
+
await this.db.insertInto("_emdash_404_log").values({
|
|
318
318
|
id,
|
|
319
319
|
path: entry.path,
|
|
320
320
|
referrer,
|
|
@@ -329,22 +329,18 @@ var RedirectRepository = class RedirectRepository {
|
|
|
329
329
|
referrer,
|
|
330
330
|
user_agent: userAgent,
|
|
331
331
|
ip
|
|
332
|
-
})).
|
|
333
|
-
await this.enforce404Cap();
|
|
332
|
+
})).execute();
|
|
334
333
|
}
|
|
335
334
|
/**
|
|
336
335
|
* Delete the oldest rows from `_emdash_404_log` if the row count exceeds
|
|
337
336
|
* MAX_404_LOG_ROWS. "Oldest" is by `last_seen_at`, so a path that keeps
|
|
338
337
|
* getting hit stays in the table even if it was first seen long ago.
|
|
339
338
|
*
|
|
340
|
-
*
|
|
339
|
+
* Called by scheduled system cleanup, never by the anonymous request path.
|
|
341
340
|
*/
|
|
342
|
-
async
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
if (count <= MAX_404_LOG_ROWS) return;
|
|
346
|
-
const excess = count - MAX_404_LOG_ROWS;
|
|
347
|
-
await this.db.deleteFrom("_emdash_404_log").where("id", "in", this.db.selectFrom("_emdash_404_log").select("id").orderBy("last_seen_at", "asc").orderBy("id", "asc").limit(excess)).execute();
|
|
341
|
+
async cleanup404Log() {
|
|
342
|
+
const result = await this.db.deleteFrom("_emdash_404_log").where("id", "not in", this.db.selectFrom("_emdash_404_log").select("id").orderBy("last_seen_at", "desc").orderBy("id", "desc").limit(MAX_404_LOG_ROWS)).executeTakeFirst();
|
|
343
|
+
return Number(result.numDeletedRows);
|
|
348
344
|
}
|
|
349
345
|
async find404s(opts) {
|
|
350
346
|
const limit = Math.min(Math.max(opts.limit ?? 50, 1), 100);
|
|
@@ -412,4 +408,4 @@ var RedirectRepository = class RedirectRepository {
|
|
|
412
408
|
|
|
413
409
|
//#endregion
|
|
414
410
|
export { RedirectWriteBusyError as n, RedirectRepository as t };
|
|
415
|
-
//# sourceMappingURL=redirect-
|
|
411
|
+
//# sourceMappingURL=redirect-B29UjdUn.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redirect-B29UjdUn.mjs","names":[],"sources":["../src/database/repositories/redirect.ts"],"sourcesContent":["import { sql, type Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { interpolateUrlPattern } from \"../../i18n/resolve.js\";\nimport {\n\tcompilePattern,\n\tmatchPattern,\n\tinterpolateDestination,\n\tisPattern,\n} from \"../../redirects/patterns.js\";\nimport { currentTimestampValue, isPostgres } from \"../dialect-helpers.js\";\nimport type { Database, RedirectTable } from \"../types.js\";\nimport { encodeCursor, decodeCursor, type FindManyResult } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Bounded 404 logging\n// ---------------------------------------------------------------------------\n\n/**\n * Hard cap on rows stored in `_emdash_404_log`. Scheduled maintenance evicts\n * the oldest rows by `last_seen_at` without adding a read-amplifying count to\n * the anonymous request path.\n */\nexport const MAX_404_LOG_ROWS = 10_000;\n\n/** Max stored length for the `Referer` header — truncated on insert. */\nexport const REFERRER_MAX_LENGTH = 512;\n\n/** Max stored length for the `User-Agent` header — truncated on insert. */\nexport const USER_AGENT_MAX_LENGTH = 256;\n\n/** Pattern to escape LIKE wildcards: %, _, and backslash */\nconst LIKE_ESCAPE_RE = /[\\\\%_]/g;\n\n/**\n * Truncate a header-derived string to `max` chars, preserving `null`/`undefined`\n * as `null`. Empty strings stay empty (the caller decides whether to coerce).\n */\nfunction truncateOrNull(value: string | null | undefined, max: number): string | null {\n\tif (value === null || value === undefined) return null;\n\treturn value.length > max ? value.slice(0, max) : value;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface Redirect {\n\tid: string;\n\tsource: string;\n\tdestination: string;\n\ttype: number;\n\tisPattern: boolean;\n\tenabled: boolean;\n\thits: number;\n\tlastHitAt: string | null;\n\tgroupName: string | null;\n\tauto: boolean;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface CreateRedirectInput {\n\tsource: string;\n\tdestination: string;\n\ttype?: number;\n\tisPattern?: boolean;\n\tenabled?: boolean;\n\tgroupName?: string | null;\n\tauto?: boolean;\n}\n\nexport interface UpdateRedirectInput {\n\tsource?: string;\n\tdestination?: string;\n\ttype?: number;\n\tisPattern?: boolean;\n\tenabled?: boolean;\n\tgroupName?: string | null;\n}\n\nexport interface NotFoundEntry {\n\tid: string;\n\tpath: string;\n\treferrer: string | null;\n\tuserAgent: string | null;\n\tip: string | null;\n\tcreatedAt: string;\n}\n\nexport interface NotFoundSummary {\n\tpath: string;\n\tcount: number;\n\tlastSeen: string;\n\ttopReferrer: string | null;\n}\n\nexport interface RedirectMatch {\n\tredirect: Redirect;\n\tresolvedDestination: string;\n}\n\nexport interface VersionedRedirectRecord {\n\tredirect: Redirect;\n\tconfigRevision: string;\n}\n\nexport class RedirectWriteBusyError extends Error {\n\toverride readonly name = \"RedirectWriteBusyError\";\n}\n\nexport interface RedirectWriteFence {\n\ttoken: string;\n\tgeneration: number;\n}\n\nconst REDIRECT_WRITE_LOCK_ID = 1;\nconst REDIRECT_WRITE_LEASE_MS = 30_000;\nconst REDIRECT_WRITE_LOCK_ATTEMPTS = 5;\nconst POSTGRES_REDIRECT_LOCK_KEY = 1_168_624_763;\n\n// ---------------------------------------------------------------------------\n// Row mapping\n// ---------------------------------------------------------------------------\n\nfunction rowToRedirect(row: RedirectTable): Redirect {\n\treturn {\n\t\tid: row.id,\n\t\tsource: row.source,\n\t\tdestination: row.destination,\n\t\ttype: row.type,\n\t\tisPattern: row.is_pattern === 1,\n\t\tenabled: row.enabled === 1,\n\t\thits: row.hits,\n\t\tlastHitAt: row.last_hit_at,\n\t\tgroupName: row.group_name,\n\t\tauto: row.auto === 1,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Repository\n// ---------------------------------------------------------------------------\n\nexport class RedirectRepository {\n\tconstructor(readonly db: Kysely<Database>) {}\n\n\t// --- CRUD ---------------------------------------------------------------\n\n\tasync findById(id: string): Promise<Redirect | null> {\n\t\treturn (await this.findVersionedById(id))?.redirect ?? null;\n\t}\n\n\tasync findVersionedById(id: string): Promise<VersionedRedirectRecord | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_redirects\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? { redirect: rowToRedirect(row), configRevision: row.config_revision } : null;\n\t}\n\n\tasync findBySource(source: string): Promise<Redirect | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_redirects\")\n\t\t\t.selectAll()\n\t\t\t.where(\"source\", \"=\", source)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? rowToRedirect(row) : null;\n\t}\n\n\tasync findConfigRevision(id: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_redirects\")\n\t\t\t.select(\"config_revision\")\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row?.config_revision ?? null;\n\t}\n\n\tasync withWriteLock<T>(\n\t\taction: (fence: RedirectWriteFence, repository: RedirectRepository) => Promise<T>,\n\t): Promise<T> {\n\t\tif (isPostgres(this.db)) {\n\t\t\tif (this.db.isTransaction) {\n\t\t\t\tawait sql`SELECT pg_advisory_xact_lock(${POSTGRES_REDIRECT_LOCK_KEY})`.execute(this.db);\n\t\t\t\treturn this.withLease(action);\n\t\t\t}\n\t\t\treturn this.db.transaction().execute(async (transaction) => {\n\t\t\t\tawait sql`SELECT pg_advisory_xact_lock(${POSTGRES_REDIRECT_LOCK_KEY})`.execute(transaction);\n\t\t\t\tconst repository = new RedirectRepository(transaction);\n\t\t\t\treturn repository.withLease(action);\n\t\t\t});\n\t\t}\n\t\treturn this.withLease(action);\n\t}\n\n\tprivate async withLease<T>(\n\t\taction: (fence: RedirectWriteFence, repository: RedirectRepository) => Promise<T>,\n\t): Promise<T> {\n\t\tconst token = ulid();\n\t\tlet fence: RedirectWriteFence | undefined;\n\t\tfor (let attempt = 0; attempt < REDIRECT_WRITE_LOCK_ATTEMPTS; attempt++) {\n\t\t\tconst now = Date.now();\n\t\t\tconst result = await this.db\n\t\t\t\t.updateTable(\"_emdash_redirect_write_lock\")\n\t\t\t\t.set({\n\t\t\t\t\ttoken,\n\t\t\t\t\texpires_at: now + REDIRECT_WRITE_LEASE_MS,\n\t\t\t\t\tgeneration: sql`generation + 1`,\n\t\t\t\t})\n\t\t\t\t.where(\"id\", \"=\", REDIRECT_WRITE_LOCK_ID)\n\t\t\t\t.where((eb) => eb.or([eb(\"token\", \"=\", \"\"), eb(\"expires_at\", \"<\", now)]))\n\t\t\t\t.returning(\"generation\")\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (result) {\n\t\t\t\tfence = { token, generation: result.generation };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));\n\t\t}\n\t\tif (!fence) {\n\t\t\tthrow new RedirectWriteBusyError(\"Another redirect change is in progress\");\n\t\t}\n\t\ttry {\n\t\t\treturn await action(fence, this);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait this.db\n\t\t\t\t\t.updateTable(\"_emdash_redirect_write_lock\")\n\t\t\t\t\t.set({ token: \"\", expires_at: 0 })\n\t\t\t\t\t.where(\"id\", \"=\", REDIRECT_WRITE_LOCK_ID)\n\t\t\t\t\t.where(\"token\", \"=\", token)\n\t\t\t\t\t.execute();\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to release redirect write lock:\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync findMany(opts: {\n\t\tcursor?: string;\n\t\tlimit?: number;\n\t\tsearch?: string;\n\t\tgroup?: string;\n\t\tenabled?: boolean;\n\t\tauto?: boolean;\n\t}): Promise<FindManyResult<Redirect>> {\n\t\tconst limit = Math.min(Math.max(opts.limit ?? 50, 1), 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_redirects\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"created_at\", \"desc\")\n\t\t\t.orderBy(\"id\", \"desc\")\n\t\t\t.limit(limit + 1);\n\n\t\tif (opts.search) {\n\t\t\t// Escape LIKE wildcards in the search term to prevent injection.\n\t\t\t// Must include ESCAPE clause for SQLite to recognize backslash as escape char.\n\t\t\tconst escaped = opts.search.replace(LIKE_ESCAPE_RE, (c) => `\\\\${c}`);\n\t\t\tconst term = `%${escaped}%`;\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\tsql<boolean>`source LIKE ${term} ESCAPE '\\\\'`,\n\t\t\t\t\tsql<boolean>`destination LIKE ${term} ESCAPE '\\\\'`,\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tif (opts.group !== undefined) {\n\t\t\tquery = query.where(\"group_name\", \"=\", opts.group);\n\t\t}\n\n\t\tif (opts.enabled !== undefined) {\n\t\t\tquery = query.where(\"enabled\", \"=\", opts.enabled ? 1 : 0);\n\t\t}\n\n\t\tif (opts.auto !== undefined) {\n\t\t\tquery = query.where(\"auto\", \"=\", opts.auto ? 1 : 0);\n\t\t}\n\n\t\tif (opts.cursor) {\n\t\t\tconst decoded = decodeCursor(opts.cursor);\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"created_at\", \"<\", decoded.orderValue),\n\t\t\t\t\teb.and([eb(\"created_at\", \"=\", decoded.orderValue), eb(\"id\", \"<\", decoded.id)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\tconst items = rows.slice(0, limit).map(rowToRedirect);\n\t\tconst result: FindManyResult<Redirect> = { items };\n\n\t\tif (rows.length > limit) {\n\t\t\tconst last = items.at(-1)!;\n\t\t\tresult.nextCursor = encodeCursor(last.createdAt, last.id);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync create(input: CreateRedirectInput, fence?: RedirectWriteFence): Promise<Redirect> {\n\t\tif (!fence) {\n\t\t\treturn this.withWriteLock((currentFence, repository) =>\n\t\t\t\trepository.create(input, currentFence),\n\t\t\t);\n\t\t}\n\t\tconst id = ulid();\n\t\tconst now = new Date().toISOString();\n\t\tconst patternFlag = input.isPattern ?? isPattern(input.source);\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_redirects\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tsource: input.source,\n\t\t\t\tdestination: input.destination,\n\t\t\t\ttype: input.type ?? 301,\n\t\t\t\tis_pattern: patternFlag ? 1 : 0,\n\t\t\t\tenabled: input.enabled !== false ? 1 : 0,\n\t\t\t\thits: 0,\n\t\t\t\tlast_hit_at: null,\n\t\t\t\tgroup_name: input.groupName ?? null,\n\t\t\t\tauto: input.auto ? 1 : 0,\n\t\t\t\tconfig_revision: ulid(),\n\t\t\t\tsource_guard: 1,\n\t\t\t\twrite_generation: fence?.generation ?? 0,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn (await this.findById(id))!;\n\t}\n\n\tasync update(\n\t\tid: string,\n\t\tinput: UpdateRedirectInput,\n\t\texpectedRevision?: string,\n\t\tfence?: RedirectWriteFence,\n\t): Promise<Redirect | null> {\n\t\tif (!fence) {\n\t\t\treturn this.withWriteLock((currentFence, repository) =>\n\t\t\t\trepository.update(id, input, expectedRevision, currentFence),\n\t\t\t);\n\t\t}\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst now = new Date(\n\t\t\tMath.max(Date.now(), new Date(existing.updatedAt).getTime() + 1),\n\t\t).toISOString();\n\t\tconst values: Record<string, unknown> = { updated_at: now, config_revision: ulid() };\n\t\tif (fence) values.write_generation = fence.generation;\n\n\t\tif (input.source !== undefined) {\n\t\t\tvalues.source = input.source;\n\t\t\tvalues.source_guard = 1;\n\t\t\tvalues.is_pattern =\n\t\t\t\tinput.isPattern !== undefined ? (input.isPattern ? 1 : 0) : isPattern(input.source) ? 1 : 0;\n\t\t} else if (input.isPattern !== undefined) {\n\t\t\tvalues.is_pattern = input.isPattern ? 1 : 0;\n\t\t}\n\n\t\tif (input.destination !== undefined) values.destination = input.destination;\n\t\tif (input.type !== undefined) values.type = input.type;\n\t\tif (input.enabled !== undefined) values.enabled = input.enabled ? 1 : 0;\n\t\tif (input.groupName !== undefined) values.group_name = input.groupName;\n\n\t\tlet query = this.db.updateTable(\"_emdash_redirects\").set(values).where(\"id\", \"=\", id);\n\t\tif (expectedRevision !== undefined) {\n\t\t\tquery = query.where(\"config_revision\", \"=\", expectedRevision);\n\t\t}\n\t\tif (fence) {\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.exists(\n\t\t\t\t\teb\n\t\t\t\t\t\t.selectFrom(\"_emdash_redirect_write_lock\")\n\t\t\t\t\t\t.select(\"id\")\n\t\t\t\t\t\t.where(\"id\", \"=\", REDIRECT_WRITE_LOCK_ID)\n\t\t\t\t\t\t.where(\"token\", \"=\", fence.token)\n\t\t\t\t\t\t.where(\"generation\", \"=\", fence.generation),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tconst result = await query.executeTakeFirst();\n\t\tif (BigInt(result.numUpdatedRows) === 0n) return null;\n\n\t\treturn (await this.findById(id))!;\n\t}\n\n\tasync delete(\n\t\tid: string,\n\t\texpectedRevision?: string,\n\t\tfence?: RedirectWriteFence,\n\t): Promise<boolean> {\n\t\tif (!fence) {\n\t\t\treturn this.withWriteLock((currentFence, repository) =>\n\t\t\t\trepository.delete(id, expectedRevision, currentFence),\n\t\t\t);\n\t\t}\n\t\tlet query = this.db.deleteFrom(\"_emdash_redirects\").where(\"id\", \"=\", id);\n\t\tif (expectedRevision !== undefined) {\n\t\t\tquery = query.where(\"config_revision\", \"=\", expectedRevision);\n\t\t}\n\t\tif (fence) {\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.exists(\n\t\t\t\t\teb\n\t\t\t\t\t\t.selectFrom(\"_emdash_redirect_write_lock\")\n\t\t\t\t\t\t.select(\"id\")\n\t\t\t\t\t\t.where(\"id\", \"=\", REDIRECT_WRITE_LOCK_ID)\n\t\t\t\t\t\t.where(\"token\", \"=\", fence.token)\n\t\t\t\t\t\t.where(\"generation\", \"=\", fence.generation),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn BigInt(result.numDeletedRows) > 0n;\n\t}\n\n\t/**\n\t * Fetch all enabled redirects (for loop detection graph building).\n\t * Not paginated — returns the full set.\n\t */\n\tasync findAllEnabled(): Promise<Redirect[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_redirects\")\n\t\t\t.selectAll()\n\t\t\t.where(\"enabled\", \"=\", 1)\n\t\t\t.execute();\n\t\treturn rows.map(rowToRedirect);\n\t}\n\n\t// --- Matching -----------------------------------------------------------\n\n\tasync findExactMatch(path: string): Promise<Redirect | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_redirects\")\n\t\t\t.selectAll()\n\t\t\t.where(\"source\", \"=\", path)\n\t\t\t.where(\"enabled\", \"=\", 1)\n\t\t\t.where(\"is_pattern\", \"=\", 0)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? rowToRedirect(row) : null;\n\t}\n\n\tasync findEnabledPatternRules(): Promise<Redirect[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_redirects\")\n\t\t\t.selectAll()\n\t\t\t.where(\"enabled\", \"=\", 1)\n\t\t\t.where(\"is_pattern\", \"=\", 1)\n\t\t\t.execute();\n\t\treturn rows.map(rowToRedirect);\n\t}\n\n\t/**\n\t * Match a request path against all enabled redirect rules.\n\t * Checks exact matches first (indexed), then pattern rules.\n\t * Returns the matched redirect and the resolved destination URL.\n\t */\n\tasync matchPath(path: string): Promise<RedirectMatch | null> {\n\t\t// 1. Exact match (fast, indexed)\n\t\tconst exact = await this.findExactMatch(path);\n\t\tif (exact) {\n\t\t\treturn { redirect: exact, resolvedDestination: exact.destination };\n\t\t}\n\n\t\t// 2. Pattern match\n\t\tconst patterns = await this.findEnabledPatternRules();\n\t\tfor (const redirect of patterns) {\n\t\t\tconst compiled = compilePattern(redirect.source);\n\t\t\tconst params = matchPattern(compiled, path);\n\t\t\tif (params) {\n\t\t\t\tconst resolved = interpolateDestination(redirect.destination, params);\n\t\t\t\treturn { redirect, resolvedDestination: resolved };\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t// --- Hit tracking -------------------------------------------------------\n\n\tasync recordHit(id: string): Promise<void> {\n\t\tawait sql`\n\t\t\tUPDATE _emdash_redirects\n\t\t\tSET hits = hits + 1, last_hit_at = ${currentTimestampValue(this.db)}, updated_at = ${currentTimestampValue(this.db)}\n\t\t\tWHERE id = ${id}\n\t\t`.execute(this.db);\n\t}\n\n\t// --- Auto-redirects (slug change) ---------------------------------------\n\n\t/**\n\t * Create an auto-redirect when a content slug changes.\n\t * Uses the collection's URL pattern to compute old/new URLs.\n\t * Collapses existing redirect chains pointing to the old URL and\n\t * removes redirects that would shadow the now-live new URL, so a\n\t * rename that is later reverted cannot form a loop (#1986).\n\t *\n\t * Returns null when old and new URL are identical (nothing to redirect).\n\t */\n\tasync createAutoRedirect(\n\t\tcollection: string,\n\t\toldSlug: string,\n\t\tnewSlug: string,\n\t\tcontentId: string,\n\t\turlPattern: string | null,\n\t\toldPublishedAt?: string | null,\n\t\tnewPublishedAt?: string | null,\n\t): Promise<Redirect | null> {\n\t\treturn this.withWriteLock(async (fence, repository) => {\n\t\t\tconst oldUrl = interpolateUrlPattern({\n\t\t\t\tpattern: urlPattern,\n\t\t\t\tcollection,\n\t\t\t\tslug: oldSlug,\n\t\t\t\tid: contentId,\n\t\t\t\tdate: oldPublishedAt,\n\t\t\t});\n\t\t\tconst newUrl = interpolateUrlPattern({\n\t\t\t\tpattern: urlPattern,\n\t\t\t\tcollection,\n\t\t\t\tslug: newSlug,\n\t\t\t\tid: contentId,\n\t\t\t\tdate: newPublishedAt,\n\t\t\t});\n\n\t\t\t// A redirect from a URL to itself would make the page unreachable\n\t\t\tif (oldUrl === newUrl) return null;\n\n\t\t\t// The new URL serves live content again — any redirect from it would\n\t\t\tawait repository.db\n\t\t\t\t.deleteFrom(\"_emdash_redirects\")\n\t\t\t\t.where(\"source\", \"=\", newUrl)\n\t\t\t\t.where((eb) =>\n\t\t\t\t\teb.exists(\n\t\t\t\t\t\teb\n\t\t\t\t\t\t\t.selectFrom(\"_emdash_redirect_write_lock\")\n\t\t\t\t\t\t\t.select(\"id\")\n\t\t\t\t\t\t\t.where(\"id\", \"=\", REDIRECT_WRITE_LOCK_ID)\n\t\t\t\t\t\t\t.where(\"token\", \"=\", fence.token)\n\t\t\t\t\t\t\t.where(\"generation\", \"=\", fence.generation),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.execute();\n\n\t\t\t// Collapse chains: update any existing redirects pointing to the old URL\n\t\t\tawait repository.collapseChains(oldUrl, newUrl, fence);\n\n\t\t\t// Check if a redirect from this source already exists\n\t\t\tconst existing = await repository.findBySource(oldUrl);\n\t\t\tif (existing) {\n\t\t\t\t// Update the existing redirect to point to the new URL\n\t\t\t\treturn (await repository.update(existing.id, { destination: newUrl }, undefined, fence))!;\n\t\t\t}\n\n\t\t\treturn repository.create(\n\t\t\t\t{\n\t\t\t\t\tsource: oldUrl,\n\t\t\t\t\tdestination: newUrl,\n\t\t\t\t\ttype: 301,\n\t\t\t\t\tisPattern: false,\n\t\t\t\t\tauto: true,\n\t\t\t\t\tgroupName: \"Auto: slug change\",\n\t\t\t\t},\n\t\t\t\tfence,\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Update all redirects whose destination matches oldDestination\n\t * to point to newDestination instead. Prevents redirect chains.\n\t * Returns the number of updated rows.\n\t */\n\tasync collapseChains(\n\t\toldDestination: string,\n\t\tnewDestination: string,\n\t\tfence?: RedirectWriteFence,\n\t): Promise<number> {\n\t\tif (!fence) {\n\t\t\treturn this.withWriteLock((currentFence, repository) =>\n\t\t\t\trepository.collapseChains(oldDestination, newDestination, currentFence),\n\t\t\t);\n\t\t}\n\t\tlet query = this.db\n\t\t\t.updateTable(\"_emdash_redirects\")\n\t\t\t.set({\n\t\t\t\tdestination: newDestination,\n\t\t\t\tupdated_at: new Date().toISOString(),\n\t\t\t\tconfig_revision: ulid(),\n\t\t\t\t...(fence ? { write_generation: fence.generation } : {}),\n\t\t\t})\n\t\t\t.where(\"destination\", \"=\", oldDestination);\n\t\tif (fence) {\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.exists(\n\t\t\t\t\teb\n\t\t\t\t\t\t.selectFrom(\"_emdash_redirect_write_lock\")\n\t\t\t\t\t\t.select(\"id\")\n\t\t\t\t\t\t.where(\"id\", \"=\", REDIRECT_WRITE_LOCK_ID)\n\t\t\t\t\t\t.where(\"token\", \"=\", fence.token)\n\t\t\t\t\t\t.where(\"generation\", \"=\", fence.generation),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result.numUpdatedRows);\n\t}\n\n\t// --- 404 log ------------------------------------------------------------\n\n\t/**\n\t * Record a 404 hit for `entry.path`.\n\t *\n\t * Dedups by path: repeat hits increment `hits` and refresh `last_seen_at`\n\t * on the existing row instead of inserting a new one. Referrer and\n\t * user-agent are truncated to bounded lengths so a malicious client can't\n\t * blow up storage with huge headers. When the table would exceed\n\t * MAX_404_LOG_ROWS, the oldest entries (by `last_seen_at`) are evicted.\n\t *\n\t * This is called from the public redirect middleware on every 404 and\n\t * must never throw for an unauthenticated caller — failures bubble up to\n\t * the middleware, which swallows them.\n\t */\n\tasync log404(entry: {\n\t\tpath: string;\n\t\treferrer?: string | null;\n\t\tuserAgent?: string | null;\n\t\tip?: string | null;\n\t}): Promise<void> {\n\t\tconst now = new Date().toISOString();\n\t\tconst referrer = truncateOrNull(entry.referrer, REFERRER_MAX_LENGTH);\n\t\tconst userAgent = truncateOrNull(entry.userAgent, USER_AGENT_MAX_LENGTH);\n\t\tconst ip = entry.ip ?? null;\n\t\tconst id = ulid();\n\n\t\t// Atomic upsert by path. The UNIQUE index on `path` makes this safe\n\t\t// under concurrency: two requests for the same new path can't both\n\t\t// insert — the second one hits the conflict branch and increments\n\t\t// hits instead of failing with a uniqueness error.\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_404_log\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tpath: entry.path,\n\t\t\t\treferrer,\n\t\t\t\tuser_agent: userAgent,\n\t\t\t\tip,\n\t\t\t\thits: 1,\n\t\t\t\tlast_seen_at: now,\n\t\t\t\tcreated_at: now,\n\t\t\t})\n\t\t\t.onConflict((oc) =>\n\t\t\t\toc.column(\"path\").doUpdateSet({\n\t\t\t\t\thits: sql`${sql.ref(\"_emdash_404_log.hits\")} + 1`,\n\t\t\t\t\tlast_seen_at: now,\n\t\t\t\t\treferrer,\n\t\t\t\t\tuser_agent: userAgent,\n\t\t\t\t\tip,\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Delete the oldest rows from `_emdash_404_log` if the row count exceeds\n\t * MAX_404_LOG_ROWS. \"Oldest\" is by `last_seen_at`, so a path that keeps\n\t * getting hit stays in the table even if it was first seen long ago.\n\t *\n\t * Called by scheduled system cleanup, never by the anonymous request path.\n\t */\n\tasync cleanup404Log(): Promise<number> {\n\t\t// Keep the newest rows in one statement. Deriving the victims inside the\n\t\t// DELETE makes overlapping cleanup runs idempotent: each statement\n\t\t// evaluates the current newest set instead of acting on a stale count.\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_404_log\")\n\t\t\t.where(\n\t\t\t\t\"id\",\n\t\t\t\t\"not in\",\n\t\t\t\tthis.db\n\t\t\t\t\t.selectFrom(\"_emdash_404_log\")\n\t\t\t\t\t.select(\"id\")\n\t\t\t\t\t.orderBy(\"last_seen_at\", \"desc\")\n\t\t\t\t\t.orderBy(\"id\", \"desc\")\n\t\t\t\t\t.limit(MAX_404_LOG_ROWS),\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows);\n\t}\n\n\tasync find404s(opts: {\n\t\tcursor?: string;\n\t\tlimit?: number;\n\t\tsearch?: string;\n\t}): Promise<FindManyResult<NotFoundEntry>> {\n\t\tconst limit = Math.min(Math.max(opts.limit ?? 50, 1), 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_404_log\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"created_at\", \"desc\")\n\t\t\t.orderBy(\"id\", \"desc\")\n\t\t\t.limit(limit + 1);\n\n\t\tif (opts.search) {\n\t\t\tconst escaped = opts.search.replace(LIKE_ESCAPE_RE, (c) => `\\\\${c}`);\n\t\t\tconst term = `%${escaped}%`;\n\t\t\tquery = query.where(sql<boolean>`path LIKE ${term} ESCAPE '\\\\'`);\n\t\t}\n\n\t\tif (opts.cursor) {\n\t\t\tconst decoded = decodeCursor(opts.cursor);\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"created_at\", \"<\", decoded.orderValue),\n\t\t\t\t\teb.and([eb(\"created_at\", \"=\", decoded.orderValue), eb(\"id\", \"<\", decoded.id)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\tconst items: NotFoundEntry[] = rows.slice(0, limit).map((row) => ({\n\t\t\tid: row.id,\n\t\t\tpath: row.path,\n\t\t\treferrer: row.referrer,\n\t\t\tuserAgent: row.user_agent,\n\t\t\tip: row.ip,\n\t\t\tcreatedAt: row.created_at,\n\t\t}));\n\n\t\tconst result: FindManyResult<NotFoundEntry> = { items };\n\t\tif (rows.length > limit) {\n\t\t\tconst last = items.at(-1)!;\n\t\t\tresult.nextCursor = encodeCursor(last.createdAt, last.id);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync get404Summary(limit = 50): Promise<NotFoundSummary[]> {\n\t\t// Since rows are now deduped by path, each path has exactly one row\n\t\t// with `hits` as the running count and `last_seen_at` as the latest\n\t\t// timestamp. The subquery for `top_referrer` collapses to a simple\n\t\t// pick of the row's stored referrer (the most recent one seen).\n\t\tconst rows = await sql<{\n\t\t\tpath: string;\n\t\t\tcount: number;\n\t\t\tlast_seen: string;\n\t\t\ttop_referrer: string | null;\n\t\t}>`\n\t\t\tSELECT\n\t\t\t\tpath,\n\t\t\t\tSUM(hits) as count,\n\t\t\t\tMAX(last_seen_at) as last_seen,\n\t\t\t\t(\n\t\t\t\t\tSELECT referrer FROM _emdash_404_log AS inner_log\n\t\t\t\t\tWHERE inner_log.path = _emdash_404_log.path\n\t\t\t\t\t\tAND referrer IS NOT NULL AND referrer != ''\n\t\t\t\t\tLIMIT 1\n\t\t\t\t) as top_referrer\n\t\t\tFROM _emdash_404_log\n\t\t\tGROUP BY path\n\t\t\tORDER BY count DESC\n\t\t\tLIMIT ${limit}\n\t\t`.execute(this.db);\n\n\t\treturn rows.rows.map((row) => ({\n\t\t\tpath: row.path,\n\t\t\tcount: Number(row.count),\n\t\t\tlastSeen: row.last_seen,\n\t\t\ttopReferrer: row.top_referrer,\n\t\t}));\n\t}\n\n\tasync delete404(id: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_404_log\")\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn BigInt(result.numDeletedRows) > 0n;\n\t}\n\n\tasync clear404s(): Promise<number> {\n\t\tconst result = await this.db.deleteFrom(\"_emdash_404_log\").executeTakeFirst();\n\t\treturn Number(result.numDeletedRows);\n\t}\n\n\tasync prune404s(olderThan: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(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AAM;GACxB,UAAU,IAAI;GACd,aAAa,IAAI;GACjB,EAAE;;CAGJ,MAAM,UAAU,IAA8B;EAC7C,MAAM,SAAS,MAAM,KAAK,GACxB,WAAW,kBAAkB,CAC7B,MAAM,MAAM,KAAK,GAAG,CACpB,kBAAkB;AACpB,SAAO,OAAO,OAAO,eAAe,GAAG;;CAGxC,MAAM,YAA6B;EAClC,MAAM,SAAS,MAAM,KAAK,GAAG,WAAW,kBAAkB,CAAC,kBAAkB;AAC7E,SAAO,OAAO,OAAO,eAAe;;CAGrC,MAAM,UAAU,WAAoC;EACnD,MAAM,SAAS,MAAM,KAAK,GACxB,WAAW,kBAAkB,CAC7B,MAAM,cAAc,KAAK,UAAU,CACnC,kBAAkB;AACpB,SAAO,OAAO,OAAO,eAAe"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as OptionsRepository } from "./options-DhrI7eMv.mjs";
|
|
2
2
|
import { i as InvalidCursorError } from "./types-BkUg2yHx.mjs";
|
|
3
3
|
import { a as validateDestinationParams, o as validatePattern, r as isPattern } from "./patterns-BhAvqO0S.mjs";
|
|
4
|
-
import { n as RedirectWriteBusyError, t as RedirectRepository } from "./redirect-
|
|
4
|
+
import { n as RedirectWriteBusyError, t as RedirectRepository } from "./redirect-B29UjdUn.mjs";
|
|
5
5
|
import { n as invalidateRedirectCache } from "./cache-m7UEkRFV.mjs";
|
|
6
6
|
import { n as isTerminalStatus } from "./status-DZKIG4a9.mjs";
|
|
7
7
|
import { n as wouldCreateLoop, t as detectLoops } from "./loops-BQSzv5Zn.mjs";
|
|
@@ -443,4 +443,4 @@ async function handleNotFoundPrune(db, olderThan) {
|
|
|
443
443
|
|
|
444
444
|
//#endregion
|
|
445
445
|
export { handleRedirectCreate as a, handleRedirectList as c, handleNotFoundSummary as i, handleRedirectUpdate as l, handleNotFoundList as n, handleRedirectDelete as o, handleNotFoundPrune as r, handleRedirectGet as s, handleNotFoundClear as t };
|
|
446
|
-
//# sourceMappingURL=redirects-
|
|
446
|
+
//# sourceMappingURL=redirects-Ca2MPfEG.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirects-CYu1u1aK.mjs","names":[],"sources":["../src/api/handlers/redirects.ts"],"sourcesContent":["/**\n * Redirect CRUD and 404 log handlers\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { OptionsRepository } from \"../../database/repositories/options.js\";\nimport {\n\tRedirectRepository,\n\tRedirectWriteBusyError,\n\ttype RedirectWriteFence,\n\ttype Redirect,\n\ttype NotFoundEntry,\n\ttype NotFoundSummary,\n} from \"../../database/repositories/redirect.js\";\nimport { InvalidCursorError } from \"../../database/repositories/types.js\";\nimport type { FindManyResult } from \"../../database/repositories/types.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { invalidateRedirectCache } from \"../../redirects/cache.js\";\nimport { wouldCreateLoop, detectLoops, type RedirectEdge } from \"../../redirects/loops.js\";\nimport { validatePattern, validateDestinationParams, isPattern } from \"../../redirects/patterns.js\";\nimport { isTerminalStatus } from \"../../redirects/status.js\";\nimport type { ApiResult } from \"../types.js\";\n\nasync function withRedirectWriteLock<T>(\n\trepo: RedirectRepository,\n\taction: (fence: RedirectWriteFence, repository: RedirectRepository) => Promise<ApiResult<T>>,\n): Promise<ApiResult<T>> {\n\ttry {\n\t\treturn await repo.withWriteLock(action);\n\t} catch (error) {\n\t\tif (error instanceof RedirectWriteBusyError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"REDIRECT_BUSY\", message: \"Another redirect change is in progress\" },\n\t\t\t};\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Redirects\n// ---------------------------------------------------------------------------\n\n/**\n * List redirects with cursor pagination and optional filters\n */\nexport async function handleRedirectList(\n\tdb: Kysely<Database>,\n\tparams: {\n\t\tcursor?: string;\n\t\tlimit?: number;\n\t\tsearch?: string;\n\t\tgroup?: string;\n\t\tenabled?: boolean;\n\t\tauto?: boolean;\n\t},\n): Promise<ApiResult<FindManyResult<Redirect> & { loopRedirectIds?: string[] }>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst result = await repo.findMany(params);\n\n\t\tconst loopRedirectIds = await getLoopRedirectIds(db);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\t...result,\n\t\t\t\t...(loopRedirectIds.length > 0 ? { loopRedirectIds } : {}),\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tif (error instanceof InvalidCursorError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_CURSOR\", message: error.message },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_LIST_ERROR\", message: \"Failed to fetch redirects\" },\n\t\t};\n\t}\n}\n\n/**\n * Create a redirect rule\n */\nexport async function handleRedirectCreate(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tsource: string;\n\t\tdestination?: string;\n\t\ttype?: number;\n\t\tenabled?: boolean;\n\t\tgroupName?: string | null;\n\t},\n): Promise<ApiResult<Redirect>> {\n\ttry {\n\t\tconst lockRepo = new RedirectRepository(db);\n\t\tconst result = await withRedirectWriteLock(lockRepo, async (fence, repo) => {\n\t\t\tconst type = input.type ?? 301;\n\t\t\t// Terminal statuses (410 Gone / 451) are served directly and have no\n\t\t\t// destination — skip the destination/loop checks for them.\n\t\t\tconst terminal = isTerminalStatus(type);\n\t\t\tconst destination = terminal ? \"\" : (input.destination ?? \"\");\n\n\t\t\t// Source and destination must differ\n\t\t\tif (!terminal && input.source === destination) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: \"Source and destination must be different\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// If source looks like a pattern, validate it\n\t\t\tconst sourceIsPattern = isPattern(input.source);\n\t\t\tif (sourceIsPattern) {\n\t\t\t\tconst patternError = validatePattern(input.source);\n\t\t\t\tif (patternError) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"VALIDATION_ERROR\", message: `Invalid source pattern: ${patternError}` },\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Validate destination params reference valid source params\n\t\t\t\t// (terminal rules have no destination to interpolate)\n\t\t\t\tif (!terminal) {\n\t\t\t\t\tconst destError = validateDestinationParams(input.source, destination);\n\t\t\t\t\tif (destError) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\terror: { code: \"VALIDATION_ERROR\", message: destError },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check for duplicate source (exact match only for non-patterns)\n\t\t\tconst existing = await repo.findBySource(input.source);\n\t\t\tif (existing) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\tmessage: `A redirect from \"${input.source}\" already exists`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Check for redirect loops (skip if creating as disabled, or terminal —\n\t\t\t// a Gone rule has no destination, so it can't form a loop)\n\t\t\tif (!terminal && input.enabled !== false) {\n\t\t\t\tconst edges = toEdges(await repo.findAllEnabled());\n\t\t\t\tconst loopPath = wouldCreateLoop(input.source, destination, edges);\n\t\t\t\tif (loopPath) return loopError(loopPath);\n\t\t\t}\n\n\t\t\tconst redirect = await repo.create(\n\t\t\t\t{\n\t\t\t\t\tsource: input.source,\n\t\t\t\t\tdestination,\n\t\t\t\t\ttype,\n\t\t\t\t\tisPattern: sourceIsPattern,\n\t\t\t\t\tenabled: input.enabled ?? true,\n\t\t\t\t\tgroupName: input.groupName ?? null,\n\t\t\t\t},\n\t\t\t\tfence,\n\t\t\t);\n\t\t\treturn { success: true, data: redirect };\n\t\t});\n\t\tif (result.success) invalidateRedirectCache();\n\t\treturn result;\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_CREATE_ERROR\", message: \"Failed to create redirect\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a redirect by ID\n */\nexport async function handleRedirectGet(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<Redirect>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst redirect = await repo.findById(id);\n\n\t\tif (!redirect) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Redirect \"${id}\" not found` },\n\t\t\t};\n\t\t}\n\n\t\treturn { success: true, data: redirect };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_GET_ERROR\", message: \"Failed to fetch redirect\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a redirect by ID\n */\nexport async function handleRedirectUpdate(\n\tdb: Kysely<Database>,\n\tid: string,\n\tinput: {\n\t\tsource?: string;\n\t\tdestination?: string;\n\t\ttype?: number;\n\t\tenabled?: boolean;\n\t\tgroupName?: string | null;\n\t},\n\toptions?: { expectedRevision?: string },\n): Promise<ApiResult<Redirect>> {\n\ttry {\n\t\tconst lockRepo = new RedirectRepository(db);\n\t\tconst result = await withRedirectWriteLock(lockRepo, async (fence, repo) => {\n\t\t\tconst existing = await repo.findById(id);\n\t\t\tif (!existing) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: \"NOT_FOUND\", message: `Redirect \"${id}\" not found` },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (options?.expectedRevision !== undefined) {\n\t\t\t\tconst currentRevision = await repo.findConfigRevision(id);\n\t\t\t\tif (currentRevision !== options.expectedRevision) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"CONFLICT\", message: \"Redirect changed since it was read\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst newSource = input.source ?? existing.source;\n\t\t\tconst newType = input.type ?? existing.type;\n\t\t\tconst terminal = isTerminalStatus(newType);\n\t\t\tconst newDest = terminal ? \"\" : (input.destination ?? existing.destination);\n\t\t\tif (!terminal && !newDest) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: \"destination is required for redirect types (301, 302, 307, 308)\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Source and destination must differ\n\t\t\tif (!terminal && newSource === newDest) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: \"Source and destination must be different\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// If source is changing, validate patterns\n\t\t\tif (input.source !== undefined) {\n\t\t\t\tconst sourceIsPattern = isPattern(input.source);\n\t\t\t\tif (sourceIsPattern) {\n\t\t\t\t\tconst patternError = validatePattern(input.source);\n\t\t\t\t\tif (patternError) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\t\t\tmessage: `Invalid source pattern: ${patternError}`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Check for duplicate source (exclude self)\n\t\t\t\tconst dup = await repo.findBySource(input.source);\n\t\t\t\tif (dup && dup.id !== id) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\t\tmessage: `A redirect from \"${input.source}\" already exists`,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Validate destination params against the (possibly updated) source\n\t\t\tconst newSourceIsPattern = isPattern(newSource);\n\t\t\tif (newSourceIsPattern && !terminal) {\n\t\t\t\tconst destError = validateDestinationParams(newSource, newDest);\n\t\t\t\tif (destError) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"VALIDATION_ERROR\", message: destError },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check for redirect loops if source or destination changed\n\t\t\tconst willBeEnabled = input.enabled ?? existing.enabled;\n\t\t\tif (\n\t\t\t\t!terminal &&\n\t\t\t\twillBeEnabled &&\n\t\t\t\t(input.source !== undefined || input.destination !== undefined)\n\t\t\t) {\n\t\t\t\tconst edges = toEdges(await repo.findAllEnabled());\n\t\t\t\tconst loopPath = wouldCreateLoop(newSource, newDest, edges, id);\n\t\t\t\tif (loopPath) return loopError(loopPath);\n\t\t\t}\n\n\t\t\tconst updated = await repo.update(\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\tsource: input.source,\n\t\t\t\t\tdestination: terminal ? \"\" : input.destination,\n\t\t\t\t\ttype: input.type,\n\t\t\t\t\tenabled: input.enabled,\n\t\t\t\t\tgroupName: input.groupName,\n\t\t\t\t},\n\t\t\t\toptions?.expectedRevision,\n\t\t\t\tfence,\n\t\t\t);\n\n\t\t\tif (!updated) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: options?.expectedRevision\n\t\t\t\t\t\t? { code: \"CONFLICT\", message: \"Redirect changed since it was read\" }\n\t\t\t\t\t\t: { code: \"REDIRECT_UPDATE_ERROR\", message: \"Failed to update redirect\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Recompute cache — redirect was modified, so re-fetch\n\t\t\tawait updateLoopCache(repo.db);\n\t\t\treturn { success: true, data: updated };\n\t\t});\n\t\tif (result.success) invalidateRedirectCache();\n\t\treturn result;\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_UPDATE_ERROR\", message: \"Failed to update redirect\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a redirect by ID\n */\nexport async function handleRedirectDelete(\n\tdb: Kysely<Database>,\n\tid: string,\n\toptions?: { expectedRevision?: string },\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst lockRepo = new RedirectRepository(db);\n\t\tconst result = await withRedirectWriteLock<{ deleted: true }>(lockRepo, async (fence, repo) => {\n\t\t\tif (options?.expectedRevision !== undefined) {\n\t\t\t\tconst existing = await repo.findById(id);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"NOT_FOUND\", message: `Redirect \"${id}\" not found` },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst currentRevision = await repo.findConfigRevision(id);\n\t\t\t\tif (currentRevision !== options.expectedRevision) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"CONFLICT\", message: \"Redirect changed since it was read\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst deleted = await repo.delete(id, options?.expectedRevision, fence);\n\n\t\t\tif (!deleted) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: options?.expectedRevision\n\t\t\t\t\t\t? { code: \"CONFLICT\", message: \"Redirect changed since it was read\" }\n\t\t\t\t\t\t: { code: \"NOT_FOUND\", message: `Redirect \"${id}\" not found` },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tawait updateLoopCache(repo.db);\n\t\t\treturn { success: true, data: { deleted: true } };\n\t\t});\n\t\tif (result.success) invalidateRedirectCache();\n\t\treturn result;\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_DELETE_ERROR\", message: \"Failed to delete redirect\" },\n\t\t};\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Loop analysis cache\n// ---------------------------------------------------------------------------\n\nfunction loopError(loopPath: string[]): ApiResult<never> {\n\tconst hops = loopPath\n\t\t.slice(0, -1)\n\t\t.map((p, i) => `${p} \\u2192 ${loopPath[i + 1]}`)\n\t\t.join(\"\\n\");\n\treturn {\n\t\tsuccess: false,\n\t\terror: {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: `This redirect would create a loop:\\n${hops}`,\n\t\t},\n\t};\n}\n\nfunction toEdges(redirects: Redirect[]): RedirectEdge[] {\n\treturn redirects.map((r) => ({\n\t\tid: r.id,\n\t\tsource: r.source,\n\t\tdestination: r.destination,\n\t\tenabled: r.enabled,\n\t\tisPattern: r.isPattern,\n\t}));\n}\n\nconst LOOP_CACHE_KEY = \"_redirect_loop_ids\";\n\n/**\n * Recompute loop redirect IDs and store in the options table.\n */\nasync function updateLoopCache(db: Kysely<Database>): Promise<void> {\n\ttry {\n\t\tconst options = new OptionsRepository(db);\n\t\tconst edges = toEdges(await new RedirectRepository(db).findAllEnabled());\n\t\tconst loopRedirectIds = detectLoops(edges);\n\t\tawait options.set(LOOP_CACHE_KEY, loopRedirectIds);\n\t} catch (error) {\n\t\tconsole.error(\"Failed to update redirect loop cache:\", error);\n\t}\n}\n\n/**\n * Get loop redirect IDs from cache, computing lazily on first access.\n */\nasync function getLoopRedirectIds(db: Kysely<Database>): Promise<string[]> {\n\ttry {\n\t\tconst options = new OptionsRepository(db);\n\t\tconst cached = await options.get<string[]>(LOOP_CACHE_KEY);\n\t\tif (cached !== null) return cached;\n\n\t\t// First access after upgrade — compute and cache\n\t\tawait updateLoopCache(db);\n\t\treturn (await options.get<string[]>(LOOP_CACHE_KEY)) ?? [];\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// 404 Log\n// ---------------------------------------------------------------------------\n\n/**\n * List 404 log entries with cursor pagination\n */\nexport async function handleNotFoundList(\n\tdb: Kysely<Database>,\n\tparams: { cursor?: string; limit?: number; search?: string },\n): Promise<ApiResult<FindManyResult<NotFoundEntry>>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst result = await repo.find404s(params);\n\t\treturn { success: true, data: result };\n\t} catch (error) {\n\t\tif (error instanceof InvalidCursorError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_CURSOR\", message: error.message },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND_LIST_ERROR\", message: \"Failed to fetch 404 log\" },\n\t\t};\n\t}\n}\n\n/**\n * Get 404 summary (grouped by path, sorted by count)\n */\nexport async function handleNotFoundSummary(\n\tdb: Kysely<Database>,\n\tlimit?: number,\n): Promise<ApiResult<{ items: NotFoundSummary[] }>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst items = await repo.get404Summary(limit);\n\t\treturn { success: true, data: { items } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND_SUMMARY_ERROR\", message: \"Failed to fetch 404 summary\" },\n\t\t};\n\t}\n}\n\n/**\n * Clear all 404 log entries\n */\nexport async function handleNotFoundClear(\n\tdb: Kysely<Database>,\n): Promise<ApiResult<{ deleted: number }>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst deleted = await repo.clear404s();\n\t\treturn { success: true, data: { deleted } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND_CLEAR_ERROR\", message: \"Failed to clear 404 log\" },\n\t\t};\n\t}\n}\n\n/**\n * Prune 404 log entries older than a given date\n */\nexport async function handleNotFoundPrune(\n\tdb: Kysely<Database>,\n\tolderThan: string,\n): Promise<ApiResult<{ deleted: number }>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst deleted = await repo.prune404s(olderThan);\n\t\treturn { success: true, data: { deleted } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND_PRUNE_ERROR\", message: \"Failed to prune 404 log\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;AAwBA,eAAe,sBACd,MACA,QACwB;AACxB,KAAI;AACH,SAAO,MAAM,KAAK,cAAc,OAAO;UAC/B,OAAO;AACf,MAAI,iBAAiB,uBACpB,QAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAiB,SAAS;IAA0C;GACnF;AAEF,QAAM;;;;;;AAWR,eAAsB,mBACrB,IACA,QAQgF;AAChF,KAAI;EAEH,MAAM,SAAS,MADF,IAAI,mBAAmB,GAAG,CACb,SAAS,OAAO;EAE1C,MAAM,kBAAkB,MAAM,mBAAmB,GAAG;AAEpD,SAAO;GACN,SAAS;GACT,MAAM;IACL,GAAG;IACH,GAAI,gBAAgB,SAAS,IAAI,EAAE,iBAAiB,GAAG,EAAE;IACzD;GACD;UACO,OAAO;AACf,MAAI,iBAAiB,mBACpB,QAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAkB,SAAS,MAAM;IAAS;GACzD;AAEF,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAuB,SAAS;IAA6B;GAC5E;;;;;;AAOH,eAAsB,qBACrB,IACA,OAO+B;AAC/B,KAAI;EAEH,MAAM,SAAS,MAAM,sBADJ,IAAI,mBAAmB,GAAG,EACU,OAAO,OAAO,SAAS;GAC3E,MAAM,OAAO,MAAM,QAAQ;GAG3B,MAAM,WAAW,iBAAiB,KAAK;GACvC,MAAM,cAAc,WAAW,KAAM,MAAM,eAAe;AAG1D,OAAI,CAAC,YAAY,MAAM,WAAW,YACjC,QA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sources":["../src/api/handlers/redirects.ts"],"sourcesContent":["/**\n * Redirect CRUD and 404 log handlers\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { OptionsRepository } from \"../../database/repositories/options.js\";\nimport {\n\tRedirectRepository,\n\tRedirectWriteBusyError,\n\ttype RedirectWriteFence,\n\ttype Redirect,\n\ttype NotFoundEntry,\n\ttype NotFoundSummary,\n} from \"../../database/repositories/redirect.js\";\nimport { InvalidCursorError } from \"../../database/repositories/types.js\";\nimport type { FindManyResult } from \"../../database/repositories/types.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { invalidateRedirectCache } from \"../../redirects/cache.js\";\nimport { wouldCreateLoop, detectLoops, type RedirectEdge } from \"../../redirects/loops.js\";\nimport { validatePattern, validateDestinationParams, isPattern } from \"../../redirects/patterns.js\";\nimport { isTerminalStatus } from \"../../redirects/status.js\";\nimport type { ApiResult } from \"../types.js\";\n\nasync function withRedirectWriteLock<T>(\n\trepo: RedirectRepository,\n\taction: (fence: RedirectWriteFence, repository: RedirectRepository) => Promise<ApiResult<T>>,\n): Promise<ApiResult<T>> {\n\ttry {\n\t\treturn await repo.withWriteLock(action);\n\t} catch (error) {\n\t\tif (error instanceof RedirectWriteBusyError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"REDIRECT_BUSY\", message: \"Another redirect change is in progress\" },\n\t\t\t};\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Redirects\n// ---------------------------------------------------------------------------\n\n/**\n * List redirects with cursor pagination and optional filters\n */\nexport async function handleRedirectList(\n\tdb: Kysely<Database>,\n\tparams: {\n\t\tcursor?: string;\n\t\tlimit?: number;\n\t\tsearch?: string;\n\t\tgroup?: string;\n\t\tenabled?: boolean;\n\t\tauto?: boolean;\n\t},\n): Promise<ApiResult<FindManyResult<Redirect> & { loopRedirectIds?: string[] }>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst result = await repo.findMany(params);\n\n\t\tconst loopRedirectIds = await getLoopRedirectIds(db);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\t...result,\n\t\t\t\t...(loopRedirectIds.length > 0 ? { loopRedirectIds } : {}),\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tif (error instanceof InvalidCursorError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_CURSOR\", message: error.message },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_LIST_ERROR\", message: \"Failed to fetch redirects\" },\n\t\t};\n\t}\n}\n\n/**\n * Create a redirect rule\n */\nexport async function handleRedirectCreate(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tsource: string;\n\t\tdestination?: string;\n\t\ttype?: number;\n\t\tenabled?: boolean;\n\t\tgroupName?: string | null;\n\t},\n): Promise<ApiResult<Redirect>> {\n\ttry {\n\t\tconst lockRepo = new RedirectRepository(db);\n\t\tconst result = await withRedirectWriteLock(lockRepo, async (fence, repo) => {\n\t\t\tconst type = input.type ?? 301;\n\t\t\t// Terminal statuses (410 Gone / 451) are served directly and have no\n\t\t\t// destination — skip the destination/loop checks for them.\n\t\t\tconst terminal = isTerminalStatus(type);\n\t\t\tconst destination = terminal ? \"\" : (input.destination ?? \"\");\n\n\t\t\t// Source and destination must differ\n\t\t\tif (!terminal && input.source === destination) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: \"Source and destination must be different\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// If source looks like a pattern, validate it\n\t\t\tconst sourceIsPattern = isPattern(input.source);\n\t\t\tif (sourceIsPattern) {\n\t\t\t\tconst patternError = validatePattern(input.source);\n\t\t\t\tif (patternError) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"VALIDATION_ERROR\", message: `Invalid source pattern: ${patternError}` },\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Validate destination params reference valid source params\n\t\t\t\t// (terminal rules have no destination to interpolate)\n\t\t\t\tif (!terminal) {\n\t\t\t\t\tconst destError = validateDestinationParams(input.source, destination);\n\t\t\t\t\tif (destError) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\terror: { code: \"VALIDATION_ERROR\", message: destError },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check for duplicate source (exact match only for non-patterns)\n\t\t\tconst existing = await repo.findBySource(input.source);\n\t\t\tif (existing) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\tmessage: `A redirect from \"${input.source}\" already exists`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Check for redirect loops (skip if creating as disabled, or terminal —\n\t\t\t// a Gone rule has no destination, so it can't form a loop)\n\t\t\tif (!terminal && input.enabled !== false) {\n\t\t\t\tconst edges = toEdges(await repo.findAllEnabled());\n\t\t\t\tconst loopPath = wouldCreateLoop(input.source, destination, edges);\n\t\t\t\tif (loopPath) return loopError(loopPath);\n\t\t\t}\n\n\t\t\tconst redirect = await repo.create(\n\t\t\t\t{\n\t\t\t\t\tsource: input.source,\n\t\t\t\t\tdestination,\n\t\t\t\t\ttype,\n\t\t\t\t\tisPattern: sourceIsPattern,\n\t\t\t\t\tenabled: input.enabled ?? true,\n\t\t\t\t\tgroupName: input.groupName ?? null,\n\t\t\t\t},\n\t\t\t\tfence,\n\t\t\t);\n\t\t\treturn { success: true, data: redirect };\n\t\t});\n\t\tif (result.success) invalidateRedirectCache();\n\t\treturn result;\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_CREATE_ERROR\", message: \"Failed to create redirect\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a redirect by ID\n */\nexport async function handleRedirectGet(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<Redirect>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst redirect = await repo.findById(id);\n\n\t\tif (!redirect) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Redirect \"${id}\" not found` },\n\t\t\t};\n\t\t}\n\n\t\treturn { success: true, data: redirect };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_GET_ERROR\", message: \"Failed to fetch redirect\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a redirect by ID\n */\nexport async function handleRedirectUpdate(\n\tdb: Kysely<Database>,\n\tid: string,\n\tinput: {\n\t\tsource?: string;\n\t\tdestination?: string;\n\t\ttype?: number;\n\t\tenabled?: boolean;\n\t\tgroupName?: string | null;\n\t},\n\toptions?: { expectedRevision?: string },\n): Promise<ApiResult<Redirect>> {\n\ttry {\n\t\tconst lockRepo = new RedirectRepository(db);\n\t\tconst result = await withRedirectWriteLock(lockRepo, async (fence, repo) => {\n\t\t\tconst existing = await repo.findById(id);\n\t\t\tif (!existing) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: \"NOT_FOUND\", message: `Redirect \"${id}\" not found` },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (options?.expectedRevision !== undefined) {\n\t\t\t\tconst currentRevision = await repo.findConfigRevision(id);\n\t\t\t\tif (currentRevision !== options.expectedRevision) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"CONFLICT\", message: \"Redirect changed since it was read\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst newSource = input.source ?? existing.source;\n\t\t\tconst newType = input.type ?? existing.type;\n\t\t\tconst terminal = isTerminalStatus(newType);\n\t\t\tconst newDest = terminal ? \"\" : (input.destination ?? existing.destination);\n\t\t\tif (!terminal && !newDest) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: \"destination is required for redirect types (301, 302, 307, 308)\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Source and destination must differ\n\t\t\tif (!terminal && newSource === newDest) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: \"Source and destination must be different\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// If source is changing, validate patterns\n\t\t\tif (input.source !== undefined) {\n\t\t\t\tconst sourceIsPattern = isPattern(input.source);\n\t\t\t\tif (sourceIsPattern) {\n\t\t\t\t\tconst patternError = validatePattern(input.source);\n\t\t\t\t\tif (patternError) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\t\t\tmessage: `Invalid source pattern: ${patternError}`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Check for duplicate source (exclude self)\n\t\t\t\tconst dup = await repo.findBySource(input.source);\n\t\t\t\tif (dup && dup.id !== id) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\t\tmessage: `A redirect from \"${input.source}\" already exists`,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Validate destination params against the (possibly updated) source\n\t\t\tconst newSourceIsPattern = isPattern(newSource);\n\t\t\tif (newSourceIsPattern && !terminal) {\n\t\t\t\tconst destError = validateDestinationParams(newSource, newDest);\n\t\t\t\tif (destError) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"VALIDATION_ERROR\", message: destError },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check for redirect loops if source or destination changed\n\t\t\tconst willBeEnabled = input.enabled ?? existing.enabled;\n\t\t\tif (\n\t\t\t\t!terminal &&\n\t\t\t\twillBeEnabled &&\n\t\t\t\t(input.source !== undefined || input.destination !== undefined)\n\t\t\t) {\n\t\t\t\tconst edges = toEdges(await repo.findAllEnabled());\n\t\t\t\tconst loopPath = wouldCreateLoop(newSource, newDest, edges, id);\n\t\t\t\tif (loopPath) return loopError(loopPath);\n\t\t\t}\n\n\t\t\tconst updated = await repo.update(\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\tsource: input.source,\n\t\t\t\t\tdestination: terminal ? \"\" : input.destination,\n\t\t\t\t\ttype: input.type,\n\t\t\t\t\tenabled: input.enabled,\n\t\t\t\t\tgroupName: input.groupName,\n\t\t\t\t},\n\t\t\t\toptions?.expectedRevision,\n\t\t\t\tfence,\n\t\t\t);\n\n\t\t\tif (!updated) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: options?.expectedRevision\n\t\t\t\t\t\t? { code: \"CONFLICT\", message: \"Redirect changed since it was read\" }\n\t\t\t\t\t\t: { code: \"REDIRECT_UPDATE_ERROR\", message: \"Failed to update redirect\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Recompute cache — redirect was modified, so re-fetch\n\t\t\tawait updateLoopCache(repo.db);\n\t\t\treturn { success: true, data: updated };\n\t\t});\n\t\tif (result.success) invalidateRedirectCache();\n\t\treturn result;\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_UPDATE_ERROR\", message: \"Failed to update redirect\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a redirect by ID\n */\nexport async function handleRedirectDelete(\n\tdb: Kysely<Database>,\n\tid: string,\n\toptions?: { expectedRevision?: string },\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst lockRepo = new RedirectRepository(db);\n\t\tconst result = await withRedirectWriteLock<{ deleted: true }>(lockRepo, async (fence, repo) => {\n\t\t\tif (options?.expectedRevision !== undefined) {\n\t\t\t\tconst existing = await repo.findById(id);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"NOT_FOUND\", message: `Redirect \"${id}\" not found` },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst currentRevision = await repo.findConfigRevision(id);\n\t\t\t\tif (currentRevision !== options.expectedRevision) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: { code: \"CONFLICT\", message: \"Redirect changed since it was read\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst deleted = await repo.delete(id, options?.expectedRevision, fence);\n\n\t\t\tif (!deleted) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: options?.expectedRevision\n\t\t\t\t\t\t? { code: \"CONFLICT\", message: \"Redirect changed since it was read\" }\n\t\t\t\t\t\t: { code: \"NOT_FOUND\", message: `Redirect \"${id}\" not found` },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tawait updateLoopCache(repo.db);\n\t\t\treturn { success: true, data: { deleted: true } };\n\t\t});\n\t\tif (result.success) invalidateRedirectCache();\n\t\treturn result;\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REDIRECT_DELETE_ERROR\", message: \"Failed to delete redirect\" },\n\t\t};\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Loop analysis cache\n// ---------------------------------------------------------------------------\n\nfunction loopError(loopPath: string[]): ApiResult<never> {\n\tconst hops = loopPath\n\t\t.slice(0, -1)\n\t\t.map((p, i) => `${p} \\u2192 ${loopPath[i + 1]}`)\n\t\t.join(\"\\n\");\n\treturn {\n\t\tsuccess: false,\n\t\terror: {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: `This redirect would create a loop:\\n${hops}`,\n\t\t},\n\t};\n}\n\nfunction toEdges(redirects: Redirect[]): RedirectEdge[] {\n\treturn redirects.map((r) => ({\n\t\tid: r.id,\n\t\tsource: r.source,\n\t\tdestination: r.destination,\n\t\tenabled: r.enabled,\n\t\tisPattern: r.isPattern,\n\t}));\n}\n\nconst LOOP_CACHE_KEY = \"_redirect_loop_ids\";\n\n/**\n * Recompute loop redirect IDs and store in the options table.\n */\nasync function updateLoopCache(db: Kysely<Database>): Promise<void> {\n\ttry {\n\t\tconst options = new OptionsRepository(db);\n\t\tconst edges = toEdges(await new RedirectRepository(db).findAllEnabled());\n\t\tconst loopRedirectIds = detectLoops(edges);\n\t\tawait options.set(LOOP_CACHE_KEY, loopRedirectIds);\n\t} catch (error) {\n\t\tconsole.error(\"Failed to update redirect loop cache:\", error);\n\t}\n}\n\n/**\n * Get loop redirect IDs from cache, computing lazily on first access.\n */\nasync function getLoopRedirectIds(db: Kysely<Database>): Promise<string[]> {\n\ttry {\n\t\tconst options = new OptionsRepository(db);\n\t\tconst cached = await options.get<string[]>(LOOP_CACHE_KEY);\n\t\tif (cached !== null) return cached;\n\n\t\t// First access after upgrade — compute and cache\n\t\tawait updateLoopCache(db);\n\t\treturn (await options.get<string[]>(LOOP_CACHE_KEY)) ?? [];\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// 404 Log\n// ---------------------------------------------------------------------------\n\n/**\n * List 404 log entries with cursor pagination\n */\nexport async function handleNotFoundList(\n\tdb: Kysely<Database>,\n\tparams: { cursor?: string; limit?: number; search?: string },\n): Promise<ApiResult<FindManyResult<NotFoundEntry>>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst result = await repo.find404s(params);\n\t\treturn { success: true, data: result };\n\t} catch (error) {\n\t\tif (error instanceof InvalidCursorError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_CURSOR\", message: error.message },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND_LIST_ERROR\", message: \"Failed to fetch 404 log\" },\n\t\t};\n\t}\n}\n\n/**\n * Get 404 summary (grouped by path, sorted by count)\n */\nexport async function handleNotFoundSummary(\n\tdb: Kysely<Database>,\n\tlimit?: number,\n): Promise<ApiResult<{ items: NotFoundSummary[] }>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst items = await repo.get404Summary(limit);\n\t\treturn { success: true, data: { items } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND_SUMMARY_ERROR\", message: \"Failed to fetch 404 summary\" },\n\t\t};\n\t}\n}\n\n/**\n * Clear all 404 log entries\n */\nexport async function handleNotFoundClear(\n\tdb: Kysely<Database>,\n): Promise<ApiResult<{ deleted: number }>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst deleted = await repo.clear404s();\n\t\treturn { success: true, data: { deleted } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND_CLEAR_ERROR\", message: \"Failed to clear 404 log\" },\n\t\t};\n\t}\n}\n\n/**\n * Prune 404 log entries older than a given date\n */\nexport async function handleNotFoundPrune(\n\tdb: Kysely<Database>,\n\tolderThan: string,\n): Promise<ApiResult<{ deleted: number }>> {\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\t\tconst deleted = await repo.prune404s(olderThan);\n\t\treturn { success: true, data: { deleted } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND_PRUNE_ERROR\", message: \"Failed to prune 404 log\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;AAwBA,eAAe,sBACd,MACA,QACwB;AACxB,KAAI;AACH,SAAO,MAAM,KAAK,cAAc,OAAO;UAC/B,OAAO;AACf,MAAI,iBAAiB,uBACpB,QAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAiB,SAAS;IAA0C;GACnF;AAEF,QAAM;;;;;;AAWR,eAAsB,mBACrB,IACA,QAQgF;AAChF,KAAI;EAEH,MAAM,SAAS,MADF,IAAI,mBAAmB,GAAG,CACb,SAAS,OAAO;EAE1C,MAAM,kBAAkB,MAAM,mBAAmB,GAAG;AAEpD,SAAO;GACN,SAAS;GACT,MAAM;IACL,GAAG;IACH,GAAI,gBAAgB,SAAS,IAAI,EAAE,iBAAiB,GAAG,EAAE;IACzD;GACD;UACO,OAAO;AACf,MAAI,iBAAiB,mBACpB,QAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAkB,SAAS,MAAM;IAAS;GACzD;AAEF,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAuB,SAAS;IAA6B;GAC5E;;;;;;AAOH,eAAsB,qBACrB,IACA,OAO+B;AAC/B,KAAI;EAEH,MAAM,SAAS,MAAM,sBADJ,IAAI,mBAAmB,GAAG,EACU,OAAO,OAAO,SAAS;GAC3E,MAAM,OAAO,MAAM,QAAQ;GAG3B,MAAM,WAAW,iBAAiB,KAAK;GACvC,MAAM,cAAc,WAAW,KAAM,MAAM,eAAe;AAG1D,OAAI,CAAC,YAAY,MAAM,WAAW,YACjC,QAAO;IACN,SAAS;IACT,OAAO;KACN,MAAM;KACN,SAAS;KACT;IACD;GAIF,MAAM,kBAAkB,UAAU,MAAM,OAAO;AAC/C,OAAI,iBAAiB;IACpB,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AM,QAAQ,IAAc,eAAe,IAAK,EAAE;SACnD;AACP,SAAO,EAAE;;;;;;AAWX,eAAsB,mBACrB,IACA,QACoD;AACpD,KAAI;AAGH,SAAO;GAAE,SAAS;GAAM,MADT,MADF,IAAI,mBAAmB,GAAG,CACb,SAAS,OAAO;GACJ;UAC9B,OAAO;AACf,MAAI,iBAAiB,mBACpB,QAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAkB,SAAS,MAAM;IAAS;GACzD;AAEF,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAwB,SAAS;IAA2B;GAC3E;;;;;;AAOH,eAAsB,sBACrB,IACA,OACmD;AACnD,KAAI;AAGH,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,OADlB,MADD,IAAI,mBAAmB,GAAG,CACd,cAAc,MAAM,EACN;GAAE;SAClC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAA2B,SAAS;IAA+B;GAClF;;;;;;AAOH,eAAsB,oBACrB,IAC0C;AAC1C,KAAI;AAGH,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SADhB,MADH,IAAI,mBAAmB,GAAG,CACZ,WAAW,EACG;GAAE;SACpC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAyB,SAAS;IAA2B;GAC5E;;;;;;AAOH,eAAsB,oBACrB,IACA,WAC0C;AAC1C,KAAI;AAGH,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SADhB,MADH,IAAI,mBAAmB,GAAG,CACZ,UAAU,UAAU,EACN;GAAE;SACpC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAyB,SAAS;IAA2B;GAC5E"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { p as PluginRouteError, t as PluginContextFactory } from "./context-
|
|
1
|
+
import { p as PluginRouteError, t as PluginContextFactory } from "./context-BV_7t-Ua.mjs";
|
|
2
2
|
import { t as extractRequestMeta } from "./request-meta-sZXt3sRo.mjs";
|
|
3
3
|
import { t as SiteWriteBlockedError } from "./fence-CMDXJYc_.mjs";
|
|
4
4
|
import { n as parseDeclaredPluginRouteInput } from "./route-wire--1hLuACz.mjs";
|
|
@@ -269,4 +269,4 @@ var PluginRouteRegistry = class {
|
|
|
269
269
|
|
|
270
270
|
//#endregion
|
|
271
271
|
export { toRouteCallerInfo as a, pluginPublicRouteAcknowledgementSchema as i, buildRouteMeta as n, parseRouteInput as r, PluginRouteRegistry as t };
|
|
272
|
-
//# sourceMappingURL=routes-
|
|
272
|
+
//# sourceMappingURL=routes-vrR95WR6.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes-CUsM40Cc.mjs","names":[],"sources":["../src/plugins/routes.ts"],"sourcesContent":["/**\n * Plugin Routes v2\n *\n * Handles plugin API route invocation with:\n * - Input validation via Zod schemas\n * - Route context creation\n * - Error handling\n *\n */\n\nimport type { PluginUiContext } from \"@emdash-cms/blocks/server\";\nimport type {\n\tPluginRouteMethod,\n\tPluginRouteRequest,\n\tPluginRouteResponseMode,\n} from \"@emdash-cms/plugin-types\";\nimport { routeNameSchema } from \"@emdash-cms/plugin-types\";\nimport { z } from \"zod\";\n\nimport { SiteWriteBlockedError } from \"../transfer/fence.js\";\nimport { PluginContextFactory, type PluginContextFactoryOptions } from \"./context.js\";\nimport { extractRequestMeta } from \"./request-meta.js\";\nimport { PluginRouteError } from \"./route-error.js\";\nimport { parseDeclaredPluginRouteInput } from \"./route-wire.js\";\nimport type { ResolvedPlugin, RouteContext, PluginRoute, UserInfo } from \"./types.js\";\n\nexport { PluginRouteError };\n\n/**\n * Body-reading methods on `Request`. EmDash parses the request body once before\n * the handler runs and exposes the result as `ctx.input`, leaving the underlying\n * stream consumed. Calling any of these on `ctx.request` would re-read a spent\n * stream and throw an opaque platform error (\"Body is unusable: Body has already\n * been read\") with no hint about `ctx.input` — so the guard replaces them with an\n * actionable message instead.\n */\nconst CONSUMED_BODY_METHODS = new Set([\"json\", \"text\", \"arrayBuffer\", \"blob\", \"formData\", \"bytes\"]);\n\n/**\n * Wrap the request handed to a plugin route handler so an accidental\n * `ctx.request.json()` (or `.text()`, `.formData()`, …) fails with a message\n * pointing at `ctx.input` rather than the runtime's cryptic \"body already read\"\n * error. Every non-body member passes through unchanged; function members are\n * bound to the underlying request so methods like `clone()` don't throw an\n * \"Illegal invocation\" when called on the proxy.\n */\nfunction guardConsumedRequestBody(request: Request): Request {\n\treturn new Proxy(request, {\n\t\tget(target, prop) {\n\t\t\tif (typeof prop === \"string\" && CONSUMED_BODY_METHODS.has(prop)) {\n\t\t\t\treturn () => {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[emdash] ctx.request.${prop}() is not available inside a plugin route handler: ` +\n\t\t\t\t\t\t\t`EmDash has already parsed the request body and exposes it as ctx.input. ` +\n\t\t\t\t\t\t\t`Read ctx.input instead of ctx.request.${prop}().`,\n\t\t\t\t\t);\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst value = Reflect.get(target, prop, target);\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t});\n}\n\n/**\n * Route metadata (public flag) without the handler.\n * Used by the catch-all route to decide auth before dispatch.\n */\nexport interface RouteMeta {\n\tpublic: boolean;\n\tpermission?: string;\n\t/**\n\t * Cache-Control value for successful GET responses. Only ever set for\n\t * public routes — authenticated responses must stay `private, no-store`.\n\t */\n\tcacheControl?: string;\n\tmethods?: PluginRouteMethod[];\n\trequest?: PluginRouteRequest;\n\tresponse?: PluginRouteResponseMode;\n}\n\nexport const pluginPublicRouteAcknowledgementSchema = z.array(routeNameSchema);\n\nexport type PluginContentCacheInvalidator = (tags: string[]) => Promise<void>;\n\n/**\n * Build RouteMeta from a route's `public`/`cacheControl` flags. Single source\n * of truth for the \"cacheControl is only ever exposed on public routes\"\n * invariant — used for trusted routes and manifest-declared sandboxed routes.\n */\nexport function buildRouteMeta(route: {\n\tpublic?: boolean;\n\tpermission?: string;\n\tcacheControl?: string;\n\tmethods?: PluginRouteMethod[];\n\trequest?: PluginRouteRequest;\n\tresponse?: PluginRouteResponseMode;\n}): RouteMeta {\n\tconst meta: RouteMeta = { public: route.public === true };\n\tif (route.permission !== undefined) meta.permission = route.permission;\n\tif (route.methods !== undefined) meta.methods = [...route.methods];\n\tif (route.request !== undefined) {\n\t\tmeta.request = {\n\t\t\t...route.request,\n\t\t\t...(route.request.headers ? { headers: [...route.request.headers] } : {}),\n\t\t};\n\t}\n\tif (route.response !== undefined) meta.response = route.response;\n\t// Private responses are per-user and must never become cacheable, even if\n\t// a route sets both flags.\n\tif (meta.public && typeof route.cacheControl === \"string\" && route.cacheControl.length > 0) {\n\t\tmeta.cacheControl = route.cacheControl;\n\t}\n\treturn meta;\n}\n\n/**\n * HTTP methods that carry a request body. Everything else (GET, HEAD, DELETE)\n * takes its route input from the URL query string.\n */\nconst BODY_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\"]);\n\n/**\n * Parse a plugin route's input from the request, by method.\n *\n * Body methods (POST/PUT/PATCH) parse the JSON body as before. Bodyless\n * methods (GET/HEAD/DELETE) have no body, so `request.json()` resolves to\n * undefined and fails schema validation, so parse the query string into\n * an object instead. Repeated keys (`?tag=a&tag=b`) become an array so array\n * schemas work; a single key stays a scalar.\n */\nexport async function parseRouteInput(\n\trequest: Request,\n\tdeclaration?: PluginRouteRequest,\n): Promise<unknown> {\n\tif (declaration) return parseDeclaredPluginRouteInput(request, declaration);\n\tif (BODY_METHODS.has(request.method.toUpperCase())) {\n\t\ttry {\n\t\t\treturn await request.json();\n\t\t} catch {\n\t\t\t// No body or not JSON\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tconst params = new URL(request.url).searchParams;\n\tconst input: Record<string, string | string[]> = {};\n\tfor (const key of new Set(params.keys())) {\n\t\tconst values = params.getAll(key);\n\t\tinput[key] = values.length > 1 ? values : values[0];\n\t}\n\treturn input;\n}\n\n/**\n * Result from a route invocation\n */\nexport interface RouteResult<T = unknown> {\n\tsuccess: boolean;\n\tdata?: T;\n\terror?: {\n\t\tcode: string;\n\t\tmessage: string;\n\t\tdetails?: unknown;\n\t};\n\tstatus: number;\n}\n\n/**\n * Host-side user shape accepted when dispatching a plugin route. Structurally\n * matches `User` from `@emdash-cms/auth` so hosts can pass `locals.user`\n * directly without the plugin layer depending on the auth package.\n */\nexport interface RouteCallerInput {\n\tid: string;\n\temail: string;\n\tname: string | null;\n\trole: number;\n\tcreatedAt: Date | string;\n}\n\n/**\n * Convert the host's authenticated user into the read-only `UserInfo` shape\n * exposed to plugins as `ctx.user`. Strips sensitive/irrelevant fields and\n * keeps the value structured-clone-safe for sandboxed plugins.\n */\nexport function toRouteCallerInfo(user: RouteCallerInput): UserInfo {\n\treturn {\n\t\tid: user.id,\n\t\temail: user.email,\n\t\tname: user.name,\n\t\trole: user.role,\n\t\tcreatedAt: typeof user.createdAt === \"string\" ? user.createdAt : user.createdAt.toISOString(),\n\t};\n}\n\n/**\n * Route invocation options\n */\nexport interface InvokeRouteOptions {\n\t/** The original request */\n\trequest: Request;\n\t/** Request body (already parsed) */\n\tbody?: unknown;\n\t/**\n\t * Authenticated caller resolved by the host, exposed to the handler as\n\t * `ctx.user`. Undefined for public routes and unbound machine tokens.\n\t */\n\tuser?: UserInfo;\n\t/** Host-attested context for a validated Block Kit request. */\n\tui?: PluginUiContext;\n}\n\n/**\n * Route handler for a plugin\n */\nexport class PluginRouteHandler {\n\tprivate contextFactory: PluginContextFactory;\n\tprivate plugin: ResolvedPlugin;\n\tprivate trustedProxyHeaders: string[];\n\n\tconstructor(plugin: ResolvedPlugin, factoryOptions: PluginContextFactoryOptions) {\n\t\tthis.plugin = plugin;\n\t\tthis.contextFactory = new PluginContextFactory(factoryOptions);\n\t\tthis.trustedProxyHeaders = factoryOptions.trustedProxyHeaders ?? [];\n\t}\n\n\t/**\n\t * Invoke a route by name\n\t */\n\tasync invoke(routeName: string, options: InvokeRouteOptions): Promise<RouteResult> {\n\t\tconst route = this.plugin.routes[routeName];\n\n\t\tif (!route) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"ROUTE_NOT_FOUND\",\n\t\t\t\t\tmessage: `Route \"${routeName}\" not found in plugin \"${this.plugin.id}\"`,\n\t\t\t\t},\n\t\t\t\tstatus: 404,\n\t\t\t};\n\t\t}\n\n\t\t// Validate input if schema is provided\n\t\tlet validatedInput: unknown;\n\t\tif (route.input) {\n\t\t\tconst parseResult = route.input.safeParse(options.body);\n\t\t\tif (!parseResult.success) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: \"Invalid request body\",\n\t\t\t\t\t\tdetails: z.formatError(parseResult.error),\n\t\t\t\t\t},\n\t\t\t\t\tstatus: 400,\n\t\t\t\t};\n\t\t\t}\n\t\t\tvalidatedInput = parseResult.data;\n\t\t} else {\n\t\t\tvalidatedInput = options.body;\n\t\t}\n\n\t\t// Create route context\n\t\tconst baseContext = this.contextFactory.createContext(this.plugin);\n\t\tconst routeContext: RouteContext = {\n\t\t\t...baseContext,\n\t\t\tinput: validatedInput,\n\t\t\t// The body is already parsed into `input`; guard `ctx.request`'s\n\t\t\t// body-reading methods so a re-read fails with an actionable message.\n\t\t\t// Metadata extraction uses the original request (headers only).\n\t\t\trequest: guardConsumedRequestBody(options.request),\n\t\t\trequestMeta: extractRequestMeta(options.request, this.trustedProxyHeaders),\n\t\t\tuser: options.user,\n\t\t\tui: options.ui,\n\t\t};\n\n\t\t// Execute handler\n\t\ttry {\n\t\t\tconst result = await route.handler(routeContext);\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: result,\n\t\t\t\tstatus: 200,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof SiteWriteBlockedError) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: error.code, message: error.message },\n\t\t\t\t\tstatus: error.status,\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Handle known error types\n\t\t\tif (error instanceof PluginRouteError) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: error.code,\n\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\tdetails: error.details,\n\t\t\t\t\t},\n\t\t\t\t\tstatus: error.status,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Unknown error -- log internally, return generic message\n\t\t\tconsole.error(`[plugin:${this.plugin.id}] Route handler failed:`, error);\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INTERNAL_ERROR\",\n\t\t\t\t\tmessage: \"An internal error occurred\",\n\t\t\t\t},\n\t\t\t\tstatus: 500,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Get all route names\n\t */\n\tgetRouteNames(): string[] {\n\t\treturn Object.keys(this.plugin.routes);\n\t}\n\n\t/**\n\t * Check if a route exists\n\t */\n\thasRoute(name: string): boolean {\n\t\treturn name in this.plugin.routes;\n\t}\n\n\t/**\n\t * Get route metadata without invoking the handler.\n\t * Returns null if the route doesn't exist.\n\t */\n\tgetRouteMeta(name: string): RouteMeta | null {\n\t\tconst route: PluginRoute | undefined = this.plugin.routes[name];\n\t\tif (!route) return null;\n\t\treturn buildRouteMeta(route);\n\t}\n}\n\n/**\n * Registry for all plugin route handlers\n */\nexport class PluginRouteRegistry {\n\tprivate handlers: Map<string, PluginRouteHandler> = new Map();\n\n\tconstructor(private factoryOptions: PluginContextFactoryOptions) {}\n\n\t/**\n\t * Register a plugin's routes\n\t */\n\tregister(plugin: ResolvedPlugin): void {\n\t\tconst handler = new PluginRouteHandler(plugin, this.factoryOptions);\n\t\tthis.handlers.set(plugin.id, handler);\n\t}\n\n\t/**\n\t * Unregister a plugin's routes\n\t */\n\tunregister(pluginId: string): void {\n\t\tthis.handlers.delete(pluginId);\n\t}\n\n\t/**\n\t * Invoke a plugin route\n\t */\n\tasync invoke(\n\t\tpluginId: string,\n\t\trouteName: string,\n\t\toptions: InvokeRouteOptions,\n\t): Promise<RouteResult> {\n\t\tconst handler = this.handlers.get(pluginId);\n\n\t\tif (!handler) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"PLUGIN_NOT_FOUND\",\n\t\t\t\t\tmessage: `Plugin \"${pluginId}\" not found`,\n\t\t\t\t},\n\t\t\t\tstatus: 404,\n\t\t\t};\n\t\t}\n\n\t\treturn handler.invoke(routeName, options);\n\t}\n\n\t/**\n\t * Get all registered plugin IDs\n\t */\n\tgetPluginIds(): string[] {\n\t\treturn [...this.handlers.keys()];\n\t}\n\n\t/**\n\t * Get routes for a plugin\n\t */\n\tgetRoutes(pluginId: string): string[] {\n\t\treturn this.handlers.get(pluginId)?.getRouteNames() ?? [];\n\t}\n\n\t/**\n\t * Get route metadata for a specific plugin route.\n\t * Returns null if the plugin or route doesn't exist.\n\t */\n\tgetRouteMeta(pluginId: string, routeName: string): RouteMeta | null {\n\t\tconst handler = this.handlers.get(pluginId);\n\t\tif (!handler) return null;\n\t\treturn handler.getRouteMeta(routeName);\n\t}\n}\n\n/**\n * Create a route registry\n */\nexport function createRouteRegistry(\n\tfactoryOptions: PluginContextFactoryOptions,\n): PluginRouteRegistry {\n\treturn new PluginRouteRegistry(factoryOptions);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,MAAM,wBAAwB,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAe;CAAQ;CAAY;CAAQ,CAAC;;;;;;;;;AAUnG,SAAS,yBAAyB,SAA2B;AAC5D,QAAO,IAAI,MAAM,SAAS,EACzB,IAAI,QAAQ,MAAM;AACjB,MAAI,OAAO,SAAS,YAAY,sBAAsB,IAAI,KAAK,CAC9D,cAAa;AACZ,SAAM,IAAI,MACT,wBAAwB,KAAK,m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AM,UAAU,KAAK,SAAS,IAAI,SAAS;AAC3C,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,QAAQ,aAAa,UAAU"}
|
|
1
|
+
{"version":3,"file":"routes-vrR95WR6.mjs","names":[],"sources":["../src/plugins/routes.ts"],"sourcesContent":["/**\n * Plugin Routes v2\n *\n * Handles plugin API route invocation with:\n * - Input validation via Zod schemas\n * - Route context creation\n * - Error handling\n *\n */\n\nimport type { PluginUiContext } from \"@emdash-cms/blocks/server\";\nimport type {\n\tPluginRouteMethod,\n\tPluginRouteRequest,\n\tPluginRouteResponseMode,\n} from \"@emdash-cms/plugin-types\";\nimport { routeNameSchema } from \"@emdash-cms/plugin-types\";\nimport { z } from \"zod\";\n\nimport { SiteWriteBlockedError } from \"../transfer/fence.js\";\nimport { PluginContextFactory, type PluginContextFactoryOptions } from \"./context.js\";\nimport { extractRequestMeta } from \"./request-meta.js\";\nimport { PluginRouteError } from \"./route-error.js\";\nimport { parseDeclaredPluginRouteInput } from \"./route-wire.js\";\nimport type { ResolvedPlugin, RouteContext, PluginRoute, UserInfo } from \"./types.js\";\n\nexport { PluginRouteError };\n\n/**\n * Body-reading methods on `Request`. EmDash parses the request body once before\n * the handler runs and exposes the result as `ctx.input`, leaving the underlying\n * stream consumed. Calling any of these on `ctx.request` would re-read a spent\n * stream and throw an opaque platform error (\"Body is unusable: Body has already\n * been read\") with no hint about `ctx.input` — so the guard replaces them with an\n * actionable message instead.\n */\nconst CONSUMED_BODY_METHODS = new Set([\"json\", \"text\", \"arrayBuffer\", \"blob\", \"formData\", \"bytes\"]);\n\n/**\n * Wrap the request handed to a plugin route handler so an accidental\n * `ctx.request.json()` (or `.text()`, `.formData()`, …) fails with a message\n * pointing at `ctx.input` rather than the runtime's cryptic \"body already read\"\n * error. Every non-body member passes through unchanged; function members are\n * bound to the underlying request so methods like `clone()` don't throw an\n * \"Illegal invocation\" when called on the proxy.\n */\nfunction guardConsumedRequestBody(request: Request): Request {\n\treturn new Proxy(request, {\n\t\tget(target, prop) {\n\t\t\tif (typeof prop === \"string\" && CONSUMED_BODY_METHODS.has(prop)) {\n\t\t\t\treturn () => {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[emdash] ctx.request.${prop}() is not available inside a plugin route handler: ` +\n\t\t\t\t\t\t\t`EmDash has already parsed the request body and exposes it as ctx.input. ` +\n\t\t\t\t\t\t\t`Read ctx.input instead of ctx.request.${prop}().`,\n\t\t\t\t\t);\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst value = Reflect.get(target, prop, target);\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t});\n}\n\n/**\n * Route metadata (public flag) without the handler.\n * Used by the catch-all route to decide auth before dispatch.\n */\nexport interface RouteMeta {\n\tpublic: boolean;\n\tpermission?: string;\n\t/**\n\t * Cache-Control value for successful GET responses. Only ever set for\n\t * public routes — authenticated responses must stay `private, no-store`.\n\t */\n\tcacheControl?: string;\n\tmethods?: PluginRouteMethod[];\n\trequest?: PluginRouteRequest;\n\tresponse?: PluginRouteResponseMode;\n}\n\nexport const pluginPublicRouteAcknowledgementSchema = z.array(routeNameSchema);\n\nexport type PluginContentCacheInvalidator = (tags: string[]) => Promise<void>;\n\n/**\n * Build RouteMeta from a route's `public`/`cacheControl` flags. Single source\n * of truth for the \"cacheControl is only ever exposed on public routes\"\n * invariant — used for trusted routes and manifest-declared sandboxed routes.\n */\nexport function buildRouteMeta(route: {\n\tpublic?: boolean;\n\tpermission?: string;\n\tcacheControl?: string;\n\tmethods?: PluginRouteMethod[];\n\trequest?: PluginRouteRequest;\n\tresponse?: PluginRouteResponseMode;\n}): RouteMeta {\n\tconst meta: RouteMeta = { public: route.public === true };\n\tif (route.permission !== undefined) meta.permission = route.permission;\n\tif (route.methods !== undefined) meta.methods = [...route.methods];\n\tif (route.request !== undefined) {\n\t\tmeta.request = {\n\t\t\t...route.request,\n\t\t\t...(route.request.headers ? { headers: [...route.request.headers] } : {}),\n\t\t};\n\t}\n\tif (route.response !== undefined) meta.response = route.response;\n\t// Private responses are per-user and must never become cacheable, even if\n\t// a route sets both flags.\n\tif (meta.public && typeof route.cacheControl === \"string\" && route.cacheControl.length > 0) {\n\t\tmeta.cacheControl = route.cacheControl;\n\t}\n\treturn meta;\n}\n\n/**\n * HTTP methods that carry a request body. Everything else (GET, HEAD, DELETE)\n * takes its route input from the URL query string.\n */\nconst BODY_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\"]);\n\n/**\n * Parse a plugin route's input from the request, by method.\n *\n * Body methods (POST/PUT/PATCH) parse the JSON body as before. Bodyless\n * methods (GET/HEAD/DELETE) have no body, so `request.json()` resolves to\n * undefined and fails schema validation, so parse the query string into\n * an object instead. Repeated keys (`?tag=a&tag=b`) become an array so array\n * schemas work; a single key stays a scalar.\n */\nexport async function parseRouteInput(\n\trequest: Request,\n\tdeclaration?: PluginRouteRequest,\n): Promise<unknown> {\n\tif (declaration) return parseDeclaredPluginRouteInput(request, declaration);\n\tif (BODY_METHODS.has(request.method.toUpperCase())) {\n\t\ttry {\n\t\t\treturn await request.json();\n\t\t} catch {\n\t\t\t// No body or not JSON\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tconst params = new URL(request.url).searchParams;\n\tconst input: Record<string, string | string[]> = {};\n\tfor (const key of new Set(params.keys())) {\n\t\tconst values = params.getAll(key);\n\t\tinput[key] = values.length > 1 ? values : values[0];\n\t}\n\treturn input;\n}\n\n/**\n * Result from a route invocation\n */\nexport interface RouteResult<T = unknown> {\n\tsuccess: boolean;\n\tdata?: T;\n\terror?: {\n\t\tcode: string;\n\t\tmessage: string;\n\t\tdetails?: unknown;\n\t};\n\tstatus: number;\n}\n\n/**\n * Host-side user shape accepted when dispatching a plugin route. Structurally\n * matches `User` from `@emdash-cms/auth` so hosts can pass `locals.user`\n * directly without the plugin layer depending on the auth package.\n */\nexport interface RouteCallerInput {\n\tid: string;\n\temail: string;\n\tname: string | null;\n\trole: number;\n\tcreatedAt: Date | string;\n}\n\n/**\n * Convert the host's authenticated user into the read-only `UserInfo` shape\n * exposed to plugins as `ctx.user`. Strips sensitive/irrelevant fields and\n * keeps the value structured-clone-safe for sandboxed plugins.\n */\nexport function toRouteCallerInfo(user: RouteCallerInput): UserInfo {\n\treturn {\n\t\tid: user.id,\n\t\temail: user.email,\n\t\tname: user.name,\n\t\trole: user.role,\n\t\tcreatedAt: typeof user.createdAt === \"string\" ? user.createdAt : user.createdAt.toISOString(),\n\t};\n}\n\n/**\n * Route invocation options\n */\nexport interface InvokeRouteOptions {\n\t/** The original request */\n\trequest: Request;\n\t/** Request body (already parsed) */\n\tbody?: unknown;\n\t/**\n\t * Authenticated caller resolved by the host, exposed to the handler as\n\t * `ctx.user`. Undefined for public routes and unbound machine tokens.\n\t */\n\tuser?: UserInfo;\n\t/** Host-attested context for a validated Block Kit request. */\n\tui?: PluginUiContext;\n}\n\n/**\n * Route handler for a plugin\n */\nexport class PluginRouteHandler {\n\tprivate contextFactory: PluginContextFactory;\n\tprivate plugin: ResolvedPlugin;\n\tprivate trustedProxyHeaders: string[];\n\n\tconstructor(plugin: ResolvedPlugin, factoryOptions: PluginContextFactoryOptions) {\n\t\tthis.plugin = plugin;\n\t\tthis.contextFactory = new PluginContextFactory(factoryOptions);\n\t\tthis.trustedProxyHeaders = factoryOptions.trustedProxyHeaders ?? [];\n\t}\n\n\t/**\n\t * Invoke a route by name\n\t */\n\tasync invoke(routeName: string, options: InvokeRouteOptions): Promise<RouteResult> {\n\t\tconst route = this.plugin.routes[routeName];\n\n\t\tif (!route) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"ROUTE_NOT_FOUND\",\n\t\t\t\t\tmessage: `Route \"${routeName}\" not found in plugin \"${this.plugin.id}\"`,\n\t\t\t\t},\n\t\t\t\tstatus: 404,\n\t\t\t};\n\t\t}\n\n\t\t// Validate input if schema is provided\n\t\tlet validatedInput: unknown;\n\t\tif (route.input) {\n\t\t\tconst parseResult = route.input.safeParse(options.body);\n\t\t\tif (!parseResult.success) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: \"Invalid request body\",\n\t\t\t\t\t\tdetails: z.formatError(parseResult.error),\n\t\t\t\t\t},\n\t\t\t\t\tstatus: 400,\n\t\t\t\t};\n\t\t\t}\n\t\t\tvalidatedInput = parseResult.data;\n\t\t} else {\n\t\t\tvalidatedInput = options.body;\n\t\t}\n\n\t\t// Create route context\n\t\tconst baseContext = this.contextFactory.createContext(this.plugin);\n\t\tconst routeContext: RouteContext = {\n\t\t\t...baseContext,\n\t\t\tinput: validatedInput,\n\t\t\t// The body is already parsed into `input`; guard `ctx.request`'s\n\t\t\t// body-reading methods so a re-read fails with an actionable message.\n\t\t\t// Metadata extraction uses the original request (headers only).\n\t\t\trequest: guardConsumedRequestBody(options.request),\n\t\t\trequestMeta: extractRequestMeta(options.request, this.trustedProxyHeaders),\n\t\t\tuser: options.user,\n\t\t\tui: options.ui,\n\t\t};\n\n\t\t// Execute handler\n\t\ttry {\n\t\t\tconst result = await route.handler(routeContext);\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: result,\n\t\t\t\tstatus: 200,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof SiteWriteBlockedError) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: error.code, message: error.message },\n\t\t\t\t\tstatus: error.status,\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Handle known error types\n\t\t\tif (error instanceof PluginRouteError) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: error.code,\n\t\t\t\t\t\tmessage: error.message,\n\t\t\t\t\t\tdetails: error.details,\n\t\t\t\t\t},\n\t\t\t\t\tstatus: error.status,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Unknown error -- log internally, return generic message\n\t\t\tconsole.error(`[plugin:${this.plugin.id}] Route handler failed:`, error);\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INTERNAL_ERROR\",\n\t\t\t\t\tmessage: \"An internal error occurred\",\n\t\t\t\t},\n\t\t\t\tstatus: 500,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Get all route names\n\t */\n\tgetRouteNames(): string[] {\n\t\treturn Object.keys(this.plugin.routes);\n\t}\n\n\t/**\n\t * Check if a route exists\n\t */\n\thasRoute(name: string): boolean {\n\t\treturn name in this.plugin.routes;\n\t}\n\n\t/**\n\t * Get route metadata without invoking the handler.\n\t * Returns null if the route doesn't exist.\n\t */\n\tgetRouteMeta(name: string): RouteMeta | null {\n\t\tconst route: PluginRoute | undefined = this.plugin.routes[name];\n\t\tif (!route) return null;\n\t\treturn buildRouteMeta(route);\n\t}\n}\n\n/**\n * Registry for all plugin route handlers\n */\nexport class PluginRouteRegistry {\n\tprivate handlers: Map<string, PluginRouteHandler> = new Map();\n\n\tconstructor(private factoryOptions: PluginContextFactoryOptions) {}\n\n\t/**\n\t * Register a plugin's routes\n\t */\n\tregister(plugin: ResolvedPlugin): void {\n\t\tconst handler = new PluginRouteHandler(plugin, this.factoryOptions);\n\t\tthis.handlers.set(plugin.id, handler);\n\t}\n\n\t/**\n\t * Unregister a plugin's routes\n\t */\n\tunregister(pluginId: string): void {\n\t\tthis.handlers.delete(pluginId);\n\t}\n\n\t/**\n\t * Invoke a plugin route\n\t */\n\tasync invoke(\n\t\tpluginId: string,\n\t\trouteName: string,\n\t\toptions: InvokeRouteOptions,\n\t): Promise<RouteResult> {\n\t\tconst handler = this.handlers.get(pluginId);\n\n\t\tif (!handler) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"PLUGIN_NOT_FOUND\",\n\t\t\t\t\tmessage: `Plugin \"${pluginId}\" not found`,\n\t\t\t\t},\n\t\t\t\tstatus: 404,\n\t\t\t};\n\t\t}\n\n\t\treturn handler.invoke(routeName, options);\n\t}\n\n\t/**\n\t * Get all registered plugin IDs\n\t */\n\tgetPluginIds(): string[] {\n\t\treturn [...this.handlers.keys()];\n\t}\n\n\t/**\n\t * Get routes for a plugin\n\t */\n\tgetRoutes(pluginId: string): string[] {\n\t\treturn this.handlers.get(pluginId)?.getRouteNames() ?? [];\n\t}\n\n\t/**\n\t * Get route metadata for a specific plugin route.\n\t * Returns null if the plugin or route doesn't exist.\n\t */\n\tgetRouteMeta(pluginId: string, routeName: string): RouteMeta | null {\n\t\tconst handler = this.handlers.get(pluginId);\n\t\tif (!handler) return null;\n\t\treturn handler.getRouteMeta(routeName);\n\t}\n}\n\n/**\n * Create a route registry\n */\nexport function createRouteRegistry(\n\tfactoryOptions: PluginContextFactoryOptions,\n): PluginRouteRegistry {\n\treturn new PluginRouteRegistry(factoryOptions);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,MAAM,wBAAwB,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAe;CAAQ;CAAY;CAAQ,CAAC;;;;;;;;;AAUnG,SAAS,yBAAyB,SAA2B;AAC5D,QAAO,IAAI,MAAM,SAAS,EACzB,IAAI,QAAQ,MAAM;AACjB,MAAI,OAAO,SAAS,YAAY,sBAAsB,IAAI,KAAK,CAC9D,cAAa;AACZ,SAAM,IAAI,MACT,wBAAwB,KAAK,mKAEa,KAAK,KAC/C;;EAGH,MAAM,QAAQ,QAAQ,IAAI,QAAQ,MAAM,OAAO;AAC/C,SAAO,OAAO,UAAU,aAAa,MAAM,KAAK,OAAO,GAAG;IAE3D,CAAC;;AAoBH,MAAa,yCAAyC,EAAE,MAAM,gBAAgB;;;;;;AAS9E,SAAgB,eAAe,OAOjB;CACb,MAAM,OAAkB,EAAE,QAAQ,MAAM,WAAW,MAAM;AACzD,KAAI,MAAM,eAAe,OAAW,MAAK,aAA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