@schematichq/schematic-typescript-node 1.4.8 → 1.5.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.
@@ -0,0 +1,175 @@
1
+ import type * as api from "../api";
2
+ import type { RedisClient } from "../cache/redis";
3
+ /**
4
+ * Behavior when a lease cannot be acquired or reserved against (API error,
5
+ * lease/reservation store unreachable, insufficient balance).
6
+ * - `fail-open`: err on the side of assuming the credits are there — the rules
7
+ * engine still evaluates the flag (plan targeting, overrides, and all
8
+ * non-credit conditions apply) with the credit balance substituted to an
9
+ * effectively unlimited value, so only the credit gate is bypassed. No
10
+ * reservation is issued.
11
+ * - `fail-closed`: `check()` returns `{ allowed: false }` so the caller blocks the action
12
+ */
13
+ export type OnAcquireFailure = "fail-open" | "fail-closed";
14
+ export declare const DEFAULT_LEASE_DURATION_MS: number;
15
+ export declare const DEFAULT_RESERVATION_TTL_MS: number;
16
+ export declare const DEFAULT_LEASE_SIZE: number;
17
+ export declare const DEFAULT_LOW_WATER_MARK: number;
18
+ export declare const DEFAULT_SWEEP_INTERVAL_MS: number;
19
+ export declare const DEFAULT_PREWARM_RESOLVE_TIMEOUT_MS: number;
20
+ export declare const DEFAULT_PREWARM_POLL_INTERVAL_MS: number;
21
+ /**
22
+ * Configuration block enabling client-side lease + reservation behavior on
23
+ * `client.check` / `client.trackWithReservation`. Omit to keep the SDK
24
+ * lease-unaware (`check` falls back to a plain flag check).
25
+ */
26
+ export interface CreditLeaseConfig {
27
+ /** Default lease duration in milliseconds. Default `DEFAULT_LEASE_DURATION_MS` (5 minutes). */
28
+ defaultLeaseDuration?: number;
29
+ /**
30
+ * Default reservation TTL in milliseconds. Default `DEFAULT_RESERVATION_TTL_MS`
31
+ * (60 seconds). Size this above the longest expected gap between `check()`
32
+ * and `trackWithReservation()`: a settle arriving after the TTL still bills
33
+ * the server but doesn't re-debit the local lease (its hold was already
34
+ * swept back), so the local balance reads high until the lease rolls over.
35
+ */
36
+ defaultReservationTTL?: number;
37
+ /** Default lease size (credit amount requested). Default `DEFAULT_LEASE_SIZE` (10000). */
38
+ defaultLeaseSize?: number;
39
+ /**
40
+ * Fraction of remaining lease balance below which the SDK kicks off a
41
+ * background extend. Default `DEFAULT_LOW_WATER_MARK` (0.25).
42
+ */
43
+ lowWaterMark?: number;
44
+ /** Sweep interval (ms) for expired reservations. Default `DEFAULT_SWEEP_INTERVAL_MS` (1000). */
45
+ sweepIntervalMs?: number;
46
+ /**
47
+ * Max time `prewarm()` will wait for a freshly-identified company to
48
+ * surface in the datastream cache when only secondary keys are passed.
49
+ * Set to 0 to skip waiting entirely (prewarm bails immediately if the
50
+ * company isn't already cached). Default `DEFAULT_PREWARM_RESOLVE_TIMEOUT_MS`
51
+ * (5000ms).
52
+ */
53
+ prewarmResolveTimeoutMs?: number;
54
+ /**
55
+ * Pre-connected Redis client for lease + reservation state. Optional: when
56
+ * omitted, the SDK reuses the DataStream cache's Redis client
57
+ * (`dataStream.redisClient`) if one is configured, so an existing Redis
58
+ * setup backs leases automatically. Set this only to point lease state at a
59
+ * *different* Redis than the DataStream cache.
60
+ *
61
+ * When neither this nor `dataStream.redisClient` is configured, the SDK
62
+ * falls back to per-process in-memory stores — single-pod only, since
63
+ * cross-pod gating is lost (a warning is logged). With a Redis client
64
+ * present, the Lua-driven `tryReserve` / `consume` paths give atomic
65
+ * cross-pod gating.
66
+ */
67
+ redisClient?: RedisClient;
68
+ /**
69
+ * Optional Redis key prefix. Falls back to `dataStream.redisKeyPrefix` when
70
+ * unset, then to `schematic:`.
71
+ */
72
+ redisKeyPrefix?: string;
73
+ /** Per-credit-type overrides (keyed by credit type ID). */
74
+ overrides?: Record<string, Partial<Omit<CreditLeaseConfig, "overrides" | "sweepIntervalMs" | "redisClient" | "redisKeyPrefix">>>;
75
+ }
76
+ /** Resolved config for a single credit type after applying defaults + overrides. */
77
+ export interface ResolvedLeaseConfig {
78
+ leaseDuration: number;
79
+ reservationTTL: number;
80
+ leaseSize: number;
81
+ lowWaterMark: number;
82
+ }
83
+ /** Handle returned by `client.check` when a reservation is issued. Pass to `client.trackWithReservation`. */
84
+ export interface Reservation {
85
+ /** Opaque reservation ID. */
86
+ id: string;
87
+ /** Underlying lease ID this reservation draws from. */
88
+ leaseId: string;
89
+ /** Company that owns the lease. */
90
+ companyId: string;
91
+ /** Credit type the reservation reserves against. */
92
+ creditTypeId: string;
93
+ /** Event subtype to record on the Track event when consumed. */
94
+ eventSubtype: string;
95
+ /** Quantity (in event units) the caller declared upfront. */
96
+ quantityReserved: number;
97
+ /** Credits reserved = `quantityReserved * consumptionRate`. */
98
+ creditsReserved: number;
99
+ /** Consumption rate at the time the reservation was issued. */
100
+ consumptionRate: number;
101
+ /** When the reservation expires and gets swept back to the lease. */
102
+ expiresAt: Date;
103
+ /**
104
+ * Evaluation context used to issue this reservation. Threaded into the
105
+ * Track event in `trackWithReservation` so the server can attribute usage
106
+ * to the same company/user.
107
+ */
108
+ evalCtx: api.CheckFlagRequestBody;
109
+ }
110
+ /** Options accepted by `client.check`. */
111
+ export interface CheckOptions {
112
+ /**
113
+ * Quantity (in event units) to gate the check on — the check reserves
114
+ * `usage × consumption_rate` credits from the lease. A check issues at
115
+ * most ONE reservation, against a single event subtype.
116
+ */
117
+ usage?: number;
118
+ /**
119
+ * Event subtype the `usage` applies to (e.g. `"inference_tokens"`).
120
+ * Disambiguates which credit condition to gate on when the flag meters
121
+ * more than one event. Optional when the flag's credit condition is
122
+ * unambiguous.
123
+ */
124
+ eventSubtype?: string;
125
+ /**
126
+ * What to do when a lease cannot be acquired (API error, store
127
+ * unreachable, insufficient remote balance). Default: `fail-closed`
128
+ * (`allowed = false`, no reservation) — deny when the gate can't gate.
129
+ * Override to `fail-open` for trusted/known customers where letting
130
+ * traffic through is preferable to a denial; the flag's rules are still
131
+ * evaluated with an assumed-sufficient credit balance, so only the credit
132
+ * gate is bypassed (see `OnAcquireFailure`).
133
+ */
134
+ onAcquireFailure?: OnAcquireFailure;
135
+ /** Default value to return on error. */
136
+ defaultValue?: boolean | (() => boolean);
137
+ /** Custom timeout for API calls within this check (ms). */
138
+ timeoutMs?: number;
139
+ }
140
+ /** Result of `client.check`. */
141
+ export interface CheckResult {
142
+ /** Whether the caller is permitted to proceed. */
143
+ allowed: boolean;
144
+ /** Boolean flag value (`allowed` mirrors this in non-lease paths). */
145
+ value: boolean;
146
+ /** Reservation handle when a lease-bearing check passed. */
147
+ reservation?: Reservation;
148
+ /** Human-readable reason (from the rules engine or the SDK). */
149
+ reason: string;
150
+ /**
151
+ * Entitlement payload from the check.
152
+ *
153
+ * NOTE: `entitlement.creditRemaining` (and `creditTotal` / `creditUsed`) is
154
+ * NOT lease-aware and must not be used as a user-facing balance when credit
155
+ * leases are enabled. The WASM derives those fields from the company's
156
+ * server `creditBalances`, which a lease distorts: a plain `checkFlag` sees
157
+ * the balance net of the whole lease tranche (reads low/~0), and a
158
+ * lease-bearing `check()` sees the substituted *tranche-local* balance, not
159
+ * the company total. For any "credits remaining" display use
160
+ * `client.getCreditBalance(...).settled` (`B − spent`), which speaks the
161
+ * server's `remaining`/`reserved`/`settled` vocabulary.
162
+ */
163
+ entitlement?: api.RulesengineFeatureEntitlement;
164
+ /** Flag key checked. */
165
+ flagKey: string;
166
+ /** Flag ID if known. */
167
+ flagId?: string;
168
+ /** Optional error string (populated when the SDK fell back to a default). */
169
+ err?: string;
170
+ }
171
+ /** Extras accepted by `trackWithReservation`. */
172
+ export interface TrackWithReservationOptions {
173
+ /** Optional traits to attach to the emitted Track event. */
174
+ traits?: Record<string, unknown>;
175
+ }
@@ -1,4 +1,6 @@
1
1
  import * as Schematic from '../api/types';
2
+ import { RulesEngineClient } from '../rules-engine';
3
+ import type { CheckFlagOptions } from '../wrapper';
2
4
  import { Logger } from '../logger';
3
5
  import { LazyEmitter } from './emitter';
4
6
  import type { CacheProvider } from '../cache/types';
@@ -9,7 +11,11 @@ import { type RedisClient } from '../cache/redis';
9
11
  export interface DataStreamClientOptions {
10
12
  /** Schematic API key for authentication */
11
13
  apiKey: string;
12
- /** Base URL for the API (will be converted to WebSocket URL) */
14
+ /**
15
+ * Base URL for the API, converted to its WebSocket counterpart (e.g.
16
+ * https://api.schematichq.com -> wss://datastream.schematichq.com).
17
+ * Defaults to the standard Schematic API environment.
18
+ */
13
19
  baseURL?: string;
14
20
  /** Logger for debug/info/error messages */
15
21
  logger: Logger;
@@ -38,7 +44,7 @@ export interface DataStreamClientOptions {
38
44
  */
39
45
  export declare class DataStreamClient extends LazyEmitter {
40
46
  private readonly apiKey;
41
- private readonly baseURL?;
47
+ private readonly baseURL;
42
48
  private readonly logger;
43
49
  private readonly cacheTTL;
44
50
  private readonly companyCacheProvider;
@@ -106,7 +112,17 @@ export declare class DataStreamClient extends LazyEmitter {
106
112
  checkFlag(evalCtx: {
107
113
  company?: Record<string, string>;
108
114
  user?: Record<string, string>;
109
- }, flagKey: string): Promise<Schematic.RulesengineCheckFlagResult>;
115
+ }, flagKey: string, options?: CheckFlagOptions): Promise<Schematic.RulesengineCheckFlagResult>;
116
+ /**
117
+ * Public accessor for the cached company snapshot. Used by credit-lease
118
+ * callers that need the company's `credit_balances` so they can substitute
119
+ * a lease-bound view before calling the rules engine.
120
+ */
121
+ getCachedCompany(keys: Record<string, string>): Promise<Schematic.RulesengineCompany | null>;
122
+ /** Public accessor for the cached user snapshot. */
123
+ getCachedUser(keys: Record<string, string>): Promise<Schematic.RulesengineUser | null>;
124
+ /** Public accessor for the rules engine. Used by credit-lease eval. */
125
+ getRulesEngine(): RulesEngineClient;
110
126
  /**
111
127
  * UpdateCompanyMetrics updates company metrics locally (for track events)
112
128
  */
package/dist/index.d.ts CHANGED
@@ -6,4 +6,5 @@ export { ConsoleLogger, LogLevel, type Logger } from "./logger";
6
6
  export { SchematicEnvironment } from "./environments";
7
7
  export { SchematicError, SchematicTimeoutError } from "./errors";
8
8
  export { RulesEngineClient } from "./rules-engine";
9
+ export type { CheckOptions, CheckResult, CreditLeaseConfig, OnAcquireFailure, Reservation, TrackWithReservationOptions, } from "./credits";
9
10
  export { verifyWebhookSignature, verifySignature, computeSignature, computeHexSignature, WebhookSignatureError, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER } from "./webhooks";