@opencloudcms/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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +337 -2
  3. package/dist/cjs/actions/runner.js +434 -0
  4. package/dist/cjs/core/account.js +22 -0
  5. package/dist/cjs/core/actions.js +56 -0
  6. package/dist/cjs/core/auth.js +73 -0
  7. package/dist/cjs/core/client.js +160 -0
  8. package/dist/cjs/core/content.js +89 -0
  9. package/dist/cjs/core/default-client.js +27 -0
  10. package/dist/cjs/core/errors.js +53 -0
  11. package/dist/cjs/core/typed.js +22 -0
  12. package/dist/cjs/core/types.js +2 -0
  13. package/dist/cjs/core/utils.js +64 -0
  14. package/dist/cjs/index.js +37 -0
  15. package/dist/cjs/next/loopback.js +12 -0
  16. package/dist/cjs/next/server.js +99 -0
  17. package/dist/cjs/next/stubs.js +10 -0
  18. package/dist/cjs/package.json +1 -0
  19. package/dist/cjs/react/provider.js +162 -0
  20. package/dist/cjs/react/stubs.js +13 -0
  21. package/dist/cjs/server.js +38 -0
  22. package/dist/esm/actions/runner.d.ts +92 -0
  23. package/dist/esm/actions/runner.js +428 -0
  24. package/dist/esm/core/account.d.ts +20 -0
  25. package/dist/esm/core/account.js +19 -0
  26. package/dist/esm/core/actions.d.ts +81 -0
  27. package/dist/esm/core/actions.js +51 -0
  28. package/dist/esm/core/auth.d.ts +61 -0
  29. package/dist/esm/core/auth.js +69 -0
  30. package/dist/esm/core/client.d.ts +2 -0
  31. package/dist/esm/core/client.js +157 -0
  32. package/dist/esm/core/content.d.ts +5 -0
  33. package/dist/esm/core/content.js +85 -0
  34. package/dist/esm/core/default-client.d.ts +9 -0
  35. package/dist/esm/core/default-client.js +23 -0
  36. package/dist/esm/core/errors.d.ts +13 -0
  37. package/dist/esm/core/errors.js +47 -0
  38. package/dist/esm/core/typed.d.ts +31 -0
  39. package/dist/esm/core/typed.js +19 -0
  40. package/dist/esm/core/types.d.ts +90 -0
  41. package/dist/esm/core/types.js +1 -0
  42. package/dist/esm/core/utils.d.ts +27 -0
  43. package/dist/esm/core/utils.js +56 -0
  44. package/dist/esm/index.d.ts +20 -0
  45. package/dist/esm/index.js +12 -0
  46. package/dist/esm/next/loopback.d.ts +6 -0
  47. package/dist/esm/next/loopback.js +9 -0
  48. package/dist/esm/next/server.d.ts +19 -0
  49. package/dist/esm/next/server.js +60 -0
  50. package/dist/esm/next/stubs.d.ts +5 -0
  51. package/dist/esm/next/stubs.js +7 -0
  52. package/dist/esm/package.json +1 -0
  53. package/dist/esm/react/provider.d.ts +38 -0
  54. package/dist/esm/react/provider.js +153 -0
  55. package/dist/esm/react/stubs.d.ts +6 -0
  56. package/dist/esm/react/stubs.js +10 -0
  57. package/dist/esm/server.d.ts +21 -0
  58. package/dist/esm/server.js +13 -0
  59. package/package.json +61 -3
@@ -0,0 +1,428 @@
1
+ // The browser half of page actions (page-actions goals 7–9): one runner for buttons, forms and `useAction`.
2
+ // No React here: `core/blocks` triggers and the provider's hooks both delegate to an `ActionRunner`.
3
+ import { safeRedirectTarget } from '../core/auth.js';
4
+ import { ApiError, errorMessage, isApiError } from '../core/errors.js';
5
+ import { newRequestId } from '../core/actions.js';
6
+ import { safeReturnTo } from '../core/utils.js';
7
+ /** DOM event dispatched (bubbling) on the trigger for every phase; on `document` for runs without a trigger. */
8
+ export const ACTION_EVENT = 'opencloudcms:action';
9
+ export const BUILTIN_ACTIONS = ['sign-in', 'sign-out', 'navigate-back'];
10
+ const BUILTIN = new Set(BUILTIN_ACTIONS);
11
+ /** Triggers with a run in flight, shared by every runner: a double click or double submit is ignored. */
12
+ const busy = new WeakSet();
13
+ const SUCCESS_TEXT = { 'en-US': 'Sent successfully.', 'vi-VN': 'Đã gửi thành công.' };
14
+ const PREVIEW_TEXT = { 'en-US': 'Actions are disabled in preview', 'vi-VN': 'Hành động bị tắt khi xem trước' };
15
+ /** Built-ins that only navigate in the browser: harmless in a draft preview. */
16
+ const PREVIEW_SAFE_BUILTINS = new Set(['sign-in', 'navigate-back']);
17
+ const isVi = (locale) => !!locale && /^vi(\b|[-_])/i.test(locale);
18
+ const hasDom = () => typeof document !== 'undefined' && !!document;
19
+ const currentPath = () => typeof location !== 'undefined' && location ? `${location.pathname}${location.search ?? ''}` : '/';
20
+ export class ActionRunner {
21
+ o;
22
+ overrides = [];
23
+ /** Holders of runner-level draft preview (`setPreview`): preview is on while any holds it. */
24
+ previewHolders = new Set();
25
+ constructor(o) {
26
+ this.o = o;
27
+ }
28
+ /** Hooks of `name` from the current `actions` (the last definition wins). */
29
+ hooksOf(name) {
30
+ const list = this.o.actions ?? [];
31
+ for (let i = list.length - 1; i >= 0; i--)
32
+ if (list[i]?.name === name)
33
+ return list[i].hooks ?? {};
34
+ return {};
35
+ }
36
+ /** Layer UI handlers over the constructor's adapter (e.g. the page's overlay store). Returns an undo. */
37
+ setUi(ui) {
38
+ this.overrides = [...this.overrides, ui];
39
+ return () => {
40
+ this.overrides = this.overrides.filter((x) => x !== ui);
41
+ };
42
+ }
43
+ /**
44
+ * Runner-level draft preview (page-actions goal 11): while on, every run is a preview run, also `useAction` in custom
45
+ * code that never passes `preview`. Held per `key` (default: the runner): on while any key holds it, idempotent per
46
+ * key. Returns an undo that releases `key`. `core/blocks`' `ActionScope` holds it on a draft preview page.
47
+ */
48
+ setPreview(on, key = this) {
49
+ if (on)
50
+ this.previewHolders.add(key);
51
+ else
52
+ this.previewHolders.delete(key);
53
+ return () => {
54
+ this.previewHolders.delete(key);
55
+ };
56
+ }
57
+ isPreview() {
58
+ return this.previewHolders.size > 0;
59
+ }
60
+ /** Runs the whole lifecycle (goal 8). Never throws; `{ ok: false }` without `error` means ignored or cancelled. */
61
+ async run(trigger, input) {
62
+ if (trigger) {
63
+ if (busy.has(trigger))
64
+ return { ok: false };
65
+ busy.add(trigger);
66
+ }
67
+ const name = input.name;
68
+ const target = trigger ?? (hasDom() ? document : null);
69
+ const emit = (phase, extra = {}) => {
70
+ if (!target || typeof CustomEvent !== 'function')
71
+ return;
72
+ const detail = { name, phase, ...extra };
73
+ target.dispatchEvent(new CustomEvent(ACTION_EVENT, { bubbles: true, detail }));
74
+ };
75
+ const form = input.form ?? null;
76
+ const ctx = { name, form, phase: 'before' };
77
+ const ui = this.makeUi(ctx);
78
+ const hooks = this.hooksOf(name);
79
+ let outcome = { ok: false };
80
+ let settled = { ok: false };
81
+ let restore = null;
82
+ try {
83
+ emit('trigger');
84
+ if (form)
85
+ clearFieldErrors(form);
86
+ let req = { id: input.id ?? newRequestId(), name, params: input.params ?? {} };
87
+ if (input.input !== undefined)
88
+ req.input = input.input;
89
+ if (input.page)
90
+ req.page = input.page;
91
+ // Read before any await: a run started while the page is in preview stays a preview run.
92
+ const preview = input.preview === true || this.isPreview();
93
+ if (preview && !(await this.previewSafe(name))) {
94
+ ui.toast(isVi(this.o.client.options.locale) ? PREVIEW_TEXT['vi-VN'] : PREVIEW_TEXT['en-US'], 'info');
95
+ settled = { ok: false, code: 'preview_disabled' };
96
+ return outcome;
97
+ }
98
+ if (!BUILTIN.has(name) && (await this.signedOutButRequired(name))) {
99
+ this.toSignIn();
100
+ const error = new ApiError(401, 'unauthenticated', 'Sign in to continue');
101
+ outcome = { ok: false, error };
102
+ settled = { ok: false, code: error.code };
103
+ return outcome;
104
+ }
105
+ if (hooks.beforeRun) {
106
+ const next = await hooks.beforeRun(req, ui);
107
+ if (next === false) {
108
+ settled = { ok: false, code: 'cancelled' };
109
+ return outcome;
110
+ }
111
+ if (next && typeof next === 'object') {
112
+ req = { ...next, name, id: typeof next.id === 'string' && next.id ? next.id : req.id, params: next.params ?? {} };
113
+ }
114
+ }
115
+ restore = markPending(trigger, form);
116
+ emit('pending');
117
+ let result;
118
+ let error;
119
+ try {
120
+ result = await this.execute(req);
121
+ }
122
+ catch (e) {
123
+ error = isApiError(e) ? e : new ApiError(0, 'action_failed', e instanceof Error ? e.message : String(e));
124
+ }
125
+ if (error) {
126
+ outcome = { ok: false, error };
127
+ settled = { ok: false, code: error.code };
128
+ emit('error', settled);
129
+ if (error.status === 401) {
130
+ // Session expired between page load and click: sign in again, back to this page. No toast, no hook.
131
+ this.toSignIn(error.details?.signIn);
132
+ return outcome;
133
+ }
134
+ ctx.phase = 'error';
135
+ ctx.error = error;
136
+ await report(name, () => (hooks.onError ? hooks.onError(error, ui) : ui.defaultBehaviour()));
137
+ }
138
+ else {
139
+ outcome = { ok: true, result };
140
+ settled = { ok: true };
141
+ emit('success', settled);
142
+ ctx.phase = 'success';
143
+ ctx.result = result;
144
+ await report(name, () => (hooks.onSuccess ? hooks.onSuccess(result, ui) : ui.defaultBehaviour()));
145
+ }
146
+ return outcome;
147
+ }
148
+ catch (e) {
149
+ // A throwing beforeRun (or anything unexpected before the call): logged, the run ends.
150
+ console.error(`[opencloudcms] action "${name}" failed:`, e);
151
+ const error = isApiError(e) ? e : new ApiError(0, 'action_failed', e instanceof Error ? e.message : String(e));
152
+ outcome = { ok: false, error };
153
+ settled = { ok: false, code: error.code };
154
+ emit('error', settled);
155
+ return outcome;
156
+ }
157
+ finally {
158
+ restore?.();
159
+ if (trigger)
160
+ busy.delete(trigger);
161
+ emit('settled', settled);
162
+ }
163
+ }
164
+ async execute(req) {
165
+ const { client } = this.o;
166
+ switch (req.name) {
167
+ case 'sign-in':
168
+ client.auth.signIn(currentPath());
169
+ return null;
170
+ case 'sign-out': {
171
+ const out = await client.auth.signOut({ navigate: false });
172
+ await report('sign-out', () => this.o.onAuthChange());
173
+ return out;
174
+ }
175
+ case 'navigate-back':
176
+ if (typeof history !== 'undefined' && history)
177
+ history.back();
178
+ return null;
179
+ default:
180
+ return client.actions.run(req.name, { id: req.id, params: req.params, input: req.input, page: req.page });
181
+ }
182
+ }
183
+ /** Draft preview: whether `name` may run for real. An unreadable manifest blocks it (fail closed). */
184
+ async previewSafe(name) {
185
+ if (PREVIEW_SAFE_BUILTINS.has(name))
186
+ return true;
187
+ if (BUILTIN.has(name))
188
+ return false;
189
+ try {
190
+ const m = await this.o.client.actions.manifest();
191
+ return m?.actions?.find((a) => a.name === name)?.previewSafe === true;
192
+ }
193
+ catch {
194
+ return false;
195
+ }
196
+ }
197
+ /** True only when the manifest says `requireCustomer` and the customer is known to be signed out. */
198
+ async signedOutButRequired(name) {
199
+ let required = false;
200
+ try {
201
+ const m = await this.o.client.actions.manifest();
202
+ required = !!m?.actions?.find((a) => a.name === name)?.requireCustomer;
203
+ }
204
+ catch {
205
+ return false; // manifest unavailable: the server's 401 still sends the customer to sign in
206
+ }
207
+ if (!required)
208
+ return false;
209
+ try {
210
+ return (await this.o.getCustomer()) === null;
211
+ }
212
+ catch {
213
+ return false;
214
+ }
215
+ }
216
+ /**
217
+ * The page's `sign-in` overlay when it has one (and an overlay handler), else `<path>?returnTo=<current path>` where
218
+ * `path` is the server's `signIn` (its configured loginPath, from a 401) when it is a safe local path, else `signInPath`.
219
+ */
220
+ toSignIn(serverPath) {
221
+ const open = this.adapter('openOverlay');
222
+ if (open && hasDom() && document.querySelector('dialog[data-ocms-overlay="sign-in"]')) {
223
+ open('sign-in');
224
+ return;
225
+ }
226
+ const fromServer = typeof serverPath === 'string' && serverPath && safeReturnTo(serverPath) === serverPath ? serverPath : '';
227
+ const base = fromServer || this.o.signInPath || '/account/login';
228
+ const sep = base.includes('?') ? '&' : '?';
229
+ this.go(`${base}${sep}returnTo=${encodeURIComponent(safeReturnTo(currentPath()))}`);
230
+ }
231
+ /** The UiAdapter's `navigate`, else `location.assign`. `to` must already be safe. */
232
+ go(to) {
233
+ const nav = this.adapter('navigate');
234
+ if (nav)
235
+ nav(to);
236
+ else if (typeof location !== 'undefined' && location)
237
+ location.assign(to);
238
+ }
239
+ adapter(key) {
240
+ for (let i = this.overrides.length - 1; i >= 0; i--) {
241
+ const fn = this.overrides[i][key];
242
+ if (fn)
243
+ return fn;
244
+ }
245
+ return this.o.ui?.[key];
246
+ }
247
+ makeUi(ctx) {
248
+ const { client } = this.o;
249
+ const locale = client.options.locale;
250
+ const ui = {
251
+ navigate: (path) => this.go(safeRedirectTarget(path)),
252
+ toast: (message, tone = 'info') => (this.adapter('toast') ?? domToast)(message, tone),
253
+ confirm: async (message) => {
254
+ const own = this.adapter('confirm');
255
+ if (own)
256
+ return !!(await own(message));
257
+ return typeof window !== 'undefined' && typeof window.confirm === 'function' ? !!window.confirm(message) : false;
258
+ },
259
+ openOverlay: (n) => this.adapter('openOverlay')?.(n),
260
+ closeOverlay: (n) => this.adapter('closeOverlay')?.(n),
261
+ resetForm: () => {
262
+ if (!ctx.form)
263
+ return;
264
+ ctx.form.reset();
265
+ clearFieldErrors(ctx.form);
266
+ },
267
+ refresh: () => {
268
+ const own = this.adapter('refresh');
269
+ if (own)
270
+ own();
271
+ else if (typeof location !== 'undefined' && location)
272
+ location.reload();
273
+ },
274
+ setFieldErrors: (issues) => {
275
+ if (ctx.form)
276
+ setFieldErrors(ctx.form, issues);
277
+ },
278
+ defaultBehaviour: () => {
279
+ if (ctx.phase === 'success') {
280
+ if (ctx.name === 'sign-out')
281
+ ui.navigate('/');
282
+ else if (ctx.form && !BUILTIN.has(ctx.name)) {
283
+ if (ctx.form.getAttribute('data-reset-on-success') !== 'false')
284
+ ui.resetForm();
285
+ ui.toast(isVi(locale) ? SUCCESS_TEXT['vi-VN'] : SUCCESS_TEXT['en-US'], 'success');
286
+ }
287
+ }
288
+ else if (ctx.phase === 'error' && ctx.error) {
289
+ if (ctx.form && ctx.error.issues)
290
+ ui.setFieldErrors(ctx.error.issues);
291
+ ui.toast(errorMessage(ctx.error, locale, client.options.messages), 'error');
292
+ }
293
+ },
294
+ };
295
+ return ui;
296
+ }
297
+ }
298
+ /** Runs a client hook; a throw is logged, never propagated (the run still settles). */
299
+ async function report(name, fn) {
300
+ try {
301
+ await fn();
302
+ }
303
+ catch (e) {
304
+ console.error(`[opencloudcms] action "${name}" hook failed:`, e);
305
+ }
306
+ }
307
+ function markPending(trigger, form) {
308
+ const undo = [];
309
+ const busyOn = (el) => {
310
+ if (el.getAttribute('aria-busy') === 'true')
311
+ return;
312
+ el.setAttribute('aria-busy', 'true');
313
+ undo.push(() => el.removeAttribute('aria-busy'));
314
+ };
315
+ const disable = (el) => {
316
+ const d = el;
317
+ if (typeof d.disabled !== 'boolean' || d.disabled)
318
+ return;
319
+ d.disabled = true;
320
+ undo.push(() => {
321
+ d.disabled = false;
322
+ });
323
+ };
324
+ if (trigger) {
325
+ busyOn(trigger);
326
+ disable(trigger);
327
+ }
328
+ if (form) {
329
+ busyOn(form);
330
+ form.querySelectorAll('button[type="submit"], button:not([type]), input[type="submit"]').forEach(disable);
331
+ }
332
+ return () => undo.reverse().forEach((f) => f());
333
+ }
334
+ // ── Field errors ─────────────────────────────────────────────────────────────────────────────────────────────────
335
+ const ERR_FOR = 'data-ocms-error-for';
336
+ const GENERATED = 'data-ocms-generated';
337
+ const MARKED = 'data-ocms-invalid';
338
+ let errSeq = 0;
339
+ function controlsNamed(form, name) {
340
+ return Array.from(form.elements).filter((el) => el.name === name);
341
+ }
342
+ function messageSlot(form, name) {
343
+ return Array.from(form.querySelectorAll(`[${ERR_FOR}]`)).find((el) => el.getAttribute(ERR_FOR) === name) ?? null;
344
+ }
345
+ /** Undoes `setFieldErrors` (only what the runner set: an author's own `aria-invalid` is left alone). */
346
+ export function clearFieldErrors(form) {
347
+ form.querySelectorAll(`[${MARKED}]`).forEach((el) => {
348
+ const id = el.getAttribute(MARKED) ?? '';
349
+ el.removeAttribute(MARKED);
350
+ el.removeAttribute('aria-invalid');
351
+ const rest = (el.getAttribute('aria-describedby') ?? '').split(/\s+/).filter((t) => t && t !== id);
352
+ if (rest.length)
353
+ el.setAttribute('aria-describedby', rest.join(' '));
354
+ else
355
+ el.removeAttribute('aria-describedby');
356
+ });
357
+ form.querySelectorAll(`[${ERR_FOR}]`).forEach((el) => {
358
+ if (el.hasAttribute(GENERATED))
359
+ el.remove();
360
+ else
361
+ el.textContent = '';
362
+ });
363
+ }
364
+ /** `['input', <name>, ...]` issues → `aria-invalid` on the controls named `<name>` and the first message in `[data-ocms-error-for]`. */
365
+ export function setFieldErrors(form, issues) {
366
+ clearFieldErrors(form);
367
+ const byName = new Map();
368
+ for (const i of issues ?? []) {
369
+ if (!Array.isArray(i?.path) || i.path[0] !== 'input' || i.path.length < 2)
370
+ continue;
371
+ const field = String(i.path[1]);
372
+ if (!byName.has(field))
373
+ byName.set(field, String(i.message ?? ''));
374
+ }
375
+ for (const [field, message] of byName) {
376
+ const controls = controlsNamed(form, field);
377
+ if (!controls.length)
378
+ continue;
379
+ let slot = messageSlot(form, field);
380
+ if (!slot) {
381
+ slot = document.createElement('span');
382
+ slot.className = 'ocms-field-error';
383
+ slot.setAttribute(ERR_FOR, field);
384
+ slot.setAttribute(GENERATED, '');
385
+ controls[controls.length - 1].after(slot);
386
+ }
387
+ if (!slot.id)
388
+ slot.id = `ocms-err-${++errSeq}`;
389
+ slot.textContent = message;
390
+ for (const c of controls) {
391
+ c.setAttribute('aria-invalid', 'true');
392
+ c.setAttribute(MARKED, slot.id);
393
+ const ids = (c.getAttribute('aria-describedby') ?? '').split(/\s+/).filter(Boolean);
394
+ if (!ids.includes(slot.id))
395
+ c.setAttribute('aria-describedby', [...ids, slot.id].join(' '));
396
+ }
397
+ }
398
+ }
399
+ // ── Default toast ────────────────────────────────────────────────────────────────────────────────────────────────
400
+ const TOAST_CSS = [
401
+ ':where(.ocms-toasts){position:fixed;right:1rem;bottom:1rem;z-index:2147483000;display:flex;flex-direction:column;gap:.5rem;max-width:min(24rem,calc(100vw - 2rem))}',
402
+ ':where(.ocms-toast){padding:.75rem 1rem;border-radius:.5rem;background:#1f2937;color:#fff;box-shadow:0 4px 16px rgba(0,0,0,.2)}',
403
+ ':where(.ocms-toast[data-tone="error"]){background:#b91c1c}',
404
+ ':where(.ocms-toast[data-tone="success"]){background:#15803d}',
405
+ ].join('');
406
+ function domToast(message, tone = 'info') {
407
+ if (!hasDom() || !document.body)
408
+ return;
409
+ if (!document.querySelector('style[data-ocms-toast]')) {
410
+ const style = document.createElement('style');
411
+ style.setAttribute('data-ocms-toast', '');
412
+ style.textContent = TOAST_CSS; // `:where()`: zero specificity, any theme rule wins
413
+ document.head?.append(style);
414
+ }
415
+ let box = document.querySelector('.ocms-toasts');
416
+ if (!box) {
417
+ box = document.createElement('div');
418
+ box.className = 'ocms-toasts';
419
+ document.body.append(box);
420
+ }
421
+ const t = document.createElement('div');
422
+ t.className = 'ocms-toast';
423
+ t.setAttribute('data-tone', tone);
424
+ t.setAttribute('role', tone === 'error' ? 'alert' : 'status');
425
+ t.textContent = message;
426
+ box.append(t);
427
+ setTimeout(() => t.remove(), 5000);
428
+ }
@@ -0,0 +1,20 @@
1
+ import type { Customer } from './auth.js';
2
+ import type { Client } from './types.js';
3
+ export interface AccountClient {
4
+ update(o: {
5
+ name: string | null;
6
+ }): Promise<Customer>;
7
+ password: {
8
+ /** For an account without a password yet. */
9
+ set(newPassword: string): Promise<void>;
10
+ change(currentPassword: string, newPassword: string): Promise<void>;
11
+ };
12
+ identifiers: {
13
+ add(identifier: string): Promise<{
14
+ resendAfterSec: number;
15
+ }>;
16
+ verify(identifier: string, code: string): Promise<Customer>;
17
+ remove(id: string): Promise<Customer>;
18
+ };
19
+ }
20
+ export declare function createAccount(client: Client): AccountClient;
@@ -0,0 +1,19 @@
1
+ const BASE = '/api/customer/account';
2
+ export function createAccount(client) {
3
+ return {
4
+ update: (o) => client.request('PATCH', BASE, { body: { name: o.name } }),
5
+ password: {
6
+ async set(newPassword) {
7
+ await client.request('POST', `${BASE}/password`, { body: { newPassword } });
8
+ },
9
+ async change(currentPassword, newPassword) {
10
+ await client.request('POST', `${BASE}/password`, { body: { currentPassword, newPassword } });
11
+ },
12
+ },
13
+ identifiers: {
14
+ add: (identifier) => client.request('POST', `${BASE}/identifiers`, { body: { identifier } }),
15
+ verify: (identifier, code) => client.request('POST', `${BASE}/identifiers/verify`, { body: { identifier, code } }),
16
+ remove: (id) => client.request('DELETE', `${BASE}/identifiers/${encodeURIComponent(id)}`),
17
+ },
18
+ };
19
+ }
@@ -0,0 +1,81 @@
1
+ import type { ApiError } from './errors.js';
2
+ import type { ApiIssue, Client } from './types.js';
3
+ /** A page action call as the runner builds it (page-actions goal 8 step 2). `id` is a fresh UUID per trigger. */
4
+ export interface ActionRequest {
5
+ id: string;
6
+ name: string;
7
+ params: Record<string, unknown>;
8
+ input?: Record<string, unknown>;
9
+ page?: {
10
+ documentId: string;
11
+ locale: string;
12
+ };
13
+ }
14
+ /**
15
+ * `GET /api/actions/manifest`. Structurally compatible with `ActionManifest` of `@opencloudcms/schema` (copied: the
16
+ * SDK has no schema dependency). Param descriptors are kept loose: the runner only reads `name` and `requireCustomer`.
17
+ */
18
+ export interface ActionManifest {
19
+ actions: {
20
+ name: string;
21
+ label?: unknown;
22
+ params: ({
23
+ name: string;
24
+ kind: string;
25
+ required: boolean;
26
+ } & Record<string, unknown>)[];
27
+ hasInput?: boolean;
28
+ requireCustomer?: boolean;
29
+ previewSafe?: boolean;
30
+ }[];
31
+ }
32
+ export interface RunActionOptions {
33
+ params?: Record<string, unknown>;
34
+ input?: Record<string, unknown>;
35
+ page?: {
36
+ documentId: string;
37
+ locale: string;
38
+ };
39
+ /** Default: a new UUID. Pass the same id to retry one logical call (the server sees it as `ctx.requestId`). */
40
+ id?: string;
41
+ }
42
+ export interface ActionsClient {
43
+ /** `POST /api/actions/:name` → the action's `result`. Throws `ApiError` on any error answer. */
44
+ run<T = unknown>(name: string, o?: RunActionOptions): Promise<T>;
45
+ /** The public action manifest, cached 60 s per client. */
46
+ manifest(): Promise<ActionManifest>;
47
+ }
48
+ /** What hooks and the runner's default behaviour use to act on the page. */
49
+ export interface ActionUi {
50
+ /** Same-site navigation: a local path, or an absolute URL on this origin; anything else goes to `/`. */
51
+ navigate(path: string): void;
52
+ toast(message: string, tone?: 'success' | 'error' | 'info'): void;
53
+ confirm(message: string): Promise<boolean>;
54
+ openOverlay(name: string): void;
55
+ closeOverlay(name?: string): void;
56
+ /** Resets the triggering form (and clears its field errors); no-op for buttons. */
57
+ resetForm(): void;
58
+ /** Reloads the page data (default: `location.reload()`; a Next app can pass `router.refresh`). */
59
+ refresh(): void;
60
+ /** Shows `['input', <name>]` issues next to the matching controls of the triggering form; clears earlier ones. */
61
+ setFieldErrors(issues: ApiIssue[]): void;
62
+ /** Runs what would have run without the hook (in `onSuccess`: the success default; in `onError`: the error default). */
63
+ defaultBehaviour(): void;
64
+ }
65
+ export interface ActionClientHooks<R = any> {
66
+ /** Change the request (return it) or cancel (return `false`). Returning nothing keeps it. */
67
+ beforeRun?(req: ActionRequest, ui: ActionUi): ActionRequest | false | void | Promise<ActionRequest | false | void>;
68
+ /** Replaces the default success behaviour. */
69
+ onSuccess?(result: R, ui: ActionUi): void | Promise<void>;
70
+ /** Replaces the default error behaviour (call `ui.defaultBehaviour()` to keep it). */
71
+ onError?(err: ApiError, ui: ActionUi): void | Promise<void>;
72
+ }
73
+ /** The browser half of an action, mounted with `<OpenCloudCmsProvider actions={[...]}>`. */
74
+ export interface ActionClientDefinition {
75
+ readonly name: string;
76
+ readonly hooks: ActionClientHooks;
77
+ }
78
+ export declare function defineActionClient<R = any>(name: string, hooks: ActionClientHooks<R>): ActionClientDefinition;
79
+ /** RFC 4122 v4. `crypto.randomUUID` exists only in secure contexts, so fall back to `getRandomValues`. */
80
+ export declare function newRequestId(): string;
81
+ export declare function createActions(client: Client): ActionsClient;
@@ -0,0 +1,51 @@
1
+ export function defineActionClient(name, hooks) {
2
+ if (typeof name !== 'string' || !name)
3
+ throw new TypeError('defineActionClient: name is required');
4
+ return Object.freeze({ name, hooks: Object.freeze({ ...hooks }) });
5
+ }
6
+ const hex = (b) => b.toString(16).padStart(2, '0');
7
+ /** RFC 4122 v4. `crypto.randomUUID` exists only in secure contexts, so fall back to `getRandomValues`. */
8
+ export function newRequestId() {
9
+ const c = globalThis.crypto;
10
+ if (typeof c?.randomUUID === 'function')
11
+ return c.randomUUID();
12
+ const b = new Uint8Array(16);
13
+ if (typeof c?.getRandomValues === 'function')
14
+ c.getRandomValues(b);
15
+ else
16
+ for (let i = 0; i < 16; i++)
17
+ b[i] = Math.floor(Math.random() * 256);
18
+ b[6] = (b[6] & 0x0f) | 0x40;
19
+ b[8] = (b[8] & 0x3f) | 0x80;
20
+ const h = Array.from(b, hex).join('');
21
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
22
+ }
23
+ const MANIFEST_TTL_MS = 60_000;
24
+ export function createActions(client) {
25
+ let cached = null;
26
+ return {
27
+ async run(name, o = {}) {
28
+ const body = { id: o.id ?? newRequestId(), params: o.params ?? {} };
29
+ if (o.input !== undefined)
30
+ body.input = o.input;
31
+ if (o.page)
32
+ body.page = o.page;
33
+ const res = await client.request('POST', `/api/actions/${encodeURIComponent(name)}`, { body });
34
+ return res?.result;
35
+ },
36
+ manifest() {
37
+ const now = Date.now();
38
+ if (cached && now - cached.at < MANIFEST_TTL_MS)
39
+ return cached.value;
40
+ const value = client.request('GET', '/api/actions/manifest');
41
+ const entry = { at: now, value };
42
+ cached = entry;
43
+ // A failed fetch is not cached.
44
+ value.catch(() => {
45
+ if (cached === entry)
46
+ cached = null;
47
+ });
48
+ return value;
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,61 @@
1
+ import type { Client } from './types.js';
2
+ export interface Customer {
3
+ id: string;
4
+ name: string | null;
5
+ identifiers: {
6
+ id: string;
7
+ kind: 'email' | 'phone';
8
+ value: string;
9
+ verified: boolean;
10
+ }[];
11
+ }
12
+ type MethodFlags = {
13
+ otp: boolean;
14
+ password: boolean;
15
+ };
16
+ export interface SignInMethods {
17
+ email: MethodFlags | null;
18
+ phone: MethodFlags | null;
19
+ }
20
+ export interface AuthClient {
21
+ /** The signed-in customer; `null` when not signed in (401). */
22
+ me(): Promise<Customer | null>;
23
+ methods(): Promise<SignInMethods>;
24
+ /** Cookie mode: navigates to the BFF login. Bearer mode: throws `unsupported_in_bearer_mode`. */
25
+ signIn(returnTo?: string): void;
26
+ signOut(o?: {
27
+ navigate?: boolean;
28
+ }): Promise<{
29
+ redirectTo: string;
30
+ }>;
31
+ otp: {
32
+ /** `{ redirectTo }` when the interaction has already ended (follow it with `followRedirect`). */
33
+ request(uid: string, identifier: string): Promise<{
34
+ resendAfterSec: number;
35
+ } | {
36
+ redirectTo: string;
37
+ }>;
38
+ verify(uid: string, identifier: string, code: string, name?: string): Promise<{
39
+ redirectTo: string;
40
+ }>;
41
+ };
42
+ password: {
43
+ signIn(uid: string, identifier: string, password: string): Promise<{
44
+ redirectTo: string;
45
+ }>;
46
+ };
47
+ passwordReset: {
48
+ request(identifier: string): Promise<{
49
+ resendAfterSec: number;
50
+ }>;
51
+ confirm(identifier: string, code: string, newPassword: string): Promise<void>;
52
+ };
53
+ /** Navigates to `redirectTo` when it is a path or on this origin; otherwise `/`. */
54
+ followRedirect(r: {
55
+ redirectTo: string;
56
+ }): void;
57
+ }
58
+ /** A same-site navigation target: a safe local path, or an absolute http(s) URL on this origin; else `/`. */
59
+ export declare function safeRedirectTarget(redirectTo: string): string;
60
+ export declare function createAuth(client: Client): AuthClient;
61
+ export {};