@veroxm/sdk 1.11.0 → 1.13.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/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.13.0
4
+
5
+ - App translations: `app.translations.get('ar')` reads a locale's whole bundle in one request: its texts (nested, or
6
+ dotted keys with `flat`), writing direction (`dir: 'rtl'`), own name ("العربية") and the project's translations
7
+ `version`. Keys not translated yet come from the default locale (`fallback: false` for only the locale's own), and
8
+ `fallback` lists them. `resource('ar')` is the bare texts as i18next loads them; `locales()` lists the project's
9
+ locales with their direction and coverage (`translated` of `total`). Pass `version` for an address that is cached for
10
+ a year. Any key of the project can read them, a browser key too. `fetchTranslations({ baseUrl, projectId, apiKey,
11
+ locale })` and `fetchTranslationLocales(...)` do the same without a `VeroXMApp`.
12
+ - `createTranslator(texts, { locale })` gives `t(key, values)` for those texts, i18next-style: `{{name}}`,
13
+ `{{user.name}}`, `$t(other.key)`, and plural forms by `count` (`items_one`, `items_other`, `items_zero`). A key with
14
+ no text gives the key itself, or the fallback you pass. Needs a VeroXM server with app translations.
15
+ - `VeroxmI18nextBackend`: an i18next backend, `i18next.use(VeroxmI18nextBackend).init({ backend: { baseUrl, projectId,
16
+ apiKey } })`. One request per language; the "translation" namespace gets the whole bundle and another namespace the
17
+ texts under its name. A language the project doesn't have loads as empty, so i18next falls back to `fallbackLng`.
18
+ `fetchTranslationResource(...)` reads the bare texts without a `VeroXMApp`.
19
+
20
+ ## 1.12.0
21
+
22
+ - Safe retries for writes: `content(slug).create()`, `update()`, `delete()` and `functions.call()` take an
23
+ `idempotencyKey` (any text, 1 to 255 visible characters; a new UUID per write). It is sent as `Idempotency-Key`,
24
+ and the server does the write once for that key: a repeat within 24 hours gets the first answer back. With a key, the
25
+ write is retried like a read, with the app's `retries` or the call's own `retries`, including while the first
26
+ attempt is still running (409 `idempotency_in_progress`). Without a key, writes are never retried, as before. Needs a
27
+ VeroXM server with Idempotency-Key support; an older one ignores the header.
28
+
3
29
  ## 1.11.0
4
30
 
5
31
  - Query text: `content(slug).list({ q })`, `search({ q })` and `count({ q })` take one readable line instead of `where`
package/dist/client.d.ts CHANGED
@@ -6,6 +6,7 @@ import { FunctionsResource } from './functions.js';
6
6
  import { TasksResource } from './tasks.js';
7
7
  import { ProcessesResource } from './processes.js';
8
8
  import { FormsResource } from './forms.js';
9
+ import { TranslationsResource } from './translations.js';
9
10
  import { type TokenStorage } from './token-storage.js';
10
11
  export interface VeroXMAppOptions {
11
12
  /** Your VeroXM deployment's origin, e.g. "https://cms.example.com" -- no trailing /public/... needed, VeroXMApp builds that itself. */
@@ -43,6 +44,8 @@ export declare class VeroXMApp {
43
44
  readonly processes: ProcessesResource;
44
45
  /** The project's forms and responses (server keys with forms:read). */
45
46
  readonly forms: FormsResource;
47
+ /** The project's app translations: a locale's whole bundle in one request (any key, a browser key too). */
48
+ readonly translations: TranslationsResource;
46
49
  private readonly apiBase;
47
50
  private readonly timeoutMs;
48
51
  private readonly retries;
package/dist/client.js CHANGED
@@ -7,6 +7,7 @@ import { FunctionsResource } from './functions.js';
7
7
  import { TasksResource } from './tasks.js';
8
8
  import { ProcessesResource } from './processes.js';
9
9
  import { FormsResource } from './forms.js';
10
+ import { TranslationsResource } from './translations.js';
10
11
  import { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
11
12
  function defaultTokenStorage(projectId) {
12
13
  if (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {
@@ -29,6 +30,7 @@ export class VeroXMApp {
29
30
  this.tasks = new TasksResource(this);
30
31
  this.processes = new ProcessesResource(this);
31
32
  this.forms = new FormsResource(this);
33
+ this.translations = new TranslationsResource(this);
32
34
  }
33
35
  static initializeApp(options) {
34
36
  checkTimeout(options.timeoutMs);
package/dist/content.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { VeroXMApp } from './client.js';
2
- import type { RequestControl } from './http.js';
2
+ import type { RequestControl, WriteControl } from './http.js';
3
3
  export interface ListOptions extends RequestControl {
4
4
  /** Field-value filter -- an array of `{field: value}` clauses (AND'ed together), each value either a scalar or an operator object like `{like: '...'}`, `{gte: '...'}`, `{in: 'a,b,c'}`, etc. See the project's SDK Docs tab for the full operator list. */
5
5
  where?: unknown;
@@ -80,7 +80,7 @@ export declare class ContentResource<T = Record<string, unknown>> {
80
80
  * publish immediately. A database content model that allows creating entries takes its writable fields (and `id` when
81
81
  * it takes the key from you); `userId` / `ctx` say whose row it is for a model limited to the caller's rows.
82
82
  */
83
- create(data: Record<string, unknown>, options?: Pick<ListOptions, 'userId' | 'ctx'>): Promise<T>;
83
+ create(data: Record<string, unknown>, options?: Pick<ListOptions, 'userId' | 'ctx'> & WriteControl): Promise<T>;
84
84
  /**
85
85
  * A partial update -- only the fields present in `data` are changed.
86
86
  * Publish state follows the same rule as create(): omitting `draft` (or
@@ -89,6 +89,6 @@ export declare class ContentResource<T = Record<string, unknown>> {
89
89
  * Pass `draft: true` explicitly to keep (or return) it unpublished.
90
90
  * (A database content model has no drafts: its writable fields only.)
91
91
  */
92
- update(id: number | string, data: Record<string, unknown>, options?: Pick<ListOptions, 'userId' | 'ctx'>): Promise<T>;
93
- delete(id: number | string, options?: Pick<ListOptions, 'userId' | 'ctx'>): Promise<void>;
92
+ update(id: number | string, data: Record<string, unknown>, options?: Pick<ListOptions, 'userId' | 'ctx'> & WriteControl): Promise<T>;
93
+ delete(id: number | string, options?: Pick<ListOptions, 'userId' | 'ctx'> & WriteControl): Promise<void>;
94
94
  }
package/dist/content.js CHANGED
@@ -9,6 +9,14 @@ function control(options) {
9
9
  ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
10
10
  };
11
11
  }
12
+ /** control() plus a write's Idempotency-Key and its retries (only the keys that were given). */
13
+ function writeControl(options) {
14
+ return {
15
+ ...control(options),
16
+ ...(options.idempotencyKey !== undefined ? { idempotencyKey: options.idempotencyKey } : {}),
17
+ ...(options.retries !== undefined ? { retries: options.retries } : {}),
18
+ };
19
+ }
12
20
  /**
13
21
  * Typed access to one content collection's entries. `T` is whatever
14
22
  * shape you expect back (the API's actual response is a plain object per
@@ -83,7 +91,7 @@ export class ContentResource {
83
91
  * it takes the key from you); `userId` / `ctx` say whose row it is for a model limited to the caller's rows.
84
92
  */
85
93
  async create(data, options = {}) {
86
- return this.app.request({ method: 'POST', path: this.root(), query: callerQuery(options), json: data });
94
+ return this.app.request({ method: 'POST', path: this.root(), query: callerQuery(options), json: data, ...writeControl(options) });
87
95
  }
88
96
  /**
89
97
  * A partial update -- only the fields present in `data` are changed.
@@ -94,9 +102,9 @@ export class ContentResource {
94
102
  * (A database content model has no drafts: its writable fields only.)
95
103
  */
96
104
  async update(id, data, options = {}) {
97
- return this.app.request({ method: 'PATCH', path: `${this.root()}/${encodeURIComponent(String(id))}`, query: callerQuery(options), json: data });
105
+ return this.app.request({ method: 'PATCH', path: `${this.root()}/${encodeURIComponent(String(id))}`, query: callerQuery(options), json: data, ...writeControl(options) });
98
106
  }
99
107
  async delete(id, options = {}) {
100
- await this.app.request({ method: 'DELETE', path: `${this.root()}/${encodeURIComponent(String(id))}`, query: callerQuery(options) });
108
+ await this.app.request({ method: 'DELETE', path: `${this.root()}/${encodeURIComponent(String(id))}`, query: callerQuery(options), ...writeControl(options) });
101
109
  }
102
110
  }
@@ -1,5 +1,5 @@
1
1
  import type { VeroXMApp } from './client.js';
2
- import type { RequestControl } from './http.js';
2
+ import type { RequestControl, WriteControl } from './http.js';
3
3
  type Query = Record<string, string | number | boolean | undefined>;
4
4
  /**
5
5
  * Project functions with an HTTP trigger (Developer > Functions). Who may call one is the function's own setting:
@@ -12,10 +12,13 @@ type Query = Record<string, string | number | boolean | undefined>;
12
12
  export declare class FunctionsResource {
13
13
  private readonly app;
14
14
  constructor(app: VeroXMApp);
15
- /** POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. */
15
+ /**
16
+ * POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. With
17
+ * `idempotencyKey` the function runs once for that key, and the call is retried like a GET.
18
+ */
16
19
  call<T = unknown>(name: string, body?: Record<string, unknown> | unknown[], options?: {
17
20
  query?: Query;
18
- } & RequestControl): Promise<T>;
21
+ } & WriteControl): Promise<T>;
19
22
  /** GET /functions/:name (the function reads `query` as `request.query`). Retried with the app's `retries`. */
20
23
  get<T = unknown>(name: string, query?: Query, options?: RequestControl): Promise<T>;
21
24
  }
package/dist/functions.js CHANGED
@@ -10,10 +10,22 @@ export class FunctionsResource {
10
10
  constructor(app) {
11
11
  this.app = app;
12
12
  }
13
- /** POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. */
13
+ /**
14
+ * POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. With
15
+ * `idempotencyKey` the function runs once for that key, and the call is retried like a GET.
16
+ */
14
17
  async call(name, body, options = {}) {
15
- const { query, signal, timeoutMs } = options;
16
- return (await this.app.request({ method: 'POST', path: path(name), json: body, query, signal, timeoutMs }));
18
+ const { query, signal, timeoutMs, idempotencyKey, retries } = options;
19
+ return (await this.app.request({
20
+ method: 'POST',
21
+ path: path(name),
22
+ json: body,
23
+ query,
24
+ signal,
25
+ timeoutMs,
26
+ ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),
27
+ ...(retries !== undefined ? { retries } : {}),
28
+ }));
17
29
  }
18
30
  /** GET /functions/:name (the function reads `query` as `request.query`). Retried with the app's `retries`. */
19
31
  async get(name, query = {}, options = {}) {
@@ -1136,6 +1136,26 @@ export interface paths {
1136
1136
  patch?: never;
1137
1137
  trace?: never;
1138
1138
  };
1139
+ "/projects/{uuid}/queries/{slug}": {
1140
+ parameters: {
1141
+ query?: never;
1142
+ header?: never;
1143
+ path?: never;
1144
+ cookie?: never;
1145
+ };
1146
+ /**
1147
+ * A named query's entries
1148
+ * @description The entries of a query saved in the dashboard (Settings > Named queries), by its slug: its content model, filter and sort are fixed, and the answer is the same as the content list's. The key needs `read`, and database:<db>:read when the query reads a database content model. Page with `limit` and `offset` (`limit` up to the query's page limit, which is also the default). Sending `q`, `where`, `sort` or `filter.*` is 400 `fixed_query`. The `X-VeroXM-Query` header names the query.
1149
+ */
1150
+ get: operations["runNamedQuery"];
1151
+ put?: never;
1152
+ post?: never;
1153
+ delete?: never;
1154
+ options?: never;
1155
+ head?: never;
1156
+ patch?: never;
1157
+ trace?: never;
1158
+ };
1139
1159
  "/forms/{publicId}": {
1140
1160
  parameters: {
1141
1161
  query?: never;
@@ -1290,6 +1310,86 @@ export interface paths {
1290
1310
  patch?: never;
1291
1311
  trace?: never;
1292
1312
  };
1313
+ "/projects/{uuid}/translations": {
1314
+ parameters: {
1315
+ query?: never;
1316
+ header?: never;
1317
+ path?: never;
1318
+ cookie?: never;
1319
+ };
1320
+ /**
1321
+ * The project's locales: names, writing direction and how much is translated
1322
+ * @description Any key of the project, a browser key too. Every answer has an ETag: send it back as If-None-Match and an unchanged answer is a 304 with no body. The project's own address (/projects/{uuid}/...) is cacheable by CDNs; with `v` set to the current version it is cached for a year. The short address (/translations/...) takes the project from the key and is cached by the browser only.
1323
+ */
1324
+ get: operations["listTranslationLocales"];
1325
+ put?: never;
1326
+ post?: never;
1327
+ delete?: never;
1328
+ options?: never;
1329
+ head?: never;
1330
+ patch?: never;
1331
+ trace?: never;
1332
+ };
1333
+ "/projects/{uuid}/translations/{locale}": {
1334
+ parameters: {
1335
+ query?: never;
1336
+ header?: never;
1337
+ path?: never;
1338
+ cookie?: never;
1339
+ };
1340
+ /**
1341
+ * A locale's app translations
1342
+ * @description Any key of the project, a browser key too. Every answer has an ETag: send it back as If-None-Match and an unchanged answer is a 304 with no body. The project's own address (/projects/{uuid}/...) is cacheable by CDNs; with `v` set to the current version it is cached for a year. The short address (/translations/...) takes the project from the key and is cached by the browser only.
1343
+ */
1344
+ get: operations["getTranslations"];
1345
+ put?: never;
1346
+ post?: never;
1347
+ delete?: never;
1348
+ options?: never;
1349
+ head?: never;
1350
+ patch?: never;
1351
+ trace?: never;
1352
+ };
1353
+ "/translations": {
1354
+ parameters: {
1355
+ query?: never;
1356
+ header?: never;
1357
+ path?: never;
1358
+ cookie?: never;
1359
+ };
1360
+ /**
1361
+ * The project's locales: names, writing direction and how much is translated
1362
+ * @description Any key of the project, a browser key too. Every answer has an ETag: send it back as If-None-Match and an unchanged answer is a 304 with no body. The project's own address (/projects/{uuid}/...) is cacheable by CDNs; with `v` set to the current version it is cached for a year. The short address (/translations/...) takes the project from the key and is cached by the browser only.
1363
+ */
1364
+ get: operations["listTranslationLocalesByKey"];
1365
+ put?: never;
1366
+ post?: never;
1367
+ delete?: never;
1368
+ options?: never;
1369
+ head?: never;
1370
+ patch?: never;
1371
+ trace?: never;
1372
+ };
1373
+ "/translations/{locale}": {
1374
+ parameters: {
1375
+ query?: never;
1376
+ header?: never;
1377
+ path?: never;
1378
+ cookie?: never;
1379
+ };
1380
+ /**
1381
+ * A locale's app translations
1382
+ * @description Any key of the project, a browser key too. Every answer has an ETag: send it back as If-None-Match and an unchanged answer is a 304 with no body. The project's own address (/projects/{uuid}/...) is cacheable by CDNs; with `v` set to the current version it is cached for a year. The short address (/translations/...) takes the project from the key and is cached by the browser only.
1383
+ */
1384
+ get: operations["getTranslationsByKey"];
1385
+ put?: never;
1386
+ post?: never;
1387
+ delete?: never;
1388
+ options?: never;
1389
+ head?: never;
1390
+ patch?: never;
1391
+ trace?: never;
1392
+ };
1293
1393
  }
1294
1394
  export type webhooks = Record<string, never>;
1295
1395
  export interface components {
@@ -2380,6 +2480,51 @@ export interface components {
2380
2480
  /** @description Pass as `cursor` for the next page; null at the end. */
2381
2481
  next: string | null;
2382
2482
  };
2483
+ /** @description Texts by key: nested objects (`{ "checkout": { "pay": "Pay {{amount}}" } }`), or dotted keys with `flat=1`. Texts keep i18next placeholders (`{{name}}`, `$t(key)`). */
2484
+ TranslationTexts: {
2485
+ [key: string]: string | components["schemas"]["TranslationTexts"];
2486
+ };
2487
+ TranslationLocale: {
2488
+ /** @description The locale code, e.g. "ar". */
2489
+ code: string;
2490
+ /** @description The project's name for it ("Arabic"). */
2491
+ name: string;
2492
+ /** @description Its own name ("العربية"). */
2493
+ nativeName: string;
2494
+ /**
2495
+ * @description Writing direction.
2496
+ * @enum {string}
2497
+ */
2498
+ dir: "rtl" | "ltr";
2499
+ isDefault: boolean;
2500
+ /** @description Keys of the default locale with a text in this one. */
2501
+ translated: number;
2502
+ /** @description Keys of the default locale. */
2503
+ total: number;
2504
+ };
2505
+ TranslationLocales: {
2506
+ /** @description Rises with every change: send it as `v` for an address cached for a year. */
2507
+ version: number;
2508
+ defaultLocale: string;
2509
+ locales: components["schemas"]["TranslationLocale"][];
2510
+ };
2511
+ TranslationBundle: {
2512
+ /** @description The locale answered: "ar" for a request for "ar-SA" when the project has only "ar". */
2513
+ locale: string;
2514
+ name: string;
2515
+ nativeName: string;
2516
+ /** @enum {string} */
2517
+ dir: "rtl" | "ltr";
2518
+ defaultLocale: string;
2519
+ version: number;
2520
+ /** @description Keys in the bundle. */
2521
+ keys: number;
2522
+ /** @description Keys with a text in this locale. */
2523
+ translated: number;
2524
+ /** @description Keys whose text is the default locale's (not translated yet). */
2525
+ fallback: string[];
2526
+ translations: components["schemas"]["TranslationTexts"];
2527
+ };
2383
2528
  };
2384
2529
  responses: {
2385
2530
  /** @description The request is not valid */
@@ -3594,7 +3739,10 @@ export interface operations {
3594
3739
  /** @description A database content model limited to the caller's rows: whose (project keys). */
3595
3740
  userId?: string;
3596
3741
  };
3597
- header?: never;
3742
+ header?: {
3743
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3744
+ "Idempotency-Key"?: string;
3745
+ };
3598
3746
  path: {
3599
3747
  /** @description The project's UUID. */
3600
3748
  uuid: string;
@@ -3714,7 +3862,10 @@ export interface operations {
3714
3862
  /** @description A database content model limited to the caller's rows: whose (project keys). */
3715
3863
  userId?: string;
3716
3864
  };
3717
- header?: never;
3865
+ header?: {
3866
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3867
+ "Idempotency-Key"?: string;
3868
+ };
3718
3869
  path: {
3719
3870
  /** @description The project's UUID. */
3720
3871
  uuid: string;
@@ -3753,7 +3904,10 @@ export interface operations {
3753
3904
  /** @description A database content model limited to the caller's rows: whose (project keys). */
3754
3905
  userId?: string;
3755
3906
  };
3756
- header?: never;
3907
+ header?: {
3908
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3909
+ "Idempotency-Key"?: string;
3910
+ };
3757
3911
  path: {
3758
3912
  /** @description The project's UUID. */
3759
3913
  uuid: string;
@@ -3822,7 +3976,10 @@ export interface operations {
3822
3976
  uploadMedia: {
3823
3977
  parameters: {
3824
3978
  query?: never;
3825
- header?: never;
3979
+ header?: {
3980
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3981
+ "Idempotency-Key"?: string;
3982
+ };
3826
3983
  path: {
3827
3984
  /** @description The project's UUID. */
3828
3985
  uuid: string;
@@ -3854,7 +4011,10 @@ export interface operations {
3854
4011
  deleteMedia: {
3855
4012
  parameters: {
3856
4013
  query?: never;
3857
- header?: never;
4014
+ header?: {
4015
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
4016
+ "Idempotency-Key"?: string;
4017
+ };
3858
4018
  path: {
3859
4019
  /** @description The project's UUID. */
3860
4020
  uuid: string;
@@ -3882,7 +4042,10 @@ export interface operations {
3882
4042
  updateMediaCaption: {
3883
4043
  parameters: {
3884
4044
  query?: never;
3885
- header?: never;
4045
+ header?: {
4046
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
4047
+ "Idempotency-Key"?: string;
4048
+ };
3886
4049
  path: {
3887
4050
  /** @description The project's UUID. */
3888
4051
  uuid: string;
@@ -3978,7 +4141,10 @@ export interface operations {
3978
4141
  callFunction: {
3979
4142
  parameters: {
3980
4143
  query?: never;
3981
- header?: never;
4144
+ header?: {
4145
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
4146
+ "Idempotency-Key"?: string;
4147
+ };
3982
4148
  path: {
3983
4149
  /** @description The project's UUID. */
3984
4150
  uuid: string;
@@ -4104,7 +4270,10 @@ export interface operations {
4104
4270
  completeTask: {
4105
4271
  parameters: {
4106
4272
  query?: never;
4107
- header?: never;
4273
+ header?: {
4274
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
4275
+ "Idempotency-Key"?: string;
4276
+ };
4108
4277
  path: {
4109
4278
  /** @description The project's UUID. */
4110
4279
  uuid: string;
@@ -4138,7 +4307,10 @@ export interface operations {
4138
4307
  startProcess: {
4139
4308
  parameters: {
4140
4309
  query?: never;
4141
- header?: never;
4310
+ header?: {
4311
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
4312
+ "Idempotency-Key"?: string;
4313
+ };
4142
4314
  path: {
4143
4315
  /** @description The project's UUID. */
4144
4316
  uuid: string;
@@ -4879,6 +5051,48 @@ export interface operations {
4879
5051
  429: components["responses"]["E429"];
4880
5052
  };
4881
5053
  };
5054
+ runNamedQuery: {
5055
+ parameters: {
5056
+ query?: {
5057
+ offset?: number;
5058
+ limit?: number;
5059
+ count?: string;
5060
+ timestamps?: string;
5061
+ locale?: string;
5062
+ state?: string;
5063
+ /** @description A database content model limited to the caller's rows: whose (project keys). `ctx.<name>=` likewise. */
5064
+ userId?: string;
5065
+ };
5066
+ header?: never;
5067
+ path: {
5068
+ /** @description The project's UUID. */
5069
+ uuid: string;
5070
+ /** @description The named query's slug. */
5071
+ slug: string;
5072
+ };
5073
+ cookie?: never;
5074
+ };
5075
+ requestBody?: never;
5076
+ responses: {
5077
+ /** @description OK */
5078
+ 200: {
5079
+ headers: {
5080
+ [name: string]: unknown;
5081
+ };
5082
+ content: {
5083
+ "application/json": components["schemas"]["Entry"][] | number;
5084
+ };
5085
+ };
5086
+ 400: components["responses"]["E400"];
5087
+ 401: components["responses"]["E401"];
5088
+ 403: components["responses"]["E403"];
5089
+ 404: components["responses"]["E404"];
5090
+ 429: components["responses"]["E429"];
5091
+ 502: components["responses"]["E502"];
5092
+ 503: components["responses"]["E503"];
5093
+ 504: components["responses"]["E504"];
5094
+ };
5095
+ };
4882
5096
  getPublicForm: {
4883
5097
  parameters: {
4884
5098
  query?: never;
@@ -4907,7 +5121,10 @@ export interface operations {
4907
5121
  submitFormResponse: {
4908
5122
  parameters: {
4909
5123
  query?: never;
4910
- header?: never;
5124
+ header?: {
5125
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
5126
+ "Idempotency-Key"?: string;
5127
+ };
4911
5128
  path: {
4912
5129
  /** @description The form id (f_...). */
4913
5130
  publicId: string;
@@ -5121,4 +5338,127 @@ export interface operations {
5121
5338
  429: components["responses"]["E429"];
5122
5339
  };
5123
5340
  };
5341
+ listTranslationLocales: {
5342
+ parameters: {
5343
+ query?: never;
5344
+ header?: never;
5345
+ path: {
5346
+ /** @description The project's UUID. */
5347
+ uuid: string;
5348
+ };
5349
+ cookie?: never;
5350
+ };
5351
+ requestBody?: never;
5352
+ responses: {
5353
+ /** @description OK */
5354
+ 200: {
5355
+ headers: {
5356
+ [name: string]: unknown;
5357
+ };
5358
+ content: {
5359
+ "application/json": components["schemas"]["TranslationLocales"];
5360
+ };
5361
+ };
5362
+ 401: components["responses"]["E401"];
5363
+ 403: components["responses"]["E403"];
5364
+ 429: components["responses"]["E429"];
5365
+ };
5366
+ };
5367
+ getTranslations: {
5368
+ parameters: {
5369
+ query?: {
5370
+ /** @description i18next: only the texts (TranslationTexts), as i18next backends load them. */
5371
+ format?: "i18next";
5372
+ /** @description Dotted keys instead of nested objects. */
5373
+ flat?: "1" | "0" | "true" | "false";
5374
+ /** @description Default on: the default locale's text for keys not translated yet. 0: only this locale's own texts. */
5375
+ fallback?: "1" | "0" | "true" | "false";
5376
+ /** @description The current translations version: a long-cached address (a new version is a new address). */
5377
+ v?: number;
5378
+ };
5379
+ header?: never;
5380
+ path: {
5381
+ /** @description The project's UUID. */
5382
+ uuid: string;
5383
+ /** @description A locale of the project; "ar-SA" is answered by "ar" when the project has only "ar". */
5384
+ locale: string;
5385
+ };
5386
+ cookie?: never;
5387
+ };
5388
+ requestBody?: never;
5389
+ responses: {
5390
+ /** @description The bundle, or with format=i18next only its texts */
5391
+ 200: {
5392
+ headers: {
5393
+ [name: string]: unknown;
5394
+ };
5395
+ content: {
5396
+ "application/json": components["schemas"]["TranslationBundle"] | components["schemas"]["TranslationTexts"];
5397
+ };
5398
+ };
5399
+ 401: components["responses"]["E401"];
5400
+ 403: components["responses"]["E403"];
5401
+ 404: components["responses"]["E404"];
5402
+ 429: components["responses"]["E429"];
5403
+ };
5404
+ };
5405
+ listTranslationLocalesByKey: {
5406
+ parameters: {
5407
+ query?: never;
5408
+ header?: never;
5409
+ path?: never;
5410
+ cookie?: never;
5411
+ };
5412
+ requestBody?: never;
5413
+ responses: {
5414
+ /** @description OK */
5415
+ 200: {
5416
+ headers: {
5417
+ [name: string]: unknown;
5418
+ };
5419
+ content: {
5420
+ "application/json": components["schemas"]["TranslationLocales"];
5421
+ };
5422
+ };
5423
+ 401: components["responses"]["E401"];
5424
+ 403: components["responses"]["E403"];
5425
+ 429: components["responses"]["E429"];
5426
+ };
5427
+ };
5428
+ getTranslationsByKey: {
5429
+ parameters: {
5430
+ query?: {
5431
+ /** @description i18next: only the texts (TranslationTexts), as i18next backends load them. */
5432
+ format?: "i18next";
5433
+ /** @description Dotted keys instead of nested objects. */
5434
+ flat?: "1" | "0" | "true" | "false";
5435
+ /** @description Default on: the default locale's text for keys not translated yet. 0: only this locale's own texts. */
5436
+ fallback?: "1" | "0" | "true" | "false";
5437
+ /** @description The current translations version: a long-cached address (a new version is a new address). */
5438
+ v?: number;
5439
+ };
5440
+ header?: never;
5441
+ path: {
5442
+ /** @description A locale of the project; "ar-SA" is answered by "ar" when the project has only "ar". */
5443
+ locale: string;
5444
+ };
5445
+ cookie?: never;
5446
+ };
5447
+ requestBody?: never;
5448
+ responses: {
5449
+ /** @description The bundle, or with format=i18next only its texts */
5450
+ 200: {
5451
+ headers: {
5452
+ [name: string]: unknown;
5453
+ };
5454
+ content: {
5455
+ "application/json": components["schemas"]["TranslationBundle"] | components["schemas"]["TranslationTexts"];
5456
+ };
5457
+ };
5458
+ 401: components["responses"]["E401"];
5459
+ 403: components["responses"]["E403"];
5460
+ 404: components["responses"]["E404"];
5461
+ 429: components["responses"]["E429"];
5462
+ };
5463
+ };
5124
5464
  }
package/dist/http.d.ts CHANGED
@@ -18,7 +18,26 @@ export interface RawRequestOptions extends RequestControl {
18
18
  /** Sent as a `multipart/form-data` body (file uploads) -- fetch sets the boundary Content-Type itself, so never set one manually alongside this. */
19
19
  form?: FormData;
20
20
  headers?: Record<string, string>;
21
- /** Extra attempts for a GET or HEAD that fails in a way worth retrying (see `isRetryable`). Ignored for other methods. */
21
+ /**
22
+ * Extra attempts for a GET or HEAD that fails in a way worth retrying (see `isRetryable`), or for a write sent with
23
+ * an `idempotencyKey`. Ignored for other writes.
24
+ */
25
+ retries?: number;
26
+ /**
27
+ * Sent as `Idempotency-Key`: the server does the write once, and answers a repeat of it (same key, same request,
28
+ * within 24 hours) with the first answer. A write with a key is retried like a GET.
29
+ */
30
+ idempotencyKey?: string;
31
+ }
32
+ /** Writes a retry can't double: the ones that take an `idempotencyKey`. */
33
+ export interface WriteControl extends RequestControl {
34
+ /**
35
+ * Makes retries safe: the server does the write once for this key (any text, 1 to 255 visible characters; a new
36
+ * UUID per write), and a repeat gets the first answer. With a key the write is retried like a GET, with the app's
37
+ * `retries` or this call's.
38
+ */
39
+ idempotencyKey?: string;
40
+ /** Extra attempts, from 0 to 5; only used with `idempotencyKey`. Overrides the app's `retries` for this call. */
22
41
  retries?: number;
23
42
  }
24
43
  /** Throws a RangeError for a `retries` that isn't a whole number from 0 to 5. */
package/dist/http.js CHANGED
@@ -29,8 +29,9 @@ function parseRetryAfter(value) {
29
29
  function isRetryable(err) {
30
30
  if (err instanceof VeroXMTimeoutError)
31
31
  return true;
32
+ // 409 idempotency_in_progress: the first request with the key is still running.
32
33
  if (err instanceof VeroXMApiError)
33
- return RETRY_STATUSES.has(err.status);
34
+ return RETRY_STATUSES.has(err.status) || (err.status === 409 && err.code === 'idempotency_in_progress');
34
35
  // fetch rejects with a TypeError when the network fails (browsers, Node's undici, React Native).
35
36
  return err instanceof TypeError;
36
37
  }
@@ -133,7 +134,10 @@ export async function rawRequest(apiBase, opts, internal = {}) {
133
134
  url.searchParams.set(key, String(value));
134
135
  }
135
136
  }
136
- const headers = { ...opts.headers };
137
+ if (opts.idempotencyKey !== undefined && !/^[\x21-\x7e]{1,255}$/.test(opts.idempotencyKey)) {
138
+ throw new RangeError('idempotencyKey must be 1 to 255 visible characters (no spaces)');
139
+ }
140
+ const headers = { ...opts.headers, ...(opts.idempotencyKey !== undefined ? { 'Idempotency-Key': opts.idempotencyKey } : {}) };
137
141
  let body;
138
142
  if (opts.form) {
139
143
  body = opts.form;
@@ -144,8 +148,9 @@ export async function rawRequest(apiBase, opts, internal = {}) {
144
148
  }
145
149
  const method = opts.method ?? 'GET';
146
150
  const init = { method, headers, body };
147
- // `repeatable` lets a caller vouch for a POST that changes nothing (a GraphQL query).
148
- const repeatable = internal.repeatable ?? REPEATABLE.has(method.toUpperCase());
151
+ // `repeatable` lets a caller vouch for a POST that changes nothing (a GraphQL query). A write with an
152
+ // Idempotency-Key is done once by the server however often it is sent.
153
+ const repeatable = internal.repeatable ?? (REPEATABLE.has(method.toUpperCase()) || opts.idempotencyKey !== undefined);
149
154
  const retries = repeatable ? (opts.retries ?? 0) : 0;
150
155
  const control = { signal: opts.signal, timeoutMs: opts.timeoutMs };
151
156
  for (let n = 0;; n++) {
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export type { PasskeyOptionsJSON, PasskeyProvider } from './passkeys.js';
7
7
  export { createPkce } from './pkce.js';
8
8
  export { ContentResource } from './content.js';
9
9
  export type { ListOptions } from './content.js';
10
- export type { RequestControl } from './http.js';
10
+ export type { RequestControl, WriteControl } from './http.js';
11
11
  export { graphqlRequest, VeroXMGraphQLError } from './graphql.js';
12
12
  export type { GraphQLErrorItem, GraphQLRequestOptions } from './graphql.js';
13
13
  export { MediaResource } from './media.js';
@@ -19,6 +19,8 @@ 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 { TranslationsResource, fetchTranslations, fetchTranslationResource, fetchTranslationLocales, createTranslator, VeroxmI18nextBackend, } from './translations.js';
23
+ export type { FetchTranslationsOptions, TranslationBundle, TranslationBundleOptions, TranslationLocale, TranslationLocales, TranslationTexts, TranslationValues, Translator, VeroxmI18nextBackendOptions, } from './translations.js';
22
24
  export { embedForm, embedFormsFromPage } from './embed.js';
23
25
  export type { FormEmbed, FormEmbedMode, FormEmbedOpenTrigger, FormEmbedOptions, FormEmbedTracker } from './embed.js';
24
26
  export type { Schemas } from './schemas.js';
package/dist/index.js CHANGED
@@ -10,6 +10,8 @@ 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
+ // App translations: a locale's bundle in one request, and a t() for its texts.
14
+ export { TranslationsResource, fetchTranslations, fetchTranslationResource, fetchTranslationLocales, createTranslator, VeroxmI18nextBackend, } from './translations.js';
13
15
  // Showing forms in a page: inline, popup, full page or toast.
14
16
  export { embedForm, embedFormsFromPage } from './embed.js';
15
17
  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.11.0",
3
+ "version": "1.13.0",
4
4
  "description": "VeroXM client for JavaScript and TypeScript: content, media, experiences, events and the visitor tracker.",
5
5
  "keywords": [
6
6
  "veroxm",