@fayz-ai/sdk 0.1.0

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 (50) hide show
  1. package/dist/app-params.cjs +16 -0
  2. package/dist/app-params.cjs.map +1 -0
  3. package/dist/app-params.d.ts +4 -0
  4. package/dist/app-params.d.ts.map +1 -0
  5. package/dist/app-params.js +3 -0
  6. package/dist/app-params.js.map +1 -0
  7. package/dist/chunk-ENWSXKQE.cjs +125 -0
  8. package/dist/chunk-ENWSXKQE.cjs.map +1 -0
  9. package/dist/chunk-FRIOW6KW.js +122 -0
  10. package/dist/chunk-FRIOW6KW.js.map +1 -0
  11. package/dist/chunk-O6XSRB3Q.js +77 -0
  12. package/dist/chunk-O6XSRB3Q.js.map +1 -0
  13. package/dist/chunk-REGBJXXB.cjs +81 -0
  14. package/dist/chunk-REGBJXXB.cjs.map +1 -0
  15. package/dist/chunk-YGX37DT3.js +65 -0
  16. package/dist/chunk-YGX37DT3.js.map +1 -0
  17. package/dist/chunk-ZMHI2XGY.cjs +68 -0
  18. package/dist/chunk-ZMHI2XGY.cjs.map +1 -0
  19. package/dist/client.cjs +22 -0
  20. package/dist/client.cjs.map +1 -0
  21. package/dist/client.d.ts +36 -0
  22. package/dist/client.d.ts.map +1 -0
  23. package/dist/client.js +5 -0
  24. package/dist/client.js.map +1 -0
  25. package/dist/index.cjs +38 -0
  26. package/dist/index.cjs.map +1 -0
  27. package/dist/index.d.ts +7 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +5 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/runtime.cjs +16 -0
  32. package/dist/runtime.cjs.map +1 -0
  33. package/dist/runtime.d.ts +96 -0
  34. package/dist/runtime.d.ts.map +1 -0
  35. package/dist/runtime.js +3 -0
  36. package/dist/runtime.js.map +1 -0
  37. package/dist/types.cjs +4 -0
  38. package/dist/types.cjs.map +1 -0
  39. package/dist/types.d.ts +63 -0
  40. package/dist/types.d.ts.map +1 -0
  41. package/dist/types.js +3 -0
  42. package/dist/types.js.map +1 -0
  43. package/package.json +67 -0
  44. package/src/app-params.ts +69 -0
  45. package/src/client.test.ts +41 -0
  46. package/src/client.ts +103 -0
  47. package/src/index.ts +28 -0
  48. package/src/runtime.test.ts +123 -0
  49. package/src/runtime.ts +211 -0
  50. package/src/types.ts +67 -0
package/src/client.ts ADDED
@@ -0,0 +1,103 @@
1
+ import { appParams } from './app-params'
2
+ import { createFayzRuntimeClient } from './runtime'
3
+ import type { FayzAuthMeResponse, FayzUser } from './types'
4
+
5
+ export interface FayzClientOptions {
6
+ baseUrl?: string
7
+ token?: string | (() => string | undefined | Promise<string | undefined>)
8
+ appId?: string
9
+ fetcher?: typeof fetch
10
+ }
11
+
12
+ export interface FayzRequestOptions extends Omit<RequestInit, 'headers'> {
13
+ headers?: Record<string, string>
14
+ token?: string
15
+ }
16
+
17
+ export class FayzApiError extends Error {
18
+ constructor(
19
+ message: string,
20
+ readonly status: number,
21
+ readonly responseBody?: unknown,
22
+ ) {
23
+ super(message)
24
+ this.name = 'FayzApiError'
25
+ }
26
+ }
27
+
28
+ function normalizeBaseUrl(baseUrl: string): string {
29
+ return baseUrl.replace(/\/+$/, '')
30
+ }
31
+
32
+ function apiPath(path: string): string {
33
+ if (/^https?:\/\//.test(path)) return path
34
+ const normalized = path.startsWith('/') ? path : `/${path}`
35
+ return normalized.startsWith('/api/') ? normalized : `/api${normalized}`
36
+ }
37
+
38
+ async function parseResponse<T>(response: Response): Promise<T> {
39
+ if (response.status === 204) return undefined as T
40
+
41
+ const text = await response.text()
42
+ let body: unknown
43
+ try {
44
+ body = text ? JSON.parse(text) : undefined
45
+ } catch {
46
+ body = text
47
+ }
48
+
49
+ if (!response.ok) {
50
+ const message = typeof body === 'object' && body
51
+ ? String((body as { message?: unknown; error?: unknown }).message ?? (body as { error?: unknown }).error ?? `Fayz API request failed with status ${response.status}`)
52
+ : `Fayz API request failed with status ${response.status}`
53
+ throw new FayzApiError(message, response.status, body)
54
+ }
55
+
56
+ return body as T
57
+ }
58
+
59
+ async function resolveToken(token: FayzClientOptions['token']): Promise<string | undefined> {
60
+ return typeof token === 'function' ? token() : token
61
+ }
62
+
63
+ function unwrapUser(body: FayzUser | FayzAuthMeResponse): FayzUser {
64
+ return typeof body === 'object' && body && 'user' in body
65
+ ? (body as FayzAuthMeResponse).user
66
+ : body as FayzUser
67
+ }
68
+
69
+ export function createFayzClient(options: FayzClientOptions = {}) {
70
+ const baseUrl = normalizeBaseUrl(options.baseUrl ?? appParams.apiBaseUrl)
71
+ const fetcher = options.fetcher ?? fetch
72
+ const appId = options.appId ?? appParams.appId
73
+ const token = options.token ?? appParams.token
74
+
75
+ async function request<T>(path: string, init: FayzRequestOptions = {}): Promise<T> {
76
+ const requestToken = init.token ?? await resolveToken(token)
77
+ const headers: Record<string, string> = {
78
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
79
+ ...(appId ? { 'X-App-Id': appId } : {}),
80
+ ...init.headers,
81
+ ...(requestToken ? { Authorization: `Bearer ${requestToken}` } : {}),
82
+ }
83
+ const response = await fetcher(`${baseUrl}${apiPath(path)}`, {
84
+ ...init,
85
+ headers,
86
+ })
87
+ return parseResponse<T>(response)
88
+ }
89
+
90
+ return {
91
+ request,
92
+ auth: {
93
+ async me(): Promise<FayzUser> {
94
+ return unwrapUser(await request<FayzUser | FayzAuthMeResponse>('/auth/me'))
95
+ },
96
+ },
97
+ runtime: {
98
+ createClient: createFayzRuntimeClient,
99
+ },
100
+ }
101
+ }
102
+
103
+ export const fayz = createFayzClient()
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ export { appParams, resolveAppParams } from './app-params'
2
+ export { createFayzClient, fayz, FayzApiError } from './client'
3
+ export type { FayzClientOptions, FayzRequestOptions } from './client'
4
+ export {
5
+ createFayzRuntimeClient,
6
+ FayzRuntimeError,
7
+ } from './runtime'
8
+ export type {
9
+ FayzRuntimeClientOptions,
10
+ FayzRuntimeEnvironment,
11
+ GoogleCalendarEvent,
12
+ GoogleCalendarEventInput,
13
+ GoogleCalendarEventTime,
14
+ ListGoogleCalendarEventsInput,
15
+ PluginOAuthExchangeInput,
16
+ PluginOAuthExchangeResponse,
17
+ RuntimePluginOAuthGrant,
18
+ } from './runtime'
19
+ export type {
20
+ AppManifest,
21
+ FayzApiErrorBody,
22
+ FayzAppParams,
23
+ FayzAuthMeResponse,
24
+ FayzUser,
25
+ PageManifest,
26
+ PluginRef,
27
+ SurfaceManifest,
28
+ } from './types'
@@ -0,0 +1,123 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import {
3
+ createFayzRuntimeClient,
4
+ FayzRuntimeError,
5
+ } from './runtime'
6
+
7
+ function jsonResponse(body: unknown, status = 200): Response {
8
+ return new Response(JSON.stringify(body), {
9
+ status,
10
+ headers: { 'Content-Type': 'application/json' },
11
+ })
12
+ }
13
+
14
+ describe('createFayzRuntimeClient', () => {
15
+ it('exchanges runtime-data tokens for broker tokens without sending provider credentials', async () => {
16
+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse({
17
+ token: 'broker-token',
18
+ tokenType: 'Bearer',
19
+ expiresIn: 300,
20
+ projectId: 'project-1',
21
+ tenantKey: 'tenant-a',
22
+ environment: 'preview',
23
+ pluginId: '@fayz/plugin-agenda',
24
+ grants: [{ grantId: 'grant-1', provider: 'google-calendar', scopes: ['calendar.read'] }],
25
+ }))
26
+ const client = createFayzRuntimeClient({
27
+ baseUrl: 'https://api.fayz.ai/',
28
+ projectId: 'project-1',
29
+ runtimeToken: 'runtime-token',
30
+ fetcher,
31
+ })
32
+
33
+ const response = await client.exchangePluginOAuth({
34
+ pluginId: '@fayz/plugin-agenda',
35
+ scopes: ['calendar.read'],
36
+ })
37
+
38
+ expect(response.token).toBe('broker-token')
39
+ expect(fetcher).toHaveBeenCalledWith(
40
+ 'https://api.fayz.ai/api/v1/runtime/projects/project-1/oauth/exchange',
41
+ expect.objectContaining({
42
+ method: 'POST',
43
+ headers: expect.objectContaining({
44
+ Authorization: 'Bearer runtime-token',
45
+ 'Content-Type': 'application/json',
46
+ }),
47
+ body: JSON.stringify({
48
+ pluginId: '@fayz/plugin-agenda',
49
+ environment: 'preview',
50
+ scopes: ['calendar.read'],
51
+ }),
52
+ }),
53
+ )
54
+ expect(JSON.stringify(fetcher.mock.calls)).not.toContain('clientSecret')
55
+ expect(JSON.stringify(fetcher.mock.calls)).not.toContain('refreshToken')
56
+ expect(JSON.stringify(fetcher.mock.calls)).not.toContain('accessToken')
57
+ })
58
+
59
+ it('calls Google Calendar broker routes with the short-lived plugin OAuth token', async () => {
60
+ const fetcher = vi.fn<typeof fetch>()
61
+ .mockResolvedValueOnce(jsonResponse({ provider: 'google-calendar', calendarId: 'primary', events: [] }))
62
+ .mockResolvedValueOnce(jsonResponse({ provider: 'google-calendar', calendarId: 'primary', event: { id: 'event-1' } }, 201))
63
+ .mockResolvedValueOnce(jsonResponse({ provider: 'google-calendar', calendarId: 'primary', event: { id: 'event-1' } }))
64
+ .mockResolvedValueOnce(new Response(null, { status: 204 }))
65
+ const client = createFayzRuntimeClient({
66
+ baseUrl: 'https://api.fayz.ai',
67
+ projectId: 'project-1',
68
+ runtimeToken: 'runtime-token',
69
+ fetcher,
70
+ })
71
+ const calendar = client.googleCalendar('broker-token')
72
+
73
+ await calendar.listEvents({
74
+ calendarId: 'primary',
75
+ timeMin: '2026-06-14T00:00:00.000Z',
76
+ timeMax: '2026-06-15T00:00:00.000Z',
77
+ maxResults: 25,
78
+ })
79
+ await calendar.createEvent('primary', {
80
+ summary: 'Haircut',
81
+ start: { dateTime: '2026-06-14T09:00:00.000Z' },
82
+ end: { dateTime: '2026-06-14T09:30:00.000Z' },
83
+ })
84
+ await calendar.updateEvent('primary', 'event-1', { summary: 'Updated haircut' })
85
+ await calendar.deleteEvent('primary', 'event-1')
86
+
87
+ expect(fetcher.mock.calls[0][0]).toBe(
88
+ 'https://api.fayz.ai/api/v1/runtime/projects/project-1/oauth/google-calendar/events?calendarId=primary&timeMin=2026-06-14T00%3A00%3A00.000Z&timeMax=2026-06-15T00%3A00%3A00.000Z&maxResults=25',
89
+ )
90
+ expect(fetcher.mock.calls[1][0]).toBe(
91
+ 'https://api.fayz.ai/api/v1/runtime/projects/project-1/oauth/google-calendar/events?calendarId=primary',
92
+ )
93
+ expect(fetcher.mock.calls[2][0]).toBe(
94
+ 'https://api.fayz.ai/api/v1/runtime/projects/project-1/oauth/google-calendar/events/event-1?calendarId=primary',
95
+ )
96
+ expect(fetcher.mock.calls[3][0]).toBe(
97
+ 'https://api.fayz.ai/api/v1/runtime/projects/project-1/oauth/google-calendar/events/event-1?calendarId=primary',
98
+ )
99
+ expect(fetcher.mock.calls[0][1]).toEqual(expect.objectContaining({
100
+ headers: expect.objectContaining({ Authorization: 'Bearer broker-token' }),
101
+ }))
102
+ expect(fetcher.mock.calls[1][1]).toEqual(expect.objectContaining({ method: 'POST' }))
103
+ expect(fetcher.mock.calls[2][1]).toEqual(expect.objectContaining({ method: 'PATCH' }))
104
+ expect(fetcher.mock.calls[3][1]).toEqual(expect.objectContaining({ method: 'DELETE' }))
105
+ })
106
+
107
+ it('keeps non-json upstream errors debuggable', async () => {
108
+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response('upstream unavailable', { status: 502 }))
109
+ const client = createFayzRuntimeClient({
110
+ baseUrl: 'https://api.fayz.ai',
111
+ projectId: 'project-1',
112
+ runtimeToken: 'runtime-token',
113
+ fetcher,
114
+ })
115
+
116
+ await expect(client.exchangePluginOAuth({ pluginId: '@fayz/plugin-agenda' }))
117
+ .rejects.toMatchObject({
118
+ name: 'FayzRuntimeError',
119
+ status: 502,
120
+ responseBody: 'upstream unavailable',
121
+ } satisfies Partial<FayzRuntimeError>)
122
+ })
123
+ })
package/src/runtime.ts ADDED
@@ -0,0 +1,211 @@
1
+ export interface FayzRuntimeClientOptions {
2
+ baseUrl: string
3
+ projectId: string
4
+ runtimeToken: string
5
+ fetcher?: typeof fetch
6
+ }
7
+
8
+ export type FayzRuntimeEnvironment = 'preview' | 'production'
9
+
10
+ export interface PluginOAuthExchangeInput {
11
+ pluginId: string
12
+ environment?: FayzRuntimeEnvironment
13
+ scopes?: string[]
14
+ }
15
+
16
+ export interface RuntimePluginOAuthGrant {
17
+ grantId: string
18
+ provider: string
19
+ scopes: string[]
20
+ }
21
+
22
+ export interface PluginOAuthExchangeResponse {
23
+ token: string
24
+ tokenType: 'Bearer'
25
+ expiresIn: number
26
+ projectId: string
27
+ tenantKey: string
28
+ environment: FayzRuntimeEnvironment
29
+ pluginId: string
30
+ grants: RuntimePluginOAuthGrant[]
31
+ }
32
+
33
+ export interface GoogleCalendarEventTime {
34
+ dateTime: string
35
+ timeZone?: string
36
+ }
37
+
38
+ export interface GoogleCalendarEventInput {
39
+ summary: string
40
+ description?: string
41
+ location?: string
42
+ start: GoogleCalendarEventTime
43
+ end: GoogleCalendarEventTime
44
+ attendees?: Array<{ email: string }>
45
+ }
46
+
47
+ export interface GoogleCalendarEvent {
48
+ id: string
49
+ summary?: string
50
+ description?: string
51
+ location?: string
52
+ start: { dateTime?: string; date?: string; timeZone?: string }
53
+ end: { dateTime?: string; date?: string; timeZone?: string }
54
+ status?: string
55
+ htmlLink?: string
56
+ [key: string]: unknown
57
+ }
58
+
59
+ export interface ListGoogleCalendarEventsInput {
60
+ calendarId: string
61
+ timeMin?: string
62
+ timeMax?: string
63
+ maxResults?: number
64
+ q?: string
65
+ }
66
+
67
+ export class FayzRuntimeError extends Error {
68
+ constructor(
69
+ message: string,
70
+ readonly status: number,
71
+ readonly responseBody?: unknown,
72
+ ) {
73
+ super(message)
74
+ this.name = 'FayzRuntimeError'
75
+ }
76
+ }
77
+
78
+ function normalizeBaseUrl(baseUrl: string): string {
79
+ return baseUrl.replace(/\/+$/, '')
80
+ }
81
+
82
+ function assertRequired(value: string, field: string): string {
83
+ const normalized = value.trim()
84
+ if (!normalized) throw new Error(`${field} is required`)
85
+ return normalized
86
+ }
87
+
88
+ function runtimePath(projectId: string, suffix: string): string {
89
+ return `/api/v1/runtime/projects/${encodeURIComponent(projectId)}${suffix}`
90
+ }
91
+
92
+ function queryString(params: Record<string, string | number | undefined>): string {
93
+ const search = new URLSearchParams()
94
+ for (const [key, value] of Object.entries(params)) {
95
+ if (value !== undefined && value !== '') search.set(key, String(value))
96
+ }
97
+ const value = search.toString()
98
+ return value ? `?${value}` : ''
99
+ }
100
+
101
+ async function parseResponse<T>(response: Response): Promise<T> {
102
+ if (response.status === 204) return undefined as T
103
+
104
+ const text = await response.text()
105
+ let body: unknown
106
+ try {
107
+ body = text ? JSON.parse(text) : undefined
108
+ } catch {
109
+ body = text
110
+ }
111
+
112
+ if (!response.ok) {
113
+ const message = typeof body === 'object' && body && 'message' in body
114
+ ? String((body as { message: unknown }).message)
115
+ : `Fayz runtime request failed with status ${response.status}`
116
+ throw new FayzRuntimeError(message, response.status, body)
117
+ }
118
+
119
+ return body as T
120
+ }
121
+
122
+ export function createFayzRuntimeClient(options: FayzRuntimeClientOptions) {
123
+ const baseUrl = normalizeBaseUrl(assertRequired(options.baseUrl, 'baseUrl'))
124
+ const projectId = assertRequired(options.projectId, 'projectId')
125
+ const runtimeToken = assertRequired(options.runtimeToken, 'runtimeToken')
126
+ const fetcher = options.fetcher ?? fetch
127
+
128
+ async function request<T>(
129
+ path: string,
130
+ token: string,
131
+ init: Omit<RequestInit, 'headers'> & { headers?: Record<string, string> } = {},
132
+ ): Promise<T> {
133
+ const response = await fetcher(`${baseUrl}${path}`, {
134
+ ...init,
135
+ headers: {
136
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
137
+ ...init.headers,
138
+ Authorization: `Bearer ${token}`,
139
+ },
140
+ })
141
+ return parseResponse<T>(response)
142
+ }
143
+
144
+ async function exchangePluginOAuth(input: PluginOAuthExchangeInput): Promise<PluginOAuthExchangeResponse> {
145
+ return request<PluginOAuthExchangeResponse>(
146
+ runtimePath(projectId, '/oauth/exchange'),
147
+ runtimeToken,
148
+ {
149
+ method: 'POST',
150
+ body: JSON.stringify({
151
+ pluginId: input.pluginId,
152
+ environment: input.environment ?? 'preview',
153
+ ...(input.scopes ? { scopes: input.scopes } : {}),
154
+ }),
155
+ },
156
+ )
157
+ }
158
+
159
+ function googleCalendar(pluginOAuthToken: string) {
160
+ const brokerToken = assertRequired(pluginOAuthToken, 'pluginOAuthToken')
161
+ const eventsPath = runtimePath(projectId, '/oauth/google-calendar/events')
162
+
163
+ return {
164
+ listEvents(input: ListGoogleCalendarEventsInput) {
165
+ const calendarId = assertRequired(input.calendarId, 'calendarId')
166
+ return request<{
167
+ provider: 'google-calendar'
168
+ calendarId: string
169
+ timeMin: string
170
+ timeMax: string
171
+ events: GoogleCalendarEvent[]
172
+ }>(
173
+ `${eventsPath}${queryString({
174
+ calendarId,
175
+ timeMin: input.timeMin,
176
+ timeMax: input.timeMax,
177
+ maxResults: input.maxResults,
178
+ q: input.q,
179
+ })}`,
180
+ brokerToken,
181
+ )
182
+ },
183
+ createEvent(calendarId: string, event: GoogleCalendarEventInput) {
184
+ return request<{ provider: 'google-calendar'; calendarId: string; event: GoogleCalendarEvent }>(
185
+ `${eventsPath}${queryString({ calendarId: assertRequired(calendarId, 'calendarId') })}`,
186
+ brokerToken,
187
+ { method: 'POST', body: JSON.stringify(event) },
188
+ )
189
+ },
190
+ updateEvent(calendarId: string, eventId: string, updates: Partial<GoogleCalendarEventInput>) {
191
+ return request<{ provider: 'google-calendar'; calendarId: string; event: GoogleCalendarEvent }>(
192
+ `${eventsPath}/${encodeURIComponent(assertRequired(eventId, 'eventId'))}${queryString({ calendarId: assertRequired(calendarId, 'calendarId') })}`,
193
+ brokerToken,
194
+ { method: 'PATCH', body: JSON.stringify(updates) },
195
+ )
196
+ },
197
+ deleteEvent(calendarId: string, eventId: string) {
198
+ return request<void>(
199
+ `${eventsPath}/${encodeURIComponent(assertRequired(eventId, 'eventId'))}${queryString({ calendarId: assertRequired(calendarId, 'calendarId') })}`,
200
+ brokerToken,
201
+ { method: 'DELETE' },
202
+ )
203
+ },
204
+ }
205
+ }
206
+
207
+ return {
208
+ exchangePluginOAuth,
209
+ googleCalendar,
210
+ }
211
+ }
package/src/types.ts ADDED
@@ -0,0 +1,67 @@
1
+ export type FayzRuntimeEnvironment = 'preview' | 'production'
2
+
3
+ export interface FayzUser {
4
+ id: string
5
+ email?: string | null
6
+ name?: string | null
7
+ avatarUrl?: string | null
8
+ isGuest?: boolean
9
+ createdAt?: string
10
+ updatedAt?: string
11
+ [key: string]: unknown
12
+ }
13
+
14
+ export interface FayzAuthMeResponse {
15
+ user: FayzUser
16
+ impersonation?: unknown
17
+ }
18
+
19
+ export interface FayzApiErrorBody {
20
+ message?: string
21
+ error?: string
22
+ code?: string
23
+ [key: string]: unknown
24
+ }
25
+
26
+ export interface FayzAppParams {
27
+ appId?: string
28
+ apiBaseUrl: string
29
+ token?: string
30
+ projectId?: string
31
+ environment: FayzRuntimeEnvironment
32
+ }
33
+
34
+ export interface AppManifest {
35
+ manifestVersion: number
36
+ id: string
37
+ name: string
38
+ backend?: { provider?: string; [key: string]: unknown }
39
+ locale?: Record<string, unknown>
40
+ theme?: Record<string, unknown>
41
+ permissions?: Record<string, unknown>
42
+ billing?: Record<string, unknown>
43
+ entities?: unknown[]
44
+ surfaces?: Record<string, SurfaceManifest>
45
+ [key: string]: unknown
46
+ }
47
+
48
+ export interface SurfaceManifest {
49
+ scaffold: string
50
+ options?: Record<string, unknown>
51
+ plugins?: PluginRef[]
52
+ pages?: PageManifest[]
53
+ [key: string]: unknown
54
+ }
55
+
56
+ export interface PluginRef {
57
+ id: string
58
+ config?: Record<string, unknown>
59
+ }
60
+
61
+ export interface PageManifest {
62
+ path: string
63
+ label?: string
64
+ component?: string
65
+ blocks?: unknown[]
66
+ [key: string]: unknown
67
+ }