twenty-client-sdk 0.8.0-canary.3

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.
@@ -0,0 +1,3 @@
1
+ export declare class CoreApiClient {
2
+ constructor();
3
+ }
@@ -0,0 +1 @@
1
+ export type CoreSchema = {};
@@ -0,0 +1,2 @@
1
+ export { CoreApiClient } from './generated/index';
2
+ export * as CoreSchema from './generated/schema';
package/dist/core.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class e{constructor(){throw new Error("CoreApiClient was not generated. Install this app on a Twenty instance or run `twenty app:dev`.")}}const t=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));exports.CoreApiClient=e;exports.CoreSchema=t;
package/dist/core.mjs ADDED
@@ -0,0 +1,14 @@
1
+ class t {
2
+ constructor() {
3
+ throw new Error(
4
+ "CoreApiClient was not generated. Install this app on a Twenty instance or run `twenty app:dev`."
5
+ );
6
+ }
7
+ }
8
+ const o = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
9
+ __proto__: null
10
+ }, Symbol.toStringTag, { value: "Module" }));
11
+ export {
12
+ t as CoreApiClient,
13
+ o as CoreSchema
14
+ };
@@ -0,0 +1,7 @@
1
+ type ClientWrapperOptions = {
2
+ apiClientName: string;
3
+ defaultUrl: string;
4
+ includeUploadFile: boolean;
5
+ };
6
+ export declare const buildClientWrapperSource: (templateSource: string, options: ClientWrapperOptions) => string;
7
+ export {};
@@ -0,0 +1,4 @@
1
+ export declare const ensureDir: (dirPath: string) => Promise<string | undefined>;
2
+ export declare const emptyDir: (dirPath: string) => Promise<void>;
3
+ export declare const move: (src: string, dest: string) => Promise<void>;
4
+ export declare const remove: (filePath: string) => Promise<void>;
@@ -0,0 +1,10 @@
1
+ export declare const GENERATED_CORE_DIR = "core/generated";
2
+ export declare const generateCoreClientFromSchema: ({ schema, outputPath, clientWrapperTemplateSource, }: {
3
+ schema: string;
4
+ outputPath: string;
5
+ clientWrapperTemplateSource?: string | undefined;
6
+ }) => Promise<void>;
7
+ export declare const replaceCoreClient: ({ packageRoot, schema, }: {
8
+ packageRoot: string;
9
+ schema: string;
10
+ }) => Promise<void>;
@@ -0,0 +1,5 @@
1
+ export declare const generateMetadataClient: ({ schema, outputPath, clientWrapperTemplateSource, }: {
2
+ schema: string;
3
+ outputPath: string;
4
+ clientWrapperTemplateSource?: string | undefined;
5
+ }) => Promise<void>;
@@ -0,0 +1,2 @@
1
+ export { GENERATED_CORE_DIR, generateCoreClientFromSchema, replaceCoreClient, } from './generate-core-client';
2
+ export { generateMetadataClient } from './generate-metadata-client';
@@ -0,0 +1,42 @@
1
+ type QueryGenqlSelection = Record<string, unknown>;
2
+ type MutationGenqlSelection = Record<string, unknown>;
3
+ type GraphqlOperation = Record<string, unknown>;
4
+ type ClientOptions = {
5
+ url?: string;
6
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
7
+ fetcher?: (operation: GraphqlOperation | GraphqlOperation[]) => Promise<unknown>;
8
+ fetch?: typeof globalThis.fetch;
9
+ batch?: unknown;
10
+ };
11
+ type TwentyGeneratedClientOptions = ClientOptions;
12
+ export declare class TwentyGeneratedClient {
13
+ private client;
14
+ private url;
15
+ private requestOptions;
16
+ private headers;
17
+ private fetchImplementation;
18
+ private authorizationToken;
19
+ private refreshAccessTokenPromise;
20
+ constructor(options?: TwentyGeneratedClientOptions);
21
+ query<R extends QueryGenqlSelection>(request: R & {
22
+ __name?: string;
23
+ }): Promise<unknown>;
24
+ mutation<R extends MutationGenqlSelection>(request: R & {
25
+ __name?: string;
26
+ }): Promise<unknown>;
27
+ uploadFile(fileBuffer: Buffer, filename: string, contentType: string | undefined, fieldMetadataUniversalIdentifier: string): Promise<{
28
+ id: string;
29
+ path: string;
30
+ size: number;
31
+ createdAt: string;
32
+ url: string;
33
+ }>;
34
+ private executeGraphqlRequestWithOptionalRefresh;
35
+ private executeGraphqlRequest;
36
+ private resolveHeaders;
37
+ private shouldRefreshToken;
38
+ private assertResponseIsSuccessful;
39
+ private requestRefreshedAccessToken;
40
+ private setAuthorizationToken;
41
+ }
42
+ export {};
@@ -0,0 +1,440 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const r=require("node:fs/promises"),s=require("node:path"),h=require("@genql/cli"),c=require("esbuild"),f="TWENTY_API_URL",q="// __STRIPPED_DURING_INJECTION_START__",w="// __STRIPPED_DURING_INJECTION_END__",u="// __UPLOAD_FILE_START__",d="// __UPLOAD_FILE_END__",o=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),m=(n,t)=>{let e=n;return e=e.replace(new RegExp(`${o(q)}[\\s\\S]*?${o(w)}\\n?`),""),e=e.replace("'__TWENTY_DEFAULT_URL__'",t.defaultUrl),e=e.replace(/TwentyGeneratedClient/g,t.apiClientName),t.includeUploadFile?(e=e.replace(new RegExp(`\\s*${o(u)}\\n`),`
2
+ `),e=e.replace(new RegExp(`\\s*${o(d)}\\n`),`
3
+ `)):e=e.replace(new RegExp(`\\s*${o(u)}[\\s\\S]*?${o(d)}\\n?`),`
4
+ `),`
5
+ // ${t.apiClientName} (auto-injected by twenty-client-sdk)
6
+ ${e}`},y=n=>r.mkdir(n,{recursive:!0}),_=async n=>{let t;try{t=await r.readdir(n)}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT"){await r.mkdir(n,{recursive:!0});return}throw e}await Promise.all(t.map(e=>r.rm(s.join(n,e),{recursive:!0,force:!0})))},A=async(n,t)=>{try{await r.rename(n,t)}catch(e){if(e instanceof Error&&"code"in e&&e.code==="EXDEV")await r.cp(n,t,{recursive:!0}),await r.rm(n,{recursive:!0,force:!0});else throw e}},p=n=>r.rm(n,{recursive:!0,force:!0}),T=`// Ambient type stubs for the genql-generated code this template gets
7
+ // injected into. They enable full typecheck/lint on this file.
8
+ // __STRIPPED_DURING_INJECTION_START__
9
+ type QueryGenqlSelection = Record<string, unknown>;
10
+ type MutationGenqlSelection = Record<string, unknown>;
11
+ type GraphqlOperation = Record<string, unknown>;
12
+
13
+ type ClientOptions = {
14
+ url?: string;
15
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
16
+ fetcher?: (
17
+ operation: GraphqlOperation | GraphqlOperation[],
18
+ ) => Promise<unknown>;
19
+ fetch?: typeof globalThis.fetch;
20
+ batch?: unknown;
21
+ };
22
+
23
+ type Client = {
24
+ query: (
25
+ request: QueryGenqlSelection & { __name?: string },
26
+ ) => Promise<unknown>;
27
+ mutation: (
28
+ request: MutationGenqlSelection & { __name?: string },
29
+ ) => Promise<unknown>;
30
+ };
31
+
32
+ declare function createClient(options: ClientOptions): Client;
33
+
34
+ declare class GenqlError extends Error {
35
+ constructor(errors: unknown, data: unknown);
36
+ }
37
+ // __STRIPPED_DURING_INJECTION_END__
38
+
39
+ const APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';
40
+ const API_KEY_ENV_KEY = 'TWENTY_API_KEY';
41
+
42
+ type TwentyGeneratedClientOptions = ClientOptions;
43
+
44
+ type ProcessEnvironment = Record<string, string | undefined>;
45
+
46
+ type GraphqlErrorPayloadEntry = {
47
+ message?: string;
48
+ extensions?: { code?: string };
49
+ };
50
+
51
+ type GraphqlResponsePayload = {
52
+ data?: Record<string, unknown>;
53
+ errors?: GraphqlErrorPayloadEntry[];
54
+ };
55
+
56
+ type GraphqlResponse = {
57
+ status: number;
58
+ statusText: string;
59
+ payload: GraphqlResponsePayload | null;
60
+ rawBody: string;
61
+ };
62
+
63
+ const getProcessEnvironment = (): ProcessEnvironment => {
64
+ const processObject = (
65
+ globalThis as { process?: { env?: ProcessEnvironment } }
66
+ ).process;
67
+
68
+ return processObject?.env ?? {};
69
+ };
70
+
71
+ const getTokenFromAuthorizationHeader = (
72
+ authorizationHeader: string | undefined,
73
+ ): string | null => {
74
+ if (typeof authorizationHeader !== 'string') {
75
+ return null;
76
+ }
77
+
78
+ const trimmedAuthorizationHeader = authorizationHeader.trim();
79
+
80
+ if (trimmedAuthorizationHeader.length === 0) {
81
+ return null;
82
+ }
83
+
84
+ if (trimmedAuthorizationHeader === 'Bearer') {
85
+ return null;
86
+ }
87
+
88
+ if (trimmedAuthorizationHeader.startsWith('Bearer ')) {
89
+ return trimmedAuthorizationHeader.slice('Bearer '.length).trim();
90
+ }
91
+
92
+ return trimmedAuthorizationHeader;
93
+ };
94
+
95
+ const getTokenFromHeaders = (
96
+ headers: HeadersInit | undefined,
97
+ ): string | null => {
98
+ if (!headers) {
99
+ return null;
100
+ }
101
+
102
+ if (headers instanceof Headers) {
103
+ return getTokenFromAuthorizationHeader(
104
+ headers.get('Authorization') ?? undefined,
105
+ );
106
+ }
107
+
108
+ if (Array.isArray(headers)) {
109
+ const matchedAuthorizationHeader = headers.find(
110
+ ([headerName]) => headerName.toLowerCase() === 'authorization',
111
+ );
112
+
113
+ return getTokenFromAuthorizationHeader(matchedAuthorizationHeader?.[1]);
114
+ }
115
+
116
+ const headersRecord = headers as Record<string, string | undefined>;
117
+
118
+ return getTokenFromAuthorizationHeader(
119
+ headersRecord.Authorization ?? headersRecord.authorization,
120
+ );
121
+ };
122
+
123
+ const hasAuthenticationErrorInGraphqlPayload = (
124
+ payload: GraphqlResponsePayload | null,
125
+ ): boolean => {
126
+ if (!payload?.errors) {
127
+ return false;
128
+ }
129
+
130
+ return payload.errors.some((graphqlError) => {
131
+ return (
132
+ graphqlError.extensions?.code === 'UNAUTHENTICATED' ||
133
+ graphqlError.message?.toLowerCase() === 'unauthorized'
134
+ );
135
+ });
136
+ };
137
+
138
+ const defaultOptions: TwentyGeneratedClientOptions = {
139
+ url: '__TWENTY_DEFAULT_URL__',
140
+ headers: {
141
+ 'Content-Type': 'application/json',
142
+ },
143
+ };
144
+
145
+ export class TwentyGeneratedClient {
146
+ private client: Client;
147
+ private url: string;
148
+ private requestOptions: RequestInit;
149
+ private headers: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
150
+ private fetchImplementation: typeof globalThis.fetch | null;
151
+ private authorizationToken: string | null;
152
+ private refreshAccessTokenPromise: Promise<string | null> | null = null;
153
+
154
+ constructor(options?: TwentyGeneratedClientOptions) {
155
+ const merged: TwentyGeneratedClientOptions = {
156
+ ...defaultOptions,
157
+ ...options,
158
+ };
159
+
160
+ const {
161
+ url,
162
+ headers,
163
+ fetch: customFetchImplementation,
164
+ fetcher: _fetcher,
165
+ batch: _batch,
166
+ ...requestOptions
167
+ } = merged;
168
+
169
+ this.url = url ?? '';
170
+ this.requestOptions = requestOptions;
171
+ this.headers = headers ?? {};
172
+ this.fetchImplementation =
173
+ customFetchImplementation ?? globalThis.fetch ?? null;
174
+
175
+ const processEnvironment = getProcessEnvironment();
176
+ const tokenFromHeaders = getTokenFromHeaders(
177
+ typeof headers === 'function' ? undefined : headers,
178
+ );
179
+
180
+ // Priority: explicit header > app access token > api key (legacy).
181
+ this.authorizationToken =
182
+ tokenFromHeaders ??
183
+ processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??
184
+ processEnvironment[API_KEY_ENV_KEY] ??
185
+ null;
186
+
187
+ this.client = createClient({
188
+ ...merged,
189
+ headers: undefined,
190
+ fetcher: async (operation) =>
191
+ this.executeGraphqlRequestWithOptionalRefresh({
192
+ operation,
193
+ }),
194
+ });
195
+ }
196
+
197
+ query<R extends QueryGenqlSelection>(request: R & { __name?: string }) {
198
+ return this.client.query(request);
199
+ }
200
+
201
+ mutation<R extends MutationGenqlSelection>(request: R & { __name?: string }) {
202
+ return this.client.mutation(request);
203
+ }
204
+
205
+ // __UPLOAD_FILE_START__
206
+ async uploadFile(
207
+ fileBuffer: Buffer,
208
+ filename: string,
209
+ contentType: string = 'application/octet-stream',
210
+ fieldMetadataUniversalIdentifier: string,
211
+ ): Promise<{
212
+ id: string;
213
+ path: string;
214
+ size: number;
215
+ createdAt: string;
216
+ url: string;
217
+ }> {
218
+ const form = new FormData();
219
+
220
+ form.append(
221
+ 'operations',
222
+ JSON.stringify({
223
+ query: \`mutation UploadFilesFieldFileByUniversalIdentifier($file: Upload!, $fieldMetadataUniversalIdentifier: String!) {
224
+ uploadFilesFieldFileByUniversalIdentifier(file: $file, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { id path size createdAt url }
225
+ }\`,
226
+ variables: {
227
+ file: null,
228
+ fieldMetadataUniversalIdentifier,
229
+ },
230
+ }),
231
+ );
232
+ form.append('map', JSON.stringify({ '0': ['variables.file'] }));
233
+ form.append(
234
+ '0',
235
+ new Blob([fileBuffer as BlobPart], { type: contentType }),
236
+ filename,
237
+ );
238
+
239
+ const result = await this.executeGraphqlRequestWithOptionalRefresh({
240
+ operation: form,
241
+ headers: {},
242
+ requestInit: {
243
+ method: 'POST',
244
+ },
245
+ });
246
+
247
+ if (result.errors) {
248
+ throw new GenqlError(result.errors, result.data);
249
+ }
250
+
251
+ const data = result.data as Record<string, unknown>;
252
+
253
+ return data.uploadFilesFieldFileByUniversalIdentifier as {
254
+ id: string;
255
+ path: string;
256
+ size: number;
257
+ createdAt: string;
258
+ url: string;
259
+ };
260
+ }
261
+ // __UPLOAD_FILE_END__
262
+
263
+ private async executeGraphqlRequestWithOptionalRefresh({
264
+ operation,
265
+ headers,
266
+ requestInit,
267
+ }: {
268
+ operation: GraphqlOperation | GraphqlOperation[] | FormData;
269
+ headers?: HeadersInit;
270
+ requestInit?: RequestInit;
271
+ }) {
272
+ const firstResponse = await this.executeGraphqlRequest({
273
+ operation,
274
+ headers,
275
+ requestInit,
276
+ token: this.authorizationToken,
277
+ });
278
+
279
+ if (this.shouldRefreshToken(firstResponse)) {
280
+ const refreshedAccessToken = await this.requestRefreshedAccessToken();
281
+
282
+ if (refreshedAccessToken) {
283
+ const retryResponse = await this.executeGraphqlRequest({
284
+ operation,
285
+ headers,
286
+ requestInit,
287
+ token: refreshedAccessToken,
288
+ });
289
+
290
+ return this.assertResponseIsSuccessful(retryResponse);
291
+ }
292
+ }
293
+
294
+ return this.assertResponseIsSuccessful(firstResponse);
295
+ }
296
+
297
+ private async executeGraphqlRequest({
298
+ operation,
299
+ headers,
300
+ requestInit,
301
+ token,
302
+ }: {
303
+ operation: GraphqlOperation | GraphqlOperation[] | FormData;
304
+ headers?: HeadersInit;
305
+ requestInit?: RequestInit;
306
+ token: string | null;
307
+ }): Promise<GraphqlResponse> {
308
+ if (!this.fetchImplementation) {
309
+ throw new Error(
310
+ 'Global \`fetch\` function is not available, ' +
311
+ 'pass a fetch implementation to the Twenty client',
312
+ );
313
+ }
314
+
315
+ const resolvedHeaders = await this.resolveHeaders();
316
+ const requestHeaders = new Headers(resolvedHeaders);
317
+
318
+ if (headers) {
319
+ new Headers(headers).forEach((value, key) =>
320
+ requestHeaders.set(key, value),
321
+ );
322
+ }
323
+
324
+ if (operation instanceof FormData) {
325
+ requestHeaders.delete('Content-Type');
326
+ } else {
327
+ requestHeaders.set('Content-Type', 'application/json');
328
+ }
329
+
330
+ if (token) {
331
+ requestHeaders.set('Authorization', \`Bearer \${token}\`);
332
+ } else {
333
+ requestHeaders.delete('Authorization');
334
+ }
335
+
336
+ const response = await this.fetchImplementation.call(globalThis, this.url, {
337
+ ...this.requestOptions,
338
+ ...requestInit,
339
+ method: requestInit?.method ?? 'POST',
340
+ headers: requestHeaders,
341
+ body:
342
+ operation instanceof FormData ? operation : JSON.stringify(operation),
343
+ });
344
+
345
+ const rawBody = await response.text();
346
+ let payload: GraphqlResponsePayload | null = null;
347
+
348
+ if (rawBody.trim().length > 0) {
349
+ try {
350
+ payload = JSON.parse(rawBody) as GraphqlResponsePayload;
351
+ } catch {
352
+ payload = null;
353
+ }
354
+ }
355
+
356
+ return {
357
+ status: response.status,
358
+ statusText: response.statusText,
359
+ payload,
360
+ rawBody,
361
+ };
362
+ }
363
+
364
+ private async resolveHeaders(): Promise<HeadersInit> {
365
+ if (typeof this.headers === 'function') {
366
+ return (await this.headers()) ?? {};
367
+ }
368
+
369
+ return this.headers ?? {};
370
+ }
371
+
372
+ private shouldRefreshToken(response: GraphqlResponse): boolean {
373
+ if (response.status === 401) {
374
+ return true;
375
+ }
376
+
377
+ return hasAuthenticationErrorInGraphqlPayload(response.payload);
378
+ }
379
+
380
+ private assertResponseIsSuccessful(response: GraphqlResponse) {
381
+ if (response.status < 200 || response.status >= 300) {
382
+ throw new Error(\`\${response.statusText}: \${response.rawBody}\`);
383
+ }
384
+
385
+ if (response.payload === null) {
386
+ throw new Error('Invalid JSON response');
387
+ }
388
+
389
+ return response.payload;
390
+ }
391
+
392
+ private async requestRefreshedAccessToken(): Promise<string | null> {
393
+ const refreshAccessTokenFunction = (
394
+ globalThis as {
395
+ frontComponentHostCommunicationApi?: {
396
+ requestAccessTokenRefresh?: () => Promise<string>;
397
+ };
398
+ }
399
+ ).frontComponentHostCommunicationApi?.requestAccessTokenRefresh;
400
+
401
+ if (typeof refreshAccessTokenFunction !== 'function') {
402
+ return null;
403
+ }
404
+
405
+ if (!this.refreshAccessTokenPromise) {
406
+ this.refreshAccessTokenPromise = refreshAccessTokenFunction()
407
+ .then((refreshedAccessToken) => {
408
+ if (
409
+ typeof refreshedAccessToken !== 'string' ||
410
+ refreshedAccessToken.length === 0
411
+ ) {
412
+ return null;
413
+ }
414
+
415
+ this.setAuthorizationToken(refreshedAccessToken);
416
+
417
+ return refreshedAccessToken;
418
+ })
419
+ .catch((refreshError: unknown) => {
420
+ console.error('Twenty client: token refresh failed', refreshError);
421
+
422
+ return null;
423
+ })
424
+ .finally(() => {
425
+ this.refreshAccessTokenPromise = null;
426
+ });
427
+ }
428
+
429
+ return this.refreshAccessTokenPromise;
430
+ }
431
+
432
+ private setAuthorizationToken(token: string) {
433
+ this.authorizationToken = token;
434
+
435
+ const processEnvironment = getProcessEnvironment();
436
+
437
+ processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] = token;
438
+ }
439
+ }
440
+ `,R={DateTime:"string",JSON:"Record<string, unknown>",UUID:"string"},E="core/generated",g=async({schema:n,outputPath:t,clientWrapperTemplateSource:e})=>{const a=e??T,i=`${t}.tmp`;await y(i),await _(i);try{await h.generate({schema:n,output:i,scalarTypes:R});const l=m(a,{apiClientName:"CoreApiClient",defaultUrl:`\`\${process.env.${f}}/graphql\``,includeUploadFile:!0});await r.appendFile(s.join(i,"index.ts"),l),await p(t),await A(i,t),await P(t)}catch(l){throw await p(i),l}},I=async({packageRoot:n,schema:t})=>{const e=s.join(n,"dist",E);await g({schema:t,outputPath:e}),await r.copyFile(s.join(e,"index.mjs"),s.join(n,"dist","core.mjs")),await r.copyFile(s.join(e,"index.cjs"),s.join(n,"dist","core.cjs"))},P=async n=>{const t=s.join(n,"index.ts"),e=s.join(n,"index.mjs");await c.build({entryPoints:[t],outfile:e,bundle:!0,format:"esm",platform:"node",target:"node18",sourcemap:!1,minify:!1}),await c.build({entryPoints:[t],outfile:s.join(n,"index.cjs"),bundle:!0,format:"cjs",platform:"node",target:"node18",sourcemap:!1,minify:!1}),await r.writeFile(s.join(n,"package.json"),JSON.stringify({type:"module",main:"index.mjs",module:"index.mjs"},null,2))},k={DateTime:"string",JSON:"Record<string, unknown>",UUID:"string"},C=async({schema:n,outputPath:t,clientWrapperTemplateSource:e})=>{const a=e??T;await y(t),await _(t),await h.generate({schema:n,output:t,scalarTypes:{...k,Upload:"File"}});const i=m(a,{apiClientName:"MetadataApiClient",defaultUrl:`\`\${process.env.${f}}/metadata\``,includeUploadFile:!0});await r.appendFile(s.join(t,"index.ts"),i)};exports.GENERATED_CORE_DIR=E;exports.generateCoreClientFromSchema=g;exports.generateMetadataClient=C;exports.replaceCoreClient=I;