Merge twenty-cli into twenty-sdk (#16150)
- Moves twenty-cli content into twenty-sdk - add a new twenty-sdk:0.1.0 version - this new twenty-sdk exports a cli command called 'twenty' (like twenty-cli before) - deprecates twenty-cli - simplify app init command base-project - use `twenty-sdk:0.1.0` in base project - move the "twenty-sdk/application" barrel to "twenty-sdk" - add `create-twenty-app` package <img width="1512" height="919" alt="image" src="https://github.com/user-attachments/assets/007bef45-4e71-419a-9213-cebed376adbf" /> <img width="1506" height="929" alt="image" src="https://github.com/user-attachments/assets/3de2fec6-1624-4923-ae13-f4e1cf165eb5" />
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
import { convertToLabel } from '../convert-to-label';
|
||||
|
||||
describe('convertToLabel', () => {
|
||||
it('should convert to label', () => {
|
||||
expect(convertToLabel('toto')).toBe('Toto');
|
||||
expect(convertToLabel('totoTata')).toBe('Toto tata');
|
||||
expect(convertToLabel('totoTataTiti')).toBe('Toto tata titi');
|
||||
expect(convertToLabel('toto-tata-titi')).toBe('Toto tata titi');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { getFunctionBaseFile } from '../get-function-base-file';
|
||||
|
||||
describe('getFunctionBaseFile', () => {
|
||||
it('should render proper file', () => {
|
||||
expect(
|
||||
getFunctionBaseFile({
|
||||
name: 'serverless-function-name',
|
||||
universalIdentifier: '71e45a58-41da-4ae4-8b73-a543c0a9d3d4',
|
||||
}),
|
||||
).toBe(`import { type FunctionConfig } from 'twenty-sdk';
|
||||
|
||||
export const main = async (params: {
|
||||
a: string;
|
||||
b: number;
|
||||
}): Promise<{ message: string }> => {
|
||||
const { a, b } = params;
|
||||
|
||||
// Rename the parameters and code below with your own logic
|
||||
// This is just an example
|
||||
const message = \`Hello, input: \${a} and \${b}\`;
|
||||
|
||||
return { message };
|
||||
};
|
||||
|
||||
export const config: FunctionConfig = {
|
||||
universalIdentifier: '71e45a58-41da-4ae4-8b73-a543c0a9d3d4',
|
||||
name: 'serverless-function-name',
|
||||
timeoutSeconds: 5,
|
||||
};
|
||||
|
||||
`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { getObjectDecoratedClass } from '../get-object-decorated-class';
|
||||
|
||||
describe('getObjectDecoratedClass', () => {
|
||||
it('should return proper object file', () => {
|
||||
expect(
|
||||
getObjectDecoratedClass({
|
||||
data: {
|
||||
universalIdentifier: '4122a047-260f-4cf1-bf4f-a268579d7ddf',
|
||||
nameSingular: 'name',
|
||||
namePlural: 'names',
|
||||
labelSingular: 'Name',
|
||||
labelPlural: 'Names',
|
||||
},
|
||||
name: 'MyNewObject',
|
||||
}),
|
||||
).toBe(
|
||||
`import { Object } from 'twenty-sdk';
|
||||
|
||||
@Object({
|
||||
universalIdentifier: '4122a047-260f-4cf1-bf4f-a268579d7ddf',
|
||||
nameSingular: 'name',
|
||||
namePlural: 'names',
|
||||
labelSingular: 'Name',
|
||||
labelPlural: 'Names',
|
||||
})
|
||||
export class MyNewObject {}
|
||||
`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,494 @@
|
||||
import { ensureDirSync, writeFileSync, removeSync } from 'fs-extra';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { loadManifest } from '../load-manifest';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
const write = (root: string, file: string, content: string) => {
|
||||
const abs = join(root, file);
|
||||
ensureDirSync(resolve(abs, '..'));
|
||||
writeFileSync(abs, content, 'utf8');
|
||||
};
|
||||
|
||||
const tsLibMock = `declare module 'tslib' {
|
||||
export const __decorate: any;
|
||||
export const __metadata: any;
|
||||
export const __param: any;
|
||||
export const __awaiter: any;
|
||||
export const __read: any;
|
||||
export const __spread: any;
|
||||
export const __spreadArray: any;
|
||||
export const __assign: any;
|
||||
}`;
|
||||
|
||||
const twentySdkTypesMock = `
|
||||
declare module 'twenty-sdk' {
|
||||
export type SyncableEntityOptions = { universalIdentifier: string };
|
||||
|
||||
type ApplicationVariable = SyncableEntityOptions & {
|
||||
value?: string;
|
||||
description?: string;
|
||||
isSecret?: boolean;
|
||||
};
|
||||
|
||||
export type ApplicationConfig = SyncableEntityOptions & {
|
||||
displayName?: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
applicationVariables?: Record<string, ApplicationVariable>;
|
||||
};
|
||||
|
||||
type RouteTrigger = {
|
||||
type: 'route';
|
||||
path: string;
|
||||
httpMethod: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
isAuthRequired: boolean;
|
||||
};
|
||||
|
||||
type CronTrigger = {
|
||||
type: 'cron';
|
||||
pattern: string;
|
||||
};
|
||||
|
||||
type DatabaseEventTrigger = {
|
||||
type: 'databaseEvent';
|
||||
eventName: string;
|
||||
};
|
||||
|
||||
type ServerlessFunctionTrigger = SyncableEntityOptions &
|
||||
(RouteTrigger | CronTrigger | DatabaseEventTrigger);
|
||||
|
||||
export type FunctionConfig = SyncableEntityOptions & {
|
||||
name?: string;
|
||||
description?: string;
|
||||
timeoutSeconds?: number;
|
||||
triggers?: ServerlessFunctionTrigger[];
|
||||
};
|
||||
|
||||
type ObjectMetadataOptions = SyncableEntityOptions & {
|
||||
nameSingular: string;
|
||||
namePlural: string;
|
||||
labelSingular: string;
|
||||
labelPlural: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
};
|
||||
|
||||
export const ObjectMetadata = (_: ObjectMetadataOptions): ClassDecorator => {
|
||||
return () => {};
|
||||
};
|
||||
|
||||
export class BaseObjectMetadata {}
|
||||
|
||||
export enum FieldMetadataType {
|
||||
TEXT = 'TEXT',
|
||||
FULL_NAME = 'FULL_NAME',
|
||||
ADDRESS = 'ADDRESS',
|
||||
SELECT = 'SELECT',
|
||||
DATE_TIME = 'DATE_TIME',
|
||||
}
|
||||
|
||||
export const FieldMetadata: (_: any) => PropertyDecorator;
|
||||
}
|
||||
`;
|
||||
|
||||
const serverlessFunctionMock = `
|
||||
import { type FunctionConfig } from 'twenty-sdk';
|
||||
|
||||
export const main = async (params: any): Promise<any> => {
|
||||
return {};
|
||||
}
|
||||
|
||||
export const config: FunctionConfig = {
|
||||
universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
|
||||
name: 'hello',
|
||||
timeoutSeconds: 2,
|
||||
triggers: [
|
||||
{
|
||||
universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
|
||||
type: 'route',
|
||||
path: '/post-card/create',
|
||||
httpMethod: 'GET',
|
||||
isAuthRequired: false
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
|
||||
type: 'cron',
|
||||
pattern: '0 0 1 1 *', // Every year 1st of January
|
||||
},
|
||||
{
|
||||
universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
|
||||
type: 'databaseEvent',
|
||||
eventName: 'person.created'
|
||||
}
|
||||
]
|
||||
};`;
|
||||
|
||||
const objectMock = `import {
|
||||
ObjectMetadata,
|
||||
BaseObjectMetadata,
|
||||
FieldMetadata,
|
||||
FieldMetadataType
|
||||
} from 'twenty-sdk';
|
||||
|
||||
enum PostCardStatus {
|
||||
DRAFT = 'DRAFT',
|
||||
SENT = 'SENT',
|
||||
DELIVERED = 'DELIVERED',
|
||||
RETURNED = 'RETURNED',
|
||||
}
|
||||
|
||||
@ObjectMetadata({
|
||||
universalIdentifier: '54b589ca-eeed-4950-a176-358418b85c05',
|
||||
nameSingular: 'postCard',
|
||||
namePlural: 'postCards',
|
||||
labelSingular: 'Post card',
|
||||
labelPlural: 'Post cards',
|
||||
description: ' A post card object',
|
||||
icon: 'IconMail',
|
||||
})
|
||||
export class PostCard extends BaseObjectMetadata {
|
||||
@FieldMetadata({
|
||||
universalIdentifier: '58a0a314-d7ea-4865-9850-7fb84e72f30b',
|
||||
type: FieldMetadataType.TEXT,
|
||||
label: 'Content',
|
||||
description: "Postcard's content",
|
||||
})
|
||||
content: string;
|
||||
|
||||
@FieldMetadata({
|
||||
universalIdentifier: 'c6aa31f3-da76-4ac6-889f-475e226009ac',
|
||||
type: FieldMetadataType.FULL_NAME,
|
||||
label: 'Recipient name',
|
||||
})
|
||||
recipientName: string;
|
||||
|
||||
@FieldMetadata({
|
||||
universalIdentifier: '95045777-a0ad-49ec-98f9-22f9fc0c8266',
|
||||
type: FieldMetadataType.ADDRESS,
|
||||
label: 'Recipient address',
|
||||
})
|
||||
recipientAddress: string;
|
||||
|
||||
@FieldMetadata({
|
||||
universalIdentifier: '87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
|
||||
type: FieldMetadataType.SELECT,
|
||||
label: 'Status',
|
||||
defaultValue: \`'\${PostCardStatus.DRAFT}'\`,
|
||||
options: [
|
||||
{
|
||||
value: PostCardStatus.DRAFT,
|
||||
label: 'Draft',
|
||||
position: 0,
|
||||
color: 'gray',
|
||||
},
|
||||
{
|
||||
value: PostCardStatus.SENT,
|
||||
label: 'Sent',
|
||||
position: 1,
|
||||
color: 'orange',
|
||||
},
|
||||
{
|
||||
value: PostCardStatus.DELIVERED,
|
||||
label: 'Delivered',
|
||||
position: 2,
|
||||
color: 'green',
|
||||
},
|
||||
{
|
||||
value: PostCardStatus.RETURNED,
|
||||
label: 'Returned',
|
||||
position: 3,
|
||||
color: 'orange',
|
||||
},
|
||||
],
|
||||
})
|
||||
status: 'draft' | 'sent' | 'delivered' | 'returned';
|
||||
|
||||
@FieldMetadata({
|
||||
universalIdentifier: 'e06abe72-5b44-4e7f-93be-afc185a3c433',
|
||||
type: FieldMetadataType.DATE_TIME,
|
||||
label: 'Delivered at',
|
||||
isNullable: true,
|
||||
defaultValue: null,
|
||||
})
|
||||
deliveredAt?: Date;
|
||||
}
|
||||
`;
|
||||
|
||||
const packageJsonMock = {
|
||||
name: 'my-app',
|
||||
version: '0.0.1',
|
||||
license: 'MIT',
|
||||
engines: {
|
||||
node: '^24.5.0',
|
||||
npm: 'please-use-yarn',
|
||||
yarn: '>=4.0.2',
|
||||
},
|
||||
packageManager: 'yarn@4.9.2',
|
||||
scripts: {
|
||||
'create-entity': 'twenty app add',
|
||||
dev: 'twenty app dev',
|
||||
generate: 'twenty app generate',
|
||||
sync: 'twenty app sync',
|
||||
uninstall: 'twenty app uninstall',
|
||||
auth: 'twenty auth login',
|
||||
},
|
||||
dependencies: {
|
||||
'twenty-sdk': '0.1.0',
|
||||
},
|
||||
devDependencies: {
|
||||
'@types/node': '^24.7.2',
|
||||
typescript: '^5.9.3',
|
||||
},
|
||||
};
|
||||
|
||||
const tsConfigJsonMock = {
|
||||
compileOnSave: false,
|
||||
compilerOptions: {
|
||||
sourceMap: true,
|
||||
declaration: true,
|
||||
outDir: './dist',
|
||||
rootDir: '.',
|
||||
moduleResolution: 'node',
|
||||
allowSyntheticDefaultImports: true,
|
||||
emitDecoratorMetadata: true,
|
||||
experimentalDecorators: true,
|
||||
importHelpers: true,
|
||||
allowUnreachableCode: false,
|
||||
strictNullChecks: true,
|
||||
alwaysStrict: true,
|
||||
noImplicitAny: true,
|
||||
strictBindCallApply: false,
|
||||
target: 'es2018',
|
||||
module: 'esnext',
|
||||
lib: ['es2020', 'dom'],
|
||||
skipLibCheck: true,
|
||||
skipDefaultLibCheck: true,
|
||||
resolveJsonModule: true,
|
||||
},
|
||||
|
||||
exclude: ['node_modules', 'dist', '**/*.test.ts', '**/*.spec.ts'],
|
||||
};
|
||||
|
||||
const yarnLockMock = `# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
# yarn lockfile v1
|
||||
`;
|
||||
|
||||
const applicationConfigMock = `import { type ApplicationConfig } from 'twenty-sdk';
|
||||
|
||||
const config: ApplicationConfig = {
|
||||
universalIdentifier: '${v4()}',
|
||||
displayName: 'My App',
|
||||
description: 'My app description',
|
||||
};
|
||||
|
||||
export default config;
|
||||
`;
|
||||
|
||||
describe('loadManifest (integration)', () => {
|
||||
const appDirectory = join(tmpdir(), 'test-app');
|
||||
|
||||
beforeEach(async () => {
|
||||
await ensureDirSync(appDirectory);
|
||||
|
||||
write(appDirectory, 'yarn.lock', yarnLockMock);
|
||||
|
||||
write(appDirectory, 'application.config.ts', applicationConfigMock);
|
||||
|
||||
write(
|
||||
appDirectory,
|
||||
'tsconfig.json',
|
||||
JSON.stringify(tsConfigJsonMock, null, 2),
|
||||
);
|
||||
|
||||
write(
|
||||
appDirectory,
|
||||
'package.json',
|
||||
JSON.stringify(packageJsonMock, null, 2),
|
||||
);
|
||||
|
||||
write(appDirectory, 'src/Account.ts', objectMock);
|
||||
|
||||
write(appDirectory, 'src/hello.ts', serverlessFunctionMock);
|
||||
|
||||
write(
|
||||
appDirectory,
|
||||
'src/types/twenty-sdk-application.d.ts',
|
||||
twentySdkTypesMock,
|
||||
);
|
||||
|
||||
write(
|
||||
appDirectory,
|
||||
'src/types/tslib.d.ts',
|
||||
// minimal + future-proof
|
||||
tsLibMock,
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
removeSync(appDirectory);
|
||||
});
|
||||
|
||||
it('builds a full manifest for a valid workspace', async () => {
|
||||
const { packageJson, yarnLock, manifest } =
|
||||
await loadManifest(appDirectory);
|
||||
|
||||
expect(packageJson.name).toBe('my-app');
|
||||
expect(packageJson.version).toBe('0.0.1');
|
||||
expect(packageJson.license).toBe('MIT');
|
||||
expect(yarnLock).toContain(
|
||||
'# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.',
|
||||
);
|
||||
|
||||
// application
|
||||
const { universalIdentifier: _, ...otherInfo } = manifest.application;
|
||||
expect(otherInfo).toEqual({
|
||||
displayName: 'My App',
|
||||
description: 'My app description',
|
||||
});
|
||||
|
||||
expect(manifest.objects.length).toBe(1);
|
||||
|
||||
for (const object of manifest.objects) {
|
||||
const { universalIdentifier: _, fields, ...otherInfo } = object;
|
||||
expect(otherInfo).toEqual({
|
||||
description: ' A post card object',
|
||||
icon: 'IconMail',
|
||||
labelPlural: 'Post cards',
|
||||
labelSingular: 'Post card',
|
||||
namePlural: 'postCards',
|
||||
nameSingular: 'postCard',
|
||||
});
|
||||
|
||||
expect(Array.isArray(fields)).toBe(true);
|
||||
|
||||
expect(fields).toEqual([
|
||||
{
|
||||
universalIdentifier: '58a0a314-d7ea-4865-9850-7fb84e72f30b',
|
||||
type: 'TEXT',
|
||||
label: 'Content',
|
||||
description: "Postcard's content",
|
||||
name: 'content',
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'c6aa31f3-da76-4ac6-889f-475e226009ac',
|
||||
type: 'FULL_NAME',
|
||||
label: 'Recipient name',
|
||||
name: 'recipientName',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '95045777-a0ad-49ec-98f9-22f9fc0c8266',
|
||||
type: 'ADDRESS',
|
||||
label: 'Recipient address',
|
||||
name: 'recipientAddress',
|
||||
},
|
||||
{
|
||||
universalIdentifier: '87b675b8-dd8c-4448-b4ca-20e5a2234a1e',
|
||||
type: 'SELECT',
|
||||
label: 'Status',
|
||||
defaultValue: "'DRAFT'",
|
||||
options: [
|
||||
{ value: 'DRAFT', label: 'Draft', position: 0, color: 'gray' },
|
||||
{ value: 'SENT', label: 'Sent', position: 1, color: 'orange' },
|
||||
{
|
||||
value: 'DELIVERED',
|
||||
label: 'Delivered',
|
||||
position: 2,
|
||||
color: 'green',
|
||||
},
|
||||
{
|
||||
value: 'RETURNED',
|
||||
label: 'Returned',
|
||||
position: 3,
|
||||
color: 'orange',
|
||||
},
|
||||
],
|
||||
name: 'status',
|
||||
},
|
||||
{
|
||||
universalIdentifier: 'e06abe72-5b44-4e7f-93be-afc185a3c433',
|
||||
type: 'DATE_TIME',
|
||||
label: 'Delivered at',
|
||||
isNullable: true,
|
||||
defaultValue: null,
|
||||
name: 'deliveredAt',
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
// serverless functions
|
||||
for (const serverlessFunction of manifest.serverlessFunctions) {
|
||||
const {
|
||||
universalIdentifier: _,
|
||||
handlerPath: __,
|
||||
triggers,
|
||||
...otherInfo
|
||||
} = serverlessFunction;
|
||||
|
||||
expect(otherInfo).toEqual({
|
||||
handlerName: 'main',
|
||||
name: 'hello',
|
||||
timeoutSeconds: 2,
|
||||
});
|
||||
|
||||
for (const trigger of triggers) {
|
||||
const { universalIdentifier: _, ...otherInfo } = trigger;
|
||||
switch (trigger.type) {
|
||||
case 'route':
|
||||
expect(otherInfo).toEqual({
|
||||
isAuthRequired: false,
|
||||
httpMethod: 'GET',
|
||||
path: '/post-card/create',
|
||||
type: 'route',
|
||||
});
|
||||
break;
|
||||
case 'cron':
|
||||
expect(otherInfo).toEqual({
|
||||
pattern: '0 0 1 1 *',
|
||||
type: 'cron',
|
||||
});
|
||||
break;
|
||||
case 'databaseEvent':
|
||||
expect(otherInfo).toEqual({
|
||||
eventName: 'person.created',
|
||||
type: 'databaseEvent',
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should not define serverless for util file', async () => {
|
||||
write(
|
||||
appDirectory,
|
||||
'src/utils/format.ts',
|
||||
`
|
||||
export const format = async (params: any): Promise<any> => {
|
||||
return {};
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const { manifest } = await loadManifest(appDirectory);
|
||||
expect(manifest.serverlessFunctions.length).toBe(1);
|
||||
});
|
||||
|
||||
it('manifest should contains typescript sources', async () => {
|
||||
const { manifest } = await loadManifest(appDirectory);
|
||||
// the method is already exercised in loadManifest; just assert again:
|
||||
expect(Object.keys(manifest.sources)).toEqual([
|
||||
'application.config.ts',
|
||||
'src',
|
||||
]);
|
||||
expect(Object.keys(manifest.sources['src'])).toEqual([
|
||||
'Account.ts',
|
||||
'hello.ts',
|
||||
]);
|
||||
});
|
||||
|
||||
it('manifest should contains typescript sources', async () => {
|
||||
const { shouldGenerate } = await loadManifest(appDirectory);
|
||||
expect(shouldGenerate).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { startCase } from 'lodash';
|
||||
|
||||
export const convertToLabel = (str: string) => {
|
||||
const s = startCase(str).toLowerCase();
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import path from 'path';
|
||||
import * as fs from 'fs-extra';
|
||||
|
||||
export const findPathFile = async (
|
||||
appPath: string,
|
||||
fileName: string,
|
||||
): Promise<string> => {
|
||||
const jsonPath = path.join(appPath, fileName);
|
||||
|
||||
if (await fs.pathExists(jsonPath)) {
|
||||
return jsonPath;
|
||||
}
|
||||
|
||||
throw new Error(`${fileName} not found in ${appPath}`);
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
type Diagnostic,
|
||||
formatDiagnosticsWithColorAndContext,
|
||||
sys,
|
||||
} from 'typescript';
|
||||
|
||||
export const formatAndWarnTsDiagnostics = ({
|
||||
diagnostics,
|
||||
}: {
|
||||
diagnostics: Diagnostic[];
|
||||
}) => {
|
||||
if (diagnostics.length > 0) {
|
||||
const formattedDiagnostics = formatDiagnosticsWithColorAndContext(
|
||||
diagnostics,
|
||||
{
|
||||
getCanonicalFileName: (f) => f,
|
||||
getCurrentDirectory: sys.getCurrentDirectory,
|
||||
getNewLine: () => sys.newLine,
|
||||
},
|
||||
);
|
||||
|
||||
console.warn(formattedDiagnostics);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import { join } from 'path';
|
||||
import { CURRENT_EXECUTION_DIRECTORY } from '../constants/current-execution-directory';
|
||||
|
||||
export const formatPath = (appPath?: string) => {
|
||||
return appPath && !appPath?.startsWith('/')
|
||||
? join(CURRENT_EXECUTION_DIRECTORY, appPath)
|
||||
: appPath;
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import kebabCase from 'lodash.kebabcase';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
export const getFunctionBaseFile = ({
|
||||
name,
|
||||
universalIdentifier = v4(),
|
||||
}: {
|
||||
name: string;
|
||||
universalIdentifier?: string;
|
||||
}) => {
|
||||
const kebabCaseName = kebabCase(name);
|
||||
|
||||
return `import { type FunctionConfig } from 'twenty-sdk';
|
||||
|
||||
export const main = async (params: {
|
||||
a: string;
|
||||
b: number;
|
||||
}): Promise<{ message: string }> => {
|
||||
const { a, b } = params;
|
||||
|
||||
// Rename the parameters and code below with your own logic
|
||||
// This is just an example
|
||||
const message = \`Hello, input: $\{a} and $\{b}\`;
|
||||
|
||||
return { message };
|
||||
};
|
||||
|
||||
export const config: FunctionConfig = {
|
||||
universalIdentifier: '${universalIdentifier}',
|
||||
name: '${kebabCaseName}',
|
||||
timeoutSeconds: 5,
|
||||
};
|
||||
|
||||
`;
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import camelcase from 'lodash.camelcase';
|
||||
|
||||
export const getObjectDecoratedClass = ({
|
||||
data,
|
||||
name,
|
||||
}: {
|
||||
data: object;
|
||||
name: string;
|
||||
}) => {
|
||||
const decoratorOptions = Object.entries(data)
|
||||
.map(([key, value]) => ` ${key}: '${value}',`)
|
||||
.join('\n');
|
||||
|
||||
const camelCaseName = camelcase(name);
|
||||
|
||||
const className = camelCaseName[0].toUpperCase() + camelCaseName.slice(1);
|
||||
|
||||
return `import { Object } from 'twenty-sdk';
|
||||
|
||||
@Object({
|
||||
${decoratorOptions}
|
||||
})
|
||||
export class ${className} {}
|
||||
`;
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
import { join } from 'path';
|
||||
import {
|
||||
createProgram,
|
||||
formatDiagnosticsWithColorAndContext,
|
||||
parseJsonConfigFileContent,
|
||||
readConfigFile,
|
||||
sys,
|
||||
type Program,
|
||||
type Diagnostic,
|
||||
} from 'typescript';
|
||||
|
||||
const getProgramFromTsconfig = ({
|
||||
appPath,
|
||||
tsconfigPath = 'tsconfig.json',
|
||||
}: {
|
||||
appPath: string;
|
||||
tsconfigPath?: string;
|
||||
}) => {
|
||||
const configFile = readConfigFile(join(appPath, tsconfigPath), sys.readFile);
|
||||
if (configFile.error)
|
||||
throw new Error(
|
||||
formatDiagnosticsWithColorAndContext([configFile.error], {
|
||||
getCanonicalFileName: (f) => f,
|
||||
getCurrentDirectory: sys.getCurrentDirectory,
|
||||
getNewLine: () => sys.newLine,
|
||||
}),
|
||||
);
|
||||
const parsed = parseJsonConfigFileContent(configFile.config, sys, appPath);
|
||||
if (parsed.errors.length) {
|
||||
throw new Error(
|
||||
formatDiagnosticsWithColorAndContext(parsed.errors, {
|
||||
getCanonicalFileName: (f) => f,
|
||||
getCurrentDirectory: sys.getCurrentDirectory,
|
||||
getNewLine: () => sys.newLine,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return createProgram(parsed.fileNames, parsed.options);
|
||||
};
|
||||
|
||||
export const getTsProgramAndDiagnostics = async ({
|
||||
appPath,
|
||||
}: {
|
||||
appPath: string;
|
||||
}): Promise<{ program: Program; diagnostics: Diagnostic[] }> => {
|
||||
const program = getProgramFromTsconfig({
|
||||
appPath,
|
||||
tsconfigPath: 'tsconfig.json',
|
||||
});
|
||||
|
||||
return {
|
||||
diagnostics: [
|
||||
...program.getSyntacticDiagnostics(),
|
||||
...program.getSemanticDiagnostics(),
|
||||
...program.getGlobalDiagnostics(),
|
||||
],
|
||||
program,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import { type ParseError, parse as parseJsonc } from 'jsonc-parser';
|
||||
|
||||
export interface JsoncParseOptions {
|
||||
allowTrailingComma?: boolean;
|
||||
disallowComments?: boolean;
|
||||
allowEmptyContent?: boolean;
|
||||
}
|
||||
|
||||
export class JsoncParseError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly parseErrors: ParseError[],
|
||||
public readonly filePath?: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'JsoncParseError';
|
||||
}
|
||||
}
|
||||
|
||||
export const parseJsoncString = (
|
||||
content: string,
|
||||
options: JsoncParseOptions = {},
|
||||
): any => {
|
||||
const parseErrors: ParseError[] = [];
|
||||
|
||||
const result = parseJsonc(content, parseErrors, {
|
||||
allowTrailingComma: options.allowTrailingComma ?? true,
|
||||
disallowComments: options.disallowComments ?? false,
|
||||
allowEmptyContent: options.allowEmptyContent ?? false,
|
||||
});
|
||||
|
||||
if (parseErrors.length > 0) {
|
||||
const errorMessages = parseErrors.map(
|
||||
(error) => `Line ${error.offset}: ${error.error}`,
|
||||
);
|
||||
throw new JsoncParseError(
|
||||
`JSONC parse errors:\n${errorMessages.join('\n')}`,
|
||||
parseErrors,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export const parseTextFile = async (filePath: string) => {
|
||||
return await fs.readFile(filePath, 'utf8');
|
||||
};
|
||||
|
||||
export const parseJsoncFile = async (
|
||||
filePath: string,
|
||||
options: JsoncParseOptions = {},
|
||||
): Promise<any> => {
|
||||
try {
|
||||
const content = await fs.readFile(filePath, 'utf8');
|
||||
return parseJsoncString(content, options);
|
||||
} catch (error) {
|
||||
if (error instanceof JsoncParseError) {
|
||||
throw new JsoncParseError(error.message, error.parseErrors, filePath);
|
||||
}
|
||||
throw new Error(`Failed to read file ${filePath}: ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
export const writeJsoncFile = async (
|
||||
filePath: string,
|
||||
data: any,
|
||||
options: { spaces?: number } = {},
|
||||
): Promise<void> => {
|
||||
const content = JSON.stringify(data, null, options.spaces ?? 2);
|
||||
await fs.writeFile(filePath, content, 'utf8');
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import dotenv from 'dotenv';
|
||||
import { findPathFile } from './find-path-file';
|
||||
|
||||
export const loadEnvVariables = async (appPath: string) => {
|
||||
let envFile = '';
|
||||
|
||||
try {
|
||||
const envFilePath = await findPathFile(appPath, '.env');
|
||||
|
||||
envFile = await fs.readFile(envFilePath, 'utf8');
|
||||
} catch {
|
||||
// Allow missing .env
|
||||
}
|
||||
|
||||
return dotenv.parse(envFile);
|
||||
};
|
||||
@@ -0,0 +1,532 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import { posix, relative, sep } from 'path';
|
||||
import {
|
||||
type Decorator,
|
||||
type Expression,
|
||||
type FunctionDeclaration,
|
||||
type Modifier,
|
||||
type Node,
|
||||
type Program,
|
||||
type SourceFile,
|
||||
SyntaxKind,
|
||||
type VariableDeclaration,
|
||||
forEachChild,
|
||||
getDecorators,
|
||||
isArrayLiteralExpression,
|
||||
isArrowFunction,
|
||||
isCallExpression,
|
||||
isClassDeclaration,
|
||||
isComputedPropertyName,
|
||||
isExportAssignment,
|
||||
isFunctionExpression,
|
||||
isIdentifier,
|
||||
isImportDeclaration,
|
||||
isNoSubstitutionTemplateLiteral,
|
||||
isNumericLiteral,
|
||||
isObjectLiteralExpression,
|
||||
isPropertyAccessExpression,
|
||||
isPropertyAssignment,
|
||||
isPropertyDeclaration,
|
||||
isShorthandPropertyAssignment,
|
||||
isStringLiteralLike,
|
||||
isTemplateExpression,
|
||||
isVariableStatement,
|
||||
} from 'typescript';
|
||||
import { GENERATED_FOLDER_NAME } from '../services/generate.service';
|
||||
import {
|
||||
type AppManifest,
|
||||
type Application,
|
||||
type FieldMetadata,
|
||||
type ObjectManifest,
|
||||
type PackageJson,
|
||||
type ServerlessFunctionManifest,
|
||||
type Sources,
|
||||
} from '../types/config.types';
|
||||
import { findPathFile } from '../utils/find-path-file';
|
||||
import { getTsProgramAndDiagnostics } from '../utils/get-ts-program-and-diagnostics';
|
||||
import { parseJsoncFile, parseTextFile } from '../utils/jsonc-parser';
|
||||
import { formatAndWarnTsDiagnostics } from './format-and-warn-ts-diagnostics';
|
||||
|
||||
type JSONValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| JSONValue[]
|
||||
| { [k: string]: JSONValue };
|
||||
|
||||
const isDecoratorNamed = (node: Decorator, name: string): node is Decorator => {
|
||||
const expr = node.expression;
|
||||
if (isCallExpression(expr)) {
|
||||
if (isIdentifier(expr.expression)) return expr.expression.text === name;
|
||||
if (isPropertyAccessExpression(expr.expression))
|
||||
return expr.expression.name.text === name;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const exprToValue = (expr: Expression): JSONValue => {
|
||||
if (isStringLiteralLike(expr)) return expr.text;
|
||||
if (isNumericLiteral(expr)) return Number(expr.text);
|
||||
if (expr.kind === SyntaxKind.TrueKeyword) return true;
|
||||
if (expr.kind === SyntaxKind.FalseKeyword) return false;
|
||||
if (expr.kind === SyntaxKind.NullKeyword) return null;
|
||||
|
||||
if (isPropertyAccessExpression(expr)) {
|
||||
if (isIdentifier(expr.expression) && isIdentifier(expr.name)) {
|
||||
return expr.name.text;
|
||||
}
|
||||
return String(expr.getText());
|
||||
}
|
||||
|
||||
if (isNoSubstitutionTemplateLiteral(expr)) {
|
||||
return expr.text;
|
||||
}
|
||||
if (isTemplateExpression(expr)) {
|
||||
let out = expr.head.text;
|
||||
for (const span of expr.templateSpans) {
|
||||
const v = exprToValue(span.expression);
|
||||
out += String(v) + span.literal.text;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
if (isArrayLiteralExpression(expr)) {
|
||||
return expr.elements.map((e) =>
|
||||
e.kind === SyntaxKind.SpreadElement ? [] : exprToValue(e),
|
||||
);
|
||||
}
|
||||
|
||||
if (isObjectLiteralExpression(expr)) {
|
||||
const obj: Record<string, JSONValue> = {};
|
||||
for (const prop of expr.properties) {
|
||||
if (isPropertyAssignment(prop)) {
|
||||
const key =
|
||||
isIdentifier(prop.name) || isStringLiteralLike(prop.name)
|
||||
? prop.name.text
|
||||
: isComputedPropertyName(prop.name) &&
|
||||
isStringLiteralLike(prop.name.expression)
|
||||
? prop.name.expression.text
|
||||
: undefined;
|
||||
if (key) obj[key] = exprToValue(prop.initializer);
|
||||
} else if (isShorthandPropertyAssignment(prop)) {
|
||||
// Unsupported without a checker; skip to keep it "light".
|
||||
// Could resolve via typechecker if needed.
|
||||
}
|
||||
// getters/setters/methods are ignored intentionally
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
// Keep it intentionally strict/lightweight: anything non-literal becomes a string fallback.
|
||||
// You can throw instead if you prefer to fail fast.
|
||||
return isIdentifier(expr)
|
||||
? expr.text
|
||||
: String((expr as any).getText?.() ?? '');
|
||||
};
|
||||
|
||||
const getFirstArgObject = (dec: Decorator) => {
|
||||
if (!isCallExpression(dec.expression)) return undefined;
|
||||
const [firstArg] = dec.expression.arguments;
|
||||
return firstArg && isObjectLiteralExpression(firstArg)
|
||||
? (exprToValue(firstArg) as Record<string, JSONValue>)
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const collectObjects = (program: Program) => {
|
||||
const manifest: ObjectManifest[] = [];
|
||||
|
||||
for (const sf of program.getSourceFiles()) {
|
||||
if (sf.isDeclarationFile) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const visit = (node: Node) => {
|
||||
if (isClassDeclaration(node) && getDecorators(node)?.length) {
|
||||
const decorators = getDecorators(node);
|
||||
const objectDec = decorators?.find(
|
||||
(d) =>
|
||||
isDecoratorNamed(d, 'ObjectMetadata') ||
|
||||
isDecoratorNamed(d, 'Object'),
|
||||
);
|
||||
if (objectDec) {
|
||||
const cfg = getFirstArgObject(objectDec);
|
||||
if (cfg && typeof cfg === 'object' && !Array.isArray(cfg)) {
|
||||
const fields: Array<Record<string, JSONValue>> = [];
|
||||
|
||||
for (const member of node.members) {
|
||||
if (!isPropertyDeclaration(member)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fieldDec = getDecorators(member)?.find(
|
||||
(d) =>
|
||||
isDecoratorNamed(d, 'FieldMetadata') ||
|
||||
isDecoratorNamed(d, 'Field'),
|
||||
);
|
||||
|
||||
if (!fieldDec) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fieldCfg = getFirstArgObject(fieldDec);
|
||||
|
||||
if (!fieldCfg) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to attach the TypeScript property name as "name"
|
||||
let name: string | undefined;
|
||||
if (member.name && isIdentifier(member.name)) {
|
||||
name = member.name.text;
|
||||
} else {
|
||||
// fallback to AST text if not a simple identifier
|
||||
name = member.name?.getText?.() ?? undefined;
|
||||
}
|
||||
|
||||
fields.push({
|
||||
...(fieldCfg as FieldMetadata),
|
||||
...(name ? { name } : {}),
|
||||
});
|
||||
}
|
||||
manifest.push({ ...(cfg as any), fields } as ObjectManifest);
|
||||
}
|
||||
}
|
||||
}
|
||||
forEachChild(node, visit);
|
||||
};
|
||||
|
||||
visit(sf);
|
||||
}
|
||||
|
||||
return manifest;
|
||||
};
|
||||
|
||||
// Add if you want a small guard for "export" presence on statements
|
||||
const hasExportModifier = (st: any) =>
|
||||
st.modifiers?.some((m: Modifier) => m.kind === SyntaxKind.ExportKeyword) ??
|
||||
false;
|
||||
|
||||
/**
|
||||
* Finds (and validates) the new serverless file shape:
|
||||
* - exactly 2 exported bindings
|
||||
* - one must be `config` (typed FunctionConfig)
|
||||
* - the other must be a function (exported function declaration, or const initialized with arrow/function expression)
|
||||
*/
|
||||
const findHandlerAndConfig = (
|
||||
sf: SourceFile,
|
||||
): {
|
||||
handlerName: ServerlessFunctionManifest['handlerName'];
|
||||
configObject: Pick<
|
||||
ServerlessFunctionManifest,
|
||||
| 'universalIdentifier'
|
||||
| 'name'
|
||||
| 'description'
|
||||
| 'timeoutSeconds'
|
||||
| 'triggers'
|
||||
>;
|
||||
} => {
|
||||
type Exported = {
|
||||
name: string;
|
||||
kind: 'function' | 'const';
|
||||
init?: Expression;
|
||||
declNode: Node;
|
||||
};
|
||||
|
||||
const exported: Exported[] = [];
|
||||
|
||||
// 1) export const X = <arrow|function expr>
|
||||
for (const st of sf.statements) {
|
||||
if (!isVariableStatement(st) || !hasExportModifier(st)) continue;
|
||||
|
||||
for (const decl of st.declarationList.declarations) {
|
||||
if (!isIdentifier(decl.name)) continue;
|
||||
|
||||
const name = decl.name.text;
|
||||
const init = decl.initializer ?? undefined;
|
||||
|
||||
exported.push({
|
||||
name,
|
||||
kind: 'const',
|
||||
init,
|
||||
declNode: decl,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 2) export function X() { ... }
|
||||
for (const st of sf.statements) {
|
||||
if (st.kind === SyntaxKind.FunctionDeclaration && hasExportModifier(st)) {
|
||||
const fd = st as FunctionDeclaration;
|
||||
if (fd.name && isIdentifier(fd.name)) {
|
||||
exported.push({
|
||||
name: fd.name.text,
|
||||
kind: 'function',
|
||||
init: undefined,
|
||||
declNode: fd,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Enforce exactly two exports
|
||||
const unique = Array.from(new Map(exported.map((e) => [e.name, e])).values());
|
||||
if (unique.length !== 2) {
|
||||
throw new Error(
|
||||
`Serverless file ${sf.fileName} must export exactly 2 bindings (handler + config). Found: ${unique.map((e) => e.name).join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Find config
|
||||
const configExport = unique.find((e) => e.name === 'config');
|
||||
if (!configExport) {
|
||||
throw new Error(
|
||||
`Serverless file ${sf.fileName} must export a binding named "config".`,
|
||||
);
|
||||
}
|
||||
// Must be initialized to an object literal
|
||||
if (!configExport.init || !isObjectLiteralExpression(configExport.init)) {
|
||||
throw new Error(
|
||||
`"config" in ${sf.fileName} must be initialized to an object literal.`,
|
||||
);
|
||||
}
|
||||
// (Light) type guard: ensure declared type mentions FunctionConfig if present
|
||||
const maybeVarDecl = configExport.declNode as VariableDeclaration;
|
||||
if ('type' in maybeVarDecl && maybeVarDecl.type) {
|
||||
const typeText = maybeVarDecl.type.getText(sf);
|
||||
if (!/\bFunctionConfig\b/.test(typeText)) {
|
||||
throw new Error(
|
||||
`"config" in ${sf.fileName} must be typed as FunctionConfig (got: ${typeText}).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const configObject = exprToValue(configExport.init) as Pick<
|
||||
ServerlessFunctionManifest,
|
||||
| 'universalIdentifier'
|
||||
| 'name'
|
||||
| 'description'
|
||||
| 'timeoutSeconds'
|
||||
| 'triggers'
|
||||
>;
|
||||
|
||||
// Identify the handler: the other export
|
||||
const handlerExport = unique.find((e) => e.name !== 'config');
|
||||
if (!handlerExport) {
|
||||
throw new Error(`Could not find the handler export in ${sf.fileName}.`);
|
||||
}
|
||||
|
||||
// If it's a const, make sure it’s a function-ish initializer
|
||||
if (handlerExport.kind === 'const') {
|
||||
const init = handlerExport.init;
|
||||
const isFuncLike =
|
||||
!!init && (isArrowFunction(init) || isFunctionExpression(init));
|
||||
if (!isFuncLike) {
|
||||
throw new Error(
|
||||
`Handler "${handlerExport.name}" in ${sf.fileName} must be a function (arrow or function expression).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
handlerName: handlerExport.name,
|
||||
configObject,
|
||||
};
|
||||
};
|
||||
|
||||
const posixRelativeFromCwd = (fileName: string, appPath: string) => {
|
||||
const rel = relative(appPath, fileName);
|
||||
// normalize to posix separators for portability / manifest stability
|
||||
return rel.split(sep).join(posix.sep);
|
||||
};
|
||||
|
||||
const collectServerlessFunctions = (program: Program, appPath: string) => {
|
||||
const serverlessFunctions: ServerlessFunctionManifest[] = [];
|
||||
|
||||
for (const sf of program.getSourceFiles()) {
|
||||
if (sf.isDeclarationFile) continue;
|
||||
|
||||
try {
|
||||
const { handlerName, configObject } = findHandlerAndConfig(sf);
|
||||
|
||||
const handlerPath = posixRelativeFromCwd(sf.fileName, appPath);
|
||||
|
||||
serverlessFunctions.push({
|
||||
...configObject,
|
||||
handlerPath,
|
||||
handlerName,
|
||||
});
|
||||
} catch {
|
||||
// Not a serverless file under the new format — ignore and continue scanning.
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return serverlessFunctions;
|
||||
};
|
||||
|
||||
const setNested = (root: Sources, parts: string[], value: string) => {
|
||||
let cur: Sources = root;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const key = parts[i];
|
||||
if (i === parts.length - 1) {
|
||||
cur[key] = value;
|
||||
} else {
|
||||
cur[key] = (cur[key] ?? {}) as Sources;
|
||||
cur = cur[key] as Sources;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const loadFolderContentIntoJson = async (
|
||||
program: Program,
|
||||
appPath: string,
|
||||
): Promise<Sources> => {
|
||||
const sources: Sources = {};
|
||||
|
||||
// Iterate only files the TS program knows about.
|
||||
for (const sf of program.getSourceFiles()) {
|
||||
const abs = sf.fileName;
|
||||
|
||||
// Skip .d.ts and anything outside sourcePath
|
||||
if (sf.isDeclarationFile) continue;
|
||||
if (!abs.startsWith(appPath + sep) && abs !== appPath) continue;
|
||||
|
||||
// Keep only TS/TSX files
|
||||
if (!(abs.endsWith('.ts') || abs.endsWith('.tsx'))) continue;
|
||||
|
||||
// Optional extra guard (usually unnecessary if tsconfig excludes node_modules)
|
||||
if (abs.includes(`${sep}node_modules${sep}`)) continue;
|
||||
|
||||
const relFromRoot = relative(appPath, abs);
|
||||
const parts = relFromRoot.split(sep);
|
||||
|
||||
const content = await fs.readFile(abs, 'utf8');
|
||||
setNested(sources, parts, content);
|
||||
}
|
||||
|
||||
return sources;
|
||||
};
|
||||
|
||||
export const extractTwentyAppConfig = (program: Program): Application => {
|
||||
for (const sf of program.getSourceFiles()) {
|
||||
if (sf.isDeclarationFile || !sf.fileName.endsWith('application.config.ts'))
|
||||
continue;
|
||||
|
||||
let found: Application | undefined;
|
||||
|
||||
const visit = (node: any): void => {
|
||||
// Look for "export default twentyAppConfig"
|
||||
if (isExportAssignment(node) && isIdentifier(node.expression)) {
|
||||
const varName = node.expression.text;
|
||||
|
||||
// find the corresponding variable declaration
|
||||
for (const stmt of sf.statements) {
|
||||
if (isVariableStatement(stmt)) {
|
||||
for (const decl of stmt.declarationList.declarations) {
|
||||
if (isIdentifier(decl.name) && decl.name.text === varName) {
|
||||
if (
|
||||
decl.initializer &&
|
||||
isObjectLiteralExpression(decl.initializer)
|
||||
) {
|
||||
found = exprToValue(decl.initializer) as Application;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!found) forEachChild(node, visit);
|
||||
};
|
||||
|
||||
visit(sf);
|
||||
|
||||
if (found) return found;
|
||||
}
|
||||
|
||||
throw new Error('Could not find default exported ApplicationConfig');
|
||||
};
|
||||
|
||||
const isGeneratedModuleUsedInProgram = (program: Program): boolean => {
|
||||
for (const sf of program.getSourceFiles()) {
|
||||
if (sf.isDeclarationFile) continue;
|
||||
|
||||
let found = false;
|
||||
|
||||
const visit = (node: Node): void => {
|
||||
if (found) return;
|
||||
|
||||
if (isImportDeclaration(node)) {
|
||||
const moduleSpecifier = node.moduleSpecifier;
|
||||
|
||||
if (isStringLiteralLike(moduleSpecifier)) {
|
||||
const moduleText = moduleSpecifier.text;
|
||||
|
||||
// Match ../../generated, ../generated, ./foo/generated, etc.
|
||||
const isGeneratedModule =
|
||||
moduleText === GENERATED_FOLDER_NAME ||
|
||||
moduleText.endsWith(`/${GENERATED_FOLDER_NAME}`);
|
||||
|
||||
if (isGeneratedModule && node.importClause) {
|
||||
found = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
forEachChild(node, visit);
|
||||
};
|
||||
|
||||
visit(sf);
|
||||
|
||||
if (found) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
export const loadManifest = async (
|
||||
appPath: string,
|
||||
): Promise<{
|
||||
packageJson: PackageJson;
|
||||
yarnLock: string;
|
||||
manifest: AppManifest;
|
||||
shouldGenerate: boolean;
|
||||
}> => {
|
||||
const packageJson = await parseJsoncFile(
|
||||
await findPathFile(appPath, 'package.json'),
|
||||
);
|
||||
|
||||
const yarnLock = await parseTextFile(
|
||||
await findPathFile(appPath, 'yarn.lock'),
|
||||
);
|
||||
|
||||
const { diagnostics, program } = await getTsProgramAndDiagnostics({
|
||||
appPath,
|
||||
});
|
||||
|
||||
formatAndWarnTsDiagnostics({
|
||||
diagnostics,
|
||||
});
|
||||
|
||||
const [objects, serverlessFunctions, application, sources] = [
|
||||
collectObjects(program),
|
||||
collectServerlessFunctions(program, appPath),
|
||||
extractTwentyAppConfig(program),
|
||||
await loadFolderContentIntoJson(program, appPath),
|
||||
];
|
||||
|
||||
const shouldGenerate = isGeneratedModuleUsedInProgram(program);
|
||||
|
||||
return {
|
||||
packageJson,
|
||||
yarnLock,
|
||||
manifest: {
|
||||
application,
|
||||
objects,
|
||||
serverlessFunctions,
|
||||
sources,
|
||||
},
|
||||
shouldGenerate,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user