@thecms/sdk 0.0.0-stage → 0.20.1-dev.122

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.js ADDED
@@ -0,0 +1,944 @@
1
+ // src/errors.ts
2
+ var CmsError = class extends Error {
3
+ constructor(status, code, message, details) {
4
+ super(message);
5
+ this.status = status;
6
+ this.code = code;
7
+ this.details = details;
8
+ this.name = "CmsError";
9
+ }
10
+ };
11
+ async function toError(res) {
12
+ const body = await res.json().catch(() => null);
13
+ const e = body?.error;
14
+ return new CmsError(res.status, e?.code ?? `HTTP_${res.status}`, e?.message ?? res.statusText, e?.details);
15
+ }
16
+
17
+ // src/manage.ts
18
+ var enc = encodeURIComponent;
19
+ function recordsQuery(q = {}) {
20
+ const out = {
21
+ sort: q.sort ? `${q.sort.field}:${q.sort.direction ?? "asc"}` : void 0,
22
+ limit: q.limit !== void 0 ? String(q.limit) : void 0,
23
+ cursor: q.cursor,
24
+ offset: q.offset !== void 0 ? String(q.offset) : void 0,
25
+ search: q.search,
26
+ status: q.status,
27
+ untranslated: q.untranslated,
28
+ depth: q.depth !== void 0 ? String(q.depth) : void 0,
29
+ lang: q.lang,
30
+ full: q.full ? "1" : void 0
31
+ };
32
+ for (const f of q.where ?? []) out[`where[${f.field}][${f.op}]`] = Array.isArray(f.value) ? f.value.join(",") : String(f.value);
33
+ return out;
34
+ }
35
+ function uploadOptions(opts) {
36
+ if (!opts) return {};
37
+ const o = opts;
38
+ return o.for !== void 0 || o.links !== void 0 && !Array.isArray(o.links) ? o : { links: opts };
39
+ }
40
+ function management(caller, auth) {
41
+ const readerToken = () => auth.reader?.() || void 0;
42
+ const guard = (fn) => auth.key || auth.token || readerToken() ? fn() : Promise.reject(new CmsError(0, "API_KEY_REQUIRED", auth.reader ? "Sign the user in first: the management part of an app acts as its signed-in user" : "The management part of the SDK needs the workspace's secretKey (server-side only) or the personal token of thecms login (a person's script)"));
43
+ const call = (method, path, opts = {}) => {
44
+ const token = auth.token ?? readerToken();
45
+ return caller(method, path, token ? { ...opts, token } : opts);
46
+ };
47
+ return {
48
+ records: {
49
+ /** A page of records of an entity, with the API key's filters (`where`, `sort`, `limit` ≤ 200, `cursor`, `search`). */
50
+ list: (entity, query) => guard(() => call("GET", `/records/${enc(entity)}`, { query: recordsQuery(query) })),
51
+ get: (entity, id, opts = {}) => guard(() => call("GET", `/records/${enc(entity)}/${enc(id)}`, {
52
+ query: { depth: opts.depth !== void 0 ? String(opts.depth) : void 0, lang: opts.lang }
53
+ })),
54
+ /**
55
+ * Creates a draft. A site's server that writes what a visitor sent (a shape that `writes`) passes the visitor's
56
+ * address as `forwardedFor`: the key only creates, so the platform asks for it (422 "the visitor's address is
57
+ * required" without) and limits the writes per visitor and per schema (429 `RATE_LIMITED`).
58
+ */
59
+ create: (entity, data, opts = {}) => guard(() => call("POST", `/records/${enc(entity)}`, { body: data, ...opts.forwardedFor ? { forwardedFor: opts.forwardedFor } : {} })),
60
+ /** Changes the draft (publish to make it public). */
61
+ update: (entity, id, data) => guard(() => call("PUT", `/records/${enc(entity)}/${enc(id)}`, { body: data })),
62
+ /** Publishes now or at `publishAt`; with `unpublishAt` it is withdrawn at that time if still this version (D604). */
63
+ publish: (entity, id, opts = {}) => guard(() => call("POST", `/records/${enc(entity)}/${enc(id)}/publish`, { body: opts })),
64
+ unpublish: (entity, id) => guard(() => call("POST", `/records/${enc(entity)}/${enc(id)}/unpublish`)),
65
+ delete: (entity, id) => guard(() => call("DELETE", `/records/${enc(entity)}/${enc(id)}`))
66
+ },
67
+ media: {
68
+ list: (query = {}) => guard(() => call("GET", "/assets", {
69
+ query: { limit: query.limit?.toString(), offset: query.offset?.toString(), search: query.search, mime: query.mime }
70
+ })),
71
+ get: (id) => guard(() => call("GET", `/assets/${enc(id)}`)),
72
+ /**
73
+ * Upload a file; `links` = the records it belongs to (entity → ids) or,
74
+ * as the third argument, `{ links?, for? }`. READER-WRITES (D566): an
75
+ * app's user uploads only `for: { schema, field }` — a file field their
76
+ * app's role writes (its rule applies).
77
+ */
78
+ upload: (file, filename, opts) => guard(() => {
79
+ const { links, for: target } = uploadOptions(opts);
80
+ const form = new FormData();
81
+ form.append("file", file, filename);
82
+ if (links) form.append("links", JSON.stringify(links));
83
+ if (target) form.append("for", JSON.stringify(target));
84
+ return call("POST", "/assets", { form });
85
+ }),
86
+ setLinks: (id, links) => guard(() => call("PUT", `/assets/${enc(id)}/links`, { body: { links } })),
87
+ /** Alternative text per locale and focal point. */
88
+ update: (id, details) => guard(() => call("PUT", `/assets/${enc(id)}`, { body: details })),
89
+ delete: (id) => guard(() => call("DELETE", `/assets/${enc(id)}`))
90
+ },
91
+ products: {
92
+ list: () => guard(() => call("GET", "/products")),
93
+ get: (id) => guard(() => call("GET", `/products/${enc(id)}`)),
94
+ create: (input) => guard(() => call("POST", "/products", { body: input })),
95
+ update: (id, input) => guard(() => call("PUT", `/products/${enc(id)}`, { body: input })),
96
+ archive: (id) => guard(() => call("POST", `/products/${enc(id)}/archive`))
97
+ },
98
+ /** AGENT D461: the workspace's languages (the default one never changes). */
99
+ languages: {
100
+ get: () => guard(() => call("GET", "/i18n")),
101
+ add: (locale) => guard(() => call("POST", "/i18n/locales", { body: { locale } }))
102
+ },
103
+ /** AGENT D461: the workspace's applications and their manual redirects (an old address → a path or an URL, 301 / 302). */
104
+ applications: {
105
+ list: () => guard(() => call("GET", "/applications")),
106
+ redirects: {
107
+ list: (appId) => guard(() => call("GET", `/applications/${enc(appId)}/redirects`)),
108
+ add: (appId, redirect) => guard(() => call("POST", `/applications/${enc(appId)}/redirects`, { body: redirect })),
109
+ remove: (appId, fromPath) => guard(() => call("DELETE", `/applications/${enc(appId)}/redirects`, { query: { from: fromPath } }))
110
+ }
111
+ },
112
+ /** VISITS (D159): the navigation history, from the site's server (permission `visits` of the key's role). */
113
+ visits: {
114
+ /** The history of an anonymous visitor (the site's id) or of a reader, newest first; `reader` = whom the visitor id is linked to. */
115
+ of: (who, page2 = {}) => guard(() => call("GET", "/visits", {
116
+ query: { ..."visitor" in who ? { visitor: who.visitor } : { reader: who.reader }, limit: page2.limit?.toString(), cursor: page2.cursor }
117
+ })),
118
+ /** The most visited pages of the last `days` (30), of one entity's records with `entity`. */
119
+ popular: (q = {}) => guard(() => call("GET", "/visits/popular", {
120
+ query: { entity: q.entity, days: q.days?.toString(), limit: q.limit?.toString() }
121
+ })),
122
+ /** Forget an anonymous visitor (every visit of the id). Irreversible. */
123
+ forget: (visitor) => guard(() => call("DELETE", `/visits/visitors/${enc(visitor)}`))
124
+ }
125
+ };
126
+ }
127
+
128
+ // src/live.ts
129
+ var NO_STORE = { cache: "no-store" };
130
+ function createLive(deps) {
131
+ const feeds = /* @__PURE__ */ new Map();
132
+ const wait2 = (ms) => new Promise((r) => setTimeout(r, ms));
133
+ const spread = (ms) => Math.floor(Math.random() * Math.max(0, ms));
134
+ function feedOf(source) {
135
+ const tenant = source.url.split("/")[2] ?? "";
136
+ let key = `public:${tenant}`;
137
+ let stream2 = `/v1/${tenant}/public/live`;
138
+ let changes = `/v1/${tenant}/public/changes`;
139
+ if (source.channel === "preview") {
140
+ const token = source.listen ?? "";
141
+ const q = `?listen=${encodeURIComponent(token)}`;
142
+ key = `preview:${token}`;
143
+ stream2 = `/v1/${tenant}/public/preview/live${q}`;
144
+ changes = `/v1/${tenant}/public/preview/changes${q}`;
145
+ }
146
+ let feed = feeds.get(key);
147
+ if (!feed) feeds.set(key, feed = { stream: stream2, changes, watches: /* @__PURE__ */ new Set(), abort: null, running: false, lastV: 0 });
148
+ return feed;
149
+ }
150
+ async function refresh(feed, w, v) {
151
+ if (!feed.watches.has(w)) return;
152
+ if (w.signalOnly) {
153
+ w.callback(Array.isArray(w.data) ? [...w.data] : { ...w.data });
154
+ return;
155
+ }
156
+ try {
157
+ const res = await deps.fetch(`${deps.base}${w.url}${w.url.includes("?") ? "&" : "?"}v=${v}`, {
158
+ headers: deps.headers(),
159
+ signal: feed.abort?.signal,
160
+ ...NO_STORE
161
+ });
162
+ if (res.status === 404) {
163
+ w.callback(null);
164
+ return;
165
+ }
166
+ if (!res.ok) return;
167
+ const fresh = await res.json();
168
+ if (fresh._live) {
169
+ w.tags = new Set(fresh._live.tags);
170
+ w.url = fresh._live.url;
171
+ }
172
+ if (feed.watches.has(w)) w.callback(fresh);
173
+ } catch {
174
+ }
175
+ }
176
+ function changed(feed, c) {
177
+ if (c.v > feed.lastV) feed.lastV = c.v;
178
+ for (const w of feed.watches) {
179
+ if (!c.tags.some((t) => w.tags.has(t))) continue;
180
+ if (w.timer) clearTimeout(w.timer);
181
+ w.timer = setTimeout(() => {
182
+ w.timer = null;
183
+ void refresh(feed, w, c.v);
184
+ }, spread(deps.jitterMs));
185
+ }
186
+ }
187
+ async function stream(feed, signal) {
188
+ let res;
189
+ try {
190
+ res = await deps.fetch(`${deps.base}${feed.stream}`, {
191
+ headers: { ...deps.headers(), Accept: "text/event-stream" },
192
+ signal,
193
+ ...NO_STORE
194
+ });
195
+ } catch {
196
+ return false;
197
+ }
198
+ if (!res.ok || !res.body) return false;
199
+ const reader = res.body.getReader();
200
+ const decoder = new TextDecoder();
201
+ let buffer = "";
202
+ try {
203
+ for (; ; ) {
204
+ const { value, done } = await reader.read();
205
+ if (done) return true;
206
+ buffer += decoder.decode(value, { stream: true });
207
+ let end;
208
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
209
+ const block = buffer.slice(0, end);
210
+ buffer = buffer.slice(end + 2);
211
+ let event = "message";
212
+ let data = "";
213
+ for (const line of block.split("\n")) {
214
+ if (line.startsWith("event:")) event = line.slice(6).trim();
215
+ else if (line.startsWith("data:")) data += line.slice(5).trim();
216
+ }
217
+ if (event === "changed" && data) {
218
+ try {
219
+ changed(feed, JSON.parse(data));
220
+ } catch {
221
+ }
222
+ }
223
+ }
224
+ }
225
+ } catch {
226
+ return true;
227
+ }
228
+ }
229
+ async function poll(feed, signal) {
230
+ try {
231
+ const res = await deps.fetch(`${deps.base}${feed.changes}`, { headers: deps.headers(), signal, ...NO_STORE });
232
+ if (!res.ok) return;
233
+ const { changes } = await res.json();
234
+ for (const c of changes) if (c.v > feed.lastV) changed(feed, c);
235
+ } catch {
236
+ }
237
+ }
238
+ async function loop(feed) {
239
+ feed.running = true;
240
+ feed.abort = new AbortController();
241
+ const signal = feed.abort.signal;
242
+ feed.lastV = Date.now();
243
+ while (feed.watches.size > 0 && !signal.aborted) {
244
+ const kept = await stream(feed, signal);
245
+ if (signal.aborted || feed.watches.size === 0) break;
246
+ if (kept) {
247
+ await wait2(2e3 + spread(8e3));
248
+ continue;
249
+ }
250
+ const until = Date.now() + 5 * 6e4;
251
+ while (Date.now() < until && feed.watches.size > 0 && !signal.aborted) {
252
+ await poll(feed, signal);
253
+ await wait2(deps.pollMs + spread(deps.pollMs / 2));
254
+ }
255
+ }
256
+ feed.running = false;
257
+ }
258
+ return {
259
+ /**
260
+ * Follow an answer: `callback(fresh)` with the same kind of data whenever it
261
+ * changes (`null` when it no longer exists). A preview's answer (D271): the
262
+ * same data as a new object — read it again from the site's server. Returns `stop()`.
263
+ */
264
+ watch(data, callback) {
265
+ if (!data?._live) return () => {
266
+ };
267
+ const feed = feedOf(data._live);
268
+ const w = {
269
+ tags: new Set(data._live.tags),
270
+ url: data._live.url,
271
+ callback,
272
+ timer: null,
273
+ signalOnly: data._live.channel === "preview",
274
+ data
275
+ };
276
+ feed.watches.add(w);
277
+ if (!feed.running) void loop(feed);
278
+ return () => {
279
+ if (w.timer) clearTimeout(w.timer);
280
+ feed.watches.delete(w);
281
+ if (feed.watches.size === 0) {
282
+ feed.abort?.abort();
283
+ feed.running = false;
284
+ }
285
+ };
286
+ }
287
+ };
288
+ }
289
+
290
+ // src/channel.ts
291
+ var PLATFORM_API = "https://apidev.dotscms.com";
292
+
293
+ // src/platform.ts
294
+ function platformUrl(path) {
295
+ return /^https?:\/\//.test(path) ? path : `${PLATFORM_API}${path.startsWith("/") ? "" : "/"}${path}`;
296
+ }
297
+ var SDK_VERSION = "0.20.1-dev.122";
298
+ var SITE_PROTOCOL = 2;
299
+ var SITE_HEADER = "X-CMS-Site";
300
+ var siteHeader = (library, version) => `${library}/${version}; protocol=${SITE_PROTOCOL}`;
301
+ var UNKNOWN_VISITOR_HEADER = "X-CMS-Visitor";
302
+ var UNKNOWN_VISITOR = "unknown";
303
+
304
+ // src/sdk.ts
305
+ function listToken(link) {
306
+ const raw = typeof link === "string" ? link : link.token;
307
+ return raw.includes("/") ? raw.slice(raw.lastIndexOf("/") + 1).split("?")[0] : raw;
308
+ }
309
+ function newVisitorId() {
310
+ return globalThis.crypto.randomUUID();
311
+ }
312
+ var UNLOCK_MAX_KEYS = 100;
313
+ var RETRY_DELAYS_MS = [250, 1e3, 2500];
314
+ var RETRY_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
315
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
316
+ function retryAfterMs(res, fallback) {
317
+ const s = Number(res.headers.get("Retry-After"));
318
+ return Number.isFinite(s) && s > 0 ? Math.min(s * 1e3, 5e3) : fallback;
319
+ }
320
+ var SITE_TTL_MS = 6e4;
321
+ function createSdk(options) {
322
+ if (options.secretKey && options.personalToken) throw new Error("theCMS.: secretKey or personalToken, not both \u2014 the API key for what runs without a person, the personal token for a person's script");
323
+ if (options.reader && (options.secretKey || options.personalToken)) throw new Error("theCMS.: reader is for an app without a server \u2014 never with secretKey or personalToken");
324
+ const base = PLATFORM_API;
325
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
326
+ let known = null;
327
+ let asking = null;
328
+ async function where() {
329
+ if (known && Date.now() - known.at < SITE_TTL_MS) return known;
330
+ asking ??= (async () => {
331
+ try {
332
+ const h = { Accept: "application/json" };
333
+ if (typeof globalThis.document === "undefined") h[SITE_HEADER] = siteHeader("sdk", SDK_VERSION);
334
+ const res = await doFetch(`${base}/v1/_sites/${encodeURIComponent(options.publicKey)}`, { headers: h, ...NO_STORE });
335
+ if (!res.ok) throw await toError(res);
336
+ const site2 = await res.json();
337
+ known = { ...site2, at: Date.now() };
338
+ return site2;
339
+ } finally {
340
+ asking = null;
341
+ }
342
+ })();
343
+ return asking;
344
+ }
345
+ function t() {
346
+ if (!known) throw new Error("theCMS.: the site of this public key is not known yet");
347
+ return encodeURIComponent(known.workspace);
348
+ }
349
+ function headers(call2) {
350
+ const h = { Accept: "application/json" };
351
+ if (options.secretKey) h["X-Api-Key"] = options.secretKey;
352
+ if (call2.unknownVisitor) h[UNKNOWN_VISITOR_HEADER] = UNKNOWN_VISITOR;
353
+ else if (call2.forwardedFor) {
354
+ h["X-Forwarded-For"] = call2.forwardedFor;
355
+ h["X-Thecms-Visitor"] = call2.forwardedFor;
356
+ }
357
+ if (call2.token) h.Authorization = `Bearer ${call2.token}`;
358
+ if (call2.json) h["Content-Type"] = "application/json";
359
+ return h;
360
+ }
361
+ function url(path, query) {
362
+ const full = path.startsWith("/v1/") ? path : `/v1/${t()}${path}`;
363
+ const qs = new URLSearchParams();
364
+ for (const [k, v] of Object.entries(query ?? {})) for (const one of v === void 0 ? [] : Array.isArray(v) ? v : [v]) qs.append(k, one);
365
+ const s = qs.toString();
366
+ return `${base}${full}${s ? (full.includes("?") ? "&" : "?") + s : ""}`;
367
+ }
368
+ const call = async (method, path, opts = {}) => {
369
+ if (!path.startsWith("/v1/")) await where();
370
+ const write = method !== "GET" && method !== "HEAD" && !opts.form;
371
+ const h = headers({ ...opts, json: opts.body !== void 0 });
372
+ if (write) h["Idempotency-Key"] = newVisitorId();
373
+ const init = {
374
+ method,
375
+ headers: h,
376
+ body: opts.form ?? (opts.body !== void 0 ? JSON.stringify(opts.body) : void 0),
377
+ signal: opts.signal,
378
+ // never a copy kept by the site's own fetch cache: freshness is our CDN's (it is emptied at each publish)
379
+ ...method === "GET" ? NO_STORE : {}
380
+ };
381
+ for (let attempt = 0; ; attempt++) {
382
+ const delay = write ? RETRY_DELAYS_MS[attempt] : void 0;
383
+ let res;
384
+ try {
385
+ res = await doFetch(url(path, opts.query), init);
386
+ } catch (err) {
387
+ if (delay === void 0 || opts.signal?.aborted) throw err;
388
+ await wait(delay);
389
+ continue;
390
+ }
391
+ if (delay !== void 0 && (RETRY_STATUSES.has(res.status) || res.status === 409 && res.headers.has("Retry-After"))) {
392
+ await wait(retryAfterMs(res, delay));
393
+ continue;
394
+ }
395
+ if (!res.ok) throw await toError(res);
396
+ return res.status === 204 ? void 0 : await res.json();
397
+ }
398
+ };
399
+ const BATCH_MAX = 50;
400
+ const FLUSH_MS = 3e4;
401
+ const g = globalThis;
402
+ const inBrowser = typeof g.document !== "undefined";
403
+ const queue = /* @__PURE__ */ new Map();
404
+ let timer = null;
405
+ let listening = false;
406
+ function send(b, beacon) {
407
+ const body = JSON.stringify({ ...b.visitor ? { visitor: b.visitor } : {}, views: b.views });
408
+ if (beacon && !b.readerToken && g.navigator?.sendBeacon && g.Blob && g.navigator.sendBeacon(url("/public/visits"), new g.Blob([body], { type: "text/plain" }))) return;
409
+ void doFetch(url("/public/visits"), {
410
+ method: "POST",
411
+ headers: headers({ forwardedFor: b.forwardedFor, token: b.readerToken, json: true }),
412
+ body,
413
+ keepalive: true
414
+ }).catch(() => void 0);
415
+ }
416
+ function flushViews(beacon = false) {
417
+ if (timer) clearTimeout(timer);
418
+ timer = null;
419
+ for (const b of queue.values()) send(b, beacon);
420
+ queue.clear();
421
+ }
422
+ function track(key, opts) {
423
+ if (!known) {
424
+ void where().then(() => track(key, opts), () => void 0);
425
+ return;
426
+ }
427
+ const view = { id: newVisitorId().replace(/-/g, ""), key, at: (/* @__PURE__ */ new Date()).toISOString() };
428
+ const who = { visitor: opts.visitor ?? options.visitor?.() ?? void 0, readerToken: opts.readerToken, forwardedFor: opts.forwardedFor };
429
+ if (!inBrowser) {
430
+ send({ ...who, views: [view] }, false);
431
+ return;
432
+ }
433
+ const group = `${who.visitor ?? ""}|${who.readerToken ?? ""}|${who.forwardedFor ?? ""}`;
434
+ const batch = queue.get(group) ?? { ...who, views: [] };
435
+ batch.views.push(view);
436
+ queue.set(group, batch);
437
+ if (batch.views.length >= BATCH_MAX) {
438
+ send(batch, false);
439
+ queue.delete(group);
440
+ }
441
+ if (!listening) {
442
+ listening = true;
443
+ g.document.addEventListener("visibilitychange", () => {
444
+ if (g.document.visibilityState === "hidden") flushViews(true);
445
+ });
446
+ g.addEventListener?.("pagehide", () => flushViews(true));
447
+ }
448
+ timer ??= setTimeout(() => flushViews(false), FLUSH_MS);
449
+ }
450
+ const manage = management(call, { key: !!options.secretKey, token: options.personalToken, reader: options.reader });
451
+ const live = createLive({
452
+ base,
453
+ fetch: doFetch,
454
+ headers: () => headers({}),
455
+ jitterMs: options.live?.jitterMs ?? 3e3,
456
+ pollMs: options.live?.pollMs ?? 1e4
457
+ });
458
+ let site = null;
459
+ const sdk = {
460
+ // ─── Pages ────────────────────────────────────────────────────────────
461
+ /**
462
+ * The page of the site at a full public path (locale prefix included, the
463
+ * default locale has none). Redirects and "not found" come back as data:
464
+ * the site decides how to answer.
465
+ */
466
+ async page(path, opts = {}) {
467
+ const { app } = await where();
468
+ const res = await doFetch(url(`/views/${encodeURIComponent(app)}/route`, {
469
+ path,
470
+ preview: opts.preview,
471
+ country: opts.preview ? opts.country : void 0,
472
+ list: opts.lists?.length ? opts.lists.map(listToken) : void 0
473
+ }), { headers: headers(opts), signal: opts.signal, ...NO_STORE });
474
+ if (res.status === 404) return { kind: "notFound" };
475
+ if (res.status === 403) {
476
+ const body2 = await res.clone().json().catch(() => null);
477
+ if (body2?.error?.code === "GEO_BLOCKED") {
478
+ return { kind: "geoBlocked", country: body2.error.country, continent: body2.error.continent };
479
+ }
480
+ throw await toError(res);
481
+ }
482
+ if (!res.ok) throw await toError(res);
483
+ const body = await res.json();
484
+ if ("redirect" in body) return { kind: "redirect", ...body.redirect };
485
+ if (body._visit && (opts.track ?? options.track ?? true)) track(body._visit, opts);
486
+ return { kind: "page", page: body };
487
+ },
488
+ /**
489
+ * PREVIEW P5 (D227): is this preview token's session still in force, and
490
+ * until when? `{ active: false }` once it expired or was ended.
491
+ */
492
+ async previewStatus(token, opts = {}) {
493
+ const res = await doFetch(url("/public/preview/changes", { preview: token }), { headers: headers(opts), signal: opts.signal, ...NO_STORE });
494
+ if (res.status === 401) return { active: false };
495
+ if (!res.ok) throw await toError(res);
496
+ const { expiresAt } = await res.json();
497
+ return { active: true, expiresAt };
498
+ },
499
+ /**
500
+ * SITE-KEY (D253): what holds for the whole site — its address, the prefix
501
+ * of its preview route, whether it has a sitemap, the languages, the
502
+ * workspace's globals (`{ key: value }`, every variant: a translated value
503
+ * as `{ language: text }`, a file as its public object) and messages (per
504
+ * language, nested by key: ready for i18next or next-intl). Kept a minute;
505
+ * `live.watch(site, …)` follows it.
506
+ */
507
+ async site(opts = {}) {
508
+ if (site && Date.now() - site.at < SITE_TTL_MS) return site.answer;
509
+ const { workspace, app } = await where();
510
+ const answer = { ...await call("GET", `/views/${encodeURIComponent(app)}/site`, opts), workspace, app };
511
+ site = { answer, at: Date.now() };
512
+ return answer;
513
+ },
514
+ /**
515
+ * The site's sitemap (`file`: one part of an index, `"1.xml"`), to serve it
516
+ * from the site's own address; null when the application publishes none.
517
+ */
518
+ async sitemap(file, opts = {}) {
519
+ const { app } = await where();
520
+ const path = `/views/${encodeURIComponent(app)}/${file ? `sitemap/${encodeURIComponent(file)}` : "sitemap.xml"}`;
521
+ const res = await doFetch(url(path), { headers: { ...headers(opts), Accept: "application/xml" }, signal: opts.signal, ...NO_STORE });
522
+ if (res.status === 404) return null;
523
+ if (!res.ok) throw await toError(res);
524
+ return res.text();
525
+ },
526
+ /**
527
+ * SEO-AI (D491): the site's llms.txt (`part`: one part of an index), to
528
+ * serve from the site's own address (`/llms.txt`); null while the
529
+ * application has AI readers off.
530
+ */
531
+ async llms(part, opts = {}) {
532
+ const { app } = await where();
533
+ const path = `/views/${encodeURIComponent(app)}/${part ? `llms/${encodeURIComponent(String(part))}.txt` : "llms.txt"}`;
534
+ const res = await doFetch(url(path), { headers: { ...headers(opts), Accept: "text/plain" }, signal: opts.signal, ...NO_STORE });
535
+ if (res.status === 404) return null;
536
+ if (!res.ok) throw await toError(res);
537
+ return res.text();
538
+ },
539
+ /**
540
+ * SEO-AI (D492): the clean text (markdown) of the published page at `path`,
541
+ * as a reader from nowhere known reads it — to serve from the site's
542
+ * address of the text (`/llms` + the page's path); null when there is no
543
+ * page to read or AI readers are off.
544
+ */
545
+ async pageText(path, opts = {}) {
546
+ const { app } = await where();
547
+ const res = await doFetch(url(`/views/${encodeURIComponent(app)}/text`, { path }), { headers: { ...headers(opts), Accept: "text/markdown" }, signal: opts.signal, ...NO_STORE });
548
+ if (res.status === 404) return null;
549
+ if (!res.ok) throw await toError(res);
550
+ return res.text();
551
+ },
552
+ // ─── Lists ────────────────────────────────────────────────────────────
553
+ /**
554
+ * F3b.8: a list is a block of a page (`page()`); its next pages and
555
+ * narrowed filters come back as links built by the CMS (D304: `{ token, url }`
556
+ * — `pagination.next`, `pages[]`, `filters[].options[]`, `filters[].clear`).
557
+ * The whole page at a list's state: `page(path, { lists: [link.token] })`.
558
+ * The list alone (e.g. "load more" without moving): `follow(link)`.
559
+ */
560
+ follow(link, opts = {}) {
561
+ const path = typeof link === "string" ? link.includes("/") ? link : `/public/records/${link}` : link.url ?? `/public/records/${link.token}`;
562
+ return call("GET", path, opts);
563
+ },
564
+ // ─── Paywall (D9: two calls, never one personalised answer) ─────────
565
+ /**
566
+ * F3b.7 (D55): the values of protected fields by their keys (`_protected`
567
+ * of a public answer), for the end-user's purchases. One result per key,
568
+ * in order; more than 100 keys go in several calls.
569
+ */
570
+ async unlock(keys, endUserToken, opts = {}) {
571
+ const results = [];
572
+ for (let i = 0; i < keys.length; i += UNLOCK_MAX_KEYS) {
573
+ const part = await call("POST", "/monetization/unlock", {
574
+ ...opts,
575
+ token: endUserToken,
576
+ body: { keys: keys.slice(i, i + UNLOCK_MAX_KEYS) }
577
+ });
578
+ results.push(...part.results);
579
+ }
580
+ return { results };
581
+ },
582
+ // ─── Readers (SIGN-IN: the platform signs them in) ───────────────────
583
+ /**
584
+ * SIGN-IN (D346): where to send the browser to sign a reader in with one
585
+ * of the site's methods (`site().signIn[].key`). The platform does the
586
+ * whole sign-in and comes back to the site's `/api/cms/signed-in?code=…&to=…`
587
+ * (or to `returnTo` with `?signin=<reason>` when it refuses). `returnTo` is
588
+ * a path of the site (`/…`).
589
+ */
590
+ async signInUrl(key, returnTo = "/", opts = {}) {
591
+ await where();
592
+ return url(`/readers/sign-in/${encodeURIComponent(key)}`, { app: options.publicKey, return: returnTo, challenge: opts.challenge });
593
+ },
594
+ /**
595
+ * D346 — server side: the code of `/api/cms/signed-in` for the reader's
596
+ * session (60 s, once). The token stays on the server (a cookie of the site).
597
+ */
598
+ exchangeSignIn(code, opts = {}) {
599
+ const { verifier, ...rest } = opts;
600
+ return call("POST", "/readers/sessions", { ...rest, body: { code, app: options.publicKey, ...verifier ? { verifier } : {} } });
601
+ },
602
+ /**
603
+ * READER-WRITES (D567, D571): an app user's session renewed with its
604
+ * refresh token — a new 1-hour token; the refresh token stays the same.
605
+ * Refused (401) once the reader is revoked or forgotten or the app's users
606
+ * lost their role: sign in again.
607
+ */
608
+ refreshSession(refreshToken, opts = {}) {
609
+ return call("POST", "/readers/sessions/refresh", { ...opts, body: { refreshToken, app: options.publicKey } });
610
+ },
611
+ auth: {
612
+ me(endUserToken, opts = {}) {
613
+ return call("GET", "/auth/me", { ...opts, token: endUserToken });
614
+ }
615
+ },
616
+ me: {
617
+ /** What the end-user owns and which fields of which entity it unlocks. */
618
+ entitlements(endUserToken, opts = {}) {
619
+ return call(
620
+ "GET",
621
+ "/me/entitlements",
622
+ { ...opts, token: endUserToken }
623
+ );
624
+ }
625
+ },
626
+ // ─── Payments (PAYMENTS D354–D361: the provider is only a gateway) ───
627
+ /**
628
+ * D361 — buy a product: theCMS. prices it for the reader's country, picks
629
+ * its payment provider and creates the order; send the reader to
630
+ * `redirectUrl`. They come back to `returnTo` (a path of this site) with
631
+ * `?order=<id>`. Refusals are a `CmsError` with `details.reason`
632
+ * (`not_on_sale`, `not_in_your_country`, `no_methods_for_you`,
633
+ * `provider_disabled`, `provider_refused`, `provider_unreachable`,
634
+ * `already_owned_forever`). From a server, pass `forwardedFor` (and the
635
+ * secret key) so the reader's country is theirs, not the server's.
636
+ */
637
+ checkout(productId, returnTo, endUserToken, opts = {}) {
638
+ return call("POST", "/checkout", { ...opts, token: endUserToken, body: { productId, app: options.publicKey, return: returnTo } });
639
+ },
640
+ /** D360 — the reader's purchases, newest first: product, when, what was paid, until when, in force, still on sale. */
641
+ purchases(endUserToken, opts = {}) {
642
+ return call("GET", "/me/purchases", { ...opts, token: endUserToken });
643
+ },
644
+ /** D355 — the state of one of the reader's orders (the return page's `?order=<id>`): `pending` until the provider's notice. */
645
+ order(id, endUserToken, opts = {}) {
646
+ return call("GET", `/me/orders/${encodeURIComponent(id)}`, { ...opts, token: endUserToken });
647
+ },
648
+ // ─── Management (server-side, API key) ──────────────────────────────
649
+ ...manage,
650
+ // ─── Live (LIVE L3) ──────────────────────────────────────────────────
651
+ live: {
652
+ /**
653
+ * Follow data the site already has — a page (`r.page`), a list (`follow`),
654
+ * the globals, the messages: `callback(fresh)` with the new data
655
+ * whenever it changes (`null` when it no longer exists). The site applies
656
+ * it as it wants. Returns `stop()`.
657
+ */
658
+ watch: live.watch
659
+ },
660
+ // ─── Visits (D159–D161) ──────────────────────────────────────────────
661
+ visits: {
662
+ /** The signed-in reader's pages, newest first (also the ones their browser read before signing in). */
663
+ me(readerToken, page2 = {}, opts = {}) {
664
+ return call("GET", "/public/visits/me", { ...opts, token: readerToken, query: { limit: page2.limit?.toString(), cursor: page2.cursor } });
665
+ },
666
+ /**
667
+ * Record a view of a page you already have (NEXT, D187: resolved on a server, drawn in the browser):
668
+ * its `_visit` key goes in the queue like `page()` would send it. Nothing without a key (a preview).
669
+ */
670
+ track(data, opts = {}) {
671
+ if (data?._visit) track(data._visit, opts);
672
+ },
673
+ /** Send the queued page views now (a browser sends them by itself when the page hides, or every 30 s). */
674
+ flush() {
675
+ flushViews(false);
676
+ },
677
+ /** with the API key: `of`, `popular`, `forget` */
678
+ ...manage.visits
679
+ }
680
+ };
681
+ return sdk;
682
+ }
683
+
684
+ // src/pkce.ts
685
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
686
+ function base64url(bytes) {
687
+ let out = "";
688
+ for (let i = 0; i < bytes.length; i += 3) {
689
+ const n = bytes[i] << 16 | (bytes[i + 1] ?? 0) << 8 | (bytes[i + 2] ?? 0);
690
+ out += B64[n >> 18 & 63] + B64[n >> 12 & 63];
691
+ if (i + 1 < bytes.length) out += B64[n >> 6 & 63];
692
+ if (i + 2 < bytes.length) out += B64[n & 63];
693
+ }
694
+ return out;
695
+ }
696
+ function webCrypto() {
697
+ const c = globalThis.crypto;
698
+ if (!c?.subtle || !c.getRandomValues) throw new Error("theCMS.: PKCE needs Web Crypto (crypto.subtle and crypto.getRandomValues)");
699
+ return c;
700
+ }
701
+ async function pkceChallenge(verifier) {
702
+ const digest = await webCrypto().subtle.digest("SHA-256", new TextEncoder().encode(verifier));
703
+ return base64url(new Uint8Array(digest));
704
+ }
705
+ async function createPkce() {
706
+ const verifier = base64url(webCrypto().getRandomValues(new Uint8Array(32)));
707
+ return { verifier, challenge: await pkceChallenge(verifier) };
708
+ }
709
+
710
+ // src/image.ts
711
+ var STEPS = [64, 160, 320, 480, 640, 960, 1280, 1920, 2560];
712
+ var page = globalThis;
713
+ function imageFor(asset, element, opts = {}) {
714
+ const box = element.getBoundingClientRect();
715
+ const dpr = page.devicePixelRatio || 1;
716
+ const want = Math.ceil(box.width * dpr);
717
+ const max = asset.width ?? STEPS[STEPS.length - 1];
718
+ const step = STEPS.find((s) => s >= want && s <= max) ?? STEPS.filter((s) => s <= max).pop() ?? STEPS[0];
719
+ if (!asset.url) return "";
720
+ const u = new URL(asset.url, PLATFORM_API);
721
+ u.searchParams.set("w", String(step));
722
+ if (opts.height && box.height > 0) {
723
+ u.searchParams.set("h", String(Math.ceil(box.height * step / Math.max(box.width, 1))));
724
+ u.searchParams.set("fit", "cover");
725
+ }
726
+ if (!u.searchParams.has("fmt")) u.searchParams.set("fmt", "auto");
727
+ return u.toString().replace(/%2C/g, ",");
728
+ }
729
+
730
+ // src/preview.ts
731
+ var PREVIEW_PARAM = "preview";
732
+ function previewEntryUrl(siteUrl, path, token) {
733
+ const page2 = path === "/" || path === "" ? "" : encodeURI(path.startsWith("/") ? path : `/${path}`);
734
+ return `${siteUrl.replace(/\/+$/, "")}${page2 || "/"}?${PREVIEW_PARAM}=${encodeURIComponent(token)}`;
735
+ }
736
+ function previewEntry(url) {
737
+ const u = new URL(String(url), "http://site.invalid");
738
+ const token = u.searchParams.get(PREVIEW_PARAM);
739
+ if (!token) return null;
740
+ u.searchParams.delete(PREVIEW_PARAM);
741
+ return { token, clean: `${u.pathname}${u.search}${u.hash}` };
742
+ }
743
+ var LIST_PARAM = "f";
744
+ var PREVIEW_COOKIE = "cms_preview";
745
+ var FRAME_HEADER = "X-CMS-Frame";
746
+ function previewRequestAllowed(secFetchDest, opts = {}) {
747
+ const dest = secFetchDest?.trim().toLowerCase() ?? "";
748
+ if (dest === "iframe") return true;
749
+ return !opts.entry && opts.frame?.trim() === "1";
750
+ }
751
+ var cookieTail = (secure) => secure ? ["HttpOnly", "SameSite=None", "Secure", "Partitioned"] : ["HttpOnly", "SameSite=Lax"];
752
+ function previewCookie(token, expiresAt, opts = {}) {
753
+ const seconds = Math.max(1, Math.floor((Date.parse(expiresAt) - Date.now()) / 1e3));
754
+ return [`${PREVIEW_COOKIE}=${encodeURIComponent(token)}`, "Path=/", `Max-Age=${seconds}`, ...cookieTail(opts.secure !== false)].join("; ");
755
+ }
756
+ function readPreviewCookie(cookieHeader) {
757
+ for (const part of (cookieHeader ?? "").split(";")) {
758
+ const i = part.indexOf("=");
759
+ if (i > 0 && part.slice(0, i).trim() === PREVIEW_COOKIE) {
760
+ const value = part.slice(i + 1).trim();
761
+ try {
762
+ return value ? decodeURIComponent(value) : void 0;
763
+ } catch {
764
+ return void 0;
765
+ }
766
+ }
767
+ }
768
+ return void 0;
769
+ }
770
+
771
+ // src/editor.ts
772
+ var BLOCK = "[data-cms-block][data-uid]";
773
+ var framed = false;
774
+ function markFrameRequests() {
775
+ const g = globalThis;
776
+ const w = g.window;
777
+ if (framed || !w || !w.parent || w.parent === w || !g.fetch || !g.location || !g.Headers) return;
778
+ framed = true;
779
+ const origin = g.location.origin;
780
+ const base = g.fetch.bind(g);
781
+ const H = g.Headers;
782
+ g.fetch = (input, init) => {
783
+ const target = typeof input === "string" ? input : input.href ?? input.url ?? "";
784
+ let same = false;
785
+ try {
786
+ same = new URL(target, origin).origin === origin;
787
+ } catch {
788
+ }
789
+ if (!same) return base(input, init);
790
+ const headers = new H(init?.headers ?? (typeof input === "object" && input && "headers" in input ? input.headers : void 0));
791
+ headers.set(FRAME_HEADER, "1");
792
+ return base(input, { ...init, headers });
793
+ };
794
+ }
795
+ var SAFE_UID = /^[\w:.-]+$/;
796
+ function closest(target, selector) {
797
+ const el = target;
798
+ return el && typeof el.closest === "function" ? el.closest(selector) : null;
799
+ }
800
+ function editorBridge(opts) {
801
+ const env = globalThis;
802
+ const { window: w, document: d, location: loc } = env;
803
+ if (!w || !d || !loc || !w.parent || w.parent === w) return () => {
804
+ };
805
+ const parent = w.parent;
806
+ const send = (message) => parent.postMessage(message, "*");
807
+ send({ type: "thecms:preview", protocol: SITE_PROTOCOL, path: loc.pathname + loc.search, ...opts.page });
808
+ const rectOf = (el) => {
809
+ const range = d.createRange();
810
+ range.selectNodeContents(el);
811
+ const b = range.getBoundingClientRect();
812
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
813
+ };
814
+ const blocks = () => Array.from(d.querySelectorAll(BLOCK), (el) => {
815
+ const error = el.getAttribute("data-error");
816
+ return {
817
+ uid: el.getAttribute("data-uid"),
818
+ in: el.getAttribute("data-in") === "layout" ? "layout" : "view",
819
+ set: el.getAttribute("data-set") ?? "",
820
+ shape: el.getAttribute("data-shape"),
821
+ rect: rectOf(el),
822
+ ...el.hasAttribute("data-missing") ? { missing: true } : {},
823
+ ...error ? { error } : {}
824
+ };
825
+ });
826
+ let queued = false;
827
+ const report = () => {
828
+ if (queued) return;
829
+ queued = true;
830
+ const run = () => {
831
+ queued = false;
832
+ send({ type: "thecms:blocks", blocks: blocks() });
833
+ };
834
+ if (w.requestAnimationFrame) w.requestAnimationFrame(run);
835
+ else setTimeout(run, 16);
836
+ };
837
+ report();
838
+ const onClick = (e) => {
839
+ if (e.defaultPrevented || e.button !== 0) return;
840
+ const a = closest(e.target, "a[href]");
841
+ if (a) {
842
+ const raw = a.getAttribute("href");
843
+ if (!raw || raw.startsWith("#") || a.hasAttribute("download")) return;
844
+ let url;
845
+ try {
846
+ url = new URL(raw, loc.origin + loc.pathname + loc.search);
847
+ } catch {
848
+ return;
849
+ }
850
+ e.preventDefault();
851
+ e.stopPropagation();
852
+ send(url.origin === loc.origin ? { type: "thecms:navigate", path: url.pathname + url.search + url.hash } : { type: "thecms:navigate", path: url.href, external: true });
853
+ return;
854
+ }
855
+ const block = closest(e.target, BLOCK);
856
+ const uid = block?.getAttribute("data-uid");
857
+ if (uid) send({ type: "thecms:pick", uid });
858
+ };
859
+ const onMessage = (e) => {
860
+ if (e.source !== parent) return;
861
+ const command = e.data;
862
+ if (command?.type !== "thecms:focus" || typeof command.uid !== "string" || !SAFE_UID.test(command.uid)) return;
863
+ const el = d.querySelector(`[data-cms-block][data-uid="${command.uid}"]`);
864
+ if (el) w.scrollBy?.({ top: rectOf(el).y - 24, behavior: "smooth" });
865
+ report();
866
+ };
867
+ d.addEventListener("click", onClick, true);
868
+ w.addEventListener("message", onMessage);
869
+ w.addEventListener("scroll", report, { passive: true });
870
+ w.addEventListener("resize", report);
871
+ const observers = [];
872
+ if (env.MutationObserver) {
873
+ const mo = new env.MutationObserver(report);
874
+ mo.observe(d.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
875
+ observers.push(mo);
876
+ }
877
+ if (env.ResizeObserver) {
878
+ const ro = new env.ResizeObserver(report);
879
+ ro.observe(d.documentElement);
880
+ observers.push(ro);
881
+ }
882
+ return () => {
883
+ d.removeEventListener("click", onClick, true);
884
+ w.removeEventListener("message", onMessage);
885
+ w.removeEventListener("scroll", report);
886
+ w.removeEventListener("resize", report);
887
+ for (const o of observers) o.disconnect();
888
+ };
889
+ }
890
+
891
+ // src/rss.ts
892
+ var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
893
+ function rss(records, channel) {
894
+ const items = records.map((r) => {
895
+ const i = channel.item(r);
896
+ const date = i.pubDate ? new Date(i.pubDate).toUTCString() : null;
897
+ return [
898
+ "<item>",
899
+ `<title>${esc(i.title)}</title>`,
900
+ `<link>${esc(i.link)}</link>`,
901
+ i.description ? `<description>${esc(i.description)}</description>` : "",
902
+ date ? `<pubDate>${date}</pubDate>` : "",
903
+ `<guid isPermaLink="${i.guid ? "false" : "true"}">${esc(i.guid ?? i.link)}</guid>`,
904
+ "</item>"
905
+ ].join("");
906
+ });
907
+ return `<?xml version="1.0" encoding="UTF-8"?>
908
+ <rss version="2.0"><channel><title>${esc(channel.title)}</title><link>${esc(channel.link)}</link><description>${esc(channel.description ?? channel.title)}</description>` + items.join("") + `</channel></rss>`;
909
+ }
910
+
911
+ // src/structured.ts
912
+ function jsonLdText(value) {
913
+ if (!value) return null;
914
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
915
+ }
916
+ export {
917
+ CmsError,
918
+ FRAME_HEADER,
919
+ LIST_PARAM,
920
+ PLATFORM_API,
921
+ PREVIEW_COOKIE,
922
+ PREVIEW_PARAM,
923
+ SDK_VERSION,
924
+ SITE_HEADER,
925
+ SITE_PROTOCOL,
926
+ UNKNOWN_VISITOR,
927
+ UNKNOWN_VISITOR_HEADER,
928
+ createPkce,
929
+ createSdk,
930
+ editorBridge,
931
+ imageFor,
932
+ jsonLdText,
933
+ markFrameRequests,
934
+ newVisitorId,
935
+ pkceChallenge,
936
+ platformUrl,
937
+ previewCookie,
938
+ previewEntry,
939
+ previewEntryUrl,
940
+ previewRequestAllowed,
941
+ readPreviewCookie,
942
+ rss,
943
+ siteHeader
944
+ };