@murumets-ee/content-api 0.98.0 → 0.99.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/index.d.mts +101 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.d.mts
CHANGED
|
@@ -516,6 +516,13 @@ interface ResolvedBlockTree {
|
|
|
516
516
|
* part. Only DECLARED columns are projected — never the row.
|
|
517
517
|
*/
|
|
518
518
|
readonly detail?: ResolvedDetail;
|
|
519
|
+
/**
|
|
520
|
+
* Block type → the data a plugin's provider resolved for it
|
|
521
|
+
* (davatoidud-toolkit PR04, `blocks.dataProviders`). Structural mirror of
|
|
522
|
+
* `@murumets-ee/content`'s field; each value is validated by the block that
|
|
523
|
+
* draws it, on the consumer's side of the process boundary.
|
|
524
|
+
*/
|
|
525
|
+
readonly blockData?: Readonly<Record<string, unknown>>;
|
|
519
526
|
}
|
|
520
527
|
/** One labelled value of a row's detail — structural mirror of a collection row's meta line. */
|
|
521
528
|
interface ResolvedDetailFact {
|
|
@@ -784,6 +791,83 @@ interface ContentApiDetailTemplates {
|
|
|
784
791
|
}): Promise<Record<string, unknown>>;
|
|
785
792
|
}
|
|
786
793
|
//#endregion
|
|
794
|
+
//#region src/forms.d.ts
|
|
795
|
+
/**
|
|
796
|
+
* `/_forms/:id/token` and `POST /_forms/:id/submissions` — the one place this
|
|
797
|
+
* read-only API accepts a write (forms plan D003).
|
|
798
|
+
*
|
|
799
|
+
* A form on a site is posted by the VISITOR to the site's own front (same
|
|
800
|
+
* origin, works without JavaScript); the front forwards it here with its site
|
|
801
|
+
* key and the visitor's address. So both routes answer only a caller carrying a
|
|
802
|
+
* verified site key — the site comes from that key and nothing else — and a
|
|
803
|
+
* caller without one gets the same 404 as a route that does not exist. A
|
|
804
|
+
* browser never reaches them directly.
|
|
805
|
+
*
|
|
806
|
+
* What this module owns is the HTTP edge: the key requirement, the body cap,
|
|
807
|
+
* parsing, the visitor address, and turning the provider's verdict into a
|
|
808
|
+
* response. Every decision about the FORM — which form, spam, validation,
|
|
809
|
+
* rate limits, the extra check, storage — is the injected `forms` provider's
|
|
810
|
+
* (`@murumets-ee/forms/server`), because this package is a leaf (D032).
|
|
811
|
+
*
|
|
812
|
+
* Every response here is `no-store`: a token is minted for one visitor's
|
|
813
|
+
* ask, and a submission's answer is about one post (C5 — nothing from a
|
|
814
|
+
* submission in a cache).
|
|
815
|
+
*/
|
|
816
|
+
/** What a rendered form needs: a fresh token, its trap's name, its extra check. */
|
|
817
|
+
interface ContentApiFormTicket {
|
|
818
|
+
readonly token: string;
|
|
819
|
+
readonly honeypot: string;
|
|
820
|
+
readonly challenge: {
|
|
821
|
+
readonly provider: 'turnstile' | 'recaptcha';
|
|
822
|
+
readonly siteKey: string;
|
|
823
|
+
} | null;
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* The provider's verdict on one post. `accepted` is ALSO the answer to spam —
|
|
827
|
+
* a bot is told it succeeded (forms D004) — so this module cannot tell the two
|
|
828
|
+
* apart, and the response it builds is the same bytes for both.
|
|
829
|
+
*/
|
|
830
|
+
type ContentApiFormSubmitResult = {
|
|
831
|
+
readonly kind: 'accepted';
|
|
832
|
+
} | {
|
|
833
|
+
readonly kind: 'invalid';
|
|
834
|
+
readonly fields: Readonly<Record<string, string>>;
|
|
835
|
+
} | {
|
|
836
|
+
readonly kind: 'rate_limited';
|
|
837
|
+
readonly retryAfterSeconds: number;
|
|
838
|
+
} | {
|
|
839
|
+
readonly kind: 'challenge_failed';
|
|
840
|
+
} | {
|
|
841
|
+
readonly kind: 'unavailable';
|
|
842
|
+
} | {
|
|
843
|
+
readonly kind: 'not_found';
|
|
844
|
+
};
|
|
845
|
+
/**
|
|
846
|
+
* The forms provider. Omit it and both routes are 404 (opt-in,
|
|
847
|
+
* deny-by-default). Wire `createFormsContentApi(getToolkitApp)` from
|
|
848
|
+
* `@murumets-ee/forms/server`.
|
|
849
|
+
*/
|
|
850
|
+
interface ContentApiForms {
|
|
851
|
+
issueToken(input: {
|
|
852
|
+
site: string;
|
|
853
|
+
formId: string;
|
|
854
|
+
purpose: 'render' | 'visitor';
|
|
855
|
+
visitorAddress: string | null;
|
|
856
|
+
}): Promise<ContentApiFormTicket | null | 'rate_limited'>;
|
|
857
|
+
submit(input: {
|
|
858
|
+
site: string;
|
|
859
|
+
formId: string;
|
|
860
|
+
body: unknown;
|
|
861
|
+
visitorAddress: string | null;
|
|
862
|
+
}): Promise<ContentApiFormSubmitResult>;
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Largest submission body accepted. A form has at most 100 fields and its
|
|
866
|
+
* longest answer is 5,000 characters; this is room for a long message and a
|
|
867
|
+
* CAPTCHA token, and well short of anything worth parsing for a flood.
|
|
868
|
+
*/
|
|
869
|
+
declare const MAX_FORM_BODY_BYTES: number;
|
|
870
|
+
//#endregion
|
|
787
871
|
//#region src/limits.d.ts
|
|
788
872
|
interface ContentApiLimits {
|
|
789
873
|
/**
|
|
@@ -964,7 +1048,7 @@ type ResolveEntityHref = (target: {
|
|
|
964
1048
|
*
|
|
965
1049
|
* `code` is machine contract; `message` is not, and is free to be specific.
|
|
966
1050
|
*/
|
|
967
|
-
declare const ERROR_CODES: readonly ["NOT_FOUND", "VALIDATION_ERROR", "INTERNAL_ERROR", "RATE_LIMITED", "SERVICE_OVERLOADED"];
|
|
1051
|
+
declare const ERROR_CODES: readonly ["NOT_FOUND", "VALIDATION_ERROR", "INTERNAL_ERROR", "RATE_LIMITED", "SERVICE_OVERLOADED", "FORM_INVALID", "CHALLENGE_FAILED", "PAYLOAD_TOO_LARGE"];
|
|
968
1052
|
/** One of {@link ERROR_CODES}. */
|
|
969
1053
|
type ContentApiErrorCode = (typeof ERROR_CODES)[number];
|
|
970
1054
|
//#endregion
|
|
@@ -1866,6 +1950,14 @@ interface ContentApiConfig {
|
|
|
1866
1950
|
* gate.
|
|
1867
1951
|
*/
|
|
1868
1952
|
menus?: ContentApiMenus;
|
|
1953
|
+
/**
|
|
1954
|
+
* Form submissions (forms plan D003/D004). When present, the handler serves
|
|
1955
|
+
* `GET /_forms/:id/token` and `POST /_forms/:id/submissions` — to a caller
|
|
1956
|
+
* whose site KEY names the site, and nobody else; omit and both stay 404
|
|
1957
|
+
* (opt-in — deny-by-default). Injected (not imported) so this stays a leaf
|
|
1958
|
+
* package — wire `createFormsContentApi` from `@murumets-ee/forms/server`.
|
|
1959
|
+
*/
|
|
1960
|
+
forms?: ContentApiForms;
|
|
1869
1961
|
/**
|
|
1870
1962
|
* Site-chrome provider (plan/api phase 07). When present, the handler serves
|
|
1871
1963
|
* `GET /_chrome`; omit and it stays 404 (opt-in — deny-by-default). Injected
|
|
@@ -2123,6 +2215,13 @@ interface SchemaCacheTags {
|
|
|
2123
2215
|
declare const API_VERSION = "v1";
|
|
2124
2216
|
declare function createContentApiHandler(config: ContentApiConfig): {
|
|
2125
2217
|
GET: (req: Request, ctx: RouteContext) => Promise<Response>;
|
|
2218
|
+
/**
|
|
2219
|
+
* The one write route, `POST /_forms/:id/submissions` (forms D003) — a
|
|
2220
|
+
* 404 for every other path, and for that one too unless `forms` is wired.
|
|
2221
|
+
* It goes through the SAME dispatch as a read: the survival guard, the
|
|
2222
|
+
* site from the key, the fairness limit and the request context.
|
|
2223
|
+
*/
|
|
2224
|
+
POST: (req: Request, ctx: RouteContext) => Promise<Response>;
|
|
2126
2225
|
OPTIONS: (req: Request) => Promise<Response>;
|
|
2127
2226
|
/**
|
|
2128
2227
|
* Invalidate the cached permission checker. Call this from the
|
|
@@ -2133,5 +2232,5 @@ declare function createContentApiHandler(config: ContentApiConfig): {
|
|
|
2133
2232
|
invalidatePermissionCache: () => void;
|
|
2134
2233
|
};
|
|
2135
2234
|
//#endregion
|
|
2136
|
-
export { API_VERSION, type BlockTreeRef, CACHE_TAG_NAMESPACE, type CacheTagsConfig, type ContentApiChrome, type ContentApiChromeRegion, type ContentApiChromeRegions, type ContentApiConfig, type ContentApiDetailTemplates, type ContentApiErrorCode, type ContentApiErrorReport, type ContentApiMenus, type ContentApiPrincipal, type ContentApiResolution, type ContentApiResolvedMenu, type ContentApiResolvedMenuItem, type ContentApiSearchConfig, type ContentApiSite, type ContentApiSiteProvider, type ContentPathEntry, type ContentResolveResult, DEFAULT_SEARCH_RESULTS, DETAIL_TEMPLATE_FIELD, ERROR_CODES, MAX_CACHE_TAGS_PER_RESPONSE, MAX_CACHE_TAG_HEADER_BYTES, MAX_CACHE_TAG_LENGTH, MAX_RESOLUTIONS_PER_DOCUMENT, MAX_SEARCH_RESULTS, MEDIA_TAG_ENTITY, type MediaProjection, type MediaSource, type ReferenceProjection, type ResolutionBudget, type ResolutionKind, type ResolveBlocks, type ResolveEntityHref, type ResolveMedia, type ResolvedBlockTree, SHARED_SITE_TAG_SEGMENT, type SchemaCacheTags, type SearchHit, type UnresolvedBlockRef, VISITOR_ADDRESS_HEADER, createContentApiHandler, isResolvedBlockTree };
|
|
2235
|
+
export { API_VERSION, type BlockTreeRef, CACHE_TAG_NAMESPACE, type CacheTagsConfig, type ContentApiChrome, type ContentApiChromeRegion, type ContentApiChromeRegions, type ContentApiConfig, type ContentApiDetailTemplates, type ContentApiErrorCode, type ContentApiErrorReport, type ContentApiFormSubmitResult, type ContentApiFormTicket, type ContentApiForms, type ContentApiMenus, type ContentApiPrincipal, type ContentApiResolution, type ContentApiResolvedMenu, type ContentApiResolvedMenuItem, type ContentApiSearchConfig, type ContentApiSite, type ContentApiSiteProvider, type ContentPathEntry, type ContentResolveResult, DEFAULT_SEARCH_RESULTS, DETAIL_TEMPLATE_FIELD, ERROR_CODES, MAX_CACHE_TAGS_PER_RESPONSE, MAX_CACHE_TAG_HEADER_BYTES, MAX_CACHE_TAG_LENGTH, MAX_FORM_BODY_BYTES, MAX_RESOLUTIONS_PER_DOCUMENT, MAX_SEARCH_RESULTS, MEDIA_TAG_ENTITY, type MediaProjection, type MediaSource, type ReferenceProjection, type ResolutionBudget, type ResolutionKind, type ResolveBlocks, type ResolveEntityHref, type ResolveMedia, type ResolvedBlockTree, SHARED_SITE_TAG_SEGMENT, type SchemaCacheTags, type SearchHit, type UnresolvedBlockRef, VISITOR_ADDRESS_HEADER, createContentApiHandler, isResolvedBlockTree };
|
|
2137
2236
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/cache-tags.ts","../src/resolution-budget.ts","../src/blocks.ts","../src/detail-template.ts","../src/limits.ts","../src/media.ts","../src/references.ts","../src/response.ts","../src/search.ts","../src/types.ts","../src/handler.ts"],"mappings":";;;;;;;;;;;;AA8FA;;;;AAAgC;AAOhC;;;;AAAiC;AAOjC;;;;AAAwC;AAqCxC;;;;AAAuC;AAYvC;;;;AAA6B;AAyC7B;;;;AAAoC;AAMpC;;;;;;;;AAmCW;;;;;;;;ACtMkE;AAE7E;;;;AAAqD;AA0BrD;;;;AAAyC;AAUzC;;;;;;;;;;;;;;;;;;;;;;AAuBkB;;;;ACxClB;;;;cFgCa,mBAAA;;;;AElBI;AAyEjB;cFhDa,oBAAA;;;AEkDA;AAGb;;cF9Ca,2BAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AE0IqB;AAIlC;;;;cFzGa,0BAAA;;;;;AE6GI;AAIjB;;;;;cFrGa,gBAAA;;;;;;;;;;;;;;;cAyCA,uBAAA;;;;;UAMI,eAAA;EEmKA;;;;;;;;;;;AAQ2B;EF9J1C,OAAA;EEkK+B;;;;;;;;AAIlB;AAIf;;;EF7JE,MAAA;EEsKS;;;;;;;;EF7JT,SAAA;AAAA;;;;;;;;;AAjJF;;;;AAAgC;AAOhC;;;;AAAiC;AAOjC;;;;AAAwC;AAqCxC;;;;AAAuC;AAYvC;;;;AAA6B;AAyC7B;;;;AAAoC;AAMpC;;;;AA/C6B,cCpHvB,gBAAA;AAAA,KAEM,c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iBAuqBG,uBAAA,CAAwB,MAAA,EAAQ,gBAAA;aAk1GjC,OAAA,EAAO,GAAA,EAAO,YAAA,KAAY,OAAA,CAAA,QAAA;iBAChB,OAAA,KAAU,OAAA,CAAQ,QAAA;ET/8I1B"}
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/cache-tags.ts","../src/resolution-budget.ts","../src/blocks.ts","../src/detail-template.ts","../src/forms.ts","../src/limits.ts","../src/media.ts","../src/references.ts","../src/response.ts","../src/search.ts","../src/types.ts","../src/handler.ts"],"mappings":";;;;;;;;;;;;AA8FA;;;;AAAgC;AAOhC;;;;AAAiC;AAOjC;;;;AAAwC;AAqCxC;;;;AAAuC;AAYvC;;;;AAA6B;AAyC7B;;;;AAAoC;AAMpC;;;;;;;;AAmCW;;;;;;;;ACtMkE;AAE7E;;;;AAAqD;AA0BrD;;;;AAAyC;AAUzC;;;;;;;;;;;;;;;;;;;;;;AAuBkB;;;;ACxClB;;;;cFgCa,mBAAA;;;;AElBI;AAyEjB;cFhDa,oBAAA;;;AEkDA;AAGb;;cF9Ca,2BAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCA,0BAAA;AEgHb;;;;;;;;;AAIiB;AAJjB,cFpGa,gBAAA;;;;;;;;;;;;;;;cAyCA,uBAAA;;;;;UAMI,eAAA;EE4EN;;;;AAA8D;AA8FzE;;;;;;;EF7JE,OAAA;EEqKS;;;AAAiC;AAI5C;;;;;;;;EF5JE,MAAA;EEgKa;AAIf;;;;;;;EF3JE,SAAA;AAAA;;;;;;;;;AAjJF;;;;AAAgC;AAOhC;;;;AAAiC;AAOjC;;;;AAAwC;AAqCxC;;;;AAAuC;AAYvC;;;;AAA6B;AAyC7B;;;;AAAoC;AAMpC;;;;AA/C6B,cCpHvB,gBAAA;AAAA,KAEM,cAAA,WAAyB,gBAAgB;;;ADoM1C;;;;;;;;ACtMkE;AAE7E;;;;AAAqD;AA0BrD;;;;AAAyC;AAUzC;;;cAV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;;;;;AAwGS;;;;ACz7BX;;ED8ZE,WAAA,GAAc,QAAA,CAAS,MAAA;EC9ZD;AAAA;AAuqBxB;;;;;;;;ED7PE,eAAA,GAAkB,yBAAA;ECunHU;;;;;;;;;;;;;;;;;;;;;;;;;;ED3lH5B,OAAA,IAAW,GAAA,EAAK,qBAAA,YAAiC,OAAA;EC4lHhB;;;;;;;;;;;;ED9kHjC,MAAA,GAAS,gBAAA;;;;;;;;;EAUT,MAAA,GAAS,sBAAA;AAAA;;;;;;;;;;;UAaM,qBAAA;;EAEf,MAAA;;EAEA,IAAA,EAAM,mBAAmB;;EAEzB,IAAA;;EAEA,MAAA;;EAEA,SAAA;;EAEA,WAAA;AAAA;;;;;;;;;UAsVe,eAAA;;EAEf,MAAA;;EAEA,SAAA;;;;;EAKA,QAAA;;;;;;;;;;;;;EAaA,UAAA;;;;;;;;;;;EAWA,UAAA;;EAEA,YAAA;;;;;;EAMA,kBAAA;;;;;;EAMA,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6DA,SAAA;AAAA;;;;;;;AVhvCS;;;;;;;;ACtMkE;AAE7E;;;;AAAqD;AA0BrD;cUiea,WAAA;AAAA,iBAuqBG,uBAAA,CAAwB,MAAA,EAAQ,gBAAA;aAm3GjC,OAAA,EAAO,GAAA,EAAO,YAAA,KAAY,OAAA,CAAA,QAAA;EV3/IA;AAUzC;;;;;cUw/IgB,OAAA,EAAO,GAAA,EAAO,YAAA,KAAY,OAAA,CAAA,QAAA;iBACjB,OAAA,KAAU,OAAA,CAAQ,QAAA;EVp+InB"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CountCache as e,SITE_COLUMN as t,SiteRequiredError as n,blockTreeFieldsOf as r,blockTreeTemplateOf as i,buildTranslationsSearchExists as a,decodeCursor as o,encodeCursor as s,filterTranslatableFields as c,getEntityTitleField as l,getSearchableConfig as u,hasSiteTemplates as d,isSiteBound as f,isSortOnlyInternalField as p,isTemplateDrawn as m,isValidSiteHandle as h}from"@murumets-ee/entity";import{LOCALE_PATTERN as g,REQUEST_ID_HEADER as _,escapeLikePattern as v,getApp as y,getAppOrUndefined as b,getContext as x,getCurrentSite as S,readSiteOriginIndex as C,readSiteRecord as w,requireSiteFor as T,resolveImplicitSite as E,resolveRequestId as D,runBounded as O,runWithContextAsync as ee,siteSecurityFields as te}from"@murumets-ee/core";import{z as k}from"zod";import{schemaRegistry as ne}from"@murumets-ee/db";import{QueryClient as re}from"@murumets-ee/entity/query";import{and as ie,asc as ae,desc as A,eq as j,getTableColumns as M,gte as oe,ilike as se,inArray as ce,lte as N,or as le,sql as P}from"drizzle-orm";import{InMemoryRateLimitStore as F,Semaphore as ue,createClientIpResolver as I,runWithDeadline as de}from"@murumets-ee/core/limits";const fe=/[\u200B-\u200D\u2060\uFEFF]/g;function pe(e){return e.replace(fe,``).trim()}const L=2048,me=k.object({limit:k.coerce.number().int().min(1).max(100).default(20),offset:k.coerce.number().int().min(0).default(0),sort:k.string().regex(/^-?[a-zA-Z_]+$/).optional(),locale:k.string().regex(g).optional(),fields:k.string().optional(),search:k.string().max(200).refine(e=>{let t=pe(e);return t.length===0||t.length>=2},{message:`search must be at least 2 characters`}).optional(),cursor:k.string().max(500).optional(),populate:k.string().max(200).optional()}).strict(),he=k.object({locale:k.string().regex(g).optional(),fields:k.string().optional(),populate:k.string().max(200).optional(),page:k.string().regex(/^(?:[1-9][0-9]?|100)$/).transform(Number).optional()}).strict(),ge=k.object({locale:k.string().regex(g).optional()}).strict(),_e=/^filter\[([a-zA-Z0-9_]+)\]$/;function R(e,t){let n={};for(let[r,i]of e.searchParams.entries())t?.allowFilters===!0&&_e.test(r)||(n[r]=i);return n}const ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ye=/^\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})?)?$/;function be(e){if(!ye.test(e))return!1;let t=Date.parse(e);return Number.isNaN(t)?!1:e.length===10?new Date(t).toISOString().slice(0,10)===e:!0}function xe(e){if(e.trim()===``)return!1;let t=Number(e);return Number.isFinite(t)}function Se(e){return ve.test(e)}function Ce(e,t){switch(e.type){case`boolean`:return t===`true`?!0:t===`false`?!1:null;case`reference`:case`media`:return ve.test(t)?t:null;case`select`:return e.options.includes(t)?t:null;case`date`:return be(t.startsWith(`gte:`)||t.startsWith(`lte:`)?t.slice(4):t)?t:null;case`number`:return xe(t)?Number(t):null;case`text`:return t.length<=200?t:null;default:return null}}function z(e,t){return e.startsWith(`_`)||t?.internal===!0||t?.adminOnly===!0}function we(e,t){if(!e)return;let n=e.split(`,`).map(e=>e.trim()).filter(e=>{if(!Object.hasOwn(t,e))return!1;let n=t[e];return n!==void 0&&!z(e,n)&&n.type!==`blockTree`});return n.includes(`id`)||n.unshift(`id`),n}function Te(e,t){if(!e)return{fields:[],dropped:[],requested:0};let n=[...new Set(e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0))],r=[],i=[];for(let e of n){if(!Object.hasOwn(t,e)){i.push(e);continue}let n=t[e];if(!n||z(e,n)||n.type!==`reference`){i.push(e);continue}r.push(e)}return{fields:r,dropped:i,requested:n.length}}const Ee=[`reference`,`populate`,`media`,`block`],De=200;function Oe(e){if(!Number.isInteger(e)||e<0)throw Error(`content-api: resolution budget ceiling must be a non-negative integer, received ${String(e)}.`);let t=e,n=0,r=new Map;return{claim(e,i){if(!Number.isInteger(i)||i<=0)return 0;let a=Math.min(i,t);t-=a,n+=a;let o=i-a;return o>0&&r.set(e,(r.get(e)??0)+o),a},get remaining(){return t},get granted(){return n},get hasDrops(){return r.size>0},dropSummary(){let e={};for(let t of Ee){let n=r.get(t);n!==void 0&&n>0&&(e[t]=n)}return e},ceiling:e}}function ke(e){if(e===void 0)return 200;if(!Number.isInteger(e)||e<0)throw Error(`content-api: \`maxResolutionsPerDocument\` must be an integer >= 0, received ${String(e)}. If this came from an environment variable, it is probably unset — omit the option to get the package default (200).`);return Math.min(e,200)}const Ae=2e3;function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){if(!B(e))return!1;let t=e=>e===void 0||typeof e==`string`&&e.length<=Ae,n=e=>e===void 0||typeof e==`number`&&Number.isFinite(e)&&e>=0;if(!t(e.title)||!t(e.text))return!1;let r=e.price;if(r!==void 0&&(!B(r)||typeof r.amount!=`number`||!Number.isFinite(r.amount)||r.amount<0||!n(r.compareAt)||!t(r.unit)))return!1;let i=e.facts;if(i!==void 0){if(!Array.isArray(i)||i.length>12)return!1;for(let e of i)if(!B(e)||typeof e.key!=`string`||typeof e.label!=`string`||typeof e.value!=`string`&&typeof e.value!=`number`||e.format!==void 0&&e.format!==`price`)return!1}let a=e.body;if(a!==void 0){if(!B(a)||typeof a.html!=`string`||a.html.length>5e5||!Array.isArray(a.headings)||a.headings.length>100)return!1;for(let e of a.headings)if(!B(e)||typeof e.id!=`string`||typeof e.text!=`string`||e.level!==2&&e.level!==3)return!1}let o=e.embed;if(o!==void 0&&(!B(o)||typeof o.provider!=`string`||typeof o.reference!=`string`))return!1;let s=e.breadcrumbs;if(s!==void 0){if(!Array.isArray(s)||s.length>8)return!1;for(let e of s){if(!B(e)||typeof e.label!=`string`||e.label.length>Ae)return!1;if(e.href!==void 0){if(typeof e.href!=`string`||e.href.length>1e3||!e.href.startsWith(`/`)||e.href.startsWith(`//`))return!1;for(let t of e.href){let e=t.codePointAt(0)??0;if(e<=32||e===127||t===`\\`)return!1}}}}return!0}const H=new Set([`price`,`number`,`text`]);function U(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return W(t.name)&&W(t.label)&&H.has(t.format)&&(t.unit===void 0||W(t.unit))}function W(e){if(typeof e!=`string`||e.length>1200)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<32)return!1;return!0}function je(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let{sources:t,values:n}=e;if(typeof t!=`object`||!t||Array.isArray(t)||typeof n!=`object`||!n||Array.isArray(n))return!1;let r=Object.entries(t);if(r.length>32)return!1;for(let[,e]of r){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.label!=`string`||t.labelKey!==void 0&&typeof t.labelKey!=`string`||t.kind!==void 0&&t.kind!==`price`&&t.kind!==`text`&&t.kind!==`list`&&t.kind!==`facts`||t.facts!==void 0&&(!Array.isArray(t.facts)||t.facts.length>48||!t.facts.every(U))||t.fields!==void 0&&(!Array.isArray(t.fields)||t.fields.length>64||!t.fields.every(e=>typeof e==`string`)))return!1}let i=Object.entries(n);if(i.length>32)return!1;for(let[,e]of i){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);if(t.length>200)return!1;for(let[,e]of t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.amount!==void 0&&(typeof t.amount!=`number`||!Number.isFinite(t.amount))||t.compareAt!==void 0&&(typeof t.compareAt!=`number`||!Number.isFinite(t.compareAt))||t.unit!==void 0&&typeof t.unit!=`string`||t.text!==void 0&&!W(t.text)||t.items!==void 0&&(!Array.isArray(t.items)||t.items.length>100||!t.items.every(W)))return!1;if(t.facts!==void 0){if(typeof t.facts!=`object`||t.facts===null||Array.isArray(t.facts))return!1;let e=Object.entries(t.facts);if(e.length>48)return!1;for(let[,t]of e)if(!(typeof t==`number`&&Number.isFinite(t)||W(t)))return!1}}}return!0}const Me=new Set([`ok`,`unset`,`unavailable`,`over-budget`,`needs-document`]);function Ne(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.status!=`string`||!Me.has(t.status)||t.entity!==null&&(typeof t.entity!=`string`||t.entity===``)||!Array.isArray(t.rows)||t.rows.length>100)return!1;if(t.page!==void 0){if(typeof t.page!=`object`||t.page===null||Array.isArray(t.page))return!1;let e=t.page;if(typeof e.number!=`number`||!Number.isInteger(e.number)||e.number<1||e.number>100||typeof e.hasNext!=`boolean`)return!1}if(t.status===`ok`&&t.entity===null||t.status!==`ok`&&t.rows.length>0||(t.status===`unset`||t.status===`unavailable`)&&t.entity!==null)return!1;for(let e of t.rows){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.id!=`string`||t.id===``)return!1;for(let e of[t.title,t.text,t.href])if(e!==null&&typeof e!=`string`)return!1;if(t.image!==null){if(typeof t.image!=`object`||Array.isArray(t.image))return!1;let e=t.image;if(typeof e.url!=`string`||e.alt!==null&&typeof e.alt!=`string`)return!1;for(let t of[e.width,e.height])if(t!==null&&typeof t!=`number`)return!1}}return!0}function Pe(e){if(!Number.isInteger(e)||e<0)throw Error(`content-api: collection allowance must be a non-negative integer, received ${String(e)}.`);let t=e,n=0;return{claim:()=>t===0?(n+=1,!1):(--t,!0),refusedCount:()=>n}}function G(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.resolved!==1||!Array.isArray(t.blocks))return!1;let n=t.links;if(typeof n!=`object`||!n||Array.isArray(n))return!1;for(let e of Object.values(n))if(e!==null&&typeof e!=`string`)return!1;let r=new Set,i=t.refs;if(i!==void 0){if(!Array.isArray(i))return!1;for(let e of i){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.entity!=`string`||t.entity===``||typeof t.id!=`string`||t.id===``)return!1;r.add(`${t.entity}\u0000${t.id}`)}}let a=t.collections;if(a!==void 0){if(typeof a!=`object`||!a||Array.isArray(a))return!1;let e=Object.entries(a);if(e.length>64)return!1;for(let[t,n]of e){if(t===``||!Ne(n))return!1;if(!(n.status!==`ok`||n.entity===null)){for(let e of n.rows)if(!r.has(`${n.entity}\u0000${e.id}`))return!1}}}let o=t.unresolved;if(o!==void 0){if(!Array.isArray(o))return!1;for(let e of o)if(!Fe(e))return!1}return!(t.live!==void 0&&!je(t.live)||t.currency!==void 0&&typeof t.currency!=`string`||t.detail!==void 0&&!V(t.detail))}function Fe(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.kind!==`media`&&t.kind!==`link`||typeof t.ref!=`string`?!1:t.reason===`unresolvable`||t.reason===`budget`}function Ie(e){return r(e).filter(e=>!e.internal).map(e=>e.name)}const Le=Object.freeze({resolved:1,blocks:Object.freeze([]),links:Object.freeze({})});async function Re(e,t,n){try{let r=await e(t,n.boundValues===void 0?n:{...n,boundValues:structuredClone(n.boundValues)});return G(r)?{ok:!0,envelope:r}:{ok:!1,failure:`malformed`}}catch(e){return{ok:!1,failure:`threw`,error:e}}}async function ze(e,t,n){let r=await Re(e,t,n);if(r.ok)return{envelope:r.envelope};let i=await Re(e,t,{...n,budget:Oe(0),claimCollection:void 0});return i.ok?{envelope:i.envelope,failure:r.failure,error:r.error}:{envelope:Le,failure:r.failure,retryFailure:i.failure,error:r.error??i.error}}async function Be(e,t,n){if(t.length===0)return;let r=n.resolveBlocks;if(!r)return;let a=Ie(e);if(a.length===0)return;let o=new Map;for(let t of a){let r;if(d(e,t)){if(n.siteOf===void 0)throw Error(`content-api: '${e.name}.${t}' declares siteTemplates but block resolution was given no siteOf to learn the row’s site`);r=await n.siteOf(e)}o.set(t,i(e,t,r))}let s=0,c=0,l=0,u,f,p=new Set,m=new Set,h=new Set;for(let i of t)for(let t of a){let a=i[t],d=o.get(t);if(d!==void 0&&!Object.hasOwn(i,t)||d===void 0&&a==null)continue;let g=await ze(r,d===void 0?a:[],{locale:n.locale,budget:n.budget,entity:e.name,field:t,...d!==void 0&&{template:d},boundValues:{...i},...n.canReadEntity!==void 0&&{canReadEntity:n.canReadEntity},...n.collectionAllowance!==void 0&&{claimCollection:n.collectionAllowance.claim},...n.page!==void 0&&{page:n.page}});if(g.failure===`threw`?(s+=1,p.add(t),u??=g.error):g.failure===`malformed`&&(c+=1,m.add(t)),g.retryFailure!==void 0&&(l+=1,h.add(t),f??=g.error,n.cacheTags?.markUncacheable()),i[t]=g.envelope,g.envelope.refs!==void 0)for(let e of g.envelope.refs)n.cacheTags?.addDocument(e.entity,e.id);if(g.envelope.collections!==void 0)for(let e of Object.values(g.envelope.collections))e.entity!==null&&n.cacheTags?.addCollection(e.entity)}s>0&&n.logger?.warn({entity:e.name,fields:[...p],rows:t.length,failures:s,err:u},`content-api: block resolver threw — no tree is served as stored; each was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them. Fields that failed that retry as well are reported separately, as empty.`),c>0&&n.logger?.warn({entity:e.name,fields:[...m],rows:t.length,failures:c},`content-api: block resolver returned a value that is not a ResolvedBlockTree — no tree is served as stored; each was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them. Fields that failed that retry as well are reported separately, as empty.`),l>0&&n.logger?.warn({entity:e.name,fields:[...h],rows:t.length,failures:l,err:f},`content-api: block resolver failed TWICE, including on the in-memory retry — those fields are served as an empty resolved tree, so that content is missing from the response. Serving the stored tree instead would put the media urls recorded when an editor picked them, which may be signed, on a cacheable anonymous response.`)}const Ve=`lumi`,He=128,Ue=128,We=3072,Ge=`media`,Ke=/^[A-Za-z0-9_.-]+$/,qe=`_`,Je={enabled:!0,header:`Cache-Tag`,separator:`,`},Ye=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Xe=[`cache-control`,`vary`,`content-type`],Ze=[`access-control-`];function Qe(e){if(e){if(e.enabled!==void 0&&typeof e.enabled!=`boolean`)throw Error(`content-api cache: \`cache.tags.enabled\` must be a boolean, received ${JSON.stringify(e.enabled)}.`);if(e.header!==void 0){if(typeof e.header!=`string`||!Ye.test(e.header))throw Error(`content-api cache: \`cache.tags.header\` must be a valid HTTP field name (RFC 9110 §5.1 token), received ${JSON.stringify(e.header)}. Common values: \`Cache-Tag\` (Cloudflare/Netlify, the default), \`Surrogate-Key\` (Fastly), \`Edge-Cache-Tag\` (Akamai).`);let t=e.header.toLowerCase();if(Xe.includes(t)||Ze.some(e=>t.startsWith(e)))throw Error(`content-api cache: \`cache.tags.header\` may not be ${JSON.stringify(e.header)} — this package writes that header itself on the same responses, so the tags would either overwrite it or be overwritten, silently and on every request.`)}if(e.separator!==void 0&&e.separator!==`,`&&e.separator!==` `)throw Error(`content-api cache: \`cache.tags.separator\` must be ',' or ' ', received ${JSON.stringify(e.separator)}. Cloudflare and Akamai parse comma-separated tags; Fastly parses space-separated ones. A third separator would not error at the CDN — it would parse as one giant unmatched key, which is the silent failure this refuses.`)}}function $e(e){return{enabled:e?.enabled??Je.enabled,header:e?.header??Je.header,separator:e?.separator??Je.separator}}function et(e){return typeof e==`string`&&e!==``&&Ke.test(e)}function tt(e,t){function n(e){if(t===void 0)return Ve;let n=t(e);return et(n)?`${Ve}:${n}`:void 0}let r=new Set,i=0,a=!1,o=e.header.length+4,s=!1;function c(e){if(r.has(e))return;if(e.length>128||r.size>=128){i+=1;return}let t=e.length+(r.size===0?0:1);if(s||o+t>3072){s=!0,i+=1;return}o+=t,r.add(e)}return{addDocument(e,t){if(!et(e)||!et(t)){i+=1;return}let r=n(e);if(r===void 0){i+=1;return}c(`${r}:${e}:${t}`)},addCollection(e){if(!et(e)){i+=1;return}let t=n(e);if(t===void 0){i+=1;return}c(`${t}:${e}`)},get tags(){return[...r]},markUncacheable(){a=!0},get dropped(){return i},get uncacheable(){return a},headers(){return!e.enabled||r.size===0?{}:{[e.header]:[...r].join(e.separator)}}}}const nt=`_template`;function rt(e){if(typeof e!=`string`)return;let t=e.trim();return t===``?void 0:t.slice(0,2e3)}async function it(e,t,n,r){let i={...t};for(let e of Object.keys(t))e!==`id`&&delete t[e];let a=n.detailTemplates;if(!a)return;let o=n.locale??n.defaultLocale;if(o===void 0)return;try{let n=await a.publicRow({entity:e.name,row:i,locale:o}),r=rt(n.title),s=rt(n.description);r!==void 0&&(t.title=r),s!==void 0&&(t.description=s)}catch(t){n.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to project a row — served with its id only`),n.cacheTags?.markUncacheable()}if(!r)return;let s=n.resolveBlocks;if(!s||(n.cacheTags?.addCollection(a.entity),n.budget.claim(`block`,1)<1))return;let c;try{c=await a.readTemplate({entity:e.name,locale:o})}catch(t){n.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to read the template — the row is served without one and the response is not cacheable`),n.cacheTags?.markUncacheable();return}if(c===null||typeof c.id!=`string`||!Array.isArray(c.blocks))return;n.cacheTags?.addDocument(a.entity,c.id);let l=await ze(s,c.blocks,{locale:n.locale,budget:n.budget,entity:e.name,field:nt,boundValues:i,rowIsForeign:!0,...n.canReadEntity!==void 0&&{canReadEntity:n.canReadEntity},...n.collectionAllowance!==void 0&&{claimCollection:n.collectionAllowance.claim},...n.page!==void 0&&{page:n.page}});l.failure!==void 0&&n.logger?.warn({entity:e.name,field:nt,failure:l.failure,retryFailure:l.retryFailure,err:l.error},`content-api: block resolver failed on a detail template — served re-resolved with an exhausted budget, or empty if that failed as well`),l.retryFailure!==void 0&&n.cacheTags?.markUncacheable(),at(l.envelope,n),t[nt]=l.envelope}function at(e,t){if(e.refs!==void 0)for(let n of e.refs)t.cacheTags?.addDocument(n.entity,n.id);if(e.collections!==void 0)for(let n of Object.values(e.collections))n.entity!==null&&t.cacheTags?.addCollection(n.entity)}function K(e){let t=Math.ceil(e/6);return{maxAge:t,swr:e-t}}const ot=[`defaultMaxAge`,`defaultStaleWhileRevalidate`,`maxAge`,`staleWhileRevalidate`];function st(e,t){if(e!==void 0&&(typeof e!=`number`||!Number.isInteger(e)||e<0))throw Error(`content-api cache: \`${t}.maxStaleSeconds\` must be a non-negative integer, received ${JSON.stringify(e)}. Use 0 for \`no-store\` if you need a published edit visible on the very next request.`)}function ct(e,t){for(let n of ot)if(n in e)throw Error(`content-api cache: \`${t}.${n}\` was removed (D036). Use \`maxStaleSeconds\` — ONE number naming the TOTAL staleness window in seconds. The old pair's real window was their SUM and nothing said so, which is the defect D036 exists to close: \`defaultMaxAge: 10\` bought a 310-second window, not a 10-second one. The max-age / stale-while-revalidate split is now derived, so what is emitted always sums to what you declared.`)}function lt(e){if(e){ct(e,`cache`),st(e.maxStaleSeconds,`cache`),Qe(e.tags);for(let[t,n]of Object.entries(e.entities??{})){if(!n)continue;let e=`cache.entities.${t}`;ct(n,e),st(n.maxStaleSeconds,e)}}}function ut(e,t){let n=t?.entities?.[e];return n?.cacheable===!1?0:n?.maxStaleSeconds??t?.maxStaleSeconds??360}function dt(e,t){let n=ut(e,t);if(n===0)return{"Cache-Control":`no-store`};let{maxAge:r,swr:i}=K(n);return{"Cache-Control":`public, max-age=${r}, stale-while-revalidate=${i}`}}const ft=[`Origin`];function pt(e,t){let n=new Set,r=[];for(let i of[...e?.split(`,`)??[],...ft,...t]){let e=i.trim();if(e===``)continue;let t=e.toLowerCase();n.has(t)||(n.add(t),r.push(e))}return r.join(`, `)}function q(e,t,n,r,i,a){let o=(n!==`identified`&&i.kind!==`undeclared`&&a?.uncacheable!==!0?dt(e,r):{"Cache-Control":`no-store`})[`Cache-Control`]??`no-store`,s={"Cache-Control":n===`site-keyed`?o.replace(/^public\b/,`private`):o};return{...t,...s,...s[`Cache-Control`]===`no-store`?{}:a?.headers(),Vary:pt(t.Vary,i.kind===`declared`?i.headers:[])}}function mt(e,t,n,r){let i=r?.uncacheable===!0?{"Cache-Control":`no-store`}:dt(e,n);return{...t,...i,...i[`Cache-Control`]===`no-store`?{}:r?.headers(),Vary:pt(void 0,[])}}function ht(e,t){return{...e,Vary:pt(e.Vary,t.kind===`declared`?t.headers:[])}}function gt(e,t){if(!t)return{};let n=e.headers.get(`Origin`);return n!==null&&t.allowedOrigins.includes(n)?{"Access-Control-Allow-Origin":n,"Access-Control-Allow-Methods":`GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Accept, Authorization`,"Access-Control-Max-Age":String(t.maxAge??3600),Vary:`Origin`}:{Vary:`Origin`}}function _t(e,t,n){let r={...gt(e,t),...dt(`_preflight`,n)};return new Response(null,{status:204,headers:r})}var vt=class extends Error{constructor(){super(`Service overloaded`),this.name=`ServiceOverloadedError`}},yt=class extends Error{constructor(){super(`Request deadline exceeded`),this.name=`RequestDeadlineError`}};function bt(e,t,n){if(e===void 0)return t;if(!Number.isInteger(e)||e<0)throw Error(`content-api limits: \`${n}\` must be a non-negative integer (got ${e})`);return e}function xt(e,t,n){if(e===void 0)return t;if(!Number.isInteger(e)||e<1)throw Error(`content-api limits: \`${n}\` must be a positive integer (got ${e})`);return e}function St(e){return{maxConcurrentRequests:xt(e?.maxConcurrentRequests,64,`maxConcurrentRequests`),maxQueuedRequests:bt(e?.maxQueuedRequests,128,`maxQueuedRequests`),requestTimeoutMs:xt(e?.requestTimeoutMs,1e4,`requestTimeoutMs`),anonymousTokensPerInstance:xt(e?.anonymousTokensPerInstance,120,`anonymousTokensPerInstance`),intervalMs:xt(e?.intervalMs,6e4,`intervalMs`),maxBudgetPerInstance:xt(e?.maxBudgetPerInstance,6e3,`maxBudgetPerInstance`)}}var Ct=class{semaphore;store;limits;getClientIp;constructor(e){this.getClientIp=e?.getClientIp,this.limits=St(e),this.semaphore=new ue(this.limits.maxConcurrentRequests,this.limits.maxQueuedRequests),this.store=e?.store??new F}async acquire(e){await this.semaphore.acquire(()=>new vt,e)}release(){this.semaphore.release()}async runGuarded(e){return await de(e,this.limits.requestTimeoutMs,()=>new yt)}consumeFairness(e,t,n){let r=this.resolveKey(e,t);if(r)return{decision:this.store.consume(r.key,{tokens:this.budgetFor(t),intervalMs:this.limits.intervalMs},n),keyClass:r.keyClass}}budgetFor(e){let t=e.budgetPerInstance??this.limits.anonymousTokensPerInstance;return Math.min(t,this.limits.maxBudgetPerInstance)}resolveKey(e,t){if(t.principalId!==void 0)return{key:`principal:${t.principalId}`,keyClass:`principal`};let n=this.getClientIp?.(e);if(n!==void 0&&n!==``)return{key:`ip:${n}`,keyClass:`client-ip`}}};function wt(e){let t=[];for(let[n,r]of Object.entries(e.allFields))r.type!==`media`||z(n,r)||t.push([n,r]);return t}async function Tt(e,t,n){if(t.length===0)return;let r=wt(e);if(r.length===0)return;let i=new Set;for(let e of t)for(let[t]of r){if(!Object.hasOwn(e,t))continue;let n=e[t];typeof n==`string`&&n!==``&&i.add(n)}let a=new Map;if(i.size>0&&n.resolveMedia){let t=[...i],r=n.budget.claim(`media`,t.length),o=t.slice(0,r);if(o.length>0)try{a=await n.resolveMedia(o,{locale:n.locale})}catch(t){n.logger?.warn({entity:e.name,err:t},"content-api: media resolver threw — media fields resolve to null (if this is a ForbiddenError, the requesting role is missing `media:view`)")}}else i.size>0&&n.logger?.debug({entity:e.name,mediaFields:r.map(([e])=>e)},"content-api: no `resolveMedia` provider wired — media fields resolve to null");for(let[e,t]of a)i.has(e)&&t?.id===e&&n.cacheTags?.addDocument(Ge,e);for(let e of t)for(let[t]of r){if(!Object.hasOwn(e,t))continue;let n=e[t];e[t]=typeof n==`string`?a.get(n)??null:null}}function Et(e){let t=[];for(let[n,r]of Object.entries(e.allFields))r.type!==`reference`||z(n,r)||t.push([n,r]);return t}function Dt(e){return typeof e==`string`&&e.length>0}function Ot(e,t){return t===`many`?Array.isArray(e)?e.filter(Dt):[]:Dt(e)?[e]:[]}async function kt(e,t,n,r,i=0){if(t.length===0)return;let a=Et(e);if(a.length===0)return;let o=new Map,s=[];for(let e of t)for(let[t,c]of a){if(!Object.hasOwn(e,t))continue;let a=Ot(e[t],c.cardinality),l=i===0&&n.has(t),u=r.reachableEntity(c.entity);if(!u||a.length===0){s.push({row:e,field:t,cardinality:c.cardinality,groupKey:null,ids:a});continue}let d=`${u.name}::${l?`full`:`projection`}`,f=o.get(d);f||(f={target:u,expand:l,ids:new Set},o.set(d,f));for(let e of a)f.ids.add(e);s.push({row:e,field:t,cardinality:c.cardinality,groupKey:d,ids:a})}let c=new Map;for(let[e,t]of o){let n=[...t.ids],a=r.budget.claim(t.expand?`populate`:`reference`,n.length),o=n.slice(0,a);if(o.length===0){c.set(e,new Map);continue}let s=l(t.target),u=m(t.target),d=u?r.templateDrawnTitle:void 0,f=t.expand||d!==void 0?void 0:u?[`id`]:At([`id`,s]),p=await r.readRowsByIds(t.target,o,f),h=new Map;if(t.expand){for(let e of p){let t=e.id;Dt(t)&&h.set(t,e)}await kt(t.target,p,new Set,r,i+1),await r.afterExpand?.(t.target,p)}else{let e=await jt(t.target.name,p,r);for(let[n,r]of p.entries()){let i=r.id;if(!Dt(i))continue;let a=u?await d?.(t.target,r)??null:r[s];h.set(i,{id:i,entityType:t.target.name,title:typeof a==`string`?a:null,href:e[n]??null})}}for(let e of h.keys())r.cacheTags?.addDocument(t.target.name,e);c.set(e,h)}for(let e of s){let t=e.groupKey===null?void 0:c.get(e.groupKey);if(e.cardinality===`many`){e.row[e.field]=e.ids.map(e=>t?.get(e)).filter(e=>e!==void 0);continue}let n=e.ids[0];e.row[e.field]=n===void 0?null:t?.get(n)??null}}function At(e){return[...new Set(e)]}async function jt(e,t,n){let r=n.resolveEntityHref;return r?O(t,async t=>{let i=t.id;if(!Dt(i))return null;try{return await r({entity:e,id:i,...n.locale!==void 0&&{locale:n.locale}})??null}catch(t){return n.logger?.debug({entity:e,id:i,err:t},`content-api: resolveEntityHref threw — reference resolves without an href`),null}}):t.map(()=>null)}const Mt=[`NOT_FOUND`,`VALIDATION_ERROR`,`INTERNAL_ERROR`,`RATE_LIMITED`,`SERVICE_OVERLOADED`];function J(e,t=200,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`,...n}})}const Nt={"Cache-Control":`no-store`},Pt=new WeakMap;function Ft(e){return Pt.get(e)}function Y(e,t,n,r){let i=J({error:{status:n,message:e,code:t}},n,{...r,...Nt});return Pt.set(i,t),i}function X(e){return Y(`Not found`,`NOT_FOUND`,404,e)}function It(e,t){return Y(`Rate limit exceeded`,`RATE_LIMITED`,429,{...t,"Retry-After":String(e)})}function Lt(e,t){return Y(`Service overloaded`,`SERVICE_OVERLOADED`,503,{...t,"Retry-After":String(e)})}const Rt=20,zt=50,Bt=k.object({q:k.string().max(200).refine(e=>pe(e).length>=2,{message:`q must be at least 2 characters`}),types:k.string().max(808).optional(),limit:k.coerce.number().int().min(1).default(20),locale:k.string().regex(g).optional()}).strict();function Vt(e){return u(e)===void 0||m(e)?!1:e.kind!==`singleton`}function Ht(e,t){if(t===void 0)return[...e];let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``);if(n.length===0)return null;for(let t of n)if(!e.includes(t))return null;return e.filter(e=>n.includes(e))}function Ut(e){for(let[t,n]of wt(e)){let e=n.accept;if(e===void 0||e.length===0||e.some(e=>e===`*/*`||e.startsWith(`image/`)))return t}return null}function Wt(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.url==`string`}function Gt(e){let t=e.admin?.labelSingular;if(typeof t==`string`&&t.trim()!==``)return t.trim();let n=e.name.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase();return n===``?e.name:`${n.charAt(0).toUpperCase()}${n.slice(1)}`}function Kt(e,t){if(typeof e!=`string`)return null;let n=e.replace(/\s+/g,` `).trim();return n===``?null:n.length>t?`${n.slice(0,t-1).trimEnd()}…`:n}const qt=[`summary`,`excerpt`,`description`,`intro`,`lead`],Jt=new Set([`text`]);function Yt(e,t,n){let r=null,i=e.allFields;for(let e of qt){let n=i[e];if(!(n===void 0||!Jt.has(n.type))&&(r=Kt(t[e],300),r!==null))break}let a=null,o=u(e);if(o)try{let e=o.projection({...t});r??=Kt(e.description,300),a=Kt(e.label,300)}catch{}return{title:Kt(t[n],300)??a??(typeof t.id==`string`?t.id:``),summary:r}}function Xt(e,t){let n=[];for(let r of[!0,!1]){let i=e.map(e=>e.hits.filter(e=>e.titleHit===r).map(e=>e.hit));for(let e=0;n.length<t;e++){let r=!1;for(let a of i){let i=a[e];if(i!==void 0&&(r=!0,n.push(i),n.length===t))break}if(!r)break}}return n}function Zt(e,t){let n=pe(t).toLocaleLowerCase();return n!==``&&e.toLocaleLowerCase().includes(n)}const Qt=`x-lumi-visitor-address`;function $t(e,t,n){if(e===void 0)return t;if(!Number.isSafeInteger(e)||e<1)throw Error(`content-api search: \`${n}\` must be a positive integer (got ${e})`);return e}var en=class{getClientIp;store;tokens;intervalMs;readVisitor=I({header:Qt,trustedProxyHops:1,surface:`content-api visitor search`});constructor(e,t){this.getClientIp=t,this.tokens=$t(e?.searchesPerVisitorPerInstance,30,`searchesPerVisitorPerInstance`),this.intervalMs=$t(e?.intervalMs,6e4,`intervalMs`),this.store=e?.store??new F}consume(e,t,n){let r=this.keyFor(e,t);if(r!==void 0)return{decision:this.store.consume(`search:${r.key}`,{tokens:this.tokens,intervalMs:this.intervalMs},n),keyClass:r.keyClass}}keyFor(e,t){if(t.principalId!==void 0)return{key:`principal:${t.principalId}`,keyClass:`principal`};if(t.site!==void 0){let n=this.readVisitor(e.headers);if(n!==null)return{key:`visitor:${t.site}:${n}`,keyClass:`visitor`}}if(t.site!==void 0)return;let n=this.getClientIp?.(e);if(n!==void 0&&n!==``)return{key:`ip:${n}`,keyClass:`client-ip`}}};const tn={referenceProjection:{fields:{id:`string`,entityType:`string`,title:`string`,href:`string`},nullableFields:[`title`,`href`],nullable:!0,arrayForCardinalityMany:!0},mediaProjection:{fields:{id:`string`,url:`string`,mimeType:`string`,width:`number`,height:`number`,alt:`string`,title:`string`,variants:`object`,sources:`object`,avifSources:`object`,focalPoint:`object`,blurDataUrl:`string`},nullableFields:[`mimeType`,`width`,`height`,`alt`,`title`,`blurDataUrl`],optionalFields:[`avifSources`],nullable:!0,arrayForCardinalityMany:!1}};function nn(e,t){let n={type:e.type};return e.required&&(n.required=!0),e.translatable&&(n.translatable=!0),e.type===`select`&&(n.options=e.options),e.type===`blockTree`&&(n.selectable=!1),e.type===`media`&&(n.wire=`mediaProjection`),e.type===`reference`&&(n.cardinality=e.cardinality,n.wire=`referenceProjection`,t(e.entity)&&(n.entity=e.entity,n.populatable=!0)),n}function rn(e,t){let n=e.allFields,r={},i=m(e);for(let[e,a]of Object.entries(n))z(e,a)||i&&e!==`id`||(r[e]=nn(a,t));let a=u(e);for(let e of a?.fields??[]){let t=r[e];t&&(t.searchable=!0)}return{name:e.name,pluralName:`${e.name}s`,kind:e.kind??`collection`,...i&&{drawnBy:`template`},fields:r}}const an={type:`string`},on={type:`string`},sn={type:`string`,maxLength:200,maxItems:5};function cn(e){let{maxLimit:t,maxOffset:n,hasResolution:r,hasMenus:i,hasChrome:a}=e,o=[{id:`list`,path:`/:entity`,data:`array`,entityKind:`collection`,params:{limit:{type:`number`,min:1,max:t,default:Math.min(20,t)},offset:{type:`number`,min:0,max:n,default:0},sort:{type:`string`},locale:an,fields:on,search:{type:`string`,maxLength:200,minLength:2},cursor:{type:`string`,maxLength:500},populate:sn,"filter[<field>]":{type:`string`}},meta:{total:{type:`number`,nullable:!0,suppressedBy:[`search`]},limit:{type:`number`},offset:{type:`number`},hasMore:{type:`boolean`},nextCursor:{type:`string`,optional:!0}}},{id:`singleton`,path:`/:entity`,data:`object`,entityKind:`singleton`,params:{locale:an,fields:on,populate:sn}},{id:`count`,path:`/:entity/count`,data:`object`,entityKind:`collection`,params:{locale:an}},{id:`byId`,path:`/:entity/:id`,data:`object`,entityKind:`collection`,params:{locale:an,fields:on,populate:sn}},{id:`bySlug`,path:`/:entity/slug/:slug`,data:`object`,entityKind:`collection`,params:{locale:an,fields:on,populate:sn}}];return r&&o.push({id:`resolve`,path:`/_resolve`,data:`object`,params:{path:{type:`string`,required:!0,maxLength:L},locale:{type:`string`,required:!0}}},{id:`paths`,path:`/_paths`,data:`array`,params:{locale:{type:`string`,required:!0},entity:{type:`string`,required:!0,maxLength:100},cursor:{type:`string`},limit:{type:`number`,min:1,max:t,default:Math.min(20,t)}},meta:{limit:{type:`number`},hasMore:{type:`boolean`},nextCursor:{type:`string`,optional:!0}}},{id:`alternates`,path:`/_alternates`,data:`array`,params:{entity:{type:`string`,required:!0,maxLength:100},id:{type:`string`,required:!0}}}),o.push({id:`site`,path:`/_site`,data:`object`,params:{}}),o.push({id:`search`,path:`/_search`,data:`array`,params:{q:{type:`string`,required:!0,minLength:2,maxLength:200},types:{type:`string`,maxLength:808},limit:{type:`number`,default:20,min:1,max:50},locale:{type:`string`}},meta:{limit:{type:`number`}}}),i&&o.push({id:`menu`,path:`/_menu`,data:`object`,params:{handle:{type:`string`,required:!0,maxLength:128},locale:{type:`string`,required:!0},currentPath:{type:`string`,maxLength:L}}}),a&&o.push({id:`chrome`,path:`/_chrome`,data:`object`,params:{locale:{type:`string`,required:!0},entity:{type:`string`,maxLength:100},id:{type:`string`}}}),o}function ln(e,t){if(!e.enabled)return null;let n=t?`${Ve}:{site}`:Ve;return{header:e.header,separator:e.separator,document:`${n}:{entity}:{id}`,collection:`${n}:{entity}`,sharedSite:t?`_`:null,maxTagLength:128,maxTagsPerResponse:128,maxHeaderBytes:We,uncovered:[`menuTargets`,`crossEntityPathChanges`,`mediaVariantStyles`,`outOfBandPathChanges`]}}function un(e){let{entities:t,checkPermission:n,version:r}=e,i={maxResolutionsPerDocument:e.maxResolutionsPerDocument,anonymousRequestsPerInstance:e.limits.anonymousTokensPerInstance,rateLimitWindowMs:e.limits.intervalMs,maxRequestsPerInstance:e.limits.maxBudgetPerInstance,maxConcurrentRequests:e.limits.maxConcurrentRequests,requestTimeoutMs:e.limits.requestTimeoutMs},a=t.filter(e=>n(e.name)),o=new Set(a.map(e=>e.name)),s=e=>o.has(e);return{version:r,surface:cn(e),envelopes:{dataKey:`data`,metaKey:`meta`,errorKey:`error`,errorCodes:Mt},limits:i,projections:tn,cacheTags:ln(e.cacheTags,e.siteScopedTags===!0),entities:a.map(e=>rn(e,s))}}const dn=`public`,fn=new Set;function pn(e){return typeof e==`string`&&e!==``}function mn(e){return Array.isArray(e)}const hn=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;function gn(e){let t=e.credentialHeaders;if(t!==void 0){if(!mn(t))throw Error(`content-api: \`credentialHeaders\` must be an array of HTTP header names, received ${JSON.stringify(t)}.`);for(let e of t)if(!pn(e)||e===`*`||!hn.test(e))throw Error(`content-api: \`credentialHeaders\` entry ${JSON.stringify(e)} is not a valid HTTP header name. Each entry is emitted verbatim in \`Vary\`, so it must be a bare field-name token (\`Cookie\`, \`Authorization\`, \`X-Preview-Token\`). \`*\` is refused: it means "never reuse this response", which is \`Cache-Control: no-store\` spelled obscurely — omit the option instead, which fails closed to exactly that.`)}if(!e.authenticate){if(t!==void 0&&t.length>0)throw Error("content-api: `credentialHeaders` was declared without an `authenticate` hook. This package parses no credential itself, so nothing reads those headers and listing them in `Vary` can only fragment a shared cache. Remove the option, or wire the `authenticate` hook it describes.");return{kind:`none`}}return t===void 0||t.length===0?{kind:`undeclared`}:{kind:`declared`,headers:t}}const _n=k.object({path:k.string().min(1).max(L),locale:k.string().regex(g)}).strict(),vn=k.object({locale:k.string().regex(g),entity:k.string().min(1).max(100),cursor:k.string().refine(e=>Se(e),`Invalid cursor`).optional(),limit:k.coerce.number().int().min(1).max(100).default(20)}).strict(),yn=k.object({entity:k.string().min(1).max(100),id:k.string().refine(e=>Se(e),`Invalid id`)}).strict(),bn=[`header`,`footer`],xn=k.object({locale:k.string().regex(g),entity:k.string().min(1).max(100).optional(),id:k.string().refine(e=>Se(e),`Invalid id`).optional()}).strict().refine(e=>e.entity===void 0==(e.id===void 0),`Both ?entity= and ?id= are required to name a document, or neither.`),Sn=k.object({}).strict();function Cn(e){return e instanceof n||e instanceof Error&&e.name===`SiteRequiredError`}const wn=k.object({handle:k.string().min(1).max(128),locale:k.string().regex(g),currentPath:k.string().min(1).max(L).optional()}).strict(),Tn=new Set([`_schema`,`_site`,`_resolve`,`_paths`,`_alternates`,`_menu`,`_chrome`,`_search`]),En=`v1`,Dn=/^v\d+$/;function On(e){let t=new Map;for(let n of e){let e=`${n.name}s`;if(Tn.has(n.name)||Tn.has(e))throw Error(`@murumets-ee/content-api: entity name "${n.name}" collides with a reserved route segment (${[...Tn].join(`, `)}). Rename the entity — its API surface would otherwise be permanently unreachable, shadowed by the special dispatch that runs before entity-whitelist resolution.`);if(Dn.test(n.name)||Dn.test(e))throw Error(`@murumets-ee/content-api: entity name "${n.name}" is a reserved API-version segment. Every route is served under a version prefix (this instance mounts /v1/), and the prefix is matched as a PATTERN ("v" followed by digits) so that a future /v2/ can never be shadowed by an entity added in the meantime. Rename the entity.`);if(n.scope!==void 0&&n.scope!==`global`)throw Error(`@murumets-ee/content-api: entity "${n.name}" declares scope "${n.scope}", which this surface cannot serve. The public read path resolves no scope for a caller, so QueryClient would apply NO scope filter and return every tenant's rows to every caller. Remove it from the content-api whitelist, or serve it through a surface that establishes a scope in the request context.`);t.set(n.name,n),t.set(e,n)}return t}function kn(e,n){let r=e[t];if(!r)throw Error(`site-bound '${n}' translations have no ${t} column`);return r}function Z(e){let t=ne.get(e);if(t)return{table:t,cols:M(t)}}const An=new Set([`text`,`richtext`,`slug`,`select`]);function jn(e,t,n){let r=u(e);if(!r)return;let i=t.trim();if(i.length===0)return;let o=Z(e.name);if(!o)return;let{cols:s}=o,l=[],d=`%${v(i)}%`,f=e.allFields,p=r.fields.filter(e=>{let t=Object.hasOwn(f,e)?f[e]:void 0;return t!==void 0&&An.has(t.type)&&!z(e,t)}),m=r.fts?.fields.some(e=>z(e,f[e]))??!1,h=fn;if(r.fts&&!m){let e=s._search_tsv;if(e){let t=r.fts.language??`simple`;l.push(P`${e} @@ websearch_to_tsquery(${t}, ${i})`),h=new Set(r.fts.fields)}}for(let e of p){if(h.has(e))continue;let t=s[e];t&&l.push(se(t,d))}let g=c(e.allFields,p),_=s.id;if(n!==void 0&&g.length>0&&_){let t=ne.get(`${e.name}_translations`);if(t){let e=a({idColumn:_,translationsTable:t,fields:g,locale:n,buildCondition:e=>se(e,d)});e&&l.push(e)}}if(l.length===0)return;let y=l[0];if(y)return l.length===1?y:le(y,...l.slice(1))}function Mn(e,t,n){let r=Z(e.name);if(!r)return[];let{cols:i}=r,a=e.allFields,o=t.trim(),s=`%${v(o)}%`,c=[],d=l(e),f=Object.hasOwn(a,d)?a[d]:void 0,p,m=i[d];if(m&&f!==void 0&&An.has(f.type)&&!z(d,f)){let t=n!==void 0&&f.translatable===!0?Z(`${e.name}_translations`):void 0,r=t?.cols[d],a=t?.cols.entityId,o=t?.cols.locale,c=i.id;p=t&&r&&a&&o&&c&&n!==void 0?P`COALESCE((SELECT ${r} FROM ${t.table} WHERE ${a} = ${c} AND ${o} = ${n} LIMIT 1), ${m}) ILIKE ${s}`:se(m,s)}p&&c.push(P`CASE WHEN ${p} THEN 0 ELSE 1 END`);let h=u(e),g=h?.fts?.fields.some(e=>z(e,a[e]))??!1,_=i._search_tsv;if(h?.fts&&!g&&_){let e=h.fts.language??`simple`;c.push(A(P`ts_rank(${_}, websearch_to_tsquery(${e}, ${o}))`))}let y=i.updatedAt;y&&c.push(A(y));let b=i.id;return b&&c.push(ae(b)),c}function Nn(e,t,n){let r=e.name;if(!t)return{orderBy:void 0};let i=t.startsWith(`-`),a=i?t.slice(1):t,o={orderBy:void 0,dropped:t};if(!Object.hasOwn(n,a))return o;let s=n[a];if(!s||s.type===`blockTree`||z(a,s)&&!p(e,a))return o;let c=Z(r);if(!c)return o;let l=c.cols[a];return l?{orderBy:i?A(l):ae(l),field:a}:o}function Pn(e,t,n){let r=[],i=[],a=Z(e);if(!a)return{conditions:r,dropped:i};let{cols:o}=a;for(let[e,a]of t.searchParams.entries()){let t=e.match(_e);if(!t)continue;let s=t[1];if(s===void 0)continue;if(!Object.hasOwn(n,s)){i.push(s);continue}let c=n[s];if(!c||c.type===`blockTree`){i.push(s);continue}if(z(s,c)){i.push(s);continue}let l=o[s];if(!l){i.push(s);continue}let u=Ce(c,a);if(u===null){i.push(s);continue}if(c.type===`date`&&typeof u==`string`){if(u.startsWith(`gte:`)){r.push(oe(l,u.slice(4)));continue}if(u.startsWith(`lte:`)){r.push(N(l,u.slice(4)));continue}}r.push(j(l,u))}return{conditions:r,dropped:i}}function Fn(e,t,n,r,i=!0){if(!(!i||t<=n))return Y(`?${e}=${t} exceeds the maximum of ${n}.${e===`offset`?` Use ?cursor= for deep pagination.`:``}`,`VALIDATION_ERROR`,400,r)}function In(e,t,n){return n?e:Math.min(e,t)}function Ln(e,t,{allowZero:n=!1}={}){if(t===void 0)return;let r=+!n;if(!Number.isInteger(t)||t<r)throw Error(`content-api: \`${e}\` must be an integer >= ${r}, received ${String(t)}. A ceiling below that does not tighten the bound, it removes it: the limit reaches the query layer falsy, no LIMIT clause is emitted, and the whole table is returned on a public route. If this came from an environment variable, it is probably unset.`)}function Q(e){return e.length<=256?e:`${e.slice(0,256)}…[truncated]`}const Rn=new WeakMap,zn=new WeakMap;function Bn(e){if(e.requestId)try{Rn.set(e,y().logger.child({requestId:e.requestId,...e.user?.id!==void 0&&{principalId:e.user.id}}))}catch{}}async function Vn(e,t){let n=b();if(!n)return{locales:[]};let r=e??await E(n).catch(()=>void 0);if(r===void 0)return{locales:[]};let i=await w(n,r);if(!i)return{locales:[]};let a=e=>e!==void 0&&(i.locales.length===0||i.locales.includes(e)),o=n.config.sites?.multiple===!0?i.defaultLocale:void 0,s=a(o)?o:a(t)?t:i.locales[0];return{locales:i.locales,...s!==void 0&&{defaultLocale:s}}}function $(){let e=x();return(e?Rn.get(e):void 0)??y().logger}function Hn(t){let{entities:n,defaultLocale:r,publicRole:i=`public`,cors:a,cache:c,onError:u,resolution:d,menus:g,chrome:v,site:k}=t,ne=new Map;for(let[e,n]of Object.entries(t.siteForHost??{})){if(!h(n))throw Error(`content-api: \`siteForHost['${e}']\` is ${JSON.stringify(n)}, which is not a site handle.`);ne.set(e.trim().toLowerCase(),n)}function ae(e){if(!e.multiSite)return;let t=b()?.entities;return n=>{let r=t?.get(n);return r!==void 0&&!f(r)?`_`:e.site??`_`}}let A=()=>{let e=x();return(e?zn.get(e):void 0)??r};Ln(`maxLimit`,t.maxLimit),Ln(`maxOffset`,t.maxOffset,{allowZero:!0}),lt(c);let M=$e(c?.tags);if(!pn(i))throw Error(`content-api: \`publicRole\` must be a non-empty string, received ${JSON.stringify(i)}. An empty public role matches no permission yet is not the anonymous role either, so every unauthenticated request reaches the read path with no groups and fails as a 500. If this came from an environment variable, it is probably unset — omit the option to get "public".`);let oe=Math.min(t.maxLimit??100,100),se=Math.min(t.maxOffset??1e3,1e3),N=gn(t),P=new Ct(t.limits),F=new en(t.search,t.search?.getClientIp??t.limits?.getClientIp);On(n);let ue;function I(){if(ue)return ue;let e=b(),t=n;if(e){t=[];for(let r of n){let n=e.entities.get(r.name);if(n===void 0){e.logger.error(`content-api: "${r.name}" is in createContentApiHandler({ entities }) but the app does not register an entity of that name — it is NOT served. Register it through lumi.config (entities or a plugin) or remove it from the whitelist.`);continue}t.push(n)}}let r={list:t,map:On(t)};return e&&(ue=r),r}if(Object.hasOwn(t,`exposeInternalFields`))throw Error("content-api: `exposeInternalFields` has been removed (plan/api D024). Its only sanctioned use was publishing `_overrides`, which D011 replaced by composing site chrome SERVER-side — so the field no longer needs to reach the wire, and no other internal field was ever safe to list (`_workflowStatus` and `_workflowAssignee` describe an editorial process and name a user; `_version`/`_versionedAt` expose revision cadence). Fetch composed chrome from `GET /_chrome` instead. Remove the option: it is refused rather than ignored, because silently dropping a field you configured is exactly the failure this package throws at construction to prevent.");let de=new Set(g?.handles??[]),fe=ke(t.maxResolutionsPerDocument),pe=new e(5e3),L=null,_e=0;async function ve(){let e=Date.now();return(!L||e-_e>3e4)&&(L=await t.loadPermissions(),_e=e),L}function ye(){L=null,_e=0}function be(){return{id:dn,role:i,hasIdentity:!1}}function xe(e){try{$().warn({err:e},"content-api: `authenticate` hook threw — serving the anonymous principal")}catch{console.warn("[content-api] `authenticate` hook threw:",e)}}async function Ce(e){if(!t.authenticate)return be();let n;try{n=await t.authenticate(e)}catch(e){return xe(e),be()}if(!n||!pn(n.role)||n.id!==void 0&&!pn(n.id)||n.name!==void 0&&typeof n.name!=`string`||n.email!==void 0&&typeof n.email!=`string`||n.site!==void 0&&!(typeof n.site==`string`&&h(n.site)))return be();let r=n.rateBudgetPerInstance!==void 0&&Number.isSafeInteger(n.rateBudgetPerInstance)&&n.rateBudgetPerInstance>=1;return{id:n.id??dn,hasIdentity:n.id!==void 0,role:n.role,...n.name!==void 0&&{name:n.name},...n.email!==void 0&&{email:n.email},...r&&{rateBudgetPerInstance:n.rateBudgetPerInstance},...n.site!==void 0&&{site:n.site}}}function Ee(e){if(ne.size===0)return;let t=(e.headers.get(`host`)??new URL(e.url).host).trim().toLowerCase();return ne.get(t)}async function De(e,t){let n=S();if(t.site!==void 0&&n!==void 0&&n!==t.site)return K({credentialSite:t.site,mountSite:n},`content-api: a credential bound to one site was presented to a mount running as another`),null;let r=t.site??n??Ee(e),i=b();if(!i)return{...r!==void 0&&{site:r},multiSite:!1};let a=i.config.sites?.multiple===!0,o=r??await E(i).catch(()=>void 0);if(o===void 0)return{multiSite:a};let s=await w(i,o);return r!==void 0&&(s===void 0||s.status!==`active`)?null:{...r!==void 0&&{site:r},...s!==void 0&&{record:s},multiSite:a}}async function Ae(e){let t=b(),n=t?.config.sites?.multiple===!0;if(!t||!n)return a;if(!e.headers.has(`Origin`))return a??{allowedOrigins:[]};try{let e=await C(t);return e.truncated&&at(`site-origin-index-truncated`,{listed:e.byOrigin.size},`content-api: the site registry holds more active sites than the origin index reads — some sites’ CORS preflights will be refused`),{allowedOrigins:[...new Set([...a?.allowedOrigins??[],...e.byOrigin.keys()])],...a?.maxAge!==void 0&&{maxAge:a.maxAge}}}catch(e){return K({err:e},`content-api: could not read site origins for CORS`),a}}function B(e){return e.hasIdentity||e.role!==i?`identified`:e.site===void 0?`anonymous`:`site-keyed`}function V(e,t,n){return e(t,n,`view`)}function H(e){let t=y();return new re({entity:e,db:t.db.readOnly,logger:$().child({entity:e.name}),countCache:pe,contextResolver:()=>{let e=x();if(!(!e?.user||!e?.checker))return{user:e.user,checker:e.checker,...e.scope!==void 0&&{scope:e.scope},...te(e,t)}}})}function U(e,n,i,a){let o={budget:Oe(fe),cacheTags:a,resolveMedia:t.resolveMedia,resolveBlocks:t.resolveBlocks,siteOf:e=>T(e),afterExpand:async(e,t)=>{if(m(e)){for(let n of t)await it(e,n,Ne(o),!1);return}await Tt(e,t,o),await Be(e,t,o)},locale:i,reachableEntity:t=>{let r=I().map.get(t);if(!(!r||r.name!==t))return V(e,n,r.name)?r:void 0},canReadEntity:t=>{let r=I().map.get(t);return r!==void 0&&r.name===t&&V(e,n,t)},collectionAllowance:Pe(12),templateDrawnTitle:async(e,n)=>{let s=t.detailTemplates,c=i??r;if(!s||c===void 0)return null;try{let t=await s.publicRow({entity:e.name,row:n,locale:c}),r=typeof t.title==`string`?t.title.trim():``;return r===``?null:r.slice(0,2e3)}catch(t){return o.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to project a reference title`),a.markUncacheable(),null}},readRowsByIds:async(e,t,n)=>{let a=Z(e.name)?.cols.id;return!a||t.length===0||fe===0?[]:await H(e).findMany({where:ce(a,[...t]),limit:Math.min(t.length,fe),...n!==void 0&&{select:[...n]},...i!==void 0&&{locale:i},defaultLocale:r})},resolveEntityHref:t.resolveEntityHref,logger:W()};return o}function W(){try{return $()}catch{return}}function je(e,t,n){let r=e.collectionAllowance?.refusedCount()??0;if(r>0)try{$().warn({entity:t,path:Q(n),cap:12,refused:r},`content-api: per-response collection cap reached — the collection blocks past it rendered empty`)}catch{console.warn(`[content-api] collection cap reached for`,t,Q(n))}if(e.budget.hasDrops)try{$().warn({entity:t,path:Q(n),ceiling:e.budget.ceiling,resolved:e.budget.granted,dropped:e.budget.dropSummary()},`content-api: per-document resolution budget exhausted — response rendered with unresolved targets`)}catch{console.warn(`[content-api] resolution budget exhausted for`,t,Q(n))}}function Me(e,t,n,r){let i=Te(e,n);return i.requested>5?{response:Y(`?populate= names ${i.requested} fields, which exceeds the maximum of 5.`,`VALIDATION_ERROR`,400,r)}:(i.dropped.length>0&&W()?.debug({entity:t.name,droppedPopulate:i.dropped},`content-api: rejected ?populate= fields (unknown, internal, or not a reference)`),{fields:new Set(i.fields)})}function Ne(e){return{...e,detailTemplates:t.detailTemplates,defaultLocale:r}}async function G(e,t,n,r,i){await kt(e,t,n,r),await Tt(e,t,r),await Be(e,t,r),je(r,e.name,i)}async function Fe(e,t,n,i,a,l){let u=new URL(e.url),d=me.safeParse(R(u,{allowFilters:!0}));if(!d.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let{limit:f,offset:m,sort:h,locale:g,fields:_,search:v,cursor:y,populate:b}=d.data,x=u.searchParams.has(`limit`),S=Fn(`limit`,f,oe,a,x);if(S)return S;let C=Fn(`offset`,m,se,a);if(C)return C;let w=In(f,oe,x),T=t.allFields,E=Me(b,t,T,a);if(`response`in E)return E.response;let D;if(y){let e=o(y);if(!e)return Y(`Invalid cursor`,`VALIDATION_ERROR`,400,a);if(!Object.hasOwn(T,e.field)&&e.field!==`id`||e.field!==`id`&&z(e.field,T[e.field]))return Y(`Invalid cursor field`,`VALIDATION_ERROR`,400,a);D=e}let O=[],ee=!1;if(v){let e=jn(t,v,g??A());e&&(O.push(e),ee=!0)}let te=Pn(t.name,u,T);O.push(...te.conditions);let k=Nn(t,h,T),ne=k.orderBy;if(D!==void 0&&k.field!==void 0&&p(t,k.field))return Y(`Invalid cursor for this sort`,`VALIDATION_ERROR`,400,a);let re=we(_,T);if(te.dropped.length>0||k.dropped!==void 0){let e=[...new Set(te.dropped)],n=e.slice(0,20).map(Q);$().info({entity:t.name,...te.dropped.length>0&&{droppedFilters:n,...e.length>n.length&&{droppedFiltersOmitted:e.length-n.length}},...k.dropped!==void 0&&{droppedSort:Q(k.dropped)}},`content-api: rejected query params (unknown, internal, or invalid)`)}let ae=H(t),j=g??A(),M=ee,ce={where:O.length>0?ie(...O):void 0,limit:M?w+1:w,offset:m,orderBy:ne,select:re,locale:j,defaultLocale:r,cursor:D},[le,P]=await Promise.all([ae.findMany(ce),M?Promise.resolve(null):ae.count({where:O.length>0?ie(...O):void 0,locale:j})]),F=M&&le.length>w?le.slice(0,w):le,ue=M?le.length>w:m+w<(P??0),I;if(F.length>0&&F.length===w){let e=F[F.length-1],t=D?.field??k.field,n=D?.direction??(h?.startsWith(`-`)?`desc`:`asc`);t&&e[t]!==void 0&&(I=s(e,t,n))}l.addCollection(t.name);for(let e of F)l.addDocument(t.name,e.id);let de=U(i,n.role,j,l);return await G(t,F,E.fields,de,u.pathname),J({data:F,meta:{total:P,limit:w,offset:m,hasMore:ue,nextCursor:I}},200,q(t.name,a,B(n),c,N,l))}async function Ie(e,t,n,r,i){let a=new URL(e.url),o=ge.safeParse(R(a));if(!o.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let s=await H(t).count({locale:o.data.locale??A()});return i.addCollection(t.name),J({data:{count:s}},200,q(t.name,r,B(n),c,N,i))}async function Le(e,t,n,i,a,o,s){if(!Se(n))return X(o);let l=new URL(e.url),u=he.safeParse(R(l));if(!u.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let{locale:d,fields:f,populate:p,page:h}=u.data,g=t.allFields,_=m(t)?void 0:we(f,g),v=d??A(),y=Me(p,t,g,o);if(`response`in y)return y.response;let b=await H(t).findById(n,{..._!==void 0&&{select:_},...v!==void 0&&{locale:v},defaultLocale:r});if(!b)return X(o);s.addDocument(t.name,n);let x={...U(a,i.role,v,s),...h!==void 0&&h>1&&{page:h}};return m(t)?(await it(t,b,Ne(x),!0),je(x,t.name,l.pathname)):await G(t,[b],y.fields,x,l.pathname),J({data:b},200,q(t.name,o,B(i),c,N,s))}async function Re(e,t,n,i,a,o,s){let l=new URL(e.url),u=he.safeParse(R(l));if(!u.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let d=t.allFields;if(!d.slug)return X(o);let{locale:f,fields:p,populate:m,page:h}=u.data,g=we(p,d),_=f??A(),v=Me(m,t,d,o);if(`response`in v)return v.response;let b=Z(t.name);if(!b)return X(o);let x=b.cols.slug,S=b.cols.id;if(!x||!S)return X(o);let C=H(t),w=d.slug,E=j(x,n);if(w.translatable&&_){let e=Z(`${t.name}_translations`);if(e){let r=e.cols.slug,i=e.cols.locale,a=e.cols.entityId;if(r&&i&&a){let o=y(),s=await T(t,o),c=ie(j(r,n),j(i,_)),l=await o.db.readOnly.select({entityId:a}).from(e.table).where(s===void 0?c:ie(c,j(kn(e.cols,t.name),s)));l.length>0&&(E=le(ce(S,l.map(e=>e.entityId)),j(x,n))??j(x,n))}}}let D=await C.findMany({where:E,limit:1,select:g,locale:_,defaultLocale:r});if(D.length===0)return X(o);s.addCollection(t.name),s.addDocument(t.name,D[0]?.id);let O={...U(a,i.role,_,s),...h!==void 0&&h>1&&{page:h}};return await G(t,D,v.fields,O,l.pathname),J({data:D[0]},200,q(t.name,o,B(i),c,N,s))}async function Ve(e,t,n,i,a,o){let s=new URL(e.url),l=he.safeParse(R(s));if(!l.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let{locale:u,fields:d,populate:f,page:p}=l.data,m=t.allFields,h=we(d,m),g=u??A(),_=Me(f,t,m,a);if(`response`in _)return _.response;let v=(await H(t).findMany({limit:1,select:h,locale:g,defaultLocale:r}))[0];if(!v)return X(a);o.addCollection(t.name),o.addDocument(t.name,v.id);let y={...U(i,n.role,g,o),...p!==void 0&&p>1&&{page:p}};return await G(t,[v],_.fields,y,s.pathname),J({data:v},200,q(t.name,a,B(n),c,N,o))}function He(e){return I().map.get(e)??I().map.get(e.endsWith(`s`)?e.slice(0,-1):e)}function Ue(e,t){if(process.env.NODE_ENV!==`development`)return;let n=JSON.stringify(e.slice(0,100)),r=t===void 0?`${n} is not in the content-api whitelist — add it to createContentApiHandler({ entities: [...] }) in your content route.`:`"${t.name}" is whitelisted but the requesting role lacks 'view' — grant it in the Permission Matrix, or seed it. Note that entity.access.view is advisory metadata the firewall never reads, so a restrictive value there is not the cause.`;console.warn(`[content-api] 404 for ${n}: ${r} (Both refusals are 404 by design — this line is the server-side disambiguation, and the response is unchanged.)`)}async function Ge(e,t,n,r,i){if(!d)return X(r);let a=new URL(e.url),o=_n.safeParse(R(a));if(!o.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{path:s,locale:l}=o.data,u=await d.resolvePath(s,l);if(u.kind===`none`)return X(r);if(u.kind===`redirect`)return J({data:u},200,{...r,"Cache-Control":`no-store`});let f=He(u.entityType);return!f||!V(n,t.role,f.name)?(Ue(u.entityType,f),X(r)):(i.addCollection(f.name),i.addDocument(f.name,u.id),J({data:u},200,q(f.name,r,B(t),c,N,i)))}async function Ke(e,t,n,r,i){if(!d)return X(r);let a=new URL(e.url),o=vn.safeParse(R(a));if(!o.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{locale:s,entity:l,cursor:u,limit:f}=o.data,p=a.searchParams.has(`limit`),m=Fn(`limit`,f,oe,r,p);if(m)return m;let h=In(f,oe,p),g=He(l);if(!g||!V(n,t.role,g.name))return Ue(l,g),X(r);let _=d.enumeratePaths({locale:s,entityType:g.name,...u!==void 0&&{afterDocumentId:u}}),v=[];for await(let e of _)if(v.push(e),v.length===h)break;let y=v.length===h,b=y?v[v.length-1]?.id:void 0;i.addCollection(g.name);for(let e of v)i.addDocument(g.name,e.id);return J({data:v,meta:{limit:h,hasMore:y,nextCursor:b}},200,q(g.name,r,B(t),c,N,i))}async function qe(e,t,n,r,i){if(!d)return X(r);let a=new URL(e.url),o=yn.safeParse(R(a));if(!o.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{entity:s,id:l}=o.data,u=He(s);if(!u||!V(n,t.role,u.name))return Ue(s,u),X(r);let f=x()?.availableLocales,p=await d.getAlternates(u.name,l),m=f?p.filter(e=>f.includes(e.locale)):p;return i.addCollection(u.name),i.addDocument(u.name,l),J({data:m},200,q(u.name,r,B(t),c,N,i))}async function Je(e,t,n,r){if(!g)return X(n);let i=new URL(e.url),a=wn.safeParse(R(i));if(!a.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,n);let{handle:o,locale:s,currentPath:l}=a.data;if(!de.has(o))return X(n);let u=await g.getMenu(o,{locale:s,...l!==void 0&&{currentPath:l}});return u?(r.addDocument(`_menu`,o),J({data:u},200,t.site===void 0?mt(`_menu`,n,c,r):q(`_menu`,n,B(t),c,N,r))):X(n)}async function Ye(e,t,n,r,i,a){if(!Sn.safeParse(R(new URL(e.url))).success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,i);let o=n.record;if(!o)return X(i);let s=await k?.getI18n(o.handle);if((s?.locales??o.locales).length===0)return at(`site-i18n-unwired:${o.handle}`,{site:o.handle},"content-api: GET /_site cannot answer — this site serves every enabled locale and the mount wires no `site.getI18n` to say which those are. Wire it (see the content route the admin app ships), or give the site an explicit locale list."),X(i);let l=s?.locales??o.locales,u=s?.defaultLocale??r.defaultLocale??l[0];if(u===void 0)return X(i);let d={handle:o.handle,name:o.name,locales:l.length>0?[...l]:[u],defaultLocale:u,routingStrategy:s?.routingStrategy??o.routingStrategy??`no-prefix-default`,origins:[...o.origins]};return a.addDocument(`_site`,o.handle),J({data:d},200,q(`_site`,i,B(t),c,N,a))}async function Xe(e,n,i,a,o,s){let u=F.consume(e,{principalId:n.hasIdentity?n.id:void 0,site:n.site});if(u&&!u.decision.allowed)return K({limit:`search`,keyClass:u.keyClass},`content-api: caller exceeded its visitor-search budget`),It(u.decision.retryAfterSeconds,o);let d=new URL(e.url),f=Bt.safeParse(R(d));if(!f.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let{q:p,types:m,limit:h,locale:g}=f.data,_=Fn(`limit`,h,50,o);if(_)return _;let v=Ht(a.record?.searchTypes??[],m);if(v===null||v.length===0)return X(o);let y=[];for(let e of v){let t=I().map.get(e);if(t!==void 0&&t.name===e&&V(i,n.role,e)&&Vt(t)){y.push(t);continue}if(Ue(e,t),m!==void 0)return X(o);at(`search-type:${a.site??``}:${e}`,{site:a.site,type:e},`content-api: a type in the site's searchTypes cannot be searched by this caller — it is skipped`)}if(y.length===0)return X(o);let b=g??A(),x=[];for(let e of y){s.addCollection(e.name);let t=jn(e,p,b);if(!t)continue;let n=await H(e).findMany({where:t,limit:h,orderBy:Mn(e,p,b),locale:b,defaultLocale:r}),i=l(e),a=Object.hasOwn(e.allFields,i)?e.allFields[i]:void 0,o=a!==void 0&&An.has(a.type),c=[];for(let t of n){let n=t.id;if(typeof n!=`string`)continue;let{title:r,summary:a}=Yt(e,t,i),s=t[i];c.push({hit:{entity:e,row:t,id:n,title:r,summary:a},titleHit:o&&typeof s==`string`&&Zt(s,p)})}c.length>0&&x.push({hits:c})}let S=Xt(x,h),C=U(i,n.role,b,s);for(let e of S)s.addDocument(e.entity.name,e.id);let w=new Map;for(let e of y){let t=S.filter(t=>t.entity===e);if(t.length===0)continue;let n=Ut(e);if(n===null)continue;let r=t.map(e=>({id:e.id,[n]:e.row[n]}));await Tt(e,r,C),t.forEach((e,t)=>{w.set(e,r[t]?.[n]??null)})}let T=t.resolveEntityHref,E=await O(S,async e=>{if(!T)return null;try{return await T({entity:e.entity.name,id:e.id,...b!==void 0&&{locale:b}})??null}catch(t){return $().debug({entity:e.entity.name,id:e.id,err:t},`content-api: resolveEntityHref threw — search result served without a path`),null}});return je(C,`_search`,d.pathname),J({data:S.map((e,t)=>{let n=w.get(e);return{type:e.entity.name,typeLabel:Gt(e.entity),id:e.id,title:e.title,summary:e.summary,image:Wt(n)?n:null,path:E[t]??null}}),meta:{limit:h}},200,q(`_search`,o,B(n),c,N,s))}async function Ze(e,n,r,i,a){if(!v)return X(i);let o=new URL(e.url),s=xn.safeParse(R(o));if(!s.success)return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,i);let{locale:l,entity:u,id:d}=s.data;if(!V(r,n.role,v.entity))return X(i);let f;if(u!==void 0&&d!==void 0){let e=He(u);e&&V(r,n.role,e.name)?f={entityType:e.name,id:d}:W()?.debug({entity:u,locale:l},`content-api: _chrome document is unreachable for this caller — serving the site default`)}a.addCollection(v.entity),f!==void 0&&a.addDocument(f.entityType,f.id);let p=U(r,n.role,l,a),m=await v.getChrome({locale:l,...f!==void 0&&{document:f},budget:p.budget}),h=e=>e&&typeof e==`object`?{blocks:Array.isArray(e.blocks)?e.blocks:[],overridden:e.overridden===!0}:null,g=async(e,n)=>{if(n===null||!t.resolveBlocks||n.blocks.length===0)return n;let r=await ze(t.resolveBlocks,n.blocks,{locale:l,budget:p.budget,entity:v.entity,field:e,...p.canReadEntity!==void 0&&{canReadEntity:p.canReadEntity},...p.collectionAllowance!==void 0&&{claimCollection:p.collectionAllowance.claim}});r.failure===`threw`?W()?.warn({entity:v.entity,region:e,err:r.error},`content-api: block resolver threw — this chrome region is not served as stored; it was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them`):r.failure===`malformed`&&W()?.warn({entity:v.entity,region:e},`content-api: block resolver returned a value that is not a ResolvedBlockTree — this chrome region is not served as stored; it was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them`),r.retryFailure!==void 0&&(a.markUncacheable(),W()?.warn({entity:v.entity,region:e,err:r.error},`content-api: block resolver failed TWICE, including on the in-memory retry — serving this chrome region EMPTY, so whatever it held is missing from every page render. Serving the stored region instead would put the media urls recorded when an editor picked them, which may be signed, on a cacheable anonymous response`));let i=r.envelope;if(i.refs!==void 0)for(let e of i.refs)a.addDocument(e.entity,e.id);if(i.collections!==void 0)for(let e of Object.values(i.collections))e.entity!==null&&a.addCollection(e.entity);return{blocks:[...i.blocks],overridden:n.overridden,resolved:i.resolved,links:i.links,...i.unresolved!==void 0&&i.unresolved.length>0&&{unresolved:i.unresolved},...i.refs!==void 0&&i.refs.length>0&&{refs:i.refs},...i.collections!==void 0&&{collections:i.collections},...i.live!==void 0&&{live:i.live},...i.currency!==void 0&&{currency:i.currency}}},_={};for(let e of bn)_[e]=await g(e,h(m?.[e]));let y={header:_.header??null,footer:_.footer??null};return je(p,v.entity,o.pathname),J({data:y},200,q(v.entity,i,B(n),c,N,a))}async function Qe(e,t){let n=D(e),r={},i=S(),a={requestId:n,...i!==void 0&&{site:i}};return Bn(a),await ee(a,async()=>{let i=await st(e,t,n,r);return et(i,n),nt(i,e,n,r),i})}function et(e,t){(e.headers.get(`Cache-Control`)??``).includes(`no-store`)&&e.headers.set(_,t)}function nt(e,t,n,r){if(!u||e.status<400)return;let i=Ft(e);if(i!==void 0)try{Promise.resolve(u({status:e.status,code:i,path:Q(new URL(t.url).pathname),...r.entity!==void 0&&{entity:r.entity},requestId:n,...r.principalId!==void 0&&{principalId:r.principalId}})).catch(ot)}catch(e){ot(e)}}let rt=new Set;function at(e,t,n){rt.has(e)||(rt.add(e),K(t,n))}function K(e,t){try{$().warn(e,t)}catch{try{console.warn(`[content-api]`,t,e)}catch{}}}function ot(e){try{$().warn({err:e},"content-api: `onError` monitoring hook failed")}catch{}}async function st(e,t,n,r){let i=gt(e,await Ae(e)),a=ht(i,N);try{await P.acquire(e.signal)}catch(e){return e instanceof vt?(K({limit:`survival`,maxConcurrentRequests:P.limits.maxConcurrentRequests,maxQueuedRequests:P.limits.maxQueuedRequests},`content-api: shedding load — concurrency slots and wait queue both full`),Lt(1,a)):(K({err:e},`content-api: acquiring a concurrency slot failed`),Y(`Internal server error`,`INTERNAL_ERROR`,500,a))}try{return await P.runGuarded(a=>ct(e,t,n,r,i,a))}catch(e){if(e instanceof yt)return K({limit:`deadline`,requestTimeoutMs:P.limits.requestTimeoutMs},`content-api: request exceeded the wall clock`),Lt(1,a);throw e}finally{P.release()}}async function ct(e,t,n,i,o,s){let c=o;try{let l=t.path;if(!l||l.length===0||l[0]!==`v1`)return X(o);let u=l.slice(1);if(u.length===0)return X(o);if(new URL(e.url).searchParams.has(`site`))return Y(`Invalid query parameters`,`VALIDATION_ERROR`,400,ht(o,N));let f=await Ce(e),p=f.role,h=await De(e,f);if(h===null)return X(ht(a?{Vary:`Origin`}:{},N));let _=h.multiSite?gt(e,{allowedOrigins:h.record?.origins??[],...a?.maxAge!==void 0&&{maxAge:a.maxAge}}):o,y=P.consumeFairness(e,{principalId:f.hasIdentity?f.id:void 0,budgetPerInstance:f.rateBudgetPerInstance}),b=ht(_,N);c=b;let x=tt(M,ae(h));if(y&&!y.decision.allowed)return K({limit:`fairness`,keyClass:y.keyClass},`content-api: caller exceeded its per-instance budget`),It(y.decision.retryAfterSeconds,b);let S=await ve();i.principalId=f.id;let C=h.site,w=await Vn(C,r),T=new URL(e.url).searchParams.get(`locale`);if(T!==null&&T!==``&&w.locales.length>0&&!w.locales.includes(T))return Y(`Locale '${T}' is not served by this site`,`VALIDATION_ERROR`,400,b);let E={user:{id:f.id,groups:p?[p]:[],...f.name!==void 0&&{name:f.name},...f.email!==void 0&&{email:f.email}},checker:S,requestId:n,...C!==void 0&&{site:C},...w.locales.length>0&&{availableLocales:w.locales}};w.defaultLocale!==void 0&&zn.set(E,w.defaultLocale),Bn(E);let D=await ee(E,async()=>{if(s?.aborted)throw new yt;if(u[0]===`_schema`)return J(un({entities:I().list,checkPermission:e=>V(S,p,e),version:`v1`,maxLimit:oe,maxOffset:se,maxResolutionsPerDocument:fe,limits:P.limits,hasResolution:d!==void 0,hasMenus:g!==void 0,hasChrome:v!==void 0,cacheTags:M,siteScopedTags:h.multiSite}),200,{...b,"Cache-Control":`no-store`});if(u[0]===`_resolve`)return Ge(e,f,S,b,x);if(u[0]===`_paths`)return Ke(e,f,S,b,x);if(u[0]===`_alternates`)return qe(e,f,S,b,x);if(u[0]===`_menu`)return Je(e,f,b,x);if(u[0]===`_site`)return Ye(e,f,h,w,b,x);if(u[0]===`_chrome`)return Ze(e,f,S,b,x);if(u[0]===`_search`&&u.length===1)return Xe(e,f,S,h,b,x);let t=u[0];if(t===void 0)return X(b);let n=He(t);if(!n||!V(S,p,n.name))return Ue(t,n),X(b);if(i.entity=n.name,n.kind===`singleton`)return u.length===1?Ve(e,n,f,S,b,x):X(b);if(m(n)){let t=u[1];return u.length===2&&t!==void 0?Le(e,n,t,f,S,b,x):X(b)}return u.length===1?Fe(e,n,f,S,b,x):u[1]===`count`?Ie(e,n,f,b,x):u[1]===`slug`&&u[2]?Re(e,n,u[2],f,S,b,x):u.length===2&&u[1]!==void 0?Le(e,n,u[1],f,S,b,x):X(b)});return x.dropped>0&&D.headers.has(M.header)&&K({dropped:x.dropped,emitted:x.tags.length,maxTags:128,maxHeaderBytes:We,...i.entity!==void 0&&{entity:i.entity},path:Q(new URL(e.url).pathname)},`content-api: cache tags refused — this response depends on documents it does not name, so a purge for them will not invalidate it`),D}catch(t){if(t instanceof yt)throw t;if(Cn(t))return X(c);let n=new URL(e.url).pathname;try{$().error({err:t,path:Q(n)},`content-api handler error`)}catch{console.error(`[content-api] handler error:`,t)}return Y(`Internal server error`,`INTERNAL_ERROR`,500,c)}}return{GET:(e,t)=>Qe(e,t),OPTIONS:async e=>_t(e,await Ae(e),c),invalidatePermissionCache:ye}}export{En as API_VERSION,Ve as CACHE_TAG_NAMESPACE,Rt as DEFAULT_SEARCH_RESULTS,nt as DETAIL_TEMPLATE_FIELD,Mt as ERROR_CODES,Ue as MAX_CACHE_TAGS_PER_RESPONSE,We as MAX_CACHE_TAG_HEADER_BYTES,He as MAX_CACHE_TAG_LENGTH,De as MAX_RESOLUTIONS_PER_DOCUMENT,zt as MAX_SEARCH_RESULTS,Ge as MEDIA_TAG_ENTITY,qe as SHARED_SITE_TAG_SEGMENT,Qt as VISITOR_ADDRESS_HEADER,Hn as createContentApiHandler,G as isResolvedBlockTree};
|
|
1
|
+
import{CountCache as e,SITE_COLUMN as t,SiteRequiredError as n,blockTreeFieldsOf as r,blockTreeTemplateOf as i,buildTranslationsSearchExists as a,decodeCursor as o,encodeCursor as s,filterTranslatableFields as c,getEntityTitleField as l,getSearchableConfig as u,hasSiteTemplates as d,isSiteBound as f,isSortOnlyInternalField as p,isTemplateDrawn as m,isValidSiteHandle as h}from"@murumets-ee/entity";import{LOCALE_PATTERN as g,REQUEST_ID_HEADER as _,escapeLikePattern as v,getApp as y,getAppOrUndefined as b,getContext as x,getCurrentSite as S,readSiteOriginIndex as C,readSiteRecord as w,requireSiteFor as T,resolveImplicitSite as E,resolveRequestId as D,runBounded as O,runWithContextAsync as ee,siteSecurityFields as te}from"@murumets-ee/core";import{z as k}from"zod";import{InMemoryRateLimitStore as ne,Semaphore as re,createClientIpResolver as ie,runWithDeadline as A}from"@murumets-ee/core/limits";import{schemaRegistry as j}from"@murumets-ee/db";import{QueryClient as ae}from"@murumets-ee/entity/query";import{and as oe,asc as se,desc as ce,eq as M,getTableColumns as N,gte as P,ilike as le,inArray as F,lte as ue,or as de,sql as I}from"drizzle-orm";const fe=/[\u200B-\u200D\u2060\uFEFF]/g;function L(e){return e.replace(fe,``).trim()}const pe=2048,me=k.object({limit:k.coerce.number().int().min(1).max(100).default(20),offset:k.coerce.number().int().min(0).default(0),sort:k.string().regex(/^-?[a-zA-Z_]+$/).optional(),locale:k.string().regex(g).optional(),fields:k.string().optional(),search:k.string().max(200).refine(e=>{let t=L(e);return t.length===0||t.length>=2},{message:`search must be at least 2 characters`}).optional(),cursor:k.string().max(500).optional(),populate:k.string().max(200).optional()}).strict(),he=k.object({locale:k.string().regex(g).optional(),fields:k.string().optional(),populate:k.string().max(200).optional(),page:k.string().regex(/^(?:[1-9][0-9]?|100)$/).transform(Number).optional()}).strict(),ge=k.object({locale:k.string().regex(g).optional()}).strict(),_e=/^filter\[([a-zA-Z0-9_]+)\]$/;function R(e,t){let n={};for(let[r,i]of e.searchParams.entries())t?.allowFilters===!0&&_e.test(r)||(n[r]=i);return n}const ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ye=/^\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})?)?$/;function be(e){if(!ye.test(e))return!1;let t=Date.parse(e);return Number.isNaN(t)?!1:e.length===10?new Date(t).toISOString().slice(0,10)===e:!0}function xe(e){if(e.trim()===``)return!1;let t=Number(e);return Number.isFinite(t)}function Se(e){return ve.test(e)}function Ce(e,t){switch(e.type){case`boolean`:return t===`true`?!0:t===`false`?!1:null;case`reference`:case`media`:return ve.test(t)?t:null;case`select`:return e.options.includes(t)?t:null;case`date`:return be(t.startsWith(`gte:`)||t.startsWith(`lte:`)?t.slice(4):t)?t:null;case`number`:return xe(t)?Number(t):null;case`text`:return t.length<=200?t:null;default:return null}}function z(e,t){return e.startsWith(`_`)||t?.internal===!0||t?.adminOnly===!0}function we(e,t){if(!e)return;let n=e.split(`,`).map(e=>e.trim()).filter(e=>{if(!Object.hasOwn(t,e))return!1;let n=t[e];return n!==void 0&&!z(e,n)&&n.type!==`blockTree`});return n.includes(`id`)||n.unshift(`id`),n}function Te(e,t){if(!e)return{fields:[],dropped:[],requested:0};let n=[...new Set(e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0))],r=[],i=[];for(let e of n){if(!Object.hasOwn(t,e)){i.push(e);continue}let n=t[e];if(!n||z(e,n)||n.type!==`reference`){i.push(e);continue}r.push(e)}return{fields:r,dropped:i,requested:n.length}}const Ee=[`reference`,`populate`,`media`,`block`],De=200;function Oe(e){if(!Number.isInteger(e)||e<0)throw Error(`content-api: resolution budget ceiling must be a non-negative integer, received ${String(e)}.`);let t=e,n=0,r=new Map;return{claim(e,i){if(!Number.isInteger(i)||i<=0)return 0;let a=Math.min(i,t);t-=a,n+=a;let o=i-a;return o>0&&r.set(e,(r.get(e)??0)+o),a},get remaining(){return t},get granted(){return n},get hasDrops(){return r.size>0},dropSummary(){let e={};for(let t of Ee){let n=r.get(t);n!==void 0&&n>0&&(e[t]=n)}return e},ceiling:e}}function ke(e){if(e===void 0)return 200;if(!Number.isInteger(e)||e<0)throw Error(`content-api: \`maxResolutionsPerDocument\` must be an integer >= 0, received ${String(e)}. If this came from an environment variable, it is probably unset — omit the option to get the package default (200).`);return Math.min(e,200)}const Ae=2e3;function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){if(!B(e))return!1;let t=e=>e===void 0||typeof e==`string`&&e.length<=Ae,n=e=>e===void 0||typeof e==`number`&&Number.isFinite(e)&&e>=0;if(!t(e.title)||!t(e.text))return!1;let r=e.price;if(r!==void 0&&(!B(r)||typeof r.amount!=`number`||!Number.isFinite(r.amount)||r.amount<0||!n(r.compareAt)||!t(r.unit)))return!1;let i=e.facts;if(i!==void 0){if(!Array.isArray(i)||i.length>12)return!1;for(let e of i)if(!B(e)||typeof e.key!=`string`||typeof e.label!=`string`||typeof e.value!=`string`&&typeof e.value!=`number`||e.format!==void 0&&e.format!==`price`)return!1}let a=e.body;if(a!==void 0){if(!B(a)||typeof a.html!=`string`||a.html.length>5e5||!Array.isArray(a.headings)||a.headings.length>100)return!1;for(let e of a.headings)if(!B(e)||typeof e.id!=`string`||typeof e.text!=`string`||e.level!==2&&e.level!==3)return!1}let o=e.embed;if(o!==void 0&&(!B(o)||typeof o.provider!=`string`||typeof o.reference!=`string`))return!1;let s=e.breadcrumbs;if(s!==void 0){if(!Array.isArray(s)||s.length>8)return!1;for(let e of s){if(!B(e)||typeof e.label!=`string`||e.label.length>Ae)return!1;if(e.href!==void 0){if(typeof e.href!=`string`||e.href.length>1e3||!e.href.startsWith(`/`)||e.href.startsWith(`//`))return!1;for(let t of e.href){let e=t.codePointAt(0)??0;if(e<=32||e===127||t===`\\`)return!1}}}}return!0}const H=new Set([`price`,`number`,`text`]);function U(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return W(t.name)&&W(t.label)&&H.has(t.format)&&(t.unit===void 0||W(t.unit))}function W(e){if(typeof e!=`string`||e.length>1200)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<32)return!1;return!0}function je(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let{sources:t,values:n}=e;if(typeof t!=`object`||!t||Array.isArray(t)||typeof n!=`object`||!n||Array.isArray(n))return!1;let r=Object.entries(t);if(r.length>32)return!1;for(let[,e]of r){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.label!=`string`||t.labelKey!==void 0&&typeof t.labelKey!=`string`||t.kind!==void 0&&t.kind!==`price`&&t.kind!==`text`&&t.kind!==`list`&&t.kind!==`facts`||t.facts!==void 0&&(!Array.isArray(t.facts)||t.facts.length>48||!t.facts.every(U))||t.fields!==void 0&&(!Array.isArray(t.fields)||t.fields.length>64||!t.fields.every(e=>typeof e==`string`)))return!1}let i=Object.entries(n);if(i.length>32)return!1;for(let[,e]of i){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);if(t.length>200)return!1;for(let[,e]of t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.amount!==void 0&&(typeof t.amount!=`number`||!Number.isFinite(t.amount))||t.compareAt!==void 0&&(typeof t.compareAt!=`number`||!Number.isFinite(t.compareAt))||t.unit!==void 0&&typeof t.unit!=`string`||t.text!==void 0&&!W(t.text)||t.items!==void 0&&(!Array.isArray(t.items)||t.items.length>100||!t.items.every(W)))return!1;if(t.facts!==void 0){if(typeof t.facts!=`object`||t.facts===null||Array.isArray(t.facts))return!1;let e=Object.entries(t.facts);if(e.length>48)return!1;for(let[,t]of e)if(!(typeof t==`number`&&Number.isFinite(t)||W(t)))return!1}}}return!0}const Me=new Set([`ok`,`unset`,`unavailable`,`over-budget`,`needs-document`]);function Ne(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.status!=`string`||!Me.has(t.status)||t.entity!==null&&(typeof t.entity!=`string`||t.entity===``)||!Array.isArray(t.rows)||t.rows.length>100)return!1;if(t.page!==void 0){if(typeof t.page!=`object`||t.page===null||Array.isArray(t.page))return!1;let e=t.page;if(typeof e.number!=`number`||!Number.isInteger(e.number)||e.number<1||e.number>100||typeof e.hasNext!=`boolean`)return!1}if(t.status===`ok`&&t.entity===null||t.status!==`ok`&&t.rows.length>0||(t.status===`unset`||t.status===`unavailable`)&&t.entity!==null)return!1;for(let e of t.rows){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.id!=`string`||t.id===``)return!1;for(let e of[t.title,t.text,t.href])if(e!==null&&typeof e!=`string`)return!1;if(t.image!==null){if(typeof t.image!=`object`||Array.isArray(t.image))return!1;let e=t.image;if(typeof e.url!=`string`||e.alt!==null&&typeof e.alt!=`string`)return!1;for(let t of[e.width,e.height])if(t!==null&&typeof t!=`number`)return!1}}return!0}function Pe(e){if(!Number.isInteger(e)||e<0)throw Error(`content-api: collection allowance must be a non-negative integer, received ${String(e)}.`);let t=e,n=0;return{claim:()=>t===0?(n+=1,!1):(--t,!0),refusedCount:()=>n}}const Fe=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;function Ie(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.keys(e);return t.length>16?!1:t.every(e=>Fe.test(e))}function Le(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.resolved!==1||!Array.isArray(t.blocks))return!1;let n=t.links;if(typeof n!=`object`||!n||Array.isArray(n))return!1;for(let e of Object.values(n))if(e!==null&&typeof e!=`string`)return!1;let r=new Set,i=t.refs;if(i!==void 0){if(!Array.isArray(i))return!1;for(let e of i){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.entity!=`string`||t.entity===``||typeof t.id!=`string`||t.id===``)return!1;r.add(`${t.entity}\u0000${t.id}`)}}let a=t.collections;if(a!==void 0){if(typeof a!=`object`||!a||Array.isArray(a))return!1;let e=Object.entries(a);if(e.length>64)return!1;for(let[t,n]of e){if(t===``||!Ne(n))return!1;if(!(n.status!==`ok`||n.entity===null)){for(let e of n.rows)if(!r.has(`${n.entity}\u0000${e.id}`))return!1}}}let o=t.unresolved;if(o!==void 0){if(!Array.isArray(o))return!1;for(let e of o)if(!Re(e))return!1}return!(t.live!==void 0&&!je(t.live)||t.currency!==void 0&&typeof t.currency!=`string`||t.detail!==void 0&&!V(t.detail)||t.blockData!==void 0&&!Ie(t.blockData))}function Re(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.kind!==`media`&&t.kind!==`link`||typeof t.ref!=`string`?!1:t.reason===`unresolvable`||t.reason===`budget`}function ze(e){return r(e).filter(e=>!e.internal).map(e=>e.name)}const Be=Object.freeze({resolved:1,blocks:Object.freeze([]),links:Object.freeze({})});async function Ve(e,t,n){try{let r=await e(t,n.boundValues===void 0?n:{...n,boundValues:structuredClone(n.boundValues)});return Le(r)?{ok:!0,envelope:r}:{ok:!1,failure:`malformed`}}catch(e){return{ok:!1,failure:`threw`,error:e}}}async function He(e,t,n){let r=await Ve(e,t,n);if(r.ok)return{envelope:r.envelope};let i=await Ve(e,t,{...n,budget:Oe(0),claimCollection:void 0});return i.ok?{envelope:i.envelope,failure:r.failure,error:r.error}:{envelope:Be,failure:r.failure,retryFailure:i.failure,error:r.error??i.error}}async function Ue(e,t,n){if(t.length===0)return;let r=n.resolveBlocks;if(!r)return;let a=ze(e);if(a.length===0)return;let o=new Map;for(let t of a){let r;if(d(e,t)){if(n.siteOf===void 0)throw Error(`content-api: '${e.name}.${t}' declares siteTemplates but block resolution was given no siteOf to learn the row’s site`);r=await n.siteOf(e)}o.set(t,i(e,t,r))}let s=0,c=0,l=0,u,f,p=new Set,m=new Set,h=new Set;for(let i of t)for(let t of a){let a=i[t],d=o.get(t);if(d!==void 0&&!Object.hasOwn(i,t)||d===void 0&&a==null)continue;let g=await He(r,d===void 0?a:[],{locale:n.locale,budget:n.budget,entity:e.name,field:t,...d!==void 0&&{template:d},boundValues:{...i},...n.canReadEntity!==void 0&&{canReadEntity:n.canReadEntity},...n.collectionAllowance!==void 0&&{claimCollection:n.collectionAllowance.claim},...n.page!==void 0&&{page:n.page}});if(g.failure===`threw`?(s+=1,p.add(t),u??=g.error):g.failure===`malformed`&&(c+=1,m.add(t)),g.retryFailure!==void 0&&(l+=1,h.add(t),f??=g.error,n.cacheTags?.markUncacheable()),i[t]=g.envelope,g.envelope.refs!==void 0)for(let e of g.envelope.refs)n.cacheTags?.addDocument(e.entity,e.id);if(g.envelope.collections!==void 0)for(let e of Object.values(g.envelope.collections))e.entity!==null&&n.cacheTags?.addCollection(e.entity)}s>0&&n.logger?.warn({entity:e.name,fields:[...p],rows:t.length,failures:s,err:u},`content-api: block resolver threw — no tree is served as stored; each was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them. Fields that failed that retry as well are reported separately, as empty.`),c>0&&n.logger?.warn({entity:e.name,fields:[...m],rows:t.length,failures:c},`content-api: block resolver returned a value that is not a ResolvedBlockTree — no tree is served as stored; each was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them. Fields that failed that retry as well are reported separately, as empty.`),l>0&&n.logger?.warn({entity:e.name,fields:[...h],rows:t.length,failures:l,err:f},`content-api: block resolver failed TWICE, including on the in-memory retry — those fields are served as an empty resolved tree, so that content is missing from the response. Serving the stored tree instead would put the media urls recorded when an editor picked them, which may be signed, on a cacheable anonymous response.`)}const G=`lumi`,We=128,Ge=128,Ke=3072,qe=`media`,Je=/^[A-Za-z0-9_.-]+$/,Ye=`_`,Xe={enabled:!0,header:`Cache-Tag`,separator:`,`},Ze=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Qe=[`cache-control`,`vary`,`content-type`],$e=[`access-control-`];function et(e){if(e){if(e.enabled!==void 0&&typeof e.enabled!=`boolean`)throw Error(`content-api cache: \`cache.tags.enabled\` must be a boolean, received ${JSON.stringify(e.enabled)}.`);if(e.header!==void 0){if(typeof e.header!=`string`||!Ze.test(e.header))throw Error(`content-api cache: \`cache.tags.header\` must be a valid HTTP field name (RFC 9110 §5.1 token), received ${JSON.stringify(e.header)}. Common values: \`Cache-Tag\` (Cloudflare/Netlify, the default), \`Surrogate-Key\` (Fastly), \`Edge-Cache-Tag\` (Akamai).`);let t=e.header.toLowerCase();if(Qe.includes(t)||$e.some(e=>t.startsWith(e)))throw Error(`content-api cache: \`cache.tags.header\` may not be ${JSON.stringify(e.header)} — this package writes that header itself on the same responses, so the tags would either overwrite it or be overwritten, silently and on every request.`)}if(e.separator!==void 0&&e.separator!==`,`&&e.separator!==` `)throw Error(`content-api cache: \`cache.tags.separator\` must be ',' or ' ', received ${JSON.stringify(e.separator)}. Cloudflare and Akamai parse comma-separated tags; Fastly parses space-separated ones. A third separator would not error at the CDN — it would parse as one giant unmatched key, which is the silent failure this refuses.`)}}function tt(e){return{enabled:e?.enabled??Xe.enabled,header:e?.header??Xe.header,separator:e?.separator??Xe.separator}}function nt(e){return typeof e==`string`&&e!==``&&Je.test(e)}function rt(e,t){function n(e){if(t===void 0)return G;let n=t(e);return nt(n)?`${G}:${n}`:void 0}let r=new Set,i=0,a=!1,o=e.header.length+4,s=!1;function c(e){if(r.has(e))return;if(e.length>128||r.size>=128){i+=1;return}let t=e.length+(r.size===0?0:1);if(s||o+t>3072){s=!0,i+=1;return}o+=t,r.add(e)}return{addDocument(e,t){if(!nt(e)||!nt(t)){i+=1;return}let r=n(e);if(r===void 0){i+=1;return}c(`${r}:${e}:${t}`)},addCollection(e){if(!nt(e)){i+=1;return}let t=n(e);if(t===void 0){i+=1;return}c(`${t}:${e}`)},get tags(){return[...r]},markUncacheable(){a=!0},get dropped(){return i},get uncacheable(){return a},headers(){return!e.enabled||r.size===0?{}:{[e.header]:[...r].join(e.separator)}}}}const it=`_template`;function at(e){if(typeof e!=`string`)return;let t=e.trim();return t===``?void 0:t.slice(0,2e3)}async function ot(e,t,n,r){let i={...t};for(let e of Object.keys(t))e!==`id`&&delete t[e];let a=n.detailTemplates;if(!a)return;let o=n.locale??n.defaultLocale;if(o===void 0)return;try{let n=await a.publicRow({entity:e.name,row:i,locale:o}),r=at(n.title),s=at(n.description);r!==void 0&&(t.title=r),s!==void 0&&(t.description=s)}catch(t){n.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to project a row — served with its id only`),n.cacheTags?.markUncacheable()}if(!r)return;let s=n.resolveBlocks;if(!s||(n.cacheTags?.addCollection(a.entity),n.budget.claim(`block`,1)<1))return;let c;try{c=await a.readTemplate({entity:e.name,locale:o})}catch(t){n.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to read the template — the row is served without one and the response is not cacheable`),n.cacheTags?.markUncacheable();return}if(c===null||typeof c.id!=`string`||!Array.isArray(c.blocks))return;n.cacheTags?.addDocument(a.entity,c.id);let l=await He(s,c.blocks,{locale:n.locale,budget:n.budget,entity:e.name,field:it,boundValues:i,rowIsForeign:!0,...n.canReadEntity!==void 0&&{canReadEntity:n.canReadEntity},...n.collectionAllowance!==void 0&&{claimCollection:n.collectionAllowance.claim},...n.page!==void 0&&{page:n.page}});l.failure!==void 0&&n.logger?.warn({entity:e.name,field:it,failure:l.failure,retryFailure:l.retryFailure,err:l.error},`content-api: block resolver failed on a detail template — served re-resolved with an exhausted budget, or empty if that failed as well`),l.retryFailure!==void 0&&n.cacheTags?.markUncacheable(),K(l.envelope,n),t[it]=l.envelope}function K(e,t){if(e.refs!==void 0)for(let n of e.refs)t.cacheTags?.addDocument(n.entity,n.id);if(e.collections!==void 0)for(let n of Object.values(e.collections))n.entity!==null&&t.cacheTags?.addCollection(n.entity)}const st=[`NOT_FOUND`,`VALIDATION_ERROR`,`INTERNAL_ERROR`,`RATE_LIMITED`,`SERVICE_OVERLOADED`,`FORM_INVALID`,`CHALLENGE_FAILED`,`PAYLOAD_TOO_LARGE`];function q(e,t=200,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`,...n}})}const ct={"Cache-Control":`no-store`},lt=new WeakMap;function ut(e){return lt.get(e)}function J(e,t,n,r,i){let a=q({error:{status:n,message:e,code:t,...i}},n,{...r,...ct});return lt.set(a,t),a}function Y(e){return J(`Not found`,`NOT_FOUND`,404,e)}function dt(e,t){return J(`Rate limit exceeded`,`RATE_LIMITED`,429,{...t,"Retry-After":String(e)})}function ft(e,t){return J(`Service overloaded`,`SERVICE_OVERLOADED`,503,{...t,"Retry-After":String(e)})}function pt(e){let t=[];for(let[n,r]of Object.entries(e.allFields))r.type!==`media`||z(n,r)||t.push([n,r]);return t}async function mt(e,t,n){if(t.length===0)return;let r=pt(e);if(r.length===0)return;let i=new Set;for(let e of t)for(let[t]of r){if(!Object.hasOwn(e,t))continue;let n=e[t];typeof n==`string`&&n!==``&&i.add(n)}let a=new Map;if(i.size>0&&n.resolveMedia){let t=[...i],r=n.budget.claim(`media`,t.length),o=t.slice(0,r);if(o.length>0)try{a=await n.resolveMedia(o,{locale:n.locale})}catch(t){n.logger?.warn({entity:e.name,err:t},"content-api: media resolver threw — media fields resolve to null (if this is a ForbiddenError, the requesting role is missing `media:view`)")}}else i.size>0&&n.logger?.debug({entity:e.name,mediaFields:r.map(([e])=>e)},"content-api: no `resolveMedia` provider wired — media fields resolve to null");for(let[e,t]of a)i.has(e)&&t?.id===e&&n.cacheTags?.addDocument(qe,e);for(let e of t)for(let[t]of r){if(!Object.hasOwn(e,t))continue;let n=e[t];e[t]=typeof n==`string`?a.get(n)??null:null}}const ht=20,gt=50,_t=k.object({q:k.string().max(200).refine(e=>L(e).length>=2,{message:`q must be at least 2 characters`}),types:k.string().max(808).optional(),limit:k.coerce.number().int().min(1).default(20),locale:k.string().regex(g).optional()}).strict();function vt(e){return u(e)===void 0||m(e)?!1:e.kind!==`singleton`}function yt(e,t){if(t===void 0)return[...e];let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``);if(n.length===0)return null;for(let t of n)if(!e.includes(t))return null;return e.filter(e=>n.includes(e))}function bt(e){for(let[t,n]of pt(e)){let e=n.accept;if(e===void 0||e.length===0||e.some(e=>e===`*/*`||e.startsWith(`image/`)))return t}return null}function xt(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.url==`string`}function St(e){let t=e.admin?.labelSingular;if(typeof t==`string`&&t.trim()!==``)return t.trim();let n=e.name.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase();return n===``?e.name:`${n.charAt(0).toUpperCase()}${n.slice(1)}`}function Ct(e,t){if(typeof e!=`string`)return null;let n=e.replace(/\s+/g,` `).trim();return n===``?null:n.length>t?`${n.slice(0,t-1).trimEnd()}…`:n}const wt=[`summary`,`excerpt`,`description`,`intro`,`lead`],Tt=new Set([`text`]);function Et(e,t,n){let r=null,i=e.allFields;for(let e of wt){let n=i[e];if(!(n===void 0||!Tt.has(n.type))&&(r=Ct(t[e],300),r!==null))break}let a=null,o=u(e);if(o)try{let e=o.projection({...t});r??=Ct(e.description,300),a=Ct(e.label,300)}catch{}return{title:Ct(t[n],300)??a??(typeof t.id==`string`?t.id:``),summary:r}}function Dt(e,t){let n=[];for(let r of[!0,!1]){let i=e.map(e=>e.hits.filter(e=>e.titleHit===r).map(e=>e.hit));for(let e=0;n.length<t;e++){let r=!1;for(let a of i){let i=a[e];if(i!==void 0&&(r=!0,n.push(i),n.length===t))break}if(!r)break}}return n}function Ot(e,t){let n=L(t).toLocaleLowerCase();return n!==``&&e.toLocaleLowerCase().includes(n)}const kt=`x-lumi-visitor-address`;function At(e,t,n){if(e===void 0)return t;if(!Number.isSafeInteger(e)||e<1)throw Error(`content-api search: \`${n}\` must be a positive integer (got ${e})`);return e}var jt=class{getClientIp;store;tokens;intervalMs;readVisitor=ie({header:kt,trustedProxyHops:1,surface:`content-api visitor search`});constructor(e,t){this.getClientIp=t,this.tokens=At(e?.searchesPerVisitorPerInstance,30,`searchesPerVisitorPerInstance`),this.intervalMs=At(e?.intervalMs,6e4,`intervalMs`),this.store=e?.store??new ne}consume(e,t,n){let r=this.keyFor(e,t);if(r!==void 0)return{decision:this.store.consume(`search:${r.key}`,{tokens:this.tokens,intervalMs:this.intervalMs},n),keyClass:r.keyClass}}keyFor(e,t){if(t.principalId!==void 0)return{key:`principal:${t.principalId}`,keyClass:`principal`};if(t.site!==void 0){let n=this.readVisitor(e.headers);if(n!==null)return{key:`visitor:${t.site}:${n}`,keyClass:`visitor`}}if(t.site!==void 0)return;let n=this.getClientIp?.(e);if(n!==void 0&&n!==``)return{key:`ip:${n}`,keyClass:`client-ip`}}};const Mt=64*1024,Nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Pt=ie({header:kt,trustedProxyHops:1,surface:`content-api form submissions`}),Ft={"Cache-Control":`no-store`};function It(e,t){if(e.length!==3||e[0]!==`_forms`||e[2]!==t)return;let n=e[1];return n!==void 0&&Nt.test(n)?n:void 0}async function Lt(e,t){let n=e.headers.get(`content-type`)??``;if(!/^application\/json\s*(?:;|$)/i.test(n))return{ok:!1,reason:`invalid`};let r=e.headers.get(`content-length`);if(r!==null&&Number(r)>t)return{ok:!1,reason:`too_large`};if(e.body===null)return{ok:!1,reason:`invalid`};let i=e.body.getReader(),a=[],o=0;for(;;){let{done:e,value:n}=await i.read();if(e)break;if(o+=n.byteLength,o>t)return await i.cancel(),{ok:!1,reason:`too_large`};a.push(n)}let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.byteLength;try{return{ok:!0,value:JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(s))}}catch{return{ok:!1,reason:`invalid`}}}async function Rt(e){if(e.keySite===void 0)return Y(e.headers);let t=await e.forms.issueToken({site:e.keySite,formId:e.formId,purpose:new URL(e.req.url).searchParams.get(`for`)===`visitor`?`visitor`:`render`,visitorAddress:Pt(e.req.headers)});return t===null?Y(e.headers):t===`rate_limited`?dt(600,e.headers):q({data:t},200,{...e.headers,...Ft})}async function zt(e){if(e.keySite===void 0)return Y(e.headers);let t=await Lt(e.req,Mt);if(!t.ok)return t.reason===`too_large`?J(`Submission too large`,`PAYLOAD_TOO_LARGE`,413,e.headers):J(`Malformed submission`,`VALIDATION_ERROR`,400,e.headers);let n=await e.forms.submit({site:e.keySite,formId:e.formId,body:t.value,visitorAddress:Pt(e.req.headers)});switch(n.kind){case`accepted`:return q({data:{ok:!0}},200,{...e.headers,...Ft});case`invalid`:return Bt(n.fields,e.headers);case`rate_limited`:return dt(n.retryAfterSeconds,e.headers);case`challenge_failed`:return J(`Verification failed`,`CHALLENGE_FAILED`,400,e.headers);case`unavailable`:return ft(30,e.headers);case`not_found`:return Y(e.headers)}}function Bt(e,t){return J(`Some answers need attention`,`FORM_INVALID`,400,t,{fields:e})}function Vt(e){let t=Math.ceil(e/6);return{maxAge:t,swr:e-t}}const Ht=[`defaultMaxAge`,`defaultStaleWhileRevalidate`,`maxAge`,`staleWhileRevalidate`];function Ut(e,t){if(e!==void 0&&(typeof e!=`number`||!Number.isInteger(e)||e<0))throw Error(`content-api cache: \`${t}.maxStaleSeconds\` must be a non-negative integer, received ${JSON.stringify(e)}. Use 0 for \`no-store\` if you need a published edit visible on the very next request.`)}function Wt(e,t){for(let n of Ht)if(n in e)throw Error(`content-api cache: \`${t}.${n}\` was removed (D036). Use \`maxStaleSeconds\` — ONE number naming the TOTAL staleness window in seconds. The old pair's real window was their SUM and nothing said so, which is the defect D036 exists to close: \`defaultMaxAge: 10\` bought a 310-second window, not a 10-second one. The max-age / stale-while-revalidate split is now derived, so what is emitted always sums to what you declared.`)}function Gt(e){if(e){Wt(e,`cache`),Ut(e.maxStaleSeconds,`cache`),et(e.tags);for(let[t,n]of Object.entries(e.entities??{})){if(!n)continue;let e=`cache.entities.${t}`;Wt(n,e),Ut(n.maxStaleSeconds,e)}}}function Kt(e,t){let n=t?.entities?.[e];return n?.cacheable===!1?0:n?.maxStaleSeconds??t?.maxStaleSeconds??360}function qt(e,t){let n=Kt(e,t);if(n===0)return{"Cache-Control":`no-store`};let{maxAge:r,swr:i}=Vt(n);return{"Cache-Control":`public, max-age=${r}, stale-while-revalidate=${i}`}}const Jt=[`Origin`];function Yt(e,t){let n=new Set,r=[];for(let i of[...e?.split(`,`)??[],...Jt,...t]){let e=i.trim();if(e===``)continue;let t=e.toLowerCase();n.has(t)||(n.add(t),r.push(e))}return r.join(`, `)}function X(e,t,n,r,i,a){let o=(n!==`identified`&&i.kind!==`undeclared`&&a?.uncacheable!==!0?qt(e,r):{"Cache-Control":`no-store`})[`Cache-Control`]??`no-store`,s={"Cache-Control":n===`site-keyed`?o.replace(/^public\b/,`private`):o};return{...t,...s,...s[`Cache-Control`]===`no-store`?{}:a?.headers(),Vary:Yt(t.Vary,i.kind===`declared`?i.headers:[])}}function Xt(e,t,n,r){let i=r?.uncacheable===!0?{"Cache-Control":`no-store`}:qt(e,n);return{...t,...i,...i[`Cache-Control`]===`no-store`?{}:r?.headers(),Vary:Yt(void 0,[])}}function Zt(e,t){return{...e,Vary:Yt(e.Vary,t.kind===`declared`?t.headers:[])}}function Qt(e,t){if(!t)return{};let n=e.headers.get(`Origin`);return n!==null&&t.allowedOrigins.includes(n)?{"Access-Control-Allow-Origin":n,"Access-Control-Allow-Methods":`GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Accept, Authorization`,"Access-Control-Max-Age":String(t.maxAge??3600),Vary:`Origin`}:{Vary:`Origin`}}function $t(e,t,n){let r={...Qt(e,t),...qt(`_preflight`,n)};return new Response(null,{status:204,headers:r})}var en=class extends Error{constructor(){super(`Service overloaded`),this.name=`ServiceOverloadedError`}},tn=class extends Error{constructor(){super(`Request deadline exceeded`),this.name=`RequestDeadlineError`}};function nn(e,t,n){if(e===void 0)return t;if(!Number.isInteger(e)||e<0)throw Error(`content-api limits: \`${n}\` must be a non-negative integer (got ${e})`);return e}function rn(e,t,n){if(e===void 0)return t;if(!Number.isInteger(e)||e<1)throw Error(`content-api limits: \`${n}\` must be a positive integer (got ${e})`);return e}function an(e){return{maxConcurrentRequests:rn(e?.maxConcurrentRequests,64,`maxConcurrentRequests`),maxQueuedRequests:nn(e?.maxQueuedRequests,128,`maxQueuedRequests`),requestTimeoutMs:rn(e?.requestTimeoutMs,1e4,`requestTimeoutMs`),anonymousTokensPerInstance:rn(e?.anonymousTokensPerInstance,120,`anonymousTokensPerInstance`),intervalMs:rn(e?.intervalMs,6e4,`intervalMs`),maxBudgetPerInstance:rn(e?.maxBudgetPerInstance,6e3,`maxBudgetPerInstance`)}}var on=class{semaphore;store;limits;getClientIp;constructor(e){this.getClientIp=e?.getClientIp,this.limits=an(e),this.semaphore=new re(this.limits.maxConcurrentRequests,this.limits.maxQueuedRequests),this.store=e?.store??new ne}async acquire(e){await this.semaphore.acquire(()=>new en,e)}release(){this.semaphore.release()}async runGuarded(e){return await A(e,this.limits.requestTimeoutMs,()=>new tn)}consumeFairness(e,t,n){let r=this.resolveKey(e,t);if(r)return{decision:this.store.consume(r.key,{tokens:this.budgetFor(t),intervalMs:this.limits.intervalMs},n),keyClass:r.keyClass}}budgetFor(e){let t=e.budgetPerInstance??this.limits.anonymousTokensPerInstance;return Math.min(t,this.limits.maxBudgetPerInstance)}resolveKey(e,t){if(t.principalId!==void 0)return{key:`principal:${t.principalId}`,keyClass:`principal`};let n=this.getClientIp?.(e);if(n!==void 0&&n!==``)return{key:`ip:${n}`,keyClass:`client-ip`}}};function sn(e){let t=[];for(let[n,r]of Object.entries(e.allFields))r.type!==`reference`||z(n,r)||t.push([n,r]);return t}function cn(e){return typeof e==`string`&&e.length>0}function ln(e,t){return t===`many`?Array.isArray(e)?e.filter(cn):[]:cn(e)?[e]:[]}async function un(e,t,n,r,i=0){if(t.length===0)return;let a=sn(e);if(a.length===0)return;let o=new Map,s=[];for(let e of t)for(let[t,c]of a){if(!Object.hasOwn(e,t))continue;let a=ln(e[t],c.cardinality),l=i===0&&n.has(t),u=r.reachableEntity(c.entity);if(!u||a.length===0){s.push({row:e,field:t,cardinality:c.cardinality,groupKey:null,ids:a});continue}let d=`${u.name}::${l?`full`:`projection`}`,f=o.get(d);f||(f={target:u,expand:l,ids:new Set},o.set(d,f));for(let e of a)f.ids.add(e);s.push({row:e,field:t,cardinality:c.cardinality,groupKey:d,ids:a})}let c=new Map;for(let[e,t]of o){let n=[...t.ids],a=r.budget.claim(t.expand?`populate`:`reference`,n.length),o=n.slice(0,a);if(o.length===0){c.set(e,new Map);continue}let s=l(t.target),u=m(t.target),d=u?r.templateDrawnTitle:void 0,f=t.expand||d!==void 0?void 0:u?[`id`]:dn([`id`,s]),p=await r.readRowsByIds(t.target,o,f),h=new Map;if(t.expand){for(let e of p){let t=e.id;cn(t)&&h.set(t,e)}await un(t.target,p,new Set,r,i+1),await r.afterExpand?.(t.target,p)}else{let e=await fn(t.target.name,p,r);for(let[n,r]of p.entries()){let i=r.id;if(!cn(i))continue;let a=u?await d?.(t.target,r)??null:r[s];h.set(i,{id:i,entityType:t.target.name,title:typeof a==`string`?a:null,href:e[n]??null})}}for(let e of h.keys())r.cacheTags?.addDocument(t.target.name,e);c.set(e,h)}for(let e of s){let t=e.groupKey===null?void 0:c.get(e.groupKey);if(e.cardinality===`many`){e.row[e.field]=e.ids.map(e=>t?.get(e)).filter(e=>e!==void 0);continue}let n=e.ids[0];e.row[e.field]=n===void 0?null:t?.get(n)??null}}function dn(e){return[...new Set(e)]}async function fn(e,t,n){let r=n.resolveEntityHref;return r?O(t,async t=>{let i=t.id;if(!cn(i))return null;try{return await r({entity:e,id:i,...n.locale!==void 0&&{locale:n.locale}})??null}catch(t){return n.logger?.debug({entity:e,id:i,err:t},`content-api: resolveEntityHref threw — reference resolves without an href`),null}}):t.map(()=>null)}const pn={referenceProjection:{fields:{id:`string`,entityType:`string`,title:`string`,href:`string`},nullableFields:[`title`,`href`],nullable:!0,arrayForCardinalityMany:!0},mediaProjection:{fields:{id:`string`,url:`string`,mimeType:`string`,width:`number`,height:`number`,alt:`string`,title:`string`,variants:`object`,sources:`object`,avifSources:`object`,focalPoint:`object`,blurDataUrl:`string`},nullableFields:[`mimeType`,`width`,`height`,`alt`,`title`,`blurDataUrl`],optionalFields:[`avifSources`],nullable:!0,arrayForCardinalityMany:!1}};function mn(e,t){let n={type:e.type};return e.required&&(n.required=!0),e.translatable&&(n.translatable=!0),e.type===`select`&&(n.options=e.options),e.type===`blockTree`&&(n.selectable=!1),e.type===`media`&&(n.wire=`mediaProjection`),e.type===`reference`&&(n.cardinality=e.cardinality,n.wire=`referenceProjection`,t(e.entity)&&(n.entity=e.entity,n.populatable=!0)),n}function hn(e,t){let n=e.allFields,r={},i=m(e);for(let[e,a]of Object.entries(n))z(e,a)||i&&e!==`id`||(r[e]=mn(a,t));let a=u(e);for(let e of a?.fields??[]){let t=r[e];t&&(t.searchable=!0)}return{name:e.name,pluralName:`${e.name}s`,kind:e.kind??`collection`,...i&&{drawnBy:`template`},fields:r}}const gn={type:`string`},_n={type:`string`},vn={type:`string`,maxLength:200,maxItems:5};function yn(e){let{maxLimit:t,maxOffset:n,hasResolution:r,hasMenus:i,hasChrome:a}=e,o=[{id:`list`,path:`/:entity`,data:`array`,entityKind:`collection`,params:{limit:{type:`number`,min:1,max:t,default:Math.min(20,t)},offset:{type:`number`,min:0,max:n,default:0},sort:{type:`string`},locale:gn,fields:_n,search:{type:`string`,maxLength:200,minLength:2},cursor:{type:`string`,maxLength:500},populate:vn,"filter[<field>]":{type:`string`}},meta:{total:{type:`number`,nullable:!0,suppressedBy:[`search`]},limit:{type:`number`},offset:{type:`number`},hasMore:{type:`boolean`},nextCursor:{type:`string`,optional:!0}}},{id:`singleton`,path:`/:entity`,data:`object`,entityKind:`singleton`,params:{locale:gn,fields:_n,populate:vn}},{id:`count`,path:`/:entity/count`,data:`object`,entityKind:`collection`,params:{locale:gn}},{id:`byId`,path:`/:entity/:id`,data:`object`,entityKind:`collection`,params:{locale:gn,fields:_n,populate:vn}},{id:`bySlug`,path:`/:entity/slug/:slug`,data:`object`,entityKind:`collection`,params:{locale:gn,fields:_n,populate:vn}}];return r&&o.push({id:`resolve`,path:`/_resolve`,data:`object`,params:{path:{type:`string`,required:!0,maxLength:pe},locale:{type:`string`,required:!0}}},{id:`paths`,path:`/_paths`,data:`array`,params:{locale:{type:`string`,required:!0},entity:{type:`string`,required:!0,maxLength:100},cursor:{type:`string`},limit:{type:`number`,min:1,max:t,default:Math.min(20,t)}},meta:{limit:{type:`number`},hasMore:{type:`boolean`},nextCursor:{type:`string`,optional:!0}}},{id:`alternates`,path:`/_alternates`,data:`array`,params:{entity:{type:`string`,required:!0,maxLength:100},id:{type:`string`,required:!0}}}),o.push({id:`site`,path:`/_site`,data:`object`,params:{}}),o.push({id:`search`,path:`/_search`,data:`array`,params:{q:{type:`string`,required:!0,minLength:2,maxLength:200},types:{type:`string`,maxLength:808},limit:{type:`number`,default:20,min:1,max:50},locale:{type:`string`}},meta:{limit:{type:`number`}}}),i&&o.push({id:`menu`,path:`/_menu`,data:`object`,params:{handle:{type:`string`,required:!0,maxLength:128},locale:{type:`string`,required:!0},currentPath:{type:`string`,maxLength:pe}}}),a&&o.push({id:`chrome`,path:`/_chrome`,data:`object`,params:{locale:{type:`string`,required:!0},entity:{type:`string`,maxLength:100},id:{type:`string`}}}),o}function bn(e,t){if(!e.enabled)return null;let n=t?`${G}:{site}`:G;return{header:e.header,separator:e.separator,document:`${n}:{entity}:{id}`,collection:`${n}:{entity}`,sharedSite:t?`_`:null,maxTagLength:128,maxTagsPerResponse:128,maxHeaderBytes:Ke,uncovered:[`menuTargets`,`crossEntityPathChanges`,`mediaVariantStyles`,`outOfBandPathChanges`]}}function xn(e){let{entities:t,checkPermission:n,version:r}=e,i={maxResolutionsPerDocument:e.maxResolutionsPerDocument,anonymousRequestsPerInstance:e.limits.anonymousTokensPerInstance,rateLimitWindowMs:e.limits.intervalMs,maxRequestsPerInstance:e.limits.maxBudgetPerInstance,maxConcurrentRequests:e.limits.maxConcurrentRequests,requestTimeoutMs:e.limits.requestTimeoutMs},a=t.filter(e=>n(e.name)),o=new Set(a.map(e=>e.name)),s=e=>o.has(e);return{version:r,surface:yn(e),envelopes:{dataKey:`data`,metaKey:`meta`,errorKey:`error`,errorCodes:st},limits:i,projections:pn,cacheTags:bn(e.cacheTags,e.siteScopedTags===!0),entities:a.map(e=>hn(e,s))}}const Sn=`public`,Cn=new Set;function wn(e){return typeof e==`string`&&e!==``}function Tn(e){return Array.isArray(e)}const En=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;function Dn(e){let t=e.credentialHeaders;if(t!==void 0){if(!Tn(t))throw Error(`content-api: \`credentialHeaders\` must be an array of HTTP header names, received ${JSON.stringify(t)}.`);for(let e of t)if(!wn(e)||e===`*`||!En.test(e))throw Error(`content-api: \`credentialHeaders\` entry ${JSON.stringify(e)} is not a valid HTTP header name. Each entry is emitted verbatim in \`Vary\`, so it must be a bare field-name token (\`Cookie\`, \`Authorization\`, \`X-Preview-Token\`). \`*\` is refused: it means "never reuse this response", which is \`Cache-Control: no-store\` spelled obscurely — omit the option instead, which fails closed to exactly that.`)}if(!e.authenticate){if(t!==void 0&&t.length>0)throw Error("content-api: `credentialHeaders` was declared without an `authenticate` hook. This package parses no credential itself, so nothing reads those headers and listing them in `Vary` can only fragment a shared cache. Remove the option, or wire the `authenticate` hook it describes.");return{kind:`none`}}return t===void 0||t.length===0?{kind:`undeclared`}:{kind:`declared`,headers:t}}const On=k.object({path:k.string().min(1).max(pe),locale:k.string().regex(g)}).strict(),kn=k.object({locale:k.string().regex(g),entity:k.string().min(1).max(100),cursor:k.string().refine(e=>Se(e),`Invalid cursor`).optional(),limit:k.coerce.number().int().min(1).max(100).default(20)}).strict(),An=k.object({entity:k.string().min(1).max(100),id:k.string().refine(e=>Se(e),`Invalid id`)}).strict(),jn=[`header`,`footer`],Mn=k.object({locale:k.string().regex(g),entity:k.string().min(1).max(100).optional(),id:k.string().refine(e=>Se(e),`Invalid id`).optional()}).strict().refine(e=>e.entity===void 0==(e.id===void 0),`Both ?entity= and ?id= are required to name a document, or neither.`),Nn=k.object({}).strict();function Pn(e){return e instanceof n||e instanceof Error&&e.name===`SiteRequiredError`}const Fn=k.object({handle:k.string().min(1).max(128),locale:k.string().regex(g),currentPath:k.string().min(1).max(pe).optional()}).strict(),In=new Set([`_schema`,`_site`,`_resolve`,`_paths`,`_alternates`,`_menu`,`_chrome`,`_search`,`_forms`]),Ln=`v1`,Rn=/^v\d+$/;function zn(e){let t=new Map;for(let n of e){let e=`${n.name}s`;if(In.has(n.name)||In.has(e))throw Error(`@murumets-ee/content-api: entity name "${n.name}" collides with a reserved route segment (${[...In].join(`, `)}). Rename the entity — its API surface would otherwise be permanently unreachable, shadowed by the special dispatch that runs before entity-whitelist resolution.`);if(Rn.test(n.name)||Rn.test(e))throw Error(`@murumets-ee/content-api: entity name "${n.name}" is a reserved API-version segment. Every route is served under a version prefix (this instance mounts /v1/), and the prefix is matched as a PATTERN ("v" followed by digits) so that a future /v2/ can never be shadowed by an entity added in the meantime. Rename the entity.`);if(n.scope!==void 0&&n.scope!==`global`)throw Error(`@murumets-ee/content-api: entity "${n.name}" declares scope "${n.scope}", which this surface cannot serve. The public read path resolves no scope for a caller, so QueryClient would apply NO scope filter and return every tenant's rows to every caller. Remove it from the content-api whitelist, or serve it through a surface that establishes a scope in the request context.`);t.set(n.name,n),t.set(e,n)}return t}function Bn(e,n){let r=e[t];if(!r)throw Error(`site-bound '${n}' translations have no ${t} column`);return r}function Z(e){let t=j.get(e);if(t)return{table:t,cols:N(t)}}const Vn=new Set([`text`,`richtext`,`slug`,`select`]);function Hn(e,t,n){let r=u(e);if(!r)return;let i=t.trim();if(i.length===0)return;let o=Z(e.name);if(!o)return;let{cols:s}=o,l=[],d=`%${v(i)}%`,f=e.allFields,p=r.fields.filter(e=>{let t=Object.hasOwn(f,e)?f[e]:void 0;return t!==void 0&&Vn.has(t.type)&&!z(e,t)}),m=r.fts?.fields.some(e=>z(e,f[e]))??!1,h=Cn;if(r.fts&&!m){let e=s._search_tsv;if(e){let t=r.fts.language??`simple`;l.push(I`${e} @@ websearch_to_tsquery(${t}, ${i})`),h=new Set(r.fts.fields)}}for(let e of p){if(h.has(e))continue;let t=s[e];t&&l.push(le(t,d))}let g=c(e.allFields,p),_=s.id;if(n!==void 0&&g.length>0&&_){let t=j.get(`${e.name}_translations`);if(t){let e=a({idColumn:_,translationsTable:t,fields:g,locale:n,buildCondition:e=>le(e,d)});e&&l.push(e)}}if(l.length===0)return;let y=l[0];if(y)return l.length===1?y:de(y,...l.slice(1))}function Un(e,t,n){let r=Z(e.name);if(!r)return[];let{cols:i}=r,a=e.allFields,o=t.trim(),s=`%${v(o)}%`,c=[],d=l(e),f=Object.hasOwn(a,d)?a[d]:void 0,p,m=i[d];if(m&&f!==void 0&&Vn.has(f.type)&&!z(d,f)){let t=n!==void 0&&f.translatable===!0?Z(`${e.name}_translations`):void 0,r=t?.cols[d],a=t?.cols.entityId,o=t?.cols.locale,c=i.id;p=t&&r&&a&&o&&c&&n!==void 0?I`COALESCE((SELECT ${r} FROM ${t.table} WHERE ${a} = ${c} AND ${o} = ${n} LIMIT 1), ${m}) ILIKE ${s}`:le(m,s)}p&&c.push(I`CASE WHEN ${p} THEN 0 ELSE 1 END`);let h=u(e),g=h?.fts?.fields.some(e=>z(e,a[e]))??!1,_=i._search_tsv;if(h?.fts&&!g&&_){let e=h.fts.language??`simple`;c.push(ce(I`ts_rank(${_}, websearch_to_tsquery(${e}, ${o}))`))}let y=i.updatedAt;y&&c.push(ce(y));let b=i.id;return b&&c.push(se(b)),c}function Wn(e,t,n){let r=e.name;if(!t)return{orderBy:void 0};let i=t.startsWith(`-`),a=i?t.slice(1):t,o={orderBy:void 0,dropped:t};if(!Object.hasOwn(n,a))return o;let s=n[a];if(!s||s.type===`blockTree`||z(a,s)&&!p(e,a))return o;let c=Z(r);if(!c)return o;let l=c.cols[a];return l?{orderBy:i?ce(l):se(l),field:a}:o}function Gn(e,t,n){let r=[],i=[],a=Z(e);if(!a)return{conditions:r,dropped:i};let{cols:o}=a;for(let[e,a]of t.searchParams.entries()){let t=e.match(_e);if(!t)continue;let s=t[1];if(s===void 0)continue;if(!Object.hasOwn(n,s)){i.push(s);continue}let c=n[s];if(!c||c.type===`blockTree`){i.push(s);continue}if(z(s,c)){i.push(s);continue}let l=o[s];if(!l){i.push(s);continue}let u=Ce(c,a);if(u===null){i.push(s);continue}if(c.type===`date`&&typeof u==`string`){if(u.startsWith(`gte:`)){r.push(P(l,u.slice(4)));continue}if(u.startsWith(`lte:`)){r.push(ue(l,u.slice(4)));continue}}r.push(M(l,u))}return{conditions:r,dropped:i}}function Kn(e,t,n,r,i=!0){if(!(!i||t<=n))return J(`?${e}=${t} exceeds the maximum of ${n}.${e===`offset`?` Use ?cursor= for deep pagination.`:``}`,`VALIDATION_ERROR`,400,r)}function qn(e,t,n){return n?e:Math.min(e,t)}function Jn(e,t,{allowZero:n=!1}={}){if(t===void 0)return;let r=+!n;if(!Number.isInteger(t)||t<r)throw Error(`content-api: \`${e}\` must be an integer >= ${r}, received ${String(t)}. A ceiling below that does not tighten the bound, it removes it: the limit reaches the query layer falsy, no LIMIT clause is emitted, and the whole table is returned on a public route. If this came from an environment variable, it is probably unset.`)}function Q(e){return e.length<=256?e:`${e.slice(0,256)}…[truncated]`}const Yn=new WeakMap,Xn=new WeakMap;function Zn(e){if(e.requestId)try{Yn.set(e,y().logger.child({requestId:e.requestId,...e.user?.id!==void 0&&{principalId:e.user.id}}))}catch{}}async function Qn(e,t){let n=b();if(!n)return{locales:[]};let r=e??await E(n).catch(()=>void 0);if(r===void 0)return{locales:[]};let i=await w(n,r);if(!i)return{locales:[]};let a=e=>e!==void 0&&(i.locales.length===0||i.locales.includes(e)),o=n.config.sites?.multiple===!0?i.defaultLocale:void 0,s=a(o)?o:a(t)?t:i.locales[0];return{locales:i.locales,...s!==void 0&&{defaultLocale:s}}}function $(){let e=x();return(e?Yn.get(e):void 0)??y().logger}function $n(t){let{entities:n,defaultLocale:r,publicRole:i=`public`,cors:a,cache:c,onError:u,resolution:d,menus:g,chrome:v,forms:k,site:ne}=t,re=new Map;for(let[e,n]of Object.entries(t.siteForHost??{})){if(!h(n))throw Error(`content-api: \`siteForHost['${e}']\` is ${JSON.stringify(n)}, which is not a site handle.`);re.set(e.trim().toLowerCase(),n)}function ie(e){if(!e.multiSite)return;let t=b()?.entities;return n=>{let r=t?.get(n);return r!==void 0&&!f(r)?`_`:e.site??`_`}}let A=()=>{let e=x();return(e?Xn.get(e):void 0)??r};Jn(`maxLimit`,t.maxLimit),Jn(`maxOffset`,t.maxOffset,{allowZero:!0}),Gt(c);let j=tt(c?.tags);if(!wn(i))throw Error(`content-api: \`publicRole\` must be a non-empty string, received ${JSON.stringify(i)}. An empty public role matches no permission yet is not the anonymous role either, so every unauthenticated request reaches the read path with no groups and fails as a 500. If this came from an environment variable, it is probably unset — omit the option to get "public".`);let se=Math.min(t.maxLimit??100,100),ce=Math.min(t.maxOffset??1e3,1e3),N=Dn(t),P=new on(t.limits),le=new jt(t.search,t.search?.getClientIp??t.limits?.getClientIp);zn(n);let ue;function I(){if(ue)return ue;let e=b(),t=n;if(e){t=[];for(let r of n){let n=e.entities.get(r.name);if(n===void 0){e.logger.error(`content-api: "${r.name}" is in createContentApiHandler({ entities }) but the app does not register an entity of that name — it is NOT served. Register it through lumi.config (entities or a plugin) or remove it from the whitelist.`);continue}t.push(n)}}let r={list:t,map:zn(t)};return e&&(ue=r),r}if(Object.hasOwn(t,`exposeInternalFields`))throw Error("content-api: `exposeInternalFields` has been removed (plan/api D024). Its only sanctioned use was publishing `_overrides`, which D011 replaced by composing site chrome SERVER-side — so the field no longer needs to reach the wire, and no other internal field was ever safe to list (`_workflowStatus` and `_workflowAssignee` describe an editorial process and name a user; `_version`/`_versionedAt` expose revision cadence). Fetch composed chrome from `GET /_chrome` instead. Remove the option: it is refused rather than ignored, because silently dropping a field you configured is exactly the failure this package throws at construction to prevent.");let fe=new Set(g?.handles??[]),L=ke(t.maxResolutionsPerDocument),pe=new e(5e3),_e=null,ve=0;async function ye(){let e=Date.now();return(!_e||e-ve>3e4)&&(_e=await t.loadPermissions(),ve=e),_e}function be(){_e=null,ve=0}function xe(){return{id:Sn,role:i,hasIdentity:!1}}function Ce(e){try{$().warn({err:e},"content-api: `authenticate` hook threw — serving the anonymous principal")}catch{console.warn("[content-api] `authenticate` hook threw:",e)}}async function Ee(e){if(!t.authenticate)return xe();let n;try{n=await t.authenticate(e)}catch(e){return Ce(e),xe()}if(!n||!wn(n.role)||n.id!==void 0&&!wn(n.id)||n.name!==void 0&&typeof n.name!=`string`||n.email!==void 0&&typeof n.email!=`string`||n.site!==void 0&&!(typeof n.site==`string`&&h(n.site)))return xe();let r=n.rateBudgetPerInstance!==void 0&&Number.isSafeInteger(n.rateBudgetPerInstance)&&n.rateBudgetPerInstance>=1;return{id:n.id??Sn,hasIdentity:n.id!==void 0,role:n.role,...n.name!==void 0&&{name:n.name},...n.email!==void 0&&{email:n.email},...r&&{rateBudgetPerInstance:n.rateBudgetPerInstance},...n.site!==void 0&&{site:n.site}}}function De(e){if(re.size===0)return;let t=(e.headers.get(`host`)??new URL(e.url).host).trim().toLowerCase();return re.get(t)}async function Ae(e,t){let n=S();if(t.site!==void 0&&n!==void 0&&n!==t.site)return K({credentialSite:t.site,mountSite:n},`content-api: a credential bound to one site was presented to a mount running as another`),null;let r=t.site??n??De(e),i=b();if(!i)return{...r!==void 0&&{site:r},multiSite:!1};let a=i.config.sites?.multiple===!0,o=r??await E(i).catch(()=>void 0);if(o===void 0)return{multiSite:a};let s=await w(i,o);return r!==void 0&&(s===void 0||s.status!==`active`)?null:{...r!==void 0&&{site:r},...s!==void 0&&{record:s},multiSite:a}}async function B(e){let t=b(),n=t?.config.sites?.multiple===!0;if(!t||!n)return a;if(!e.headers.has(`Origin`))return a??{allowedOrigins:[]};try{let e=await C(t);return e.truncated&&at(`site-origin-index-truncated`,{listed:e.byOrigin.size},`content-api: the site registry holds more active sites than the origin index reads — some sites’ CORS preflights will be refused`),{allowedOrigins:[...new Set([...a?.allowedOrigins??[],...e.byOrigin.keys()])],...a?.maxAge!==void 0&&{maxAge:a.maxAge}}}catch(e){return K({err:e},`content-api: could not read site origins for CORS`),a}}function V(e){return e.hasIdentity||e.role!==i?`identified`:e.site===void 0?`anonymous`:`site-keyed`}function H(e,t,n){return e(t,n,`view`)}function U(e){let t=y();return new ae({entity:e,db:t.db.readOnly,logger:$().child({entity:e.name}),countCache:pe,contextResolver:()=>{let e=x();if(!(!e?.user||!e?.checker))return{user:e.user,checker:e.checker,...e.scope!==void 0&&{scope:e.scope},...te(e,t)}}})}function W(e,n,i,a){let o={budget:Oe(L),cacheTags:a,resolveMedia:t.resolveMedia,resolveBlocks:t.resolveBlocks,siteOf:e=>T(e),afterExpand:async(e,t)=>{if(m(e)){for(let n of t)await ot(e,n,Fe(o),!1);return}await mt(e,t,o),await Ue(e,t,o)},locale:i,reachableEntity:t=>{let r=I().map.get(t);if(!(!r||r.name!==t))return H(e,n,r.name)?r:void 0},canReadEntity:t=>{let r=I().map.get(t);return r!==void 0&&r.name===t&&H(e,n,t)},collectionAllowance:Pe(12),templateDrawnTitle:async(e,n)=>{let s=t.detailTemplates,c=i??r;if(!s||c===void 0)return null;try{let t=await s.publicRow({entity:e.name,row:n,locale:c}),r=typeof t.title==`string`?t.title.trim():``;return r===``?null:r.slice(0,2e3)}catch(t){return o.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to project a reference title`),a.markUncacheable(),null}},readRowsByIds:async(e,t,n)=>{let a=Z(e.name)?.cols.id;return!a||t.length===0||L===0?[]:await U(e).findMany({where:F(a,[...t]),limit:Math.min(t.length,L),...n!==void 0&&{select:[...n]},...i!==void 0&&{locale:i},defaultLocale:r})},resolveEntityHref:t.resolveEntityHref,logger:je()};return o}function je(){try{return $()}catch{return}}function Me(e,t,n){let r=e.collectionAllowance?.refusedCount()??0;if(r>0)try{$().warn({entity:t,path:Q(n),cap:12,refused:r},`content-api: per-response collection cap reached — the collection blocks past it rendered empty`)}catch{console.warn(`[content-api] collection cap reached for`,t,Q(n))}if(e.budget.hasDrops)try{$().warn({entity:t,path:Q(n),ceiling:e.budget.ceiling,resolved:e.budget.granted,dropped:e.budget.dropSummary()},`content-api: per-document resolution budget exhausted — response rendered with unresolved targets`)}catch{console.warn(`[content-api] resolution budget exhausted for`,t,Q(n))}}function Ne(e,t,n,r){let i=Te(e,n);return i.requested>5?{response:J(`?populate= names ${i.requested} fields, which exceeds the maximum of 5.`,`VALIDATION_ERROR`,400,r)}:(i.dropped.length>0&&je()?.debug({entity:t.name,droppedPopulate:i.dropped},`content-api: rejected ?populate= fields (unknown, internal, or not a reference)`),{fields:new Set(i.fields)})}function Fe(e){return{...e,detailTemplates:t.detailTemplates,defaultLocale:r}}async function Ie(e,t,n,r,i){await un(e,t,n,r),await mt(e,t,r),await Ue(e,t,r),Me(r,e.name,i)}async function Le(e,t,n,i,a,l){let u=new URL(e.url),d=me.safeParse(R(u,{allowFilters:!0}));if(!d.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let{limit:f,offset:m,sort:h,locale:g,fields:_,search:v,cursor:y,populate:b}=d.data,x=u.searchParams.has(`limit`),S=Kn(`limit`,f,se,a,x);if(S)return S;let C=Kn(`offset`,m,ce,a);if(C)return C;let w=qn(f,se,x),T=t.allFields,E=Ne(b,t,T,a);if(`response`in E)return E.response;let D;if(y){let e=o(y);if(!e)return J(`Invalid cursor`,`VALIDATION_ERROR`,400,a);if(!Object.hasOwn(T,e.field)&&e.field!==`id`||e.field!==`id`&&z(e.field,T[e.field]))return J(`Invalid cursor field`,`VALIDATION_ERROR`,400,a);D=e}let O=[],ee=!1;if(v){let e=Hn(t,v,g??A());e&&(O.push(e),ee=!0)}let te=Gn(t.name,u,T);O.push(...te.conditions);let k=Wn(t,h,T),ne=k.orderBy;if(D!==void 0&&k.field!==void 0&&p(t,k.field))return J(`Invalid cursor for this sort`,`VALIDATION_ERROR`,400,a);let re=we(_,T);if(te.dropped.length>0||k.dropped!==void 0){let e=[...new Set(te.dropped)],n=e.slice(0,20).map(Q);$().info({entity:t.name,...te.dropped.length>0&&{droppedFilters:n,...e.length>n.length&&{droppedFiltersOmitted:e.length-n.length}},...k.dropped!==void 0&&{droppedSort:Q(k.dropped)}},`content-api: rejected query params (unknown, internal, or invalid)`)}let ie=U(t),j=g??A(),ae=ee,M={where:O.length>0?oe(...O):void 0,limit:ae?w+1:w,offset:m,orderBy:ne,select:re,locale:j,defaultLocale:r,cursor:D},[P,le]=await Promise.all([ie.findMany(M),ae?Promise.resolve(null):ie.count({where:O.length>0?oe(...O):void 0,locale:j})]),F=ae&&P.length>w?P.slice(0,w):P,ue=ae?P.length>w:m+w<(le??0),de;if(F.length>0&&F.length===w){let e=F[F.length-1],t=D?.field??k.field,n=D?.direction??(h?.startsWith(`-`)?`desc`:`asc`);t&&e[t]!==void 0&&(de=s(e,t,n))}l.addCollection(t.name);for(let e of F)l.addDocument(t.name,e.id);let I=W(i,n.role,j,l);return await Ie(t,F,E.fields,I,u.pathname),q({data:F,meta:{total:le,limit:w,offset:m,hasMore:ue,nextCursor:de}},200,X(t.name,a,V(n),c,N,l))}async function Re(e,t,n,r,i){let a=new URL(e.url),o=ge.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let s=await U(t).count({locale:o.data.locale??A()});return i.addCollection(t.name),q({data:{count:s}},200,X(t.name,r,V(n),c,N,i))}async function ze(e,t,n,i,a,o,s){if(!Se(n))return Y(o);let l=new URL(e.url),u=he.safeParse(R(l));if(!u.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let{locale:d,fields:f,populate:p,page:h}=u.data,g=t.allFields,_=m(t)?void 0:we(f,g),v=d??A(),y=Ne(p,t,g,o);if(`response`in y)return y.response;let b=await U(t).findById(n,{..._!==void 0&&{select:_},...v!==void 0&&{locale:v},defaultLocale:r});if(!b)return Y(o);s.addDocument(t.name,n);let x={...W(a,i.role,v,s),...h!==void 0&&h>1&&{page:h}};return m(t)?(await ot(t,b,Fe(x),!0),Me(x,t.name,l.pathname)):await Ie(t,[b],y.fields,x,l.pathname),q({data:b},200,X(t.name,o,V(i),c,N,s))}async function Be(e,t,n,i,a,o,s){let l=new URL(e.url),u=he.safeParse(R(l));if(!u.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let d=t.allFields;if(!d.slug)return Y(o);let{locale:f,fields:p,populate:m,page:h}=u.data,g=we(p,d),_=f??A(),v=Ne(m,t,d,o);if(`response`in v)return v.response;let b=Z(t.name);if(!b)return Y(o);let x=b.cols.slug,S=b.cols.id;if(!x||!S)return Y(o);let C=U(t),w=d.slug,E=M(x,n);if(w.translatable&&_){let e=Z(`${t.name}_translations`);if(e){let r=e.cols.slug,i=e.cols.locale,a=e.cols.entityId;if(r&&i&&a){let o=y(),s=await T(t,o),c=oe(M(r,n),M(i,_)),l=await o.db.readOnly.select({entityId:a}).from(e.table).where(s===void 0?c:oe(c,M(Bn(e.cols,t.name),s)));l.length>0&&(E=de(F(S,l.map(e=>e.entityId)),M(x,n))??M(x,n))}}}let D=await C.findMany({where:E,limit:1,select:g,locale:_,defaultLocale:r});if(D.length===0)return Y(o);s.addCollection(t.name),s.addDocument(t.name,D[0]?.id);let O={...W(a,i.role,_,s),...h!==void 0&&h>1&&{page:h}};return await Ie(t,D,v.fields,O,l.pathname),q({data:D[0]},200,X(t.name,o,V(i),c,N,s))}async function Ve(e,t,n,i,a,o){let s=new URL(e.url),l=he.safeParse(R(s));if(!l.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let{locale:u,fields:d,populate:f,page:p}=l.data,m=t.allFields,h=we(d,m),g=u??A(),_=Ne(f,t,m,a);if(`response`in _)return _.response;let v=(await U(t).findMany({limit:1,select:h,locale:g,defaultLocale:r}))[0];if(!v)return Y(a);o.addCollection(t.name),o.addDocument(t.name,v.id);let y={...W(i,n.role,g,o),...p!==void 0&&p>1&&{page:p}};return await Ie(t,[v],_.fields,y,s.pathname),q({data:v},200,X(t.name,a,V(n),c,N,o))}function G(e){return I().map.get(e)??I().map.get(e.endsWith(`s`)?e.slice(0,-1):e)}function We(e,t){if(process.env.NODE_ENV!==`development`)return;let n=JSON.stringify(e.slice(0,100)),r=t===void 0?`${n} is not in the content-api whitelist — add it to createContentApiHandler({ entities: [...] }) in your content route.`:`"${t.name}" is whitelisted but the requesting role lacks 'view' — grant it in the Permission Matrix, or seed it. Note that entity.access.view is advisory metadata the firewall never reads, so a restrictive value there is not the cause.`;console.warn(`[content-api] 404 for ${n}: ${r} (Both refusals are 404 by design — this line is the server-side disambiguation, and the response is unchanged.)`)}async function Ge(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=On.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{path:s,locale:l}=o.data,u=await d.resolvePath(s,l);if(u.kind===`none`)return Y(r);if(u.kind===`redirect`)return q({data:u},200,{...r,"Cache-Control":`no-store`});let f=G(u.entityType);return!f||!H(n,t.role,f.name)?(We(u.entityType,f),Y(r)):(i.addCollection(f.name),i.addDocument(f.name,u.id),q({data:u},200,X(f.name,r,V(t),c,N,i)))}async function qe(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=kn.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{locale:s,entity:l,cursor:u,limit:f}=o.data,p=a.searchParams.has(`limit`),m=Kn(`limit`,f,se,r,p);if(m)return m;let h=qn(f,se,p),g=G(l);if(!g||!H(n,t.role,g.name))return We(l,g),Y(r);let _=d.enumeratePaths({locale:s,entityType:g.name,...u!==void 0&&{afterDocumentId:u}}),v=[];for await(let e of _)if(v.push(e),v.length===h)break;let y=v.length===h,b=y?v[v.length-1]?.id:void 0;i.addCollection(g.name);for(let e of v)i.addDocument(g.name,e.id);return q({data:v,meta:{limit:h,hasMore:y,nextCursor:b}},200,X(g.name,r,V(t),c,N,i))}async function Je(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=An.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{entity:s,id:l}=o.data,u=G(s);if(!u||!H(n,t.role,u.name))return We(s,u),Y(r);let f=x()?.availableLocales,p=await d.getAlternates(u.name,l),m=f?p.filter(e=>f.includes(e.locale)):p;return i.addCollection(u.name),i.addDocument(u.name,l),q({data:m},200,X(u.name,r,V(t),c,N,i))}async function Ye(e,t,n,r){if(!g)return Y(n);let i=new URL(e.url),a=Fn.safeParse(R(i));if(!a.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,n);let{handle:o,locale:s,currentPath:l}=a.data;if(!fe.has(o))return Y(n);let u=await g.getMenu(o,{locale:s,...l!==void 0&&{currentPath:l}});return u?(r.addDocument(`_menu`,o),q({data:u},200,t.site===void 0?Xt(`_menu`,n,c,r):X(`_menu`,n,V(t),c,N,r))):Y(n)}async function Xe(e,t,n,r,i,a){if(!Nn.safeParse(R(new URL(e.url))).success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,i);let o=n.record;if(!o)return Y(i);let s=await ne?.getI18n(o.handle);if((s?.locales??o.locales).length===0)return at(`site-i18n-unwired:${o.handle}`,{site:o.handle},"content-api: GET /_site cannot answer — this site serves every enabled locale and the mount wires no `site.getI18n` to say which those are. Wire it (see the content route the admin app ships), or give the site an explicit locale list."),Y(i);let l=s?.locales??o.locales,u=s?.defaultLocale??r.defaultLocale??l[0];if(u===void 0)return Y(i);let d={handle:o.handle,name:o.name,locales:l.length>0?[...l]:[u],defaultLocale:u,routingStrategy:s?.routingStrategy??o.routingStrategy??`no-prefix-default`,origins:[...o.origins]};return a.addDocument(`_site`,o.handle),q({data:d},200,X(`_site`,i,V(t),c,N,a))}async function Ze(e,n,i,a,o,s){let u=le.consume(e,{principalId:n.hasIdentity?n.id:void 0,site:n.site});if(u&&!u.decision.allowed)return K({limit:`search`,keyClass:u.keyClass},`content-api: caller exceeded its visitor-search budget`),dt(u.decision.retryAfterSeconds,o);let d=new URL(e.url),f=_t.safeParse(R(d));if(!f.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let{q:p,types:m,limit:h,locale:g}=f.data,_=Kn(`limit`,h,50,o);if(_)return _;let v=yt(a.record?.searchTypes??[],m);if(v===null||v.length===0)return Y(o);let y=[];for(let e of v){let t=I().map.get(e);if(t!==void 0&&t.name===e&&H(i,n.role,e)&&vt(t)){y.push(t);continue}if(We(e,t),m!==void 0)return Y(o);at(`search-type:${a.site??``}:${e}`,{site:a.site,type:e},`content-api: a type in the site's searchTypes cannot be searched by this caller — it is skipped`)}if(y.length===0)return Y(o);let b=g??A(),x=[];for(let e of y){s.addCollection(e.name);let t=Hn(e,p,b);if(!t)continue;let n=await U(e).findMany({where:t,limit:h,orderBy:Un(e,p,b),locale:b,defaultLocale:r}),i=l(e),a=Object.hasOwn(e.allFields,i)?e.allFields[i]:void 0,o=a!==void 0&&Vn.has(a.type),c=[];for(let t of n){let n=t.id;if(typeof n!=`string`)continue;let{title:r,summary:a}=Et(e,t,i),s=t[i];c.push({hit:{entity:e,row:t,id:n,title:r,summary:a},titleHit:o&&typeof s==`string`&&Ot(s,p)})}c.length>0&&x.push({hits:c})}let S=Dt(x,h),C=W(i,n.role,b,s);for(let e of S)s.addDocument(e.entity.name,e.id);let w=new Map;for(let e of y){let t=S.filter(t=>t.entity===e);if(t.length===0)continue;let n=bt(e);if(n===null)continue;let r=t.map(e=>({id:e.id,[n]:e.row[n]}));await mt(e,r,C),t.forEach((e,t)=>{w.set(e,r[t]?.[n]??null)})}let T=t.resolveEntityHref,E=await O(S,async e=>{if(!T)return null;try{return await T({entity:e.entity.name,id:e.id,...b!==void 0&&{locale:b}})??null}catch(t){return $().debug({entity:e.entity.name,id:e.id,err:t},`content-api: resolveEntityHref threw — search result served without a path`),null}});return Me(C,`_search`,d.pathname),q({data:S.map((e,t)=>{let n=w.get(e);return{type:e.entity.name,typeLabel:St(e.entity),id:e.id,title:e.title,summary:e.summary,image:xt(n)?n:null,path:E[t]??null}}),meta:{limit:h}},200,X(`_search`,o,V(n),c,N,s))}async function Qe(e,n,r,i,a){if(!v)return Y(i);let o=new URL(e.url),s=Mn.safeParse(R(o));if(!s.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,i);let{locale:l,entity:u,id:d}=s.data;if(!H(r,n.role,v.entity))return Y(i);let f;if(u!==void 0&&d!==void 0){let e=G(u);e&&H(r,n.role,e.name)?f={entityType:e.name,id:d}:je()?.debug({entity:u,locale:l},`content-api: _chrome document is unreachable for this caller — serving the site default`)}a.addCollection(v.entity),f!==void 0&&a.addDocument(f.entityType,f.id);let p=W(r,n.role,l,a),m=await v.getChrome({locale:l,...f!==void 0&&{document:f},budget:p.budget}),h=e=>e&&typeof e==`object`?{blocks:Array.isArray(e.blocks)?e.blocks:[],overridden:e.overridden===!0}:null,g=async(e,n)=>{if(n===null||!t.resolveBlocks||n.blocks.length===0)return n;let r=await He(t.resolveBlocks,n.blocks,{locale:l,budget:p.budget,entity:v.entity,field:e,...p.canReadEntity!==void 0&&{canReadEntity:p.canReadEntity},...p.collectionAllowance!==void 0&&{claimCollection:p.collectionAllowance.claim}});r.failure===`threw`?je()?.warn({entity:v.entity,region:e,err:r.error},`content-api: block resolver threw — this chrome region is not served as stored; it was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them`):r.failure===`malformed`&&je()?.warn({entity:v.entity,region:e},`content-api: block resolver returned a value that is not a ResolvedBlockTree — this chrome region is not served as stored; it was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them`),r.retryFailure!==void 0&&(a.markUncacheable(),je()?.warn({entity:v.entity,region:e,err:r.error},`content-api: block resolver failed TWICE, including on the in-memory retry — serving this chrome region EMPTY, so whatever it held is missing from every page render. Serving the stored region instead would put the media urls recorded when an editor picked them, which may be signed, on a cacheable anonymous response`));let i=r.envelope;if(i.refs!==void 0)for(let e of i.refs)a.addDocument(e.entity,e.id);if(i.collections!==void 0)for(let e of Object.values(i.collections))e.entity!==null&&a.addCollection(e.entity);return{blocks:[...i.blocks],overridden:n.overridden,resolved:i.resolved,links:i.links,...i.unresolved!==void 0&&i.unresolved.length>0&&{unresolved:i.unresolved},...i.refs!==void 0&&i.refs.length>0&&{refs:i.refs},...i.collections!==void 0&&{collections:i.collections},...i.live!==void 0&&{live:i.live},...i.currency!==void 0&&{currency:i.currency}}},_={};for(let e of jn)_[e]=await g(e,h(m?.[e]));let y={header:_.header??null,footer:_.footer??null};return Me(p,v.entity,o.pathname),q({data:y},200,X(v.entity,i,V(n),c,N,a))}async function $e(e,t){let n=D(e),r={},i=S(),a={requestId:n,...i!==void 0&&{site:i}};return Zn(a),await ee(a,async()=>{let i=await ct(e,t,n,r);return et(i,n),nt(i,e,n,r),i})}function et(e,t){(e.headers.get(`Cache-Control`)??``).includes(`no-store`)&&e.headers.set(_,t)}function nt(e,t,n,r){if(!u||e.status<400)return;let i=ut(e);if(i!==void 0)try{Promise.resolve(u({status:e.status,code:i,path:Q(new URL(t.url).pathname),...r.entity!==void 0&&{entity:r.entity},requestId:n,...r.principalId!==void 0&&{principalId:r.principalId}})).catch(st)}catch(e){st(e)}}let it=new Set;function at(e,t,n){it.has(e)||(it.add(e),K(t,n))}function K(e,t){try{$().warn(e,t)}catch{try{console.warn(`[content-api]`,t,e)}catch{}}}function st(e){try{$().warn({err:e},"content-api: `onError` monitoring hook failed")}catch{}}async function ct(e,t,n,r){let i=Qt(e,await B(e)),a=Zt(i,N);try{await P.acquire(e.signal)}catch(e){return e instanceof en?(K({limit:`survival`,maxConcurrentRequests:P.limits.maxConcurrentRequests,maxQueuedRequests:P.limits.maxQueuedRequests},`content-api: shedding load — concurrency slots and wait queue both full`),ft(1,a)):(K({err:e},`content-api: acquiring a concurrency slot failed`),J(`Internal server error`,`INTERNAL_ERROR`,500,a))}try{return await P.runGuarded(a=>lt(e,t,n,r,i,a))}catch(e){if(e instanceof tn)return K({limit:`deadline`,requestTimeoutMs:P.limits.requestTimeoutMs},`content-api: request exceeded the wall clock`),ft(1,a);throw e}finally{P.release()}}async function lt(e,t,n,i,o,s){let c=o;try{let l=t.path;if(!l||l.length===0||l[0]!==`v1`)return Y(o);let u=l.slice(1);if(u.length===0)return Y(o);if(new URL(e.url).searchParams.has(`site`))return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,Zt(o,N));let f=await Ee(e),p=f.role,h=await Ae(e,f);if(h===null)return Y(Zt(a?{Vary:`Origin`}:{},N));let _=h.multiSite?Qt(e,{allowedOrigins:h.record?.origins??[],...a?.maxAge!==void 0&&{maxAge:a.maxAge}}):o,y=P.consumeFairness(e,{principalId:f.hasIdentity?f.id:void 0,budgetPerInstance:f.rateBudgetPerInstance}),b=Zt(_,N);c=b;let x=rt(j,ie(h));if(y&&!y.decision.allowed)return K({limit:`fairness`,keyClass:y.keyClass},`content-api: caller exceeded its per-instance budget`),dt(y.decision.retryAfterSeconds,b);let S=await ye();i.principalId=f.id;let C=h.site,w=await Qn(C,r),T=new URL(e.url).searchParams.get(`locale`);if(T!==null&&T!==``&&w.locales.length>0&&!w.locales.includes(T))return J(`Locale '${T}' is not served by this site`,`VALIDATION_ERROR`,400,b);let E={user:{id:f.id,groups:p?[p]:[],...f.name!==void 0&&{name:f.name},...f.email!==void 0&&{email:f.email}},checker:S,requestId:n,...C!==void 0&&{site:C},...w.locales.length>0&&{availableLocales:w.locales}};w.defaultLocale!==void 0&&Xn.set(E,w.defaultLocale),Zn(E);let D=await ee(E,async()=>{if(s?.aborted)throw new tn;if(e.method===`POST`){let t=It(u,`submissions`);return k===void 0||t===void 0?Y(b):zt({forms:k,keySite:f.site,formId:t,headers:b,req:e})}if(u[0]===`_forms`){let t=It(u,`token`);return k===void 0||t===void 0?Y(b):Rt({forms:k,keySite:f.site,formId:t,headers:b,req:e})}if(u[0]===`_schema`)return q(xn({entities:I().list,checkPermission:e=>H(S,p,e),version:`v1`,maxLimit:se,maxOffset:ce,maxResolutionsPerDocument:L,limits:P.limits,hasResolution:d!==void 0,hasMenus:g!==void 0,hasChrome:v!==void 0,cacheTags:j,siteScopedTags:h.multiSite}),200,{...b,"Cache-Control":`no-store`});if(u[0]===`_resolve`)return Ge(e,f,S,b,x);if(u[0]===`_paths`)return qe(e,f,S,b,x);if(u[0]===`_alternates`)return Je(e,f,S,b,x);if(u[0]===`_menu`)return Ye(e,f,b,x);if(u[0]===`_site`)return Xe(e,f,h,w,b,x);if(u[0]===`_chrome`)return Qe(e,f,S,b,x);if(u[0]===`_search`&&u.length===1)return Ze(e,f,S,h,b,x);let t=u[0];if(t===void 0)return Y(b);let n=G(t);if(!n||!H(S,p,n.name))return We(t,n),Y(b);if(i.entity=n.name,n.kind===`singleton`)return u.length===1?Ve(e,n,f,S,b,x):Y(b);if(m(n)){let t=u[1];return u.length===2&&t!==void 0?ze(e,n,t,f,S,b,x):Y(b)}return u.length===1?Le(e,n,f,S,b,x):u[1]===`count`?Re(e,n,f,b,x):u[1]===`slug`&&u[2]?Be(e,n,u[2],f,S,b,x):u.length===2&&u[1]!==void 0?ze(e,n,u[1],f,S,b,x):Y(b)});return x.dropped>0&&D.headers.has(j.header)&&K({dropped:x.dropped,emitted:x.tags.length,maxTags:128,maxHeaderBytes:Ke,...i.entity!==void 0&&{entity:i.entity},path:Q(new URL(e.url).pathname)},`content-api: cache tags refused — this response depends on documents it does not name, so a purge for them will not invalidate it`),D}catch(t){if(t instanceof tn)throw t;if(Pn(t))return Y(c);let n=new URL(e.url).pathname;try{$().error({err:t,path:Q(n)},`content-api handler error`)}catch{console.error(`[content-api] handler error:`,t)}return J(`Internal server error`,`INTERNAL_ERROR`,500,c)}}return{GET:(e,t)=>$e(e,t),POST:(e,t)=>$e(e,t),OPTIONS:async e=>$t(e,await B(e),c),invalidatePermissionCache:be}}export{Ln as API_VERSION,G as CACHE_TAG_NAMESPACE,ht as DEFAULT_SEARCH_RESULTS,it as DETAIL_TEMPLATE_FIELD,st as ERROR_CODES,Ge as MAX_CACHE_TAGS_PER_RESPONSE,Ke as MAX_CACHE_TAG_HEADER_BYTES,We as MAX_CACHE_TAG_LENGTH,Mt as MAX_FORM_BODY_BYTES,De as MAX_RESOLUTIONS_PER_DOCUMENT,gt as MAX_SEARCH_RESULTS,qe as MEDIA_TAG_ENTITY,Ye as SHARED_SITE_TAG_SEGMENT,kt as VISITOR_ADDRESS_HEADER,$n as createContentApiHandler,Le as isResolvedBlockTree};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|