twenty-sdk 0.6.2 → 0.6.3-alpha

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 (49) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.mjs +1 -1
  3. package/dist/front-component-renderer/index.cjs +1 -1
  4. package/dist/front-component-renderer/index.mjs +1 -1
  5. package/dist/front-component-renderer/types/FrontComponentExecutionContext.d.ts +1 -0
  6. package/dist/front-component-renderer/types/FrontComponentHostCommunicationApi.d.ts +2 -1
  7. package/dist/index.cjs +2 -2
  8. package/dist/index.mjs +121 -114
  9. package/dist/sdk/front-component-api/functions/openAskAIWithPrompt.d.ts +2 -0
  10. package/dist/sdk/front-component-api/functions/openAskAIWithPrompt.js +12 -0
  11. package/dist/sdk/front-component-api/functions/openAskAIWithPrompt.js.map +1 -0
  12. package/dist/sdk/front-component-api/globals/frontComponentHostCommunicationApi.d.ts +4 -0
  13. package/dist/sdk/front-component-api/globals/frontComponentHostCommunicationApi.js.map +1 -1
  14. package/dist/sdk/front-component-api/hooks/useRecordId.d.ts +1 -0
  15. package/dist/sdk/front-component-api/hooks/useRecordId.js +6 -0
  16. package/dist/sdk/front-component-api/hooks/useRecordId.js.map +1 -0
  17. package/dist/sdk/front-component-api/index.d.ts +2 -0
  18. package/dist/sdk/front-component-api/types/FrontComponentExecutionContext.d.ts +1 -0
  19. package/dist/sdk/index.d.ts +1 -1
  20. package/dist/sdk/index.js +59 -55
  21. package/dist/sdk/index.js.map +1 -1
  22. package/package.json +1 -1
  23. package/generated/core/index.ts +0 -406
  24. package/generated/core/runtime/batcher.ts +0 -265
  25. package/generated/core/runtime/createClient.ts +0 -68
  26. package/generated/core/runtime/error.ts +0 -29
  27. package/generated/core/runtime/fetcher.ts +0 -98
  28. package/generated/core/runtime/generateGraphqlOperation.ts +0 -225
  29. package/generated/core/runtime/index.ts +0 -13
  30. package/generated/core/runtime/linkTypeMap.ts +0 -139
  31. package/generated/core/runtime/typeSelection.ts +0 -98
  32. package/generated/core/runtime/types.ts +0 -69
  33. package/generated/core/schema.graphql +0 -36745
  34. package/generated/core/schema.ts +0 -39341
  35. package/generated/core/types.ts +0 -45860
  36. package/generated/index.ts +0 -2
  37. package/generated/metadata/index.ts +0 -469
  38. package/generated/metadata/runtime/batcher.ts +0 -265
  39. package/generated/metadata/runtime/createClient.ts +0 -68
  40. package/generated/metadata/runtime/error.ts +0 -29
  41. package/generated/metadata/runtime/fetcher.ts +0 -98
  42. package/generated/metadata/runtime/generateGraphqlOperation.ts +0 -225
  43. package/generated/metadata/runtime/index.ts +0 -13
  44. package/generated/metadata/runtime/linkTypeMap.ts +0 -139
  45. package/generated/metadata/runtime/typeSelection.ts +0 -98
  46. package/generated/metadata/runtime/types.ts +0 -69
  47. package/generated/metadata/schema.graphql +0 -3971
  48. package/generated/metadata/schema.ts +0 -8357
  49. package/generated/metadata/types.ts +0 -10044
@@ -1 +1 @@
1
- {"version":3,"file":"frontComponentHostCommunicationApi.js","sources":["../../../../src/sdk/front-component-api/globals/frontComponentHostCommunicationApi.ts"],"sourcesContent":["import {\n type AppPath,\n type CommandMenuPages,\n type EnqueueSnackbarParams,\n type NavigateOptions,\n} from 'twenty-shared/types';\nimport { type getAppPath } from 'twenty-shared/utils';\n\nexport type NavigateFunction = <T extends AppPath>(\n to: T,\n params?: Parameters<typeof getAppPath<T>>[1],\n queryParams?: Record<string, any>,\n options?: NavigateOptions,\n) => Promise<void>;\n\nexport type OpenSidePanelPageFunction = (params: {\n page: CommandMenuPages;\n pageTitle: string;\n pageIcon?: string;\n shouldResetSearchState?: boolean;\n}) => Promise<void>;\n\nexport type UnmountFrontComponentFunction = () => Promise<void>;\n\nexport type EnqueueSnackbarFunction = (\n params: EnqueueSnackbarParams,\n) => Promise<void>;\n\nexport type CloseSidePanelFunction = () => Promise<void>;\n\nexport type RequestAccessTokenRefreshFunction = () => Promise<string>;\n\nexport type FrontComponentHostCommunicationApiStore = {\n navigate?: NavigateFunction;\n requestAccessTokenRefresh?: RequestAccessTokenRefreshFunction;\n openSidePanelPage?: OpenSidePanelPageFunction;\n unmountFrontComponent?: UnmountFrontComponentFunction;\n enqueueSnackbar?: EnqueueSnackbarFunction;\n closeSidePanel?: CloseSidePanelFunction;\n};\n\ndeclare global {\n var frontComponentHostCommunicationApi: FrontComponentHostCommunicationApiStore;\n}\n\nglobalThis.frontComponentHostCommunicationApi ??= {};\n\nexport const frontComponentHostCommunicationApi =\n globalThis.frontComponentHostCommunicationApi;\n"],"names":["frontComponentHostCommunicationApi"],"mappings":"AA6CA,WAAW,uCAAuC,CAAA;AAE3C,MAAMA,IACX,WAAW;"}
1
+ {"version":3,"file":"frontComponentHostCommunicationApi.js","sources":["../../../../src/sdk/front-component-api/globals/frontComponentHostCommunicationApi.ts"],"sourcesContent":["import {\n type AppPath,\n type CommandMenuPages,\n type EnqueueSnackbarParams,\n type NavigateOptions,\n} from 'twenty-shared/types';\nimport { type getAppPath } from 'twenty-shared/utils';\n\nexport type NavigateFunction = <T extends AppPath>(\n to: T,\n params?: Parameters<typeof getAppPath<T>>[1],\n queryParams?: Record<string, any>,\n options?: NavigateOptions,\n) => Promise<void>;\n\nexport type OpenSidePanelPageFunction = (params: {\n page: CommandMenuPages;\n pageTitle: string;\n pageIcon?: string;\n shouldResetSearchState?: boolean;\n}) => Promise<void>;\n\nexport type UnmountFrontComponentFunction = () => Promise<void>;\n\nexport type EnqueueSnackbarFunction = (\n params: EnqueueSnackbarParams,\n) => Promise<void>;\n\nexport type CloseSidePanelFunction = () => Promise<void>;\n\nexport type RequestAccessTokenRefreshFunction = () => Promise<string>;\n\nexport type OpenAskAIWithPromptFunction = (params: {\n prompt: string;\n}) => Promise<void>;\n\nexport type FrontComponentHostCommunicationApiStore = {\n navigate?: NavigateFunction;\n requestAccessTokenRefresh?: RequestAccessTokenRefreshFunction;\n openSidePanelPage?: OpenSidePanelPageFunction;\n unmountFrontComponent?: UnmountFrontComponentFunction;\n enqueueSnackbar?: EnqueueSnackbarFunction;\n closeSidePanel?: CloseSidePanelFunction;\n openAskAIWithPrompt?: OpenAskAIWithPromptFunction;\n};\n\ndeclare global {\n var frontComponentHostCommunicationApi: FrontComponentHostCommunicationApiStore;\n}\n\nglobalThis.frontComponentHostCommunicationApi ??= {};\n\nexport const frontComponentHostCommunicationApi =\n globalThis.frontComponentHostCommunicationApi;\n"],"names":["frontComponentHostCommunicationApi"],"mappings":"AAkDA,WAAW,uCAAuC,CAAA;AAE3C,MAAMA,IACX,WAAW;"}
@@ -0,0 +1 @@
1
+ export declare const useRecordId: () => string | null;
@@ -0,0 +1,6 @@
1
+ import { useFrontComponentExecutionContext as e } from "./useFrontComponentExecutionContext.js";
2
+ const t = (o) => o.recordId, n = () => e(t);
3
+ export {
4
+ n as useRecordId
5
+ };
6
+ //# sourceMappingURL=useRecordId.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRecordId.js","sources":["../../../../src/sdk/front-component-api/hooks/useRecordId.ts"],"sourcesContent":["import { type FrontComponentExecutionContext } from '../types/FrontComponentExecutionContext';\nimport { useFrontComponentExecutionContext } from './useFrontComponentExecutionContext';\n\nconst selectRecordId = (\n context: FrontComponentExecutionContext,\n): string | null => context.recordId;\n\nexport const useRecordId = (): string | null => {\n return useFrontComponentExecutionContext(selectRecordId);\n};\n"],"names":["selectRecordId","context","useRecordId","useFrontComponentExecutionContext"],"mappings":";AAGA,MAAMA,IAAiB,CACrBC,MACkBA,EAAQ,UAEfC,IAAc,MAClBC,EAAkCH,CAAc;"}
@@ -2,10 +2,12 @@ export { setFrontComponentExecutionContext } from './context/frontComponentConte
2
2
  export { closeSidePanel } from './functions/closeSidePanel';
3
3
  export { enqueueSnackbar } from './functions/enqueueSnackbar';
4
4
  export { navigate } from './functions/navigate';
5
+ export { openAskAIWithPrompt } from './functions/openAskAIWithPrompt';
5
6
  export { openSidePanelPage } from './functions/openSidePanelPage';
6
7
  export { unmountFrontComponent } from './functions/unmountFrontComponent';
7
8
  export { useFrontComponentExecutionContext } from './hooks/useFrontComponentExecutionContext';
8
9
  export { useFrontComponentId } from './hooks/useFrontComponentId';
10
+ export { useRecordId } from './hooks/useRecordId';
9
11
  export { useUserId } from './hooks/useUserId';
10
12
  export type { FrontComponentExecutionContext } from './types/FrontComponentExecutionContext';
11
13
  export { getFrontComponentActionErrorDedupeKey } from './utils/getFrontComponentActionErrorDedupeKey';
@@ -1,4 +1,5 @@
1
1
  export type FrontComponentExecutionContext = {
2
2
  frontComponentId: string;
3
3
  userId: string | null;
4
+ recordId: string | null;
4
5
  };
@@ -38,7 +38,7 @@ export { ActionLink } from './action';
38
38
  export type { ActionLinkProps } from './action';
39
39
  export { ActionOpenSidePanelPage } from './action';
40
40
  export type { ActionOpenSidePanelPageProps } from './action';
41
- export { enqueueSnackbar, getFrontComponentActionErrorDedupeKey, closeSidePanel, navigate, openSidePanelPage, unmountFrontComponent, useFrontComponentExecutionContext, useFrontComponentId, useUserId, } from './front-component-api';
41
+ export { enqueueSnackbar, getFrontComponentActionErrorDedupeKey, closeSidePanel, navigate, openAskAIWithPrompt, openSidePanelPage, unmountFrontComponent, useFrontComponentExecutionContext, useFrontComponentId, useRecordId, useUserId, } from './front-component-api';
42
42
  export type { FrontComponentExecutionContext } from './front-component-api';
43
43
  export { AppPath, CommandMenuPages } from 'twenty-shared/types';
44
44
  export type { EnqueueSnackbarParams, SnackBarVariant, } from 'twenty-shared/types';
package/dist/sdk/index.js CHANGED
@@ -1,83 +1,87 @@
1
1
  import { defineApplication as r } from "./application/define-application.js";
2
2
  import { createValidationResult as n } from "./common/utils/create-validation-result.js";
3
3
  import { defineFrontComponent as i } from "./define-front-component.js";
4
- import { defineField as a } from "./fields/define-field.js";
5
- import { AggregateOperations as x, AppPath as l, CommandMenuPages as d, FieldMetadataType as T, ObjectRecordGroupByDateGranularity as s, RelationOnDeleteAction as E, PageLayoutTabLayoutMode as A, RelationType as O } from "twenty-shared/types";
6
- import { validateFields as u } from "./fields/validate-fields.js";
4
+ import { defineField as m } from "./fields/define-field.js";
5
+ import { AggregateOperations as x, AppPath as d, CommandMenuPages as l, FieldMetadataType as T, ObjectRecordGroupByDateGranularity as s, RelationOnDeleteAction as A, PageLayoutTabLayoutMode as E, RelationType as c } from "twenty-shared/types";
6
+ import { validateFields as O } from "./fields/validate-fields.js";
7
7
  import { defineLogicFunction as g } from "./logic-functions/define-logic-function.js";
8
- import { definePreInstallLogicFunction as P } from "./logic-functions/define-pre-install-logic-function.js";
9
- import { definePostInstallLogicFunction as F } from "./logic-functions/define-post-install-logic-function.js";
10
- import { defineNavigationMenuItem as M } from "./navigation-menu-items/define-navigation-menu-item.js";
8
+ import { definePreInstallLogicFunction as S } from "./logic-functions/define-pre-install-logic-function.js";
9
+ import { definePostInstallLogicFunction as C } from "./logic-functions/define-post-install-logic-function.js";
10
+ import { defineNavigationMenuItem as L } from "./navigation-menu-items/define-navigation-menu-item.js";
11
11
  import { defineObject as D } from "./objects/define-object.js";
12
- import { STANDARD_OBJECTS as y, STANDARD_OBJECTS as I } from "twenty-shared/metadata";
12
+ import { STANDARD_OBJECTS as I, STANDARD_OBJECTS as y } from "twenty-shared/metadata";
13
13
  import { definePageLayout as b } from "./page-layouts/define-page-layout.js";
14
- import { defineRole as G } from "./roles/define-role.js";
15
- import { PermissionFlagType as J } from "twenty-shared/constants";
14
+ import { defineRole as k } from "./roles/define-role.js";
15
+ import { PermissionFlagType as H } from "twenty-shared/constants";
16
16
  import { defineSkill as v } from "./skills/define-skill.js";
17
- import { defineView as U } from "./views/define-view.js";
18
- import { Action as q } from "./action/Action.js";
19
- import { ActionLink as K } from "./action/ActionLink.js";
17
+ import { defineView as j } from "./views/define-view.js";
18
+ import { Action as W } from "./action/Action.js";
19
+ import { ActionLink as w } from "./action/ActionLink.js";
20
20
  import { ActionOpenSidePanelPage as z } from "./action/ActionOpenSidePanelPage.js";
21
21
  import { closeSidePanel as X } from "./front-component-api/functions/closeSidePanel.js";
22
22
  import { enqueueSnackbar as Z } from "./front-component-api/functions/enqueueSnackbar.js";
23
23
  import { navigate as ee } from "./front-component-api/functions/navigate.js";
24
- import { openSidePanelPage as re } from "./front-component-api/functions/openSidePanelPage.js";
25
- import { unmountFrontComponent as ne } from "./front-component-api/functions/unmountFrontComponent.js";
26
- import { useFrontComponentExecutionContext as ie } from "./front-component-api/hooks/useFrontComponentExecutionContext.js";
27
- import { useFrontComponentId as ae } from "./front-component-api/hooks/useFrontComponentId.js";
28
- import { useUserId as xe } from "./front-component-api/hooks/useUserId.js";
29
- import { getFrontComponentActionErrorDedupeKey as de } from "./front-component-api/utils/getFrontComponentActionErrorDedupeKey.js";
30
- import { ALLOWED_HTML_ELEMENTS as se } from "./front-component-api/constants/AllowedHtmlElements.js";
31
- import { COMMON_HTML_EVENTS as Ae } from "./front-component-api/constants/CommonHtmlEvents.js";
32
- import { EVENT_TO_REACT as ce } from "./front-component-api/constants/EventToReact.js";
33
- import { HTML_COMMON_PROPERTIES as _e } from "./front-component-api/constants/HtmlCommonProperties.js";
34
- import { HTML_TAG_TO_REMOTE_COMPONENT as Se } from "./front-component-api/constants/HtmlTagToRemoteComponent.js";
35
- import { installStyleBridge as Ce } from "./front-component-renderer/polyfills/installStyleBridge.js";
36
- import { exposeGlobals as Le } from "./front-component-renderer/remote/utils/exposeGlobals.js";
24
+ import { openAskAIWithPrompt as re } from "./front-component-api/functions/openAskAIWithPrompt.js";
25
+ import { openSidePanelPage as ne } from "./front-component-api/functions/openSidePanelPage.js";
26
+ import { unmountFrontComponent as ie } from "./front-component-api/functions/unmountFrontComponent.js";
27
+ import { useFrontComponentExecutionContext as me } from "./front-component-api/hooks/useFrontComponentExecutionContext.js";
28
+ import { useFrontComponentId as xe } from "./front-component-api/hooks/useFrontComponentId.js";
29
+ import { useRecordId as le } from "./front-component-api/hooks/useRecordId.js";
30
+ import { useUserId as se } from "./front-component-api/hooks/useUserId.js";
31
+ import { getFrontComponentActionErrorDedupeKey as Ee } from "./front-component-api/utils/getFrontComponentActionErrorDedupeKey.js";
32
+ import { ALLOWED_HTML_ELEMENTS as ue } from "./front-component-api/constants/AllowedHtmlElements.js";
33
+ import { COMMON_HTML_EVENTS as _e } from "./front-component-api/constants/CommonHtmlEvents.js";
34
+ import { EVENT_TO_REACT as Pe } from "./front-component-api/constants/EventToReact.js";
35
+ import { HTML_COMMON_PROPERTIES as Re } from "./front-component-api/constants/HtmlCommonProperties.js";
36
+ import { HTML_TAG_TO_REMOTE_COMPONENT as Fe } from "./front-component-api/constants/HtmlTagToRemoteComponent.js";
37
+ import { installStyleBridge as Me } from "./front-component-renderer/polyfills/installStyleBridge.js";
38
+ import { exposeGlobals as Ne } from "./front-component-renderer/remote/utils/exposeGlobals.js";
37
39
  export {
38
- se as ALLOWED_HTML_ELEMENTS,
39
- q as Action,
40
- K as ActionLink,
40
+ ue as ALLOWED_HTML_ELEMENTS,
41
+ W as Action,
42
+ w as ActionLink,
41
43
  z as ActionOpenSidePanelPage,
42
44
  x as AggregateOperations,
43
- l as AppPath,
44
- Ae as COMMON_HTML_EVENTS,
45
- d as CommandMenuPages,
46
- ce as EVENT_TO_REACT,
45
+ d as AppPath,
46
+ _e as COMMON_HTML_EVENTS,
47
+ l as CommandMenuPages,
48
+ Pe as EVENT_TO_REACT,
47
49
  T as FieldType,
48
- _e as HTML_COMMON_PROPERTIES,
49
- Se as HTML_TAG_TO_REMOTE_COMPONENT,
50
+ Re as HTML_COMMON_PROPERTIES,
51
+ Fe as HTML_TAG_TO_REMOTE_COMPONENT,
50
52
  s as ObjectRecordGroupByDateGranularity,
51
- E as OnDeleteAction,
52
- A as PageLayoutTabLayoutMode,
53
- J as PermissionFlag,
54
- O as RelationType,
55
- y as STANDARD_OBJECT,
56
- I as STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
53
+ A as OnDeleteAction,
54
+ E as PageLayoutTabLayoutMode,
55
+ H as PermissionFlag,
56
+ c as RelationType,
57
+ I as STANDARD_OBJECT,
58
+ y as STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
57
59
  X as closeSidePanel,
58
60
  n as createValidationResult,
59
61
  r as defineApplication,
60
- a as defineField,
62
+ m as defineField,
61
63
  i as defineFrontComponent,
62
64
  g as defineLogicFunction,
63
- M as defineNavigationMenuItem,
65
+ L as defineNavigationMenuItem,
64
66
  D as defineObject,
65
67
  b as definePageLayout,
66
- F as definePostInstallLogicFunction,
67
- P as definePreInstallLogicFunction,
68
- G as defineRole,
68
+ C as definePostInstallLogicFunction,
69
+ S as definePreInstallLogicFunction,
70
+ k as defineRole,
69
71
  v as defineSkill,
70
- U as defineView,
72
+ j as defineView,
71
73
  Z as enqueueSnackbar,
72
- Le as exposeGlobals,
73
- de as getFrontComponentActionErrorDedupeKey,
74
- Ce as installStyleBridge,
74
+ Ne as exposeGlobals,
75
+ Ee as getFrontComponentActionErrorDedupeKey,
76
+ Me as installStyleBridge,
75
77
  ee as navigate,
76
- re as openSidePanelPage,
77
- ne as unmountFrontComponent,
78
- ie as useFrontComponentExecutionContext,
79
- ae as useFrontComponentId,
80
- xe as useUserId,
81
- u as validateFields
78
+ re as openAskAIWithPrompt,
79
+ ne as openSidePanelPage,
80
+ ie as unmountFrontComponent,
81
+ me as useFrontComponentExecutionContext,
82
+ xe as useFrontComponentId,
83
+ le as useRecordId,
84
+ se as useUserId,
85
+ O as validateFields
82
86
  };
83
87
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "twenty-sdk",
3
- "version": "0.6.2",
3
+ "version": "0.6.3-alpha",
4
4
  "main": "dist/index.cjs",
5
5
  "module": "dist/index.mjs",
6
6
  "types": "dist/sdk/index.d.ts",
@@ -1,406 +0,0 @@
1
- // @ts-nocheck
2
- import type {
3
- QueryGenqlSelection,
4
- Query,
5
- MutationGenqlSelection,
6
- Mutation,
7
- } from './schema'
8
- import {
9
- linkTypeMap,
10
- createClient as createClientOriginal,
11
- generateGraphqlOperation,
12
- type FieldsSelection,
13
- type GraphqlOperation,
14
- type ClientOptions,
15
- GenqlError,
16
- } from './runtime'
17
- export type { FieldsSelection } from './runtime'
18
- export { GenqlError }
19
-
20
- import types from './types'
21
- export * from './schema'
22
- const typeMap = linkTypeMap(types as any)
23
-
24
- export interface Client {
25
- query<R extends QueryGenqlSelection>(
26
- request: R & { __name?: string },
27
- ): Promise<FieldsSelection<Query, R>>
28
-
29
- mutation<R extends MutationGenqlSelection>(
30
- request: R & { __name?: string },
31
- ): Promise<FieldsSelection<Mutation, R>>
32
- }
33
-
34
- export const createClient = function (options?: ClientOptions): Client {
35
- return createClientOriginal({
36
- url: undefined,
37
-
38
- ...options,
39
- queryRoot: typeMap.Query!,
40
- mutationRoot: typeMap.Mutation!,
41
- subscriptionRoot: typeMap.Subscription!,
42
- }) as any
43
- }
44
-
45
- export const everything = {
46
- __scalar: true,
47
- }
48
-
49
- export type QueryResult<fields extends QueryGenqlSelection> = FieldsSelection<
50
- Query,
51
- fields
52
- >
53
- export const generateQueryOp: (
54
- fields: QueryGenqlSelection & { __name?: string },
55
- ) => GraphqlOperation = function (fields) {
56
- return generateGraphqlOperation('query', typeMap.Query!, fields as any)
57
- }
58
-
59
- export type MutationResult<fields extends MutationGenqlSelection> =
60
- FieldsSelection<Mutation, fields>
61
- export const generateMutationOp: (
62
- fields: MutationGenqlSelection & { __name?: string },
63
- ) => GraphqlOperation = function (fields) {
64
- return generateGraphqlOperation('mutation', typeMap.Mutation!, fields as any)
65
- }
66
-
67
-
68
- // ----------------------------------------------------
69
- // CoreApiClient (auto-injected)
70
- // ----------------------------------------------------
71
-
72
- const APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';
73
- const API_KEY_ENV_KEY = 'TWENTY_API_KEY';
74
-
75
- type CoreApiClientOptions = ClientOptions
76
-
77
- type ProcessEnvironment = Record<string, string | undefined>
78
-
79
- type GraphqlError = {
80
- message?: string;
81
- extensions?: { code?: string };
82
- }
83
-
84
- type GraphqlResponsePayload = {
85
- data?: Record<string, unknown>
86
- errors?: GraphqlError[];
87
- }
88
-
89
- type GraphqlResponse = {
90
- status: number;
91
- statusText: string;
92
- payload: GraphqlResponsePayload | null;
93
- rawBody: string;
94
- }
95
-
96
- const getProcessEnvironment = (): ProcessEnvironment => {
97
- const processObject = (globalThis as { process?: { env?: ProcessEnvironment } })
98
- .process;
99
-
100
- return processObject?.env ?? {};
101
- }
102
-
103
- const getTokenFromAuthorizationHeader = (
104
- authorizationHeader: string | undefined,
105
- ): string | null => {
106
- if (typeof authorizationHeader !== 'string') {
107
- return null;
108
- }
109
-
110
- const trimmedAuthorizationHeader = authorizationHeader.trim();
111
-
112
- if (trimmedAuthorizationHeader.length === 0) {
113
- return null;
114
- }
115
-
116
- if (trimmedAuthorizationHeader === 'Bearer') {
117
- return null;
118
- }
119
-
120
- if (trimmedAuthorizationHeader.startsWith('Bearer ')) {
121
- return trimmedAuthorizationHeader.slice('Bearer '.length).trim();
122
- }
123
-
124
- return trimmedAuthorizationHeader;
125
- }
126
-
127
- const getTokenFromHeaders = (headers: HeadersInit | undefined): string | null => {
128
- if (!headers) {
129
- return null;
130
- }
131
-
132
- if (headers instanceof Headers) {
133
- return getTokenFromAuthorizationHeader(headers.get('Authorization') ?? undefined);
134
- }
135
-
136
- if (Array.isArray(headers)) {
137
- const matchedAuthorizationHeader = headers.find(
138
- ([headerName]) => headerName.toLowerCase() === 'authorization',
139
- );
140
-
141
- return getTokenFromAuthorizationHeader(matchedAuthorizationHeader?.[1]);
142
- }
143
-
144
- const headersRecord = headers as Record<string, string | undefined>;
145
-
146
- return getTokenFromAuthorizationHeader(
147
- headersRecord.Authorization ?? headersRecord.authorization,
148
- );
149
- }
150
-
151
- const hasAuthenticationErrorInGraphqlPayload = (
152
- payload: GraphqlResponsePayload | null,
153
- ): boolean => {
154
- if (!payload?.errors) {
155
- return false;
156
- }
157
-
158
- return payload.errors.some((error) => {
159
- return (
160
- error.extensions?.code === 'UNAUTHENTICATED' ||
161
- error.message?.toLowerCase() === 'unauthorized'
162
- );
163
- });
164
- }
165
-
166
- const defaultOptions: CoreApiClientOptions = {
167
- url: `${process.env.TWENTY_API_URL}/graphql`,
168
- headers: {
169
- 'Content-Type': 'application/json',
170
- },
171
- }
172
-
173
- export class CoreApiClient {
174
- private client: Client;
175
- private url: string;
176
- private requestOptions: RequestInit;
177
- private headers: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
178
- private fetchImplementation: typeof globalThis.fetch | null;
179
- private authorizationToken: string | null;
180
- private refreshAccessTokenPromise: Promise<string | null> | null = null;
181
-
182
- constructor(options?: CoreApiClientOptions) {
183
- const merged: CoreApiClientOptions = {
184
- ...defaultOptions,
185
- ...options,
186
- }
187
-
188
- const {
189
- url,
190
- headers,
191
- fetch: customFetchImplementation,
192
- fetcher: _fetcher,
193
- batch: _batch,
194
- ...requestOptions
195
- } = merged;
196
-
197
- this.url = url ?? '';
198
- this.requestOptions = requestOptions;
199
- this.headers = headers ?? {};
200
- this.fetchImplementation = customFetchImplementation ?? globalThis.fetch ?? null;
201
-
202
- const processEnvironment = getProcessEnvironment();
203
- const tokenFromHeaders = getTokenFromHeaders(
204
- typeof headers === 'function' ? undefined : headers,
205
- );
206
-
207
- // Priority: explicit header > TWENTY_APP_ACCESS_TOKEN > TWENTY_API_KEY (legacy fallback).
208
- this.authorizationToken =
209
- tokenFromHeaders ??
210
- processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??
211
- processEnvironment[API_KEY_ENV_KEY] ??
212
- null;
213
-
214
- this.client = createClient({
215
- ...merged,
216
- headers: undefined,
217
- fetcher: async (operation) =>
218
- this.executeGraphqlRequestWithOptionalRefresh({
219
- operation,
220
- }),
221
- });
222
- }
223
-
224
- query<R extends QueryGenqlSelection>(request: R & { __name?: string }) {
225
- return this.client.query(request);
226
- }
227
-
228
- mutation<R extends MutationGenqlSelection>(request: R & { __name?: string }) {
229
- return this.client.mutation(request);
230
- }
231
-
232
- private async executeGraphqlRequestWithOptionalRefresh({
233
- operation,
234
- headers,
235
- requestInit,
236
- }: {
237
- operation: GraphqlOperation | GraphqlOperation[] | FormData;
238
- headers?: HeadersInit;
239
- requestInit?: RequestInit;
240
- }) {
241
- const firstResponse = await this.executeGraphqlRequest({
242
- operation,
243
- headers,
244
- requestInit,
245
- token: this.authorizationToken,
246
- });
247
-
248
- if (this.shouldRefreshToken(firstResponse)) {
249
- const refreshedAccessToken = await this.requestRefreshedAccessToken();
250
-
251
- if (refreshedAccessToken) {
252
- const retryResponse = await this.executeGraphqlRequest({
253
- operation,
254
- headers,
255
- requestInit,
256
- token: refreshedAccessToken,
257
- });
258
-
259
- return this.assertResponseIsSuccessful(retryResponse);
260
- }
261
- }
262
-
263
- return this.assertResponseIsSuccessful(firstResponse);
264
- }
265
-
266
- private async executeGraphqlRequest({
267
- operation,
268
- headers,
269
- requestInit,
270
- token,
271
- }: {
272
- operation: GraphqlOperation | GraphqlOperation[] | FormData;
273
- headers?: HeadersInit;
274
- requestInit?: RequestInit;
275
- token: string | null;
276
- }): Promise<GraphqlResponse> {
277
- if (!this.fetchImplementation) {
278
- throw new Error(
279
- 'Global `fetch` function is not available, pass a fetch implementation to the Twenty client',
280
- );
281
- }
282
-
283
- const resolvedHeaders = await this.resolveHeaders();
284
- const requestHeaders = new Headers(resolvedHeaders);
285
-
286
- if (headers) {
287
- new Headers(headers).forEach((value, key) => requestHeaders.set(key, value));
288
- }
289
-
290
- if (operation instanceof FormData) {
291
- requestHeaders.delete('Content-Type');
292
- } else {
293
- requestHeaders.set('Content-Type', 'application/json');
294
- }
295
-
296
- if (token) {
297
- requestHeaders.set('Authorization', `Bearer ${token}`);
298
- } else {
299
- requestHeaders.delete('Authorization');
300
- }
301
-
302
- const response = await this.fetchImplementation.call(globalThis, this.url, {
303
- ...this.requestOptions,
304
- ...requestInit,
305
- method: requestInit?.method ?? 'POST',
306
- headers: requestHeaders,
307
- body: operation instanceof FormData ? operation : JSON.stringify(operation),
308
- });
309
-
310
- const rawBody = await response.text();
311
- let payload: GraphqlResponsePayload | null = null;
312
-
313
- if (rawBody.trim().length > 0) {
314
- try {
315
- payload = JSON.parse(rawBody) as GraphqlResponsePayload;
316
- } catch {
317
- payload = null;
318
- }
319
- }
320
-
321
- return {
322
- status: response.status,
323
- statusText: response.statusText,
324
- payload,
325
- rawBody,
326
- }
327
- }
328
-
329
- private async resolveHeaders(): Promise<HeadersInit> {
330
- if (typeof this.headers === 'function') {
331
- return (await this.headers()) ?? {};
332
- }
333
-
334
- return this.headers ?? {};
335
- }
336
-
337
- private shouldRefreshToken(response: GraphqlResponse): boolean {
338
- if (response.status === 401) {
339
- return true;
340
- }
341
-
342
- return hasAuthenticationErrorInGraphqlPayload(response.payload);
343
- }
344
-
345
- private assertResponseIsSuccessful(response: GraphqlResponse) {
346
- if (response.status < 200 || response.status >= 300) {
347
- throw new Error(`${response.statusText}: ${response.rawBody}`);
348
- }
349
-
350
- if (response.payload === null) {
351
- throw new Error('Invalid JSON response');
352
- }
353
-
354
- return response.payload;
355
- }
356
-
357
- private async requestRefreshedAccessToken(): Promise<string | null> {
358
- const refreshAccessTokenFunction = (
359
- globalThis as {
360
- frontComponentHostCommunicationApi?: {
361
- requestAccessTokenRefresh?: () => Promise<string>
362
- }
363
- }
364
- ).frontComponentHostCommunicationApi?.requestAccessTokenRefresh;
365
-
366
- if (typeof refreshAccessTokenFunction !== 'function') {
367
- return null;
368
- }
369
-
370
- if (!this.refreshAccessTokenPromise) {
371
- this.refreshAccessTokenPromise = refreshAccessTokenFunction()
372
- .then((refreshedAccessToken) => {
373
- if (
374
- typeof refreshedAccessToken !== 'string' ||
375
- refreshedAccessToken.length === 0
376
- ) {
377
- return null;
378
- }
379
-
380
- this.setAuthorizationToken(refreshedAccessToken);
381
-
382
- return refreshedAccessToken;
383
- })
384
- .catch((error) => {
385
- console.error('Twenty client: token refresh failed', error);
386
-
387
- return null;
388
- })
389
- .finally(() => {
390
- this.refreshAccessTokenPromise = null;
391
- });
392
- }
393
-
394
- return this.refreshAccessTokenPromise;
395
- }
396
-
397
- private setAuthorizationToken(token: string) {
398
- this.authorizationToken = token;
399
-
400
- const processEnvironment = getProcessEnvironment();
401
-
402
- processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] = token;
403
- processEnvironment[API_KEY_ENV_KEY] = token;
404
- }
405
- }
406
-