@murumets-ee/content-api 0.1.4 → 0.1.5
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 +135 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +9 -9
- package/dist/index.d.ts +0 -179
- package/dist/index.js +0 -1
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { PermissionChecker } from "@murumets-ee/core";
|
|
2
|
+
import { Entity } from "@murumets-ee/entity";
|
|
3
|
+
|
|
4
|
+
//#region src/types.d.ts
|
|
5
|
+
/** CORS configuration — deny-by-default, explicit origin allowlist. */
|
|
6
|
+
interface CorsConfig {
|
|
7
|
+
/** Allowed origins. Each matched exactly — no regex, no wildcards. */
|
|
8
|
+
allowedOrigins: string[];
|
|
9
|
+
/** Preflight cache max age (seconds). Default: 3600 */
|
|
10
|
+
maxAge?: number;
|
|
11
|
+
}
|
|
12
|
+
/** Per-entity cache override. */
|
|
13
|
+
interface EntityCacheConfig {
|
|
14
|
+
/** Cache-Control max-age in seconds. */
|
|
15
|
+
maxAge?: number;
|
|
16
|
+
/** stale-while-revalidate window in seconds. */
|
|
17
|
+
staleWhileRevalidate?: number;
|
|
18
|
+
/** Whether this entity is cacheable. Default: true. Set false → no-store. */
|
|
19
|
+
cacheable?: boolean;
|
|
20
|
+
}
|
|
21
|
+
/** Global cache configuration. */
|
|
22
|
+
interface CacheConfig {
|
|
23
|
+
/** Default max-age for all entities (seconds). Default: 60 */
|
|
24
|
+
defaultMaxAge?: number;
|
|
25
|
+
/** Default stale-while-revalidate (seconds). Default: 300 */
|
|
26
|
+
defaultStaleWhileRevalidate?: number;
|
|
27
|
+
/** Per-entity overrides, keyed by entity name. */
|
|
28
|
+
entities?: Record<string, EntityCacheConfig>;
|
|
29
|
+
}
|
|
30
|
+
/** Content API handler configuration. */
|
|
31
|
+
interface ContentApiConfig {
|
|
32
|
+
/** Entity whitelist — ONLY these entities are queryable. Deny-by-default. */
|
|
33
|
+
entities: Entity[];
|
|
34
|
+
/**
|
|
35
|
+
* Permission checker — REQUIRED. Same pattern as admin API handler.
|
|
36
|
+
* Called lazily on first request, result cached with 30s TTL.
|
|
37
|
+
* Checks: `checker(role, entityName, 'view')` → boolean.
|
|
38
|
+
*/
|
|
39
|
+
loadPermissions: () => Promise<PermissionChecker>;
|
|
40
|
+
/**
|
|
41
|
+
* Optional auth. Returns user role, or null for anonymous.
|
|
42
|
+
* When null or not provided → uses `publicRole`.
|
|
43
|
+
*
|
|
44
|
+
* Enables preview mode (e.g. bearer token → editor sees more entities).
|
|
45
|
+
*/
|
|
46
|
+
authenticate?: (req: Request) => Promise<{
|
|
47
|
+
role: string;
|
|
48
|
+
} | null>;
|
|
49
|
+
/**
|
|
50
|
+
* Role for unauthenticated requests. Default: `'public'`.
|
|
51
|
+
* Must have explicit 'view' permission per entity to see anything.
|
|
52
|
+
*/
|
|
53
|
+
publicRole?: string;
|
|
54
|
+
/** Default content locale for translation merging. */
|
|
55
|
+
defaultLocale?: string;
|
|
56
|
+
/** CORS configuration. Required when serving cross-origin. */
|
|
57
|
+
cors?: CorsConfig;
|
|
58
|
+
/** Cache-Control header configuration. */
|
|
59
|
+
cache?: CacheConfig;
|
|
60
|
+
/** Max pagination limit. Default: 100. Hard-capped at 100. */
|
|
61
|
+
maxLimit?: number;
|
|
62
|
+
/** Error hook for monitoring/logging. Errors are fire-and-forget. */
|
|
63
|
+
onError?: (err: {
|
|
64
|
+
status: number;
|
|
65
|
+
message: string;
|
|
66
|
+
entity?: string;
|
|
67
|
+
path: string;
|
|
68
|
+
}) => void;
|
|
69
|
+
}
|
|
70
|
+
interface ContentListResponse<T = Record<string, unknown>> {
|
|
71
|
+
data: T[];
|
|
72
|
+
meta: {
|
|
73
|
+
total: number;
|
|
74
|
+
limit: number;
|
|
75
|
+
offset: number;
|
|
76
|
+
hasMore: boolean; /** Opaque cursor for fetching the next page via keyset pagination. */
|
|
77
|
+
nextCursor?: string;
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
interface ContentSingleResponse<T = Record<string, unknown>> {
|
|
81
|
+
data: T;
|
|
82
|
+
}
|
|
83
|
+
interface ContentCountResponse {
|
|
84
|
+
data: {
|
|
85
|
+
count: number;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
interface ContentErrorResponse {
|
|
89
|
+
error: {
|
|
90
|
+
status: number;
|
|
91
|
+
message: string;
|
|
92
|
+
code: string;
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/** Field metadata exposed by /_schema (public-safe subset of FieldConfig). */
|
|
96
|
+
interface SchemaField {
|
|
97
|
+
type: string;
|
|
98
|
+
required?: boolean;
|
|
99
|
+
options?: readonly string[];
|
|
100
|
+
cardinality?: 'one' | 'many';
|
|
101
|
+
}
|
|
102
|
+
/** Entity metadata exposed by /_schema. */
|
|
103
|
+
interface SchemaEntity {
|
|
104
|
+
name: string;
|
|
105
|
+
pluralName: string;
|
|
106
|
+
fields: Record<string, SchemaField>;
|
|
107
|
+
}
|
|
108
|
+
/** Full /_schema response. */
|
|
109
|
+
interface SchemaResponse {
|
|
110
|
+
entities: SchemaEntity[];
|
|
111
|
+
}
|
|
112
|
+
/** Next.js catch-all route context shape. */
|
|
113
|
+
interface RouteContext {
|
|
114
|
+
params: Promise<{
|
|
115
|
+
path: string[];
|
|
116
|
+
}>;
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
//#region src/handler.d.ts
|
|
120
|
+
declare function createContentApiHandler(config: ContentApiConfig): {
|
|
121
|
+
GET: (req: Request, ctx: RouteContext) => Promise<Response>;
|
|
122
|
+
OPTIONS: (req: Request) => Response;
|
|
123
|
+
};
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/schema-endpoint.d.ts
|
|
126
|
+
/** Convert an Entity to public-safe schema metadata. */
|
|
127
|
+
declare function toSchemaEntity(entity: Entity): SchemaEntity;
|
|
128
|
+
/**
|
|
129
|
+
* Build the full /_schema response.
|
|
130
|
+
* Only includes entities that pass the permission check.
|
|
131
|
+
*/
|
|
132
|
+
declare function buildSchemaResponse(entities: Entity[], checkPermission: (entityName: string) => boolean): SchemaResponse;
|
|
133
|
+
//#endregion
|
|
134
|
+
export { type CacheConfig, type ContentApiConfig, type ContentCountResponse, type ContentErrorResponse, type ContentListResponse, type ContentSingleResponse, type CorsConfig, type EntityCacheConfig, type RouteContext, type SchemaEntity, type SchemaField, type SchemaResponse, buildSchemaResponse, createContentApiHandler, toSchemaEntity };
|
|
135
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/handler.ts","../src/schema-endpoint.ts"],"mappings":";;;;;UAciB,UAAA;EAYA;EAVf,cAAA;;EAEA,MAAA;AAAA;;UAQe,iBAAA;EAMN;EAJT,MAAA;EAQe;EANf,oBAAA;;EAEA,SAAA;AAAA;;UAIe,WAAA;EAMJ;EAJX,aAAA;EAI2C;EAF3C,2BAAA;EAUe;EARf,QAAA,GAAW,MAAA,SAAe,iBAAA;AAAA;;UAQX,gBAAA;EASQ;EAPvB,QAAA,EAAU,MAAA;EAeuB;;;;;EARjC,eAAA,QAAuB,OAAA,CAAQ,iBAAA;EAPrB;;;;;;EAeV,YAAA,IAAgB,GAAA,EAAK,OAAA,KAAY,OAAA;IAAU,IAAA;EAAA;EAM3C;;;;EAAA,UAAA;EASQ;EANR,aAAA;EAYA;EATA,IAAA,GAAO,UAAA;EAS2B;EANlC,KAAA,GAAQ,WAAA;EAM4D;EAHpE,QAAA;EAGkF;EAAlF,OAAA,IAAW,GAAA;IAAO,MAAA;IAAgB,OAAA;IAAiB,MAAA;IAAiB,IAAA;EAAA;AAAA;AAAA,UAOrD,mBAAA,KAAwB,MAAA;EACvC,IAAA,EAAM,CAAA;EACN,IAAA;IACE,KAAA;IACA,KAAA;IACA,MAAA;IACA,OAAA,WAEA;IAAA,UAAA;EAAA;AAAA;AAAA,UAIa,qBAAA,KAA0B,MAAA;EACzC,IAAA,EAAM,CAAA;AAAA;AAAA,UAGS,oBAAA;EACf,IAAA;IAAQ,KAAA;EAAA;AAAA;AAAA,UAGO,oBAAA;EACf,KAAA;IACE,MAAA;IACA,OAAA;IACA,IAAA;EAAA;AAAA;;UASa,WAAA;EACf,IAAA;EACA,QAAA;EACA,OAAA;EACA,WAAA;AAAA;;UAIe,YAAA;EACf,IAAA;EACA,UAAA;EACA,MAAA,EAAQ,MAAA,SAAe,WAAA;AAAA;;UAIR,cAAA;EACf,QAAA,EAAU,YAAA;AAAA;;UAQK,YAAA;EACf,MAAA,EAAQ,OAAA;IAAU,IAAA;EAAA;AAAA;;;iBCHJ,uBAAA,CAAwB,MAAA,EAAQ,gBAAA;aAsWjC,OAAA,EAAO,GAAA,EAAO,YAAA,KAAY,OAAA,CAAA,QAAA;iBACtB,OAAA,KAAO,QAAA;AAAA;;;;iBC1dV,cAAA,CAAe,MAAA,EAAQ,MAAA,GAAS,YAAA;;;;AFChD;iBEoBgB,mBAAA,CACd,QAAA,EAAU,MAAA,IACV,eAAA,GAAkB,UAAA,uBACjB,cAAA"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{getApp as e}from"@murumets-ee/core";import{schemaRegistry as t}from"@murumets-ee/db";import{CountCache as n,decodeCursor as r,encodeCursor as i,estimateRowCount as a}from"@murumets-ee/entity";import{QueryClient as o}from"@murumets-ee/entity/query";import{and as s,asc as c,desc as l,eq as u,gte as d,ilike as f,inArray as p,lte as m,or as h}from"drizzle-orm";import{z as g}from"zod";function _(e,t){let n=t?.entities?.[e];if(n?.cacheable===!1)return{"Cache-Control":`no-store`};let r=n?.maxAge??t?.defaultMaxAge??60,i=n?.staleWhileRevalidate??t?.defaultStaleWhileRevalidate??300;return{"Cache-Control":`public, max-age=${r}, stale-while-revalidate=${i}`}}function v(e,t){if(!t)return{};let n=e.headers.get(`Origin`);return!n||!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`}}function y(e,t){let n=v(e,t);return new Response(null,{status:204,headers:n})}const b=g.object({limit:g.coerce.number().int().min(1).max(100).default(20),offset:g.coerce.number().int().min(0).default(0),sort:g.string().regex(/^-?[a-zA-Z_]+$/).optional(),locale:g.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/).optional(),fields:g.string().optional(),search:g.string().max(200).optional(),cursor:g.string().max(500).optional()}),x=g.object({locale:g.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/).optional(),fields:g.string().optional()}),S=g.object({locale:g.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/).optional()});function C(e){return e.replace(/[%_\\]/g,`\\$&`)}const w=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function T(e,t){switch(e.type){case`boolean`:return t===`true`?!0:t===`false`?!1:null;case`reference`:case`media`:return w.test(t)?t:null;case`select`:return e.options.includes(t)?t:null;case`date`:return t;case`text`:case`number`:return t;default:return null}}function E(e,t){if(!e)return;let n=e.split(`,`).map(e=>e.trim()).filter(e=>e in t&&!e.startsWith(`_`)&&t[e].type!==`blocks`);return n.length>0&&!n.includes(`id`)&&n.unshift(`id`),n.length>0?n:void 0}function D(e,t=200,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`,...n}})}function O(e,t,n,r){return D({error:{status:n,message:e,code:t}},n,r)}function k(e){return O(`Not found`,`NOT_FOUND`,404,e)}function A(e){let t={type:e.type};return e.required&&(t.required=!0),e.type===`select`&&(t.options=e.options),e.type===`reference`&&(t.cardinality=e.cardinality),t}function j(e){let t=e.allFields,n={};for(let[e,r]of Object.entries(t))e.startsWith(`_`)||(n[e]=A(r));return{name:e.name,pluralName:`${e.name}s`,fields:n}}function M(e,t){return{entities:e.filter(e=>t(e.name)).map(j)}}function N(e){let t=new Map;for(let n of e)t.set(n.name,n),t.set(`${n.name}s`,n);return t}function P(e,n){let r=t.get(e.name);if(!r)return;let i=e.allFields;for(let[e,t]of Object.entries(i))if(t.type===`text`&&(t.indexed||t.required)){let t=r[e];if(t)return f(t,`%${C(n)}%`)}}function F(e,n,r){if(!n)return;let i=n.startsWith(`-`),a=i?n.slice(1):n,o=r[a];if(!o||o.type===`blocks`)return;let s=t.get(e);if(!(!s||!s[a]))return i?l(s[a]):c(s[a])}function I(e,n,r){let i=t.get(e);if(!i)return[];let a=[];for(let[e,t]of n.searchParams.entries()){let n=e.match(/^filter\[([a-zA-Z_]+)\]$/);if(!n)continue;let o=n[1],s=r[o];if(!s||s.type===`blocks`)continue;let c=i[o];if(!c)continue;if(s.type===`date`){t.startsWith(`gte:`)?a.push(d(c,t.slice(4))):t.startsWith(`lte:`)?a.push(m(c,t.slice(4))):a.push(u(c,t));continue}let l=T(s,t);l!==null&&a.push(u(c,l))}return a}function L(c){let{entities:l,defaultLocale:d,publicRole:f=`public`,cors:m,cache:g,onError:C}=c,w=Math.min(c.maxLimit??100,100),T=N(l),A=new n(5e3),j=null,L=0;async function R(){let e=Date.now();return(!j||e-L>3e4)&&(j=await c.loadPermissions(),L=e),j}async function z(e){if(!c.authenticate)return f;try{return(await c.authenticate(e))?.role??f}catch{return f}}function B(e,t,n){return e(t,n,`view`)}function V(t){let n=e();return new o({entity:t,db:n.db.readOnly,logger:n.logger.child({entity:t.name}),countCache:A})}async function H(e,t,n){let a=new URL(e.url),o=b.safeParse(Object.fromEntries(a.searchParams));if(!o.success)return O(`Invalid query parameters`,`VALIDATION_ERROR`,400,n);let{limit:c,offset:l,sort:u,locale:f,fields:p,search:m,cursor:h}=o.data,v=Math.min(c,w),y=t.allFields,x;if(h){let e=r(h);if(!e)return O(`Invalid cursor`,`VALIDATION_ERROR`,400,n);if(!(e.field in y)&&e.field!==`id`)return O(`Invalid cursor field`,`VALIDATION_ERROR`,400,n);x=e}let S=[];if(m){let e=P(t,m);e&&S.push(e)}let C=I(t.name,a,y);S.push(...C);let T=F(t.name,u,y),k=E(p,y),A=V(t),j=f??d,M={where:S.length>0?s(...S):void 0,limit:v,offset:l,orderBy:T,select:k,locale:j,defaultLocale:d,cursor:x},[N,L]=await Promise.all([A.findMany(M),A.count({where:S.length>0?s(...S):void 0})]),R;if(N.length>0&&N.length===v){let e=N[N.length-1],t=x?.field??(u?u.startsWith(`-`)?u.slice(1):u:void 0),n=x?.direction??(u?.startsWith(`-`)?`desc`:`asc`);t&&e[t]!==void 0&&(R=i(e,t,n))}let z={...n,..._(t.name,g)};return D({data:N,meta:{total:L,limit:v,offset:l,hasMore:l+v<L,nextCursor:R}},200,z)}async function U(t,n,r){let i=new URL(t.url);return S.safeParse(Object.fromEntries(i.searchParams)).success?i.searchParams.get(`countMode`)===`estimate`?D({data:{count:await a(e().db.readOnly,n.name),estimate:!0}},200,{...r,..._(n.name,g)}):D({data:{count:await V(n).count()}},200,{...r,..._(n.name,g)}):O(`Invalid query parameters`,`VALIDATION_ERROR`,400,r)}async function W(e,t,n,r){let i=new URL(e.url),a=x.safeParse(Object.fromEntries(i.searchParams));if(!a.success)return O(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{locale:o,fields:s}=a.data,c=t.allFields,l=E(s,c),u=o??d,f=await V(t).findById(n,{select:l,locale:u,defaultLocale:d});return f?D({data:f},200,{...r,..._(t.name,g)}):k(r)}async function G(n,r,i,a){let o=new URL(n.url),c=x.safeParse(Object.fromEntries(o.searchParams));if(!c.success)return O(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let l=r.allFields;if(!l.slug)return k(a);let{locale:f,fields:m}=c.data,v=E(m,l),y=f??d,b=t.get(r.name);if(!b?.slug)return k(a);let S=V(r),C=l.slug,w=u(b.slug,i);if(C.translatable&&y){let n=`${r.name}_translations`,a=t.get(n);if(a?.slug){let t=await e().db.readOnly.select({entityId:a.entityId}).from(a).where(s(u(a.slug,i),u(a.locale,y)));if(t.length>0){let e=t.map(e=>e.entityId);w=h(p(b.id,e),u(b.slug,i))}}}let T=await S.findMany({where:w,limit:1,select:v,locale:y,defaultLocale:d});return T.length===0?k(a):D({data:T[0]},200,{...a,..._(r.name,g)})}async function K(e,t){let n=v(e,m);try{let r=await t.params.then(e=>e.path);if(!r||r.length===0)return k(n);let i=await z(e),a=await R();if(r[0]===`_schema`)return D(M(l,e=>B(a,i,e)),200,{...n,"Cache-Control":`no-store`});let o=r[0],s=T.get(o)??T.get(o.endsWith(`s`)?o.slice(0,-1):o);return!s||!B(a,i,s.name)?k(n):r.length===1?H(e,s,n):r[1]===`count`?U(e,s,n):r[1]===`slug`&&r[2]?G(e,s,r[2],n):r.length===2?W(e,s,r[1],n):k(n)}catch(t){let r=t instanceof Error?t.message:`Internal server error`;return console.error(`[content-api] handler error:`,t),C?.({status:500,message:r,path:new URL(e.url).pathname}),O(`Internal server error`,`INTERNAL_ERROR`,500,n)}}return{GET:(e,t)=>K(e,t),OPTIONS:e=>y(e,m)}}export{M as buildSchemaResponse,L as createContentApiHandler,j as toSchemaEntity};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/cache.ts","../src/cors.ts","../src/query-params.ts","../src/response.ts","../src/schema-endpoint.ts","../src/handler.ts"],"sourcesContent":["/**\n * Cache-Control header builder.\n *\n * Defaults: public, max-age=60, stale-while-revalidate=300.\n * Per-entity overrides for hot content (low TTL) vs static pages (high TTL).\n */\n\nimport type { CacheConfig } from './types.js'\n\nexport function buildCacheHeaders(\n entityName: string,\n config: CacheConfig | undefined,\n): Record<string, string> {\n const entityConfig = config?.entities?.[entityName]\n\n if (entityConfig?.cacheable === false) {\n return { 'Cache-Control': 'no-store' }\n }\n\n const maxAge = entityConfig?.maxAge ?? config?.defaultMaxAge ?? 60\n const swr = entityConfig?.staleWhileRevalidate ?? config?.defaultStaleWhileRevalidate ?? 300\n\n return {\n 'Cache-Control': `public, max-age=${maxAge}, stale-while-revalidate=${swr}`,\n }\n}\n","/**\n * CORS — Origin allowlist with exact match.\n *\n * No wildcards, no regex. This is a CMS content API — you know which\n * frontends consume it. Vary: Origin ensures CDNs cache per-origin.\n */\n\nimport type { CorsConfig } from './types.js'\n\nexport function buildCorsHeaders(\n req: Request,\n config: CorsConfig | undefined,\n): Record<string, string> {\n if (!config) return {}\n\n const origin = req.headers.get('Origin')\n if (!origin) return {}\n\n // Exact match only\n if (!config.allowedOrigins.includes(origin)) return {}\n\n return {\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': 'GET, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Accept, Authorization',\n 'Access-Control-Max-Age': String(config.maxAge ?? 3600),\n Vary: 'Origin',\n }\n}\n\nexport function corsPreflightResponse(req: Request, config: CorsConfig | undefined): Response {\n const headers = buildCorsHeaders(req, config)\n return new Response(null, { status: 204, headers })\n}\n","/**\n * Query parameter validation — Zod schemas for all content API endpoints.\n *\n * All user input is validated before it touches QueryClient.\n * Pagination hard-capped at MAX_LIMIT. Sort/filter restricted to queryable columns.\n */\n\nimport type { FieldConfig } from '@murumets-ee/entity'\nimport { z } from 'zod'\n\nexport const MAX_LIMIT = 100\n\n/** List endpoint query params. */\nexport const listParamsSchema = z.object({\n limit: z.coerce.number().int().min(1).max(MAX_LIMIT).default(20),\n offset: z.coerce.number().int().min(0).default(0),\n sort: z\n .string()\n .regex(/^-?[a-zA-Z_]+$/)\n .optional(),\n locale: z\n .string()\n .regex(/^[a-z]{2}(-[A-Z]{2})?$/)\n .optional(),\n fields: z.string().optional(),\n search: z.string().max(200).optional(),\n /** Opaque cursor for keyset pagination (base64-encoded JSON). */\n cursor: z.string().max(500).optional(),\n})\n\n/** Single entity query params. */\nexport const singleParamsSchema = z.object({\n locale: z\n .string()\n .regex(/^[a-z]{2}(-[A-Z]{2})?$/)\n .optional(),\n fields: z.string().optional(),\n})\n\n/** Count endpoint query params. */\nexport const countParamsSchema = z.object({\n locale: z\n .string()\n .regex(/^[a-z]{2}(-[A-Z]{2})?$/)\n .optional(),\n})\n\n/** Escape LIKE wildcards to prevent wildcard injection in search queries. */\nexport function escapeLikePattern(s: string): string {\n return s.replace(/[%_\\\\]/g, '\\\\$&')\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/**\n * Validate a filter value against the field type.\n * Returns the validated value or null if invalid.\n */\nexport function validateFilterValue(fieldConfig: FieldConfig, raw: string): unknown {\n switch (fieldConfig.type) {\n case 'boolean':\n if (raw === 'true') return true\n if (raw === 'false') return false\n return null\n\n case 'reference':\n case 'media':\n return UUID_RE.test(raw) ? raw : null\n\n case 'select':\n return fieldConfig.options.includes(raw) ? raw : null\n\n case 'date':\n // Plain date or gte:/lte: prefix handled by caller\n return raw\n\n case 'text':\n case 'number':\n return raw\n\n default:\n return null\n }\n}\n\n/**\n * Parse field selection string into validated field names.\n * Unknown/internal field names are silently dropped (no info leakage).\n */\nexport function parseFieldSelection(\n fieldsParam: string | undefined,\n allFields: Record<string, FieldConfig>,\n): string[] | undefined {\n if (!fieldsParam) return undefined\n\n const requested = fieldsParam.split(',').map((f) => f.trim())\n const valid = requested.filter(\n (name) => name in allFields && !name.startsWith('_') && allFields[name].type !== 'blocks',\n )\n\n // Always include id\n if (valid.length > 0 && !valid.includes('id')) {\n valid.unshift('id')\n }\n\n return valid.length > 0 ? valid : undefined\n}\n","/**\n * Response helpers — JSON envelope builders.\n */\n\nexport function jsonResponse(\n data: unknown,\n status = 200,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n ...extraHeaders,\n },\n })\n}\n\nexport function errorResponse(\n message: string,\n code: string,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return jsonResponse({ error: { status, message, code } }, status, extraHeaders)\n}\n\nexport function notFoundResponse(extraHeaders?: Record<string, string>): Response {\n return errorResponse('Not found', 'NOT_FOUND', 404, extraHeaders)\n}\n","/**\n * Schema introspection endpoint — GET /_schema\n *\n * Returns public-safe entity metadata for SDK generation.\n * Only exposes: type, required, options (select), cardinality (reference).\n * Internal fields (_version, _scopeId) excluded.\n * No hooks, behaviors, access rules, or implementation details.\n *\n * Response is filtered by the caller's role permissions — only entities\n * the role can 'view' are included.\n */\n\nimport type { Entity, FieldConfig } from '@murumets-ee/entity'\nimport type { SchemaEntity, SchemaField, SchemaResponse } from './types.js'\n\n/** Convert a FieldConfig to the public-safe SchemaField subset. */\nfunction toSchemaField(config: FieldConfig): SchemaField {\n const field: SchemaField = { type: config.type }\n\n if (config.required) {\n field.required = true\n }\n\n if (config.type === 'select') {\n field.options = config.options\n }\n\n if (config.type === 'reference') {\n field.cardinality = config.cardinality\n }\n\n return field\n}\n\n/** Convert an Entity to public-safe schema metadata. */\nexport function toSchemaEntity(entity: Entity): SchemaEntity {\n const allFields = entity.allFields as Record<string, FieldConfig>\n const fields: Record<string, SchemaField> = {}\n\n for (const [name, config] of Object.entries(allFields)) {\n // Skip internal fields\n if (name.startsWith('_')) continue\n fields[name] = toSchemaField(config)\n }\n\n return {\n name: entity.name,\n pluralName: `${entity.name}s`,\n fields,\n }\n}\n\n/**\n * Build the full /_schema response.\n * Only includes entities that pass the permission check.\n */\nexport function buildSchemaResponse(\n entities: Entity[],\n checkPermission: (entityName: string) => boolean,\n): SchemaResponse {\n const visible = entities.filter((e) => checkPermission(e.name))\n return {\n entities: visible.map(toSchemaEntity),\n }\n}\n","/**\n * Content API handler factory\n *\n * Creates a read-only catch-all route handler for public content delivery.\n * Mirrors the `createAdminApiHandler` pattern but with:\n * - No mutations (GET + OPTIONS only)\n * - Permission-gated (public role starts with 0 permissions)\n * - Published content only (QueryClient auto-filters)\n * - CORS + Cache-Control headers\n *\n * @example\n * ```typescript\n * // app/api/content/[...path]/route.ts\n * import { createContentApiHandler } from '@murumets-ee/content-api'\n * import { Article, Page } from '@/entities'\n *\n * const handler = createContentApiHandler({\n * entities: [Article, Page],\n * loadPermissions: async () => {\n * const roles = await loadRoles(getApp())\n * return buildPermissionChecker(roles)\n * },\n * cors: { allowedOrigins: ['https://www.example.com'] },\n * })\n *\n * export const { GET, OPTIONS } = handler\n * ```\n */\n\nimport type { PermissionChecker } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { schemaRegistry } from '@murumets-ee/db'\nimport type { CursorInput, Entity, FieldConfig, SlugField } from '@murumets-ee/entity'\nimport { CountCache, decodeCursor, encodeCursor, estimateRowCount } from '@murumets-ee/entity'\nimport { QueryClient } from '@murumets-ee/entity/query'\nimport { and, asc, desc, eq, gte, ilike, inArray, lte, or, type SQL } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport { buildCacheHeaders } from './cache.js'\nimport { buildCorsHeaders, corsPreflightResponse } from './cors.js'\nimport {\n countParamsSchema,\n escapeLikePattern,\n listParamsSchema,\n MAX_LIMIT,\n parseFieldSelection,\n singleParamsSchema,\n validateFilterValue,\n} from './query-params.js'\nimport { errorResponse, jsonResponse, notFoundResponse } from './response.js'\nimport { buildSchemaResponse } from './schema-endpoint.js'\nimport type { ContentApiConfig, RouteContext } from './types.js'\n\n// ---------------------------------------------------------------------------\n// Entity resolution (whitelist-based, same pattern as admin handler)\n// ---------------------------------------------------------------------------\n\nfunction buildEntityMap(entities: Entity[]): Map<string, Entity> {\n const map = new Map<string, Entity>()\n for (const entity of entities) {\n map.set(entity.name, entity)\n map.set(`${entity.name}s`, entity)\n }\n return map\n}\n\n// ---------------------------------------------------------------------------\n// Query helpers\n// ---------------------------------------------------------------------------\n\nfunction buildSearchCondition(entity: Entity, search: string): SQL | undefined {\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n const table = schemaRegistry.get(entity.name) as PgTableWithColumns<any> | undefined\n if (!table) return undefined\n\n const allFields = entity.allFields as Record<string, FieldConfig>\n for (const [fieldName, config] of Object.entries(allFields)) {\n if (config.type === 'text' && (config.indexed || config.required)) {\n const column = table[fieldName]\n if (column) return ilike(column, `%${escapeLikePattern(search)}%`)\n }\n }\n return undefined\n}\n\nfunction buildOrderBy(\n entityName: string,\n sortParam: string | undefined,\n allFields: Record<string, FieldConfig>,\n): SQL | undefined {\n if (!sortParam) return undefined\n\n const descending = sortParam.startsWith('-')\n const fieldName = descending ? sortParam.slice(1) : sortParam\n\n const fieldConfig = allFields[fieldName]\n if (!fieldConfig || fieldConfig.type === 'blocks') return undefined\n\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n const table = schemaRegistry.get(entityName) as PgTableWithColumns<any> | undefined\n if (!table || !table[fieldName]) return undefined\n\n return descending ? desc(table[fieldName]) : asc(table[fieldName])\n}\n\nfunction buildFilterConditions(\n entityName: string,\n url: URL,\n allFields: Record<string, FieldConfig>,\n): SQL[] {\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n const table = schemaRegistry.get(entityName) as PgTableWithColumns<any> | undefined\n if (!table) return []\n\n const conditions: SQL[] = []\n\n for (const [key, raw] of url.searchParams.entries()) {\n const match = key.match(/^filter\\[([a-zA-Z_]+)\\]$/)\n if (!match) continue\n\n const fieldName = match[1]\n const fieldConfig = allFields[fieldName]\n if (!fieldConfig || fieldConfig.type === 'blocks') continue\n\n const column = table[fieldName]\n if (!column) continue\n\n // Date range filters: gte: / lte: prefix\n if (fieldConfig.type === 'date') {\n if (raw.startsWith('gte:')) {\n conditions.push(gte(column, raw.slice(4)))\n } else if (raw.startsWith('lte:')) {\n conditions.push(lte(column, raw.slice(4)))\n } else {\n conditions.push(eq(column, raw))\n }\n continue\n }\n\n const validated = validateFilterValue(fieldConfig, raw)\n if (validated === null) continue\n conditions.push(eq(column, validated))\n }\n\n return conditions\n}\n\n// ---------------------------------------------------------------------------\n// Handler factory\n// ---------------------------------------------------------------------------\n\nexport function createContentApiHandler(config: ContentApiConfig) {\n const {\n entities,\n defaultLocale,\n publicRole = 'public',\n cors: corsConfig,\n cache: cacheConfig,\n onError,\n } = config\n const maxLimit = Math.min(config.maxLimit ?? MAX_LIMIT, MAX_LIMIT)\n const entityMap = buildEntityMap(entities)\n\n // Shared count cache — reduces COUNT(*) queries on paginated list pages.\n const countCache = new CountCache(5000)\n\n // Lazy-loaded permission checker — cached with 30s TTL\n const PERMISSION_CACHE_TTL_MS = 30_000\n let permissionChecker: PermissionChecker | null = null\n let permissionCacheTime = 0\n\n async function getChecker(): Promise<PermissionChecker> {\n const now = Date.now()\n if (!permissionChecker || now - permissionCacheTime > PERMISSION_CACHE_TTL_MS) {\n permissionChecker = await config.loadPermissions()\n permissionCacheTime = now\n }\n return permissionChecker\n }\n\n // -- Role resolution -------------------------------------------------------\n\n async function resolveRole(req: Request): Promise<string> {\n if (!config.authenticate) return publicRole\n try {\n const result = await config.authenticate(req)\n return result?.role ?? publicRole\n } catch {\n return publicRole\n }\n }\n\n // -- Permission check (returns 404 on deny to avoid info leakage) ----------\n\n function hasViewPermission(\n checker: PermissionChecker,\n role: string,\n entityName: string,\n ): boolean {\n return checker(role, entityName, 'view')\n }\n\n // -- Create QueryClient from entity ----------------------------------------\n\n function createClient(entity: Entity): QueryClient {\n const app = getApp()\n return new QueryClient({\n entity,\n db: app.db.readOnly,\n logger: app.logger.child({ entity: entity.name }),\n countCache,\n })\n }\n\n // -- Endpoint handlers -----------------------------------------------------\n\n async function handleList(\n req: Request,\n entity: Entity,\n corsHeaders: Record<string, string>,\n ): Promise<Response> {\n const url = new URL(req.url)\n const params = listParamsSchema.safeParse(Object.fromEntries(url.searchParams))\n if (!params.success) {\n return errorResponse('Invalid query parameters', 'VALIDATION_ERROR', 400, corsHeaders)\n }\n\n const {\n limit: rawLimit,\n offset,\n sort,\n locale,\n fields,\n search,\n cursor: cursorParam,\n } = params.data\n const limit = Math.min(rawLimit, maxLimit)\n const allFields = entity.allFields as Record<string, FieldConfig>\n\n // Cursor-based pagination (opt-in, replaces OFFSET when provided)\n let cursor: CursorInput | undefined\n if (cursorParam) {\n const decoded = decodeCursor(cursorParam)\n if (!decoded) {\n return errorResponse('Invalid cursor', 'VALIDATION_ERROR', 400, corsHeaders)\n }\n // Whitelist: cursor field must be a real field on the entity\n if (!(decoded.field in allFields) && decoded.field !== 'id') {\n return errorResponse('Invalid cursor field', 'VALIDATION_ERROR', 400, corsHeaders)\n }\n cursor = decoded\n }\n\n const where: SQL[] = []\n if (search) {\n const searchCondition = buildSearchCondition(entity, search)\n if (searchCondition) where.push(searchCondition)\n }\n\n const filterConditions = buildFilterConditions(entity.name, url, allFields)\n where.push(...filterConditions)\n\n const orderBy = buildOrderBy(entity.name, sort, allFields)\n const select = parseFieldSelection(fields, allFields)\n\n const client = createClient(entity)\n const resolvedLocale = locale ?? defaultLocale\n const queryOpts = {\n where: where.length > 0 ? and(...where) : undefined,\n limit,\n offset,\n orderBy,\n select,\n locale: resolvedLocale,\n defaultLocale,\n cursor,\n }\n\n const [items, total] = await Promise.all([\n client.findMany(queryOpts),\n client.count({ where: where.length > 0 ? and(...where) : undefined }),\n ])\n\n // Build nextCursor from last item for keyset pagination\n let nextCursor: string | undefined\n if (items.length > 0 && items.length === limit) {\n const lastItem = items[items.length - 1] as Record<string, unknown>\n // Derive sort field and direction from cursor or sort param\n const cursorField =\n cursor?.field ?? (sort ? (sort.startsWith('-') ? sort.slice(1) : sort) : undefined)\n const cursorDirection: 'asc' | 'desc' =\n cursor?.direction ?? (sort?.startsWith('-') ? 'desc' : 'asc')\n if (cursorField && lastItem[cursorField] !== undefined) {\n nextCursor = encodeCursor(lastItem, cursorField, cursorDirection)\n }\n }\n\n const headers = {\n ...corsHeaders,\n ...buildCacheHeaders(entity.name, cacheConfig),\n }\n\n return jsonResponse(\n {\n data: items,\n meta: { total, limit, offset, hasMore: offset + limit < total, nextCursor },\n },\n 200,\n headers,\n )\n }\n\n async function handleCount(\n req: Request,\n entity: Entity,\n corsHeaders: Record<string, string>,\n ): Promise<Response> {\n const url = new URL(req.url)\n const params = countParamsSchema.safeParse(Object.fromEntries(url.searchParams))\n if (!params.success) {\n return errorResponse('Invalid query parameters', 'VALIDATION_ERROR', 400, corsHeaders)\n }\n\n const countMode = url.searchParams.get('countMode')\n\n // Fast path: use Postgres row estimate for unfiltered counts\n if (countMode === 'estimate') {\n const app = getApp()\n const count = await estimateRowCount(app.db.readOnly, entity.name)\n return jsonResponse({ data: { count, estimate: true } }, 200, {\n ...corsHeaders,\n ...buildCacheHeaders(entity.name, cacheConfig),\n })\n }\n\n const client = createClient(entity)\n const count = await client.count()\n\n return jsonResponse({ data: { count } }, 200, {\n ...corsHeaders,\n ...buildCacheHeaders(entity.name, cacheConfig),\n })\n }\n\n async function handleById(\n req: Request,\n entity: Entity,\n id: string,\n corsHeaders: Record<string, string>,\n ): Promise<Response> {\n const url = new URL(req.url)\n const params = singleParamsSchema.safeParse(Object.fromEntries(url.searchParams))\n if (!params.success) {\n return errorResponse('Invalid query parameters', 'VALIDATION_ERROR', 400, corsHeaders)\n }\n\n const { locale, fields } = params.data\n const allFields = entity.allFields as Record<string, FieldConfig>\n const select = parseFieldSelection(fields, allFields)\n const resolvedLocale = locale ?? defaultLocale\n\n const client = createClient(entity)\n const item = await client.findById(id, {\n select,\n locale: resolvedLocale,\n defaultLocale,\n })\n if (!item) return notFoundResponse(corsHeaders)\n\n return jsonResponse({ data: item }, 200, {\n ...corsHeaders,\n ...buildCacheHeaders(entity.name, cacheConfig),\n })\n }\n\n async function handleBySlug(\n req: Request,\n entity: Entity,\n slug: string,\n corsHeaders: Record<string, string>,\n ): Promise<Response> {\n const url = new URL(req.url)\n const params = singleParamsSchema.safeParse(Object.fromEntries(url.searchParams))\n if (!params.success) {\n return errorResponse('Invalid query parameters', 'VALIDATION_ERROR', 400, corsHeaders)\n }\n\n // Check entity has a slug field\n const allFields = entity.allFields as Record<string, FieldConfig>\n if (!allFields.slug) return notFoundResponse(corsHeaders)\n\n const { locale, fields } = params.data\n const select = parseFieldSelection(fields, allFields)\n const resolvedLocale = locale ?? defaultLocale\n\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n const table = schemaRegistry.get(entity.name) as PgTableWithColumns<any> | undefined\n if (!table?.slug) return notFoundResponse(corsHeaders)\n\n const client = createClient(entity)\n const slugConfig = allFields.slug as SlugField\n\n // For translatable slugs, also search the translation table.\n // A non-default locale's slug may live in {entity}_translations, not the main table.\n let whereClause: SQL = eq(table.slug, slug)\n\n if (slugConfig.translatable && resolvedLocale) {\n const translationTableName = `${entity.name}_translations`\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n const translationTable = schemaRegistry.get(translationTableName) as\n | PgTableWithColumns<any>\n | undefined\n if (translationTable?.slug) {\n // Find entity IDs whose translated slug matches (for the requested locale)\n const app = getApp()\n const translationMatches = await app.db.readOnly\n .select({ entityId: translationTable.entityId })\n .from(translationTable)\n .where(and(eq(translationTable.slug, slug), eq(translationTable.locale, resolvedLocale)))\n\n if (translationMatches.length > 0) {\n const translatedIds = translationMatches.map((r) => r.entityId as string)\n // Match by translated slug OR by main table slug (fallback)\n whereClause = or(inArray(table.id, translatedIds), eq(table.slug, slug))!\n }\n }\n }\n\n const results = await client.findMany({\n where: whereClause,\n limit: 1,\n select,\n locale: resolvedLocale,\n defaultLocale,\n })\n\n if (results.length === 0) return notFoundResponse(corsHeaders)\n\n return jsonResponse({ data: results[0] }, 200, {\n ...corsHeaders,\n ...buildCacheHeaders(entity.name, cacheConfig),\n })\n }\n\n // -- Central dispatch -------------------------------------------------------\n\n async function handleGet(req: Request, ctx: RouteContext): Promise<Response> {\n const corsHeaders = buildCorsHeaders(req, corsConfig)\n\n try {\n const segments = await ctx.params.then((p) => p.path)\n if (!segments || segments.length === 0) {\n return notFoundResponse(corsHeaders)\n }\n\n // Resolve role + load permissions\n const role = await resolveRole(req)\n const checker = await getChecker()\n\n // /_schema — entity introspection (filtered by role)\n if (segments[0] === '_schema') {\n const schema = buildSchemaResponse(entities, (name) =>\n hasViewPermission(checker, role, name),\n )\n return jsonResponse(schema, 200, {\n ...corsHeaders,\n 'Cache-Control': 'no-store',\n })\n }\n\n // Resolve entity from whitelist\n const entityName = segments[0]\n const entity =\n entityMap.get(entityName) ??\n entityMap.get(entityName.endsWith('s') ? entityName.slice(0, -1) : entityName)\n\n // Entity not in whitelist OR role lacks view permission → 404\n if (!entity || !hasViewPermission(checker, role, entity.name)) {\n return notFoundResponse(corsHeaders)\n }\n\n // Route to handler\n if (segments.length === 1) {\n return handleList(req, entity, corsHeaders)\n }\n if (segments[1] === 'count') {\n return handleCount(req, entity, corsHeaders)\n }\n if (segments[1] === 'slug' && segments[2]) {\n return handleBySlug(req, entity, segments[2], corsHeaders)\n }\n if (segments.length === 2) {\n return handleById(req, entity, segments[1], corsHeaders)\n }\n\n return notFoundResponse(corsHeaders)\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Internal server error'\n console.error('[content-api] handler error:', err)\n onError?.({\n status: 500,\n message,\n path: new URL(req.url).pathname,\n })\n return errorResponse('Internal server error', 'INTERNAL_ERROR', 500, corsHeaders)\n }\n }\n\n return {\n GET: (req: Request, ctx: RouteContext) => handleGet(req, ctx),\n OPTIONS: (req: Request) => corsPreflightResponse(req, corsConfig),\n }\n}\n"],"mappings":"sYASA,SAAgB,EACd,EACA,EACwB,CACxB,IAAM,EAAe,GAAQ,WAAW,GAExC,GAAI,GAAc,YAAc,GAC9B,MAAO,CAAE,gBAAiB,WAAY,CAGxC,IAAM,EAAS,GAAc,QAAU,GAAQ,eAAiB,GAC1D,EAAM,GAAc,sBAAwB,GAAQ,6BAA+B,IAEzF,MAAO,CACL,gBAAiB,mBAAmB,EAAO,2BAA2B,IACvE,CCfH,SAAgB,EACd,EACA,EACw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,EAAS,KAAO,QACX,EAAY,EAAK,EAAQ,EAAY,CAE1C,EAAS,KAAO,QAAU,EAAS,GAC9B,EAAa,EAAK,EAAQ,EAAS,GAAI,EAAY,CAExD,EAAS,SAAW,EACf,EAAW,EAAK,EAAQ,EAAS,GAAI,EAAY,CAGnD,EAAiB,EAAY,OAC7B,EAAK,CACZ,IAAM,EAAU,aAAe,MAAQ,EAAI,QAAU,wBAOrD,OANA,QAAQ,MAAM,+BAAgC,EAAI,CAClD,IAAU,CACR,OAAQ,IACR,UACA,KAAM,IAAI,IAAI,EAAI,IAAI,CAAC,SACxB,CAAC,CACK,EAAc,wBAAyB,iBAAkB,IAAK,EAAY,EAIrF,MAAO,CACL,KAAM,EAAc,IAAsB,EAAU,EAAK,EAAI,CAC7D,QAAU,GAAiB,EAAsB,EAAK,EAAW,CAClE"}
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@murumets-ee/content-api",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"license": "Elastic-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": {
|
|
8
|
-
"types": "./dist/index.d.
|
|
9
|
-
"import": "./dist/index.
|
|
8
|
+
"types": "./dist/index.d.mts",
|
|
9
|
+
"import": "./dist/index.mjs"
|
|
10
10
|
}
|
|
11
11
|
},
|
|
12
12
|
"files": [
|
|
@@ -15,18 +15,18 @@
|
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"drizzle-orm": "^0.45.1",
|
|
17
17
|
"zod": "^3.24.1",
|
|
18
|
-
"@murumets-ee/
|
|
19
|
-
"@murumets-ee/entity": "0.1.
|
|
20
|
-
"@murumets-ee/
|
|
18
|
+
"@murumets-ee/db": "0.1.5",
|
|
19
|
+
"@murumets-ee/entity": "0.1.5",
|
|
20
|
+
"@murumets-ee/core": "0.1.6"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
|
-
"
|
|
23
|
+
"tsdown": "^0.21.7",
|
|
24
24
|
"typescript": "^5.7.2",
|
|
25
25
|
"vitest": "^2.1.8"
|
|
26
26
|
},
|
|
27
27
|
"scripts": {
|
|
28
|
-
"build": "
|
|
29
|
-
"dev": "
|
|
28
|
+
"build": "tsdown",
|
|
29
|
+
"dev": "tsdown --watch",
|
|
30
30
|
"test": "vitest"
|
|
31
31
|
}
|
|
32
32
|
}
|
package/dist/index.d.ts
DELETED
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
import { PermissionChecker } from '@murumets-ee/core';
|
|
2
|
-
import { Entity } from '@murumets-ee/entity';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Content API — Public types
|
|
6
|
-
*
|
|
7
|
-
* All configuration, request, and response types for the read-only content API.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
/** CORS configuration — deny-by-default, explicit origin allowlist. */
|
|
11
|
-
interface CorsConfig {
|
|
12
|
-
/** Allowed origins. Each matched exactly — no regex, no wildcards. */
|
|
13
|
-
allowedOrigins: string[];
|
|
14
|
-
/** Preflight cache max age (seconds). Default: 3600 */
|
|
15
|
-
maxAge?: number;
|
|
16
|
-
}
|
|
17
|
-
/** Per-entity cache override. */
|
|
18
|
-
interface EntityCacheConfig {
|
|
19
|
-
/** Cache-Control max-age in seconds. */
|
|
20
|
-
maxAge?: number;
|
|
21
|
-
/** stale-while-revalidate window in seconds. */
|
|
22
|
-
staleWhileRevalidate?: number;
|
|
23
|
-
/** Whether this entity is cacheable. Default: true. Set false → no-store. */
|
|
24
|
-
cacheable?: boolean;
|
|
25
|
-
}
|
|
26
|
-
/** Global cache configuration. */
|
|
27
|
-
interface CacheConfig {
|
|
28
|
-
/** Default max-age for all entities (seconds). Default: 60 */
|
|
29
|
-
defaultMaxAge?: number;
|
|
30
|
-
/** Default stale-while-revalidate (seconds). Default: 300 */
|
|
31
|
-
defaultStaleWhileRevalidate?: number;
|
|
32
|
-
/** Per-entity overrides, keyed by entity name. */
|
|
33
|
-
entities?: Record<string, EntityCacheConfig>;
|
|
34
|
-
}
|
|
35
|
-
/** Content API handler configuration. */
|
|
36
|
-
interface ContentApiConfig {
|
|
37
|
-
/** Entity whitelist — ONLY these entities are queryable. Deny-by-default. */
|
|
38
|
-
entities: Entity[];
|
|
39
|
-
/**
|
|
40
|
-
* Permission checker — REQUIRED. Same pattern as admin API handler.
|
|
41
|
-
* Called lazily on first request, result cached with 30s TTL.
|
|
42
|
-
* Checks: `checker(role, entityName, 'view')` → boolean.
|
|
43
|
-
*/
|
|
44
|
-
loadPermissions: () => Promise<PermissionChecker>;
|
|
45
|
-
/**
|
|
46
|
-
* Optional auth. Returns user role, or null for anonymous.
|
|
47
|
-
* When null or not provided → uses `publicRole`.
|
|
48
|
-
*
|
|
49
|
-
* Enables preview mode (e.g. bearer token → editor sees more entities).
|
|
50
|
-
*/
|
|
51
|
-
authenticate?: (req: Request) => Promise<{
|
|
52
|
-
role: string;
|
|
53
|
-
} | null>;
|
|
54
|
-
/**
|
|
55
|
-
* Role for unauthenticated requests. Default: `'public'`.
|
|
56
|
-
* Must have explicit 'view' permission per entity to see anything.
|
|
57
|
-
*/
|
|
58
|
-
publicRole?: string;
|
|
59
|
-
/** Default content locale for translation merging. */
|
|
60
|
-
defaultLocale?: string;
|
|
61
|
-
/** CORS configuration. Required when serving cross-origin. */
|
|
62
|
-
cors?: CorsConfig;
|
|
63
|
-
/** Cache-Control header configuration. */
|
|
64
|
-
cache?: CacheConfig;
|
|
65
|
-
/** Max pagination limit. Default: 100. Hard-capped at 100. */
|
|
66
|
-
maxLimit?: number;
|
|
67
|
-
/** Error hook for monitoring/logging. Errors are fire-and-forget. */
|
|
68
|
-
onError?: (err: {
|
|
69
|
-
status: number;
|
|
70
|
-
message: string;
|
|
71
|
-
entity?: string;
|
|
72
|
-
path: string;
|
|
73
|
-
}) => void;
|
|
74
|
-
}
|
|
75
|
-
interface ContentListResponse<T = Record<string, unknown>> {
|
|
76
|
-
data: T[];
|
|
77
|
-
meta: {
|
|
78
|
-
total: number;
|
|
79
|
-
limit: number;
|
|
80
|
-
offset: number;
|
|
81
|
-
hasMore: boolean;
|
|
82
|
-
/** Opaque cursor for fetching the next page via keyset pagination. */
|
|
83
|
-
nextCursor?: string;
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
interface ContentSingleResponse<T = Record<string, unknown>> {
|
|
87
|
-
data: T;
|
|
88
|
-
}
|
|
89
|
-
interface ContentCountResponse {
|
|
90
|
-
data: {
|
|
91
|
-
count: number;
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
interface ContentErrorResponse {
|
|
95
|
-
error: {
|
|
96
|
-
status: number;
|
|
97
|
-
message: string;
|
|
98
|
-
code: string;
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
/** Field metadata exposed by /_schema (public-safe subset of FieldConfig). */
|
|
102
|
-
interface SchemaField {
|
|
103
|
-
type: string;
|
|
104
|
-
required?: boolean;
|
|
105
|
-
options?: readonly string[];
|
|
106
|
-
cardinality?: 'one' | 'many';
|
|
107
|
-
}
|
|
108
|
-
/** Entity metadata exposed by /_schema. */
|
|
109
|
-
interface SchemaEntity {
|
|
110
|
-
name: string;
|
|
111
|
-
pluralName: string;
|
|
112
|
-
fields: Record<string, SchemaField>;
|
|
113
|
-
}
|
|
114
|
-
/** Full /_schema response. */
|
|
115
|
-
interface SchemaResponse {
|
|
116
|
-
entities: SchemaEntity[];
|
|
117
|
-
}
|
|
118
|
-
/** Next.js catch-all route context shape. */
|
|
119
|
-
interface RouteContext {
|
|
120
|
-
params: Promise<{
|
|
121
|
-
path: string[];
|
|
122
|
-
}>;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Content API handler factory
|
|
127
|
-
*
|
|
128
|
-
* Creates a read-only catch-all route handler for public content delivery.
|
|
129
|
-
* Mirrors the `createAdminApiHandler` pattern but with:
|
|
130
|
-
* - No mutations (GET + OPTIONS only)
|
|
131
|
-
* - Permission-gated (public role starts with 0 permissions)
|
|
132
|
-
* - Published content only (QueryClient auto-filters)
|
|
133
|
-
* - CORS + Cache-Control headers
|
|
134
|
-
*
|
|
135
|
-
* @example
|
|
136
|
-
* ```typescript
|
|
137
|
-
* // app/api/content/[...path]/route.ts
|
|
138
|
-
* import { createContentApiHandler } from '@murumets-ee/content-api'
|
|
139
|
-
* import { Article, Page } from '@/entities'
|
|
140
|
-
*
|
|
141
|
-
* const handler = createContentApiHandler({
|
|
142
|
-
* entities: [Article, Page],
|
|
143
|
-
* loadPermissions: async () => {
|
|
144
|
-
* const roles = await loadRoles(getApp())
|
|
145
|
-
* return buildPermissionChecker(roles)
|
|
146
|
-
* },
|
|
147
|
-
* cors: { allowedOrigins: ['https://www.example.com'] },
|
|
148
|
-
* })
|
|
149
|
-
*
|
|
150
|
-
* export const { GET, OPTIONS } = handler
|
|
151
|
-
* ```
|
|
152
|
-
*/
|
|
153
|
-
|
|
154
|
-
declare function createContentApiHandler(config: ContentApiConfig): {
|
|
155
|
-
GET: (req: Request, ctx: RouteContext) => Promise<Response>;
|
|
156
|
-
OPTIONS: (req: Request) => Response;
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Schema introspection endpoint — GET /_schema
|
|
161
|
-
*
|
|
162
|
-
* Returns public-safe entity metadata for SDK generation.
|
|
163
|
-
* Only exposes: type, required, options (select), cardinality (reference).
|
|
164
|
-
* Internal fields (_version, _scopeId) excluded.
|
|
165
|
-
* No hooks, behaviors, access rules, or implementation details.
|
|
166
|
-
*
|
|
167
|
-
* Response is filtered by the caller's role permissions — only entities
|
|
168
|
-
* the role can 'view' are included.
|
|
169
|
-
*/
|
|
170
|
-
|
|
171
|
-
/** Convert an Entity to public-safe schema metadata. */
|
|
172
|
-
declare function toSchemaEntity(entity: Entity): SchemaEntity;
|
|
173
|
-
/**
|
|
174
|
-
* Build the full /_schema response.
|
|
175
|
-
* Only includes entities that pass the permission check.
|
|
176
|
-
*/
|
|
177
|
-
declare function buildSchemaResponse(entities: Entity[], checkPermission: (entityName: string) => boolean): SchemaResponse;
|
|
178
|
-
|
|
179
|
-
export { type CacheConfig, type ContentApiConfig, type ContentCountResponse, type ContentErrorResponse, type ContentListResponse, type ContentSingleResponse, type CorsConfig, type EntityCacheConfig, type RouteContext, type SchemaEntity, type SchemaField, type SchemaResponse, buildSchemaResponse, createContentApiHandler, toSchemaEntity };
|
package/dist/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {getApp}from'@murumets-ee/core';import {schemaRegistry}from'@murumets-ee/db';import {CountCache,decodeCursor,encodeCursor,estimateRowCount}from'@murumets-ee/entity';import {QueryClient}from'@murumets-ee/entity/query';import {and,eq,or,inArray,ilike,gte,lte,desc,asc}from'drizzle-orm';import {z}from'zod';function v(t,e){let n=e?.entities?.[t];if(n?.cacheable===false)return {"Cache-Control":"no-store"};let o=n?.maxAge??e?.defaultMaxAge??60,c=n?.staleWhileRevalidate??e?.defaultStaleWhileRevalidate??300;return {"Cache-Control":`public, max-age=${o}, stale-while-revalidate=${c}`}}function B(t,e){if(!e)return {};let n=t.headers.get("Origin");return n?e.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(e.maxAge??3600),Vary:"Origin"}:{}:{}}function ne(t,e){let n=B(t,e);return new Response(null,{status:204,headers:n})}var $=100,re=z.object({limit:z.coerce.number().int().min(1).max($).default(20),offset:z.coerce.number().int().min(0).default(0),sort:z.string().regex(/^-?[a-zA-Z_]+$/).optional(),locale:z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/).optional(),fields:z.string().optional(),search:z.string().max(200).optional(),cursor:z.string().max(500).optional()}),Z=z.object({locale:z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/).optional(),fields:z.string().optional()}),se=z.object({locale:z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/).optional()});function ie(t){return t.replace(/[%_\\]/g,"\\$&")}var Ce=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function oe(t,e){switch(t.type){case "boolean":return e==="true"?true:e==="false"?false:null;case "reference":case "media":return Ce.test(e)?e:null;case "select":return t.options.includes(e)?e:null;case "date":return e;case "text":case "number":return e;default:return null}}function D(t,e){if(!t)return;let o=t.split(",").map(c=>c.trim()).filter(c=>c in e&&!c.startsWith("_")&&e[c].type!=="blocks");return o.length>0&&!o.includes("id")&&o.unshift("id"),o.length>0?o:void 0}function E(t,e=200,n){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":"application/json",...n}})}function S(t,e,n,o){return E({error:{status:n,message:t,code:e}},n,o)}function P(t){return S("Not found","NOT_FOUND",404,t)}function Re(t){let e={type:t.type};return t.required&&(e.required=true),t.type==="select"&&(e.options=t.options),t.type==="reference"&&(e.cardinality=t.cardinality),e}function ae(t){let e=t.allFields,n={};for(let[o,c]of Object.entries(e))o.startsWith("_")||(n[o]=Re(c));return {name:t.name,pluralName:`${t.name}s`,fields:n}}function G(t,e){return {entities:t.filter(o=>e(o.name)).map(ae)}}function Te(t){let e=new Map;for(let n of t)e.set(n.name,n),e.set(`${n.name}s`,n);return e}function ve(t,e){let n=schemaRegistry.get(t.name);if(!n)return;let o=t.allFields;for(let[c,f]of Object.entries(o))if(f.type==="text"&&(f.indexed||f.required)){let u=n[c];if(u)return ilike(u,`%${ie(e)}%`)}}function Me(t,e,n){if(!e)return;let o=e.startsWith("-"),c=o?e.slice(1):e,f=n[c];if(!f||f.type==="blocks")return;let u=schemaRegistry.get(t);if(!(!u||!u[c]))return o?desc(u[c]):asc(u[c])}function Ne(t,e,n){let o=schemaRegistry.get(t);if(!o)return [];let c=[];for(let[f,u]of e.searchParams.entries()){let W=f.match(/^filter\[([a-zA-Z_]+)\]$/);if(!W)continue;let N=W[1],O=n[N];if(!O||O.type==="blocks")continue;let F=o[N];if(!F)continue;if(O.type==="date"){u.startsWith("gte:")?c.push(gte(F,u.slice(4))):u.startsWith("lte:")?c.push(lte(F,u.slice(4))):c.push(eq(F,u));continue}let L=oe(O,u);L!==null&&c.push(eq(F,L));}return c}function _e(t){let{entities:e,defaultLocale:n,publicRole:o="public",cors:c,cache:f,onError:u}=t,W=Math.min(t.maxLimit??$,$),N=Te(e),O=new CountCache(5e3),F=3e4,L=null,K=0;async function ce(){let i=Date.now();return (!L||i-K>F)&&(L=await t.loadPermissions(),K=i),L}async function le(i){if(!t.authenticate)return o;try{return (await t.authenticate(i))?.role??o}catch{return o}}function Y(i,r,a){return i(r,a,"view")}function q(i){let r=getApp();return new QueryClient({entity:i,db:r.db.readOnly,logger:r.logger.child({entity:i.name}),countCache:O})}async function ue(i,r,a){let s=new URL(i.url),p=re.safeParse(Object.fromEntries(s.searchParams));if(!p.success)return S("Invalid query parameters","VALIDATION_ERROR",400,a);let{limit:g,offset:d,sort:l,locale:h,fields:R,search:x,cursor:A}=p.data,y=Math.min(g,W),T=r.allFields,I;if(A){let C=decodeCursor(A);if(!C)return S("Invalid cursor","VALIDATION_ERROR",400,a);if(!(C.field in T)&&C.field!=="id")return S("Invalid cursor field","VALIDATION_ERROR",400,a);I=C;}let b=[];if(x){let C=ve(r,x);C&&b.push(C);}let V=Ne(r.name,s,T);b.push(...V);let w=Me(r.name,l,T),H=D(R,T),_=q(r),z=h??n,Q={where:b.length>0?and(...b):void 0,limit:y,offset:d,orderBy:w,select:H,locale:z,defaultLocale:n,cursor:I},[j,ee]=await Promise.all([_.findMany(Q),_.count({where:b.length>0?and(...b):void 0})]),te;if(j.length>0&&j.length===y){let C=j[j.length-1],U=I?.field??(l?l.startsWith("-")?l.slice(1):l:void 0),he=I?.direction??(l?.startsWith("-")?"desc":"asc");U&&C[U]!==void 0&&(te=encodeCursor(C,U,he));}let ge={...a,...v(r.name,f)};return E({data:j,meta:{total:ee,limit:y,offset:d,hasMore:d+y<ee,nextCursor:te}},200,ge)}async function de(i,r,a){let s=new URL(i.url);if(!se.safeParse(Object.fromEntries(s.searchParams)).success)return S("Invalid query parameters","VALIDATION_ERROR",400,a);if(s.searchParams.get("countMode")==="estimate"){let h=getApp(),R=await estimateRowCount(h.db.readOnly,r.name);return E({data:{count:R,estimate:true}},200,{...a,...v(r.name,f)})}let l=await q(r).count();return E({data:{count:l}},200,{...a,...v(r.name,f)})}async function fe(i,r,a,s){let p=new URL(i.url),g=Z.safeParse(Object.fromEntries(p.searchParams));if(!g.success)return S("Invalid query parameters","VALIDATION_ERROR",400,s);let{locale:d,fields:l}=g.data,h=r.allFields,R=D(l,h),x=d??n,y=await q(r).findById(a,{select:R,locale:x,defaultLocale:n});return y?E({data:y},200,{...s,...v(r.name,f)}):P(s)}async function me(i,r,a,s){let p=new URL(i.url),g=Z.safeParse(Object.fromEntries(p.searchParams));if(!g.success)return S("Invalid query parameters","VALIDATION_ERROR",400,s);let d=r.allFields;if(!d.slug)return P(s);let{locale:l,fields:h}=g.data,R=D(h,d),x=l??n,A=schemaRegistry.get(r.name);if(!A?.slug)return P(s);let y=q(r),T=d.slug,I=eq(A.slug,a);if(T.translatable&&x){let V=`${r.name}_translations`,w=schemaRegistry.get(V);if(w?.slug){let _=await getApp().db.readOnly.select({entityId:w.entityId}).from(w).where(and(eq(w.slug,a),eq(w.locale,x)));if(_.length>0){let z=_.map(Q=>Q.entityId);I=or(inArray(A.id,z),eq(A.slug,a));}}}let b=await y.findMany({where:I,limit:1,select:R,locale:x,defaultLocale:n});return b.length===0?P(s):E({data:b[0]},200,{...s,...v(r.name,f)})}async function pe(i,r){let a=B(i,c);try{let s=await r.params.then(h=>h.path);if(!s||s.length===0)return P(a);let p=await le(i),g=await ce();if(s[0]==="_schema"){let h=G(e,R=>Y(g,p,R));return E(h,200,{...a,"Cache-Control":"no-store"})}let d=s[0],l=N.get(d)??N.get(d.endsWith("s")?d.slice(0,-1):d);return !l||!Y(g,p,l.name)?P(a):s.length===1?ue(i,l,a):s[1]==="count"?de(i,l,a):s[1]==="slug"&&s[2]?me(i,l,s[2],a):s.length===2?fe(i,l,s[1],a):P(a)}catch(s){let p=s instanceof Error?s.message:"Internal server error";return console.error("[content-api] handler error:",s),u?.({status:500,message:p,path:new URL(i.url).pathname}),S("Internal server error","INTERNAL_ERROR",500,a)}}return {GET:(i,r)=>pe(i,r),OPTIONS:i=>ne(i,c)}}export{G as buildSchemaResponse,_e as createContentApiHandler,ae as toSchemaEntity};
|