The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
chore(cli): check the twenty package before publishing and bump it to 0.4.0 (#27489)
Weikoac68a396173d
diff --git a/.github/workflows/ci-cli.yaml b/.github/workflows/ci-cli.yamlindex 37437512cd5..35ba968f131 100644--- a/.github/workflows/ci-cli.yaml+++ b/.github/workflows/ci-cli.yaml@@ -22,7 +22,6 @@ jobs:packages/twenty-sdk/**packages/twenty-client-sdk/**packages/twenty-ui/**- packages/create-twenty-app/**.github/actions/yarn-install/**.github/workflows/ci-cli.yamlpackage.jsondiff --git a/LICENSE b/LICENSEindex 085e0c6baf7..7f79939e3b6 100644--- a/LICENSE+++ b/LICENSE@@ -4,7 +4,7 @@ This project is mostly licensed under the GNU Affero General Public License v3.01. Certain files are licensed under a commercial license. These files are clearly marked with the following comment at the top of the file: /* @license Enterprise */Files with this comment are not licensed under the AGPLv3, but instead are subject to the commercial license terms defined at the end of this file.-2. Certain packages are licensed under the MIT license instead of the AGPLv3, as indicated by the license field of their package.json and the LICENSE file at the package root. This currently includes the application development toolkit (twenty-sdk, twenty-client-sdk, create-twenty-app, twenty-shared), the twenty-ui component library, and the applications under packages/twenty-apps.+2. Certain packages are licensed under the MIT license instead of the AGPLv3, as indicated by the license field of their package.json and the LICENSE file at the package root. This currently includes the application development toolkit (the twenty CLI, twenty-sdk, twenty-client-sdk, create-twenty-app, twenty-shared), the twenty-ui component library, and the applications under packages/twenty-apps.The AGPLv3 applies to the rest of the project, with the following additional permission:diff --git a/packages/twenty-cli/CONTRIBUTING.md b/packages/twenty-cli/CONTRIBUTING.mdindex 9b05907e573..42dc0310a0f 100644--- a/packages/twenty-cli/CONTRIBUTING.md+++ b/packages/twenty-cli/CONTRIBUTING.md@@ -52,7 +52,7 @@ changed server workflows against a disposable workspace when appropriate.| `src/doctor` | Read-only setup and connection diagnostics || `src/app` | Project tooling and application lifecycle, see its [module map](src/app/README.md) || `src/input`, `src/output` | Input parsing, human/JSON/NDJSON output and error contracts |-| `app-template-overlay` | CLI-based test harness applied over the shared app template |+| `app-template` | App source, configuration and CLI-based integration-test harness copied by `app init` |Command definitions are the source for help and `twenty commands`. Keep handlerslazy so discovery does not load compiler or app code. Put a workflow's rules in@@ -85,7 +85,7 @@ Changes must preserve these contracts:## PackagingVite builds the CLI, its worker and lazy chunks into `dist`. It also copies the-`create-twenty-app` template and the CLI test-harness overlay there. Chokidar,+CLI-owned `app-template` there. Chokidar,esbuild, tinyglobby and the CLI's TypeScript parser are runtime dependencies;other imported libraries are bundled. The parser is separate from the app'scompiler used for typechecking.@@ -103,14 +103,41 @@ yarn nx run twenty-cli:test:packageThis runs the binary declared in the workspace's `package.json` directly, packsthe CLI, and installs the archive with only its production dependencies in atemporary directory outside the monorepo. It checks help, offline doctor, app initialization including the-template overlay, and a compiler diagnostic from the installed worker. npm+integration-test harness, and a compiler diagnostic from the installed worker. npmregistry access is required for installation; the commands do not contact aTwenty workspace. Temporary files are removed afterward, and nothing ispublished. CI runs the same target for CLI and dependency changes.+## Releases++The CLI has its own release line. A `cli/vX.Y.Z` tag publishes the `twenty`+package at that version, which must match `package.json`.++`app init` pins `twenty-client-sdk`, `twenty-sdk` and `twenty-ui` to the+`twenty-sdk` version of the commit the CLI was built from. `main` moves+to the next, unpublished SDK version right after each SDK release, so a CLI+release must be built from the commit of an SDK release:++1. Merge the CLI version bump before that SDK release is tagged.+2. Once the `sdk/vA.B.C` packages are on npm, tag the same commit `cli/vX.Y.Z`.++`yarn npm publish` first runs `scripts/check-publish.mjs`, which needs a fresh+build and npm registry access. It fails when the executable, worker, lazy chunks+or templates are missing, when `dist` was built for another version, when one of+its CLI runs fails or times out, or when `app init` would pin versions that are+not on npm. An unreachable registry is reported separately from a missing+version. The check does not read tags: it confirms that the pinned versions are+published, and tagging the SDK release commit remains a release step. Its tests+run with `twenty-cli:test:package`. To run the check itself before tagging:++```bash+yarn nx build twenty-cli+node packages/twenty-cli/scripts/check-publish.mjs+```+## App integration tests-`app-template-overlay` supplies the integration-test setup for CLI-created apps.+`app-template/src/__tests__` supplies the integration-test setup for CLI-created apps.It deploys the app before tests and uninstalls it afterward by invoking theinstalled CLI with `--json`. Apps invoke the executable rather than import theCLI as a library or add it as a dependency. See thediff --git a/packages/twenty-cli/LICENSE b/packages/twenty-cli/LICENSEnew file mode 100644index 00000000000..d5b4186eb66--- /dev/null+++ b/packages/twenty-cli/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2023-present Twenty.com, PBC++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/twenty-cli/app-template/.nvmrc b/packages/twenty-cli/app-template/.nvmrcnew file mode 100644index 00000000000..341cb50613a--- /dev/null+++ b/packages/twenty-cli/app-template/.nvmrc@@ -0,0 +1 @@+24.5.0diff --git a/packages/twenty-cli/app-template/.oxlintrc.json b/packages/twenty-cli/app-template/.oxlintrc.jsonnew file mode 100644index 00000000000..369b9cfd762--- /dev/null+++ b/packages/twenty-cli/app-template/.oxlintrc.json@@ -0,0 +1,37 @@+{+ "$schema": "./node_modules/oxlint/configuration_schema.json",+ "plugins": ["typescript"],+ "categories": {+ "correctness": "off"+ },+ "ignorePatterns": ["node_modules", "dist"],+ "rules": {+ "no-unused-vars": "off",++ "typescript/no-unused-vars": [+ "warn",+ {+ "argsIgnorePattern": "^_"+ }+ ],+ "typescript/no-explicit-any": "off"+ },+ "overrides": [+ {+ "files": ["**/*.logic-function.ts", "**/logic-functions/**/*.ts"],+ "rules": {+ "no-restricted-imports": [+ "error",+ {+ "patterns": [+ {+ "group": ["twenty-shared", "twenty-shared/*"],+ "message": "Logic functions must not import from twenty-shared directly. Import runtime types and helpers from `twenty-sdk/logic-function` instead so the logic-function bundle stays minimal."+ }+ ]+ }+ ]+ }+ }+ ]+}diff --git a/packages/twenty-cli/app-template/AGENTS.md b/packages/twenty-cli/app-template/AGENTS.mdnew file mode 100644index 00000000000..7629e26d549--- /dev/null+++ b/packages/twenty-cli/app-template/AGENTS.md@@ -0,0 +1,70 @@+## Base documentation++- Getting started:+ - https://docs.twenty.com/developers/extend/apps/getting-started/quick-start.md+ - https://docs.twenty.com/developers/extend/apps/getting-started/concepts.md+ - https://docs.twenty.com/developers/extend/apps/getting-started/project-structure.md+ - https://docs.twenty.com/developers/extend/apps/getting-started/local-server.md+ - https://docs.twenty.com/developers/extend/apps/getting-started/scaffolding.md+ - https://docs.twenty.com/developers/extend/apps/getting-started/troubleshooting.md+- Config:+ - https://docs.twenty.com/developers/extend/apps/config/overview.md+ - https://docs.twenty.com/developers/extend/apps/config/application.md+ - https://docs.twenty.com/developers/extend/apps/config/roles.md+ - https://docs.twenty.com/developers/extend/apps/config/install-hooks.md+ - https://docs.twenty.com/developers/extend/apps/config/public-assets.md+- Data:+ - https://docs.twenty.com/developers/extend/apps/data/overview.md+ - https://docs.twenty.com/developers/extend/apps/data/objects.md+ - https://docs.twenty.com/developers/extend/apps/data/extending-objects.md+ - https://docs.twenty.com/developers/extend/apps/data/relations.md+- Logic:+ - https://docs.twenty.com/developers/extend/apps/logic/overview.md+ - https://docs.twenty.com/developers/extend/apps/logic/logic-functions.md+ - https://docs.twenty.com/developers/extend/apps/logic/skills-and-agents.md+ - https://docs.twenty.com/developers/extend/apps/logic/connections.md+- Layout:+ - https://docs.twenty.com/developers/extend/apps/layout/overview.md+ - https://docs.twenty.com/developers/extend/apps/layout/views.md+ - https://docs.twenty.com/developers/extend/apps/layout/navigation-menu-items.md+ - https://docs.twenty.com/developers/extend/apps/layout/page-layouts.md+ - https://docs.twenty.com/developers/extend/apps/layout/front-components.md+ - https://docs.twenty.com/developers/extend/apps/layout/command-menu-items.md+- Operations:+ - https://docs.twenty.com/developers/extend/apps/operations/overview.md+ - https://docs.twenty.com/developers/extend/apps/operations/cli.md+ - https://docs.twenty.com/developers/extend/apps/operations/testing.md+ - https://docs.twenty.com/developers/extend/apps/operations/publishing.md+- Rich app example: https://github.com/twentyhq/twenty/tree/main/packages/twenty-apps/examples/postcard++## UUID requirement++- All generated UUIDs must be valid UUID v4.++## Common Pitfalls++- Creating a view without a navigationMenuItem associated. This will make the view available on the left sidebar.+- Creating a front-end component that has a scroll instead of being responsive to its fixed widget height and width, unless it is specifically meant to be used in a canvas tab.++## Best practice++It's highly recommended to create new app entities using `yarn twenty dev:add`. These are the options:++| Entity type | Command | Generated file |+| -------------------- | ---------------------------------------- | ------------------------------------- |+| Object | `yarn twenty dev:add object` | `src/objects/<name>.ts` |+| Field | `yarn twenty dev:add field` | `src/fields/<name>.ts` |+| Logic function | `yarn twenty dev:add logicFunction` | `src/logic-functions/<name>.ts` |+| Front component | `yarn twenty dev:add frontComponent` | `src/front-components/<name>.tsx` |+| Role | `yarn twenty dev:add role` | `src/roles/<name>.ts` |+| Skill | `yarn twenty dev:add skill` | `src/skills/<name>.ts` |+| Agent | `yarn twenty dev:add agent` | `src/agents/<name>.ts` |+| View | `yarn twenty dev:add view` | `src/views/<name>.ts` |+| Navigation menu item | `yarn twenty dev:add navigationMenuItem` | `src/navigation-menu-items/<name>.ts` |+| Page layout | `yarn twenty dev:add pageLayout` | `src/page-layouts/<name>.ts` |+| Page layout tab | `yarn twenty dev:add pageLayoutTab` | `src/page-layout-tabs/<name>.ts` |+| Command menu item | `yarn twenty dev:add commandMenuItem` | `src/command-menu-items/<name>.ts` |+| View field | `yarn twenty dev:add viewField` | `src/view-fields/<name>.ts` |+| Connection provider | `yarn twenty dev:add connectionProvider` | `src/connection-providers/<name>.ts` |++This helps automatically generate required IDs etc.diff --git a/packages/twenty-cli/app-template/CHANGELOG.md b/packages/twenty-cli/app-template/CHANGELOG.mdnew file mode 100644index 00000000000..2a7fb15fd18--- /dev/null+++ b/packages/twenty-cli/app-template/CHANGELOG.md@@ -0,0 +1,7 @@+# Changelog++All notable changes to this application are documented in this file.++## 0.1.0++- Initial application scaffolded with `twenty app init`diff --git a/packages/twenty-cli/app-template/README.md b/packages/twenty-cli/app-template/README.mdnew file mode 100644index 00000000000..0b5463eb0f8--- /dev/null+++ b/packages/twenty-cli/app-template/README.md@@ -0,0 +1,34 @@+# My Twenty App++Describe your app in one or two sentences.++## Features++List the top things your app does, for example:++- Feature one+- Feature two+- Feature three++## Getting started++Setup instructions live in [SETUP.md](SETUP.md).++## Publishing++The `Publish` workflow (`.github/workflows/publish.yml`) publishes the app to npm with provenance using [npm trusted publishing](https://docs.npmjs.com/trusted-publishers). To publish:++1. On npmjs.com register this repository as a trusted publisher of your package, pointing at the `publish.yml` workflow.+2. Bump the version in `package.json`, then push a version tag (e.g. `git tag v1.0.0 && git push --tags`) or run the workflow manually from the Actions tab.++Publishing with provenance is also how you prove ownership when claiming your app in a Twenty marketplace.++## Changelog++Notable changes are documented in [CHANGELOG.md](CHANGELOG.md).++## Learn more++- [Twenty Apps documentation](https://docs.twenty.com/developers/extend/apps/getting-started/quick-start)+- [twenty-sdk CLI reference](https://www.npmjs.com/package/twenty-sdk)+- [Discord](https://discord.gg/cx5n4Jzs57)diff --git a/packages/twenty-cli/app-template/SETUP.md b/packages/twenty-cli/app-template/SETUP.mdnew file mode 100644index 00000000000..c7a92a07d36--- /dev/null+++ b/packages/twenty-cli/app-template/SETUP.md@@ -0,0 +1,47 @@+# Setup++Follow these steps to get your app running locally.++## Prerequisites++- Node.js (version specified in `.nvmrc`)+- Yarn 4+- Docker (to run the local Twenty server)++## Steps++1. Install dependencies:++ ```bash+ yarn install+ ```++ The committed `yarn.lock` pins exact, integrity-checked versions, so this+ resolves nothing from the registry.++2. Start the local Twenty server:++ ```bash+ yarn twenty docker:start+ ```++ Check the server status at any time with `yarn twenty docker:status`.++3. Start the development server and sync your app:++ ```bash+ yarn twenty dev+ ```++4. Open [http://localhost:2020](http://localhost:2020) and log in with the default development credentials: `[email protected]` / `[email protected]`.++## Verifying your setup++- `yarn lint` - Lint the project with oxlint+- `yarn typecheck` - Type-check the project+- `yarn test:unit` - Run unit tests+- `yarn test` - Run integration tests++## Troubleshooting++See the [troubleshooting guide](https://docs.twenty.com/developers/extend/apps/getting-started/troubleshooting) or ask on [Discord](https://discord.gg/cx5n4Jzs57).diff --git a/packages/twenty-cli/app-template/github/workflows/cd.yml b/packages/twenty-cli/app-template/github/workflows/cd.ymlnew file mode 100644index 00000000000..0ec483fc577--- /dev/null+++ b/packages/twenty-cli/app-template/github/workflows/cd.yml@@ -0,0 +1,42 @@+name: CD++on:+ push:+ branches:+ - main+ pull_request:+ types: [labeled]++permissions:+ contents: read++env:+ TWENTY_DEPLOY_URL: http://localhost:2020++concurrency:+ group: cd-${{ github.ref }}+ cancel-in-progress: true++jobs:+ deploy-and-install:+ if: >-+ github.event_name == 'push' ||+ (github.event_name == 'pull_request' && github.event.label.name == 'deploy')+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@v4+ with:+ ref: ${{ github.event.pull_request.head.sha || github.sha }}++ - name: Deploy+ uses: twentyhq/twenty/.github/actions/deploy-twenty-app@main+ with:+ api-url: ${{ env.TWENTY_DEPLOY_URL }}+ api-key: ${{ secrets.TWENTY_DEPLOY_API_KEY }}++ - name: Install+ uses: twentyhq/twenty/.github/actions/install-twenty-app@main+ with:+ api-url: ${{ env.TWENTY_DEPLOY_URL }}+ api-key: ${{ secrets.TWENTY_DEPLOY_API_KEY }}diff --git a/packages/twenty-cli/app-template/github/workflows/ci.yml b/packages/twenty-cli/app-template/github/workflows/ci.ymlnew file mode 100644index 00000000000..95e85ef31a2--- /dev/null+++ b/packages/twenty-cli/app-template/github/workflows/ci.yml@@ -0,0 +1,57 @@+name: CI++on:+ push:+ branches:+ - main+ pull_request: {}++permissions:+ contents: read++env:+ TWENTY_VERSION: latest++concurrency:+ group: ci-${{ github.ref }}+ cancel-in-progress: true++jobs:+ test:+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Spawn Twenty test instance+ id: twenty+ uses: twentyhq/twenty/.github/actions/spawn-twenty-app-dev-test@main+ with:+ twenty-version: ${{ env.TWENTY_VERSION }}++ - name: Enable Corepack+ run: corepack enable++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version-file: '.nvmrc'+ cache: yarn++ - name: Install dependencies+ run: yarn install --immutable++ - name: Lint+ run: yarn lint++ - name: Typecheck+ run: yarn typecheck++ - name: Unit tests+ run: yarn test:unit++ - name: Run integration tests+ run: yarn test+ env:+ TWENTY_API_URL: ${{ steps.twenty.outputs.server-url }}+ TWENTY_API_KEY: ${{ steps.twenty.outputs.api-key }}diff --git a/packages/twenty-cli/app-template/github/workflows/publish.yml b/packages/twenty-cli/app-template/github/workflows/publish.ymlnew file mode 100644index 00000000000..f6b564bee8e--- /dev/null+++ b/packages/twenty-cli/app-template/github/workflows/publish.yml@@ -0,0 +1,52 @@+# Publishes the app to npm with provenance (npm trusted publishing).+#+# One-time setup:+# 1. On npmjs.com open your package > Settings > Trusted Publisher and register+# this repository and this workflow file (publish.yml).+# See https://docs.npmjs.com/trusted-publishers+# 2. Push a version tag (e.g. `git tag v1.0.0 && git push --tags`) or run the+# workflow manually from the Actions tab.+#+# Publishing with provenance certifies which GitHub repository the package is+# built from. This is also how you claim ownership of your app in a Twenty+# marketplace: the claim flow verifies you own the GitHub account or+# organization the provenance points to.+name: Publish++on:+ push:+ tags:+ - 'v*'+ workflow_dispatch:++permissions:+ contents: read+ # Required for npm trusted publishing (OIDC provenance).+ id-token: write++jobs:+ publish:+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: 24+ registry-url: https://registry.npmjs.org++ - name: Update npm+ # Trusted publishing requires npm 11.5.1 or later.+ run: npm install -g npm@latest++ - name: Install dependencies+ run: yarn install --immutable++ - name: Publish to npm+ # Uncomment if publishing from a private source repo: npm rejects+ # OIDC provenance for private repos+ # env:+ # TWENTY_APP_PUBLISH_DISABLE_PROVENANCE: 'true'+ run: yarn twenty app:publishdiff --git a/packages/twenty-cli/app-template/gitignore b/packages/twenty-cli/app-template/gitignorenew file mode 100644index 00000000000..9fc1d5c3242--- /dev/null+++ b/packages/twenty-cli/app-template/gitignore@@ -0,0 +1,43 @@+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.++# dependencies+/node_modules+/.pnp+.pnp.*+.yarn/*+!.yarn/patches+!.yarn/plugins+!.yarn/releases+!.yarn/sdks+!.yarn/versions++# codegen+generated++# testing+/coverage++# dev+/dist/++.twenty++# production+/build++# misc+.DS_Store+*.pem++# debug+npm-debug.log*+yarn-debug.log*+yarn-error.log*+.pnpm-debug.log*++# env files (can opt-in for committing if needed)+.env*++# typescript+*.tsbuildinfo+*.d.tsdiff --git a/packages/twenty-cli/app-template/locales/en.json b/packages/twenty-cli/app-template/locales/en.jsonnew file mode 100644index 00000000000..0967ef424bc--- /dev/null+++ b/packages/twenty-cli/app-template/locales/en.json@@ -0,0 +1 @@+{}diff --git a/packages/twenty-cli/app-template/package.json b/packages/twenty-cli/app-template/package.jsonnew file mode 100644index 00000000000..86f75128754--- /dev/null+++ b/packages/twenty-cli/app-template/package.json@@ -0,0 +1,36 @@+{+ "name": "TO-BE-GENERATED",+ "version": "0.1.0",+ "license": "MIT",+ "engines": {+ "node": "^24.5.0",+ "npm": "please-use-yarn",+ "yarn": ">=4.0.2"+ },+ "keywords": [],+ "packageManager": "[email protected]",+ "scripts": {+ "twenty": "twenty",+ "lint": "oxlint -c .oxlintrc.json .",+ "lint:fix": "oxlint --fix -c .oxlintrc.json .",+ "typecheck": "tsgo --noEmit -p tsconfig.spec.json",+ "test": "vitest run",+ "test:watch": "vitest",+ "test:unit": "vitest run --config vitest.unit.config.ts"+ },+ "dependencies": {},+ "devDependencies": {+ "@types/node": "^24.7.2",+ "@types/react": "^19.0.0",+ "@typescript/native-preview": "^7.0.0-dev.20260116.1",+ "oxlint": "^0.16.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "twenty-client-sdk": "TO-BE-GENERATED",+ "twenty-sdk": "TO-BE-GENERATED",+ "twenty-ui": "TO-BE-GENERATED",+ "typescript": "^5.9.3",+ "vite-tsconfig-paths": "^4.2.1",+ "vitest": "^4.0.0"+ }+}diff --git a/packages/twenty-cli/app-template/public/logo.svg b/packages/twenty-cli/app-template/public/logo.svgnew file mode 100644index 00000000000..639ff19f349--- /dev/null+++ b/packages/twenty-cli/app-template/public/logo.svg@@ -0,0 +1,7 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" fill="none">+ <rect width="80" height="80" rx="16" fill="#141414"/>+ <rect x="20" y="20" width="16" height="16" rx="4" fill="#FAFAFA"/>+ <rect x="44" y="20" width="16" height="16" rx="4" fill="#FAFAFA" opacity="0.6"/>+ <rect x="20" y="44" width="16" height="16" rx="4" fill="#FAFAFA" opacity="0.6"/>+ <rect x="44" y="44" width="16" height="16" rx="4" fill="#FAFAFA" opacity="0.3"/>+</svg>diff --git a/packages/twenty-cli/app-template/src/__tests__/application-config.test.ts b/packages/twenty-cli/app-template/src/__tests__/application-config.test.tsnew file mode 100644index 00000000000..fdc1c6235c9--- /dev/null+++ b/packages/twenty-cli/app-template/src/__tests__/application-config.test.ts@@ -0,0 +1,14 @@+import {+ APP_DESCRIPTION,+ APP_DISPLAY_NAME,+ APPLICATION_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';+import { describe, expect, it } from 'vitest';++describe('application identifiers', () => {+ it('should expose the application metadata constants', () => {+ expect(APP_DISPLAY_NAME).toBeTruthy();+ expect(typeof APP_DESCRIPTION).toBe('string');+ expect(APPLICATION_UNIVERSAL_IDENTIFIER).toBeTruthy();+ });+});diff --git a/packages/twenty-cli/app-template-overlay/src/__tests__/global-setup.ts b/packages/twenty-cli/app-template/src/__tests__/global-setup.tssimilarity index 100%rename from packages/twenty-cli/app-template-overlay/src/__tests__/global-setup.tsrename to packages/twenty-cli/app-template/src/__tests__/global-setup.tsdiff --git a/packages/twenty-cli/app-template-overlay/src/__tests__/run-twenty.ts b/packages/twenty-cli/app-template/src/__tests__/run-twenty.tssimilarity index 100%rename from packages/twenty-cli/app-template-overlay/src/__tests__/run-twenty.tsrename to packages/twenty-cli/app-template/src/__tests__/run-twenty.tsdiff --git a/packages/twenty-cli/app-template/src/__tests__/schema.integration-test.ts b/packages/twenty-cli/app-template/src/__tests__/schema.integration-test.tsnew file mode 100644index 00000000000..31007e28e95--- /dev/null+++ b/packages/twenty-cli/app-template/src/__tests__/schema.integration-test.ts@@ -0,0 +1,46 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import { MetadataApiClient } from 'twenty-client-sdk/metadata';+import { APPLICATION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { describe, expect, it } from 'vitest';++describe('App installation', () => {+ it('should find the installed app in the applications list', async () => {+ const client = new MetadataApiClient();++ const result = await client.query({+ findManyApplications: {+ id: true,+ name: true,+ universalIdentifier: true,+ },+ });++ const app = result.findManyApplications.find(+ (a: { universalIdentifier: string }) =>+ a.universalIdentifier === APPLICATION_UNIVERSAL_IDENTIFIER,+ );++ expect(app).toBeDefined();+ });+});++describe('CoreApiClient', () => {+ it('should support CRUD on standard objects', async () => {+ const client = new CoreApiClient();++ const created = await client.mutation({+ createNote: {+ __args: { data: { title: 'Integration test note' } },+ id: true,+ },+ });+ expect(created.createNote.id).toBeDefined();++ await client.mutation({+ destroyNote: {+ __args: { id: created.createNote.id },+ id: true,+ },+ });+ });+});diff --git a/packages/twenty-cli/app-template/src/application-config.ts b/packages/twenty-cli/app-template/src/application-config.tsnew file mode 100644index 00000000000..088f9d1ea94--- /dev/null+++ b/packages/twenty-cli/app-template/src/application-config.ts@@ -0,0 +1,13 @@+import { defineApplication } from 'twenty-sdk/define';++import {+ APP_DESCRIPTION,+ APP_DISPLAY_NAME,+ APPLICATION_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';++export default defineApplication({+ universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,+ displayName: APP_DISPLAY_NAME,+ description: APP_DESCRIPTION,+});diff --git a/packages/twenty-cli/app-template/src/constants/universal-identifiers.ts b/packages/twenty-cli/app-template/src/constants/universal-identifiers.tsnew file mode 100644index 00000000000..d6dde8dd5c4--- /dev/null+++ b/packages/twenty-cli/app-template/src/constants/universal-identifiers.ts@@ -0,0 +1,12 @@+export const APP_DISPLAY_NAME = 'DISPLAY-NAME-TO-BE-GENERATED';+export const APP_DESCRIPTION = 'DESCRIPTION-TO-BE-GENERATED';+export const APPLICATION_UNIVERSAL_IDENTIFIER = 'UUID-TO-BE-GENERATED';+export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER = 'UUID-TO-BE-GENERATED';+export const HEALTH_CHECK_UNIVERSAL_IDENTIFIER = 'UUID-TO-BE-GENERATED';+export const MAIN_PAGE_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER =+ 'UUID-TO-BE-GENERATED';+export const MAIN_PAGE_LAYOUT_UNIVERSAL_IDENTIFIER = 'UUID-TO-BE-GENERATED';+export const MAIN_PAGE_LAYOUT_TAB_UNIVERSAL_IDENTIFIER = 'UUID-TO-BE-GENERATED';+export const MAIN_PAGE_WIDGET_UNIVERSAL_IDENTIFIER = 'UUID-TO-BE-GENERATED';+export const MAIN_PAGE_NAVIGATION_MENU_ITEM_UNIVERSAL_IDENTIFIER =+ 'UUID-TO-BE-GENERATED';diff --git a/packages/twenty-cli/app-template/src/default-role.ts b/packages/twenty-cli/app-template/src/default-role.tsnew file mode 100644index 00000000000..a6abf654453--- /dev/null+++ b/packages/twenty-cli/app-template/src/default-role.ts@@ -0,0 +1,16 @@+import { defineApplicationRole } from 'twenty-sdk/define';++import {+ APP_DISPLAY_NAME,+ DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';++export default defineApplicationRole({+ universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,+ label: `${APP_DISPLAY_NAME} default function role`,+ description: `${APP_DISPLAY_NAME} default function role`,+ canReadAllObjectRecords: true,+ canUpdateAllObjectRecords: true,+ canSoftDeleteAllObjectRecords: true,+ canDestroyAllObjectRecords: false,+});diff --git a/packages/twenty-cli/app-template/src/front-components/main-page.tsx b/packages/twenty-cli/app-template/src/front-components/main-page.tsxnew file mode 100644index 00000000000..ce33dd031b5--- /dev/null+++ b/packages/twenty-cli/app-template/src/front-components/main-page.tsx@@ -0,0 +1,287 @@+import { defineFrontComponent } from 'twenty-sdk/define';+import { useState } from 'react';+import { Avatar } from 'twenty-ui/primitives/data-display';+import {+ IconBox,+ IconHierarchy,+ IconLayout,+ IconSettingsAutomation,+} from 'twenty-ui/icon';++import {+ APP_DISPLAY_NAME,+ MAIN_PAGE_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';++const DOCS_BASE_URL = 'https://docs.twenty.com/developers/extend/apps';++const CATEGORIES = [+ {+ title: 'Data model',+ color: '#73D08D',+ items: [+ { label: 'CUSTOM OBJECT', href: `${DOCS_BASE_URL}/data/objects` },+ {+ label: 'CUSTOM FIELDS',+ href: `${DOCS_BASE_URL}/data/extending-objects`,+ },+ ],+ rotation: '2.4deg',+ },+ {+ title: 'Logic',+ color: '#F4D345',+ items: [+ {+ label: 'TOOLS',+ href: `${DOCS_BASE_URL}/logic/logic-functions`,+ },+ {+ label: 'LOGIC FUNCTION',+ href: `${DOCS_BASE_URL}/logic/logic-functions`,+ },+ {+ label: 'SKILLS',+ href: `${DOCS_BASE_URL}/logic/skills-and-agents`,+ },+ ],+ rotation: '0deg',+ },+ {+ title: 'Layout',+ color: '#C4A2E0',+ items: [+ { label: 'VIEWS', href: `${DOCS_BASE_URL}/layout/views` },+ { label: 'WIDGETS', href: `${DOCS_BASE_URL}/layout/page-layouts` },+ {+ label: 'LAYOUT PAGES',+ href: `${DOCS_BASE_URL}/layout/page-layouts`,+ },+ {+ label: 'COMMANDS',+ href: `${DOCS_BASE_URL}/layout/command-menu-items`,+ },+ ],+ rotation: '-2.8deg',+ },+] as const;++const ArrowUpRight = ({ color = '#999' }: { color?: string }) => (+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none">+ <path+ d="M4.5 3.5H10.5V9.5M10.5 3.5L3.5 10.5"+ stroke={color}+ strokeWidth="1.2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+);++const CategoryCard = ({+ title,+ color,+ items,+ rotation,+}: {+ title: string;+ color: string;+ items: ReadonlyArray<{ label: string; href: string }>;+ rotation: string;+}) => {+ const [hoveredItem, setHoveredItem] = useState<string | null>(null);++ const CategoryIcon = () => {+ if (title === 'Data model') {+ return <IconHierarchy color={color} size="20px" />;+ }+ if (title === 'Logic') {+ return <IconSettingsAutomation color={color} size="20px" />;+ }+ if (title === 'Layout') {+ return <IconLayout color={color} size="20px" />;+ }+ };++ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ border: `1px solid ${color}80`,+ borderRadius: '12px',+ overflow: 'hidden',+ width: '240px',+ background: '#FFFFFF',+ transform: `rotate(${rotation})`,+ boxShadow: '0 2px 8px rgba(0, 0, 0, 0.04)',+ }}+ >+ <div+ style={{+ padding: '16px 20px',+ background: `${color}22`,+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ }}+ >+ <CategoryIcon />+ <span+ style={{+ fontSize: '16px',+ fontWeight: 600,+ color: color,+ }}+ >+ {title}+ </span>+ </div>+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ padding: '8px',+ gap: '4px',+ }}+ >+ {items.map((item) => {+ const isHovered = hoveredItem === item.label;++ return (+ <a+ key={item.label}+ href={item.href}+ target="_blank"+ rel="noopener noreferrer"+ onMouseEnter={() => setHoveredItem(item.label)}+ onMouseLeave={() => setHoveredItem(null)}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ textDecoration: 'none',+ cursor: 'pointer',+ padding: '10px 12px',+ borderRadius: '8px',+ background: isHovered ? '#0000000A' : 'transparent',+ transition: 'background 0.15s',+ }}+ >+ <IconBox color={color} size="20px" />+ <span+ style={{+ fontSize: '13px',+ fontWeight: 300,+ color: '#333',+ letterSpacing: '0.5px',+ flex: 1,+ }}+ >+ {item.label}+ </span>+ {isHovered && <ArrowUpRight />}+ </a>+ );+ })}+ </div>+ </div>+ );+};++const MainPage = () => {+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ fontFamily:+ 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',+ gap: '8px',+ padding: '40px',+ }}+ >+ <Avatar name={APP_DISPLAY_NAME} colorSeed={APP_DISPLAY_NAME} size="xl" />+ <span+ style={{+ fontSize: '24px',+ fontWeight: 600,+ color: '#333',+ marginTop: '8px',+ }}+ >+ {APP_DISPLAY_NAME}+ </span>+ <span+ style={{+ fontSize: '13px',+ color: '#888',+ textAlign: 'center',+ lineHeight: '1.5',+ }}+ >+ Was installed successfully.+ <br />+ You can now add content to your app.+ </span>+ <a+ href="/settings/applications#installed"+ style={{+ display: 'inline-flex',+ alignItems: 'center',+ gap: '6px',+ marginTop: '16px',+ fontSize: '13px',+ color: '#333',+ textDecoration: 'none',+ padding: '8px 16px',+ borderRadius: '8px',+ border: '1px solid #e0e0e0',+ background: '#fafafa',+ transition: 'background 0.15s, border-color 0.15s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.background = '#f0f0f0';+ e.currentTarget.style.borderColor = '#ccc';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.background = '#fafafa';+ e.currentTarget.style.borderColor = '#e0e0e0';+ }}+ >+ Open app settings+ <ArrowUpRight color="#333" />+ </a>+ <div+ style={{+ display: 'flex',+ gap: '16px',+ marginTop: '32px',+ flexWrap: 'wrap',+ justifyContent: 'center',+ alignItems: 'flex-start',+ }}+ >+ {CATEGORIES.map((category) => (+ <CategoryCard+ key={category.title}+ title={category.title}+ color={category.color}+ items={category.items}+ rotation={category.rotation}+ />+ ))}+ </div>+ </div>+ );+};++export default defineFrontComponent({+ universalIdentifier: MAIN_PAGE_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+ name: APP_DISPLAY_NAME,+ description: `${APP_DISPLAY_NAME} front component displaying the app logo and name`,+ component: MainPage,+});diff --git a/packages/twenty-cli/app-template/src/logic-functions/health-check.ts b/packages/twenty-cli/app-template/src/logic-functions/health-check.tsnew file mode 100644index 00000000000..f50c8a9567c--- /dev/null+++ b/packages/twenty-cli/app-template/src/logic-functions/health-check.ts@@ -0,0 +1,11 @@+import { defineHealthCheck } from 'twenty-sdk/define';++import { HEALTH_CHECK_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';++export default defineHealthCheck({+ universalIdentifier: HEALTH_CHECK_UNIVERSAL_IDENTIFIER,+ name: 'health-check',+ handler: async () => {+ return { status: 'OK' };+ },+});diff --git a/packages/twenty-cli/app-template/src/navigation-menu-items/main-page.navigation-menu-item.ts b/packages/twenty-cli/app-template/src/navigation-menu-items/main-page.navigation-menu-item.tsnew file mode 100644index 00000000000..cccb05675eb--- /dev/null+++ b/packages/twenty-cli/app-template/src/navigation-menu-items/main-page.navigation-menu-item.ts@@ -0,0 +1,19 @@+import {+ defineNavigationMenuItem,+ NavigationMenuItemType,+} from 'twenty-sdk/define';++import {+ APP_DISPLAY_NAME,+ MAIN_PAGE_LAYOUT_UNIVERSAL_IDENTIFIER,+ MAIN_PAGE_NAVIGATION_MENU_ITEM_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';++export default defineNavigationMenuItem({+ universalIdentifier: MAIN_PAGE_NAVIGATION_MENU_ITEM_UNIVERSAL_IDENTIFIER,+ name: APP_DISPLAY_NAME,+ icon: 'IconFile',+ position: -1,+ type: NavigationMenuItemType.PAGE_LAYOUT,+ pageLayoutUniversalIdentifier: MAIN_PAGE_LAYOUT_UNIVERSAL_IDENTIFIER,+});diff --git a/packages/twenty-cli/app-template/src/page-layouts/main-page.page-layout.ts b/packages/twenty-cli/app-template/src/page-layouts/main-page.page-layout.tsnew file mode 100644index 00000000000..6154377a08f--- /dev/null+++ b/packages/twenty-cli/app-template/src/page-layouts/main-page.page-layout.ts@@ -0,0 +1,46 @@+import {+ definePageLayout,+ PageLayoutTabLayoutMode,+ PageLayoutWidgetVerticalListHeightBehavior,+} from 'twenty-sdk/define';++import {+ APP_DISPLAY_NAME,+ MAIN_PAGE_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+ MAIN_PAGE_LAYOUT_TAB_UNIVERSAL_IDENTIFIER,+ MAIN_PAGE_LAYOUT_UNIVERSAL_IDENTIFIER,+ MAIN_PAGE_WIDGET_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';++export default definePageLayout({+ universalIdentifier: MAIN_PAGE_LAYOUT_UNIVERSAL_IDENTIFIER,+ name: APP_DISPLAY_NAME,+ type: 'STANDALONE_PAGE',+ tabs: [+ {+ universalIdentifier: MAIN_PAGE_LAYOUT_TAB_UNIVERSAL_IDENTIFIER,+ title: 'Overview',+ position: 0,+ icon: 'IconApps',+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,+ widgets: [+ {+ universalIdentifier: MAIN_PAGE_WIDGET_UNIVERSAL_IDENTIFIER,+ title: ' ',+ type: 'FRONT_COMPONENT',+ position: {+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,+ index: 0,+ heightBehavior:+ PageLayoutWidgetVerticalListHeightBehavior.TAB_VIEWPORT,+ },+ configuration: {+ configurationType: 'FRONT_COMPONENT',+ frontComponentUniversalIdentifier:+ MAIN_PAGE_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+ },+ },+ ],+ },+ ],+});diff --git a/packages/twenty-cli/app-template/tsconfig.json b/packages/twenty-cli/app-template/tsconfig.jsonnew file mode 100644index 00000000000..12aa0c23886--- /dev/null+++ b/packages/twenty-cli/app-template/tsconfig.json@@ -0,0 +1,37 @@+{+ "compileOnSave": false,+ "compilerOptions": {+ "sourceMap": true,+ "declaration": true,+ "outDir": "./dist",+ "rootDir": ".",+ "jsx": "react-jsx",+ "moduleResolution": "bundler",+ "allowSyntheticDefaultImports": true,+ "emitDecoratorMetadata": true,+ "experimentalDecorators": true,+ "importHelpers": true,+ "allowUnreachableCode": false,+ "strict": true,+ "alwaysStrict": true,+ "noImplicitAny": true,+ "strictBindCallApply": false,+ "target": "es2020",+ "module": "esnext",+ "lib": ["es2020", "dom"],+ "skipLibCheck": true,+ "skipDefaultLibCheck": true,+ "resolveJsonModule": true,+ "paths": {+ "src/*": ["./src/*"],+ "~/*": ["./*"]+ }+ },+ "exclude": [+ "node_modules",+ "dist",+ "**/*.test.ts",+ "**/*.spec.ts",+ "**/*.integration-test.ts"+ ]+}diff --git a/packages/twenty-cli/app-template/tsconfig.spec.json b/packages/twenty-cli/app-template/tsconfig.spec.jsonnew file mode 100644index 00000000000..ea69a6c0105--- /dev/null+++ b/packages/twenty-cli/app-template/tsconfig.spec.json@@ -0,0 +1,9 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "composite": true,+ "types": ["vitest/globals", "node"]+ },+ "include": ["src/**/*.ts", "src/**/*.tsx"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/twenty-cli/app-template/vitest.config.ts b/packages/twenty-cli/app-template/vitest.config.tsnew file mode 100644index 00000000000..055af77dbec--- /dev/null+++ b/packages/twenty-cli/app-template/vitest.config.ts@@ -0,0 +1,31 @@+import tsconfigPaths from 'vite-tsconfig-paths';+import { defineConfig } from 'vitest/config';++const TWENTY_API_URL = process.env.TWENTY_API_URL ?? 'http://localhost:2020';+const TWENTY_API_KEY =+ process.env.TWENTY_API_KEY ??+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyMDIwMjAyMC0xYzI1LTRkMDItYmYyNS02YWVjY2Y3ZWE0MTkiLCJ0eXBlIjoiQVBJX0tFWSIsIndvcmtzcGFjZUlkIjoiMjAyMDIwMjAtMWMyNS00ZDAyLWJmMjUtNmFlY2NmN2VhNDE5IiwiaWF0IjoxNzM1Njg5NjAwLCJleHAiOjQ4OTE0NDk2MDAsImp0aSI6IjIwMjAyMDIwLWY0MDEtNGQ4YS1hNzMxLTY0ZDAwN2MyN2JhZCJ9.bfQjfyN0NEtTCLE_xPyNcwonDzlSXFoP8kdCQTdnuDc';++// Make env vars available to globalSetup (test.env only applies to workers)+process.env.TWENTY_API_URL = TWENTY_API_URL;+process.env.TWENTY_API_KEY = TWENTY_API_KEY;++export default defineConfig({+ plugins: [+ tsconfigPaths({+ projects: ['tsconfig.spec.json'],+ ignoreConfigErrors: true,+ }),+ ],+ test: {+ testTimeout: 120_000,+ hookTimeout: 120_000,+ fileParallelism: false,+ include: ['src/**/*.integration-test.ts'],+ globalSetup: ['src/__tests__/global-setup.ts'],+ env: {+ TWENTY_API_URL,+ TWENTY_API_KEY,+ },+ },+});diff --git a/packages/twenty-cli/app-template/vitest.unit.config.ts b/packages/twenty-cli/app-template/vitest.unit.config.tsnew file mode 100644index 00000000000..e0d140015bb--- /dev/null+++ b/packages/twenty-cli/app-template/vitest.unit.config.ts@@ -0,0 +1,14 @@+import tsconfigPaths from 'vite-tsconfig-paths';+import { defineConfig } from 'vitest/config';++export default defineConfig({+ plugins: [+ tsconfigPaths({+ projects: ['tsconfig.spec.json'],+ ignoreConfigErrors: true,+ }),+ ],+ test: {+ include: ['src/**/*.test.ts'],+ },+});diff --git a/packages/twenty-cli/app-template/yarnrc.yml b/packages/twenty-cli/app-template/yarnrc.ymlnew file mode 100644index 00000000000..3186f3f0795--- /dev/null+++ b/packages/twenty-cli/app-template/yarnrc.yml@@ -0,0 +1 @@+nodeLinker: node-modulesdiff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex ba0c6243062..0bf8e0671f1 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -526,7 +526,7 @@ Commands print readable text by default. With `--json`, a command prints exactly"ok": true,"command": "version","data": {- "version": "0.3.0",+ "version": "0.4.0","node": "24.9.0","platform": "darwin","arch": "arm64"diff --git a/packages/twenty-cli/package.json b/packages/twenty-cli/package.jsonindex 74bfac2380d..ec5788e79ef 100644--- a/packages/twenty-cli/package.json+++ b/packages/twenty-cli/package.json@@ -1,6 +1,6 @@{"name": "twenty",- "version": "0.3.0",+ "version": "0.4.0","description": "The Twenty command line.","homepage": "https://twenty.com","repository": {@@ -11,7 +11,7 @@"bugs": {"url": "https://github.com/twentyhq/twenty/issues"},- "license": "AGPL-3.0",+ "license": "MIT","bin": "dist/cli.cjs","files": ["dist",@@ -20,17 +20,20 @@"src/app/**/README.md"],"scripts": {- "build": "npx rimraf dist && npx vite build"+ "build": "npx rimraf dist && npx vite build",+ "prepublish": "node scripts/check-publish.mjs"},"engines": {"node": "^24.5.0"},"devDependencies": {"@sniptt/guards": "^0.2.0",+ "@types/lodash.startcase": "^4","@types/node": "^24.0.0","@types/semver": "^7.5.8","cjs-module-lexer": "^2.2.0","commander": "^14.0.3",+ "lodash.startcase": "^4.4.0","semver": "7.6.3","twenty-client-sdk": "workspace:*","twenty-shared": "workspace:*",diff --git a/packages/twenty-cli/project.json b/packages/twenty-cli/project.jsonindex aec9dab6d46..5a602bd378b 100644--- a/packages/twenty-cli/project.json+++ b/packages/twenty-cli/project.json@@ -4,7 +4,7 @@"sourceRoot": "packages/twenty-cli/src","projectType": "application","tags": ["scope:cli"],- "implicitDependencies": ["create-twenty-app"],+ "implicitDependencies": ["twenty-sdk"],"targets": {"build": {"dependsOn": ["^build"],@@ -25,7 +25,7 @@"dependsOn": ["build"],"cache": false,"options": {- "command": "node --test packages/twenty-cli/scripts/test-package.mjs"+ "command": "node --test packages/twenty-cli/scripts/test-check-publish.mjs packages/twenty-cli/scripts/test-package.mjs"}},"test": {diff --git a/packages/twenty-cli/scripts/check-publish-readiness.mjs b/packages/twenty-cli/scripts/check-publish-readiness.mjsnew file mode 100644index 00000000000..e4ecb18018c--- /dev/null+++ b/packages/twenty-cli/scripts/check-publish-readiness.mjs@@ -0,0 +1,368 @@+import { execFileSync } from 'node:child_process';+import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, join, relative, resolve } from 'node:path';++const NPM_REGISTRY_URL = 'https://registry.npmjs.org';+const REGISTRY_TIMEOUT_MILLISECONDS = 15_000;+const COMMAND_TIMEOUT_MILLISECONDS = 60_000;+const SHEBANG = '#!/usr/bin/env node';+const PACKAGE_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;+const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;+const RELATIVE_REQUIRE_PATTERN = /require\(["'`](\.{1,2}\/[^"'`]+)["'`]\)/g;+const REQUIRED_FILES = ['dist/app-worker.cjs'];+const COPIED_DIRECTORIES = [+ {+ source: 'app-template',+ target: 'dist/app-template',+ },+];+const RENDERED_APP_FILES = [+ 'package.json',+ 'tsconfig.json',+ '.yarnrc.yml',+ 'src/application-config.ts',+ 'src/__tests__/run-twenty.ts',+];+const BUILD_HINT = 'Build it first with: yarn nx build twenty-cli';++export class PublishCheckError extends Error {}++const fail = (message) => {+ throw new PublishCheckError(message);+};++const readJson = async (path) => JSON.parse(await readFile(path, 'utf8'));++const getFileSize = async (path) => {+ const file = await stat(path).catch(() => undefined);++ return file?.isFile() === true ? file.size : undefined;+};++const checkExecutable = async ({ packageDirectory, executable }) => {+ const executablePath = join(packageDirectory, executable);+ const file = await stat(executablePath).catch(() => undefined);++ if (file?.isFile() !== true) {+ fail(`${executable} is missing. ${BUILD_HINT}`);+ }++ if ((file.mode & 0o111) === 0) {+ fail(`${executable} is not executable. ${BUILD_HINT}`);+ }++ const [firstLine] = (await readFile(executablePath, 'utf8')).split('\n', 1);++ if (firstLine !== SHEBANG) {+ fail(`${executable} does not start with "${SHEBANG}".`);+ }+};++const checkRequiredFiles = async (packageDirectory) => {+ for (const requiredFile of REQUIRED_FILES) {+ const size = await getFileSize(join(packageDirectory, requiredFile));++ if (size === undefined || size === 0) {+ fail(`${requiredFile} is missing or empty. ${BUILD_HINT}`);+ }+ }+};++const listFiles = async (directory) => {+ const entries = await readdir(directory, {+ withFileTypes: true,+ recursive: true,+ });++ return entries+ .filter((entry) => entry.isFile())+ .map((entry) => relative(directory, join(entry.parentPath, entry.name)));+};++const checkCopiedDirectories = async (packageDirectory) => {+ let fileCount = 0;++ for (const { source, target } of COPIED_DIRECTORIES) {+ const sourceFiles = await listFiles(join(packageDirectory, source)).catch(+ () => [],+ );++ if (sourceFiles.length === 0) {+ fail(`${source} is missing. Run this check from a repository checkout.`);+ }++ for (const file of sourceFiles) {+ const copied = await readFile(join(packageDirectory, target, file)).catch(+ () => undefined,+ );++ if (copied === undefined) {+ fail(`${target}/${file} is missing. ${BUILD_HINT}`);+ }++ if (+ !copied.equals(await readFile(join(packageDirectory, source, file)))+ ) {+ fail(`${target}/${file} differs from ${source}/${file}. ${BUILD_HINT}`);+ }+ }++ fileCount += sourceFiles.length;+ }++ return fileCount;+};++const listBundleFiles = async (directory) => {+ const entries = await readdir(directory, { withFileTypes: true });+ const nested = await Promise.all(+ entries+ .filter((entry) => entry.isDirectory() && entry.name === 'chunks')+ .map((entry) => listBundleFiles(join(directory, entry.name))),+ );++ return [+ ...entries+ .filter((entry) => entry.isFile() && entry.name.endsWith('.cjs'))+ .map((entry) => join(directory, entry.name)),+ ...nested.flat(),+ ];+};++const checkBundleReferences = async (packageDirectory) => {+ const bundleFiles = await listBundleFiles(join(packageDirectory, 'dist'));++ for (const bundleFile of bundleFiles) {+ const source = await readFile(bundleFile, 'utf8');++ for (const [, specifier] of source.matchAll(RELATIVE_REQUIRE_PATTERN)) {+ const target = resolve(dirname(bundleFile), specifier);++ if ((await getFileSize(target)) === undefined) {+ fail(+ `${relative(packageDirectory, bundleFile)} requires ${specifier}, which is missing. ${BUILD_HINT}`,+ );+ }+ }+ }++ return bundleFiles.length;+};++const parseResult = (output) => {+ try {+ return JSON.parse(output);+ } catch {+ return undefined;+ }+};++const describeExit = ({ error, commandTimeoutMilliseconds }) => {+ if (error.code === 'ETIMEDOUT') {+ return `timed out after ${commandTimeoutMilliseconds / 1000}s`;+ }++ return typeof error.signal === 'string'+ ? `was stopped by ${error.signal}`+ : `exited with code ${error.status}`;+};++const describeError = (result) =>+ typeof result?.error?.code === 'string'+ ? `: ${result.error.code} ${result.error.message}`+ : ` without an error result. ${BUILD_HINT}`;++const runCli = ({+ packageDirectory,+ executable,+ commandArguments,+ home,+ commandTimeoutMilliseconds,+}) => {+ const command = `twenty ${commandArguments.join(' ')}`;+ const environment = Object.fromEntries(+ Object.entries(process.env).filter(([name]) => !name.startsWith('TWENTY_')),+ );+ let output;++ try {+ output = execFileSync(+ process.execPath,+ [join(packageDirectory, executable), ...commandArguments, '--json'],+ {+ cwd: home,+ env: { ...environment, HOME: home, USERPROFILE: home, NO_COLOR: '1' },+ encoding: 'utf8',+ timeout: commandTimeoutMilliseconds,+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ );+ } catch (error) {+ fail(+ `${command} ${describeExit({ error, commandTimeoutMilliseconds })}${describeError(parseResult(error.stdout))}`,+ );+ }++ const result = parseResult(output);++ if (result?.ok !== true) {+ fail(`${command} did not report success${describeError(result)}`);+ }++ return result.data;+};++const checkBuiltVersion = ({ version, ...cliOptions }) => {+ const data = runCli({ ...cliOptions, commandArguments: ['version'] });++ if (data.version !== version) {+ fail(+ `dist was built as version ${data.version}, but package.json is ${version}. ${BUILD_HINT}`,+ );+ }+};++const readTemplatePins = async (cliOptions) => {+ const appName = 'publish-check-app';+ const data = runCli({+ ...cliOptions,+ commandArguments: ['app', 'init', appName, '--no-input'],+ });+ const appDirectory = join(cliOptions.home, appName);++ for (const file of RENDERED_APP_FILES) {+ const size = await getFileSize(join(appDirectory, file));++ if (size === undefined || size === 0) {+ fail(`app init did not create ${file}.`);+ }+ }++ if (+ !(+ await readFile(join(appDirectory, 'src/application-config.ts'), 'utf8')+ ).includes('defineApplication')+ ) {+ fail(+ 'app init created src/application-config.ts without defineApplication.',+ );+ }++ const appPackageJson = await readJson(join(appDirectory, 'package.json'));+ const renderedVersions = {+ ...appPackageJson.dependencies,+ ...appPackageJson.devDependencies,+ };++ if (!Array.isArray(data.packages) || data.packages.length === 0) {+ fail('app init did not report the packages it pins.');+ }++ return data.packages.map(({ name, version }) => {+ if (!PACKAGE_NAME_PATTERN.test(name)) {+ fail(`app init reported an unexpected package name: ${name}`);+ }++ if (renderedVersions[name] !== version) {+ fail(+ `app init reported ${name}@${version}, but the generated package.json pins ${renderedVersions[name]}.`,+ );+ }++ if (!EXACT_VERSION_PATTERN.test(version)) {+ fail(`app init pins ${name} to ${version}, not an exact version.`);+ }++ return { name, version };+ });+};++const lookUpPublishedVersion = async ({ registryUrl, name, version }) => {+ try {+ const response = await fetch(`${registryUrl}/${name}/${version}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MILLISECONDS),+ });++ if (response.ok) {+ return 'published';+ }++ return response.status === 404 ? 'missing' : `HTTP ${response.status}`;+ } catch (error) {+ return error.message;+ }+};++const checkPinsArePublished = async ({ registryUrl, pins }) => {+ const lookups = await Promise.all(+ pins.map(async (pin) => ({+ ...pin,+ status: await lookUpPublishedVersion({ registryUrl, ...pin }),+ })),+ );+ const missing = lookups.filter(({ status }) => status === 'missing');+ const unverified = lookups.filter(+ ({ status }) => status !== 'missing' && status !== 'published',+ );++ if (missing.length > 0) {+ fail(+ `app init would pin versions that are not on npm: ${missing.map(({ name, version }) => `${name}@${version}`).join(', ')}. ` ++ 'Publish the matching SDK release first, and tag this CLI release on the same commit as its sdk/v* tag.',+ );+ }++ if (unverified.length > 0) {+ fail(+ `Could not verify these versions on ${registryUrl}: ${unverified.map(({ name, version, status }) => `${name}@${version} (${status})`).join(', ')}. ` ++ 'Retry once the registry is reachable.',+ );+ }+};++export const checkPublishReadiness = async ({+ packageDirectory,+ registryUrl = NPM_REGISTRY_URL,+ commandTimeoutMilliseconds = COMMAND_TIMEOUT_MILLISECONDS,+}) => {+ const { bin, version } = await readJson(+ join(packageDirectory, 'package.json'),+ );++ if (typeof bin !== 'string') {+ fail('package.json bin must be the path of the twenty executable.');+ }++ await checkExecutable({ packageDirectory, executable: bin });+ await checkRequiredFiles(packageDirectory);++ const templateFileCount = await checkCopiedDirectories(packageDirectory);+ const bundleFileCount = await checkBundleReferences(packageDirectory);+ const home = await mkdtemp(join(tmpdir(), 'twenty-publish-check-'));+ const cliOptions = {+ packageDirectory,+ executable: bin,+ home,+ commandTimeoutMilliseconds,+ };++ try {+ checkBuiltVersion({ ...cliOptions, version });++ const pins = await readTemplatePins(cliOptions);++ await checkPinsArePublished({ registryUrl, pins });++ return {+ version,+ executable: bin,+ bundleFileCount,+ templateFileCount,+ pins,+ };+ } finally {+ await rm(home, { recursive: true, force: true });+ }+};diff --git a/packages/twenty-cli/scripts/check-publish.mjs b/packages/twenty-cli/scripts/check-publish.mjsnew file mode 100644index 00000000000..d15b614bd67--- /dev/null+++ b/packages/twenty-cli/scripts/check-publish.mjs@@ -0,0 +1,28 @@+import { fileURLToPath } from 'node:url';++import {+ checkPublishReadiness,+ PublishCheckError,+} from './check-publish-readiness.mjs';++try {+ const { version, executable, bundleFileCount, templateFileCount, pins } =+ await checkPublishReadiness({+ packageDirectory: fileURLToPath(new URL('..', import.meta.url)),+ });++ console.log(`twenty ${version} is ready to publish:`);+ console.log(+ ` ${executable}, the app worker, ${bundleFileCount} bundle files and ${templateFileCount} template files are present`,+ );+ console.log(+ ` app init pins ${pins.map(({ name, version: pinnedVersion }) => `${name}@${pinnedVersion}`).join(', ')}, all on npm`,+ );+} catch (error) {+ if (!(error instanceof PublishCheckError)) {+ throw error;+ }++ console.error(`Publish check failed: ${error.message}`);+ process.exitCode = 1;+}diff --git a/packages/twenty-cli/scripts/test-check-publish.mjs b/packages/twenty-cli/scripts/test-check-publish.mjsnew file mode 100644index 00000000000..b7a7104c72b--- /dev/null+++ b/packages/twenty-cli/scripts/test-check-publish.mjs@@ -0,0 +1,298 @@+import { strict as assert } from 'node:assert';+import { chmod, cp, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { createServer } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';++import {+ checkPublishReadiness,+ PublishCheckError,+} from './check-publish-readiness.mjs';++const PACKAGE_VERSION = '1.0.0';+const PINS = [+ { name: 'twenty-client-sdk', version: '2.45.0' },+ { name: 'twenty-sdk', version: '2.45.0' },+ { name: 'twenty-ui', version: '2.45.0' },+];++const registryStatuses = new Map();+const registry = createServer((request, response) => {+ response.statusCode = registryStatuses.get(request.url) ?? 404;+ response.end('{}');+});++await new Promise((resolve, reject) => {+ registry.once('error', reject);+ registry.listen(0, '127.0.0.1', resolve);+});+registry.unref();++const registryUrl = `http://127.0.0.1:${registry.address().port}`;+let root;++const createCliSource = ({+ version = PACKAGE_VERSION,+ exitCode = 0,+ hangs = false,+ reportedPins = PINS,+ renderedPins = PINS,+ skippedFiles = [],+}) => `#!/usr/bin/env node+const fs = require('node:fs');+const path = require('node:path');+require('./chunks/commands.cjs');+const options = ${JSON.stringify({ version, exitCode, hangs, reportedPins, renderedPins, skippedFiles })};+const [command, subcommand, appName] = process.argv.slice(2);+const writeAppFile = (appDirectory, file, content) => {+ if (options.skippedFiles.includes(file)) {+ return;+ }+ fs.mkdirSync(path.dirname(path.join(appDirectory, file)), { recursive: true });+ fs.writeFileSync(path.join(appDirectory, file), content);+};+const reply = (data) => {+ console.log(JSON.stringify({ ok: true, data }));+ if (options.hangs) {+ setTimeout(() => {}, 60_000);+ }+ process.exitCode = options.exitCode;+};+if (command === 'version') {+ reply({ version: options.version });+} else if (command === 'app' && subcommand === 'init') {+ const appDirectory = path.join(process.cwd(), appName);+ const devDependencies = Object.fromEntries(+ options.renderedPins.map(({ name, version }) => [name, version]),+ );+ writeAppFile(appDirectory, 'package.json', JSON.stringify({ devDependencies }));+ writeAppFile(appDirectory, 'tsconfig.json', '{}');+ writeAppFile(appDirectory, '.yarnrc.yml', 'nodeLinker: node-modules');+ writeAppFile(appDirectory, 'src/application-config.ts', 'export default defineApplication({});');+ writeAppFile(appDirectory, 'src/__tests__/run-twenty.ts', 'export {};');+ reply({ packages: options.reportedPins });+}+`;++const createPackage = async (cliOptions = {}) => {+ const packageDirectory = join(root, 'twenty-cli');+ const templateDirectory = join(packageDirectory, 'app-template');+ const executable = join(packageDirectory, 'dist/cli.cjs');++ await mkdir(join(packageDirectory, 'dist/chunks'), { recursive: true });+ await mkdir(join(templateDirectory, 'src/__tests__'), { recursive: true });+ await writeFile(+ join(packageDirectory, 'package.json'),+ JSON.stringify({+ name: 'twenty',+ version: PACKAGE_VERSION,+ bin: 'dist/cli.cjs',+ }),+ );+ await writeFile(executable, createCliSource(cliOptions));+ await chmod(executable, 0o755);+ await writeFile(+ join(packageDirectory, 'dist/chunks/commands.cjs'),+ 'module.exports = {};',+ );+ await writeFile(+ join(packageDirectory, 'dist/app-worker.cjs'),+ 'require("./chunks/commands.cjs");',+ );+ await writeFile(join(templateDirectory, 'package.json'), '{}');+ await writeFile(+ join(templateDirectory, 'src/__tests__/run-twenty.ts'),+ 'export {};',+ );+ await cp(templateDirectory, join(packageDirectory, 'dist/app-template'), {+ recursive: true,+ });++ return packageDirectory;+};++const assertFailure = (promise, pattern) =>+ assert.rejects(promise, (error) => {+ assert.ok(error instanceof PublishCheckError, error);+ assert.match(error.message, pattern);++ return true;+ });++const testPublishCheck = (name, run) =>+ test(name, async () => {+ root = await mkdtemp(join(tmpdir(), 'twenty-publish-check-test-'));+ registryStatuses.clear();++ for (const pin of PINS) {+ registryStatuses.set(`/${pin.name}/${pin.version}`, 200);+ }++ try {+ await run();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++await testPublishCheck(+ 'accepts a complete build whose app init pins are on npm',+ async () => {+ const packageDirectory = await createPackage();++ assert.deepEqual(+ await checkPublishReadiness({ packageDirectory, registryUrl }),+ {+ version: PACKAGE_VERSION,+ executable: 'dist/cli.cjs',+ bundleFileCount: 3,+ templateFileCount: 2,+ pins: PINS,+ },+ );+ },+);++await testPublishCheck('refuses a package without its executable', async () => {+ const packageDirectory = await createPackage();++ await rm(join(packageDirectory, 'dist/cli.cjs'));+ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /^dist\/cli\.cjs is missing/,+ );+});++await testPublishCheck(+ 'refuses a build whose lazy chunk is missing',+ async () => {+ const packageDirectory = await createPackage();++ await rm(join(packageDirectory, 'dist/chunks/commands.cjs'));+ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /requires \.\/chunks\/commands\.cjs, which is missing/,+ );+ },+);++await testPublishCheck(+ 'refuses a missing or stale copy of the app template',+ async () => {+ const packageDirectory = await createPackage();+ const copiedFile = join(packageDirectory, 'dist/app-template/package.json');++ await writeFile(copiedFile, '{"stale":true}');+ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /^dist\/app-template\/package\.json differs from/,+ );++ await rm(copiedFile);+ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /^dist\/app-template\/package\.json is missing/,+ );+ },+);++await testPublishCheck('refuses a build made for another version', async () => {+ const packageDirectory = await createPackage({ version: '0.9.0' });++ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /dist was built as version 0\.9\.0, but package\.json is 1\.0\.0/,+ );+});++await testPublishCheck(+ 'refuses a CLI run that exits with an error after printing success',+ async () => {+ const packageDirectory = await createPackage({ exitCode: 1 });++ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /^twenty version exited with code 1 without an error result/,+ );+ },+);++await testPublishCheck(+ 'refuses a CLI run that does not finish in time',+ async () => {+ const packageDirectory = await createPackage({ hangs: true });++ await assertFailure(+ checkPublishReadiness({+ packageDirectory,+ registryUrl,+ commandTimeoutMilliseconds: 1_000,+ }),+ /^twenty version timed out after 1s/,+ );+ },+);++await testPublishCheck(+ 'refuses an app init that leaves out an essential file',+ async () => {+ const packageDirectory = await createPackage({+ skippedFiles: ['.yarnrc.yml'],+ });++ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /^app init did not create \.yarnrc\.yml/,+ );+ },+);++await testPublishCheck(+ 'refuses pins that differ from the generated package.json',+ async () => {+ const packageDirectory = await createPackage({+ renderedPins: PINS.map((pin) =>+ pin.name === 'twenty-sdk' ? { ...pin, version: '2.44.0' } : pin,+ ),+ });++ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /reported twenty-sdk@2\.45\.0, but the generated package\.json pins 2\.44\.0/,+ );+ },+);++await testPublishCheck('refuses pins that npm does not serve', async () => {+ const packageDirectory = await createPackage();++ registryStatuses.delete('/twenty-sdk/2.45.0');+ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /^app init would pin versions that are not on npm: twenty-sdk@2\.45\.0\./,+ );+});++await testPublishCheck(+ 'reports registry errors apart from missing versions',+ async () => {+ const packageDirectory = await createPackage();++ registryStatuses.set('/twenty-ui/2.45.0', 500);+ await assertFailure(+ checkPublishReadiness({ packageDirectory, registryUrl }),+ /^Could not verify these versions on http:\/\/127\.0\.0\.1:\d+: twenty-ui@2\.45\.0 \(HTTP 500\)/,+ );++ await assertFailure(+ checkPublishReadiness({+ packageDirectory,+ registryUrl: 'http://127.0.0.1:1',+ }),+ /^Could not verify these versions on http:\/\/127\.0\.0\.1:1: twenty-client-sdk@2\.45\.0 \(.+\)/,+ );+ },+);++await new Promise((resolve) => registry.close(resolve));diff --git a/packages/twenty-cli/scripts/test-package.mjs b/packages/twenty-cli/scripts/test-package.mjsindex d4cb25b3fa5..6c1246dafcd 100644--- a/packages/twenty-cli/scripts/test-package.mjs+++ b/packages/twenty-cli/scripts/test-package.mjs@@ -98,7 +98,7 @@ await test('the packed CLI works outside the monorepo', async (context) => {});await context.test(- 'app init renders the template and its CLI overlay',+ 'app init renders the template and its CLI test harness',async () => {const result = JSON.parse(cli('app', 'init', 'smoke-app', '--json', '--no-input'),diff --git a/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts b/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.tsindex 6fcbae9fad6..a7ae1f0d212 100644--- a/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts+++ b/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts@@ -4,7 +4,7 @@ import { delimiter, dirname, join } from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { runTwenty } from '../../../app-template-overlay/src/__tests__/run-twenty';+import { runTwenty } from '../../../app-template/src/__tests__/run-twenty';describe('runTwenty in the app template', () => {let root: string;diff --git a/packages/twenty-cli/src/app/add/prepare-app-add-file.ts b/packages/twenty-cli/src/app/add/prepare-app-add-file.tsindex 6d667bad00b..df1c8abf8e0 100644--- a/packages/twenty-cli/src/app/add/prepare-app-add-file.ts+++ b/packages/twenty-cli/src/app/add/prepare-app-add-file.ts@@ -1,4 +1,3 @@-import { convertToLabel } from '@create-twenty-app/utils/convert-to-label';import { isValidUniversalIdentifier } from 'twenty-shared/application';import {FieldMetadataType,@@ -7,6 +6,7 @@ import {} from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';+import { convertToLabel } from '@/app/convert-to-label';import { APP_ADD_ENTITIES } from '@/app/add/constants/app-add-entities.constant';import { getFieldBaseFile } from '@/app/add/entity-field-template';import { getFrontComponentBaseFile } from '@/app/add/entity-front-component-template';diff --git a/packages/twenty-cli/src/app/constants/app-template-package-version.constant.ts b/packages/twenty-cli/src/app/constants/app-template-package-version.constant.tsnew file mode 100644index 00000000000..97ff504c0ef--- /dev/null+++ b/packages/twenty-cli/src/app/constants/app-template-package-version.constant.ts@@ -0,0 +1,3 @@+import { version } from '../../../../twenty-sdk/package.json';++export const APP_TEMPLATE_PACKAGE_VERSION = version;diff --git a/packages/twenty-cli/src/app/constants/app-template-packages.constant.ts b/packages/twenty-cli/src/app/constants/app-template-packages.constant.tsnew file mode 100644index 00000000000..5d337958006--- /dev/null+++ b/packages/twenty-cli/src/app/constants/app-template-packages.constant.ts@@ -0,0 +1,5 @@+export const APP_TEMPLATE_FIRST_PARTY_PACKAGES = [+ 'twenty-client-sdk',+ 'twenty-sdk',+ 'twenty-ui',+] as const;diff --git a/packages/twenty-cli/src/app/convert-to-label.ts b/packages/twenty-cli/src/app/convert-to-label.tsnew file mode 100644index 00000000000..62d3131eeec--- /dev/null+++ b/packages/twenty-cli/src/app/convert-to-label.ts@@ -0,0 +1,5 @@+import startCase from 'lodash.startcase';+import { capitalize } from 'twenty-shared/utils';++export const convertToLabel = (name: string): string =>+ capitalize(startCase(name).toLowerCase());diff --git a/packages/twenty-cli/src/app/create-app-project.ts b/packages/twenty-cli/src/app/create-app-project.tsindex 04968c0bc57..bce947beeff 100644--- a/packages/twenty-cli/src/app/create-app-project.ts+++ b/packages/twenty-cli/src/app/create-app-project.ts@@ -1,7 +1,6 @@import { constants } from 'node:fs';import {copyFile,- cp,mkdir,mkdtemp,readdir,@@ -11,16 +10,12 @@ import {rmdir,stat,unlink,- writeFile,} from 'node:fs/promises';import { basename, dirname, join, relative } from 'node:path';-import { TEMPLATE_PACKAGE_VERSION } from '@create-twenty-app/constants/template-package-version';-import { copyBaseApplicationProject } from '@create-twenty-app/utils/app-template';import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';-import { getAppTemplateDirectory } from '@/app/get-app-template-directory';-import { getAppTemplateOverlayDirectory } from '@/app/get-app-template-overlay-directory';+import { renderAppTemplate } from '@/app/render-app-template';import { CliError } from '@/output/cli-error';import { EXIT_CODE } from '@/output/constants/exit-code.constant';import { hasErrorCode } from '@/utils/has-error-code';@@ -160,30 +155,14 @@ export const createAppProject = async ({);try {- await copyBaseApplicationProject({+ await renderAppTemplate({appName,appDisplayName,appDescription,appDirectory: stagingDirectory,- templateDirectory: getAppTemplateDirectory(),});signal.throwIfAborted();- const packageJsonPath = join(stagingDirectory, 'package.json');- const packageJson: { engines: Record<string, string> } = JSON.parse(- await readFile(packageJsonPath, 'utf8'),- );-- packageJson.engines = {- ...packageJson.engines,- twenty: `>=${TEMPLATE_PACKAGE_VERSION}`,- };-- await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));- await cp(getAppTemplateOverlayDirectory(), stagingDirectory, {- recursive: true,- });-const unrenderedFiles = await findUnrenderedFiles(stagingDirectory);if (isNonEmptyArray(unrenderedFiles)) {diff --git a/packages/twenty-cli/src/app/get-app-template-overlay-directory.ts b/packages/twenty-cli/src/app/get-app-template-overlay-directory.tsdeleted file mode 100644index 95f7237f563..00000000000--- a/packages/twenty-cli/src/app/get-app-template-overlay-directory.ts+++ /dev/null@@ -1,5 +0,0 @@-import { realpathSync } from 'node:fs';-import { dirname, join } from 'node:path';--export const getAppTemplateOverlayDirectory = () =>- join(dirname(realpathSync(process.argv[1] ?? '')), 'app-template-overlay');diff --git a/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts b/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.tsindex ad4fbfb565b..0fbb7fd3d91 100644--- a/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts+++ b/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts@@ -39,11 +39,7 @@ vi.mock('@/app/get-app-worker-launch', () => ({}));vi.mock('@/app/get-app-template-directory', () => ({getAppTemplateDirectory: () =>- join(REPOSITORY_ROOT, 'packages/create-twenty-app/src/constants/template'),-}));-vi.mock('@/app/get-app-template-overlay-directory', () => ({- getAppTemplateOverlayDirectory: () =>- join(REPOSITORY_ROOT, 'packages/twenty-cli/app-template-overlay'),+ join(REPOSITORY_ROOT, 'packages/twenty-cli/app-template'),}));const REPOSITORY_ROOT = fileURLToPath(diff --git a/packages/twenty-cli/src/app/render-app-template.ts b/packages/twenty-cli/src/app/render-app-template.tsnew file mode 100644index 00000000000..952fb1b18fc--- /dev/null+++ b/packages/twenty-cli/src/app/render-app-template.ts@@ -0,0 +1,64 @@+import { randomUUID } from 'node:crypto';+import { cp, readFile, rename, writeFile } from 'node:fs/promises';+import { join } from 'node:path';++import { APP_TEMPLATE_PACKAGE_VERSION } from '@/app/constants/app-template-package-version.constant';+import { APP_TEMPLATE_FIRST_PARTY_PACKAGES } from '@/app/constants/app-template-packages.constant';+import { getAppTemplateDirectory } from '@/app/get-app-template-directory';+import { printTypescriptValue } from '@/app/pull/print-typescript-value';++export const renderAppTemplate = async ({+ appDirectory,+ appName,+ appDisplayName,+ appDescription,+}: {+ appDirectory: string;+ appName: string;+ appDisplayName: string;+ appDescription: string;+}) => {+ await cp(getAppTemplateDirectory(), appDirectory, { recursive: true });++ // npm excludes these dotfiles when packing the template.+ for (const [source, destination] of [+ ['gitignore', '.gitignore'],+ ['github', '.github'],+ ['yarnrc.yml', '.yarnrc.yml'],+ ]) {+ await rename(join(appDirectory, source), join(appDirectory, destination));+ }++ await cp(join(appDirectory, 'AGENTS.md'), join(appDirectory, 'CLAUDE.md'));++ const identifiersPath = join(+ appDirectory,+ 'src/constants/universal-identifiers.ts',+ );+ const identifiers = (await readFile(identifiersPath, 'utf8'))+ .replace(/'DISPLAY-NAME-TO-BE-GENERATED'/g, () =>+ printTypescriptValue({ value: appDisplayName }),+ )+ .replace(/'DESCRIPTION-TO-BE-GENERATED'/g, () =>+ printTypescriptValue({ value: appDescription }),+ )+ .replace(/UUID-TO-BE-GENERATED/g, () => randomUUID());++ await writeFile(identifiersPath, identifiers);++ const packageJsonPath = join(appDirectory, 'package.json');+ const packageJson: {+ name: string;+ engines: Record<string, string>;+ devDependencies: Record<string, string>;+ } = JSON.parse(await readFile(packageJsonPath, 'utf8'));++ packageJson.name = appName;+ packageJson.engines.twenty = `>=${APP_TEMPLATE_PACKAGE_VERSION}`;++ for (const packageName of APP_TEMPLATE_FIRST_PARTY_PACKAGES) {+ packageJson.devDependencies[packageName] = APP_TEMPLATE_PACKAGE_VERSION;+ }++ await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));+};diff --git a/packages/twenty-cli/src/app/snapshots/__tests__/snapshot-parity.spec.ts b/packages/twenty-cli/src/app/snapshots/__tests__/snapshot-parity.spec.tsindex 924554b5bdc..5176302fadf 100644--- a/packages/twenty-cli/src/app/snapshots/__tests__/snapshot-parity.spec.ts+++ b/packages/twenty-cli/src/app/snapshots/__tests__/snapshot-parity.spec.ts@@ -33,11 +33,7 @@ vi.mock('@/app/get-app-worker-launch', () => ({}));vi.mock('@/app/get-app-template-directory', () => ({getAppTemplateDirectory: () =>- join(REPOSITORY_ROOT, 'packages/create-twenty-app/src/constants/template'),-}));-vi.mock('@/app/get-app-template-overlay-directory', () => ({- getAppTemplateOverlayDirectory: () =>- join(REPOSITORY_ROOT, 'packages/twenty-cli/app-template-overlay'),+ join(REPOSITORY_ROOT, 'packages/twenty-cli/app-template'),}));const REPOSITORY_ROOT = fileURLToPath(diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-build.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-build.spec.tsindex dfc461aa829..94604b694b3 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-build.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-build.spec.ts@@ -28,6 +28,7 @@ import {parseSingleJsonLine,runCliForTest,} from '@/__tests__/utils/run-cli-for-test';+import { CLI_VERSION } from '@/constants/cli-version.constant';const initializeModulePaths = () => {if (!('_initPaths' in Module) || !isFunction(Module._initPaths)) {@@ -188,9 +189,9 @@ describe('app build and typecheck', () => {]);expect(exitCode).toBe(0);- expect(stderr).toContain('Building fake-app with twenty 0.3.0');+ expect(stderr).toContain(`Building fake-app with twenty ${CLI_VERSION}`);expect(stderr).toContain('A deprecated option is used.');- expect(stdout).toContain('Built Fake App with twenty 0.3.0');+ expect(stdout).toContain(`Built Fake App with twenty ${CLI_VERSION}`);expect(stdout).toContain('2 files · 1.5 KB');expect(stdout).toContain('1 logic function · 1 source file');expect(stdout).toContain('Nothing was uploaded.');diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.tsindex 9149fa8dd47..38f1ded9c03 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts@@ -14,25 +14,20 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';-import { TEMPLATE_PACKAGE_VERSION } from '@create-twenty-app/constants/template-package-version';import { isDefined } from 'twenty-shared/utils';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { APP_TEMPLATE_PACKAGE_VERSION } from '@/app/constants/app-template-package-version.constant';import {parseSingleJsonLine,runCliForTest,} from '@/__tests__/utils/run-cli-for-test';import { getAppTemplateDirectory } from '@/app/get-app-template-directory';-import { getAppTemplateOverlayDirectory } from '@/app/get-app-template-overlay-directory';vi.mock('@/app/get-app-template-directory', () => ({getAppTemplateDirectory: vi.fn(),}));-vi.mock('@/app/get-app-template-overlay-directory', () => ({- getAppTemplateOverlayDirectory: vi.fn(),-}));-vi.mock('node:fs/promises', async (importOriginal) => {const actual = await importOriginal<typeof fileSystemPromises>();@@ -40,14 +35,7 @@ vi.mock('node:fs/promises', async (importOriginal) => {});const TEMPLATE_DIRECTORY = fileURLToPath(- new URL(- '../../../../../create-twenty-app/src/constants/template',- import.meta.url,- ),-);--const TEMPLATE_OVERLAY_DIRECTORY = fileURLToPath(- new URL('../../../../app-template-overlay', import.meta.url),+ new URL('../../../../app-template', import.meta.url),);const UUID_PATTERN =@@ -79,9 +67,6 @@ describe('app init', () => {await mkdir(join(root, 'home'));await mkdir(workDirectory);vi.mocked(getAppTemplateDirectory).mockReturnValue(TEMPLATE_DIRECTORY);- vi.mocked(getAppTemplateOverlayDirectory).mockReturnValue(- TEMPLATE_OVERLAY_DIRECTORY,- );vi.stubEnv('HOME', join(root, 'home'));vi.stubEnv('TWENTY_API_KEY', '');vi.stubEnv('TWENTY_API_URL', '');@@ -119,13 +104,13 @@ describe('app init', () => {engines: {node: '^24.5.0',npm: 'please-use-yarn',- twenty: `>=${TEMPLATE_PACKAGE_VERSION}`,+ twenty: `>=${APP_TEMPLATE_PACKAGE_VERSION}`,yarn: '>=4.0.2',},devDependencies: {- 'twenty-client-sdk': TEMPLATE_PACKAGE_VERSION,- 'twenty-sdk': TEMPLATE_PACKAGE_VERSION,- 'twenty-ui': TEMPLATE_PACKAGE_VERSION,+ 'twenty-client-sdk': APP_TEMPLATE_PACKAGE_VERSION,+ 'twenty-sdk': APP_TEMPLATE_PACKAGE_VERSION,+ 'twenty-ui': APP_TEMPLATE_PACKAGE_VERSION,},});@@ -168,7 +153,7 @@ describe('app init', () => {expect(globalSetup).not.toContain('twenty-sdk/cli');expect(await readFile(join(testsDirectory, 'run-twenty.ts'), 'utf8')).toBe(await readFile(- join(TEMPLATE_OVERLAY_DIRECTORY, 'src', '__tests__', 'run-twenty.ts'),+ join(TEMPLATE_DIRECTORY, 'src', '__tests__', 'run-twenty.ts'),'utf8',),);@@ -202,9 +187,9 @@ describe('app init', () => {path: appDirectory,},packages: [- { name: 'twenty-client-sdk', version: TEMPLATE_PACKAGE_VERSION },- { name: 'twenty-sdk', version: TEMPLATE_PACKAGE_VERSION },- { name: 'twenty-ui', version: TEMPLATE_PACKAGE_VERSION },+ { name: 'twenty-client-sdk', version: APP_TEMPLATE_PACKAGE_VERSION },+ { name: 'twenty-sdk', version: APP_TEMPLATE_PACKAGE_VERSION },+ { name: 'twenty-ui', version: APP_TEMPLATE_PACKAGE_VERSION },],nextSteps: [{ command: 'cd apps/billing', description: 'Enter the new app' },diff --git a/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts b/packages/twenty-cli/src/commands/app/init/run-app-init-command.tsindex 70ec82a6a7f..c8e958c4805 100644--- a/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts+++ b/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts@@ -1,10 +1,10 @@import { basename, isAbsolute, relative, resolve } from 'node:path';-import { TEMPLATE_PACKAGE_VERSION } from '@create-twenty-app/constants/template-package-version';-import { TEMPLATE_FIRST_PARTY_PACKAGES } from '@create-twenty-app/constants/template-packages';-import { convertToLabel } from '@create-twenty-app/utils/convert-to-label';import { isNonEmptyString } from '@sniptt/guards';+import { APP_TEMPLATE_PACKAGE_VERSION } from '@/app/constants/app-template-package-version.constant';+import { APP_TEMPLATE_FIRST_PARTY_PACKAGES } from '@/app/constants/app-template-packages.constant';+import { convertToLabel } from '@/app/convert-to-label';import { createAppProject } from '@/app/create-app-project';import { formatAppInitSummary } from '@/app/format-app-init-summary';import { getAppInitNextSteps } from '@/app/get-app-init-next-steps';@@ -85,7 +85,7 @@ export const runAppInitCommand: CommandRun = async ({}),remoteName,});- const packageNames = [...TEMPLATE_FIRST_PARTY_PACKAGES];+ const packageNames = [...APP_TEMPLATE_FIRST_PARTY_PACKAGES];return {data: {@@ -97,7 +97,7 @@ export const runAppInitCommand: CommandRun = async ({},packages: packageNames.map((name) => ({name,- version: TEMPLATE_PACKAGE_VERSION,+ version: APP_TEMPLATE_PACKAGE_VERSION,})),nextSteps,},@@ -105,7 +105,7 @@ export const runAppInitCommand: CommandRun = async ({appName,location,packageNames,- packageVersion: TEMPLATE_PACKAGE_VERSION,+ packageVersion: APP_TEMPLATE_PACKAGE_VERSION,nextSteps,}),};diff --git a/packages/twenty-cli/tsconfig.json b/packages/twenty-cli/tsconfig.jsonindex a5499218b31..96a34a98fd0 100644--- a/packages/twenty-cli/tsconfig.json+++ b/packages/twenty-cli/tsconfig.json@@ -11,8 +11,7 @@"lib": ["es2024"],"types": ["node"],"paths": {- "@/*": ["./src/*"],- "@create-twenty-app/*": ["../create-twenty-app/src/*"]+ "@/*": ["./src/*"]}},"include": ["src/**/*.ts", "vite.config.ts", "vitest.config.ts"]diff --git a/packages/twenty-cli/vite.config.ts b/packages/twenty-cli/vite.config.tsindex 06392941017..0742cf682dd 100644--- a/packages/twenty-cli/vite.config.ts+++ b/packages/twenty-cli/vite.config.ts@@ -21,18 +21,10 @@ export default defineConfig({name: 'copy-app-template',closeBundle: async () => {await cp(- path.resolve(- __dirname,- '../create-twenty-app/src/constants/template',- ),+ path.resolve(__dirname, 'app-template'),path.resolve(__dirname, 'dist/app-template'),{ recursive: true },);- await cp(- path.resolve(__dirname, 'app-template-overlay'),- path.resolve(__dirname, 'dist/app-template-overlay'),- { recursive: true },- );},},],@@ -40,7 +32,6 @@ export default defineConfig({resolve: {alias: {'@/': `${path.resolve(__dirname, 'src')}/`,- '@create-twenty-app/': `${path.resolve(__dirname, '../create-twenty-app/src')}/`,},},build: {diff --git a/packages/twenty-cli/vitest.config.ts b/packages/twenty-cli/vitest.config.tsindex 99c7fc76ced..31eaef6aa1e 100644--- a/packages/twenty-cli/vitest.config.ts+++ b/packages/twenty-cli/vitest.config.ts@@ -5,7 +5,6 @@ export default defineConfig({resolve: {alias: {'@/': `${path.resolve(__dirname, 'src')}/`,- '@create-twenty-app/': `${path.resolve(__dirname, '../create-twenty-app/src')}/`,},},test: {diff --git a/yarn.lock b/yarn.lockindex 166df7dbd40..0373eb14bd8 100644--- a/yarn.lock+++ b/yarn.lock@@ -51032,12 +51032,14 @@ __metadata:resolution: "twenty@workspace:packages/twenty-cli"dependencies:"@sniptt/guards": "npm:^0.2.0"+ "@types/lodash.startcase": "npm:^4""@types/node": "npm:^24.0.0""@types/semver": "npm:^7.5.8"chokidar: "npm:^3.6.0"cjs-module-lexer: "npm:^2.2.0"commander: "npm:^14.0.3"esbuild: "npm:^0.28.1"+ lodash.startcase: "npm:^4.4.0"semver: "npm:7.6.3"tinyglobby: "npm:^0.2.15"twenty-client-sdk: "workspace:*"