Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

throw on undefined unless defaultValue is defined #46

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/few-wombats-reply.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@vercel/flags': patch
---

- fix: Fall back to `defaultValue` when a feature flag returns `undefined`
- fix: Throw error when a flag resolves to `undefined` and no `defaultValue` is present
- fix: Export `Identify` and `Decide` types

The value `undefined` can not be serialized so feature flags should never resolve to `undefined`. Use `null` instead.
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { flag } from '@vercel/flags/next';

export const firstPrecomputedFlag = flag({
export const firstPrecomputedFlag = flag<boolean>({
key: 'first-precomputed-flag',
decide: () => Math.random() > 0.5,
});

export const secondPrecomputedFlag = flag({
export const secondPrecomputedFlag = flag<boolean>({
key: 'second-precomputed-flag',
decide: () => Date.now() % 2 === 0,
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { flag } from '@vercel/flags/next';

export const basicEdgeMiddlewareFlag = flag({
export const basicEdgeMiddlewareFlag = flag<boolean>({
key: 'basic-edge-middleware-flag',
decide({ cookies }) {
return cookies.get('basic-edge-middleware-flag')?.value === '1';
Expand Down
2 changes: 1 addition & 1 deletion examples/snippets/app/getting-started/overview/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { DemoFlag } from '@/components/demo-flag';
import { ReloadButton } from './reload-button';

// declare a feature flag
const randomFlag = flag({
const randomFlag = flag<boolean>({
key: 'random-flag',
decide() {
// this flag will be on for 50% of visitors
Expand Down
2 changes: 1 addition & 1 deletion examples/snippets/flags.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { flag } from '@vercel/flags/next';

export const exampleFlag = flag({
export const exampleFlag = flag<boolean>({
key: 'example-flag',
decide() {
return true;
Expand Down
2 changes: 1 addition & 1 deletion examples/snippets/lib/pages-router-precomputed/flags.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { flag } from '@vercel/flags/next';

export const exampleFlag = flag({
export const exampleFlag = flag<boolean>({
key: 'pages-router-precomputed-example-flag',
decide() {
return true;
Expand Down
5 changes: 3 additions & 2 deletions examples/summer-sale/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@ export const showFreeDeliveryBannerFlag = flag<boolean>({
],
});

export const countryFlag = flag({
export const countryFlag = flag<string>({
key: 'country',
defaultValue: 'no accept-lanugage header',
async decide({ headers }) {
return headers.get('accept-language') || 'no accept-lanugage header';
return headers.get('accept-language') ?? this.defaultValue!;
},
});

Expand Down
2 changes: 1 addition & 1 deletion packages/flags/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Create a file called flags.ts in your project and declare your first feature fla
// app/flags.tsx
import { flag } from '@vercel/flags/next';

export const exampleFlag = flag({
export const exampleFlag = flag<boolean>({
key: 'example-flag',
decide() {
return true;
Expand Down
2 changes: 2 additions & 0 deletions packages/flags/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export type {
FlagOverridesType,
FlagDeclaration,
GenerousOption,
Identify,
Decide,
} from './types';
export { safeJsonStringify } from './lib/safe-json-stringify';
export { encrypt, decrypt } from './lib/crypto';
Expand Down
181 changes: 164 additions & 17 deletions packages/flags/src/next/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { flag, precompute } from '.';
import { IncomingMessage } from 'node:http';
import { NextApiRequestCookies } from 'next/dist/server/api-utils';
import { Readable } from 'node:stream';
import { encrypt } from '..';
import { type Adapter, encrypt } from '..';

const mocks = vi.hoisted(() => {
return {
Expand Down Expand Up @@ -50,7 +50,7 @@ describe('flag on app router', () => {
it('allows declaring a flag', async () => {
mocks.headers.mockReturnValueOnce(new Headers());

const f = await flag({
const f = flag<boolean>({
key: 'first-flag',
decide: () => false,
});
Expand All @@ -62,7 +62,7 @@ describe('flag on app router', () => {
it('caches for the duration of a request', async () => {
let i = 0;
const decide = vi.fn(() => i++);
const f = await flag({ key: 'first-flag', decide });
const f = flag<number>({ key: 'first-flag', decide });

// first request using the flag twice
const headersOfFirstRequest = new Headers();
Expand Down Expand Up @@ -94,7 +94,7 @@ describe('flag on app router', () => {

const mockDecide = vi.fn(() => promise);

const f = await flag({
const f = flag<boolean>({
key: 'first-flag',
decide: mockDecide,
});
Expand All @@ -119,7 +119,7 @@ describe('flag on app router', () => {

it('respects overrides', async () => {
const decide = vi.fn(() => false);
const f = await flag({ key: 'first-flag', decide });
const f = flag<boolean>({ key: 'first-flag', decide });

// first request using the flag twice
const headersOfFirstRequest = new Headers();
Expand All @@ -139,7 +139,11 @@ describe('flag on app router', () => {

it('uses precomputed values', async () => {
const decide = vi.fn(() => true);
const f = flag({ key: 'first-flag', decide, options: [false, true] });
const f = flag<boolean>({
key: 'first-flag',
decide,
options: [false, true],
});
const flagGroup = [f];
const code = await precompute(flagGroup);
expect(decide).toHaveBeenCalledTimes(1);
Expand All @@ -149,7 +153,7 @@ describe('flag on app router', () => {

it('uses precomputed values even when options are inferred', async () => {
const decide = vi.fn(() => true);
const f = flag({ key: 'first-flag', decide });
const f = flag<boolean>({ key: 'first-flag', decide });
const flagGroup = [f];
const code = await precompute(flagGroup);
expect(decide).toHaveBeenCalledTimes(1);
Expand All @@ -166,7 +170,7 @@ describe('flag on app router', () => {
const mockDecide = vi.fn(() => promise);
const catchFn = vi.fn();

const f = await flag({
const f = flag<boolean>({
key: 'first-flag',
decide: mockDecide,
defaultValue: false,
Expand All @@ -185,6 +189,48 @@ describe('flag on app router', () => {
expect(catchFn).not.toHaveBeenCalled();
expect(mockDecide).toHaveBeenCalledTimes(1);
});

it('falls back to the defaultValue when a decide function returns undefined', async () => {
const syncFlag = flag<boolean>({
key: 'sync-flag',
// @ts-expect-error this is the case we are testing
decide: () => undefined,
defaultValue: true,
});

await expect(syncFlag()).resolves.toEqual(true);

const asyncFlag = flag<boolean>({
key: 'async-flag',
// @ts-expect-error this is the case we are testing
decide: async () => undefined,
defaultValue: true,
});

await expect(asyncFlag()).resolves.toEqual(true);
});

it('throws an error when the decide function returns undefined and no defaultValue is provided', async () => {
const syncFlag = flag<boolean>({
key: 'sync-flag',
// @ts-expect-error this is the case we are testing
decide: () => undefined,
});

await expect(syncFlag()).rejects.toThrow(
'@vercel/flags: Flag "sync-flag" must have a defaultValue or a decide function that returns a value',
);

const asyncFlag = flag<string>({
key: 'async-flag',
// @ts-expect-error this is the case we are testing
decide: async () => undefined,
});

await expect(asyncFlag()).rejects.toThrow(
'@vercel/flags: Flag "async-flag" must have a defaultValue or a decide function that returns a value',
);
});
});

describe('flag on pages router', () => {
Expand All @@ -196,7 +242,7 @@ describe('flag on pages router', () => {
it('allows declaring a flag', async () => {
mocks.headers.mockReturnValueOnce(new Headers());

const f = await flag({
const f = flag<boolean>({
key: 'first-flag',
decide: () => false,
});
Expand All @@ -214,7 +260,7 @@ describe('flag on pages router', () => {
it('caches for the duration of a request', async () => {
let i = 0;
const decide = vi.fn(() => i++);
const f = await flag({ key: 'first-flag', decide });
const f = flag<number>({ key: 'first-flag', decide });

const [firstRequest, socket1] = createRequest();
const [secondRequest, socket2] = createRequest();
Expand Down Expand Up @@ -246,7 +292,7 @@ describe('flag on pages router', () => {

const mockDecide = vi.fn(() => promise);

const f = await flag({
const f = flag<boolean>({
key: 'first-flag',
decide: mockDecide,
});
Expand All @@ -272,18 +318,69 @@ describe('flag on pages router', () => {
const mockDecide = vi.fn(() => {
throw new Error('custom error');
});
const f = await flag({
const f = flag<boolean>({
key: 'first-flag',
decide: mockDecide,
});

const [firstRequest, socket1] = createRequest();
expect(mockDecide).toHaveBeenCalledTimes(0);
await expect(() => f()).rejects.toThrow('custom error');
await expect(() => f(firstRequest)).rejects.toThrow('custom error');
expect(mockDecide).toHaveBeenCalledTimes(1);
socket1.destroy();
});

it('falls back to the defaultValue when a decide function returns undefined', async () => {
const [firstRequest, socket1] = createRequest();
const syncFlag = flag<boolean>({
key: 'sync-flag',
// @ts-expect-error this is the case we are testing
decide: () => undefined,
defaultValue: true,
});

await expect(syncFlag(firstRequest)).resolves.toEqual(true);

const asyncFlag = flag<boolean>({
key: 'async-flag',
// @ts-expect-error this is the case we are testing
decide: async () => undefined,
defaultValue: true,
});

await expect(asyncFlag(firstRequest)).resolves.toEqual(true);

socket1.destroy();
});

it('throws an error when the decide function returns undefined and no defaultValue is provided', async () => {
const [firstRequest, socket1] = createRequest();
const syncFlag = flag<boolean>({
key: 'sync-flag',
// @ts-expect-error this is the case we are testing
decide: () => undefined,
});

await expect(syncFlag(firstRequest)).rejects.toThrow(
'@vercel/flags: Flag "sync-flag" must have a defaultValue or a decide function that returns a value',
);

const asyncFlag = flag<string>({
key: 'async-flag',
// @ts-expect-error this is the case we are testing
decide: async () => undefined,
});

await expect(asyncFlag(firstRequest)).rejects.toThrow(
'@vercel/flags: Flag "async-flag" must have a defaultValue or a decide function that returns a value',
);

socket1.destroy();
});

it('respects overrides', async () => {
const decide = vi.fn(() => false);
const f = await flag({ key: 'first-flag', decide });
const f = flag<boolean>({ key: 'first-flag', decide });
const override = await encrypt({ 'first-flag': true });

const [firstRequest, socket1] = createRequest({
Expand All @@ -296,7 +393,11 @@ describe('flag on pages router', () => {

it('uses precomputed values', async () => {
const decide = vi.fn(() => true);
const f = flag({ key: 'first-flag', decide, options: [false, true] });
const f = flag<boolean>({
key: 'first-flag',
decide,
options: [false, true],
});
const flagGroup = [f];
const code = await precompute(flagGroup);
expect(decide).toHaveBeenCalledTimes(1);
Expand All @@ -313,7 +414,7 @@ describe('flag on pages router', () => {
const mockDecide = vi.fn(() => promise);
const catchFn = vi.fn();

const f = await flag({
const f = flag<boolean>({
key: 'first-flag',
decide: mockDecide,
defaultValue: false,
Expand Down Expand Up @@ -341,7 +442,7 @@ describe('dynamic io', () => {
(error as any).digest = 'DYNAMIC_SERVER_USAGE;dynamic usage error';
throw error;
});
const f = await flag({
const f = flag<boolean>({
key: 'first-flag',
decide: mockDecide,
defaultValue: false,
Expand All @@ -351,3 +452,49 @@ describe('dynamic io', () => {
expect(mockDecide).toHaveBeenCalledTimes(1);
});
});

describe('adapters', () => {
function createTestAdapter() {
return function testAdapter<ValueType, EntitiesType>(
value: ValueType,
): Adapter<ValueType, EntitiesType> {
return {
decide: () => value,
origin: (key) => `fake-origin#${key}`,
};
};
}

it("should use the adapter's decide function when provided", async () => {
const testAdapter = createTestAdapter();

mocks.headers.mockReturnValueOnce(new Headers());

const f = flag<number>({
key: 'adapter-flag',
adapter: testAdapter(5),
});

expect(f).toHaveProperty('key', 'adapter-flag');
await expect(f()).resolves.toEqual(5);
expect(f).toHaveProperty('origin', 'fake-origin#adapter-flag');
});

it("should throw when an adapter's decide function returns undefined", async () => {
const testAdapter = createTestAdapter();

mocks.headers.mockReturnValueOnce(new Headers());

const f = flag<boolean>({
key: 'adapter-flag',
// @ts-expect-error this is the case we are testing
adapter: testAdapter(undefined),
});

expect(f).toHaveProperty('key', 'adapter-flag');
await expect(f()).rejects.toThrow(
'@vercel/flags: Flag "adapter-flag" must have a defaultValue or a decide function that returns a value',
);
expect(f).toHaveProperty('origin', 'fake-origin#adapter-flag');
});
});
Loading
Loading