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