@dif.sh/flags-sdk 0.6.2
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/README.md +114 -0
- package/dist/index.cjs +167 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +130 -0
- package/dist/index.d.ts +130 -0
- package/dist/index.js +167 -0
- package/dist/index.js.map +1 -0
- package/package.json +73 -0
package/README.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Flags SDK - dif.sh Provider
|
|
2
|
+
|
|
3
|
+
The dif.sh adapter for the [Flags SDK](https://flags-sdk.dev/) assigns feature flags and A/B experiments that [dif.sh](https://www.dif.sh/docs/) keeps as Markdown files in your repository.
|
|
4
|
+
|
|
5
|
+
`dif build` compiles every `dif/experiments/active/*.md` file into `dif/generated/client.ts`. The adapter calls `assign()` from `@dif.sh/sdk` against that file on each `decide`. No network request is made.
|
|
6
|
+
|
|
7
|
+
## Setup
|
|
8
|
+
|
|
9
|
+
The dif.sh provider is available in the `@dif.sh/flags-sdk` module. Install it with `@dif.sh/sdk`, which is a peer dependency:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm i @dif.sh/flags-sdk @dif.sh/sdk
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Keep exactly one copy of `@dif.sh/sdk` in your install. The generated client registers experiments into a module-level registry inside `@dif.sh/sdk`, and the adapter reads from that same registry. A second copy would be empty and every flag would fall back to its `defaultValue`.
|
|
16
|
+
|
|
17
|
+
`dif init` gitignores `dif/generated/`, so generate the client before every build:
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"scripts": {
|
|
22
|
+
"prebuild": "dif build"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Provider Instance
|
|
28
|
+
|
|
29
|
+
You can import the default adapter instance `difAdapter` from `@dif.sh/flags-sdk`:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { difAdapter } from "@dif.sh/flags-sdk";
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`difAdapter` exposes:
|
|
36
|
+
|
|
37
|
+
- `difAdapter.variant()` resolves to the assigned variant id, such as `"control"` or `"variant_a"`.
|
|
38
|
+
- `difAdapter.isEnabled()` resolves to `true` when the assigned variant is not the first declared variant. `difAdapter.isEnabled({ on: "variant_b" })` resolves to `true` only for `variant_b`.
|
|
39
|
+
- `difAdapter.identify` reads `userId` from the `dif_uid` cookie.
|
|
40
|
+
|
|
41
|
+
Use `createDifAdapter` to change the defaults:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { createDifAdapter } from "@dif.sh/flags-sdk";
|
|
45
|
+
|
|
46
|
+
const dif = createDifAdapter({
|
|
47
|
+
cookieName: "dif_uid",
|
|
48
|
+
overrides: process.env.VERCEL_ENV !== "production",
|
|
49
|
+
onExposure: ({ key, variant, bucket, userId }) => {
|
|
50
|
+
// send to your analytics; errors are logged and never change the decision
|
|
51
|
+
},
|
|
52
|
+
origin: (key) =>
|
|
53
|
+
`https://github.com/acme/app/blob/main/dif/experiments/active/${key}.md`,
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
| Option | Default | Effect |
|
|
58
|
+
| --- | --- | --- |
|
|
59
|
+
| `cookieName` | `"dif_uid"` | Cookie `identify` reads the user id from. |
|
|
60
|
+
| `overrides` | `true` | Honor the `_dif` cookie that `dif qa --force` preview links (`?_dif=key=variant`) set. |
|
|
61
|
+
| `onExposure` | none | Called when a user is bucketed into a variant. Not called for a missing user id, an audience miss, an exclusion-group loss, or a `_dif` force. |
|
|
62
|
+
| `origin` | none | URL shown in the Flags Explorer for each flag. |
|
|
63
|
+
|
|
64
|
+
## Example
|
|
65
|
+
|
|
66
|
+
The flag `key` is the experiment id, which is the `.md` filename stem.
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
// flags.ts
|
|
70
|
+
import "./dif/generated/client";
|
|
71
|
+
import { flag } from "flags/next";
|
|
72
|
+
import { difAdapter } from "@dif.sh/flags-sdk";
|
|
73
|
+
|
|
74
|
+
export const newCheckoutFlag = flag<boolean>({
|
|
75
|
+
key: "new-checkout",
|
|
76
|
+
defaultValue: false,
|
|
77
|
+
adapter: difAdapter.isEnabled(),
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
export const heroCtaFlag = flag<string>({
|
|
81
|
+
key: "home-hero-cta",
|
|
82
|
+
defaultValue: "control",
|
|
83
|
+
adapter: difAdapter.variant(),
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
What `decide` returns for a flag whose variants are `control`, `variant_a`:
|
|
88
|
+
|
|
89
|
+
| Request | `variant()` | `isEnabled()` | `onExposure` |
|
|
90
|
+
| --- | --- | --- | --- |
|
|
91
|
+
| `dif_uid` cookie set, audience matches | bucketed variant | `variant !== "control"` | called |
|
|
92
|
+
| no `dif_uid` cookie | `"control"` | `false` | not called |
|
|
93
|
+
| audience miss or exclusion-group loss | `"control"` | `false` | not called |
|
|
94
|
+
| `_dif=new-checkout=variant_a` cookie | `"variant_a"` | `true` | not called |
|
|
95
|
+
| key missing from `dif/generated/client.ts` | throws, flag returns `defaultValue` | throws, flag returns `defaultValue` | not called |
|
|
96
|
+
|
|
97
|
+
`identify` cannot set cookies. Mint `dif_uid` in `middleware.ts` so the first request is bucketed; see [`proxy.ts` in the example app](https://github.com/dif-sh/nextjs-feature-flags) for a working version.
|
|
98
|
+
|
|
99
|
+
## Flags Explorer
|
|
100
|
+
|
|
101
|
+
Emit your dif experiments from the `.well-known/vercel/flags` route with `getProviderData`. Pass your `flags.ts` exports so `isEnabled()` flags get `false`/`true` options:
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
// app/.well-known/vercel/flags/route.ts
|
|
105
|
+
import { createFlagsDiscoveryEndpoint } from "flags/next";
|
|
106
|
+
import { getProviderData } from "@dif.sh/flags-sdk";
|
|
107
|
+
import * as flags from "../../../../flags";
|
|
108
|
+
|
|
109
|
+
export const GET = createFlagsDiscoveryEndpoint(() => getProviderData({ flags }));
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Documentation
|
|
113
|
+
|
|
114
|
+
The [dif.sh docs](https://www.dif.sh/docs/) cover the file format, the CLI, and the SDK. [dif-sh/nextjs-feature-flags](https://github.com/dif-sh/nextjs-feature-flags) is a runnable Next.js app using one flag.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/index.ts
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
var _sdk = require('@dif.sh/sdk');
|
|
8
|
+
var DIF_UID_COOKIE = "dif_uid";
|
|
9
|
+
var DIF_OVERRIDES_COOKIE = "_dif";
|
|
10
|
+
var PACKAGE = "@dif.sh/flags-sdk";
|
|
11
|
+
function readCookie(cookies, name) {
|
|
12
|
+
var _a;
|
|
13
|
+
const value = (_a = cookies == null ? void 0 : cookies.get(name)) == null ? void 0 : _a.value;
|
|
14
|
+
return value ? value : void 0;
|
|
15
|
+
}
|
|
16
|
+
function decodeCookie(value) {
|
|
17
|
+
if (value === void 0 || !value.includes("%")) return value;
|
|
18
|
+
try {
|
|
19
|
+
return decodeURIComponent(value);
|
|
20
|
+
} catch (e) {
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function unknownKeyError(key) {
|
|
25
|
+
return new Error(
|
|
26
|
+
`${PACKAGE}: No dif experiment is registered for flag "${key}". Import the generated client once in flags.ts (import './dif/generated/client'), run \`dif build\`, and check that dif/experiments/active/${key}.md has \`status: active\`.`
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
function createDifAdapter(options = {}) {
|
|
30
|
+
const cookieName = _nullishCoalesce(options.cookieName, () => ( DIF_UID_COOKIE));
|
|
31
|
+
const honorOverrides = options.overrides !== false;
|
|
32
|
+
const onExposure = options.onExposure;
|
|
33
|
+
const adapterId = Symbol(PACKAGE);
|
|
34
|
+
const identify = ({ cookies }) => ({
|
|
35
|
+
userId: _nullishCoalesce(readCookie(cookies, cookieName), () => ( null)),
|
|
36
|
+
attributes: {}
|
|
37
|
+
});
|
|
38
|
+
function reportExposure(exposure) {
|
|
39
|
+
if (!onExposure) return;
|
|
40
|
+
try {
|
|
41
|
+
const result = onExposure(exposure);
|
|
42
|
+
if (result && typeof result.then === "function") {
|
|
43
|
+
result.then(void 0, (error) => {
|
|
44
|
+
console.error(`${PACKAGE}: onExposure rejected`, error);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
} catch (error) {
|
|
48
|
+
console.error(`${PACKAGE}: onExposure threw`, error);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function decideAssignment({
|
|
52
|
+
key,
|
|
53
|
+
entities,
|
|
54
|
+
cookies
|
|
55
|
+
}) {
|
|
56
|
+
const userId = _nullishCoalesce((entities ? entities.userId : readCookie(cookies, cookieName)), () => ( null));
|
|
57
|
+
const overrides = honorOverrides ? _nullishCoalesce(_sdk.parseOverrides.call(void 0,
|
|
58
|
+
decodeCookie(readCookie(cookies, DIF_OVERRIDES_COOKIE))
|
|
59
|
+
), () => ( {})) : {};
|
|
60
|
+
const assignment = _sdk.assign.call(void 0, key, {
|
|
61
|
+
userId,
|
|
62
|
+
attributes: _nullishCoalesce((entities == null ? void 0 : entities.attributes), () => ( {})),
|
|
63
|
+
overrides
|
|
64
|
+
});
|
|
65
|
+
const spec = _sdk.getSpec.call(void 0, key);
|
|
66
|
+
if (!assignment || !spec) throw unknownKeyError(key);
|
|
67
|
+
if (assignment.exposed && assignment.bucket !== null && userId !== null) {
|
|
68
|
+
reportExposure({
|
|
69
|
+
key,
|
|
70
|
+
variant: assignment.variant,
|
|
71
|
+
bucket: assignment.bucket,
|
|
72
|
+
userId
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return { assignment, spec };
|
|
76
|
+
}
|
|
77
|
+
function base() {
|
|
78
|
+
return {
|
|
79
|
+
adapterId,
|
|
80
|
+
identify,
|
|
81
|
+
...options.origin !== void 0 ? { origin: options.origin } : {}
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function variant() {
|
|
85
|
+
return {
|
|
86
|
+
...base(),
|
|
87
|
+
decide(params) {
|
|
88
|
+
return decideAssignment(params).assignment.variant;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function isEnabled(isEnabledOptions = {}) {
|
|
93
|
+
const on = isEnabledOptions.on;
|
|
94
|
+
return {
|
|
95
|
+
...base(),
|
|
96
|
+
decide(params) {
|
|
97
|
+
const { assignment, spec } = decideAssignment(params);
|
|
98
|
+
if (on === void 0) return assignment.variant !== spec.variants[0];
|
|
99
|
+
if (!spec.variants.includes(on)) {
|
|
100
|
+
throw new Error(
|
|
101
|
+
`${PACKAGE}: isEnabled({ on: "${on}" }): "${on}" is not a declared variant of "${params.key}" (variants: ${spec.variants.join(", ")}).`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return assignment.variant === on;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return { variant, isEnabled, identify };
|
|
109
|
+
}
|
|
110
|
+
var defaultDifAdapter;
|
|
111
|
+
function getOrCreateDefaultAdapter() {
|
|
112
|
+
if (!defaultDifAdapter) {
|
|
113
|
+
defaultDifAdapter = createDifAdapter();
|
|
114
|
+
}
|
|
115
|
+
return defaultDifAdapter;
|
|
116
|
+
}
|
|
117
|
+
var difAdapter = {
|
|
118
|
+
variant: () => getOrCreateDefaultAdapter().variant(),
|
|
119
|
+
isEnabled: (...args) => getOrCreateDefaultAdapter().isEnabled(...args),
|
|
120
|
+
identify: (params) => getOrCreateDefaultAdapter().identify(params)
|
|
121
|
+
};
|
|
122
|
+
function describe(spec) {
|
|
123
|
+
const weights = spec.variants.map((v) => `${v} ${_nullishCoalesce(spec.weights[v], () => ( 0))}%`).join(", ");
|
|
124
|
+
const group = spec.exclusionGroup !== null ? ` Exclusion group: ${spec.exclusionGroup}.` : "";
|
|
125
|
+
return `Surface: ${spec.surface}. Weights: ${weights}. Fallback: ${spec.variants[0]}.${group}`;
|
|
126
|
+
}
|
|
127
|
+
function isDeclaredFlag(value) {
|
|
128
|
+
return (typeof value === "function" || typeof value === "object" && value !== null) && typeof value.key === "string";
|
|
129
|
+
}
|
|
130
|
+
function getProviderData(options = {}) {
|
|
131
|
+
const booleanKeys = /* @__PURE__ */ new Set();
|
|
132
|
+
for (const declared of Object.values(_nullishCoalesce(options.flags, () => ( {})))) {
|
|
133
|
+
if (isDeclaredFlag(declared) && typeof declared.defaultValue === "boolean") {
|
|
134
|
+
booleanKeys.add(declared.key);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const specs = _sdk.registered.call(void 0, );
|
|
138
|
+
const definitions = specs.reduce((acc, spec) => {
|
|
139
|
+
const origin = typeof options.origin === "function" ? options.origin(spec.id) : options.origin;
|
|
140
|
+
acc[spec.id] = {
|
|
141
|
+
options: booleanKeys.has(spec.id) ? [
|
|
142
|
+
{ value: false, label: `Disabled (${spec.variants[0]})` },
|
|
143
|
+
{ value: true, label: "Enabled" }
|
|
144
|
+
] : spec.variants.map((v) => ({ value: v, label: v })),
|
|
145
|
+
description: describe(spec),
|
|
146
|
+
...origin !== void 0 ? { origin } : {}
|
|
147
|
+
};
|
|
148
|
+
return acc;
|
|
149
|
+
}, {});
|
|
150
|
+
return {
|
|
151
|
+
definitions,
|
|
152
|
+
hints: specs.length === 0 ? [
|
|
153
|
+
{
|
|
154
|
+
key: "dif/empty-registry",
|
|
155
|
+
text: `${PACKAGE}: no experiments are registered. Import './dif/generated/client' in this route and run \`dif build\`.`
|
|
156
|
+
}
|
|
157
|
+
] : []
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
exports.DIF_OVERRIDES_COOKIE = DIF_OVERRIDES_COOKIE; exports.DIF_UID_COOKIE = DIF_UID_COOKIE; exports.createDifAdapter = createDifAdapter; exports.difAdapter = difAdapter; exports.getProviderData = getProviderData;
|
|
167
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/dif/dif/cli/packages/flags-sdk/dist/index.cjs","../src/index.ts"],"names":[],"mappings":"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","file":"/home/runner/work/dif/dif/cli/packages/flags-sdk/dist/index.cjs","sourcesContent":[null,"import {\n type Assignment,\n type AttributeBag,\n type ExperimentSpec,\n assign,\n getSpec,\n parseOverrides,\n registered,\n} from '@dif.sh/sdk';\nimport type {\n Adapter,\n FlagDefinitionsType,\n Identify,\n ProviderData,\n ReadonlyRequestCookies,\n} from 'flags';\n\nexport type { AttributeBag };\n\n/**\n * The evaluation context the dif adapter buckets on.\n *\n * `userId` is hashed with the experiment's salt to pick a bucket `0..9999`.\n * `attributes` feed the experiment's compiled `audience:` predicate.\n */\nexport type DifEntities = {\n /** Stable id to bucket on. `null` serves the first declared variant and records no exposure. */\n userId: string | null;\n /** Audience attributes (`locale`, `device_type`, `plan`, ...). Defaults to `{}`. */\n attributes?: AttributeBag;\n};\n\n/** Cookie holding the anonymous id `identify` reads. Same name `@dif.sh/svelte` mints. */\nexport const DIF_UID_COOKIE = 'dif_uid';\n\n/**\n * Cookie holding QA forces in the `id=variant,id2=variant` form that\n * `dif qa --force` preview links (`?_dif=...`) write.\n */\nexport const DIF_OVERRIDES_COOKIE = '_dif';\n\n/** Payload passed to {@link DifAdapterOptions.onExposure}. */\nexport type DifExposure = {\n /** Flag key, which is the experiment id (the `.md` filename stem). */\n key: string;\n /** Variant the user was bucketed into. */\n variant: string;\n /** Bucket `0..9999`. */\n bucket: number;\n /** The `userId` that was bucketed. */\n userId: string;\n};\n\nexport interface DifAdapterOptions {\n /** Cookie `identify` reads the user id from. Default `\"dif_uid\"`. */\n cookieName?: string;\n /** Honor the `_dif` QA force cookie. Default `true`; pass `false` to ignore it (e.g. in production). */\n overrides?: boolean;\n /**\n * Called once per `decide` that buckets a user into a variant. Not called for\n * a `null` userId, an audience miss, an exclusion-group loss, or a `_dif`\n * force. Errors and rejections are logged and never change the decision; the\n * returned promise is not awaited, so wrap slow work in `waitUntil`.\n */\n onExposure?: (exposure: DifExposure) => void | Promise<void>;\n /** Where a flag is managed, e.g. its `.md` file on GitHub. Shown in the Flags Explorer. */\n origin?: string | ((key: string) => string | undefined);\n}\n\nexport type DifAdapter = {\n /** Adapter resolving to the assigned variant id (`\"control\"`, `\"variant_a\"`, ...). */\n variant: <V extends string = string>() => Adapter<V, DifEntities>;\n /**\n * Adapter resolving to `true` when the assigned variant is not the first\n * declared variant, or, with `{ on }`, when it equals `on`.\n */\n isEnabled: (options?: { on?: string }) => Adapter<boolean, DifEntities>;\n /** Reads `userId` from the `dif_uid` cookie. Returns `attributes: {}`. */\n identify: Identify<DifEntities>;\n};\n\nconst PACKAGE = '@dif.sh/flags-sdk';\n\nfunction readCookie(\n cookies: ReadonlyRequestCookies | undefined,\n name: string,\n): string | undefined {\n const value = cookies?.get(name)?.value;\n return value ? value : undefined;\n}\n\n/** Browsers write `_dif` URL-encoded (`a%3Dv1%2Cb%3Dv2`); some cookie parsers decode it, some don't. */\nfunction decodeCookie(value: string | undefined): string | undefined {\n if (value === undefined || !value.includes('%')) return value;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction unknownKeyError(key: string): Error {\n return new Error(\n `${PACKAGE}: No dif experiment is registered for flag \"${key}\". ` +\n `Import the generated client once in flags.ts (import './dif/generated/client'), ` +\n `run \\`dif build\\`, and check that dif/experiments/active/${key}.md has \\`status: active\\`.`,\n );\n}\n\n/**\n * Create a dif adapter for the Flags SDK.\n *\n * Assignment is local: `decide` calls `assign()` from `@dif.sh/sdk` against the\n * specs `dif/generated/client.ts` registered. No network request is made.\n *\n * ```ts\n * // flags.ts\n * import './dif/generated/client';\n * import { flag } from 'flags/next';\n * import { createDifAdapter } from '@dif.sh/flags-sdk';\n *\n * const dif = createDifAdapter({\n * onExposure: ({ key, variant, userId }) => track('dif.exposure', { key, variant, userId }),\n * });\n *\n * export const newCheckout = flag({\n * key: 'new-checkout',\n * defaultValue: false,\n * adapter: dif.isEnabled(),\n * });\n * ```\n */\nexport function createDifAdapter(options: DifAdapterOptions = {}): DifAdapter {\n const cookieName = options.cookieName ?? DIF_UID_COOKIE;\n const honorOverrides = options.overrides !== false;\n const onExposure = options.onExposure;\n const adapterId = Symbol(PACKAGE);\n\n const identify: Identify<DifEntities> = ({ cookies }) => ({\n userId: readCookie(cookies, cookieName) ?? null,\n attributes: {},\n });\n\n function reportExposure(exposure: DifExposure): void {\n if (!onExposure) return;\n try {\n const result = onExposure(exposure);\n if (result && typeof result.then === 'function') {\n result.then(undefined, (error: unknown) => {\n console.error(`${PACKAGE}: onExposure rejected`, error);\n });\n }\n } catch (error) {\n console.error(`${PACKAGE}: onExposure threw`, error);\n }\n }\n\n function decideAssignment({\n key,\n entities,\n cookies,\n }: {\n key: string;\n entities?: DifEntities;\n cookies: ReadonlyRequestCookies;\n }): { assignment: Assignment; spec: ExperimentSpec } {\n const userId =\n (entities ? entities.userId : readCookie(cookies, cookieName)) ?? null;\n const overrides = honorOverrides\n ? (parseOverrides(\n decodeCookie(readCookie(cookies, DIF_OVERRIDES_COOKIE)),\n ) ?? {})\n : {};\n\n const assignment = assign(key, {\n userId,\n attributes: entities?.attributes ?? {},\n overrides,\n });\n const spec = getSpec(key);\n if (!assignment || !spec) throw unknownKeyError(key);\n\n if (assignment.exposed && assignment.bucket !== null && userId !== null) {\n reportExposure({\n key,\n variant: assignment.variant,\n bucket: assignment.bucket,\n userId,\n });\n }\n return { assignment, spec };\n }\n\n function base<V>(): Omit<Adapter<V, DifEntities>, 'decide'> {\n return {\n adapterId,\n identify,\n ...(options.origin !== undefined ? { origin: options.origin } : {}),\n };\n }\n\n function variant<V extends string = string>(): Adapter<V, DifEntities> {\n return {\n ...base<V>(),\n decide(params): V {\n return decideAssignment(params).assignment.variant as V;\n },\n };\n }\n\n function isEnabled(\n isEnabledOptions: { on?: string } = {},\n ): Adapter<boolean, DifEntities> {\n const on = isEnabledOptions.on;\n return {\n ...base<boolean>(),\n decide(params): boolean {\n const { assignment, spec } = decideAssignment(params);\n if (on === undefined) return assignment.variant !== spec.variants[0];\n if (!spec.variants.includes(on)) {\n throw new Error(\n `${PACKAGE}: isEnabled({ on: \"${on}\" }): \"${on}\" is not a declared variant of \"${params.key}\" ` +\n `(variants: ${spec.variants.join(', ')}).`,\n );\n }\n return assignment.variant === on;\n },\n };\n }\n\n return { variant, isEnabled, identify };\n}\n\nlet defaultDifAdapter: DifAdapter | undefined;\n\nfunction getOrCreateDefaultAdapter(): DifAdapter {\n if (!defaultDifAdapter) {\n defaultDifAdapter = createDifAdapter();\n }\n return defaultDifAdapter;\n}\n\n/**\n * The default dif adapter: `dif_uid` cookie, `_dif` forces honored, no\n * exposure callback. Use {@link createDifAdapter} to change any of those.\n *\n * ```ts\n * // flags.ts\n * import './dif/generated/client';\n * import { flag } from 'flags/next';\n * import { difAdapter } from '@dif.sh/flags-sdk';\n *\n * export const heroCta = flag<string>({\n * key: 'home-hero-cta',\n * defaultValue: 'control',\n * adapter: difAdapter.variant(),\n * });\n * ```\n */\nexport const difAdapter: DifAdapter = {\n variant: <V extends string = string>() =>\n getOrCreateDefaultAdapter().variant<V>(),\n isEnabled: (...args) => getOrCreateDefaultAdapter().isEnabled(...args),\n identify: (params) => getOrCreateDefaultAdapter().identify(params),\n};\n\nfunction describe(spec: ExperimentSpec): string {\n const weights = spec.variants\n .map((v) => `${v} ${spec.weights[v] ?? 0}%`)\n .join(', ');\n const group =\n spec.exclusionGroup !== null\n ? ` Exclusion group: ${spec.exclusionGroup}.`\n : '';\n return `Surface: ${spec.surface}. Weights: ${weights}. Fallback: ${spec.variants[0]}.${group}`;\n}\n\n/** The two fields of a `flag()` declaration {@link getProviderData} reads. */\ntype DeclaredFlag = { key: string; defaultValue?: unknown };\n\nfunction isDeclaredFlag(value: unknown): value is DeclaredFlag {\n return (\n (typeof value === 'function' ||\n (typeof value === 'object' && value !== null)) &&\n typeof (value as DeclaredFlag).key === 'string'\n );\n}\n\n/**\n * Get Flags Explorer data for every experiment `dif/generated/client.ts`\n * registered. Import the generated client (or your `flags.ts`) in the route\n * first, or the registry is empty.\n *\n * Each definition lists the declared variants as options. Pass your `flags.ts`\n * exports as `flags` and any flag with a boolean `defaultValue` (an\n * `isEnabled()` flag) gets `false`/`true` options instead, so a Flags Explorer\n * override has the type the flag returns.\n *\n * ```ts\n * // app/.well-known/vercel/flags/route.ts\n * import { createFlagsDiscoveryEndpoint } from 'flags/next';\n * import { getProviderData } from '@dif.sh/flags-sdk';\n * import * as flags from '../../../../flags';\n *\n * export const GET = createFlagsDiscoveryEndpoint(() => getProviderData({ flags }));\n * ```\n */\nexport function getProviderData(\n options: {\n origin?: DifAdapterOptions['origin'];\n /** Your `flags.ts` exports. Used only to find flags with a boolean `defaultValue`. */\n flags?: Record<string, unknown>;\n } = {},\n): ProviderData {\n const booleanKeys = new Set<string>();\n for (const declared of Object.values(options.flags ?? {})) {\n if (isDeclaredFlag(declared) && typeof declared.defaultValue === 'boolean') {\n booleanKeys.add(declared.key);\n }\n }\n\n const specs = registered();\n const definitions = specs.reduce<FlagDefinitionsType>((acc, spec) => {\n const origin =\n typeof options.origin === 'function'\n ? options.origin(spec.id)\n : options.origin;\n acc[spec.id] = {\n options: booleanKeys.has(spec.id)\n ? [\n { value: false, label: `Disabled (${spec.variants[0]})` },\n { value: true, label: 'Enabled' },\n ]\n : spec.variants.map((v) => ({ value: v, label: v })),\n description: describe(spec),\n ...(origin !== undefined ? { origin } : {}),\n };\n return acc;\n }, {});\n\n return {\n definitions,\n hints:\n specs.length === 0\n ? [\n {\n key: 'dif/empty-registry',\n text: `${PACKAGE}: no experiments are registered. Import './dif/generated/client' in this route and run \\`dif build\\`.`,\n },\n ]\n : [],\n };\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { AttributeBag } from '@dif.sh/sdk';
|
|
2
|
+
export { AttributeBag } from '@dif.sh/sdk';
|
|
3
|
+
import { Adapter, Identify, ProviderData } from 'flags';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The evaluation context the dif adapter buckets on.
|
|
7
|
+
*
|
|
8
|
+
* `userId` is hashed with the experiment's salt to pick a bucket `0..9999`.
|
|
9
|
+
* `attributes` feed the experiment's compiled `audience:` predicate.
|
|
10
|
+
*/
|
|
11
|
+
type DifEntities = {
|
|
12
|
+
/** Stable id to bucket on. `null` serves the first declared variant and records no exposure. */
|
|
13
|
+
userId: string | null;
|
|
14
|
+
/** Audience attributes (`locale`, `device_type`, `plan`, ...). Defaults to `{}`. */
|
|
15
|
+
attributes?: AttributeBag;
|
|
16
|
+
};
|
|
17
|
+
/** Cookie holding the anonymous id `identify` reads. Same name `@dif.sh/svelte` mints. */
|
|
18
|
+
declare const DIF_UID_COOKIE = "dif_uid";
|
|
19
|
+
/**
|
|
20
|
+
* Cookie holding QA forces in the `id=variant,id2=variant` form that
|
|
21
|
+
* `dif qa --force` preview links (`?_dif=...`) write.
|
|
22
|
+
*/
|
|
23
|
+
declare const DIF_OVERRIDES_COOKIE = "_dif";
|
|
24
|
+
/** Payload passed to {@link DifAdapterOptions.onExposure}. */
|
|
25
|
+
type DifExposure = {
|
|
26
|
+
/** Flag key, which is the experiment id (the `.md` filename stem). */
|
|
27
|
+
key: string;
|
|
28
|
+
/** Variant the user was bucketed into. */
|
|
29
|
+
variant: string;
|
|
30
|
+
/** Bucket `0..9999`. */
|
|
31
|
+
bucket: number;
|
|
32
|
+
/** The `userId` that was bucketed. */
|
|
33
|
+
userId: string;
|
|
34
|
+
};
|
|
35
|
+
interface DifAdapterOptions {
|
|
36
|
+
/** Cookie `identify` reads the user id from. Default `"dif_uid"`. */
|
|
37
|
+
cookieName?: string;
|
|
38
|
+
/** Honor the `_dif` QA force cookie. Default `true`; pass `false` to ignore it (e.g. in production). */
|
|
39
|
+
overrides?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Called once per `decide` that buckets a user into a variant. Not called for
|
|
42
|
+
* a `null` userId, an audience miss, an exclusion-group loss, or a `_dif`
|
|
43
|
+
* force. Errors and rejections are logged and never change the decision; the
|
|
44
|
+
* returned promise is not awaited, so wrap slow work in `waitUntil`.
|
|
45
|
+
*/
|
|
46
|
+
onExposure?: (exposure: DifExposure) => void | Promise<void>;
|
|
47
|
+
/** Where a flag is managed, e.g. its `.md` file on GitHub. Shown in the Flags Explorer. */
|
|
48
|
+
origin?: string | ((key: string) => string | undefined);
|
|
49
|
+
}
|
|
50
|
+
type DifAdapter = {
|
|
51
|
+
/** Adapter resolving to the assigned variant id (`"control"`, `"variant_a"`, ...). */
|
|
52
|
+
variant: <V extends string = string>() => Adapter<V, DifEntities>;
|
|
53
|
+
/**
|
|
54
|
+
* Adapter resolving to `true` when the assigned variant is not the first
|
|
55
|
+
* declared variant, or, with `{ on }`, when it equals `on`.
|
|
56
|
+
*/
|
|
57
|
+
isEnabled: (options?: {
|
|
58
|
+
on?: string;
|
|
59
|
+
}) => Adapter<boolean, DifEntities>;
|
|
60
|
+
/** Reads `userId` from the `dif_uid` cookie. Returns `attributes: {}`. */
|
|
61
|
+
identify: Identify<DifEntities>;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Create a dif adapter for the Flags SDK.
|
|
65
|
+
*
|
|
66
|
+
* Assignment is local: `decide` calls `assign()` from `@dif.sh/sdk` against the
|
|
67
|
+
* specs `dif/generated/client.ts` registered. No network request is made.
|
|
68
|
+
*
|
|
69
|
+
* ```ts
|
|
70
|
+
* // flags.ts
|
|
71
|
+
* import './dif/generated/client';
|
|
72
|
+
* import { flag } from 'flags/next';
|
|
73
|
+
* import { createDifAdapter } from '@dif.sh/flags-sdk';
|
|
74
|
+
*
|
|
75
|
+
* const dif = createDifAdapter({
|
|
76
|
+
* onExposure: ({ key, variant, userId }) => track('dif.exposure', { key, variant, userId }),
|
|
77
|
+
* });
|
|
78
|
+
*
|
|
79
|
+
* export const newCheckout = flag({
|
|
80
|
+
* key: 'new-checkout',
|
|
81
|
+
* defaultValue: false,
|
|
82
|
+
* adapter: dif.isEnabled(),
|
|
83
|
+
* });
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
declare function createDifAdapter(options?: DifAdapterOptions): DifAdapter;
|
|
87
|
+
/**
|
|
88
|
+
* The default dif adapter: `dif_uid` cookie, `_dif` forces honored, no
|
|
89
|
+
* exposure callback. Use {@link createDifAdapter} to change any of those.
|
|
90
|
+
*
|
|
91
|
+
* ```ts
|
|
92
|
+
* // flags.ts
|
|
93
|
+
* import './dif/generated/client';
|
|
94
|
+
* import { flag } from 'flags/next';
|
|
95
|
+
* import { difAdapter } from '@dif.sh/flags-sdk';
|
|
96
|
+
*
|
|
97
|
+
* export const heroCta = flag<string>({
|
|
98
|
+
* key: 'home-hero-cta',
|
|
99
|
+
* defaultValue: 'control',
|
|
100
|
+
* adapter: difAdapter.variant(),
|
|
101
|
+
* });
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
declare const difAdapter: DifAdapter;
|
|
105
|
+
/**
|
|
106
|
+
* Get Flags Explorer data for every experiment `dif/generated/client.ts`
|
|
107
|
+
* registered. Import the generated client (or your `flags.ts`) in the route
|
|
108
|
+
* first, or the registry is empty.
|
|
109
|
+
*
|
|
110
|
+
* Each definition lists the declared variants as options. Pass your `flags.ts`
|
|
111
|
+
* exports as `flags` and any flag with a boolean `defaultValue` (an
|
|
112
|
+
* `isEnabled()` flag) gets `false`/`true` options instead, so a Flags Explorer
|
|
113
|
+
* override has the type the flag returns.
|
|
114
|
+
*
|
|
115
|
+
* ```ts
|
|
116
|
+
* // app/.well-known/vercel/flags/route.ts
|
|
117
|
+
* import { createFlagsDiscoveryEndpoint } from 'flags/next';
|
|
118
|
+
* import { getProviderData } from '@dif.sh/flags-sdk';
|
|
119
|
+
* import * as flags from '../../../../flags';
|
|
120
|
+
*
|
|
121
|
+
* export const GET = createFlagsDiscoveryEndpoint(() => getProviderData({ flags }));
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
declare function getProviderData(options?: {
|
|
125
|
+
origin?: DifAdapterOptions['origin'];
|
|
126
|
+
/** Your `flags.ts` exports. Used only to find flags with a boolean `defaultValue`. */
|
|
127
|
+
flags?: Record<string, unknown>;
|
|
128
|
+
}): ProviderData;
|
|
129
|
+
|
|
130
|
+
export { DIF_OVERRIDES_COOKIE, DIF_UID_COOKIE, type DifAdapter, type DifAdapterOptions, type DifEntities, type DifExposure, createDifAdapter, difAdapter, getProviderData };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { AttributeBag } from '@dif.sh/sdk';
|
|
2
|
+
export { AttributeBag } from '@dif.sh/sdk';
|
|
3
|
+
import { Adapter, Identify, ProviderData } from 'flags';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The evaluation context the dif adapter buckets on.
|
|
7
|
+
*
|
|
8
|
+
* `userId` is hashed with the experiment's salt to pick a bucket `0..9999`.
|
|
9
|
+
* `attributes` feed the experiment's compiled `audience:` predicate.
|
|
10
|
+
*/
|
|
11
|
+
type DifEntities = {
|
|
12
|
+
/** Stable id to bucket on. `null` serves the first declared variant and records no exposure. */
|
|
13
|
+
userId: string | null;
|
|
14
|
+
/** Audience attributes (`locale`, `device_type`, `plan`, ...). Defaults to `{}`. */
|
|
15
|
+
attributes?: AttributeBag;
|
|
16
|
+
};
|
|
17
|
+
/** Cookie holding the anonymous id `identify` reads. Same name `@dif.sh/svelte` mints. */
|
|
18
|
+
declare const DIF_UID_COOKIE = "dif_uid";
|
|
19
|
+
/**
|
|
20
|
+
* Cookie holding QA forces in the `id=variant,id2=variant` form that
|
|
21
|
+
* `dif qa --force` preview links (`?_dif=...`) write.
|
|
22
|
+
*/
|
|
23
|
+
declare const DIF_OVERRIDES_COOKIE = "_dif";
|
|
24
|
+
/** Payload passed to {@link DifAdapterOptions.onExposure}. */
|
|
25
|
+
type DifExposure = {
|
|
26
|
+
/** Flag key, which is the experiment id (the `.md` filename stem). */
|
|
27
|
+
key: string;
|
|
28
|
+
/** Variant the user was bucketed into. */
|
|
29
|
+
variant: string;
|
|
30
|
+
/** Bucket `0..9999`. */
|
|
31
|
+
bucket: number;
|
|
32
|
+
/** The `userId` that was bucketed. */
|
|
33
|
+
userId: string;
|
|
34
|
+
};
|
|
35
|
+
interface DifAdapterOptions {
|
|
36
|
+
/** Cookie `identify` reads the user id from. Default `"dif_uid"`. */
|
|
37
|
+
cookieName?: string;
|
|
38
|
+
/** Honor the `_dif` QA force cookie. Default `true`; pass `false` to ignore it (e.g. in production). */
|
|
39
|
+
overrides?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Called once per `decide` that buckets a user into a variant. Not called for
|
|
42
|
+
* a `null` userId, an audience miss, an exclusion-group loss, or a `_dif`
|
|
43
|
+
* force. Errors and rejections are logged and never change the decision; the
|
|
44
|
+
* returned promise is not awaited, so wrap slow work in `waitUntil`.
|
|
45
|
+
*/
|
|
46
|
+
onExposure?: (exposure: DifExposure) => void | Promise<void>;
|
|
47
|
+
/** Where a flag is managed, e.g. its `.md` file on GitHub. Shown in the Flags Explorer. */
|
|
48
|
+
origin?: string | ((key: string) => string | undefined);
|
|
49
|
+
}
|
|
50
|
+
type DifAdapter = {
|
|
51
|
+
/** Adapter resolving to the assigned variant id (`"control"`, `"variant_a"`, ...). */
|
|
52
|
+
variant: <V extends string = string>() => Adapter<V, DifEntities>;
|
|
53
|
+
/**
|
|
54
|
+
* Adapter resolving to `true` when the assigned variant is not the first
|
|
55
|
+
* declared variant, or, with `{ on }`, when it equals `on`.
|
|
56
|
+
*/
|
|
57
|
+
isEnabled: (options?: {
|
|
58
|
+
on?: string;
|
|
59
|
+
}) => Adapter<boolean, DifEntities>;
|
|
60
|
+
/** Reads `userId` from the `dif_uid` cookie. Returns `attributes: {}`. */
|
|
61
|
+
identify: Identify<DifEntities>;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Create a dif adapter for the Flags SDK.
|
|
65
|
+
*
|
|
66
|
+
* Assignment is local: `decide` calls `assign()` from `@dif.sh/sdk` against the
|
|
67
|
+
* specs `dif/generated/client.ts` registered. No network request is made.
|
|
68
|
+
*
|
|
69
|
+
* ```ts
|
|
70
|
+
* // flags.ts
|
|
71
|
+
* import './dif/generated/client';
|
|
72
|
+
* import { flag } from 'flags/next';
|
|
73
|
+
* import { createDifAdapter } from '@dif.sh/flags-sdk';
|
|
74
|
+
*
|
|
75
|
+
* const dif = createDifAdapter({
|
|
76
|
+
* onExposure: ({ key, variant, userId }) => track('dif.exposure', { key, variant, userId }),
|
|
77
|
+
* });
|
|
78
|
+
*
|
|
79
|
+
* export const newCheckout = flag({
|
|
80
|
+
* key: 'new-checkout',
|
|
81
|
+
* defaultValue: false,
|
|
82
|
+
* adapter: dif.isEnabled(),
|
|
83
|
+
* });
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
declare function createDifAdapter(options?: DifAdapterOptions): DifAdapter;
|
|
87
|
+
/**
|
|
88
|
+
* The default dif adapter: `dif_uid` cookie, `_dif` forces honored, no
|
|
89
|
+
* exposure callback. Use {@link createDifAdapter} to change any of those.
|
|
90
|
+
*
|
|
91
|
+
* ```ts
|
|
92
|
+
* // flags.ts
|
|
93
|
+
* import './dif/generated/client';
|
|
94
|
+
* import { flag } from 'flags/next';
|
|
95
|
+
* import { difAdapter } from '@dif.sh/flags-sdk';
|
|
96
|
+
*
|
|
97
|
+
* export const heroCta = flag<string>({
|
|
98
|
+
* key: 'home-hero-cta',
|
|
99
|
+
* defaultValue: 'control',
|
|
100
|
+
* adapter: difAdapter.variant(),
|
|
101
|
+
* });
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
declare const difAdapter: DifAdapter;
|
|
105
|
+
/**
|
|
106
|
+
* Get Flags Explorer data for every experiment `dif/generated/client.ts`
|
|
107
|
+
* registered. Import the generated client (or your `flags.ts`) in the route
|
|
108
|
+
* first, or the registry is empty.
|
|
109
|
+
*
|
|
110
|
+
* Each definition lists the declared variants as options. Pass your `flags.ts`
|
|
111
|
+
* exports as `flags` and any flag with a boolean `defaultValue` (an
|
|
112
|
+
* `isEnabled()` flag) gets `false`/`true` options instead, so a Flags Explorer
|
|
113
|
+
* override has the type the flag returns.
|
|
114
|
+
*
|
|
115
|
+
* ```ts
|
|
116
|
+
* // app/.well-known/vercel/flags/route.ts
|
|
117
|
+
* import { createFlagsDiscoveryEndpoint } from 'flags/next';
|
|
118
|
+
* import { getProviderData } from '@dif.sh/flags-sdk';
|
|
119
|
+
* import * as flags from '../../../../flags';
|
|
120
|
+
*
|
|
121
|
+
* export const GET = createFlagsDiscoveryEndpoint(() => getProviderData({ flags }));
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
declare function getProviderData(options?: {
|
|
125
|
+
origin?: DifAdapterOptions['origin'];
|
|
126
|
+
/** Your `flags.ts` exports. Used only to find flags with a boolean `defaultValue`. */
|
|
127
|
+
flags?: Record<string, unknown>;
|
|
128
|
+
}): ProviderData;
|
|
129
|
+
|
|
130
|
+
export { DIF_OVERRIDES_COOKIE, DIF_UID_COOKIE, type DifAdapter, type DifAdapterOptions, type DifEntities, type DifExposure, createDifAdapter, difAdapter, getProviderData };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
assign,
|
|
4
|
+
getSpec,
|
|
5
|
+
parseOverrides,
|
|
6
|
+
registered
|
|
7
|
+
} from "@dif.sh/sdk";
|
|
8
|
+
var DIF_UID_COOKIE = "dif_uid";
|
|
9
|
+
var DIF_OVERRIDES_COOKIE = "_dif";
|
|
10
|
+
var PACKAGE = "@dif.sh/flags-sdk";
|
|
11
|
+
function readCookie(cookies, name) {
|
|
12
|
+
var _a;
|
|
13
|
+
const value = (_a = cookies == null ? void 0 : cookies.get(name)) == null ? void 0 : _a.value;
|
|
14
|
+
return value ? value : void 0;
|
|
15
|
+
}
|
|
16
|
+
function decodeCookie(value) {
|
|
17
|
+
if (value === void 0 || !value.includes("%")) return value;
|
|
18
|
+
try {
|
|
19
|
+
return decodeURIComponent(value);
|
|
20
|
+
} catch {
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function unknownKeyError(key) {
|
|
25
|
+
return new Error(
|
|
26
|
+
`${PACKAGE}: No dif experiment is registered for flag "${key}". Import the generated client once in flags.ts (import './dif/generated/client'), run \`dif build\`, and check that dif/experiments/active/${key}.md has \`status: active\`.`
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
function createDifAdapter(options = {}) {
|
|
30
|
+
const cookieName = options.cookieName ?? DIF_UID_COOKIE;
|
|
31
|
+
const honorOverrides = options.overrides !== false;
|
|
32
|
+
const onExposure = options.onExposure;
|
|
33
|
+
const adapterId = Symbol(PACKAGE);
|
|
34
|
+
const identify = ({ cookies }) => ({
|
|
35
|
+
userId: readCookie(cookies, cookieName) ?? null,
|
|
36
|
+
attributes: {}
|
|
37
|
+
});
|
|
38
|
+
function reportExposure(exposure) {
|
|
39
|
+
if (!onExposure) return;
|
|
40
|
+
try {
|
|
41
|
+
const result = onExposure(exposure);
|
|
42
|
+
if (result && typeof result.then === "function") {
|
|
43
|
+
result.then(void 0, (error) => {
|
|
44
|
+
console.error(`${PACKAGE}: onExposure rejected`, error);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
} catch (error) {
|
|
48
|
+
console.error(`${PACKAGE}: onExposure threw`, error);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function decideAssignment({
|
|
52
|
+
key,
|
|
53
|
+
entities,
|
|
54
|
+
cookies
|
|
55
|
+
}) {
|
|
56
|
+
const userId = (entities ? entities.userId : readCookie(cookies, cookieName)) ?? null;
|
|
57
|
+
const overrides = honorOverrides ? parseOverrides(
|
|
58
|
+
decodeCookie(readCookie(cookies, DIF_OVERRIDES_COOKIE))
|
|
59
|
+
) ?? {} : {};
|
|
60
|
+
const assignment = assign(key, {
|
|
61
|
+
userId,
|
|
62
|
+
attributes: (entities == null ? void 0 : entities.attributes) ?? {},
|
|
63
|
+
overrides
|
|
64
|
+
});
|
|
65
|
+
const spec = getSpec(key);
|
|
66
|
+
if (!assignment || !spec) throw unknownKeyError(key);
|
|
67
|
+
if (assignment.exposed && assignment.bucket !== null && userId !== null) {
|
|
68
|
+
reportExposure({
|
|
69
|
+
key,
|
|
70
|
+
variant: assignment.variant,
|
|
71
|
+
bucket: assignment.bucket,
|
|
72
|
+
userId
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return { assignment, spec };
|
|
76
|
+
}
|
|
77
|
+
function base() {
|
|
78
|
+
return {
|
|
79
|
+
adapterId,
|
|
80
|
+
identify,
|
|
81
|
+
...options.origin !== void 0 ? { origin: options.origin } : {}
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function variant() {
|
|
85
|
+
return {
|
|
86
|
+
...base(),
|
|
87
|
+
decide(params) {
|
|
88
|
+
return decideAssignment(params).assignment.variant;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function isEnabled(isEnabledOptions = {}) {
|
|
93
|
+
const on = isEnabledOptions.on;
|
|
94
|
+
return {
|
|
95
|
+
...base(),
|
|
96
|
+
decide(params) {
|
|
97
|
+
const { assignment, spec } = decideAssignment(params);
|
|
98
|
+
if (on === void 0) return assignment.variant !== spec.variants[0];
|
|
99
|
+
if (!spec.variants.includes(on)) {
|
|
100
|
+
throw new Error(
|
|
101
|
+
`${PACKAGE}: isEnabled({ on: "${on}" }): "${on}" is not a declared variant of "${params.key}" (variants: ${spec.variants.join(", ")}).`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return assignment.variant === on;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return { variant, isEnabled, identify };
|
|
109
|
+
}
|
|
110
|
+
var defaultDifAdapter;
|
|
111
|
+
function getOrCreateDefaultAdapter() {
|
|
112
|
+
if (!defaultDifAdapter) {
|
|
113
|
+
defaultDifAdapter = createDifAdapter();
|
|
114
|
+
}
|
|
115
|
+
return defaultDifAdapter;
|
|
116
|
+
}
|
|
117
|
+
var difAdapter = {
|
|
118
|
+
variant: () => getOrCreateDefaultAdapter().variant(),
|
|
119
|
+
isEnabled: (...args) => getOrCreateDefaultAdapter().isEnabled(...args),
|
|
120
|
+
identify: (params) => getOrCreateDefaultAdapter().identify(params)
|
|
121
|
+
};
|
|
122
|
+
function describe(spec) {
|
|
123
|
+
const weights = spec.variants.map((v) => `${v} ${spec.weights[v] ?? 0}%`).join(", ");
|
|
124
|
+
const group = spec.exclusionGroup !== null ? ` Exclusion group: ${spec.exclusionGroup}.` : "";
|
|
125
|
+
return `Surface: ${spec.surface}. Weights: ${weights}. Fallback: ${spec.variants[0]}.${group}`;
|
|
126
|
+
}
|
|
127
|
+
function isDeclaredFlag(value) {
|
|
128
|
+
return (typeof value === "function" || typeof value === "object" && value !== null) && typeof value.key === "string";
|
|
129
|
+
}
|
|
130
|
+
function getProviderData(options = {}) {
|
|
131
|
+
const booleanKeys = /* @__PURE__ */ new Set();
|
|
132
|
+
for (const declared of Object.values(options.flags ?? {})) {
|
|
133
|
+
if (isDeclaredFlag(declared) && typeof declared.defaultValue === "boolean") {
|
|
134
|
+
booleanKeys.add(declared.key);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const specs = registered();
|
|
138
|
+
const definitions = specs.reduce((acc, spec) => {
|
|
139
|
+
const origin = typeof options.origin === "function" ? options.origin(spec.id) : options.origin;
|
|
140
|
+
acc[spec.id] = {
|
|
141
|
+
options: booleanKeys.has(spec.id) ? [
|
|
142
|
+
{ value: false, label: `Disabled (${spec.variants[0]})` },
|
|
143
|
+
{ value: true, label: "Enabled" }
|
|
144
|
+
] : spec.variants.map((v) => ({ value: v, label: v })),
|
|
145
|
+
description: describe(spec),
|
|
146
|
+
...origin !== void 0 ? { origin } : {}
|
|
147
|
+
};
|
|
148
|
+
return acc;
|
|
149
|
+
}, {});
|
|
150
|
+
return {
|
|
151
|
+
definitions,
|
|
152
|
+
hints: specs.length === 0 ? [
|
|
153
|
+
{
|
|
154
|
+
key: "dif/empty-registry",
|
|
155
|
+
text: `${PACKAGE}: no experiments are registered. Import './dif/generated/client' in this route and run \`dif build\`.`
|
|
156
|
+
}
|
|
157
|
+
] : []
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
export {
|
|
161
|
+
DIF_OVERRIDES_COOKIE,
|
|
162
|
+
DIF_UID_COOKIE,
|
|
163
|
+
createDifAdapter,
|
|
164
|
+
difAdapter,
|
|
165
|
+
getProviderData
|
|
166
|
+
};
|
|
167
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n type Assignment,\n type AttributeBag,\n type ExperimentSpec,\n assign,\n getSpec,\n parseOverrides,\n registered,\n} from '@dif.sh/sdk';\nimport type {\n Adapter,\n FlagDefinitionsType,\n Identify,\n ProviderData,\n ReadonlyRequestCookies,\n} from 'flags';\n\nexport type { AttributeBag };\n\n/**\n * The evaluation context the dif adapter buckets on.\n *\n * `userId` is hashed with the experiment's salt to pick a bucket `0..9999`.\n * `attributes` feed the experiment's compiled `audience:` predicate.\n */\nexport type DifEntities = {\n /** Stable id to bucket on. `null` serves the first declared variant and records no exposure. */\n userId: string | null;\n /** Audience attributes (`locale`, `device_type`, `plan`, ...). Defaults to `{}`. */\n attributes?: AttributeBag;\n};\n\n/** Cookie holding the anonymous id `identify` reads. Same name `@dif.sh/svelte` mints. */\nexport const DIF_UID_COOKIE = 'dif_uid';\n\n/**\n * Cookie holding QA forces in the `id=variant,id2=variant` form that\n * `dif qa --force` preview links (`?_dif=...`) write.\n */\nexport const DIF_OVERRIDES_COOKIE = '_dif';\n\n/** Payload passed to {@link DifAdapterOptions.onExposure}. */\nexport type DifExposure = {\n /** Flag key, which is the experiment id (the `.md` filename stem). */\n key: string;\n /** Variant the user was bucketed into. */\n variant: string;\n /** Bucket `0..9999`. */\n bucket: number;\n /** The `userId` that was bucketed. */\n userId: string;\n};\n\nexport interface DifAdapterOptions {\n /** Cookie `identify` reads the user id from. Default `\"dif_uid\"`. */\n cookieName?: string;\n /** Honor the `_dif` QA force cookie. Default `true`; pass `false` to ignore it (e.g. in production). */\n overrides?: boolean;\n /**\n * Called once per `decide` that buckets a user into a variant. Not called for\n * a `null` userId, an audience miss, an exclusion-group loss, or a `_dif`\n * force. Errors and rejections are logged and never change the decision; the\n * returned promise is not awaited, so wrap slow work in `waitUntil`.\n */\n onExposure?: (exposure: DifExposure) => void | Promise<void>;\n /** Where a flag is managed, e.g. its `.md` file on GitHub. Shown in the Flags Explorer. */\n origin?: string | ((key: string) => string | undefined);\n}\n\nexport type DifAdapter = {\n /** Adapter resolving to the assigned variant id (`\"control\"`, `\"variant_a\"`, ...). */\n variant: <V extends string = string>() => Adapter<V, DifEntities>;\n /**\n * Adapter resolving to `true` when the assigned variant is not the first\n * declared variant, or, with `{ on }`, when it equals `on`.\n */\n isEnabled: (options?: { on?: string }) => Adapter<boolean, DifEntities>;\n /** Reads `userId` from the `dif_uid` cookie. Returns `attributes: {}`. */\n identify: Identify<DifEntities>;\n};\n\nconst PACKAGE = '@dif.sh/flags-sdk';\n\nfunction readCookie(\n cookies: ReadonlyRequestCookies | undefined,\n name: string,\n): string | undefined {\n const value = cookies?.get(name)?.value;\n return value ? value : undefined;\n}\n\n/** Browsers write `_dif` URL-encoded (`a%3Dv1%2Cb%3Dv2`); some cookie parsers decode it, some don't. */\nfunction decodeCookie(value: string | undefined): string | undefined {\n if (value === undefined || !value.includes('%')) return value;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction unknownKeyError(key: string): Error {\n return new Error(\n `${PACKAGE}: No dif experiment is registered for flag \"${key}\". ` +\n `Import the generated client once in flags.ts (import './dif/generated/client'), ` +\n `run \\`dif build\\`, and check that dif/experiments/active/${key}.md has \\`status: active\\`.`,\n );\n}\n\n/**\n * Create a dif adapter for the Flags SDK.\n *\n * Assignment is local: `decide` calls `assign()` from `@dif.sh/sdk` against the\n * specs `dif/generated/client.ts` registered. No network request is made.\n *\n * ```ts\n * // flags.ts\n * import './dif/generated/client';\n * import { flag } from 'flags/next';\n * import { createDifAdapter } from '@dif.sh/flags-sdk';\n *\n * const dif = createDifAdapter({\n * onExposure: ({ key, variant, userId }) => track('dif.exposure', { key, variant, userId }),\n * });\n *\n * export const newCheckout = flag({\n * key: 'new-checkout',\n * defaultValue: false,\n * adapter: dif.isEnabled(),\n * });\n * ```\n */\nexport function createDifAdapter(options: DifAdapterOptions = {}): DifAdapter {\n const cookieName = options.cookieName ?? DIF_UID_COOKIE;\n const honorOverrides = options.overrides !== false;\n const onExposure = options.onExposure;\n const adapterId = Symbol(PACKAGE);\n\n const identify: Identify<DifEntities> = ({ cookies }) => ({\n userId: readCookie(cookies, cookieName) ?? null,\n attributes: {},\n });\n\n function reportExposure(exposure: DifExposure): void {\n if (!onExposure) return;\n try {\n const result = onExposure(exposure);\n if (result && typeof result.then === 'function') {\n result.then(undefined, (error: unknown) => {\n console.error(`${PACKAGE}: onExposure rejected`, error);\n });\n }\n } catch (error) {\n console.error(`${PACKAGE}: onExposure threw`, error);\n }\n }\n\n function decideAssignment({\n key,\n entities,\n cookies,\n }: {\n key: string;\n entities?: DifEntities;\n cookies: ReadonlyRequestCookies;\n }): { assignment: Assignment; spec: ExperimentSpec } {\n const userId =\n (entities ? entities.userId : readCookie(cookies, cookieName)) ?? null;\n const overrides = honorOverrides\n ? (parseOverrides(\n decodeCookie(readCookie(cookies, DIF_OVERRIDES_COOKIE)),\n ) ?? {})\n : {};\n\n const assignment = assign(key, {\n userId,\n attributes: entities?.attributes ?? {},\n overrides,\n });\n const spec = getSpec(key);\n if (!assignment || !spec) throw unknownKeyError(key);\n\n if (assignment.exposed && assignment.bucket !== null && userId !== null) {\n reportExposure({\n key,\n variant: assignment.variant,\n bucket: assignment.bucket,\n userId,\n });\n }\n return { assignment, spec };\n }\n\n function base<V>(): Omit<Adapter<V, DifEntities>, 'decide'> {\n return {\n adapterId,\n identify,\n ...(options.origin !== undefined ? { origin: options.origin } : {}),\n };\n }\n\n function variant<V extends string = string>(): Adapter<V, DifEntities> {\n return {\n ...base<V>(),\n decide(params): V {\n return decideAssignment(params).assignment.variant as V;\n },\n };\n }\n\n function isEnabled(\n isEnabledOptions: { on?: string } = {},\n ): Adapter<boolean, DifEntities> {\n const on = isEnabledOptions.on;\n return {\n ...base<boolean>(),\n decide(params): boolean {\n const { assignment, spec } = decideAssignment(params);\n if (on === undefined) return assignment.variant !== spec.variants[0];\n if (!spec.variants.includes(on)) {\n throw new Error(\n `${PACKAGE}: isEnabled({ on: \"${on}\" }): \"${on}\" is not a declared variant of \"${params.key}\" ` +\n `(variants: ${spec.variants.join(', ')}).`,\n );\n }\n return assignment.variant === on;\n },\n };\n }\n\n return { variant, isEnabled, identify };\n}\n\nlet defaultDifAdapter: DifAdapter | undefined;\n\nfunction getOrCreateDefaultAdapter(): DifAdapter {\n if (!defaultDifAdapter) {\n defaultDifAdapter = createDifAdapter();\n }\n return defaultDifAdapter;\n}\n\n/**\n * The default dif adapter: `dif_uid` cookie, `_dif` forces honored, no\n * exposure callback. Use {@link createDifAdapter} to change any of those.\n *\n * ```ts\n * // flags.ts\n * import './dif/generated/client';\n * import { flag } from 'flags/next';\n * import { difAdapter } from '@dif.sh/flags-sdk';\n *\n * export const heroCta = flag<string>({\n * key: 'home-hero-cta',\n * defaultValue: 'control',\n * adapter: difAdapter.variant(),\n * });\n * ```\n */\nexport const difAdapter: DifAdapter = {\n variant: <V extends string = string>() =>\n getOrCreateDefaultAdapter().variant<V>(),\n isEnabled: (...args) => getOrCreateDefaultAdapter().isEnabled(...args),\n identify: (params) => getOrCreateDefaultAdapter().identify(params),\n};\n\nfunction describe(spec: ExperimentSpec): string {\n const weights = spec.variants\n .map((v) => `${v} ${spec.weights[v] ?? 0}%`)\n .join(', ');\n const group =\n spec.exclusionGroup !== null\n ? ` Exclusion group: ${spec.exclusionGroup}.`\n : '';\n return `Surface: ${spec.surface}. Weights: ${weights}. Fallback: ${spec.variants[0]}.${group}`;\n}\n\n/** The two fields of a `flag()` declaration {@link getProviderData} reads. */\ntype DeclaredFlag = { key: string; defaultValue?: unknown };\n\nfunction isDeclaredFlag(value: unknown): value is DeclaredFlag {\n return (\n (typeof value === 'function' ||\n (typeof value === 'object' && value !== null)) &&\n typeof (value as DeclaredFlag).key === 'string'\n );\n}\n\n/**\n * Get Flags Explorer data for every experiment `dif/generated/client.ts`\n * registered. Import the generated client (or your `flags.ts`) in the route\n * first, or the registry is empty.\n *\n * Each definition lists the declared variants as options. Pass your `flags.ts`\n * exports as `flags` and any flag with a boolean `defaultValue` (an\n * `isEnabled()` flag) gets `false`/`true` options instead, so a Flags Explorer\n * override has the type the flag returns.\n *\n * ```ts\n * // app/.well-known/vercel/flags/route.ts\n * import { createFlagsDiscoveryEndpoint } from 'flags/next';\n * import { getProviderData } from '@dif.sh/flags-sdk';\n * import * as flags from '../../../../flags';\n *\n * export const GET = createFlagsDiscoveryEndpoint(() => getProviderData({ flags }));\n * ```\n */\nexport function getProviderData(\n options: {\n origin?: DifAdapterOptions['origin'];\n /** Your `flags.ts` exports. Used only to find flags with a boolean `defaultValue`. */\n flags?: Record<string, unknown>;\n } = {},\n): ProviderData {\n const booleanKeys = new Set<string>();\n for (const declared of Object.values(options.flags ?? {})) {\n if (isDeclaredFlag(declared) && typeof declared.defaultValue === 'boolean') {\n booleanKeys.add(declared.key);\n }\n }\n\n const specs = registered();\n const definitions = specs.reduce<FlagDefinitionsType>((acc, spec) => {\n const origin =\n typeof options.origin === 'function'\n ? options.origin(spec.id)\n : options.origin;\n acc[spec.id] = {\n options: booleanKeys.has(spec.id)\n ? [\n { value: false, label: `Disabled (${spec.variants[0]})` },\n { value: true, label: 'Enabled' },\n ]\n : spec.variants.map((v) => ({ value: v, label: v })),\n description: describe(spec),\n ...(origin !== undefined ? { origin } : {}),\n };\n return acc;\n }, {});\n\n return {\n definitions,\n hints:\n specs.length === 0\n ? [\n {\n key: 'dif/empty-registry',\n text: `${PACKAGE}: no experiments are registered. Import './dif/generated/client' in this route and run \\`dif build\\`.`,\n },\n ]\n : [],\n };\n}\n"],"mappings":"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","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dif.sh/flags-sdk",
|
|
3
|
+
"version": "0.6.2",
|
|
4
|
+
"description": "Vercel Flags SDK adapter for dif.sh — assigns variants from dif/generated/client.ts.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"flags-sdk",
|
|
7
|
+
"vercel",
|
|
8
|
+
"dif.sh",
|
|
9
|
+
"feature-flags",
|
|
10
|
+
"ab-testing",
|
|
11
|
+
"experimentation",
|
|
12
|
+
"flags-as-code"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://www.dif.sh/docs/",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/dif-sh/dif/issues"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/dif-sh/dif.git",
|
|
21
|
+
"directory": "cli/packages/flags-sdk"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"author": "Chris Fowles <chris@dif.sh>",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"type": "module",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"import": "./dist/index.js",
|
|
30
|
+
"require": "./dist/index.cjs"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"main": "./dist/index.js",
|
|
34
|
+
"typesVersions": {
|
|
35
|
+
"*": {
|
|
36
|
+
".": [
|
|
37
|
+
"dist/*.d.ts",
|
|
38
|
+
"dist/*.d.cts"
|
|
39
|
+
]
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist",
|
|
44
|
+
"README.md"
|
|
45
|
+
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "rimraf dist && tsup",
|
|
48
|
+
"dev": "tsup --watch --clean=false",
|
|
49
|
+
"test": "vitest --run",
|
|
50
|
+
"test:watch": "vitest",
|
|
51
|
+
"type-check": "tsc --noEmit",
|
|
52
|
+
"lint": "tsc --noEmit",
|
|
53
|
+
"prepublishOnly": "npm run lint && npm test && npm run build"
|
|
54
|
+
},
|
|
55
|
+
"peerDependencies": {
|
|
56
|
+
"@dif.sh/sdk": "^0.6.2"
|
|
57
|
+
},
|
|
58
|
+
"devDependencies": {
|
|
59
|
+
"@dif.sh/sdk": "file:../sdk",
|
|
60
|
+
"@types/node": "22.14.0",
|
|
61
|
+
"flags": "^4.3.1",
|
|
62
|
+
"rimraf": "6.1.2",
|
|
63
|
+
"tsup": "8.5.1",
|
|
64
|
+
"typescript": "5.6.3",
|
|
65
|
+
"vitest": "^3.2.7"
|
|
66
|
+
},
|
|
67
|
+
"publishConfig": {
|
|
68
|
+
"access": "public"
|
|
69
|
+
},
|
|
70
|
+
"engines": {
|
|
71
|
+
"node": ">=20.19"
|
|
72
|
+
}
|
|
73
|
+
}
|