@ops-ai/toggly-fastify 0.1.3 → 0.3.0

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/dist/index.cjs CHANGED
@@ -66,12 +66,28 @@ async function extractIdentity(request, config) {
66
66
  return void 0;
67
67
  }
68
68
  async function extractContext(request, config) {
69
+ const headers = request.headers;
70
+ const headerRequest = (0, import_toggly_node_core.fromHttpRequest)(headers).request;
69
71
  if (config.getContext) {
70
- return config.getContext(request);
72
+ const custom = await config.getContext(request);
73
+ return {
74
+ ...custom,
75
+ // Field-level merge: custom wins; missing keys filled from headers
76
+ request: {
77
+ ...headerRequest,
78
+ ...custom.request
79
+ }
80
+ };
71
81
  }
72
82
  const identity = await extractIdentity(request, config);
83
+ const groups = config.getGroups ? await config.getGroups(request) : void 0;
84
+ const claims = config.getClaims ? await config.getClaims(request) : void 0;
85
+ const fromReq = (0, import_toggly_node_core.fromHttpRequest)(headers, { identity, groups, claims });
73
86
  return {
74
- identity,
87
+ identity: fromReq.identity,
88
+ groups: fromReq.groups,
89
+ claims: fromReq.claims,
90
+ request: fromReq.request,
75
91
  traits: {
76
92
  ip: request.ip,
77
93
  userAgent: request.headers["user-agent"],
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/plugin.ts"],"sourcesContent":["// Plugin\nexport {\n togglyPlugin,\n featureGate,\n featureRoutes,\n withFeature,\n featuresHandler,\n getFastifyToggly,\n closeFastifyToggly,\n} from './plugin.js'\n\n// Types\nexport type {\n TogglyFastifyConfig,\n TogglyRequestData,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Re-export core types for convenience\nexport type {\n TogglyClient,\n TogglyConfig,\n TogglyServerConfig,\n TogglyState,\n FeatureDefinitions,\n FeatureRequirement,\n EvaluationContext,\n Hook,\n HookMetadata,\n} from '@ops-ai/toggly-node-core'\n\n// Re-export core utilities\nexport {\n createTogglyClient,\n initToggly,\n getToggly,\n useToggly,\n closeToggly,\n createLoggingHook,\n createMemoryCache,\n createFileCache,\n} from '@ops-ai/toggly-node-core'\n","import type {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n FastifyPluginAsync,\n} from 'fastify'\n\n// Custom type for preHandler hooks (simpler than Fastify's complex generic type)\ntype PreHandlerHook = (\n request: FastifyRequest,\n reply: FastifyReply\n) => Promise<unknown>\nimport fp from 'fastify-plugin'\nimport {\n createTogglyClient,\n normalizeFeatureKeys,\n type TogglyClient,\n type EvaluationContext,\n} from '@ops-ai/toggly-node-core'\nimport type {\n TogglyFastifyConfig,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Module-level client singleton\nlet fastifyClient: TogglyClient | null = null\n\n/**\n * Get the Fastify Toggly client\n */\nexport function getFastifyToggly(): TogglyClient | null {\n return fastifyClient\n}\n\n/**\n * Get identity from request\n */\nasync function extractIdentity(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<string | undefined> {\n // Use custom extractor if provided\n if (config.getIdentity) {\n return config.getIdentity(request)\n }\n\n // Default: check header\n const headerIdentity = request.headers['x-toggly-identity']\n if (typeof headerIdentity === 'string') {\n return headerIdentity\n }\n\n return undefined\n}\n\n/**\n * Get evaluation context from request\n */\nasync function extractContext(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<EvaluationContext> {\n // Use custom extractor if provided\n if (config.getContext) {\n return config.getContext(request)\n }\n\n // Default: extract basic context\n const identity = await extractIdentity(request, config)\n\n return {\n identity,\n traits: {\n ip: request.ip,\n userAgent: request.headers['user-agent'],\n path: request.url,\n method: request.method,\n },\n }\n}\n\n/**\n * Toggly Fastify plugin\n *\n * This plugin:\n * 1. Initializes the Toggly client\n * 2. Attaches feature flag helpers to the request object\n * 3. Extracts identity and context from the request\n */\nconst togglyPluginAsync: FastifyPluginAsync<TogglyFastifyConfig> = async (\n fastify: FastifyInstance,\n config: TogglyFastifyConfig\n) => {\n // Initialize client\n if (!fastifyClient) {\n fastifyClient = createTogglyClient(config)\n await fastifyClient.init()\n }\n\n // Add hook to attach toggly to request\n fastify.addHook('preHandler', async (request: FastifyRequest) => {\n if (!fastifyClient) {\n throw new Error('Toggly client not initialized')\n }\n\n // Extract context from request\n const context = await extractContext(request, config)\n const identity = context.identity\n\n // Attach Toggly helpers to request\n request.toggly = {\n client: fastifyClient,\n features: fastifyClient.state.features,\n identity,\n context,\n isFeatureOn: (featureKey: string) => fastifyClient!.isFeatureOn(featureKey, context),\n isFeatureOff: (featureKey: string) => fastifyClient!.isFeatureOff(featureKey, context),\n evaluateFeatureGate: (featureKeys, requirement, negate) =>\n fastifyClient!.evaluateFeatureGate(featureKeys, requirement, negate, context),\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', async () => {\n closeFastifyToggly()\n })\n}\n\n/**\n * Toggly Fastify plugin with proper encapsulation\n */\nexport const togglyPlugin = fp(togglyPluginAsync, {\n name: '@ops-ai/toggly-fastify',\n fastify: '>=4.0.0',\n})\n\n/**\n * Create a feature gate preHandler hook\n *\n * Protects routes by checking if specified features are enabled\n */\nexport function featureGate(options: FeatureGateOptions): PreHandlerHook {\n const {\n featureKey,\n requirement = 'all',\n negate = false,\n onDisabled,\n redirectTo,\n redirectStatus = 302,\n } = options\n\n const featureKeys = normalizeFeatureKeys(featureKey)\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!request.toggly) {\n throw new Error('Toggly plugin must be registered before using featureGate')\n }\n\n const isEnabled = await request.toggly.evaluateFeatureGate(featureKeys, requirement, negate)\n\n if (isEnabled) {\n return // Continue to handler\n }\n\n // Feature is disabled\n if (redirectTo) {\n return reply.redirect(redirectTo, redirectStatus)\n }\n\n if (onDisabled) {\n await onDisabled(request)\n return\n }\n\n // Default: 404\n return reply.status(404).send({\n error: 'Not Found',\n message: 'The requested resource is not available',\n })\n }\n}\n\n/**\n * Create preHandler that applies feature gates based on route patterns\n */\nexport function featureRoutes(routes: FeatureRouteOptions[]): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n for (const route of routes) {\n // Check if route matches\n const pathMatches =\n typeof route.path === 'string'\n ? request.url === route.path || request.url.startsWith(route.path)\n : route.path.test(request.url)\n\n if (!pathMatches) {\n continue\n }\n\n // Check if method matches\n if (route.methods && !route.methods.includes(request.method.toUpperCase())) {\n continue\n }\n\n // Apply feature gate\n const gate = featureGate(route)\n return gate(request, reply)\n }\n\n // No matching route, continue\n return\n }\n}\n\n/**\n * Create a decorated route handler that checks features\n */\nexport function withFeature(\n featureKey: string | string[],\n options: Omit<FeatureGateOptions, 'featureKey'> = {}\n): PreHandlerHook {\n return featureGate({ featureKey, ...options })\n}\n\n/**\n * Get features route handler\n */\nexport async function featuresHandler(\n request: FastifyRequest,\n reply: FastifyReply\n): Promise<void> {\n if (!request.toggly) {\n return reply.status(500).send({\n error: 'Internal Server Error',\n message: 'Toggly plugin not configured',\n })\n }\n\n return reply.send({\n features: request.toggly.features,\n identity: request.toggly.identity,\n })\n}\n\n/**\n * Close the Fastify Toggly client\n */\nexport function closeFastifyToggly(): void {\n if (fastifyClient) {\n fastifyClient.close()\n fastifyClient = null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,4BAAe;AACf,8BAKO;AAQP,IAAI,gBAAqC;AAKlC,SAAS,mBAAwC;AACtD,SAAO;AACT;AAKA,eAAe,gBACb,SACA,QAC6B;AAE7B,MAAI,OAAO,aAAa;AACtB,WAAO,OAAO,YAAY,OAAO;AAAA,EACnC;AAGA,QAAM,iBAAiB,QAAQ,QAAQ,mBAAmB;AAC1D,MAAI,OAAO,mBAAmB,UAAU;AACtC,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKA,eAAe,eACb,SACA,QAC4B;AAE5B,MAAI,OAAO,YAAY;AACrB,WAAO,OAAO,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AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,qBAA2B;AACzC,MAAI,eAAe;AACjB,kBAAc,MAAM;AACpB,oBAAgB;AAAA,EAClB;AACF;;;AD3NA,IAAAC,2BASO;","names":["fp","import_toggly_node_core"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/plugin.ts"],"sourcesContent":["// Plugin\nexport {\n togglyPlugin,\n featureGate,\n featureRoutes,\n withFeature,\n featuresHandler,\n getFastifyToggly,\n closeFastifyToggly,\n} from './plugin.js'\n\n// Types\nexport type {\n TogglyFastifyConfig,\n TogglyRequestData,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Re-export core types for convenience\nexport type {\n TogglyClient,\n TogglyConfig,\n TogglyServerConfig,\n TogglyState,\n FeatureDefinitions,\n FeatureRequirement,\n EvaluationContext,\n Hook,\n HookMetadata,\n} from '@ops-ai/toggly-node-core'\n\n// Re-export core utilities\nexport {\n createTogglyClient,\n initToggly,\n getToggly,\n useToggly,\n closeToggly,\n createLoggingHook,\n createMemoryCache,\n createFileCache,\n} from '@ops-ai/toggly-node-core'\n","import type {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n FastifyPluginAsync,\n} from 'fastify'\n\n// Custom type for preHandler hooks (simpler than Fastify's complex generic type)\ntype PreHandlerHook = (\n request: FastifyRequest,\n reply: FastifyReply\n) => Promise<unknown>\nimport fp from 'fastify-plugin'\nimport {\n createTogglyClient,\n normalizeFeatureKeys,\n fromHttpRequest,\n type TogglyClient,\n type EvaluationContext,\n} from '@ops-ai/toggly-node-core'\nimport type {\n TogglyFastifyConfig,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Module-level client singleton\nlet fastifyClient: TogglyClient | null = null\n\n/**\n * Get the Fastify Toggly client\n */\nexport function getFastifyToggly(): TogglyClient | null {\n return fastifyClient\n}\n\n/**\n * Get identity from request\n */\nasync function extractIdentity(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<string | undefined> {\n // Use custom extractor if provided\n if (config.getIdentity) {\n return config.getIdentity(request)\n }\n\n // Default: check header\n const headerIdentity = request.headers['x-toggly-identity']\n if (typeof headerIdentity === 'string') {\n return headerIdentity\n }\n\n return undefined\n}\n\n/**\n * Get evaluation context from request\n */\nasync function extractContext(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<EvaluationContext> {\n const headers = request.headers as Record<string, string | string[] | undefined>\n const headerRequest = fromHttpRequest(headers).request\n\n // Custom full context: use returned fields, fill missing request from headers\n if (config.getContext) {\n const custom = await config.getContext(request)\n return {\n ...custom,\n // Field-level merge: custom wins; missing keys filled from headers\n request: {\n ...headerRequest,\n ...custom.request,\n },\n }\n }\n\n // Default: identity / groups / claims providers + segment request headers\n const identity = await extractIdentity(request, config)\n const groups = config.getGroups ? await config.getGroups(request) : undefined\n const claims = config.getClaims ? await config.getClaims(request) : undefined\n const fromReq = fromHttpRequest(headers, { identity, groups, claims })\n\n return {\n identity: fromReq.identity,\n groups: fromReq.groups,\n claims: fromReq.claims,\n request: fromReq.request,\n traits: {\n ip: request.ip,\n userAgent: request.headers['user-agent'],\n path: request.url,\n method: request.method,\n },\n }\n}\n\n/**\n * Toggly Fastify plugin\n *\n * This plugin:\n * 1. Initializes the Toggly client\n * 2. Attaches feature flag helpers to the request object\n * 3. Extracts identity and context from the request\n */\nconst togglyPluginAsync: FastifyPluginAsync<TogglyFastifyConfig> = async (\n fastify: FastifyInstance,\n config: TogglyFastifyConfig\n) => {\n // Initialize client\n if (!fastifyClient) {\n fastifyClient = createTogglyClient(config)\n await fastifyClient.init()\n }\n\n // Add hook to attach toggly to request\n fastify.addHook('preHandler', async (request: FastifyRequest) => {\n if (!fastifyClient) {\n throw new Error('Toggly client not initialized')\n }\n\n // Extract context from request\n const context = await extractContext(request, config)\n const identity = context.identity\n\n // Attach Toggly helpers to request\n request.toggly = {\n client: fastifyClient,\n features: fastifyClient.state.features,\n identity,\n context,\n isFeatureOn: (featureKey: string) => fastifyClient!.isFeatureOn(featureKey, context),\n isFeatureOff: (featureKey: string) => fastifyClient!.isFeatureOff(featureKey, context),\n evaluateFeatureGate: (featureKeys, requirement, negate) =>\n fastifyClient!.evaluateFeatureGate(featureKeys, requirement, negate, context),\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', async () => {\n closeFastifyToggly()\n })\n}\n\n/**\n * Toggly Fastify plugin with proper encapsulation\n */\nexport const togglyPlugin = fp(togglyPluginAsync, {\n name: '@ops-ai/toggly-fastify',\n fastify: '>=4.0.0',\n})\n\n/**\n * Create a feature gate preHandler hook\n *\n * Protects routes by checking if specified features are enabled\n */\nexport function featureGate(options: FeatureGateOptions): PreHandlerHook {\n const {\n featureKey,\n requirement = 'all',\n negate = false,\n onDisabled,\n redirectTo,\n redirectStatus = 302,\n } = options\n\n const featureKeys = normalizeFeatureKeys(featureKey)\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!request.toggly) {\n throw new Error('Toggly plugin must be registered before using featureGate')\n }\n\n const isEnabled = await request.toggly.evaluateFeatureGate(featureKeys, requirement, negate)\n\n if (isEnabled) {\n return // Continue to handler\n }\n\n // Feature is disabled\n if (redirectTo) {\n return reply.redirect(redirectTo, redirectStatus)\n }\n\n if (onDisabled) {\n await onDisabled(request)\n return\n }\n\n // Default: 404\n return reply.status(404).send({\n error: 'Not Found',\n message: 'The requested resource is not available',\n })\n }\n}\n\n/**\n * Create preHandler that applies feature gates based on route patterns\n */\nexport function featureRoutes(routes: FeatureRouteOptions[]): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n for (const route of routes) {\n // Check if route matches\n const pathMatches =\n typeof route.path === 'string'\n ? request.url === route.path || request.url.startsWith(route.path)\n : route.path.test(request.url)\n\n if (!pathMatches) {\n continue\n }\n\n // Check if method matches\n if (route.methods && !route.methods.includes(request.method.toUpperCase())) {\n continue\n }\n\n // Apply feature gate\n const gate = featureGate(route)\n return gate(request, reply)\n }\n\n // No matching route, continue\n return\n }\n}\n\n/**\n * Create a decorated route handler that checks features\n */\nexport function withFeature(\n featureKey: string | string[],\n options: Omit<FeatureGateOptions, 'featureKey'> = {}\n): PreHandlerHook {\n return featureGate({ featureKey, ...options })\n}\n\n/**\n * Get features route handler\n */\nexport async function featuresHandler(\n request: FastifyRequest,\n reply: FastifyReply\n): Promise<void> {\n if (!request.toggly) {\n return reply.status(500).send({\n error: 'Internal Server Error',\n message: 'Toggly plugin not configured',\n })\n }\n\n return reply.send({\n features: request.toggly.features,\n identity: request.toggly.identity,\n })\n}\n\n/**\n * Close the Fastify Toggly client\n */\nexport function closeFastifyToggly(): void {\n if (fastifyClient) {\n fastifyClient.close()\n fastifyClient = null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,4BAAe;AACf,8BAMO;AAQP,IAAI,gBAAqC;AAKlC,SAAS,mBAAwC;AACtD,SAAO;AACT;AAKA,eAAe,gBACb,SACA,QAC6B;AAE7B,MAAI,OAAO,aAAa;AACtB,WAAO,OAAO,YAAY,OAAO;AAAA,EACnC;AAGA,QAAM,iBAAiB,QAAQ,QAAQ,mBAAmB;AAC1D,MAAI,OAAO,mBAAmB,UAAU;AACtC,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKA,eAAe,eACb,SACA,QAC4B;AAC5B,QAAM,UAAU,QAAQ;AACxB,QAAM,oBAAgB,yCAAgB,OAAO,EAAE;AAG/C,MAAI,OAAO,YAAY;AACrB,UAAM,SAAS,MAAM,OAAO,WAAW,OAAO;AAC9C,WAAO;AAAA,MACL,GAAG;AAAA;AAAA,MAEH,SAAS;AAAA,QACP,GAAG;AAAA,QACH,GAAG,OAAO;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AAGA,QAAM,WAAW,MAAM,gBAAgB,SAAS,MAAM;AACtD,QAAM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Q;AACnB,WAAO,MAAM,OAAO,GAAG,EAAE,KAAK;AAAA,MAC5B,OAAO;AAAA,MACP,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO,MAAM,KAAK;AAAA,IAChB,UAAU,QAAQ,OAAO;AAAA,IACzB,UAAU,QAAQ,OAAO;AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,qBAA2B;AACzC,MAAI,eAAe;AACjB,kBAAc,MAAM;AACpB,oBAAgB;AAAA,EAClB;AACF;;;AD7OA,IAAAC,2BASO;","names":["fp","import_toggly_node_core"]}
package/dist/index.d.cts CHANGED
@@ -12,7 +12,17 @@ interface TogglyFastifyConfig extends TogglyServerConfig {
12
12
  */
13
13
  getIdentity?: (request: FastifyRequest) => string | undefined | Promise<string | undefined>;
14
14
  /**
15
- * Function to extract evaluation context from request
15
+ * Function to extract group memberships from request
16
+ */
17
+ getGroups?: (request: FastifyRequest) => string[] | undefined | Promise<string[] | undefined>;
18
+ /**
19
+ * Function to extract principal / JWT-style claims from request
20
+ */
21
+ getClaims?: (request: FastifyRequest) => Record<string, string> | undefined | Promise<Record<string, string> | undefined>;
22
+ /**
23
+ * Function to extract evaluation context from request.
24
+ * When provided, returned fields are used; missing `request` is still
25
+ * filled from HTTP headers via `fromHttpRequest`.
16
26
  */
17
27
  getContext?: (request: FastifyRequest) => EvaluationContext | Promise<EvaluationContext>;
18
28
  }
package/dist/index.d.ts CHANGED
@@ -12,7 +12,17 @@ interface TogglyFastifyConfig extends TogglyServerConfig {
12
12
  */
13
13
  getIdentity?: (request: FastifyRequest) => string | undefined | Promise<string | undefined>;
14
14
  /**
15
- * Function to extract evaluation context from request
15
+ * Function to extract group memberships from request
16
+ */
17
+ getGroups?: (request: FastifyRequest) => string[] | undefined | Promise<string[] | undefined>;
18
+ /**
19
+ * Function to extract principal / JWT-style claims from request
20
+ */
21
+ getClaims?: (request: FastifyRequest) => Record<string, string> | undefined | Promise<Record<string, string> | undefined>;
22
+ /**
23
+ * Function to extract evaluation context from request.
24
+ * When provided, returned fields are used; missing `request` is still
25
+ * filled from HTTP headers via `fromHttpRequest`.
16
26
  */
17
27
  getContext?: (request: FastifyRequest) => EvaluationContext | Promise<EvaluationContext>;
18
28
  }
package/dist/index.js CHANGED
@@ -2,7 +2,8 @@
2
2
  import fp from "fastify-plugin";
3
3
  import {
4
4
  createTogglyClient,
5
- normalizeFeatureKeys
5
+ normalizeFeatureKeys,
6
+ fromHttpRequest
6
7
  } from "@ops-ai/toggly-node-core";
7
8
  var fastifyClient = null;
8
9
  function getFastifyToggly() {
@@ -19,12 +20,28 @@ async function extractIdentity(request, config) {
19
20
  return void 0;
20
21
  }
21
22
  async function extractContext(request, config) {
23
+ const headers = request.headers;
24
+ const headerRequest = fromHttpRequest(headers).request;
22
25
  if (config.getContext) {
23
- return config.getContext(request);
26
+ const custom = await config.getContext(request);
27
+ return {
28
+ ...custom,
29
+ // Field-level merge: custom wins; missing keys filled from headers
30
+ request: {
31
+ ...headerRequest,
32
+ ...custom.request
33
+ }
34
+ };
24
35
  }
25
36
  const identity = await extractIdentity(request, config);
37
+ const groups = config.getGroups ? await config.getGroups(request) : void 0;
38
+ const claims = config.getClaims ? await config.getClaims(request) : void 0;
39
+ const fromReq = fromHttpRequest(headers, { identity, groups, claims });
26
40
  return {
27
- identity,
41
+ identity: fromReq.identity,
42
+ groups: fromReq.groups,
43
+ claims: fromReq.claims,
44
+ request: fromReq.request,
28
45
  traits: {
29
46
  ip: request.ip,
30
47
  userAgent: request.headers["user-agent"],
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/plugin.ts","../src/index.ts"],"sourcesContent":["import type {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n FastifyPluginAsync,\n} from 'fastify'\n\n// Custom type for preHandler hooks (simpler than Fastify's complex generic type)\ntype PreHandlerHook = (\n request: FastifyRequest,\n reply: FastifyReply\n) => Promise<unknown>\nimport fp from 'fastify-plugin'\nimport {\n createTogglyClient,\n normalizeFeatureKeys,\n type TogglyClient,\n type EvaluationContext,\n} from '@ops-ai/toggly-node-core'\nimport type {\n TogglyFastifyConfig,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Module-level client singleton\nlet fastifyClient: TogglyClient | null = null\n\n/**\n * Get the Fastify Toggly client\n */\nexport function getFastifyToggly(): TogglyClient | null {\n return fastifyClient\n}\n\n/**\n * Get identity from request\n */\nasync function extractIdentity(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<string | undefined> {\n // Use custom extractor if provided\n if (config.getIdentity) {\n return config.getIdentity(request)\n }\n\n // Default: check header\n const headerIdentity = request.headers['x-toggly-identity']\n if (typeof headerIdentity === 'string') {\n return headerIdentity\n }\n\n return undefined\n}\n\n/**\n * Get evaluation context from request\n */\nasync function extractContext(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<EvaluationContext> {\n // Use custom extractor if provided\n if (config.getContext) {\n return config.getContext(request)\n }\n\n // Default: extract basic context\n const identity = await extractIdentity(request, config)\n\n return {\n identity,\n traits: {\n ip: request.ip,\n userAgent: request.headers['user-agent'],\n path: request.url,\n method: request.method,\n },\n }\n}\n\n/**\n * Toggly Fastify plugin\n *\n * This plugin:\n * 1. Initializes the Toggly client\n * 2. Attaches feature flag helpers to the request object\n * 3. Extracts identity and context from the request\n */\nconst togglyPluginAsync: FastifyPluginAsync<TogglyFastifyConfig> = async (\n fastify: FastifyInstance,\n config: TogglyFastifyConfig\n) => {\n // Initialize client\n if (!fastifyClient) {\n fastifyClient = createTogglyClient(config)\n await fastifyClient.init()\n }\n\n // Add hook to attach toggly to request\n fastify.addHook('preHandler', async (request: FastifyRequest) => {\n if (!fastifyClient) {\n throw new Error('Toggly client not initialized')\n }\n\n // Extract context from request\n const context = await extractContext(request, config)\n const identity = context.identity\n\n // Attach Toggly helpers to request\n request.toggly = {\n client: fastifyClient,\n features: fastifyClient.state.features,\n identity,\n context,\n isFeatureOn: (featureKey: string) => fastifyClient!.isFeatureOn(featureKey, context),\n isFeatureOff: (featureKey: string) => fastifyClient!.isFeatureOff(featureKey, context),\n evaluateFeatureGate: (featureKeys, requirement, negate) =>\n fastifyClient!.evaluateFeatureGate(featureKeys, requirement, negate, context),\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', async () => {\n closeFastifyToggly()\n })\n}\n\n/**\n * Toggly Fastify plugin with proper encapsulation\n */\nexport const togglyPlugin = fp(togglyPluginAsync, {\n name: '@ops-ai/toggly-fastify',\n fastify: '>=4.0.0',\n})\n\n/**\n * Create a feature gate preHandler hook\n *\n * Protects routes by checking if specified features are enabled\n */\nexport function featureGate(options: FeatureGateOptions): PreHandlerHook {\n const {\n featureKey,\n requirement = 'all',\n negate = false,\n onDisabled,\n redirectTo,\n redirectStatus = 302,\n } = options\n\n const featureKeys = normalizeFeatureKeys(featureKey)\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!request.toggly) {\n throw new Error('Toggly plugin must be registered before using featureGate')\n }\n\n const isEnabled = await request.toggly.evaluateFeatureGate(featureKeys, requirement, negate)\n\n if (isEnabled) {\n return // Continue to handler\n }\n\n // Feature is disabled\n if (redirectTo) {\n return reply.redirect(redirectTo, redirectStatus)\n }\n\n if (onDisabled) {\n await onDisabled(request)\n return\n }\n\n // Default: 404\n return reply.status(404).send({\n error: 'Not Found',\n message: 'The requested resource is not available',\n })\n }\n}\n\n/**\n * Create preHandler that applies feature gates based on route patterns\n */\nexport function featureRoutes(routes: FeatureRouteOptions[]): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n for (const route of routes) {\n // Check if route matches\n const pathMatches =\n typeof route.path === 'string'\n ? request.url === route.path || request.url.startsWith(route.path)\n : route.path.test(request.url)\n\n if (!pathMatches) {\n continue\n }\n\n // Check if method matches\n if (route.methods && !route.methods.includes(request.method.toUpperCase())) {\n continue\n }\n\n // Apply feature gate\n const gate = featureGate(route)\n return gate(request, reply)\n }\n\n // No matching route, continue\n return\n }\n}\n\n/**\n * Create a decorated route handler that checks features\n */\nexport function withFeature(\n featureKey: string | string[],\n options: Omit<FeatureGateOptions, 'featureKey'> = {}\n): PreHandlerHook {\n return featureGate({ featureKey, ...options })\n}\n\n/**\n * Get features route handler\n */\nexport async function featuresHandler(\n request: FastifyRequest,\n reply: FastifyReply\n): Promise<void> {\n if (!request.toggly) {\n return reply.status(500).send({\n error: 'Internal Server Error',\n message: 'Toggly plugin not configured',\n })\n }\n\n return reply.send({\n features: request.toggly.features,\n identity: request.toggly.identity,\n })\n}\n\n/**\n * Close the Fastify Toggly client\n */\nexport function closeFastifyToggly(): void {\n if (fastifyClient) {\n fastifyClient.close()\n fastifyClient = null\n }\n}\n","// Plugin\nexport {\n togglyPlugin,\n featureGate,\n featureRoutes,\n withFeature,\n featuresHandler,\n getFastifyToggly,\n closeFastifyToggly,\n} from './plugin.js'\n\n// Types\nexport type {\n TogglyFastifyConfig,\n TogglyRequestData,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Re-export core types for convenience\nexport type {\n TogglyClient,\n TogglyConfig,\n TogglyServerConfig,\n TogglyState,\n FeatureDefinitions,\n FeatureRequirement,\n EvaluationContext,\n Hook,\n HookMetadata,\n} from '@ops-ai/toggly-node-core'\n\n// Re-export core utilities\nexport {\n createTogglyClient,\n initToggly,\n getToggly,\n useToggly,\n closeToggly,\n createLoggingHook,\n createMemoryCache,\n createFileCache,\n} from '@ops-ai/toggly-node-core'\n"],"mappings":";AAYA,OAAO,QAAQ;AACf;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAQP,IAAI,gBAAqC;AAKlC,SAAS,mBAAwC;AACtD,SAAO;AACT;AAKA,eAAe,gBACb,SACA,QAC6B;AAE7B,MAAI,OAAO,aAAa;AACtB,WAAO,OAAO,YAAY,OAAO;AAAA,EACnC;AAGA,QAAM,iBAAiB,QAAQ,QAAQ,mBAAmB;AAC1D,MAAI,OAAO,mBAAmB,UAAU;AACtC,WAAO;AAAA,EACT;AAEA,SAA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KAAK;AAAA,IAChB,UAAU,QAAQ,OAAO;AAAA,IACzB,UAAU,QAAQ,OAAO;AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,qBAA2B;AACzC,MAAI,eAAe;AACjB,kBAAc,MAAM;AACpB,oBAAgB;AAAA,EAClB;AACF;;;AC3NA;AAAA,EACE,sBAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["createTogglyClient"]}
1
+ {"version":3,"sources":["../src/plugin.ts","../src/index.ts"],"sourcesContent":["import type {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n FastifyPluginAsync,\n} from 'fastify'\n\n// Custom type for preHandler hooks (simpler than Fastify's complex generic type)\ntype PreHandlerHook = (\n request: FastifyRequest,\n reply: FastifyReply\n) => Promise<unknown>\nimport fp from 'fastify-plugin'\nimport {\n createTogglyClient,\n normalizeFeatureKeys,\n fromHttpRequest,\n type TogglyClient,\n type EvaluationContext,\n} from '@ops-ai/toggly-node-core'\nimport type {\n TogglyFastifyConfig,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Module-level client singleton\nlet fastifyClient: TogglyClient | null = null\n\n/**\n * Get the Fastify Toggly client\n */\nexport function getFastifyToggly(): TogglyClient | null {\n return fastifyClient\n}\n\n/**\n * Get identity from request\n */\nasync function extractIdentity(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<string | undefined> {\n // Use custom extractor if provided\n if (config.getIdentity) {\n return config.getIdentity(request)\n }\n\n // Default: check header\n const headerIdentity = request.headers['x-toggly-identity']\n if (typeof headerIdentity === 'string') {\n return headerIdentity\n }\n\n return undefined\n}\n\n/**\n * Get evaluation context from request\n */\nasync function extractContext(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<EvaluationContext> {\n const headers = request.headers as Record<string, string | string[] | undefined>\n const headerRequest = fromHttpRequest(headers).request\n\n // Custom full context: use returned fields, fill missing request from headers\n if (config.getContext) {\n const custom = await config.getContext(request)\n return {\n ...custom,\n // Field-level merge: custom wins; missing keys filled from headers\n request: {\n ...headerRequest,\n ...custom.request,\n },\n }\n }\n\n // Default: identity / groups / claims providers + segment request headers\n const identity = await extractIdentity(request, config)\n const groups = config.getGroups ? await config.getGroups(request) : undefined\n const claims = config.getClaims ? await config.getClaims(request) : undefined\n const fromReq = fromHttpRequest(headers, { identity, groups, claims })\n\n return {\n identity: fromReq.identity,\n groups: fromReq.groups,\n claims: fromReq.claims,\n request: fromReq.request,\n traits: {\n ip: request.ip,\n userAgent: request.headers['user-agent'],\n path: request.url,\n method: request.method,\n },\n }\n}\n\n/**\n * Toggly Fastify plugin\n *\n * This plugin:\n * 1. Initializes the Toggly client\n * 2. Attaches feature flag helpers to the request object\n * 3. Extracts identity and context from the request\n */\nconst togglyPluginAsync: FastifyPluginAsync<TogglyFastifyConfig> = async (\n fastify: FastifyInstance,\n config: TogglyFastifyConfig\n) => {\n // Initialize client\n if (!fastifyClient) {\n fastifyClient = createTogglyClient(config)\n await fastifyClient.init()\n }\n\n // Add hook to attach toggly to request\n fastify.addHook('preHandler', async (request: FastifyRequest) => {\n if (!fastifyClient) {\n throw new Error('Toggly client not initialized')\n }\n\n // Extract context from request\n const context = await extractContext(request, config)\n const identity = context.identity\n\n // Attach Toggly helpers to request\n request.toggly = {\n client: fastifyClient,\n features: fastifyClient.state.features,\n identity,\n context,\n isFeatureOn: (featureKey: string) => fastifyClient!.isFeatureOn(featureKey, context),\n isFeatureOff: (featureKey: string) => fastifyClient!.isFeatureOff(featureKey, context),\n evaluateFeatureGate: (featureKeys, requirement, negate) =>\n fastifyClient!.evaluateFeatureGate(featureKeys, requirement, negate, context),\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', async () => {\n closeFastifyToggly()\n })\n}\n\n/**\n * Toggly Fastify plugin with proper encapsulation\n */\nexport const togglyPlugin = fp(togglyPluginAsync, {\n name: '@ops-ai/toggly-fastify',\n fastify: '>=4.0.0',\n})\n\n/**\n * Create a feature gate preHandler hook\n *\n * Protects routes by checking if specified features are enabled\n */\nexport function featureGate(options: FeatureGateOptions): PreHandlerHook {\n const {\n featureKey,\n requirement = 'all',\n negate = false,\n onDisabled,\n redirectTo,\n redirectStatus = 302,\n } = options\n\n const featureKeys = normalizeFeatureKeys(featureKey)\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!request.toggly) {\n throw new Error('Toggly plugin must be registered before using featureGate')\n }\n\n const isEnabled = await request.toggly.evaluateFeatureGate(featureKeys, requirement, negate)\n\n if (isEnabled) {\n return // Continue to handler\n }\n\n // Feature is disabled\n if (redirectTo) {\n return reply.redirect(redirectTo, redirectStatus)\n }\n\n if (onDisabled) {\n await onDisabled(request)\n return\n }\n\n // Default: 404\n return reply.status(404).send({\n error: 'Not Found',\n message: 'The requested resource is not available',\n })\n }\n}\n\n/**\n * Create preHandler that applies feature gates based on route patterns\n */\nexport function featureRoutes(routes: FeatureRouteOptions[]): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n for (const route of routes) {\n // Check if route matches\n const pathMatches =\n typeof route.path === 'string'\n ? request.url === route.path || request.url.startsWith(route.path)\n : route.path.test(request.url)\n\n if (!pathMatches) {\n continue\n }\n\n // Check if method matches\n if (route.methods && !route.methods.includes(request.method.toUpperCase())) {\n continue\n }\n\n // Apply feature gate\n const gate = featureGate(route)\n return gate(request, reply)\n }\n\n // No matching route, continue\n return\n }\n}\n\n/**\n * Create a decorated route handler that checks features\n */\nexport function withFeature(\n featureKey: string | string[],\n options: Omit<FeatureGateOptions, 'featureKey'> = {}\n): PreHandlerHook {\n return featureGate({ featureKey, ...options })\n}\n\n/**\n * Get features route handler\n */\nexport async function featuresHandler(\n request: FastifyRequest,\n reply: FastifyReply\n): Promise<void> {\n if (!request.toggly) {\n return reply.status(500).send({\n error: 'Internal Server Error',\n message: 'Toggly plugin not configured',\n })\n }\n\n return reply.send({\n features: request.toggly.features,\n identity: request.toggly.identity,\n })\n}\n\n/**\n * Close the Fastify Toggly client\n */\nexport function closeFastifyToggly(): void {\n if (fastifyClient) {\n fastifyClient.close()\n fastifyClient = null\n }\n}\n","// Plugin\nexport {\n togglyPlugin,\n featureGate,\n featureRoutes,\n withFeature,\n featuresHandler,\n getFastifyToggly,\n closeFastifyToggly,\n} from './plugin.js'\n\n// Types\nexport type {\n TogglyFastifyConfig,\n TogglyRequestData,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Re-export core types for convenience\nexport type {\n TogglyClient,\n TogglyConfig,\n TogglyServerConfig,\n TogglyState,\n FeatureDefinitions,\n FeatureRequirement,\n EvaluationContext,\n Hook,\n HookMetadata,\n} from '@ops-ai/toggly-node-core'\n\n// Re-export core utilities\nexport {\n createTogglyClient,\n initToggly,\n getToggly,\n useToggly,\n closeToggly,\n createLoggingHook,\n createMemoryCache,\n createFileCache,\n} from '@ops-ai/toggly-node-core'\n"],"mappings":";AAYA,OAAO,QAAQ;AACf;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAQP,IAAI,gBAAqC;AAKlC,SAAS,mBAAwC;AACtD,SAAO;AACT;AAKA,eAAe,gBACb,SACA,QAC6B;AAE7B,MAAI,OAAO,aAAa;AACtB,WAAO,OAAO,YAAY,OAAO;AAAA,EACnC;AAGA,QAAM,iBAAiB,QAAQ,QAAQ,mBAAmB;AAC1D,MAAI,OAAO,mBAAmB,UAAU;AACtC,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKA,eAAe,eACb,SACA,QAC4B;AAC5B,QAAM,UAAU,QAAQ;AACxB,QAAM,gBAAgB,gBAAgB,OAAO,EAAE;AAG/C,MAAI,OAAO,YAAY;AACrB,UAAM,SAAS,MAAM,OAAO,WAAW,OAAO;AAC9C,WAAO;AAAA,MACL,GAAG;AAAA;AAAA,MAEH,SAAS;AAAA,QACP,GAAG;AAAA,QACH,GAAG,OAAO;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AAGA,QA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ACA,OACe;AACf,MAAI,CAAC,QAAQ,QAAQ;AACnB,WAAO,MAAM,OAAO,GAAG,EAAE,KAAK;AAAA,MAC5B,OAAO;AAAA,MACP,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO,MAAM,KAAK;AAAA,IAChB,UAAU,QAAQ,OAAO;AAAA,IACzB,UAAU,QAAQ,OAAO;AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,qBAA2B;AACzC,MAAI,eAAe;AACjB,kBAAc,MAAM;AACpB,oBAAgB;AAAA,EAClB;AACF;;;AC7OA;AAAA,EACE,sBAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["createTogglyClient"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ops-ai/toggly-fastify",
3
- "version": "0.1.3",
3
+ "version": "0.3.0",
4
4
  "description": "Toggly feature flags Fastify plugin",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "fastify-plugin": "^5.0.1",
55
- "@ops-ai/toggly-node-core": "0.4.2"
55
+ "@ops-ai/toggly-node-core": "^0.7.0"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@types/node": "^22.15.30",