The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(sdk): expose programmatic application client generation (#26889)
Weiko71b871ece1dd
diff --git a/packages/twenty-sdk/docs/build.md b/packages/twenty-sdk/docs/build.mdindex d58c4a4662d..1c48570df9f 100644--- a/packages/twenty-sdk/docs/build.md+++ b/packages/twenty-sdk/docs/build.md@@ -1,6 +1,6 @@# Programmatic application builds-`twenty-sdk/build` exposes local build and typecheck operations for scripts, CI jobs, and integrations. It requires an app project and its installed dependencies, but no workspace connection or separate CLI package. The SDK does not manage credentials, read CLI configuration, contact a workspace, prompt, print results, or exit the process through this entry point. Application source is trusted executable code and can have its own side effects; callers that need process isolation should use a worker or child process.+`twenty-sdk/build` exposes local build, typecheck, and client-generation operations for scripts, CI jobs, and integrations. It requires an app project and its installed dependencies, but no workspace connection or separate CLI package. The SDK does not manage credentials, read CLI configuration, contact a workspace, prompt, print results, or exit the process through this entry point. Application source is trusted executable code and can have its own side effects; callers that need process isolation should use a worker or child process.Read `twenty-sdk/build/descriptor.json` before importing the SDK. It is generated from the package version and Node requirement at build time. Its protocol version is independent of SDK semver and server compatibility. Importing the build entry does not load TypeScript or esbuild.@@ -30,17 +30,17 @@ try {Save the example as `build.mjs` in the app project and run it with Node. `typecheckApp({ appPath: process.cwd() })` checks the project without building artifacts. Public types, including `BuildSnapshot`, `BuildResult`, and `BuildDiagnostic`, are exported from `twenty-sdk/build`; consumers do not need the private `twenty-shared` package.-Protocol 1 advertises `build`, `typecheck`, and `releaseSnapshot`. Check the descriptor's capabilities rather than inferring them from the SDK version. Operations are loaded lazily, so importing the entry or reading `BUILD_DESCRIPTOR` does not load TypeScript or esbuild.+Protocol 1 advertises `build`, `typecheck`, `releaseSnapshot`, and `generateClient`. Older SDK releases may not offer every capability. Check the descriptor's capabilities rather than inferring them from the SDK version. Operations are loaded lazily, so importing the entry or reading `BUILD_DESCRIPTOR` does not load TypeScript or esbuild.-The import path and named exports `buildAppSnapshot`, `typecheckApp`, `releaseAppSnapshot`, and `BUILD_DESCRIPTOR` are public SDK API for local application builds and typechecking. A protocol version bump does not make renaming those exports backward-compatible; changes must preserve existing imports or follow a breaking SDK release. Workspace authentication, uploads, and synchronization remain outside this entry point.+The import path and named exports `buildAppSnapshot`, `typecheckApp`, `releaseAppSnapshot`, `generateAppClient`, and `BUILD_DESCRIPTOR` are public SDK API for local application tooling. A protocol version bump does not make renaming those exports backward-compatible; changes must preserve existing imports or follow a breaking SDK release. Workspace authentication, uploads, and synchronization remain outside this entry point.## Results and diagnosticsOperations return `{ success: true, data, diagnostics }` or `{ success: false, error: { code, message }, diagnostics }`. Typechecking succeeds with `data: null` and emits no files. Missing or invalid TypeScript configuration is a failure, including diagnostics without a source location.-Diagnostics have `severity`, `code`, and `message`, with optional project-relative `file` and one-based `line` and `column`. Codes include TypeScript codes such as `TS2322`. Operation error codes are `INVALID_APP_PATH`, `MANIFEST_BUILD_FAILED`, `BUILD_FAILED`, `TYPECHECK_FAILED`, `CANCELLED`, `SNAPSHOT_NOT_FOUND`, and `SNAPSHOT_RELEASE_FAILED`. Callers decide how to display results and which exit codes to use.+Diagnostics have `severity`, `code`, and `message`, with optional project-relative `file` and one-based `line` and `column`. Codes include TypeScript codes such as `TS2322`. Operation error codes are `INVALID_APP_PATH`, `MANIFEST_BUILD_FAILED`, `BUILD_FAILED`, `TYPECHECK_FAILED`, `CLIENT_GENERATION_FAILED`, `CANCELLED`, `SNAPSHOT_NOT_FOUND`, and `SNAPSHOT_RELEASE_FAILED`. Callers decide how to display results and which exit codes to use.-Both new operations fail on TypeScript configuration and project-reference errors, including errors without a source location. The legacy builder's text parser silently ignored some of these failures; successful legacy builds do not establish that a project passes typechecking. Before migrating, run the new typecheck operation and fix its diagnostics. For `TS6305`, build the referenced TypeScript projects first, or correct references that should not be part of the app compilation. Regenerate any app-specific client types against the intended workspace and SDK. The SDK never builds referenced projects or emits declarations implicitly, so its declared file writes remain accurate.+Build and typecheck fail on TypeScript configuration and project-reference errors, including errors without a source location. The legacy builder's text parser silently ignored some of these failures; successful legacy builds do not establish that a project passes typechecking. Before migrating, run the new typecheck operation and fix its diagnostics. For `TS6305`, build the referenced TypeScript projects first, or correct references that should not be part of the app compilation. Regenerate any app-specific client types against the intended workspace and SDK. The SDK never builds referenced projects or emits declarations implicitly, so its declared file writes remain accurate.Build and typecheck accept an optional `AbortSignal`. Cancellation is checked between asynchronous stages; synchronous TypeScript checking cannot be interrupted in-process. Use a worker or child process when immediate cancellation or protection against app code calling `process.exit` is required. This is process isolation, not a sandbox for untrusted code.@@ -64,6 +64,30 @@ Keep the owning SDK instance alive while consuming a snapshot. `releaseSnapshot`Failed builds clean up their own directory. A killed process can leave an orphan. Protocol 1 does not automatically prune other processes' directories. To remove crash leftovers manually, stop all SDK build processes using that app first, then remove its `.twenty/snapshots` directory. This keeps active snapshots safe from PID reuse and cleanup races.+## Client generation++`generateAppClient({ appPath, schema, signal? })` generates the core API client from a supplied GraphQL schema string. The caller fetches the application schema using its own workspace connection. The SDK reuses the existing client generator without network requests and returns `BuildResult<null>`. It does not register, install, or synchronize an application, modify app source, or write pull-base state.++```ts+import { readFile } from 'node:fs/promises';+import { generateAppClient } from 'twenty-sdk/build';++const result = await generateAppClient({+ appPath: process.cwd(),+ schema: await readFile('./application-schema.graphql', 'utf8'),+});++if (!result.success) {+ throw new Error(result.error.message);+}+```++`appPath` must be an absolute path to an existing directory with `node_modules/twenty-client-sdk` installed. The operation validates the package manifest before writing, with no fallback to a parent or global installation. Dependency symlinks are followed, so a linked package's target is modified. Avoid parallel generation for apps sharing the same installed client package.++The descriptor lists writes under `node_modules/twenty-client-sdk/dist`: `core/generated/**`, the temporary `core/generated.tmp/**` directory, `core.mjs`, and `core.cjs`. Metadata clients and other package files are preserved. Client replacement is not atomic: generation or filesystem failures can leave partially updated local files. Fix the cause and rerun generation against the intended schema; failure does not roll back a prior remote sync.++Cancellation is checked before generation starts and after the generator settles. An already-aborted signal causes no writes. In-flight generation cannot be interrupted cooperatively; the operation waits for its writes to stop before returning `CANCELLED`. An independent generation failure remains `CLIENT_GENERATION_FAILED` even if the signal was aborted while generation was running. Completed or partial local writes can remain, including if the caller forcibly terminates a worker. Callers should report the remote sync and local generation outcomes separately.+## Existing SDK commandsThe existing `twenty` binary and `twenty-sdk/cli` exports remain available. This API adds no executable, changes no command names, and requires no command migration.diff --git a/packages/twenty-sdk/src/application-build/__tests__/generate-application-client.spec.ts b/packages/twenty-sdk/src/application-build/__tests__/generate-application-client.spec.tsnew file mode 100644index 00000000000..71317679529--- /dev/null+++ b/packages/twenty-sdk/src/application-build/__tests__/generate-application-client.spec.ts@@ -0,0 +1,262 @@+import { createRequire } from 'node:module';+import {+ mkdir,+ mkdtemp,+ readFile,+ readdir,+ rm,+ writeFile,+} from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import * as clientGenerator from 'twenty-client-sdk/generate';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { generateAppClient } from '@/application-build';++const SCHEMA = 'type Query { greeting: String }';++describe('generateAppClient', () => {+ let appPath: string;+ let packageRoot: string;++ beforeEach(async () => {+ appPath = await mkdtemp(join(tmpdir(), 'twenty-generate-client-'));+ packageRoot = join(appPath, 'node_modules', 'twenty-client-sdk');+ await mkdir(join(packageRoot, 'dist'), { recursive: true });+ await writeFile(+ join(packageRoot, 'package.json'),+ JSON.stringify({ name: 'twenty-client-sdk' }),+ );+ await writeFile(join(packageRoot, 'dist', 'core.cjs'), 'old core client');+ await writeFile(join(packageRoot, 'dist', 'core.mjs'), 'old core client');+ await writeFile(+ join(packageRoot, 'dist', 'metadata.cjs'),+ 'metadata client',+ );+ await writeFile(join(appPath, 'source.ts'), 'export const source = true;');+ });++ afterEach(async () => {+ vi.restoreAllMocks();+ await rm(appPath, { recursive: true, force: true });+ });++ it('generates a usable client without changing app source or metadata client', async () => {+ expect(await generateAppClient({ appPath, schema: SCHEMA })).toEqual({+ success: true,+ data: null,+ diagnostics: [],+ });+ expect(+ await readFile(+ join(packageRoot, 'dist', 'core/generated/schema.graphql'),+ 'utf8',+ ),+ ).toContain('greeting: String');+ expect(+ createRequire(import.meta.url)(join(packageRoot, 'dist', 'core.cjs')),+ ).toHaveProperty('CoreApiClient');+ expect(+ await readFile(join(packageRoot, 'dist', 'core.mjs'), 'utf8'),+ ).toContain('CoreApiClient');+ expect(+ await readFile(join(packageRoot, 'dist', 'metadata.cjs'), 'utf8'),+ ).toBe('metadata client');+ expect(await readFile(join(appPath, 'source.ts'), 'utf8')).toBe(+ 'export const source = true;',+ );+ expect((await readdir(appPath)).sort()).toEqual([+ 'node_modules',+ 'source.ts',+ ]);+ expect(await readdir(join(packageRoot, 'dist', 'core'))).toEqual([+ 'generated',+ ]);+ });++ it.each(['not a schema', ''])(+ 'leaves the installed client unchanged for invalid schema: %s',+ async (schema) => {+ expect(await generateAppClient({ appPath, schema })).toMatchObject({+ success: false,+ error: { code: 'CLIENT_GENERATION_FAILED' },+ });+ expect(+ await readFile(join(packageRoot, 'dist', 'core.cjs'), 'utf8'),+ ).toBe('old core client');+ expect(+ await readFile(join(packageRoot, 'dist', 'core.mjs'), 'utf8'),+ ).toBe('old core client');+ },+ );++ it('does not create a partial package when the dependency is missing', async () => {+ await rm(join(appPath, 'node_modules'), { recursive: true });++ expect(await generateAppClient({ appPath, schema: SCHEMA })).toMatchObject({+ success: false,+ error: { code: 'CLIENT_GENERATION_FAILED' },+ });+ expect(await readdir(appPath)).toEqual(['source.ts']);+ });++ it.each([null, {}, []])(+ 'rejects a non-string schema from JavaScript callers: %j',+ async (schema) => {+ expect(+ await Reflect.apply(generateAppClient, undefined, [+ { appPath, schema },+ ]),+ ).toMatchObject({+ success: false,+ error: { code: 'CLIENT_GENERATION_FAILED' },+ });+ expect((await readdir(join(packageRoot, 'dist'))).sort()).toEqual([+ 'core.cjs',+ 'core.mjs',+ 'metadata.cjs',+ ]);+ },+ );++ it.each(['null', '{"name":"other-package"}', '{'])(+ 'rejects an invalid installed package manifest: %s',+ async (manifest) => {+ await writeFile(join(packageRoot, 'package.json'), manifest);++ expect(+ await generateAppClient({ appPath, schema: SCHEMA }),+ ).toMatchObject({+ success: false,+ error: { code: 'CLIENT_GENERATION_FAILED' },+ });+ expect((await readdir(join(packageRoot, 'dist'))).sort()).toEqual([+ 'core.cjs',+ 'core.mjs',+ 'metadata.cjs',+ ]);+ },+ );++ it('rejects a relative app path', async () => {+ expect(+ await generateAppClient({ appPath: '.', schema: SCHEMA }),+ ).toMatchObject({+ success: false,+ error: { code: 'INVALID_APP_PATH' },+ });+ });++ it.each([undefined, 'Stopped by caller', Number.NaN])(+ 'does not write files when already cancelled with reason %s',+ async (reason) => {+ expect(+ await generateAppClient({+ appPath,+ schema: SCHEMA,+ signal: AbortSignal.abort(reason),+ }),+ ).toMatchObject({ success: false, error: { code: 'CANCELLED' } });+ expect((await readdir(join(packageRoot, 'dist'))).sort()).toEqual([+ 'core.cjs',+ 'core.mjs',+ 'metadata.cjs',+ ]);+ },+ );++ it('waits for an in-flight generator to settle before reporting cancellation', async () => {+ const controller = new AbortController();+ let resolveStarted: (() => void) | undefined;+ let resolveFinish: (() => void) | undefined;+ const started = new Promise<void>((resolve) => {+ resolveStarted = resolve;+ });+ const finish = new Promise<void>((resolve) => {+ resolveFinish = resolve;+ });++ const replaceCoreClientSpy = vi+ .spyOn(clientGenerator, 'replaceCoreClient')+ .mockImplementation(async () => {+ resolveStarted?.();+ await finish;+ await writeFile(+ join(packageRoot, 'dist', 'core.cjs'),+ 'finished client',+ );+ });++ let settled = false;+ const operation = generateAppClient({+ appPath,+ schema: SCHEMA,+ signal: controller.signal,+ }).then((result) => {+ settled = true;+ return result;+ });++ await started;+ controller.abort();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(settled).toBe(false);+ resolveFinish?.();++ expect(await operation).toMatchObject({+ success: false,+ error: { code: 'CANCELLED' },+ });+ expect(replaceCoreClientSpy).toHaveBeenCalledTimes(1);+ expect(replaceCoreClientSpy).toHaveBeenCalledWith({+ packageRoot,+ schema: SCHEMA,+ });+ expect(await readFile(join(packageRoot, 'dist', 'core.cjs'), 'utf8')).toBe(+ 'finished client',+ );+ });++ it.each([false, true])(+ 'preserves a generator failure and partial writes when cancellation is %s',+ async (shouldCancel) => {+ const controller = new AbortController();+ const replaceCoreClientSpy = vi+ .spyOn(clientGenerator, 'replaceCoreClient')+ .mockImplementation(async () => {+ if (shouldCancel) {+ controller.abort();+ }++ await writeFile(+ join(packageRoot, 'dist', 'core.cjs'),+ 'partially replaced',+ );+ throw new Error('Client compilation failed');+ });++ expect(+ await generateAppClient({+ appPath,+ schema: SCHEMA,+ signal: controller.signal,+ }),+ ).toMatchObject({+ success: false,+ error: {+ code: 'CLIENT_GENERATION_FAILED',+ message: 'Client compilation failed',+ },+ });+ expect(replaceCoreClientSpy).toHaveBeenCalledTimes(1);+ expect(replaceCoreClientSpy).toHaveBeenCalledWith({+ packageRoot,+ schema: SCHEMA,+ });+ expect(+ await readFile(join(packageRoot, 'dist', 'core.cjs'), 'utf8'),+ ).toBe('partially replaced');+ },+ );+});diff --git a/packages/twenty-sdk/src/application-build/build-descriptor.ts b/packages/twenty-sdk/src/application-build/build-descriptor.tsindex 532ac7dea19..48f2acfffa3 100644--- a/packages/twenty-sdk/src/application-build/build-descriptor.ts+++ b/packages/twenty-sdk/src/application-build/build-descriptor.ts@@ -6,10 +6,16 @@ export const BUILD_DESCRIPTOR: BuildDescriptor = {protocolVersion: 1,sdkVersion: packageJson.version,requiredNode: packageJson.engines.node,- capabilities: ['build', 'typecheck', 'releaseSnapshot'],+ capabilities: ['build', 'typecheck', 'releaseSnapshot', 'generateClient'],fileWrites: {build: ['.twenty/snapshots/**'],typecheck: [],releaseSnapshot: ['.twenty/snapshots/**'],+ generateClient: [+ 'node_modules/twenty-client-sdk/dist/core/generated/**',+ 'node_modules/twenty-client-sdk/dist/core/generated.tmp/**',+ 'node_modules/twenty-client-sdk/dist/core.mjs',+ 'node_modules/twenty-client-sdk/dist/core.cjs',+ ],},};diff --git a/packages/twenty-sdk/src/application-build/generate-application-client.ts b/packages/twenty-sdk/src/application-build/generate-application-client.tsnew file mode 100644index 00000000000..28768df4614--- /dev/null+++ b/packages/twenty-sdk/src/application-build/generate-application-client.ts@@ -0,0 +1,63 @@+import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { isNonEmptyString, isObject } from '@sniptt/guards';+import { replaceCoreClient } from 'twenty-client-sdk/generate';++import {+ type BuildResult,+ type GenerateAppClientOptions,+} from '@/application-build/types';+import { validateAppPath } from '@/application-build/validate-app-path';++export const generateApplicationClient = async ({+ appPath,+ schema,+ signal,+}: GenerateAppClientOptions): Promise<BuildResult<null>> => {+ const validation = await validateAppPath(appPath);++ if (!validation.success) {+ return validation;+ }++ try {+ signal?.throwIfAborted();++ if (!isNonEmptyString(schema)) {+ throw new Error('schema must be a non-empty GraphQL schema string.');+ }++ const packageRoot = join(appPath, 'node_modules', 'twenty-client-sdk');+ const packageJson: unknown = JSON.parse(+ await readFile(join(packageRoot, 'package.json'), 'utf8'),+ );++ if (+ !isObject(packageJson) ||+ !('name' in packageJson) ||+ packageJson.name !== 'twenty-client-sdk'+ ) {+ throw new Error(+ 'Expected twenty-client-sdk in the app node_modules directory.',+ );+ }++ signal?.throwIfAborted();+ await replaceCoreClient({ packageRoot, schema });+ signal?.throwIfAborted();++ return { success: true, data: null, diagnostics: [] };+ } catch (error) {+ return {+ success: false,+ error: {+ code:+ signal?.aborted && Object.is(error, signal.reason)+ ? 'CANCELLED'+ : 'CLIENT_GENERATION_FAILED',+ message: error instanceof Error ? error.message : String(error),+ },+ diagnostics: [],+ };+ }+};diff --git a/packages/twenty-sdk/src/application-build/index.ts b/packages/twenty-sdk/src/application-build/index.tsindex 070c343bcd2..847d31911b8 100644--- a/packages/twenty-sdk/src/application-build/index.ts+++ b/packages/twenty-sdk/src/application-build/index.ts@@ -2,6 +2,7 @@ import {type BuildOperationOptions,type BuildResult,type BuildSnapshot,+ type GenerateAppClientOptions,} from '@/application-build/types';export { BUILD_DESCRIPTOR } from '@/application-build/build-descriptor';@@ -15,6 +16,7 @@ export type {BuildErrorCode,BuildOperationOptions,BuildResult,+ GenerateAppClientOptions,} from '@/application-build/types';export const buildAppSnapshot = async (@@ -33,3 +35,10 @@ export const releaseAppSnapshot = async (options: {buildId: string;}): Promise<BuildResult<null>> =>(await import('@/application-build/build-snapshot')).releaseSnapshot(options);++export const generateAppClient = async (+ options: GenerateAppClientOptions,+): Promise<BuildResult<null>> =>+ (+ await import('@/application-build/generate-application-client')+ ).generateApplicationClient(options);diff --git a/packages/twenty-sdk/src/application-build/types.ts b/packages/twenty-sdk/src/application-build/types.tsindex 87799274050..5860f63787b 100644--- a/packages/twenty-sdk/src/application-build/types.ts+++ b/packages/twenty-sdk/src/application-build/types.ts@@ -1,11 +1,18 @@-export type BuildCapability = 'build' | 'typecheck' | 'releaseSnapshot';+export type BuildCapability =+ | 'build'+ | 'typecheck'+ | 'releaseSnapshot'+ | 'generateClient';export type BuildDescriptor = {protocolVersion: number;sdkVersion: string;requiredNode: string;capabilities: readonly BuildCapability[];- fileWrites: Record<BuildCapability, readonly string[]>;+ fileWrites: Record<+ 'build' | 'typecheck' | 'releaseSnapshot',+ readonly string[]+ > & { generateClient?: readonly string[] };};export type BuildDiagnostic = {@@ -23,6 +30,7 @@ export type BuildErrorCode =| 'MANIFEST_BUILD_FAILED'| 'BUILD_FAILED'| 'TYPECHECK_FAILED'+ | 'CLIENT_GENERATION_FAILED'| 'SNAPSHOT_NOT_FOUND'| 'SNAPSHOT_RELEASE_FAILED';@@ -64,3 +72,7 @@ export type BuildSnapshot = {};export type BuildOperationOptions = { appPath: string; signal?: AbortSignal };++export type GenerateAppClientOptions = BuildOperationOptions & {+ schema: string;+};