@shipeasy/sdk 5.4.0 → 6.2.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.
@@ -101,8 +101,8 @@ interface AutoCollectGroups {
101
101
  errors: boolean;
102
102
  engagement: boolean;
103
103
  }
104
- type FlagsClientBrowserEnv = "dev" | "staging" | "prod";
105
- interface FlagsClientBrowserOptions {
104
+ type EngineEnv = "dev" | "staging" | "prod";
105
+ interface EngineOptions {
106
106
  sdkKey: string;
107
107
  baseUrl?: string;
108
108
  autoGuardrails?: boolean;
@@ -121,7 +121,7 @@ interface FlagsClientBrowserOptions {
121
121
  */
122
122
  autoCollectAlways?: boolean;
123
123
  /** Which published env to read values from. Defaults to "prod". */
124
- env?: FlagsClientBrowserEnv;
124
+ env?: EngineEnv;
125
125
  /**
126
126
  * Per-evaluation usage telemetry. ON by default — each getFlag/getConfig/
127
127
  * getExperiment/getKillswitch call fires one fire-and-forget sendBeacon so
@@ -158,11 +158,11 @@ interface FlagsClientBrowserOptions {
158
158
  * Test mode — no network at all. identify()/init are no-ops (never call
159
159
  * /sdk/evaluate), track() is a no-op, telemetry is forced off, and the client
160
160
  * starts "ready" with an empty eval result. Prefer the
161
- * {@link FlagsClientBrowser.forTesting} factory over passing this directly.
161
+ * {@link Engine.forTesting} factory over passing this directly.
162
162
  */
163
163
  testMode?: boolean;
164
164
  }
165
- declare class FlagsClientBrowser {
165
+ declare class Engine {
166
166
  private readonly sdkKey;
167
167
  private readonly baseUrl;
168
168
  private readonly autoGuardrails;
@@ -187,7 +187,7 @@ declare class FlagsClientBrowser {
187
187
  private readonly configOverrides;
188
188
  private readonly experimentOverrides;
189
189
  private onOverrideChange;
190
- constructor(opts: FlagsClientBrowserOptions);
190
+ constructor(opts: EngineOptions);
191
191
  /**
192
192
  * Build a no-network, immediately-usable browser client for tests
193
193
  * (Statsig-style). identify() is a no-op (never calls /sdk/evaluate), track()
@@ -196,12 +196,12 @@ declare class FlagsClientBrowser {
196
196
  * key required.
197
197
  *
198
198
  * ```ts
199
- * const client = FlagsClientBrowser.forTesting();
199
+ * const client = Engine.forTesting();
200
200
  * client.overrideFlag("new_checkout", true);
201
201
  * client.getFlag("new_checkout"); // true
202
202
  * ```
203
203
  */
204
- static forTesting(opts?: Partial<FlagsClientBrowserOptions>): FlagsClientBrowser;
204
+ static forTesting(opts?: Partial<EngineOptions>): Engine;
205
205
  identify(user: User): Promise<void>;
206
206
  /**
207
207
  * Report a structured error into the errors primitive. Flushes immediately
@@ -289,10 +289,10 @@ interface ShipeasySdkBridge {
289
289
  *
290
290
  * ```ts
291
291
  * import { OpenFeature } from "@openfeature/web-sdk";
292
- * import { FlagsClientBrowser } from "@shipeasy/sdk/client";
292
+ * import { Engine } from "@shipeasy/sdk/client";
293
293
  * import { ShipeasyProvider } from "@shipeasy/sdk/openfeature-web";
294
294
  *
295
- * const client = new FlagsClientBrowser({ sdkKey: NEXT_PUBLIC_SHIPEASY_CLIENT_KEY });
295
+ * const client = new Engine({ sdkKey: NEXT_PUBLIC_SHIPEASY_CLIENT_KEY });
296
296
  * await OpenFeature.setContext({ targetingKey: "u1", plan: "pro" });
297
297
  * await OpenFeature.setProviderAndWait(new ShipeasyProvider(client));
298
298
  *
@@ -307,7 +307,7 @@ interface ShipeasySdkBridge {
307
307
 
308
308
  /**
309
309
  * Shipeasy OpenFeature provider (client/web paradigm). Wraps a
310
- * `FlagsClientBrowser`. Context changes are reconciled through `identify()`;
310
+ * `Engine`. Context changes are reconciled through `identify()`;
311
311
  * flag reads come from the cached eval result.
312
312
  */
313
313
  declare class ShipeasyProvider implements Provider {
@@ -316,7 +316,7 @@ declare class ShipeasyProvider implements Provider {
316
316
  readonly name: "shipeasy";
317
317
  };
318
318
  readonly runsOn: "client";
319
- constructor(client: FlagsClientBrowser);
319
+ constructor(client: Engine);
320
320
  /** Identify with the initial static context so the first read is warm. */
321
321
  initialize(context?: EvaluationContext): Promise<void>;
322
322
  /** Re-identify when the application author changes the static context. */
@@ -181,7 +181,7 @@ interface StickyEntry {
181
181
  /**
182
182
  * Pluggable sticky-bucketing store for the server (doc 20 §2). Keyed by the
183
183
  * bucketing unit; the value is that unit's per-experiment assignments. Absent
184
- * from {@link FlagsClientOptions} ⇒ today's deterministic behaviour. Use
184
+ * from {@link EngineOptions} ⇒ today's deterministic behaviour. Use
185
185
  * {@link createInMemoryStickyStore} or a cookie-bridge built from request
186
186
  * cookies.
187
187
  */
@@ -198,7 +198,7 @@ interface Killswitch {
198
198
  killed: 0 | 1 | boolean;
199
199
  switches?: Record<string, 0 | 1 | boolean>;
200
200
  }
201
- /** Body of `GET /sdk/flags` — the snapshot's `flags` field. See {@link FlagsClient.fromSnapshot}. */
201
+ /** Body of `GET /sdk/flags` — the snapshot's `flags` field. See {@link Engine.fromSnapshot}. */
202
202
  interface FlagsBlob {
203
203
  version: string;
204
204
  plan: string;
@@ -208,7 +208,7 @@ interface FlagsBlob {
208
208
  }>;
209
209
  killswitches: Record<string, Killswitch>;
210
210
  }
211
- /** Body of `GET /sdk/experiments` — the snapshot's `experiments` field. See {@link FlagsClient.fromSnapshot}. */
211
+ /** Body of `GET /sdk/experiments` — the snapshot's `experiments` field. See {@link Engine.fromSnapshot}. */
212
212
  interface ExpsBlob {
213
213
  version: string;
214
214
  universes: Record<string, Universe>;
@@ -221,12 +221,12 @@ interface BootstrapPayload {
221
221
  killswitches: Record<string, boolean | Record<string, boolean>>;
222
222
  }
223
223
  declare const ANON_ID_COOKIE = "__se_anon_id";
224
- type FlagsClientEnv = "dev" | "staging" | "prod";
225
- interface FlagsClientOptions {
224
+ type EngineEnv = "dev" | "staging" | "prod";
225
+ interface EngineOptions {
226
226
  apiKey: string;
227
227
  baseUrl?: string;
228
228
  /** Which published env to read values from. Defaults to "prod". */
229
- env?: FlagsClientEnv;
229
+ env?: EngineEnv;
230
230
  /**
231
231
  * Preload the flags blob synchronously without a network fetch. Primarily
232
232
  * for tests; production callers should rely on init()/initOnce().
@@ -261,12 +261,12 @@ interface FlagsClientOptions {
261
261
  /**
262
262
  * Test mode — no network at all. init()/initOnce() are no-ops (never fetch),
263
263
  * track() is a no-op, telemetry is forced off, and the client starts
264
- * "initialized" with an empty blob. Prefer the {@link FlagsClient.forTesting}
264
+ * "initialized" with an empty blob. Prefer the {@link Engine.forTesting}
265
265
  * factory over passing this directly.
266
266
  */
267
267
  testMode?: boolean;
268
268
  }
269
- declare class FlagsClient {
269
+ declare class Engine {
270
270
  private readonly apiKey;
271
271
  private readonly baseUrl;
272
272
  private readonly env;
@@ -286,7 +286,7 @@ declare class FlagsClient {
286
286
  private readonly configOverrides;
287
287
  private readonly experimentOverrides;
288
288
  private readonly changeListeners;
289
- constructor(opts: FlagsClientOptions);
289
+ constructor(opts: EngineOptions);
290
290
  /**
291
291
  * Build a no-network, immediately-usable client for tests (Statsig-style).
292
292
  * init()/initOnce() are no-ops (never fetch), track() is a no-op, telemetry
@@ -294,12 +294,12 @@ declare class FlagsClient {
294
294
  * with overrideFlag/overrideConfig/overrideExperiment. No SDK key required.
295
295
  *
296
296
  * ```ts
297
- * const client = FlagsClient.forTesting();
297
+ * const client = Engine.forTesting();
298
298
  * client.overrideFlag("new_checkout", true);
299
299
  * client.getFlag("new_checkout", { user_id: "u1" }); // true
300
300
  * ```
301
301
  */
302
- static forTesting(opts?: Partial<FlagsClientOptions>): FlagsClient;
302
+ static forTesting(opts?: Partial<EngineOptions>): Engine;
303
303
  /**
304
304
  * Build a fully OFFLINE client from a pre-captured snapshot — no network ever.
305
305
  * Reuses the test-mode plumbing (init()/initOnce()/track() are no-ops,
@@ -313,14 +313,14 @@ declare class FlagsClient {
313
313
  static fromSnapshot(snapshot: {
314
314
  flags: FlagsBlob;
315
315
  experiments: ExpsBlob;
316
- }): FlagsClient;
316
+ }): Engine;
317
317
  /**
318
318
  * Build a fully OFFLINE client from a snapshot JSON file on disk (Node only —
319
319
  * not available in the browser entrypoint). The file must contain
320
320
  * `{ "flags": <GET /sdk/flags body>, "experiments": <GET /sdk/experiments body> }`.
321
- * See {@link FlagsClient.fromSnapshot}.
321
+ * See {@link Engine.fromSnapshot}.
322
322
  */
323
- static fromFile(path: string): FlagsClient;
323
+ static fromFile(path: string): Engine;
324
324
  init(): Promise<void>;
325
325
  initOnce(): Promise<void>;
326
326
  /** Force `getFlag(name, …)` to return `value`, ignoring the fetched gate. */
@@ -440,8 +440,8 @@ interface FetchLabelsOptions {
440
440
  timeoutMs?: number;
441
441
  }
442
442
  declare function fetchLabelsForSSR(opts: FetchLabelsOptions): Promise<LabelFile | null>;
443
- declare function configureShipeasyServer(opts: FlagsClientOptions): FlagsClient;
444
- declare function getShipeasyServerClient(): FlagsClient | null;
443
+ declare function configureShipeasyServer(opts: EngineOptions): Engine;
444
+ declare function getShipeasyServerClient(): Engine | null;
445
445
  declare function _resetShipeasyServerForTests(): void;
446
446
  interface ShipeasyServerConfig {
447
447
  /**
@@ -463,13 +463,13 @@ interface ShipeasyServerConfig {
463
463
  /**
464
464
  * Disable per-evaluation usage telemetry. ON by default. On Cloudflare
465
465
  * Workers each beacon is an outbound subrequest, so disable on hot SSR paths
466
- * that evaluate many flags per request. See {@link FlagsClientOptions.disableTelemetry}.
466
+ * that evaluate many flags per request. See {@link EngineOptions.disableTelemetry}.
467
467
  */
468
468
  disableTelemetry?: boolean;
469
469
  /**
470
470
  * Attribute names usable for targeting but never persisted in analytics
471
471
  * (LD/Statsig `privateAttributes`). Stripped from every outbound `track()`
472
- * payload. See {@link FlagsClientOptions.privateAttributes}.
472
+ * payload. See {@link EngineOptions.privateAttributes}.
473
473
  */
474
474
  privateAttributes?: string[];
475
475
  }
@@ -547,7 +547,7 @@ declare function getBootstrapData(bootstrap: BootstrapPayload | null, i18nData:
547
547
  */
548
548
  declare function getBootstrapTags(bootstrap: BootstrapPayload | null, i18nData: I18nForRequest | null, opts: BootstrapEmitOptions): string;
549
549
  declare const flags: {
550
- configure(opts: FlagsClientOptions): void;
550
+ configure(opts: EngineOptions): void;
551
551
  /**
552
552
  * Long-running server: starts the background poll. Call once at app boot.
553
553
  * Throws if the initial fetch fails (caller decides whether to crash or degrade).
@@ -570,7 +570,7 @@ declare const flags: {
570
570
  ks(name: string, switchKey?: string): boolean;
571
571
  track(userId: string, eventName: string, props?: Record<string, unknown>): void;
572
572
  /** Emit an exposure for an enrolled experiment at the decision point. See
573
- * {@link FlagsClient.logExposure}. No-op before configure(). */
573
+ * {@link Engine.logExposure}. No-op before configure(). */
574
574
  logExposure(user: string | User, name: string): void;
575
575
  /**
576
576
  * Evaluate all flags / configs / experiments for a user against the locally
@@ -579,6 +579,165 @@ declare const flags: {
579
579
  */
580
580
  evaluate(user: User, rawUrl?: string): BootstrapPayload;
581
581
  };
582
+ /** Transform YOUR application's user object into Shipeasy targeting attributes. */
583
+ type AttributesFn<U = unknown> = (user: U) => User;
584
+ interface ConfigureOptions<U = unknown> extends Omit<EngineOptions, "apiKey"> {
585
+ /** Server key — the single key the server side accepts (SHIPEASY_SERVER_KEY). */
586
+ apiKey: string;
587
+ /**
588
+ * Map your own user object into the attribute bag every flag/experiment
589
+ * evaluation sees. Runs once per `new Client(user)`. Omit when you already
590
+ * pass a plain attribute object (identity transform — the object is used
591
+ * verbatim, so it should carry `user_id`/`anonymous_id` + any targeting attrs).
592
+ */
593
+ attributes?: AttributesFn<U>;
594
+ /**
595
+ * Long-running server: start the **background poll** internally (initial fetch
596
+ * + periodic refresh) so flags stay fresh without a redeploy. Default `false`.
597
+ * With `poll: false` (default) a one-shot fetch is kicked off fire-and-forget
598
+ * (serverless-friendly). You never need to call `engine.init()` yourself —
599
+ * configuration owns the lifecycle.
600
+ */
601
+ poll?: boolean;
602
+ /**
603
+ * One-shot fetch on configure (fire-and-forget). Default `true`. Ignored when
604
+ * `poll: true` (the poll does the initial fetch). Set `false` only if you want
605
+ * to control the first fetch yourself.
606
+ */
607
+ init?: boolean;
608
+ }
609
+ /**
610
+ * Configure the SDK once at app boot, then evaluate per user with
611
+ * `new Client(user)`. Builds the process-wide {@link Engine} (polling + blob
612
+ * cache + HTTP) and registers the `attributes` transform. The first call wins;
613
+ * later calls return the existing engine (mirrors {@link configureShipeasyServer}).
614
+ *
615
+ * ```ts
616
+ * import { configure, Client } from "@shipeasy/sdk/server";
617
+ *
618
+ * configure({
619
+ * apiKey: process.env.SHIPEASY_SERVER_KEY!,
620
+ * attributes: (u: MyUser) => ({ user_id: u.id, plan: u.plan, country: u.geo.country }),
621
+ * });
622
+ *
623
+ * const flags = new Client(currentUser);
624
+ * if (flags.getFlag("new_checkout")) { ... }
625
+ * ```
626
+ */
627
+ declare function configure<U = unknown>(opts: ConfigureOptions<U>): Engine;
628
+ /** Test seam: reset the registered attribute transform. */
629
+ declare function _resetConfigureForTests(): void;
630
+ /** Seed shapes shared by {@link configureForTesting} / {@link configureForOffline}. */
631
+ interface ConfigureTestOptions<U = unknown> {
632
+ /** Same transform as {@link configure} (default identity). */
633
+ attributes?: AttributesFn<U>;
634
+ /** `{ name: bool }` — forced `getFlag` results. */
635
+ flags?: Record<string, boolean>;
636
+ /** `{ name: value }` — forced `getConfig` results. */
637
+ configs?: Record<string, unknown>;
638
+ /** `{ name: [group, params] }` — forced enrolments. */
639
+ experiments?: Record<string, [string, Record<string, unknown>]>;
640
+ }
641
+ /**
642
+ * Configure the SDK in **test mode** — a drop-in sibling of {@link configure}
643
+ * with no network, ever (no api key needed). Seed what your code under test
644
+ * should see, then read through the ordinary `new Client(user)`:
645
+ *
646
+ * ```ts
647
+ * configureForTesting({ flags: { new_checkout: true } });
648
+ * const flags = new Client({ user_id: "u_1" });
649
+ * flags.getFlag("new_checkout"); // true
650
+ * ```
651
+ *
652
+ * Replaces any previously-configured engine, so tests can reconfigure freely.
653
+ */
654
+ declare function configureForTesting<U = unknown>(opts?: ConfigureTestOptions<U>): Engine;
655
+ /** Options for {@link configureForOffline} — exactly one of `snapshot` / `path`. */
656
+ interface ConfigureOfflineOptions<U = unknown> extends ConfigureTestOptions<U> {
657
+ /** In-memory `{ flags: <body of /sdk/flags>, experiments: <body of /sdk/experiments> }`. */
658
+ snapshot?: {
659
+ flags: FlagsBlob;
660
+ experiments: ExpsBlob;
661
+ };
662
+ /** Path to a JSON file `{ flags, experiments }`. */
663
+ path?: string;
664
+ }
665
+ /**
666
+ * Configure the SDK **offline** — evaluate the REAL rules from an in-memory
667
+ * snapshot or a JSON file, with no network. A drop-in sibling of
668
+ * {@link configure} (no api key needed). Optional `flags`/`configs`/`experiments`
669
+ * overrides are layered on top (same shapes as {@link configureForTesting}).
670
+ * Replaces any previously-configured engine.
671
+ */
672
+ declare function configureForOffline<U = unknown>(opts: ConfigureOfflineOptions<U>): Engine;
673
+ /**
674
+ * Force `getFlag(name)` → `value` on the spot, for the current config. A quick
675
+ * in-test override layered on top of whatever {@link configureForTesting} /
676
+ * {@link configureForOffline} (or {@link configure}) set up — wins over the blob
677
+ * until {@link clearOverrides}.
678
+ */
679
+ declare function overrideFlag(name: string, value: boolean): void;
680
+ /** Force `getConfig(name)` → `value` on the spot (see {@link overrideFlag}). */
681
+ declare function overrideConfig(name: string, value: unknown): void;
682
+ /**
683
+ * Force `getExperiment(name)` to report enrolment in `group` with `params` on
684
+ * the spot (see {@link overrideFlag}).
685
+ */
686
+ declare function overrideExperiment(name: string, group: string, params: Record<string, unknown>): void;
687
+ /**
688
+ * Drop every on-the-spot flag/config/experiment override — INCLUDING the seed
689
+ * from {@link configureForTesting} (test mode has no blob beneath, so everything
690
+ * reverts to the empty-blob defaults). Under {@link configureForOffline} the
691
+ * snapshot remains and evaluations revert to it.
692
+ */
693
+ declare function clearOverrides(): void;
694
+ /**
695
+ * Register a listener fired after a background poll fetches NEW data (a 200, not
696
+ * a 304). Returns an unsubscribe callable. Requires `configure({ poll: true })`
697
+ * (no poll thread runs otherwise). Configuration owns the engine; you never
698
+ * touch it.
699
+ */
700
+ declare function onChange(listener: () => void): () => void;
701
+ /**
702
+ * A user-bound evaluation handle. Construct one per user/request — it's cheap
703
+ * (it delegates to the {@link Engine} built by {@link configure}); it does NOT
704
+ * open its own connection or poll. The configured `attributes` transform runs
705
+ * once here, so every getFlag/getConfig/getExperiment reads the same bag.
706
+ *
707
+ * ```ts
708
+ * const flags = new Client(req.user);
709
+ * flags.getFlag("new_checkout"); // no user arg — bound at construction
710
+ * flags.getExperiment("price_test", { price: 9 });
711
+ * ```
712
+ */
713
+ declare class Client<U = unknown> {
714
+ private readonly engine;
715
+ /** The resolved attribute bag this handle evaluates against. */
716
+ readonly attributes: User;
717
+ constructor(user: U);
718
+ getFlag(name: string, defaultValue?: boolean): boolean;
719
+ getFlagDetail(name: string): FlagDetail;
720
+ getConfig<T = unknown>(name: string, decode?: (raw: unknown) => T): T | undefined;
721
+ getConfig<T = unknown>(name: string, opts: GetConfigOptions<T>): T;
722
+ getExperiment<P extends Record<string, unknown>>(name: string, defaultParams: P, decode?: (raw: unknown) => P): ExperimentResult<P>;
723
+ /** Read a killswitch (not user-bound; mirrors {@link Engine.getKillswitch}). */
724
+ getKillswitch(name: string, switchKey?: string): boolean;
725
+ /**
726
+ * Record a conversion/metric event for the bound user. Derives the unit from
727
+ * the resolved attribute bag (`user_id`, else `anonymous_id`) and delegates to
728
+ * {@link Engine.track} — so an experiment is end-to-end Client-only (no need to
729
+ * drop down to the Engine to log a conversion). Fire-and-forget; no-op in test
730
+ * mode.
731
+ */
732
+ track(eventName: string, props?: Record<string, unknown>): void;
733
+ /**
734
+ * Emit an exposure event for `name` at this server-side decision point for the
735
+ * bound user. Delegates to {@link Engine.logExposure} with the resolved
736
+ * attribute bag (re-evaluates enrolment; no-op when the user isn't enrolled or
737
+ * in test mode).
738
+ */
739
+ logExposure(name: string): void;
740
+ }
582
741
  interface SeeApi {
583
742
  /**
584
743
  * Report a handled problem and its product consequence:
@@ -630,4 +789,4 @@ interface SeeApi {
630
789
  */
631
790
  declare const see: SeeApi;
632
791
 
633
- export { ANON_ID_COOKIE, type BootstrapData, type BootstrapEmitOptions, type BootstrapPayload, type Consequence, type ExperimentResult, type ExpsBlob, FLAG_REASONS, type FetchLabelsOptions, type FlagDetail, type FlagReason, type FlagsBlob, FlagsClient, type FlagsClientEnv, type FlagsClientOptions, type GetConfigOptions, type I18nForRequest, type LabelFile, type ScriptTagSpec, type SeeApi, type SeeChain, type SeeControlFlowChain, type SeeErrorEvent, type SeeExtras, type SeeKind, type SeeViolationChain, type ShipeasyServerConfig, type ShipeasyServerHandle, type StickyBucketStore, type StickyEntry, type User, type Violation, _murmur3ForTests, _resetShipeasyServerForTests, configureShipeasyServer, createInMemoryStickyStore, fetchLabelsForSSR, flags, getBootstrapData, getBootstrapTags, getShipeasyServerClient, i18n, isExpected, see, seeContext, shipeasy, version };
792
+ export { ANON_ID_COOKIE, type AttributesFn, type BootstrapData, type BootstrapEmitOptions, type BootstrapPayload, Client, type ConfigureOfflineOptions, type ConfigureOptions, type ConfigureTestOptions, type Consequence, Engine, type EngineEnv, type EngineOptions, type ExperimentResult, type ExpsBlob, FLAG_REASONS, type FetchLabelsOptions, type FlagDetail, type FlagReason, type FlagsBlob, type GetConfigOptions, type I18nForRequest, type LabelFile, type ScriptTagSpec, type SeeApi, type SeeChain, type SeeControlFlowChain, type SeeErrorEvent, type SeeExtras, type SeeKind, type SeeViolationChain, type ShipeasyServerConfig, type ShipeasyServerHandle, type StickyBucketStore, type StickyEntry, type User, type Violation, _murmur3ForTests, _resetConfigureForTests, _resetShipeasyServerForTests, clearOverrides, configure, configureForOffline, configureForTesting, configureShipeasyServer, createInMemoryStickyStore, fetchLabelsForSSR, flags, getBootstrapData, getBootstrapTags, getShipeasyServerClient, i18n, isExpected, onChange, overrideConfig, overrideExperiment, overrideFlag, see, seeContext, shipeasy, version };