@murumets-ee/content-api 0.1.1 → 0.1.3
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/package.json +5 -6
- package/dist/index.cjs +0 -1
- package/dist/index.d.cts +0 -179
package/package.json
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@murumets-ee/content-api",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"license": "Elastic-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": {
|
|
8
8
|
"types": "./dist/index.d.ts",
|
|
9
|
-
"import": "./dist/index.js"
|
|
10
|
-
"require": "./dist/index.cjs"
|
|
9
|
+
"import": "./dist/index.js"
|
|
11
10
|
}
|
|
12
11
|
},
|
|
13
12
|
"files": [
|
|
@@ -16,9 +15,9 @@
|
|
|
16
15
|
"dependencies": {
|
|
17
16
|
"drizzle-orm": "^0.45.1",
|
|
18
17
|
"zod": "^3.24.1",
|
|
19
|
-
"@murumets-ee/core": "0.1.
|
|
20
|
-
"@murumets-ee/entity": "0.1.
|
|
21
|
-
"@murumets-ee/db": "0.1.
|
|
18
|
+
"@murumets-ee/core": "0.1.4",
|
|
19
|
+
"@murumets-ee/entity": "0.1.3",
|
|
20
|
+
"@murumets-ee/db": "0.1.3"
|
|
22
21
|
},
|
|
23
22
|
"devDependencies": {
|
|
24
23
|
"tsup": "^8.3.5",
|
package/dist/index.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var core=require('@murumets-ee/core'),db=require('@murumets-ee/db'),entity=require('@murumets-ee/entity'),query=require('@murumets-ee/entity/query'),drizzleOrm=require('drizzle-orm'),zod=require('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=zod.z.object({limit:zod.z.coerce.number().int().min(1).max($).default(20),offset:zod.z.coerce.number().int().min(0).default(0),sort:zod.z.string().regex(/^-?[a-zA-Z_]+$/).optional(),locale:zod.z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/).optional(),fields:zod.z.string().optional(),search:zod.z.string().max(200).optional(),cursor:zod.z.string().max(500).optional()}),Z=zod.z.object({locale:zod.z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/).optional(),fields:zod.z.string().optional()}),se=zod.z.object({locale:zod.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=db.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 drizzleOrm.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=db.schemaRegistry.get(t);if(!(!u||!u[c]))return o?drizzleOrm.desc(u[c]):drizzleOrm.asc(u[c])}function Ne(t,e,n){let o=db.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(drizzleOrm.gte(F,u.slice(4))):u.startsWith("lte:")?c.push(drizzleOrm.lte(F,u.slice(4))):c.push(drizzleOrm.eq(F,u));continue}let L=oe(O,u);L!==null&&c.push(drizzleOrm.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 entity.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=core.getApp();return new query.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=entity.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?drizzleOrm.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?drizzleOrm.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=entity.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=core.getApp(),R=await entity.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=db.schemaRegistry.get(r.name);if(!A?.slug)return P(s);let y=q(r),T=d.slug,I=drizzleOrm.eq(A.slug,a);if(T.translatable&&x){let V=`${r.name}_translations`,w=db.schemaRegistry.get(V);if(w?.slug){let _=await core.getApp().db.readOnly.select({entityId:w.entityId}).from(w).where(drizzleOrm.and(drizzleOrm.eq(w.slug,a),drizzleOrm.eq(w.locale,x)));if(_.length>0){let z=_.map(Q=>Q.entityId);I=drizzleOrm.or(drizzleOrm.inArray(A.id,z),drizzleOrm.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)}}exports.buildSchemaResponse=G;exports.createContentApiHandler=_e;exports.toSchemaEntity=ae;
|
package/dist/index.d.cts
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 };
|