emdash 0.6.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapters-Di31kZ28.d.mts → adapters-BKSf3T9R.d.mts} +1 -1
- package/dist/{adapters-Di31kZ28.d.mts.map → adapters-BKSf3T9R.d.mts.map} +1 -1
- package/dist/{apply-B4MsLM-w.mjs → apply-x0eMK1lX.mjs} +186 -28
- package/dist/apply-x0eMK1lX.mjs.map +1 -0
- package/dist/astro/index.d.mts +6 -6
- package/dist/astro/index.d.mts.map +1 -1
- package/dist/astro/index.mjs +92 -17
- package/dist/astro/index.mjs.map +1 -1
- package/dist/astro/middleware/auth.d.mts +5 -5
- package/dist/astro/middleware/auth.d.mts.map +1 -1
- package/dist/astro/middleware/auth.mjs +22 -2
- package/dist/astro/middleware/auth.mjs.map +1 -1
- package/dist/astro/middleware/redirect.mjs +2 -2
- package/dist/astro/middleware/request-context.mjs +7 -2
- package/dist/astro/middleware/request-context.mjs.map +1 -1
- package/dist/astro/middleware/setup.mjs +1 -1
- package/dist/astro/middleware.d.mts.map +1 -1
- package/dist/astro/middleware.mjs +263 -74
- package/dist/astro/middleware.mjs.map +1 -1
- package/dist/astro/types.d.mts +25 -8
- package/dist/astro/types.d.mts.map +1 -1
- package/dist/{byline-C4OVd8b3.mjs → byline-Chbr2GoP.mjs} +3 -3
- package/dist/byline-Chbr2GoP.mjs.map +1 -0
- package/dist/{bylines-hPTW79hw.mjs → bylines-CRNsVG88.mjs} +4 -4
- package/dist/{bylines-hPTW79hw.mjs.map → bylines-CRNsVG88.mjs.map} +1 -1
- package/dist/cli/index.mjs +17 -13
- package/dist/cli/index.mjs.map +1 -1
- package/dist/client/cf-access.d.mts +1 -1
- package/dist/client/index.d.mts +1 -1
- package/dist/client/index.mjs +1 -1
- package/dist/{content-BsBoyj8G.mjs → content-BcQPYxdV.mjs} +39 -15
- package/dist/content-BcQPYxdV.mjs.map +1 -0
- package/dist/db/index.d.mts +3 -3
- package/dist/db/index.mjs +1 -1
- package/dist/db/libsql.d.mts +1 -1
- package/dist/db/postgres.d.mts +1 -1
- package/dist/db/sqlite.d.mts +1 -1
- package/dist/{db-errors-D0UT85nC.mjs → db-errors-l1Qh2RPR.mjs} +1 -1
- package/dist/{db-errors-D0UT85nC.mjs.map → db-errors-l1Qh2RPR.mjs.map} +1 -1
- package/dist/{default-CME5YdZ3.mjs → default-DCVqE5ib.mjs} +1 -1
- package/dist/{default-CME5YdZ3.mjs.map → default-DCVqE5ib.mjs.map} +1 -1
- package/dist/{error-CiYn9yDu.mjs → error-zG5T1UGA.mjs} +1 -1
- package/dist/error-zG5T1UGA.mjs.map +1 -0
- package/dist/{index-BYv0mB9g.d.mts → index-DIb-CzNx.d.mts} +232 -15
- package/dist/index-DIb-CzNx.d.mts.map +1 -0
- package/dist/index.d.mts +11 -11
- package/dist/index.mjs +23 -21
- package/dist/{load-CBcmDIot.mjs → load-CyEoextb.mjs} +1 -1
- package/dist/{load-CBcmDIot.mjs.map → load-CyEoextb.mjs.map} +1 -1
- package/dist/{loader-DeiBJEMe.mjs → loader-CndGj8kM.mjs} +8 -6
- package/dist/loader-CndGj8kM.mjs.map +1 -0
- package/dist/{manifest-schema-V30qsMft.mjs → manifest-schema-DH9xhc6t.mjs} +13 -1
- package/dist/manifest-schema-DH9xhc6t.mjs.map +1 -0
- package/dist/media/index.d.mts +1 -1
- package/dist/media/local-runtime.d.mts +7 -7
- package/dist/media/local-runtime.mjs +2 -2
- package/dist/{media-DqHVh136.mjs → media-D8FbNsl0.mjs} +4 -7
- package/dist/media-D8FbNsl0.mjs.map +1 -0
- package/dist/{mode-CpNnGkPz.mjs → mode-BnAOqItE.mjs} +1 -1
- package/dist/mode-BnAOqItE.mjs.map +1 -0
- package/dist/page/index.d.mts +2 -2
- package/dist/placeholder-C-fk5hYI.mjs.map +1 -1
- package/dist/{placeholder-tzpqGWII.d.mts → placeholder-D29tWZ7o.d.mts} +1 -1
- package/dist/{placeholder-tzpqGWII.d.mts.map → placeholder-D29tWZ7o.d.mts.map} +1 -1
- package/dist/plugins/adapt-sandbox-entry.d.mts +5 -5
- package/dist/plugins/adapt-sandbox-entry.mjs +1 -1
- package/dist/{query-Bk_3vKvU.mjs → query-fqEdLFms.mjs} +9 -9
- package/dist/{query-Bk_3vKvU.mjs.map → query-fqEdLFms.mjs.map} +1 -1
- package/dist/{redirect-7lGhLBNZ.mjs → redirect-D_pshWdf.mjs} +69 -13
- package/dist/redirect-D_pshWdf.mjs.map +1 -0
- package/dist/{registry-Ci3WxVAr.mjs → registry-C3Mr0ODu.mjs} +33 -9
- package/dist/registry-C3Mr0ODu.mjs.map +1 -0
- package/dist/{request-cache-DiR961CV.mjs → request-cache-Ci7f5pBb.mjs} +1 -1
- package/dist/request-cache-Ci7f5pBb.mjs.map +1 -0
- package/dist/{runner-Fl2NcUUz.d.mts → runner-OURCaApa.d.mts} +2 -2
- package/dist/{runner-Fl2NcUUz.d.mts.map → runner-OURCaApa.d.mts.map} +1 -1
- package/dist/{runner-Cd-_WyDo.mjs → runner-tQ7BJ4T7.mjs} +211 -134
- package/dist/runner-tQ7BJ4T7.mjs.map +1 -0
- package/dist/runtime.d.mts +6 -6
- package/dist/runtime.mjs +2 -2
- package/dist/{search-DI4bM2w9.mjs → search-BoZYFuUk.mjs} +339 -102
- package/dist/search-BoZYFuUk.mjs.map +1 -0
- package/dist/seed/index.d.mts +2 -2
- package/dist/seed/index.mjs +12 -12
- package/dist/seo/index.d.mts +1 -1
- package/dist/storage/local.d.mts +1 -1
- package/dist/storage/local.mjs +1 -1
- package/dist/storage/s3.d.mts +1 -1
- package/dist/storage/s3.d.mts.map +1 -1
- package/dist/storage/s3.mjs +4 -4
- package/dist/storage/s3.mjs.map +1 -1
- package/dist/{taxonomies-DbrKzDju.mjs → taxonomies-B4IAshV8.mjs} +5 -5
- package/dist/{taxonomies-DbrKzDju.mjs.map → taxonomies-B4IAshV8.mjs.map} +1 -1
- package/dist/{tokens-BFPFx3CA.mjs → tokens-D9vnZqYS.mjs} +1 -1
- package/dist/{tokens-BFPFx3CA.mjs.map → tokens-D9vnZqYS.mjs.map} +1 -1
- package/dist/{transport-BykRfpyy.mjs → transport-C9ugt2Nr.mjs} +1 -1
- package/dist/{transport-BykRfpyy.mjs.map → transport-C9ugt2Nr.mjs.map} +1 -1
- package/dist/{transport-H4Iwx7tC.d.mts → transport-CUnEL3Vs.d.mts} +1 -1
- package/dist/{transport-H4Iwx7tC.d.mts.map → transport-CUnEL3Vs.d.mts.map} +1 -1
- package/dist/types-BIgulNsW.mjs +68 -0
- package/dist/types-BIgulNsW.mjs.map +1 -0
- package/dist/{types-DDS4MxsT.mjs → types-Bm1dn-q3.mjs} +1 -1
- package/dist/{types-DDS4MxsT.mjs.map → types-Bm1dn-q3.mjs.map} +1 -1
- package/dist/{types-CnZYHyLW.d.mts → types-BmPPSUEx.d.mts} +1 -1
- package/dist/{types-CnZYHyLW.d.mts.map → types-BmPPSUEx.d.mts.map} +1 -1
- package/dist/{types-6CUZRrZP.d.mts → types-BrA0xf5I.d.mts} +24 -2
- package/dist/{types-6CUZRrZP.d.mts.map → types-BrA0xf5I.d.mts.map} +1 -1
- package/dist/{types-8xrvl_68.d.mts → types-CS8FIX7L.d.mts} +10 -1
- package/dist/{types-8xrvl_68.d.mts.map → types-CS8FIX7L.d.mts.map} +1 -1
- package/dist/{types-BH2L167P.mjs → types-CgqmmMJB.mjs} +1 -1
- package/dist/{types-BH2L167P.mjs.map → types-CgqmmMJB.mjs.map} +1 -1
- package/dist/{types-CFWjXmus.d.mts → types-DIMwPFub.d.mts} +1 -1
- package/dist/{types-CFWjXmus.d.mts.map → types-DIMwPFub.d.mts.map} +1 -1
- package/dist/{types-DgrIP0tF.d.mts → types-i36XcA_X.d.mts} +49 -6
- package/dist/types-i36XcA_X.d.mts.map +1 -0
- package/dist/{validate-CqsNItbt.mjs → validate-CxVsLehf.mjs} +2 -2
- package/dist/{validate-CqsNItbt.mjs.map → validate-CxVsLehf.mjs.map} +1 -1
- package/dist/{validate-CaLH1Ia2.d.mts → validate-DHxmpFJt.d.mts} +4 -4
- package/dist/{validate-CaLH1Ia2.d.mts.map → validate-DHxmpFJt.d.mts.map} +1 -1
- package/dist/validation-C-ZpN2GI.mjs +144 -0
- package/dist/validation-C-ZpN2GI.mjs.map +1 -0
- package/dist/version-DJrV1K0M.mjs +7 -0
- package/dist/{version-Uaf2ynPX.mjs.map → version-DJrV1K0M.mjs.map} +1 -1
- package/dist/zod-generator-CpwccCIv.mjs +132 -0
- package/dist/zod-generator-CpwccCIv.mjs.map +1 -0
- package/package.json +19 -6
- package/src/api/auth-storage.ts +37 -0
- package/src/api/error.ts +6 -0
- package/src/api/errors.ts +8 -0
- package/src/api/handlers/comments.ts +13 -0
- package/src/api/handlers/content.ts +124 -3
- package/src/api/handlers/index.ts +2 -0
- package/src/api/handlers/media.ts +8 -1
- package/src/api/handlers/menus.ts +160 -21
- package/src/api/handlers/redirects.ts +16 -3
- package/src/api/handlers/sections.ts +8 -1
- package/src/api/handlers/taxonomies.ts +128 -16
- package/src/api/handlers/validation.ts +212 -0
- package/src/api/openapi/document.ts +4 -1
- package/src/api/public-url.ts +6 -3
- package/src/api/route-utils.ts +14 -0
- package/src/api/schemas/common.ts +1 -1
- package/src/api/schemas/content.ts +8 -0
- package/src/api/schemas/setup.ts +8 -0
- package/src/api/schemas/widgets.ts +12 -10
- package/src/api/setup-complete.ts +40 -0
- package/src/astro/integration/font-provider.ts +3 -1
- package/src/astro/integration/index.ts +15 -2
- package/src/astro/integration/routes.ts +28 -0
- package/src/astro/integration/runtime.ts +74 -2
- package/src/astro/integration/virtual-modules.ts +41 -0
- package/src/astro/integration/vite-config.ts +43 -12
- package/src/astro/middleware/auth.ts +21 -0
- package/src/astro/middleware.ts +18 -1
- package/src/astro/routes/PluginRegistry.tsx +10 -1
- package/src/astro/routes/admin.astro +14 -7
- package/src/astro/routes/api/auth/magic-link/send.ts +2 -1
- package/src/astro/routes/api/auth/mode.ts +57 -0
- package/src/astro/routes/api/auth/oauth/[provider]/callback.ts +23 -3
- package/src/astro/routes/api/auth/oauth/[provider].ts +10 -4
- package/src/astro/routes/api/auth/passkey/options.ts +2 -1
- package/src/astro/routes/api/auth/signup/request.ts +26 -8
- package/src/astro/routes/api/comments/[collection]/[contentId]/index.ts +10 -6
- package/src/astro/routes/api/content/[collection]/[id]/compare.ts +1 -1
- package/src/astro/routes/api/content/[collection]/[id]/preview-url.ts +1 -1
- package/src/astro/routes/api/content/[collection]/[id]/revisions.ts +1 -1
- package/src/astro/routes/api/content/[collection]/[id]/translations.ts +26 -0
- package/src/astro/routes/api/content/[collection]/[id].ts +30 -2
- package/src/astro/routes/api/content/[collection]/index.ts +20 -10
- package/src/astro/routes/api/content/[collection]/trash.ts +1 -1
- package/src/astro/routes/api/import/wordpress/media.ts +2 -7
- package/src/astro/routes/api/import/wordpress/prepare.ts +10 -0
- package/src/astro/routes/api/import/wordpress-plugin/analyze.ts +4 -3
- package/src/astro/routes/api/import/wordpress-plugin/execute.ts +4 -3
- package/src/astro/routes/api/manifest.ts +7 -0
- package/src/astro/routes/api/oauth/device/code.ts +2 -1
- package/src/astro/routes/api/oauth/device/token.ts +2 -1
- package/src/astro/routes/api/settings/email.ts +4 -9
- package/src/astro/routes/api/setup/admin-verify.ts +30 -5
- package/src/astro/routes/api/setup/admin.ts +38 -8
- package/src/astro/routes/api/setup/index.ts +7 -4
- package/src/astro/routes/api/setup/status.ts +3 -1
- package/src/astro/routes/api/widget-areas/[name]/widgets/[id].ts +4 -1
- package/src/astro/routes/api/widget-areas/[name]/widgets.ts +4 -1
- package/src/astro/routes/api/widget-areas/[name].ts +4 -1
- package/src/astro/routes/api/widget-areas/index.ts +4 -1
- package/src/astro/types.ts +18 -0
- package/src/auth/mode.ts +15 -3
- package/src/auth/providers/github-admin.tsx +29 -0
- package/src/auth/providers/github.ts +31 -0
- package/src/auth/providers/google-admin.tsx +44 -0
- package/src/auth/providers/google.ts +31 -0
- package/src/auth/rate-limit.ts +50 -22
- package/src/auth/setup-nonce.ts +22 -0
- package/src/auth/trusted-proxy.ts +92 -0
- package/src/auth/types.ts +114 -4
- package/src/cli/commands/bundle.ts +3 -1
- package/src/components/EmDashImage.astro +7 -6
- package/src/components/Gallery.astro +5 -3
- package/src/components/Image.astro +8 -3
- package/src/components/InlinePortableTextEditor.tsx +2 -1
- package/src/components/LiveSearch.astro +5 -14
- package/src/database/migrations/035_bounded_404_log.ts +112 -0
- package/src/database/migrations/runner.ts +2 -0
- package/src/database/repositories/audit.ts +6 -8
- package/src/database/repositories/byline.ts +6 -8
- package/src/database/repositories/comment.ts +12 -16
- package/src/database/repositories/content.ts +79 -40
- package/src/database/repositories/index.ts +1 -1
- package/src/database/repositories/media.ts +10 -13
- package/src/database/repositories/options.ts +25 -0
- package/src/database/repositories/plugin-storage.ts +4 -6
- package/src/database/repositories/redirect.ts +123 -24
- package/src/database/repositories/taxonomy.ts +14 -3
- package/src/database/repositories/types.ts +57 -8
- package/src/database/repositories/user.ts +6 -8
- package/src/database/types.ts +9 -0
- package/src/emdash-runtime.ts +309 -91
- package/src/import/registry.ts +4 -3
- package/src/import/ssrf.ts +253 -12
- package/src/index.ts +5 -1
- package/src/loader.ts +6 -5
- package/src/mcp/server.ts +753 -107
- package/src/media/normalize.ts +1 -1
- package/src/media/url.ts +78 -0
- package/src/plugins/context.ts +15 -3
- package/src/plugins/email-console.ts +10 -3
- package/src/plugins/hooks.ts +11 -0
- package/src/plugins/manager.ts +6 -0
- package/src/plugins/manifest-schema.ts +12 -0
- package/src/plugins/request-meta.ts +66 -15
- package/src/plugins/routes.ts +3 -1
- package/src/plugins/types.ts +23 -2
- package/src/query.ts +1 -1
- package/src/request-cache.ts +3 -0
- package/src/schema/registry.ts +41 -5
- package/src/search/fts-manager.ts +0 -2
- package/src/search/query.ts +111 -26
- package/src/search/types.ts +8 -1
- package/src/sections/index.ts +7 -9
- package/src/seed/apply.ts +26 -0
- package/src/storage/s3.ts +12 -6
- package/src/virtual-modules.d.ts +21 -1
- package/src/visual-editing/toolbar.ts +6 -1
- package/src/widgets/index.ts +1 -1
- package/dist/apply-B4MsLM-w.mjs.map +0 -1
- package/dist/byline-C4OVd8b3.mjs.map +0 -1
- package/dist/content-BsBoyj8G.mjs.map +0 -1
- package/dist/error-CiYn9yDu.mjs.map +0 -1
- package/dist/index-BYv0mB9g.d.mts.map +0 -1
- package/dist/loader-DeiBJEMe.mjs.map +0 -1
- package/dist/manifest-schema-V30qsMft.mjs.map +0 -1
- package/dist/media-DqHVh136.mjs.map +0 -1
- package/dist/mode-CpNnGkPz.mjs.map +0 -1
- package/dist/redirect-7lGhLBNZ.mjs.map +0 -1
- package/dist/registry-Ci3WxVAr.mjs.map +0 -1
- package/dist/request-cache-DiR961CV.mjs.map +0 -1
- package/dist/runner-Cd-_WyDo.mjs.map +0 -1
- package/dist/search-DI4bM2w9.mjs.map +0 -1
- package/dist/types-CMMN0pNg.mjs +0 -31
- package/dist/types-CMMN0pNg.mjs.map +0 -1
- package/dist/types-DgrIP0tF.d.mts.map +0 -1
- package/dist/version-Uaf2ynPX.mjs +0 -7
package/dist/index.mjs
CHANGED
|
@@ -1,32 +1,34 @@
|
|
|
1
1
|
import { getRequestContext, runWithContext } from "./request-context.mjs";
|
|
2
2
|
import { t as EmDashDatabaseError } from "./connection-2igzM-AT.mjs";
|
|
3
3
|
import "./dialect-helpers-DhTzaUxP.mjs";
|
|
4
|
-
import { t as getMigrationStatus } from "./runner-
|
|
5
|
-
import { $ as
|
|
6
|
-
import { i as decodeSlug, t as ContentRepository } from "./content-
|
|
4
|
+
import { t as getMigrationStatus } from "./runner-tQ7BJ4T7.mjs";
|
|
5
|
+
import { $ as prosemirrorToPortableText, A as isStandardPluginDefinition, At as handleContentSchedule, C as getAllSources, Ct as handleContentGet, D as probeUrl, Dt as handleContentPermanentDelete, E as getUrlSources, Et as handleContentListTrashed, F as createPluginManager, H as createHookPipeline, I as PluginRouteError, It as portableText, J as definePlugin, Lt as reference, M as SandboxNotAvailableError, Mt as handleContentUnpublish, N as createNoopSandboxRunner, Nt as handleContentUnschedule, O as registerSource, Ot as handleContentPublish, P as PluginManager, Pt as handleContentUpdate, Q as portableTextToProsemirror, Rt as image, S as clearSources, St as handleContentDuplicate, T as getSource, Tt as handleContentList, V as HookPipeline, X as parseWxrString, Y as parseWxr, Z as after, _ as buildPreviewUrl, _t as handleContentCountScheduled, a as search, b as parseWxrDate, bt as handleContentDelete, c as getWidgetArea, ct as handleMediaDelete, d as getMenu, dt as handleMediaUpdate, et as isSafeHref, f as getMenus, ft as handleRevisionGet, g as isPreviewRequest, gt as handleContentCompare, h as getPreviewToken, ht as generateManifest, i as getSuggestions, it as getSections, j as NoopSandboxRunner, jt as handleContentTranslations, k as importReusableBlocksAsSections, kt as handleContentRestore, l as getWidgetAreas, lt as handleMediaGet, m as getComments, mt as handleRevisionRestore, n as extractSearchableFields, o as searchCollection, ot as getCollectionInfo, p as getCommentCount, pt as handleRevisionList, r as getSearchStats, rt as getSection, s as searchWithDb, st as handleMediaCreate, t as extractPlainText, tt as sanitizeHref, u as getWidgetComponents, ut as handleMediaList, v as getPreviewUrl, vt as handleContentCountTrashed, w as getFileSources, wt as handleContentGetIncludingTrashed, x as wxrSource, xt as handleContentDiscardDraft, y as wordpressRestSource, yt as handleContentCreate } from "./search-BoZYFuUk.mjs";
|
|
6
|
+
import { i as decodeSlug, t as ContentRepository } from "./content-BcQPYxdV.mjs";
|
|
7
7
|
import "./base64-MBPo9ozB.mjs";
|
|
8
|
-
import { t as EmDashValidationError } from "./types-
|
|
9
|
-
import { t as MediaRepository } from "./media-
|
|
10
|
-
import { c as
|
|
11
|
-
import "./redirect-
|
|
12
|
-
import "./byline-
|
|
8
|
+
import { n as InvalidCursorError, t as EmDashValidationError } from "./types-BIgulNsW.mjs";
|
|
9
|
+
import { t as MediaRepository } from "./media-D8FbNsl0.mjs";
|
|
10
|
+
import { c as getPluginSetting, d as getSiteSettings, f as setSiteSettings, l as getPluginSettings, t as applySeed, u as getSiteSetting } from "./apply-x0eMK1lX.mjs";
|
|
11
|
+
import "./redirect-D_pshWdf.mjs";
|
|
12
|
+
import "./byline-Chbr2GoP.mjs";
|
|
13
13
|
import { n as normalizeMediaValue, t as generatePlaceholder } from "./placeholder-C-fk5hYI.mjs";
|
|
14
14
|
import { n as getI18nConfig, r as isI18nEnabled, t as getFallbackChain } from "./config-BXwuX8Bx.mjs";
|
|
15
|
-
import {
|
|
16
|
-
import { i as
|
|
17
|
-
import "./
|
|
18
|
-
import "./
|
|
19
|
-
import
|
|
20
|
-
import { i as
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
15
|
+
import { n as computeContentHash, r as hashString } from "./zod-generator-CpwccCIv.mjs";
|
|
16
|
+
import { i as FTSManager, n as SchemaRegistry, t as SchemaError } from "./registry-C3Mr0ODu.mjs";
|
|
17
|
+
import { i as RESERVED_FIELD_SLUGS, n as FIELD_TYPE_TO_COLUMN, r as RESERVED_COLLECTION_SLUGS } from "./types-Bm1dn-q3.mjs";
|
|
18
|
+
import "./loader-CndGj8kM.mjs";
|
|
19
|
+
import "./request-cache-Ci7f5pBb.mjs";
|
|
20
|
+
import { a as getTaxonomyDefs, c as getTermsForEntries, i as getTaxonomyDef, l as invalidateTermCache, n as getEntriesByTerm, o as getTaxonomyTerms, r as getEntryTerms, s as getTerm, t as getAllTermsForEntries } from "./taxonomies-B4IAshV8.mjs";
|
|
21
|
+
import { i as pluginManifestSchema } from "./manifest-schema-DH9xhc6t.mjs";
|
|
22
|
+
import { t as EmDashStorageError } from "./types-CgqmmMJB.mjs";
|
|
23
|
+
import "./error-zG5T1UGA.mjs";
|
|
24
|
+
import { c as createEditable, i as getTranslations, l as createNoop, n as getEmDashCollection, r as getEmDashEntry, s as resolveEmDashPath, t as getEditMeta } from "./query-fqEdLFms.mjs";
|
|
23
25
|
import { adaptSandboxEntry } from "./plugins/adapt-sandbox-entry.mjs";
|
|
24
|
-
import { n as parseContentId, r as verifyPreviewToken, t as generatePreviewToken } from "./tokens-
|
|
26
|
+
import { n as parseContentId, r as verifyPreviewToken, t as generatePreviewToken } from "./tokens-D9vnZqYS.mjs";
|
|
25
27
|
import { getContentSeo, getSeoMeta } from "./seo/index.mjs";
|
|
26
|
-
import { n as getByline, r as getBylineBySlug } from "./bylines-
|
|
27
|
-
import { t as validateSeed } from "./validate-
|
|
28
|
-
import "./load-
|
|
28
|
+
import { n as getByline, r as getBylineBySlug } from "./bylines-CRNsVG88.mjs";
|
|
29
|
+
import { t as validateSeed } from "./validate-CxVsLehf.mjs";
|
|
30
|
+
import "./load-CyEoextb.mjs";
|
|
29
31
|
import "./seed/index.mjs";
|
|
30
32
|
import { ulid } from "ulidx";
|
|
31
33
|
|
|
32
|
-
export { ContentRepository, EmDashDatabaseError, EmDashStorageError, EmDashValidationError, FIELD_TYPE_TO_COLUMN, FTSManager, HookPipeline, MediaRepository, NoopSandboxRunner, PluginManager, PluginRouteError, RESERVED_COLLECTION_SLUGS, RESERVED_FIELD_SLUGS, SandboxNotAvailableError, SchemaError, SchemaRegistry, adaptSandboxEntry, after, applySeed, buildPreviewUrl, clearSources, computeContentHash, createEditable, createHookPipeline, createNoop, createNoopSandboxRunner, createPluginManager, decodeSlug, definePlugin, extractPlainText, extractSearchableFields, generateManifest, generatePlaceholder, generatePreviewToken, getAllSources, getAllTermsForEntries, getByline, getBylineBySlug, getCollectionInfo, getCommentCount, getComments, getContentSeo, getEditMeta, getEmDashCollection, getEmDashEntry, getEntriesByTerm, getEntryTerms, getFallbackChain, getFileSources, getI18nConfig, getMenu, getMenus, getMigrationStatus, getPluginSetting, getPluginSettings, getPreviewToken, getPreviewUrl, getRequestContext, getSearchStats, getSection, getSections, getSeoMeta, getSiteSetting, getSiteSettings, getSource, getSuggestions, getTaxonomyDef, getTaxonomyDefs, getTaxonomyTerms, getTerm, getTermsForEntries, getTranslations, getUrlSources, getWidgetArea, getWidgetAreas, getWidgetComponents, handleContentCompare, handleContentCountScheduled, handleContentCountTrashed, handleContentCreate, handleContentDelete, handleContentDiscardDraft, handleContentDuplicate, handleContentGet, handleContentGetIncludingTrashed, handleContentList, handleContentListTrashed, handleContentPermanentDelete, handleContentPublish, handleContentRestore, handleContentSchedule, handleContentTranslations, handleContentUnpublish, handleContentUnschedule, handleContentUpdate, handleMediaCreate, handleMediaDelete, handleMediaGet, handleMediaList, handleMediaUpdate, handleRevisionGet, handleRevisionList, handleRevisionRestore, hashString, image, importReusableBlocksAsSections, invalidateTermCache, isI18nEnabled, isPreviewRequest, isSafeHref, isStandardPluginDefinition, normalizeMediaValue, parseContentId, parseWxr, parseWxrDate, parseWxrString, pluginManifestSchema, portableText, portableTextToProsemirror, probeUrl, prosemirrorToPortableText, reference, registerSource, resolveEmDashPath, runWithContext, sanitizeHref, search, searchCollection, searchWithDb, setSiteSettings, ulid, validateSeed, verifyPreviewToken, wordpressRestSource, wxrSource };
|
|
34
|
+
export { ContentRepository, EmDashDatabaseError, EmDashStorageError, EmDashValidationError, FIELD_TYPE_TO_COLUMN, FTSManager, HookPipeline, InvalidCursorError, MediaRepository, NoopSandboxRunner, PluginManager, PluginRouteError, RESERVED_COLLECTION_SLUGS, RESERVED_FIELD_SLUGS, SandboxNotAvailableError, SchemaError, SchemaRegistry, adaptSandboxEntry, after, applySeed, buildPreviewUrl, clearSources, computeContentHash, createEditable, createHookPipeline, createNoop, createNoopSandboxRunner, createPluginManager, decodeSlug, definePlugin, extractPlainText, extractSearchableFields, generateManifest, generatePlaceholder, generatePreviewToken, getAllSources, getAllTermsForEntries, getByline, getBylineBySlug, getCollectionInfo, getCommentCount, getComments, getContentSeo, getEditMeta, getEmDashCollection, getEmDashEntry, getEntriesByTerm, getEntryTerms, getFallbackChain, getFileSources, getI18nConfig, getMenu, getMenus, getMigrationStatus, getPluginSetting, getPluginSettings, getPreviewToken, getPreviewUrl, getRequestContext, getSearchStats, getSection, getSections, getSeoMeta, getSiteSetting, getSiteSettings, getSource, getSuggestions, getTaxonomyDef, getTaxonomyDefs, getTaxonomyTerms, getTerm, getTermsForEntries, getTranslations, getUrlSources, getWidgetArea, getWidgetAreas, getWidgetComponents, handleContentCompare, handleContentCountScheduled, handleContentCountTrashed, handleContentCreate, handleContentDelete, handleContentDiscardDraft, handleContentDuplicate, handleContentGet, handleContentGetIncludingTrashed, handleContentList, handleContentListTrashed, handleContentPermanentDelete, handleContentPublish, handleContentRestore, handleContentSchedule, handleContentTranslations, handleContentUnpublish, handleContentUnschedule, handleContentUpdate, handleMediaCreate, handleMediaDelete, handleMediaGet, handleMediaList, handleMediaUpdate, handleRevisionGet, handleRevisionList, handleRevisionRestore, hashString, image, importReusableBlocksAsSections, invalidateTermCache, isI18nEnabled, isPreviewRequest, isSafeHref, isStandardPluginDefinition, normalizeMediaValue, parseContentId, parseWxr, parseWxrDate, parseWxrString, pluginManifestSchema, portableText, portableTextToProsemirror, probeUrl, prosemirrorToPortableText, reference, registerSource, resolveEmDashPath, runWithContext, sanitizeHref, search, searchCollection, searchWithDb, setSiteSettings, ulid, validateSeed, verifyPreviewToken, wordpressRestSource, wxrSource };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-
|
|
1
|
+
{"version":3,"file":"load-CyEoextb.mjs","names":[],"sources":["../src/seed/load.ts"],"sourcesContent":["/**\n * Seed file loading\n *\n * Imports seed data from the virtual module, which embeds the user's seed file\n * (or the default seed) at Vite build time. This avoids runtime filesystem access,\n * which doesn't work in workerd/miniflare where process.cwd() returns \"/\".\n */\n\nimport type { SeedFile } from \"./types.js\";\n\ninterface SeedModule {\n\tseed: SeedFile;\n\tuserSeed: SeedFile | null;\n}\n\nasync function getSeedModule(): Promise<SeedModule> {\n\t// @ts-ignore - virtual module, only available within Vite runtime\n\treturn import(\"virtual:emdash/seed\") as Promise<SeedModule>;\n}\n\n/**\n * Load the seed file (user seed or default).\n */\nexport async function loadSeed(): Promise<SeedFile> {\n\tconst { seed } = await getSeedModule();\n\treturn seed;\n}\n\n/**\n * Load the user's seed file, or null if none exists.\n */\nexport async function loadUserSeed(): Promise<SeedFile | null> {\n\tconst { userSeed } = await getSeedModule();\n\treturn userSeed ?? null;\n}\n"],"mappings":";;;;;;;AAeA,eAAe,gBAAqC;AAEnD,QAAO,OAAO;;;;;AAMf,eAAsB,WAA8B;CACnD,MAAM,EAAE,SAAS,MAAM,eAAe;AACtC,QAAO;;;;;AAMR,eAAsB,eAAyC;CAC9D,MAAM,EAAE,aAAa,MAAM,eAAe;AAC1C,QAAO,YAAY"}
|
|
@@ -3,8 +3,8 @@ import { getRequestContext } from "./request-context.mjs";
|
|
|
3
3
|
import { kyselyLogOption } from "./database/instrumentation.mjs";
|
|
4
4
|
import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
|
|
5
5
|
import { i as isPostgres, r as currentTimestampValue } from "./dialect-helpers-DhTzaUxP.mjs";
|
|
6
|
-
import {
|
|
7
|
-
import { t as isMissingTableError } from "./db-errors-
|
|
6
|
+
import { i as encodeCursor, r as decodeCursor } from "./types-BIgulNsW.mjs";
|
|
7
|
+
import { t as isMissingTableError } from "./db-errors-l1Qh2RPR.mjs";
|
|
8
8
|
import { Kysely, sql } from "kysely";
|
|
9
9
|
|
|
10
10
|
//#region src/loader.ts
|
|
@@ -199,11 +199,13 @@ function buildOrderByClause(orderBy, tablePrefix) {
|
|
|
199
199
|
/**
|
|
200
200
|
* Build a cursor WHERE condition for keyset pagination.
|
|
201
201
|
* Uses the primary sort field + id as tiebreaker for stable ordering.
|
|
202
|
+
*
|
|
203
|
+
* Throws `InvalidCursorError` if the cursor is malformed; callers should
|
|
204
|
+
* let this propagate so users see a real error rather than silently
|
|
205
|
+
* falling back to the first page.
|
|
202
206
|
*/
|
|
203
207
|
function buildCursorCondition(cursor, orderBy, tablePrefix) {
|
|
204
|
-
const
|
|
205
|
-
if (!decoded) return null;
|
|
206
|
-
const { orderValue, id: cursorId } = decoded;
|
|
208
|
+
const { orderValue, id: cursorId } = decodeCursor(cursor);
|
|
207
209
|
const primary = getPrimarySort(orderBy, tablePrefix);
|
|
208
210
|
const idField = tablePrefix ? `${tablePrefix}.id` : "id";
|
|
209
211
|
if (primary.direction === "desc") return sql`(${sql.ref(primary.field)} < ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} < ${cursorId}))`;
|
|
@@ -452,4 +454,4 @@ function emdashLoader() {
|
|
|
452
454
|
|
|
453
455
|
//#endregion
|
|
454
456
|
export { getDb as n, loader_exports as r, emdashLoader as t };
|
|
455
|
-
//# sourceMappingURL=loader-
|
|
457
|
+
//# sourceMappingURL=loader-CndGj8kM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loader-CndGj8kM.mjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Astro Live Collections loader for EmDash\n *\n * This loader implements the Astro LiveLoader interface to fetch content\n * at runtime from the database, enabling live editing without rebuilds.\n *\n * Architecture:\n * - Single `_emdash` Astro collection handles all content types\n * - Dialect comes from virtual module (configured in astro.config.mjs)\n * - Each content type maps to its own database table: ec_posts, ec_products, etc.\n * - `getEmDashCollection()` / `getEmDashEntry()` wrap Astro's live collection API\n */\n\nimport type { LiveLoader } from \"astro/loaders\";\nimport { Kysely, sql, type Dialect } from \"kysely\";\n\nimport { currentTimestampValue, isPostgres } from \"./database/dialect-helpers.js\";\nimport { kyselyLogOption } from \"./database/instrumentation.js\";\nimport { decodeCursor, encodeCursor } from \"./database/repositories/types.js\";\nimport { validateIdentifier } from \"./database/validate.js\";\nimport type { Database } from \"./index.js\";\nimport { getRequestContext } from \"./request-context.js\";\nimport { isMissingTableError } from \"./utils/db-errors.js\";\n\nconst FIELD_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * System columns that are not part of the content data\n */\n/**\n * System columns excluded from entry.data\n * Note: slug is intentionally NOT excluded - it's useful as data.slug in templates\n */\nconst SYSTEM_COLUMNS = new Set([\n\t\"id\",\n\t// \"slug\" - kept in data for template access\n\t\"status\",\n\t\"author_id\",\n\t\"primary_byline_id\",\n\t\"created_at\",\n\t\"updated_at\",\n\t\"published_at\",\n\t\"scheduled_at\",\n\t\"deleted_at\",\n\t\"version\",\n\t\"live_revision_id\",\n\t\"draft_revision_id\",\n\t\"locale\",\n\t\"translation_group\",\n]);\n\n/**\n * Get the table name for a collection type\n */\nfunction getTableName(type: string): string {\n\tvalidateIdentifier(type, \"collection type\");\n\treturn `ec_${type}`;\n}\n\n/**\n * Cache for taxonomy names (only used for the primary database).\n * Skipped when a per-request DB override is active (e.g. preview mode)\n * because the override DB may have different taxonomies.\n */\nlet taxonomyNames: Set<string> | null = null;\n\n/**\n * Get all taxonomy names (cached for the primary DB, bypassed only when\n * the per-request DB is an isolated instance — playground / DO preview).\n * Plain D1 Sessions routing shares schema with the singleton, so the\n * module-scoped cache stays valid.\n */\nasync function getTaxonomyNames(db: Kysely<Database>): Promise<Set<string>> {\n\tconst hasIsolatedDb = getRequestContext()?.dbIsIsolated === true;\n\n\tif (!hasIsolatedDb && taxonomyNames) {\n\t\treturn taxonomyNames;\n\t}\n\n\ttry {\n\t\tconst defs = await db.selectFrom(\"_emdash_taxonomy_defs\").select(\"name\").execute();\n\t\tconst names = new Set(defs.map((d) => d.name));\n\t\tif (!hasIsolatedDb) {\n\t\t\ttaxonomyNames = names;\n\t\t}\n\t\treturn names;\n\t} catch {\n\t\t// Table doesn't exist yet, return empty set\n\t\tconst empty = new Set<string>();\n\t\tif (!hasIsolatedDb) {\n\t\t\ttaxonomyNames = empty;\n\t\t}\n\t\treturn empty;\n\t}\n}\n\n/**\n * System columns to include in data (mapped to camelCase where needed)\n */\nconst INCLUDE_IN_DATA: Record<string, string> = {\n\tid: \"id\",\n\tstatus: \"status\",\n\tauthor_id: \"authorId\",\n\tprimary_byline_id: \"primaryBylineId\",\n\tcreated_at: \"createdAt\",\n\tupdated_at: \"updatedAt\",\n\tpublished_at: \"publishedAt\",\n\tscheduled_at: \"scheduledAt\",\n\tdraft_revision_id: \"draftRevisionId\",\n\tlive_revision_id: \"liveRevisionId\",\n\tlocale: \"locale\",\n\ttranslation_group: \"translationGroup\",\n};\n\n/** System date columns that should be converted to Date objects */\nconst DATE_COLUMNS = new Set([\"created_at\", \"updated_at\", \"published_at\", \"scheduled_at\"]);\n\n/** Safely extract a string value from a record, returning fallback if not a string */\nfunction rowStr(row: Record<string, unknown>, key: string, fallback = \"\"): string {\n\tconst val = row[key];\n\treturn typeof val === \"string\" ? val : fallback;\n}\n\n/**\n * Map a database row to entry data\n * Extracts content fields (non-system columns) and parses JSON where needed.\n * System columns needed for templates (id, status, dates) are included with camelCase names.\n */\nfunction mapRowToData(row: Record<string, unknown>): Record<string, unknown> {\n\tconst data: Record<string, unknown> = {};\n\n\tfor (const [key, value] of Object.entries(row)) {\n\t\t// Include certain system columns (mapped to camelCase where needed)\n\t\tif (key in INCLUDE_IN_DATA) {\n\t\t\t// Convert date columns from ISO strings to Date objects\n\t\t\tif (DATE_COLUMNS.has(key)) {\n\t\t\t\tdata[INCLUDE_IN_DATA[key]] = typeof value === \"string\" ? new Date(value) : null;\n\t\t\t} else {\n\t\t\t\tdata[INCLUDE_IN_DATA[key]] = value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (SYSTEM_COLUMNS.has(key)) continue;\n\n\t\t// Try to parse JSON strings (for portableText, json fields, etc.)\n\t\tif (typeof value === \"string\") {\n\t\t\ttry {\n\t\t\t\t// Only parse if it looks like JSON (starts with { or [)\n\t\t\t\tif (value.startsWith(\"{\") || value.startsWith(\"[\")) {\n\t\t\t\t\tdata[key] = JSON.parse(value);\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = value;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tdata[key] = value;\n\t\t\t}\n\t\t} else {\n\t\t\tdata[key] = value;\n\t\t}\n\t}\n\n\treturn data;\n}\n\n/**\n * Map revision data (already-parsed JSON object) to entry data.\n * Strips _-prefixed metadata keys (e.g. _slug) used internally by revisions.\n */\nfunction mapRevisionData(data: Record<string, unknown>): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (key.startsWith(\"_\")) continue; // revision metadata\n\t\tresult[key] = value;\n\t}\n\treturn result;\n}\n\n// Virtual module imports are lazy-loaded to avoid errors when importing\n// emdash outside of Astro/Vite context (e.g., in astro.config.mjs)\nlet virtualConfig:\n\t| {\n\t\t\tdatabase?: { config: unknown };\n\t\t\ti18n?: { defaultLocale: string; locales: string[]; prefixDefaultLocale?: boolean } | null;\n\t }\n\t| undefined;\nlet virtualCreateDialect: ((config: unknown) => Dialect) | undefined;\n\nasync function loadVirtualModules() {\n\tif (virtualConfig === undefined) {\n\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t// @ts-ignore - virtual module\n\t\tconst configModule = await import(\"virtual:emdash/config\");\n\t\tvirtualConfig = configModule.default;\n\t}\n\tif (virtualCreateDialect === undefined) {\n\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t// @ts-ignore - virtual module\n\t\tconst dialectModule = await import(\"virtual:emdash/dialect\");\n\t\tvirtualCreateDialect = dialectModule.createDialect;\n\t\t// dialectType is no longer needed here — dialect detection is\n\t\t// done via the db adapter instance in dialect-helpers.ts\n\t}\n}\n\n/**\n * Entry data type - generic object\n */\nexport type EntryData = Record<string, unknown>;\n\n/**\n * Sort direction\n */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/**\n * Order by specification - field name to direction\n * @example { created_at: \"desc\" } - Sort by created_at descending\n * @example { title: \"asc\" } - Sort by title ascending\n */\nexport type OrderBySpec = Record<string, SortDirection>;\n\n/**\n * Build WHERE clause for status filtering.\n * When filtering for 'published' status, also include scheduled content\n * whose scheduled_at time has passed (treating it as effectively published).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nfunction buildStatusCondition(\n\tdb: Kysely<any>,\n\tstatus: string,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\tconst statusField = tablePrefix ? `${tablePrefix}.status` : \"status\";\n\tconst scheduledAtField = tablePrefix ? `${tablePrefix}.scheduled_at` : \"scheduled_at\";\n\n\tif (status === \"published\") {\n\t\t// Include both published content AND scheduled content past its publish time.\n\t\t// scheduled_at is stored as text (ISO 8601). On Postgres, we must cast it\n\t\t// to timestamptz for the comparison with CURRENT_TIMESTAMP to work.\n\t\tconst scheduledAtExpr = isPostgres(db)\n\t\t\t? sql`${sql.ref(scheduledAtField)}::timestamptz`\n\t\t\t: sql.ref(scheduledAtField);\n\t\treturn sql`(${sql.ref(statusField)} = 'published' OR (${sql.ref(statusField)} = 'scheduled' AND ${scheduledAtExpr} <= ${currentTimestampValue(db)}))`;\n\t}\n\n\t// For other statuses (draft, archived), just match exactly\n\treturn sql`${sql.ref(statusField)} = ${status}`;\n}\n\n/**\n * Resolved primary sort field and direction (used for cursor pagination).\n */\ninterface PrimarySort {\n\tfield: string;\n\tdirection: SortDirection;\n}\n\n/**\n * Get the primary sort field from an orderBy spec (first valid field, or default).\n */\nfunction getPrimarySort(orderBy: OrderBySpec | undefined, tablePrefix?: string): PrimarySort {\n\tif (orderBy) {\n\t\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t\tif (FIELD_NAME_PATTERN.test(field)) {\n\t\t\t\tconst fullField = tablePrefix ? `${tablePrefix}.${field}` : field;\n\t\t\t\treturn { field: fullField, direction };\n\t\t\t}\n\t\t}\n\t}\n\tconst defaultField = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\treturn { field: defaultField, direction: \"desc\" };\n}\n\n/**\n * Build ORDER BY clause from orderBy spec\n * Validates field names to prevent SQL injection (alphanumeric + underscore only)\n * Supports multiple sort fields in object key order\n */\nfunction buildOrderByClause(\n\torderBy: OrderBySpec | undefined,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\t// Default to created_at DESC\n\tif (!orderBy || Object.keys(orderBy).length === 0) {\n\t\tconst field = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\t\treturn sql`ORDER BY ${sql.ref(field)} DESC, ${sql.ref(tablePrefix ? `${tablePrefix}.id` : \"id\")} DESC`;\n\t}\n\n\tconst sortParts: ReturnType<typeof sql>[] = [];\n\n\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t// Validate field name (alphanumeric + underscore only)\n\t\tif (!FIELD_NAME_PATTERN.test(field)) {\n\t\t\tcontinue; // Skip invalid field names\n\t\t}\n\n\t\tconst fullField = tablePrefix ? `${tablePrefix}.${field}` : field;\n\t\tconst dir = direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\t\tsortParts.push(sql`${sql.ref(fullField)} ${dir}`);\n\t}\n\n\t// If no valid sort fields, fall back to default\n\tif (sortParts.length === 0) {\n\t\tconst defaultField = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\t\treturn sql`ORDER BY ${sql.ref(defaultField)} DESC, ${sql.ref(tablePrefix ? `${tablePrefix}.id` : \"id\")} DESC`;\n\t}\n\n\t// Add id as tiebreaker to ensure stable cursor ordering\n\tconst primary = getPrimarySort(orderBy, tablePrefix);\n\tconst idField = tablePrefix ? `${tablePrefix}.id` : \"id\";\n\tconst idDir = primary.direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\tsortParts.push(sql`${sql.ref(idField)} ${idDir}`);\n\n\treturn sql`ORDER BY ${sql.join(sortParts, sql`, `)}`;\n}\n\n/**\n * Build a cursor WHERE condition for keyset pagination.\n * Uses the primary sort field + id as tiebreaker for stable ordering.\n *\n * Throws `InvalidCursorError` if the cursor is malformed; callers should\n * let this propagate so users see a real error rather than silently\n * falling back to the first page.\n */\nfunction buildCursorCondition(\n\tcursor: string,\n\torderBy: OrderBySpec | undefined,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\tconst { orderValue, id: cursorId } = decodeCursor(cursor);\n\tconst primary = getPrimarySort(orderBy, tablePrefix);\n\tconst idField = tablePrefix ? `${tablePrefix}.id` : \"id\";\n\n\tif (primary.direction === \"desc\") {\n\t\treturn sql`(${sql.ref(primary.field)} < ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} < ${cursorId}))`;\n\t}\n\treturn sql`(${sql.ref(primary.field)} > ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} > ${cursorId}))`;\n}\n\n/**\n * Filter for loadCollection - type is required\n */\nexport interface CollectionFilter {\n\ttype: string;\n\tstatus?: \"draft\" | \"published\" | \"archived\";\n\tlimit?: number;\n\t/**\n\t * Opaque cursor for keyset pagination.\n\t * Pass the `nextCursor` value from a previous result to fetch the next page.\n\t */\n\tcursor?: string;\n\t/**\n\t * Filter by field values or taxonomy terms\n\t */\n\twhere?: Record<string, string | string[]>;\n\t/**\n\t * Order results by field(s)\n\t * @default { created_at: \"desc\" }\n\t */\n\torderBy?: OrderBySpec;\n\t/**\n\t * Filter by locale (e.g. 'en', 'fr').\n\t * When set, only returns content in this locale.\n\t */\n\tlocale?: string;\n}\n\n/**\n * Filter for loadEntry - type and id are required\n */\nexport interface EntryFilter {\n\ttype: string;\n\tid: string;\n\t/**\n\t * When set, fetch content data from this revision instead of the content table.\n\t * Used by preview mode to serve draft revision data.\n\t */\n\trevisionId?: string;\n\t/**\n\t * Locale to scope slug lookup. Only affects slug resolution;\n\t * IDs are globally unique and always resolve regardless of locale.\n\t */\n\tlocale?: string;\n}\n\n// Cached database instance (shared across calls)\nlet dbInstance: Kysely<Database> | null = null;\n\n/**\n * Get the database instance. Used by query wrapper functions and middleware.\n *\n * Checks the ALS request context first — if a per-request DB override is set\n * (e.g. by DO preview middleware), it takes precedence over the module-level\n * cached instance. This allows preview mode to route queries to an isolated\n * Durable Object database without modifying any calling code.\n *\n * Initializes the default database on first call using config from virtual module.\n */\nexport async function getDb(): Promise<Kysely<Database>> {\n\t// Per-request DB override via ALS (normal mode)\n\tconst ctx = getRequestContext();\n\tif (ctx?.db) {\n\t\treturn ctx.db as Kysely<Database>; // eslint-disable-line typescript-eslint(no-unsafe-type-assertion) -- db is typed as unknown in RequestContext to avoid circular deps\n\t}\n\n\tif (!dbInstance) {\n\t\tawait loadVirtualModules();\n\t\tif (!virtualConfig?.database || typeof virtualCreateDialect !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"EmDash database not configured. Add database config to emdash() in astro.config.mjs\",\n\t\t\t);\n\t\t}\n\t\tconst dialect = virtualCreateDialect(virtualConfig.database.config);\n\t\tdbInstance = new Kysely<Database>({ dialect, log: kyselyLogOption() });\n\t}\n\treturn dbInstance;\n}\n\n/**\n * Create an EmDash Live Collections loader\n *\n * This loader handles ALL content types in a single Astro collection.\n * Use `getEmDashCollection()` and `getEmDashEntry()` to query\n * specific content types.\n *\n * Database is configured in astro.config.mjs via the emdash() integration.\n *\n * @example\n * ```ts\n * // src/live.config.ts\n * import { defineLiveCollection } from \"astro:content\";\n * import { emdashLoader } from \"emdash\";\n *\n * export const collections = {\n * emdash: defineLiveCollection({\n * loader: emdashLoader(),\n * }),\n * };\n * ```\n */\nexport function emdashLoader(): LiveLoader<EntryData, EntryFilter, CollectionFilter> {\n\treturn {\n\t\tname: \"emdash\",\n\n\t\t/**\n\t\t * Load all entries for a content type\n\t\t */\n\t\tasync loadCollection({ filter }) {\n\t\t\ttry {\n\t\t\t\t// Get DB instance (initializes on first use)\n\t\t\t\tconst db = await getDb();\n\n\t\t\t\t// Type filter is required\n\t\t\t\tconst type = filter?.type;\n\t\t\t\tif (!type) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\"type filter is required. Use getEmDashCollection() instead of getLiveCollection() directly.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Query the per-collection table (ec_posts, ec_products, etc.)\n\t\t\t\tconst tableName = getTableName(type);\n\n\t\t\t\t// Build query with dynamic table name\n\t\t\t\tconst status = filter?.status || \"published\";\n\t\t\t\tconst limit = filter?.limit;\n\t\t\t\tconst cursor = filter?.cursor;\n\t\t\t\tconst where = filter?.where;\n\t\t\t\tconst orderBy = filter?.orderBy;\n\t\t\t\tconst locale = filter?.locale;\n\n\t\t\t\t// Cursor pagination: over-fetch by 1 to detect next page\n\t\t\t\tconst fetchLimit = limit ? limit + 1 : undefined;\n\n\t\t\t\t// Build cursor condition if cursor is provided\n\t\t\t\tconst cursorCondition = cursor ? buildCursorCondition(cursor, orderBy) : null;\n\t\t\t\tconst cursorConditionPrefixed = cursor\n\t\t\t\t\t? buildCursorCondition(cursor, orderBy, tableName)\n\t\t\t\t\t: null;\n\n\t\t\t\t// Check if we need taxonomy filtering\n\t\t\t\tlet result: { rows: Record<string, unknown>[] };\n\n\t\t\t\tif (where && Object.keys(where).length > 0) {\n\t\t\t\t\t// Get taxonomy names to detect taxonomy filters\n\t\t\t\t\tconst taxNames = await getTaxonomyNames(db);\n\t\t\t\t\tconst taxonomyFilters: Record<string, string | string[]> = {};\n\n\t\t\t\t\tfor (const [key, value] of Object.entries(where)) {\n\t\t\t\t\t\tif (taxNames.has(key)) {\n\t\t\t\t\t\t\ttaxonomyFilters[key] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// If we have taxonomy filters, use JOIN\n\t\t\t\t\tif (Object.keys(taxonomyFilters).length > 0) {\n\t\t\t\t\t\t// Build query with taxonomy JOIN\n\t\t\t\t\t\t// For now, support single taxonomy filter (can extend later for multiple)\n\t\t\t\t\t\tconst [taxName, termSlugs] = Object.entries(taxonomyFilters)[0];\n\t\t\t\t\t\tconst slugs = Array.isArray(termSlugs) ? termSlugs : [termSlugs];\n\t\t\t\t\t\tconst orderByClause = buildOrderByClause(orderBy, tableName);\n\n\t\t\t\t\t\tconst statusCondition = buildStatusCondition(db, status, tableName);\n\t\t\t\t\t\tconst localeCondition = locale\n\t\t\t\t\t\t\t? sql`AND ${sql.ref(tableName)}.locale = ${locale}`\n\t\t\t\t\t\t\t: sql``;\n\t\t\t\t\t\tconst cursorCond = cursorConditionPrefixed\n\t\t\t\t\t\t\t? sql`AND ${cursorConditionPrefixed}`\n\t\t\t\t\t\t\t: sql``;\n\t\t\t\t\t\tresult = await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT DISTINCT ${sql.ref(tableName)}.* FROM ${sql.ref(tableName)}\n\t\t\t\t\t\t\tINNER JOIN content_taxonomies ct\n\t\t\t\t\t\t\t\tON ct.collection = ${type}\n\t\t\t\t\t\t\t\tAND ct.entry_id = ${sql.ref(tableName)}.id\n\t\t\t\t\t\t\tINNER JOIN taxonomies t\n\t\t\t\t\t\t\t\tON t.id = ct.taxonomy_id\n\t\t\t\t\t\t\tWHERE ${sql.ref(tableName)}.deleted_at IS NULL\n\t\t\t\t\t\t\t\tAND ${statusCondition}\n\t\t\t\t\t\t\t\t${localeCondition}\n\t\t\t\t\t\t\t\t${cursorCond}\n\t\t\t\t\t\t\t\tAND t.name = ${taxName}\n\t\t\t\t\t\t\t\tAND t.slug IN (${sql.join(slugs.map((s) => sql`${s}`))})\n\t\t\t\t\t\t\t${orderByClause}\n\t\t\t\t\t\t\t${fetchLimit ? sql`LIMIT ${fetchLimit}` : sql``}\n\t\t\t\t\t\t`.execute(db);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// No taxonomy filters, use simple query\n\t\t\t\t\t\tconst orderByClause = buildOrderByClause(orderBy);\n\t\t\t\t\t\tconst statusCondition = buildStatusCondition(db, status);\n\t\t\t\t\t\tconst localeFilter = locale ? sql`AND locale = ${locale}` : sql``;\n\t\t\t\t\t\tconst cursorCond = cursorCondition ? sql`AND ${cursorCondition}` : sql``;\n\t\t\t\t\t\tresult = await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\t\tAND ${statusCondition}\n\t\t\t\t\t\t\t${localeFilter}\n\t\t\t\t\t\t\t${cursorCond}\n\t\t\t\t\t\t\t${orderByClause}\n\t\t\t\t\t\t\t${fetchLimit ? sql`LIMIT ${fetchLimit}` : sql``}\n\t\t\t\t\t\t`.execute(db);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// No where clause, use simple query\n\t\t\t\t\tconst orderByClause = buildOrderByClause(orderBy);\n\t\t\t\t\tconst statusCondition = buildStatusCondition(db, status);\n\t\t\t\t\tconst localeFilter = locale ? sql`AND locale = ${locale}` : sql``;\n\t\t\t\t\tconst cursorCond = cursorCondition ? sql`AND ${cursorCondition}` : sql``;\n\t\t\t\t\tresult = await sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\tAND ${statusCondition}\n\t\t\t\t\t\t${localeFilter}\n\t\t\t\t\t\t${cursorCond}\n\t\t\t\t\t\t${orderByClause}\n\t\t\t\t\t\t${fetchLimit ? sql`LIMIT ${fetchLimit}` : sql``}\n\t\t\t\t\t`.execute(db);\n\t\t\t\t}\n\n\t\t\t\t// Detect whether there are more results (over-fetched by 1)\n\t\t\t\tconst hasMore = limit ? result.rows.length > limit : false;\n\t\t\t\tconst rows = hasMore ? result.rows.slice(0, limit) : result.rows;\n\n\t\t\t\t// Map rows to entries\n\t\t\t\tconst i18nConfig = virtualConfig?.i18n;\n\t\t\t\tconst i18nEnabled = i18nConfig && i18nConfig.locales.length > 1;\n\t\t\t\tconst entries = rows.map((row) => {\n\t\t\t\t\tconst slug = rowStr(row, \"slug\") || rowStr(row, \"id\");\n\t\t\t\t\tconst rowLocale = rowStr(row, \"locale\");\n\t\t\t\t\tconst shouldPrefix =\n\t\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\t\trowLocale !== \"\" &&\n\t\t\t\t\t\t(rowLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\t\tconst id = shouldPrefix ? `${rowLocale}/${slug}` : slug;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tslug: rowStr(row, \"slug\"),\n\t\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\t\tdata: mapRowToData(row),\n\t\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\t\t// Encode nextCursor from the last row if there are more results\n\t\t\t\tlet nextCursor: string | undefined;\n\t\t\t\tif (hasMore && rows.length > 0) {\n\t\t\t\t\tconst lastRow = rows.at(-1)!;\n\t\t\t\t\tconst primary = getPrimarySort(orderBy);\n\t\t\t\t\t// Strip table prefix from field name for row lookup\n\t\t\t\t\tconst fieldName = primary.field.includes(\".\")\n\t\t\t\t\t\t? primary.field.split(\".\").pop()!\n\t\t\t\t\t\t: primary.field;\n\t\t\t\t\tconst lastOrderValue = lastRow[fieldName];\n\t\t\t\t\tconst orderStr =\n\t\t\t\t\t\ttypeof lastOrderValue === \"string\" || typeof lastOrderValue === \"number\"\n\t\t\t\t\t\t\t? String(lastOrderValue)\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\tnextCursor = encodeCursor(orderStr, String(lastRow.id));\n\t\t\t\t}\n\n\t\t\t\t// Collection-level cache hint uses the most recent updated_at\n\t\t\t\tlet collectionLastModified: Date | undefined;\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (row.updated_at) {\n\t\t\t\t\t\tconst d = new Date(rowStr(row, \"updated_at\"));\n\t\t\t\t\t\tif (!collectionLastModified || d > collectionLastModified) {\n\t\t\t\t\t\t\tcollectionLastModified = d;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tentries,\n\t\t\t\t\tnextCursor,\n\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\ttags: [type],\n\t\t\t\t\t\tlastModified: collectionLastModified,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\t// Handle missing table gracefully - return empty collection.\n\t\t\t\t// This happens before migrations have run.\n\t\t\t\tif (isMissingTableError(error)) {\n\t\t\t\t\treturn { entries: [] };\n\t\t\t\t}\n\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\treturn {\n\t\t\t\t\terror: new Error(`Failed to load collection: ${message}`),\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Load a single entry by type and ID/slug\n\t\t *\n\t\t * When filter.revisionId is set (preview mode), the entry's data\n\t\t * comes from the revisions table instead of the content table columns.\n\t\t */\n\t\tasync loadEntry({ filter }) {\n\t\t\ttry {\n\t\t\t\t// Get DB instance\n\t\t\t\tconst db = await getDb();\n\n\t\t\t\t// Both type and id are required\n\t\t\t\tconst type = filter?.type;\n\t\t\t\tconst id = filter?.id;\n\n\t\t\t\tif (!type || !id) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\"type and id filters are required. Use getEmDashEntry() instead of getLiveEntry() directly.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Query the per-collection table\n\t\t\t\tconst tableName = getTableName(type);\n\t\t\t\tconst locale = filter?.locale;\n\n\t\t\t\t// Use raw SQL for dynamic table name, match by slug or id\n\t\t\t\t// When locale is specified, prefer locale-scoped slug match,\n\t\t\t\t// but IDs are globally unique so always check id without locale scope\n\t\t\t\tconst result = locale\n\t\t\t\t\t? await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\t\tAND ((slug = ${id} AND locale = ${locale}) OR id = ${id})\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`.execute(db)\n\t\t\t\t\t: await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT * FROM ${sql.ref(tableName)}\n\t\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\t\tAND (slug = ${id} OR id = ${id})\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`.execute(db);\n\n\t\t\t\tconst row = result.rows[0];\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst i18nConfig = virtualConfig?.i18n;\n\t\t\t\tconst i18nEnabled = i18nConfig && i18nConfig.locales.length > 1;\n\t\t\t\tconst entrySlug = rowStr(row, \"slug\") || rowStr(row, \"id\");\n\t\t\t\tconst entryLocale = rowStr(row, \"locale\");\n\t\t\t\tconst shouldPrefixEntry =\n\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\tentryLocale !== \"\" &&\n\t\t\t\t\t(entryLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\tconst entryId = shouldPrefixEntry ? `${entryLocale}/${entrySlug}` : entrySlug;\n\n\t\t\t\t// Preview mode: override content fields with revision data,\n\t\t\t\t// keeping system metadata from the content table row.\n\t\t\t\tconst revisionId = filter?.revisionId;\n\t\t\t\tif (revisionId) {\n\t\t\t\t\tconst revRow = await sql<{ data: string }>`\n\t\t\t\t\t\tSELECT data FROM revisions\n\t\t\t\t\t\tWHERE id = ${revisionId}\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t`.execute(db);\n\n\t\t\t\t\tconst revData = revRow.rows[0];\n\t\t\t\t\tif (revData) {\n\t\t\t\t\t\tconst parsed: Record<string, unknown> = JSON.parse(revData.data);\n\t\t\t\t\t\t// System metadata from content table + content fields from revision\n\t\t\t\t\t\tconst systemData: Record<string, unknown> = {};\n\t\t\t\t\t\tfor (const [key, mappedKey] of Object.entries(INCLUDE_IN_DATA)) {\n\t\t\t\t\t\t\tif (key in row) {\n\t\t\t\t\t\t\t\tif (DATE_COLUMNS.has(key)) {\n\t\t\t\t\t\t\t\t\tsystemData[mappedKey] = typeof row[key] === \"string\" ? new Date(row[key]) : null;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tsystemData[mappedKey] = row[key];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Use slug from revision metadata if present, else from content table\n\t\t\t\t\t\tconst slug = typeof parsed._slug === \"string\" ? parsed._slug : rowStr(row, \"slug\");\n\t\t\t\t\t\tconst revSlug = slug || rowStr(row, \"id\");\n\t\t\t\t\t\tconst revLocale = rowStr(row, \"locale\");\n\t\t\t\t\t\tconst shouldPrefixRev =\n\t\t\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\t\t\trevLocale !== \"\" &&\n\t\t\t\t\t\t\t(revLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\t\t\tconst revId = shouldPrefixRev ? `${revLocale}/${revSlug}` : revSlug;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tid: revId,\n\t\t\t\t\t\t\tslug,\n\t\t\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\t\t\tdata: { ...systemData, slug, ...mapRevisionData(parsed) },\n\t\t\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\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\treturn {\n\t\t\t\t\tid: entryId,\n\t\t\t\t\tslug: rowStr(row, \"slug\"),\n\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\tdata: mapRowToData(row),\n\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\t// Handle missing table gracefully - return undefined (not found).\n\t\t\t\t// This happens before migrations have run.\n\t\t\t\tif (isMissingTableError(error)) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\treturn {\n\t\t\t\t\terror: new Error(`Failed to load entry: ${message}`),\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,MAAM,qBAAqB;;;;;;;;AAS3B,MAAM,iBAAiB,IAAI,IAAI;CAC9B;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,CAAC;;;;AAKF,SAAS,aAAa,MAAsB;AAC3C,oBAAmB,MAAM,kBAAkB;AAC3C,QAAO,MAAM;;;;;;;AAQd,IAAI,gBAAoC;;;;;;;AAQxC,eAAe,iBAAiB,IAA4C;CAC3E,MAAM,gBAAgB,mBAAmB,EAAE,iBAAiB;AAE5D,KAAI,CAAC,iBAAiB,cACrB,QAAO;AAGR,KAAI;EACH,MAAM,OAAO,MAAM,GAAG,WAAW,wBAAwB,CAAC,OAAO,OAAO,CAAC,SAAS;EAClF,MAAM,QAAQ,IAAI,IAAI,KAAK,KAAK,MAAM,EAAE,KAAK,CAAC;AAC9C,MAAI,CAAC,cACJ,iBAAgB;AAEjB,SAAO;SACA;EAEP,MAAM,wBAAQ,IAAI,KAAa;AAC/B,MAAI,CAAC,cACJ,iBAAgB;AAEjB,SAAO;;;;;;AAOT,MAAM,kBAA0C;CAC/C,IAAI;CACJ,QAAQ;CACR,WAAW;CACX,mBAAmB;CACnB,YAAY;CACZ,YAAY;CACZ,cAAc;CACd,cAAc;CACd,mBAAmB;CACnB,kBAAkB;CAClB,QAAQ;CACR,mBAAmB;CACnB;;AAGD,MAAM,eAAe,IAAI,IAAI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,OAAO,KAAK,KAAK;MACzC,MAAM,YAAY,OAAO,KAAK,SAAS;AAMvC,aAAO;OACN,IALA,eACA,cAAc,OACb,cAAc,WAAW,iBAAiB,WAAW,uBACvB,GAAG,UAAU,GAAG,YAAY;OAG3D;OACA,QAAQ,OAAO,KAAK,UAAU,QAAQ;OACtC,MAAM;QAAE,GAAG;QAAY;QAAM,GAAG,gBAAgB,OAAO;QAAE;OACzD,WAAW;QACV,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC;QACzB,cAAc,IAAI,aAAa,IAAI,KAAK,OAAO,KAAK,aAAa,CAAC,GAAG;QACrE;OACD;;;AAIH,WAAO;KACN,IAAI;KACJ,MAAM,OAAO,KAAK,OAAO;KACzB,QAAQ,OAAO,KAAK,UAAU,QAAQ;KACtC,MAAM,aAAa,IAAI;KACvB,WAAW;MACV,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC;MACzB,cAAc,IAAI,aAAa,IAAI,KAAK,OAAO,KAAK,aAAa,CAAC,GAAG;MACrE;KACD;YACO,OAAO;AAGf,QAAI,oBAAoB,MAAM,CAC7B;IAGD,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,WAAO,EACN,uBAAO,IAAI,MAAM,yBAAyB,UAAU,EACpD;;;EAGH"}
|
|
@@ -127,6 +127,18 @@ const settingFieldSchema = z.discriminatedUnion("type", [
|
|
|
127
127
|
z.object({
|
|
128
128
|
...baseSettingFields,
|
|
129
129
|
type: z.literal("secret")
|
|
130
|
+
}),
|
|
131
|
+
z.object({
|
|
132
|
+
...baseSettingFields,
|
|
133
|
+
type: z.literal("url"),
|
|
134
|
+
default: z.string().optional(),
|
|
135
|
+
placeholder: z.string().optional()
|
|
136
|
+
}),
|
|
137
|
+
z.object({
|
|
138
|
+
...baseSettingFields,
|
|
139
|
+
type: z.literal("email"),
|
|
140
|
+
default: z.string().optional(),
|
|
141
|
+
placeholder: z.string().optional()
|
|
130
142
|
})
|
|
131
143
|
]);
|
|
132
144
|
const adminPageSchema = z.object({
|
|
@@ -184,4 +196,4 @@ function normalizeManifestRoute(entry) {
|
|
|
184
196
|
|
|
185
197
|
//#endregion
|
|
186
198
|
export { pluginManifestSchema as i, PLUGIN_CAPABILITIES as n, normalizeManifestRoute as r, HOOK_NAMES as t };
|
|
187
|
-
//# sourceMappingURL=manifest-schema-
|
|
199
|
+
//# sourceMappingURL=manifest-schema-DH9xhc6t.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manifest-schema-DH9xhc6t.mjs","names":[],"sources":["../src/plugins/manifest-schema.ts"],"sourcesContent":["/**\n * Zod schema for PluginManifest validation\n *\n * Used to validate manifest.json from plugin bundles at every parse site:\n * - Client-side download (marketplace.ts extractBundle)\n * - R2 load (api/handlers/marketplace.ts loadBundleFromR2)\n * - CLI publish preview (cli/commands/publish.ts readManifestFromTarball)\n * - Marketplace ingest extends this with publishing-specific fields\n */\n\nimport { z } from \"zod\";\n\n// ── Enum values (must stay in sync with types.ts) ───────────────\n\nexport const PLUGIN_CAPABILITIES = [\n\t\"network:fetch\",\n\t\"network:fetch:any\",\n\t\"read:content\",\n\t\"write:content\",\n\t\"read:media\",\n\t\"write:media\",\n\t\"read:users\",\n\t\"email:send\",\n\t\"email:provide\",\n\t\"email:intercept\",\n\t\"page:inject\",\n] as const;\n\n/** Must stay in sync with FieldType in schema/types.ts */\nconst FIELD_TYPES = [\n\t\"string\",\n\t\"text\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"datetime\",\n\t\"select\",\n\t\"multiSelect\",\n\t\"portableText\",\n\t\"image\",\n\t\"file\",\n\t\"reference\",\n\t\"json\",\n\t\"slug\",\n\t\"repeater\",\n] as const;\n\nexport const HOOK_NAMES = [\n\t\"plugin:install\",\n\t\"plugin:activate\",\n\t\"plugin:deactivate\",\n\t\"plugin:uninstall\",\n\t\"content:beforeSave\",\n\t\"content:afterSave\",\n\t\"content:beforeDelete\",\n\t\"content:afterDelete\",\n\t\"content:afterPublish\",\n\t\"content:afterUnpublish\",\n\t\"media:beforeUpload\",\n\t\"media:afterUpload\",\n\t\"cron\",\n\t\"email:beforeSend\",\n\t\"email:deliver\",\n\t\"email:afterSend\",\n\t\"comment:beforeCreate\",\n\t\"comment:moderate\",\n\t\"comment:afterCreate\",\n\t\"comment:afterModerate\",\n\t\"page:metadata\",\n\t\"page:fragments\",\n] as const;\n\n/**\n * Structured hook entry for manifest — name plus optional metadata.\n * During a transition period, both plain strings and objects are accepted.\n */\nconst manifestHookEntrySchema = z.object({\n\tname: z.enum(HOOK_NAMES),\n\texclusive: z.boolean().optional(),\n\tpriority: z.number().int().optional(),\n\ttimeout: z.number().int().positive().optional(),\n});\n\n/**\n * Structured route entry for manifest — name plus optional metadata.\n * Both plain strings and objects are accepted; strings are normalized\n * to `{ name }` objects via `normalizeManifestRoute()`.\n */\n/** Route names must be safe path segments — alphanumeric, hyphens, underscores, forward slashes */\nconst routeNamePattern = /^[a-zA-Z0-9][a-zA-Z0-9_\\-/]*$/;\n\nconst manifestRouteEntrySchema = z.object({\n\tname: z.string().min(1).regex(routeNamePattern, \"Route name must be a safe path segment\"),\n\tpublic: z.boolean().optional(),\n});\n\n// ── Sub-schemas ─────────────────────────────────────────────────\n\n/** Index field names must be valid identifiers to prevent SQL injection via JSON path expressions */\nconst indexFieldName = z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/);\n\nconst storageCollectionSchema = z.object({\n\tindexes: z.array(z.union([indexFieldName, z.array(indexFieldName)])),\n\tuniqueIndexes: z.array(z.union([indexFieldName, z.array(indexFieldName)])).optional(),\n});\n\nconst baseSettingFields = {\n\tlabel: z.string(),\n\tdescription: z.string().optional(),\n};\n\nconst settingFieldSchema = z.discriminatedUnion(\"type\", [\n\tz.object({\n\t\t...baseSettingFields,\n\t\ttype: z.literal(\"string\"),\n\t\tdefault: z.string().optional(),\n\t\tmultiline: z.boolean().optional(),\n\t}),\n\tz.object({\n\t\t...baseSettingFields,\n\t\ttype: z.literal(\"number\"),\n\t\tdefault: z.number().optional(),\n\t\tmin: z.number().optional(),\n\t\tmax: z.number().optional(),\n\t}),\n\tz.object({ ...baseSettingFields, type: z.literal(\"boolean\"), default: z.boolean().optional() }),\n\tz.object({\n\t\t...baseSettingFields,\n\t\ttype: z.literal(\"select\"),\n\t\toptions: z.array(z.object({ value: z.string(), label: z.string() })),\n\t\tdefault: z.string().optional(),\n\t}),\n\tz.object({ ...baseSettingFields, type: z.literal(\"secret\") }),\n\tz.object({\n\t\t...baseSettingFields,\n\t\ttype: z.literal(\"url\"),\n\t\tdefault: z.string().optional(),\n\t\tplaceholder: z.string().optional(),\n\t}),\n\tz.object({\n\t\t...baseSettingFields,\n\t\ttype: z.literal(\"email\"),\n\t\tdefault: z.string().optional(),\n\t\tplaceholder: z.string().optional(),\n\t}),\n]);\n\nconst adminPageSchema = z.object({\n\tpath: z.string(),\n\tlabel: z.string(),\n\ticon: z.string().optional(),\n});\n\nconst dashboardWidgetSchema = z.object({\n\tid: z.string(),\n\tsize: z.enum([\"full\", \"half\", \"third\"]).optional(),\n\ttitle: z.string().optional(),\n});\n\nconst pluginAdminConfigSchema = z.object({\n\tentry: z.string().optional(),\n\tsettingsSchema: z.record(z.string(), settingFieldSchema).optional(),\n\tpages: z.array(adminPageSchema).optional(),\n\twidgets: z.array(dashboardWidgetSchema).optional(),\n\tfieldWidgets: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: z.string().min(1),\n\t\t\t\tlabel: z.string().min(1),\n\t\t\t\tfieldTypes: z.array(z.enum(FIELD_TYPES)),\n\t\t\t\telements: z\n\t\t\t\t\t.array(\n\t\t\t\t\t\tz\n\t\t\t\t\t\t\t.object({\n\t\t\t\t\t\t\t\ttype: z.string(),\n\t\t\t\t\t\t\t\taction_id: z.string(),\n\t\t\t\t\t\t\t\tlabel: z.string().optional(),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.passthrough(),\n\t\t\t\t\t)\n\t\t\t\t\t.optional(),\n\t\t\t}),\n\t\t)\n\t\t.optional(),\n});\n\n// ── Main schema ─────────────────────────────────────────────────\n\n/**\n * Zod schema matching the PluginManifest interface from types.ts.\n *\n * Every JSON.parse of a manifest.json should validate through this.\n */\nexport const pluginManifestSchema = z.object({\n\tid: z.string().min(1),\n\tversion: z.string().min(1),\n\tcapabilities: z.array(z.enum(PLUGIN_CAPABILITIES)),\n\tallowedHosts: z.array(z.string()),\n\tstorage: z.record(z.string(), storageCollectionSchema),\n\t/**\n\t * Hook declarations — accepts both plain name strings (legacy) and\n\t * structured objects with exclusive/priority/timeout metadata.\n\t * Plain strings are normalized to `{ name }` objects after parsing.\n\t */\n\thooks: z.array(z.union([z.enum(HOOK_NAMES), manifestHookEntrySchema])),\n\t/**\n\t * Route declarations — accepts both plain name strings and\n\t * structured objects with public metadata.\n\t * Plain strings are normalized to `{ name }` objects after parsing.\n\t */\n\troutes: z.array(\n\t\tz.union([\n\t\t\tz.string().min(1).regex(routeNamePattern, \"Route name must be a safe path segment\"),\n\t\t\tmanifestRouteEntrySchema,\n\t\t]),\n\t),\n\tadmin: pluginAdminConfigSchema,\n});\n\nexport type ValidatedPluginManifest = z.infer<typeof pluginManifestSchema>;\n\n/**\n * Normalize a manifest hook entry — plain strings become `{ name }` objects.\n */\nexport function normalizeManifestHook(\n\tentry: string | { name: string; exclusive?: boolean; priority?: number; timeout?: number },\n): { name: string; exclusive?: boolean; priority?: number; timeout?: number } {\n\tif (typeof entry === \"string\") {\n\t\treturn { name: entry };\n\t}\n\treturn entry;\n}\n\n/**\n * Normalize a manifest route entry — plain strings become `{ name }` objects.\n */\nexport function normalizeManifestRoute(entry: string | { name: string; public?: boolean }): {\n\tname: string;\n\tpublic?: boolean;\n} {\n\tif (typeof entry === \"string\") {\n\t\treturn { name: entry };\n\t}\n\treturn entry;\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAa,sBAAsB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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ponentEmbed, b as mediaItemToValue, c as EmbedResult, d as MediaListResult, f as MediaProvider, g as MediaUploadInput, h as MediaProviderItem, i as AudioEmbed, l as ImageEmbed, m as MediaProviderDescriptor, n as generatePlaceholder, o as CreateMediaProviderFn, p as MediaProviderCapabilities, r as normalizeMediaValue, s as EmbedOptions, t as PlaceholderData, u as MediaListOptions, v as ThumbnailOptions, y as VideoEmbed } from "../placeholder-
|
|
1
|
+
import { _ as MediaValue, a as ComponentEmbed, b as mediaItemToValue, c as EmbedResult, d as MediaListResult, f as MediaProvider, g as MediaUploadInput, h as MediaProviderItem, i as AudioEmbed, l as ImageEmbed, m as MediaProviderDescriptor, n as generatePlaceholder, o as CreateMediaProviderFn, p as MediaProviderCapabilities, r as normalizeMediaValue, s as EmbedOptions, t as PlaceholderData, u as MediaListOptions, v as ThumbnailOptions, y as VideoEmbed } from "../placeholder-D29tWZ7o.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/media/local.d.ts
|
|
4
4
|
interface LocalMediaConfig {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { h as MediaProviderItem, o as CreateMediaProviderFn } from "../placeholder-
|
|
2
|
-
import { t as Database } from "../types-
|
|
3
|
-
import "../index-
|
|
4
|
-
import "../runner-
|
|
5
|
-
import "../types-
|
|
6
|
-
import { d as Storage } from "../types-
|
|
7
|
-
import "../validate-
|
|
1
|
+
import { h as MediaProviderItem, o as CreateMediaProviderFn } from "../placeholder-D29tWZ7o.mjs";
|
|
2
|
+
import { t as Database } from "../types-CS8FIX7L.mjs";
|
|
3
|
+
import "../index-DIb-CzNx.mjs";
|
|
4
|
+
import "../runner-OURCaApa.mjs";
|
|
5
|
+
import "../types-i36XcA_X.mjs";
|
|
6
|
+
import { d as Storage } from "../types-DIMwPFub.mjs";
|
|
7
|
+
import "../validate-DHxmpFJt.mjs";
|
|
8
8
|
import "../index.mjs";
|
|
9
9
|
import { Kysely } from "kysely";
|
|
10
10
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "../base64-MBPo9ozB.mjs";
|
|
2
|
-
import "../types-
|
|
3
|
-
import { t as MediaRepository } from "../media-
|
|
2
|
+
import "../types-BIgulNsW.mjs";
|
|
3
|
+
import { t as MediaRepository } from "../media-D8FbNsl0.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/media/local-runtime.ts
|
|
6
6
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as encodeCursor, r as decodeCursor } from "./types-BIgulNsW.mjs";
|
|
2
2
|
import { sql } from "kysely";
|
|
3
3
|
import { ulid } from "ulidx";
|
|
4
4
|
|
|
@@ -102,11 +102,8 @@ var MediaRepository = class {
|
|
|
102
102
|
const limit = Math.min(options.limit || 50, 100);
|
|
103
103
|
let query = this.db.selectFrom("media").selectAll().orderBy("created_at", "desc").orderBy("id", "desc").limit(limit + 1);
|
|
104
104
|
if (options.cursor) {
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
const { orderValue: createdAt, id: cursorId } = decoded;
|
|
108
|
-
query = query.where((eb) => eb.or([eb("created_at", "<", createdAt), eb.and([eb("created_at", "=", createdAt), eb("id", "<", cursorId)])]));
|
|
109
|
-
}
|
|
105
|
+
const { orderValue: createdAt, id: cursorId } = decodeCursor(options.cursor);
|
|
106
|
+
query = query.where((eb) => eb.or([eb("created_at", "<", createdAt), eb.and([eb("created_at", "=", createdAt), eb("id", "<", cursorId)])]));
|
|
110
107
|
}
|
|
111
108
|
if (options.mimeType) {
|
|
112
109
|
const pattern = `${escapeLike(options.mimeType)}%`;
|
|
@@ -197,4 +194,4 @@ var MediaRepository = class {
|
|
|
197
194
|
|
|
198
195
|
//#endregion
|
|
199
196
|
export { MediaRepository as t };
|
|
200
|
-
//# sourceMappingURL=media-
|
|
197
|
+
//# sourceMappingURL=media-D8FbNsl0.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"media-D8FbNsl0.mjs","names":[],"sources":["../src/database/repositories/media.ts"],"sourcesContent":["import { sql, type Kysely, type SqlBool } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport type { Database, MediaRow } from \"../types.js\";\nimport type { FindManyResult } from \"./types.js\";\nimport { encodeCursor, decodeCursor } from \"./types.js\";\n\n/** Escape LIKE wildcard characters and the escape char itself in user-supplied values */\nfunction escapeLike(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"%\", \"\\\\%\").replaceAll(\"_\", \"\\\\_\");\n}\n\nexport type MediaStatus = \"pending\" | \"ready\" | \"failed\";\n\nexport interface MediaItem {\n\tid: string;\n\tfilename: string;\n\tmimeType: string;\n\tsize: number | null;\n\twidth: number | null;\n\theight: number | null;\n\talt: string | null;\n\tcaption: string | null;\n\tstorageKey: string;\n\tstatus: MediaStatus;\n\tcontentHash: string | null;\n\tblurhash: string | null;\n\tdominantColor: string | null;\n\tcreatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface CreateMediaInput {\n\tfilename: string;\n\tmimeType: string;\n\tsize?: number;\n\twidth?: number;\n\theight?: number;\n\talt?: string;\n\tcaption?: string;\n\tstorageKey: string;\n\tcontentHash?: string;\n\tblurhash?: string;\n\tdominantColor?: string;\n\tstatus?: MediaStatus;\n\tauthorId?: string;\n}\n\nexport interface FindManyMediaOptions {\n\tlimit?: number;\n\tcursor?: string;\n\tmimeType?: string; // Filter by mime type prefix, e.g., \"image/\"\n\tstatus?: MediaStatus | \"all\"; // Filter by status, defaults to \"ready\"\n}\n\n/**\n * Media repository for database operations\n */\nexport class MediaRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new media item\n\t */\n\tasync create(input: CreateMediaInput): Promise<MediaItem> {\n\t\tconst id = ulid();\n\t\tconst now = new Date().toISOString();\n\n\t\tconst row: Omit<MediaRow, \"rowid\"> = {\n\t\t\tid,\n\t\t\tfilename: input.filename,\n\t\t\tmime_type: input.mimeType,\n\t\t\tsize: input.size ?? null,\n\t\t\twidth: input.width ?? null,\n\t\t\theight: input.height ?? null,\n\t\t\talt: input.alt ?? null,\n\t\t\tcaption: input.caption ?? null,\n\t\t\tstorage_key: input.storageKey,\n\t\t\tcontent_hash: input.contentHash ?? null,\n\t\t\tblurhash: input.blurhash ?? null,\n\t\t\tdominant_color: input.dominantColor ?? null,\n\t\t\tstatus: input.status ?? \"ready\",\n\t\t\tcreated_at: now,\n\t\t\tauthor_id: input.authorId ?? null,\n\t\t};\n\n\t\tawait this.db.insertInto(\"media\").values(row).execute();\n\n\t\treturn this.rowToItem(row as MediaRow);\n\t}\n\n\t/**\n\t * Create a pending media item (for signed URL upload flow)\n\t */\n\tasync createPending(input: {\n\t\tfilename: string;\n\t\tmimeType: string;\n\t\tsize?: number;\n\t\tstorageKey: string;\n\t\tcontentHash?: string;\n\t\tauthorId?: string;\n\t}): Promise<MediaItem> {\n\t\treturn this.create({\n\t\t\t...input,\n\t\t\tstatus: \"pending\",\n\t\t});\n\t}\n\n\t/**\n\t * Confirm upload (mark as ready)\n\t */\n\tasync confirmUpload(\n\t\tid: string,\n\t\tmetadata?: { width?: number; height?: number; size?: number },\n\t): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst updates: Partial<MediaRow> = {\n\t\t\tstatus: \"ready\",\n\t\t};\n\t\tif (metadata?.width !== undefined) updates.width = metadata.width;\n\t\tif (metadata?.height !== undefined) updates.height = metadata.height;\n\t\tif (metadata?.size !== undefined) updates.size = metadata.size;\n\n\t\tawait this.db.updateTable(\"media\").set(updates).where(\"id\", \"=\", id).execute();\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Mark upload as failed\n\t */\n\tasync markFailed(id: string): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tawait this.db.updateTable(\"media\").set({ status: \"failed\" }).where(\"id\", \"=\", id).execute();\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Find media by ID\n\t */\n\tasync findById(id: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find media by filename\n\t * Useful for idempotent imports\n\t */\n\tasync findByFilename(filename: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"filename\", \"=\", filename)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find media by content hash\n\t * Used for deduplication - same content = same hash\n\t */\n\tasync findByContentHash(contentHash: string): Promise<MediaItem | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.selectAll()\n\t\t\t.where(\"content_hash\", \"=\", contentHash)\n\t\t\t.where(\"status\", \"=\", \"ready\")\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToItem(row) : null;\n\t}\n\n\t/**\n\t * Find many media items with cursor pagination\n\t *\n\t * Uses keyset pagination (cursor-based) for consistent results.\n\t * The cursor encodes the created_at and id of the last item.\n\t */\n\tasync findMany(options: FindManyMediaOptions = {}): Promise<FindManyResult<MediaItem>> {\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"media\")\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\t// Handle cursor-based pagination — throws on invalid cursor.\n\t\tif (options.cursor) {\n\t\t\tconst { orderValue: createdAt, id: cursorId } = decodeCursor(options.cursor);\n\n\t\t\t// Keyset pagination: get items where (created_at, id) < cursor\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"created_at\", \"<\", createdAt),\n\t\t\t\t\teb.and([eb(\"created_at\", \"=\", createdAt), eb(\"id\", \"<\", cursorId)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tif (options.mimeType) {\n\t\t\tconst pattern = `${escapeLike(options.mimeType)}%`;\n\t\t\tquery = query.where(sql<SqlBool>`mime_type LIKE ${pattern} ESCAPE '\\\\'`);\n\t\t}\n\n\t\t// Default to only showing ready items\n\t\tif (options.status !== \"all\") {\n\t\t\tquery = query.where(\"status\", \"=\", options.status ?? \"ready\");\n\t\t}\n\n\t\tconst rows = await query.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToItem(row));\n\n\t\tlet nextCursor: string | undefined;\n\t\tif (hasMore && items.length > 0) {\n\t\t\tconst lastItem = items.at(-1)!;\n\t\t\tnextCursor = encodeCursor(lastItem.createdAt, lastItem.id);\n\t\t}\n\n\t\treturn { items, nextCursor };\n\t}\n\n\t/**\n\t * Update media metadata\n\t */\n\tasync update(\n\t\tid: string,\n\t\tinput: Partial<Pick<CreateMediaInput, \"alt\" | \"caption\" | \"width\" | \"height\">>,\n\t): Promise<MediaItem | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst updates: Partial<MediaRow> = {};\n\t\tif (input.alt !== undefined) updates.alt = input.alt;\n\t\tif (input.caption !== undefined) updates.caption = input.caption;\n\t\tif (input.width !== undefined) updates.width = input.width;\n\t\tif (input.height !== undefined) updates.height = input.height;\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"media\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Delete media item\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db.deleteFrom(\"media\").where(\"id\", \"=\", id).executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Count media items\n\t */\n\tasync count(mimeType?: string): Promise<number> {\n\t\tlet query = this.db.selectFrom(\"media\").select((eb) => eb.fn.count(\"id\").as(\"count\"));\n\n\t\tif (mimeType) {\n\t\t\tconst pattern = `${escapeLike(mimeType)}%`;\n\t\t\tquery = query.where(sql<SqlBool>`mime_type LIKE ${pattern} ESCAPE '\\\\'`);\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count || 0);\n\t}\n\n\t/**\n\t * Delete pending uploads older than the given age.\n\t * Pending uploads that were never confirmed indicate abandoned upload flows.\n\t *\n\t * Returns the storage keys of deleted rows so callers can remove the\n\t * corresponding files from object storage.\n\t */\n\tasync cleanupPendingUploads(maxAgeMs: number = 60 * 60 * 1000): Promise<string[]> {\n\t\tconst cutoff = new Date(Date.now() - maxAgeMs).toISOString();\n\n\t\t// Select the storage keys first -- SQLite doesn't support RETURNING\n\t\t// on DELETE in all drivers, and Kysely's RETURNING isn't universal.\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"media\")\n\t\t\t.select(\"storage_key\")\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.execute();\n\n\t\tif (rows.length === 0) return [];\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"media\")\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.where(\"created_at\", \"<\", cutoff)\n\t\t\t.execute();\n\n\t\treturn rows.map((r) => r.storage_key);\n\t}\n\n\t/**\n\t * Convert database row to MediaItem\n\t */\n\tprivate rowToItem(row: MediaRow): MediaItem {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tfilename: row.filename,\n\t\t\tmimeType: row.mime_type,\n\t\t\tsize: row.size,\n\t\t\twidth: row.width,\n\t\t\theight: row.height,\n\t\t\talt: row.alt,\n\t\t\tcaption: row.caption,\n\t\t\tstorageKey: row.storage_key,\n\t\t\tcontentHash: row.content_hash,\n\t\t\tblurhash: row.blurhash,\n\t\t\tdominantColor: row.dominant_color,\n\t\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- DB stores string; validated at insert but linter can't follow\n\t\t\tstatus: row.status as MediaStatus,\n\t\t\tcreatedAt: row.created_at,\n\t\t\tauthorId: row.author_id,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;AAQA,SAAS,WAAW,OAAuB;AAC1C,QAAO,MAAM,WAAW,MAAM,OAAO,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW,KAAK,MAAM;;;;;AAiDpF,IAAa,kBAAb,MAA6B;CAC5B,YAAY,AAAQ,IAAsB;EAAtB;;;;;CAKpB,MAAM,OAAO,OAA6C;EACzD,MAAM,KAAK,MAAM;EACjB,MAAM,uBAAM,IAAI,MAAM,EAAC,aAAa;EAEpC,MAAM,MAA+B;GACpC;GACA,UAAU,MAAM;GAChB,WAAW,MAAM;GACjB,MAAM,MAAM,QAAQ;GACpB,OAAO,MAAM,SAAS;GACtB,QAAQ,MAAM,UAAU;GACxB,KAAK,MAAM,OAAO;GAClB,SAAS,MAAM,WAAW;GAC1B,aAAa,MAAM;GACnB,cAAc,MAAM,eAAe;GACnC,UAAU,MAAM,YAAY;GAC5B,gBAAgB,MAAM,iBAAiB;GACvC,QAAQ,MAAM,UAAU;GACxB,YAAY;GACZ,WAAW,MAAM,YAAY;GAC7B;AAED,QAAM,KAAK,GAAG,WAAW,QAAQ,CAAC,OAAO,IAAI,CAAC,SAAS;AAEvD,SAAO,KAAK,UAAU,IAAgB;;;;;CAMvC,MAAM,cAAc,OAOG;AACtB,SAAO,KAAK,OAAO;GAClB,GAAG;GACH,QAAQ;GACR,CAAC;;;;;CAMH,MAAM,cACL,IACA,UAC4B;AAE5B,MAAI,CADa,MAAM,KAAK,SAAS,GAAG,CAEvC,QAAO;EAGR,MAAM,UAA6B,EAClC,QAAQ,SACR;AACD,M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GACZ,KAAK,IAAI;GACT,SAAS,IAAI;GACb,YAAY,IAAI;GAChB,aAAa,IAAI;GACjB,UAAU,IAAI;GACd,eAAe,IAAI;GAEnB,QAAQ,IAAI;GACZ,WAAW,IAAI;GACf,UAAU,IAAI;GACd"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mode-BnAOqItE.mjs","names":[],"sources":["../src/auth/mode.ts"],"sourcesContent":["/**\n * Auth Mode Detection\n *\n * Determines which authentication provider is active based on config.\n * Supports both passkey (default) and external auth providers via AuthDescriptor.\n */\n\nimport type { EmDashConfig } from \"../astro/integration/runtime.js\";\nimport type {\n\tAuthDescriptor,\n\tAuthProviderDescriptor,\n\tAuthRouteDescriptor,\n\tAuthResult,\n\tExternalAuthConfig,\n} from \"./types.js\";\n\nexport type {\n\tAuthDescriptor,\n\tAuthProviderDescriptor,\n\tAuthRouteDescriptor,\n\tAuthResult,\n\tExternalAuthConfig,\n};\n\n/**\n * Passkey auth mode (default)\n */\nexport interface PasskeyAuthMode {\n\ttype: \"passkey\";\n}\n\n/**\n * External auth provider mode (Cloudflare Access, etc.)\n */\nexport interface ExternalAuthMode {\n\ttype: \"external\";\n\t/** Provider type identifier (e.g., \"cloudflare-access\") */\n\tproviderType: string;\n\t/** Module to import for authentication */\n\tentrypoint: string;\n\t/** Provider-specific configuration */\n\tconfig: unknown;\n}\n\n/**\n * Union of all auth modes\n */\nexport type AuthMode = PasskeyAuthMode | ExternalAuthMode;\n\n/**\n * Extended config type with auth.\n *\n * This is the same as `EmDashConfig` with an optional `auth` field.\n * Kept for backwards compatibility — prefer `EmDashConfig` in new code\n * since `getAuthMode` now accepts `EmDashConfig` directly.\n */\nexport interface EmDashConfigWithAuth extends EmDashConfig {\n\tauth?: AuthDescriptor;\n}\n\n/**\n * Determine the active auth mode from config.\n *\n * Accepts `EmDashConfig` (or subtype) — checks for `auth` field via duck typing.\n *\n * @param config EmDash configuration\n * @returns The active auth mode\n */\nexport function getAuthMode(\n\tconfig: (EmDashConfig & { auth?: AuthDescriptor }) | null | undefined,\n): AuthMode {\n\tconst auth = config?.auth;\n\n\t// Check for AuthDescriptor (transparent external auth like Cloudflare Access)\n\tif (auth && \"entrypoint\" in auth && auth.entrypoint) {\n\t\treturn {\n\t\t\ttype: \"external\",\n\t\t\tproviderType: auth.type,\n\t\t\tentrypoint: auth.entrypoint,\n\t\t\tconfig: auth.config,\n\t\t};\n\t}\n\n\t// Default to passkey\n\treturn { type: \"passkey\" };\n}\n\n/**\n * Check if an external auth provider is active\n */\nexport function isExternalAuthEnabled(\n\tconfig: (EmDashConfig & { auth?: AuthDescriptor }) | null | undefined,\n): boolean {\n\treturn getAuthMode(config).type === \"external\";\n}\n\n/**\n * Get external auth config if enabled\n */\nexport function getExternalAuthConfig(\n\tconfig: (EmDashConfig & { auth?: AuthDescriptor }) | null | undefined,\n): ExternalAuthMode | null {\n\tconst mode = getAuthMode(config);\n\tif (mode.type === \"external\") {\n\t\treturn mode;\n\t}\n\treturn null;\n}\n"],"mappings":";;;;;;;;;AAoEA,SAAgB,YACf,QACW;CACX,MAAM,OAAO,QAAQ;AAGrB,KAAI,QAAQ,gBAAgB,QAAQ,KAAK,WACxC,QAAO;EACN,MAAM;EACN,cAAc,KAAK;EACnB,YAAY,KAAK;EACjB,QAAQ,KAAK;EACb;AAIF,QAAO,EAAE,MAAM,WAAW"}
|
package/dist/page/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as PageMetadataContribution, D as PageFragmentContribution, N as PageMetadataLinkRel, P as PagePlacement, q as PublicPageContext, t as BreadcrumbItem } from "../types-
|
|
2
|
-
import { n as SeoSettings } from "../types-
|
|
1
|
+
import { A as PageMetadataContribution, D as PageFragmentContribution, N as PageMetadataLinkRel, P as PagePlacement, q as PublicPageContext, t as BreadcrumbItem } from "../types-i36XcA_X.mjs";
|
|
2
|
+
import { n as SeoSettings } from "../types-BmPPSUEx.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/page/context.d.ts
|
|
5
5
|
/** Fields shared by both input forms */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"placeholder-C-fk5hYI.mjs","names":[],"sources":["../src/media/normalize.ts","../src/media/placeholder.ts"],"sourcesContent":["/**\n * Media Value Normalization\n *\n * Normalizes media field values into a consistent shape regardless of\n * creation path (seed scripts, media picker, WP import, URL input).\n *\n * Called at content create/update time when a media provider is available,\n * filling in missing dimensions, storageKey, mimeType, and filename from\n * the provider's `get()` method.\n */\n\nimport type { MediaProvider, MediaProviderItem, MediaValue } from \"./types.js\";\n\nconst INTERNAL_MEDIA_PREFIX = \"/_emdash/api/media/file/\";\nconst URL_PATTERN = /^https?:\\/\\//;\n\n/**\n * Normalize a media field value into a consistent MediaValue shape.\n *\n * - `null`/`undefined` → `null`\n * - Bare URL string → `{ provider: \"external\", id: \"\", src: url }`\n * - Bare internal media URL → resolved via local provider's `get()`\n * - Object with `provider` + `id` → enriched with missing fields from provider\n */\nexport async function normalizeMediaValue(\n\tvalue: unknown,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue | null> {\n\tif (value == null) return null;\n\n\t// Bare string URL\n\tif (typeof value === \"string\") {\n\t\treturn normalizeStringUrl(value, getProvider);\n\t}\n\n\t// Not an object — can't normalize\n\tif (!isRecord(value)) return null;\n\n\t// Must have at least an id to be a valid media value\n\tif (!(\"id\" in value) && !(\"src\" in value)) return null;\n\n\tconst provider = (typeof value.provider === \"string\" ? value.provider : undefined) || \"local\";\n\tconst id = typeof value.id === \"string\" ? value.id : \"\";\n\n\t// External URLs — return as-is, no server-side dimension detection\n\tif (provider === \"external\") {\n\t\treturn recordToMediaValue(value);\n\t}\n\n\t// Build the base value from the input\n\tconst result: MediaValue = { ...recordToMediaValue(value), provider };\n\n\t// For local media, strip `src` — it's derived at display time from storageKey\n\tif (provider === \"local\") {\n\t\tdelete result.src;\n\t}\n\n\t// Determine if we need to call the provider\n\tconst needsDimensions = result.width == null || result.height == null;\n\tconst needsStorageKey = provider === \"local\" && !result.meta?.storageKey;\n\tconst needsFileInfo = !result.mimeType || !result.filename;\n\tconst needsLookup = needsDimensions || needsStorageKey || needsFileInfo;\n\n\tif (!needsLookup || !id) return result;\n\n\t// Try to enrich from provider\n\tconst mediaProvider = getProvider(provider);\n\tif (!mediaProvider?.get) return result;\n\n\tlet providerItem: MediaProviderItem | null;\n\ttry {\n\t\tproviderItem = await mediaProvider.get(id);\n\t} catch {\n\t\treturn result;\n\t}\n\n\tif (!providerItem) return result;\n\n\treturn mergeProviderData(result, providerItem);\n}\n\nfunction normalizeStringUrl(\n\turl: string,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue | null> {\n\t// Internal media URL — try to resolve via local provider\n\tif (url.startsWith(INTERNAL_MEDIA_PREFIX)) {\n\t\treturn resolveInternalUrl(url, getProvider);\n\t}\n\n\t// External HTTP(S) URL\n\tif (URL_PATTERN.test(url)) {\n\t\treturn Promise.resolve({\n\t\t\tprovider: \"external\",\n\t\t\tid: \"\",\n\t\t\tsrc: url,\n\t\t});\n\t}\n\n\t// Unrecognized string — treat as external\n\treturn Promise.resolve({\n\t\tprovider: \"external\",\n\t\tid: \"\",\n\t\tsrc: url,\n\t});\n}\n\nasync function resolveInternalUrl(\n\turl: string,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue> {\n\tconst storageKey = url.slice(INTERNAL_MEDIA_PREFIX.length);\n\tconst localProvider = getProvider(\"local\");\n\n\tif (!localProvider?.get) {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\tlet item: MediaProviderItem | null;\n\ttry {\n\t\titem = await localProvider.get(storageKey);\n\t} catch {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\tif (!item) {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\treturn {\n\t\tprovider: \"local\",\n\t\tid: item.id,\n\t\tfilename: item.filename,\n\t\tmimeType: item.mimeType,\n\t\twidth: item.width,\n\t\theight: item.height,\n\t\talt: item.alt,\n\t\tmeta: item.meta,\n\t};\n}\n\n/**\n * Merge provider data into an existing MediaValue, preserving caller-supplied fields.\n * Caller `alt` takes priority over provider `alt` (per-usage, not per-image).\n */\nfunction mergeProviderData(existing: MediaValue, item: MediaProviderItem): MediaValue {\n\tconst result = { ...existing };\n\n\t// Fill missing dimensions\n\tif (result.width == null && item.width != null) result.width = item.width;\n\tif (result.height == null && item.height != null) result.height = item.height;\n\n\t// Fill missing file info\n\tif (!result.filename && item.filename) result.filename = item.filename;\n\tif (!result.mimeType && item.mimeType) result.mimeType = item.mimeType;\n\n\t// Fill missing alt (provider alt is fallback, not override)\n\tif (!result.alt && item.alt) result.alt = item.alt;\n\n\t// Fill missing meta (merge, don't replace)\n\tif (item.meta) {\n\t\tresult.meta = { ...item.meta, ...result.meta };\n\t}\n\n\treturn result;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Extract known MediaValue fields from a runtime-checked record.\n * Avoids unsafe `as MediaValue` cast by reading each property explicitly.\n */\nfunction recordToMediaValue(obj: Record<string, unknown>): MediaValue {\n\tconst result: MediaValue = {\n\t\tid: typeof obj.id === \"string\" ? obj.id : \"\",\n\t};\n\tif (typeof obj.provider === \"string\") result.provider = obj.provider;\n\tif (typeof obj.src === \"string\") result.src = obj.src;\n\tif (typeof obj.previewUrl === \"string\") result.previewUrl = obj.previewUrl;\n\tif (typeof obj.filename === \"string\") result.filename = obj.filename;\n\tif (typeof obj.mimeType === \"string\") result.mimeType = obj.mimeType;\n\tif (typeof obj.width === \"number\") result.width = obj.width;\n\tif (typeof obj.height === \"number\") result.height = obj.height;\n\tif (typeof obj.alt === \"string\") result.alt = obj.alt;\n\tif (isRecord(obj.meta)) result.meta = obj.meta;\n\treturn result;\n}\n","/**\n * Image Placeholder Generation\n *\n * Generates blurhash and dominant color from image buffers for LQIP support.\n * Decodes images via jpeg-js (pure JS) and upng-js (pure JS, uses pako for\n * deflate). No Node-specific dependencies — works in Workers and Node SSR.\n */\n\nimport { encode } from \"blurhash\";\nimport { imageSize } from \"image-size\";\n\nexport interface PlaceholderData {\n\tblurhash: string;\n\tdominantColor: string;\n}\n\nconst SUPPORTED_TYPES: Record<string, \"jpeg\" | \"png\"> = {\n\t\"image/jpeg\": \"jpeg\",\n\t\"image/jpg\": \"jpeg\",\n\t\"image/png\": \"png\",\n};\n\n/** Max width for blurhash input. Encode is O(w*h*components), so downsample first. */\nconst MAX_ENCODE_WIDTH = 32;\n\n/** Max decoded RGBA size (32 MB). Images exceeding this skip placeholder generation. */\nconst MAX_DECODED_BYTES = 32 * 1024 * 1024;\n\ninterface DecodedImage {\n\twidth: number;\n\theight: number;\n\tdata: Uint8Array;\n}\n\n/**\n * Decode a JPEG buffer into raw RGBA pixel data.\n */\nasync function decodeJpeg(buffer: Uint8Array): Promise<DecodedImage> {\n\tconst { decode } = await import(\"jpeg-js\");\n\tconst result = decode(buffer, { useTArray: true });\n\treturn { width: result.width, height: result.height, data: result.data };\n}\n\n/**\n * Decode a PNG buffer into raw RGBA pixel data.\n * Uses upng-js (pure JS with pako deflate) — no Node zlib dependency.\n */\nasync function decodePng(buffer: Uint8Array): Promise<DecodedImage> {\n\t// @ts-expect-error -- upng-js has no type declarations\n\tconst UPNG = (await import(\"upng-js\")).default;\n\tconst img = UPNG.decode(buffer.buffer);\n\t// toRGBA8 returns an array of frames; take the first frame\n\tconst frames: ArrayBuffer[] = UPNG.toRGBA8(img);\n\tconst rgba = new Uint8Array(frames[0]);\n\treturn { width: img.width, height: img.height, data: rgba };\n}\n\n/**\n * Extract the dominant color from RGBA pixel data.\n * Simple average of all non-transparent pixels.\n */\nfunction extractDominantColor(data: Uint8Array, width: number, height: number): string {\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tlet count = 0;\n\n\tconst len = width * height * 4;\n\tfor (let i = 0; i < len; i += 4) {\n\t\tconst a = data[i + 3];\n\t\tif (a < 128) continue; // skip mostly-transparent pixels\n\t\tr += data[i];\n\t\tg += data[i + 1];\n\t\tb += data[i + 2];\n\t\tcount++;\n\t}\n\n\tif (count === 0) return \"rgb(0,0,0)\";\n\n\tconst avgR = Math.round(r / count);\n\tconst avgG = Math.round(g / count);\n\tconst avgB = Math.round(b / count);\n\treturn `rgb(${avgR},${avgG},${avgB})`;\n}\n\n/**\n * Read image dimensions from headers without decoding pixel data.\n */\nfunction getImageDimensions(buffer: Uint8Array): { width: number; height: number } | null {\n\ttry {\n\t\tconst result = imageSize(buffer);\n\t\tif (result.width != null && result.height != null) {\n\t\t\treturn { width: result.width, height: result.height };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Generate blurhash and dominant color from an image buffer.\n * Returns null for non-image MIME types or on failure.\n *\n * @param dimensions - Optional pre-known dimensions. Used as a fallback when\n * image-size cannot parse the buffer (e.g. truncated headers). When the\n * decoded size (width * height * 4) exceeds MAX_DECODED_BYTES, placeholder\n * generation is skipped to avoid OOM on memory-constrained runtimes.\n */\nexport async function generatePlaceholder(\n\tbuffer: Uint8Array,\n\tmimeType: string,\n\tdimensions?: { width: number; height: number },\n): Promise<PlaceholderData | null> {\n\tconst format = SUPPORTED_TYPES[mimeType];\n\tif (!format) return null;\n\n\ttry {\n\t\t// Safety net: skip decode if the image would exceed the memory budget\n\t\tconst dims = getImageDimensions(buffer) ?? dimensions;\n\t\tif (dims && dims.width * dims.height * 4 > MAX_DECODED_BYTES) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst imageData = format === \"jpeg\" ? await decodeJpeg(buffer) : await decodePng(buffer);\n\t\tconst { width, height, data } = imageData;\n\n\t\tif (width === 0 || height === 0) return null;\n\n\t\t// Downsample for blurhash encoding if needed\n\t\tlet encodePixels: Uint8ClampedArray;\n\t\tlet encodeWidth: number;\n\t\tlet encodeHeight: number;\n\n\t\tif (width > MAX_ENCODE_WIDTH) {\n\t\t\tconst scale = MAX_ENCODE_WIDTH / width;\n\t\t\tencodeWidth = MAX_ENCODE_WIDTH;\n\t\t\tencodeHeight = Math.max(1, Math.round(height * scale));\n\t\t\tencodePixels = downsample(data, width, height, encodeWidth, encodeHeight);\n\t\t} else {\n\t\t\tencodeWidth = width;\n\t\t\tencodeHeight = height;\n\t\t\tencodePixels = new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength);\n\t\t}\n\n\t\tconst blurhash = encode(encodePixels, encodeWidth, encodeHeight, 4, 3);\n\t\tconst dominantColor = extractDominantColor(data, width, height);\n\n\t\treturn { blurhash, dominantColor };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Nearest-neighbor downsample of RGBA pixel data.\n */\nfunction downsample(\n\tsrc: Uint8Array,\n\tsrcW: number,\n\tsrcH: number,\n\tdstW: number,\n\tdstH: number,\n): Uint8ClampedArray {\n\tconst dst = new Uint8ClampedArray(dstW * dstH * 4);\n\n\tfor (let y = 0; y < dstH; y++) {\n\t\tconst srcY = Math.floor((y * srcH) / dstH);\n\t\tfor (let x = 0; x < dstW; x++) {\n\t\t\tconst srcX = Math.floor((x * srcW) / dstW);\n\t\t\tconst srcIdx = (srcY * srcW + srcX) * 4;\n\t\t\tconst dstIdx = (y * dstW + x) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx]!;\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1]!;\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2]!;\n\t\t\tdst[dstIdx + 3] = src[srcIdx + 3]!;\n\t\t}\n\t}\n\n\treturn dst;\n}\n"],"mappings":";;;;AAaA,MAAM,wBAAwB;AAC9B,MAAM,cAAc;;;;;;;;;AAUpB,eAAsB,oBACrB,OACA,aAC6B;AAC7B,KAAI,SAAS,KAAM,QAAO;AAG1B,KAAI,OAAO,UAAU,SACpB,QAAO,mBAAmB,OAAO,YAAY;AAI9C,KAAI,CAAC,SAAS,MAAM,CAAE,QAAO;AAG7B,KAAI,E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,KAAK;EAC9B,MAAM,OAAO,KAAK,MAAO,IAAI,OAAQ,KAAK;AAC1C,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;GAC9B,MAAM,OAAO,KAAK,MAAO,IAAI,OAAQ,KAAK;GAC1C,MAAM,UAAU,OAAO,OAAO,QAAQ;GACtC,MAAM,UAAU,IAAI,OAAO,KAAK;AAChC,OAAI,UAAU,IAAI;AAClB,OAAI,SAAS,KAAK,IAAI,SAAS;AAC/B,OAAI,SAAS,KAAK,IAAI,SAAS;AAC/B,OAAI,SAAS,KAAK,IAAI,SAAS;;;AAIjC,QAAO"}
|
|
1
|
+
{"version":3,"file":"placeholder-C-fk5hYI.mjs","names":[],"sources":["../src/media/normalize.ts","../src/media/placeholder.ts"],"sourcesContent":["/**\n * Media Value Normalization\n *\n * Normalizes media field values into a consistent shape regardless of\n * creation path (seed scripts, media picker, WP import, URL input).\n *\n * Called at content create/update time when a media provider is available,\n * filling in missing dimensions, storageKey, mimeType, and filename from\n * the provider's `get()` method.\n */\n\nimport type { MediaProvider, MediaProviderItem, MediaValue } from \"./types.js\";\n\nexport const INTERNAL_MEDIA_PREFIX = \"/_emdash/api/media/file/\";\nconst URL_PATTERN = /^https?:\\/\\//;\n\n/**\n * Normalize a media field value into a consistent MediaValue shape.\n *\n * - `null`/`undefined` → `null`\n * - Bare URL string → `{ provider: \"external\", id: \"\", src: url }`\n * - Bare internal media URL → resolved via local provider's `get()`\n * - Object with `provider` + `id` → enriched with missing fields from provider\n */\nexport async function normalizeMediaValue(\n\tvalue: unknown,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue | null> {\n\tif (value == null) return null;\n\n\t// Bare string URL\n\tif (typeof value === \"string\") {\n\t\treturn normalizeStringUrl(value, getProvider);\n\t}\n\n\t// Not an object — can't normalize\n\tif (!isRecord(value)) return null;\n\n\t// Must have at least an id to be a valid media value\n\tif (!(\"id\" in value) && !(\"src\" in value)) return null;\n\n\tconst provider = (typeof value.provider === \"string\" ? value.provider : undefined) || \"local\";\n\tconst id = typeof value.id === \"string\" ? value.id : \"\";\n\n\t// External URLs — return as-is, no server-side dimension detection\n\tif (provider === \"external\") {\n\t\treturn recordToMediaValue(value);\n\t}\n\n\t// Build the base value from the input\n\tconst result: MediaValue = { ...recordToMediaValue(value), provider };\n\n\t// For local media, strip `src` — it's derived at display time from storageKey\n\tif (provider === \"local\") {\n\t\tdelete result.src;\n\t}\n\n\t// Determine if we need to call the provider\n\tconst needsDimensions = result.width == null || result.height == null;\n\tconst needsStorageKey = provider === \"local\" && !result.meta?.storageKey;\n\tconst needsFileInfo = !result.mimeType || !result.filename;\n\tconst needsLookup = needsDimensions || needsStorageKey || needsFileInfo;\n\n\tif (!needsLookup || !id) return result;\n\n\t// Try to enrich from provider\n\tconst mediaProvider = getProvider(provider);\n\tif (!mediaProvider?.get) return result;\n\n\tlet providerItem: MediaProviderItem | null;\n\ttry {\n\t\tproviderItem = await mediaProvider.get(id);\n\t} catch {\n\t\treturn result;\n\t}\n\n\tif (!providerItem) return result;\n\n\treturn mergeProviderData(result, providerItem);\n}\n\nfunction normalizeStringUrl(\n\turl: string,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue | null> {\n\t// Internal media URL — try to resolve via local provider\n\tif (url.startsWith(INTERNAL_MEDIA_PREFIX)) {\n\t\treturn resolveInternalUrl(url, getProvider);\n\t}\n\n\t// External HTTP(S) URL\n\tif (URL_PATTERN.test(url)) {\n\t\treturn Promise.resolve({\n\t\t\tprovider: \"external\",\n\t\t\tid: \"\",\n\t\t\tsrc: url,\n\t\t});\n\t}\n\n\t// Unrecognized string — treat as external\n\treturn Promise.resolve({\n\t\tprovider: \"external\",\n\t\tid: \"\",\n\t\tsrc: url,\n\t});\n}\n\nasync function resolveInternalUrl(\n\turl: string,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue> {\n\tconst storageKey = url.slice(INTERNAL_MEDIA_PREFIX.length);\n\tconst localProvider = getProvider(\"local\");\n\n\tif (!localProvider?.get) {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\tlet item: MediaProviderItem | null;\n\ttry {\n\t\titem = await localProvider.get(storageKey);\n\t} catch {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\tif (!item) {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\treturn {\n\t\tprovider: \"local\",\n\t\tid: item.id,\n\t\tfilename: item.filename,\n\t\tmimeType: item.mimeType,\n\t\twidth: item.width,\n\t\theight: item.height,\n\t\talt: item.alt,\n\t\tmeta: item.meta,\n\t};\n}\n\n/**\n * Merge provider data into an existing MediaValue, preserving caller-supplied fields.\n * Caller `alt` takes priority over provider `alt` (per-usage, not per-image).\n */\nfunction mergeProviderData(existing: MediaValue, item: MediaProviderItem): MediaValue {\n\tconst result = { ...existing };\n\n\t// Fill missing dimensions\n\tif (result.width == null && item.width != null) result.width = item.width;\n\tif (result.height == null && item.height != null) result.height = item.height;\n\n\t// Fill missing file info\n\tif (!result.filename && item.filename) result.filename = item.filename;\n\tif (!result.mimeType && item.mimeType) result.mimeType = item.mimeType;\n\n\t// Fill missing alt (provider alt is fallback, not override)\n\tif (!result.alt && item.alt) result.alt = item.alt;\n\n\t// Fill missing meta (merge, don't replace)\n\tif (item.meta) {\n\t\tresult.meta = { ...item.meta, ...result.meta };\n\t}\n\n\treturn result;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Extract known MediaValue fields from a runtime-checked record.\n * Avoids unsafe `as MediaValue` cast by reading each property explicitly.\n */\nfunction recordToMediaValue(obj: Record<string, unknown>): MediaValue {\n\tconst result: MediaValue = {\n\t\tid: typeof obj.id === \"string\" ? obj.id : \"\",\n\t};\n\tif (typeof obj.provider === \"string\") result.provider = obj.provider;\n\tif (typeof obj.src === \"string\") result.src = obj.src;\n\tif (typeof obj.previewUrl === \"string\") result.previewUrl = obj.previewUrl;\n\tif (typeof obj.filename === \"string\") result.filename = obj.filename;\n\tif (typeof obj.mimeType === \"string\") result.mimeType = obj.mimeType;\n\tif (typeof obj.width === \"number\") result.width = obj.width;\n\tif (typeof obj.height === \"number\") result.height = obj.height;\n\tif (typeof obj.alt === \"string\") result.alt = obj.alt;\n\tif (isRecord(obj.meta)) result.meta = obj.meta;\n\treturn result;\n}\n","/**\n * Image Placeholder Generation\n *\n * Generates blurhash and dominant color from image buffers for LQIP support.\n * Decodes images via jpeg-js (pure JS) and upng-js (pure JS, uses pako for\n * deflate). No Node-specific dependencies — works in Workers and Node SSR.\n */\n\nimport { encode } from \"blurhash\";\nimport { imageSize } from \"image-size\";\n\nexport interface PlaceholderData {\n\tblurhash: string;\n\tdominantColor: string;\n}\n\nconst SUPPORTED_TYPES: Record<string, \"jpeg\" | \"png\"> = {\n\t\"image/jpeg\": \"jpeg\",\n\t\"image/jpg\": \"jpeg\",\n\t\"image/png\": \"png\",\n};\n\n/** Max width for blurhash input. Encode is O(w*h*components), so downsample first. */\nconst MAX_ENCODE_WIDTH = 32;\n\n/** Max decoded RGBA size (32 MB). Images exceeding this skip placeholder generation. */\nconst MAX_DECODED_BYTES = 32 * 1024 * 1024;\n\ninterface DecodedImage {\n\twidth: number;\n\theight: number;\n\tdata: Uint8Array;\n}\n\n/**\n * Decode a JPEG buffer into raw RGBA pixel data.\n */\nasync function decodeJpeg(buffer: Uint8Array): Promise<DecodedImage> {\n\tconst { decode } = await import(\"jpeg-js\");\n\tconst result = decode(buffer, { useTArray: true });\n\treturn { width: result.width, height: result.height, data: result.data };\n}\n\n/**\n * Decode a PNG buffer into raw RGBA pixel data.\n * Uses upng-js (pure JS with pako deflate) — no Node zlib dependency.\n */\nasync function decodePng(buffer: Uint8Array): Promise<DecodedImage> {\n\t// @ts-expect-error -- upng-js has no type declarations\n\tconst UPNG = (await import(\"upng-js\")).default;\n\tconst img = UPNG.decode(buffer.buffer);\n\t// toRGBA8 returns an array of frames; take the first frame\n\tconst frames: ArrayBuffer[] = UPNG.toRGBA8(img);\n\tconst rgba = new Uint8Array(frames[0]);\n\treturn { width: img.width, height: img.height, data: rgba };\n}\n\n/**\n * Extract the dominant color from RGBA pixel data.\n * Simple average of all non-transparent pixels.\n */\nfunction extractDominantColor(data: Uint8Array, width: number, height: number): string {\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tlet count = 0;\n\n\tconst len = width * height * 4;\n\tfor (let i = 0; i < len; i += 4) {\n\t\tconst a = data[i + 3];\n\t\tif (a < 128) continue; // skip mostly-transparent pixels\n\t\tr += data[i];\n\t\tg += data[i + 1];\n\t\tb += data[i + 2];\n\t\tcount++;\n\t}\n\n\tif (count === 0) return \"rgb(0,0,0)\";\n\n\tconst avgR = Math.round(r / count);\n\tconst avgG = Math.round(g / count);\n\tconst avgB = Math.round(b / count);\n\treturn `rgb(${avgR},${avgG},${avgB})`;\n}\n\n/**\n * Read image dimensions from headers without decoding pixel data.\n */\nfunction getImageDimensions(buffer: Uint8Array): { width: number; height: number } | null {\n\ttry {\n\t\tconst result = imageSize(buffer);\n\t\tif (result.width != null && result.height != null) {\n\t\t\treturn { width: result.width, height: result.height };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Generate blurhash and dominant color from an image buffer.\n * Returns null for non-image MIME types or on failure.\n *\n * @param dimensions - Optional pre-known dimensions. Used as a fallback when\n * image-size cannot parse the buffer (e.g. truncated headers). When the\n * decoded size (width * height * 4) exceeds MAX_DECODED_BYTES, placeholder\n * generation is skipped to avoid OOM on memory-constrained runtimes.\n */\nexport async function generatePlaceholder(\n\tbuffer: Uint8Array,\n\tmimeType: string,\n\tdimensions?: { width: number; height: number },\n): Promise<PlaceholderData | null> {\n\tconst format = SUPPORTED_TYPES[mimeType];\n\tif (!format) return null;\n\n\ttry {\n\t\t// Safety net: skip decode if the image would exceed the memory budget\n\t\tconst dims = getImageDimensions(buffer) ?? dimensions;\n\t\tif (dims && dims.width * dims.height * 4 > MAX_DECODED_BYTES) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst imageData = format === \"jpeg\" ? await decodeJpeg(buffer) : await decodePng(buffer);\n\t\tconst { width, height, data } = imageData;\n\n\t\tif (width === 0 || height === 0) return null;\n\n\t\t// Downsample for blurhash encoding if needed\n\t\tlet encodePixels: Uint8ClampedArray;\n\t\tlet encodeWidth: number;\n\t\tlet encodeHeight: number;\n\n\t\tif (width > MAX_ENCODE_WIDTH) {\n\t\t\tconst scale = MAX_ENCODE_WIDTH / width;\n\t\t\tencodeWidth = MAX_ENCODE_WIDTH;\n\t\t\tencodeHeight = Math.max(1, Math.round(height * scale));\n\t\t\tencodePixels = downsample(data, width, height, encodeWidth, encodeHeight);\n\t\t} else {\n\t\t\tencodeWidth = width;\n\t\t\tencodeHeight = height;\n\t\t\tencodePixels = new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength);\n\t\t}\n\n\t\tconst blurhash = encode(encodePixels, encodeWidth, encodeHeight, 4, 3);\n\t\tconst dominantColor = extractDominantColor(data, width, height);\n\n\t\treturn { blurhash, dominantColor };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Nearest-neighbor downsample of RGBA pixel data.\n */\nfunction downsample(\n\tsrc: Uint8Array,\n\tsrcW: number,\n\tsrcH: number,\n\tdstW: number,\n\tdstH: number,\n): Uint8ClampedArray {\n\tconst dst = new Uint8ClampedArray(dstW * dstH * 4);\n\n\tfor (let y = 0; y < dstH; y++) {\n\t\tconst srcY = Math.floor((y * srcH) / dstH);\n\t\tfor (let x = 0; x < dstW; x++) {\n\t\t\tconst srcX = Math.floor((x * srcW) / dstW);\n\t\t\tconst srcIdx = (srcY * srcW + srcX) * 4;\n\t\t\tconst dstIdx = (y * dstW + x) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx]!;\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1]!;\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2]!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AI,kBAAkB,KAAK,QAAQ,KAAK,YAAY,KAAK,WAAW;;AAMpF,SAAO;GAAE,UAHQ,OAAO,cAAc,aAAa,cAAc,GAAG,EAAE;GAGnD,eAFG,qBAAqB,MAAM,OAAO,OAAO;GAE7B;SAC3B;AACP,SAAO;;;;;;AAOT,SAAS,WACR,KACA,MACA,MACA,MACA,MACoB;CACpB,MAAM,MAAM,IAAI,kBAAkB,OAAO,OAAO,EAAE;AAElD,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;EAC9B,MAAM,OAAO,KAAK,MAAO,IAAI,OAAQ,KAAK;AAC1C,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;GAC9B,MAAM,OAAO,KAAK,MAAO,IAAI,OAAQ,KAAK;GAC1C,MAAM,UAAU,OAAO,OAAO,QAAQ;GACtC,MAAM,UAAU,IAAI,OAAO,KAAK;AAChC,OAAI,UAAU,IAAI;AAClB,OAAI,SAAS,KAAK,IAAI,SAAS;AAC/B,OAAI,SAAS,KAAK,IAAI,SAAS;AAC/B,OAAI,SAAS,KAAK,IAAI,SAAS;;;AAIjC,QAAO"}
|
|
@@ -281,4 +281,4 @@ declare function generatePlaceholder(buffer: Uint8Array, mimeType: string, dimen
|
|
|
281
281
|
}): Promise<PlaceholderData | null>;
|
|
282
282
|
//#endregion
|
|
283
283
|
export { MediaValue as _, ComponentEmbed as a, mediaItemToValue as b, EmbedResult as c, MediaListResult as d, MediaProvider as f, MediaUploadInput as g, MediaProviderItem as h, AudioEmbed as i, ImageEmbed as l, MediaProviderDescriptor as m, generatePlaceholder as n, CreateMediaProviderFn as o, MediaProviderCapabilities as p, normalizeMediaValue as r, EmbedOptions as s, PlaceholderData as t, MediaListOptions as u, ThumbnailOptions as v, VideoEmbed as y };
|
|
284
|
-
//# sourceMappingURL=placeholder-
|
|
284
|
+
//# sourceMappingURL=placeholder-D29tWZ7o.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"placeholder-
|
|
1
|
+
{"version":3,"file":"placeholder-D29tWZ7o.d.mts","names":[],"sources":["../src/media/types.ts","../src/media/normalize.ts","../src/media/placeholder.ts"],"mappings":";;AAYA;;;;;;;;;;UAAiB,uBAAA,WAAkC,MAAA;EAKlD;EAHA,EAAA;EASA;EANA,IAAA;EAYA;EATA,IAAA;EAYA;EATA,UAAA;EASe;EANf,WAAA;EAYgB;EAThB,YAAA,EAAc,yBAAA;;EAGd,MAAA,EAAQ,OAAA;AAAA;;;;UAMQ,yBAAA;EAQV;EANN,MAAA;EAYgC;EAVhC,MAAA;EAUgC;EARhC,MAAA;EAYA;EAVA,MAAA;AAAA;;;AAoBD;UAdiB,gBAAA;;EAEhB,MAAA;EAaA;EAXA,KAAA;EAYA;EAVA,KAAA;EAUU;EARV,QAAA;AAAA;;;;UAMgB,eAAA;EAChB,KAAA,EAAO,iBAAA;EACP,UAAA;AAAA;;;;;UAOgB,iBAAA;EAiBH;EAfb,EAAA;EAqBgB;EAnBhB,QAAA;;EAEA,QAAA;EAkBA;EAhBA,IAAA;EAiBA;EAfA,KAAA;EACA,MAAA;EAeG;EAbH,GAAA;EAmB4B;EAjB5B,UAAA;EAiB4B;EAf5B,IAAA,GAAO,MAAA;AAAA;;;;UAMS,gBAAA;EAChB,IAAA,EAAM,IAAA;EACN,QAAA;EACA,GAAA;AAAA;;;;UAMgB,YAAA;EAYS;EAVzB,KAAA;EAUmD;EARnD,MAAA;EAQ8E;EAN9E,MAAA;AAAA;;;;KAMW,WAAA,GAAc,UAAA,GAAa,UAAA,GAAa,UAAA,GAAa,cAAA;AAAA,UAEhD,UAAA;EAChB,IAAA;EACA,GAAA;EACA,MAAA;EACA,KAAA;EACA,KAAA;EACA,MAAA;EACA,GAAA;EAIkB;EAFlB,UAAA;EAEmD;EAAnD,MAAA,IAAU,IAAA;IAAQ,KAAA;IAAgB,MAAA;IAAiB,MAAA;EAAA;AAAA;AAAA,UAGnC,UAAA;EAChB,IAAA;EAEA;EAAA,GAAA;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AA;EA9B2C;EAiC3C,IAAA,GAAO,MAAA;AAAA;;;;iBAMQ,gBAAA,CAAiB,UAAA,UAAoB,IAAA,EAAM,iBAAA,GAAoB,UAAA;;;;;;;;;;;iBCnPzD,mBAAA,CACrB,KAAA,WACA,WAAA,GAAc,EAAA,aAAe,aAAA,eAC3B,OAAA,CAAQ,UAAA;;;;ADfX;;;;;;UEDiB,eAAA;EAChB,QAAA;EACA,aAAA;AAAA;;;;;;;;;;iBAgGqB,mBAAA,CACrB,MAAA,EAAQ,UAAA,EACR,QAAA,UACA,UAAA;EAAe,KAAA;EAAe,MAAA;AAAA,IAC5B,OAAA,CAAQ,eAAA"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import "../types-
|
|
2
|
-
import { mn as PluginDescriptor } from "../index-
|
|
3
|
-
import "../runner-
|
|
4
|
-
import { X as ResolvedPlugin, tt as StandardPluginDefinition } from "../types-
|
|
5
|
-
import "../validate-
|
|
1
|
+
import "../types-CS8FIX7L.mjs";
|
|
2
|
+
import { mn as PluginDescriptor } from "../index-DIb-CzNx.mjs";
|
|
3
|
+
import "../runner-OURCaApa.mjs";
|
|
4
|
+
import { X as ResolvedPlugin, tt as StandardPluginDefinition } from "../types-i36XcA_X.mjs";
|
|
5
|
+
import "../validate-DHxmpFJt.mjs";
|
|
6
6
|
|
|
7
7
|
//#region src/plugins/adapt-sandbox-entry.d.ts
|
|
8
8
|
/**
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-ClPoSABd.mjs";
|
|
2
2
|
import { getRequestContext } from "./request-context.mjs";
|
|
3
3
|
import { n as getI18nConfig, r as isI18nEnabled, t as getFallbackChain } from "./config-BXwuX8Bx.mjs";
|
|
4
|
-
import { t as isMissingTableError } from "./db-errors-
|
|
5
|
-
import { n as requestCached } from "./request-cache-
|
|
4
|
+
import { t as isMissingTableError } from "./db-errors-l1Qh2RPR.mjs";
|
|
5
|
+
import { n as requestCached } from "./request-cache-Ci7f5pBb.mjs";
|
|
6
6
|
|
|
7
7
|
//#region src/visual-editing/editable.ts
|
|
8
8
|
/**
|
|
@@ -381,7 +381,7 @@ async function getEmDashEntry(type, id, options) {
|
|
|
381
381
|
async function hydrateEntryBylines(type, entries) {
|
|
382
382
|
if (entries.length === 0) return;
|
|
383
383
|
try {
|
|
384
|
-
const { getBylinesForEntries } = await import("./bylines-
|
|
384
|
+
const { getBylinesForEntries } = await import("./bylines-CRNsVG88.mjs").then((n) => n.t);
|
|
385
385
|
const ids = entries.map((e) => dataStr(entryData(e), "id")).filter(Boolean);
|
|
386
386
|
if (ids.length === 0) return;
|
|
387
387
|
const bylinesMap = await getBylinesForEntries(type, ids);
|
|
@@ -417,7 +417,7 @@ async function hydrateEntryBylines(type, entries) {
|
|
|
417
417
|
async function hydrateEntryTerms(type, entries) {
|
|
418
418
|
if (entries.length === 0) return;
|
|
419
419
|
try {
|
|
420
|
-
const { getAllTermsForEntries } = await import("./taxonomies-
|
|
420
|
+
const { getAllTermsForEntries } = await import("./taxonomies-B4IAshV8.mjs").then((n) => n.u);
|
|
421
421
|
const ids = entries.map((e) => dataStr(entryData(e), "id")).filter(Boolean);
|
|
422
422
|
if (ids.length === 0) return;
|
|
423
423
|
const termsMap = await getAllTermsForEntries(type, ids);
|
|
@@ -451,9 +451,9 @@ async function hydrateEntryTerms(type, entries) {
|
|
|
451
451
|
*/
|
|
452
452
|
async function getTranslations(type, id) {
|
|
453
453
|
try {
|
|
454
|
-
const db = (await import("./loader-
|
|
454
|
+
const db = (await import("./loader-CndGj8kM.mjs").then((n) => n.r)).getDb;
|
|
455
455
|
const dbInstance = await db();
|
|
456
|
-
const { ContentRepository } = await import("./content-
|
|
456
|
+
const { ContentRepository } = await import("./content-BcQPYxdV.mjs").then((n) => n.n);
|
|
457
457
|
const repo = new ContentRepository(dbInstance);
|
|
458
458
|
const item = await repo.findByIdOrSlug(type, id);
|
|
459
459
|
if (!item) return {
|
|
@@ -522,8 +522,8 @@ function invalidateUrlPatternCache() {
|
|
|
522
522
|
*/
|
|
523
523
|
async function resolveEmDashPath(path) {
|
|
524
524
|
if (!cachedUrlPatterns) {
|
|
525
|
-
const { getDb } = await import("./loader-
|
|
526
|
-
const { SchemaRegistry } = await import("./registry-
|
|
525
|
+
const { getDb } = await import("./loader-CndGj8kM.mjs").then((n) => n.r);
|
|
526
|
+
const { SchemaRegistry } = await import("./registry-C3Mr0ODu.mjs").then((n) => n.r);
|
|
527
527
|
const collections = await new SchemaRegistry(await getDb()).listCollections();
|
|
528
528
|
cachedUrlPatterns = [];
|
|
529
529
|
for (const collection of collections) {
|
|
@@ -555,4 +555,4 @@ async function resolveEmDashPath(path) {
|
|
|
555
555
|
|
|
556
556
|
//#endregion
|
|
557
557
|
export { invalidateUrlPatternCache as a, createEditable as c, getTranslations as i, createNoop as l, getEmDashCollection as n, query_exports as o, getEmDashEntry as r, resolveEmDashPath as s, getEditMeta as t };
|
|
558
|
-
//# sourceMappingURL=query-
|
|
558
|
+
//# sourceMappingURL=query-fqEdLFms.mjs.map
|