@toggld/js 0.0.0-stage → 0.9.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 +202 -0
- package/README.md +355 -2
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +243 -0
- package/dist/core-BQfyNOoT.mjs +921 -0
- package/dist/details-AiMdctXB.mjs +365 -0
- package/dist/effect.d.mts +17 -0
- package/dist/effect.mjs +75 -0
- package/dist/effectService-CGZnDaqS.d.mts +48 -0
- package/dist/effectService-DPD-fNCI.mjs +17 -0
- package/dist/index.d.mts +54 -0
- package/dist/index.mjs +127 -0
- package/dist/serverless-B_Vyg8Nd.mjs +259 -0
- package/dist/serverless-e__iCjpQ.d.mts +206 -0
- package/dist/serverless-effect.d.mts +51 -0
- package/dist/serverless-effect.mjs +121 -0
- package/dist/serverless.d.mts +3 -0
- package/dist/serverless.mjs +38 -0
- package/dist/types-BHn_vrQq.d.mts +211 -0
- package/dist/wire-CrkBeqnM.mjs +447 -0
- package/package.json +76 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,356 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @toggld/js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Toggld SDK for server-side JavaScript. Evaluate feature flags from Node.js
|
|
4
|
+
servers, and from serverless and edge runtimes (Cloudflare Workers, Vercel,
|
|
5
|
+
AWS Lambda), against the Toggld flag API.
|
|
6
|
+
|
|
7
|
+
> **Renamed from `@toggld/node`.** Up to 0.8.0 this package was published as
|
|
8
|
+
> `@toggld/node`. Replace the package name in your imports and
|
|
9
|
+
> `package.json`. The modes were renamed too: `mode: "local"` is now
|
|
10
|
+
> `mode: "sync"` (the default), and `sync: { file }` is now
|
|
11
|
+
> `mode: "file", file`. Both old forms throw a `TypeError`. `@toggld/node`
|
|
12
|
+
> gets no more releases.
|
|
13
|
+
|
|
14
|
+
Four entries ship from one implementation:
|
|
15
|
+
|
|
16
|
+
- **`@toggld/js`** — a plain Promise API with **no runtime dependencies**.
|
|
17
|
+
- **`@toggld/js/effect`** — the native [Effect](https://effect.website) API:
|
|
18
|
+
the client as a service + `Layer`. Only this entry needs `effect`.
|
|
19
|
+
- **`@toggld/js/serverless`** — the remote client for serverless and edge
|
|
20
|
+
runtimes: one bulk evaluation request per incoming request, with an optional
|
|
21
|
+
cache. No `node:` imports, so it runs on Workers without `nodejs_compat`.
|
|
22
|
+
See [Serverless client](#serverless-client).
|
|
23
|
+
- **`@toggld/js/serverless/effect`** — the serverless client as the same
|
|
24
|
+
Effect `ToggldClient` service as `@toggld/js/effect`.
|
|
25
|
+
|
|
26
|
+
Three evaluation modes for `ToggldClient` (`mode`), plus the serverless client:
|
|
27
|
+
|
|
28
|
+
- **Sync** (`mode: "sync"`, the default) — a copy of the flag rules stays
|
|
29
|
+
current in the background (a snapshot fetch plus a live WebSocket stream,
|
|
30
|
+
with polling as a safety net and fallback) and every evaluation runs
|
|
31
|
+
**in your process** on the bundled engine, with no request per evaluation.
|
|
32
|
+
See [ADR-0012](../../docs/adr/0012-definition-sync-and-local-evaluation.md).
|
|
33
|
+
- **File** (`mode: "file"`) — the same in-process evaluation, from a flag
|
|
34
|
+
**file** on disk, watched for edits. No network. See
|
|
35
|
+
[Flag files](#flag-files-offline) below.
|
|
36
|
+
- **Remote** (`mode: "remote"`) — every call asks the flag API, which evaluates
|
|
37
|
+
the flag against your context and returns the resolved value (OpenFeature
|
|
38
|
+
"remote evaluation" over the OFREP endpoints).
|
|
39
|
+
- **Serverless** (`@toggld/js/serverless`) — one remote bulk request per
|
|
40
|
+
incoming request, for serverless and edge runtimes. See
|
|
41
|
+
[Serverless client](#serverless-client).
|
|
42
|
+
|
|
43
|
+
### Why sync is the default
|
|
44
|
+
|
|
45
|
+
- **Fast.** An evaluation takes microseconds, not a network round trip.
|
|
46
|
+
- **Keeps working.** After the first sync, evaluations use the last snapshot
|
|
47
|
+
while the API is unreachable.
|
|
48
|
+
- **No request per lookup.** Sync-mode evaluations never reach the API, so they
|
|
49
|
+
are not billable evaluation requests and do not use your rate limit.
|
|
50
|
+
Remote mode sends one request for each evaluation.
|
|
51
|
+
|
|
52
|
+
### What sync mode needs
|
|
53
|
+
|
|
54
|
+
- **A secret SDK key** (`ffk_…`): a server SDK key or a management key. The
|
|
55
|
+
snapshot holds your targeting rules, so public browser tokens (`ffp_…`)
|
|
56
|
+
cannot download it. Creating a sync-mode client with a public token, without
|
|
57
|
+
a key, or without a valid `endpoint` throws a `TypeError` at once.
|
|
58
|
+
- **Network access to `/sync/v1`** on the API: `GET /sync/v1/flags` over
|
|
59
|
+
HTTPS, and the `/sync/v1/stream` WebSocket. Without a usable WebSocket, the
|
|
60
|
+
SDK keeps polling the snapshot (every 30 s by default) and retries the stream.
|
|
61
|
+
- **A long-lived process**, such as a web server or a worker. The sync runs
|
|
62
|
+
in the background for the life of the client.
|
|
63
|
+
|
|
64
|
+
### When to use remote mode
|
|
65
|
+
|
|
66
|
+
Pass `mode: "remote"` when the process must not hold your targeting rules, or
|
|
67
|
+
keeps no memory between requests:
|
|
68
|
+
|
|
69
|
+
- **A public token** (`ffp_…`), or any process that should see evaluated values
|
|
70
|
+
only, not the rules.
|
|
71
|
+
- **Runtimes without memory between requests**, such as Fastly Compute.
|
|
72
|
+
|
|
73
|
+
On **serverless functions** (AWS Lambda, Vercel and Netlify functions) and
|
|
74
|
+
**edge runtimes** (Cloudflare Workers, Vercel Edge), use the
|
|
75
|
+
[serverless client](#serverless-client) instead: it sends one bulk request per
|
|
76
|
+
incoming request, which is one billable request however many flags you read.
|
|
77
|
+
In sync mode, `create` throws a
|
|
78
|
+
`TypeError` on Workers and Vercel Edge, and logs one warning on AWS Lambda
|
|
79
|
+
(the process freezes between invocations, so the stream and poll stall).
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
const client = await ToggldClient.create({ sdkKey, endpoint, mode: "remote" })
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Short scripts and CLI tools can use any mode. In sync mode, `create` waits
|
|
86
|
+
for the snapshot, and the script must call `close()` to exit.
|
|
87
|
+
|
|
88
|
+
## Install
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
pnpm add @toggld/js
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
That is all the Promise API needs. For the Effect API, install `effect` too
|
|
95
|
+
(`pnpm add effect`): it is an optional peer dependency (`^4.0.5`), so
|
|
96
|
+
`@toggld/js/effect` runs on your app's copy of Effect, and its `Layer`
|
|
97
|
+
composes with the app's layers. Importing `@toggld/js/effect` without
|
|
98
|
+
`effect` installed fails with `ERR_MODULE_NOT_FOUND`.
|
|
99
|
+
|
|
100
|
+
## Promise API
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { ToggldClient } from "@toggld/js"
|
|
104
|
+
|
|
105
|
+
// Sync mode (the default). `create` resolves once the first snapshot
|
|
106
|
+
// has synced, or after `sync.readyTimeoutMs` (5 s).
|
|
107
|
+
const client = await ToggldClient.create({
|
|
108
|
+
sdkKey: process.env.TOGGLD_SDK_KEY!, // a secret SDK key (ffk_…)
|
|
109
|
+
endpoint: "https://api.toggld.io",
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
// Typed getters — return the default on any error, never throw.
|
|
113
|
+
const on = await client.getBooleanValue("new-checkout", false, {
|
|
114
|
+
targetingKey: "user-123",
|
|
115
|
+
plan: "premium",
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
// Full OpenFeature evaluation details.
|
|
119
|
+
const details = await client.getStringDetails("theme", "light", { targetingKey: "user-123" })
|
|
120
|
+
// ^ { flagKey, value, variant, reason, errorCode, errorMessage, flagMetadata }
|
|
121
|
+
|
|
122
|
+
// Every flag for the environment, evaluated in-process.
|
|
123
|
+
const everything = await client.evaluateAll({ targetingKey: "user-123" })
|
|
124
|
+
|
|
125
|
+
await client.close() // stops background sync and sends remaining telemetry
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Getters exist for each flag type: `getBooleanValue` / `getBooleanDetails`,
|
|
129
|
+
`getStringValue` / `…`, `getNumberValue` / `…`, and `getObjectValue<T>` / `…`.
|
|
130
|
+
|
|
131
|
+
## Effect API
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { Effect } from "effect"
|
|
135
|
+
import { ToggldClient, layer } from "@toggld/js/effect"
|
|
136
|
+
|
|
137
|
+
const program = Effect.gen(function* () {
|
|
138
|
+
const flags = yield* ToggldClient
|
|
139
|
+
return yield* flags.getBooleanValue("new-checkout", false, { targetingKey: "user-123" })
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
program.pipe(
|
|
143
|
+
Effect.provide(layer({ sdkKey, endpoint })),
|
|
144
|
+
Effect.runPromise,
|
|
145
|
+
)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The `layer` is self-contained, so you only provide this one layer. It is a thin
|
|
149
|
+
wrapper over the same client the Promise API uses: like `create`, building it
|
|
150
|
+
waits for the first snapshot for up to `sync.readyTimeoutMs`. The layer's scope
|
|
151
|
+
owns the client, and closing the scope closes it (sync stops, the stream
|
|
152
|
+
closes, and remaining telemetry is sent). Build the layer once per process, for
|
|
153
|
+
example with a `ManagedRuntime`, not once per request. Sync- and file-mode
|
|
154
|
+
evaluations are synchronous effects; remote ones are interruptible, and interrupting one aborts
|
|
155
|
+
its request.
|
|
156
|
+
|
|
157
|
+
## Serverless client
|
|
158
|
+
|
|
159
|
+
`@toggld/js/serverless` is a remote client for runtimes that run code only
|
|
160
|
+
while they handle a request. Create the client once per isolate or process;
|
|
161
|
+
create a request view per incoming request with `forRequest(ctx)`.
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
import { createServerlessClient, type ServerlessClient } from "@toggld/js/serverless"
|
|
165
|
+
|
|
166
|
+
let flags: ServerlessClient | undefined
|
|
167
|
+
|
|
168
|
+
export default {
|
|
169
|
+
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
|
170
|
+
flags ??= createServerlessClient({ sdkKey: env.TOGGLD_SDK_KEY, endpoint: "https://api.toggld.io" })
|
|
171
|
+
const f = flags.forRequest(ctx)
|
|
172
|
+
const on = await f.getBooleanValue("new-checkout", false, { targetingKey: "user-123" })
|
|
173
|
+
return new Response(on ? "new" : "old")
|
|
174
|
+
},
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
The first evaluation in a view sends one bulk request
|
|
179
|
+
(`POST /ofrep/v1/evaluate/flags`) with its context. Every later read in that
|
|
180
|
+
view with the same context uses the answer; a different context sends its own
|
|
181
|
+
request. Nothing is kept between requests, so a change shows on the next
|
|
182
|
+
request. A bulk request is one billable request, whatever the number of flags.
|
|
183
|
+
Failures (network, timeout after `timeoutMs`, default 1.5 s, or a refusal)
|
|
184
|
+
resolve to your defaults with an error code; nothing throws.
|
|
185
|
+
|
|
186
|
+
To send fewer requests, pass a `cache`: `memoryCache({ ttlMs })` keeps results
|
|
187
|
+
in isolate memory, and any key-value store can implement `EvaluationCache`. A
|
|
188
|
+
cache trades freshness for fewer billable requests. On AWS Lambda and Node.js
|
|
189
|
+
serverless functions, call `flags.forRequest()` without a context; cache
|
|
190
|
+
writes then run inline.
|
|
191
|
+
|
|
192
|
+
The client counts each read that resolves a flag (the API does not count bulk
|
|
193
|
+
requests in analytics) and sends the counts to `POST /v1/telemetry` when the
|
|
194
|
+
oldest is 30 seconds old or 1,000 groups have built up: in the request's
|
|
195
|
+
`waitUntil`, or started without waiting when there is none. Evaluations never
|
|
196
|
+
wait for it. Set `telemetry: false` to send nothing. See the
|
|
197
|
+
[serverless client guide](https://docs.toggld.io/sdks/js/serverless) and
|
|
198
|
+
[ADR-0020](../../docs/adr/0020-serverless-client-and-toggld-js.md).
|
|
199
|
+
|
|
200
|
+
## Options
|
|
201
|
+
|
|
202
|
+
| Option | Type | Default | Notes |
|
|
203
|
+
| ---------------- | --------------------- | ---------------- | ---------------------------------------------------------------- |
|
|
204
|
+
| `sdkKey` | `string` | — | Secret evaluation (or management) key, `ffk_…`; sent as `Bearer`. A public token (`ffp_…`) needs `mode: "remote"`. |
|
|
205
|
+
| `endpoint` | `string` | — | Base URL of the flag API. It may have a path prefix, for a [proxy on your own domain](https://docs.toggld.io/sdks/proxy). |
|
|
206
|
+
| `mode` | `"sync" \| "file" \| "remote"` | `"sync"` | Sync = background sync + in-process engine. File = in-process engine over a flag file. Remote = one OFREP request per evaluation. |
|
|
207
|
+
| `file` | `string` | `./toggld.flags.json` | The flag file, in file mode only (a `TypeError` with any other mode). `TOGGLD_FLAGS_FILE` overrides it. |
|
|
208
|
+
| `sync.transport` | `"ws" \| "poll"` | `"ws"` | Sync mode: live stream (with poll safety net) vs polling only. |
|
|
209
|
+
| `sync.pollIntervalMs` | `number` | `30000` | Sync mode: snapshot poll cadence; cold start retries faster. Does not apply to files. |
|
|
210
|
+
| `sync.readyTimeoutMs` | `number` | `5000` | Sync mode: how long `create` (and the Effect `layer`) waits for the first snapshot. |
|
|
211
|
+
| `defaultContext` | `EvaluationContext` | `{}` | Merged under per-call context (per-call attributes win). |
|
|
212
|
+
| `timeoutMs` | `number` | `5000` | Per-request timeout. |
|
|
213
|
+
| `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (tests, proxies, instrumentation). |
|
|
214
|
+
|
|
215
|
+
### Readiness
|
|
216
|
+
|
|
217
|
+
In sync mode, `create` waits for the first snapshot or `sync.readyTimeoutMs`
|
|
218
|
+
(default 5 s), whichever comes first. If the snapshot has not arrived by then,
|
|
219
|
+
the SDK logs one warning with the last sync error (for example HTTP 401 for a
|
|
220
|
+
wrong key), and sync keeps retrying in the background. Until a snapshot
|
|
221
|
+
arrives, evaluations return your defaults with `reason: "ERROR"` and
|
|
222
|
+
`errorCode: "PROVIDER_NOT_READY"`, and their `errorMessage` names the last sync
|
|
223
|
+
error. `evaluateAll` returns an empty array. `client.ready()` waits for the
|
|
224
|
+
first snapshot with no time limit, so add your own timeout if you use it at
|
|
225
|
+
startup. In file mode, `create` resolves after the first read of the file. In
|
|
226
|
+
remote mode, `create` and `ready()` resolve at once.
|
|
227
|
+
|
|
228
|
+
### Shutdown
|
|
229
|
+
|
|
230
|
+
Call `close()` when the process stops. It stops the sync, closes the stream,
|
|
231
|
+
and sends the remaining telemetry (bounded by `timeoutMs`). A sync-mode client keeps
|
|
232
|
+
the Node.js process alive until you close it, so a short script must call
|
|
233
|
+
`close()` to exit.
|
|
234
|
+
|
|
235
|
+
Changes on the connected Node instance normally arrive through WebSocket pushes.
|
|
236
|
+
The SDK also polls every 30 seconds, even while the stream stays healthy.
|
|
237
|
+
Polling recovers writes from other instances and announcements that the bounded
|
|
238
|
+
server buffer drops. With healthy requests, the conservative bound is
|
|
239
|
+
`sync.pollIntervalMs + 2 * timeoutMs`, plus scheduling delays, or 40 seconds by default.
|
|
240
|
+
The [Node sync guide](../../docs/node-sync.md) defines the assumptions and deployment requirements.
|
|
241
|
+
|
|
242
|
+
### How fast is sync mode?
|
|
243
|
+
|
|
244
|
+
`pnpm bench:sync` (from the repo root) runs the same workload with sync off vs
|
|
245
|
+
on — representative numbers on a laptop, loopback server:
|
|
246
|
+
|
|
247
|
+
```
|
|
248
|
+
sync OFF (remote OFREP) ~11,600 evals/s p50 2.4 ms
|
|
249
|
+
sync ON (local engine) ~1,090,000 evals/s p50 27 µs (0.6 µs single-caller)
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Flag files (offline)
|
|
253
|
+
|
|
254
|
+
For local development, CI, or offline runs, a client in file mode evaluates
|
|
255
|
+
against a **file** instead of syncing over the network — same engine, same results, no
|
|
256
|
+
flag API required. Generate the file with the bundled CLI:
|
|
257
|
+
|
|
258
|
+
```bash
|
|
259
|
+
# Fetch the environment's current flags into ./toggld.flags.json.
|
|
260
|
+
# Prompts for the key if you omit --sdk-key (or set TOGGLD_SDK_KEY).
|
|
261
|
+
# Uses https://api.toggld.io unless you pass --api or set TOGGLD_API_URL.
|
|
262
|
+
npx @toggld/js pull --sdk-key ffk_…
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Then create a client in file mode — no `sdkKey` or `endpoint` needed:
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
const client = await ToggldClient.create({
|
|
269
|
+
mode: "file",
|
|
270
|
+
file: "./toggld.flags.json", // the default; omit it to use this path
|
|
271
|
+
})
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
The file is a `FlagSnapshot` (the exact wire snapshot the SDK syncs) wrapped in a
|
|
275
|
+
small provenance envelope, so it is human-readable, diffable, and editable —
|
|
276
|
+
flip an `enabled`, nudge a rollout, commit a fixture. **Edits are picked up
|
|
277
|
+
live** (the file is watched); no restart, and no need to change `version`.
|
|
278
|
+
The client also re-reads the file every 30 seconds as a safety net
|
|
279
|
+
(`sync.pollIntervalMs` does not apply to files).
|
|
280
|
+
|
|
281
|
+
You can also redirect *any* client to a file with **no code change** by setting
|
|
282
|
+
`TOGGLD_FLAGS_FILE` — it switches a client in any mode to file mode with that
|
|
283
|
+
path, even a client with `mode: "remote"`, and overrides `file`:
|
|
284
|
+
|
|
285
|
+
```bash
|
|
286
|
+
TOGGLD_FLAGS_FILE=./toggld.flags.json node server.js
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
`pull` needs a secret key (`ffk_…`); it is one-shot and idempotent (an unchanged
|
|
290
|
+
version is not rewritten — pass `--force` to override). See
|
|
291
|
+
[ADR-0013](../../docs/adr/0013-local-flag-files-and-pull-cli.md). Remote-segment
|
|
292
|
+
membership (ADR-0006) is not yet available offline; a file-mode client warns
|
|
293
|
+
once and treats a remote segment's non-rule-matched subjects as non-members.
|
|
294
|
+
|
|
295
|
+
## Error semantics
|
|
296
|
+
|
|
297
|
+
Evaluation never throws. On a network failure, timeout, unknown flag, server
|
|
298
|
+
error, or a value whose type doesn't match the requested getter, the call
|
|
299
|
+
resolves to your **default value**. The `*Details` methods carry `reason:
|
|
300
|
+
"ERROR"` and an OpenFeature `errorCode` (`FLAG_NOT_FOUND`, `TYPE_MISMATCH`,
|
|
301
|
+
`TARGETING_KEY_MISSING`, `PARSE_ERROR`, `GENERAL`, …) describing what happened.
|
|
302
|
+
A rejected request, such as HTTP 401 for a wrong SDK key or HTTP 429 for a rate
|
|
303
|
+
limit, reports `GENERAL` with the HTTP status in `errorMessage`.
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
## Evaluation telemetry
|
|
307
|
+
|
|
308
|
+
The SDK counts the flags your code reads for analytics (the API does not count
|
|
309
|
+
bulk requests). Sync mode counts every evaluation; remote mode counts each flag
|
|
310
|
+
`evaluateAll` returns (the API counts its single evaluations); the serverless
|
|
311
|
+
client counts each read that resolves a flag, and sends from requests (see
|
|
312
|
+
[Serverless client](#serverless-client)).
|
|
313
|
+
It groups counts by flag, variant, result reason, and UTC minute. The SDK sends
|
|
314
|
+
batches to `POST /v1/telemetry` every 30 seconds and during `close()`.
|
|
315
|
+
Evaluation calls do not wait for these requests. Both SDK APIs use this reporter.
|
|
316
|
+
|
|
317
|
+
The SDK reports engine results for known flags, including engine errors.
|
|
318
|
+
It excludes unknown flags, calls before readiness, and errors from typed getters.
|
|
319
|
+
Each bulk evaluation counts each flag once. The SDK sends no user identities,
|
|
320
|
+
evaluation context, values, or metadata. File mode sends no telemetry, even
|
|
321
|
+
when credentials are present.
|
|
322
|
+
|
|
323
|
+
```ts
|
|
324
|
+
const client = await ToggldClient.create({
|
|
325
|
+
endpoint,
|
|
326
|
+
sdkKey,
|
|
327
|
+
telemetry: { flushIntervalMs: 30_000 },
|
|
328
|
+
})
|
|
329
|
+
|
|
330
|
+
await client.getBooleanValue("checkout", false, { targetingKey: "user-123" })
|
|
331
|
+
await client.flushTelemetry()
|
|
332
|
+
await client.close()
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
Set `telemetry: false` to disable reporting. Use `flushTelemetry()` to send counts
|
|
336
|
+
before the next interval. Effect users can yield `client.flushTelemetry` and close
|
|
337
|
+
the layer scope to flush remaining counts. A flush failure leaves the batch
|
|
338
|
+
queued for the next attempt. Retries keep the same batch ID to prevent duplicate
|
|
339
|
+
counts after a lost response.
|
|
340
|
+
|
|
341
|
+
The SDK holds at most 10,000 active groups and 10,000 groups awaiting retry.
|
|
342
|
+
If the active buffer fills, the SDK drops new groups. Each request contains at
|
|
343
|
+
most 1,000 groups. Each count stops at 1,000,000,000. Keys and variants longer
|
|
344
|
+
than 256 characters do not produce telemetry. Process crashes can lose buffered
|
|
345
|
+
counts. Closing the client limits its final telemetry attempt to `timeoutMs`,
|
|
346
|
+
which defaults to five seconds. Counts remain approximate.
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
The integration suite can use Postgres for the complete SDK-to-storage path.
|
|
350
|
+
It creates tenants and flags, so use a disposable database. From the repository
|
|
351
|
+
root, set `DATABASE_URL` to that database and run the command below. The test
|
|
352
|
+
server applies migrations before it starts.
|
|
353
|
+
|
|
354
|
+
```bash
|
|
355
|
+
TOGGLD_TEST_POSTGRES=1 DATABASE_URL=postgres://postgres:postgres@localhost:55439/toggld pnpm --filter @toggld/js exec vitest run test/telemetry.test.ts
|
|
356
|
+
```
|
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|