@veroxm/sdk 1.12.0 → 1.14.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/dist/index.d.ts CHANGED
@@ -19,6 +19,10 @@ export { ProcessesResource } from './processes.js';
19
19
  export type { ProcessRun, ProcessRunDetail, ProcessRunListOptions } from './processes.js';
20
20
  export { FormsResource } from './forms.js';
21
21
  export type { FormDetail, FormResponse, FormResponseListOptions, FormResponsePage, FormSummary } from './forms.js';
22
+ export { FilesResource, uploadWithGrant } from './files.js';
23
+ export type { FileFolderRule, FileGrant, FileGrantOptions, StoredFile, StoredFileEvent, StoredFileEventOptions, StoredFileEventPage, StoredFileLink, StoredFileListOptions, StoredFilePage } from './files.js';
24
+ export { TranslationsResource, fetchTranslations, fetchTranslationResource, fetchTranslationLocales, createTranslator, VeroxmI18nextBackend, } from './translations.js';
25
+ export type { FetchTranslationsOptions, TranslationBundle, TranslationBundleOptions, TranslationLocale, TranslationLocales, TranslationTexts, TranslationValues, Translator, VeroxmI18nextBackendOptions, } from './translations.js';
22
26
  export { embedForm, embedFormsFromPage } from './embed.js';
23
27
  export type { FormEmbed, FormEmbedMode, FormEmbedOpenTrigger, FormEmbedOptions, FormEmbedTracker } from './embed.js';
24
28
  export type { Schemas } from './schemas.js';
package/dist/index.js CHANGED
@@ -10,6 +10,10 @@ export { FunctionsResource } from './functions.js';
10
10
  export { TasksResource } from './tasks.js';
11
11
  export { ProcessesResource } from './processes.js';
12
12
  export { FormsResource } from './forms.js';
13
+ // Private files: a server key's, and one-time upload links a browser uses.
14
+ export { FilesResource, uploadWithGrant } from './files.js';
15
+ // App translations: a locale's bundle in one request, and a t() for its texts.
16
+ export { TranslationsResource, fetchTranslations, fetchTranslationResource, fetchTranslationLocales, createTranslator, VeroxmI18nextBackend, } from './translations.js';
13
17
  // Showing forms in a page: inline, popup, full page or toast.
14
18
  export { embedForm, embedFormsFromPage } from './embed.js';
15
19
  export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTimeoutError, VeroXMTwoStepRequiredError } from './errors.js';
@@ -0,0 +1,106 @@
1
+ import type { VeroXMApp } from './client.js';
2
+ import { type RequestControl } from './http.js';
3
+ import type { Schemas } from './schemas.js';
4
+ /** Nested texts: `{ checkout: { pay: "Pay {{amount}}" } }`. With `flat`, dotted keys instead: `{ "checkout.pay": ... }`. */
5
+ export type TranslationTexts = Schemas['TranslationTexts'];
6
+ /** One locale of the project: its names, writing direction (`dir`, for `<html dir>`) and `translated` of `total` keys. */
7
+ export type TranslationLocale = Schemas['TranslationLocale'];
8
+ /** The project's locales, and the translations `version` (pass it as `version` for an address cached for a year). */
9
+ export type TranslationLocales = Schemas['TranslationLocales'];
10
+ /** A locale's whole bundle: its texts, direction, names, and `fallback` (keys shown in the default locale). */
11
+ export type TranslationBundle = Schemas['TranslationBundle'];
12
+ export interface TranslationBundleOptions extends RequestControl {
13
+ /** Fill keys this locale doesn't have yet from the default locale. Default: true. */
14
+ fallback?: boolean;
15
+ /** Dotted keys (`"checkout.pay"`) instead of nested objects. Default: false. */
16
+ flat?: boolean;
17
+ /** The project's translations version (from `locales()` or an earlier bundle): an address cached for a year. */
18
+ version?: number;
19
+ /** Extra attempts after a network error, a timeout, or 429, 502, 503 or 504. Default: the app's `retries`. */
20
+ retries?: number;
21
+ }
22
+ /**
23
+ * The project's app translations, read with any of its keys (`auth.signInWithApiKey`), a browser key too. Bundles are
24
+ * cached by browsers and CDNs; pass `version` for an address that never changes.
25
+ */
26
+ export declare class TranslationsResource {
27
+ private readonly app;
28
+ constructor(app: VeroXMApp);
29
+ /** The locales with their names, writing direction and coverage, and the current version. */
30
+ locales(options?: RequestControl & {
31
+ retries?: number;
32
+ }): Promise<TranslationLocales>;
33
+ /** A locale's bundle: its texts, direction and names. A locale the project doesn't have rejects with 404 `locale_not_found`. */
34
+ get(locale: string, options?: TranslationBundleOptions): Promise<TranslationBundle>;
35
+ /** Only the texts, as i18next loads a resource: `i18n.addResourceBundle('ar', 'translation', await app.translations.resource('ar'))`. */
36
+ resource(locale: string, options?: TranslationBundleOptions): Promise<TranslationTexts>;
37
+ }
38
+ export interface FetchTranslationsOptions extends TranslationBundleOptions {
39
+ /** Your VeroXM deployment's origin, e.g. "https://cms.example.com". */
40
+ baseUrl: string;
41
+ /** The project's UUID: its own address, which CDNs can cache. */
42
+ projectId: string;
43
+ /** Any key of the project (a browser key is enough): sent as `Authorization: Bearer <apiKey>`. */
44
+ apiKey: string;
45
+ /** The fetch to send with (e.g. one adding Next.js cache options). Default: the global fetch. */
46
+ fetch?: typeof fetch;
47
+ }
48
+ /** A locale's bundle without a VeroXMApp: `await fetchTranslations({ baseUrl, projectId, apiKey, locale: 'ar' })`. */
49
+ export declare function fetchTranslations(options: FetchTranslationsOptions & {
50
+ locale: string;
51
+ }): Promise<TranslationBundle>;
52
+ /** Only the texts, as i18next loads them, without a VeroXMApp. */
53
+ export declare function fetchTranslationResource(options: FetchTranslationsOptions & {
54
+ locale: string;
55
+ }): Promise<TranslationTexts>;
56
+ /** The project's locales without a VeroXMApp. */
57
+ export declare function fetchTranslationLocales(options: Omit<FetchTranslationsOptions, 'fallback' | 'flat' | 'version'>): Promise<TranslationLocales>;
58
+ /** Values for a text's `{{placeholders}}`; `count` also picks a plural form (`key_one`, `key_other`...). */
59
+ export type TranslationValues = Record<string, unknown> & {
60
+ count?: number;
61
+ };
62
+ export interface Translator {
63
+ /**
64
+ * The text for `key` with its `{{placeholders}}` filled in, i18next-style: `{{name}}`, `{{user.name}}`, `{{- html}}`
65
+ * and `{{price, currency}}` (the format part is ignored), `$t(other.key)` for another text, and plural forms by
66
+ * `count` (`cart.items_one`, `cart.items_other`). A key with no text gives the key itself, or `fallback`.
67
+ */
68
+ (key: string, values?: TranslationValues, fallback?: string): string;
69
+ /** True when the bundle has a text for `key`. */
70
+ has(key: string): boolean;
71
+ }
72
+ /**
73
+ * A `t(key, values)` over a bundle's texts (nested or flat), e.g. `createTranslator(bundle.translations, { locale:
74
+ * bundle.locale })`. The locale picks plural forms; without one, `count === 1` is "one" and anything else "other".
75
+ */
76
+ export declare function createTranslator(texts: TranslationTexts, options?: {
77
+ locale?: string;
78
+ }): Translator;
79
+ export interface VeroxmI18nextBackendOptions extends Omit<FetchTranslationsOptions, 'flat' | 'signal'> {
80
+ /** The namespace that gets the whole bundle. Other namespaces get the texts under their name. Default: "translation". */
81
+ defaultNamespace?: string;
82
+ }
83
+ type ReadCallback = (error: unknown, data: TranslationTexts | false | null) => void;
84
+ /**
85
+ * An i18next backend that loads each language from VeroXM in one request:
86
+ *
87
+ * ```ts
88
+ * i18next.use(VeroxmI18nextBackend).init({
89
+ * lng: 'ar', fallbackLng: 'en',
90
+ * backend: { baseUrl: 'https://cms.example.com', projectId: '<project uuid>', apiKey: '<browser key>' },
91
+ * });
92
+ * ```
93
+ *
94
+ * The "translation" namespace gets the whole bundle; another namespace, such as `useTranslation('checkout')`, gets the
95
+ * texts under `checkout`. A language the project doesn't have loads as empty, so i18next falls back to `fallbackLng`.
96
+ */
97
+ export declare class VeroxmI18nextBackend {
98
+ static readonly type: "backend";
99
+ readonly type: "backend";
100
+ private options;
101
+ private readonly loading;
102
+ constructor(services?: unknown, options?: VeroxmI18nextBackendOptions);
103
+ init(_services?: unknown, options?: VeroxmI18nextBackendOptions): void;
104
+ read(language: string, namespace: string, callback: ReadCallback): void;
105
+ }
106
+ export {};
@@ -0,0 +1,177 @@
1
+ import { rawRequest } from './http.js';
2
+ function bundleQuery(options, format) {
3
+ return {
4
+ format,
5
+ fallback: options.fallback === false ? 0 : undefined,
6
+ flat: options.flat ? 1 : undefined,
7
+ v: options.version,
8
+ };
9
+ }
10
+ function control(options) {
11
+ return { signal: options.signal, timeoutMs: options.timeoutMs, retries: options.retries };
12
+ }
13
+ /**
14
+ * The project's app translations, read with any of its keys (`auth.signInWithApiKey`), a browser key too. Bundles are
15
+ * cached by browsers and CDNs; pass `version` for an address that never changes.
16
+ */
17
+ export class TranslationsResource {
18
+ constructor(app) {
19
+ this.app = app;
20
+ }
21
+ /** The locales with their names, writing direction and coverage, and the current version. */
22
+ async locales(options = {}) {
23
+ return (await this.app.request({ path: '/translations', ...control(options) }));
24
+ }
25
+ /** A locale's bundle: its texts, direction and names. A locale the project doesn't have rejects with 404 `locale_not_found`. */
26
+ async get(locale, options = {}) {
27
+ return (await this.app.request({ path: `/translations/${encodeURIComponent(locale)}`, query: bundleQuery(options), ...control(options) }));
28
+ }
29
+ /** Only the texts, as i18next loads a resource: `i18n.addResourceBundle('ar', 'translation', await app.translations.resource('ar'))`. */
30
+ async resource(locale, options = {}) {
31
+ return (await this.app.request({ path: `/translations/${encodeURIComponent(locale)}`, query: bundleQuery(options, 'i18next'), ...control(options) }));
32
+ }
33
+ }
34
+ function projectBase(options) {
35
+ return `${options.baseUrl.replace(/\/$/, '')}/public/v2/projects/${encodeURIComponent(options.projectId)}`;
36
+ }
37
+ function send(options, path, query) {
38
+ return rawRequest(projectBase(options), { path, query, headers: { Authorization: `Bearer ${options.apiKey}` }, ...control(options) }, { fetch: options.fetch });
39
+ }
40
+ /** A locale's bundle without a VeroXMApp: `await fetchTranslations({ baseUrl, projectId, apiKey, locale: 'ar' })`. */
41
+ export async function fetchTranslations(options) {
42
+ return (await send(options, `/translations/${encodeURIComponent(options.locale)}`, bundleQuery(options)));
43
+ }
44
+ /** Only the texts, as i18next loads them, without a VeroXMApp. */
45
+ export async function fetchTranslationResource(options) {
46
+ return (await send(options, `/translations/${encodeURIComponent(options.locale)}`, bundleQuery(options, 'i18next')));
47
+ }
48
+ /** The project's locales without a VeroXMApp. */
49
+ export async function fetchTranslationLocales(options) {
50
+ return (await send(options, '/translations'));
51
+ }
52
+ function lookup(texts, key) {
53
+ const direct = texts[key];
54
+ if (typeof direct === 'string')
55
+ return direct;
56
+ let node = texts;
57
+ for (const part of key.split('.')) {
58
+ if (!node || typeof node !== 'object')
59
+ return undefined;
60
+ node = node[part];
61
+ }
62
+ return typeof node === 'string' ? node : undefined;
63
+ }
64
+ function valueAt(values, path) {
65
+ if (path in values)
66
+ return values[path];
67
+ let node = values;
68
+ for (const part of path.split('.')) {
69
+ if (node === null || typeof node !== 'object')
70
+ return undefined;
71
+ node = node[part];
72
+ }
73
+ return node;
74
+ }
75
+ const PLACEHOLDER = /\{\{\s*(?:-\s*)?([^{},\s-][^{},\s]*)\s*(?:,[^{}]*)?\}\}/g;
76
+ const NESTED = /\$t\(\s*([^,()\s]+)\s*\)/g;
77
+ /**
78
+ * A `t(key, values)` over a bundle's texts (nested or flat), e.g. `createTranslator(bundle.translations, { locale:
79
+ * bundle.locale })`. The locale picks plural forms; without one, `count === 1` is "one" and anything else "other".
80
+ */
81
+ export function createTranslator(texts, options = {}) {
82
+ let plurals;
83
+ try {
84
+ if (options.locale && typeof Intl !== 'undefined')
85
+ plurals = new Intl.PluralRules(options.locale);
86
+ }
87
+ catch {
88
+ plurals = undefined;
89
+ }
90
+ const form = (count) => (plurals ? plurals.select(count) : count === 1 ? 'one' : 'other');
91
+ const find = (key, values) => {
92
+ if (values && typeof values.count === 'number') {
93
+ const plural = (values.count === 0 ? lookup(texts, `${key}_zero`) : undefined) ?? lookup(texts, `${key}_${form(values.count)}`) ?? lookup(texts, `${key}_other`);
94
+ if (plural !== undefined)
95
+ return plural;
96
+ }
97
+ return lookup(texts, key);
98
+ };
99
+ const render = (text, values, depth) => {
100
+ let out = depth < 5 ? text.replace(NESTED, (whole, k) => {
101
+ const inner = find(k, values);
102
+ return inner === undefined ? whole : render(inner, values, depth + 1);
103
+ }) : text;
104
+ if (values) {
105
+ out = out.replace(PLACEHOLDER, (whole, name) => {
106
+ const v = valueAt(values, name);
107
+ return v === undefined || v === null ? whole : String(v);
108
+ });
109
+ }
110
+ return out;
111
+ };
112
+ const t = ((key, values, fallback) => {
113
+ const text = find(key, values);
114
+ if (text === undefined)
115
+ return fallback ?? key;
116
+ return render(text, values, 0);
117
+ });
118
+ t.has = (key) => lookup(texts, key) !== undefined;
119
+ return t;
120
+ }
121
+ /**
122
+ * An i18next backend that loads each language from VeroXM in one request:
123
+ *
124
+ * ```ts
125
+ * i18next.use(VeroxmI18nextBackend).init({
126
+ * lng: 'ar', fallbackLng: 'en',
127
+ * backend: { baseUrl: 'https://cms.example.com', projectId: '<project uuid>', apiKey: '<browser key>' },
128
+ * });
129
+ * ```
130
+ *
131
+ * The "translation" namespace gets the whole bundle; another namespace, such as `useTranslation('checkout')`, gets the
132
+ * texts under `checkout`. A language the project doesn't have loads as empty, so i18next falls back to `fallbackLng`.
133
+ */
134
+ export class VeroxmI18nextBackend {
135
+ constructor(services, options) {
136
+ this.type = 'backend';
137
+ this.loading = new Map();
138
+ this.init(services, options);
139
+ }
140
+ init(_services, options) {
141
+ if (options)
142
+ this.options = options;
143
+ }
144
+ read(language, namespace, callback) {
145
+ const options = this.options;
146
+ if (!options?.baseUrl || !options.projectId || !options.apiKey) {
147
+ callback(new Error('VeroxmI18nextBackend needs backend: { baseUrl, projectId, apiKey }.'), false);
148
+ return;
149
+ }
150
+ if (language === 'cimode') {
151
+ callback(null, {});
152
+ return;
153
+ }
154
+ // One request per language, whatever the number of namespaces.
155
+ let texts = this.loading.get(language);
156
+ if (!texts) {
157
+ texts = fetchTranslationResource({ ...options, locale: language }).catch((e) => {
158
+ this.loading.delete(language);
159
+ if (isMissingLocale(e))
160
+ return {};
161
+ throw e;
162
+ });
163
+ this.loading.set(language, texts);
164
+ }
165
+ texts.then((all) => {
166
+ if (namespace === (options.defaultNamespace ?? 'translation'))
167
+ return callback(null, all);
168
+ const part = all[namespace];
169
+ callback(null, part && typeof part === 'object' ? part : {});
170
+ }, (e) => callback(e, false));
171
+ }
172
+ }
173
+ VeroxmI18nextBackend.type = 'backend';
174
+ function isMissingLocale(e) {
175
+ const err = e;
176
+ return !!err && err.status === 404 && err.code === 'locale_not_found';
177
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veroxm/sdk",
3
- "version": "1.12.0",
3
+ "version": "1.14.0",
4
4
  "description": "VeroXM client for JavaScript and TypeScript: content, media, experiences, events and the visitor tracker.",
5
5
  "keywords": [
6
6
  "veroxm",