@productcraft/flags 0.0.0 → 0.2.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +395 -1
  3. package/api.md +1532 -0
  4. package/dist/browser/chunk-DIPMYL6H.cjs +598 -0
  5. package/dist/browser/chunk-DIPMYL6H.cjs.map +1 -0
  6. package/dist/browser/chunk-OI4KARX6.js +593 -0
  7. package/dist/browser/chunk-OI4KARX6.js.map +1 -0
  8. package/dist/browser/chunk-UFZYZXX5.js +1584 -0
  9. package/dist/browser/chunk-UFZYZXX5.js.map +1 -0
  10. package/dist/browser/chunk-YAW7UFU3.cjs +1584 -0
  11. package/dist/browser/chunk-YAW7UFU3.cjs.map +1 -0
  12. package/dist/browser/index.cjs +105 -0
  13. package/dist/browser/index.cjs.map +1 -0
  14. package/dist/browser/index.js +9 -0
  15. package/dist/browser/index.js.map +1 -0
  16. package/dist/browser/management.cjs +12 -0
  17. package/dist/browser/management.cjs.map +1 -0
  18. package/dist/browser/management.js +3 -0
  19. package/dist/browser/management.js.map +1 -0
  20. package/dist/browser/testing.cjs +1315 -0
  21. package/dist/browser/testing.cjs.map +1 -0
  22. package/dist/browser/testing.js +1307 -0
  23. package/dist/browser/testing.js.map +1 -0
  24. package/dist/chunk-ERCRURB5.js +1584 -0
  25. package/dist/chunk-ERCRURB5.js.map +1 -0
  26. package/dist/chunk-ERZAYN5A.js +626 -0
  27. package/dist/chunk-ERZAYN5A.js.map +1 -0
  28. package/dist/chunk-HOIKWDWQ.cjs +1584 -0
  29. package/dist/chunk-HOIKWDWQ.cjs.map +1 -0
  30. package/dist/chunk-J62ZCSIV.cjs +631 -0
  31. package/dist/chunk-J62ZCSIV.cjs.map +1 -0
  32. package/dist/client-DQaz2Leb.d.cts +175 -0
  33. package/dist/client-DQaz2Leb.d.ts +175 -0
  34. package/dist/client-bVEJfS6_.d.cts +11007 -0
  35. package/dist/client-bVEJfS6_.d.ts +11007 -0
  36. package/dist/index.cjs +105 -0
  37. package/dist/index.cjs.map +1 -0
  38. package/dist/index.d.cts +5 -0
  39. package/dist/index.d.ts +5 -0
  40. package/dist/index.js +9 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/management.cjs +12 -0
  43. package/dist/management.cjs.map +1 -0
  44. package/dist/management.d.cts +3 -0
  45. package/dist/management.d.ts +3 -0
  46. package/dist/management.js +3 -0
  47. package/dist/management.js.map +1 -0
  48. package/dist/testing.cjs +1315 -0
  49. package/dist/testing.cjs.map +1 -0
  50. package/dist/testing.d.cts +71 -0
  51. package/dist/testing.d.ts +71 -0
  52. package/dist/testing.js +1307 -0
  53. package/dist/testing.js.map +1 -0
  54. package/manifest.json +875 -0
  55. package/package.json +121 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ProductCraft
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,397 @@
1
1
  # @productcraft/flags
2
2
 
3
- Placeholder. The first release is 0.1.0: https://github.com/clauderanelagh/productcraft-node/tree/main/packages/flags
3
+ Feature flags and remote settings for Node.js, browsers and React Native, from [ProductCraft Flags](https://productcraft.co/docs/flags).
4
+
5
+ - **`FlagsClient`** downloads one small config JSON per environment and evaluates flags **locally** with [`@productcraft/flags-engine`](https://www.npmjs.com/package/@productcraft/flags-engine). User attributes never leave your app, and an evaluation is a function call, not a request.
6
+ - **`Flags`** is the management API client (projects, configs, environments, flags, targeting rules, segments, SDK keys, history, webhooks), generated from the production OpenAPI spec like every ProductCraft SDK.
7
+
8
+ Free during the preview. Requires Node.js 20.3 or later on the server; in a browser or React Native app, see [Browsers and React Native](#browsers-and-react-native).
9
+
10
+ ```sh
11
+ npm install @productcraft/flags
12
+ ```
13
+
14
+ ## Evaluate flags
15
+
16
+ Create an SDK key in the console (**Flags > SDK keys**, one per config and environment), then:
17
+
18
+ ```ts
19
+ import { FlagsClient } from "@productcraft/flags";
20
+
21
+ const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY });
22
+
23
+ const user = { identifier: "user-123", email: "ada@example.com", country: "NL", custom: { plan: "pro" } };
24
+ if (await flags.getValue("new_checkout", false, user)) {
25
+ // the new checkout
26
+ }
27
+ const banner = await flags.getValue("banner_text", "Welcome", user); // string
28
+ const limits = await flags.getJson<{ max: number }>("limits", { max: 5 }, user); // parsed JSON
29
+ ```
30
+
31
+ The value's type follows your default: `false` gives a `boolean`, `"Welcome"` a `string`, `5` a `number`. An object, array or `null` default on a json setting returns the parsed value; a `null` default is allowed for every type. `getJson<T>()` always parses, and returns your default if the text is not JSON.
32
+
33
+ **`getValue` never throws** once the client is constructed. A network error, a bad response, an unknown key or a type mismatch returns your default and emits an `error` event. Only a missing or garbled SDK key throws (`ConfigurationError`, at construction).
34
+
35
+ ### The user
36
+
37
+ `{ identifier, email, country, custom }`, ConfigCat's shape. Flat attributes work too: `{ identifier: "u1", plan: "pro" }`. A rule on attribute `a` reads `custom[a]` first, then the top-level `a`. Percentage rollouts hash the setting with `identifier` (or the setting's percentage attribute), so a user keeps their bucket.
38
+
39
+ ```ts
40
+ import { FlagsClient } from "@productcraft/flags";
41
+ const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY });
42
+
43
+ flags.setDefaultUser({ identifier: "user-123" }); // or `defaultUser` in the options
44
+ await flags.getValue("new_checkout", false); // uses the default user
45
+ await flags.getValue("new_checkout", false, { identifier: "user-456" }); // replaces it as a whole (no merge)
46
+ ```
47
+
48
+ Text comparisons are by codepoint with no Unicode normalisation: pass emails and names in **NFC** (`email.normalize("NFC")`), or two spellings of the same address can match different rules and buckets.
49
+
50
+ ### Why a value? Details, all values, snapshots
51
+
52
+ ```ts
53
+ import { FlagsClient } from "@productcraft/flags";
54
+ const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY });
55
+ const user = { identifier: "user-123" };
56
+
57
+ const d = await flags.getValueDetails("new_checkout", false, user);
58
+ console.log(d.value, d.reason, d.variant, d.ruleIndex, d.percentageIndex, d.errorCode, d.revision);
59
+
60
+ const all = await flags.getAllValues(user); // { key: value }, json settings parsed
61
+
62
+ await flags.waitForReady();
63
+ const snap = flags.snapshot(); // synchronous evaluation of the config held right now
64
+ snap.getValue("new_checkout", false, user);
65
+ ```
66
+
67
+ `reason` is `STATIC`, `TARGETING_MATCH`, `SPLIT`, `DEFAULT` or `ERROR`, or `CACHED` / `STALE` when the value came from the cache or `bootstrap` before a download, or from an older config while downloads fail.
68
+
69
+ ## Polling and propagation
70
+
71
+ | Mode | Behaviour |
72
+ |---|---|
73
+ | `{ mode: "auto", intervalSeconds: 60, maxInitWaitSeconds: 5 }` (default) | Downloads on a timer (minimum 30 s, ±10% jitter). The first `getValue` waits up to `maxInitWaitSeconds` for the first download, then serves the cache, `bootstrap` or your defaults. |
74
+ | `{ mode: "lazy", ttlSeconds: 60 }` | No timers. Downloads on use once the config is older than `ttlSeconds` (minimum 30 s), serving the held config while it refreshes. |
75
+ | `{ mode: "manual" }` | Downloads only when you call `forceRefresh()`. |
76
+
77
+ Downloads send `If-None-Match`, so an unchanged config costs a `304`. A change you save in the console reaches an auto-polling client within **interval × 1.1 + 5 s** (the jittered poll, plus up to 5 s for the delivery endpoint to pick up the publish): about 71 s at the default, 38 s at the 30 s minimum. A proxy or CDN of your own in front of the delivery URL may add up to 15 s (`s-maxage`). Call `forceRefresh()` to fetch now.
78
+
79
+ ```ts
80
+ import { FlagsClient } from "@productcraft/flags";
81
+ const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY, polling: { mode: "auto", intervalSeconds: 30 } });
82
+
83
+ flags.on("ready", (state) => console.log("flags", state));
84
+ flags.on("configChanged", (e) => console.log("config revision", e.revision));
85
+ flags.on("error", (err) => console.warn(err.code, err.message));
86
+ flags.on("evaluated", (d) => console.debug(d.key, d.value, d.reason));
87
+
88
+ await flags.forceRefresh();
89
+ flags.setOffline(); // stop all network access; evaluations keep working
90
+ flags.setOnline();
91
+ flags.close(); // stop timers (call it on shutdown)
92
+ ```
93
+
94
+ `flags.state` is `initializing`, `ready`, `stale` (the last download failed), `key_invalid` (the key was revoked or expired: the client keeps the config it holds), `offline` or `closed`. Errors back off up to 4× the interval and honour `Retry-After`.
95
+
96
+ ## Fail-safe: cache and bootstrap
97
+
98
+ What the client evaluates, in order: a fresh download, the last config it holds, your **cache** (read at start-up), your **`bootstrap`** config, and finally the default you pass to `getValue`. A full ProductCraft outage never turns your flags off when the cache or `bootstrap` is set up.
99
+
100
+ ```ts
101
+ import { FlagsClient, type FlagsCache } from "@productcraft/flags";
102
+ import { readFileSync } from "node:fs";
103
+
104
+ declare const redis: { get(key: string): Promise<string | null>; set(key: string, value: string): Promise<unknown> };
105
+
106
+ // Any store with get/set: Redis, a KV namespace, a file. Keys never contain the SDK key.
107
+ const cache: FlagsCache = { get: (key) => redis.get(key), set: async (key, value) => void (await redis.set(key, value)) };
108
+
109
+ const flags = new FlagsClient({
110
+ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY,
111
+ cache,
112
+ // A config JSON shipped with your build (download it from the delivery URL in CI, or `snapshot().toJSON()`).
113
+ bootstrap: readFileSync("flags-bootstrap.json", "utf8"),
114
+ });
115
+ ```
116
+
117
+ The client refuses a download over 2 MiB, never moves back to an older revision of the config, and only follows delivery hints that point at `https://*.productcraft.co`.
118
+
119
+ ## Serverless and edge functions
120
+
121
+ Timers do not survive between invocations, so use **lazy polling with the shared cache and `bootstrap`**: a cold start reads the cache (one Redis round trip, no download while the cached config is younger than `ttlSeconds`), and only one invocation per TTL downloads, with `If-None-Match`.
122
+
123
+ ```ts
124
+ import { FlagsClient, type FlagsCache } from "@productcraft/flags";
125
+ declare const cache: FlagsCache;
126
+ declare const bootstrapConfig: object;
127
+
128
+ // Module scope: reused while the instance stays warm.
129
+ const flags = new FlagsClient({
130
+ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY,
131
+ polling: { mode: "lazy", ttlSeconds: 60 },
132
+ cache,
133
+ bootstrap: bootstrapConfig,
134
+ });
135
+
136
+ export async function handler(event: { userId: string }) {
137
+ const enabled = await flags.getValue("new_checkout", false, { identifier: event.userId });
138
+ return { enabled };
139
+ }
140
+ ```
141
+
142
+ ## Overrides
143
+
144
+ Overrides set values locally: for local development, tests, or a kill switch you control from an environment variable.
145
+
146
+ ```ts
147
+ import { FlagsClient } from "@productcraft/flags";
148
+
149
+ // From a map. `behaviour`: "local_over_remote" (default), "remote_over_local" or "local_only" (no downloads, no key needed).
150
+ const dev = new FlagsClient({ overrides: { values: { new_checkout: true, limits: { max: 50 } }, behaviour: "local_only" } });
151
+
152
+ // From a JSON file (Node only), reloaded on change with `watch: true`.
153
+ const local = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY, overrides: { file: "./flags.local.json", watch: true } });
154
+
155
+ // From an environment variable holding a JSON object (Node only): PRODUCTCRAFT_FLAGS_OVERRIDES='{"new_checkout": false}'
156
+ const ops = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY, overrides: { env: "PRODUCTCRAFT_FLAGS_OVERRIDES" } });
157
+ ```
158
+
159
+ ## Testing
160
+
161
+ `@productcraft/flags/testing` exports `createTestClient`: a `FlagsClient` with fixed values, no network and no timers, and `set()` to change a value mid-test.
162
+
163
+ ```ts
164
+ import { describe, expect, it } from "vitest"; // or Jest: the same calls
165
+ import { createTestClient } from "@productcraft/flags/testing";
166
+
167
+ async function checkoutVersion(flags: { getValue(key: string, def: boolean): Promise<boolean> }) {
168
+ return (await flags.getValue("new_checkout", false)) ? "v2" : "v1";
169
+ }
170
+
171
+ describe("checkout", () => {
172
+ it("follows the new_checkout flag", async () => {
173
+ const flags = createTestClient({ values: { new_checkout: true } });
174
+ expect(await checkoutVersion(flags)).toBe("v2");
175
+ flags.set("new_checkout", false); // emits configChanged
176
+ expect(await checkoutVersion(flags)).toBe("v1");
177
+ });
178
+ });
179
+ ```
180
+
181
+ The same subpath exports `createMockFetch()` for the management client.
182
+
183
+ ## Browsers and React Native
184
+
185
+ Bundlers that honour the `browser` or `react-native` export condition (Vite, webpack, esbuild, Rollup, Metro, Next.js client bundles) get a build of the same `FlagsClient` without the Node-only parts, so nothing changes in your code:
186
+
187
+ - **No `node:` import and no `process.env` read.** `overrides.file` and `overrides.env` are Node-only and report an `overrides` error; use `overrides.values`.
188
+ - **The browser HTTP cache revalidates the config.** A page sends no `If-None-Match` (it would force a CORS preflight on every poll); the delivery endpoint allows any origin.
189
+ - **Auto polling pauses while the tab is hidden** and downloads once when it is shown again.
190
+ - `cache` takes any `{ get, set }`, for example over `localStorage`, so a returning visitor starts with the last config.
191
+
192
+ ```ts
193
+ import { FlagsClient } from "@productcraft/flags";
194
+
195
+ const store = { get: (k: string) => localStorage.getItem(k), set: (k: string, v: string) => localStorage.setItem(k, v) };
196
+ const flags = new FlagsClient({ sdkKey: "pcf_sdk_…", cache: store, defaultUser: { identifier: "user-123" } });
197
+ flags.on("configChanged", () => render());
198
+ const showBanner = await flags.getValue("show_banner", false);
199
+ declare function render(): void;
200
+ ```
201
+
202
+ For React (hooks, a provider and SSR without a flash) use [`@productcraft/flags-react`](https://www.npmjs.com/package/@productcraft/flags-react). The management client `Flags` keeps refusing to run in a browser with a workspace key.
203
+
204
+ **A key used in a browser or mobile app makes its whole config public** (next section).
205
+
206
+ ## Server and client configs
207
+
208
+ An SDK key can read its whole config: flag and segment keys (which can reveal what you are building) and every cleartext rule value. Keep server keys on the server. If a key ships in a browser or mobile app, that config is public: give client-side flags their own config with no internal rules. Confidential comparators hash their values, which hides them from casual reading but not from a determined attacker (the salt ships in the same JSON). Server-only and client key types are planned.
209
+
210
+ ## Manage flags from code
211
+
212
+ `Flags` is the management API: workspace API key (`PRODUCTCRAFT_API_KEY`) or a platform session, policy-gated, with retries, idempotency keys, pagination and typed errors.
213
+
214
+ ```ts
215
+ import { Flags } from "@productcraft/flags";
216
+
217
+ const flags = new Flags({ apiKey: process.env.PRODUCTCRAFT_API_KEY, workspaceId: "acme-corp" });
218
+ const project = await flags.projects.create({ name: "Storefront", environment_preset: "dev_staging_prod" });
219
+ for await (const p of flags.projects.list()) console.log(p.name);
220
+ ```
221
+
222
+ ## Migrating from ConfigCat
223
+
224
+ Import your ConfigCat product in the console (**Flags > Import from ConfigCat**): percentage rollouts keep their buckets because each imported flag's seed is its ConfigCat key. Before you swap the SDK, run [`examples/configcat-dual-run.mjs`](https://github.com/clauderanelagh/productcraft-node/blob/main/examples/configcat-dual-run.mjs): it evaluates the same users (synthetic, plus a file of your own) with both SDKs locally and prints every difference.
225
+
226
+ ```sh
227
+ cd examples && npm install
228
+ node configcat-dual-run.mjs --configcat-key "$CONFIGCAT_SDK_KEY" --flags-key "$PRODUCTCRAFT_FLAGS_SDK_KEY" --users 1000 --users-file users.json
229
+ ```
230
+
231
+ The user object has the same shape (`identifier`, `email`, `country`, `custom`); `getValueAsync(key, def, user)` becomes `getValue(key, def, user)`, `forceRefreshAsync()` becomes `forceRefresh()`, and `PollingMode.AutoPoll` becomes `{ mode: "auto" }`.
232
+
233
+ <!-- generated:start (scripts/gen-sdk.mjs; edits between the markers are overwritten) -->
234
+
235
+ ## Resources
236
+
237
+ Full reference: [api.md](./api.md).
238
+
239
+ - `flags.changes`: `retrieve`, `revert`
240
+ - `flags.configs`: `compare`, `delete`, `environments.copy`, `environments.evaluate`, `environments.revisions.list`, `environments.revisions.retrieve`, `environments.sdkKeys.endGracePeriod`, `environments.sdkKeys.list`, `environments.sdkKeys.reveal`, `environments.sdkKeys.rotate`, `environments.values.list`, `retrieve`, `settings.create`, `settings.list`, `update`
241
+ - `flags.imports`: `create`
242
+ - `flags.limits`: `retrieve`
243
+ - `flags.projects`: `changes.export`, `changes.list`, `configs.create`, `configs.list`, `create`, `delete`, `environments.create`, `environments.delete`, `environments.list`, `environments.retrieve`, `environments.update`, `list`, `retrieve`, `segments.create`, `segments.list`, `update`
244
+ - `flags.segments`: `delete`, `retrieve`, `revealConfidential`, `update`
245
+ - `flags.settings`: `delete`, `retrieve`, `update`, `values.replace`, `values.retrieve`, `values.revealConfidential`, `values.update`
246
+ - `flags.stats`: `retrieve`
247
+ - `flags.webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`
248
+
249
+ ## Pagination
250
+
251
+ List methods return a `PagePromise`: `for await` walks every item across pages, `await` gives one page.
252
+
253
+ ```ts
254
+ import { Flags } from "@productcraft/flags";
255
+ const flags = new Flags({ apiKey: process.env.PRODUCTCRAFT_API_KEY });
256
+ for await (const item of flags.projects.list({ limit: 50 })) console.log(item);
257
+ const page = await flags.projects.list();
258
+ if (page.hasNextPage()) await page.getNextPage();
259
+ const all = await flags.projects.list().toArray({ maxItems: 500 });
260
+ ```
261
+
262
+ ## Errors
263
+
264
+ Every failure is a class you can catch. `APIError` carries `status`, `code`, `message`, `errors[]`, `requestId` and `docUrl`.
265
+
266
+ ```ts
267
+ import { Flags, NotFoundError, RateLimitError, APIError } from "@productcraft/flags";
268
+ const flags = new Flags();
269
+ try {
270
+ await flags.changes.retrieve("00000000-0000-0000-0000-000000000000");
271
+ } catch (err) {
272
+ if (err instanceof NotFoundError) console.log(err.code, err.requestId, err.docUrl);
273
+ else if (err instanceof RateLimitError) console.log(err.retryAfter);
274
+ else if (err instanceof APIError) console.log(err.status, err.errors);
275
+ else throw err;
276
+ }
277
+ ```
278
+
279
+ ## Retries and timeouts
280
+
281
+ Network errors, 408, 429, 5xx and `409 IDEMPOTENCY_IN_PROGRESS` are retried twice by default with exponential backoff and jitter, honouring `Retry-After` up to 60 s. A POST or PATCH without an idempotency key is never retried. Each attempt times out after 60 s, so the worst case with defaults is about 3 minutes; pass `signal: AbortSignal.timeout(ms)` for an overall deadline.
282
+
283
+ ```ts
284
+ import { Flags } from "@productcraft/flags";
285
+ const flags = new Flags({ maxRetries: 3, timeout: 20_000 });
286
+ await flags.projects.list({}, { maxRetries: 0, signal: AbortSignal.timeout(5_000) });
287
+ ```
288
+
289
+ ## Idempotency
290
+
291
+ Writes that support it send an `Idempotency-Key` automatically and reuse it on every retry. Pass your own to make a retry across processes safe. If the API's idempotency store is unavailable it runs the request without it (fail-open), so a retry during that window can execute twice.
292
+
293
+ ```ts
294
+ import { Flags } from "@productcraft/flags";
295
+ const flags = new Flags({ apiKey: process.env.PRODUCTCRAFT_API_KEY });
296
+ const project = await flags.projects.create({ name: "Storefront" }, { idempotencyKey: "order-1234" });
297
+ ```
298
+
299
+ ## Webhooks
300
+
301
+ `flags.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Flags.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_FLAGS_WEBHOOK_SECRET`.
302
+
303
+ Next.js route handler:
304
+
305
+ ```ts
306
+ import { Flags } from "@productcraft/flags";
307
+ const flags = new Flags();
308
+ export async function POST(req: Request) {
309
+ const event = await flags.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
310
+ switch (event.type) {
311
+ case "config.published":
312
+ console.log(event.data);
313
+ break;
314
+ default:
315
+ break; // UnknownWebhookEvent: types added later
316
+ }
317
+ return new Response(null, { status: 204 });
318
+ }
319
+ ```
320
+
321
+ Express (keep the body raw):
322
+
323
+ ```ts
324
+ import express from "express";
325
+ import { Flags } from "@productcraft/flags";
326
+ const flags = new Flags();
327
+ const app = express();
328
+ app.post("/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
329
+ const event = await flags.webhooks.unwrap({ payload: req.body, headers: req.headers });
330
+ console.log(event.type);
331
+ res.sendStatus(204);
332
+ });
333
+ ```
334
+
335
+ Hono:
336
+
337
+ ```ts
338
+ import { Hono } from "hono";
339
+ import { Flags } from "@productcraft/flags";
340
+ const flags = new Flags();
341
+ const app = new Hono();
342
+ app.post("/webhooks", async (c) => {
343
+ const event = await flags.webhooks.unwrap({ payload: await c.req.text(), headers: c.req.raw.headers });
344
+ console.log(event.type);
345
+ return c.body(null, 204);
346
+ });
347
+ ```
348
+
349
+ Testing a handler: `webhooks.sign()` signs an event the way ProductCraft does, so a test needs no live delivery and no hand-rolled HMAC.
350
+
351
+ ```ts
352
+ import { Flags } from "@productcraft/flags";
353
+ const flags = new Flags({ webhookSecret: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw" });
354
+ const { payload, headers } = await flags.webhooks.sign({ payload: { id: "evt_test_1", type: "config.published", created_at: new Date().toISOString(), data: {} } });
355
+ const event = await flags.webhooks.unwrap({ payload, headers });
356
+ console.log(event.type);
357
+ ```
358
+
359
+ ## Raw responses
360
+
361
+ Every returned object has a non-enumerable `lastResponse` (`requestId`, `status`, `headers`). `.withResponse()` adds the `Response` and parsed rate-limit headers.
362
+
363
+ ```ts
364
+ import { Flags } from "@productcraft/flags";
365
+ const flags = new Flags({ apiKey: process.env.PRODUCTCRAFT_API_KEY });
366
+ const id = "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b";
367
+ const obj = await flags.changes.retrieve(id);
368
+ console.log(obj.lastResponse.requestId);
369
+ const { data, response, requestId, rateLimit } = await flags.changes.retrieve(id).withResponse();
370
+ console.log(data, response.status, requestId, rateLimit?.remaining);
371
+ ```
372
+
373
+ ## Testing
374
+
375
+ `@productcraft/flags/testing` exports `createMockFetch()`, a `fetch` that answers every operation with its spec example. Override one operation by name. It also exports `signWebhook({ payload, secret })`, which signs a test event for your webhook handler (the same as `webhooks.sign()`, without a client).
376
+
377
+ ```ts
378
+ import { Flags } from "@productcraft/flags";
379
+ import { createMockFetch } from "@productcraft/flags/testing";
380
+ const fetch = createMockFetch();
381
+ const flags = new Flags({ apiKey: "test", workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b", fetch });
382
+ await flags.projects.list();
383
+ console.log(fetch.calls.length);
384
+ ```
385
+
386
+ ## Escape hatch
387
+
388
+ `.client` is the typed `openapi-fetch` client over the same credential and base URL (no retries). Use it for anything the resource methods do not cover.
389
+
390
+ ```ts
391
+ import { Flags } from "@productcraft/flags";
392
+ const flags = new Flags({ apiKey: process.env.PRODUCTCRAFT_API_KEY });
393
+ const { data, error } = await flags.client.GET("/v1/workspaces/{workspace_id}/limits", { params: { path: { workspace_id: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" } } });
394
+ console.log(data, error);
395
+ ```
396
+
397
+ <!-- generated:end -->