@dipswitch/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/LICENSE +21 -0
- package/README.md +48 -2
- package/dist/index.cjs +378 -0
- package/dist/index.d.cts +39 -0
- package/dist/index.d.mts +39 -0
- package/dist/index.mjs +376 -0
- package/package.json +26 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Engineers Space LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,49 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dipswitch/sdk-node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Dipswitch feature flags for Node. It keeps your application's rules in memory, so a check makes no network call, and learns about changes within seconds. No dependencies; Node 20 or later.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
Until the packages are on npm, install the tarball:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install ./dipswitch-sdk-node-0.1.0.tgz
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## First use
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createClient } from '@dipswitch/sdk-node'
|
|
17
|
+
|
|
18
|
+
// A server key is secret: keep it in the environment, never in a browser.
|
|
19
|
+
const flags = createClient({ serverKey: process.env.DIPSWITCH_SERVER_KEY ?? '' })
|
|
20
|
+
|
|
21
|
+
// Settles once the first load is done or has failed; until then checks return their defaults.
|
|
22
|
+
await flags.ready
|
|
23
|
+
if (flags.isEnabled('new-billing', 'user-42', false)) {
|
|
24
|
+
// the new billing path
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const stop = flags.onChange(() => console.log('flags changed'))
|
|
28
|
+
stop()
|
|
29
|
+
|
|
30
|
+
// On shutdown, so the process can exit.
|
|
31
|
+
flags.close()
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Signing browser identities
|
|
35
|
+
|
|
36
|
+
Use the client key's identity secret on your backend to sign a user ID from the authenticated session. Send the ID and signature to the browser.
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { signIdentity } from '@dipswitch/sdk-node'
|
|
40
|
+
|
|
41
|
+
export function identityForBrowser(userId: string) {
|
|
42
|
+
const identitySecret = process.env.DIPSWITCH_IDENTITY_SECRET
|
|
43
|
+
if (!identitySecret) throw new Error('Set DIPSWITCH_IDENTITY_SECRET')
|
|
44
|
+
|
|
45
|
+
return { id: userId, signature: signIdentity(userId, identitySecret) }
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The result is the hexadecimal HMAC-SHA256 digest of the UTF-8 user ID. Other backends can generate it with the same algorithm and the full identity secret as a UTF-8 string.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let node_crypto = require("node:crypto");
|
|
3
|
+
// ../eval/dist/evaluate.js
|
|
4
|
+
/**
|
|
5
|
+
* Prepares a ruleset for `evaluate`. Expects a ruleset the schema accepts;
|
|
6
|
+
* for one it would refuse, it still does not throw: a segment that is not
|
|
7
|
+
* listed counts as empty, and a user listed both on and off is off.
|
|
8
|
+
* Maps and sets, not objects, so an id such as `__proto__` is an id like any other.
|
|
9
|
+
*/
|
|
10
|
+
function compile(ruleset) {
|
|
11
|
+
const segments = /* @__PURE__ */ new Map();
|
|
12
|
+
for (const [key, members] of Object.entries(ruleset.segments)) segments.set(key, new Set(members));
|
|
13
|
+
const members = (key) => segments.get(key) ?? /* @__PURE__ */ new Set();
|
|
14
|
+
const flags = /* @__PURE__ */ new Map();
|
|
15
|
+
for (const [key, flag] of Object.entries(ruleset.flags)) {
|
|
16
|
+
const users = /* @__PURE__ */ new Map();
|
|
17
|
+
for (const id of flag.users.on) users.set(id, true);
|
|
18
|
+
for (const id of flag.users.off) users.set(id, false);
|
|
19
|
+
flags.set(key, {
|
|
20
|
+
enabled: flag.enabled,
|
|
21
|
+
defaultOn: flag.defaultOn,
|
|
22
|
+
users,
|
|
23
|
+
segmentsOn: flag.segments.on.map(members),
|
|
24
|
+
segmentsOff: flag.segments.off.map(members)
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
version: ruleset.version,
|
|
29
|
+
flags
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const disabled = {
|
|
33
|
+
value: false,
|
|
34
|
+
reason: "DISABLED"
|
|
35
|
+
};
|
|
36
|
+
const targetedOff = {
|
|
37
|
+
value: false,
|
|
38
|
+
reason: "TARGETING_MATCH"
|
|
39
|
+
};
|
|
40
|
+
const targetedOn = {
|
|
41
|
+
value: true,
|
|
42
|
+
reason: "TARGETING_MATCH"
|
|
43
|
+
};
|
|
44
|
+
const defaultOff = {
|
|
45
|
+
value: false,
|
|
46
|
+
reason: "STATIC"
|
|
47
|
+
};
|
|
48
|
+
const defaultOn = {
|
|
49
|
+
value: true,
|
|
50
|
+
reason: "STATIC"
|
|
51
|
+
};
|
|
52
|
+
/** The same evaluation, with the rule that decided the value. */
|
|
53
|
+
function evaluateWithReason(ruleset, flagKey, userId) {
|
|
54
|
+
const flag = ruleset.flags.get(flagKey);
|
|
55
|
+
if (flag === void 0) return void 0;
|
|
56
|
+
if (!flag.enabled) return disabled;
|
|
57
|
+
if (userId !== void 0) {
|
|
58
|
+
const own = flag.users.get(userId);
|
|
59
|
+
if (own !== void 0) return own ? targetedOn : targetedOff;
|
|
60
|
+
if (flag.segmentsOff.some((segment) => segment.has(userId))) return targetedOff;
|
|
61
|
+
if (flag.segmentsOn.some((segment) => segment.has(userId))) return targetedOn;
|
|
62
|
+
}
|
|
63
|
+
return flag.defaultOn ? defaultOn : defaultOff;
|
|
64
|
+
}
|
|
65
|
+
// src/sse.ts
|
|
66
|
+
var SseParser = class {
|
|
67
|
+
decoder = new TextDecoder();
|
|
68
|
+
buffer = "";
|
|
69
|
+
event = "";
|
|
70
|
+
data = [];
|
|
71
|
+
/** Takes the next bytes of the stream; returns the events they complete. */
|
|
72
|
+
push(chunk) {
|
|
73
|
+
this.buffer += this.decoder.decode(chunk, { stream: true });
|
|
74
|
+
const events = [];
|
|
75
|
+
for (;;) {
|
|
76
|
+
const end = this.buffer.search(/\r\n|\r|\n/);
|
|
77
|
+
if (end < 0) break;
|
|
78
|
+
if (this.buffer[end] === "\r" && end === this.buffer.length - 1) break;
|
|
79
|
+
const line = this.buffer.slice(0, end);
|
|
80
|
+
this.buffer = this.buffer.slice(end + (this.buffer.startsWith("\r\n", end) ? 2 : 1));
|
|
81
|
+
if (line === "") {
|
|
82
|
+
if (this.data.length > 0) events.push({
|
|
83
|
+
event: this.event || "message",
|
|
84
|
+
data: this.data.join("\n")
|
|
85
|
+
});
|
|
86
|
+
this.event = "";
|
|
87
|
+
this.data = [];
|
|
88
|
+
} else if (!line.startsWith(":")) {
|
|
89
|
+
const colon = line.indexOf(":");
|
|
90
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
91
|
+
const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
92
|
+
if (field === "event") this.event = value;
|
|
93
|
+
else if (field === "data") this.data.push(value);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return events;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const POLL_EVERY_MS = 3e4;
|
|
100
|
+
/** The refetch after an event waits a random time up to this, so one change does not hit `edge` from every server at once. */
|
|
101
|
+
const REFETCH_DELAY_MAX_MS = 2e3;
|
|
102
|
+
/** When a refetch finds an older version than the event's, or "not modified": wait, ask again, at most so many times. */
|
|
103
|
+
const RETRY_AFTER_MS = 1e3;
|
|
104
|
+
/** A stream that ended is opened again after a random time up to this. */
|
|
105
|
+
const RECONNECT_MAX_MS = 3e4;
|
|
106
|
+
/** A request with no answer by then is given up. */
|
|
107
|
+
const REQUEST_TIMEOUT_MS = 1e4;
|
|
108
|
+
/** `edge` sends the heartbeat every 30 seconds: a stream silent for this long is dead and is opened again. */
|
|
109
|
+
const STREAM_IDLE_MS = 75e3;
|
|
110
|
+
function createClient(options) {
|
|
111
|
+
if (typeof options?.serverKey !== "string" || options.serverKey === "") throw new TypeError("createClient needs a `serverKey`.");
|
|
112
|
+
return new Client(options.serverKey, (options.edgeUrl ?? "https://edge.dipswitch.co").replace(/\/+$/, ""));
|
|
113
|
+
}
|
|
114
|
+
var Client = class {
|
|
115
|
+
key;
|
|
116
|
+
base;
|
|
117
|
+
ready;
|
|
118
|
+
compiled;
|
|
119
|
+
held;
|
|
120
|
+
etag;
|
|
121
|
+
settled = false;
|
|
122
|
+
stopped = false;
|
|
123
|
+
listeners = /* @__PURE__ */ new Set();
|
|
124
|
+
timers = /* @__PURE__ */ new Set();
|
|
125
|
+
requests = /* @__PURE__ */ new Set();
|
|
126
|
+
poller;
|
|
127
|
+
/** The newest version an event announced that is not held yet, while a refetch for it is under way. */
|
|
128
|
+
wanted;
|
|
129
|
+
/** Since when every answer has been a 401. */
|
|
130
|
+
unauthorizedSince;
|
|
131
|
+
/** After a 429: no request for the ruleset before this time (docs/PLAN.md, Wire contract: When answers fail). */
|
|
132
|
+
quietUntil = 0;
|
|
133
|
+
retryTimer;
|
|
134
|
+
constructor(key, base) {
|
|
135
|
+
this.key = key;
|
|
136
|
+
this.base = base;
|
|
137
|
+
this.ready = this.load().then(() => {
|
|
138
|
+
this.settled = true;
|
|
139
|
+
if (this.stopped) return;
|
|
140
|
+
this.poller = setInterval(() => void this.load(), POLL_EVERY_MS);
|
|
141
|
+
this.connect();
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
isEnabled(flagKey, userId, defaultValue) {
|
|
145
|
+
return this.getFlagDetails(flagKey, userId).value ?? defaultValue;
|
|
146
|
+
}
|
|
147
|
+
get snapshotVersion() {
|
|
148
|
+
return this.held;
|
|
149
|
+
}
|
|
150
|
+
getFlagDetails(flagKey, userId) {
|
|
151
|
+
if (!this.compiled) return {
|
|
152
|
+
value: void 0,
|
|
153
|
+
reason: "NOT_READY"
|
|
154
|
+
};
|
|
155
|
+
return evaluateWithReason(this.compiled, flagKey, userId ?? void 0) ?? {
|
|
156
|
+
value: void 0,
|
|
157
|
+
reason: "FLAG_NOT_FOUND"
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
onChange(listener) {
|
|
161
|
+
this.listeners.add(listener);
|
|
162
|
+
return () => void this.listeners.delete(listener);
|
|
163
|
+
}
|
|
164
|
+
close() {
|
|
165
|
+
this.stopped = true;
|
|
166
|
+
clearInterval(this.poller);
|
|
167
|
+
for (const timer of this.timers) clearTimeout(timer);
|
|
168
|
+
this.timers.clear();
|
|
169
|
+
for (const request of this.requests) request.abort();
|
|
170
|
+
this.requests.clear();
|
|
171
|
+
this.listeners.clear();
|
|
172
|
+
}
|
|
173
|
+
/** Stops for good, keeping the values: a revoked key, a key of the wrong kind, or 5 minutes of 401. */
|
|
174
|
+
stop(reason) {
|
|
175
|
+
if (this.stopped) return;
|
|
176
|
+
console.warn(`@dipswitch/sdk-node: stopped (${reason}); flags keep their last values.`);
|
|
177
|
+
this.close();
|
|
178
|
+
}
|
|
179
|
+
/** A timer that `close()` clears. */
|
|
180
|
+
after(ms, work) {
|
|
181
|
+
const timer = setTimeout(() => {
|
|
182
|
+
this.timers.delete(timer);
|
|
183
|
+
if (!this.stopped) work();
|
|
184
|
+
}, ms);
|
|
185
|
+
this.timers.add(timer);
|
|
186
|
+
return timer;
|
|
187
|
+
}
|
|
188
|
+
/** A request to `edge` with the key in a header, never in the URL. `close()` aborts it through `controller`. */
|
|
189
|
+
send(path, controller, headers = {}) {
|
|
190
|
+
this.requests.add(controller);
|
|
191
|
+
return fetch(`${this.base}${path}`, {
|
|
192
|
+
headers: {
|
|
193
|
+
authorization: `Bearer ${this.key}`,
|
|
194
|
+
...headers
|
|
195
|
+
},
|
|
196
|
+
signal: controller.signal
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
clear(timer) {
|
|
200
|
+
if (timer === void 0) return;
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
this.timers.delete(timer);
|
|
203
|
+
}
|
|
204
|
+
/** Fetches the ruleset, with the ETag of the one held, and takes it if it is newer. Never throws. */
|
|
205
|
+
async load() {
|
|
206
|
+
if (this.stopped || Date.now() < this.quietUntil) return { kind: "failed" };
|
|
207
|
+
const controller = new AbortController();
|
|
208
|
+
const timeout = this.after(REQUEST_TIMEOUT_MS, () => controller.abort());
|
|
209
|
+
try {
|
|
210
|
+
const response = await this.send("/server/ruleset", controller, this.etag ? { "if-none-match": this.etag } : {});
|
|
211
|
+
this.answered(response.status);
|
|
212
|
+
if (response.status === 429) this.backOff(response);
|
|
213
|
+
if (response.status !== 200) {
|
|
214
|
+
await response.body?.cancel();
|
|
215
|
+
return response.status === 304 ? { kind: "not-modified" } : {
|
|
216
|
+
kind: "status",
|
|
217
|
+
status: response.status
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
const body = await response.json();
|
|
221
|
+
if (!isRuleset(body)) return { kind: "failed" };
|
|
222
|
+
this.take(body, response.headers.get("etag"));
|
|
223
|
+
return {
|
|
224
|
+
kind: "ruleset",
|
|
225
|
+
version: BigInt(body.version)
|
|
226
|
+
};
|
|
227
|
+
} catch {
|
|
228
|
+
return { kind: "failed" };
|
|
229
|
+
} finally {
|
|
230
|
+
this.requests.delete(controller);
|
|
231
|
+
this.clear(timeout);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** After a 429: waits what `Retry-After` says, then asks once on its own. */
|
|
235
|
+
backOff(response) {
|
|
236
|
+
const wait = retryAfterMs(response.headers.get("retry-after"));
|
|
237
|
+
if (wait <= 0) return;
|
|
238
|
+
const deadline = Date.now() + wait;
|
|
239
|
+
if (this.stopped || deadline <= this.quietUntil) return;
|
|
240
|
+
this.quietUntil = deadline;
|
|
241
|
+
if (this.retryTimer !== void 0) {
|
|
242
|
+
clearTimeout(this.retryTimer);
|
|
243
|
+
this.timers.delete(this.retryTimer);
|
|
244
|
+
}
|
|
245
|
+
this.retryTimer = this.after(wait, () => {
|
|
246
|
+
this.retryTimer = void 0;
|
|
247
|
+
return this.load();
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/** Takes a ruleset only if it is newer than the one held: an older answer never replaces newer data. */
|
|
251
|
+
take(ruleset, etag) {
|
|
252
|
+
const version = BigInt(ruleset.version);
|
|
253
|
+
if (this.held !== void 0 && version <= this.held) return;
|
|
254
|
+
this.compiled = compile(ruleset);
|
|
255
|
+
this.held = version;
|
|
256
|
+
this.etag = etag ?? `"${ruleset.version}"`;
|
|
257
|
+
if (this.settled) this.changed();
|
|
258
|
+
}
|
|
259
|
+
changed() {
|
|
260
|
+
for (const listener of [...this.listeners]) try {
|
|
261
|
+
listener();
|
|
262
|
+
} catch (error) {
|
|
263
|
+
console.error("@dipswitch/sdk-node: a change listener threw", error);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/** Keeps the 401 clock and stops on 403: any answer other than 401 starts the 5 minutes again. */
|
|
267
|
+
answered(status) {
|
|
268
|
+
if (status === 403) return this.stop("this is not a server key (403)");
|
|
269
|
+
if (status !== 401) {
|
|
270
|
+
this.unauthorizedSince = void 0;
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
const now = Date.now();
|
|
274
|
+
this.unauthorizedSince ??= now;
|
|
275
|
+
if (now - this.unauthorizedSince >= 3e5) this.stop("the key has been refused for 5 minutes (401)");
|
|
276
|
+
}
|
|
277
|
+
/** A `change` event: refetch after a random delay, unless the version is held already. */
|
|
278
|
+
announced(version) {
|
|
279
|
+
if (this.held !== void 0 && version <= this.held) return;
|
|
280
|
+
const running = this.wanted !== void 0;
|
|
281
|
+
if (running && version <= this.wanted) return;
|
|
282
|
+
this.wanted = version;
|
|
283
|
+
if (!running) this.after(Math.random() * REFETCH_DELAY_MAX_MS, () => this.refetch(0));
|
|
284
|
+
}
|
|
285
|
+
async refetch(retry) {
|
|
286
|
+
const answer = await this.load();
|
|
287
|
+
if (this.stopped) return;
|
|
288
|
+
const wanted = this.wanted;
|
|
289
|
+
if (this.held !== void 0 && this.held >= wanted) {
|
|
290
|
+
this.wanted = void 0;
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if ((answer.kind === "ruleset" || answer.kind === "not-modified") && retry < 5) {
|
|
294
|
+
this.after(RETRY_AFTER_MS, () => this.refetch(retry + 1));
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
this.wanted = void 0;
|
|
298
|
+
}
|
|
299
|
+
/** Holds the stream open; when it ends for any reason but a stop, opens it again after a random delay. */
|
|
300
|
+
async connect() {
|
|
301
|
+
const controller = new AbortController();
|
|
302
|
+
let idle;
|
|
303
|
+
const watch = () => {
|
|
304
|
+
this.clear(idle);
|
|
305
|
+
idle = this.after(STREAM_IDLE_MS, () => controller.abort());
|
|
306
|
+
};
|
|
307
|
+
try {
|
|
308
|
+
watch();
|
|
309
|
+
const response = await this.send("/server/stream", controller, { accept: "text/event-stream" });
|
|
310
|
+
this.answered(response.status);
|
|
311
|
+
if (response.status !== 200 || !response.body) await response.body?.cancel();
|
|
312
|
+
else {
|
|
313
|
+
const parser = new SseParser();
|
|
314
|
+
const reader = response.body.getReader();
|
|
315
|
+
for (;;) {
|
|
316
|
+
watch();
|
|
317
|
+
const { value, done } = await reader.read();
|
|
318
|
+
if (done) break;
|
|
319
|
+
for (const event of parser.push(value)) {
|
|
320
|
+
this.received(event.event, event.data);
|
|
321
|
+
if (this.stopped) break;
|
|
322
|
+
}
|
|
323
|
+
if (this.stopped) break;
|
|
324
|
+
}
|
|
325
|
+
await reader.cancel();
|
|
326
|
+
}
|
|
327
|
+
} catch {} finally {
|
|
328
|
+
this.clear(idle);
|
|
329
|
+
this.requests.delete(controller);
|
|
330
|
+
controller.abort();
|
|
331
|
+
}
|
|
332
|
+
if (!this.stopped) this.after(Math.random() * RECONNECT_MAX_MS, () => this.connect());
|
|
333
|
+
}
|
|
334
|
+
received(event, data) {
|
|
335
|
+
if (event === "revoked") return this.stop("the key was revoked");
|
|
336
|
+
if (event !== "change") return;
|
|
337
|
+
try {
|
|
338
|
+
const version = JSON.parse(data)?.version;
|
|
339
|
+
if (typeof version === "string" && VERSION.test(version)) this.announced(BigInt(version));
|
|
340
|
+
} catch {}
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
const VERSION = /^(0|[1-9][0-9]{0,18})$/;
|
|
344
|
+
const isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
345
|
+
const isOverrides = (value) => typeof value === "object" && value !== null && isStrings(value.on) && isStrings(value.off);
|
|
346
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
347
|
+
/** Whether an answer has the shape of a ruleset, so a broken answer is never taken. Fields it does not know are ignored. */
|
|
348
|
+
function isRuleset(value) {
|
|
349
|
+
if (!isRecord(value) || typeof value.env !== "string" || typeof value.version !== "string" || !VERSION.test(value.version)) return false;
|
|
350
|
+
if (!isRecord(value.flags) || !isRecord(value.segments)) return false;
|
|
351
|
+
for (const flag of Object.values(value.flags)) {
|
|
352
|
+
if (!isRecord(flag) || typeof flag.enabled !== "boolean" || typeof flag.defaultOn !== "boolean") return false;
|
|
353
|
+
if (!isOverrides(flag.users) || !isOverrides(flag.segments)) return false;
|
|
354
|
+
}
|
|
355
|
+
return Object.values(value.segments).every(isStrings);
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* `Retry-After` in milliseconds: whole seconds, or an HTTP date; 0 for none or one it cannot read.
|
|
359
|
+
* The same in sdk-js and sdk-node: sdk-js copies in only types, never code (docs/PLAN.md, SDKs: `eval`).
|
|
360
|
+
*/
|
|
361
|
+
function retryAfterMs(value) {
|
|
362
|
+
if (!value) return 0;
|
|
363
|
+
if (/^[0-9]+$/.test(value.trim())) return Number(value.trim()) * 1e3;
|
|
364
|
+
const at = Date.parse(value);
|
|
365
|
+
return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
|
|
366
|
+
}
|
|
367
|
+
// ../eval/dist/keys.js
|
|
368
|
+
/** HMAC-SHA256 for the exact UTF-8 user id, shared by the signer and verifier. */
|
|
369
|
+
function identityDigest(userId, identitySecret) {
|
|
370
|
+
return (0, node_crypto.createHmac)("sha256", identitySecret).update(userId).digest();
|
|
371
|
+
}
|
|
372
|
+
// src/identity.ts
|
|
373
|
+
/** Signs a user id on your backend with a client key's identity secret. */
|
|
374
|
+
function signIdentity(userId, identitySecret) {
|
|
375
|
+
return identityDigest(userId, identitySecret).toString("hex");
|
|
376
|
+
}
|
|
377
|
+
exports.createClient = createClient;
|
|
378
|
+
exports.signIdentity = signIdentity;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** A local SDK lookup, which can distinguish an empty cache from a missing key. */
|
|
2
|
+
type FlagDetails<Reason extends string> = {
|
|
3
|
+
readonly value: boolean;
|
|
4
|
+
readonly reason: Reason;
|
|
5
|
+
} | {
|
|
6
|
+
readonly value: undefined;
|
|
7
|
+
readonly reason: 'NOT_READY' | 'FLAG_NOT_FOUND';
|
|
8
|
+
};
|
|
9
|
+
interface ClientOptions {
|
|
10
|
+
/** A server key of one application and environment. Secret: it is only ever sent in a header. */
|
|
11
|
+
serverKey: string;
|
|
12
|
+
/** The address of `edge`. `https://edge.dipswitch.co` when not given. */
|
|
13
|
+
edgeUrl?: string;
|
|
14
|
+
}
|
|
15
|
+
interface DipswitchClient {
|
|
16
|
+
/**
|
|
17
|
+
* Settles once the first load is done or has failed; never rejects. Until
|
|
18
|
+
* then, and while nothing could be loaded, every check returns its default.
|
|
19
|
+
*/
|
|
20
|
+
readonly ready: Promise<void>;
|
|
21
|
+
/** Version of the ruleset in memory, when one has loaded. */
|
|
22
|
+
readonly snapshotVersion: bigint | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* The flag's value for this user, read from memory. `defaultValue` when the
|
|
25
|
+
* SDK has no data for the flag: not loaded yet, deleted, or not assigned to
|
|
26
|
+
* this application. Without a user id (`undefined`), no override applies.
|
|
27
|
+
*/
|
|
28
|
+
isEnabled(flagKey: string, userId: string | undefined, defaultValue: boolean): boolean;
|
|
29
|
+
/** The current value and its reason, or why no value can be read. */
|
|
30
|
+
getFlagDetails(flagKey: string, userId?: string): FlagDetails<'STATIC' | 'TARGETING_MATCH' | 'DISABLED'>;
|
|
31
|
+
/** Calls `listener` whenever newer flags have arrived after `ready`. Returns what removes it. */
|
|
32
|
+
onChange(listener: () => void): () => void;
|
|
33
|
+
/** Stops every request and timer. The values held stay readable. */
|
|
34
|
+
close(): void;
|
|
35
|
+
}
|
|
36
|
+
export declare function createClient(options: ClientOptions): DipswitchClient;
|
|
37
|
+
/** Signs a user id on your backend with a client key's identity secret. */
|
|
38
|
+
export declare function signIdentity(userId: string, identitySecret: string): string;
|
|
39
|
+
export type { ClientOptions, DipswitchClient };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** A local SDK lookup, which can distinguish an empty cache from a missing key. */
|
|
2
|
+
type FlagDetails<Reason extends string> = {
|
|
3
|
+
readonly value: boolean;
|
|
4
|
+
readonly reason: Reason;
|
|
5
|
+
} | {
|
|
6
|
+
readonly value: undefined;
|
|
7
|
+
readonly reason: 'NOT_READY' | 'FLAG_NOT_FOUND';
|
|
8
|
+
};
|
|
9
|
+
interface ClientOptions {
|
|
10
|
+
/** A server key of one application and environment. Secret: it is only ever sent in a header. */
|
|
11
|
+
serverKey: string;
|
|
12
|
+
/** The address of `edge`. `https://edge.dipswitch.co` when not given. */
|
|
13
|
+
edgeUrl?: string;
|
|
14
|
+
}
|
|
15
|
+
interface DipswitchClient {
|
|
16
|
+
/**
|
|
17
|
+
* Settles once the first load is done or has failed; never rejects. Until
|
|
18
|
+
* then, and while nothing could be loaded, every check returns its default.
|
|
19
|
+
*/
|
|
20
|
+
readonly ready: Promise<void>;
|
|
21
|
+
/** Version of the ruleset in memory, when one has loaded. */
|
|
22
|
+
readonly snapshotVersion: bigint | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* The flag's value for this user, read from memory. `defaultValue` when the
|
|
25
|
+
* SDK has no data for the flag: not loaded yet, deleted, or not assigned to
|
|
26
|
+
* this application. Without a user id (`undefined`), no override applies.
|
|
27
|
+
*/
|
|
28
|
+
isEnabled(flagKey: string, userId: string | undefined, defaultValue: boolean): boolean;
|
|
29
|
+
/** The current value and its reason, or why no value can be read. */
|
|
30
|
+
getFlagDetails(flagKey: string, userId?: string): FlagDetails<'STATIC' | 'TARGETING_MATCH' | 'DISABLED'>;
|
|
31
|
+
/** Calls `listener` whenever newer flags have arrived after `ready`. Returns what removes it. */
|
|
32
|
+
onChange(listener: () => void): () => void;
|
|
33
|
+
/** Stops every request and timer. The values held stay readable. */
|
|
34
|
+
close(): void;
|
|
35
|
+
}
|
|
36
|
+
export declare function createClient(options: ClientOptions): DipswitchClient;
|
|
37
|
+
/** Signs a user id on your backend with a client key's identity secret. */
|
|
38
|
+
export declare function signIdentity(userId: string, identitySecret: string): string;
|
|
39
|
+
export type { ClientOptions, DipswitchClient };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
// ../eval/dist/evaluate.js
|
|
3
|
+
/**
|
|
4
|
+
* Prepares a ruleset for `evaluate`. Expects a ruleset the schema accepts;
|
|
5
|
+
* for one it would refuse, it still does not throw: a segment that is not
|
|
6
|
+
* listed counts as empty, and a user listed both on and off is off.
|
|
7
|
+
* Maps and sets, not objects, so an id such as `__proto__` is an id like any other.
|
|
8
|
+
*/
|
|
9
|
+
function compile(ruleset) {
|
|
10
|
+
const segments = /* @__PURE__ */ new Map();
|
|
11
|
+
for (const [key, members] of Object.entries(ruleset.segments)) segments.set(key, new Set(members));
|
|
12
|
+
const members = (key) => segments.get(key) ?? /* @__PURE__ */ new Set();
|
|
13
|
+
const flags = /* @__PURE__ */ new Map();
|
|
14
|
+
for (const [key, flag] of Object.entries(ruleset.flags)) {
|
|
15
|
+
const users = /* @__PURE__ */ new Map();
|
|
16
|
+
for (const id of flag.users.on) users.set(id, true);
|
|
17
|
+
for (const id of flag.users.off) users.set(id, false);
|
|
18
|
+
flags.set(key, {
|
|
19
|
+
enabled: flag.enabled,
|
|
20
|
+
defaultOn: flag.defaultOn,
|
|
21
|
+
users,
|
|
22
|
+
segmentsOn: flag.segments.on.map(members),
|
|
23
|
+
segmentsOff: flag.segments.off.map(members)
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
version: ruleset.version,
|
|
28
|
+
flags
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const disabled = {
|
|
32
|
+
value: false,
|
|
33
|
+
reason: "DISABLED"
|
|
34
|
+
};
|
|
35
|
+
const targetedOff = {
|
|
36
|
+
value: false,
|
|
37
|
+
reason: "TARGETING_MATCH"
|
|
38
|
+
};
|
|
39
|
+
const targetedOn = {
|
|
40
|
+
value: true,
|
|
41
|
+
reason: "TARGETING_MATCH"
|
|
42
|
+
};
|
|
43
|
+
const defaultOff = {
|
|
44
|
+
value: false,
|
|
45
|
+
reason: "STATIC"
|
|
46
|
+
};
|
|
47
|
+
const defaultOn = {
|
|
48
|
+
value: true,
|
|
49
|
+
reason: "STATIC"
|
|
50
|
+
};
|
|
51
|
+
/** The same evaluation, with the rule that decided the value. */
|
|
52
|
+
function evaluateWithReason(ruleset, flagKey, userId) {
|
|
53
|
+
const flag = ruleset.flags.get(flagKey);
|
|
54
|
+
if (flag === void 0) return void 0;
|
|
55
|
+
if (!flag.enabled) return disabled;
|
|
56
|
+
if (userId !== void 0) {
|
|
57
|
+
const own = flag.users.get(userId);
|
|
58
|
+
if (own !== void 0) return own ? targetedOn : targetedOff;
|
|
59
|
+
if (flag.segmentsOff.some((segment) => segment.has(userId))) return targetedOff;
|
|
60
|
+
if (flag.segmentsOn.some((segment) => segment.has(userId))) return targetedOn;
|
|
61
|
+
}
|
|
62
|
+
return flag.defaultOn ? defaultOn : defaultOff;
|
|
63
|
+
}
|
|
64
|
+
// src/sse.ts
|
|
65
|
+
var SseParser = class {
|
|
66
|
+
decoder = new TextDecoder();
|
|
67
|
+
buffer = "";
|
|
68
|
+
event = "";
|
|
69
|
+
data = [];
|
|
70
|
+
/** Takes the next bytes of the stream; returns the events they complete. */
|
|
71
|
+
push(chunk) {
|
|
72
|
+
this.buffer += this.decoder.decode(chunk, { stream: true });
|
|
73
|
+
const events = [];
|
|
74
|
+
for (;;) {
|
|
75
|
+
const end = this.buffer.search(/\r\n|\r|\n/);
|
|
76
|
+
if (end < 0) break;
|
|
77
|
+
if (this.buffer[end] === "\r" && end === this.buffer.length - 1) break;
|
|
78
|
+
const line = this.buffer.slice(0, end);
|
|
79
|
+
this.buffer = this.buffer.slice(end + (this.buffer.startsWith("\r\n", end) ? 2 : 1));
|
|
80
|
+
if (line === "") {
|
|
81
|
+
if (this.data.length > 0) events.push({
|
|
82
|
+
event: this.event || "message",
|
|
83
|
+
data: this.data.join("\n")
|
|
84
|
+
});
|
|
85
|
+
this.event = "";
|
|
86
|
+
this.data = [];
|
|
87
|
+
} else if (!line.startsWith(":")) {
|
|
88
|
+
const colon = line.indexOf(":");
|
|
89
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
90
|
+
const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
91
|
+
if (field === "event") this.event = value;
|
|
92
|
+
else if (field === "data") this.data.push(value);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return events;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const POLL_EVERY_MS = 3e4;
|
|
99
|
+
/** The refetch after an event waits a random time up to this, so one change does not hit `edge` from every server at once. */
|
|
100
|
+
const REFETCH_DELAY_MAX_MS = 2e3;
|
|
101
|
+
/** When a refetch finds an older version than the event's, or "not modified": wait, ask again, at most so many times. */
|
|
102
|
+
const RETRY_AFTER_MS = 1e3;
|
|
103
|
+
/** A stream that ended is opened again after a random time up to this. */
|
|
104
|
+
const RECONNECT_MAX_MS = 3e4;
|
|
105
|
+
/** A request with no answer by then is given up. */
|
|
106
|
+
const REQUEST_TIMEOUT_MS = 1e4;
|
|
107
|
+
/** `edge` sends the heartbeat every 30 seconds: a stream silent for this long is dead and is opened again. */
|
|
108
|
+
const STREAM_IDLE_MS = 75e3;
|
|
109
|
+
function createClient(options) {
|
|
110
|
+
if (typeof options?.serverKey !== "string" || options.serverKey === "") throw new TypeError("createClient needs a `serverKey`.");
|
|
111
|
+
return new Client(options.serverKey, (options.edgeUrl ?? "https://edge.dipswitch.co").replace(/\/+$/, ""));
|
|
112
|
+
}
|
|
113
|
+
var Client = class {
|
|
114
|
+
key;
|
|
115
|
+
base;
|
|
116
|
+
ready;
|
|
117
|
+
compiled;
|
|
118
|
+
held;
|
|
119
|
+
etag;
|
|
120
|
+
settled = false;
|
|
121
|
+
stopped = false;
|
|
122
|
+
listeners = /* @__PURE__ */ new Set();
|
|
123
|
+
timers = /* @__PURE__ */ new Set();
|
|
124
|
+
requests = /* @__PURE__ */ new Set();
|
|
125
|
+
poller;
|
|
126
|
+
/** The newest version an event announced that is not held yet, while a refetch for it is under way. */
|
|
127
|
+
wanted;
|
|
128
|
+
/** Since when every answer has been a 401. */
|
|
129
|
+
unauthorizedSince;
|
|
130
|
+
/** After a 429: no request for the ruleset before this time (docs/PLAN.md, Wire contract: When answers fail). */
|
|
131
|
+
quietUntil = 0;
|
|
132
|
+
retryTimer;
|
|
133
|
+
constructor(key, base) {
|
|
134
|
+
this.key = key;
|
|
135
|
+
this.base = base;
|
|
136
|
+
this.ready = this.load().then(() => {
|
|
137
|
+
this.settled = true;
|
|
138
|
+
if (this.stopped) return;
|
|
139
|
+
this.poller = setInterval(() => void this.load(), POLL_EVERY_MS);
|
|
140
|
+
this.connect();
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
isEnabled(flagKey, userId, defaultValue) {
|
|
144
|
+
return this.getFlagDetails(flagKey, userId).value ?? defaultValue;
|
|
145
|
+
}
|
|
146
|
+
get snapshotVersion() {
|
|
147
|
+
return this.held;
|
|
148
|
+
}
|
|
149
|
+
getFlagDetails(flagKey, userId) {
|
|
150
|
+
if (!this.compiled) return {
|
|
151
|
+
value: void 0,
|
|
152
|
+
reason: "NOT_READY"
|
|
153
|
+
};
|
|
154
|
+
return evaluateWithReason(this.compiled, flagKey, userId ?? void 0) ?? {
|
|
155
|
+
value: void 0,
|
|
156
|
+
reason: "FLAG_NOT_FOUND"
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
onChange(listener) {
|
|
160
|
+
this.listeners.add(listener);
|
|
161
|
+
return () => void this.listeners.delete(listener);
|
|
162
|
+
}
|
|
163
|
+
close() {
|
|
164
|
+
this.stopped = true;
|
|
165
|
+
clearInterval(this.poller);
|
|
166
|
+
for (const timer of this.timers) clearTimeout(timer);
|
|
167
|
+
this.timers.clear();
|
|
168
|
+
for (const request of this.requests) request.abort();
|
|
169
|
+
this.requests.clear();
|
|
170
|
+
this.listeners.clear();
|
|
171
|
+
}
|
|
172
|
+
/** Stops for good, keeping the values: a revoked key, a key of the wrong kind, or 5 minutes of 401. */
|
|
173
|
+
stop(reason) {
|
|
174
|
+
if (this.stopped) return;
|
|
175
|
+
console.warn(`@dipswitch/sdk-node: stopped (${reason}); flags keep their last values.`);
|
|
176
|
+
this.close();
|
|
177
|
+
}
|
|
178
|
+
/** A timer that `close()` clears. */
|
|
179
|
+
after(ms, work) {
|
|
180
|
+
const timer = setTimeout(() => {
|
|
181
|
+
this.timers.delete(timer);
|
|
182
|
+
if (!this.stopped) work();
|
|
183
|
+
}, ms);
|
|
184
|
+
this.timers.add(timer);
|
|
185
|
+
return timer;
|
|
186
|
+
}
|
|
187
|
+
/** A request to `edge` with the key in a header, never in the URL. `close()` aborts it through `controller`. */
|
|
188
|
+
send(path, controller, headers = {}) {
|
|
189
|
+
this.requests.add(controller);
|
|
190
|
+
return fetch(`${this.base}${path}`, {
|
|
191
|
+
headers: {
|
|
192
|
+
authorization: `Bearer ${this.key}`,
|
|
193
|
+
...headers
|
|
194
|
+
},
|
|
195
|
+
signal: controller.signal
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
clear(timer) {
|
|
199
|
+
if (timer === void 0) return;
|
|
200
|
+
clearTimeout(timer);
|
|
201
|
+
this.timers.delete(timer);
|
|
202
|
+
}
|
|
203
|
+
/** Fetches the ruleset, with the ETag of the one held, and takes it if it is newer. Never throws. */
|
|
204
|
+
async load() {
|
|
205
|
+
if (this.stopped || Date.now() < this.quietUntil) return { kind: "failed" };
|
|
206
|
+
const controller = new AbortController();
|
|
207
|
+
const timeout = this.after(REQUEST_TIMEOUT_MS, () => controller.abort());
|
|
208
|
+
try {
|
|
209
|
+
const response = await this.send("/server/ruleset", controller, this.etag ? { "if-none-match": this.etag } : {});
|
|
210
|
+
this.answered(response.status);
|
|
211
|
+
if (response.status === 429) this.backOff(response);
|
|
212
|
+
if (response.status !== 200) {
|
|
213
|
+
await response.body?.cancel();
|
|
214
|
+
return response.status === 304 ? { kind: "not-modified" } : {
|
|
215
|
+
kind: "status",
|
|
216
|
+
status: response.status
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
const body = await response.json();
|
|
220
|
+
if (!isRuleset(body)) return { kind: "failed" };
|
|
221
|
+
this.take(body, response.headers.get("etag"));
|
|
222
|
+
return {
|
|
223
|
+
kind: "ruleset",
|
|
224
|
+
version: BigInt(body.version)
|
|
225
|
+
};
|
|
226
|
+
} catch {
|
|
227
|
+
return { kind: "failed" };
|
|
228
|
+
} finally {
|
|
229
|
+
this.requests.delete(controller);
|
|
230
|
+
this.clear(timeout);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
/** After a 429: waits what `Retry-After` says, then asks once on its own. */
|
|
234
|
+
backOff(response) {
|
|
235
|
+
const wait = retryAfterMs(response.headers.get("retry-after"));
|
|
236
|
+
if (wait <= 0) return;
|
|
237
|
+
const deadline = Date.now() + wait;
|
|
238
|
+
if (this.stopped || deadline <= this.quietUntil) return;
|
|
239
|
+
this.quietUntil = deadline;
|
|
240
|
+
if (this.retryTimer !== void 0) {
|
|
241
|
+
clearTimeout(this.retryTimer);
|
|
242
|
+
this.timers.delete(this.retryTimer);
|
|
243
|
+
}
|
|
244
|
+
this.retryTimer = this.after(wait, () => {
|
|
245
|
+
this.retryTimer = void 0;
|
|
246
|
+
return this.load();
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
/** Takes a ruleset only if it is newer than the one held: an older answer never replaces newer data. */
|
|
250
|
+
take(ruleset, etag) {
|
|
251
|
+
const version = BigInt(ruleset.version);
|
|
252
|
+
if (this.held !== void 0 && version <= this.held) return;
|
|
253
|
+
this.compiled = compile(ruleset);
|
|
254
|
+
this.held = version;
|
|
255
|
+
this.etag = etag ?? `"${ruleset.version}"`;
|
|
256
|
+
if (this.settled) this.changed();
|
|
257
|
+
}
|
|
258
|
+
changed() {
|
|
259
|
+
for (const listener of [...this.listeners]) try {
|
|
260
|
+
listener();
|
|
261
|
+
} catch (error) {
|
|
262
|
+
console.error("@dipswitch/sdk-node: a change listener threw", error);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/** Keeps the 401 clock and stops on 403: any answer other than 401 starts the 5 minutes again. */
|
|
266
|
+
answered(status) {
|
|
267
|
+
if (status === 403) return this.stop("this is not a server key (403)");
|
|
268
|
+
if (status !== 401) {
|
|
269
|
+
this.unauthorizedSince = void 0;
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const now = Date.now();
|
|
273
|
+
this.unauthorizedSince ??= now;
|
|
274
|
+
if (now - this.unauthorizedSince >= 3e5) this.stop("the key has been refused for 5 minutes (401)");
|
|
275
|
+
}
|
|
276
|
+
/** A `change` event: refetch after a random delay, unless the version is held already. */
|
|
277
|
+
announced(version) {
|
|
278
|
+
if (this.held !== void 0 && version <= this.held) return;
|
|
279
|
+
const running = this.wanted !== void 0;
|
|
280
|
+
if (running && version <= this.wanted) return;
|
|
281
|
+
this.wanted = version;
|
|
282
|
+
if (!running) this.after(Math.random() * REFETCH_DELAY_MAX_MS, () => this.refetch(0));
|
|
283
|
+
}
|
|
284
|
+
async refetch(retry) {
|
|
285
|
+
const answer = await this.load();
|
|
286
|
+
if (this.stopped) return;
|
|
287
|
+
const wanted = this.wanted;
|
|
288
|
+
if (this.held !== void 0 && this.held >= wanted) {
|
|
289
|
+
this.wanted = void 0;
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if ((answer.kind === "ruleset" || answer.kind === "not-modified") && retry < 5) {
|
|
293
|
+
this.after(RETRY_AFTER_MS, () => this.refetch(retry + 1));
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
this.wanted = void 0;
|
|
297
|
+
}
|
|
298
|
+
/** Holds the stream open; when it ends for any reason but a stop, opens it again after a random delay. */
|
|
299
|
+
async connect() {
|
|
300
|
+
const controller = new AbortController();
|
|
301
|
+
let idle;
|
|
302
|
+
const watch = () => {
|
|
303
|
+
this.clear(idle);
|
|
304
|
+
idle = this.after(STREAM_IDLE_MS, () => controller.abort());
|
|
305
|
+
};
|
|
306
|
+
try {
|
|
307
|
+
watch();
|
|
308
|
+
const response = await this.send("/server/stream", controller, { accept: "text/event-stream" });
|
|
309
|
+
this.answered(response.status);
|
|
310
|
+
if (response.status !== 200 || !response.body) await response.body?.cancel();
|
|
311
|
+
else {
|
|
312
|
+
const parser = new SseParser();
|
|
313
|
+
const reader = response.body.getReader();
|
|
314
|
+
for (;;) {
|
|
315
|
+
watch();
|
|
316
|
+
const { value, done } = await reader.read();
|
|
317
|
+
if (done) break;
|
|
318
|
+
for (const event of parser.push(value)) {
|
|
319
|
+
this.received(event.event, event.data);
|
|
320
|
+
if (this.stopped) break;
|
|
321
|
+
}
|
|
322
|
+
if (this.stopped) break;
|
|
323
|
+
}
|
|
324
|
+
await reader.cancel();
|
|
325
|
+
}
|
|
326
|
+
} catch {} finally {
|
|
327
|
+
this.clear(idle);
|
|
328
|
+
this.requests.delete(controller);
|
|
329
|
+
controller.abort();
|
|
330
|
+
}
|
|
331
|
+
if (!this.stopped) this.after(Math.random() * RECONNECT_MAX_MS, () => this.connect());
|
|
332
|
+
}
|
|
333
|
+
received(event, data) {
|
|
334
|
+
if (event === "revoked") return this.stop("the key was revoked");
|
|
335
|
+
if (event !== "change") return;
|
|
336
|
+
try {
|
|
337
|
+
const version = JSON.parse(data)?.version;
|
|
338
|
+
if (typeof version === "string" && VERSION.test(version)) this.announced(BigInt(version));
|
|
339
|
+
} catch {}
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
const VERSION = /^(0|[1-9][0-9]{0,18})$/;
|
|
343
|
+
const isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
344
|
+
const isOverrides = (value) => typeof value === "object" && value !== null && isStrings(value.on) && isStrings(value.off);
|
|
345
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
346
|
+
/** Whether an answer has the shape of a ruleset, so a broken answer is never taken. Fields it does not know are ignored. */
|
|
347
|
+
function isRuleset(value) {
|
|
348
|
+
if (!isRecord(value) || typeof value.env !== "string" || typeof value.version !== "string" || !VERSION.test(value.version)) return false;
|
|
349
|
+
if (!isRecord(value.flags) || !isRecord(value.segments)) return false;
|
|
350
|
+
for (const flag of Object.values(value.flags)) {
|
|
351
|
+
if (!isRecord(flag) || typeof flag.enabled !== "boolean" || typeof flag.defaultOn !== "boolean") return false;
|
|
352
|
+
if (!isOverrides(flag.users) || !isOverrides(flag.segments)) return false;
|
|
353
|
+
}
|
|
354
|
+
return Object.values(value.segments).every(isStrings);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* `Retry-After` in milliseconds: whole seconds, or an HTTP date; 0 for none or one it cannot read.
|
|
358
|
+
* The same in sdk-js and sdk-node: sdk-js copies in only types, never code (docs/PLAN.md, SDKs: `eval`).
|
|
359
|
+
*/
|
|
360
|
+
function retryAfterMs(value) {
|
|
361
|
+
if (!value) return 0;
|
|
362
|
+
if (/^[0-9]+$/.test(value.trim())) return Number(value.trim()) * 1e3;
|
|
363
|
+
const at = Date.parse(value);
|
|
364
|
+
return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
|
|
365
|
+
}
|
|
366
|
+
// ../eval/dist/keys.js
|
|
367
|
+
/** HMAC-SHA256 for the exact UTF-8 user id, shared by the signer and verifier. */
|
|
368
|
+
function identityDigest(userId, identitySecret) {
|
|
369
|
+
return createHmac("sha256", identitySecret).update(userId).digest();
|
|
370
|
+
}
|
|
371
|
+
// src/identity.ts
|
|
372
|
+
/** Signs a user id on your backend with a client key's identity secret. */
|
|
373
|
+
function signIdentity(userId, identitySecret) {
|
|
374
|
+
return identityDigest(userId, identitySecret).toString("hex");
|
|
375
|
+
}
|
|
376
|
+
export { createClient, signIdentity };
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dipswitch/sdk-node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Dipswitch feature flags for Node: the rules in memory, checks with no network call, changes within seconds.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=20"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"import": {
|
|
13
|
+
"types": "./dist/index.d.mts",
|
|
14
|
+
"default": "./dist/index.mjs"
|
|
15
|
+
},
|
|
16
|
+
"require": {
|
|
17
|
+
"types": "./dist/index.d.cts",
|
|
18
|
+
"default": "./dist/index.cjs"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"main": "./dist/index.cjs",
|
|
23
|
+
"module": "./dist/index.mjs",
|
|
24
|
+
"types": "./dist/index.d.cts",
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"sideEffects": false
|
|
6
29
|
}
|