flags 0.2.2 → 3.1.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +434 -0
  2. package/LICENSE.md +21 -0
  3. package/README.md +44 -93
  4. package/dist/analytics.cjs +7 -0
  5. package/dist/analytics.cjs.map +1 -0
  6. package/dist/analytics.d.cts +8 -0
  7. package/dist/analytics.d.ts +8 -0
  8. package/dist/analytics.js +7 -0
  9. package/dist/analytics.js.map +1 -0
  10. package/dist/chunk-2UDLZC33.js +9 -0
  11. package/dist/chunk-2UDLZC33.js.map +1 -0
  12. package/dist/chunk-7EGZDBDN.js +406 -0
  13. package/dist/chunk-7EGZDBDN.js.map +1 -0
  14. package/dist/chunk-AVMIIWOF.cjs +21 -0
  15. package/dist/chunk-AVMIIWOF.cjs.map +1 -0
  16. package/dist/chunk-IGXYQW6R.cjs +406 -0
  17. package/dist/chunk-IGXYQW6R.cjs.map +1 -0
  18. package/dist/chunk-MEG7RDX7.cjs +9 -0
  19. package/dist/chunk-MEG7RDX7.cjs.map +1 -0
  20. package/dist/chunk-ZNKTXALY.js +21 -0
  21. package/dist/chunk-ZNKTXALY.js.map +1 -0
  22. package/dist/index.cjs +25 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +89 -0
  25. package/dist/index.d.ts +89 -0
  26. package/dist/index.js +25 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/next.cjs +613 -0
  29. package/dist/next.cjs.map +1 -0
  30. package/dist/next.d.cts +191 -0
  31. package/dist/next.d.ts +191 -0
  32. package/dist/next.js +613 -0
  33. package/dist/next.js.map +1 -0
  34. package/dist/react.cjs +39 -0
  35. package/dist/react.cjs.map +1 -0
  36. package/dist/react.d.cts +20 -0
  37. package/dist/react.d.ts +20 -0
  38. package/dist/react.js +39 -0
  39. package/dist/react.js.map +1 -0
  40. package/dist/sveltekit.cjs +171 -0
  41. package/dist/sveltekit.cjs.map +1 -0
  42. package/dist/sveltekit.d.cts +42 -0
  43. package/dist/sveltekit.d.ts +42 -0
  44. package/dist/sveltekit.js +171 -0
  45. package/dist/sveltekit.js.map +1 -0
  46. package/dist/types-CGpl9epN.d.cts +237 -0
  47. package/dist/types-CGpl9epN.d.ts +237 -0
  48. package/package.json +112 -28
  49. package/LICENSE +0 -9
  50. package/dist/flags.cjs +0 -366
  51. package/dist/flags.cjs.map +0 -1
  52. package/dist/flags.d.cts +0 -84
  53. package/dist/flags.d.ts +0 -84
  54. package/dist/flags.js +0 -330
  55. package/dist/flags.js.map +0 -1
@@ -0,0 +1,171 @@
1
+ import {
2
+ normalizeOptions
3
+ } from "./chunk-ZNKTXALY.js";
4
+ import {
5
+ HeadersAdapter,
6
+ RequestCookiesAdapter,
7
+ decrypt,
8
+ encrypt,
9
+ reportValue,
10
+ verifyAccess
11
+ } from "./chunk-7EGZDBDN.js";
12
+ import {
13
+ safeJsonStringify
14
+ } from "./chunk-2UDLZC33.js";
15
+
16
+ // src/sveltekit/index.ts
17
+ import { AsyncLocalStorage } from "node:async_hooks";
18
+ import { RequestCookies } from "@edge-runtime/cookies";
19
+ function hasOwnProperty(obj, prop) {
20
+ return obj.hasOwnProperty(prop);
21
+ }
22
+ var headersMap = /* @__PURE__ */ new WeakMap();
23
+ var cookiesMap = /* @__PURE__ */ new WeakMap();
24
+ function sealHeaders(headers) {
25
+ const cached = headersMap.get(headers);
26
+ if (cached !== void 0)
27
+ return cached;
28
+ const sealed = HeadersAdapter.seal(headers);
29
+ headersMap.set(headers, sealed);
30
+ return sealed;
31
+ }
32
+ function sealCookies(headers) {
33
+ const cached = cookiesMap.get(headers);
34
+ if (cached !== void 0)
35
+ return cached;
36
+ const sealed = RequestCookiesAdapter.seal(new RequestCookies(headers));
37
+ cookiesMap.set(headers, sealed);
38
+ return sealed;
39
+ }
40
+ async function resolveObjectPromises(obj) {
41
+ const entries = Object.entries(obj);
42
+ const resolvedEntries = await Promise.all(
43
+ entries.map(async ([key, promise]) => {
44
+ const value = await promise;
45
+ return [key, value];
46
+ })
47
+ );
48
+ return Object.fromEntries(resolvedEntries);
49
+ }
50
+ function getDecide(definition) {
51
+ return function decide(params) {
52
+ if (typeof definition.decide === "function") {
53
+ return definition.decide(params);
54
+ }
55
+ if (typeof definition.adapter?.decide === "function") {
56
+ return definition.adapter.decide({ key: definition.key, ...params });
57
+ }
58
+ throw new Error(`flags: No decide function provided for ${definition.key}`);
59
+ };
60
+ }
61
+ function flag(definition) {
62
+ const decide = getDecide(definition);
63
+ const flagImpl = async function flagImpl2() {
64
+ const store = flagStorage.getStore();
65
+ if (!store) {
66
+ throw new Error("flags: context not found");
67
+ }
68
+ if (hasOwnProperty(store.usedFlags, definition.key)) {
69
+ const valuePromise2 = store.usedFlags[definition.key];
70
+ if (typeof valuePromise2 !== "undefined") {
71
+ return valuePromise2;
72
+ }
73
+ }
74
+ const overridesCookie = store.event.cookies.get("vercel-flag-overrides");
75
+ const overrides = overridesCookie ? await decrypt(overridesCookie, store.secret) : void 0;
76
+ if (overrides && hasOwnProperty(overrides, definition.key)) {
77
+ const value2 = overrides[definition.key];
78
+ if (typeof value2 !== "undefined") {
79
+ reportValue(definition.key, value2);
80
+ store.usedFlags[definition.key] = Promise.resolve(value2);
81
+ return value2;
82
+ }
83
+ }
84
+ const valuePromise = decide(
85
+ {
86
+ headers: sealHeaders(store.event.request.headers),
87
+ cookies: sealCookies(store.event.request.headers)
88
+ },
89
+ // @ts-expect-error not part of the type, but we supply it for convenience
90
+ { event: store.event }
91
+ );
92
+ store.usedFlags[definition.key] = valuePromise;
93
+ const value = await valuePromise;
94
+ reportValue(definition.key, value);
95
+ return value;
96
+ };
97
+ flagImpl.key = definition.key;
98
+ flagImpl.defaultValue = definition.defaultValue;
99
+ flagImpl.origin = definition.origin;
100
+ flagImpl.description = definition.description;
101
+ flagImpl.options = definition.options;
102
+ flagImpl.decide = decide;
103
+ return flagImpl;
104
+ }
105
+ function getProviderData(flags) {
106
+ const definitions = Object.values(flags).reduce(
107
+ (acc, d) => {
108
+ acc[d.key] = {
109
+ options: normalizeOptions(d.options),
110
+ origin: d.origin,
111
+ description: d.description
112
+ };
113
+ return acc;
114
+ },
115
+ {}
116
+ );
117
+ return { definitions, hints: [] };
118
+ }
119
+ function createContext(event, secret) {
120
+ return {
121
+ event,
122
+ secret,
123
+ usedFlags: {}
124
+ };
125
+ }
126
+ var flagStorage = new AsyncLocalStorage();
127
+ function createHandle({
128
+ secret,
129
+ flags
130
+ }) {
131
+ return function handle({ event, resolve }) {
132
+ if (flags && // avoid creating the URL object for every request by checking with includes() first
133
+ event.request.url.includes("/.well-known/") && new URL(event.request.url).pathname === "/.well-known/vercel/flags") {
134
+ return handleWellKnownFlagsRoute(event, secret, flags);
135
+ }
136
+ const flagContext = createContext(event, secret);
137
+ return flagStorage.run(
138
+ flagContext,
139
+ () => resolve(event, {
140
+ transformPageChunk: async ({ html }) => {
141
+ const store = flagStorage.getStore();
142
+ if (!store || Object.keys(store.usedFlags).length === 0)
143
+ return html;
144
+ const encryptedFlagValues = await encrypt(
145
+ await resolveObjectPromises(store.usedFlags),
146
+ secret
147
+ );
148
+ return html.replace(
149
+ "</body>",
150
+ `<script type="application/json" data-flag-values>${safeJsonStringify(encryptedFlagValues)}</script></body>`
151
+ );
152
+ }
153
+ })
154
+ );
155
+ };
156
+ }
157
+ async function handleWellKnownFlagsRoute(event, secret, flags) {
158
+ const access = await verifyAccess(
159
+ event.request.headers.get("Authorization"),
160
+ secret
161
+ );
162
+ if (!access)
163
+ return new Response(null, { status: 401 });
164
+ return Response.json(getProviderData(flags));
165
+ }
166
+ export {
167
+ createHandle,
168
+ flag,
169
+ getProviderData
170
+ };
171
+ //# sourceMappingURL=sveltekit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sveltekit/index.ts"],"sourcesContent":["import type { Handle, RequestEvent } from '@sveltejs/kit';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport {\n type ApiData,\n decrypt,\n encrypt,\n reportValue,\n safeJsonStringify,\n verifyAccess,\n type JsonValue,\n type FlagDefinitionsType,\n} from '..';\nimport { Decide, FlagDeclaration, GenerousOption } from '../types';\nimport {\n type ReadonlyHeaders,\n HeadersAdapter,\n} from '../spec-extension/adapters/headers';\nimport {\n type ReadonlyRequestCookies,\n RequestCookiesAdapter,\n} from '../spec-extension/adapters/request-cookies';\nimport { normalizeOptions } from '../lib/normalize-options';\nimport { RequestCookies } from '@edge-runtime/cookies';\n\nfunction hasOwnProperty<X extends {}, Y extends PropertyKey>(\n obj: X,\n prop: Y,\n): obj is X & Record<Y, unknown> {\n return obj.hasOwnProperty(prop);\n}\n\nconst headersMap = new WeakMap<Headers, ReadonlyHeaders>();\nconst cookiesMap = new WeakMap<Headers, ReadonlyRequestCookies>();\n\nfunction sealHeaders(headers: Headers): ReadonlyHeaders {\n const cached = headersMap.get(headers);\n if (cached !== undefined) return cached;\n\n const sealed = HeadersAdapter.seal(headers);\n headersMap.set(headers, sealed);\n return sealed;\n}\n\nfunction sealCookies(headers: Headers): ReadonlyRequestCookies {\n const cached = cookiesMap.get(headers);\n if (cached !== undefined) return cached;\n\n const sealed = RequestCookiesAdapter.seal(new RequestCookies(headers));\n cookiesMap.set(headers, sealed);\n return sealed;\n}\n\ntype Flag<ReturnValue> = (() => ReturnValue | Promise<ReturnValue>) & {\n key: string;\n description?: string;\n origin?: string | Record<string, unknown>;\n options?: GenerousOption<ReturnValue>[];\n};\n\ntype PromisesMap<T> = {\n [K in keyof T]: Promise<T[K]>;\n};\n\nasync function resolveObjectPromises<T>(obj: PromisesMap<T>): Promise<T> {\n // Convert the object into an array of [key, promise] pairs\n const entries = Object.entries(obj) as [keyof T, Promise<any>][];\n\n // Use Promise.all to wait for all the promises to resolve\n const resolvedEntries = await Promise.all(\n entries.map(async ([key, promise]) => {\n const value = await promise;\n return [key, value] as [keyof T, T[keyof T]];\n }),\n );\n\n // Convert the array of resolved [key, value] pairs back into an object\n return Object.fromEntries(resolvedEntries) as T;\n}\n\nfunction getDecide<ValueType, EntitiesType>(\n definition: FlagDeclaration<ValueType, EntitiesType>,\n): Decide<ValueType, EntitiesType> {\n return function decide(params) {\n if (typeof definition.decide === 'function') {\n return definition.decide(params);\n }\n if (typeof definition.adapter?.decide === 'function') {\n return definition.adapter.decide({ key: definition.key, ...params });\n }\n throw new Error(`flags: No decide function provided for ${definition.key}`);\n };\n}\n\n/**\n * Declares a feature flag\n */\nexport function flag<T>(definition: FlagDeclaration<T, unknown>): Flag<T> {\n const decide = getDecide<T, unknown>(definition);\n\n const flagImpl = async function flagImpl(): Promise<T> {\n const store = flagStorage.getStore();\n\n if (!store) {\n throw new Error('flags: context not found');\n }\n\n if (hasOwnProperty(store.usedFlags, definition.key)) {\n const valuePromise = store.usedFlags[definition.key];\n if (typeof valuePromise !== 'undefined') {\n return valuePromise as Promise<T>;\n }\n }\n\n const overridesCookie = store.event.cookies.get('vercel-flag-overrides');\n const overrides = overridesCookie\n ? await decrypt<Record<string, T>>(overridesCookie, store.secret)\n : undefined;\n\n if (overrides && hasOwnProperty(overrides, definition.key)) {\n const value = overrides[definition.key];\n if (typeof value !== 'undefined') {\n reportValue(definition.key, value);\n store.usedFlags[definition.key] = Promise.resolve(value as JsonValue);\n return value;\n }\n }\n\n const valuePromise = decide(\n {\n headers: sealHeaders(store.event.request.headers),\n cookies: sealCookies(store.event.request.headers),\n },\n // @ts-expect-error not part of the type, but we supply it for convenience\n { event: store.event },\n );\n store.usedFlags[definition.key] = valuePromise as Promise<JsonValue>;\n\n const value = await valuePromise;\n reportValue(definition.key, value);\n return value;\n };\n\n flagImpl.key = definition.key;\n flagImpl.defaultValue = definition.defaultValue;\n flagImpl.origin = definition.origin;\n flagImpl.description = definition.description;\n flagImpl.options = definition.options;\n flagImpl.decide = decide;\n // flagImpl.identify = definition.identify;\n\n return flagImpl;\n}\n\nexport function getProviderData(\n flags: Record<string, Flag<JsonValue>>,\n): ApiData {\n const definitions = Object.values(flags).reduce<FlagDefinitionsType>(\n (acc, d) => {\n acc[d.key] = {\n options: normalizeOptions(d.options),\n origin: d.origin,\n description: d.description,\n };\n return acc;\n },\n {},\n );\n\n return { definitions, hints: [] };\n}\n\ninterface AsyncLocalContext {\n event: RequestEvent<Partial<Record<string, string>>, string | null>;\n secret: string;\n usedFlags: Record<string, Promise<JsonValue>>;\n}\n\nfunction createContext(\n event: RequestEvent<Partial<Record<string, string>>, string | null>,\n secret: string,\n): AsyncLocalContext {\n return {\n event,\n secret,\n usedFlags: {},\n };\n}\n\nconst flagStorage = new AsyncLocalStorage<AsyncLocalContext>();\n\n/**\n * Establishes context for flags, so they have access to the\n * request and cookie.\n *\n * Also registers evaluated flags, except for flags used only after `resolve` calls in other handlers.\n *\n * @example Usage example in src/hooks.server.ts\n *\n * ```ts\n * import { createHandle } from 'flags/sveltekit';\n * import { FLAGS_SECRET } from '$env/static/private';\n * import * as flags from '$lib/flags';\n *\n * export const handle = createHandle({ secret: FLAGS_SECRET, flags });\n * ```\n *\n * @example Usage example in src/hooks.server.ts with other handlers\n *\n * Note that when composing `createHandle` with `sequence` then `createHandle` should come first. Only handlers after it will be able to access feature flags.\n */\nexport function createHandle({\n secret,\n flags,\n}: {\n secret: string;\n flags?: Record<string, Flag<JsonValue>>;\n}): Handle {\n return function handle({ event, resolve }) {\n if (\n flags &&\n // avoid creating the URL object for every request by checking with includes() first\n event.request.url.includes('/.well-known/') &&\n new URL(event.request.url).pathname === '/.well-known/vercel/flags'\n ) {\n return handleWellKnownFlagsRoute(event, secret, flags);\n }\n\n const flagContext = createContext(event, secret);\n return flagStorage.run(flagContext, () =>\n resolve(event, {\n transformPageChunk: async ({ html }) => {\n const store = flagStorage.getStore();\n if (!store || Object.keys(store.usedFlags).length === 0) return html;\n\n // This is for reporting which flags were used when this page was generated,\n // so the value shows up in Vercel Toolbar, without the client ever being\n // aware of this feature flag.\n const encryptedFlagValues = await encrypt(\n await resolveObjectPromises(store.usedFlags),\n secret,\n );\n\n return html.replace(\n '</body>',\n `<script type=\"application/json\" data-flag-values>${safeJsonStringify(encryptedFlagValues)}</script></body>`,\n );\n },\n }),\n );\n };\n}\n\nasync function handleWellKnownFlagsRoute(\n event: RequestEvent<Partial<Record<string, string>>, string | null>,\n secret: string,\n flags: Record<string, Flag<JsonValue>>,\n) {\n const access = await verifyAccess(\n event.request.headers.get('Authorization'),\n secret,\n );\n if (!access) return new Response(null, { status: 401 });\n return Response.json(getProviderData(flags));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AACA,SAAS,yBAAyB;AAqBlC,SAAS,sBAAsB;AAE/B,SAAS,eACP,KACA,MAC+B;AAC/B,SAAO,IAAI,eAAe,IAAI;AAChC;AAEA,IAAM,aAAa,oBAAI,QAAkC;AACzD,IAAM,aAAa,oBAAI,QAAyC;AAEhE,SAAS,YAAY,SAAmC;AACtD,QAAM,SAAS,WAAW,IAAI,OAAO;AACrC,MAAI,WAAW;AAAW,WAAO;AAEjC,QAAM,SAAS,eAAe,KAAK,OAAO;AAC1C,aAAW,IAAI,SAAS,MAAM;AAC9B,SAAO;AACT;AAEA,SAAS,YAAY,SAA0C;AAC7D,QAAM,SAAS,WAAW,IAAI,OAAO;AACrC,MAAI,WAAW;AAAW,WAAO;AAEjC,QAAM,SAAS,sBAAsB,KAAK,IAAI,eAAe,OAAO,CAAC;AACrE,aAAW,IAAI,SAAS,MAAM;AAC9B,SAAO;AACT;AAaA,eAAe,sBAAyB,KAAiC;AAEvE,QAAM,UAAU,OAAO,QAAQ,GAAG;AAGlC,QAAM,kBAAkB,MAAM,QAAQ;AAAA,IACpC,QAAQ,IAAI,OAAO,CAAC,KAAK,OAAO,MAAM;AACpC,YAAM,QAAQ,MAAM;AACpB,aAAO,CAAC,KAAK,KAAK;AAAA,IACpB,CAAC;AAAA,EACH;AAGA,SAAO,OAAO,YAAY,eAAe;AAC3C;AAEA,SAAS,UACP,YACiC;AACjC,SAAO,SAAS,OAAO,QAAQ;AAC7B,QAAI,OAAO,WAAW,WAAW,YAAY;AA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;AAAA,UACF;AAEA,iBAAO,KAAK;AAAA,YACV;AAAA,YACA,oDAAoD,kBAAkB,mBAAmB,CAAC;AAAA,UAC5F;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,eAAe,0BACb,OACA,QACA,OACA;AACA,QAAM,SAAS,MAAM;AAAA,IACnB,MAAM,QAAQ,QAAQ,IAAI,eAAe;AAAA,IACzC;AAAA,EACF;AACA,MAAI,CAAC;AAAQ,WAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AACtD,SAAO,SAAS,KAAK,gBAAgB,KAAK,CAAC;AAC7C;","names":["flagImpl","valuePromise","value"]}
@@ -0,0 +1,237 @@
1
+ import { IncomingHttpHeaders } from 'http';
2
+ import { RequestCookies, ResponseCookies } from '@edge-runtime/cookies';
3
+
4
+ type ReadonlyHeaders = Headers & {
5
+ /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
6
+ append(...args: any[]): void;
7
+ /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
8
+ set(...args: any[]): void;
9
+ /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
10
+ delete(...args: any[]): void;
11
+ };
12
+ declare class HeadersAdapter extends Headers {
13
+ private readonly headers;
14
+ constructor(headers: IncomingHttpHeaders);
15
+ /**
16
+ * Seals a Headers instance to prevent modification by throwing an error when
17
+ * any mutating method is called.
18
+ */
19
+ static seal(headers: Headers): ReadonlyHeaders;
20
+ /**
21
+ * Merges a header value into a string. This stores multiple values as an
22
+ * array, so we need to merge them into a string.
23
+ *
24
+ * @param value a header value
25
+ * @returns a merged header value (a string)
26
+ */
27
+ private merge;
28
+ /**
29
+ * Creates a Headers instance from a plain object or a Headers instance.
30
+ *
31
+ * @param headers a plain object or a Headers instance
32
+ * @returns a headers instance
33
+ */
34
+ static from(headers: IncomingHttpHeaders | Headers): Headers;
35
+ append(name: string, value: string): void;
36
+ delete(name: string): void;
37
+ get(name: string): string | null;
38
+ has(name: string): boolean;
39
+ set(name: string, value: string): void;
40
+ forEach(callbackfn: (value: string, name: string, parent: Headers) => void, thisArg?: any): void;
41
+ entries(): HeadersIterator<[string, string]>;
42
+ keys(): HeadersIterator<string>;
43
+ values(): HeadersIterator<string>;
44
+ [Symbol.iterator](): HeadersIterator<[string, string]>;
45
+ }
46
+
47
+ type ReadonlyRequestCookies = Omit<RequestCookies, 'set' | 'clear' | 'delete'> & Pick<ResponseCookies, 'set' | 'delete'>;
48
+ declare class RequestCookiesAdapter {
49
+ static seal(cookies: RequestCookies): ReadonlyRequestCookies;
50
+ }
51
+
52
+ type FlagParamsType = {
53
+ headers: ReadonlyHeaders;
54
+ cookies: ReadonlyRequestCookies;
55
+ };
56
+ /**
57
+ * Data flag providers can return to integrate with the toolbar.
58
+ */
59
+ type ProviderData = {
60
+ definitions: FlagDefinitionsType;
61
+ hints: {
62
+ key: string;
63
+ text: string;
64
+ }[];
65
+ };
66
+ /**
67
+ * Describes the provider of a feature flag
68
+ */
69
+ type Origin = {
70
+ provider: 'vercel';
71
+ projectId: string;
72
+ } | {
73
+ provider: 'edge-config';
74
+ edgeConfigId: string;
75
+ edgeConfigItemKey?: string;
76
+ teamSlug: string;
77
+ } | Record<string, unknown>;
78
+ /**
79
+ * Data returned by the .well-known/vercel/flags API Route which the toolbar understands.
80
+ */
81
+ type ApiData = {
82
+ /**
83
+ * Metadata about your application's feature flags
84
+ */
85
+ definitions?: FlagDefinitionsType;
86
+ /**
87
+ * Hints show up in the toolbar. They are meant to be used in case loading
88
+ * data from your flag provider fails. For example when the provider fails to
89
+ * responed or the configuration is invalid due to a missing environment variable.
90
+ */
91
+ hints?: ProviderData['hints'];
92
+ /**
93
+ * Sets the encryption mode for the vercel-flag-overrides cookie
94
+ * - when set to "encrypted" the toolbar will store encrypted overrides
95
+ * - when set to "plaintext" the toolbar will store plaintext overrides
96
+ */
97
+ overrideEncryptionMode?: 'encrypted' | 'plaintext';
98
+ };
99
+ /**
100
+ * Represents a JSON stringifiable value.
101
+ *
102
+ * This is essentially just `any` to make it easy to work with, but we use a dedicated type to signal the intent.
103
+ */
104
+ type JsonValue = any;
105
+ interface FlagOptionType {
106
+ value: JsonValue;
107
+ label?: string;
108
+ }
109
+ interface FlagDefinitionType {
110
+ options?: FlagOptionType[];
111
+ /**
112
+ * The URL where the feature flag can be managed.
113
+ */
114
+ origin?: string | Origin;
115
+ description?: string;
116
+ /**
117
+ * When a feature flag is declared through `flag` or `declareFlag` instead
118
+ * of being loaded from an external source like a feature flag provider's SDK
119
+ * then this will be `true`.
120
+ */
121
+ declaredInCode?: boolean;
122
+ /**
123
+ * The defaultValue defined in code which will be used when the flag
124
+ * can not be loaded from the provider or throws an error.
125
+ */
126
+ defaultValue?: JsonValue;
127
+ /**
128
+ * The timestamp in milliseconds of when the flag was updated.
129
+ */
130
+ updatedAt?: number;
131
+ /**
132
+ * The timestamp in milliseconds of when the flag was created.
133
+ */
134
+ createdAt?: number;
135
+ }
136
+ /**
137
+ * Definitions of a feature flags.
138
+ *
139
+ * Definitions are data like the description, available options, or its origin.
140
+ */
141
+ type FlagDefinitionsType = Record<string, FlagDefinitionType>;
142
+ /**
143
+ * Values of feature flags.
144
+ *
145
+ * This record consists of key-value pairs of flag keys and the value they resolved to.
146
+ */
147
+ type FlagValuesType = Record<string, JsonValue>;
148
+ /**
149
+ * Overrides of feature flags.
150
+ *
151
+ * This record consists of key-value pairs of flag keys and the override to be used for them.
152
+ */
153
+ type FlagOverridesType = Record<string, JsonValue>;
154
+ type FlagOption<T> = {
155
+ value: T;
156
+ label?: string;
157
+ };
158
+ type GenerousOption<T> = boolean extends T ? boolean | FlagOption<T> : T extends string | number ? T | FlagOption<T> : FlagOption<T>;
159
+ type Decide<ValueType, EntitiesType> = (params: FlagParamsType & {
160
+ entities?: EntitiesType;
161
+ }) => Promise<ValueType> | ValueType;
162
+ type Identify<EntitiesType> = (params: FlagParamsType) => Promise<EntitiesType | undefined> | EntitiesType | undefined;
163
+ /** An adapter interface to use the Flags SDK with any flag provider */
164
+ interface Adapter<ValueType, EntitiesType> {
165
+ initialize?: () => Promise<void>;
166
+ identify?: Identify<EntitiesType>;
167
+ origin?: Origin | string | ((key: string) => Origin | string | undefined);
168
+ config?: {
169
+ reportValue?: boolean;
170
+ };
171
+ decide: (params: {
172
+ key: string;
173
+ entities?: EntitiesType;
174
+ headers: ReadonlyHeaders;
175
+ cookies: ReadonlyRequestCookies;
176
+ defaultValue?: ValueType;
177
+ }) => Promise<ValueType> | ValueType;
178
+ }
179
+ /**
180
+ * Definition when declaring a feature flag, as provided to `flag(declaration)`
181
+ */
182
+ type FlagDeclaration<ValueType, EntitiesType> = {
183
+ /**
184
+ * The key of the feature flag
185
+ */
186
+ key: string;
187
+ /**
188
+ * An optional defaultValue which will be used when the flag's `decide` function returns undefined or throws an error. Catches async errors too.
189
+ */
190
+ defaultValue?: ValueType;
191
+ /**
192
+ * A URL where this feature flag can be managed. Will show up in Vercel Toolbar.
193
+ */
194
+ origin?: string | Origin;
195
+ /**
196
+ * A description of this feature flag. Will show up in Vercel Toolbar.
197
+ */
198
+ description?: string;
199
+ /**
200
+ * An array containing available options.
201
+ *
202
+ * The returend value does not need to be declared in `options`, but it's recommended as all declared options show up in Vercel Toolbar.
203
+ *
204
+ * Value is required, but the label is optional.
205
+ * @example `[{ label: "Off", value: false }, { label: "On", value: true }]`
206
+ *
207
+ * Non-objects like strings can be passed using shorthands which will be used as values without labels.
208
+ * @example `["EUR", "USD"]`
209
+ */
210
+ options?: GenerousOption<ValueType>[];
211
+ /**
212
+ * Configuration options that can be passed to the flag.
213
+ */
214
+ config?: {
215
+ reportValue?: boolean;
216
+ };
217
+ /**
218
+ * Adapters can implement default behavior for flags.
219
+ *
220
+ * Explicitly provided values always override adapters.
221
+ */
222
+ /**
223
+ * This function is called when the feature flag is used (and no override is present) to return a value.
224
+ */
225
+ /**
226
+ * This function can establish entities which the `decide` function will be called with.
227
+ */
228
+ identify?: Identify<EntitiesType>;
229
+ } & ({
230
+ adapter: Adapter<ValueType, EntitiesType>;
231
+ decide?: Decide<ValueType, EntitiesType>;
232
+ } | {
233
+ adapter?: Adapter<ValueType, EntitiesType>;
234
+ decide: Decide<ValueType, EntitiesType>;
235
+ });
236
+
237
+ export { type Adapter as A, type Decide as D, type FlagOptionType as F, type GenerousOption as G, HeadersAdapter as H, type Identify as I, type JsonValue as J, type Origin as O, type ProviderData as P, type ReadonlyHeaders as R, type ApiData as a, type FlagDefinitionType as b, type FlagDefinitionsType as c, type FlagValuesType as d, type FlagOverridesType as e, type FlagDeclaration as f, type ReadonlyRequestCookies as g, RequestCookiesAdapter as h, type FlagOption as i };
@@ -0,0 +1,237 @@
1
+ import { IncomingHttpHeaders } from 'http';
2
+ import { RequestCookies, ResponseCookies } from '@edge-runtime/cookies';
3
+
4
+ type ReadonlyHeaders = Headers & {
5
+ /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
6
+ append(...args: any[]): void;
7
+ /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
8
+ set(...args: any[]): void;
9
+ /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
10
+ delete(...args: any[]): void;
11
+ };
12
+ declare class HeadersAdapter extends Headers {
13
+ private readonly headers;
14
+ constructor(headers: IncomingHttpHeaders);
15
+ /**
16
+ * Seals a Headers instance to prevent modification by throwing an error when
17
+ * any mutating method is called.
18
+ */
19
+ static seal(headers: Headers): ReadonlyHeaders;
20
+ /**
21
+ * Merges a header value into a string. This stores multiple values as an
22
+ * array, so we need to merge them into a string.
23
+ *
24
+ * @param value a header value
25
+ * @returns a merged header value (a string)
26
+ */
27
+ private merge;
28
+ /**
29
+ * Creates a Headers instance from a plain object or a Headers instance.
30
+ *
31
+ * @param headers a plain object or a Headers instance
32
+ * @returns a headers instance
33
+ */
34
+ static from(headers: IncomingHttpHeaders | Headers): Headers;
35
+ append(name: string, value: string): void;
36
+ delete(name: string): void;
37
+ get(name: string): string | null;
38
+ has(name: string): boolean;
39
+ set(name: string, value: string): void;
40
+ forEach(callbackfn: (value: string, name: string, parent: Headers) => void, thisArg?: any): void;
41
+ entries(): HeadersIterator<[string, string]>;
42
+ keys(): HeadersIterator<string>;
43
+ values(): HeadersIterator<string>;
44
+ [Symbol.iterator](): HeadersIterator<[string, string]>;
45
+ }
46
+
47
+ type ReadonlyRequestCookies = Omit<RequestCookies, 'set' | 'clear' | 'delete'> & Pick<ResponseCookies, 'set' | 'delete'>;
48
+ declare class RequestCookiesAdapter {
49
+ static seal(cookies: RequestCookies): ReadonlyRequestCookies;
50
+ }
51
+
52
+ type FlagParamsType = {
53
+ headers: ReadonlyHeaders;
54
+ cookies: ReadonlyRequestCookies;
55
+ };
56
+ /**
57
+ * Data flag providers can return to integrate with the toolbar.
58
+ */
59
+ type ProviderData = {
60
+ definitions: FlagDefinitionsType;
61
+ hints: {
62
+ key: string;
63
+ text: string;
64
+ }[];
65
+ };
66
+ /**
67
+ * Describes the provider of a feature flag
68
+ */
69
+ type Origin = {
70
+ provider: 'vercel';
71
+ projectId: string;
72
+ } | {
73
+ provider: 'edge-config';
74
+ edgeConfigId: string;
75
+ edgeConfigItemKey?: string;
76
+ teamSlug: string;
77
+ } | Record<string, unknown>;
78
+ /**
79
+ * Data returned by the .well-known/vercel/flags API Route which the toolbar understands.
80
+ */
81
+ type ApiData = {
82
+ /**
83
+ * Metadata about your application's feature flags
84
+ */
85
+ definitions?: FlagDefinitionsType;
86
+ /**
87
+ * Hints show up in the toolbar. They are meant to be used in case loading
88
+ * data from your flag provider fails. For example when the provider fails to
89
+ * responed or the configuration is invalid due to a missing environment variable.
90
+ */
91
+ hints?: ProviderData['hints'];
92
+ /**
93
+ * Sets the encryption mode for the vercel-flag-overrides cookie
94
+ * - when set to "encrypted" the toolbar will store encrypted overrides
95
+ * - when set to "plaintext" the toolbar will store plaintext overrides
96
+ */
97
+ overrideEncryptionMode?: 'encrypted' | 'plaintext';
98
+ };
99
+ /**
100
+ * Represents a JSON stringifiable value.
101
+ *
102
+ * This is essentially just `any` to make it easy to work with, but we use a dedicated type to signal the intent.
103
+ */
104
+ type JsonValue = any;
105
+ interface FlagOptionType {
106
+ value: JsonValue;
107
+ label?: string;
108
+ }
109
+ interface FlagDefinitionType {
110
+ options?: FlagOptionType[];
111
+ /**
112
+ * The URL where the feature flag can be managed.
113
+ */
114
+ origin?: string | Origin;
115
+ description?: string;
116
+ /**
117
+ * When a feature flag is declared through `flag` or `declareFlag` instead
118
+ * of being loaded from an external source like a feature flag provider's SDK
119
+ * then this will be `true`.
120
+ */
121
+ declaredInCode?: boolean;
122
+ /**
123
+ * The defaultValue defined in code which will be used when the flag
124
+ * can not be loaded from the provider or throws an error.
125
+ */
126
+ defaultValue?: JsonValue;
127
+ /**
128
+ * The timestamp in milliseconds of when the flag was updated.
129
+ */
130
+ updatedAt?: number;
131
+ /**
132
+ * The timestamp in milliseconds of when the flag was created.
133
+ */
134
+ createdAt?: number;
135
+ }
136
+ /**
137
+ * Definitions of a feature flags.
138
+ *
139
+ * Definitions are data like the description, available options, or its origin.
140
+ */
141
+ type FlagDefinitionsType = Record<string, FlagDefinitionType>;
142
+ /**
143
+ * Values of feature flags.
144
+ *
145
+ * This record consists of key-value pairs of flag keys and the value they resolved to.
146
+ */
147
+ type FlagValuesType = Record<string, JsonValue>;
148
+ /**
149
+ * Overrides of feature flags.
150
+ *
151
+ * This record consists of key-value pairs of flag keys and the override to be used for them.
152
+ */
153
+ type FlagOverridesType = Record<string, JsonValue>;
154
+ type FlagOption<T> = {
155
+ value: T;
156
+ label?: string;
157
+ };
158
+ type GenerousOption<T> = boolean extends T ? boolean | FlagOption<T> : T extends string | number ? T | FlagOption<T> : FlagOption<T>;
159
+ type Decide<ValueType, EntitiesType> = (params: FlagParamsType & {
160
+ entities?: EntitiesType;
161
+ }) => Promise<ValueType> | ValueType;
162
+ type Identify<EntitiesType> = (params: FlagParamsType) => Promise<EntitiesType | undefined> | EntitiesType | undefined;
163
+ /** An adapter interface to use the Flags SDK with any flag provider */
164
+ interface Adapter<ValueType, EntitiesType> {
165
+ initialize?: () => Promise<void>;
166
+ identify?: Identify<EntitiesType>;
167
+ origin?: Origin | string | ((key: string) => Origin | string | undefined);
168
+ config?: {
169
+ reportValue?: boolean;
170
+ };
171
+ decide: (params: {
172
+ key: string;
173
+ entities?: EntitiesType;
174
+ headers: ReadonlyHeaders;
175
+ cookies: ReadonlyRequestCookies;
176
+ defaultValue?: ValueType;
177
+ }) => Promise<ValueType> | ValueType;
178
+ }
179
+ /**
180
+ * Definition when declaring a feature flag, as provided to `flag(declaration)`
181
+ */
182
+ type FlagDeclaration<ValueType, EntitiesType> = {
183
+ /**
184
+ * The key of the feature flag
185
+ */
186
+ key: string;
187
+ /**
188
+ * An optional defaultValue which will be used when the flag's `decide` function returns undefined or throws an error. Catches async errors too.
189
+ */
190
+ defaultValue?: ValueType;
191
+ /**
192
+ * A URL where this feature flag can be managed. Will show up in Vercel Toolbar.
193
+ */
194
+ origin?: string | Origin;
195
+ /**
196
+ * A description of this feature flag. Will show up in Vercel Toolbar.
197
+ */
198
+ description?: string;
199
+ /**
200
+ * An array containing available options.
201
+ *
202
+ * The returend value does not need to be declared in `options`, but it's recommended as all declared options show up in Vercel Toolbar.
203
+ *
204
+ * Value is required, but the label is optional.
205
+ * @example `[{ label: "Off", value: false }, { label: "On", value: true }]`
206
+ *
207
+ * Non-objects like strings can be passed using shorthands which will be used as values without labels.
208
+ * @example `["EUR", "USD"]`
209
+ */
210
+ options?: GenerousOption<ValueType>[];
211
+ /**
212
+ * Configuration options that can be passed to the flag.
213
+ */
214
+ config?: {
215
+ reportValue?: boolean;
216
+ };
217
+ /**
218
+ * Adapters can implement default behavior for flags.
219
+ *
220
+ * Explicitly provided values always override adapters.
221
+ */
222
+ /**
223
+ * This function is called when the feature flag is used (and no override is present) to return a value.
224
+ */
225
+ /**
226
+ * This function can establish entities which the `decide` function will be called with.
227
+ */
228
+ identify?: Identify<EntitiesType>;
229
+ } & ({
230
+ adapter: Adapter<ValueType, EntitiesType>;
231
+ decide?: Decide<ValueType, EntitiesType>;
232
+ } | {
233
+ adapter?: Adapter<ValueType, EntitiesType>;
234
+ decide: Decide<ValueType, EntitiesType>;
235
+ });
236
+
237
+ export { type Adapter as A, type Decide as D, type FlagOptionType as F, type GenerousOption as G, HeadersAdapter as H, type Identify as I, type JsonValue as J, type Origin as O, type ProviderData as P, type ReadonlyHeaders as R, type ApiData as a, type FlagDefinitionType as b, type FlagDefinitionsType as c, type FlagValuesType as d, type FlagOverridesType as e, type FlagDeclaration as f, type ReadonlyRequestCookies as g, RequestCookiesAdapter as h, type FlagOption as i };