@@ -0,0 +1,159 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { getScenarioRuntime, RudderClient } from '../../src/client/RudderClient.js';
|
||||
import { createFakeTokenStore } from '../helpers/FakeTokenStore.js';
|
||||
import { createFakeGateway, type FakeGateway } from '../helpers/fakeGateway.js';
|
||||
import { stubDeterministicUuid } from '../helpers/memoryPlanStore.js';
|
||||
import { plan } from '../helpers/plan.js';
|
||||
import type { StoreOfferEffect } from '../../src/index.js';
|
||||
import type { PlanRun, ScenarioRunFailedEvent } from '../../src/scenario/engine/types.js';
|
||||
|
||||
function makeClient(): RudderClient {
|
||||
return new RudderClient({
|
||||
baseUrl: 'https://api.test.rudder.build',
|
||||
projectKey: 'test-project',
|
||||
tokenStore: createFakeTokenStore(),
|
||||
runtime: { planStateStore: null },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* An offer whose `onPurchase` continuation lives server-side (boundary node):
|
||||
* the client doesn't hold the post-purchase DAG — it must call back so the
|
||||
* server can validate the transaction and decide what happens next.
|
||||
*
|
||||
* `onDecline`, by contrast, is a plain local edge handled entirely on-device.
|
||||
*/
|
||||
function offerWithBoundary() {
|
||||
return plan('offer_flow')
|
||||
.runId('offer_flow-run')
|
||||
.node('offer', 'store', { storeSlug: 'starter', message: 'Buy the starter pack!' })
|
||||
.node('consolation', 'notification', { message: 'Maybe next time!' })
|
||||
.edge('offer', 'onDecline', 'consolation')
|
||||
.boundary('offer', 'onPurchase') // server owns what comes after a purchase
|
||||
.build();
|
||||
}
|
||||
|
||||
/** What the server returns from the callback — a fresh plan = a new run. */
|
||||
function rewardContinuation() {
|
||||
return plan('reward_flow')
|
||||
.runId('reward_flow-run')
|
||||
.node('reward', 'notification', { message: 'Reward granted: 500 gems!' })
|
||||
.build();
|
||||
}
|
||||
|
||||
describe('E2E: boundary nodes (server-side continuation)', () => {
|
||||
let gateway: FakeGateway;
|
||||
let client: RudderClient;
|
||||
|
||||
beforeEach(() => {
|
||||
stubDeterministicUuid();
|
||||
gateway = createFakeGateway({
|
||||
stores: [{
|
||||
slug: 'starter',
|
||||
name: 'Starter',
|
||||
offers: [{ id: 'pack_1', name: 'Starter Pack' }],
|
||||
}],
|
||||
});
|
||||
gateway.install();
|
||||
client = makeClient();
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('purchase crosses the boundary → callback fires and continues the scenario', async () => {
|
||||
gateway.onEvent('player_login', offerWithBoundary());
|
||||
gateway.onCallback('offer', 'onPurchase', rewardContinuation());
|
||||
|
||||
const messages: string[] = [];
|
||||
const completed: PlanRun[] = [];
|
||||
let offer: StoreOfferEffect | undefined;
|
||||
const runtime = await getScenarioRuntime(client);
|
||||
client.effects.onStoreOffer((effect) => { offer = effect; });
|
||||
client.effects.onNotification((effect) => { messages.push(effect.message); });
|
||||
runtime.onRunCompleted = (r) => completed.push(r);
|
||||
|
||||
const token = (await client.auth.loginWithDevice()).accessToken;
|
||||
await vi.waitFor(() => expect(offer).toBeDefined());
|
||||
|
||||
await offer!.buy(offer!.offers[0]);
|
||||
|
||||
// The callback hit the gateway with the boundary's source node/handle + token.
|
||||
const callback = gateway.recorded.find((r) => r.path === '/sdk/v1/scenarios/callback');
|
||||
expect(callback?.body).toEqual({ scenarioId: 'offer_flow', nodeId: 'offer', handle: 'onPurchase', runId: 'offer_flow-run' });
|
||||
expect(callback?.authToken).toBe(token);
|
||||
|
||||
// The server-supplied continuation ran (as a new run), not the local edge.
|
||||
expect(messages).toEqual(['Reward granted: 500 gems!']);
|
||||
expect(messages).not.toContain('Maybe next time!');
|
||||
|
||||
// The original run finished; the continuation ('reward_flow') is now active.
|
||||
expect(completed.map((r) => r.scenarioId)).toContain('offer_flow');
|
||||
expect(runtime.activeRuns.map((r) => r.scenarioId)).toEqual(['reward_flow']);
|
||||
});
|
||||
|
||||
it('decline stays local → no callback, local edge is followed', async () => {
|
||||
gateway.onEvent('player_login', offerWithBoundary());
|
||||
|
||||
const messages: string[] = [];
|
||||
let offer: StoreOfferEffect | undefined;
|
||||
client.effects.onStoreOffer((effect) => { offer = effect; });
|
||||
client.effects.onNotification((effect) => { messages.push(effect.message); });
|
||||
|
||||
await client.auth.loginWithDevice();
|
||||
await vi.waitFor(() => expect(offer).toBeDefined());
|
||||
await offer!.dismiss();
|
||||
|
||||
expect(gateway.recorded.some((r) => r.path === '/sdk/v1/scenarios/callback')).toBe(false);
|
||||
expect(messages).toEqual(['Maybe next time!']);
|
||||
});
|
||||
|
||||
it('a boundary takes precedence over a local edge on the SAME handle', async () => {
|
||||
// `offer` has BOTH a boundary AND a local edge on onPurchase.
|
||||
const conflicting = plan('offer_flow')
|
||||
.runId('offer_flow-conflict')
|
||||
.node('offer', 'store', { storeSlug: 'starter', message: 'Buy!' })
|
||||
.node('local_next', 'notification', { message: 'LOCAL branch' })
|
||||
.edge('offer', 'onPurchase', 'local_next')
|
||||
.boundary('offer', 'onPurchase')
|
||||
.build();
|
||||
gateway.onEvent('player_login', conflicting);
|
||||
gateway.onCallback('offer', 'onPurchase', rewardContinuation());
|
||||
|
||||
const messages: string[] = [];
|
||||
let offer: StoreOfferEffect | undefined;
|
||||
client.effects.onStoreOffer((effect) => { offer = effect; });
|
||||
client.effects.onNotification((effect) => { messages.push(effect.message); });
|
||||
|
||||
await client.auth.loginWithDevice();
|
||||
await vi.waitFor(() => expect(offer).toBeDefined());
|
||||
await offer!.buy(offer!.offers[0]);
|
||||
|
||||
// Only the server continuation ran; the local edge was suppressed.
|
||||
expect(messages).toEqual(['Reward granted: 500 gems!']);
|
||||
expect(messages).not.toContain('LOCAL branch');
|
||||
});
|
||||
|
||||
it('a failing callback does not fail or crash the run', async () => {
|
||||
gateway.onEvent('player_login', offerWithBoundary());
|
||||
gateway.onCallbackError('offer', 'onPurchase', 500);
|
||||
|
||||
const failures: ScenarioRunFailedEvent[] = [];
|
||||
const completed: PlanRun[] = [];
|
||||
let offer: StoreOfferEffect | undefined;
|
||||
const runtime = await getScenarioRuntime(client);
|
||||
client.effects.onStoreOffer((effect) => { offer = effect; });
|
||||
runtime.onRunFailed = (e) => failures.push(e);
|
||||
runtime.onRunCompleted = (r) => completed.push(r);
|
||||
|
||||
await client.auth.loginWithDevice();
|
||||
await vi.waitFor(() => expect(offer).toBeDefined());
|
||||
|
||||
// Must not throw despite the 500 from the callback endpoint.
|
||||
await expect(offer!.buy(offer!.offers[0])).resolves.toMatchObject({ success: true });
|
||||
|
||||
expect(failures).toHaveLength(0); // 500 is transient — no terminal failure
|
||||
// The run stays pending because the boundary call failed transiently.
|
||||
// On reconnection the consumer can retry the purchase completion.
|
||||
expect(runtime.isRunning).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { RudderClient } from '../../src/client/RudderClient.js';
|
||||
import { createFakeTokenStore } from '../helpers/FakeTokenStore.js';
|
||||
import { createFakeGateway, type FakeGateway } from '../helpers/fakeGateway.js';
|
||||
import { stubDeterministicUuid } from '../helpers/memoryPlanStore.js';
|
||||
import { plan } from '../helpers/plan.js';
|
||||
import type { NotificationEffect, StoreOfferEffect } from '../../src/index.js';
|
||||
|
||||
const MINUTE = 60_000;
|
||||
|
||||
function makeClient(): RudderClient {
|
||||
return new RudderClient({
|
||||
baseUrl: 'https://api.test.rudder.build',
|
||||
projectKey: 'test-project',
|
||||
tokenStore: createFakeTokenStore(),
|
||||
runtime: { planStateStore: null }, // exercised separately in the persistence test
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The offer scenario both branches share:
|
||||
*
|
||||
* login → wait 1m → offer ──onDecline──→ wait 1m → "still available"
|
||||
* └─onPurchase─→ "thanks for your purchase"
|
||||
*/
|
||||
function offerScenario() {
|
||||
return plan('offer_flow')
|
||||
.node('wait_intro', 'wait', { duration: 1, unit: 'minutes' })
|
||||
.node('offer', 'store', { storeSlug: 'starter', offerId: 'pack_1', message: 'Limited starter pack!' })
|
||||
.node('wait_reminder', 'wait', { duration: 1, unit: 'minutes' })
|
||||
.node('reminder', 'notification', { message: 'Your offer is still available!' })
|
||||
.node('thanks', 'notification', { message: 'Thanks for your purchase!' })
|
||||
.edge('wait_intro', 'onComplete', 'offer')
|
||||
.edge('offer', 'onDecline', 'wait_reminder')
|
||||
.edge('wait_reminder', 'onComplete', 'reminder')
|
||||
.edge('offer', 'onPurchase', 'thanks')
|
||||
.build();
|
||||
}
|
||||
|
||||
describe('E2E: player offer journey', () => {
|
||||
let gateway: FakeGateway;
|
||||
let client: RudderClient;
|
||||
|
||||
beforeEach(() => {
|
||||
stubDeterministicUuid();
|
||||
vi.useFakeTimers();
|
||||
gateway = createFakeGateway({
|
||||
stores: [{
|
||||
slug: 'starter',
|
||||
name: 'Starter',
|
||||
offers: [{ id: 'pack_1', name: 'Starter Pack' }],
|
||||
}],
|
||||
});
|
||||
gateway.install();
|
||||
client = makeClient();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('authenticates the device and persists tokens for later calls', async () => {
|
||||
const res = await client.auth.loginWithDevice({ region: 'eu', language: 'en' });
|
||||
|
||||
expect(res.accessToken).toBeTruthy();
|
||||
expect(client.options.tokenStore.getAccessToken()).toBe(res.accessToken);
|
||||
|
||||
// The login request carried the project key + a device id.
|
||||
const login = gateway.recorded.find((r) => r.path === '/sdk/v1/authorization/device');
|
||||
expect(login?.body).toMatchObject({ key: 'test-project', region: 'eu', language: 'en' });
|
||||
expect((login?.body as { deviceId?: string }).deviceId).toBeTruthy();
|
||||
|
||||
// The post-login runtime trigger carries the bearer token.
|
||||
const trigger = gateway.recorded.find((r) => r.path === '/sdk/v1/scenarios/trigger');
|
||||
expect(trigger?.authToken).toBe(res.accessToken);
|
||||
});
|
||||
|
||||
it('offer appears after 1 min, player declines, reminder fires 1 min later', async () => {
|
||||
gateway.onEvent('player_login', offerScenario());
|
||||
|
||||
const notifications: NotificationEffect[] = [];
|
||||
let offer: StoreOfferEffect | undefined;
|
||||
client.effects.onStoreOffer((effect) => { offer = effect; });
|
||||
client.effects.onNotification((effect) => { notifications.push(effect); });
|
||||
|
||||
await client.auth.loginWithDevice();
|
||||
|
||||
// Immediately after login the player is just waiting — no offer yet.
|
||||
expect(offer).toBeUndefined();
|
||||
|
||||
// The offer must NOT appear before the full minute has elapsed...
|
||||
await vi.advanceTimersByTimeAsync(MINUTE - 1_000);
|
||||
expect(offer).toBeUndefined();
|
||||
|
||||
// ...and surfaces exactly when the minute is up.
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
await vi.waitFor(() => expect(offer).toBeDefined());
|
||||
expect(offer!.message).toBe('Limited starter pack!');
|
||||
|
||||
// Player declines → the DAG moves to the reminder wait, no notification yet.
|
||||
await offer!.dismiss();
|
||||
expect(notifications).toHaveLength(0);
|
||||
|
||||
// The reminder also honours the full minute, not a moment sooner.
|
||||
await vi.advanceTimersByTimeAsync(MINUTE - 1_000);
|
||||
expect(notifications).toHaveLength(0);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(notifications).toHaveLength(1);
|
||||
expect(notifications[0].message).toBe('Your offer is still available!');
|
||||
});
|
||||
|
||||
it('offer appears, player buys → "thanks" branch, and the purchase transacts', async () => {
|
||||
gateway.onEvent('player_login', offerScenario());
|
||||
|
||||
let offer: StoreOfferEffect | undefined;
|
||||
const notifications: NotificationEffect[] = [];
|
||||
client.effects.onStoreOffer((effect) => { offer = effect; });
|
||||
client.effects.onNotification((effect) => { notifications.push(effect); });
|
||||
|
||||
const accessToken = (await client.auth.loginWithDevice()).accessToken;
|
||||
await vi.advanceTimersByTimeAsync(MINUTE);
|
||||
await vi.waitFor(() => expect(offer).toBeDefined());
|
||||
|
||||
// The game buys a selected offer; the session advances only after success.
|
||||
const selectedOffer = offer!.offers[0];
|
||||
const purchase = await offer!.buy(selectedOffer, { idempotencyKey: 'idem-key-123' });
|
||||
expect(purchase.success).toBe(true);
|
||||
|
||||
// The purchase hit the gateway with idempotency key + bearer token.
|
||||
expect(gateway.purchases).toEqual([
|
||||
{ storeSlug: 'starter', offerId: 'pack_1', idempotencyKey: 'idem-key-123', authToken: accessToken },
|
||||
]);
|
||||
|
||||
// The scenario took the onPurchase branch → "thanks", and the run finished.
|
||||
expect(notifications).toHaveLength(1);
|
||||
expect(notifications[0].message).toBe('Thanks for your purchase!');
|
||||
});
|
||||
|
||||
it('declining does NOT take the purchase branch (handles are isolated)', async () => {
|
||||
gateway.onEvent('player_login', offerScenario());
|
||||
const messages: string[] = [];
|
||||
let offer: StoreOfferEffect | undefined;
|
||||
client.effects.onStoreOffer((effect) => { offer = effect; });
|
||||
client.effects.onNotification((effect) => { messages.push(effect.message); });
|
||||
|
||||
await client.auth.loginWithDevice();
|
||||
await vi.advanceTimersByTimeAsync(MINUTE);
|
||||
await vi.waitFor(() => expect(offer).toBeDefined());
|
||||
await offer!.dismiss();
|
||||
await vi.advanceTimersByTimeAsync(MINUTE);
|
||||
|
||||
expect(messages).toEqual(['Your offer is still available!']);
|
||||
expect(messages).not.toContain('Thanks for your purchase!');
|
||||
expect(gateway.purchases).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { getScenarioRuntime, RudderClient } from '../../src/client/RudderClient.js';
|
||||
import { createFakeTokenStore } from '../helpers/FakeTokenStore.js';
|
||||
import { createFakeGateway, type FakeGateway } from '../helpers/fakeGateway.js';
|
||||
import { createMemoryPlanStore, stubDeterministicUuid } from '../helpers/memoryPlanStore.js';
|
||||
import { plan } from '../helpers/plan.js';
|
||||
import type { StoreSession, WaitSession } from '../../src/scenario/engine/sessions.js';
|
||||
|
||||
const MINUTE = 60_000;
|
||||
|
||||
describe('E2E: scenario state survives a reload', () => {
|
||||
let gateway: FakeGateway;
|
||||
// Shared backing store mimics IndexedDB persisting across page loads.
|
||||
const backing = { value: null as string | null };
|
||||
|
||||
function clientWithSharedStore(): RudderClient {
|
||||
return new RudderClient({
|
||||
baseUrl: 'https://api.test.rudder.build',
|
||||
projectKey: 'test-project',
|
||||
tokenStore: createFakeTokenStore(),
|
||||
runtime: { planStateStore: createMemoryPlanStore(backing), loginEvent: null },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
stubDeterministicUuid();
|
||||
vi.useFakeTimers();
|
||||
backing.value = null;
|
||||
gateway = createFakeGateway();
|
||||
gateway.onEvent(
|
||||
'session_start',
|
||||
plan('offer_flow')
|
||||
.node('wait_intro', 'wait', { duration: 1, unit: 'minutes' })
|
||||
.node('offer', 'store', { message: 'Limited starter pack!' })
|
||||
.edge('wait_intro', 'onComplete', 'offer')
|
||||
.build(),
|
||||
);
|
||||
gateway.install();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('a wait started before reload resumes and fires the offer after reload', async () => {
|
||||
// --- Session 1: trigger the scenario, then "close the tab" mid-wait ---
|
||||
const client1 = clientWithSharedStore();
|
||||
await client1.auth.loginWithDevice();
|
||||
const runtime1 = await getScenarioRuntime(client1);
|
||||
await runtime1.send('session_start');
|
||||
expect(runtime1.isRunning).toBe(true);
|
||||
expect(backing.value).toBeTruthy(); // run was persisted
|
||||
|
||||
// --- Session 2: fresh client, same persisted state (page reload) ---
|
||||
const client2 = clientWithSharedStore();
|
||||
const runtime2 = await getScenarioRuntime(client2);
|
||||
const resumedWaits: WaitSession[] = [];
|
||||
let offer: StoreSession | undefined;
|
||||
runtime2.onWait = (s) => resumedWaits.push(s);
|
||||
runtime2.onStore = (s) => { offer = s; };
|
||||
|
||||
await client2.auth.loginWithDevice();
|
||||
|
||||
// The wait node was rehydrated and re-dispatched.
|
||||
expect(runtime2.isRunning).toBe(true);
|
||||
expect(resumedWaits).toHaveLength(1);
|
||||
expect(offer).toBeUndefined();
|
||||
|
||||
// The remaining wait time still elapses → the offer surfaces on the new client.
|
||||
await vi.advanceTimersByTimeAsync(MINUTE);
|
||||
expect(offer).toBeDefined();
|
||||
expect(offer!.get('message', '')).toBe('Limited starter pack!');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { RudderClient } from '../../src/client/RudderClient.js';
|
||||
import { createFakeTokenStore } from '../helpers/FakeTokenStore.js';
|
||||
import { createFakeGateway, type FakeGateway } from '../helpers/fakeGateway.js';
|
||||
import { stubDeterministicUuid } from '../helpers/memoryPlanStore.js';
|
||||
import { plan } from '../helpers/plan.js';
|
||||
import type { RemoteConfig } from '../../src/generated/remote-config.js';
|
||||
|
||||
interface GameRemoteConfig extends Record<string, unknown> {
|
||||
max_energy: number;
|
||||
drop_rate: number;
|
||||
pvp_enabled: boolean;
|
||||
welcome_text: string;
|
||||
boss: { hp: number; name: string };
|
||||
legacy: string;
|
||||
missing_declared: string;
|
||||
}
|
||||
|
||||
function cfg(key: string, value: string, valueType: string, active = true): RemoteConfig {
|
||||
return { key, value, valueType, active };
|
||||
}
|
||||
|
||||
function makeClient(): RudderClient<GameRemoteConfig> {
|
||||
return new RudderClient<GameRemoteConfig>({
|
||||
baseUrl: 'https://api.test.rudder.build',
|
||||
projectKey: 'test-project',
|
||||
tokenStore: createFakeTokenStore(),
|
||||
runtime: { planStateStore: null, loginEvent: null },
|
||||
});
|
||||
}
|
||||
|
||||
describe('E2E: remote config', () => {
|
||||
let gateway: FakeGateway;
|
||||
let client: RudderClient<GameRemoteConfig>;
|
||||
|
||||
beforeEach(() => {
|
||||
stubDeterministicUuid();
|
||||
gateway = createFakeGateway({
|
||||
remoteConfigs: {
|
||||
max_energy: cfg('max_energy', '50', 'int'),
|
||||
drop_rate: cfg('drop_rate', '0.25', 'float'),
|
||||
pvp_enabled: cfg('pvp_enabled', 'true', 'bool'),
|
||||
welcome_text: cfg('welcome_text', 'Hello!', 'string'),
|
||||
boss: cfg('boss', '{"hp":1000,"name":"Drake"}', 'json'),
|
||||
legacy: cfg('legacy', 'old', 'string', false), // inactive — must be excluded
|
||||
},
|
||||
});
|
||||
gateway.install();
|
||||
client = makeClient();
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('loads configs and reads them back with type coercion', async () => {
|
||||
await client.auth.loginWithDevice();
|
||||
|
||||
expect(client.remoteConfig.status).toBe('ready');
|
||||
expect(client.remoteConfig.get('max_energy', 0)).toBe(50);
|
||||
expect(client.remoteConfig.get('drop_rate', 0)).toBeCloseTo(0.25);
|
||||
expect(client.remoteConfig.get('pvp_enabled', false)).toBe(true);
|
||||
expect(client.remoteConfig.get('welcome_text', '')).toBe('Hello!');
|
||||
expect(client.remoteConfig.get('boss', { hp: 0, name: '' })).toEqual({
|
||||
hp: 1000,
|
||||
name: 'Drake',
|
||||
});
|
||||
});
|
||||
|
||||
it('inactive configs are not exposed; missing keys fall back to default', async () => {
|
||||
await client.auth.loginWithDevice();
|
||||
|
||||
expect(client.remoteConfig.get('legacy', 'DEFAULT')).toBe('DEFAULT');
|
||||
expect(client.remoteConfig.get('missing_declared', 'fallback')).toBe('fallback');
|
||||
});
|
||||
|
||||
it('get() before login returns the default (no throw)', () => {
|
||||
expect(client.remoteConfig.status).toBe('idle');
|
||||
expect(client.remoteConfig.get('max_energy', 99)).toBe(99);
|
||||
});
|
||||
|
||||
it('a remote_config_override scenario node patches the live cache', async () => {
|
||||
client = new RudderClient<GameRemoteConfig>({
|
||||
baseUrl: 'https://api.test.rudder.build',
|
||||
projectKey: 'test-project',
|
||||
tokenStore: createFakeTokenStore(),
|
||||
runtime: { planStateStore: null },
|
||||
});
|
||||
gateway.onEvent(
|
||||
'player_login',
|
||||
plan('boost')
|
||||
.node('override', 'remote_config_override', {
|
||||
patches: [{ path: 'drop_rate', valueType: 'float', value: '0.9' }],
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
|
||||
await client.auth.loginWithDevice();
|
||||
|
||||
// The override is reflected immediately, without a reload.
|
||||
expect(client.remoteConfig.get('drop_rate', 0)).toBeCloseTo(0.9);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { RudderClient } from '../../src/client/RudderClient.js';
|
||||
import { createFakeTokenStore } from '../helpers/FakeTokenStore.js';
|
||||
import { createFakeGateway, type FakeGateway } from '../helpers/fakeGateway.js';
|
||||
|
||||
function makeClient(): RudderClient {
|
||||
return new RudderClient({
|
||||
baseUrl: 'https://api.test.rudder.build',
|
||||
projectKey: 'test-project',
|
||||
tokenStore: createFakeTokenStore(),
|
||||
runtime: { planStateStore: null, loginEvent: null },
|
||||
});
|
||||
}
|
||||
|
||||
describe('E2E: player storage', () => {
|
||||
let gateway: FakeGateway;
|
||||
let client: RudderClient;
|
||||
|
||||
beforeEach(() => {
|
||||
gateway = createFakeGateway();
|
||||
gateway.install();
|
||||
client = makeClient();
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('saves items then reads them back (round-trip through the gateway)', async () => {
|
||||
await client.auth.loginWithDevice();
|
||||
|
||||
await client.storage.save([
|
||||
{ id: 'save_1', type: 'progress', data: JSON.stringify({ level: 7, gold: 1200 }) },
|
||||
{ id: 'settings', type: 'prefs', data: JSON.stringify({ sound: false }) },
|
||||
]);
|
||||
|
||||
const all = await client.storage.reload();
|
||||
expect(all.items).toHaveLength(2);
|
||||
|
||||
const progress = all.items!.find((i) => i.id === 'save_1');
|
||||
expect(JSON.parse(progress!.data!)).toEqual({ level: 7, gold: 1200 });
|
||||
});
|
||||
|
||||
it('filters by type', async () => {
|
||||
await client.auth.loginWithDevice();
|
||||
await client.storage.save([
|
||||
{ id: 'a', type: 'progress', data: '{}' },
|
||||
{ id: 'b', type: 'prefs', data: '{}' },
|
||||
]);
|
||||
|
||||
// v0.2 fetches the whole storage; filtering by type is client-side.
|
||||
const all = await client.storage.reload();
|
||||
const prefs = (all.items ?? []).filter((i) => i.type === 'prefs');
|
||||
expect(prefs).toHaveLength(1);
|
||||
expect(prefs[0].id).toBe('b');
|
||||
|
||||
// The read went out as a storage fetch with limit as a query param, not a path segment.
|
||||
const getReq = gateway.recorded.findLast((r) => r.method === 'GET' && r.path === '/sdk/v1/storage');
|
||||
expect(getReq?.query.get('limit')).toBe('100');
|
||||
});
|
||||
|
||||
it('deletes a type and the items are gone', async () => {
|
||||
await client.auth.loginWithDevice();
|
||||
await client.storage.save([
|
||||
{ id: 'a', type: 'progress', data: '{}' },
|
||||
{ id: 'b', type: 'prefs', data: '{}' },
|
||||
]);
|
||||
|
||||
await client.storage.delete('progress');
|
||||
|
||||
const remaining = await client.storage.reload();
|
||||
expect(remaining.items?.map((i) => i.id)).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('storage writes carry the auth token', async () => {
|
||||
const token = (await client.auth.loginWithDevice()).accessToken;
|
||||
await client.storage.save([{ id: 'a', type: 't', data: '{}' }]);
|
||||
|
||||
const put = gateway.recorded.find((r) => r.method === 'PUT' && r.path === '/sdk/v1/storage');
|
||||
expect(put?.authToken).toBe(token);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user