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