@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.
- package/LICENSE +21 -0
- package/README.md +337 -2
- package/dist/cjs/actions/runner.js +434 -0
- package/dist/cjs/core/account.js +22 -0
- package/dist/cjs/core/actions.js +56 -0
- package/dist/cjs/core/auth.js +73 -0
- package/dist/cjs/core/client.js +160 -0
- package/dist/cjs/core/content.js +89 -0
- package/dist/cjs/core/default-client.js +27 -0
- package/dist/cjs/core/errors.js +53 -0
- package/dist/cjs/core/typed.js +22 -0
- package/dist/cjs/core/types.js +2 -0
- package/dist/cjs/core/utils.js +64 -0
- package/dist/cjs/index.js +37 -0
- package/dist/cjs/next/loopback.js +12 -0
- package/dist/cjs/next/server.js +99 -0
- package/dist/cjs/next/stubs.js +10 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/react/provider.js +162 -0
- package/dist/cjs/react/stubs.js +13 -0
- package/dist/cjs/server.js +38 -0
- package/dist/esm/actions/runner.d.ts +92 -0
- package/dist/esm/actions/runner.js +428 -0
- package/dist/esm/core/account.d.ts +20 -0
- package/dist/esm/core/account.js +19 -0
- package/dist/esm/core/actions.d.ts +81 -0
- package/dist/esm/core/actions.js +51 -0
- package/dist/esm/core/auth.d.ts +61 -0
- package/dist/esm/core/auth.js +69 -0
- package/dist/esm/core/client.d.ts +2 -0
- package/dist/esm/core/client.js +157 -0
- package/dist/esm/core/content.d.ts +5 -0
- package/dist/esm/core/content.js +85 -0
- package/dist/esm/core/default-client.d.ts +9 -0
- package/dist/esm/core/default-client.js +23 -0
- package/dist/esm/core/errors.d.ts +13 -0
- package/dist/esm/core/errors.js +47 -0
- package/dist/esm/core/typed.d.ts +31 -0
- package/dist/esm/core/typed.js +19 -0
- package/dist/esm/core/types.d.ts +90 -0
- package/dist/esm/core/types.js +1 -0
- package/dist/esm/core/utils.d.ts +27 -0
- package/dist/esm/core/utils.js +56 -0
- package/dist/esm/index.d.ts +20 -0
- package/dist/esm/index.js +12 -0
- package/dist/esm/next/loopback.d.ts +6 -0
- package/dist/esm/next/loopback.js +9 -0
- package/dist/esm/next/server.d.ts +19 -0
- package/dist/esm/next/server.js +60 -0
- package/dist/esm/next/stubs.d.ts +5 -0
- package/dist/esm/next/stubs.js +7 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/react/provider.d.ts +38 -0
- package/dist/esm/react/provider.js +153 -0
- package/dist/esm/react/stubs.d.ts +6 -0
- package/dist/esm/react/stubs.js +10 -0
- package/dist/esm/server.d.ts +21 -0
- package/dist/esm/server.js +13 -0
- package/package.json +61 -3
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createClient = createClient;
|
|
4
|
+
const errors_js_1 = require("./errors.js");
|
|
5
|
+
const content_js_1 = require("./content.js");
|
|
6
|
+
const auth_js_1 = require("./auth.js");
|
|
7
|
+
const account_js_1 = require("./account.js");
|
|
8
|
+
const actions_js_1 = require("./actions.js");
|
|
9
|
+
/**
|
|
10
|
+
* Cookie mode: `same-origin` when `baseUrl` is the page origin (or empty). Another origin (or one that cannot be
|
|
11
|
+
* determined) gets `omit`: the SDK never sends cookies cross-origin; cross-origin storefronts use bearer mode.
|
|
12
|
+
*/
|
|
13
|
+
function credentialsFor(baseUrl) {
|
|
14
|
+
if (baseUrl === '')
|
|
15
|
+
return 'same-origin';
|
|
16
|
+
const here = typeof location !== 'undefined' && location ? location : undefined;
|
|
17
|
+
if (!here)
|
|
18
|
+
return 'omit';
|
|
19
|
+
try {
|
|
20
|
+
return new URL(baseUrl, here.href).origin === here.origin ? 'same-origin' : 'omit';
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return 'omit';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** `https://x`, `mailto:x` or `//host/x`: used as given, never prefixed with the base URL. */
|
|
27
|
+
const isAbsolute = (path) => /^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith('//');
|
|
28
|
+
function queryValue(key, v) {
|
|
29
|
+
if (v instanceof Date)
|
|
30
|
+
return v.toISOString();
|
|
31
|
+
if (typeof v === 'object' && v !== null)
|
|
32
|
+
throw new TypeError(`query value for ${key} must be a scalar or array`);
|
|
33
|
+
return String(v);
|
|
34
|
+
}
|
|
35
|
+
/** `path` (leading `/` ensured) with its own query merged with `query`; `locale` added on GET unless set (or `null`). */
|
|
36
|
+
function buildPath(path, query, locale) {
|
|
37
|
+
const p = isAbsolute(path) || path.startsWith('/') ? path : `/${path}`;
|
|
38
|
+
const at = p.indexOf('?');
|
|
39
|
+
const pathname = at < 0 ? p : p.slice(0, at);
|
|
40
|
+
const qs = new URLSearchParams(at < 0 ? '' : p.slice(at + 1));
|
|
41
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
42
|
+
if (v === undefined || v === null)
|
|
43
|
+
continue;
|
|
44
|
+
qs.append(k, Array.isArray(v) ? v.map((x) => queryValue(k, x)).join(',') : queryValue(k, v));
|
|
45
|
+
}
|
|
46
|
+
const suppressed = query !== undefined && Object.prototype.hasOwnProperty.call(query, 'locale') && query.locale === null;
|
|
47
|
+
if (locale && !suppressed && !qs.has('locale'))
|
|
48
|
+
qs.set('locale', locale);
|
|
49
|
+
// Keep `[ ] ,` readable (`filter[a][in]=x,y`); all are legal in a query string.
|
|
50
|
+
const s = qs.toString().replace(/%5B/gi, '[').replace(/%5D/gi, ']').replace(/%2C/gi, ',');
|
|
51
|
+
return s ? `${pathname}?${s}` : pathname;
|
|
52
|
+
}
|
|
53
|
+
async function readBody(res) {
|
|
54
|
+
if (res.status === 204)
|
|
55
|
+
return undefined;
|
|
56
|
+
const text = await res.text();
|
|
57
|
+
if (text === '')
|
|
58
|
+
return undefined;
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(text);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return text;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function toApiError(res, body) {
|
|
67
|
+
const error = typeof body === 'object' && body !== null ? body.error : undefined;
|
|
68
|
+
if (typeof error === 'object' && error !== null) {
|
|
69
|
+
const e = error;
|
|
70
|
+
const code = typeof e.code === 'string' && e.code ? e.code : `http_${res.status}`;
|
|
71
|
+
const message = typeof e.message === 'string' ? e.message : `${res.status} ${res.statusText}`.trim();
|
|
72
|
+
const issues = Array.isArray(e.issues) ? e.issues : undefined;
|
|
73
|
+
// A 401 from the actions endpoint carries the server's sign-in path next to `error`: expose it as `details.signIn`.
|
|
74
|
+
const signIn = body.signIn;
|
|
75
|
+
const details = typeof signIn === 'string' && !('signIn' in error) ? { ...error, signIn } : error;
|
|
76
|
+
return new errors_js_1.ApiError(res.status, code, message, issues, details);
|
|
77
|
+
}
|
|
78
|
+
return new errors_js_1.ApiError(res.status, `http_${res.status}`, `${res.status} ${res.statusText}`.trim());
|
|
79
|
+
}
|
|
80
|
+
function createClient(o = {}) {
|
|
81
|
+
const options = Object.freeze({
|
|
82
|
+
...o,
|
|
83
|
+
baseUrl: (o.baseUrl ?? '').replace(/\/+$/, ''),
|
|
84
|
+
auth: o.auth ?? 'cookie',
|
|
85
|
+
});
|
|
86
|
+
const doFetch = o.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
87
|
+
const credentials = options.auth === 'cookie' ? credentialsFor(options.baseUrl) : undefined;
|
|
88
|
+
/**
|
|
89
|
+
* Credentials and bearer tokens go only to the client's own origin. The final URL is always resolved the way a
|
|
90
|
+
* browser would (so `/\\evil.com` or `/\t/evil.com` count as another host) and its origin compared; fails closed.
|
|
91
|
+
*/
|
|
92
|
+
function toBaseOrigin(url) {
|
|
93
|
+
try {
|
|
94
|
+
const here = typeof location !== 'undefined' && location ? location.href : 'http://invalid.invalid/';
|
|
95
|
+
const base = new URL(options.baseUrl || '/', here);
|
|
96
|
+
return new URL(url, base).origin === base.origin;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async function request(method, path, r = {}) {
|
|
103
|
+
const abs = isAbsolute(path);
|
|
104
|
+
const url = `${abs ? '' : options.baseUrl}${buildPath(path, r.query, method === 'GET' && !abs ? options.locale : undefined)}`;
|
|
105
|
+
const headers = { accept: 'application/json' };
|
|
106
|
+
if (options.locale)
|
|
107
|
+
headers['accept-language'] = options.locale;
|
|
108
|
+
Object.assign(headers, lower(options.headers));
|
|
109
|
+
const own = toBaseOrigin(url);
|
|
110
|
+
if (own && options.auth === 'bearer' && options.getAccessToken) {
|
|
111
|
+
const token = await options.getAccessToken();
|
|
112
|
+
if (token)
|
|
113
|
+
headers.authorization = `Bearer ${token}`;
|
|
114
|
+
}
|
|
115
|
+
Object.assign(headers, lower(r.headers));
|
|
116
|
+
let body;
|
|
117
|
+
if (r.body !== undefined) {
|
|
118
|
+
body = JSON.stringify(r.body);
|
|
119
|
+
headers['content-type'] ??= 'application/json';
|
|
120
|
+
}
|
|
121
|
+
const init = { method, headers };
|
|
122
|
+
if (body !== undefined)
|
|
123
|
+
init.body = body;
|
|
124
|
+
if (credentials && own)
|
|
125
|
+
init.credentials = credentials;
|
|
126
|
+
if (r.signal)
|
|
127
|
+
init.signal = r.signal;
|
|
128
|
+
if (r.cache)
|
|
129
|
+
init.cache = r.cache;
|
|
130
|
+
if (r.next)
|
|
131
|
+
init.next = r.next;
|
|
132
|
+
let res;
|
|
133
|
+
let data;
|
|
134
|
+
try {
|
|
135
|
+
res = await doFetch(url, init);
|
|
136
|
+
data = await readBody(res);
|
|
137
|
+
}
|
|
138
|
+
catch (e) {
|
|
139
|
+
if (r.signal?.aborted || e?.name === 'AbortError')
|
|
140
|
+
throw e;
|
|
141
|
+
throw new errors_js_1.ApiError(0, 'network_error', e instanceof Error ? e.message : 'Network error');
|
|
142
|
+
}
|
|
143
|
+
if (!res.ok)
|
|
144
|
+
throw toApiError(res, data);
|
|
145
|
+
return data;
|
|
146
|
+
}
|
|
147
|
+
const client = { options, request };
|
|
148
|
+
client.content = (0, content_js_1.createContent)(client);
|
|
149
|
+
client.assets = (0, content_js_1.createAssets)(client);
|
|
150
|
+
client.auth = (0, auth_js_1.createAuth)(client);
|
|
151
|
+
client.account = (0, account_js_1.createAccount)(client);
|
|
152
|
+
client.actions = (0, actions_js_1.createActions)(client);
|
|
153
|
+
return client;
|
|
154
|
+
}
|
|
155
|
+
function lower(h) {
|
|
156
|
+
const out = {};
|
|
157
|
+
for (const [k, v] of Object.entries(h ?? {}))
|
|
158
|
+
out[k.toLowerCase()] = v;
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createContent = createContent;
|
|
4
|
+
exports.createAssets = createAssets;
|
|
5
|
+
const errors_js_1 = require("./errors.js");
|
|
6
|
+
const MAX_IDS = 100;
|
|
7
|
+
function listQuery(o, extra = {}) {
|
|
8
|
+
const q = {};
|
|
9
|
+
for (const [k, v] of Object.entries(o?.filter ?? {})) {
|
|
10
|
+
if (v === undefined || v === null)
|
|
11
|
+
continue;
|
|
12
|
+
if (typeof v === 'object')
|
|
13
|
+
q[`filter[${k}][in]`] = v.in;
|
|
14
|
+
else
|
|
15
|
+
q[`filter[${k}]`] = v;
|
|
16
|
+
}
|
|
17
|
+
for (const [k, v] of Object.entries(extra))
|
|
18
|
+
q[k] = v;
|
|
19
|
+
if (o?.sort !== undefined)
|
|
20
|
+
q.sort = o.sort;
|
|
21
|
+
if (o?.limit !== undefined)
|
|
22
|
+
q.limit = o.limit;
|
|
23
|
+
if (o?.offset !== undefined)
|
|
24
|
+
q.offset = o.offset;
|
|
25
|
+
if (o?.locale !== undefined)
|
|
26
|
+
q.locale = o.locale;
|
|
27
|
+
if (o?.fallback !== undefined)
|
|
28
|
+
q.fallback = o.fallback;
|
|
29
|
+
return q;
|
|
30
|
+
}
|
|
31
|
+
const apiPath = (apiId) => `/api/content/${encodeURIComponent(apiId)}`;
|
|
32
|
+
function createContent(client) {
|
|
33
|
+
async function list(apiId, o) {
|
|
34
|
+
const r = await client.request('GET', apiPath(apiId), { query: listQuery(o) });
|
|
35
|
+
return { data: r?.data ?? [], meta: r?.meta ?? {} };
|
|
36
|
+
}
|
|
37
|
+
async function get(apiId, documentId, o) {
|
|
38
|
+
try {
|
|
39
|
+
const r = await client.request('GET', `${apiPath(apiId)}/${encodeURIComponent(documentId)}`, {
|
|
40
|
+
query: { ...(o?.locale !== undefined ? { locale: o.locale } : {}), ...(o?.fallback !== undefined ? { fallback: o.fallback } : {}) },
|
|
41
|
+
});
|
|
42
|
+
return r?.data ?? null;
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
if ((0, errors_js_1.isApiError)(e) && e.status === 404)
|
|
46
|
+
return null;
|
|
47
|
+
throw e;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function bySlug(apiId, slug, o) {
|
|
51
|
+
const r = await list(apiId, { ...o, filter: { slug }, limit: 1 });
|
|
52
|
+
return r.data[0] ?? null;
|
|
53
|
+
}
|
|
54
|
+
async function byIds(apiId, ids, o) {
|
|
55
|
+
const unique = [...new Set(ids)];
|
|
56
|
+
const found = new Map();
|
|
57
|
+
for (let i = 0; i < unique.length; i += MAX_IDS) {
|
|
58
|
+
const r = await list(apiId, { ...o, filter: { documentId: { in: unique.slice(i, i + MAX_IDS) } }, limit: MAX_IDS });
|
|
59
|
+
for (const e of r.data)
|
|
60
|
+
found.set(e.documentId, e);
|
|
61
|
+
}
|
|
62
|
+
return unique.flatMap((id) => (found.has(id) ? [found.get(id)] : []));
|
|
63
|
+
}
|
|
64
|
+
return { list, get, bySlug, byIds };
|
|
65
|
+
}
|
|
66
|
+
/** Public delivery assets: `GET /api/content/assets?ids=a,b` in chunks of 100 (same parsing as core/blocks `fetchers.ts`). */
|
|
67
|
+
function createAssets(client) {
|
|
68
|
+
return {
|
|
69
|
+
async byIds(ids) {
|
|
70
|
+
const unique = [...new Set(ids)];
|
|
71
|
+
const out = [];
|
|
72
|
+
for (let i = 0; i < unique.length; i += MAX_IDS) {
|
|
73
|
+
const r = await client.request('GET', '/api/content/assets', { query: { ids: unique.slice(i, i + MAX_IDS) } });
|
|
74
|
+
for (const a of Array.isArray(r?.data) ? r.data : []) {
|
|
75
|
+
if (typeof a.id !== 'string' || typeof a.url !== 'string')
|
|
76
|
+
continue;
|
|
77
|
+
out.push({
|
|
78
|
+
id: a.id,
|
|
79
|
+
url: a.url,
|
|
80
|
+
...(typeof a.alt === 'string' ? { alt: a.alt } : {}),
|
|
81
|
+
...(typeof a.width === 'number' ? { width: a.width } : {}),
|
|
82
|
+
...(typeof a.height === 'number' ? { height: a.height } : {}),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.setDefaultClientFactory = setDefaultClientFactory;
|
|
4
|
+
exports.defaultClient = defaultClient;
|
|
5
|
+
const client_js_1 = require("./client.js");
|
|
6
|
+
const loopback_js_1 = require("../next/loopback.js");
|
|
7
|
+
let override;
|
|
8
|
+
let overridden;
|
|
9
|
+
let server;
|
|
10
|
+
let browser;
|
|
11
|
+
/** Overrides the default content client (tests / apps). Pass `undefined` to go back to the environment rule. */
|
|
12
|
+
function setDefaultClientFactory(fn) {
|
|
13
|
+
override = fn;
|
|
14
|
+
overridden = undefined;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The client used by content entries without a bound client, chosen per call by environment (not by which entry
|
|
18
|
+
* loaded last): no `window` → the process-cached `publicClient()` (loopback, cacheable); otherwise a same-origin
|
|
19
|
+
* cookie client. No `next/*` is imported here; the server client is `publicClient()` minus the Next-only options.
|
|
20
|
+
*/
|
|
21
|
+
function defaultClient() {
|
|
22
|
+
if (override)
|
|
23
|
+
return (overridden ??= override());
|
|
24
|
+
if (typeof window === 'undefined')
|
|
25
|
+
return (server ??= (0, client_js_1.createClient)({ baseUrl: (0, loopback_js_1.loopbackUrl)(), auth: 'cookie' }));
|
|
26
|
+
return (browser ??= (0, client_js_1.createClient)());
|
|
27
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isApiError = exports.ApiError = void 0;
|
|
4
|
+
exports.errorMessage = errorMessage;
|
|
5
|
+
/** A failed API call: `{ error: { code, message, issues? } }`, `http_<status>` for other bodies, `network_error` (status 0). */
|
|
6
|
+
class ApiError extends Error {
|
|
7
|
+
status;
|
|
8
|
+
code;
|
|
9
|
+
issues;
|
|
10
|
+
/** The raw `error` object of the response body (extra fields such as `signIn`). */
|
|
11
|
+
details;
|
|
12
|
+
constructor(status, code, message, issues, details) {
|
|
13
|
+
super(message || code);
|
|
14
|
+
this.name = 'ApiError';
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.code = code;
|
|
17
|
+
if (issues)
|
|
18
|
+
this.issues = issues;
|
|
19
|
+
if (details)
|
|
20
|
+
this.details = details;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.ApiError = ApiError;
|
|
24
|
+
const isApiError = (e) => e instanceof ApiError || (typeof e === 'object' && e !== null && e.name === 'ApiError' && typeof e.code === 'string');
|
|
25
|
+
exports.isApiError = isApiError;
|
|
26
|
+
const GENERIC = '__generic';
|
|
27
|
+
const BUILT_IN = {
|
|
28
|
+
invalid_identifier: { 'en-US': 'Enter a valid email address or phone number.', 'vi-VN': 'Vui lòng nhập email hoặc số điện thoại hợp lệ.' },
|
|
29
|
+
identifier_kind_disabled: { 'en-US': 'This type of sign-in is not accepted.', 'vi-VN': 'Hình thức đăng nhập này không được hỗ trợ.' },
|
|
30
|
+
method_disabled: { 'en-US': 'This sign-in method is not available.', 'vi-VN': 'Phương thức đăng nhập này không khả dụng.' },
|
|
31
|
+
invalid_code: { 'en-US': 'The code is incorrect or has expired.', 'vi-VN': 'Mã không đúng hoặc đã hết hạn.' },
|
|
32
|
+
invalid_credentials: { 'en-US': 'Incorrect sign-in details.', 'vi-VN': 'Thông tin đăng nhập không đúng.' },
|
|
33
|
+
account_disabled: { 'en-US': 'This account has been disabled.', 'vi-VN': 'Tài khoản này đã bị vô hiệu hóa.' },
|
|
34
|
+
rate_limited: { 'en-US': 'Too many attempts. Please try again later.', 'vi-VN': 'Bạn đã thử quá nhiều lần. Vui lòng thử lại sau.' },
|
|
35
|
+
weak_password: { 'en-US': 'This password is too weak.', 'vi-VN': 'Mật khẩu quá yếu.' },
|
|
36
|
+
validation_failed: { 'en-US': 'Please check the information you entered.', 'vi-VN': 'Vui lòng kiểm tra lại thông tin đã nhập.' },
|
|
37
|
+
unauthenticated: { 'en-US': 'Please sign in to continue.', 'vi-VN': 'Vui lòng đăng nhập để tiếp tục.' },
|
|
38
|
+
login_expired: { 'en-US': 'Your sign-in has expired. Please start again.', 'vi-VN': 'Phiên đăng nhập đã hết hạn. Vui lòng thử lại.' },
|
|
39
|
+
invalid_state: { 'en-US': 'Sign-in could not be completed. Please start again.', 'vi-VN': 'Không thể hoàn tất đăng nhập. Vui lòng thử lại từ đầu.' },
|
|
40
|
+
unknown_action: { 'en-US': 'This action is not available.', 'vi-VN': 'Thao tác này không khả dụng.' },
|
|
41
|
+
action_failed: { 'en-US': 'The action could not be completed. Please try again.', 'vi-VN': 'Không thể thực hiện thao tác. Vui lòng thử lại.' },
|
|
42
|
+
network_error: { 'en-US': 'Cannot connect. Check your connection and try again.', 'vi-VN': 'Không thể kết nối. Vui lòng kiểm tra mạng và thử lại.' },
|
|
43
|
+
[GENERIC]: { 'en-US': 'Something went wrong. Please try again.', 'vi-VN': 'Đã xảy ra lỗi. Vui lòng thử lại.' },
|
|
44
|
+
};
|
|
45
|
+
const toMessageLocale = (locale) => (locale && /^vi(\b|[-_])/i.test(locale) ? 'vi-VN' : 'en-US');
|
|
46
|
+
/** User-facing text for an error or error code (en-US / vi-VN), `extra` taking precedence over the built-ins. */
|
|
47
|
+
function errorMessage(err, locale, extra) {
|
|
48
|
+
const loc = toMessageLocale(locale);
|
|
49
|
+
const code = typeof err === 'string' ? err : (0, exports.isApiError)(err) ? err.code : GENERIC;
|
|
50
|
+
const own = extra?.[code];
|
|
51
|
+
const builtIn = BUILT_IN[code];
|
|
52
|
+
return own?.[loc] ?? builtIn?.[loc] ?? own?.['en-US'] ?? BUILT_IN[GENERIC][loc];
|
|
53
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createContentApi = createContentApi;
|
|
4
|
+
const default_client_js_1 = require("./default-client.js");
|
|
5
|
+
/** Typed access to content types: `createContentApi<{ product: Product }>().product.list({ filter: { slug: 'x' } })`. */
|
|
6
|
+
function createContentApi(bound) {
|
|
7
|
+
const clientOf = () => bound ?? (0, default_client_js_1.defaultClient)();
|
|
8
|
+
return new Proxy({}, {
|
|
9
|
+
get(_t, key) {
|
|
10
|
+
if (typeof key !== 'string' || key === 'then')
|
|
11
|
+
return undefined;
|
|
12
|
+
if (key === 'with')
|
|
13
|
+
return (c) => createContentApi(c);
|
|
14
|
+
return {
|
|
15
|
+
list: (o) => clientOf().content.list(key, o),
|
|
16
|
+
get: (id, o) => clientOf().content.get(key, id, o),
|
|
17
|
+
bySlug: (slug, o) => clientOf().content.bySlug(key, slug, o),
|
|
18
|
+
byIds: (ids, o) => clientOf().content.byIds(key, ids, o),
|
|
19
|
+
};
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.utils = void 0;
|
|
4
|
+
exports.formatMoney = formatMoney;
|
|
5
|
+
exports.formatDate = formatDate;
|
|
6
|
+
exports.normalizeIdentifier = normalizeIdentifier;
|
|
7
|
+
exports.safeReturnTo = safeReturnTo;
|
|
8
|
+
exports.buildQuery = buildQuery;
|
|
9
|
+
const libphonenumber_js_1 = require("libphonenumber-js");
|
|
10
|
+
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
11
|
+
function formatMoney(m, locale) {
|
|
12
|
+
return new Intl.NumberFormat(locale, { style: 'currency', currency: m.currency }).format(m.amount);
|
|
13
|
+
}
|
|
14
|
+
function formatDate(v, locale, style = 'date') {
|
|
15
|
+
const d = v instanceof Date ? v : new Date(v);
|
|
16
|
+
return new Intl.DateTimeFormat(locale, style === 'datetime' ? { dateStyle: 'medium', timeStyle: 'short' } : { dateStyle: 'medium' }).format(d);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Source of truth: packages/oauth2/src/customers/identifier.ts and its unit test (packages/oauth2/test/unit/identifier.test.ts);
|
|
20
|
+
* keep this copy in step with them.
|
|
21
|
+
* Same algorithm as the server's `normalizeIdentifier`: email trimmed + lower-cased; phone to E.164 (`region` for local numbers). */
|
|
22
|
+
function normalizeIdentifier(raw, region) {
|
|
23
|
+
const s = (raw ?? '').trim();
|
|
24
|
+
if (!s)
|
|
25
|
+
return null;
|
|
26
|
+
if (s.includes('@')) {
|
|
27
|
+
const value = s.toLowerCase();
|
|
28
|
+
return EMAIL_RE.test(value) ? { kind: 'email', value } : null;
|
|
29
|
+
}
|
|
30
|
+
const phone = (0, libphonenumber_js_1.parsePhoneNumberFromString)(s, region);
|
|
31
|
+
if (phone?.isValid())
|
|
32
|
+
return { kind: 'phone', value: phone.number };
|
|
33
|
+
// Country code typed without '+' (e.g. 84912345678).
|
|
34
|
+
if (/^\d{8,15}$/.test(s)) {
|
|
35
|
+
const intl = (0, libphonenumber_js_1.parsePhoneNumberFromString)(`+${s}`);
|
|
36
|
+
if (intl?.isValid())
|
|
37
|
+
return { kind: 'phone', value: intl.number };
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
/** A local absolute path: starts with `/`, no `//`, no `\`, no control characters; anything else `/`. */
|
|
42
|
+
function safeReturnTo(path) {
|
|
43
|
+
if (typeof path !== 'string' || !path.startsWith('/'))
|
|
44
|
+
return '/';
|
|
45
|
+
if (path.includes('\\') || path.includes('//'))
|
|
46
|
+
return '/';
|
|
47
|
+
// eslint-disable-next-line no-control-regex
|
|
48
|
+
if (/[\u0000-\u001f\u007f]/.test(path))
|
|
49
|
+
return '/';
|
|
50
|
+
return path;
|
|
51
|
+
}
|
|
52
|
+
/** `a=1&b=x+y`; undefined / null skipped, arrays joined with `,`, dates as ISO strings. `[ ] ,` stay readable. */
|
|
53
|
+
function buildQuery(params) {
|
|
54
|
+
const qs = new URLSearchParams();
|
|
55
|
+
for (const [k, v] of Object.entries(params)) {
|
|
56
|
+
if (v === undefined || v === null)
|
|
57
|
+
continue;
|
|
58
|
+
const one = (x) => (x instanceof Date ? x.toISOString() : String(x));
|
|
59
|
+
qs.append(k, Array.isArray(v) ? v.map(one).join(',') : one(v));
|
|
60
|
+
}
|
|
61
|
+
return qs.toString().replace(/%5B/gi, '[').replace(/%5D/gi, ']').replace(/%2C/gi, ',');
|
|
62
|
+
}
|
|
63
|
+
/** The public namespace: utilities are exported only through this object. */
|
|
64
|
+
exports.utils = { formatMoney, formatDate, normalizeIdentifier, safeReturnTo, buildQuery };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.useActionRunner = exports.useAction = exports.useSignOut = exports.useSignIn = exports.useCustomer = exports.useClient = exports.OpenCloudCmsProvider = exports.defineActionClient = exports.ACTION_EVENT = exports.ActionRunner = exports.requireCustomer = exports.getCustomer = exports.publicClient = exports.serverClient = exports.loopbackUrl = exports.utils = exports.errorMessage = exports.isApiError = exports.ApiError = exports.setDefaultClientFactory = exports.createContentApi = exports.createClient = void 0;
|
|
4
|
+
// Full build (`import` / `require`): everything, React provider and hooks included. The Next server helpers are
|
|
5
|
+
// stubs here (they throw when called); the `react-server` build (server.ts) has the real ones.
|
|
6
|
+
var client_js_1 = require("./core/client.js");
|
|
7
|
+
Object.defineProperty(exports, "createClient", { enumerable: true, get: function () { return client_js_1.createClient; } });
|
|
8
|
+
var typed_js_1 = require("./core/typed.js");
|
|
9
|
+
Object.defineProperty(exports, "createContentApi", { enumerable: true, get: function () { return typed_js_1.createContentApi; } });
|
|
10
|
+
var default_client_js_1 = require("./core/default-client.js");
|
|
11
|
+
Object.defineProperty(exports, "setDefaultClientFactory", { enumerable: true, get: function () { return default_client_js_1.setDefaultClientFactory; } });
|
|
12
|
+
var errors_js_1 = require("./core/errors.js");
|
|
13
|
+
Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return errors_js_1.ApiError; } });
|
|
14
|
+
Object.defineProperty(exports, "isApiError", { enumerable: true, get: function () { return errors_js_1.isApiError; } });
|
|
15
|
+
Object.defineProperty(exports, "errorMessage", { enumerable: true, get: function () { return errors_js_1.errorMessage; } });
|
|
16
|
+
var utils_js_1 = require("./core/utils.js");
|
|
17
|
+
Object.defineProperty(exports, "utils", { enumerable: true, get: function () { return utils_js_1.utils; } });
|
|
18
|
+
var loopback_js_1 = require("./next/loopback.js");
|
|
19
|
+
Object.defineProperty(exports, "loopbackUrl", { enumerable: true, get: function () { return loopback_js_1.loopbackUrl; } });
|
|
20
|
+
var stubs_js_1 = require("./next/stubs.js");
|
|
21
|
+
Object.defineProperty(exports, "serverClient", { enumerable: true, get: function () { return stubs_js_1.serverClient; } });
|
|
22
|
+
Object.defineProperty(exports, "publicClient", { enumerable: true, get: function () { return stubs_js_1.publicClient; } });
|
|
23
|
+
Object.defineProperty(exports, "getCustomer", { enumerable: true, get: function () { return stubs_js_1.getCustomer; } });
|
|
24
|
+
Object.defineProperty(exports, "requireCustomer", { enumerable: true, get: function () { return stubs_js_1.requireCustomer; } });
|
|
25
|
+
var runner_js_1 = require("./actions/runner.js");
|
|
26
|
+
Object.defineProperty(exports, "ActionRunner", { enumerable: true, get: function () { return runner_js_1.ActionRunner; } });
|
|
27
|
+
Object.defineProperty(exports, "ACTION_EVENT", { enumerable: true, get: function () { return runner_js_1.ACTION_EVENT; } });
|
|
28
|
+
var actions_js_1 = require("./core/actions.js");
|
|
29
|
+
Object.defineProperty(exports, "defineActionClient", { enumerable: true, get: function () { return actions_js_1.defineActionClient; } });
|
|
30
|
+
var provider_js_1 = require("./react/provider.js");
|
|
31
|
+
Object.defineProperty(exports, "OpenCloudCmsProvider", { enumerable: true, get: function () { return provider_js_1.OpenCloudCmsProvider; } });
|
|
32
|
+
Object.defineProperty(exports, "useClient", { enumerable: true, get: function () { return provider_js_1.useClient; } });
|
|
33
|
+
Object.defineProperty(exports, "useCustomer", { enumerable: true, get: function () { return provider_js_1.useCustomer; } });
|
|
34
|
+
Object.defineProperty(exports, "useSignIn", { enumerable: true, get: function () { return provider_js_1.useSignIn; } });
|
|
35
|
+
Object.defineProperty(exports, "useSignOut", { enumerable: true, get: function () { return provider_js_1.useSignOut; } });
|
|
36
|
+
Object.defineProperty(exports, "useAction", { enumerable: true, get: function () { return provider_js_1.useAction; } });
|
|
37
|
+
Object.defineProperty(exports, "useActionRunner", { enumerable: true, get: function () { return provider_js_1.useActionRunner; } });
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.loopbackUrl = loopbackUrl;
|
|
4
|
+
/**
|
|
5
|
+
* Loopback base URL of the OpenCloudCMS API for server-side calls: `http://127.0.0.1:${PORT ?? 4000}`, the same rule
|
|
6
|
+
* as `core/blocks`' `resolveBaseUrl` (there is no `OPENCLOUDCMS_INTERNAL_URL`; it was removed). Read per call, so a
|
|
7
|
+
* `PORT` set after import counts.
|
|
8
|
+
*/
|
|
9
|
+
function loopbackUrl() {
|
|
10
|
+
const env = typeof process !== 'undefined' && process?.env ? process.env : {};
|
|
11
|
+
return `http://127.0.0.1:${env.PORT ?? 4000}`;
|
|
12
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.publicClient = publicClient;
|
|
37
|
+
exports.serverClient = serverClient;
|
|
38
|
+
exports.getCustomer = getCustomer;
|
|
39
|
+
exports.requireCustomer = requireCustomer;
|
|
40
|
+
// Next.js server helpers (react-server build only). `next/headers` / `next/navigation` are imported lazily inside
|
|
41
|
+
// the functions, never at module load, so this file can be loaded anywhere without Next.
|
|
42
|
+
const client_js_1 = require("../core/client.js");
|
|
43
|
+
const utils_js_1 = require("../core/utils.js");
|
|
44
|
+
const loopback_js_1 = require("./loopback.js");
|
|
45
|
+
const sameOrigin = (url, base) => {
|
|
46
|
+
try {
|
|
47
|
+
return new URL(url, base).origin === new URL(base).origin;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
async function incomingHeaders() {
|
|
54
|
+
const { headers } = await Promise.resolve().then(() => __importStar(require('next/headers')));
|
|
55
|
+
return (await headers());
|
|
56
|
+
}
|
|
57
|
+
/** Loopback client without cookie forwarding: pages that only use it stay static / cacheable (`next` options pass through). */
|
|
58
|
+
function publicClient(o = {}) {
|
|
59
|
+
return (0, client_js_1.createClient)({ ...o, baseUrl: (0, loopback_js_1.loopbackUrl)(), auth: 'cookie' });
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Loopback client that forwards the incoming request's `cookie` header (read from `next/headers` on every request,
|
|
63
|
+
* only to the loopback origin). Requests default to `cache: 'no-store'`. Using it makes the page dynamic.
|
|
64
|
+
*/
|
|
65
|
+
function serverClient(o = {}) {
|
|
66
|
+
const baseUrl = (0, loopback_js_1.loopbackUrl)();
|
|
67
|
+
const inner = o.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
68
|
+
const forwarding = (async (input, init) => {
|
|
69
|
+
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
|
70
|
+
if (!sameOrigin(url, baseUrl))
|
|
71
|
+
return inner(input, init);
|
|
72
|
+
const cookie = (await incomingHeaders()).get('cookie');
|
|
73
|
+
const headers = new Headers(init?.headers);
|
|
74
|
+
if (cookie && !headers.has('cookie'))
|
|
75
|
+
headers.set('cookie', cookie);
|
|
76
|
+
return inner(input, { ...init, headers, cache: init?.cache ?? 'no-store' });
|
|
77
|
+
});
|
|
78
|
+
return (0, client_js_1.createClient)({ ...o, baseUrl, auth: 'cookie', fetch: forwarding });
|
|
79
|
+
}
|
|
80
|
+
/** The signed-in customer of the current request, `null` when signed out. Never cached across requests. */
|
|
81
|
+
function getCustomer() {
|
|
82
|
+
return serverClient().auth.me();
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The signed-in customer, or a `redirect()` to the sign-in route. `returnTo` defaults to the request path from the
|
|
86
|
+
* `x-pathname` header (set it in middleware), then Next's `next-url`, else `/`; always passed through `safeReturnTo`.
|
|
87
|
+
*/
|
|
88
|
+
async function requireCustomer(o = {}) {
|
|
89
|
+
const customer = await getCustomer();
|
|
90
|
+
if (customer)
|
|
91
|
+
return customer;
|
|
92
|
+
let returnTo = o.returnTo;
|
|
93
|
+
if (returnTo === undefined) {
|
|
94
|
+
const h = await incomingHeaders();
|
|
95
|
+
returnTo = h.get('x-pathname') ?? h.get('next-url') ?? '/';
|
|
96
|
+
}
|
|
97
|
+
const { redirect } = await Promise.resolve().then(() => __importStar(require('next/navigation')));
|
|
98
|
+
return redirect(`/api/customer/auth/login?returnTo=${encodeURIComponent((0, utils_js_1.safeReturnTo)(returnTo))}`);
|
|
99
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.requireCustomer = exports.getCustomer = exports.publicClient = exports.serverClient = void 0;
|
|
4
|
+
const only = (name) => () => {
|
|
5
|
+
throw new Error(`${name} is only available in a server component`);
|
|
6
|
+
};
|
|
7
|
+
exports.serverClient = only('serverClient');
|
|
8
|
+
exports.publicClient = only('publicClient');
|
|
9
|
+
exports.getCustomer = only('getCustomer');
|
|
10
|
+
exports.requireCustomer = only('requireCustomer');
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|