@slates/test 1.0.0-rc.3 → 1.0.0-rc.5

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/src/runtime.ts ADDED
@@ -0,0 +1,395 @@
1
+ import {
2
+ createLocalSlateTransport,
3
+ createSlatesClient,
4
+ SlateProtocolError
5
+ } from '@slates/client';
6
+ import type { SlatesProtocolClientOptions } from '@slates/client';
7
+ import {
8
+ createSlatesClientFromProfile,
9
+ openSlatesCliStore,
10
+ SlatesProfileRecord
11
+ } from '@slates/profiles';
12
+ import { readFile } from 'fs/promises';
13
+
14
+ export interface SlatesRuntimeContext {
15
+ integration: string | null;
16
+ profileId: string | null;
17
+ authMethodId: string | null;
18
+ profile: SlatesProfileRecord | null;
19
+ rootDir: string;
20
+ storePath: string;
21
+ cliDir: string;
22
+ }
23
+
24
+ export type SlatesTestClient = ReturnType<typeof createSlatesClient>;
25
+
26
+ type LocalSlate = Parameters<typeof createLocalSlateTransport>[0]['slate'];
27
+
28
+ let selectProfileAuth = (profile: SlatesProfileRecord | null, authMethodId: string | null) => {
29
+ if (!profile || !authMethodId) {
30
+ return profile;
31
+ }
32
+
33
+ let selectedAuth = profile.auth[authMethodId];
34
+ if (!selectedAuth) {
35
+ let availableAuthMethods = Object.keys(profile.auth);
36
+ throw new Error(
37
+ `No stored authentication found for auth method "${authMethodId}" in profile "${profile.name}".` +
38
+ (availableAuthMethods.length > 0
39
+ ? ` Available auth methods: ${availableAuthMethods.join(', ')}.`
40
+ : ' No auth methods are stored for this profile.')
41
+ );
42
+ }
43
+
44
+ return {
45
+ ...profile,
46
+ auth: {
47
+ [selectedAuth.authMethodId]: selectedAuth
48
+ }
49
+ };
50
+ };
51
+
52
+ export interface ExpectedSlateAction {
53
+ id: string;
54
+ name?: string;
55
+ description?: string;
56
+ readOnly?: boolean;
57
+ destructive?: boolean;
58
+ invocationType?: 'polling' | 'webhook';
59
+ }
60
+
61
+ export let getVitestExpect = () => {
62
+ let maybeExpect = (
63
+ globalThis as typeof globalThis & { expect?: typeof import('vitest').expect }
64
+ ).expect;
65
+
66
+ if (!maybeExpect) {
67
+ throw new Error('Vitest expect is not available in the current runtime.');
68
+ }
69
+
70
+ return maybeExpect;
71
+ };
72
+
73
+ export let loadSlatesRuntimeContext = async (
74
+ opts: {
75
+ cwd?: string;
76
+ profile?: string | null;
77
+ } = {}
78
+ ): Promise<SlatesRuntimeContext> => {
79
+ let runtimeContextPath = process.env.SLATES_TEST_CONTEXT_PATH;
80
+ if (runtimeContextPath) {
81
+ let raw = await readFile(runtimeContextPath, 'utf-8');
82
+ let parsed = JSON.parse(raw) as {
83
+ integration?: string | null;
84
+ profileId: string | null;
85
+ authMethodId?: string | null;
86
+ rootDir?: string;
87
+ storePath: string;
88
+ cliDir: string;
89
+ };
90
+ let store = await openSlatesCliStore({
91
+ storePath: parsed.storePath,
92
+ rootDir: parsed.rootDir ?? process.env.SLATES_STORE_ROOT_DIR
93
+ });
94
+ let authMethodId = parsed.authMethodId ?? null;
95
+ let profile = selectProfileAuth(
96
+ store.getProfile(opts.profile ?? parsed.profileId ?? null),
97
+ authMethodId
98
+ );
99
+
100
+ return {
101
+ integration: parsed.integration ?? store.scope?.key ?? null,
102
+ profileId: profile?.id ?? parsed.profileId ?? null,
103
+ authMethodId,
104
+ profile,
105
+ rootDir: parsed.rootDir ?? store.rootDir,
106
+ storePath: parsed.storePath,
107
+ cliDir: parsed.cliDir
108
+ };
109
+ }
110
+
111
+ let store = process.env.SLATES_STORE_PATH
112
+ ? await openSlatesCliStore({
113
+ storePath: process.env.SLATES_STORE_PATH,
114
+ rootDir: process.env.SLATES_STORE_ROOT_DIR
115
+ })
116
+ : await openSlatesCliStore({ cwd: opts.cwd });
117
+ let profileId = opts.profile ?? process.env.SLATES_PROFILE_ID ?? null;
118
+ let authMethodId = null;
119
+ let profile = selectProfileAuth(store.getProfile(profileId), authMethodId);
120
+
121
+ return {
122
+ integration: process.env.SLATES_INTEGRATION ?? store.scope?.key ?? null,
123
+ profileId: profile?.id ?? null,
124
+ authMethodId,
125
+ profile,
126
+ rootDir: store.rootDir,
127
+ storePath: store.storePath,
128
+ cliDir: store.dirPath
129
+ };
130
+ };
131
+
132
+ export let loadSlatesProfile = async (
133
+ opts: { cwd?: string; profile?: string | null } = {}
134
+ ) => {
135
+ let context = await loadSlatesRuntimeContext(opts);
136
+ if (!context.profile) {
137
+ throw new Error('No Slates profile is available for the current test context.');
138
+ }
139
+
140
+ return context.profile;
141
+ };
142
+
143
+ export let createSlatesTestClient = async (
144
+ opts: { cwd?: string; profile?: string | null } = {}
145
+ ) => {
146
+ let context = await loadSlatesRuntimeContext(opts);
147
+ if (!context.profile) {
148
+ throw new Error('No Slates profile is available for the current test context.');
149
+ }
150
+
151
+ let store = await openSlatesCliStore({
152
+ storePath: context.storePath,
153
+ rootDir: context.rootDir
154
+ });
155
+ return createSlatesClientFromProfile(context.profile, { cwd: opts.cwd, store });
156
+ };
157
+
158
+ export let withSlateProfile = async <T>(
159
+ profileName: string | null | undefined,
160
+ cb: (ctx: { profile: SlatesProfileRecord }) => Promise<T>
161
+ ) => {
162
+ let profile = await loadSlatesProfile({ profile: profileName });
163
+ return cb({ profile });
164
+ };
165
+
166
+ export let expectToolCall = async (d: {
167
+ client?: Awaited<ReturnType<typeof createSlatesTestClient>>;
168
+ profile?: string | null;
169
+ toolId: string;
170
+ input: Record<string, any>;
171
+ output?: Record<string, any>;
172
+ }) => {
173
+ let expect = getVitestExpect();
174
+ let client = d.client ?? (await createSlatesTestClient({ profile: d.profile }));
175
+ let result = await client.invokeTool(d.toolId, d.input);
176
+
177
+ if (d.output) {
178
+ expect(result.output).toMatchObject(d.output);
179
+ }
180
+
181
+ return result;
182
+ };
183
+
184
+ export let createLocalSlateTestClient = (opts: {
185
+ slate: LocalSlate;
186
+ state?: SlatesProtocolClientOptions['state'];
187
+ participants?: SlatesProtocolClientOptions['participants'];
188
+ }) =>
189
+ createSlatesClient({
190
+ transport: createLocalSlateTransport({ slate: opts.slate }),
191
+ state: opts.state,
192
+ participants: opts.participants
193
+ });
194
+
195
+ export let getSlateContract = async (client: SlatesTestClient) => {
196
+ let [provider, actions, authMethods, configSchema] = await Promise.all([
197
+ client.identify(),
198
+ client.listActions(),
199
+ client.listAuthMethods(),
200
+ client.getConfigSchema()
201
+ ]);
202
+
203
+ return {
204
+ provider: provider.provider,
205
+ actions: actions.actions,
206
+ tools: actions.actions.filter(action => action.type === 'action.tool'),
207
+ triggers: actions.actions.filter(action => action.type === 'action.trigger'),
208
+ authMethods: authMethods.authenticationMethods,
209
+ configSchema: configSchema.schema
210
+ };
211
+ };
212
+
213
+ let expectActionMatches = (
214
+ actual: Record<string, any> | undefined,
215
+ expected: ExpectedSlateAction
216
+ ) => {
217
+ let expect = getVitestExpect();
218
+ expect(actual).toBeTruthy();
219
+ expect(actual?.id).toBe(expected.id);
220
+
221
+ if (expected.name !== undefined) {
222
+ expect(actual?.name).toBe(expected.name);
223
+ }
224
+
225
+ if (expected.description !== undefined) {
226
+ expect(actual?.description).toBe(expected.description);
227
+ }
228
+
229
+ if (expected.readOnly !== undefined) {
230
+ expect(actual?.tags?.readOnly ?? false).toBe(expected.readOnly);
231
+ }
232
+
233
+ if (expected.destructive !== undefined) {
234
+ expect(actual?.tags?.destructive ?? false).toBe(expected.destructive);
235
+ }
236
+
237
+ if (expected.invocationType !== undefined) {
238
+ expect((actual as { invocation?: { type?: string } } | undefined)?.invocation?.type).toBe(
239
+ expected.invocationType
240
+ );
241
+ }
242
+ };
243
+
244
+ export let expectSlateContract = async (d: {
245
+ client: SlatesTestClient;
246
+ provider?: {
247
+ id: string;
248
+ name?: string;
249
+ description?: string;
250
+ };
251
+ toolIds?: string[];
252
+ triggerIds?: string[];
253
+ authMethodIds?: string[];
254
+ tools?: ExpectedSlateAction[];
255
+ triggers?: ExpectedSlateAction[];
256
+ }) => {
257
+ let expect = getVitestExpect();
258
+ let contract = await getSlateContract(d.client);
259
+
260
+ if (d.provider) {
261
+ expect(contract.provider.id).toBe(d.provider.id);
262
+ if (d.provider.name !== undefined) {
263
+ expect(contract.provider.name).toBe(d.provider.name);
264
+ }
265
+ if (d.provider.description !== undefined) {
266
+ expect(contract.provider.description).toBe(d.provider.description);
267
+ }
268
+ }
269
+
270
+ if (d.toolIds) {
271
+ expect(contract.tools.map(action => action.id)).toEqual(d.toolIds);
272
+ }
273
+
274
+ if (d.triggerIds) {
275
+ expect(contract.triggers.map(action => action.id)).toEqual(d.triggerIds);
276
+ }
277
+
278
+ if (d.authMethodIds) {
279
+ expect(contract.authMethods.map(method => method.id)).toEqual(d.authMethodIds);
280
+ }
281
+
282
+ for (let tool of d.tools ?? []) {
283
+ expectActionMatches(
284
+ contract.tools.find(action => action.id === tool.id),
285
+ tool
286
+ );
287
+ }
288
+
289
+ for (let trigger of d.triggers ?? []) {
290
+ expectActionMatches(
291
+ contract.triggers.find(action => action.id === trigger.id),
292
+ trigger
293
+ );
294
+ }
295
+
296
+ return contract;
297
+ };
298
+
299
+ export let registerSlateTriggerWebhook = async (d: {
300
+ client: SlatesTestClient;
301
+ triggerId: string;
302
+ webhookBaseUrl: string;
303
+ }) => d.client.registerTriggerWebhook(d.triggerId, d.webhookBaseUrl);
304
+
305
+ export let pollSlateTriggerEvents = async (d: {
306
+ client: SlatesTestClient;
307
+ triggerId: string;
308
+ state?: any;
309
+ }) => {
310
+ d.client.ensureSession();
311
+ return d.client.request('slates/action.trigger.poll_events', {
312
+ actionId: d.triggerId,
313
+ state: d.state ?? null
314
+ });
315
+ };
316
+
317
+ export let handleSlateTriggerWebhook = async (d: {
318
+ client: SlatesTestClient;
319
+ triggerId: string;
320
+ url: string;
321
+ method?: string;
322
+ headers?: Record<string, string>;
323
+ body?: string | Uint8Array | null;
324
+ state?: any;
325
+ }) =>
326
+ d.client.handleTriggerWebhook({
327
+ actionId: d.triggerId,
328
+ url: d.url,
329
+ method: d.method ?? 'POST',
330
+ headers: d.headers,
331
+ body: d.body,
332
+ state: d.state
333
+ });
334
+
335
+ export let unregisterSlateTriggerWebhook = async (d: {
336
+ client: SlatesTestClient;
337
+ triggerId: string;
338
+ webhookBaseUrl: string;
339
+ registrationDetails: any;
340
+ state?: any;
341
+ }) =>
342
+ d.client.unregisterTriggerWebhook({
343
+ actionId: d.triggerId,
344
+ webhookBaseUrl: d.webhookBaseUrl,
345
+ registrationDetails: d.registrationDetails,
346
+ state: d.state
347
+ });
348
+
349
+ export let mapSlateTriggerEvent = async (d: {
350
+ client: SlatesTestClient;
351
+ triggerId: string;
352
+ input: Record<string, any>;
353
+ output?: Record<string, any>;
354
+ type?: string;
355
+ }) => {
356
+ let expect = getVitestExpect();
357
+ let result = await d.client.mapTriggerEvent(d.triggerId, d.input);
358
+
359
+ if (d.type !== undefined) {
360
+ expect(result.type).toBe(d.type);
361
+ }
362
+
363
+ if (d.output) {
364
+ expect(result.output).toMatchObject(d.output);
365
+ }
366
+
367
+ return result;
368
+ };
369
+
370
+ export let expectSlateError = async (
371
+ run: Promise<unknown> | (() => Promise<unknown>),
372
+ expected: Record<string, any> | string | RegExp
373
+ ) => {
374
+ let expect = getVitestExpect();
375
+ try {
376
+ await (typeof run === 'function' ? run() : run);
377
+ } catch (error) {
378
+ if (typeof expected === 'string' || expected instanceof RegExp) {
379
+ let message = error instanceof Error ? error.message : String(error);
380
+ if (expected instanceof RegExp) {
381
+ expect(message).toMatch(expected);
382
+ } else {
383
+ expect(message).toContain(expected);
384
+ }
385
+ } else if (error instanceof SlateProtocolError) {
386
+ expect(error.data).toMatchObject(expected);
387
+ } else {
388
+ expect(error).toMatchObject(expected);
389
+ }
390
+
391
+ return error;
392
+ }
393
+
394
+ throw new Error('Expected the operation to fail, but it completed successfully.');
395
+ };