@hasura/promptql 1.0.0 → 2.0.0-alpha.1

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.
Files changed (43) hide show
  1. package/README.md +310 -134
  2. package/biome.json +8 -0
  3. package/package.json +44 -53
  4. package/src/auth/auth.test.ts +24 -0
  5. package/src/auth/auth.ts +130 -0
  6. package/src/auth/index.ts +2 -0
  7. package/src/auth/types.ts +56 -0
  8. package/src/generated/ChatV2ServerSchema.json +5841 -0
  9. package/src/generated/ChatV2ServerTypes.ts +2747 -0
  10. package/src/generated/ThreadEvents.example.json +1645 -0
  11. package/src/generated/graphql.ts +12121 -0
  12. package/src/graphql/README.md +70 -0
  13. package/src/graphql/mutations/sendThreadMessage.gql +16 -0
  14. package/src/graphql/mutations/startThread.gql +19 -0
  15. package/src/graphql/queries/getProjectInfo.gql +7 -0
  16. package/src/graphql/queries/thread.gql +39 -0
  17. package/src/graphql/subscriptions/subscribeThreadEventsByThreadId.gql +7 -0
  18. package/src/index.ts +13 -0
  19. package/src/sdk/apollo.ts +63 -0
  20. package/src/sdk/client.ts +273 -0
  21. package/src/sdk/index.ts +4 -0
  22. package/src/sdk/types.ts +254 -0
  23. package/src/sdk/utils.ts +684 -0
  24. package/src/utils.ts +16 -0
  25. package/tsconfig.json +8 -0
  26. package/LICENSE +0 -201
  27. package/dist/index.d.ts +0 -5
  28. package/dist/index.iife.js +0 -1
  29. package/dist/index.js +0 -1
  30. package/dist/index.mjs +0 -925
  31. package/dist/index.umd.js +0 -1
  32. package/dist/promptql.d.ts +0 -598
  33. package/dist/types.d.ts +0 -26
  34. package/dist/utils/index.d.ts +0 -2
  35. package/dist/utils/query-chunks.d.ts +0 -35
  36. package/dist/utils/query-stream.d.ts +0 -3
  37. package/dist/utils/utils.d.ts +0 -36
  38. package/dist/v1/client.d.ts +0 -8
  39. package/dist/v1/index.d.ts +0 -11
  40. package/dist/v1/types.d.ts +0 -100
  41. package/dist/v2/client.d.ts +0 -8
  42. package/dist/v2/index.d.ts +0 -2
  43. package/dist/v2/types.d.ts +0 -75
package/README.md CHANGED
@@ -1,196 +1,372 @@
1
- # PromptQL NodeJS SDK
1
+ # PromptQL TypeScript SDK
2
2
 
3
- A Node.js SDK for [PromptQL API](https://hasura.io/docs/promptql/promptql-apis/overview/).
3
+ A TypeScript SDK for interacting with the [PromptQL API](https://promptql.hasura.io) by Hasura. PromptQL enables natural language querying of your data through an AI-powered interface.
4
4
 
5
- ## Install
5
+ ## Features
6
6
 
7
- Run the following command:
7
+ - **Type-safe API Client**: Fully typed TypeScript SDK with auto-generated types from GraphQL schema
8
+ - **Thread Management**: Create, list, and manage conversation threads
9
+ - **Real-time Streaming**: Subscribe to thread events with GraphQL subscriptions using RxJS observables
10
+ - **Authentication**: Built-in authentication handling with service account tokens
11
+ - **Query Planning**: Access to AI agent query plans and execution steps
12
+ - **Artifact Support**: Handle modified artifacts from AI responses
13
+ - **CLI Tool**: Command-line interface for quick interactions
14
+ - **Flexible Configuration**: Support for custom base URLs, headers, and fetch implementations
8
15
 
9
- ```sh
16
+ ## Requirements
17
+
18
+ - Node.js >= 24
19
+ - TypeScript >= 5.9.2
20
+
21
+ ## Installation
22
+
23
+ ```bash
10
24
  npm install @hasura/promptql
11
25
  ```
12
26
 
13
- ## Get started
27
+ Or with your preferred package manager:
28
+
29
+ ```bash
30
+ # Yarn
31
+ yarn add @hasura/promptql
14
32
 
15
- ### Prerequisite
33
+ # pnpm
34
+ pnpm add @hasura/promptql
16
35
 
17
- - If you are new with PromptQL, follow [the quickstart guide of PromptQL](https://hasura.io/docs/promptql/quickstart/) to create a project.
18
- - Create a PromptQL API Key in project settings tab on [https://console.hasura.io](https://console.hasura.io).
19
- - Security headers and your Project API endpoint (version 1) or build version (version 2).
36
+ # Bun
37
+ bun add @hasura/promptql
38
+ ```
20
39
 
21
- ### Use PromptQL SDK
40
+ ## Quick Start
22
41
 
23
- #### Create client
42
+ ### Getting Service Account Token
24
43
 
25
- Create the PromptQL client with required configurations:
44
+ 1. Visit your Hasura project console
45
+ 2. Navigate to Project Settings
46
+ 3. Go to Service Accounts section
47
+ 4. Create a new service account token with `Read Only` permission. Avoid using the `Admin` role. Hackers can modify your project metadata if the service account token is leaked.
48
+ 5. Copy the token and use it in your SDK configuration
26
49
 
27
- ```ts
28
- import { createPromptQLClientV2 } from '@hasura/promptql';
50
+ For more details, check the [Hasura documentation](https://hasura.io/docs/3.0/project-configuration/project-management/service-accounts/#how-to-create-service-account).
29
51
 
30
- const client = createPromptQLClientV2({
31
- apiKey: '<your-promptql-api-key>',
32
- ddn: {
33
- headers: {
34
- 'Authorization': '<credential>'
35
- }
36
- },
37
- // You can define a lazy function for the ddn options.
38
- //
39
- // ddn: () => {{
40
- // headers: {
41
- // 'Authorization': '<credential>'
42
- // }
43
- // }}
52
+ ### Basic Usage
53
+
54
+ #### Start a PromptQL thread
55
+
56
+ ```typescript
57
+ import { PromptQLSdk } from '@hasura/promptql';
58
+
59
+ // Initialize the SDK
60
+ const sdk = new PromptQLSdk({
61
+ projectId: 'your-project-id',
62
+ serviceAccountToken: 'your-service-account-token',
44
63
  });
45
- ```
46
64
 
47
- #### Run a Query
48
-
49
- ```ts
50
- const runQuery = (text: string) => {
51
- return client.query({
52
- artifacts: [],
53
- interactions: [
54
- {
55
- user_message: {
56
- text,
57
- }
58
- }
59
- ],
60
- ddn: {
61
- // you can override the default ddn config,
62
- // for example, dynamic auth credentials
63
- headers: {}
64
- }
65
+ // Start a new thread
66
+ const thread = await sdk.startThread({
67
+ message: 'What are the top 10 customers by revenue?',
68
+ });
69
+
70
+ console.log('Thread ID:', thread.thread_id);
71
+
72
+ // Stream events from the thread
73
+ sdk.streamThreadEventsByThreadId(thread.thread_id).subscribe({
74
+ next: (events) => {
75
+ events.forEach(event => {
76
+ console.log('Event:', event);
65
77
  });
78
+ },
79
+ error: (err) => console.error('Error:', err),
80
+ complete: () => console.log('Interaction complete'),
81
+ });
82
+ ```
66
83
 
67
- return response.
68
- }
84
+ #### Continue a Conversation
69
85
 
70
- runQuery('what can you do?').then((response) => {
71
- console.log(response)
86
+ ```typescript
87
+ // Send a follow-up message to an existing thread
88
+ const result = await sdk.sendMessageToThread({
89
+ threadId: 'existing-thread-id',
90
+ message: 'Now show me their average order value',
72
91
  });
92
+
93
+ // Stream the response
94
+ sdk.streamThreadEventsByThreadId(result.thread_id, result.thread_event_id)
95
+ .subscribe({
96
+ next: (events) => console.log('New events:', events),
97
+ });
73
98
  ```
74
99
 
75
- ## Reference
100
+ #### Wait until the final response only
76
101
 
77
- ### Version 2
102
+ Use the `lastValueFrom` function to wrap the subscription.
78
103
 
79
- #### Natural Language
104
+ ```typescript
105
+ import { PromptQLSdk } from '@hasura/promptql';
106
+ import { lastValueFrom } from "rxjs";
80
107
 
81
- The API version 2 simplifies request parameters:
82
- - The DDN URL is replaced by `build_version`.
83
- - `llm`, `ai_primitives_llm`, and `system_instructions` are removed.
108
+ // Initialize the SDK
109
+ const sdk = new PromptQLSdk({
110
+ projectId: 'your-project-id',
111
+ serviceAccountToken: 'your-service-account-token',
112
+ });
84
113
 
85
- To use the API v2, you need to create a PromptQL Client v2:
114
+ // Start a new thread
115
+ const thread = await sdk.startThread({
116
+ message: 'What are the top 10 customers by revenue?',
117
+ });
86
118
 
87
- ```ts
88
- import { createPromptQLClientV2 } from '@hasura/promptql';
119
+ console.log('Thread ID:', thread.thread_id);
89
120
 
90
- const client = createPromptQLClientV2({
91
- apiKey: '<your-promptql-api-key>',
92
- ddn: {
93
- // build_version: '<your-build-version>',
94
- headers: {
95
- 'Authorization': '<credential>'
96
- }
97
- },
121
+ const events = await lastValueFrom(
122
+ sdk.streamThreadEventsByThreadId(
123
+ result.thread_id,
124
+ ),
125
+ );
126
+
127
+ events.forEach(event => {
128
+ console.log('Event:', event);
129
+ });
130
+ ```
131
+
132
+ #### Print new events only
133
+
134
+ ```typescript
135
+ import { PromptQLSdk, diffThreadEvents } from '@hasura/promptql';
136
+ import { pairwise, map } from 'rxjs';
137
+
138
+ // Initialize the SDK
139
+ const sdk = new PromptQLSdk({
140
+ projectId: 'your-project-id',
141
+ serviceAccountToken: 'your-service-account-token',
142
+ });
143
+
144
+ // Start a new thread
145
+ const thread = await sdk.startThread({
146
+ message: 'What are the top 10 customers by revenue?',
147
+ });
148
+
149
+ console.log('Thread ID:', thread.thread_id);
150
+
151
+ // Stream events from the thread
152
+ sdk.streamThreadEventsByThreadId(thread.thread_id)
153
+ .pipe(
154
+ pairwise(),
155
+ map(([prev, curr]) => diffThreadEvents(prev, curr)),
156
+ )
157
+ .subscribe({
158
+ next: (events) => {
159
+ events.forEach(event => {
160
+ console.log('Event:', event);
161
+ });
162
+ },
163
+ error: (err) => console.error('Error:', err),
164
+ complete: () => console.log('Interaction complete'),
165
+ });
166
+ ```
167
+
168
+ ### Listing Threads
169
+
170
+ ```typescript
171
+ const threads = await sdk.getThreads({
172
+ limit: 20,
173
+ offset: 0,
174
+ order_by: [{ created_at: 'desc' }],
175
+ where: {
176
+ // Optional filters
177
+ },
178
+ });
179
+
180
+ threads.forEach(thread => {
181
+ console.log(`Thread ${thread.id}:`, thread.title);
98
182
  });
99
183
  ```
100
184
 
101
- ##### Non-Streaming
185
+ ### Get a Specific Thread
186
+
187
+ ```typescript
188
+ const thread = await sdk.getThreadById('thread-id');
189
+ console.log('Thread:', thread);
190
+ ```
102
191
 
103
- ```ts
104
- function query(
105
- body: PromptQLQueryRequestV2,
106
- queryOptions?: FetchOptions
107
- ) => Promise<QueryResponse>
192
+ ## Event Handling
193
+
194
+ ### Basics
195
+
196
+ The data structure of event data is the union of many event type. Each event type contains a different payload. You can go to the definition of `ThreadEventData` type to view the full data structure details.
197
+
198
+ The SDK also provides utility functions to parse different event types, for example, the following example catches and prints the query plan event and the final generated response:
199
+
200
+ ```typescript
201
+ import {
202
+ getAgentPlanGenerationStartedEvent,
203
+ getAgentPlanStepGeneratedEvent,
204
+ getAgentGeneratedResponse,
205
+ getUserMessageEvent,
206
+ } from '@hasura/promptql';
207
+
208
+ sdk.streamThreadEventsByThreadId(threadId).subscribe({
209
+ next: (events) => {
210
+ events.forEach(event => {
211
+ // Check for plan generation start
212
+ const planStart = getAgentPlanGenerationStartedEvent(event.event_data);
213
+ if (planStart) {
214
+ console.log('Query Plan:\n');
215
+ return;
216
+ }
217
+
218
+ // Check for plan steps
219
+ const planStep = getAgentPlanStepGeneratedEvent(event.event_data);
220
+ if (planStep) {
221
+ console.log(` - Step ${planStep.step_index}: ${planStep.step_title}\n`);
222
+ return;
223
+ }
224
+
225
+ // Check for final response
226
+ const response = getAgentGeneratedResponse(event.event_data);
227
+ if (response) {
228
+ const xmlRegex = /<\w+.*\/>/gm;
229
+ console.log('Response:', source.replaceAll(xmlRegex, response.response.message));
230
+ if (response.response.modified_artifacts) {
231
+ console.log('Artifacts:', response.response.modified_artifacts);
232
+ }
233
+ return;
234
+ }
235
+ });
236
+ },
237
+ });
108
238
  ```
109
239
 
110
- ##### Streaming
240
+ ### Handle XML tags in generated response message
241
+
242
+ The generated message may contains XML tags. They represents custom UI elements that the markdown text doesn't support. You should parse or remove them if they aren't required.
111
243
 
112
- ```ts
113
- function queryStream(
114
- body: PromptQLQueryRequestV2,
115
- callback?: (data: QueryResponseChunk) => void | Promise<void>,
116
- queryOptions?: FetchOptions
117
- ) Promise<Response>;
244
+ Common XML tags are:
245
+
246
+ - `<artifact type="table" identifier="last_5_products" />`: the identifier of the artifact block.
247
+ - `<user_mention id="user_id" />`: mentioned user in the chat message.
248
+ - `<user_group_mention id="group_id" />`: mentioned group in the chat message.
249
+ - `<promptql_mention />`: represents a `@promptql` tag in the chat message.
250
+
251
+ You can remove them using regular expressions or parse the message to XML elements for advanced format.
252
+
253
+ ```typescript
254
+ const xmlRegex = /<\w+.*\/>/gm;
255
+ console.log(source.replaceAll(xmlRegex, ""));
118
256
  ```
119
257
 
120
- #### Execute Program
258
+ ## Configuration Options
259
+
260
+ ```typescript
261
+ interface PromptQLSdkOptions {
262
+ // Required: Project ID from PromptQL console
263
+ projectId: string;
264
+
265
+ // Required: Service account token for authentication
266
+ serviceAccountToken: string;
267
+
268
+ // Optional: Base URL of PromptQL data plane
269
+ // Default: 'https://promptql.ddn.hasura.app'
270
+ promptqlBaseUrl?: string;
271
+
272
+ // Optional: Custom authentication host (for self-hosted control plane)
273
+ authHost?: string;
274
+
275
+ // Optional: Custom fetch implementation
276
+ fetch?: typeof fetch;
277
+
278
+ // Optional: Additional headers for all requests
279
+ headers?: Record<string, string>;
121
280
 
122
- Execute a PromptQL program with your data.
281
+ // Optional: IANA timezone for time-based queries
282
+ // Default: Client's timezone
283
+ timezone?: string;
123
284
 
124
- ```ts
125
- function executeProgram: (
126
- body: PromptQLExecuteRequestV2,
127
- executeOptions?: FetchOptions,
128
- ) => Promise<PromptQlExecutionResult>
285
+ // Optional: DDN build ID
286
+ // Default: Applied build
287
+ buildId?: string;
288
+ }
129
289
  ```
130
290
 
131
- ### Version 1
291
+ ## API Reference
292
+
293
+ ### Class: `PromptQLSdk`
294
+
295
+ #### Constructor
296
+
297
+ ```typescript
298
+ new PromptQLSdk(options: PromptQLSdkOptions)
299
+ ```
132
300
 
133
- #### Natural Language
301
+ #### Methods
134
302
 
135
- The [Natural Language Query API](https://hasura.io/docs/promptql/promptql-apis/natural-language-api/) allows you to interact with PromptQL directly, sending messages and receiving responses.
303
+ ##### `getThreads(variables)`
136
304
 
137
- ##### Non-Streaming
305
+ List threads with optional filtering and pagination.
138
306
 
139
- ```ts
140
- function query(
141
- body: PromptQLQueryRequestV1,
142
- queryOptions?: FetchOptions
143
- ) => Promise<QueryResponse>
307
+ ```typescript
308
+ getThreads(variables: GetThreadsQueryVariables): Promise<ThreadFragment[]>
144
309
  ```
145
310
 
146
- ##### Streaming
311
+ ##### `getThreadById(threadId)`
147
312
 
148
- The streaming response sends chunks of data in Server-Sent Events (SSE) format.
149
- If the callback isn't set the client returns the raw response and you need to handle the response manually.
313
+ Get a specific thread by ID.
150
314
 
151
- ```ts
152
- function queryStream(
153
- body: PromptQLQueryRequestV1,
154
- callback?: (data: QueryResponseChunk) => void | Promise<void>,
155
- queryOptions?: FetchOptions
156
- ) Promise<Response>;
315
+ ```typescript
316
+ getThreadById(threadId: string): Promise<ThreadFragment | null | undefined>
157
317
  ```
158
318
 
159
- Example:
319
+ ##### `startThread(variables)`
160
320
 
161
- ```ts
162
- client
163
- .queryStream({
164
- artifacts: [],
165
- interactions: [
166
- user_message: {
167
- text: 'what can you do?',
168
- }
169
- ],
170
- },
171
- async (chunk) => {
172
- console.log(chunk);
173
- },
174
- );
321
+ Start a new thread with a message.
322
+
323
+ ```typescript
324
+ startThread(variables: StartThreadArguments): Promise<StartThreadOutput>
175
325
  ```
176
326
 
177
- #### Execute Program
327
+ ##### `sendMessageToThread(variables)`
178
328
 
179
- Execute a PromptQL program with your data.
329
+ Send a message to an existing thread.
180
330
 
181
- ```ts
182
- function executeProgram: (
183
- body: PromptQLExecuteRequestV1,
184
- executeOptions?: FetchOptions,
185
- ) => Promise<PromptQlExecutionResult>
331
+ ```typescript
332
+ sendMessageToThread(variables: SendMessageToThreadArguments): Promise<SendMessageToThreadOutput>
186
333
  ```
187
334
 
188
- ## Development
335
+ ##### `subscribeThreadEventsByThreadId(threadId, threadEventId?)`
189
336
 
190
- ### Generate types
337
+ Subscribe to events from a thread. Continues indefinitely.
191
338
 
192
- Use the following command to update TypeScript types of PromptQL APIs from OpenAPI document.
339
+ ```typescript
340
+ subscribeThreadEventsByThreadId(
341
+ threadId: string,
342
+ threadEventId?: string | null
343
+ ): Observable<ThreadEvent[]>
344
+ ```
193
345
 
194
- ```bash
195
- npm run openapi:ts
346
+ ##### `streamThreadEventsByThreadId(threadId, threadEventId?)`
347
+
348
+ Stream events from a thread. Automatically completes when interaction finishes.
349
+
350
+ ```typescript
351
+ streamThreadEventsByThreadId(
352
+ threadId: string,
353
+ threadEventId?: string | null
354
+ ): Observable<ThreadEvent[]>
196
355
  ```
356
+
357
+ ## License
358
+
359
+ Apache License 2.0 - see [LICENSE](LICENSE) file for details.
360
+
361
+ ## Links
362
+
363
+ - [PromptQL Website](https://promptql.hasura.io)
364
+ - [PromptQL Console](https://promptql.console.hasura.io)
365
+ - [Hasura Documentation](https://hasura.io/docs)
366
+
367
+ ## Support
368
+
369
+ For support, please:
370
+
371
+ 1. Check the [documentation](https://promptql.hasura.io)
372
+ 2. Join the [Hasura Discord community](https://discord.gg/hasura)
package/biome.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.3.13/schema.json",
3
+ "root": false,
4
+ "files": {
5
+ "includes": ["**/*.ts", "**/*.gql", "!src/generated/*", "!dist/**/*"]
6
+ },
7
+ "extends": ["@hasura/biome-config/base"]
8
+ }
package/package.json CHANGED
@@ -1,55 +1,46 @@
1
1
  {
2
- "name": "@hasura/promptql",
3
- "description": "A Node.js SDK allows you to interact with PromptQL API",
4
- "version": "1.0.0",
5
- "license": "Apache-2.0",
6
- "publishConfig": {
7
- "access": "public"
8
- },
9
- "main": "./dist/index.js",
10
- "module": "./dist/index.js",
11
- "types": "./dist/index.d.ts",
12
- "author": "Hasura",
13
- "homepage": "https://promptql.hasura.io",
14
- "repository": {
15
- "type": "git",
16
- "url": "git+https://github.com/hasura/promptql-nodejs-sdk.git"
17
- },
18
- "bugs": {
19
- "url": "https://github.com/hasura/promptql-nodejs-sdk/issues"
20
- },
21
- "keywords": [
22
- "promptql",
23
- "api",
24
- "typescript"
25
- ],
26
- "scripts": {
27
- "copy-files": "cp ./src/promptql.d.ts ./dist/promptql.d.ts",
28
- "build": "tsc && vite build && npm run copy-files",
29
- "release": "npm run test && changelogen --release --push && npm publish",
30
- "lint": "biome check",
31
- "lint:fix": "biome check --write",
32
- "format": "biome format --write",
33
- "test": "vitest --run",
34
- "test:coverage": "vitest --coverage",
35
- "prepublishOnly": "npm run build",
36
- "openapi:ts": "openapi-typescript https://api.promptql.pro.hasura.io/openapi.json --export-type --root-types-no-schema-prefix --root-types -o ./src/promptql.d.ts"
37
- },
38
- "files": [
39
- "dist/**/*"
40
- ],
41
- "dependencies": {
42
- "@opentelemetry/api": "*"
43
- },
44
- "devDependencies": {
45
- "@biomejs/biome": "1.9.4",
46
- "@types/node": "^25.0.10",
47
- "@vitest/coverage-v8": "^4.0.18",
48
- "changelogen": "^0.6.2",
49
- "openapi-typescript": "^7.10.1",
50
- "typescript": "^5.9.3",
51
- "vite": "^7.3.1",
52
- "vite-plugin-dts": "^4.5.4",
53
- "vitest": "^4.0.18"
54
- }
2
+ "name": "@hasura/promptql",
3
+ "description": "A Typescript SDK allows you to interact with PromptQL API",
4
+ "version": "2.0.0-alpha.1",
5
+ "license": "Apache-2.0",
6
+ "author": "Hasura",
7
+ "homepage": "https://promptql.hasura.io",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/hasura/promptql-typescript-sdk.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/hasura/promptql-typescript-sdk/issues"
14
+ },
15
+ "keywords": [
16
+ "promptql",
17
+ "api",
18
+ "typescript"
19
+ ],
20
+ "main": "./dist/index.js",
21
+ "module": "./dist/index.mjs",
22
+ "types": "./dist/index.d.ts",
23
+ "scripts": {
24
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
25
+ "build": "tsup src/index.ts --format cjs,esm --dts",
26
+ "test": "bun test",
27
+ "lint": "biome check .",
28
+ "format": "biome check . --write",
29
+ "check-types": "tsc --noEmit"
30
+ },
31
+ "devDependencies": {
32
+ "@hasura/biome-config": "workspace:*",
33
+ "@hasura/typescript-config": "workspace:*",
34
+ "@types/bun": "latest",
35
+ "@types/node": "^25.1.0",
36
+ "tsup": "^8.5.1",
37
+ "typescript": "5.9.3"
38
+ },
39
+ "dependencies": {
40
+ "@apollo/client": "^4.1.3",
41
+ "@graphql-typed-document-node/core": "^3.2.0",
42
+ "graphql": "^16.12.0",
43
+ "graphql-ws": "^6.0.7",
44
+ "rxjs": "^7.8.2"
45
+ }
55
46
  }
@@ -0,0 +1,24 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { createPromptQLAuthTokenGenerator } from "./auth";
3
+
4
+ describe("fetchPromptQLAuthToken", () => {
5
+ const promptqlProjectId = process.env.PROMPTQL_PROJECT_ID;
6
+ const serviceAccountToken = process.env.PROMPTQL_SERVICE_ACCOUNT_TOKEN;
7
+ if (!serviceAccountToken || !promptqlProjectId) {
8
+ return;
9
+ }
10
+
11
+ const fetchAuthToken = createPromptQLAuthTokenGenerator({
12
+ authHost: process.env.HASURA_AUTH_HOST,
13
+ projectId: promptqlProjectId,
14
+ promptqlGraphQLUrl: `${process.env.PROMPTQL_BASE_URL}/playground-v2-hge/v1/graphql`,
15
+ serviceAccountToken,
16
+ });
17
+
18
+ test("should fetch promptql jwt token successfully", async () => {
19
+ const token = await fetchAuthToken();
20
+ expect(token).toStartWith("eyJh");
21
+ const token2 = await fetchAuthToken();
22
+ expect(token).toEqual(token2);
23
+ });
24
+ });