The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Alias native worker APIs onto window in front components (#24190)
Raphaël Bosiaa194c7f66c2
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdxindex 81b499a9863..0139436f6a1 100644--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx@@ -799,9 +799,14 @@ Elements can measure themselves: the host mirrors geometry into the sandbox, soPositioning from `getBoundingClientRect` now works, but anything watching size changes through `ResizeObserver` (recharts `ResponsiveContainer`, Floating UI's `autoUpdate`) still does not. Prefer CSS for layout anyway: your stylesheet reaches the real page, so flexbox, grid, `aspect-ratio`, `clamp()` and `@container` behave normally, with no frame lag.<Note>-`requestAnimationFrame`, `fetch`, `setTimeout` and `queueMicrotask` work without the `window.` prefix. Only `window.requestAnimationFrame(...)` and friends throw.+`requestAnimationFrame` works, with or without the `window.` prefix. Only Chrome runs a real animation frame inside a worker; Firefox and Safari get a 16 ms timer, so use it to defer a re-read past a write, not to drive an animation.</Note>+### Global scope++The worker's own natives are also aliased onto `window`, so they work with or without the `window.` prefix: `fetch`, `setTimeout`/`clearTimeout`, `setInterval`/`clearInterval`, `queueMicrotask`, `console`, `crypto`, `performance`, `structuredClone`, `btoa`/`atob`, `URL`/`URLSearchParams`, `AbortController`/`AbortSignal`, `Headers`/`Request`/`Response`, `Blob`, `File`, `FormData` and `TextEncoder`/`TextDecoder`.++### DOM accessA `ref` gives you a sandbox element, not an `HTMLElement`.@@ -829,6 +834,7 @@ Each element forwards its own properties to the host DOM (`href` on `a`, `src`/`Component CSS, whether from `import './styles.css'`, CSS-in-JS or a `style` element, is injected into the host page's `head` **unscoped**. So class names collide with Twenty's own (prefix them, and never write bare `div { ... }` selectors), and `@media` matches the browser window rather than your widget (use `@container` with your own `container-type`). Inline `style` props are unaffected.+### Storage and network`localStorage` and `sessionStorage` are provided by Twenty rather than the browser: the component runs in a worker at an opaque origin, so the host stores the values on your app's behalf. See [storage](#storage) for their scoping and limits. IndexedDB, cookies, the Cache API and `BroadcastChannel` remain unavailable. To persist state across devices, call a [logic function](/developers/extend/apps/logic/logic-functions) and use its [key-value store](/developers/extend/apps/logic/key-value-store).@@ -847,5 +853,5 @@ Component CSS, whether from `import './styles.css'`, CSS-in-JS or a `style` elem- **File contents.** An `input` of type `file` gives your handler file metadata only, not the bytes, so `FileReader` is not available. To upload a `Blob` your code already holds — e.g. one produced by `MediaRecorder` — use the `uploadFile` host function.- **Drag-and-drop payloads.** Drag events fire, but `event.dataTransfer` is `undefined`.-- **Node built-ins.** `fs`, `path` and `node:crypto` fail the build, so move that work into a [logic function](/developers/extend/apps/logic/logic-functions). Web Crypto, `fetch`, `TextEncoder` and `URL` are available.+- **Node built-ins.** `fs`, `path` and `node:crypto` fail the build, so move that work into a [logic function](/developers/extend/apps/logic/logic-functions). Web Crypto replaces `node:crypto`, and `fetch`, `TextEncoder` and `URL` are available too, see [global scope](#global-scope) — but nothing replaces `fs`: the sandbox has no filesystem.- **`iframe`** is always re-sandboxed without `allow-same-origin`, so an embed relying on its own session renders logged out. It has no `onLoad` either.diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/AnimationFrameFallbackIntervalMs.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/AnimationFrameFallbackIntervalMs.tsnew file mode 100644index 00000000000..d853f91efc3--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/AnimationFrameFallbackIntervalMs.ts@@ -0,0 +1 @@+export const ANIMATION_FRAME_FALLBACK_INTERVAL_MS = 16;diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/NativeFunctionWindowAliasNames.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/NativeFunctionWindowAliasNames.tsnew file mode 100644index 00000000000..6ca14504522--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/NativeFunctionWindowAliasNames.ts@@ -0,0 +1,12 @@+export const NATIVE_FUNCTION_WINDOW_ALIAS_NAMES = [+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ 'queueMicrotask',+ 'setTimeout',+ 'clearTimeout',+ 'setInterval',+ 'clearInterval',+ 'structuredClone',+ 'btoa',+ 'atob',+] as const;diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/NativeValueWindowAliasNames.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/NativeValueWindowAliasNames.tsnew file mode 100644index 00000000000..380b90a95e2--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/constants/NativeValueWindowAliasNames.ts@@ -0,0 +1,17 @@+export const NATIVE_VALUE_WINDOW_ALIAS_NAMES = [+ 'console',+ 'crypto',+ 'performance',+ 'AbortController',+ 'AbortSignal',+ 'Blob',+ 'File',+ 'FormData',+ 'Headers',+ 'Request',+ 'Response',+ 'TextDecoder',+ 'TextEncoder',+ 'URL',+ 'URLSearchParams',+] as const;diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installAnimationFrameFallback.test.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installAnimationFrameFallback.test.tsnew file mode 100644index 00000000000..4a0565b53cd--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installAnimationFrameFallback.test.ts@@ -0,0 +1,63 @@+import { installAnimationFrameFallback } from '../installAnimationFrameFallback';++describe('installAnimationFrameFallback', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it('should leave a native requestAnimationFrame alone', () => {+ const nativeRequest = jest.fn();+ const nativeCancel = jest.fn();+ const globalScope: Record<string, unknown> = {+ requestAnimationFrame: nativeRequest,+ cancelAnimationFrame: nativeCancel,+ };++ installAnimationFrameFallback(globalScope);++ expect(globalScope.requestAnimationFrame).toBe(nativeRequest);+ expect(globalScope.cancelAnimationFrame).toBe(nativeCancel);+ });++ it('should run the callback with a timestamp after one frame interval', () => {+ const globalScope: Record<string, unknown> = {};+ const frameCallback = jest.fn();++ installAnimationFrameFallback(globalScope);++ (globalScope.requestAnimationFrame as typeof requestAnimationFrame)(+ frameCallback,+ );++ jest.advanceTimersByTime(15);++ expect(frameCallback).not.toHaveBeenCalled();++ jest.advanceTimersByTime(1);++ expect(frameCallback).toHaveBeenCalledWith(expect.any(Number));+ });++ it('should cancel a pending callback through its handle', () => {+ const globalScope: Record<string, unknown> = {};+ const frameCallback = jest.fn();++ installAnimationFrameFallback(globalScope);++ const frameHandle = (+ globalScope.requestAnimationFrame as typeof requestAnimationFrame+ )(frameCallback);++ (globalScope.cancelAnimationFrame as typeof cancelAnimationFrame)(+ frameHandle,+ );++ jest.advanceTimersByTime(16);++ expect(frameCallback).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installFetchWindowAlias.test.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installFetchWindowAlias.test.tsnew file mode 100644index 00000000000..c6a8f3d6b3b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installFetchWindowAlias.test.ts@@ -0,0 +1,72 @@+import { installFetchWindowAlias } from '../installFetchWindowAlias';++describe('installFetchWindowAlias', () => {+ it('should delegate window.fetch to the fetch swapped in after install', async () => {+ const initialFetch = jest.fn().mockResolvedValue('initial');+ const polyfillWindow: Record<string, unknown> = {};+ const globalScope: Record<string, unknown> = {+ window: polyfillWindow,+ fetch: initialFetch,+ };++ installFetchWindowAlias(globalScope);++ const proxiedResponse = { status: 200 };+ const proxiedFetch = jest.fn().mockResolvedValue(proxiedResponse);+ globalScope.fetch = proxiedFetch;++ const windowFetch = polyfillWindow.fetch as typeof fetch;+ const response = await windowFetch('https://api.twenty.com/graphql', {+ method: 'POST',+ });++ expect(response).toBe(proxiedResponse);+ expect(proxiedFetch).toHaveBeenCalledWith(+ 'https://api.twenty.com/graphql',+ {+ method: 'POST',+ },+ );+ expect(initialFetch).not.toHaveBeenCalled();+ });++ it('should leave the global scope fetch untouched', () => {+ const initialFetch = jest.fn();+ const globalScope: Record<string, unknown> = {+ window: {},+ fetch: initialFetch,+ };++ installFetchWindowAlias(globalScope);++ expect(globalScope.fetch).toBe(initialFetch);+ });++ it('should reject with a TypeError when no global fetch exists at call time', async () => {+ const polyfillWindow: Record<string, unknown> = {};+ const globalScope: Record<string, unknown> = { window: polyfillWindow };++ installFetchWindowAlias(globalScope);++ const windowFetch = polyfillWindow.fetch as typeof fetch;++ await expect(windowFetch('https://api.twenty.com')).rejects.toThrow(+ TypeError,+ );+ });++ it('should leave a window fetch that is already defined untouched', () => {+ const existingWindowFetch = jest.fn();+ const polyfillWindow: Record<string, unknown> = {+ fetch: existingWindowFetch,+ };+ const globalScope: Record<string, unknown> = {+ window: polyfillWindow,+ fetch: jest.fn(),+ };++ installFetchWindowAlias(globalScope);++ expect(polyfillWindow.fetch).toBe(existingWindowFetch);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installNativeWindowAliases.test.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installNativeWindowAliases.test.tsnew file mode 100644index 00000000000..f1d2cf73cc2--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installNativeWindowAliases.test.ts@@ -0,0 +1,83 @@+import { installNativeWindowAliases } from '../installNativeWindowAliases';++describe('installNativeWindowAliases', () => {+ it('should bind native scheduling functions onto a distinct window', () => {+ const receivedThisValues: unknown[] = [];+ const globalScope: Record<string, unknown> = { window: {} };+ globalScope.queueMicrotask = function (+ this: unknown,+ microtaskCallback: () => void,+ ) {+ receivedThisValues.push(this);+ microtaskCallback();+ };+ globalScope.setTimeout = jest.fn();+ globalScope.clearTimeout = jest.fn();+ globalScope.setInterval = jest.fn();+ globalScope.clearInterval = jest.fn();++ installNativeWindowAliases(globalScope);++ const polyfillWindow = globalScope.window as Record<string, unknown>;+ const microtaskCallback = jest.fn();++ (polyfillWindow.queueMicrotask as (callback: () => void) => void)(+ microtaskCallback,+ );++ expect(microtaskCallback).toHaveBeenCalledTimes(1);+ expect(receivedThisValues).toEqual([globalScope]);+ expect(polyfillWindow.setTimeout).toEqual(expect.any(Function));+ expect(polyfillWindow.clearTimeout).toEqual(expect.any(Function));+ expect(polyfillWindow.setInterval).toEqual(expect.any(Function));+ expect(polyfillWindow.clearInterval).toEqual(expect.any(Function));+ });++ it('should alias namespaces and constructors by reference rather than binding them', () => {+ const abortControllerAlias = AbortController;+ const consoleAlias = { log: () => {} };+ const polyfillWindow: Record<string, unknown> = {};+ const globalScope: Record<string, unknown> = {+ window: polyfillWindow,+ AbortController: abortControllerAlias,+ console: consoleAlias,+ };++ installNativeWindowAliases(globalScope);++ expect(polyfillWindow.AbortController).toBe(abortControllerAlias);+ expect(polyfillWindow.console).toBe(consoleAlias);+ });++ it('should alias the performance object as-is', () => {+ const performanceAlias = { now: () => 42 };+ const polyfillWindow: Record<string, unknown> = {};+ const globalScope: Record<string, unknown> = {+ window: polyfillWindow,+ performance: performanceAlias,+ };++ installNativeWindowAliases(globalScope);++ expect(polyfillWindow.performance).toBe(performanceAlias);+ });++ it('should not overwrite properties a target already defines', () => {+ const existingPerformance = { now: () => 1 };+ const existingSetTimeout = jest.fn();+ const polyfillWindow: Record<string, unknown> = {+ performance: existingPerformance,+ setTimeout: existingSetTimeout,+ };+ const globalScope: Record<string, unknown> = {+ window: polyfillWindow,+ performance: { now: () => 2 },+ setTimeout: jest.fn(),+ };++ installNativeWindowAliases(globalScope);++ expect(polyfillWindow.performance).toBe(existingPerformance);+ expect(polyfillWindow.setTimeout).toBe(existingSetTimeout);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installWindowAliasesPolyfill.test.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installWindowAliasesPolyfill.test.tsnew file mode 100644index 00000000000..458e7b7402a--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/__tests__/installWindowAliasesPolyfill.test.ts@@ -0,0 +1,76 @@+import { Window } from '@remote-dom/polyfill';++import { installWindowAliasesPolyfill } from '@/polyfills/window-aliases/utils/installWindowAliasesPolyfill';++const createSandbox = () => {+ const polyfillWindow = new Window() as unknown as Record<string, unknown>;+ const globalScope: Record<string, unknown> = {+ window: polyfillWindow,+ console,+ crypto,+ performance,+ fetch: jest.fn(),+ queueMicrotask,+ setTimeout,+ clearTimeout,+ setInterval,+ clearInterval,+ structuredClone,+ btoa,+ atob,+ AbortController,+ Headers,+ URL,+ };++ installWindowAliasesPolyfill({ globalScope });++ return { globalScope, polyfillWindow };+};++describe('installWindowAliasesPolyfill', () => {+ it('should expose the aliased natives on the remote-dom window', () => {+ const { polyfillWindow } = createSandbox();++ for (const aliasName of [+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ 'fetch',+ 'console',+ 'crypto',+ 'performance',+ 'queueMicrotask',+ 'setTimeout',+ 'structuredClone',+ 'btoa',+ 'AbortController',+ 'Headers',+ 'URL',+ ]) {+ expect(polyfillWindow[aliasName]).toBeDefined();+ }+ });++ it('should reach the fetch swapped onto the global scope after install', async () => {+ const { globalScope, polyfillWindow } = createSandbox();++ const proxiedFetch = jest.fn().mockResolvedValue({ status: 200 });+ globalScope.fetch = proxiedFetch;++ await (polyfillWindow.fetch as typeof fetch)('https://api.twenty.com');++ expect(proxiedFetch).toHaveBeenCalledWith(+ 'https://api.twenty.com',+ undefined,+ );+ expect(proxiedFetch.mock.contexts[0]).toBe(globalScope);+ });++ it('should not overwrite the properties the remote-dom window already owns', () => {+ const { polyfillWindow } = createSandbox();++ expect(polyfillWindow.window).toBe(polyfillWindow);+ expect(polyfillWindow.self).toBe(polyfillWindow);+ expect(polyfillWindow.document).toBeDefined();+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installAnimationFrameFallback.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installAnimationFrameFallback.tsnew file mode 100644index 00000000000..dcdfd160af8--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installAnimationFrameFallback.ts@@ -0,0 +1,20 @@+import { isFunction } from '@sniptt/guards';++import { ANIMATION_FRAME_FALLBACK_INTERVAL_MS } from '@/polyfills/window-aliases/constants/AnimationFrameFallbackIntervalMs';++export const installAnimationFrameFallback = (+ globalScope: Record<string, unknown>,+): void => {+ if (isFunction(globalScope.requestAnimationFrame)) {+ return;+ }++ globalScope.requestAnimationFrame = (callback: FrameRequestCallback) =>+ setTimeout(+ () => callback(performance.now()),+ ANIMATION_FRAME_FALLBACK_INTERVAL_MS,+ );+ globalScope.cancelAnimationFrame = (+ frameHandle: ReturnType<typeof setTimeout>,+ ) => clearTimeout(frameHandle);+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installFetchWindowAlias.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installFetchWindowAlias.tsnew file mode 100644index 00000000000..8f3e580cde1--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installFetchWindowAlias.ts@@ -0,0 +1,29 @@+import { isFunction } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++import { resolvePolyfillWindow } from '@/polyfills/utils/resolvePolyfillWindow';++export const installFetchWindowAlias = (+ globalScope: Record<string, unknown>,+): void => {+ const delegateToCurrentGlobalFetch = (+ input: RequestInfo | URL,+ init?: RequestInit,+ ): Promise<Response> => {+ const currentGlobalFetch = globalScope.fetch;++ if (!isFunction(currentGlobalFetch)) {+ return Promise.reject(+ new TypeError('fetch is not available in this environment'),+ );+ }++ return currentGlobalFetch.call(globalScope, input, init);+ };++ const polyfillWindow = resolvePolyfillWindow(globalScope);++ if (isDefined(polyfillWindow) && !('fetch' in polyfillWindow)) {+ polyfillWindow.fetch = delegateToCurrentGlobalFetch;+ }+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installNativeWindowAliases.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installNativeWindowAliases.tsnew file mode 100644index 00000000000..f6e5583b51e--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installNativeWindowAliases.ts@@ -0,0 +1,36 @@+import { isFunction } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++import { resolvePolyfillWindow } from '@/polyfills/utils/resolvePolyfillWindow';+import { NATIVE_FUNCTION_WINDOW_ALIAS_NAMES } from '@/polyfills/window-aliases/constants/NativeFunctionWindowAliasNames';+import { NATIVE_VALUE_WINDOW_ALIAS_NAMES } from '@/polyfills/window-aliases/constants/NativeValueWindowAliasNames';++export const installNativeWindowAliases = (+ globalScope: Record<string, unknown>,+): void => {+ const polyfillWindow = resolvePolyfillWindow(globalScope);++ if (!isDefined(polyfillWindow)) {+ return;+ }++ for (const aliasName of NATIVE_FUNCTION_WINDOW_ALIAS_NAMES) {+ const nativeFunction = globalScope[aliasName];++ if (aliasName in polyfillWindow || !isFunction(nativeFunction)) {+ continue;+ }++ polyfillWindow[aliasName] = nativeFunction.bind(globalScope);+ }++ for (const aliasName of NATIVE_VALUE_WINDOW_ALIAS_NAMES) {+ const nativeValue = globalScope[aliasName];++ if (aliasName in polyfillWindow || !isDefined(nativeValue)) {+ continue;+ }++ polyfillWindow[aliasName] = nativeValue;+ }+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installWindowAliasesPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installWindowAliasesPolyfill.tsnew file mode 100644index 00000000000..d444b847e5d--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/window-aliases/utils/installWindowAliasesPolyfill.ts@@ -0,0 +1,15 @@+import { installAnimationFrameFallback } from '@/polyfills/window-aliases/utils/installAnimationFrameFallback';+import { installFetchWindowAlias } from '@/polyfills/window-aliases/utils/installFetchWindowAlias';+import { installNativeWindowAliases } from '@/polyfills/window-aliases/utils/installNativeWindowAliases';++type InstallWindowAliasesPolyfillInput = {+ globalScope: Record<string, unknown>;+};++export const installWindowAliasesPolyfill = ({+ globalScope,+}: InstallWindowAliasesPolyfillInput): void => {+ installAnimationFrameFallback(globalScope);+ installNativeWindowAliases(globalScope);+ installFetchWindowAlias(globalScope);+};diff --git a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.tsindex 0c09f160259..ce8fc69f691 100644--- a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts+++ b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts@@ -23,6 +23,7 @@ import { installMediaCapturePolyfills } from '@/polyfills/media/utils/installMedimport { frontComponentStorageBridges } from '@/polyfills/storage/states/frontComponentStorageBridges';import { toGlobalScopeRecord } from '@/polyfills/utils/toGlobalScopeRecord';import { installStorageBridge } from '@/polyfills/storage/utils/installStorageBridge';+import { installWindowAliasesPolyfill } from '@/polyfills/window-aliases/utils/installWindowAliasesPolyfill';import { exposeGlobals } from '@/utils/exposeGlobals';import { installStylePropertyOnRemoteElements } from '@/remote/elements/utils/installStylePropertyOnRemoteElements';import { patchRemoteElementAttributes } from '@/remote/elements/utils/patchRemoteElementAttributes';@@ -62,6 +63,10 @@ installWindowGeometryPolyfill({geometryStore: workerGeometryStore,});+installWindowAliasesPolyfill({+ globalScope: toGlobalScopeRecord(globalThis),+});+installStorageBridge({globalScope: toGlobalScopeRecord(globalThis),storageBridges: frontComponentStorageBridges,