@kitcms/client 0.0.0-stage → 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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -2
  3. package/package.json +26 -3
  4. package/src/index.ts +316 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kitcms contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # @kitcms/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small typed client for Workers that read kitcms content over a Service Binding. It calls the `KitcmsRPC` entrypoint of a kitcms Worker and has no runtime dependencies, so it works in Workers. Use it for headless setups, where the CMS runs in one Worker and the site or other services run in another.
4
+
5
+ ```sh
6
+ pnpm add @kitcms/client
7
+ ```
8
+
9
+ ## Setup
10
+
11
+ 1. Bind the consumer Worker to the CMS Worker's `KitcmsRPC` entrypoint (`wrangler.jsonc`):
12
+
13
+ ```jsonc
14
+ {
15
+ "services": [{ "binding": "CMS", "service": "my-kitcms", "entrypoint": "KitcmsRPC" }],
16
+ }
17
+ ```
18
+
19
+ 2. Generate the document types from the CMS app's config. The default output is `kitcms-types.d.ts`:
20
+
21
+ ```sh
22
+ kitcms generate:types --out ../consumer/src/kitcms-types.d.ts
23
+ ```
24
+
25
+ 3. Call the CMS from the consumer Worker (as in `apps/playground-consumer/src/index.ts`):
26
+
27
+ ```ts
28
+ import { kitcms, isKitcmsClientError, type KitcmsBinding } from '@kitcms/client';
29
+ import type { KitcmsTypes } from './kitcms-types';
30
+
31
+ interface Env {
32
+ CMS: Service & KitcmsBinding;
33
+ }
34
+
35
+ export default {
36
+ async fetch(req, env): Promise<Response> {
37
+ const cms = kitcms<KitcmsTypes>(env.CMS);
38
+ // Anonymous: only published pages (the collection's read rule).
39
+ const { docs, totalDocs } = await cms.find('pages', {
40
+ sort: '-updatedAt',
41
+ depth: 1,
42
+ limit: 10,
43
+ });
44
+ return Response.json({ totalDocs, titles: docs.map((p) => p.title) });
45
+ },
46
+ } satisfies ExportedHandler<Env>;
47
+ ```
48
+
49
+ Errors arrive as `KitcmsClientError`, with the CMS error `code` and `status`:
50
+
51
+ ```ts
52
+ try {
53
+ await cms.count('users');
54
+ } catch (err) {
55
+ if (isKitcmsClientError(err)) console.log(err.code, err.status);
56
+ }
57
+ ```
58
+
59
+ ## Trusted calls
60
+
61
+ `{ as: 'system' }` skips the collection and field access rules. Hooks and validation still run. Use it only from Workers you control:
62
+
63
+ ```ts
64
+ const all = await cms.find('pages', { as: 'system', limit: 50 });
65
+ const draft = await cms.findByID('pages', id, { as: 'system', draft: true }); // drafts: system only
66
+ ```
67
+
68
+ Writes are **system-only**. Without `{ as: 'system' }` they fail with `FORBIDDEN` before doing anything:
69
+
70
+ ```ts
71
+ const page = await cms.create('pages', { title: 'Hello' }, { as: 'system' });
72
+ await cms.update('pages', page.id, { title: 'Hi' }, { as: 'system', draft: true });
73
+ await cms.move('pages', page.id, { after: otherId }, { as: 'system' }); // orderable collections
74
+ await cms.unpublish('pages', page.id, { as: 'system' });
75
+ await cms.delete('pages', page.id, { as: 'system' });
76
+ await cms.updateGlobal('site', { siteName: 'Dzongla' }, { as: 'system' });
77
+ ```
78
+
79
+ ## Notes
80
+
81
+ - Reads: `find`, `findOne`, `findByID`, `count`, `findGlobal`, `getMediaUrl` (anonymous by default). Writes: `create`, `update`, `delete`, `move`, `unpublish`, `updateGlobal` (system only).
82
+ - Under `vite dev`, the CMS RPC entrypoint is not served, and a running dev server shadows it for consumers. To test a consumer, run the CMS with `pnpm preview` (`wrangler dev`).
83
+ - Set `media.publicUrl` in the CMS config. Without it, media URLs are relative (`/api/media/...`), which a headless consumer can't use.
84
+
85
+ Status: pre-release (0.x), Cloudflare Workers + D1 + R2 only.
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@kitcms/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/Norden-Tenzin/kitcms.git",
8
+ "directory": "packages/client"
9
+ },
10
+ "homepage": "https://kitcms.dev",
11
+ "bugs": {
12
+ "url": "https://github.com/Norden-Tenzin/kitcms/issues"
13
+ },
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "exports": {
17
+ ".": {
18
+ "types": "./src/index.ts",
19
+ "default": "./src/index.ts"
20
+ }
21
+ },
22
+ "files": [
23
+ "src",
24
+ "!src/**/*.test.ts"
25
+ ],
26
+ "scripts": {
27
+ "typecheck": "tsc --noEmit"
28
+ }
6
29
  }
package/src/index.ts ADDED
@@ -0,0 +1,316 @@
1
+ // @kitcms/client: a typed wrapper for Workers that call a kitcms Service Binding (RPC entrypoint
2
+ // `KitcmsRPC`, see @kitcms/core/rpc). Workers-safe, zero runtime dependencies.
3
+ //
4
+ // import { kitcms } from '@kitcms/client';
5
+ // import type { KitcmsTypes } from './kitcms-types'; // from `kitcms generate:types`
6
+ // const cms = kitcms<KitcmsTypes>(env.CMS);
7
+ // const { docs } = await cms.find('posts', { where: { status: { equals: 'published' } }, depth: 1 });
8
+
9
+ export const VERSION = '0.0.0';
10
+
11
+ // ---------------------------------------------------------------------------------------------
12
+ // Types (self-contained mirrors of @kitcms/core's in-app typing)
13
+ // ---------------------------------------------------------------------------------------------
14
+
15
+ /** A relationship value before population: the target's id, branded with the target slug. */
16
+ export type Rel<To extends string> = string & { readonly '~rel': To };
17
+
18
+ /** The shape `kitcms generate:types` emits as `KitcmsTypes`. */
19
+ export interface KitcmsTypes {
20
+ collections: Record<string, object>;
21
+ /** Globals (single documents). Absent in configs without globals. */
22
+ globals?: Record<string, object>;
23
+ /** Create/update input shapes per collection (optional: falls back to a partial document). */
24
+ inputs?: Record<string, object>;
25
+ }
26
+
27
+ /** Every document has these. */
28
+ export interface SystemFields {
29
+ id: string;
30
+ createdAt: string;
31
+ updatedAt: string;
32
+ /** Orderable collections only: the read-only fractional order key. */
33
+ _order?: string | null;
34
+ }
35
+ /** Used when `kitcms()` is called without a type argument. */
36
+ export type GenericDoc = Record<string, unknown> & SystemFields;
37
+ export interface GenericTypes {
38
+ collections: Record<string, GenericDoc>;
39
+ globals: Record<string, Record<string, unknown> & { id: string }>;
40
+ }
41
+
42
+ /** How many levels of relationships to load. 0 (the default) returns ids. Max 2. */
43
+ export type Depth = 0 | 1 | 2;
44
+
45
+ type Prev = [never, 0, 1, 2];
46
+ /**
47
+ * Replaces relationship ids with documents, `D` levels deep. A target that is missing or not
48
+ * readable by the caller stays an id, hence `| string`.
49
+ */
50
+ export type Populate<T, Types extends KitcmsTypes, D extends number> = [D] extends [0]
51
+ ? T
52
+ : T extends Rel<infer To>
53
+ ? To extends keyof Types['collections']
54
+ ? Populate<Types['collections'][To], Types, Prev[D]> | string
55
+ : string
56
+ : T extends readonly (infer E)[]
57
+ ? Populate<E, Types, D>[]
58
+ : T extends object
59
+ ? { [K in keyof T]: Populate<T[K], Types, D> }
60
+ : T;
61
+
62
+ type Scalar = string | number | boolean;
63
+ type Range<V> = {
64
+ greater_than?: V;
65
+ greater_than_equal?: V;
66
+ less_than?: V;
67
+ less_than_equal?: V;
68
+ };
69
+ type WhereValue<V> = V extends Rel<string> ? string : V;
70
+
71
+ /** Operators available on a field whose (non-null) value type is `V`. */
72
+ export type WhereOps<V> = V extends readonly Rel<string>[]
73
+ ? { contains?: string; in?: string[]; not_in?: string[]; exists?: boolean }
74
+ : {
75
+ equals?: WhereValue<V> | null;
76
+ not_equals?: WhereValue<V> | null;
77
+ in?: WhereValue<V>[];
78
+ not_in?: WhereValue<V>[];
79
+ exists?: boolean;
80
+ } & (V extends number
81
+ ? Range<number>
82
+ : V extends string
83
+ ? { like?: string } & Range<string | Date | number>
84
+ : unknown);
85
+
86
+ type Filterable<V> = V extends Scalar ? true : V extends readonly Rel<string>[] ? true : false;
87
+
88
+ /** The untyped form of a filter. */
89
+ export interface WhereInput {
90
+ and?: WhereInput[];
91
+ or?: WhereInput[];
92
+ [field: string]: Record<string, unknown> | WhereInput[] | undefined;
93
+ }
94
+
95
+ /** A typed filter over a document's top-level filterable fields. Untyped docs take `WhereInput`. */
96
+ export type Where<Doc> = string extends keyof Doc ? WhereInput : TypedWhere<Doc>;
97
+ type TypedWhere<Doc> = {
98
+ [K in keyof Doc as Filterable<NonNullable<Doc[K]>> extends true ? K : never]?: WhereOps<NonNullable<Doc[K]>>;
99
+ } & { and?: TypedWhere<Doc>[]; or?: TypedWhere<Doc>[] };
100
+
101
+ /** `'title'` ascending, `'-title'` descending. */
102
+ export type Sort<Doc> = `${'-' | ''}${keyof Doc & string}`;
103
+
104
+ export interface PaginatedDocs<T> {
105
+ docs: T[];
106
+ totalDocs: number;
107
+ limit: number;
108
+ page: number;
109
+ totalPages: number;
110
+ hasNextPage: boolean;
111
+ hasPrevPage: boolean;
112
+ }
113
+
114
+ /** `'system'`: trusted caller, reads skip access rules. Default: anonymous. Use only from Workers you control. */
115
+ export interface CallerOptions {
116
+ as?: 'system';
117
+ }
118
+
119
+ /** Drafts are only readable by trusted callers: `draft: true` requires `as: 'system'`. */
120
+ export type DraftRead = { draft?: false; as?: 'system' } | { draft: true; as: 'system' };
121
+
122
+ export interface FindArgs<Doc, D extends Depth> extends CallerOptions {
123
+ where?: Where<Doc>;
124
+ sort?: Sort<Doc>;
125
+ /** Page size. Default 10, max 1000. */
126
+ limit?: number;
127
+ /** 1-based. Default 1. */
128
+ page?: number;
129
+ depth?: D;
130
+ /** `false` skips the total count. Default `true`. */
131
+ pagination?: boolean;
132
+ }
133
+
134
+ export interface ReadOptions<D extends Depth> extends CallerOptions {
135
+ depth?: D;
136
+ }
137
+
138
+ /** Options of every write. Writes over RPC are for trusted callers only (`as: 'system'`). */
139
+ export interface WriteOptions<D extends Depth> {
140
+ as: 'system';
141
+ depth?: D;
142
+ /** Save as a draft (collections/globals with drafts). */
143
+ draft?: boolean;
144
+ }
145
+
146
+ /** Where to put a document of an orderable collection. */
147
+ export type MoveTarget = { before: string; after?: never } | { after: string; before?: never };
148
+
149
+ /** The RPC stub: structurally, a `Service<KitcmsRPCMethods>` binding (`env.CMS`). */
150
+ export interface KitcmsBinding {
151
+ find(collection: string, options?: object): Promise<unknown>;
152
+ findOne(collection: string, options?: object): Promise<unknown>;
153
+ findByID(collection: string, id: string, options?: object): Promise<unknown>;
154
+ count(collection: string, options?: object): Promise<number>;
155
+ findGlobal(global: string, options?: object): Promise<unknown>;
156
+ getMediaUrl(key: string): Promise<string | null>;
157
+ create(collection: string, data: object, options: object): Promise<unknown>;
158
+ update(collection: string, id: string, data: object, options: object): Promise<unknown>;
159
+ delete(collection: string, id: string, options: object): Promise<unknown>;
160
+ move(collection: string, id: string, target: object, options: object): Promise<unknown>;
161
+ unpublish(collection: string, id: string, options: object): Promise<unknown>;
162
+ updateGlobal(global: string, data: object, options: object): Promise<unknown>;
163
+ }
164
+
165
+ type DocOf<T extends KitcmsTypes, S extends keyof T['collections']> = T['collections'][S];
166
+ type GlobalsOf<T extends KitcmsTypes> = NonNullable<T['globals']>;
167
+ type InputOf<T extends KitcmsTypes, S extends string> =
168
+ NonNullable<T['inputs']> extends infer I ? (S extends keyof I ? I[S] : Partial<DocOf<T, S>>) : never;
169
+ /** Write input: relationship ids are plain strings. */
170
+ type WritableValue<V> = V extends Rel<string> ? string : V extends readonly Rel<string>[] ? string[] : V;
171
+ type Writable<T> = { [K in keyof T]?: WritableValue<T[K]> };
172
+
173
+ export interface KitcmsClient<T extends KitcmsTypes = GenericTypes> {
174
+ find<S extends keyof T['collections'] & string, D extends Depth = 0>(
175
+ collection: S,
176
+ args?: Omit<FindArgs<DocOf<T, S>, D>, 'as'> & DraftRead,
177
+ ): Promise<PaginatedDocs<Populate<DocOf<T, S>, T, D>>>;
178
+
179
+ /** The first match, or `null`. */
180
+ findOne<S extends keyof T['collections'] & string, D extends Depth = 0>(
181
+ collection: S,
182
+ args?: Omit<FindArgs<DocOf<T, S>, D>, 'limit' | 'page' | 'pagination' | 'as'> & DraftRead,
183
+ ): Promise<Populate<DocOf<T, S>, T, D> | null>;
184
+
185
+ /** `null` when the document doesn't exist or the caller may not read it. */
186
+ findByID<S extends keyof T['collections'] & string, D extends Depth = 0>(
187
+ collection: S,
188
+ id: string,
189
+ args?: Omit<ReadOptions<D>, 'as'> & DraftRead,
190
+ ): Promise<Populate<DocOf<T, S>, T, D> | null>;
191
+
192
+ /** A global. An unsaved global returns its defaults. */
193
+ findGlobal<S extends keyof GlobalsOf<T> & string, D extends Depth = 0>(
194
+ global: S,
195
+ args?: Omit<ReadOptions<D>, 'as'> & DraftRead,
196
+ ): Promise<Populate<GlobalsOf<T>[S], T, D>>;
197
+
198
+ /** Trusted callers only. Throws `FORBIDDEN` without `as: 'system'`. */
199
+ create<S extends keyof T['collections'] & string, D extends Depth = 0>(
200
+ collection: S,
201
+ data: InputOf<T, S> | Writable<DocOf<T, S>>,
202
+ options: WriteOptions<D>,
203
+ ): Promise<Populate<DocOf<T, S>, T, D>>;
204
+
205
+ /** Partial update. Trusted callers only. */
206
+ update<S extends keyof T['collections'] & string, D extends Depth = 0>(
207
+ collection: S,
208
+ id: string,
209
+ data: Partial<InputOf<T, S>> | Writable<DocOf<T, S>>,
210
+ options: WriteOptions<D>,
211
+ ): Promise<Populate<DocOf<T, S>, T, D>>;
212
+
213
+ /** Trusted callers only. Returns the deleted document. */
214
+ delete<S extends keyof T['collections'] & string>(
215
+ collection: S,
216
+ id: string,
217
+ options: { as: 'system' },
218
+ ): Promise<DocOf<T, S>>;
219
+
220
+ /** Orderable collections: place a document before/after another. Trusted callers only. */
221
+ move<S extends keyof T['collections'] & string>(
222
+ collection: S,
223
+ id: string,
224
+ target: MoveTarget,
225
+ options: { as: 'system' },
226
+ ): Promise<DocOf<T, S>>;
227
+
228
+ /** Drafts: take a published document offline. Trusted callers only. */
229
+ unpublish<S extends keyof T['collections'] & string>(
230
+ collection: S,
231
+ id: string,
232
+ options: { as: 'system' },
233
+ ): Promise<DocOf<T, S>>;
234
+
235
+ /** Partial update of a global. Trusted callers only. */
236
+ updateGlobal<S extends keyof GlobalsOf<T> & string, D extends Depth = 0>(
237
+ global: S,
238
+ data: Writable<GlobalsOf<T>[S]>,
239
+ options: WriteOptions<D>,
240
+ ): Promise<Populate<GlobalsOf<T>[S], T, D>>;
241
+
242
+ count<S extends keyof T['collections'] & string>(
243
+ collection: S,
244
+ args?: { where?: Where<DocOf<T, S>> } & CallerOptions,
245
+ ): Promise<number>;
246
+
247
+ /** The public URL for an R2 key, or `null` when none is configured. */
248
+ getMediaUrl(key: string): Promise<string | null>;
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------------------------
252
+ // Errors
253
+ // ---------------------------------------------------------------------------------------------
254
+
255
+ /** A kitcms error that crossed the Service Binding. `code` and `status` mirror core's `KitcmsError`. */
256
+ export class KitcmsClientError extends Error {
257
+ readonly code: string;
258
+ readonly status: number;
259
+ constructor(code: string, status: number, message: string) {
260
+ super(message);
261
+ this.name = 'KitcmsClientError';
262
+ this.code = code;
263
+ this.status = status;
264
+ }
265
+ }
266
+
267
+ export function isKitcmsClientError(err: unknown): err is KitcmsClientError {
268
+ return err instanceof KitcmsClientError;
269
+ }
270
+
271
+ const WIRE = /kitcms:([A-Za-z_]+):(\d{3}): ([\s\S]*)$/;
272
+
273
+ /** Turns `kitcms:<CODE>:<status>: <message>` into a `KitcmsClientError`; anything else is returned as-is. */
274
+ export function parseKitcmsError(err: unknown): unknown {
275
+ if (err instanceof KitcmsClientError) return err;
276
+ const message = typeof err === 'object' && err !== null ? (err as { message?: unknown }).message : undefined;
277
+ if (typeof message !== 'string') return err;
278
+ const m = WIRE.exec(message);
279
+ if (!m) return err;
280
+ const out = new KitcmsClientError(m[1]!, Number(m[2]), m[3]!);
281
+ if (err instanceof Error && err.stack) out.cause = err;
282
+ return out;
283
+ }
284
+
285
+ // ---------------------------------------------------------------------------------------------
286
+ // Client
287
+ // ---------------------------------------------------------------------------------------------
288
+
289
+ /** Wraps a kitcms Service Binding. Pass the generated `KitcmsTypes` for typed collections. */
290
+ export function kitcms<T extends KitcmsTypes = GenericTypes>(binding: KitcmsBinding): KitcmsClient<T> {
291
+ async function call<R>(fn: () => Promise<R>): Promise<R> {
292
+ try {
293
+ return await fn();
294
+ } catch (e) {
295
+ throw parseKitcmsError(e);
296
+ }
297
+ }
298
+ // Options are forwarded untouched; the server whitelists and validates them.
299
+ return {
300
+ find: (collection, args) => call(() => binding.find(collection, args) as Promise<never>),
301
+ findOne: (collection, args) => call(() => binding.findOne(collection, args) as Promise<never>),
302
+ findByID: (collection, id, args) => call(() => binding.findByID(collection, id, args) as Promise<never>),
303
+ count: (collection, args) => call(() => binding.count(collection, args)),
304
+ findGlobal: (global, args) => call(() => binding.findGlobal(global, args) as Promise<never>),
305
+ getMediaUrl: (key) => call(() => binding.getMediaUrl(key)),
306
+ create: (collection, data, options) => call(() => binding.create(collection, data, options) as Promise<never>),
307
+ update: (collection, id, data, options) =>
308
+ call(() => binding.update(collection, id, data, options) as Promise<never>),
309
+ delete: (collection, id, options) => call(() => binding.delete(collection, id, options) as Promise<never>),
310
+ move: (collection, id, target, options) =>
311
+ call(() => binding.move(collection, id, target, options) as Promise<never>),
312
+ unpublish: (collection, id, options) => call(() => binding.unpublish(collection, id, options) as Promise<never>),
313
+ updateGlobal: (global, data, options) =>
314
+ call(() => binding.updateGlobal(global, data, options) as Promise<never>),
315
+ };
316
+ }