The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Store rich text as TipTap on the server (#28485)
neo773171988cc227c
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 3af5ddddeb3..85f9b7b1a74 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -4249,6 +4249,7 @@ input RevokeApiKeyInput {type RichTextBody {blocknote: Stringmarkdown: String+ tiptap: String}type Role {diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 1780291905c..61197117d36 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -3151,6 +3151,7 @@ export interface ResendEmailVerificationToken {export interface RichTextBody {blocknote?: Scalars['String']markdown?: Scalars['String']+ tiptap?: Scalars['String']__typename: 'RichTextBody'}@@ -7624,6 +7625,7 @@ export interface RevokeApiKeyInput {id: Scalars['UUID']}export interface RichTextBodyGenqlSelection{blocknote?: boolean | numbermarkdown?: boolean | number+ tiptap?: boolean | number__typename?: boolean | number__scalar?: boolean | number}diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex e0c48af5931..5f94e8c313d 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -11591,6 +11591,9 @@ export default {"markdown": [1],+ "tiptap": [+ 1+ ],"__typename": [1]diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 35390338407..c63924b75fa 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -6434,6 +6434,7 @@ export type RichTextBody = {__typename?: 'RichTextBody';blocknote?: Maybe<Scalars['String']['output']>;markdown?: Maybe<Scalars['String']['output']>;+ tiptap?: Maybe<Scalars['String']['output']>;};export type Role = {diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/types/FieldMetadata.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/types/FieldMetadata.tsindex 282fca31e76..b7465c12078 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/types/FieldMetadata.ts+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/types/FieldMetadata.ts@@ -305,6 +305,7 @@ export type FieldJsonValue = Record<string, Json> | Json[] | null;export type FieldRichTextValue = {blocknote: string | null;markdown: string | null;+ tiptap?: string | null;};const FieldActorSourceSchema = z.union([diff --git a/packages/twenty-front/src/modules/settings/data-model/constants/CompositeFieldSubFieldLabelMessages.ts b/packages/twenty-front/src/modules/settings/data-model/constants/CompositeFieldSubFieldLabelMessages.tsindex c21f86b51d1..9cae0d02a98 100644--- a/packages/twenty-front/src/modules/settings/data-model/constants/CompositeFieldSubFieldLabelMessages.ts+++ b/packages/twenty-front/src/modules/settings/data-model/constants/CompositeFieldSubFieldLabelMessages.ts@@ -51,5 +51,6 @@ export const COMPOSITE_FIELD_SUB_FIELD_LABEL_MESSAGES: {[FieldMetadataType.RICH_TEXT]: {blocknote: msg`BlockNote`,markdown: msg`Markdown`,+ tiptap: msg`TipTap`,},};diff --git a/packages/twenty-front/src/modules/settings/data-model/constants/SettingsCompositeFieldTypeConfigs.ts b/packages/twenty-front/src/modules/settings/data-model/constants/SettingsCompositeFieldTypeConfigs.tsindex 8538aeeac84..b9e48a3c466 100644--- a/packages/twenty-front/src/modules/settings/data-model/constants/SettingsCompositeFieldTypeConfigs.ts+++ b/packages/twenty-front/src/modules/settings/data-model/constants/SettingsCompositeFieldTypeConfigs.ts@@ -521,6 +521,17 @@ export const SETTINGS_COMPOSITE_FIELD_TYPE_CONFIGS = {isFilterable: false,isIncludedInUniqueConstraint: false,},+ {+ subFieldName:+ COMPOSITE_FIELD_TYPE_SUB_FIELDS_NAMES[FieldMetadataType.RICH_TEXT]+ .tiptap,+ subFieldLabel:+ COMPOSITE_FIELD_SUB_FIELD_LABEL_MESSAGES[FieldMetadataType.RICH_TEXT]+ .tiptap,+ isImportable: false,+ isFilterable: false,+ isIncludedInUniqueConstraint: false,+ },{subFieldName:COMPOSITE_FIELD_TYPE_SUB_FIELDS_NAMES[FieldMetadataType.RICH_TEXT]diff --git a/packages/twenty-server/package.json b/packages/twenty-server/package.jsonindex 556147987d4..ead03088ae4 100644--- a/packages/twenty-server/package.json+++ b/packages/twenty-server/package.json@@ -36,8 +36,6 @@"@aws-sdk/lib-storage": "3.1001.0","@aws-sdk/s3-request-presigner": "3.1001.0","@azure/msal-node": "^5.2.3",- "@blocknote/core": "^0.51.4",- "@blocknote/server-util": "^0.51.4","@clickhouse/client": "^1.18.1","@e2b/code-interpreter": "^2.6.0","@envelop/core": "4.0.3",diff --git a/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/data-arg-processor.service.ts b/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/data-arg-processor.service.tsindex 508f8518b43..e3dd402414e 100644--- a/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/data-arg-processor.service.ts+++ b/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/data-arg-processor.service.ts@@ -330,7 +330,7 @@ export class DataArgProcessorService {case FieldMetadataType.RICH_TEXT: {const validatedValue = validateRichTextFieldOrThrow(value, key);- return await transformRichTextValue(validatedValue);+ return transformRichTextValue(validatedValue);}case FieldMetadataType.LINKS: {const settings = isFieldMetadataSettingsOfType(diff --git a/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/__tests__/validate-rich-text-field-or-throw.util.spec.ts b/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/__tests__/validate-rich-text-field-or-throw.util.spec.tsindex fcf43105236..3d39f5cca8b 100644--- a/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/__tests__/validate-rich-text-field-or-throw.util.spec.ts+++ b/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/__tests__/validate-rich-text-field-or-throw.util.spec.ts@@ -86,5 +86,69 @@ describe('validateRichTextFieldOrThrow', () => {/must be a JSON array of blocks/,);});++ it('should return the value when tiptap is a rich text document', () => {+ const value = {+ tiptap: JSON.stringify({+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Hello' }],+ },+ ],+ }),+ };++ expect(validateRichTextFieldOrThrow(value, 'testField')).toEqual(value);+ });++ it('should throw when tiptap holds nodes a rich text field cannot store', () => {+ const value = {+ tiptap: JSON.stringify({+ type: 'doc',+ content: [{ type: 'button', attrs: { href: 'https://twenty.com' } }],+ }),+ };++ expect(() => validateRichTextFieldOrThrow(value, 'testField')).toThrow(+ /Invalid tiptap value/,+ );+ });++ it('should throw when a tiptap image points to a dangerous protocol', () => {+ const value = {+ tiptap: JSON.stringify({+ type: 'doc',+ content: [{ type: 'image', attrs: { src: 'javascript:alert(1)' } }],+ }),+ };++ expect(() => validateRichTextFieldOrThrow(value, 'testField')).toThrow(+ /Dangerous URL protocol/,+ );+ });++ it('should throw when a tiptap link hides its href key behind a JSON escape', () => {+ const value = {+ tiptap:+ '{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Click","marks":[{"type":"link","attrs":{"\\u0068ref":"javascript:alert(1)"}}]}]}]}',+ };++ expect(() => validateRichTextFieldOrThrow(value, 'testField')).toThrow(+ /Dangerous URL protocol/,+ );+ });++ it('should throw when a blocknote link hides its href key behind a JSON escape', () => {+ const value = {+ blocknote:+ '[{"type":"paragraph","content":[{"type":"link","\\u0068ref":"javascript:alert(1)","content":[]}]}]',+ };++ expect(() => validateRichTextFieldOrThrow(value, 'testField')).toThrow(+ /Dangerous URL protocol in blocknote content/,+ );+ });});});diff --git a/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util.ts b/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util.tsindex 39787901b8c..502f80b8d9e 100644--- a/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util.ts+++ b/packages/twenty-server/src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util.ts@@ -1,8 +1,14 @@import { inspect } from 'util';import { msg } from '@lingui/core/macro';-import { isNonEmptyString, isNull } from '@sniptt/guards';-import { isSafeUrl } from 'twenty-shared/utils';+import { isNonEmptyString, isNull, isString } from '@sniptt/guards';+import {+ isPlainObject,+ isSafeUrl,+ parseJson,+ richTextDocumentSchema,+} from 'twenty-shared/utils';+import { z } from 'zod';import { validateRawJsonFieldOrThrow } from 'src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-raw-json-field-or-throw.util';import { validateTextFieldOrThrow } from 'src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-text-field-or-throw.util';@@ -11,22 +17,28 @@ import {CommonQueryRunnerExceptionCode,} from 'src/engine/api/common/common-query-runners/errors/common-query-runner.exception';-const URL_VALUE_PATTERN = /"(?:url|href)"\s*:\s*"([^"]*)"/gi;--const hasDangerousUrl = (json: string): boolean => {- URL_VALUE_PATTERN.lastIndex = 0;+const isDangerousUrl = (url: unknown): boolean =>+ isString(url) && url.trim().length > 0 && !isSafeUrl(url.trim());- let match;-- while ((match = URL_VALUE_PATTERN.exec(json)) !== null) {- const url = match[1].trim();+const hasDangerousBlockNoteUrl = (value: unknown): boolean => {+ if (Array.isArray(value)) {+ return value.some(hasDangerousBlockNoteUrl);+ }- if (url.length > 0 && !isSafeUrl(url)) {- return true;- }+ if (!isPlainObject(value)) {+ return false;}- return false;+ return Object.entries(value).some(([key, entryValue]) => {+ switch (key) {+ case 'url':+ case 'href':+ case 'src':+ return isDangerousUrl(entryValue);+ default:+ return hasDangerousBlockNoteUrl(entryValue);+ }+ });};const validateBlocknoteFieldOrThrow = (@@ -35,7 +47,9 @@ const validateBlocknoteFieldOrThrow = (): string | null => {const textValue = validateTextFieldOrThrow(value, fieldName);- if (!isNonEmptyString(textValue)) return textValue;+ if (!isNonEmptyString(textValue)) {+ return textValue;+ }let parsed: unknown;@@ -57,7 +71,7 @@ const validateBlocknoteFieldOrThrow = ();}- if (hasDangerousUrl(textValue)) {+ if (hasDangerousBlockNoteUrl(parsed)) {throw new CommonQueryRunnerException(`Dangerous URL protocol in blocknote content for field "${fieldName}"`,CommonQueryRunnerExceptionCode.INVALID_ARGS_DATA,@@ -70,12 +84,38 @@ const validateBlocknoteFieldOrThrow = (return textValue;};+const validateTipTapFieldOrThrow = (+ value: unknown,+ fieldName: string,+): string | null => {+ const textValue = validateTextFieldOrThrow(value, fieldName);++ if (!isNonEmptyString(textValue)) {+ return textValue;+ }++ const parsedDocument = richTextDocumentSchema.safeParse(+ parseJson<unknown>(textValue),+ );++ if (!parsedDocument.success) {+ throw new CommonQueryRunnerException(+ `Invalid tiptap value for field "${fieldName}" - ${z.prettifyError(parsedDocument.error)}`,+ CommonQueryRunnerExceptionCode.INVALID_ARGS_DATA,+ { userFriendlyMessage: msg`Invalid value for rich text.` },+ );+ }++ return textValue;+};+export const validateRichTextFieldOrThrow = (value: unknown,fieldName: string,): {blocknote?: string | null;markdown?: string | null;+ tiptap?: string | null;} | null => {const preValidatedValue = validateRawJsonFieldOrThrow(value, fieldName);@@ -92,6 +132,9 @@ export const validateRichTextFieldOrThrow = (case 'markdown':validateTextFieldOrThrow(subFieldValue, `${fieldName}.${subField}`);break;+ case 'tiptap':+ validateTipTapFieldOrThrow(subFieldValue, `${fieldName}.${subField}`);+ break;default:throw new CommonQueryRunnerException(`Invalid subfield ${inspect(subField)} for rich text field "${fieldName}"`,@@ -104,5 +147,6 @@ export const validateRichTextFieldOrThrow = (return value as {blocknote?: string | null;markdown?: string | null;+ tiptap?: string | null;};};diff --git a/packages/twenty-server/src/engine/api/common/common-result-getters/handlers/field-handlers/__tests__/rich-text-field-query-result-getter.handler.spec.ts b/packages/twenty-server/src/engine/api/common/common-result-getters/handlers/field-handlers/__tests__/rich-text-field-query-result-getter.handler.spec.tsindex 45cfdb11a75..37b61648c77 100644--- a/packages/twenty-server/src/engine/api/common/common-result-getters/handlers/field-handlers/__tests__/rich-text-field-query-result-getter.handler.spec.ts+++ b/packages/twenty-server/src/engine/api/common/common-result-getters/handlers/field-handlers/__tests__/rich-text-field-query-result-getter.handler.spec.ts@@ -155,6 +155,57 @@ describe('RichTextFieldQueryResultGetterHandler', () => {});});+ describe('should sign file urls', () => {+ it('when uploaded images and files sit anywhere in the TipTap and BlockNote documents, leaving external ones alone', async () => {+ const uploadedFileUrl =+ 'https://my-domain.twenty.com/file/files-field/20202020-0000-4000-8000-000000000001';+ const tiptap = (nestedImageSrc: string, fileUrl: string) =>+ JSON.stringify({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [+ { type: 'paragraph' },+ { type: 'image', attrs: { src: nestedImageSrc } },+ ],+ },+ ],+ },+ { type: 'file', attrs: { url: fileUrl, name: 'contract.pdf' } },+ {+ type: 'image',+ attrs: { src: 'https://external.com/image.jpg' },+ },+ ],+ });+ const blocknote = (imageUrl: string) =>+ JSON.stringify([{ type: 'image', props: { url: imageUrl } }]);++ const result = await handler.handle(+ {+ ...baseRecord,+ bodyV2: {+ markdown: null,+ blocknote: blocknote(uploadedFileUrl),+ tiptap: tiptap(uploadedFileUrl, uploadedFileUrl),+ },+ },+ 'ws-1',+ richTextFieldMetadata,+ );++ expect(result.bodyV2).toEqual({+ markdown: null,+ blocknote: blocknote('signed-path'),+ tiptap: tiptap('signed-path', 'signed-path'),+ });+ });+ });+describe('should handle multiple RICH_TEXT fields', () => {it('when record has multiple rich text fields', async () => {const multiFieldMetadata = [diff --git a/packages/twenty-server/src/engine/api/common/common-result-getters/handlers/field-handlers/rich-text-field-query-result-getter.handler.ts b/packages/twenty-server/src/engine/api/common/common-result-getters/handlers/field-handlers/rich-text-field-query-result-getter.handler.tsindex ebcad4523e8..568962f1f57 100644--- a/packages/twenty-server/src/engine/api/common/common-result-getters/handlers/field-handlers/rich-text-field-query-result-getter.handler.ts+++ b/packages/twenty-server/src/engine/api/common/common-result-getters/handlers/field-handlers/rich-text-field-query-result-getter.handler.ts@@ -3,7 +3,14 @@ import {FileFolder,type ObjectRecord,} from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+import { isNonEmptyString, isString } from '@sniptt/guards';+import {+ getTipTapFileUrlAttributeName,+ isDefined,+ isTipTapNode,+ parseJson,+ type TipTapNode,+} from 'twenty-shared/utils';import { type QueryResultGetterHandlerInterface } from 'src/engine/api/graphql/workspace-query-runner/factories/query-result-getters/interfaces/query-result-getter-handler.interface';@@ -48,13 +55,22 @@ export class RichTextFieldQueryResultGetterHandler implements QueryResultGetterHfor (const field of richTextFields) {const fieldValue = record[field.name];- const blocknoteJson = fieldValue?.blocknote;- if (!blocknoteJson || typeof blocknoteJson !== 'string') {+ if (isNonEmptyString(fieldValue?.tiptap)) {+ record[field.name] = {+ ...record[field.name],+ tiptap: await this.signTipTapFileUrls({+ tiptapJson: fieldValue.tiptap,+ workspaceId,+ }),+ };+ }++ if (!isNonEmptyString(fieldValue?.blocknote)) {continue;}- const blocknoteBlocks = parseBlocknoteJsonSafely(blocknoteJson);+ const blocknoteBlocks = parseBlocknoteJsonSafely(fieldValue.blocknote);if (!isDefined(blocknoteBlocks)) {continue;@@ -66,7 +82,7 @@ export class RichTextFieldQueryResultGetterHandler implements QueryResultGetterH);record[field.name] = {- ...fieldValue,+ ...record[field.name],blocknote: JSON.stringify(signedBlocks),};}@@ -109,4 +125,67 @@ export class RichTextFieldQueryResultGetterHandler implements QueryResultGetterH}),);};++ signTipTapFileUrls = async ({+ tiptapJson,+ workspaceId,+ }: {+ tiptapJson: string;+ workspaceId: string;+ }): Promise<string> => {+ const document = parseJson<unknown>(tiptapJson);++ if (!isTipTapNode(document)) {+ return tiptapJson;+ }++ return JSON.stringify(+ await this.signTipTapNodeFileUrls({ node: document, workspaceId }),+ );+ };++ private signTipTapNodeFileUrls = async ({+ node,+ workspaceId,+ }: {+ node: TipTapNode;+ workspaceId: string;+ }): Promise<TipTapNode> => {+ const signedNode = isDefined(node.content)+ ? {+ ...node,+ content: await Promise.all(+ node.content.map((childNode) =>+ this.signTipTapNodeFileUrls({ node: childNode, workspaceId }),+ ),+ ),+ }+ : node;++ const fileUrlAttributeName = getTipTapFileUrlAttributeName(node.type);++ if (!isDefined(fileUrlAttributeName)) {+ return signedNode;+ }++ const fileUrl = node.attrs?.[fileUrlAttributeName];+ const fileIdFromUrl = isString(fileUrl)+ ? extractFileIdFromUrl(fileUrl, FileFolder.FilesField)+ : undefined;++ if (!isDefined(fileIdFromUrl)) {+ return signedNode;+ }++ const url = await this.fileUrlService.signFileByIdUrl({+ fileId: fileIdFromUrl,+ workspaceId,+ fileFolder: FileFolder.FilesField,+ });++ return {+ ...signedNode,+ attrs: { ...signedNode.attrs, [fileUrlAttributeName]: url },+ };+ };}diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/json-schemas/shared-value-definitions.json-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/json-schemas/shared-value-definitions.json-schema.tsindex 3860b3493ab..3dd67022ab7 100644--- a/packages/twenty-server/src/engine/core-modules/record-crud/json-schemas/shared-value-definitions.json-schema.ts+++ b/packages/twenty-server/src/engine/core-modules/record-crud/json-schemas/shared-value-definitions.json-schema.ts@@ -83,6 +83,6 @@ export const SHARED_VALUE_JSON_SCHEMAS = {},RichTextValue: {type: 'object',- properties: { markdown: STRING, blocknote: STRING },+ properties: { markdown: STRING },},} satisfies Record<string, JSONSchema7>;diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/utils/build-effective-selected-fields.util.ts b/packages/twenty-server/src/engine/core-modules/record-crud/utils/build-effective-selected-fields.util.tsindex 3833f50f329..0b613786a4d 100644--- a/packages/twenty-server/src/engine/core-modules/record-crud/utils/build-effective-selected-fields.util.ts+++ b/packages/twenty-server/src/engine/core-modules/record-crud/utils/build-effective-selected-fields.util.ts@@ -20,7 +20,7 @@ const LOGICAL_OPERATORS = new Set(['and', 'or', 'not']);const SUB_FIELDS_TO_EXCLUDE_BY_FIELD_TYPE: Partial<Record<FieldMetadataType, Set<string>>> = {- [FieldMetadataType.RICH_TEXT]: new Set(['blocknote']),+ [FieldMetadataType.RICH_TEXT]: new Set(['blocknote', 'tiptap']),};const buildSelectedField = ({diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/services/record-input-transformer.service.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/services/record-input-transformer.service.tsindex 64976b1b687..9f3bca21906 100644--- a/packages/twenty-server/src/engine/core-modules/record-transformer/services/record-input-transformer.service.ts+++ b/packages/twenty-server/src/engine/core-modules/record-transformer/services/record-input-transformer.service.ts@@ -80,7 +80,7 @@ export class RecordInputTransformerService {case FieldMetadataType.NUMBER:return value === null ? null : Number(value);case FieldMetadataType.RICH_TEXT:- return await transformRichTextValue(value);+ return transformRichTextValue(value);case FieldMetadataType.LINKS:return transformLinksValue({input: value,diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/convert-markdown-to-blocknote-blocks.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/convert-markdown-to-blocknote-blocks.util.spec.tsdeleted file mode 100644index 7ffa3120cb1..00000000000--- a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/convert-markdown-to-blocknote-blocks.util.spec.ts+++ /dev/null@@ -1,396 +0,0 @@-import { convertMarkdownToBlocknoteBlocks } from 'src/engine/core-modules/record-transformer/utils/convert-markdown-to-blocknote-blocks.util';--const DEFAULT_PROPS = {- backgroundColor: 'default',- textColor: 'default',- textAlignment: 'left',-};--const convertWithoutIds = (markdown: string) =>- JSON.parse(- JSON.stringify(convertMarkdownToBlocknoteBlocks(markdown), (key, value) =>- key === 'id' ? undefined : value,- ),- );--const text = (value: string, styles: Record<string, true> = {}) => ({- type: 'text',- text: value,- styles,-});--describe('convertMarkdownToBlocknoteBlocks', () => {- it('should convert headings and inline styles', () => {- expect(- convertWithoutIds(- '## Title\n\n**bold *both*** ~~gone~~ `code` [link **x**](https://example.com)',- ),- ).toEqual([- {- type: 'heading',- props: { ...DEFAULT_PROPS, level: 2, isToggleable: false },- content: [text('Title')],- children: [],- },- {- type: 'paragraph',- props: DEFAULT_PROPS,- content: [- text('bold ', { bold: true }),- text('both', { bold: true, italic: true }),- text(' '),- text('gone', { strike: true }),- text(' '),- text('code', { code: true }),- text(' '),- {- type: 'link',- href: 'https://example.com',- content: [text('link '), text('x', { bold: true })],- },- ],- children: [],- },- ]);- });-- it('should turn soft and hard line breaks into newlines', () => {- expect(convertWithoutIds('first \nsecond\nthird')).toEqual([- {- type: 'paragraph',- props: DEFAULT_PROPS,- content: [text('first\nsecond\nthird')],- children: [],- },- ]);- });-- it('should convert ordered, nested and task lists', () => {- expect(- convertWithoutIds('3. three\n4. four\n - nested\n\n- [x] done'),- ).toEqual([- {- type: 'numberedListItem',- props: { ...DEFAULT_PROPS, start: 3 },- content: [text('three')],- children: [],- },- {- type: 'numberedListItem',- props: DEFAULT_PROPS,- content: [text('four')],- children: [- {- type: 'bulletListItem',- props: DEFAULT_PROPS,- content: [text('nested')],- children: [],- },- ],- },- {- type: 'checkListItem',- props: { ...DEFAULT_PROPS, checked: true },- content: [text('done')],- children: [],- },- ]);- });-- it('should convert unchecked task items', () => {- expect(convertWithoutIds('- [ ] todo')).toEqual([- {- type: 'checkListItem',- props: { ...DEFAULT_PROPS, checked: false },- content: [text('todo')],- children: [],- },- ]);- });-- it('should only nest under an ordered item when indented past its marker', () => {- const blockTypes = (markdown: string) =>- convertMarkdownToBlocknoteBlocks(markdown).map((block) => ({- type: block.type,- childTypes: block.children?.map((child) => child.type),- }));-- expect(blockTypes('1. first\n - two spaces')).toEqual([- { type: 'numberedListItem', childTypes: [] },- { type: 'bulletListItem', childTypes: [] },- ]);- expect(blockTypes('1. first\n - three spaces')).toEqual([- { type: 'numberedListItem', childTypes: ['bulletListItem'] },- ]);- });-- it('should turn bare urls into links', () => {- expect(convertWithoutIds('see https://example.com')[0].content).toEqual([- text('see '),- {- type: 'link',- href: 'https://example.com',- content: [text('https://example.com')],- },- ]);- });-- it('should keep only the code style on inline code, even inside a link', () => {- expect(- convertWithoutIds('**bold `code`** [link `code`](https://example.com)')[0]- .content,- ).toEqual([- text('bold ', { bold: true }),- text('code', { code: true }),- text(' '),- {- type: 'link',- href: 'https://example.com',- content: [text('link ')],- },- text('code', { code: true }),- ]);- });-- it('should turn images inside list items into image children', () => {- const [listItem] = convertWithoutIds(- '- item ',- );-- expect(listItem.content).toEqual([text('item ')]);- expect(listItem.children).toEqual([- expect.objectContaining({- type: 'image',- props: expect.objectContaining({- name: 'logo',- url: 'https://example.com/logo.png',- }),- }),- ]);- });-- it('should drop urls the rich text validator would reject', () => {- expect(- convertWithoutIds(- '[click](javascript:alert%281%29)  [ok](https://example.com)',- ),- ).toEqual([- {- type: 'paragraph',- props: DEFAULT_PROPS,- content: [- text('click pixel '),- {- type: 'link',- href: 'https://example.com',- content: [text('ok')],- },- ],- children: [],- },- ]);- });-- it('should keep quote content in source order', () => {- expect(convertWithoutIds('> before\n>\n> - middle\n>\n> after')).toEqual([- {- type: 'quote',- props: { backgroundColor: 'default', textColor: 'default' },- content: [text('before\nmiddle\nafter')],- children: [],- },- ]);- });-- it('should turn images nested in links into image blocks', () => {- expect(- convertWithoutIds(- '[](https://example.com)',- ),- ).toEqual([- {- type: 'image',- props: {- textAlignment: 'left',- backgroundColor: 'default',- name: 'logo',- url: 'https://example.com/logo.png',- caption: '',- showPreview: true,- },- children: [],- },- ]);- });-- it('should keep text and nested images in source order', () => {- expect(- convertWithoutIds(- '**before  after**',- ).map((block: { type: string; content?: unknown }) => [- block.type,- block.content,- ]),- ).toEqual([- ['paragraph', [text('before ', { bold: true })]],- ['image', undefined],- ['paragraph', [text(' after', { bold: true })]],- ]);- });-- it('should keep quoted code and images', () => {- expect(- convertWithoutIds(- '> code:\n>\n> ```\n> x = 1\n> ```\n>\n> ',- ).map((block: { type: string; content?: unknown }) => [- block.type,- block.content,- ]),- ).toEqual([- ['quote', [text('code:\nx = 1')]],- ['image', undefined],- ]);- });-- it('should convert tables with their column alignment', () => {- const cellProps = {- colspan: 1,- rowspan: 1,- backgroundColor: 'default',- textColor: 'default',- };-- expect(- convertWithoutIds('| Plan | Seats |\n|---|--:|\n| Pro | 10 |'),- ).toEqual([- {- type: 'table',- props: { textColor: 'default' },- content: {- type: 'tableContent',- columnWidths: [null, null],- headerRows: 1,- rows: [- {- cells: [- {- type: 'tableCell',- content: [text('Plan')],- props: { ...cellProps, textAlignment: 'left' },- },- {- type: 'tableCell',- content: [text('Seats')],- props: { ...cellProps, textAlignment: 'right' },- },- ],- },- {- cells: [- {- type: 'tableCell',- content: [text('Pro')],- props: { ...cellProps, textAlignment: 'left' },- },- {- type: 'tableCell',- content: [text('10')],- props: { ...cellProps, textAlignment: 'right' },- },- ],- },- ],- },- children: [],- },- ]);- });-- it('should split a paragraph around images', () => {- expect(- convertWithoutIds('before  after'),- ).toEqual([- {- type: 'paragraph',- props: DEFAULT_PROPS,- content: [text('before ')],- children: [],- },- {- type: 'image',- props: {- textAlignment: 'left',- backgroundColor: 'default',- name: 'logo',- url: 'https://example.com/logo.png',- caption: '',- showPreview: true,- },- children: [],- },- {- type: 'paragraph',- props: DEFAULT_PROPS,- content: [text(' after')],- children: [],- },- ]);- });-- it('should convert quotes, code blocks and dividers', () => {- expect(- convertWithoutIds('> first\n>\n> second\n\n```\nplain\n```\n\n---'),- ).toEqual([- {- type: 'quote',- props: { backgroundColor: 'default', textColor: 'default' },- content: [text('first\nsecond')],- children: [],- },- {- type: 'codeBlock',- props: { language: 'text' },- content: [text('plain')],- children: [],- },- { type: 'divider', props: {}, children: [] },- ]);- });-- it('should keep raw html as literal text', () => {- expect(- convertWithoutIds('Hello <b>world</b>\n\n<div>\n<p>raw</p>\n</div>'),- ).toEqual([- {- type: 'paragraph',- props: DEFAULT_PROPS,- content: [text('Hello <b>world</b>')],- children: [],- },- {- type: 'paragraph',- props: DEFAULT_PROPS,- content: [text('<div>\n<p>raw</p>\n</div>')],- children: [],- },- ]);- });-- it('should return a single empty paragraph for empty markdown', () => {- expect(convertWithoutIds('')).toEqual([- { type: 'paragraph', props: DEFAULT_PROPS, content: [], children: [] },- ]);- });-- it('should give every block a unique id', () => {- const blocks = convertMarkdownToBlocknoteBlocks('- a\n - b\n\nc');- const nestedBlock = blocks[0].children?.[0];-- expect(nestedBlock).toBeDefined();-- const ids = [blocks[0].id, nestedBlock?.id, blocks[1].id];-- expect(ids.every((id) => typeof id === 'string')).toBe(true);- expect(new Set(ids).size).toBe(3);- });-});diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/convert-markdown-to-rich-text-document.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/convert-markdown-to-rich-text-document.util.spec.tsnew file mode 100644index 00000000000..ec292870299--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/convert-markdown-to-rich-text-document.util.spec.ts@@ -0,0 +1,261 @@+import { richTextDocumentSchema } from 'twenty-shared/utils';++import { convertMarkdownToRichTextDocument } from 'src/engine/core-modules/record-transformer/utils/convert-markdown-to-rich-text-document.util';++const convert = (markdown: string) => {+ const document = convertMarkdownToRichTextDocument(markdown);++ expect(richTextDocumentSchema.safeParse(document).success).toBe(true);++ return document.content;+};++const text = (value: string, marks?: Record<string, unknown>[]) =>+ marks === undefined+ ? { type: 'text', text: value }+ : { type: 'text', text: value, marks };++const paragraph = (...content: Record<string, unknown>[]) => ({+ type: 'paragraph',+ content,+});++const listItem = (...content: Record<string, unknown>[]) => ({+ type: 'listItem',+ content,+});++describe('convertMarkdownToRichTextDocument', () => {+ it('should convert headings and inline styles', () => {+ expect(+ convert(+ '## Title\n\n**bold *both*** ~~gone~~ `code` [link **x**](https://example.com)',+ ),+ ).toEqual([+ { type: 'heading', attrs: { level: 2 }, content: [text('Title')] },+ paragraph(+ text('bold ', [{ type: 'bold' }]),+ text('both', [{ type: 'bold' }, { type: 'italic' }]),+ text(' '),+ text('gone', [{ type: 'strike' }]),+ text(' '),+ text('code', [{ type: 'code' }]),+ text(' '),+ text('link ', [+ { type: 'link', attrs: { href: 'https://example.com' } },+ ]),+ text('x', [+ { type: 'bold' },+ { type: 'link', attrs: { href: 'https://example.com' } },+ ]),+ ),+ ]);+ });++ it('should turn soft and hard line breaks into hard breaks', () => {+ expect(convert('first \nsecond\nthird')).toEqual([+ paragraph(+ text('first'),+ { type: 'hardBreak' },+ text('second'),+ { type: 'hardBreak' },+ text('third'),+ ),+ ]);+ });++ it('should convert ordered, nested and task lists', () => {+ expect(convert('3. three\n4. four\n - nested\n\n- [x] done')).toEqual([+ {+ type: 'orderedList',+ attrs: { start: 3 },+ content: [+ listItem(paragraph(text('three'))),+ listItem(paragraph(text('four')), {+ type: 'bulletList',+ content: [listItem(paragraph(text('nested')))],+ }),+ ],+ },+ {+ type: 'taskList',+ content: [+ {+ type: 'taskItem',+ attrs: { checked: true },+ content: [paragraph(text('done'))],+ },+ ],+ },+ ]);+ });++ it('should only nest under an ordered item when indented past its marker', () => {+ const listTypes = (markdown: string) =>+ convert(markdown)?.map((node) => ({+ type: node.type,+ nestedTypes: node.content?.[0]?.content+ ?.slice(1)+ .map((child) => child.type),+ }));++ expect(listTypes('1. first\n - two spaces')).toEqual([+ { type: 'orderedList', nestedTypes: [] },+ { type: 'bulletList', nestedTypes: [] },+ ]);+ expect(listTypes('1. first\n - three spaces')).toEqual([+ { type: 'orderedList', nestedTypes: ['bulletList'] },+ ]);+ });++ it('should turn bare urls into links', () => {+ expect(convert('see https://example.com')).toEqual([+ paragraph(+ text('see '),+ text('https://example.com', [+ { type: 'link', attrs: { href: 'https://example.com' } },+ ]),+ ),+ ]);+ });++ it('should keep only the code mark on inline code, even inside a link', () => {+ expect(+ convert('**bold `code`** [link `code`](https://example.com)'),+ ).toEqual([+ paragraph(+ text('bold ', [{ type: 'bold' }]),+ text('code', [{ type: 'code' }]),+ text(' '),+ text('link ', [+ { type: 'link', attrs: { href: 'https://example.com' } },+ ]),+ text('code', [{ type: 'code' }]),+ ),+ ]);+ });++ it('should keep images inside list items after the item text', () => {+ expect(convert('- item ')).toEqual([+ {+ type: 'bulletList',+ content: [+ listItem(paragraph(text('item ')), {+ type: 'image',+ attrs: { src: 'https://example.com/logo.png', alt: 'logo' },+ }),+ ],+ },+ ]);+ });++ it('should drop urls the rich text validator would reject', () => {+ expect(+ convert(+ '[click](javascript:alert%281%29)  [ok](https://example.com)',+ ),+ ).toEqual([+ paragraph(+ text('click pixel '),+ text('ok', [{ type: 'link', attrs: { href: 'https://example.com' } }]),+ ),+ ]);+ });++ it('should drop urls longer than the rich text validator accepts', () => {+ const longUrl = `https://example.com/${'a'.repeat(4_000)}`;++ expect(convert(`[long](${longUrl}) `)).toEqual([+ paragraph(text('long big')),+ ]);+ });++ it('should keep the blocks of a quote in source order', () => {+ expect(convert('> before\n>\n> - middle\n>\n> after')).toEqual([+ {+ type: 'blockquote',+ content: [+ paragraph(text('before')),+ {+ type: 'bulletList',+ content: [listItem(paragraph(text('middle')))],+ },+ paragraph(text('after')),+ ],+ },+ ]);+ });++ it('should keep text and nested images in source order', () => {+ expect(+ convert('**before  after**')?.map(+ (node) => node.type,+ ),+ ).toEqual(['paragraph', 'image', 'paragraph']);+ });++ it('should convert tables with their column alignment', () => {+ expect(convert('| Plan | Seats |\n|---|--:|\n| Pro | 10 |')).toEqual([+ {+ type: 'table',+ content: [+ {+ type: 'tableRow',+ content: [+ { type: 'tableHeader', content: [paragraph(text('Plan'))] },+ {+ type: 'tableHeader',+ content: [+ {+ ...paragraph(text('Seats')),+ attrs: { textAlign: 'right' },+ },+ ],+ },+ ],+ },+ {+ type: 'tableRow',+ content: [+ { type: 'tableCell', content: [paragraph(text('Pro'))] },+ {+ type: 'tableCell',+ content: [+ { ...paragraph(text('10')), attrs: { textAlign: 'right' } },+ ],+ },+ ],+ },+ ],+ },+ ]);+ });++ it('should convert code blocks and dividers', () => {+ expect(convert('```ts\nconst a = 1;\n```\n\n---')).toEqual([+ {+ type: 'codeBlock',+ attrs: { language: 'ts' },+ content: [text('const a = 1;')],+ },+ { type: 'divider' },+ ]);+ });++ it('should keep raw html as literal text', () => {+ expect(convert('Hello <b>world</b>\n\n<div>\n<p>raw</p>\n</div>')).toEqual([+ paragraph(text('Hello <b>world</b>')),+ paragraph(+ text('<div>'),+ { type: 'hardBreak' },+ text('<p>raw</p>'),+ { type: 'hardBreak' },+ text('</div>'),+ ),+ ]);+ });++ it('should return a single empty paragraph for empty markdown', () => {+ expect(convert('')).toEqual([{ type: 'paragraph' }]);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/transform-rich-text.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/transform-rich-text.util.spec.tsindex df46d2f27c3..3ab72a0e5d9 100644--- a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/transform-rich-text.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/__tests__/transform-rich-text.util.spec.ts@@ -1,40 +1,117 @@import { transformRichTextValue } from 'src/engine/core-modules/record-transformer/utils/transform-rich-text.util';+const TIPTAP_VALUE = JSON.stringify({+ type: 'doc',+ attrs: { schemaVersion: 1 },+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Hello', marks: [{ type: 'bold' }] }],+ },+ ],+});+const BLOCKNOTE_VALUE = JSON.stringify([- { id: '1', type: 'paragraph', content: [{ type: 'text', text: 'Hello' }] },+ {+ id: '1',+ type: 'paragraph',+ props: {},+ content: [{ type: 'text', text: 'Hello', styles: { bold: true } }],+ children: [],+ },]);-const blockTypesOf = (blocknote: string | null | undefined) =>- JSON.parse(blocknote ?? '[]').map((block: { type: string }) => block.type);+const nodeTypesOf = (tiptap: string | null | undefined) =>+ JSON.parse(tiptap ?? '{}').content.map((node: { type: string }) => node.type);describe('transformRichTextValue', () => {- it('should build blocknote from markdown when only markdown is provided', async () => {- const result = await transformRichTextValue({+ it('should store TipTap as sent and derive the markdown from it', () => {+ const result = transformRichTextValue({ tiptap: TIPTAP_VALUE });++ expect(result).toEqual({+ tiptap: TIPTAP_VALUE,+ markdown: '**Hello**',+ blocknote: null,+ });+ });++ it('should ignore client markdown when TipTap is sent', () => {+ const result = transformRichTextValue({+ tiptap: TIPTAP_VALUE,+ markdown: 'stale markdown from the client',+ });++ expect(result).toEqual({+ tiptap: TIPTAP_VALUE,+ markdown: '**Hello**',+ blocknote: null,+ });+ });++ it('should stamp the schema version on TipTap sent without one', () => {+ const { attrs: _attrs, ...unversionedDocument } = JSON.parse(TIPTAP_VALUE);++ const result = transformRichTextValue({+ tiptap: JSON.stringify(unversionedDocument),+ });++ expect(JSON.parse(result.tiptap ?? '{}')).toEqual(JSON.parse(TIPTAP_VALUE));+ expect(result.markdown).toBe('**Hello**');+ });++ it('should build TipTap from markdown when only markdown is provided', () => {+ const result = transformRichTextValue({markdown: '# Title\n\n- item',});expect(result.markdown).toBe('# Title\n\n- item');- expect(blockTypesOf(result.blocknote)).toEqual([- 'heading',- 'bulletListItem',- ]);+ expect(nodeTypesOf(result.tiptap)).toEqual(['heading', 'bulletList']);+ });++ it('should convert BlockNote sent by older clients to TipTap and keep it as sent', () => {+ const result = transformRichTextValue({+ blocknote: BLOCKNOTE_VALUE,+ markdown: null,+ });++ expect(result).toEqual({+ tiptap: TIPTAP_VALUE,+ markdown: '**Hello**',+ blocknote: BLOCKNOTE_VALUE,+ });});- it('should keep both values untouched when both are provided', async () => {- const result = await transformRichTextValue({+ it('should derive the markdown from BlockNote rather than keep client markdown', () => {+ const result = transformRichTextValue({blocknote: BLOCKNOTE_VALUE,- markdown: 'Hello',+ markdown: 'stale markdown from the client',});- expect(result).toEqual({ markdown: 'Hello', blocknote: BLOCKNOTE_VALUE });+ expect(result.markdown).toBe('**Hello**');+ });++ it('should clear the BlockNote value when TipTap is sent', () => {+ expect(+ transformRichTextValue({+ tiptap: TIPTAP_VALUE,+ blocknote: BLOCKNOTE_VALUE,+ markdown: null,+ }).blocknote,+ ).toBeNull();+ });++ it('should clear the BlockNote value when only markdown is sent', () => {+ expect(+ transformRichTextValue({ markdown: '**Hello**' }).blocknote,+ ).toBeNull();});- it('should return nulls for an empty value', async () => {- const result = await transformRichTextValue({+ it('should return nulls for an empty value', () => {+ const result = transformRichTextValue({blocknote: '',markdown: null,});- expect(result).toEqual({ markdown: null, blocknote: null });+ expect(result).toEqual({ tiptap: null, markdown: null, blocknote: null });});});diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-inline-tokens.util.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-inline-tokens.util.tsindex c27c057653e..c9b84b0fea1 100644--- a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-inline-tokens.util.ts+++ b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-inline-tokens.util.ts@@ -1,12 +1,19 @@-import type { DefaultStyleSchema, Link, StyledText } from '@blocknote/core';import { type Token, type Tokens } from 'marked';-import { isDefined, isNonEmptyArray, isSafeUrl } from 'twenty-shared/utils';--type InlineStyle = 'bold' | 'italic' | 'strike' | 'code';--export type InlineContent =- | StyledText<DefaultStyleSchema>- | Link<DefaultStyleSchema>;+import {+ convertTextToTipTapNodes,+ isDefined,+ isNonEmptyArray,+ isStorableRichTextUrl,+ TIPTAP_MARK_TYPES,+ type TipTapMark,+ type TipTapNode,+} from 'twenty-shared/utils';++type InlineStyle =+ | typeof TIPTAP_MARK_TYPES.BOLD+ | typeof TIPTAP_MARK_TYPES.ITALIC+ | typeof TIPTAP_MARK_TYPES.STRIKE+ | typeof TIPTAP_MARK_TYPES.CODE;type InlineRun = {text: string;@@ -15,16 +22,16 @@ type InlineRun = {};const STYLE_BY_TOKEN_TYPE: Record<string, InlineStyle> = {- strong: 'bold',- em: 'italic',- del: 'strike',+ strong: TIPTAP_MARK_TYPES.BOLD,+ em: TIPTAP_MARK_TYPES.ITALIC,+ del: TIPTAP_MARK_TYPES.STRIKE,};export const getChildTokens = (token: Token): Token[] =>'tokens' in token && Array.isArray(token.tokens) ? token.tokens : [];export const isImageToken = (token: Token): token is Tokens.Image =>- token.type === 'image' && isSafeUrl(token.href);+ token.type === 'image' && isStorableRichTextUrl(token.href);export const splitAroundImages = (token: Token): Token[] => {const childTokens = getChildTokens(token);@@ -98,7 +105,7 @@ const collectInlineRuns = ({runs.push({ text: token.text, styles, href });break;case 'codespan':- runs.push({ text: token.text, styles: ['code'] });+ runs.push({ text: token.text, styles: [TIPTAP_MARK_TYPES.CODE] });break;case 'br':runs.push({ text: '\n', styles, href });@@ -107,7 +114,7 @@ const collectInlineRuns = ({collectInlineRuns({tokens: getChildTokens(token),styles,- href: isSafeUrl(token.href) ? token.href : href,+ href: isStorableRichTextUrl(token.href) ? token.href : href,runs,});break;@@ -115,7 +122,7 @@ const collectInlineRuns = ({runs.push({text: token.text.length > 0 ? token.text : token.href,styles,- href: isSafeUrl(token.href) ? token.href : href,+ href: isStorableRichTextUrl(token.href) ? token.href : href,});break;case 'checkbox':@@ -131,9 +138,17 @@ const isSameRunFormat = (firstRun: InlineRun, secondRun: InlineRun) =>firstRun.styles.length === secondRun.styles.length &&firstRun.styles.every((style) => secondRun.styles.includes(style));-export const convertMarkdownInlineTokens = (- tokens: Token[],-): InlineContent[] => {+const convertRunToMarks = (run: InlineRun): TipTapMark[] => {+ const marks: TipTapMark[] = run.styles.map((style) => ({ type: style }));++ if (isDefined(run.href)) {+ marks.push({ type: TIPTAP_MARK_TYPES.LINK, attrs: { href: run.href } });+ }++ return marks;+};++export const convertMarkdownInlineTokens = (tokens: Token[]): TipTapNode[] => {const runs: InlineRun[] = [];collectInlineRuns({ tokens, styles: [], runs });@@ -154,24 +169,7 @@ export const convertMarkdownInlineTokens = (}}- const content: InlineContent[] = [];-- for (const run of mergedRuns) {- const styledText: StyledText<DefaultStyleSchema> = {- type: 'text',- text: run.text,- styles: Object.fromEntries(run.styles.map((style) => [style, true])),- };- const lastContent = content[content.length - 1];-- if (!isDefined(run.href)) {- content.push(styledText);- } else if (lastContent?.type === 'link' && lastContent.href === run.href) {- lastContent.content.push(styledText);- } else {- content.push({ type: 'link', href: run.href, content: [styledText] });- }- }-- return content;+ return mergedRuns.flatMap((run) =>+ convertTextToTipTapNodes(run.text, convertRunToMarks(run)),+ );};diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-to-blocknote-blocks.util.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-to-blocknote-blocks.util.tsdeleted file mode 100644index 8955d51c2e1..00000000000--- a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-to-blocknote-blocks.util.ts+++ /dev/null@@ -1,281 +0,0 @@-import { randomUUID } from 'crypto';--import type { PartialBlock } from '@blocknote/core';-import { Lexer, type Token, type Tokens } from 'marked';-import { isNonEmptyArray } from 'twenty-shared/utils';--import {- convertMarkdownInlineTokens,- getChildTokens,- type InlineContent,- isImageToken,- splitAroundImages,-} from 'src/engine/core-modules/record-transformer/utils/convert-markdown-inline-tokens.util';--const DEFAULT_BLOCK_PROPS = {- backgroundColor: 'default',- textColor: 'default',- textAlignment: 'left',-} as const;--const createBlock = (block: PartialBlock): PartialBlock => ({- id: randomUUID(),- ...block,- children: block.children ?? [],-});--const isBlankContent = (content: InlineContent[]) =>- content.every((item) => item.type === 'text' && item.text.trim() === '');--const LINE_BREAK_TOKEN: Tokens.Br = { type: 'br', raw: '\n' };--const isListToken = (token: Token): token is Tokens.List =>- token.type === 'list';--const isTableToken = (token: Token): token is Tokens.Table =>- token.type === 'table';--const convertImage = (image: Tokens.Image): PartialBlock =>- createBlock({- type: 'image',- props: {- textAlignment: 'left',- backgroundColor: 'default',- name: image.text,- url: image.href,- caption: '',- showPreview: true,- },- });--const convertParagraph = (tokens: Token[]): PartialBlock[] => {- const blocks: PartialBlock[] = [];- let pendingTokens: Token[] = [];-- const flushParagraph = () => {- const content = convertMarkdownInlineTokens(pendingTokens);-- if (!isBlankContent(content)) {- blocks.push(- createBlock({- type: 'paragraph',- props: { ...DEFAULT_BLOCK_PROPS },- content,- }),- );- }-- pendingTokens = [];- };-- for (const token of tokens.flatMap(splitAroundImages)) {- if (!isImageToken(token)) {- pendingTokens.push(token);- continue;- }-- flushParagraph();- blocks.push(convertImage(token));- }-- flushParagraph();-- return blocks;-};--const convertListItem = ({- list,- item,- index,-}: {- list: Tokens.List;- item: Tokens.ListItem;- index: number;-}): PartialBlock => {- const tokens = item.tokens.filter(- (token) => token.type !== 'checkbox' && token.type !== 'space',- );- const [firstToken, ...otherTokens] = tokens;- const hasInlineFirstToken =- firstToken?.type === 'text' || firstToken?.type === 'paragraph';-- const inlineParts = hasInlineFirstToken- ? (firstToken.tokens ?? []).flatMap(splitAroundImages)- : [];- const content = convertMarkdownInlineTokens(- inlineParts.filter((token) => !isImageToken(token)),- );- const children = [- ...inlineParts.filter(isImageToken).map(convertImage),- ...convertBlockTokens(hasInlineFirstToken ? otherTokens : tokens),- ];-- if (item.task) {- return createBlock({- type: 'checkListItem',- props: { ...DEFAULT_BLOCK_PROPS, checked: item.checked === true },- content,- children,- });- }-- if (list.ordered) {- const start = Number(list.start);-- return createBlock({- type: 'numberedListItem',- props:- index === 0 && Number.isInteger(start) && start !== 1- ? { ...DEFAULT_BLOCK_PROPS, start }- : { ...DEFAULT_BLOCK_PROPS },- content,- children,- });- }-- return createBlock({- type: 'bulletListItem',- props: { ...DEFAULT_BLOCK_PROPS },- content,- children,- });-};--const collectQuoteLines = (tokens: Token[]): Token[][] =>- tokens.flatMap((token): Token[][] => {- switch (token.type) {- case 'space':- return [];- case 'paragraph':- case 'text':- case 'heading':- return [getChildTokens(token)];- case 'list':- return isListToken(token)- ? token.items.flatMap((item) => collectQuoteLines(item.tokens))- : [];- case 'blockquote':- return collectQuoteLines(getChildTokens(token));- case 'code':- return [[{ type: 'text', raw: token.raw, text: token.text }]];- default:- return [[{ type: 'text', raw: token.raw, text: token.raw.trimEnd() }]];- }- });--const convertTable = (table: Tokens.Table): PartialBlock => {- const toRow = (cells: Tokens.TableCell[]) => ({- cells: cells.map((cell, columnIndex) => ({- type: 'tableCell' as const,- content: convertMarkdownInlineTokens(cell.tokens),- props: {- colspan: 1,- rowspan: 1,- backgroundColor: 'default',- textColor: 'default',- textAlignment: table.align[columnIndex] ?? 'left',- },- })),- });-- return createBlock({- type: 'table',- props: { textColor: 'default' },- content: {- type: 'tableContent',- columnWidths: table.header.map(() => undefined),- headerRows: 1,- rows: [toRow(table.header), ...table.rows.map(toRow)],- },- });-};--const convertBlockTokens = (tokens: Token[]): PartialBlock[] =>- tokens.flatMap((token): PartialBlock[] => {- switch (token.type) {- case 'space':- case 'def':- return [];- case 'heading':- return [- createBlock({- type: 'heading',- props: {- ...DEFAULT_BLOCK_PROPS,- level: token.depth,- isToggleable: false,- },- content: convertMarkdownInlineTokens(token.tokens ?? []),- }),- ];- case 'paragraph':- case 'text':- return convertParagraph(token.tokens ?? [token]);- case 'code':- return [- createBlock({- type: 'codeBlock',- props: { language: token.lang || 'text' },- content:- token.text.length > 0- ? [{ type: 'text', text: token.text, styles: {} }]- : [],- }),- ];- case 'hr':- return [createBlock({ type: 'divider', props: {} })];- case 'blockquote': {- const quoteLines = collectQuoteLines(token.tokens ?? []).map((line) =>- line.flatMap(splitAroundImages),- );- const quoteTextLines = quoteLines- .map((line) => line.filter((part) => !isImageToken(part)))- .filter(isNonEmptyArray);-- return [- createBlock({- type: 'quote',- props: { backgroundColor: 'default', textColor: 'default' },- content: convertMarkdownInlineTokens(- quoteTextLines.flatMap((line, index) =>- index > 0 ? [LINE_BREAK_TOKEN, ...line] : line,- ),- ),- }),- ...quoteLines.flat().filter(isImageToken).map(convertImage),- ];- }- case 'list':- return isListToken(token)- ? token.items.map((item, index) =>- convertListItem({ list: token, item, index }),- )- : [];- case 'table':- return isTableToken(token) ? [convertTable(token)] : [];- default:- return [- createBlock({- type: 'paragraph',- props: { ...DEFAULT_BLOCK_PROPS },- content: [{ type: 'text', text: token.raw.trimEnd(), styles: {} }],- }),- ];- }- });--export const convertMarkdownToBlocknoteBlocks = (- markdown: string,-): PartialBlock[] => {- const blocks = convertBlockTokens(new Lexer({ gfm: true }).lex(markdown));-- return blocks.length > 0- ? blocks- : [- createBlock({- type: 'paragraph',- props: { ...DEFAULT_BLOCK_PROPS },- content: [],- }),- ];-};diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-to-rich-text-document.util.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-to-rich-text-document.util.tsnew file mode 100644index 00000000000..94cab174db6--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/convert-markdown-to-rich-text-document.util.ts@@ -0,0 +1,250 @@+import { Lexer, type Token, type Tokens } from 'marked';+import {+ RICH_TEXT_MAX_HEADING_LEVEL,+ type RichTextDocument,+ TIPTAP_DOCUMENT_SCHEMA_VERSION,+ TIPTAP_NODE_TYPES,+ type TipTapNode,+} from 'twenty-shared/utils';++import {+ convertMarkdownInlineTokens,+ isImageToken,+ splitAroundImages,+} from 'src/engine/core-modules/record-transformer/utils/convert-markdown-inline-tokens.util';++type ListNodeType =+ | typeof TIPTAP_NODE_TYPES.BULLET_LIST+ | typeof TIPTAP_NODE_TYPES.ORDERED_LIST+ | typeof TIPTAP_NODE_TYPES.TASK_LIST;++const isBlankContent = (content: TipTapNode[]) =>+ content.every(+ (node) =>+ node.type === TIPTAP_NODE_TYPES.HARD_BREAK ||+ (node.text ?? '').trim() === '',+ );++const isListToken = (token: Token): token is Tokens.List =>+ token.type === 'list';++const isTableToken = (token: Token): token is Tokens.Table =>+ token.type === 'table';++const createParagraphNode = (content: TipTapNode[]): TipTapNode =>+ content.length > 0+ ? { type: TIPTAP_NODE_TYPES.PARAGRAPH, content }+ : { type: TIPTAP_NODE_TYPES.PARAGRAPH };++const convertImage = (image: Tokens.Image): TipTapNode => ({+ type: TIPTAP_NODE_TYPES.IMAGE,+ attrs: {+ src: image.href,+ alt: image.text.length > 0 ? image.text : null,+ },+});++const convertParagraph = (tokens: Token[]): TipTapNode[] => {+ const nodes: TipTapNode[] = [];+ let pendingTokens: Token[] = [];++ const flushParagraph = () => {+ const content = convertMarkdownInlineTokens(pendingTokens);++ if (!isBlankContent(content)) {+ nodes.push(createParagraphNode(content));+ }++ pendingTokens = [];+ };++ for (const token of tokens.flatMap(splitAroundImages)) {+ if (!isImageToken(token)) {+ pendingTokens.push(token);+ continue;+ }++ flushParagraph();+ nodes.push(convertImage(token));+ }++ flushParagraph();++ return nodes;+};++const convertListItem = (item: Tokens.ListItem): TipTapNode => {+ const tokens = item.tokens.filter(+ (token) => token.type !== 'checkbox' && token.type !== 'space',+ );+ const [firstToken, ...otherTokens] = tokens;+ const hasInlineFirstToken =+ firstToken?.type === 'text' || firstToken?.type === 'paragraph';++ const inlineParts = hasInlineFirstToken+ ? (firstToken.tokens ?? []).flatMap(splitAroundImages)+ : [];+ const content = [+ createParagraphNode(+ convertMarkdownInlineTokens(+ inlineParts.filter((token) => !isImageToken(token)),+ ),+ ),+ ...inlineParts.filter(isImageToken).map(convertImage),+ ...convertBlockTokens(hasInlineFirstToken ? otherTokens : tokens),+ ];++ return item.task+ ? {+ type: TIPTAP_NODE_TYPES.TASK_ITEM,+ attrs: { checked: item.checked ?? false },+ content,+ }+ : { type: TIPTAP_NODE_TYPES.LIST_ITEM, content };+};++const getListNodeType = (+ list: Tokens.List,+ item: Tokens.ListItem,+): ListNodeType => {+ if (item.task) {+ return TIPTAP_NODE_TYPES.TASK_LIST;+ }++ return list.ordered+ ? TIPTAP_NODE_TYPES.ORDERED_LIST+ : TIPTAP_NODE_TYPES.BULLET_LIST;+};++const convertList = (list: Tokens.List): TipTapNode[] => {+ const nodes: TipTapNode[] = [];+ const start = Number(list.start);+ const hasCustomStart = Number.isInteger(start) && start !== 1;++ for (const item of list.items) {+ const listNodeType = getListNodeType(list, item);+ const lastNode = nodes[nodes.length - 1];++ if (lastNode?.type === listNodeType) {+ lastNode.content?.push(convertListItem(item));+ continue;+ }++ const listNode: TipTapNode = {+ type: listNodeType,+ content: [convertListItem(item)],+ };++ if (+ listNodeType === TIPTAP_NODE_TYPES.ORDERED_LIST &&+ nodes.length === 0 &&+ hasCustomStart+ ) {+ listNode.attrs = { start };+ }++ nodes.push(listNode);+ }++ return nodes;+};++const convertTable = (table: Tokens.Table): TipTapNode => {+ const toRow = (+ cells: Tokens.TableCell[],+ cellType:+ | typeof TIPTAP_NODE_TYPES.TABLE_HEADER+ | typeof TIPTAP_NODE_TYPES.TABLE_CELL,+ ): TipTapNode => ({+ type: TIPTAP_NODE_TYPES.TABLE_ROW,+ content: cells.map((cell, columnIndex) => {+ const textAlign = table.align[columnIndex];+ const paragraph = createParagraphNode(+ convertMarkdownInlineTokens(cell.tokens),+ );++ return {+ type: cellType,+ content: [+ textAlign === 'center' || textAlign === 'right'+ ? { ...paragraph, attrs: { textAlign } }+ : paragraph,+ ],+ };+ }),+ });++ return {+ type: TIPTAP_NODE_TYPES.TABLE,+ content: [+ toRow(table.header, TIPTAP_NODE_TYPES.TABLE_HEADER),+ ...table.rows.map((row) => toRow(row, TIPTAP_NODE_TYPES.TABLE_CELL)),+ ],+ };+};++const convertBlockquote = (tokens: Token[]): TipTapNode => {+ const content = convertBlockTokens(tokens);++ return {+ type: TIPTAP_NODE_TYPES.BLOCKQUOTE,+ content: content.length > 0 ? content : [createParagraphNode([])],+ };+};++const convertBlockTokens = (tokens: Token[]): TipTapNode[] =>+ tokens.flatMap((token): TipTapNode[] => {+ switch (token.type) {+ case 'space':+ case 'def':+ return [];+ case 'heading':+ return [+ {+ type: TIPTAP_NODE_TYPES.HEADING,+ attrs: {+ level: Math.min(token.depth, RICH_TEXT_MAX_HEADING_LEVEL),+ },+ content: convertMarkdownInlineTokens(token.tokens ?? []),+ },+ ];+ case 'paragraph':+ case 'text':+ return convertParagraph(token.tokens ?? [token]);+ case 'code':+ return [+ {+ type: TIPTAP_NODE_TYPES.CODE_BLOCK,+ attrs: { language: token.lang || null },+ content:+ token.text.length > 0+ ? [{ type: TIPTAP_NODE_TYPES.TEXT, text: token.text }]+ : [],+ },+ ];+ case 'hr':+ return [{ type: TIPTAP_NODE_TYPES.DIVIDER }];+ case 'blockquote':+ return [convertBlockquote(token.tokens ?? [])];+ case 'list':+ return isListToken(token) ? convertList(token) : [];+ case 'table':+ return isTableToken(token) ? [convertTable(token)] : [];+ default:+ return convertParagraph([+ { type: 'text', raw: token.raw, text: token.raw.trimEnd() },+ ]);+ }+ });++export const convertMarkdownToRichTextDocument = (+ markdown: string,+): RichTextDocument => {+ const content = convertBlockTokens(new Lexer({ gfm: true }).lex(markdown));++ return {+ type: TIPTAP_NODE_TYPES.DOCUMENT,+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },+ content: content.length > 0 ? content : [createParagraphNode([])],+ };+};diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/ensure-tiptap-schema-version.util.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/ensure-tiptap-schema-version.util.tsnew file mode 100644index 00000000000..d916b2cd71b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/ensure-tiptap-schema-version.util.ts@@ -0,0 +1,18 @@+import {+ isDefined,+ parseTipTapJsonDocument,+ TIPTAP_DOCUMENT_SCHEMA_VERSION,+} from 'twenty-shared/utils';++export const ensureTipTapSchemaVersion = (tiptap: string): string => {+ const document = parseTipTapJsonDocument(tiptap);++ if (!isDefined(document) || isDefined(document.attrs?.schemaVersion)) {+ return tiptap;+ }++ return JSON.stringify({+ ...document,+ attrs: { ...document.attrs, schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },+ });+};diff --git a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/transform-rich-text.util.ts b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/transform-rich-text.util.tsindex 3bf8eb052b2..48a75bf0721 100644--- a/packages/twenty-server/src/engine/core-modules/record-transformer/utils/transform-rich-text.util.ts+++ b/packages/twenty-server/src/engine/core-modules/record-transformer/utils/transform-rich-text.util.ts@@ -3,74 +3,58 @@ import {type RichTextMetadata,richTextValueSchema,} from 'twenty-shared/types';+import {+ convertBlockNoteToRichTextDocument,+ isDefined,+ tipTapDocumentToMarkdown,+} from 'twenty-shared/utils';-import type { ServerBlockNoteEditor } from '@blocknote/server-util';--import { convertMarkdownToBlocknoteBlocks } from 'src/engine/core-modules/record-transformer/utils/convert-markdown-to-blocknote-blocks.util';--// Reuse a single ServerBlockNoteEditor across all calls to avoid-// the cost of dynamic import resolution + instance creation (~90ms) on every transform.-let serverBlockNoteEditorPromise: Promise<ServerBlockNoteEditor> | null = null;--// SWC compiles import() to require() in CJS mode, which breaks ESM-only-// transitive dependencies in @blocknote/core. Native import() resolves-// the ESM bundle path where the full chain works.-const nativeImport = new Function('specifier', 'return import(specifier)');+import { convertMarkdownToRichTextDocument } from 'src/engine/core-modules/record-transformer/utils/convert-markdown-to-rich-text-document.util';+import { ensureTipTapSchemaVersion } from 'src/engine/core-modules/record-transformer/utils/ensure-tiptap-schema-version.util';-const loadServerBlockNoteEditor = async (): Promise<ServerBlockNoteEditor> => {- const module = await nativeImport('@blocknote/server-util');+export const transformRichTextValue = (+ // oxlint-disable-next-line typescript/no-explicit-any+ richTextValue: any,+): RichTextMetadata => {+ const { tiptap, blocknote, markdown }: RichTextMetadata = isNonEmptyString(+ richTextValue,+ )+ ? richTextValueSchema.parse(richTextValue)+ : richTextValue;- return module.ServerBlockNoteEditor.create();-};+ if (isNonEmptyString(tiptap)) {+ const versionedTipTap = ensureTipTapSchemaVersion(tiptap);-const getServerBlockNoteEditor = (): Promise<ServerBlockNoteEditor> => {- serverBlockNoteEditorPromise ??= loadServerBlockNoteEditor().catch(- (error: unknown) => {- serverBlockNoteEditorPromise = null;- throw error;- },- );+ return {+ tiptap: versionedTipTap,+ markdown: tipTapDocumentToMarkdown(versionedTipTap),+ blocknote: null,+ };+ }- return serverBlockNoteEditorPromise;-};+ const blockNoteDocument = isNonEmptyString(blocknote)+ ? convertBlockNoteToRichTextDocument(blocknote)+ : undefined;-const convertMarkdownToBlocknote = (markdown: string): string =>- JSON.stringify(convertMarkdownToBlocknoteBlocks(markdown));+ if (isDefined(blockNoteDocument)) {+ return {+ tiptap: JSON.stringify(blockNoteDocument),+ markdown: tipTapDocumentToMarkdown(blockNoteDocument),+ blocknote,+ };+ }-// Patch: Handle cases where blocknote to markdown conversion fails for certain block types (custom/code blocks)-// Todo : This may be resolved once the server-utils library is updated with proper conversion support - #947-const convertBlocknoteToMarkdown = async (- blocknote: string,-): Promise<string> => {- const serverBlockNoteEditor = await getServerBlockNoteEditor();+ const markdownDocument = isNonEmptyString(markdown)+ ? convertMarkdownToRichTextDocument(markdown)+ : undefined;- try {- return await serverBlockNoteEditor.blocksToMarkdownLossy(- JSON.parse(blocknote),- );- } catch {- return blocknote;+ if (!isDefined(markdownDocument)) {+ return { tiptap: null, markdown: null, blocknote: null };}-};--export const transformRichTextValue = async (- // oxlint-disable-next-line typescript/no-explicit-any- richTextValue: any,-): Promise<RichTextMetadata> => {- const parsedValue = isNonEmptyString(richTextValue)- ? richTextValueSchema.parse(richTextValue)- : richTextValue;return {- markdown:- parsedValue.markdown ||- (isNonEmptyString(parsedValue.blocknote)- ? await convertBlocknoteToMarkdown(parsedValue.blocknote)- : null),- blocknote:- parsedValue.blocknote ||- (isNonEmptyString(parsedValue.markdown)- ? convertMarkdownToBlocknote(parsedValue.markdown)- : null),+ tiptap: JSON.stringify(markdownDocument),+ markdown,+ blocknote: null,};};diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.tsindex a7ecf0f26ac..bc850267ca1 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts@@ -22,6 +22,7 @@ import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspaimport { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';+import { ensureWorkflowStepsTipTapSchemaVersion } from 'src/engine/core-modules/workflow/utils/ensure-workflow-steps-tiptap-schema-version.util';import { getCoreWorkflowVersionEditLockKey } from 'src/engine/core-modules/workflow/utils/get-core-workflow-version-edit-lock-key.util';import {WorkflowQueryValidationException,@@ -177,17 +178,19 @@ export class CoreWorkflowVersionWriteService {trigger: WorkflowTrigger | null;steps: WorkflowAction[] | null;}): Promise<CoreWorkflowVersionContent> {+ const versionedSteps = ensureWorkflowStepsTipTapSchemaVersion(callerSteps);+await this.assertContentIsNotMalformed({workspaceId,coreWorkflowVersionId,trigger,- steps: callerSteps,+ steps: versionedSteps,});const steps =await this.workflowSchemaWorkspaceService.enrichStepsOutputSchema({trigger,- steps: callerSteps,+ steps: versionedSteps,workspaceId,});@@ -306,17 +309,19 @@ export class CoreWorkflowVersionWriteService {trigger: WorkflowTrigger | null;steps: WorkflowAction[] | null;}): Promise<{ coreWorkflowVersionId: string }> {+ const versionedSteps = ensureWorkflowStepsTipTapSchemaVersion(callerSteps);+await this.assertContentIsNotMalformed({workspaceId,coreWorkflowVersionId: 'new draft',trigger,- steps: callerSteps,+ steps: versionedSteps,});const steps =await this.workflowSchemaWorkspaceService.enrichStepsOutputSchema({trigger,- steps: callerSteps,+ steps: versionedSteps,workspaceId,});diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/ensure-workflow-steps-tiptap-schema-version.util.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/ensure-workflow-steps-tiptap-schema-version.util.spec.tsnew file mode 100644index 00000000000..7db1aa9076f--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/ensure-workflow-steps-tiptap-schema-version.util.spec.ts@@ -0,0 +1,86 @@+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';+import { WorkflowActionType } from 'twenty-shared/workflow';++import { ensureWorkflowStepsTipTapSchemaVersion } from 'src/engine/core-modules/workflow/utils/ensure-workflow-steps-tiptap-schema-version.util';+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';++const recordStep = (+ objectRecord: Record<string, unknown>,+ type: WorkflowActionType = WorkflowActionType.CREATE_RECORD,+): WorkflowAction =>+ ({+ id: 'step-1',+ name: 'Create note',+ type,+ valid: true,+ settings: {+ input: { objectName: 'note', objectRecord },+ outputSchema: {},+ errorHandlingOptions: {+ retryOnFailure: { value: 0 },+ continueOnFailure: { value: false },+ },+ },+ }) as WorkflowAction;++const content = [+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: 'Hello ' },+ { type: 'variableTag', attrs: { variable: '{{trigger.name}}' } },+ ],+ },+];++const versionedTipTap = JSON.stringify({+ type: 'doc',+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },+ content,+});++describe('ensureWorkflowStepsTipTapSchemaVersion', () => {+ it('should stamp the schema version on record step TipTap sent without one', () => {+ const [step] =+ ensureWorkflowStepsTipTapSchemaVersion([+ recordStep({+ title: 'Meeting',+ bodyV2: {+ blocknote: null,+ markdown: null,+ tiptap: JSON.stringify({ type: 'doc', content }),+ },+ }),+ ]) ?? [];+ const objectRecord = (+ step as Extract<+ WorkflowAction,+ { type: WorkflowActionType.CREATE_RECORD }+ >+ ).settings.input.objectRecord;++ expect(objectRecord.title).toBe('Meeting');+ expect(JSON.parse(objectRecord.bodyV2.tiptap)).toEqual(+ JSON.parse(versionedTipTap),+ );+ });++ it('should keep steps whose TipTap is already versioned or absent', () => {+ const steps = [+ recordStep({+ bodyV2: { blocknote: null, markdown: null, tiptap: versionedTipTap },+ }),+ recordStep({ bodyV2: { markdown: '{{trigger.body}}' } }),+ recordStep(+ { bodyV2: { tiptap: JSON.stringify({ type: 'doc', content }) } },+ WorkflowActionType.CODE,+ ),+ ];++ expect(ensureWorkflowStepsTipTapSchemaVersion(steps)).toEqual(steps);+ });++ it('should return null steps as is', () => {+ expect(ensureWorkflowStepsTipTapSchemaVersion(null)).toBeNull();+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/ensure-workflow-steps-tiptap-schema-version.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/ensure-workflow-steps-tiptap-schema-version.util.tsnew file mode 100644index 00000000000..3b32fbf79c1--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/ensure-workflow-steps-tiptap-schema-version.util.ts@@ -0,0 +1,52 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isPlainObject } from 'twenty-shared/utils';+import { WorkflowActionType } from 'twenty-shared/workflow';++import { ensureTipTapSchemaVersion } from 'src/engine/core-modules/record-transformer/utils/ensure-tiptap-schema-version.util';+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';++const ensureFieldValueTipTapSchemaVersion = (value: unknown): unknown =>+ isPlainObject(value) && isNonEmptyString(value.tiptap)+ ? { ...value, tiptap: ensureTipTapSchemaVersion(value.tiptap) }+ : value;++const ensureStepTipTapSchemaVersion = (+ step: WorkflowAction,+): WorkflowAction => {+ switch (step.type) {+ case WorkflowActionType.CREATE_RECORD:+ case WorkflowActionType.UPDATE_RECORD:+ case WorkflowActionType.UPSERT_RECORD: {+ const objectRecord: unknown = step.settings?.input?.objectRecord;++ if (!isPlainObject(objectRecord)) {+ return step;+ }++ const versionedObjectRecord = Object.fromEntries(+ Object.entries(objectRecord).map(([fieldName, value]) => [+ fieldName,+ ensureFieldValueTipTapSchemaVersion(value),+ ]),+ );++ return {+ ...step,+ settings: {+ ...step.settings,+ input: {+ ...step.settings.input,+ objectRecord: versionedObjectRecord,+ },+ },+ } as WorkflowAction;+ }+ default:+ return step;+ }+};++export const ensureWorkflowStepsTipTapSchemaVersion = (+ steps: WorkflowAction[] | null,+): WorkflowAction[] | null =>+ Array.isArray(steps) ? steps.map(ensureStepTipTapSchemaVersion) : steps;diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/nullify-empty-rich-text-default-value.spec.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/nullify-empty-rich-text-default-value.spec.tsindex 3c3bcbe9ad8..4bf98ea37be 100644--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/nullify-empty-rich-text-default-value.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/nullify-empty-rich-text-default-value.spec.ts@@ -1,15 +1,31 @@import { nullifyEmptyRichTextDefaultValue } from '../nullify-empty-rich-text-default-value.util';describe('nullifyEmptyRichTextDefaultValue', () => {- it('returns null when both sub-fields are empty-string equivalents', () => {+ it('returns null when every sub-field is an empty-string equivalent', () => {expect(- nullifyEmptyRichTextDefaultValue({ blocknote: "''", markdown: '' }),+ nullifyEmptyRichTextDefaultValue({+ blocknote: "''",+ markdown: '',+ tiptap: "''",+ }),).toBeNull();});it('returns normalized object when blocknote has a value', () => {expect(nullifyEmptyRichTextDefaultValue({ blocknote: '[]', markdown: "''" }),- ).toEqual({ blocknote: '[]', markdown: null });+ ).toEqual({ blocknote: '[]', markdown: null, tiptap: null });+ });++ it('keeps a tiptap-only default value', () => {+ const tiptap = '{"type":"doc","content":[{"type":"paragraph"}]}';++ expect(+ nullifyEmptyRichTextDefaultValue({+ blocknote: null,+ markdown: "''",+ tiptap,+ }),+ ).toEqual({ blocknote: null, markdown: null, tiptap });});});diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/nullify-empty-rich-text-default-value.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/nullify-empty-rich-text-default-value.util.tsindex a6a67b5355e..c9db291efa9 100644--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/nullify-empty-rich-text-default-value.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/nullify-empty-rich-text-default-value.util.ts@@ -3,6 +3,13 @@ import { isDefined } from 'twenty-shared/utils';import { isNullEquivalentTextDefaultValue } from './is-null-equivalent-text-default-value.util';+const nullifyEmptyTextDefaultValue = (+ textDefaultValue: string | null | undefined,+): string | null =>+ isNullEquivalentTextDefaultValue(textDefaultValue)+ ? null+ : (textDefaultValue ?? null);+export const nullifyEmptyRichTextDefaultValue = (defaultValue: FieldMetadataDefaultValueForAnyType,): FieldMetadataDefaultValueForAnyType => {@@ -10,21 +17,21 @@ export const nullifyEmptyRichTextDefaultValue = (return null;}- const v = defaultValue as {+ const richTextDefaultValue = defaultValue as {blocknote?: string | null;markdown?: string | null;+ tiptap?: string | null;};- const blocknote = isNullEquivalentTextDefaultValue(v.blocknote)- ? null- : (v.blocknote ?? null);- const markdown = isNullEquivalentTextDefaultValue(v.markdown)- ? null- : (v.markdown ?? null);+ const blocknote = nullifyEmptyTextDefaultValue(+ richTextDefaultValue.blocknote,+ );+ const markdown = nullifyEmptyTextDefaultValue(richTextDefaultValue.markdown);+ const tiptap = nullifyEmptyTextDefaultValue(richTextDefaultValue.tiptap);- if (blocknote === null && markdown === null) {+ if (blocknote === null && markdown === null && tiptap === null) {return null;}- return { blocknote, markdown };+ return { blocknote, markdown, tiptap };};diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/dtos/rich-text-body.dto.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/dtos/rich-text-body.dto.tsindex 090cb629e0a..42ab02284eb 100644--- a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/dtos/rich-text-body.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/dtos/rich-text-body.dto.ts@@ -13,5 +13,10 @@ export class RichTextBodyDTO implements RichTextMetadata {@Field(() => String, { nullable: true })@IsString()@IsOptional()- markdown: string | null;+ markdown?: string | null;++ @Field(() => String, { nullable: true })+ @IsString()+ @IsOptional()+ tiptap?: string | null;}diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/services/page-layout-widget.service.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/services/page-layout-widget.service.tsindex d2962d2af41..11cb717519d 100644--- a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/services/page-layout-widget.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/services/page-layout-widget.service.ts@@ -1,6 +1,6 @@import { Injectable } from '@nestjs/common';-import { isDefined } from 'twenty-shared/utils';+import { isDefined, isPlainObject } from 'twenty-shared/utils';import { ApplicationService } from 'src/engine/core-modules/application/application.service';import { transformRichTextValue } from 'src/engine/core-modules/record-transformer/utils/transform-rich-text.util';@@ -30,6 +30,7 @@ import { type AllPageLayoutWidgetConfiguration } from 'src/engine/metadata-modulimport { fromFlatPageLayoutWidgetToPageLayoutWidgetDto } from 'src/engine/metadata-modules/page-layout-widget/utils/from-flat-page-layout-widget-to-page-layout-widget-dto.util';import { validateChartConfigurationFieldReferencesOrThrow } from 'src/engine/metadata-modules/page-layout-widget/utils/validate-chart-configuration-field-references.util';import { validateFieldConfigurationNestedRelationOrThrow } from 'src/engine/metadata-modules/page-layout-widget/utils/validate-field-configuration-nested-relation.util';+import { validateRichTextWidgetBodyOrThrow } from 'src/engine/metadata-modules/page-layout-widget/utils/validate-rich-text-widget-body-or-throw.util';import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';import { DashboardSyncService } from 'src/modules/dashboard-sync/services/dashboard-sync.service';@@ -98,9 +99,9 @@ export class PageLayoutWidgetService {}}- private async enrichRichTextConfigurationBody(+ private enrichRichTextConfigurationBody(configuration: AllPageLayoutWidgetConfiguration,- ): Promise<AllPageLayoutWidgetConfiguration> {+ ): AllPageLayoutWidgetConfiguration {if (configuration.configurationType !==WidgetConfigurationType.STANDALONE_RICH_TEXT@@ -108,18 +109,16 @@ export class PageLayoutWidgetService {return configuration;}- if (!isDefined(configuration.body)) {+ if (!isPlainObject(configuration.body)) {return configuration;}- try {- return {- ...configuration,- body: await transformRichTextValue(configuration.body),- };- } catch {- return configuration;- }+ validateRichTextWidgetBodyOrThrow(configuration.body);++ return {+ ...configuration,+ body: transformRichTextValue(configuration.body),+ };}private async validateConfigurationFieldReferences({@@ -225,7 +224,7 @@ export class PageLayoutWidgetService {const createInput = isDefined(input.configuration)? {...input,- configuration: await this.enrichRichTextConfigurationBody(+ configuration: this.enrichRichTextConfigurationBody(input.configuration,),}@@ -362,7 +361,7 @@ export class PageLayoutWidgetService {isConfigurationBeingUpdated && isDefined(updateData.configuration)? {...updateData,- configuration: await this.enrichRichTextConfigurationBody(+ configuration: this.enrichRichTextConfigurationBody(updateData.configuration,),}diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/__tests__/validate-rich-text-widget-body-or-throw.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/__tests__/validate-rich-text-widget-body-or-throw.util.spec.tsnew file mode 100644index 00000000000..1480b768494--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/__tests__/validate-rich-text-widget-body-or-throw.util.spec.ts@@ -0,0 +1,53 @@+import { PageLayoutWidgetException } from 'src/engine/metadata-modules/page-layout-widget/exceptions/page-layout-widget.exception';+import { validateRichTextWidgetBodyOrThrow } from 'src/engine/metadata-modules/page-layout-widget/utils/validate-rich-text-widget-body-or-throw.util';++describe('validateRichTextWidgetBodyOrThrow', () => {+ it('should accept a body holding a rich text document', () => {+ expect(() =>+ validateRichTextWidgetBodyOrThrow({+ markdown: 'Hello',+ tiptap: JSON.stringify({+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'Hello' }] },+ ],+ }),+ }),+ ).not.toThrow();+ });++ it('should reject a body holding nodes a rich text widget cannot store', () => {+ expect(() =>+ validateRichTextWidgetBodyOrThrow({+ tiptap: JSON.stringify({+ type: 'doc',+ content: [{ type: 'button', attrs: { href: 'https://twenty.com' } }],+ }),+ }),+ ).toThrow(PageLayoutWidgetException);+ });++ it('should reject a body linking to a dangerous protocol', () => {+ expect(() =>+ validateRichTextWidgetBodyOrThrow({+ tiptap: JSON.stringify({+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ {+ type: 'text',+ text: 'Click',+ marks: [+ { type: 'link', attrs: { href: 'javascript:alert(1)' } },+ ],+ },+ ],+ },+ ],+ }),+ }),+ ).toThrow(/Dangerous URL protocol/);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/validate-rich-text-widget-body-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/validate-rich-text-widget-body-or-throw.util.tsnew file mode 100644index 00000000000..ef7f8ea8faa--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/validate-rich-text-widget-body-or-throw.util.ts@@ -0,0 +1,22 @@+import { validateRichTextFieldOrThrow } from 'src/engine/api/common/common-args-processors/data-arg-processor/validator-utils/validate-rich-text-field-or-throw.util';+import { CommonQueryRunnerException } from 'src/engine/api/common/common-query-runners/errors/common-query-runner.exception';+import {+ PageLayoutWidgetException,+ PageLayoutWidgetExceptionCode,+} from 'src/engine/metadata-modules/page-layout-widget/exceptions/page-layout-widget.exception';++export const validateRichTextWidgetBodyOrThrow = (body: unknown): void => {+ try {+ validateRichTextFieldOrThrow(body, 'body');+ } catch (error) {+ if (!(error instanceof CommonQueryRunnerException)) {+ throw error;+ }++ throw new PageLayoutWidgetException(+ error.message,+ PageLayoutWidgetExceptionCode.INVALID_PAGE_LAYOUT_WIDGET_DATA,+ { userFriendlyMessage: error.userFriendlyMessage },+ );+ }+};diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/get-subfields-for-aggregate-operation.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/get-subfields-for-aggregate-operation.util.tsindex b631584caa7..32a13e8671d 100644--- a/packages/twenty-server/src/engine/twenty-orm/utils/get-subfields-for-aggregate-operation.util.ts+++ b/packages/twenty-server/src/engine/twenty-orm/utils/get-subfields-for-aggregate-operation.util.ts@@ -37,7 +37,7 @@ export const getSubfieldsForAggregateOperation = ('primaryPhoneCallingCode',];case FieldMetadataType.RICH_TEXT:- return ['blocknote', 'markdown'];+ return ['blocknote', 'markdown', 'tiptap'];default:throw new Error(`Unsupported composite field type: ${fieldType}`);}diff --git a/packages/twenty-server/src/engine/utils/convert-object-metadata-to-schema-properties.util.ts b/packages/twenty-server/src/engine/utils/convert-object-metadata-to-schema-properties.util.tsindex 4d0d176457b..060d6f81432 100644--- a/packages/twenty-server/src/engine/utils/convert-object-metadata-to-schema-properties.util.ts+++ b/packages/twenty-server/src/engine/utils/convert-object-metadata-to-schema-properties.util.ts@@ -356,6 +356,9 @@ export const convertObjectMetadataToSchemaProperties = ({markdown: {type: 'string',},+ tiptap: {+ type: 'string',+ },},};break;diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/note-data-seeds.constant.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/note-data-seeds.constant.tsindex 91945b28421..4a2640c51b0 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/note-data-seeds.constant.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/note-data-seeds.constant.ts@@ -1,10 +1,15 @@+import {+ TIPTAP_DOCUMENT_SCHEMA_VERSION,+ TIPTAP_NODE_TYPES,+} from 'twenty-shared/utils';+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';type NoteDataSeed = {id: string;position: number;title: string;- bodyV2Blocknote: string;+ bodyV2Tiptap: string;bodyV2Markdown: string;createdBySource: string;createdByWorkspaceMemberId: string;@@ -19,7 +24,7 @@ export const NOTE_DATA_SEED_COLUMNS: (keyof NoteDataSeed)[] = ['id','position','title',- 'bodyV2Blocknote',+ 'bodyV2Tiptap','bodyV2Markdown','createdBySource','createdByWorkspaceMemberId',@@ -136,6 +141,18 @@ const COMPANY_NOTE_TEMPLATES = [},];+const BUILD_BODY_TIPTAP = (text: string): string =>+ JSON.stringify({+ type: TIPTAP_NODE_TYPES.DOCUMENT,+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },+ content: [+ {+ type: TIPTAP_NODE_TYPES.PARAGRAPH,+ content: [{ type: TIPTAP_NODE_TYPES.TEXT, text }],+ },+ ],+ });+const GENERATE_NOTE_SEEDS = (): NoteDataSeed[] => {const NOTE_SEEDS: NoteDataSeed[] = [];@@ -148,19 +165,7 @@ const GENERATE_NOTE_SEEDS = (): NoteDataSeed[] => {id: NOTE_DATA_SEED_IDS[`ID_${INDEX}`],position: INDEX,title: TEMPLATE.title,- bodyV2Blocknote: JSON.stringify([- {- id: `block-${INDEX}`,- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',- },- content: [{ type: 'text', text: TEMPLATE.content, styles: {} }],- children: [],- },- ]),+ bodyV2Tiptap: BUILD_BODY_TIPTAP(TEMPLATE.content),bodyV2Markdown: TEMPLATE.content,createdBySource: 'MANUAL',createdByWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,@@ -181,19 +186,7 @@ const GENERATE_NOTE_SEEDS = (): NoteDataSeed[] => {id: NOTE_DATA_SEED_IDS[`ID_${INDEX}`],position: INDEX,title: TEMPLATE.title,- bodyV2Blocknote: JSON.stringify([- {- id: `block-${INDEX}`,- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',- },- content: [{ type: 'text', text: TEMPLATE.content, styles: {} }],- children: [],- },- ]),+ bodyV2Tiptap: BUILD_BODY_TIPTAP(TEMPLATE.content),bodyV2Markdown: TEMPLATE.content,createdBySource: 'MANUAL',createdByWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/task-data-seeds.constant.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/task-data-seeds.constant.tsindex 31f74a706dc..8ad1a396ac3 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/task-data-seeds.constant.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/task-data-seeds.constant.ts@@ -1,10 +1,15 @@+import {+ TIPTAP_DOCUMENT_SCHEMA_VERSION,+ TIPTAP_NODE_TYPES,+} from 'twenty-shared/utils';+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';type TaskDataSeed = {id: string;position: number;title: string;- bodyV2Blocknote: string;+ bodyV2Tiptap: string;bodyV2Markdown: string;status: string;dueAt: string | null;@@ -21,7 +26,7 @@ export const TASK_DATA_SEED_COLUMNS: (keyof TaskDataSeed)[] = ['id','position','title',- 'bodyV2Blocknote',+ 'bodyV2Tiptap','bodyV2Markdown','status','dueAt',@@ -178,6 +183,18 @@ const FORMAT_DUE_DATE = (daysFromNow: number | null): string | null => {return DATE.toISOString();};+const BUILD_BODY_TIPTAP = (text: string): string =>+ JSON.stringify({+ type: TIPTAP_NODE_TYPES.DOCUMENT,+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },+ content: [+ {+ type: TIPTAP_NODE_TYPES.PARAGRAPH,+ content: [{ type: TIPTAP_NODE_TYPES.TEXT, text }],+ },+ ],+ });+const GENERATE_TASK_SEEDS = (): TaskDataSeed[] => {const TASK_SEEDS: TaskDataSeed[] = [];@@ -190,19 +207,7 @@ const GENERATE_TASK_SEEDS = (): TaskDataSeed[] => {id: TASK_DATA_SEED_IDS[`ID_${INDEX}`],position: INDEX,title: TEMPLATE.title,- bodyV2Blocknote: JSON.stringify([- {- id: `block-${INDEX}`,- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',- },- content: [{ type: 'text', text: TEMPLATE.body, styles: {} }],- children: [],- },- ]),+ bodyV2Tiptap: BUILD_BODY_TIPTAP(TEMPLATE.body),bodyV2Markdown: TEMPLATE.body,status: TEMPLATE.status,dueAt: FORMAT_DUE_DATE(TEMPLATE.daysFromNow),@@ -225,19 +230,7 @@ const GENERATE_TASK_SEEDS = (): TaskDataSeed[] => {id: TASK_DATA_SEED_IDS[`ID_${INDEX}`],position: INDEX,title: TEMPLATE.title,- bodyV2Blocknote: JSON.stringify([- {- id: `block-${INDEX}`,- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',- },- content: [{ type: 'text', text: TEMPLATE.body, styles: {} }],- children: [],- },- ]),+ bodyV2Tiptap: BUILD_BODY_TIPTAP(TEMPLATE.body),bodyV2Markdown: TEMPLATE.body,status: TEMPLATE.status,dueAt: FORMAT_DUE_DATE(TEMPLATE.daysFromNow),diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-widget/compute-my-first-dashboard-widgets.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-widget/compute-my-first-dashboard-widgets.util.tsindex 158a9a14645..1803b880d12 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-widget/compute-my-first-dashboard-widgets.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-widget/compute-my-first-dashboard-widgets.util.ts@@ -5,6 +5,11 @@ import {PageLayoutTabLayoutMode,WidgetType,} from 'twenty-shared/types';+import {+ TIPTAP_DOCUMENT_SCHEMA_VERSION,+ TIPTAP_MARK_TYPES,+ TIPTAP_NODE_TYPES,+} from 'twenty-shared/utils';import { v4 } from 'uuid';import { type FlatPageLayoutWidget } from 'src/engine/metadata-modules/flat-page-layout-widget/types/flat-page-layout-widget.type';@@ -75,143 +80,78 @@ const createWelcomeRichText = ({const configuration = {configurationType: WidgetConfigurationType.STANDALONE_RICH_TEXT as const,body: {- blocknote: JSON.stringify([- {- id: v4(),- type: 'heading',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',- level: 3,- },- content: [- {- type: 'text',- text: 'Welcome to your workspace',- styles: {},- },- ],- children: [],- },- {- id: v4(),- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',- },- content: [],- children: [],- },- {- id: v4(),- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',- },- content: [- {- type: 'text',- text: 'You can edit this dashboard by clicking the ',- styles: {},- },- { type: 'text', text: 'Edit', styles: { code: true } },- {- type: 'text',- text: ' button in the top-right corner to add your own charts or customize this one.',- styles: {},- },- ],- children: [],- },- {- id: v4(),- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',- },- content: [],- children: [],- },- {- id: v4(),- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',+ tiptap: JSON.stringify({+ type: TIPTAP_NODE_TYPES.DOCUMENT,+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },+ content: [+ {+ type: TIPTAP_NODE_TYPES.HEADING,+ attrs: { level: 3 },+ content: [+ {+ type: TIPTAP_NODE_TYPES.TEXT,+ text: 'Welcome to your workspace',+ },+ ],},- content: [- {- type: 'text',- text: "Don't forget to replace the sample data with your own.",- styles: {},- },- ],- children: [],- },- {- id: v4(),- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',+ { type: TIPTAP_NODE_TYPES.PARAGRAPH },+ {+ type: TIPTAP_NODE_TYPES.PARAGRAPH,+ content: [+ {+ type: TIPTAP_NODE_TYPES.TEXT,+ text: 'You can edit this dashboard by clicking the ',+ },+ {+ type: TIPTAP_NODE_TYPES.TEXT,+ text: 'Edit',+ marks: [{ type: TIPTAP_MARK_TYPES.CODE }],+ },+ {+ type: TIPTAP_NODE_TYPES.TEXT,+ text: ' button in the top-right corner to add your own charts or customize this one.',+ },+ ],},- content: [],- children: [],- },- {- id: v4(),- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',+ { type: TIPTAP_NODE_TYPES.PARAGRAPH },+ {+ type: TIPTAP_NODE_TYPES.PARAGRAPH,+ content: [+ {+ type: TIPTAP_NODE_TYPES.TEXT,+ text: "Don't forget to replace the sample data with your own.",+ },+ ],},- content: [- {- type: 'text',- text: 'If you have any issues, you can check ',- styles: {},- },- {- type: 'link',- href: 'https://docs.twenty.com/getting-started/introduction',- content: [- {- type: 'text',- text: 'our documentation',- styles: {},- },- ],- },- {- type: 'text',- text: ' or contact us through the Support section in Settings.',- styles: {},- },- ],- children: [],- },- {- id: v4(),- type: 'paragraph',- props: {- textColor: 'default',- backgroundColor: 'default',- textAlignment: 'left',+ { type: TIPTAP_NODE_TYPES.PARAGRAPH },+ {+ type: TIPTAP_NODE_TYPES.PARAGRAPH,+ content: [+ {+ type: TIPTAP_NODE_TYPES.TEXT,+ text: 'If you have any issues, you can check ',+ },+ {+ type: TIPTAP_NODE_TYPES.TEXT,+ text: 'our documentation',+ marks: [+ {+ type: TIPTAP_MARK_TYPES.LINK,+ attrs: {+ href: 'https://docs.twenty.com/getting-started/introduction',+ },+ },+ ],+ },+ {+ type: TIPTAP_NODE_TYPES.TEXT,+ text: ' or contact us through the Support section in Settings.',+ },+ ],},- content: [],- children: [],- },- ]),+ { type: TIPTAP_NODE_TYPES.PARAGRAPH },+ ],+ }),markdown: null,},};diff --git a/packages/twenty-server/src/modules/dashboard/tools/schemas/widget.schema.ts b/packages/twenty-server/src/modules/dashboard/tools/schemas/widget.schema.tsindex 2156095b8a7..857c7d5d51f 100644--- a/packages/twenty-server/src/modules/dashboard/tools/schemas/widget.schema.ts+++ b/packages/twenty-server/src/modules/dashboard/tools/schemas/widget.schema.ts@@ -590,13 +590,6 @@ const richTextConfigSchema = z.object({configurationType: z.literal(WidgetConfigurationType.STANDALONE_RICH_TEXT),body: z.object({- blocknote: z- .string()- .nullable()- .optional()- .describe(- 'BlockNote JSON string (advanced). Stringified array of BlockNote blocks.',- ),markdown: z.string().nullable()diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/get-record-crud-rich-text-issues.util.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/get-record-crud-rich-text-issues.util.tsindex 096abd2ffbf..2ce7c297ea3 100644--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/get-record-crud-rich-text-issues.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/get-record-crud-rich-text-issues.util.ts@@ -28,7 +28,7 @@ export const getRecordCrudRichTextIssues = ({if (isDefined(fieldValue) &&- !richTextValueSchema.safeParse(fieldValue).success+ !richTextValueSchema.strict().safeParse(fieldValue).success) {issues.push({severity: 'error',diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/convert-step-object-record-tiptap-to-markdown.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/convert-step-object-record-tiptap-to-markdown.util.spec.tsindex 74a7cef6034..23d4530933f 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/convert-step-object-record-tiptap-to-markdown.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/convert-step-object-record-tiptap-to-markdown.util.spec.ts@@ -48,8 +48,32 @@ const objectMetadataInfo = {const paragraph = (content: unknown[]) =>JSON.stringify([{ type: 'paragraph', content }]);+const tipTapDocument = (content: unknown[]) =>+ JSON.stringify({+ type: 'doc',+ attrs: { schemaVersion: 1 },+ content: [{ type: 'paragraph', content }],+ });+describe('convertStepObjectRecordTipTapToMarkdown', () => {it('converts a TipTap body into markdown, keeping its variables', () => {+ const tipTapBody = tipTapDocument([+ { type: 'text', text: 'Amount', marks: [{ type: 'bold' }] },+ { type: 'text', text: ': ' },+ { type: 'variableTag', attrs: { variable: '{{trigger.body.amount}}' } },+ ]);++ const converted = convertStepObjectRecordTipTapToMarkdown(+ { body: { tiptap: tipTapBody, markdown: null } },+ objectMetadataInfo,+ );++ expect(converted.body).toEqual({+ markdown: '**Amount**: {{trigger.body.amount}}',+ });+ });++ it('still converts TipTap blocks a step saved under the blocknote key before its upgrade', () => {const tipTapBody = paragraph([{ type: 'text', text: 'Amount', marks: [{ type: 'bold' }] },{ type: 'text', text: ': ' },@@ -67,7 +91,7 @@ describe('convertStepObjectRecordTipTapToMarkdown', () => {});it('keeps a variable used as a link destination', () => {- const tipTapBody = paragraph([+ const tipTapBody = tipTapDocument([{type: 'text',text: 'Website',@@ -76,7 +100,7 @@ describe('convertStepObjectRecordTipTapToMarkdown', () => {]);const converted = convertStepObjectRecordTipTapToMarkdown(- { body: { blocknote: tipTapBody, markdown: null } },+ { body: { tiptap: tipTapBody, markdown: null } },objectMetadataInfo,);@@ -88,6 +112,10 @@ describe('convertStepObjectRecordTipTapToMarkdown', () => {name: 'a markdown only value',value: { blocknote: null, markdown: '{{trigger.body.amount}}' },},+ {+ name: 'a tiptap variable',+ value: { tiptap: '{{codeStep.report.tiptap}}', markdown: null },+ },{name: 'a blocknote variable',value: {diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/convert-step-object-record-tiptap-to-markdown.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/convert-step-object-record-tiptap-to-markdown.util.tsindex 834c71c04b5..e5291ba9deb 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/convert-step-object-record-tiptap-to-markdown.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/convert-step-object-record-tiptap-to-markdown.util.ts@@ -1,11 +1,34 @@-import { richTextValueSchema } from 'twenty-shared/types';-import { convertTipTapBlocksToMarkdown, isDefined } from 'twenty-shared/utils';+import { isNonEmptyString } from '@sniptt/guards';+import {+ type RichTextMetadata,+ richTextValueSchema,+} from 'twenty-shared/types';+import {+ convertTipTapBlocksToMarkdown,+ isDefined,+ parseTipTapJsonDocument,+ tipTapDocumentToMarkdown,+} from 'twenty-shared/utils';import { type ObjectMetadataInfo } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';import { findRichTextFieldNames } from 'src/modules/workflow/workflow-executor/utils/find-rich-text-field-names.util';-// The step editor is TipTap but saves its JSON under a key named blocknote-const workflowStepTipTapValueSchema = richTextValueSchema;+const convertStepRichTextValueToMarkdown = ({+ tiptap,+ blocknote,+}: RichTextMetadata): string | undefined => {+ const tipTapDocument = isNonEmptyString(tiptap)+ ? parseTipTapJsonDocument(tiptap)+ : undefined;++ if (isDefined(tipTapDocument)) {+ return tipTapDocumentToMarkdown(tipTapDocument);+ }++ return isDefined(blocknote)+ ? convertTipTapBlocksToMarkdown(blocknote)+ : undefined;+};export const convertStepObjectRecordTipTapToMarkdown = (stepObjectRecord: Record<string, unknown>,@@ -17,15 +40,12 @@ export const convertStepObjectRecordTipTapToMarkdown = (const objectRecord = { ...stepObjectRecord };for (const fieldName of findRichTextFieldNames(objectMetadataInfo)) {- const parsedStepValue = workflowStepTipTapValueSchema.safeParse(+ const parsedStepValue = richTextValueSchema.safeParse(stepObjectRecord[fieldName],);- const tipTapJson = parsedStepValue.success- ? parsedStepValue.data.blocknote- : undefined;- const tipTapMarkdown = isDefined(tipTapJson)- ? convertTipTapBlocksToMarkdown(tipTapJson)+ const tipTapMarkdown = parsedStepValue.success+ ? convertStepRichTextValueToMarkdown(parsedStepValue.data): undefined;// TODO: steps built through the API can hold markdown only, BlockNote or a variable instead of TipTap.diff --git a/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-database-tool-input-schemas.integration-spec.ts.snap b/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-database-tool-input-schemas.integration-spec.ts.snapindex 0699a7ba667..0f66071165f 100644--- a/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-database-tool-input-schemas.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-database-tool-input-schemas.integration-spec.ts.snap@@ -10,9 +10,6 @@ exports[`MCP database tool input schemas should list the input schemas of the no"bodyV2": {"description": "Note body","properties": {- "blocknote": {- "type": "string",- },"markdown": {"type": "string",},@@ -60,9 +57,6 @@ exports[`MCP database tool input schemas should list the input schemas of the no"bodyV2": {"description": "Note body","properties": {- "blocknote": {- "type": "string",- },"markdown": {"type": "string",},@@ -226,6 +220,15 @@ exports[`MCP database tool input schemas should list the input schemas of the no],"type": "string",},+ "tiptap": {+ "enum": [+ "AscNullsFirst",+ "AscNullsLast",+ "DescNullsFirst",+ "DescNullsLast",+ ],+ "type": "string",+ },},"type": "object",},@@ -483,7 +486,7 @@ exports[`MCP database tool input schemas should list the input schemas of the no"type": "object",},"groupBy": {- "description": "Fields to group by (max 2). Each entry must be an object with exactly one field key. At most one entry can use unnest. A record with several values is counted in each group, so totals can exceed the record count. Examples: {"status": true}, {"companyId": true}, {"createdAt": {"granularity": "MONTH", "timeZone": "UTC"}}. Available: bodyV2.blocknote, bodyV2.markdown, createdAt (date), createdBy.source, createdBy.workspaceMemberId, createdBy.name, title, updatedAt (date), updatedBy.source, updatedBy.workspaceMemberId, updatedBy.name.",+ "description": "Fields to group by (max 2). Each entry must be an object with exactly one field key. At most one entry can use unnest. A record with several values is counted in each group, so totals can exceed the record count. Examples: {"status": true}, {"companyId": true}, {"createdAt": {"granularity": "MONTH", "timeZone": "UTC"}}. Available: bodyV2.blocknote, bodyV2.markdown, bodyV2.tiptap, createdAt (date), createdBy.source, createdBy.workspaceMemberId, createdBy.name, title, updatedAt (date), updatedBy.source, updatedBy.workspaceMemberId, updatedBy.name.","items": {"anyOf": [{@@ -530,6 +533,28 @@ exports[`MCP database tool input schemas should list the input schemas of the no],"type": "object",},+ {+ "additionalProperties": false,+ "properties": {+ "bodyV2": {+ "additionalProperties": false,+ "properties": {+ "tiptap": {+ "const": true,+ "type": "boolean",+ },+ },+ "required": [+ "tiptap",+ ],+ "type": "object",+ },+ },+ "required": [+ "bodyV2",+ ],+ "type": "object",+ },{"additionalProperties": false,"properties": {@@ -1082,9 +1107,6 @@ exports[`MCP database tool input schemas should list the input schemas of the no"bodyV2": {"description": "Note body","properties": {- "blocknote": {- "type": "string",- },"markdown": {"type": "string",},@@ -1133,9 +1155,6 @@ exports[`MCP database tool input schemas should list the input schemas of the no"bodyV2": {"description": "Note body","properties": {- "blocknote": {- "type": "string",- },"markdown": {"type": "string",},@@ -1184,9 +1203,6 @@ exports[`MCP database tool input schemas should list the input schemas of the no"bodyV2": {"description": "Note body","properties": {- "blocknote": {- "type": "string",- },"markdown": {"type": "string",},diff --git a/packages/twenty-server/test/integration/graphql/suites/inputs-validation/constants/test-object-gql-fields.constant.ts b/packages/twenty-server/test/integration/graphql/suites/inputs-validation/constants/test-object-gql-fields.constant.tsindex 2ae78ad502c..f0edc2a7cc6 100644--- a/packages/twenty-server/test/integration/graphql/suites/inputs-validation/constants/test-object-gql-fields.constant.ts+++ b/packages/twenty-server/test/integration/graphql/suites/inputs-validation/constants/test-object-gql-fields.constant.ts@@ -63,5 +63,6 @@ export const TEST_OBJECT_GQL_FIELDS = `richTextField {blocknotemarkdown+ tiptap}`;diff --git a/packages/twenty-server/test/integration/graphql/suites/inputs-validation/create-validation/constants/successful-create-input-by-field-metadata-type.constant.ts b/packages/twenty-server/test/integration/graphql/suites/inputs-validation/create-validation/constants/successful-create-input-by-field-metadata-type.constant.tsindex 9f0a70bc069..1b3171e9b2c 100644--- a/packages/twenty-server/test/integration/graphql/suites/inputs-validation/create-validation/constants/successful-create-input-by-field-metadata-type.constant.ts+++ b/packages/twenty-server/test/integration/graphql/suites/inputs-validation/create-validation/constants/successful-create-input-by-field-metadata-type.constant.ts@@ -413,7 +413,26 @@ export const successfulCreateInputByFieldMetadataType: {return (record.richTextField.blocknote ==='[{"type":"paragraph","content":[{"type":"text","text":"test"}]}]' &&- record.richTextField.markdown === 'test'+ record.richTextField.markdown === 'test' &&+ JSON.parse(record.richTextField.tiptap).content[0].content[0].text ===+ 'test'+ );+ },+ },+ {+ input: {+ richTextField: {+ blocknote: null,+ markdown: null,+ tiptap:+ '{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"test","marks":[{"type":"bold"}]}]}]}',+ },+ },+ validateInput: (record: Record<string, any>) => {+ return (+ record.richTextField.blocknote === null &&+ record.richTextField.markdown === '**test**' &&+ JSON.parse(record.richTextField.tiptap).attrs.schemaVersion === 1);},},diff --git a/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/__snapshots__/successful-page-layout-widget-creation.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/__snapshots__/successful-page-layout-widget-creation.integration-spec.ts.snapindex 9f08be85199..2264e38c49b 100644--- a/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/__snapshots__/successful-page-layout-widget-creation.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/__snapshots__/successful-page-layout-widget-creation.integration-spec.ts.snap@@ -397,7 +397,8 @@ exports[`Page layout widget creation should succeed should create a page layout"configuration": {"body": {"blocknote": "[{"id":"5f4a1c1e-0000-4000-8000-000000000001","type":"paragraph","props":{},"content":[{"type":"text","text":"Hello world","styles":{}}],"children":[]}]",- "markdown": "# Hello world",+ "markdown": "Hello world",+ "tiptap": "{"type":"doc","attrs":{"schemaVersion":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Hello world"}]}]}",},"configurationType": "STANDALONE_RICH_TEXT",},@@ -424,8 +425,8 @@ exports[`Page layout widget creation should succeed should create a page layout"configuration": {"body": {"blocknote": "[{"id":"5f4a1c1e-0000-4000-8000-000000000002","type":"paragraph","props":{},"content":[{"type":"text","text":"Simple text","styles":{}}],"children":[]}]",- "markdown": "Simple text-",+ "markdown": "Simple text",+ "tiptap": "{"type":"doc","attrs":{"schemaVersion":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Simple text"}]}]}",},"configurationType": "STANDALONE_RICH_TEXT",},diff --git a/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/__snapshots__/successful-page-layout-widget-update.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/__snapshots__/successful-page-layout-widget-update.integration-spec.ts.snapindex 1e1090e3bb5..d1b8d863440 100644--- a/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/__snapshots__/successful-page-layout-widget-update.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/__snapshots__/successful-page-layout-widget-update.integration-spec.ts.snap@@ -227,7 +227,8 @@ exports[`Page layout widget update should succeed from a STANDALONE_RICH_TEXT wi"configuration": {"body": {"blocknote": "[{"id":"5f4a1c1e-0000-4000-8000-000000000001","type":"paragraph","props":{},"content":[{"type":"text","text":"Hello world","styles":{}}],"children":[]}]",- "markdown": "# Hello world",+ "markdown": "Hello world",+ "tiptap": "{"type":"doc","attrs":{"schemaVersion":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Hello world"}]}]}",},"configurationType": "STANDALONE_RICH_TEXT",},diff --git a/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/constants/widget-configuration-gql-fields.constant.ts b/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/constants/widget-configuration-gql-fields.constant.tsindex 77f47115114..d9e30a03e84 100644--- a/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/constants/widget-configuration-gql-fields.constant.ts+++ b/packages/twenty-server/test/integration/metadata/suites/page-layout-widget/constants/widget-configuration-gql-fields.constant.ts@@ -100,6 +100,7 @@ export const WIDGET_CONFIGURATION_GQL_FIELDS = `body {blocknotemarkdown+ tiptap}}`;diff --git a/packages/twenty-shared/src/constants/CompositeFieldSubFieldLabels.ts b/packages/twenty-shared/src/constants/CompositeFieldSubFieldLabels.tsindex be40792d2ff..70343d6785a 100644--- a/packages/twenty-shared/src/constants/CompositeFieldSubFieldLabels.ts+++ b/packages/twenty-shared/src/constants/CompositeFieldSubFieldLabels.ts@@ -49,5 +49,6 @@ export const COMPOSITE_FIELD_SUB_FIELD_LABELS: {[FieldMetadataType.RICH_TEXT]: {blocknote: 'BlockNote',markdown: 'Markdown',+ tiptap: 'TipTap',},};diff --git a/packages/twenty-shared/src/constants/CompositeFieldTypeSubFieldsNames.ts b/packages/twenty-shared/src/constants/CompositeFieldTypeSubFieldsNames.tsindex 81e5d91dee2..cce9dc44fd3 100644--- a/packages/twenty-shared/src/constants/CompositeFieldTypeSubFieldsNames.ts+++ b/packages/twenty-shared/src/constants/CompositeFieldTypeSubFieldsNames.ts@@ -43,5 +43,6 @@ export const COMPOSITE_FIELD_TYPE_SUB_FIELDS_NAMES = {[FieldMetadataType.RICH_TEXT]: {blocknote: 'blocknote',markdown: 'markdown',+ tiptap: 'tiptap',},} as const;diff --git a/packages/twenty-shared/src/types/FieldMetadataDefaultValue.ts b/packages/twenty-shared/src/types/FieldMetadataDefaultValue.tsindex bfede7273ed..3cc527925b9 100644--- a/packages/twenty-shared/src/types/FieldMetadataDefaultValue.ts+++ b/packages/twenty-shared/src/types/FieldMetadataDefaultValue.ts@@ -16,8 +16,9 @@ export type FieldMetadataDefaultValueNowFunction =typeof fieldMetadataDefaultValueFunctionName.NOW;export type FieldMetadataDefaultValueRichText = {- blocknote: string | null;- markdown: string | null;+ tiptap?: string | null;+ markdown?: string | null;+ blocknote?: string | null;};export type FieldMetadataDefaultValueCurrency = {diff --git a/packages/twenty-shared/src/types/composite-types/rich-text.composite-type.ts b/packages/twenty-shared/src/types/composite-types/rich-text.composite-type.tsindex b69cd1bfb0b..e002f21ae98 100644--- a/packages/twenty-shared/src/types/composite-types/rich-text.composite-type.ts+++ b/packages/twenty-shared/src/types/composite-types/rich-text.composite-type.ts@@ -17,13 +17,19 @@ export const richTextCompositeType: CompositeType = {hidden: false,isRequired: false,},+ {+ name: 'tiptap',+ type: FieldMetadataType.TEXT,+ hidden: false,+ isRequired: false,+ },],};-// with import only markdown subfield is filled, then blocknote is undefinedexport const richTextValueSchema = z.object({+ tiptap: z.string().nullable().optional(),+ markdown: z.string().nullable().optional(),blocknote: z.string().nullable().optional(),- markdown: z.string().nullable(),});export type RichTextMetadata = z.infer<typeof richTextValueSchema>;diff --git a/packages/twenty-shared/src/types/page-layout/PageLayoutWidgetConfiguration.ts b/packages/twenty-shared/src/types/page-layout/PageLayoutWidgetConfiguration.tsindex a613f502c0a..3baccd806cd 100644--- a/packages/twenty-shared/src/types/page-layout/PageLayoutWidgetConfiguration.ts+++ b/packages/twenty-shared/src/types/page-layout/PageLayoutWidgetConfiguration.ts@@ -126,8 +126,9 @@ export type FieldRichTextConfiguration = {export type StandaloneRichTextConfiguration = {configurationType: 'STANDALONE_RICH_TEXT';body: {+ tiptap?: string | null;+ markdown?: string | null;blocknote?: string | null;- markdown: string | null;};};diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.tsindex cc649cc8818..ad89a2d4db7 100644--- a/packages/twenty-shared/src/utils/index.ts+++ b/packages/twenty-shared/src/utils/index.ts@@ -255,8 +255,11 @@ export { TEMPLATE_VARIABLE_PATTERN } from './template-variable/template-variableexport type { TemplateVariableWithFallback } from './template-variable/template-variable-with-fallback';export type { CanvasTheme } from './tiptap/canvas-theme';export { CANVAS_THEME_DEFAULTS } from './tiptap/canvas-theme';+export { convertBlockNoteToRichTextDocument } from './tiptap/convert-blocknote-to-rich-text-document';export { convertEmailBodyToEmailDocument } from './tiptap/convert-email-body-to-email-document';export { convertStringBodyToEmailDocument } from './tiptap/convert-string-body-to-email-document';+export { convertTextToTipTapNodes } from './tiptap/convert-text-to-tiptap-nodes';+export { convertTipTapBlocksToDocument } from './tiptap/convert-tiptap-blocks-to-document';export { convertTipTapBlocksToMarkdown } from './tiptap/convert-tiptap-blocks-to-markdown';export type { EmailDocumentMarkType } from './tiptap/email-document-mark-catalog';export {@@ -279,9 +282,11 @@ export { emailDocumentSchema } from './tiptap/email-document-schema';export type { EmailDocumentStringContext } from './tiptap/email-document-string-context';export { EMAIL_TYPOGRAPHY } from './tiptap/email-typography';export { getFullHtmlEmailIfWholeBody } from './tiptap/get-full-html-email-if-whole-body';+export { getTipTapFileUrlAttributeName } from './tiptap/get-tiptap-file-url-attribute-name';export { HTML_ELEMENT_NAMES } from './tiptap/html-element-names';export { isCanvasTheme } from './tiptap/is-canvas-theme';export { isEmailDocumentShape } from './tiptap/is-email-document-shape';+export { isStorableRichTextUrl } from './tiptap/is-storable-rich-text-url';export type { CampaignVariableDefinition } from './tiptap/list-campaign-variables-for-fields';export { listCampaignVariablesForFields } from './tiptap/list-campaign-variables-for-fields';export { looksLikeHtml } from './tiptap/looks-like-html';@@ -295,6 +300,13 @@ export {parseCanonicalTipTapJsonDocument,} from './tiptap/parse-tiptap-json-document';export { resolveCanvasTheme } from './tiptap/resolve-canvas-theme';+export type { RichTextColor } from './tiptap/rich-text-color.type';+export { RICH_TEXT_COLORS } from './tiptap/rich-text-colors.constant';+export { richTextDocumentSchema } from './tiptap/rich-text-document-schema';+export type { RichTextDocument } from './tiptap/rich-text-document.type';+export { RICH_TEXT_MAX_HEADING_LEVEL } from './tiptap/rich-text-max-heading-level.constant';+export { RICH_TEXT_TEXT_ALIGNMENTS } from './tiptap/rich-text-text-alignments.constant';+export { RICH_TEXT_URL_MAX_LENGTH } from './tiptap/rich-text-url-max-length.constant';export { TIPTAP_DOCUMENT_SCHEMA_VERSION } from './tiptap/tiptap-document-schema-version';export { tipTapDocumentToMarkdown } from './tiptap/tiptap-document-to-markdown';export type { TipTapDocument } from './tiptap/tiptap-document';diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/convert-blocknote-to-rich-text-document.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/convert-blocknote-to-rich-text-document.test.tsnew file mode 100644index 00000000000..19737821d55--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/convert-blocknote-to-rich-text-document.test.ts@@ -0,0 +1,563 @@+import { convertBlockNoteToRichTextDocument } from '../convert-blocknote-to-rich-text-document';+import { richTextDocumentSchema } from '../rich-text-document-schema';+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from '../tiptap-document-schema-version';++const DEFAULT_PROPS = {+ textColor: 'default',+ backgroundColor: 'default',+ textAlignment: 'left',+};++const block = (+ type: string,+ content: unknown,+ props: Record<string, unknown> = {},+ children: unknown[] = [],+) => ({+ id: `${type}-id`,+ type,+ props: { ...DEFAULT_PROPS, ...props },+ content,+ children,+});++const text = (value: string, styles: Record<string, unknown> = {}) => ({+ type: 'text',+ text: value,+ styles,+});++const convert = (blocks: unknown[]) => {+ const document = convertBlockNoteToRichTextDocument(JSON.stringify(blocks));++ expect(richTextDocumentSchema.safeParse(document).success).toBe(true);++ return document?.content;+};++describe('convertBlockNoteToRichTextDocument', () => {+ it('should convert headings, styled text and a run of bullet items into one list', () => {+ expect(+ convert([+ block('heading', [text('Meeting')], { level: 2, isToggleable: false }),+ block('paragraph', [text('Hello '), text('world', { bold: true })]),+ block('bulletListItem', [text('Item one')]),+ block('bulletListItem', [text('Item two')]),+ ]),+ ).toEqual([+ {+ type: 'heading',+ attrs: { level: 2 },+ content: [{ type: 'text', text: 'Meeting' }],+ },+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: 'Hello ' },+ { type: 'text', text: 'world', marks: [{ type: 'bold' }] },+ ],+ },+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Item one' }],+ },+ ],+ },+ {+ type: 'listItem',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Item two' }],+ },+ ],+ },+ ],+ },+ ]);+ });++ it('should stamp the schema version and keep an empty note editable', () => {+ expect(convertBlockNoteToRichTextDocument('[]')).toEqual({+ type: 'doc',+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },+ content: [{ type: 'paragraph' }],+ });+ });++ it('should not convert a value that is not a BlockNote block array', () => {+ expect(convertBlockNoteToRichTextDocument('not json')).toBeUndefined();+ expect(+ convertBlockNoteToRichTextDocument(+ JSON.stringify({ type: 'doc', content: [] }),+ ),+ ).toBeUndefined();+ });++ it('should nest the children of a list item and keep the children of other blocks after them', () => {+ expect(+ convert([+ block('bulletListItem', [text('Parent')], {}, [+ block('numberedListItem', [text('Child')]),+ ]),+ block('paragraph', [text('Intro')], {}, [+ block('paragraph', [text('Indented')]),+ ]),+ ]),+ ).toEqual([+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Parent' }],+ },+ {+ type: 'orderedList',+ content: [+ {+ type: 'listItem',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Child' }],+ },+ ],+ },+ ],+ },+ ],+ },+ ],+ },+ { type: 'paragraph', content: [{ type: 'text', text: 'Intro' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'Indented' }] },+ ]);+ });++ it('should restart an ordered list where an item sets its start number', () => {+ const lists = convert([+ block('numberedListItem', [text('One')]),+ block('numberedListItem', [text('Two')]),+ block('numberedListItem', [text('Five')], { start: 5 }),+ ]);++ expect(+ lists?.map(({ type, attrs, content }) => [type, attrs, content?.length]),+ ).toEqual([+ ['orderedList', undefined, 2],+ ['orderedList', { start: 5 }, 1],+ ]);+ });++ it('should convert check list items and toggle list items', () => {+ expect(+ convert([+ block('checkListItem', [text('Done')], { checked: true }),+ block('checkListItem', [text('Todo')], { checked: false }),+ block('toggleListItem', [text('Toggle')]),+ ]),+ ).toEqual([+ {+ type: 'taskList',+ content: [+ {+ type: 'taskItem',+ attrs: { checked: true },+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'Done' }] },+ ],+ },+ {+ type: 'taskItem',+ attrs: { checked: false },+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'Todo' }] },+ ],+ },+ ],+ },+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Toggle' }],+ },+ ],+ },+ ],+ },+ ]);+ });++ it('should convert links, mentions, inline code and line breaks', () => {+ expect(+ convert([+ block('paragraph', [+ {+ type: 'link',+ href: 'https://twenty.com',+ content: [text('Twenty', { italic: true, code: true })],+ },+ text(' and '),+ {+ type: 'mention',+ props: {+ recordId: '20202020-0000-4000-8000-000000000001',+ objectMetadataId: '20202020-0000-4000-8000-000000000002',+ objectNameSingular: 'person',+ label: 'Ada Lovelace',+ imageUrl: '',+ },+ },+ text('npm run\nnext line', { code: true }),+ ]),+ ]),+ ).toEqual([+ {+ type: 'paragraph',+ content: [+ {+ type: 'text',+ text: 'Twenty',+ marks: [+ { type: 'italic' },+ { type: 'link', attrs: { href: 'https://twenty.com' } },+ ],+ },+ { type: 'text', text: ' and ' },+ {+ type: 'mentionTag',+ attrs: {+ recordId: '20202020-0000-4000-8000-000000000001',+ objectNameSingular: 'person',+ label: 'Ada Lovelace',+ imageUrl: '',+ },+ },+ { type: 'text', text: 'npm run', marks: [{ type: 'code' }] },+ { type: 'hardBreak' },+ { type: 'text', text: 'next line', marks: [{ type: 'code' }] },+ ],+ },+ ]);+ });++ it('should keep the named colors BlockNote displays and drop pasted CSS colors', () => {+ expect(+ convert([+ block(+ 'paragraph',+ [+ text('Inherits red'),+ text('Own highlight', { backgroundColor: 'yellow' }),+ text('Pasted', { textColor: 'rgb(0, 0, 0)' }),+ ],+ { textColor: 'red', textAlignment: 'center' },+ ),+ block('paragraph', [text('Plain', { textColor: 'rgb(34, 34, 34)' })]),+ ]),+ ).toEqual([+ {+ type: 'paragraph',+ attrs: { textAlign: 'center' },+ content: [+ {+ type: 'text',+ text: 'Inherits red',+ marks: [+ {+ type: 'textStyle',+ attrs: { textColor: 'red', backgroundColor: null },+ },+ ],+ },+ {+ type: 'text',+ text: 'Own highlight',+ marks: [+ {+ type: 'textStyle',+ attrs: { textColor: 'red', backgroundColor: 'yellow' },+ },+ ],+ },+ {+ type: 'text',+ text: 'Pasted',+ marks: [+ {+ type: 'textStyle',+ attrs: { textColor: 'red', backgroundColor: null },+ },+ ],+ },+ ],+ },+ { type: 'paragraph', content: [{ type: 'text', text: 'Plain' }] },+ ]);+ });++ it('should convert quotes, code blocks, dividers and keep heading levels up to 6', () => {+ expect(+ convert([+ block('quote', [text('Quoted')]),+ block('codeBlock', [text('const a = 1;\nconst b = 2;')], {+ language: 'typescript',+ }),+ block('divider', undefined),+ block('heading', [text('Small title')], { level: 5 }),+ block('heading', [text('Too deep')], { level: 9 }),+ ]),+ ).toEqual([+ {+ type: 'blockquote',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'Quoted' }] },+ ],+ },+ {+ type: 'codeBlock',+ attrs: { language: 'typescript' },+ content: [{ type: 'text', text: 'const a = 1;\nconst b = 2;' }],+ },+ { type: 'divider' },+ {+ type: 'heading',+ attrs: { level: 5 },+ content: [{ type: 'text', text: 'Small title' }],+ },+ {+ type: 'heading',+ attrs: { level: 6 },+ content: [{ type: 'text', text: 'Too deep' }],+ },+ ]);+ });++ it('should convert a table with a header row, column widths and legacy cells', () => {+ expect(+ convert([+ block('table', {+ type: 'tableContent',+ columnWidths: [120, null],+ headerRows: 1,+ rows: [+ {+ cells: [+ {+ type: 'tableCell',+ props: { colspan: 1, rowspan: 1 },+ content: [text('Name')],+ },+ {+ type: 'tableCell',+ props: { colspan: 1, rowspan: 1 },+ content: [text('Stage')],+ },+ ],+ },+ { cells: [[text('Acme')], []] },+ ],+ }),+ ]),+ ).toEqual([+ {+ type: 'table',+ content: [+ {+ type: 'tableRow',+ content: [+ {+ type: 'tableHeader',+ attrs: { colspan: 1, rowspan: 1, colwidth: [120] },+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Name' }],+ },+ ],+ },+ {+ type: 'tableHeader',+ attrs: { colspan: 1, rowspan: 1, colwidth: null },+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Stage' }],+ },+ ],+ },+ ],+ },+ {+ type: 'tableRow',+ content: [+ {+ type: 'tableCell',+ attrs: { colspan: 1, rowspan: 1, colwidth: [120] },+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Acme' }],+ },+ ],+ },+ {+ type: 'tableCell',+ attrs: { colspan: 1, rowspan: 1, colwidth: null },+ content: [{ type: 'paragraph' }],+ },+ ],+ },+ ],+ },+ ]);+ });++ it('should convert images, files and videos and skip blocks still waiting for an upload', () => {+ expect(+ convert([+ block('image', undefined, {+ url: 'https://example.com/chart.png',+ caption: '',+ name: 'chart.png',+ previewWidth: 512,+ showPreview: true,+ }),+ block('image', undefined, {+ url: 'https://example.com/team.png',+ caption: 'The team at the offsite',+ name: 'team.png',+ }),+ block('image', undefined, { url: '', name: '' }),+ block('file', undefined, {+ url: 'https://example.com/contract.pdf',+ name: 'contract.pdf',+ }),+ block('video', undefined, {+ url: 'https://example.com/demo.mp4',+ name: '',+ }),+ ]),+ ).toEqual([+ {+ type: 'image',+ attrs: {+ src: 'https://example.com/chart.png',+ alt: 'chart.png',+ title: null,+ width: 512,+ },+ },+ {+ type: 'image',+ attrs: {+ src: 'https://example.com/team.png',+ alt: 'team.png',+ title: 'The team at the offsite',+ width: null,+ },+ },+ {+ type: 'file',+ attrs: {+ url: 'https://example.com/contract.pdf',+ name: 'contract.pdf',+ },+ },+ {+ type: 'file',+ attrs: { url: 'https://example.com/demo.mp4', name: null },+ },+ ]);+ });++ it('should only produce documents the rich text write validator accepts', () => {+ const longUrl = `https://example.com/${'a'.repeat(4_000)}`;++ const document = convertBlockNoteToRichTextDocument(+ JSON.stringify([+ block('paragraph', [+ {+ type: 'link',+ href: 'javascript:alert(1)',+ content: [text('Unsafe')],+ },+ { type: 'link', href: longUrl, content: [text('Too long')] },+ { type: 'link', href: '/objects/people', content: [text('Safe')] },+ ]),+ block('heading', [text('Half level')], { level: 2.5 }),+ block('numberedListItem', [text('Fractional')], { start: 2.7 }),+ block('numberedListItem', [text('Negative')], { start: -4 }),+ block('image', undefined, { url: 'javascript:alert(1)', name: 'x' }),+ block('image', undefined, { url: longUrl, name: 'long.png' }),+ block('file', undefined, { url: 'data:text/html,hi', name: 'evil' }),+ block('audio', undefined, { url: longUrl, name: 'long.mp3' }),+ ]),+ );++ expect(richTextDocumentSchema.safeParse(document).success).toBe(true);+ expect(document?.content).toEqual([+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: 'Unsafe' },+ { type: 'text', text: 'Too long' },+ {+ type: 'text',+ text: 'Safe',+ marks: [{ type: 'link', attrs: { href: '/objects/people' } }],+ },+ ],+ },+ {+ type: 'heading',+ attrs: { level: 2 },+ content: [{ type: 'text', text: 'Half level' }],+ },+ {+ type: 'orderedList',+ attrs: { start: 2 },+ content: [+ {+ type: 'listItem',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Fractional' }],+ },+ ],+ },+ ],+ },+ {+ type: 'orderedList',+ content: [+ {+ type: 'listItem',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Negative' }],+ },+ ],+ },+ ],+ },+ ]);+ });+});diff --git a/packages/twenty-shared/src/utils/tiptap/convert-blocknote-to-rich-text-document.ts b/packages/twenty-shared/src/utils/tiptap/convert-blocknote-to-rich-text-document.tsnew file mode 100644index 00000000000..a9349e041ac--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/convert-blocknote-to-rich-text-document.ts@@ -0,0 +1,482 @@+import { isNonEmptyString, isNumber, isString } from '@sniptt/guards';++import { parseJson } from '@/utils/parseJson';+import { isPlainObject } from '@/utils/typeguard/isPlainObject';+import { isDefined } from '@/utils/validation';++import { type RichTextColor } from './rich-text-color.type';+import { RICH_TEXT_COLORS } from './rich-text-colors.constant';+import { type RichTextDocument } from './rich-text-document.type';+import { RICH_TEXT_MAX_HEADING_LEVEL } from './rich-text-max-heading-level.constant';+import { RICH_TEXT_TEXT_ALIGNMENTS } from './rich-text-text-alignments.constant';+import { convertTextToTipTapNodes } from './convert-text-to-tiptap-nodes';+import { isStorableRichTextUrl } from './is-storable-rich-text-url';+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from './tiptap-document-schema-version';+import { type TipTapMark, TIPTAP_MARK_TYPES } from './tiptap-mark-types';+import { type TipTapNode } from './tiptap-node';+import { TIPTAP_NODE_TYPES } from './tiptap-node-types';++type BlockNoteObject = Record<string, unknown>;++type BlockNoteColors = {+ textColor?: RichTextColor;+ backgroundColor?: RichTextColor;+};++type ListNodeType =+ | typeof TIPTAP_NODE_TYPES.BULLET_LIST+ | typeof TIPTAP_NODE_TYPES.ORDERED_LIST+ | typeof TIPTAP_NODE_TYPES.TASK_LIST;++const toObjects = (value: unknown): BlockNoteObject[] =>+ Array.isArray(value) ? value.filter(isPlainObject) : [];++const readProps = (blockNoteObject: BlockNoteObject): BlockNoteObject =>+ isPlainObject(blockNoteObject.props) ? blockNoteObject.props : {};++const readColor = (value: unknown): RichTextColor | undefined =>+ RICH_TEXT_COLORS.find((color) => color === value);++const readTextAlign = (value: unknown) =>+ RICH_TEXT_TEXT_ALIGNMENTS.find(+ (textAlignment) => textAlignment !== 'left' && textAlignment === value,+ );++const readBlockColors = (props: BlockNoteObject): BlockNoteColors => ({+ textColor: readColor(props.textColor),+ backgroundColor: readColor(props.backgroundColor),+});++const createNode = ({ type, attrs, content }: TipTapNode): TipTapNode => {+ const node: TipTapNode = { type };++ if (isDefined(attrs)) {+ node.attrs = attrs;+ }++ if (isDefined(content) && content.length > 0) {+ node.content = content;+ }++ return node;+};++const convertStylesToMarks = ({+ styles,+ inheritedColors,+ isInsideLink,+}: {+ styles: BlockNoteObject;+ inheritedColors: BlockNoteColors;+ isInsideLink: boolean;+}): TipTapMark[] => {+ if (styles.code === true && !isInsideLink) {+ return [{ type: TIPTAP_MARK_TYPES.CODE }];+ }++ const marks: TipTapMark[] = [];++ if (styles.bold === true) {+ marks.push({ type: TIPTAP_MARK_TYPES.BOLD });+ }++ if (styles.italic === true) {+ marks.push({ type: TIPTAP_MARK_TYPES.ITALIC });+ }++ if (styles.underline === true) {+ marks.push({ type: TIPTAP_MARK_TYPES.UNDERLINE });+ }++ if (styles.strike === true) {+ marks.push({ type: TIPTAP_MARK_TYPES.STRIKE });+ }++ const textColor = readColor(styles.textColor) ?? inheritedColors.textColor;+ const backgroundColor =+ readColor(styles.backgroundColor) ?? inheritedColors.backgroundColor;++ if (isDefined(textColor) || isDefined(backgroundColor)) {+ marks.push({+ type: TIPTAP_MARK_TYPES.TEXT_STYLE,+ attrs: {+ textColor: textColor ?? null,+ backgroundColor: backgroundColor ?? null,+ },+ });+ }++ return marks;+};++const convertStyledText = ({+ styledText,+ inheritedColors,+ linkHref,+}: {+ styledText: BlockNoteObject;+ inheritedColors: BlockNoteColors;+ linkHref?: string;+}): TipTapNode[] => {+ if (!isString(styledText.text)) {+ return [];+ }++ const marks = convertStylesToMarks({+ styles: isPlainObject(styledText.styles) ? styledText.styles : {},+ inheritedColors,+ isInsideLink: isDefined(linkHref),+ });++ if (isDefined(linkHref)) {+ marks.push({ type: TIPTAP_MARK_TYPES.LINK, attrs: { href: linkHref } });+ }++ return convertTextToTipTapNodes(styledText.text, marks);+};++const createMentionTagNode = (props: BlockNoteObject): TipTapNode => ({+ type: TIPTAP_NODE_TYPES.MENTION_TAG,+ attrs: {+ recordId: isString(props.recordId) ? props.recordId : null,+ objectNameSingular: isString(props.objectNameSingular)+ ? props.objectNameSingular+ : null,+ label: isString(props.label) ? props.label : '',+ imageUrl: isString(props.imageUrl) ? props.imageUrl : '',+ },+});++const convertInlineItem = (+ inlineItem: BlockNoteObject,+ inheritedColors: BlockNoteColors,+): TipTapNode[] => {+ switch (inlineItem.type) {+ case 'text':+ return convertStyledText({ styledText: inlineItem, inheritedColors });+ case 'link': {+ const linkHref = isStorableRichTextUrl(inlineItem.href)+ ? inlineItem.href+ : undefined;+ const linkContent = isString(inlineItem.content)+ ? [{ type: 'text', text: inlineItem.content }]+ : toObjects(inlineItem.content);++ return linkContent.flatMap((styledText) =>+ convertStyledText({ styledText, inheritedColors, linkHref }),+ );+ }+ case 'mention':+ return [createMentionTagNode(readProps(inlineItem))];+ default:+ return [];+ }+};++const convertInlineContent = ({+ content,+ inheritedColors,+}: {+ content: unknown;+ inheritedColors: BlockNoteColors;+}): TipTapNode[] =>+ isString(content)+ ? convertStyledText({ styledText: { text: content }, inheritedColors })+ : toObjects(content).flatMap((inlineItem) =>+ convertInlineItem(inlineItem, inheritedColors),+ );++const createParagraphNode = (block: BlockNoteObject): TipTapNode => {+ const props = readProps(block);+ const textAlign = readTextAlign(props.textAlignment);++ return createNode({+ type: TIPTAP_NODE_TYPES.PARAGRAPH,+ attrs: isDefined(textAlign) ? { textAlign } : undefined,+ content: convertInlineContent({+ content: block.content,+ inheritedColors: readBlockColors(props),+ }),+ });+};++const createHeadingNode = (block: BlockNoteObject): TipTapNode => {+ const props = readProps(block);+ const textAlign = readTextAlign(props.textAlignment);+ const level = isNumber(props.level)+ ? Math.min(+ Math.max(Math.trunc(props.level), 1),+ RICH_TEXT_MAX_HEADING_LEVEL,+ )+ : 1;++ return createNode({+ type: TIPTAP_NODE_TYPES.HEADING,+ attrs: isDefined(textAlign) ? { level, textAlign } : { level },+ content: convertInlineContent({+ content: block.content,+ inheritedColors: readBlockColors(props),+ }),+ });+};++const createCodeBlockNode = (block: BlockNoteObject): TipTapNode => {+ const props = readProps(block);+ const code = convertInlineContent({+ content: block.content,+ inheritedColors: {},+ })+ .map((node) =>+ node.type === TIPTAP_NODE_TYPES.HARD_BREAK ? '\n' : (node.text ?? ''),+ )+ .join('');++ return createNode({+ type: TIPTAP_NODE_TYPES.CODE_BLOCK,+ attrs: {+ language: isNonEmptyString(props.language) ? props.language : null,+ },+ content:+ code.length > 0 ? [{ type: TIPTAP_NODE_TYPES.TEXT, text: code }] : [],+ });+};++const readTableCell = (cell: unknown): BlockNoteObject => {+ if (Array.isArray(cell)) {+ return { content: cell };+ }++ return isPlainObject(cell) ? cell : {};+};++const readSpan = (value: unknown): number =>+ isNumber(value) && Number.isInteger(value) && value > 1 ? value : 1;++const createTableCellNode = ({+ cell,+ isHeader,+ columnWidth,+}: {+ cell: unknown;+ isHeader: boolean;+ columnWidth: unknown;+}): TipTapNode => {+ const tableCell = readTableCell(cell);+ const props = readProps(tableCell);+ const colspan = readSpan(props.colspan);++ return {+ type: isHeader+ ? TIPTAP_NODE_TYPES.TABLE_HEADER+ : TIPTAP_NODE_TYPES.TABLE_CELL,+ attrs: {+ colspan,+ rowspan: readSpan(props.rowspan),+ colwidth: colspan === 1 && isNumber(columnWidth) ? [columnWidth] : null,+ },+ content: [createParagraphNode(tableCell)],+ };+};++const createTableNodes = (tableContent: unknown): TipTapNode[] => {+ if (!isPlainObject(tableContent)) {+ return [];+ }++ const headerRowCount = isNumber(tableContent.headerRows)+ ? tableContent.headerRows+ : 0;+ const headerColumnCount = isNumber(tableContent.headerCols)+ ? tableContent.headerCols+ : 0;+ const columnWidths: unknown[] = Array.isArray(tableContent.columnWidths)+ ? tableContent.columnWidths+ : [];++ const rows = toObjects(tableContent.rows)+ .map((row, rowIndex) => {+ const cells: unknown[] = Array.isArray(row.cells) ? row.cells : [];++ return {+ type: TIPTAP_NODE_TYPES.TABLE_ROW,+ content: cells.map((cell, columnIndex) =>+ createTableCellNode({+ cell,+ isHeader:+ rowIndex < headerRowCount || columnIndex < headerColumnCount,+ columnWidth: columnWidths[columnIndex],+ }),+ ),+ };+ })+ .filter((row) => row.content.length > 0);++ return rows.length > 0+ ? [{ type: TIPTAP_NODE_TYPES.TABLE, content: rows }]+ : [];+};++const createImageNodes = (props: BlockNoteObject): TipTapNode[] => {+ if (!isStorableRichTextUrl(props.url)) {+ return [];+ }++ return [+ {+ type: TIPTAP_NODE_TYPES.IMAGE,+ attrs: {+ src: props.url,+ alt: isNonEmptyString(props.name) ? props.name : null,+ title: isNonEmptyString(props.caption) ? props.caption : null,+ width: isNumber(props.previewWidth) ? props.previewWidth : null,+ },+ },+ ];+};++const createFileNodes = (props: BlockNoteObject): TipTapNode[] =>+ isStorableRichTextUrl(props.url)+ ? [+ {+ type: TIPTAP_NODE_TYPES.FILE,+ attrs: {+ url: props.url,+ name: isNonEmptyString(props.name) ? props.name : null,+ },+ },+ ]+ : [];++const convertBlockContent = (block: BlockNoteObject): TipTapNode[] => {+ switch (block.type) {+ case 'paragraph':+ return [createParagraphNode(block)];+ case 'heading':+ return [createHeadingNode(block)];+ case 'quote':+ return [+ {+ type: TIPTAP_NODE_TYPES.BLOCKQUOTE,+ content: [createParagraphNode(block)],+ },+ ];+ case 'codeBlock':+ return [createCodeBlockNode(block)];+ case 'divider':+ return [{ type: TIPTAP_NODE_TYPES.DIVIDER }];+ case 'table':+ return createTableNodes(block.content);+ case 'image':+ return createImageNodes(readProps(block));+ case 'file':+ case 'video':+ case 'audio':+ return createFileNodes(readProps(block));+ default:+ return isDefined(block.content) ? [createParagraphNode(block)] : [];+ }+};++const getListNodeType = (blockType: unknown): ListNodeType | undefined => {+ switch (blockType) {+ case 'bulletListItem':+ case 'toggleListItem':+ return TIPTAP_NODE_TYPES.BULLET_LIST;+ case 'numberedListItem':+ return TIPTAP_NODE_TYPES.ORDERED_LIST;+ case 'checkListItem':+ return TIPTAP_NODE_TYPES.TASK_LIST;+ default:+ return undefined;+ }+};++const createListNode = ({+ listNodeType,+ firstItemProps,+}: {+ listNodeType: ListNodeType;+ firstItemProps: BlockNoteObject;+}): TipTapNode => {+ const start = isNumber(firstItemProps.start)+ ? Math.max(Math.trunc(firstItemProps.start), 1)+ : 1;++ return listNodeType === TIPTAP_NODE_TYPES.ORDERED_LIST && start !== 1+ ? { type: listNodeType, attrs: { start }, content: [] }+ : { type: listNodeType, content: [] };+};++const createListItemNode = ({+ block,+ listNodeType,+}: {+ block: BlockNoteObject;+ listNodeType: ListNodeType;+}): TipTapNode => {+ const content = [+ createParagraphNode(block),+ ...convertBlocks(block.children),+ ];++ return listNodeType === TIPTAP_NODE_TYPES.TASK_LIST+ ? {+ type: TIPTAP_NODE_TYPES.TASK_ITEM,+ attrs: { checked: readProps(block).checked === true },+ content,+ }+ : { type: TIPTAP_NODE_TYPES.LIST_ITEM, content };+};++const convertBlocks = (blocks: unknown): TipTapNode[] => {+ const nodes: TipTapNode[] = [];+ let currentListNode: TipTapNode | undefined;++ for (const block of toObjects(blocks)) {+ const listNodeType = getListNodeType(block.type);++ if (!isDefined(listNodeType)) {+ currentListNode = undefined;+ nodes.push(+ ...convertBlockContent(block),+ ...convertBlocks(block.children),+ );+ continue;+ }++ const props = readProps(block);+ const restartsNumbering =+ listNodeType === TIPTAP_NODE_TYPES.ORDERED_LIST && isNumber(props.start);++ if (currentListNode?.type !== listNodeType || restartsNumbering) {+ currentListNode = createListNode({+ listNodeType,+ firstItemProps: props,+ });+ nodes.push(currentListNode);+ }++ currentListNode.content?.push(createListItemNode({ block, listNodeType }));+ }++ return nodes;+};++export const convertBlockNoteToRichTextDocument = (+ serializedBlockNote: string,+): RichTextDocument | undefined => {+ const blocks = parseJson<unknown>(serializedBlockNote);++ if (!Array.isArray(blocks)) {+ return undefined;+ }++ const content = convertBlocks(blocks);++ return {+ type: TIPTAP_NODE_TYPES.DOCUMENT,+ attrs: { schemaVersion: TIPTAP_DOCUMENT_SCHEMA_VERSION },+ content:+ content.length > 0 ? content : [{ type: TIPTAP_NODE_TYPES.PARAGRAPH }],+ };+};diff --git a/packages/twenty-shared/src/utils/tiptap/convert-text-to-tiptap-nodes.ts b/packages/twenty-shared/src/utils/tiptap/convert-text-to-tiptap-nodes.tsnew file mode 100644index 00000000000..df7bbc2e4d4--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/convert-text-to-tiptap-nodes.ts@@ -0,0 +1,26 @@+import { isNonEmptyString } from '@sniptt/guards';++import { isNonEmptyArray } from '@/utils/array/isNonEmptyArray';++import { type TipTapMark } from './tiptap-mark-types';+import { type TipTapNode } from './tiptap-node';+import { TIPTAP_NODE_TYPES } from './tiptap-node-types';++export const convertTextToTipTapNodes = (+ text: string,+ marks: TipTapMark[],+): TipTapNode[] =>+ text.split('\n').flatMap((line, lineIndex) => {+ const lineNodes: TipTapNode[] =+ lineIndex > 0 ? [{ type: TIPTAP_NODE_TYPES.HARD_BREAK }] : [];++ if (isNonEmptyString(line)) {+ lineNodes.push(+ isNonEmptyArray(marks)+ ? { type: TIPTAP_NODE_TYPES.TEXT, text: line, marks }+ : { type: TIPTAP_NODE_TYPES.TEXT, text: line },+ );+ }++ return lineNodes;+ });diff --git a/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-document.ts b/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-document.tsnew file mode 100644index 00000000000..d888ac61991--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-document.ts@@ -0,0 +1,53 @@+import { isPlainObject } from '@/utils/typeguard/isPlainObject';++import { isTipTapNode } from './parse-tiptap-json-document';+import { type TipTapDocument } from './tiptap-document';+import { type TipTapNode } from './tiptap-node';+import { TIPTAP_NODE_TYPES } from './tiptap-node-types';++// Workflow steps created through the API can still hold BlockNote, which also parses as TipTap+const BLOCKNOTE_ONLY_KEYS = ['id', 'props', 'children', 'styles'];++const isBlockNoteContent = (value: unknown): boolean => {+ if (!isPlainObject(value)) {+ return false;+ }++ if (BLOCKNOTE_ONLY_KEYS.some((key) => key in value)) {+ return true;+ }++ return Array.isArray(value.content) && value.content.some(isBlockNoteContent);+};++const isTipTapDocumentNode = (+ node: TipTapNode | undefined,+): node is TipTapDocument => node?.type === TIPTAP_NODE_TYPES.DOCUMENT;++export const convertTipTapBlocksToDocument = (+ serializedBlocks: string,+): TipTapDocument | undefined => {+ let parsedBlocks: unknown;++ try {+ parsedBlocks = JSON.parse(serializedBlocks);+ } catch {+ return undefined;+ }++ const nodes = Array.isArray(parsedBlocks) ? parsedBlocks : [parsedBlocks];++ if (+ nodes.length === 0 ||+ nodes.some(isBlockNoteContent) ||+ !nodes.every(isTipTapNode)+ ) {+ return undefined;+ }++ const [firstNode] = nodes;++ return nodes.length === 1 && isTipTapDocumentNode(firstNode)+ ? firstNode+ : { type: TIPTAP_NODE_TYPES.DOCUMENT, content: nodes };+};diff --git a/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-markdown.ts b/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-markdown.tsindex 5ed445d481a..e25e0a67a2a 100644--- a/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-markdown.ts+++ b/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-markdown.ts@@ -1,52 +1,12 @@-import { isPlainObject } from '@/utils/typeguard/isPlainObject';+import { isDefined } from '@/utils/validation';-import { isTipTapNode } from './parse-tiptap-json-document';-import { type TipTapDocument } from './tiptap-document';+import { convertTipTapBlocksToDocument } from './convert-tiptap-blocks-to-document';import { tipTapDocumentToMarkdown } from './tiptap-document-to-markdown';-import { TIPTAP_NODE_TYPES } from './tiptap-node-types';--// Workflow steps created through the API can still hold BlockNote, which also parses as TipTap-const BLOCKNOTE_ONLY_KEYS = ['id', 'props', 'children', 'styles'];--const isBlockNoteContent = (value: unknown): boolean => {- if (!isPlainObject(value)) {- return false;- }-- if (BLOCKNOTE_ONLY_KEYS.some((key) => key in value)) {- return true;- }-- return Array.isArray(value.content) && value.content.some(isBlockNoteContent);-};export const convertTipTapBlocksToMarkdown = (serializedBlocks: string,): string | undefined => {- let parsedBlocks: unknown;-- try {- parsedBlocks = JSON.parse(serializedBlocks);- } catch {- return undefined;- }-- const nodes = Array.isArray(parsedBlocks) ? parsedBlocks : [parsedBlocks];-- if (- nodes.length === 0 ||- nodes.some(isBlockNoteContent) ||- !nodes.every(isTipTapNode)- ) {- return undefined;- }-- const [firstNode] = nodes;+ const document = convertTipTapBlocksToDocument(serializedBlocks);- return nodes.length === 1 && firstNode?.type === TIPTAP_NODE_TYPES.DOCUMENT- ? tipTapDocumentToMarkdown(firstNode as TipTapDocument)- : tipTapDocumentToMarkdown({- type: TIPTAP_NODE_TYPES.DOCUMENT,- content: nodes,- });+ return isDefined(document) ? tipTapDocumentToMarkdown(document) : undefined;};diff --git a/packages/twenty-shared/src/utils/tiptap/get-tiptap-file-url-attribute-name.ts b/packages/twenty-shared/src/utils/tiptap/get-tiptap-file-url-attribute-name.tsnew file mode 100644index 00000000000..77eecb11d9a--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/get-tiptap-file-url-attribute-name.ts@@ -0,0 +1,14 @@+import { TIPTAP_NODE_TYPES } from './tiptap-node-types';++export const getTipTapFileUrlAttributeName = (+ nodeType: string,+): 'src' | 'url' | undefined => {+ switch (nodeType) {+ case TIPTAP_NODE_TYPES.IMAGE:+ return 'src';+ case TIPTAP_NODE_TYPES.FILE:+ return 'url';+ default:+ return undefined;+ }+};diff --git a/packages/twenty-shared/src/utils/tiptap/is-storable-rich-text-url.ts b/packages/twenty-shared/src/utils/tiptap/is-storable-rich-text-url.tsnew file mode 100644index 00000000000..4eb14a54f13--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/is-storable-rich-text-url.ts@@ -0,0 +1,8 @@+import { isString } from '@sniptt/guards';++import { isSafeUrl } from '@/utils/url/isSafeUrl';++import { RICH_TEXT_URL_MAX_LENGTH } from './rich-text-url-max-length.constant';++export const isStorableRichTextUrl = (url: unknown): url is string =>+ isString(url) && url.length <= RICH_TEXT_URL_MAX_LENGTH && isSafeUrl(url);diff --git a/packages/twenty-shared/src/utils/tiptap/rich-text-color.type.ts b/packages/twenty-shared/src/utils/tiptap/rich-text-color.type.tsnew file mode 100644index 00000000000..9aa7a9d5bf4--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/rich-text-color.type.ts@@ -0,0 +1,3 @@+import { type RICH_TEXT_COLORS } from './rich-text-colors.constant';++export type RichTextColor = (typeof RICH_TEXT_COLORS)[number];diff --git a/packages/twenty-shared/src/utils/tiptap/rich-text-colors.constant.ts b/packages/twenty-shared/src/utils/tiptap/rich-text-colors.constant.tsnew file mode 100644index 00000000000..2800229712c--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/rich-text-colors.constant.ts@@ -0,0 +1,11 @@+export const RICH_TEXT_COLORS = [+ 'gray',+ 'brown',+ 'red',+ 'orange',+ 'yellow',+ 'green',+ 'blue',+ 'purple',+ 'pink',+] as const;diff --git a/packages/twenty-shared/src/utils/tiptap/rich-text-document-schema.ts b/packages/twenty-shared/src/utils/tiptap/rich-text-document-schema.tsnew file mode 100644index 00000000000..5d8f8d249e2--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/rich-text-document-schema.ts@@ -0,0 +1,234 @@+import { isNonEmptyString } from '@sniptt/guards';+import { z } from 'zod';++import { isSafeUrl } from '@/utils/url/isSafeUrl';++import { RICH_TEXT_COLORS } from './rich-text-colors.constant';+import { RICH_TEXT_TEXT_ALIGNMENTS } from './rich-text-text-alignments.constant';+import { RICH_TEXT_URL_MAX_LENGTH } from './rich-text-url-max-length.constant';+import { TIPTAP_DOCUMENT_SCHEMA_VERSION } from './tiptap-document-schema-version';+import { TIPTAP_MARK_TYPES } from './tiptap-mark-types';+import { type TipTapNode } from './tiptap-node';+import { TIPTAP_NODE_TYPES } from './tiptap-node-types';++const textAlignAttributeSchema = z+ .enum(RICH_TEXT_TEXT_ALIGNMENTS)+ .nullable()+ .optional();++const colorAttributeSchema = z.enum(RICH_TEXT_COLORS).nullable().optional();++const urlSchema = z+ .string()+ .max(RICH_TEXT_URL_MAX_LENGTH)+ .refine((url) => !isNonEmptyString(url.trim()) || isSafeUrl(url.trim()), {+ message: 'Dangerous URL protocol',+ });++const markSchema = z.discriminatedUnion('type', [+ z.looseObject({ type: z.literal(TIPTAP_MARK_TYPES.BOLD) }),+ z.looseObject({ type: z.literal(TIPTAP_MARK_TYPES.ITALIC) }),+ z.looseObject({ type: z.literal(TIPTAP_MARK_TYPES.UNDERLINE) }),+ z.looseObject({ type: z.literal(TIPTAP_MARK_TYPES.STRIKE) }),+ z.looseObject({ type: z.literal(TIPTAP_MARK_TYPES.CODE) }),+ z.looseObject({+ type: z.literal(TIPTAP_MARK_TYPES.LINK),+ attrs: z.looseObject({ href: urlSchema }),+ }),+ z.looseObject({+ type: z.literal(TIPTAP_MARK_TYPES.TEXT_STYLE),+ attrs: z.looseObject({+ textColor: colorAttributeSchema,+ backgroundColor: colorAttributeSchema,+ }),+ }),+]);++const textNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.TEXT),+ text: z.string().min(1),+ marks: z.array(markSchema).optional(),+});++const hardBreakNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.HARD_BREAK),+});++const mentionTagNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.MENTION_TAG),+ attrs: z.looseObject({+ recordId: z.string().nullable(),+ objectNameSingular: z.string().nullable(),+ label: z.string().nullable().optional(),+ imageUrl: z.string().nullable().optional(),+ }),+});++const inlineNodeSchema = z.discriminatedUnion('type', [+ textNodeSchema,+ hardBreakNodeSchema,+ mentionTagNodeSchema,+]);++const blockContentSchema = z.array(+ z.lazy((): z.ZodType<TipTapNode> => blockNodeSchema),+);++const paragraphNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.PARAGRAPH),+ attrs: z.looseObject({ textAlign: textAlignAttributeSchema }).optional(),+ content: z.array(inlineNodeSchema).optional(),+});++const headingNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.HEADING),+ attrs: z.looseObject({+ level: z.union([+ z.literal(1),+ z.literal(2),+ z.literal(3),+ z.literal(4),+ z.literal(5),+ z.literal(6),+ ]),+ textAlign: textAlignAttributeSchema,+ }),+ content: z.array(inlineNodeSchema).optional(),+});++const listItemNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.LIST_ITEM),+ content: blockContentSchema.min(1),+});++const bulletListNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.BULLET_LIST),+ content: z.array(listItemNodeSchema).min(1),+});++const orderedListNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.ORDERED_LIST),+ attrs: z.looseObject({ start: z.int().optional() }).optional(),+ content: z.array(listItemNodeSchema).min(1),+});++const taskItemNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.TASK_ITEM),+ attrs: z.looseObject({ checked: z.boolean() }),+ content: blockContentSchema.min(1),+});++const taskListNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.TASK_LIST),+ content: z.array(taskItemNodeSchema).min(1),+});++const blockquoteNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.BLOCKQUOTE),+ content: blockContentSchema.min(1),+});++const codeBlockNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.CODE_BLOCK),+ attrs: z.looseObject({ language: z.string().nullable() }).optional(),+ content: z+ .array(+ z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.TEXT),+ text: z.string().min(1),+ }),+ )+ .optional(),+});++const dividerNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.DIVIDER),+});++const imageNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.IMAGE),+ attrs: z.looseObject({+ src: urlSchema,+ href: urlSchema.nullable().optional(),+ alt: z.string().nullable().optional(),+ width: z.union([z.string(), z.number()]).nullable().optional(),+ }),+});++const fileNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.FILE),+ attrs: z.looseObject({+ url: urlSchema,+ name: z.string().nullable().optional(),+ }),+});++const tableCellAttributesSchema = z+ .looseObject({+ colspan: z.int().min(1).optional(),+ rowspan: z.int().min(1).optional(),+ colwidth: z.array(z.number()).nullable().optional(),+ })+ .optional();++const createTableCellNodeSchema = <+ TTableCellType extends+ | typeof TIPTAP_NODE_TYPES.TABLE_CELL+ | typeof TIPTAP_NODE_TYPES.TABLE_HEADER,+>(+ tableCellType: TTableCellType,+) =>+ z.looseObject({+ type: z.literal(tableCellType),+ attrs: tableCellAttributesSchema,+ content: blockContentSchema.min(1),+ });++const tableCellNodeSchema = createTableCellNodeSchema(+ TIPTAP_NODE_TYPES.TABLE_CELL,+);++const tableHeaderNodeSchema = createTableCellNodeSchema(+ TIPTAP_NODE_TYPES.TABLE_HEADER,+);++const tableRowNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.TABLE_ROW),+ content: z+ .array(+ z.discriminatedUnion('type', [+ tableCellNodeSchema,+ tableHeaderNodeSchema,+ ]),+ )+ .min(1),+});++const tableNodeSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.TABLE),+ content: z.array(tableRowNodeSchema).min(1),+});++const blockNodeSchema = z.discriminatedUnion('type', [+ paragraphNodeSchema,+ headingNodeSchema,+ bulletListNodeSchema,+ orderedListNodeSchema,+ taskListNodeSchema,+ blockquoteNodeSchema,+ codeBlockNodeSchema,+ dividerNodeSchema,+ imageNodeSchema,+ fileNodeSchema,+ tableNodeSchema,+]);++export const richTextDocumentSchema = z.looseObject({+ type: z.literal(TIPTAP_NODE_TYPES.DOCUMENT),+ attrs: z+ .looseObject({+ schemaVersion: z.literal(TIPTAP_DOCUMENT_SCHEMA_VERSION).optional(),+ })+ .optional(),+ content: blockContentSchema.optional(),+});diff --git a/packages/twenty-shared/src/utils/tiptap/rich-text-document.type.ts b/packages/twenty-shared/src/utils/tiptap/rich-text-document.type.tsnew file mode 100644index 00000000000..54514b07236--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/rich-text-document.type.ts@@ -0,0 +1,5 @@+import { type z } from 'zod';++import { type richTextDocumentSchema } from './rich-text-document-schema';++export type RichTextDocument = z.infer<typeof richTextDocumentSchema>;diff --git a/packages/twenty-shared/src/utils/tiptap/rich-text-max-heading-level.constant.ts b/packages/twenty-shared/src/utils/tiptap/rich-text-max-heading-level.constant.tsnew file mode 100644index 00000000000..4c271b3bad9--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/rich-text-max-heading-level.constant.ts@@ -0,0 +1 @@+export const RICH_TEXT_MAX_HEADING_LEVEL = 6;diff --git a/packages/twenty-shared/src/utils/tiptap/rich-text-text-alignments.constant.ts b/packages/twenty-shared/src/utils/tiptap/rich-text-text-alignments.constant.tsnew file mode 100644index 00000000000..f44b7f7dd9e--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/rich-text-text-alignments.constant.ts@@ -0,0 +1,6 @@+export const RICH_TEXT_TEXT_ALIGNMENTS = [+ 'left',+ 'center',+ 'right',+ 'justify',+] as const;diff --git a/packages/twenty-shared/src/utils/tiptap/rich-text-url-max-length.constant.ts b/packages/twenty-shared/src/utils/tiptap/rich-text-url-max-length.constant.tsnew file mode 100644index 00000000000..3bd7e7c4e7d--- /dev/null+++ b/packages/twenty-shared/src/utils/tiptap/rich-text-url-max-length.constant.ts@@ -0,0 +1 @@+export const RICH_TEXT_URL_MAX_LENGTH = 4_000;diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.tsindex 720b508a353..2429ae6f4ed 100644--- a/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts@@ -1,5 +1,6 @@import { formatRecordReference } from '@/ai/utils/format-record-reference.util';import { formatSkillReference } from '@/ai/utils/format-skill-reference.util';+import { isDefined } from '@/utils/validation';import { parseTipTapJsonDocument } from './parse-tiptap-json-document';import { type TipTapDocument } from './tiptap-document';@@ -57,6 +58,55 @@ const applyMark = (text: string, mark: TipTapMark): string => {}};+const buildBacktickFence = ({+ code,+ minimumLength,+}: {+ code: string;+ minimumLength: number;+}): string =>+ '`'.repeat(+ Math.max(+ minimumLength,+ ...(code.match(/`+/g) ?? []).map((backticks) => backticks.length + 1),+ ),+ );++const renderInlineCode = (code: string): string => {+ const fence = buildBacktickFence({ code, minimumLength: 1 });+ const padding = code.startsWith('`') || code.endsWith('`') ? ' ' : '';++ return `${fence}${padding}${code}${padding}${fence}`;+};++const renderCodeBlock = (node: TipTapNode): string => {+ const code = (node.content ?? []).map((child) => child.text ?? '').join('');+ const fence = buildBacktickFence({ code, minimumLength: 3 });+ const language =+ typeof node.attrs?.language === 'string' ? node.attrs.language : '';++ return `${fence}${language}\n${code}\n${fence}\n\n`;+};++const renderTableRow = (row: TipTapNode): string =>+ `| ${(row.content ?? [])+ .map((cell) => renderChildren(cell).trim().replace(/\n+/g, ' '))+ .join(' | ')} |`;++const renderTable = (node: TipTapNode): string => {+ const [headerRow, ...bodyRows] = node.content ?? [];++ if (!isDefined(headerRow)) {+ return '';+ }++ const separatorRow = `| ${(headerRow.content ?? [])+ .map(() => '---')+ .join(' | ')} |`;++ return `${[renderTableRow(headerRow), separatorRow, ...bodyRows.map(renderTableRow)].join('\n')}\n\n`;+};+const renderMention = (node: TipTapNode): string => {const objectName = node.attrs?.objectNameSingular;const recordId = node.attrs?.recordId;@@ -105,6 +155,12 @@ const renderListItem = (item: TipTapNode, marker: string): string => {const renderTipTapNodeToMarkdown = (node: TipTapNode): string => {switch (node.type) {case TIPTAP_NODE_TYPES.TEXT:+ if (+ (node.marks ?? []).some((mark) => mark.type === TIPTAP_MARK_TYPES.CODE)+ ) {+ return renderInlineCode(node.text ?? '');+ }+return [...(node.marks ?? [])].sort((firstMark, secondMark) =>@@ -182,6 +238,18 @@ const renderTipTapNodeToMarkdown = (node: TipTapNode): string => {return typeof node.attrs?.html === 'string' ? node.attrs.html : '';case TIPTAP_NODE_TYPES.DIVIDER:return '---\n\n';+ case TIPTAP_NODE_TYPES.CODE_BLOCK:+ return renderCodeBlock(node);+ case TIPTAP_NODE_TYPES.TABLE:+ return renderTable(node);+ case TIPTAP_NODE_TYPES.FILE: {+ const name = typeof node.attrs?.name === 'string' ? node.attrs.name : '';+ const url = typeof node.attrs?.url === 'string' ? node.attrs.url : '';++ return url === ''+ ? ''+ : `[${escapeMarkdownText(name === '' ? url : name)}](${escapeMarkdownDestination(url)})\n\n`;+ }default:return renderChildren(node);}diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-mark-types.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-mark-types.tsindex 862d8bd7209..366a0a2cc51 100644--- a/packages/twenty-shared/src/utils/tiptap/tiptap-mark-types.ts+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-mark-types.ts@@ -4,6 +4,8 @@ export const TIPTAP_MARK_TYPES = {UNDERLINE: 'underline',STRIKE: 'strike',LINK: 'link',+ CODE: 'code',+ TEXT_STYLE: 'textStyle',} as const;export type TipTapMarkType =diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.tsindex 548ee6a46af..b46c31b27f3 100644--- a/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts@@ -21,6 +21,12 @@ export const TIPTAP_NODE_TYPES = {DIVIDER: 'divider',HTML: 'html',HTML_DOCUMENT: 'htmlDocument',+ CODE_BLOCK: 'codeBlock',+ TABLE: 'table',+ TABLE_ROW: 'tableRow',+ TABLE_HEADER: 'tableHeader',+ TABLE_CELL: 'tableCell',+ FILE: 'file',} as const;export type TipTapNodeType =diff --git a/yarn.lock b/yarn.lockindex f463cfeb018..f443ffbb844 100644--- a/yarn.lock+++ b/yarn.lock@@ -4737,7 +4737,7 @@ __metadata:languageName: nodelinkType: hard-"@blocknote/core@npm:0.51.4, @blocknote/core@npm:^0.51.4":+"@blocknote/core@npm:0.51.4":version: 0.51.4resolution: "@blocknote/core@npm:0.51.4"dependencies:@@ -4813,25 +4813,6 @@ __metadata:languageName: nodelinkType: hard-"@blocknote/server-util@npm:^0.51.4":- version: 0.51.4- resolution: "@blocknote/server-util@npm:0.51.4"- dependencies:- "@blocknote/core": "npm:0.51.4"- "@blocknote/react": "npm:0.51.4"- "@tiptap/core": "npm:^3.13.0"- "@tiptap/pm": "npm:^3.13.0"- jsdom: "npm:^25.0.1"- y-prosemirror: "npm:^1.3.7"- y-protocols: "npm:^1.0.6"- yjs: "npm:^13.6.27"- peerDependencies:- react: ^18.0 || ^19.0 || >= 19.0.0-rc- react-dom: ^18.0 || ^19.0 || >= 19.0.0-rc- checksum: 10c0/421c693575b083300670a78f0b282d615a84d544debb7f1e0e78d03ad8c5c14dcd886ce3ff9cb0cd5f2a094607e5640351901d0299d23fbe095c538c6c7df414- languageName: node- linkType: hard-"@blocknote/xl-multi-column@npm:0.51.4":version: 0.51.4resolution: "@blocknote/xl-multi-column@npm:0.51.4"@@ -28867,7 +28848,7 @@ __metadata:languageName: nodelinkType: hard-"cssstyle@npm:^4.1.0, cssstyle@npm:^4.2.1":+"cssstyle@npm:^4.2.1":version: 4.3.1resolution: "cssstyle@npm:4.3.1"dependencies:@@ -29455,7 +29436,7 @@ __metadata:languageName: nodelinkType: hard-"decimal.js@npm:^10.4.3, decimal.js@npm:^10.5.0":+"decimal.js@npm:^10.5.0":version: 10.5.0resolution: "decimal.js@npm:10.5.0"checksum: 10c0/785c35279df32762143914668df35948920b6c1c259b933e0519a69b7003fc0a5ed2a766b1e1dda02574450c566b21738a45f15e274b47c2ac02072c0d1f3ac3@@ -34789,7 +34770,7 @@ __metadata:languageName: nodelinkType: hard-"https-proxy-agent@npm:^7.0.1, https-proxy-agent@npm:^7.0.2, https-proxy-agent@npm:^7.0.5, https-proxy-agent@npm:^7.0.6":+"https-proxy-agent@npm:^7.0.1, https-proxy-agent@npm:^7.0.2, https-proxy-agent@npm:^7.0.6":version: 7.0.6resolution: "https-proxy-agent@npm:7.0.6"dependencies:@@ -37633,40 +37614,6 @@ __metadata:languageName: nodelinkType: hard-"jsdom@npm:^25.0.1":- version: 25.0.1- resolution: "jsdom@npm:25.0.1"- dependencies:- cssstyle: "npm:^4.1.0"- data-urls: "npm:^5.0.0"- decimal.js: "npm:^10.4.3"- form-data: "npm:^4.0.0"- html-encoding-sniffer: "npm:^4.0.0"- http-proxy-agent: "npm:^7.0.2"- https-proxy-agent: "npm:^7.0.5"- is-potential-custom-element-name: "npm:^1.0.1"- nwsapi: "npm:^2.2.12"- parse5: "npm:^7.1.2"- rrweb-cssom: "npm:^0.7.1"- saxes: "npm:^6.0.0"- symbol-tree: "npm:^3.2.4"- tough-cookie: "npm:^5.0.0"- w3c-xmlserializer: "npm:^5.0.0"- webidl-conversions: "npm:^7.0.0"- whatwg-encoding: "npm:^3.1.1"- whatwg-mimetype: "npm:^4.0.0"- whatwg-url: "npm:^14.0.0"- ws: "npm:^8.18.0"- xml-name-validator: "npm:^5.0.0"- peerDependencies:- canvas: ^2.11.2- peerDependenciesMeta:- canvas:- optional: true- checksum: 10c0/6bda32a6dfe4e37a30568bf51136bdb3ba9c0b72aadd6356280404275a34c9e097c8c25b5eb3c742e602623741e172da977ff456684befd77c9042ed9bf8c2b4- languageName: node- linkType: hard-"jsdom@npm:^26.0.0":version: 26.1.0resolution: "jsdom@npm:26.1.0"@@ -41678,7 +41625,7 @@ __metadata:languageName: nodelinkType: hard-"nwsapi@npm:^2.2.12, nwsapi@npm:^2.2.16":+"nwsapi@npm:^2.2.16":version: 2.2.20resolution: "nwsapi@npm:2.2.20"checksum: 10c0/07f4dafa3186aef7c007863e90acd4342a34ba9d44b22f14f644fdb311f6086887e21c2fc15efaa826c2bc39ab2bc841364a1a630e7c87e0cb723ba59d729297@@ -43187,7 +43134,7 @@ __metadata:languageName: nodelinkType: hard-"parse5@npm:^7.0.0, parse5@npm:^7.1.2, parse5@npm:^7.2.1":+"parse5@npm:^7.0.0, parse5@npm:^7.2.1":version: 7.3.0resolution: "parse5@npm:7.3.0"dependencies:@@ -47113,13 +47060,6 @@ __metadata:languageName: nodelinkType: hard-"rrweb-cssom@npm:^0.7.1":- version: 0.7.1- resolution: "rrweb-cssom@npm:0.7.1"- checksum: 10c0/127b8ca6c8aac45e2755abbae6138d4a813b1bedc2caabf79466ae83ab3cfc84b5bfab513b7033f0aa4561c7753edf787d0dd01163ceacdee2e8eb1b6bf7237e- languageName: node- linkType: hard-"rrweb-cssom@npm:^0.8.0":version: 0.8.0resolution: "rrweb-cssom@npm:0.8.0"@@ -51112,8 +51052,6 @@ __metadata:"@aws-sdk/lib-storage": "npm:3.1001.0""@aws-sdk/s3-request-presigner": "npm:3.1001.0""@azure/msal-node": "npm:^5.2.3"- "@blocknote/core": "npm:^0.51.4"- "@blocknote/server-util": "npm:^0.51.4""@clickhouse/client": "npm:^1.18.1""@e2b/code-interpreter": "npm:^2.6.0""@envelop/core": "npm:4.0.3"