Skip to content

AI-native design editor. Open-source Figma alternative.

2.6 KB
Raw Blame
import { describe, expect, test, vi } from 'bun:test'
import { readFileSync } from 'node:fs'

import {
  createMemoryLocalCanvasStore,
  resetLocalCanvasStoreForTests
} from '@/app/storage/local-store'
import {
  persistStorageCanvasLocally,
  seedStorageCanvasFromRemote
} from '@/app/storage/sync/persist'

describe('local-first storage persistence', () => {
  test('writes document bytes before enqueueing remote synchronization', async () => {
    const store = createMemoryLocalCanvasStore()
    const observations: string[] = []
    const enqueueCanvas = vi.fn(async (canvasId: string, revision: number) => {
      const bytes = await store.readFig(canvasId)
      observations.push(`${revision}:${bytes?.join(',')}`)
    })

    const result = await persistStorageCanvasLocally(
      {
        providerId: 's3-compatible',
        canvasId: 'canvas-1',
        name: 'Stored design',
        figBytes: new Uint8Array([1, 2, 3])
      },
      { store, enqueueCanvas }
    )

    expect(result.revision).toBe(1)
    expect(observations).toEqual(['1:1,2,3'])
    expect(await store.getMeta('canvas-1')).toMatchObject({
      name: 'Stored design',
      syncStatus: 'pending',
      providerId: 's3-compatible'
    })
  })

  test('stores the embedded preview with the document', async () => {
    const store = createMemoryLocalCanvasStore()
    const enqueueCanvas = vi.fn(() => Promise.resolve())
    const figBytes = new Uint8Array(readFileSync('tests/fixtures/gold-preview.fig'))

    await persistStorageCanvasLocally(
      {
        providerId: 's3-compatible',
        canvasId: 'canvas-preview',
        name: 'Preview design',
        figBytes
      },
      { store, enqueueCanvas }
    )

    const thumbnail = await store.readThumb('canvas-preview')
    expect(thumbnail?.byteLength).toBeGreaterThan(0)
    expect(thumbnail?.subarray(0, 8)).toEqual(
      new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
    )
  })

  test('keeps the preview of a downloaded document', async () => {
    const store = createMemoryLocalCanvasStore()
    resetLocalCanvasStoreForTests(store)
    try {
      await seedStorageCanvasFromRemote({
        providerId: 'cloud',
        canvasId: 'canvas-downloaded',
        name: 'Downloaded design',
        updatedAt: '2026-10-19T00:00:00.000Z',
        figBytes: new Uint8Array(readFileSync('tests/fixtures/gold-preview.fig'))
      })
      const thumbnail = await store.readThumb('canvas-downloaded')
      expect(thumbnail?.subarray(0, 8)).toEqual(
        new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
      )
    } finally {
      resetLocalCanvasStoreForTests()
    }
  })
})