@veroxm/sdk 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Typed access to one content collection's entries. `T` is whatever
3
+ * shape you expect back (the API's actual response is a plain object per
4
+ * the collection's own fields, so this is a cast you opt into, not
5
+ * something the SDK can verify -- see your project's SDK Docs tab for
6
+ * that collection's real field list).
7
+ */
8
+ export class ContentResource {
9
+ constructor(app, slug) {
10
+ this.app = app;
11
+ this.slug = slug;
12
+ }
13
+ root() {
14
+ return `/collections/${this.slug}/content`;
15
+ }
16
+ async list(options = {}) {
17
+ return this.app.request({
18
+ path: this.root(),
19
+ query: {
20
+ limit: options.limit,
21
+ offset: options.offset,
22
+ sort: options.sort,
23
+ state: options.state,
24
+ count: options.count ? '1' : undefined,
25
+ timestamps: options.timestamps ? '1' : undefined,
26
+ locale: options.locale,
27
+ },
28
+ });
29
+ }
30
+ /** Same filters as list(), sent as a JSON body -- use this for `where`/`whereRelation`, which are awkward to express as query-string params. */
31
+ async search(options) {
32
+ return this.app.request({
33
+ method: 'POST',
34
+ path: `${this.root()}/search`,
35
+ json: options,
36
+ });
37
+ }
38
+ /** A typed shortcut for search({...options, count: true}) -- the API returns a bare number for a counting query, not a list. */
39
+ async count(options = {}) {
40
+ const result = await this.search({ ...options, count: true });
41
+ return result;
42
+ }
43
+ /**
44
+ * Only ever returns a PUBLISHED record -- the API's single-item lookup
45
+ * has no `state` override, so a draft id 404s here even right after
46
+ * create({draft: true}); use list({state: 'only_draft'}) to find/inspect
47
+ * drafts instead.
48
+ *
49
+ * No `locale` option here (unlike list()/search()/count()) -- `id`
50
+ * already identifies one exact row, which has exactly one locale;
51
+ * there's no "translation of this same id" to select between. To fetch
52
+ * a specific locale's entry, filter list()/search() by whatever field
53
+ * identifies the logical entry (e.g. `slug`) plus `locale`, not by id.
54
+ */
55
+ async get(id, options = {}) {
56
+ return this.app.request({
57
+ path: `${this.root()}/${id}`,
58
+ query: { timestamps: options.timestamps ? '1' : undefined },
59
+ });
60
+ }
61
+ /** Fields are sent flat (no wrapper). Pass `draft: true` to create without publishing; omit it (or pass false) to publish immediately. */
62
+ async create(data) {
63
+ return this.app.request({ method: 'POST', path: this.root(), json: data });
64
+ }
65
+ /**
66
+ * A partial update -- only the fields present in `data` are changed.
67
+ * Publish state follows the same rule as create(): omitting `draft` (or
68
+ * passing `draft: false`) PUBLISHES the record immediately, even if it
69
+ * was previously a draft and this update doesn't touch content fields.
70
+ * Pass `draft: true` explicitly to keep (or return) it unpublished.
71
+ */
72
+ async update(id, data) {
73
+ return this.app.request({ method: 'PATCH', path: `${this.root()}/${id}`, json: data });
74
+ }
75
+ async delete(id) {
76
+ await this.app.request({ method: 'DELETE', path: `${this.root()}/${id}` });
77
+ }
78
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Thrown for any non-2xx response from the VeroXM public API. Carries the
3
+ * HTTP status and whatever the API's own error body contained -- every
4
+ * route in this API returns errors as either `{ error: string }` (the
5
+ * shape NestJS's various *Exception classes use when constructed with a
6
+ * plain object, e.g. `new UnauthorizedException({ error: '...' })`) or
7
+ * the framework's own default `{ statusCode, message, error }` shape for
8
+ * anything Nest itself rejects.
9
+ */
10
+ export declare class VeroXMApiError extends Error {
11
+ readonly status: number;
12
+ readonly body: unknown;
13
+ constructor(status: number, body: unknown);
14
+ private static messageFrom;
15
+ }
16
+ /** Thrown when a request needs an authenticated client but no credentials have been provided yet. */
17
+ export declare class VeroXMNotAuthenticatedError extends Error {
18
+ constructor();
19
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Thrown for any non-2xx response from the VeroXM public API. Carries the
3
+ * HTTP status and whatever the API's own error body contained -- every
4
+ * route in this API returns errors as either `{ error: string }` (the
5
+ * shape NestJS's various *Exception classes use when constructed with a
6
+ * plain object, e.g. `new UnauthorizedException({ error: '...' })`) or
7
+ * the framework's own default `{ statusCode, message, error }` shape for
8
+ * anything Nest itself rejects.
9
+ */
10
+ export class VeroXMApiError extends Error {
11
+ constructor(status, body) {
12
+ super(VeroXMApiError.messageFrom(status, body));
13
+ this.name = 'VeroXMApiError';
14
+ this.status = status;
15
+ this.body = body;
16
+ }
17
+ static messageFrom(status, body) {
18
+ if (body && typeof body === 'object') {
19
+ const b = body;
20
+ if (typeof b.error === 'string')
21
+ return b.error;
22
+ if (typeof b.message === 'string')
23
+ return b.message;
24
+ if (Array.isArray(b.message))
25
+ return b.message.join(', ');
26
+ if (b.errors)
27
+ return JSON.stringify(b.errors);
28
+ }
29
+ return `Request failed with status ${status}`;
30
+ }
31
+ }
32
+ /** Thrown when a request needs an authenticated client but no credentials have been provided yet. */
33
+ export class VeroXMNotAuthenticatedError extends Error {
34
+ constructor() {
35
+ super('Not signed in -- call auth.signInWithCredentials() or auth.signInWithApiKey() first.');
36
+ this.name = 'VeroXMNotAuthenticatedError';
37
+ }
38
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export interface RawRequestOptions {
2
+ method?: string;
3
+ /** Path relative to the client's api base, e.g. "/auth/token" or "/collections/posts/content". */
4
+ path: string;
5
+ query?: Record<string, string | number | boolean | undefined>;
6
+ /** Sent as an `application/json` body. Mutually exclusive with `form`. */
7
+ json?: unknown;
8
+ /** Sent as a `multipart/form-data` body (file uploads) -- fetch sets the boundary Content-Type itself, so never set one manually alongside this. */
9
+ form?: FormData;
10
+ headers?: Record<string, string>;
11
+ }
12
+ /**
13
+ * The one place an HTTP request actually goes out. Deliberately built on
14
+ * the platform's own global `fetch`/`FormData` -- available in every
15
+ * environment this SDK targets (browsers, Node 18+, React Native 0.71+)
16
+ * without adding a runtime dependency the way `axios` or `dio`-equivalent
17
+ * libraries would.
18
+ */
19
+ export declare function rawRequest(apiBase: string, opts: RawRequestOptions): Promise<unknown>;
package/dist/http.js ADDED
@@ -0,0 +1,42 @@
1
+ import { VeroXMApiError } from './errors.js';
2
+ function safeJsonParse(text) {
3
+ try {
4
+ return JSON.parse(text);
5
+ }
6
+ catch {
7
+ return text;
8
+ }
9
+ }
10
+ /**
11
+ * The one place an HTTP request actually goes out. Deliberately built on
12
+ * the platform's own global `fetch`/`FormData` -- available in every
13
+ * environment this SDK targets (browsers, Node 18+, React Native 0.71+)
14
+ * without adding a runtime dependency the way `axios` or `dio`-equivalent
15
+ * libraries would.
16
+ */
17
+ export async function rawRequest(apiBase, opts) {
18
+ const base = apiBase.endsWith('/') ? apiBase : `${apiBase}/`;
19
+ const url = new URL(opts.path.replace(/^\//, ''), base);
20
+ if (opts.query) {
21
+ for (const [key, value] of Object.entries(opts.query)) {
22
+ if (value !== undefined)
23
+ url.searchParams.set(key, String(value));
24
+ }
25
+ }
26
+ const headers = { ...opts.headers };
27
+ let body;
28
+ if (opts.form) {
29
+ body = opts.form;
30
+ }
31
+ else if (opts.json !== undefined) {
32
+ headers['Content-Type'] = 'application/json';
33
+ body = JSON.stringify(opts.json);
34
+ }
35
+ const res = await fetch(url.toString(), { method: opts.method ?? 'GET', headers, body });
36
+ const text = await res.text();
37
+ const parsed = text ? safeJsonParse(text) : null;
38
+ if (!res.ok) {
39
+ throw new VeroXMApiError(res.status, parsed ?? text);
40
+ }
41
+ return parsed;
42
+ }
@@ -0,0 +1,12 @@
1
+ export { VeroXMApp } from './client.js';
2
+ export type { VeroXMAppOptions } from './client.js';
3
+ export { VeroXMAuth } from './auth.js';
4
+ export { ContentResource } from './content.js';
5
+ export type { ListOptions } from './content.js';
6
+ export { MediaResource } from './media.js';
7
+ export type { MediaItem, MediaPage, UploadableFile } from './media.js';
8
+ export { VeroXMApiError, VeroXMNotAuthenticatedError } from './errors.js';
9
+ export { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
10
+ export type { TokenStorage, StoredSession } from './token-storage.js';
11
+ export { VeroxmTracker, createTracker } from './tracker.js';
12
+ export type { TrackerOptions, TrackerStorage, ConsentChoices, ConsentValue, StoredConsent, ExperienceDecision, GetExperienceOptions, Recommendations, } from './tracker.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { VeroXMApp } from './client.js';
2
+ export { VeroXMAuth } from './auth.js';
3
+ export { ContentResource } from './content.js';
4
+ export { MediaResource } from './media.js';
5
+ export { VeroXMApiError, VeroXMNotAuthenticatedError } from './errors.js';
6
+ export { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
7
+ // Experience OS visitor tracking (page views, actions, consent, identify).
8
+ export { VeroxmTracker, createTracker } from './tracker.js';
@@ -0,0 +1,40 @@
1
+ import type { VeroXMApp } from './client.js';
2
+ export interface MediaItem {
3
+ id: number;
4
+ fileName: string;
5
+ fullUrl: string;
6
+ thumbUrl: string | null;
7
+ caption: string | null;
8
+ size: number | null;
9
+ width: number | null;
10
+ height: number | null;
11
+ }
12
+ export interface MediaPage {
13
+ data: MediaItem[];
14
+ page: number;
15
+ perPage: number;
16
+ total: number;
17
+ }
18
+ /**
19
+ * A Blob/File (browser -- e.g. straight from an `<input type="file">` or
20
+ * `fetch()` response) uploads as-is; the `{data, filename}` form covers
21
+ * Node/React Native, where raw bytes usually arrive as an ArrayBuffer or
22
+ * Uint8Array rather than a Blob.
23
+ */
24
+ export type UploadableFile = Blob | {
25
+ data: Blob | ArrayBuffer | Uint8Array;
26
+ filename: string;
27
+ contentType?: string;
28
+ };
29
+ export declare class MediaResource {
30
+ private readonly app;
31
+ constructor(app: VeroXMApp);
32
+ list(options?: {
33
+ page?: number;
34
+ search?: string;
35
+ }): Promise<MediaPage>;
36
+ /** Images are thumbnailed server-side automatically; other file types are stored as-is. Max size is whatever this project's server allows (commonly 20MB). */
37
+ upload(file: UploadableFile, caption?: string): Promise<MediaItem>;
38
+ updateCaption(id: number, caption: string): Promise<MediaItem>;
39
+ delete(id: number): Promise<void>;
40
+ }
package/dist/media.js ADDED
@@ -0,0 +1,40 @@
1
+ export class MediaResource {
2
+ constructor(app) {
3
+ this.app = app;
4
+ }
5
+ async list(options = {}) {
6
+ return this.app.request({
7
+ path: '/media',
8
+ query: { page: options.page, search: options.search },
9
+ });
10
+ }
11
+ /** Images are thumbnailed server-side automatically; other file types are stored as-is. Max size is whatever this project's server allows (commonly 20MB). */
12
+ async upload(file, caption) {
13
+ const form = new FormData();
14
+ if (file instanceof Blob) {
15
+ form.append('file', file);
16
+ }
17
+ else {
18
+ // TS's DOM lib types Uint8Array as generic over ArrayBufferLike (which
19
+ // includes SharedArrayBuffer), which BlobPart's own typing doesn't
20
+ // accept -- a type-checker-only mismatch, not a real runtime one,
21
+ // since both an ArrayBuffer and any ArrayBufferView are valid Blob
22
+ // constructor parts in every actual runtime this SDK targets.
23
+ const blob = file.data instanceof Blob ? file.data : new Blob([file.data], { type: file.contentType });
24
+ form.append('file', blob, file.filename);
25
+ }
26
+ if (caption)
27
+ form.append('caption', caption);
28
+ return this.app.request({ method: 'POST', path: '/media/upload', form });
29
+ }
30
+ async updateCaption(id, caption) {
31
+ return this.app.request({
32
+ method: 'PATCH',
33
+ path: `/media/${id}`,
34
+ json: { caption },
35
+ });
36
+ }
37
+ async delete(id) {
38
+ await this.app.request({ method: 'DELETE', path: `/media/${id}` });
39
+ }
40
+ }
@@ -0,0 +1,43 @@
1
+ export interface StoredSession {
2
+ accessToken: string;
3
+ refreshToken: string | null;
4
+ /** Epoch ms this access token stops being valid. */
5
+ expiresAt: number;
6
+ abilities: string[];
7
+ }
8
+ /**
9
+ * Where the SDK persists the current session between calls -- mirrors how
10
+ * Firebase Auth needs a platform-specific persistence layer, except here
11
+ * it's a plain three-method interface instead of a whole plugin system.
12
+ * `MemoryTokenStorage` (used automatically outside a browser) only lasts
13
+ * for the life of the VeroXMApp instance; `BrowserLocalStorageTokenStorage`
14
+ * (used automatically when `window.localStorage` exists) survives a page
15
+ * reload. For Node/React Native code that wants disk persistence across
16
+ * process restarts, implement this interface against whatever storage
17
+ * that environment offers and pass it as `tokenStorage` to initializeApp().
18
+ */
19
+ export interface TokenStorage {
20
+ get(): Promise<StoredSession | null>;
21
+ set(session: StoredSession): Promise<void>;
22
+ clear(): Promise<void>;
23
+ }
24
+ export declare class MemoryTokenStorage implements TokenStorage {
25
+ private session;
26
+ get(): Promise<StoredSession | null>;
27
+ set(session: StoredSession): Promise<void>;
28
+ clear(): Promise<void>;
29
+ }
30
+ /**
31
+ * Persists the session in `window.localStorage` under a project-scoped
32
+ * key, so a signed-in user stays signed in across a page reload -- the
33
+ * same convenience Firebase Auth's default browser persistence gives you.
34
+ * VeroXMApp.initializeApp picks this automatically when `window.localStorage`
35
+ * is present and no `tokenStorage` option was given.
36
+ */
37
+ export declare class BrowserLocalStorageTokenStorage implements TokenStorage {
38
+ private readonly key;
39
+ constructor(projectId: string);
40
+ get(): Promise<StoredSession | null>;
41
+ set(session: StoredSession): Promise<void>;
42
+ clear(): Promise<void>;
43
+ }
@@ -0,0 +1,43 @@
1
+ export class MemoryTokenStorage {
2
+ constructor() {
3
+ this.session = null;
4
+ }
5
+ async get() {
6
+ return this.session;
7
+ }
8
+ async set(session) {
9
+ this.session = session;
10
+ }
11
+ async clear() {
12
+ this.session = null;
13
+ }
14
+ }
15
+ /**
16
+ * Persists the session in `window.localStorage` under a project-scoped
17
+ * key, so a signed-in user stays signed in across a page reload -- the
18
+ * same convenience Firebase Auth's default browser persistence gives you.
19
+ * VeroXMApp.initializeApp picks this automatically when `window.localStorage`
20
+ * is present and no `tokenStorage` option was given.
21
+ */
22
+ export class BrowserLocalStorageTokenStorage {
23
+ constructor(projectId) {
24
+ this.key = `veroxm:session:${projectId}`;
25
+ }
26
+ async get() {
27
+ const raw = window.localStorage.getItem(this.key);
28
+ if (!raw)
29
+ return null;
30
+ try {
31
+ return JSON.parse(raw);
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ async set(session) {
38
+ window.localStorage.setItem(this.key, JSON.stringify(session));
39
+ }
40
+ async clear() {
41
+ window.localStorage.removeItem(this.key);
42
+ }
43
+ }
@@ -0,0 +1,149 @@
1
+ export interface TrackerStorage {
2
+ get(key: string): string | null;
3
+ set(key: string, value: string): void;
4
+ remove(key: string): void;
5
+ }
6
+ export interface TrackerOptions {
7
+ /** Your VeroXM API origin, e.g. "https://cms.example.com". */
8
+ baseUrl: string;
9
+ /** The project's UUID. */
10
+ projectId: string;
11
+ /** An API key with only the "Send events" (events:write) permission. */
12
+ eventsKey: string;
13
+ /** Hold everything until analytics consent is granted (default true). */
14
+ requireConsent?: boolean;
15
+ /** How often queued events are sent (default 5000 ms). */
16
+ flushIntervalMs?: number;
17
+ /** Where the visitor id, consent and unsent events are kept. Defaults to localStorage in browsers, memory elsewhere. */
18
+ storage?: TrackerStorage;
19
+ /** Called when a request fails for good (a rejected batch, a bad key). Defaults to console.warn. */
20
+ onError?: (error: Error) => void;
21
+ }
22
+ export interface ConsentChoices {
23
+ analytics?: boolean;
24
+ personalization?: boolean;
25
+ /** Emails from journeys (marketing). Separate from personalisation. */
26
+ marketing?: boolean;
27
+ }
28
+ export type ConsentValue = 'granted' | 'denied' | 'unknown';
29
+ export interface StoredConsent {
30
+ analytics: ConsentValue;
31
+ personalization: ConsentValue;
32
+ marketing: ConsentValue;
33
+ }
34
+ /** What GET /decide answered for a placement (see getExperience). */
35
+ export interface ExperienceDecision<TContent = Record<string, unknown>, TConfig = Record<string, unknown>> {
36
+ placement: string;
37
+ experienceId: number | null;
38
+ variantId: number | null;
39
+ variant: {
40
+ label: string;
41
+ isControl: boolean;
42
+ } | null;
43
+ /** "targeted" (a segment matched), "split" (weighted share) or "none" (show your default). */
44
+ /** journey = an in-app message a journey left for this person (config only). */
45
+ reason: 'targeted' | 'split' | 'journey' | 'none';
46
+ /** The variant's entry, shaped like the content API's entries; null for "none" or a config-only variant. */
47
+ content: TContent | null;
48
+ /** The variant's config (copy, flags); null if it has none. */
49
+ config: TConfig | null;
50
+ /** True when no request was made because analytics consent isn't granted yet. */
51
+ waitingForConsent?: boolean;
52
+ /** Set when the request failed or timed out (the decision is then "none"). */
53
+ error?: string;
54
+ }
55
+ /** GET /recommendations: entries of a collection ranked for this visitor. */
56
+ export interface Recommendations<TEntry = Record<string, unknown>> {
57
+ /** 'personal' = from what this person and similar visitors viewed; 'popular' = the most read. */
58
+ strategy: 'personal' | 'popular';
59
+ items: TEntry[];
60
+ /** Set when the request failed (items is then empty). */
61
+ error?: string;
62
+ }
63
+ export interface GetExperienceOptions {
64
+ /** Give up and resolve to "none" after this long (default 1500 ms). */
65
+ timeoutMs?: number;
66
+ }
67
+ export declare class VeroxmTracker {
68
+ private readonly apiBase;
69
+ private readonly key;
70
+ private readonly requireConsent;
71
+ private readonly storage;
72
+ private readonly memory;
73
+ private readonly onError;
74
+ private readonly keys;
75
+ private visitorId;
76
+ private consentState;
77
+ private queue;
78
+ private timer;
79
+ private sending;
80
+ private backoffMs;
81
+ private retryAt;
82
+ private decisions;
83
+ private readonly listeners;
84
+ constructor(options: TrackerOptions);
85
+ /** The anonymous id for this browser/app install. */
86
+ getVisitorId(): string;
87
+ /** The visitor's stored answers, so you know whether to show your consent banner (`'unknown'` = not asked yet). */
88
+ getConsent(): StoredConsent;
89
+ /** Records an action, e.g. track('demo_requested', { plan: 'enterprise' }). */
90
+ track(name: string, properties?: Record<string, unknown>): void;
91
+ /** Records a page or screen view. In a browser, path/url/title/referrer are added automatically. */
92
+ page(properties?: Record<string, unknown>): void;
93
+ /** Saves the visitor's consent answers (true = granted, false = denied, omitted = unchanged). */
94
+ consent(choices: ConsentChoices): Promise<void>;
95
+ /** Links this visitor to your own user id (e.g. after sign-in) and updates their traits. Needs analytics consent. */
96
+ identify(userId: string, traits?: Record<string, unknown>): Promise<void>;
97
+ /** Call on sign-out: starts a new anonymous visitor on this device. Consent answers are kept. */
98
+ reset(): void;
99
+ /**
100
+ * Which variant of a placement this visitor sees, e.g.
101
+ * `const d = await tracker.getExperience('home.hero')` -- then render
102
+ * `d.content` / `d.config`, or your default when `d.reason === 'none'`.
103
+ * Never rejects. Cached per placement until the visitor changes.
104
+ */
105
+ getExperience<TContent = Record<string, unknown>, TConfig = Record<string, unknown>>(placement: string, options?: GetExperienceOptions): Promise<ExperienceDecision<TContent, TConfig>>;
106
+ /**
107
+ * Records that the visitor viewed a CMS entry -- the signal behind
108
+ * personal recommendations ("people who read this also read").
109
+ */
110
+ viewContent(contentId: number, properties?: Record<string, unknown>): void;
111
+ /**
112
+ * Entries of a collection for this visitor: ranked from what they and
113
+ * similar visitors viewed when they allowed personalisation (and have
114
+ * some history), otherwise the most read. Never rejects. Works before
115
+ * consent too -- it then returns the popular ranking.
116
+ */
117
+ getRecommendations<TEntry = Record<string, unknown>>(collection: string, options?: {
118
+ limit?: number;
119
+ exclude?: number[];
120
+ timeoutMs?: number;
121
+ }): Promise<Recommendations<TEntry>>;
122
+ /**
123
+ * A feature flag or setting from a config-only experience:
124
+ * `await tracker.getFlag('checkout.flags', 'newCheckout', false)` reads
125
+ * `config.newCheckout` of this visitor's variant, else the fallback.
126
+ */
127
+ getFlag<T>(placement: string, key: string, fallback: T): Promise<T>;
128
+ /** Called when consent, identity or the visitor changes -- ask for experiences again. Returns an unsubscribe function. */
129
+ subscribe(listener: () => void): () => void;
130
+ /** Sends queued events now. Resolves when done (or deferred by a backoff). */
131
+ flush(opts?: {
132
+ keepalive?: boolean;
133
+ }): Promise<void>;
134
+ /** Stops the timer (tests, or a single-page app tearing the tracker down). */
135
+ shutdown(): void;
136
+ private changed;
137
+ private sendAll;
138
+ private enqueue;
139
+ private post;
140
+ private canSend;
141
+ /** Whether anything may be written to the device. */
142
+ private canPersist;
143
+ private store;
144
+ private readConsent;
145
+ private readQueue;
146
+ private saveQueue;
147
+ }
148
+ /** Creates a tracker. One per page/app; see VeroxmTracker for the API. */
149
+ export declare function createTracker(options: TrackerOptions): VeroxmTracker;