@flagdock/testing 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Flagdock
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,66 @@
1
- # Temporary Holding Version
1
+ # @flagdock/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test your app's [Flagdock](https://flagdock.com) feature flags without a server or network.
4
+
5
+ It is an in-memory [OpenFeature](https://openfeature.dev) provider. Set flag values for one piece of
6
+ code with `withFlags`, run a test once for every value of a flag with `eachValue`, or evaluate your
7
+ real rules from a file exported with `flagdock-export`.
8
+
9
+ ## Quickstart
10
+
11
+ 1. Install:
12
+
13
+ ```sh
14
+ npm install --save-dev @flagdock/testing @openfeature/server-sdk
15
+ ```
16
+
17
+ 2. Register the provider once in your test setup:
18
+
19
+ ```ts
20
+ import { OpenFeature } from '@openfeature/server-sdk';
21
+ import { testFlags } from '@flagdock/testing';
22
+
23
+ await OpenFeature.setProviderAndWait(testFlags.provider);
24
+ ```
25
+
26
+ 3. Use it in tests:
27
+
28
+ ```ts
29
+ import { withFlags, eachValue } from '@flagdock/testing';
30
+
31
+ test('new checkout', () =>
32
+ withFlags({ 'new-checkout': true }, async () => {
33
+ expect(await checkout(cart)).toBeOk();
34
+ }));
35
+
36
+ test('checkout works with every value', () =>
37
+ eachValue('new-checkout', async () => {
38
+ expect(await checkout(cart)).toBeOk();
39
+ }, [true, false]));
40
+ ```
41
+
42
+ `withFlags` puts things back when the code finishes, even if it throws, and is safe in tests that
43
+ run side by side. A flag the test did not set answers with your code's default and reports
44
+ `FLAG_NOT_FOUND`.
45
+
46
+ ## Test against your real rules
47
+
48
+ Save an environment's rules as JSON with a **server** SDK key:
49
+
50
+ ```sh
51
+ FLAGDOCK_KEY=hbf_srv_… npx flagdock-export --out test/flags.json
52
+ ```
53
+
54
+ ```ts
55
+ import { TestFlags } from '@flagdock/testing';
56
+
57
+ const flags = new TestFlags({ ruleset: 'test/flags.json' });
58
+ await OpenFeature.setProviderAndWait(flags.provider);
59
+ ```
60
+
61
+ Checks then follow the same rules as production, evaluated by the same engine as the SDKs, and
62
+ `eachValue` runs once for every value the flag has. Values set with `withFlags` still win.
63
+
64
+ The file holds your targeting rules: keep it in your repository, not in anything you ship.
65
+
66
+ MIT licensed. Questions: info@flagdock.com
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import { writeFileSync } from 'node:fs';
3
+ import { DEFAULT_URL, serverUrl } from './url.js';
4
+ // Saves an environment's current rules as a JSON file to test against:
5
+ // FLAGDOCK_KEY=hbf_srv_… flagdock-export --out test/flags.json
6
+ const args = process.argv.slice(2);
7
+ const arg = (name) => {
8
+ const i = args.indexOf(`--${name}`);
9
+ return i >= 0 ? args[i + 1] : undefined;
10
+ };
11
+ const USAGE = `Usage: FLAGDOCK_KEY=<server SDK key> flagdock-export [--out file.json] [--url <address>]
12
+ Saves the rules of the key's environment as JSON, for tests to load with new TestFlags({ ruleset: 'file.json' }).
13
+ The key is read from the environment so it does not end up in shell history.
14
+ --url (or FLAGDOCK_URL) is only for Flagdock running somewhere else. Default: ${DEFAULT_URL}`;
15
+ const key = process.env.FLAGDOCK_KEY ?? '';
16
+ const out = arg('out');
17
+ if (!key || args.includes('--help')) {
18
+ console.error(USAGE);
19
+ process.exit(args.includes('--help') ? 0 : 1);
20
+ }
21
+ const url = serverUrl(arg('url') ?? process.env.FLAGDOCK_URL ?? DEFAULT_URL);
22
+ if (!url) {
23
+ console.error('The address must start with https:// (http:// is only allowed for localhost), so the key is never sent in the clear.');
24
+ process.exit(1);
25
+ }
26
+ const res = await fetch(`${url}/api/v1/sdk/ruleset`, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(15_000) }).catch((err) => {
27
+ console.error(`Could not reach ${url}: ${err instanceof Error ? err.message : String(err)}`);
28
+ process.exit(1);
29
+ });
30
+ if (!res.ok) {
31
+ console.error(`The server answered ${res.status}. Check that FLAGDOCK_KEY is a server key that has not been revoked.`);
32
+ process.exit(1);
33
+ }
34
+ const text = `${JSON.stringify(await res.json(), null, 2)}\n`;
35
+ if (out) {
36
+ writeFileSync(out, text);
37
+ console.error(`Saved the rules to ${out}`);
38
+ }
39
+ else {
40
+ process.stdout.write(text);
41
+ }
42
+ //# sourceMappingURL=export-cli.js.map
@@ -0,0 +1,40 @@
1
+ import { type JsonValue, type Provider } from '@openfeature/server-sdk';
2
+ import { type Ruleset } from '@flagdock/core';
3
+ export type FlagValues = Record<string, JsonValue>;
4
+ /**
5
+ * Flags for tests: no server, no network, no shared state between tests that run side by side.
6
+ *
7
+ * Values come from three places, the first that knows the flag wins:
8
+ * 1. what the running test set with `withFlags` or `eachValue`,
9
+ * 2. values given to the constructor or `set`,
10
+ * 3. a ruleset fixture exported from the real server, evaluated with the real rules.
11
+ */
12
+ export declare class TestFlags {
13
+ private readonly scoped;
14
+ private base;
15
+ private ruleset;
16
+ constructor(options?: {
17
+ values?: FlagValues;
18
+ ruleset?: Ruleset | string;
19
+ });
20
+ /** Uses a ruleset exported with `flagdock-export` (a file path or the parsed object). */
21
+ loadRuleset(ruleset: Ruleset | string): this;
22
+ /** Sets values for every test from here on. Prefer `withFlags` inside a test. */
23
+ set(values: FlagValues): this;
24
+ /** Forgets everything set with `set`. Call it in `afterEach` if tests use `set`. */
25
+ reset(): this;
26
+ /** Runs `fn` with these flag values, then puts things back, even when `fn` throws. Nests, and is safe in parallel tests. */
27
+ withFlags<T>(values: FlagValues, fn: () => T): T;
28
+ /**
29
+ * Runs `fn` once for every value the flag can have, so no branch goes untested.
30
+ * The values come from the ruleset fixture; an on/off flag without one runs with true and false.
31
+ */
32
+ eachValue(flagKey: string, fn: (value: JsonValue, valueKey: string) => unknown, values?: JsonValue[]): Promise<void>;
33
+ /** The OpenFeature provider to register: `OpenFeature.setProvider(flags.provider)`. */
34
+ readonly provider: Provider;
35
+ private resolve;
36
+ }
37
+ /** A ready-made instance for the common case of one set of flags per test run. */
38
+ export declare const testFlags: TestFlags;
39
+ export declare const withFlags: TestFlags['withFlags'];
40
+ export declare const eachValue: TestFlags['eachValue'];
package/dist/index.js ADDED
@@ -0,0 +1,95 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { readFileSync } from 'node:fs';
3
+ import { ErrorCode } from '@openfeature/server-sdk';
4
+ import { evaluate } from '@flagdock/core';
5
+ const kindOf = (value) => typeof value === 'boolean' ? 'boolean' : typeof value === 'string' ? 'string' : typeof value === 'number' ? 'number' : 'json';
6
+ /**
7
+ * Flags for tests: no server, no network, no shared state between tests that run side by side.
8
+ *
9
+ * Values come from three places, the first that knows the flag wins:
10
+ * 1. what the running test set with `withFlags` or `eachValue`,
11
+ * 2. values given to the constructor or `set`,
12
+ * 3. a ruleset fixture exported from the real server, evaluated with the real rules.
13
+ */
14
+ export class TestFlags {
15
+ scoped = new AsyncLocalStorage();
16
+ base;
17
+ ruleset;
18
+ constructor(options = {}) {
19
+ this.base = { ...options.values };
20
+ if (options.ruleset)
21
+ this.loadRuleset(options.ruleset);
22
+ }
23
+ /** Uses a ruleset exported with `flagdock-export` (a file path or the parsed object). */
24
+ loadRuleset(ruleset) {
25
+ this.ruleset = typeof ruleset === 'string' ? JSON.parse(readFileSync(ruleset, 'utf8')) : ruleset;
26
+ return this;
27
+ }
28
+ /** Sets values for every test from here on. Prefer `withFlags` inside a test. */
29
+ set(values) {
30
+ Object.assign(this.base, values);
31
+ return this;
32
+ }
33
+ /** Forgets everything set with `set`. Call it in `afterEach` if tests use `set`. */
34
+ reset() {
35
+ this.base = {};
36
+ return this;
37
+ }
38
+ /** Runs `fn` with these flag values, then puts things back, even when `fn` throws. Nests, and is safe in parallel tests. */
39
+ withFlags(values, fn) {
40
+ return this.scoped.run({ ...this.scoped.getStore(), ...values }, fn);
41
+ }
42
+ /**
43
+ * Runs `fn` once for every value the flag can have, so no branch goes untested.
44
+ * The values come from the ruleset fixture; an on/off flag without one runs with true and false.
45
+ */
46
+ async eachValue(flagKey, fn, values) {
47
+ const known = this.ruleset?.flags[flagKey]?.values;
48
+ const cases = values ? values.map((v) => [JSON.stringify(v), v])
49
+ : known ? Object.entries(known)
50
+ : [['on', true], ['off', false]];
51
+ for (const [key, value] of cases) {
52
+ try {
53
+ await this.withFlags({ [flagKey]: value }, () => fn(value, key));
54
+ }
55
+ catch (err) {
56
+ if (err instanceof Error)
57
+ err.message = `With ${flagKey} = ${JSON.stringify(value)}: ${err.message}`;
58
+ throw err;
59
+ }
60
+ }
61
+ }
62
+ /** The OpenFeature provider to register: `OpenFeature.setProvider(flags.provider)`. */
63
+ provider = {
64
+ metadata: { name: 'flagdock-testing' },
65
+ runsOn: 'server',
66
+ resolveBooleanEvaluation: async (key, fallback, context) => this.resolve(key, fallback, context, 'boolean'),
67
+ resolveStringEvaluation: async (key, fallback, context) => this.resolve(key, fallback, context, 'string'),
68
+ resolveNumberEvaluation: async (key, fallback, context) => this.resolve(key, fallback, context, 'number'),
69
+ resolveObjectEvaluation: async (key, fallback, context) => this.resolve(key, fallback, context, 'json'),
70
+ };
71
+ resolve(flagKey, fallback, context, kind) {
72
+ const forced = { ...this.base, ...this.scoped.getStore() };
73
+ if (Object.hasOwn(forced, flagKey)) {
74
+ const value = forced[flagKey];
75
+ if (kind !== 'json' && kindOf(value) !== kind) {
76
+ return { value: fallback, reason: 'ERROR', errorCode: ErrorCode.TYPE_MISMATCH, errorMessage: `The test set "${flagKey}" to a ${kindOf(value)}, but the code asked for a ${kind}` };
77
+ }
78
+ return { value: value, reason: 'STATIC' };
79
+ }
80
+ if (this.ruleset) {
81
+ const r = evaluate(this.ruleset, flagKey, context, fallback, kind);
82
+ if (r.reason !== 'ERROR')
83
+ return { value: r.value, reason: r.reason, ...(r.valueKey !== undefined ? { variant: r.valueKey } : {}) };
84
+ if (r.errorCode !== 'FLAG_NOT_FOUND') {
85
+ return { value: fallback, reason: 'ERROR', errorCode: ErrorCode[r.errorCode ?? 'GENERAL'], ...(r.errorMessage ? { errorMessage: r.errorMessage } : {}) };
86
+ }
87
+ }
88
+ return { value: fallback, reason: 'ERROR', errorCode: ErrorCode.FLAG_NOT_FOUND, errorMessage: `No test value for "${flagKey}". Set one with withFlags, or load a ruleset that has it.` };
89
+ }
90
+ }
91
+ /** A ready-made instance for the common case of one set of flags per test run. */
92
+ export const testFlags = new TestFlags();
93
+ export const withFlags = (values, fn) => testFlags.withFlags(values, fn);
94
+ export const eachValue = (flagKey, fn, values) => testFlags.eachValue(flagKey, fn, values);
95
+ //# sourceMappingURL=index.js.map
package/dist/url.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export declare const DEFAULT_URL = "https://edge.flagdock.com";
2
+ /**
3
+ * Checks where the key will be sent. It must be https, so an admin key never crosses the network in the
4
+ * clear; plain http is accepted only for this machine. Returns the address without a trailing slash, or
5
+ * undefined when it cannot be used.
6
+ */
7
+ export declare function serverUrl(value: string): string | undefined;
package/dist/url.js ADDED
@@ -0,0 +1,22 @@
1
+ export const DEFAULT_URL = 'https://edge.flagdock.com';
2
+ const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);
3
+ /**
4
+ * Checks where the key will be sent. It must be https, so an admin key never crosses the network in the
5
+ * clear; plain http is accepted only for this machine. Returns the address without a trailing slash, or
6
+ * undefined when it cannot be used.
7
+ */
8
+ export function serverUrl(value) {
9
+ let parsed;
10
+ try {
11
+ parsed = new URL(value.trim());
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ if (parsed.username || parsed.password || parsed.search || parsed.hash)
17
+ return undefined;
18
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && LOCAL.has(parsed.hostname)))
19
+ return undefined;
20
+ return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, '');
21
+ }
22
+ //# sourceMappingURL=url.js.map
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@flagdock/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Flagdock in your tests: an in-memory OpenFeature provider with withFlags and eachValue, and flagdock-export to test against your real rules",
5
+ "keywords": [
6
+ "feature-flags",
7
+ "feature-toggles",
8
+ "openfeature",
9
+ "testing",
10
+ "flagdock"
11
+ ],
12
+ "license": "MIT",
13
+ "author": "Flagdock",
14
+ "homepage": "https://flagdock.com",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/paleka/flagsystem.git",
18
+ "directory": "packages/testing"
19
+ },
20
+ "bugs": {
21
+ "email": "info@flagdock.com"
22
+ },
23
+ "type": "module",
24
+ "main": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
32
+ "bin": {
33
+ "flagdock-export": "./dist/export-cli.js"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "!dist/**/*.map",
38
+ "!dist/*.tsbuildinfo",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "scripts": {
43
+ "build": "tsc -b"
44
+ },
45
+ "dependencies": {
46
+ "@flagdock/core": "0.1.1"
47
+ },
48
+ "peerDependencies": {
49
+ "@openfeature/server-sdk": "^1.17.0"
50
+ },
51
+ "devDependencies": {
52
+ "@openfeature/server-sdk": "^1.17.0",
53
+ "@flagdock/server": "0.1.0"
54
+ },
55
+ "sideEffects": false,
56
+ "engines": {
57
+ "node": ">=18"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }