Skip to content

Commit dbf0f64

Browse files
committed
Rewrite patching with fill()
1 parent 8c07c27 commit dbf0f64

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

packages/browser/src/integrations/featureFlags/unleash/integration.ts

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Client, Event, EventHint, IntegrationFn } from '@sentry/core';
22

3-
import { defineIntegration } from '@sentry/core';
3+
import { defineIntegration, fill, logger } from '@sentry/core';
44
import { copyFlagsFromScopeToEvent, insertFlagToScope } from '../../../utils/featureFlags';
55
import type { UnleashClient, UnleashClientClass } from './types';
66

@@ -39,21 +39,28 @@ export const unleashIntegration = defineIntegration((unleashClientClass: Unleash
3939

4040
setupOnce() {
4141
const unleashClientPrototype = unleashClientClass.prototype as UnleashClient;
42-
43-
const sentryIsEnabled = {
44-
apply: (
45-
target: (this: UnleashClient, toggleName: string) => boolean,
46-
thisArg: UnleashClient,
47-
args: [toggleName: string],
48-
) => {
49-
const result = Reflect.apply(target, thisArg, args);
50-
insertFlagToScope(args[0], result);
51-
return result;
52-
},
53-
};
54-
// eslint-disable-next-line @typescript-eslint/unbound-method
55-
const originalIsEnabled = unleashClientPrototype.isEnabled;
56-
unleashClientPrototype.isEnabled = new Proxy(originalIsEnabled, sentryIsEnabled);
42+
fill(unleashClientPrototype, 'isEnabled', _wrappedIsEnabled);
5743
},
5844
};
5945
}) satisfies IntegrationFn;
46+
47+
/**
48+
* Wraps the UnleashClient.isEnabled method to capture feature flag evaluations. Its only side effect is writing to Sentry scope.
49+
*
50+
* @param original - The original method.
51+
* @returns Wrapped method. Results should match the original.
52+
*/
53+
function _wrappedIsEnabled(original: (this: UnleashClient, ...args: unknown[]) => unknown): (this: UnleashClient, ...args: unknown[]) => unknown {
54+
return function (this: UnleashClient, ...args: unknown[]): unknown {
55+
const toggleName = args[0];
56+
const result = original.apply(this, args);
57+
58+
if (typeof toggleName === 'string' && typeof result === 'boolean') {
59+
insertFlagToScope(toggleName, result);
60+
} else {
61+
// TODO: test this branch
62+
logger.error(`[Feature Flags] UnleashClient.isEnabled does not match expected signature. arg0: ${toggleName} (${typeof toggleName}), result: ${result} (${typeof result})`);
63+
}
64+
return result;
65+
};
66+
}

0 commit comments

Comments
 (0)