@murumets-ee/content-api 0.1.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/LICENSE ADDED
@@ -0,0 +1,94 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject
14
+ to the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set
20
+ of the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other
27
+ notices of the licensor in the software. Any use of the licensor's trademarks
28
+ is subject to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license
39
+ for the software granted under these terms ends immediately. If your company
40
+ makes such a claim, your patent license ends immediately for work on behalf
41
+ of your company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from
46
+ you also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license
61
+ no later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your
64
+ licenses to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising
70
+ out of these terms or the use or nature of the software, under any kind of
71
+ legal claim.
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is
76
+ the software the licensor makes available under these terms, including any
77
+ portion of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that organization.
84
+ **control** means ownership of substantially all the assets of an entity, or
85
+ the power to direct the management and policies of an entity (for example, by
86
+ voting right, contract, or otherwise). Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your
92
+ licenses.
93
+
94
+ **trademark** means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # @murumets-ee/content-api
2
+
3
+ Read-only REST API for frontend consumption — schema endpoint, CORS, caching, and permission gating.
4
+
5
+ Part of [Lumi CMS](https://github.com/murumets-ee/lumi-cms) — a modular, type-safe CMS toolkit for Node.js.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @murumets-ee/content-api
11
+ ```
12
+
13
+ ## License
14
+
15
+ [Elastic License 2.0 (ELv2)](../../LICENSE)
@@ -0,0 +1,179 @@
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 ADDED
@@ -0,0 +1 @@
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};
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@murumets-ee/content-api",
3
+ "version": "0.1.0",
4
+ "license": "Elastic-2.0",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js"
10
+ }
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "dependencies": {
16
+ "drizzle-orm": "^0.45.1",
17
+ "zod": "^3.24.1",
18
+ "@murumets-ee/core": "0.1.0",
19
+ "@murumets-ee/entity": "0.1.0",
20
+ "@murumets-ee/db": "0.1.0"
21
+ },
22
+ "devDependencies": {
23
+ "tsup": "^8.3.5",
24
+ "typescript": "^5.7.2",
25
+ "vitest": "^2.1.8"
26
+ },
27
+ "scripts": {
28
+ "build": "tsup",
29
+ "dev": "tsup --watch",
30
+ "test": "vitest"
31
+ }
32
+ }