Skip to content
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
11 changes: 0 additions & 11 deletions packages/sdk/node-client/.eslintrc.cjs

This file was deleted.

97 changes: 97 additions & 0 deletions packages/sdk/node-client/__tests__/options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import type { NodeOptions } from '../src/NodeOptions';
import validateOptions, { filterToBaseOptions, ValidatedOptions } from '../src/options';
import { createMockLogger } from './testHelpers';

// A value no option validator should accept regardless of the field's expected type
const BOGUS_VALUE = Symbol('invalid-option-value');

// Exhaustive over keyof ValidatedOptions: adding a new node-specific option fails to compile
// here until a bogus case is added, which forces the wrong-type-warning test below to cover
// it.
const wrongTypedOptions: Record<keyof ValidatedOptions, unknown> = {
tlsParams: BOGUS_VALUE,
enableEventCompression: BOGUS_VALUE,
initialConnectionMode: BOGUS_VALUE,
plugins: BOGUS_VALUE,
localStoragePath: BOGUS_VALUE,
hash: BOGUS_VALUE,
};

const nodeOptionKeys = Object.keys(wrongTypedOptions) as (keyof ValidatedOptions)[];

let logger: ReturnType<typeof createMockLogger>;

beforeEach(() => {
logger = createMockLogger();
});

it('applies defaults when no node-specific options are provided', () => {
const out = validateOptions({}, logger);

expect(out.initialConnectionMode).toBe('streaming');
expect(out.plugins).toEqual([]);
expect(out.tlsParams).toBeUndefined();
expect(out.enableEventCompression).toBeUndefined();
expect(out.localStoragePath).toBeUndefined();
expect(out.hash).toBeUndefined();
expect(logger.warn).not.toHaveBeenCalled();
});

it('passes through valid node-specific options', () => {
const out = validateOptions(
{
initialConnectionMode: 'polling',
enableEventCompression: true,
localStoragePath: '/tmp/ld-cache',
hash: 'abc123',
},
logger,
);

expect(out.initialConnectionMode).toBe('polling');
expect(out.enableEventCompression).toBe(true);
expect(out.localStoragePath).toBe('/tmp/ld-cache');
expect(out.hash).toBe('abc123');
expect(logger.warn).not.toHaveBeenCalled();
});

it('warns and falls back to the default for an invalid initialConnectionMode', () => {
const out = validateOptions({ initialConnectionMode: 'STREAMING' as any }, logger);

expect(out.initialConnectionMode).toBe('streaming');
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('initialConnectionMode'));
});

it('warns when TLS certificate verification is disabled', () => {
validateOptions({ tlsParams: { rejectUnauthorized: false } }, logger);

expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('rejectUnauthorized'));
});

it('strips every node-specific option from the base options but keeps base options', () => {
const opts: NodeOptions = {
initialConnectionMode: 'polling',
plugins: [],
tlsParams: {},
enableEventCompression: true,
localStoragePath: '/tmp/ld-cache',
hash: 'abc123',
sendEvents: false,
};

const base = filterToBaseOptions(opts) as Record<string, unknown>;

nodeOptionKeys.forEach((key) => {
expect(base).not.toHaveProperty(key);
});
expect(base).toHaveProperty('sendEvents', false);
});

it('warns for every validated option when given a value of the wrong type', () => {
nodeOptionKeys.forEach((key) => {
const fieldLogger = createMockLogger();
validateOptions({ [key]: wrongTypedOptions[key] } as unknown as NodeOptions, fieldLogger);

expect(fieldLogger.warn).toHaveBeenCalledWith(expect.stringContaining(key));
});
});
1 change: 1 addition & 0 deletions packages/sdk/node-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"devDependencies": {
"@eslint/js": "^9.0.0",
"@types/jest": "^29.4.0",
"@types/node": "^25.9.1",
"eslint": "^9.0.0",
"eslint-import-resolver-typescript": "^4.0.0",
"eslint-plugin-import-x": "^4.0.0",
Expand Down
64 changes: 64 additions & 0 deletions packages/sdk/node-client/src/LDClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import type {
ConnectionMode,
LDClient as LDClientBase,
LDContext,
LDIdentifyOptions,
LDIdentifyResult,
LDStartOptions,
LDWaitForInitializationResult,
} from '@launchdarkly/js-client-sdk-common';

export type { LDStartOptions };

export interface LDClient extends Omit<LDClientBase, 'identify'> {
/**
* Identifies a context to LaunchDarkly and returns a promise which resolves to an object
* containing the result of the identify operation.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we need something this being for subsequent contexts and not the initial context for which you use start. (And then also updating others to have similar wording.)

*
* Unlike the server-side SDKs, the client-side Node.js SDK maintains a current context
* state, which is set when you call `identify()`.
*
* Changing the current context also causes all feature flag values to be reloaded. Until
* that has finished, calls to variation methods will still return flag values for the
* previous context. You can await the Promise to determine when the new flag values are
* available.
*
* Use {@link start} to set the initial context at startup.
*
* @param context The context to identify. @see {@link LDContext}
* @param identifyOptions Optional configuration. @see {@link LDIdentifyOptions}.
* @returns A promise which resolves to an object containing the result of the identify operation.
*/
identify(context: LDContext, identifyOptions?: LDIdentifyOptions): Promise<LDIdentifyResult>;

/**
* Starts the client and returns a promise that resolves to the initialization result.
*
* The promise will resolve to a {@link LDWaitForInitializationResult} object containing the
* status of the waitForInitialization operation.
*
* @param options Optional configuration. See {@link LDStartOptions}.
*/
start(options?: LDStartOptions): Promise<LDWaitForInitializationResult>;

/**

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we want more robust wording on this as well.

* Sets the data source connection mode.
*
* @remarks
* Switches between 'offline', 'streaming', and 'polling' at runtime without restarting
* the client. Use 'offline' to pause all LaunchDarkly network activity.
*
* @see {@link ConnectionMode}
*/
setConnectionMode(mode: ConnectionMode): Promise<void>;

/**
* Returns the current data source connection mode.
*/
getConnectionMode(): ConnectionMode;

/**
* Returns true if the client is in offline mode.
*/
isOffline(): boolean;
}
46 changes: 46 additions & 0 deletions packages/sdk/node-client/src/LDCommon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
export type {
LDIdentifyOptions,
AutoEnvAttributes,
BasicLogger,
BasicLoggerOptions,
EvaluationSeriesContext,
EvaluationSeriesData,
Hook,
HookMetadata,
IdentifySeriesContext,
IdentifySeriesData,
IdentifySeriesResult,
IdentifySeriesStatus,
LDContext,
LDContextCommon,
LDContextMeta,
LDContextStrict,
LDEvaluationDetail,
LDEvaluationDetailTyped,
LDEvaluationReason,
LDFlagSet,
LDFlagValue,
LDTimeoutError,
LDInspection,
LDLogger,
LDLogLevel,
LDMultiKindContext,
LDSingleKindContext,
TrackSeriesContext,
LDPluginBase,
LDPluginEnvironmentMetadata,
LDPluginSdkMetadata,
LDPluginApplicationMetadata,
LDPluginMetadata,
LDIdentifyResult,
LDIdentifySuccess,
LDIdentifyError,
LDIdentifyTimeout,
LDIdentifyShed,
LDDebugOverride,
LDWaitForInitializationOptions,
LDWaitForInitializationResult,
LDWaitForInitializationComplete,
LDWaitForInitializationFailed,
LDWaitForInitializationTimeout,
} from '@launchdarkly/js-client-sdk-common';
8 changes: 8 additions & 0 deletions packages/sdk/node-client/src/LDPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Hook, LDPluginBase } from '@launchdarkly/js-client-sdk-common';

import { LDClient } from './LDClient';

/**
* Interface for plugins to the LaunchDarkly SDK.
*/
export interface LDPlugin extends LDPluginBase<LDClient, Hook> {}
28 changes: 27 additions & 1 deletion packages/sdk/node-client/src/NodeOptions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { ConnectionMode, LDOptions as LDOptionsBase } from '@launchdarkly/js-client-sdk-common';

import type { LDPlugin } from './LDPlugin';

/**
* Additional parameters to pass to the Node HTTPS API for secure requests. These can include any
* of the TLS-related parameters supported by `https.request()`, such as `ca`, `cert`, and `key`.
Expand All @@ -20,7 +24,7 @@ export interface LDTLSOptions {
/**
* Configuration options for the Node client-side SDK.
*/
export interface NodeOptions {
export interface NodeOptions extends LDOptionsBase {
/**
* Additional parameters to pass to the Node HTTPS API for secure requests. These can include any
* of the TLS-related parameters supported by `https.request()`, such as `ca`, `cert`, and `key`.
Expand All @@ -42,4 +46,26 @@ export interface NodeOptions {
* Defaults to `<cwd>/ldclient-user-cache`.
*/
localStoragePath?: string;

/**
* Sets the mode to use for connections when the SDK is initialized.
*
* @remarks
* Possible values are offline, streaming, or polling. See {@link ConnectionMode} for more information.
*
* Defaults to streaming.
*/
initialConnectionMode?: ConnectionMode;

/**
* A list of plugins to be used with the SDK.
*/
plugins?: LDPlugin[];

/**
* The Secure Mode hash for the configured context.
*
* @see https://docs.launchdarkly.com/sdk/features/secure-mode
*/
hash?: string;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I always forget that we made node a web SDK.

}
40 changes: 40 additions & 0 deletions packages/sdk/node-client/src/basicLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { format } from 'util';

import {
BasicLogger,
BasicLoggerOptions,
LDLogger,
} from '@launchdarkly/js-client-sdk-common';

/**
* Provides a basic {@link LDLogger} implementation.
*
* Output is written to `console.log` using Node's `util.format` so multiple arguments and
* format specifiers (`%s`, `%d`, etc.) are formatted the way Node consumers expect.
*
* If you do not pass a logger via {@link LDOptions.logger}, the SDK falls back to
* a logger equivalent to `basicLogger({ level: 'info' })`.
*
* @example
* ```javascript
* const ldOptions = {
* logger: basicLogger({ level: 'warn' }),
* };
* ```
*/
export default function basicLogger(options: BasicLoggerOptions = {}): LDLogger {
return new BasicLogger({
...options,
destination: options.destination ?? {
// eslint-disable-next-line no-console
debug: console.debug,
// eslint-disable-next-line no-console
info: console.info,
// eslint-disable-next-line no-console
warn: console.warn,
// eslint-disable-next-line no-console
error: console.error,
},
formatter: options.formatter ?? format,
});
}
Loading
Loading