@lemonadecms/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.
@@ -0,0 +1,351 @@
1
+ // Shared, framework-independent HTTP implementation behind the fluent SDK.
2
+ // Configuration and query options are validated before sending a request. The
3
+ // selected factory supplies the credential and route; callers cannot switch modes
4
+ // through list options. Responses are checked as unknown data before their envelope
5
+ // is converted from API snake_case to SDK camelCase. No automatic retries occur.
6
+ import { CMSConfigurationError, CMSRequestError, CMSResponseError, CMSTimeoutError } from "./errors.js";
7
+ const identifier = /^[a-z][a-z0-9_]{0,47}$/;
8
+ const cursor = (value) => uuid.test(value) || (value.length <= 8192 && /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value));
9
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ const serviceURL = "https://lemonadecms.com";
11
+ // Narrow unknown JSON to an object before accessing properties. Arrays and null
12
+ // are not valid objects for the API envelope even though typeof reports object.
13
+ function record(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ // Only configured deadlines need a local controller/race. Keep the default
17
+ // fetch signal unchanged, while rejecting already-cancelled work before I/O.
18
+ // Native composition preserves fetch-style cancellation even when another caller
19
+ // listener suppresses the caller's abort event. Reject the new timeout+signal
20
+ // combination when that capability is absent rather than weaken cancellation.
21
+ // One cleanup path releases the timer and private listener regardless of outcome.
22
+ // The attached fulfillment/rejection handlers also consume late custom-fetch
23
+ // completions when a transport ignores cancellation; they cannot settle twice.
24
+ function withinDeadline(timeoutMs, callerSignal, execute) {
25
+ callerSignal?.throwIfAborted();
26
+ if (timeoutMs === undefined)
27
+ return execute(callerSignal);
28
+ if (callerSignal && typeof AbortSignal.any !== "function") {
29
+ throw new CMSConfigurationError("Combining timeoutMs and signal requires AbortSignal.any support.");
30
+ }
31
+ const controller = new AbortController();
32
+ const requestSignal = callerSignal ? AbortSignal.any([callerSignal, controller.signal]) : controller.signal;
33
+ return new Promise((resolve, reject) => {
34
+ let settled = false;
35
+ let timer;
36
+ const finish = (complete) => {
37
+ if (settled)
38
+ return;
39
+ settled = true;
40
+ if (timer !== undefined)
41
+ clearTimeout(timer);
42
+ requestSignal.removeEventListener("abort", cancel);
43
+ complete();
44
+ };
45
+ const cancel = () => {
46
+ const reason = requestSignal.reason;
47
+ finish(() => reject(reason));
48
+ controller.abort(reason);
49
+ };
50
+ requestSignal.addEventListener("abort", cancel, { once: true });
51
+ timer = setTimeout(() => {
52
+ const error = requestSignal.aborted ? requestSignal.reason : callerSignal?.aborted ? callerSignal.reason : new CMSTimeoutError(timeoutMs);
53
+ finish(() => reject(error));
54
+ controller.abort(error);
55
+ }, timeoutMs);
56
+ try {
57
+ execute(requestSignal).then(value => finish(() => resolve(value)), error => finish(() => reject(error)));
58
+ }
59
+ catch (error) {
60
+ finish(() => reject(error));
61
+ }
62
+ });
63
+ }
64
+ function query(options) {
65
+ if (!record(options) || Object.keys(options).some(key => !["select", "limit", "page", "pageSize", "after", "before", "signal", "locale", "filters", "sort", "includeRemote"].includes(key))) {
66
+ throw new TypeError("Supported list options are select, limit, page, pageSize, after, before, locale, filters, sort and signal.");
67
+ }
68
+ const params = new URLSearchParams();
69
+ if (options.includeRemote !== undefined) {
70
+ if (typeof options.includeRemote !== "boolean")
71
+ throw new TypeError("includeRemote must be a boolean.");
72
+ params.set("includeRemote", String(options.includeRemote));
73
+ }
74
+ if (options.select !== undefined) {
75
+ if (!Array.isArray(options.select) || options.select.length < 1 || options.select.length > 24 ||
76
+ new Set(options.select).size !== options.select.length ||
77
+ !options.select.every(key => typeof key === "string" && identifier.test(key))) {
78
+ throw new TypeError("select must contain 1–24 unique field identifiers.");
79
+ }
80
+ params.set("select", options.select.join(","));
81
+ }
82
+ if (options.page !== undefined || options.pageSize !== undefined) {
83
+ if (options.limit !== undefined || options.after !== undefined || options.before !== undefined)
84
+ throw new TypeError("Use page/pageSize or limit/after/before, never both modes.");
85
+ const page = options.page ?? 1, size = options.pageSize ?? 25;
86
+ if (!Number.isSafeInteger(page) || page < 1 || !Number.isInteger(size) || size < 1 || size > 100 || (page - 1) * size > 10000)
87
+ throw new TypeError("page must be positive, pageSize 1–100, and skipped rows at most 10000.");
88
+ params.set("page", String(page));
89
+ params.set("pageSize", String(size));
90
+ }
91
+ if (options.limit !== undefined) {
92
+ if (typeof options.limit !== "number" || !Number.isInteger(options.limit) || options.limit < 1 || options.limit > 100) {
93
+ throw new TypeError("limit must be an integer between 1 and 100.");
94
+ }
95
+ params.set("limit", String(options.limit));
96
+ }
97
+ if (options.locale !== undefined) {
98
+ if (typeof options.locale !== "string" || !/^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?$/.test(options.locale)) {
99
+ throw new TypeError("locale must be a language code such as en, es or pt-BR.");
100
+ }
101
+ params.set("locale", options.locale);
102
+ }
103
+ if (options.after !== undefined && options.before !== undefined) {
104
+ throw new TypeError("Use either after or before, never both.");
105
+ }
106
+ for (const direction of ["after", "before"]) {
107
+ const boundary = options[direction];
108
+ if (boundary !== undefined) {
109
+ if (typeof boundary !== "string" || !cursor(boundary)) {
110
+ throw new TypeError(`${direction} must be a cursor returned by the CMS.`);
111
+ }
112
+ params.set(direction, boundary);
113
+ }
114
+ }
115
+ if (options.filters !== undefined) {
116
+ const scalar = (v) => typeof v === "string" && v.length <= 20000 || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v);
117
+ const choices = (value) => Array.isArray(value) && value.length >= 1 && value.length <= 100 &&
118
+ new Set(value).size === value.length && value.every(option => typeof option === "string" && option.trim().length > 0 && option.length <= 20000);
119
+ if (!Array.isArray(options.filters) || options.filters.length > 10 || !options.filters.every(clause => record(clause) && Object.keys(clause).sort().join(",") === "field,op,value" && typeof clause.field === "string" && identifier.test(clause.field) &&
120
+ (clause.op === "eq" ? clause.value === null || scalar(clause.value) : clause.op === "in" ? Array.isArray(clause.value) && clause.value.length >= 1 && clause.value.length <= 100 && clause.value.every(scalar) :
121
+ ["contains_any", "contains_all"].includes(String(clause.op)) ? choices(clause.value) :
122
+ ["gt", "gte", "lt", "lte"].includes(String(clause.op)) && (typeof clause.value === "string" || typeof clause.value === "number" && Number.isFinite(clause.value))))) {
123
+ throw new TypeError("filters must contain at most ten valid scalar or multiple-choice AND clauses.");
124
+ }
125
+ const encoded = JSON.stringify(options.filters);
126
+ if (new TextEncoder().encode(encoded).length > 4096)
127
+ throw new TypeError("filters exceed 4 KB.");
128
+ params.set("filters", encoded);
129
+ }
130
+ if (options.sort !== undefined) {
131
+ if (!record(options.sort) || Object.keys(options.sort).sort().join(",") !== "direction,field" || !identifier.test(String(options.sort.field)) || !["asc", "desc"].includes(String(options.sort.direction)))
132
+ throw new TypeError("sort requires a scalar field and asc/desc direction.");
133
+ params.set("sort", JSON.stringify(options.sort));
134
+ }
135
+ return params;
136
+ }
137
+ // Network responses start as unknown even in TypeScript. Check structural
138
+ // properties before returning them, and translate HTTP snake_case metadata into
139
+ // SDK camelCase. This does not validate the caller-declared model field types.
140
+ function decodePage(value) {
141
+ if (!record(value) || !Array.isArray(value.data) || !record(value.meta) ||
142
+ typeof value.meta.limit !== "number" || !Number.isInteger(value.meta.limit) ||
143
+ value.meta.limit < 1 || value.meta.limit > 100 || value.data.length > value.meta.limit ||
144
+ !(value.meta.next_cursor === null || (typeof value.meta.next_cursor === "string" && cursor(value.meta.next_cursor)))) {
145
+ throw new CMSResponseError("CMS returned an invalid content page.");
146
+ }
147
+ const data = value.data.map(decodeEntry);
148
+ const meta = { limit: value.meta.limit, nextCursor: value.meta.next_cursor };
149
+ if (value.meta.page !== undefined || value.meta.page_size !== undefined) {
150
+ if (typeof value.meta.page !== "number" || !Number.isInteger(value.meta.page) || value.meta.page < 1 || value.meta.page_size !== value.meta.limit || (value.meta.page - 1) * value.meta.limit > 10000)
151
+ throw new CMSResponseError("CMS returned invalid numbered pagination metadata.");
152
+ meta.page = value.meta.page;
153
+ meta.pageSize = value.meta.limit;
154
+ }
155
+ // Additive metadata is optional for older installations. When supplied, check
156
+ // it rather than silently treating a malformed boundary as the end of a list.
157
+ if (value.meta.previous_cursor !== undefined) {
158
+ if (!(value.meta.previous_cursor === null || typeof value.meta.previous_cursor === "string" && cursor(value.meta.previous_cursor)))
159
+ throw new CMSResponseError("CMS returned an invalid previous cursor.");
160
+ meta.previousCursor = value.meta.previous_cursor;
161
+ }
162
+ for (const [wire, sdk] of [["has_next_page", "hasNextPage"], ["has_previous_page", "hasPreviousPage"]]) {
163
+ if (value.meta[wire] !== undefined) {
164
+ if (typeof value.meta[wire] !== "boolean")
165
+ throw new CMSResponseError("CMS returned invalid pagination metadata.");
166
+ meta[sdk] = value.meta[wire];
167
+ }
168
+ }
169
+ if (meta.hasNextPage !== undefined && meta.hasNextPage !== (meta.nextCursor !== null) ||
170
+ meta.hasPreviousPage !== undefined && meta.previousCursor !== undefined && meta.hasPreviousPage !== (meta.previousCursor !== null)) {
171
+ throw new CMSResponseError("CMS returned inconsistent pagination metadata.");
172
+ }
173
+ return { data, meta };
174
+ }
175
+ function decodeEntry(entry) {
176
+ if (!record(entry) || typeof entry.id !== "string" || !uuid.test(entry.id) || !record(entry.fields) ||
177
+ !(entry.published_at === null || typeof entry.published_at === "string"))
178
+ throw new CMSResponseError("CMS returned an invalid content entry.");
179
+ const result = { id: entry.id, fields: entry.fields, publishedAt: entry.published_at };
180
+ if (entry.remote !== undefined) {
181
+ const remote = entry.remote;
182
+ if (remote === null)
183
+ result.remote = null;
184
+ else {
185
+ if (!record(remote) || !["available", "error", "disabled", "not_linked"].includes(String(remote.status)) ||
186
+ remote.read_only !== true || typeof remote.stale !== "boolean" || typeof remote.source !== "string" ||
187
+ !(remote.error === null || typeof remote.error === "string") ||
188
+ !(remote.fetched_at === null || typeof remote.fetched_at === "string") ||
189
+ !(remote.expires_at === null || typeof remote.expires_at === "string") ||
190
+ !(remote.data === null || record(remote.data) && Object.values(remote.data).every(v => v === null ||
191
+ typeof v === "string" || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v)))) {
192
+ throw new CMSResponseError("CMS returned invalid remote metadata.");
193
+ }
194
+ result.remote = { source: remote.source, status: remote.status,
195
+ readOnly: true, stale: remote.stale, data: remote.data,
196
+ error: remote.error, fetchedAt: remote.fetched_at, expiresAt: remote.expires_at };
197
+ }
198
+ }
199
+ return result;
200
+ }
201
+ /** Internal shared transport; public exports choose the credential and route. */
202
+ export function createTransport(options, key, mode) {
203
+ if (!record(options)) {
204
+ throw new CMSConfigurationError("CMS client options must be an object.");
205
+ }
206
+ // Reject old host configuration rather than silently sending a developer's
207
+ // credentials to production. Check inherited options too: spreads and plain
208
+ // JavaScript callers must receive the same migration error as TypeScript.
209
+ if (["url", "baseURL", "baseUrl", "host", "endpoint"].some(option => option in options)) {
210
+ throw new CMSConfigurationError("CMS clients connect to https://lemonadecms.com. Remove custom URL configuration.");
211
+ }
212
+ const credential = mode === "content" ? "publicKey" : "secretKey";
213
+ if (Object.keys(options).some(option => !["projectId", credential, "fetch", "timeoutMs"].includes(option)) || "environment" in options) {
214
+ throw new CMSConfigurationError("Supported CMS options are projectId, the delivery key, fetch and timeoutMs. Select a content environment with its delivery key.");
215
+ }
216
+ const timeoutMs = options.timeoutMs;
217
+ if (timeoutMs !== undefined && (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)) {
218
+ throw new CMSConfigurationError("CMS timeoutMs must be an integer between 1 and 2147483647 milliseconds.");
219
+ }
220
+ if (typeof options.projectId !== "string" || !uuid.test(options.projectId)) {
221
+ throw new CMSConfigurationError("CMS projectId is required and must be a UUID.");
222
+ }
223
+ // Each factory chooses its credential kind. Prefix and length detect mistakes
224
+ // early; only the backend can verify whether the credential is currently valid.
225
+ const prefix = mode === "content" ? "pk" : "sk";
226
+ // Named tokens retain a visible public/preview distinction. The server owns
227
+ // scope and revocation checks; the browser factory still rejects preview keys.
228
+ const scoped = new RegExp(`^lmd_${prefix}_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\.[A-Za-z0-9_-]{43}$`);
229
+ if (typeof key !== "string" || (!new RegExp(`^${prefix}_[A-Za-z0-9_-]{43}$`).test(key) && !scoped.test(key))) {
230
+ throw new CMSConfigurationError(mode === "content"
231
+ ? "A valid publicKey (pk_ or lmd_pk_) is required. Never pass a secret key to the browser client."
232
+ : "A valid secretKey (sk_ or lmd_sk_) is required for the server preview client.");
233
+ }
234
+ // Dependency injection supports framework server contexts and deterministic tests
235
+ // without coupling the client to Vue, React, or a particular HTTP library.
236
+ const fetcher = options.fetch ?? globalThis.fetch?.bind(globalThis);
237
+ if (typeof fetcher !== "function") {
238
+ throw new CMSConfigurationError("This environment needs fetch; supply a compatible fetch implementation.");
239
+ }
240
+ const endpoint = `${serviceURL}/api/v1/projects/${options.projectId}/${mode}`;
241
+ return {
242
+ content(model) {
243
+ if (typeof model !== "string" || !identifier.test(model)) {
244
+ throw new TypeError("Content type must be a lowercase model identifier.");
245
+ }
246
+ return {
247
+ async list(options = {}) {
248
+ return await request(options);
249
+ },
250
+ pages(options = {}) {
251
+ return iteratePages(options);
252
+ },
253
+ async *entries(options = {}) {
254
+ const signal = options?.signal;
255
+ for await (const page of iteratePages(options)) {
256
+ for (const entry of page.data) {
257
+ signal?.throwIfAborted();
258
+ yield entry;
259
+ }
260
+ }
261
+ },
262
+ async get(id, options = {}) {
263
+ if (typeof id !== "string" || !uuid.test(id))
264
+ throw new TypeError("id must be an entry UUID.");
265
+ if (!record(options) || Object.keys(options).some(k => !["select", "locale", "signal", "includeRemote"].includes(k)))
266
+ throw new TypeError("get supports select, locale, includeRemote and signal.");
267
+ return await request(options, id);
268
+ },
269
+ };
270
+ // No eager fetch or prefetch: the iterator asks for a page only after the
271
+ // previous yield is consumed. A break/error closes it without more requests.
272
+ async function* iteratePages(options = {}) {
273
+ if (!record(options) || "before" in options || "page" in options || "pageSize" in options)
274
+ throw new TypeError("pages/entries support forward traversal with after.");
275
+ const { maxPages = 1000, ...list } = options;
276
+ if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 10000)
277
+ throw new TypeError("maxPages must be an integer between 1 and 10000.");
278
+ query(list);
279
+ // Freeze query semantics at first consumption; callers can reuse/mutate
280
+ // their form state without changing a traversal halfway through.
281
+ const { signal, ...serializable } = list;
282
+ const snapshot = { ...JSON.parse(JSON.stringify(serializable)), ...(signal ? { signal } : {}) };
283
+ let after = snapshot.after;
284
+ const seen = new Set(after ? [after] : []);
285
+ for (let count = 0; count < maxPages; count++) {
286
+ signal?.throwIfAborted();
287
+ const page = await request({ ...snapshot, ...(after ? { after } : {}) });
288
+ const next = page.meta.nextCursor;
289
+ if (next !== null && seen.has(next))
290
+ throw new CMSResponseError("CMS returned a repeated pagination cursor.");
291
+ yield page;
292
+ if (next === null)
293
+ return;
294
+ if (count + 1 === maxPages)
295
+ throw new RangeError("Pagination reached maxPages; resume with the last nextCursor or raise the limit.");
296
+ seen.add(next);
297
+ after = next;
298
+ }
299
+ }
300
+ async function request(options, id) {
301
+ const params = query(options);
302
+ const suffix = params.size ? `?${params}` : "";
303
+ return withinDeadline(timeoutMs, options.signal, async (signal) => {
304
+ const checkCancellation = () => {
305
+ signal?.throwIfAborted();
306
+ options.signal?.throwIfAborted();
307
+ };
308
+ checkCancellation();
309
+ // Use only bearer authorization: omit browser cookies, refuse redirects that
310
+ // could change the destination, and request fresh data. Abort and network errors
311
+ // propagate to the caller; this client does not silently retry a request.
312
+ const response = await fetcher(`${endpoint}/${model}${id ? `/${id}` : ""}${suffix}`, {
313
+ method: "GET",
314
+ headers: { Accept: "application/json", Authorization: `Bearer ${key}` },
315
+ credentials: "omit",
316
+ redirect: "error",
317
+ cache: "no-store",
318
+ ...(signal ? { signal } : {}),
319
+ });
320
+ checkCancellation();
321
+ let body;
322
+ try {
323
+ body = await response.json();
324
+ }
325
+ catch (error) {
326
+ checkCancellation();
327
+ if (error instanceof Error && error.name === "AbortError")
328
+ throw error;
329
+ if (response.ok)
330
+ throw new CMSResponseError("CMS returned invalid JSON.");
331
+ }
332
+ checkCancellation();
333
+ // An unsuccessful HTTP status becomes CMSRequestError, even if the response
334
+ // was not JSON. A successful response with malformed JSON instead signals a
335
+ // response-contract error. Consumers can distinguish these failure categories.
336
+ if (!response.ok) {
337
+ throw new CMSRequestError(record(body) && typeof body.error === "string" ? body.error : `CMS request failed (${response.status}).`, response.status, record(body) && typeof body.code === "string" ? body.code : "http_error");
338
+ }
339
+ // Validate the envelope at runtime. Model field types are the caller's
340
+ // declaration until schema-generated types/runtime validators exist.
341
+ if (id) {
342
+ if (!record(body))
343
+ throw new CMSResponseError("CMS returned an invalid content item.");
344
+ return decodeEntry(body.data);
345
+ }
346
+ return decodePage(body);
347
+ });
348
+ }
349
+ },
350
+ };
351
+ }
@@ -0,0 +1,139 @@
1
+ export type ModelMap<Models> = {
2
+ [Key in keyof Models]: object;
3
+ };
4
+ export type UntypedModels = Record<string, Record<string, unknown>>;
5
+ export type FieldName<Fields> = Extract<keyof Fields, string>;
6
+ export interface CMSBaseOptions {
7
+ /** Requests always use https://lemonadecms.com. Custom CMS hosts are unsupported. */
8
+ url?: never;
9
+ projectId: string;
10
+ /** Compatible transport for SSR, testing or polyfills; receives production URLs. */
11
+ fetch?: typeof globalThis.fetch;
12
+ /**
13
+ * Optional per-request deadline, including JSON reading: 1–2147483647 ms.
14
+ * No default deadline. Combining with a caller signal requires AbortSignal.any.
15
+ */
16
+ timeoutMs?: number;
17
+ }
18
+ export interface CMSClientOptions extends CMSBaseOptions {
19
+ publicKey: string;
20
+ }
21
+ export interface CMSPreviewOptions extends CMSBaseOptions {
22
+ secretKey: string;
23
+ }
24
+ type Scalar = string | number | boolean;
25
+ export type ScalarField<Fields> = {
26
+ [Key in FieldName<Fields>]: unknown extends Fields[Key] ? Key : NonNullable<Fields[Key]> extends Scalar ? Key : never;
27
+ }[FieldName<Fields>];
28
+ type ScalarContentFilter<Fields> = {
29
+ [Key in ScalarField<Fields>]: {
30
+ field: Key;
31
+ op: "eq";
32
+ value: Extract<Fields[Key], Scalar> | (unknown extends Fields[Key] ? Scalar : never) | null;
33
+ } | {
34
+ field: Key;
35
+ op: "in";
36
+ value: readonly (Extract<Fields[Key], Scalar> | (unknown extends Fields[Key] ? Scalar : never))[];
37
+ } | (NonNullable<Fields[Key]> extends boolean ? never : {
38
+ field: Key;
39
+ op: "gt" | "gte" | "lt" | "lte";
40
+ value: Extract<Fields[Key], string | number> | (unknown extends Fields[Key] ? string | number : never);
41
+ });
42
+ }[ScalarField<Fields>];
43
+ type ChoicesField<Fields> = {
44
+ [Key in FieldName<Fields>]: unknown extends Fields[Key] ? Key : NonNullable<Fields[Key]> extends readonly string[] ? Key : never;
45
+ }[FieldName<Fields>];
46
+ type ChoicesValue<Value> = NonNullable<Value> extends readonly (infer Option extends string)[] ? Option : string;
47
+ type ChoicesContentFilter<Fields> = {
48
+ [Key in ChoicesField<Fields>]: {
49
+ field: Key;
50
+ op: "contains_any" | "contains_all";
51
+ value: readonly ChoicesValue<Fields[Key]>[];
52
+ };
53
+ }[ChoicesField<Fields>];
54
+ export type ContentFilter<Fields> = ScalarContentFilter<Fields> | ChoicesContentFilter<Fields>;
55
+ export interface ContentSort<Fields> {
56
+ field: ScalarField<Fields>;
57
+ direction: "asc" | "desc";
58
+ }
59
+ interface BaseListOptions<Key extends string, Fields> {
60
+ select?: readonly Key[];
61
+ locale?: string;
62
+ limit?: number;
63
+ /** Up to ten AND clauses, validated against the workspace schema by the server. */
64
+ filters?: readonly ContentFilter<Fields>[];
65
+ sort?: ContentSort<Fields>;
66
+ signal?: AbortSignal;
67
+ /** Explicit live enrichment, independently cached from the saved publication. */
68
+ includeRemote?: boolean;
69
+ }
70
+ /** Follow a returned boundary in exactly one direction; or request a numbered page; modes cannot be combined. */
71
+ export type ListOptions<Key extends string = string, Fields = Record<string, unknown>> = BaseListOptions<Key, Fields> & ({
72
+ after?: string;
73
+ before?: never;
74
+ page?: never;
75
+ pageSize?: never;
76
+ } | {
77
+ before?: string;
78
+ after?: never;
79
+ page?: never;
80
+ pageSize?: never;
81
+ } | {
82
+ page?: number;
83
+ pageSize?: number;
84
+ limit?: never;
85
+ after?: never;
86
+ before?: never;
87
+ });
88
+ /** Lazy forward traversal, capped at 1,000 pages by default (maximum 10,000). */
89
+ export type PaginationOptions<Key extends string = string, Fields = Record<string, unknown>> = Omit<ListOptions<Key, Fields>, "before" | "page" | "pageSize"> & {
90
+ page?: never;
91
+ pageSize?: never;
92
+ maxPages?: number;
93
+ };
94
+ export interface ContentEntry<Fields> {
95
+ id: string;
96
+ fields: Fields;
97
+ publishedAt: string | null;
98
+ remote?: RemoteValue | null;
99
+ }
100
+ export interface RemoteValue<Data = Record<string, string | number | boolean | null>> {
101
+ source: string;
102
+ status: "available" | "error" | "disabled" | "not_linked";
103
+ readOnly: true;
104
+ stale: boolean;
105
+ data: Data | null;
106
+ error: string | null;
107
+ fetchedAt: string | null;
108
+ expiresAt: string | null;
109
+ }
110
+ export interface ContentPage<Fields> {
111
+ data: ContentEntry<Fields>[];
112
+ meta: {
113
+ nextCursor: string | null;
114
+ limit: number;
115
+ page?: number;
116
+ pageSize?: number;
117
+ previousCursor?: string | null;
118
+ hasNextPage?: boolean;
119
+ hasPreviousPage?: boolean;
120
+ };
121
+ }
122
+ export interface ContentCollection<Fields extends object> {
123
+ list<const Key extends FieldName<Fields> = FieldName<Fields>>(options?: ListOptions<Key, Fields>): Promise<ContentPage<Pick<Fields, Key>>>;
124
+ /** Fetch only as the caller requests another page. Breaking stops network work. */
125
+ pages<const Key extends FieldName<Fields> = FieldName<Fields>>(options?: PaginationOptions<Key, Fields>): AsyncIterableIterator<ContentPage<Pick<Fields, Key>>>;
126
+ /** Flatten pages lazily, retaining at most one page of entries. */
127
+ entries<const Key extends FieldName<Fields> = FieldName<Fields>>(options?: PaginationOptions<Key, Fields>): AsyncIterableIterator<ContentEntry<Pick<Fields, Key>>>;
128
+ get<const Key extends FieldName<Fields> = FieldName<Fields>>(id: string, options?: Pick<ListOptions<Key, Fields>, "select" | "locale" | "signal" | "includeRemote">): Promise<ContentEntry<Pick<Fields, Key>>>;
129
+ }
130
+ export interface CMSClient<Models extends ModelMap<Models> = UntypedModels> {
131
+ content<Model extends Extract<keyof Models, string>>(model: Model): ContentCollection<Models[Model]>;
132
+ }
133
+ /** A draft may omit required fields or contain nulls until it is published. */
134
+ export type PreviewModels<Models> = {
135
+ [Model in keyof Models]: {
136
+ [Field in keyof Models[Model]]?: Models[Model][Field] | null;
137
+ };
138
+ };
139
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ // TypeScript contracts for configuration, fluent queries, and returned pages.
2
+ // A caller can supply a model map to get checked model names and selected fields.
3
+ // These types disappear at runtime: they are not schema discovery or validation
4
+ // of arbitrary model payloads. transport.ts validates the response envelope;
5
+ // the CMS backend validates stored field values when they are written/published.
6
+ export {};
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@lemonadecms/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Framework-independent content delivery and developer tooling for Lemonade CMS",
5
+ "license": "MIT",
6
+ "homepage": "https://lemonadecms.com/guides/sdk",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/ilara-booqself/lemonadecms.git",
10
+ "directory": "packages/cms-client"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/ilara-booqself/lemonadecms/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public",
17
+ "registry": "https://registry.npmjs.org/"
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "files": [
22
+ "dist/*.js",
23
+ "dist/*.d.ts",
24
+ "bin/*.mjs",
25
+ "bin/cli/*.mjs",
26
+ "bin/codegen/*.mjs",
27
+ "README.md",
28
+ "LICENSE",
29
+ "CHANGELOG.md"
30
+ ],
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "./server": {
40
+ "types": "./dist/server.d.ts",
41
+ "browser": "./dist/server.browser.js",
42
+ "default": "./dist/server.js"
43
+ },
44
+ "./preview": {
45
+ "types": "./dist/preview.d.ts",
46
+ "default": "./dist/preview.js"
47
+ }
48
+ },
49
+ "bin": {
50
+ "cms-codegen": "bin/generate-types.mjs",
51
+ "lemonade": "bin/lemonade.mjs"
52
+ },
53
+ "private": false
54
+ }