@ops-ai/toggly-fastify 0.3.1 → 0.5.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/README.md CHANGED
@@ -11,16 +11,15 @@ npm install @ops-ai/toggly-fastify
11
11
  ## Compatibility
12
12
 
13
13
  The adapter retains its `fastify` peer range of `^4.0.0 || ^5.0.0` and its
14
- Node.js package floor of 18. Fastify 4.29.1 is tested with Node 18.20.8.
15
- Fastify 5 requires Node 20 or newer; Fastify 5.12.4 is tested with Node
16
- 20.19.6. Use a Fastify-5-compatible Node runtime even though the adapter
17
- itself can run on Node 18.
14
+ Node.js package floor of 22. Upstream still publishes Fastify 4 (`four`
15
+ dist-tag, currently 4.29.1) and Fastify 5 (`latest`, currently 5.12.7); CI
16
+ proves both majors on Node 22, 24, and 26.
18
17
 
19
18
  The compatibility harness packs the release artifact, resolves its core
20
19
  dependency from npm, type-checks its public declarations, exercises ESM and
21
20
  CommonJS exports, and starts real HTTP listeners. To provide exact Node
22
- binaries in a local matrix, set `TOGGLY_FASTIFY_NODE18` and
23
- `TOGGLY_FASTIFY_NODE20` before `pnpm test:hosts`.
21
+ binaries in a local matrix, set `TOGGLY_FASTIFY_NODE_FASTIFY4` and
22
+ `TOGGLY_FASTIFY_NODE_FASTIFY5` before `pnpm test:hosts`.
24
23
 
25
24
  ## Documentation
26
25
 
package/dist/index.cjs CHANGED
@@ -114,10 +114,16 @@ var togglyPluginAsync = async (fastify, config) => {
114
114
  context,
115
115
  isFeatureOn: (featureKey) => fastifyClient.isFeatureOn(featureKey, context),
116
116
  isFeatureOff: (featureKey) => fastifyClient.isFeatureOff(featureKey, context),
117
- evaluateFeatureGate: (featureKeys, requirement, negate) => fastifyClient.evaluateFeatureGate(featureKeys, requirement, negate, context)
117
+ evaluateFeatureGate: (featureKeys, requirement, negate) => fastifyClient.evaluateFeatureGate(featureKeys, requirement, negate, context),
118
+ getVariant(featureKey) {
119
+ return fastifyClient.getVariant(featureKey, context);
120
+ },
121
+ getVariantValue(featureKey) {
122
+ return fastifyClient.getVariantValue(featureKey, context);
123
+ }
118
124
  };
119
125
  });
120
- fastify.addHook("onClose", async () => {
126
+ fastify.addHook("onClose", () => {
121
127
  closeFastifyToggly();
122
128
  });
123
129
  };
@@ -169,7 +175,7 @@ function featureRoutes(routes) {
169
175
  const gate = featureGate(route);
170
176
  return gate(request, reply);
171
177
  }
172
- return;
178
+ return void 0;
173
179
  };
174
180
  }
175
181
  function withFeature(featureKey, options = {}) {
@@ -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 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,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AGA;AAAA,EACF;AACF;AAKO,SAAS,YACd,YACA,UAAkD,CAAC,GACnC;AAChB,SAAO,YAAY,EAAE,YAAY,GAAG,QAAQ,CAAC;AAC/C;AAKA,eAAsB,gBACpB,SACA,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;;;AD7OA,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 VariantResult,\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 getVariant(featureKey: string) {\n return fastifyClient!.getVariant(featureKey, context)\n },\n getVariantValue(featureKey: string) {\n return fastifyClient!.getVariantValue(featureKey, context)\n },\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', () => {\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 undefined\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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X,CAAC;AAAA,EACH;AACF;AAKO,SAAS,cAAc,QAA+C;AAC3E,SAAO,OAAO,SAAyB,UAAwB;AAC7D,eAAW,SAAS,QAAQ;AAE1B,YAAM,cACJ,OAAO,MAAM,SAAS,WAClB,QAAQ,QAAQ,MAAM,QAAQ,QAAQ,IAAI,WAAW,MAAM,IAAI,IAC/D,MAAM,KAAK,KAAK,QAAQ,GAAG;AAEjC,UAAI,CAAC,aAAa;AAChB;AAAA,MACF;AAGA,UAAI,MAAM,WAAW,CAAC,MAAM,QAAQ,SAAS,QAAQ,OAAO,YAAY,CAAC,GAAG;AAC1E;AAAA,MACF;AAGA,YAAM,OAAO,YAAY,KAAK;AAC9B,aAAO,KAAK,SAAS,KAAK;AAAA,IAC5B;AAGA,WAAO;AAAA,EACT;AACF;AAKO,SAAS,YACd,YACA,UAAkD,CAAC,GACnC;AAChB,SAAO,YAAY,EAAE,YAAY,GAAG,QAAQ,CAAC;AAC/C;AAKA,eAAsB,gBACpB,SACA,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;;;ADlPA,IAAAC,2BASO;","names":["fp","import_toggly_node_core"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { FastifyRequest, FastifyReply, FastifyPluginAsync } from 'fastify';
2
- import { TogglyClient, FeatureDefinitions, EvaluationContext, FeatureRequirement, TogglyServerConfig } from '@ops-ai/toggly-node-core';
3
- export { EvaluationContext, FeatureDefinitions, FeatureRequirement, Hook, HookMetadata, TogglyClient, TogglyConfig, TogglyServerConfig, TogglyState, closeToggly, createFileCache, createLoggingHook, createMemoryCache, createTogglyClient, getToggly, initToggly, useToggly } from '@ops-ai/toggly-node-core';
2
+ import { TogglyClient, FeatureDefinitions, EvaluationContext, FeatureRequirement, VariantResult, TogglyServerConfig } from '@ops-ai/toggly-node-core';
3
+ export { EvaluationContext, FeatureDefinitions, FeatureRequirement, Hook, HookMetadata, TogglyClient, TogglyConfig, TogglyServerConfig, TogglyState, VariantResult, closeToggly, createFileCache, createLoggingHook, createMemoryCache, createTogglyClient, getToggly, initToggly, useToggly } from '@ops-ai/toggly-node-core';
4
4
 
5
5
  /**
6
6
  * Fastify-specific configuration
@@ -37,6 +37,10 @@ interface TogglyRequestData {
37
37
  isFeatureOn: (featureKey: string) => Promise<boolean>;
38
38
  isFeatureOff: (featureKey: string) => Promise<boolean>;
39
39
  evaluateFeatureGate: (featureKeys: string[], requirement?: FeatureRequirement, negate?: boolean) => Promise<boolean>;
40
+ /** Fastify: catalog-local variant via the request-scoped EvaluationContext. */
41
+ getVariant(featureKey: string): Promise<VariantResult | null>;
42
+ /** Fastify: assigned variant configurationValue, or null. */
43
+ getVariantValue(featureKey: string): Promise<unknown>;
40
44
  }
41
45
  /**
42
46
  * Feature gate options for protecting routes
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { FastifyRequest, FastifyReply, FastifyPluginAsync } from 'fastify';
2
- import { TogglyClient, FeatureDefinitions, EvaluationContext, FeatureRequirement, TogglyServerConfig } from '@ops-ai/toggly-node-core';
3
- export { EvaluationContext, FeatureDefinitions, FeatureRequirement, Hook, HookMetadata, TogglyClient, TogglyConfig, TogglyServerConfig, TogglyState, closeToggly, createFileCache, createLoggingHook, createMemoryCache, createTogglyClient, getToggly, initToggly, useToggly } from '@ops-ai/toggly-node-core';
2
+ import { TogglyClient, FeatureDefinitions, EvaluationContext, FeatureRequirement, VariantResult, TogglyServerConfig } from '@ops-ai/toggly-node-core';
3
+ export { EvaluationContext, FeatureDefinitions, FeatureRequirement, Hook, HookMetadata, TogglyClient, TogglyConfig, TogglyServerConfig, TogglyState, VariantResult, closeToggly, createFileCache, createLoggingHook, createMemoryCache, createTogglyClient, getToggly, initToggly, useToggly } from '@ops-ai/toggly-node-core';
4
4
 
5
5
  /**
6
6
  * Fastify-specific configuration
@@ -37,6 +37,10 @@ interface TogglyRequestData {
37
37
  isFeatureOn: (featureKey: string) => Promise<boolean>;
38
38
  isFeatureOff: (featureKey: string) => Promise<boolean>;
39
39
  evaluateFeatureGate: (featureKeys: string[], requirement?: FeatureRequirement, negate?: boolean) => Promise<boolean>;
40
+ /** Fastify: catalog-local variant via the request-scoped EvaluationContext. */
41
+ getVariant(featureKey: string): Promise<VariantResult | null>;
42
+ /** Fastify: assigned variant configurationValue, or null. */
43
+ getVariantValue(featureKey: string): Promise<unknown>;
40
44
  }
41
45
  /**
42
46
  * Feature gate options for protecting routes
package/dist/index.js CHANGED
@@ -68,10 +68,16 @@ var togglyPluginAsync = async (fastify, config) => {
68
68
  context,
69
69
  isFeatureOn: (featureKey) => fastifyClient.isFeatureOn(featureKey, context),
70
70
  isFeatureOff: (featureKey) => fastifyClient.isFeatureOff(featureKey, context),
71
- evaluateFeatureGate: (featureKeys, requirement, negate) => fastifyClient.evaluateFeatureGate(featureKeys, requirement, negate, context)
71
+ evaluateFeatureGate: (featureKeys, requirement, negate) => fastifyClient.evaluateFeatureGate(featureKeys, requirement, negate, context),
72
+ getVariant(featureKey) {
73
+ return fastifyClient.getVariant(featureKey, context);
74
+ },
75
+ getVariantValue(featureKey) {
76
+ return fastifyClient.getVariantValue(featureKey, context);
77
+ }
72
78
  };
73
79
  });
74
- fastify.addHook("onClose", async () => {
80
+ fastify.addHook("onClose", () => {
75
81
  closeFastifyToggly();
76
82
  });
77
83
  };
@@ -123,7 +129,7 @@ function featureRoutes(routes) {
123
129
  const gate = featureGate(route);
124
130
  return gate(request, reply);
125
131
  }
126
- return;
132
+ return void 0;
127
133
  };
128
134
  }
129
135
  function withFeature(featureKey, options = {}) {
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 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,QAAM,WAAW,MAAM,gBAAgB,SAAS,MAAM;AACtD,QAAM,SAAS,OAAO,YAAY,MAAM,OAAO,UAAU,OAAO,IAAI;AACpE,QAAM,SAAS,OAAO,YAAY,MAAM,OAAO,UAAU,OAAO,IAAI;AACpE,QAAM,UAAU,gBAAgB,SAAS,EAAE,UAAU,QAAQ,OAAO,CAAC;AAErE,SAAO;AAAA,IACL,UAAU,Q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;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"]}
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 getVariant(featureKey: string) {\n return fastifyClient!.getVariant(featureKey, context)\n },\n getVariantValue(featureKey: string) {\n return fastifyClient!.getVariantValue(featureKey, context)\n },\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', () => {\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 undefined\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 VariantResult,\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;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AC9B,aAAO,KAAK,SAAS,KAAK;AAAA,IAC5B;AAGA,WAAO;AAAA,EACT;AACF;AAKO,SAAS,YACd,YACA,UAAkD,CAAC,GACnC;AAChB,SAAO,YAAY,EAAE,YAAY,GAAG,QAAQ,CAAC;AAC/C;AAKA,eAAsB,gBACpB,SACA,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;;;AClPA;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.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "Toggly feature flags Fastify plugin",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -45,26 +45,26 @@
45
45
  "url": "https://github.com/ops-ai/Toggly.FeatureManagement/issues"
46
46
  },
47
47
  "engines": {
48
- "node": ">=18.0.0"
48
+ "node": ">=22.0.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "fastify": "^4.0.0 || ^5.0.0"
52
52
  },
53
53
  "dependencies": {
54
- "fastify-plugin": "^5.0.1",
55
- "@ops-ai/toggly-node-core": "^0.9.1"
54
+ "fastify-plugin": "^5.1.0",
55
+ "@ops-ai/toggly-node-core": "^0.14.0"
56
56
  },
57
57
  "devDependencies": {
58
- "@eslint/js": "^9.39.2",
59
- "@types/node": "^22.15.30",
60
- "@vitest/coverage-v8": "^3.2.4",
61
- "eslint": "^9.28.0",
62
- "fastify": "^5.4.0",
58
+ "@eslint/js": "^9.39.5",
59
+ "@types/node": "^22.20.5",
60
+ "@vitest/coverage-v8": "^3.2.7",
61
+ "eslint": "^9.39.5",
62
+ "fastify": "^5.12.7",
63
63
  "globals": "^15.15.0",
64
- "tsup": "^8.5.0",
65
- "typescript": "^5.8.3",
66
- "typescript-eslint": "^8.70.0",
67
- "vitest": "^3.2.4"
64
+ "tsup": "^8.5.1",
65
+ "typescript": "^5.9.3",
66
+ "typescript-eslint": "^8.72.1",
67
+ "vitest": "^3.2.7"
68
68
  },
69
69
  "publishConfig": {
70
70
  "access": "public"