@dipswitch/sdk-js 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 +55 -2
- package/dist/index.d.ts +57 -0
- package/dist/index.js +1 -0
- package/package.json +16 -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,56 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dipswitch/sdk-js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Dipswitch feature flags in the browser. The client loads one user's values, reuses cached flags when available and follows changes within seconds. No dependencies.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
Until the packages are on npm, install the tarball:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install ./dipswitch-sdk-js-0.1.0.tgz
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## First use
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createClient } from '@dipswitch/sdk-js'
|
|
17
|
+
|
|
18
|
+
// The client key of your application and environment. It is public: it goes in the page.
|
|
19
|
+
const flags = createClient({ clientKey: 'ds_client_...', user: { id: 'user-42', name: 'Ana Petrović' } })
|
|
20
|
+
|
|
21
|
+
// Settles once the flags are loaded, or after 3 seconds; it never hangs.
|
|
22
|
+
await flags.ready
|
|
23
|
+
if (flags.isEnabled('new-billing', false)) {
|
|
24
|
+
// show the new billing page
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Another user signs in: until their values arrive, checks return their cached values or the defaults.
|
|
28
|
+
await flags.identify({ id: 'user-7', name: 'Boris Ilić' })
|
|
29
|
+
|
|
30
|
+
// Called whenever the values change.
|
|
31
|
+
const stop = flags.onChange(() => console.log('flags changed'))
|
|
32
|
+
stop()
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Without `user`, the client reads the values for "no user", as on a signed-out page, and nobody is recorded. A user id Dipswitch would not take (empty, over 256 characters, holding NUL, `.` or `..`) counts as no user, with a warning in the console; a name over 256 characters is cut.
|
|
36
|
+
|
|
37
|
+
## Identity verification
|
|
38
|
+
|
|
39
|
+
When an environment verifies identity, your backend signs the authenticated user's ID with the client key's identity secret. Send the user and signature to the browser. The SDK keeps the signed values separate from unsigned values and uses your flag defaults if Edge refuses the signature.
|
|
40
|
+
|
|
41
|
+
Browsers with Web Crypto digest support can reuse a signed cache after a reload. Other browsers keep signed values in memory.
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { createClient } from '@dipswitch/sdk-js'
|
|
45
|
+
|
|
46
|
+
type SignedUser = { id: string; name?: string; signature: string }
|
|
47
|
+
|
|
48
|
+
export function startFlags(clientKey: string, first: SignedUser) {
|
|
49
|
+
const flags = createClient({ clientKey, user: { id: first.id, name: first.name }, signature: first.signature })
|
|
50
|
+
return {
|
|
51
|
+
flags,
|
|
52
|
+
switchUser: (next: SignedUser) => flags.identify({ id: next.id, name: next.name }, next.signature),
|
|
53
|
+
signOut: () => flags.identify(undefined),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
interface ClientUser {
|
|
2
|
+
id: string;
|
|
3
|
+
name?: string;
|
|
4
|
+
}
|
|
5
|
+
/** A local SDK lookup, which can distinguish an empty cache from a missing key. */
|
|
6
|
+
type FlagDetails<Reason extends string> = {
|
|
7
|
+
readonly value: boolean;
|
|
8
|
+
readonly reason: Reason;
|
|
9
|
+
} | {
|
|
10
|
+
readonly value: undefined;
|
|
11
|
+
readonly reason: 'NOT_READY' | 'FLAG_NOT_FOUND';
|
|
12
|
+
};
|
|
13
|
+
/** Keeps time for the request and rendering in adapters with a five-second update check. */
|
|
14
|
+
export declare const ADAPTER_REFETCH_DELAY_MAX_MS = 4000;
|
|
15
|
+
interface ClientOptions {
|
|
16
|
+
/** A client key. It is public: it goes in the page and in URLs. */
|
|
17
|
+
clientKey: string;
|
|
18
|
+
/** The address of `edge`. `https://edge.dipswitch.co` when not given. */
|
|
19
|
+
edgeUrl?: string;
|
|
20
|
+
/**
|
|
21
|
+
* The signed-in user. Without one, the values for "no user", as on a signed-out
|
|
22
|
+
* page; an id `edge` would not take (empty, over 256 characters, holding NUL,
|
|
23
|
+
* `.` or `..`) counts as no user, with a warning in the console.
|
|
24
|
+
*/
|
|
25
|
+
user?: ClientUser;
|
|
26
|
+
/** A signature for `user` from your backend if the environment verifies identity. */
|
|
27
|
+
signature?: string;
|
|
28
|
+
/** How long `ready` and `identify` wait at most, in milliseconds. 3000 when not given. */
|
|
29
|
+
timeoutMs?: number;
|
|
30
|
+
/** `false` opens no stream: changes then arrive by polling every 60 seconds and when the tab is shown again. */
|
|
31
|
+
stream?: boolean;
|
|
32
|
+
/** Lower the maximum random delay before fetching flags after a stream event, in milliseconds. */
|
|
33
|
+
refetchDelayMaxMs?: number;
|
|
34
|
+
}
|
|
35
|
+
interface DipswitchClient {
|
|
36
|
+
/** Settles when the values are loaded, when loading failed, or after the timeout. Never rejects. */
|
|
37
|
+
readonly ready: Promise<void>;
|
|
38
|
+
/** Version of the current user's values, when a snapshot is available. */
|
|
39
|
+
readonly snapshotVersion: bigint | undefined;
|
|
40
|
+
/** The current user's value of a flag, or `defaultValue` when there is none: not loaded yet, deleted, or not for this application. */
|
|
41
|
+
isEnabled(flagKey: string, defaultValue: boolean): boolean;
|
|
42
|
+
/** The current user's loaded value, or why no value can be read. */
|
|
43
|
+
getFlagDetails(flagKey: string): FlagDetails<'CACHED'>;
|
|
44
|
+
/**
|
|
45
|
+
* Switches the user (`undefined` for no user; an id `edge` would not take
|
|
46
|
+
* counts as no user, as in `user`). Pass the signature for the new user when
|
|
47
|
+
* required. Until values arrive, checks read only this user and signature's
|
|
48
|
+
* cached values or the defaults. Settles like `ready`.
|
|
49
|
+
*/
|
|
50
|
+
identify(user: ClientUser | undefined, signature?: string): Promise<void>;
|
|
51
|
+
/** Calls `listener` whenever the values `isEnabled` reads change. Returns what removes it. */
|
|
52
|
+
onChange(listener: () => void): () => void;
|
|
53
|
+
/** Stops every request, timer and listener. The values stay readable. */
|
|
54
|
+
close(): void;
|
|
55
|
+
}
|
|
56
|
+
export declare function createClient(options: ClientOptions): DipswitchClient;
|
|
57
|
+
export type { ClientOptions, ClientUser, DipswitchClient };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=4e3,t=/^(0|[1-9]\d{0,18})$/,n=e=>{let{version:n,flags:r}=e??{};return typeof n==`string`&&t.test(n)&&typeof r==`object`&&!!r&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e==`boolean`)};function r(e){if(e==null)return;let t=typeof e==`object`?e.id:void 0,n=typeof t==`string`?[...t].length:0;if(typeof t!=`string`||n===0||n>256||t.includes(`\0`)||t===`.`||t===`..`){console.warn(`@dipswitch/sdk-js: this user id is not one edge takes (1 to 256 characters, no NUL, not . or ..); checking with no user.`);return}let r=e.name;return typeof r!=`string`||r.includes(`\0`)?{id:t}:{id:t,name:[...r].length>256?[...r].slice(0,256).join(``):r}}async function i(e,t,n){try{let r=await globalThis.crypto?.subtle?.digest(`SHA-256`,new TextEncoder().encode(n));if(!r)return;let i=Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,`0`)).join(``);return`dipswitch-signed:${JSON.stringify([e,t,i])}`}catch{}}function a(e,t,n){let a=r(t),o=a&&typeof n==`string`?n:void 0;return{body:a?{user:a,signature:o}:{},cacheKey:a&&o!==void 0?i(e,a.id,o):`dipswitch:${e}:${a?.id??``}`,requests:0,accepted:0,refused:0}}function o(e){let r=e?.clientKey;if(typeof r!=`string`||!r)throw TypeError("createClient needs a `clientKey`.");let i=`${(e.edgeUrl??`https://edge.dipswitch.co`).replace(/\/+$/,``)}/client/`,o=`?key=${encodeURIComponent(r)}`,c=e.timeoutMs??3e3,l=e.refetchDelayMaxMs??5e3,u=l>=0&&l<5e3?l:5e3,d=typeof document>`u`?void 0:document,f=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Set,h=a(r,e.user,e.signature),g,_=!1,v,y,b=0,x,S,C=(e,t)=>{let n=setTimeout(()=>{p.delete(n),_||t()},e);return p.add(n),n},w=()=>{for(let e of[...f])try{e()}catch(e){console.error(`@dipswitch/sdk-js: a change listener threw`,e)}},T=(e,t)=>{let n=e=>{if(e)try{t(e)}catch{}};if(typeof e==`string`)n(e);else return e.then(n)},E=()=>{let e=h;return T(e.cacheKey,t=>{if(e!==h||_||g||e.refused)return;let r=JSON.parse(localStorage.getItem(t)??`null`);n(r)&&(g={version:BigInt(r.version),flags:r.flags},typeof e.cacheKey!=`string`&&w())})},D=()=>{_=!0,clearInterval(R);for(let e of p)clearTimeout(e);for(let e of m)e.abort();S?.close(),d?.removeEventListener(`visibilitychange`,I),f.clear()},O=e=>{_||(console.warn(`@dipswitch/sdk-js: stopped (${e}); flags keep their last values.`),D())},k=e=>{if(e===403)return O(`this is not a client key (403)`);if(e!==401)return y=void 0;let t=Date.now();y??=t,t-y>=3e5&&O(`the key has been refused for 5 minutes (401)`)},A=e=>{let t=s(e.headers.get(`retry-after`));if(t<=0)return;let n=Date.now()+t;_||n<=b||(b=n,x!==void 0&&(clearTimeout(x),p.delete(x)),x=C(t,()=>(x=void 0,j())))},j=async()=>{if(_||Date.now()<b)return!1;let e=h,t=++e.requests,r=new AbortController;m.add(r);let a=C(1e4,()=>r.abort());try{let a=await fetch(`${i}flags${o}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e.body),signal:r.signal});k(a.status),a.status===429&&A(a);let s=a.status===200||a.status===400?await a.json():void 0;if(e!==h||_||t<=e.refused)return!1;if(a.status===400&&s?.error?.code===`invalid_identity`){if(t<e.accepted)return!1;e.refused=t;let n=g!==void 0;g=void 0;let r=T(e.cacheKey,n=>{if(e.refused!==t||e.accepted>t)return;let r=h.body.user?.id===e.body.user?.id&&h.body.signature===e.body.signature;h!==e&&r&&h.accepted||localStorage.removeItem(n)});return n&&w(),await r,!1}if(a.status!==200||!n(s))return!1;e.accepted=Math.max(e.accepted,t);let c=BigInt(s.version);if(!g||c>g.version){let t={version:c,flags:s.flags};g=t;let n=T(e.cacheKey,n=>{e===h&&!_&&g===t&&localStorage.setItem(n,JSON.stringify({version:s.version,flags:s.flags}))});w(),await n}return!0}catch{return!1}finally{m.delete(r),clearTimeout(a),p.delete(a)}},M=e=>new Promise(t=>{let n=setTimeout(t,c);e.then(()=>{clearTimeout(n),t()})}),N=async e=>{let t=g&&g.version>=v?!1:await j();_||(g&&g.version>=v?v=void 0:t&&e<5?C(1e3,()=>N(e+1)):v=void 0)},P=e=>{if(g&&e<=g.version)return;let t=v!==void 0;t&&e<=v||(v=e,t||C(Math.random()*u,()=>N(0)))},F=()=>{if(_||e.stream===!1||typeof EventSource>`u`)return;let n=new EventSource(`${i}stream${o}`);S=n,n.addEventListener(`change`,e=>{try{let n=JSON.parse(e.data).version;typeof n==`string`&&t.test(n)&&P(BigInt(n))}catch{}}),n.addEventListener(`revoked`,()=>O(`the key was revoked`)),n.onerror=()=>{n.close(),S===n&&C(Math.random()*3e4,F)}},I=()=>{d?.visibilityState===`visible`&&j()},L=E(),R=setInterval(()=>void j(),6e4);d?.addEventListener(`visibilitychange`,I);let z=M(Promise.all([L,j()]));F();let B=e=>g?Object.hasOwn(g.flags,e)?{value:g.flags[e],reason:`CACHED`}:{value:void 0,reason:`FLAG_NOT_FOUND`}:{value:void 0,reason:`NOT_READY`};return{ready:z,get snapshotVersion(){return g?.version},isEnabled:(e,t)=>B(e).value??t,getFlagDetails:B,identify(e,t){h=a(r,e,t),g=void 0;let n=E();return w(),M(Promise.all([n,j()]))},onChange(e){return f.add(e),()=>void f.delete(e)},close:D}}function s(e){if(!e)return 0;if(/^[0-9]+$/.test(e.trim()))return Number(e.trim())*1e3;let t=Date.parse(e);return Number.isNaN(t)?0:Math.max(0,t-Date.now())}export{e as ADAPTER_REFETCH_DELAY_MAX_MS,o as createClient};
|
package/package.json
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dipswitch/sdk-js",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Dipswitch feature flags in the browser: one user's values, cached, updated within seconds.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"module": "./dist/index.js",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"sideEffects": false
|
|
6
19
|
}
|