@railflag/sdk-node 0.0.0-stage → 0.1.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/README.md +39 -2
- package/dist/index.cjs +515 -0
- package/dist/index.d.cts +170 -0
- package/dist/index.d.ts +170 -0
- package/dist/index.js +494 -0
- package/package.json +56 -3
package/README.md
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @railflag/sdk-node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Railflag's OpenFeature provider for Node.js 20+. It downloads your environment's flag config once,
|
|
4
|
+
evaluates every flag check in process (no network call per check), and picks up changes within a
|
|
5
|
+
second over Server-Sent Events. If the stream drops it polls every 30 s, and if Railflag can't be
|
|
6
|
+
reached it keeps serving the last config it had.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @railflag/sdk-node @openfeature/server-sdk @openfeature/core
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { OpenFeature } from '@openfeature/server-sdk';
|
|
14
|
+
import { RailflagProvider } from '@railflag/sdk-node';
|
|
15
|
+
|
|
16
|
+
await OpenFeature.setProviderAndWait(new RailflagProvider({
|
|
17
|
+
sdkKey: process.env.RAILFLAG_SERVER_KEY!, // a server key: Environments → keys
|
|
18
|
+
baseUrl: 'https://relay-production-aa5b.up.railway.app', // required: your Railflag relay
|
|
19
|
+
}));
|
|
20
|
+
const client = OpenFeature.getClient();
|
|
21
|
+
|
|
22
|
+
if (await client.getBooleanValue('new-checkout', false, { targetingKey: 'user-42', plan: 'pro', country: 'GR' })) {
|
|
23
|
+
// ...
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- `baseUrl` is required and must start with `http://` or `https://`. The constructor throws otherwise, so an unset environment variable fails at startup instead of sending your key somewhere else.
|
|
28
|
+
- `getBooleanValue`, `getStringValue`, `getNumberValue` and `getObjectValue` work as in any OpenFeature provider. A wrong type or unknown flag returns your default with an error code.
|
|
29
|
+
- `OpenFeature.addHandler(ProviderEvents.ConfigurationChanged, fn)` tells you when flags change.
|
|
30
|
+
- A wrong key makes `setProviderAndWait` reject with `Railflag config request failed: 401`.
|
|
31
|
+
- Works from ES modules and CommonJS, and ships its own type declarations.
|
|
32
|
+
- Server keys can read every rule. Keep them on the server; browsers use `@railflag/sdk-js` with a client key.
|
|
33
|
+
|
|
34
|
+
`@openfeature/core` is a peer dependency of `@openfeature/server-sdk`. npm 7+ installs it for you,
|
|
35
|
+
but list it yourself if you use pnpm or set `legacy-peer-deps`.
|
|
36
|
+
|
|
37
|
+
## Same answers as every other SDK
|
|
38
|
+
|
|
39
|
+
Evaluation runs `packages/eval`, the same evaluator the relay uses for browsers, and the Python SDK
|
|
40
|
+
is tested against its vectors, so a user lands in the same variation whichever SDK evaluates the flag.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target2, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target2, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
ConfigSource: () => ConfigSource,
|
|
24
|
+
RailflagProvider: () => RailflagProvider
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(index_exports);
|
|
27
|
+
var import_server_sdk = require("@openfeature/server-sdk");
|
|
28
|
+
|
|
29
|
+
// ../eval/src/murmur3.ts
|
|
30
|
+
var C1 = 3432918353;
|
|
31
|
+
var C2 = 461845907;
|
|
32
|
+
function hashBytes(bytes, seed) {
|
|
33
|
+
let h = seed >>> 0;
|
|
34
|
+
const len = bytes.length;
|
|
35
|
+
const n = len & ~3;
|
|
36
|
+
let k;
|
|
37
|
+
for (let i = 0; i < n; i += 4) {
|
|
38
|
+
k = bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24;
|
|
39
|
+
k = Math.imul(k, C1);
|
|
40
|
+
k = k << 15 | k >>> 17;
|
|
41
|
+
k = Math.imul(k, C2);
|
|
42
|
+
h ^= k;
|
|
43
|
+
h = h << 13 | h >>> 19;
|
|
44
|
+
h = Math.imul(h, 5) + 3864292196 | 0;
|
|
45
|
+
}
|
|
46
|
+
k = 0;
|
|
47
|
+
const rem = len & 3;
|
|
48
|
+
if (rem === 3) k ^= bytes[n + 2] << 16;
|
|
49
|
+
if (rem >= 2) k ^= bytes[n + 1] << 8;
|
|
50
|
+
if (rem >= 1) {
|
|
51
|
+
k ^= bytes[n];
|
|
52
|
+
k = Math.imul(k, C1);
|
|
53
|
+
k = k << 15 | k >>> 17;
|
|
54
|
+
k = Math.imul(k, C2);
|
|
55
|
+
h ^= k;
|
|
56
|
+
}
|
|
57
|
+
h ^= len;
|
|
58
|
+
h ^= h >>> 16;
|
|
59
|
+
h = Math.imul(h, 2246822507);
|
|
60
|
+
h ^= h >>> 13;
|
|
61
|
+
h = Math.imul(h, 3266489909);
|
|
62
|
+
h ^= h >>> 16;
|
|
63
|
+
return h >>> 0;
|
|
64
|
+
}
|
|
65
|
+
var encoder = new TextEncoder();
|
|
66
|
+
function murmur3(input, seed = 0) {
|
|
67
|
+
return hashBytes(encoder.encode(input), seed);
|
|
68
|
+
}
|
|
69
|
+
function murmur3Latin1(input, seed = 0) {
|
|
70
|
+
const bytes = new Uint8Array(input.length);
|
|
71
|
+
for (let i = 0; i < input.length; i++) bytes[i] = input.charCodeAt(i) & 255;
|
|
72
|
+
return hashBytes(bytes, seed);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ../schema/src/index.ts
|
|
76
|
+
var import_zod = require("zod");
|
|
77
|
+
var WEIGHT_SCALE = 1e5;
|
|
78
|
+
var flagKey = import_zod.z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "Use letters, digits, dot, dash or underscore, starting with a letter or digit");
|
|
79
|
+
var flagType = import_zod.z.enum(["boolean", "string", "number", "json"]);
|
|
80
|
+
var flagKind = import_zod.z.enum(["release", "ops", "experiment", "permission"]);
|
|
81
|
+
var clauseOp = import_zod.z.enum([
|
|
82
|
+
"in",
|
|
83
|
+
"exists",
|
|
84
|
+
"startsWith",
|
|
85
|
+
"endsWith",
|
|
86
|
+
"contains",
|
|
87
|
+
"matches",
|
|
88
|
+
"lt",
|
|
89
|
+
"lte",
|
|
90
|
+
"gt",
|
|
91
|
+
"gte",
|
|
92
|
+
"semverEq",
|
|
93
|
+
"semverLt",
|
|
94
|
+
"semverGt",
|
|
95
|
+
"before",
|
|
96
|
+
"after",
|
|
97
|
+
"segmentMatch"
|
|
98
|
+
]);
|
|
99
|
+
var scalar = import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean()]);
|
|
100
|
+
var clause = import_zod.z.object({
|
|
101
|
+
attr: import_zod.z.string().min(1),
|
|
102
|
+
op: clauseOp,
|
|
103
|
+
values: import_zod.z.array(scalar).min(1),
|
|
104
|
+
negate: import_zod.z.boolean().optional()
|
|
105
|
+
});
|
|
106
|
+
var bucketing = import_zod.z.object({
|
|
107
|
+
algorithm: import_zod.z.enum(["murmur3", "abtasty"]),
|
|
108
|
+
/** abtasty: the variation group id that seeds the hash. */
|
|
109
|
+
seed: import_zod.z.string().optional()
|
|
110
|
+
});
|
|
111
|
+
var rollout = import_zod.z.object({
|
|
112
|
+
bucketBy: import_zod.z.string().optional(),
|
|
113
|
+
weights: import_zod.z.array(import_zod.z.number().int().min(0).max(WEIGHT_SCALE)).min(1),
|
|
114
|
+
bucketing: bucketing.optional()
|
|
115
|
+
}).refine((r) => r.weights.reduce((a, b) => a + b, 0) <= WEIGHT_SCALE, {
|
|
116
|
+
message: `Weights must add up to at most ${WEIGHT_SCALE}`
|
|
117
|
+
});
|
|
118
|
+
var serve = import_zod.z.union([
|
|
119
|
+
import_zod.z.object({ variation: import_zod.z.number().int().min(0) }),
|
|
120
|
+
import_zod.z.object({ rollout })
|
|
121
|
+
]);
|
|
122
|
+
var rule = import_zod.z.object({
|
|
123
|
+
id: import_zod.z.string().min(1),
|
|
124
|
+
name: import_zod.z.string().optional(),
|
|
125
|
+
clauses: import_zod.z.array(clause),
|
|
126
|
+
serve
|
|
127
|
+
});
|
|
128
|
+
var target = import_zod.z.object({
|
|
129
|
+
variation: import_zod.z.number().int().min(0),
|
|
130
|
+
values: import_zod.z.array(import_zod.z.string())
|
|
131
|
+
});
|
|
132
|
+
var prerequisite = import_zod.z.object({ key: flagKey, variation: import_zod.z.number().int().min(0) });
|
|
133
|
+
var targeting = import_zod.z.object({
|
|
134
|
+
enabled: import_zod.z.boolean(),
|
|
135
|
+
offVariation: import_zod.z.number().int().min(0),
|
|
136
|
+
fallthrough: serve,
|
|
137
|
+
targets: import_zod.z.array(target).default([]),
|
|
138
|
+
rules: import_zod.z.array(rule).default([]),
|
|
139
|
+
prerequisites: import_zod.z.array(prerequisite).default([])
|
|
140
|
+
});
|
|
141
|
+
var variation = import_zod.z.object({
|
|
142
|
+
value: import_zod.z.unknown(),
|
|
143
|
+
name: import_zod.z.string().optional(),
|
|
144
|
+
description: import_zod.z.string().optional()
|
|
145
|
+
});
|
|
146
|
+
var segmentRules = import_zod.z.object({
|
|
147
|
+
included: import_zod.z.array(import_zod.z.string()).default([]),
|
|
148
|
+
excluded: import_zod.z.array(import_zod.z.string()).default([]),
|
|
149
|
+
rules: import_zod.z.array(import_zod.z.object({ clauses: import_zod.z.array(clause) })).default([])
|
|
150
|
+
});
|
|
151
|
+
var snapshotFlag = targeting.extend({
|
|
152
|
+
key: flagKey,
|
|
153
|
+
type: flagType,
|
|
154
|
+
variations: import_zod.z.array(import_zod.z.unknown()).min(1),
|
|
155
|
+
salt: import_zod.z.string(),
|
|
156
|
+
version: import_zod.z.number().int()
|
|
157
|
+
});
|
|
158
|
+
var snapshot = import_zod.z.object({
|
|
159
|
+
env: import_zod.z.string(),
|
|
160
|
+
version: import_zod.z.number().int(),
|
|
161
|
+
generatedAt: import_zod.z.string(),
|
|
162
|
+
flags: import_zod.z.record(import_zod.z.string(), snapshotFlag),
|
|
163
|
+
segments: import_zod.z.record(import_zod.z.string(), segmentRules)
|
|
164
|
+
});
|
|
165
|
+
var evalReason = import_zod.z.enum(["STATIC", "DEFAULT", "TARGETING_MATCH", "SPLIT", "DISABLED", "ERROR"]);
|
|
166
|
+
|
|
167
|
+
// ../eval/src/bucket.ts
|
|
168
|
+
function bucketFor(flagKey2, salt, value, bucketing2) {
|
|
169
|
+
if (bucketing2?.algorithm === "abtasty") {
|
|
170
|
+
const seed = bucketing2.seed ?? "";
|
|
171
|
+
return murmur3Latin1(seed + value) % 100 * (WEIGHT_SCALE / 100);
|
|
172
|
+
}
|
|
173
|
+
const h = murmur3(`${flagKey2}.${salt}.${value}`);
|
|
174
|
+
return Math.floor(h / 4294967296 * WEIGHT_SCALE);
|
|
175
|
+
}
|
|
176
|
+
function pickWeighted(weights, bucket) {
|
|
177
|
+
let total = 0;
|
|
178
|
+
for (let i = 0; i < weights.length; i++) {
|
|
179
|
+
total += weights[i];
|
|
180
|
+
if (bucket < total) return i;
|
|
181
|
+
}
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ../eval/src/clauses.ts
|
|
186
|
+
function parseSemver(v) {
|
|
187
|
+
if (typeof v !== "string") return null;
|
|
188
|
+
const m = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(v.trim());
|
|
189
|
+
if (!m) return null;
|
|
190
|
+
return [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)];
|
|
191
|
+
}
|
|
192
|
+
function cmpSemver(a, b) {
|
|
193
|
+
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
function toTime(v) {
|
|
197
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
198
|
+
if (typeof v === "string") {
|
|
199
|
+
const t = Date.parse(v);
|
|
200
|
+
return Number.isNaN(t) ? null : t;
|
|
201
|
+
}
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
function compare(a, b) {
|
|
205
|
+
if (typeof a === "number" && typeof b === "number") return a - b;
|
|
206
|
+
if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
var regexCache = /* @__PURE__ */ new Map();
|
|
210
|
+
function regex(src) {
|
|
211
|
+
if (!regexCache.has(src)) {
|
|
212
|
+
let re = null;
|
|
213
|
+
try {
|
|
214
|
+
re = new RegExp(src);
|
|
215
|
+
} catch {
|
|
216
|
+
re = null;
|
|
217
|
+
}
|
|
218
|
+
regexCache.set(src, re);
|
|
219
|
+
}
|
|
220
|
+
return regexCache.get(src);
|
|
221
|
+
}
|
|
222
|
+
function matchOne(op, actual, expected) {
|
|
223
|
+
switch (op) {
|
|
224
|
+
case "in":
|
|
225
|
+
return actual === expected;
|
|
226
|
+
case "startsWith":
|
|
227
|
+
return typeof actual === "string" && actual.startsWith(String(expected));
|
|
228
|
+
case "endsWith":
|
|
229
|
+
return typeof actual === "string" && actual.endsWith(String(expected));
|
|
230
|
+
case "contains":
|
|
231
|
+
return typeof actual === "string" && actual.includes(String(expected));
|
|
232
|
+
case "matches": {
|
|
233
|
+
const re = typeof actual === "string" ? regex(String(expected)) : null;
|
|
234
|
+
return re !== null && re.test(actual);
|
|
235
|
+
}
|
|
236
|
+
case "lt": {
|
|
237
|
+
const c = compare(actual, expected);
|
|
238
|
+
return c !== null && c < 0;
|
|
239
|
+
}
|
|
240
|
+
case "lte": {
|
|
241
|
+
const c = compare(actual, expected);
|
|
242
|
+
return c !== null && c <= 0;
|
|
243
|
+
}
|
|
244
|
+
case "gt": {
|
|
245
|
+
const c = compare(actual, expected);
|
|
246
|
+
return c !== null && c > 0;
|
|
247
|
+
}
|
|
248
|
+
case "gte": {
|
|
249
|
+
const c = compare(actual, expected);
|
|
250
|
+
return c !== null && c >= 0;
|
|
251
|
+
}
|
|
252
|
+
case "semverEq":
|
|
253
|
+
case "semverLt":
|
|
254
|
+
case "semverGt": {
|
|
255
|
+
const a = parseSemver(actual);
|
|
256
|
+
const b = parseSemver(expected);
|
|
257
|
+
if (!a || !b) return false;
|
|
258
|
+
const c = cmpSemver(a, b);
|
|
259
|
+
return op === "semverEq" ? c === 0 : op === "semverLt" ? c < 0 : c > 0;
|
|
260
|
+
}
|
|
261
|
+
case "before":
|
|
262
|
+
case "after": {
|
|
263
|
+
const a = toTime(actual);
|
|
264
|
+
const b = toTime(expected);
|
|
265
|
+
if (a === null || b === null) return false;
|
|
266
|
+
return op === "before" ? a < b : a > b;
|
|
267
|
+
}
|
|
268
|
+
default:
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
function clauseMatches(c, ctx, env) {
|
|
273
|
+
if (c.op === "segmentMatch") {
|
|
274
|
+
const hit2 = c.values.some((s) => segmentMatches(String(s), ctx, env));
|
|
275
|
+
return c.negate ? !hit2 : hit2;
|
|
276
|
+
}
|
|
277
|
+
const actual = c.attr === "key" ? env.contextKey : ctx[c.attr];
|
|
278
|
+
if (c.op === "exists") {
|
|
279
|
+
const present = actual !== void 0 && actual !== null;
|
|
280
|
+
return c.negate ? !present : present;
|
|
281
|
+
}
|
|
282
|
+
if (actual === void 0 || actual === null) return false;
|
|
283
|
+
const values = Array.isArray(actual) ? actual : [actual];
|
|
284
|
+
const hit = values.some((a) => c.values.some((e) => matchOne(c.op, a, e)));
|
|
285
|
+
return c.negate ? !hit : hit;
|
|
286
|
+
}
|
|
287
|
+
function segmentMatches(key, ctx, env) {
|
|
288
|
+
const seg = env.segments[key];
|
|
289
|
+
if (!seg || env.depth > 5) return false;
|
|
290
|
+
const k = env.contextKey;
|
|
291
|
+
if (k !== void 0) {
|
|
292
|
+
if (seg.excluded.includes(k)) return false;
|
|
293
|
+
if (seg.included.includes(k)) return true;
|
|
294
|
+
}
|
|
295
|
+
const inner = { ...env, depth: env.depth + 1 };
|
|
296
|
+
return seg.rules.some((r) => r.clauses.every((c) => clauseMatches(c, ctx, inner)));
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ../eval/src/evaluate.ts
|
|
300
|
+
function contextKeyOf(ctx) {
|
|
301
|
+
const k = ctx.targetingKey ?? ctx.key;
|
|
302
|
+
return k === void 0 || k === null ? void 0 : String(k);
|
|
303
|
+
}
|
|
304
|
+
function typeOf(v) {
|
|
305
|
+
if (typeof v === "boolean") return "boolean";
|
|
306
|
+
if (typeof v === "string") return "string";
|
|
307
|
+
if (typeof v === "number") return "number";
|
|
308
|
+
return "json";
|
|
309
|
+
}
|
|
310
|
+
function resolveServe(flag, s, ctx, ruleId) {
|
|
311
|
+
if ("variation" in s) return { index: s.variation, reason: ruleId ? "TARGETING_MATCH" : "DEFAULT", ruleId };
|
|
312
|
+
const attr = s.rollout.bucketBy ?? "key";
|
|
313
|
+
const raw = attr === "key" ? contextKeyOf(ctx) : ctx[attr];
|
|
314
|
+
const bucket = raw === void 0 || raw === null ? 0 : bucketFor(flag.key, flag.salt, String(raw), s.rollout.bucketing);
|
|
315
|
+
const index = pickWeighted(s.rollout.weights, bucket);
|
|
316
|
+
if (index === null) return null;
|
|
317
|
+
return { index, reason: "SPLIT", ruleId };
|
|
318
|
+
}
|
|
319
|
+
function evaluateFlag(snapshot2, flag, ctx, seen) {
|
|
320
|
+
if (!flag.enabled) return { index: flag.offVariation, reason: "DISABLED" };
|
|
321
|
+
for (const p of flag.prerequisites) {
|
|
322
|
+
const pre = snapshot2.flags[p.key];
|
|
323
|
+
if (!pre || seen.has(p.key)) return { index: flag.offVariation, reason: "DEFAULT", ruleId: `prerequisite:${p.key}` };
|
|
324
|
+
seen.add(p.key);
|
|
325
|
+
const r = evaluateFlag(snapshot2, pre, ctx, seen);
|
|
326
|
+
seen.delete(p.key);
|
|
327
|
+
if (!r || !pre.enabled || r.index !== p.variation)
|
|
328
|
+
return { index: flag.offVariation, reason: "DEFAULT", ruleId: `prerequisite:${p.key}` };
|
|
329
|
+
}
|
|
330
|
+
const key = contextKeyOf(ctx);
|
|
331
|
+
if (key !== void 0) {
|
|
332
|
+
for (const t of flag.targets) {
|
|
333
|
+
if (t.values.includes(key)) return { index: t.variation, reason: "TARGETING_MATCH", ruleId: "target" };
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const env = { segments: snapshot2.segments, contextKey: key, depth: 0 };
|
|
337
|
+
for (const rule2 of flag.rules) {
|
|
338
|
+
if (!rule2.clauses.every((c) => clauseMatches(c, ctx, env))) continue;
|
|
339
|
+
const r = resolveServe(flag, rule2.serve, ctx, rule2.id);
|
|
340
|
+
if (r) return r;
|
|
341
|
+
}
|
|
342
|
+
return resolveServe(flag, flag.fallthrough, ctx, void 0) ?? { index: flag.offVariation, reason: "DEFAULT" };
|
|
343
|
+
}
|
|
344
|
+
function evaluate(snapshot2, flagKey2, ctx = {}, opts = {}) {
|
|
345
|
+
try {
|
|
346
|
+
const flag = snapshot2.flags[flagKey2];
|
|
347
|
+
if (!flag) return { value: void 0, variationIndex: null, reason: "ERROR", errorCode: "FLAG_NOT_FOUND", errorMessage: `Flag ${flagKey2} not found` };
|
|
348
|
+
const r = evaluateFlag(snapshot2, flag, ctx, /* @__PURE__ */ new Set([flagKey2]));
|
|
349
|
+
const index = r?.index ?? flag.offVariation;
|
|
350
|
+
if (index < 0 || index >= flag.variations.length)
|
|
351
|
+
return { value: void 0, variationIndex: null, reason: "ERROR", errorCode: "GENERAL", errorMessage: "Variation index out of range", flagVersion: flag.version };
|
|
352
|
+
const value = flag.variations[index];
|
|
353
|
+
if (opts.expectedType && typeOf(value) !== opts.expectedType && !(opts.expectedType === "json"))
|
|
354
|
+
return { value: void 0, variationIndex: null, reason: "ERROR", errorCode: "TYPE_MISMATCH", errorMessage: `Flag ${flagKey2} is ${flag.type}, not ${opts.expectedType}`, flagVersion: flag.version };
|
|
355
|
+
return { value, variationIndex: index, reason: r?.reason ?? "DEFAULT", ruleId: r?.ruleId, flagVersion: flag.version };
|
|
356
|
+
} catch (e) {
|
|
357
|
+
return { value: void 0, variationIndex: null, reason: "ERROR", errorCode: "GENERAL", errorMessage: e instanceof Error ? e.message : String(e) };
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// src/sse.ts
|
|
362
|
+
async function readSse(res, onEvent, signal) {
|
|
363
|
+
if (!res.body) throw new Error("No response body");
|
|
364
|
+
const reader = res.body.getReader();
|
|
365
|
+
const dec = new TextDecoder();
|
|
366
|
+
let buf = "";
|
|
367
|
+
let cur = {};
|
|
368
|
+
while (!signal.aborted) {
|
|
369
|
+
const { value, done } = await reader.read();
|
|
370
|
+
if (done) return;
|
|
371
|
+
buf += dec.decode(value, { stream: true });
|
|
372
|
+
let nl;
|
|
373
|
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
374
|
+
const line = buf.slice(0, nl).replace(/\r$/, "");
|
|
375
|
+
buf = buf.slice(nl + 1);
|
|
376
|
+
if (line === "") {
|
|
377
|
+
if (cur.data !== void 0 || cur.event) onEvent({ event: cur.event ?? "message", data: cur.data ?? "", id: cur.id });
|
|
378
|
+
cur = {};
|
|
379
|
+
} else if (!line.startsWith(":")) {
|
|
380
|
+
const i = line.indexOf(":");
|
|
381
|
+
const field = i < 0 ? line : line.slice(0, i);
|
|
382
|
+
const val = i < 0 ? "" : line.slice(i + 1).replace(/^ /, "");
|
|
383
|
+
if (field === "event") cur.event = val;
|
|
384
|
+
else if (field === "data") cur.data = cur.data === void 0 ? val : `${cur.data}
|
|
385
|
+
${val}`;
|
|
386
|
+
else if (field === "id") cur.id = val;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// src/source.ts
|
|
393
|
+
var ConfigSource = class {
|
|
394
|
+
snapshot = null;
|
|
395
|
+
etag = null;
|
|
396
|
+
opts;
|
|
397
|
+
f;
|
|
398
|
+
abort = new AbortController();
|
|
399
|
+
pollTimer;
|
|
400
|
+
listeners = /* @__PURE__ */ new Set();
|
|
401
|
+
streaming = false;
|
|
402
|
+
constructor(o) {
|
|
403
|
+
if (typeof o.baseUrl !== "string" || !/^https?:\/\//.test(o.baseUrl)) {
|
|
404
|
+
throw new TypeError(`baseUrl must be your Railflag relay URL, like https://relay.example.com (got ${JSON.stringify(o.baseUrl)})`);
|
|
405
|
+
}
|
|
406
|
+
this.opts = { stream: true, pollIntervalMs: 3e4, ...o, baseUrl: o.baseUrl.replace(/\/+$/, "") };
|
|
407
|
+
this.f = o.fetch ?? fetch;
|
|
408
|
+
}
|
|
409
|
+
onChange(l) {
|
|
410
|
+
this.listeners.add(l);
|
|
411
|
+
return () => this.listeners.delete(l);
|
|
412
|
+
}
|
|
413
|
+
async start() {
|
|
414
|
+
await this.fetchConfig();
|
|
415
|
+
this.pollTimer = setInterval(() => void this.fetchConfig().catch((e) => this.opts.logger?.warn("railflag poll failed", e)), this.opts.pollIntervalMs);
|
|
416
|
+
this.pollTimer.unref?.();
|
|
417
|
+
if (this.opts.stream) void this.streamLoop();
|
|
418
|
+
}
|
|
419
|
+
stop() {
|
|
420
|
+
this.abort.abort();
|
|
421
|
+
clearInterval(this.pollTimer);
|
|
422
|
+
}
|
|
423
|
+
async fetchConfig() {
|
|
424
|
+
const headers = { authorization: this.opts.sdkKey };
|
|
425
|
+
if (this.etag) headers["if-none-match"] = this.etag;
|
|
426
|
+
const res = await this.f(`${this.opts.baseUrl}/sdk/v1/config`, { headers, signal: this.abort.signal });
|
|
427
|
+
if (res.status === 304) return;
|
|
428
|
+
if (!res.ok) throw new Error(`Railflag config request failed: ${res.status}`);
|
|
429
|
+
const snap = await res.json();
|
|
430
|
+
if (this.snapshot && snap.version < this.snapshot.version) return;
|
|
431
|
+
this.snapshot = snap;
|
|
432
|
+
this.etag = res.headers.get("etag");
|
|
433
|
+
for (const l of this.listeners) l(snap);
|
|
434
|
+
}
|
|
435
|
+
async streamLoop() {
|
|
436
|
+
let backoff = 500;
|
|
437
|
+
while (!this.abort.signal.aborted) {
|
|
438
|
+
try {
|
|
439
|
+
const res = await this.f(`${this.opts.baseUrl}/sdk/v1/stream`, { headers: { authorization: this.opts.sdkKey }, signal: this.abort.signal });
|
|
440
|
+
if (!res.ok) throw new Error(`stream ${res.status}`);
|
|
441
|
+
this.streaming = true;
|
|
442
|
+
backoff = 500;
|
|
443
|
+
await readSse(res, (e) => {
|
|
444
|
+
if (e.event === "config") {
|
|
445
|
+
const v = Number(JSON.parse(e.data || "{}").version);
|
|
446
|
+
if (!this.snapshot || v > this.snapshot.version) void this.fetchConfig().catch(() => {
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
}, this.abort.signal);
|
|
450
|
+
} catch (e) {
|
|
451
|
+
if (this.abort.signal.aborted) return;
|
|
452
|
+
this.opts.logger?.warn("railflag stream dropped, reconnecting", e);
|
|
453
|
+
}
|
|
454
|
+
this.streaming = false;
|
|
455
|
+
if (this.abort.signal.aborted) return;
|
|
456
|
+
await new Promise((r) => setTimeout(r, backoff));
|
|
457
|
+
backoff = Math.min(backoff * 2, 3e4);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
// src/index.ts
|
|
463
|
+
var codes = {
|
|
464
|
+
FLAG_NOT_FOUND: import_server_sdk.ErrorCode.FLAG_NOT_FOUND,
|
|
465
|
+
TYPE_MISMATCH: import_server_sdk.ErrorCode.TYPE_MISMATCH,
|
|
466
|
+
PARSE_ERROR: import_server_sdk.ErrorCode.PARSE_ERROR,
|
|
467
|
+
GENERAL: import_server_sdk.ErrorCode.GENERAL
|
|
468
|
+
};
|
|
469
|
+
var RailflagProvider = class {
|
|
470
|
+
metadata = { name: "railflag" };
|
|
471
|
+
runsOn = "server";
|
|
472
|
+
events = new import_server_sdk.OpenFeatureEventEmitter();
|
|
473
|
+
source;
|
|
474
|
+
constructor(opts) {
|
|
475
|
+
this.source = new ConfigSource(opts);
|
|
476
|
+
this.source.onChange((s) => this.events.emit(import_server_sdk.ProviderEvents.ConfigurationChanged, { message: `config version ${s.version}` }));
|
|
477
|
+
}
|
|
478
|
+
async initialize() {
|
|
479
|
+
await this.source.start();
|
|
480
|
+
}
|
|
481
|
+
async onClose() {
|
|
482
|
+
this.source.stop();
|
|
483
|
+
}
|
|
484
|
+
resolve(flagKey2, def, ctx, type) {
|
|
485
|
+
const snap = this.source.snapshot;
|
|
486
|
+
if (!snap) return { value: def, reason: import_server_sdk.StandardResolutionReasons.ERROR, errorCode: import_server_sdk.ErrorCode.PROVIDER_NOT_READY };
|
|
487
|
+
const r = evaluate(snap, flagKey2, ctx, { expectedType: type });
|
|
488
|
+
if (r.reason === "ERROR") {
|
|
489
|
+
return { value: def, reason: import_server_sdk.StandardResolutionReasons.ERROR, errorCode: codes[r.errorCode ?? "GENERAL"] ?? import_server_sdk.ErrorCode.GENERAL, errorMessage: r.errorMessage };
|
|
490
|
+
}
|
|
491
|
+
return {
|
|
492
|
+
value: r.value,
|
|
493
|
+
variant: r.variationIndex === null ? void 0 : String(r.variationIndex),
|
|
494
|
+
reason: r.reason,
|
|
495
|
+
flagMetadata: { flagVersion: r.flagVersion ?? 0, ...r.ruleId ? { ruleId: r.ruleId } : {}, configVersion: snap.version }
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
resolveBooleanEvaluation(k, d, c) {
|
|
499
|
+
return Promise.resolve(this.resolve(k, d, c, "boolean"));
|
|
500
|
+
}
|
|
501
|
+
resolveStringEvaluation(k, d, c) {
|
|
502
|
+
return Promise.resolve(this.resolve(k, d, c, "string"));
|
|
503
|
+
}
|
|
504
|
+
resolveNumberEvaluation(k, d, c) {
|
|
505
|
+
return Promise.resolve(this.resolve(k, d, c, "number"));
|
|
506
|
+
}
|
|
507
|
+
resolveObjectEvaluation(k, d, c) {
|
|
508
|
+
return Promise.resolve(this.resolve(k, d, c, "json"));
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
512
|
+
0 && (module.exports = {
|
|
513
|
+
ConfigSource,
|
|
514
|
+
RailflagProvider
|
|
515
|
+
});
|