@optimizely-opal/opal-tool-ocp-sdk 0.0.0-beta.1 → 0.0.0-beta.10
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 +106 -51
- package/dist/auth/TokenVerifier.d.ts +31 -0
- package/dist/auth/TokenVerifier.d.ts.map +1 -0
- package/dist/auth/TokenVerifier.js +127 -0
- package/dist/auth/TokenVerifier.js.map +1 -0
- package/dist/auth/TokenVerifier.test.d.ts +2 -0
- package/dist/auth/TokenVerifier.test.d.ts.map +1 -0
- package/dist/auth/TokenVerifier.test.js +114 -0
- package/dist/auth/TokenVerifier.test.js.map +1 -0
- package/dist/decorator/Decorator.d.ts +4 -2
- package/dist/decorator/Decorator.d.ts.map +1 -1
- package/dist/decorator/Decorator.js +26 -4
- package/dist/decorator/Decorator.js.map +1 -1
- package/dist/decorator/Decorator.test.js +110 -0
- package/dist/decorator/Decorator.test.js.map +1 -1
- package/dist/function/ToolFunction.d.ts +14 -1
- package/dist/function/ToolFunction.d.ts.map +1 -1
- package/dist/function/ToolFunction.js +59 -3
- package/dist/function/ToolFunction.js.map +1 -1
- package/dist/function/ToolFunction.test.js +229 -104
- package/dist/function/ToolFunction.test.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/service/Service.d.ts +14 -13
- package/dist/service/Service.d.ts.map +1 -1
- package/dist/service/Service.js +25 -19
- package/dist/service/Service.js.map +1 -1
- package/dist/service/Service.test.js +122 -36
- package/dist/service/Service.test.js.map +1 -1
- package/dist/types/Models.d.ts +5 -5
- package/dist/types/Models.d.ts.map +1 -1
- package/dist/types/Models.js +9 -9
- package/dist/types/Models.js.map +1 -1
- package/package.json +10 -3
- package/src/auth/TokenVerifier.test.ts +152 -0
- package/src/auth/TokenVerifier.ts +145 -0
- package/src/decorator/Decorator.test.ts +126 -0
- package/src/decorator/Decorator.ts +32 -4
- package/src/function/ToolFunction.test.ts +259 -109
- package/src/function/ToolFunction.ts +66 -5
- package/src/index.ts +1 -0
- package/src/service/Service.test.ts +139 -28
- package/src/service/Service.ts +31 -24
- package/src/types/Models.ts +4 -4
package/package.json
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@optimizely-opal/opal-tool-ocp-sdk",
|
|
3
|
-
"version": "0.0.0-beta.
|
|
3
|
+
"version": "0.0.0-beta.10",
|
|
4
4
|
"description": "OCP SDK for Opal tool",
|
|
5
5
|
"scripts": {
|
|
6
|
+
"validate-deps": "node scripts/validate-deps.js",
|
|
7
|
+
"prebuild": "yarn run validate-deps",
|
|
6
8
|
"build": "yarn tsc",
|
|
7
9
|
"build-watch": "tsc -w",
|
|
8
10
|
"lint": "npx eslint 'src/**/*.ts'",
|
|
@@ -49,10 +51,15 @@
|
|
|
49
51
|
"rimraf": "^6.0.1",
|
|
50
52
|
"ts-jest": "^29.3.2",
|
|
51
53
|
"tslint": "^6.1.3",
|
|
52
|
-
"typescript": "^5.8.2"
|
|
54
|
+
"typescript": "^5.8.2",
|
|
55
|
+
"@zaiusinc/node-sdk": "^2.0.0",
|
|
56
|
+
"@zaiusinc/app-sdk": "^2.2.4-devmg.1"
|
|
53
57
|
},
|
|
54
58
|
"dependencies": {
|
|
55
|
-
"
|
|
59
|
+
"jose": "^6.1.0",
|
|
56
60
|
"reflect-metadata": "^0.2.2"
|
|
61
|
+
},
|
|
62
|
+
"peerDependencies": {
|
|
63
|
+
"@zaiusinc/app-sdk": "^2.2.4-devmg.1"
|
|
57
64
|
}
|
|
58
65
|
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { TokenVerifier } from './TokenVerifier';
|
|
2
|
+
|
|
3
|
+
// Test constants
|
|
4
|
+
const TEST_ISSUER = 'https://prep.login.optimizely.com/oauth2/default';
|
|
5
|
+
const TEST_JWKS_URI = 'https://prep.login.optimizely.com/oauth2/v1/keys';
|
|
6
|
+
|
|
7
|
+
// Mock fetch globally
|
|
8
|
+
global.fetch = jest.fn();
|
|
9
|
+
|
|
10
|
+
describe('TokenVerifier', () => {
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
// Reset fetch mock
|
|
13
|
+
(global.fetch as jest.Mock).mockReset();
|
|
14
|
+
|
|
15
|
+
// Reset singleton instance for each test
|
|
16
|
+
(TokenVerifier as any).instance = null;
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe('getInitializedInstance', () => {
|
|
20
|
+
it('should initialize successfully', async () => {
|
|
21
|
+
// Mock fetch for OAuth2 authorization server discovery
|
|
22
|
+
(global.fetch as jest.Mock).mockResolvedValue({
|
|
23
|
+
ok: true,
|
|
24
|
+
json: jest.fn().mockResolvedValue({
|
|
25
|
+
issuer: TEST_ISSUER,
|
|
26
|
+
jwks_uri: TEST_JWKS_URI
|
|
27
|
+
})
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const tokenVerifier = await TokenVerifier.getInitializedInstance();
|
|
31
|
+
expect(tokenVerifier).toBeInstanceOf(TokenVerifier);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('should throw error when discovery document is invalid', async () => {
|
|
35
|
+
(global.fetch as jest.Mock).mockResolvedValue({
|
|
36
|
+
ok: true,
|
|
37
|
+
json: jest.fn().mockResolvedValue({
|
|
38
|
+
// Missing issuer and jwks_uri
|
|
39
|
+
})
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
await expect(TokenVerifier.getInitializedInstance()).rejects.toThrow(
|
|
43
|
+
'Invalid discovery document: missing issuer or jwks_uri'
|
|
44
|
+
);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('should throw error when discovery endpoint is unreachable', async () => {
|
|
48
|
+
(global.fetch as jest.Mock).mockResolvedValue({
|
|
49
|
+
ok: false,
|
|
50
|
+
status: 404,
|
|
51
|
+
statusText: 'Not Found'
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
await expect(TokenVerifier.getInitializedInstance()).rejects.toThrow(
|
|
55
|
+
'Failed to fetch discovery document: 404 Not Found'
|
|
56
|
+
);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe('token verification', () => {
|
|
61
|
+
let tokenVerifier: TokenVerifier;
|
|
62
|
+
|
|
63
|
+
beforeEach(async () => {
|
|
64
|
+
// Mock successful initialization
|
|
65
|
+
(global.fetch as jest.Mock).mockResolvedValue({
|
|
66
|
+
ok: true,
|
|
67
|
+
json: jest.fn().mockResolvedValue({
|
|
68
|
+
issuer: TEST_ISSUER,
|
|
69
|
+
jwks_uri: TEST_JWKS_URI
|
|
70
|
+
})
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
tokenVerifier = await TokenVerifier.getInitializedInstance();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('should throw error for empty token', async () => {
|
|
77
|
+
await expect(tokenVerifier.verify('')).rejects.toThrow(
|
|
78
|
+
'Token cannot be null or empty'
|
|
79
|
+
);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('should throw error for undefined token', async () => {
|
|
83
|
+
await expect(tokenVerifier.verify(undefined)).rejects.toThrow(
|
|
84
|
+
'Token cannot be null or empty'
|
|
85
|
+
);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('should throw error for whitespace-only token', async () => {
|
|
89
|
+
await expect(tokenVerifier.verify(' ')).rejects.toThrow(
|
|
90
|
+
'Token cannot be null or empty'
|
|
91
|
+
);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('should return false for invalid token format', async () => {
|
|
95
|
+
const result = await tokenVerifier.verify('invalid.jwt.token');
|
|
96
|
+
expect(result).toBe(false);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe('singleton pattern', () => {
|
|
101
|
+
it('should return same instance when called multiple times', async () => {
|
|
102
|
+
// Mock successful initialization
|
|
103
|
+
(global.fetch as jest.Mock).mockResolvedValue({
|
|
104
|
+
ok: true,
|
|
105
|
+
json: jest.fn().mockResolvedValue({
|
|
106
|
+
issuer: TEST_ISSUER,
|
|
107
|
+
jwks_uri: TEST_JWKS_URI
|
|
108
|
+
})
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
const instance1 = await TokenVerifier.getInitializedInstance();
|
|
112
|
+
const instance2 = await TokenVerifier.getInitializedInstance();
|
|
113
|
+
expect(instance1).toBe(instance2);
|
|
114
|
+
});
|
|
115
|
+
it('should call correct prod OAuth2 authorization server discovery URL', async () => {
|
|
116
|
+
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue({
|
|
117
|
+
ok: true,
|
|
118
|
+
json: jest.fn().mockResolvedValue({
|
|
119
|
+
issuer: TEST_ISSUER,
|
|
120
|
+
jwks_uri: TEST_JWKS_URI
|
|
121
|
+
})
|
|
122
|
+
} as unknown as Response);
|
|
123
|
+
|
|
124
|
+
await TokenVerifier.getInitializedInstance();
|
|
125
|
+
|
|
126
|
+
expect(fetchSpy).toHaveBeenCalledWith(
|
|
127
|
+
'https://login.optimizely.com/oauth2/default/.well-known/oauth-authorization-server'
|
|
128
|
+
);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('should call correct prep OAuth2 authorization server discovery URL', async () => {
|
|
132
|
+
// Set environment variable to staging
|
|
133
|
+
process.env.environment = 'staging';
|
|
134
|
+
|
|
135
|
+
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue({
|
|
136
|
+
ok: true,
|
|
137
|
+
json: jest.fn().mockResolvedValue({
|
|
138
|
+
issuer: TEST_ISSUER,
|
|
139
|
+
jwks_uri: TEST_JWKS_URI
|
|
140
|
+
})
|
|
141
|
+
} as unknown as Response);
|
|
142
|
+
|
|
143
|
+
await TokenVerifier.getInitializedInstance();
|
|
144
|
+
|
|
145
|
+
expect(fetchSpy).toHaveBeenCalledWith(
|
|
146
|
+
'https://prep.login.optimizely.com/oauth2/default/.well-known/oauth-authorization-server'
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
});
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { jwtVerify, createRemoteJWKSet } from 'jose';
|
|
2
|
+
import { logger } from '@zaiusinc/app-sdk';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Default JWKS cache expiration time in milliseconds (1 hour)
|
|
6
|
+
*/
|
|
7
|
+
const DEFAULT_JWKS_EXPIRES_IN = 60 * 60 * 1000;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Default clock skew tolerance in seconds
|
|
11
|
+
*/
|
|
12
|
+
const DEFAULT_LEEWAY = 30;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Expected JWT audience for token validation
|
|
16
|
+
*/
|
|
17
|
+
const AUDIENCE = 'api://default';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Prep Base URL for Optimizely OAuth2 endpoints
|
|
21
|
+
*/
|
|
22
|
+
const PREP_BASE_URL = 'https://prep.login.optimizely.com/oauth2/default';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Prod Base URL for Optimizely OAuth2 endpoints
|
|
26
|
+
*/
|
|
27
|
+
const PROD_BASE_URL = 'https://login.optimizely.com/oauth2/default';
|
|
28
|
+
|
|
29
|
+
interface DiscoveryDocument {
|
|
30
|
+
issuer: string;
|
|
31
|
+
jwks_uri: string;
|
|
32
|
+
[key: string]: any;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class TokenVerifier {
|
|
36
|
+
private static instance: TokenVerifier | null = null;
|
|
37
|
+
private jwksUri?: string;
|
|
38
|
+
private issuer?: string;
|
|
39
|
+
private jwks?: ReturnType<typeof createRemoteJWKSet>;
|
|
40
|
+
private initialized: boolean = false;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Verify the provided Optimizely JWT token string
|
|
44
|
+
* @param token JWT token string to verify
|
|
45
|
+
* @returns boolean true if verification successful, false otherwise
|
|
46
|
+
* @throws Error if token is null, empty, or verifier is not properly configured
|
|
47
|
+
*/
|
|
48
|
+
public async verify(token: string | undefined): Promise<boolean> {
|
|
49
|
+
if (!token || token.trim().length === 0) {
|
|
50
|
+
throw new Error('Token cannot be null or empty');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return this.verifyToken(token);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private static getInstance(): TokenVerifier {
|
|
57
|
+
if (!TokenVerifier.instance) {
|
|
58
|
+
TokenVerifier.instance = new TokenVerifier();
|
|
59
|
+
}
|
|
60
|
+
return TokenVerifier.instance;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Get singleton instance of TokenVerifier and ensure it's initialized
|
|
65
|
+
* @returns Promise<TokenVerifier> - initialized singleton instance
|
|
66
|
+
*/
|
|
67
|
+
public static async getInitializedInstance(): Promise<TokenVerifier> {
|
|
68
|
+
const instance = TokenVerifier.getInstance();
|
|
69
|
+
if (!instance.initialized) {
|
|
70
|
+
await instance.initialize();
|
|
71
|
+
}
|
|
72
|
+
return instance;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Initialize the TokenVerifier with discovery document from well-known endpoint
|
|
77
|
+
*/
|
|
78
|
+
private async initialize(): Promise<void> {
|
|
79
|
+
if (this.initialized) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
// Use prep URL when environment variable is set to 'staging', otherwise use prod
|
|
85
|
+
const environment = process.env.environment || 'production';
|
|
86
|
+
const baseUrl = environment === 'staging' ? PREP_BASE_URL : PROD_BASE_URL;
|
|
87
|
+
const discoveryDocument = await this.fetchDiscoveryDocument(baseUrl);
|
|
88
|
+
this.issuer = discoveryDocument.issuer;
|
|
89
|
+
this.jwksUri = discoveryDocument.jwks_uri;
|
|
90
|
+
this.jwks = createRemoteJWKSet(new URL(this.jwksUri), {
|
|
91
|
+
cacheMaxAge: DEFAULT_JWKS_EXPIRES_IN,
|
|
92
|
+
cooldownDuration: DEFAULT_JWKS_EXPIRES_IN
|
|
93
|
+
});
|
|
94
|
+
this.initialized = true;
|
|
95
|
+
logger.info(`TokenVerifier initialized with issuer: ${this.issuer} (environment: ${environment})`);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
logger.error('Failed to initialize TokenVerifier', error);
|
|
98
|
+
// Re-throw the original error to preserve specific error messages for tests
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Fetch discovery document from well-known endpoint
|
|
105
|
+
*/
|
|
106
|
+
private async fetchDiscoveryDocument(baseUrl: string): Promise<DiscoveryDocument> {
|
|
107
|
+
const wellKnownUrl = `${baseUrl}/.well-known/oauth-authorization-server`;
|
|
108
|
+
|
|
109
|
+
const response = await fetch(wellKnownUrl);
|
|
110
|
+
if (!response.ok) {
|
|
111
|
+
throw new Error(`Failed to fetch discovery document: ${response.status} ${response.statusText}`);
|
|
112
|
+
}
|
|
113
|
+
const discoveryDocument = await response.json() as DiscoveryDocument;
|
|
114
|
+
if (!discoveryDocument.issuer || !discoveryDocument.jwks_uri) {
|
|
115
|
+
throw new Error('Invalid discovery document: missing issuer or jwks_uri');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return discoveryDocument;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private async verifyToken(token: string): Promise<boolean> {
|
|
122
|
+
if (!this.initialized) {
|
|
123
|
+
throw new Error('TokenVerifier not initialized. Call initialize() first.');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (!this.jwks || !this.issuer) {
|
|
127
|
+
throw new Error('TokenVerifier not properly configured.');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
await jwtVerify(token, this.jwks, {
|
|
132
|
+
issuer: this.issuer,
|
|
133
|
+
audience: AUDIENCE,
|
|
134
|
+
clockTolerance: DEFAULT_LEEWAY,
|
|
135
|
+
});
|
|
136
|
+
return true;
|
|
137
|
+
} catch (error) {
|
|
138
|
+
logger.error('Token verification failed:', error);
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export const getTokenVerifier = async (): Promise<TokenVerifier> => TokenVerifier.getInitializedInstance();
|
|
@@ -519,5 +519,131 @@ describe('Decorators', () => {
|
|
|
519
519
|
);
|
|
520
520
|
});
|
|
521
521
|
});
|
|
522
|
+
|
|
523
|
+
describe('handler instance context', () => {
|
|
524
|
+
it('should allow tool handler to call class methods', async () => {
|
|
525
|
+
class TestClass {
|
|
526
|
+
private getValue() {
|
|
527
|
+
return 'class-method-called';
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
@tool({
|
|
531
|
+
name: 'instanceMethodTest',
|
|
532
|
+
description: 'Test calling class methods',
|
|
533
|
+
parameters: [],
|
|
534
|
+
endpoint: '/instance-method-test'
|
|
535
|
+
})
|
|
536
|
+
public async instanceMethodTest(_params: any) {
|
|
537
|
+
return { result: this.getValue() };
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// Get the registered handler
|
|
542
|
+
const mockedRegisterTool = jest.mocked(toolsService.registerTool);
|
|
543
|
+
const registerToolCall = mockedRegisterTool.mock.calls.find((call) => call[0] === 'instanceMethodTest');
|
|
544
|
+
const registeredHandler = registerToolCall![2];
|
|
545
|
+
|
|
546
|
+
// Call the handler
|
|
547
|
+
const result = await registeredHandler(undefined as any, {}, {});
|
|
548
|
+
|
|
549
|
+
// Should be able to call class methods through 'this'
|
|
550
|
+
expect((result as any).result).toBe('class-method-called');
|
|
551
|
+
expect(TestClass).toBeDefined();
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
it('should allow interaction handler to call class methods', async () => {
|
|
555
|
+
class TestClass {
|
|
556
|
+
private processData() {
|
|
557
|
+
return 'interaction-processed';
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
@interaction({
|
|
561
|
+
name: 'instanceInteractionTest',
|
|
562
|
+
endpoint: '/instance-interaction-test'
|
|
563
|
+
})
|
|
564
|
+
public async instanceInteractionTest(_data: any) {
|
|
565
|
+
return { message: this.processData() };
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// Get the registered handler
|
|
570
|
+
const mockedRegisterInteraction = jest.mocked(toolsService.registerInteraction);
|
|
571
|
+
const registerInteractionCall = mockedRegisterInteraction.mock.calls.find(
|
|
572
|
+
(call) => call[0] === 'instanceInteractionTest'
|
|
573
|
+
);
|
|
574
|
+
const registeredHandler = registerInteractionCall![1];
|
|
575
|
+
|
|
576
|
+
// Call the handler
|
|
577
|
+
const result = await registeredHandler(undefined as any, {});
|
|
578
|
+
|
|
579
|
+
// Should be able to call class methods through 'this'
|
|
580
|
+
expect((result as any).message).toBe('interaction-processed');
|
|
581
|
+
expect(TestClass).toBeDefined();
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
it('should handle invalid functionContext gracefully for tool', async () => {
|
|
585
|
+
class TestClass {
|
|
586
|
+
private getValue() {
|
|
587
|
+
return 'class-method-called';
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
@tool({
|
|
591
|
+
name: 'invalidContextTest',
|
|
592
|
+
description: 'Test handling invalid context',
|
|
593
|
+
parameters: [],
|
|
594
|
+
endpoint: '/invalid-context-test'
|
|
595
|
+
})
|
|
596
|
+
public async invalidContextTest(_params: any) {
|
|
597
|
+
return { result: this.getValue() };
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// Get the registered handler
|
|
602
|
+
const mockedRegisterTool = jest.mocked(toolsService.registerTool);
|
|
603
|
+
const registerToolCall = mockedRegisterTool.mock.calls.find((call) => call[0] === 'invalidContextTest');
|
|
604
|
+
const registeredHandler = registerToolCall![2];
|
|
605
|
+
|
|
606
|
+
// Call the handler with an invalid functionContext (truthy but wrong type)
|
|
607
|
+
// This should trigger the instanceof check and create a new instance instead
|
|
608
|
+
const invalidContext = { notAnInstance: true, someOtherProperty: 'invalid' };
|
|
609
|
+
const result = await registeredHandler(invalidContext as any, {}, {});
|
|
610
|
+
|
|
611
|
+
// Should still work by creating a new instance
|
|
612
|
+
expect((result as any).result).toBe('class-method-called');
|
|
613
|
+
expect(TestClass).toBeDefined();
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
it('should handle invalid functionContext gracefully for interaction', async () => {
|
|
617
|
+
class TestClass {
|
|
618
|
+
private processData() {
|
|
619
|
+
return 'interaction-processed';
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
@interaction({
|
|
623
|
+
name: 'invalidContextInteractionTest',
|
|
624
|
+
endpoint: '/invalid-context-interaction-test'
|
|
625
|
+
})
|
|
626
|
+
public async invalidContextInteractionTest(_data: any) {
|
|
627
|
+
return { message: this.processData() };
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// Get the registered handler
|
|
632
|
+
const mockedRegisterInteraction = jest.mocked(toolsService.registerInteraction);
|
|
633
|
+
const registerInteractionCall = mockedRegisterInteraction.mock.calls.find(
|
|
634
|
+
(call) => call[0] === 'invalidContextInteractionTest'
|
|
635
|
+
);
|
|
636
|
+
const registeredHandler = registerInteractionCall![1];
|
|
637
|
+
|
|
638
|
+
// Call the handler with an invalid functionContext (truthy but wrong type)
|
|
639
|
+
// This should trigger the instanceof check and create a new instance instead
|
|
640
|
+
const invalidContext = { notAnInstance: true, someOtherProperty: 'invalid' };
|
|
641
|
+
const result = await registeredHandler(invalidContext as any, {});
|
|
642
|
+
|
|
643
|
+
// Should still work by creating a new instance
|
|
644
|
+
expect((result as any).message).toBe('interaction-processed');
|
|
645
|
+
expect(TestClass).toBeDefined();
|
|
646
|
+
});
|
|
647
|
+
});
|
|
522
648
|
});
|
|
523
649
|
|
|
@@ -42,9 +42,10 @@ export interface InteractionConfig {
|
|
|
42
42
|
/**
|
|
43
43
|
* Decorator for registering tool functions
|
|
44
44
|
* Immediately registers the tool with the global ToolsService
|
|
45
|
+
* The handler will have access to 'this' context when called
|
|
45
46
|
*/
|
|
46
47
|
export function tool(config: ToolConfig) {
|
|
47
|
-
return function(
|
|
48
|
+
return function(target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
|
|
48
49
|
// Convert parameter configs to Parameter instances
|
|
49
50
|
const parameters = (config.parameters || []).map((p) =>
|
|
50
51
|
new Parameter(p.name, p.type, p.description, p.required)
|
|
@@ -55,11 +56,24 @@ export function tool(config: ToolConfig) {
|
|
|
55
56
|
new AuthRequirement(a.provider, a.scopeBundle, a.required)
|
|
56
57
|
);
|
|
57
58
|
|
|
59
|
+
const originalMethod = descriptor.value;
|
|
60
|
+
|
|
61
|
+
const boundHandler = function(functionContext: any, params: any, authData: any) {
|
|
62
|
+
// Check if we're being called from within a ToolFunction instance context
|
|
63
|
+
// If so, use that instance; otherwise create a new one
|
|
64
|
+
const instance = (functionContext && functionContext instanceof target.constructor) ?
|
|
65
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
66
|
+
functionContext : new target.constructor();
|
|
67
|
+
|
|
68
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
69
|
+
return originalMethod.call(instance, params, authData);
|
|
70
|
+
};
|
|
71
|
+
|
|
58
72
|
// Immediately register with global ToolsService
|
|
59
73
|
toolsService.registerTool(
|
|
60
74
|
config.name,
|
|
61
75
|
config.description,
|
|
62
|
-
|
|
76
|
+
boundHandler,
|
|
63
77
|
parameters,
|
|
64
78
|
config.endpoint,
|
|
65
79
|
authRequirements
|
|
@@ -70,13 +84,27 @@ export function tool(config: ToolConfig) {
|
|
|
70
84
|
/**
|
|
71
85
|
* Decorator for registering interaction functions
|
|
72
86
|
* Immediately registers the interaction with the global ToolsService
|
|
87
|
+
* The handler will have access to 'this' context when called
|
|
73
88
|
*/
|
|
74
89
|
export function interaction(config: InteractionConfig) {
|
|
75
|
-
return function(
|
|
90
|
+
return function(target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
|
|
91
|
+
const originalMethod = descriptor.value;
|
|
92
|
+
|
|
93
|
+
const boundHandler = function(functionContext: any, data: any, authData?: any) {
|
|
94
|
+
// Check if we're being called from within a ToolFunction instance context
|
|
95
|
+
// If so, use that instance; otherwise create a new one
|
|
96
|
+
const instance = (functionContext && functionContext instanceof target.constructor) ?
|
|
97
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
98
|
+
functionContext : new target.constructor();
|
|
99
|
+
|
|
100
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
101
|
+
return originalMethod.call(instance, data, authData);
|
|
102
|
+
};
|
|
103
|
+
|
|
76
104
|
// Immediately register with global ToolsService
|
|
77
105
|
toolsService.registerInteraction(
|
|
78
106
|
config.name,
|
|
79
|
-
|
|
107
|
+
boundHandler,
|
|
80
108
|
config.endpoint
|
|
81
109
|
);
|
|
82
110
|
};
|