import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { optimizeImage } from 'wasm-image-optimization'; import LibDashStore from '../src/index.js'; import { BetterSqlite3Provider } from '../src/providers/sqlite3/index.js'; /** * Creates an isolated sqlite-backed store in a temp directory. * Call `cleanup()` in an `after()` hook. */ export async function createTestStore(prefix = 'dash-unit-') { const tempDir = mkdtempSync(join(tmpdir(), prefix)); const provider = new BetterSqlite3Provider({ filename: join(tempDir, 'test.db'), storageDir: join(tempDir, 'storage'), }); await provider.initialize(); const store = await new LibDashStore(provider); const cleanup = async () => { try { provider.db?.close?.(); } catch { // ignore } rmSync(tempDir, { recursive: true, force: true }); }; return { store, provider, tempDir, cleanup }; } let tenantSeq = 0; /** * Creates a google_auth user + company and selects it. * Returns everything a test typically needs. */ export async function createTenant(store, { name, email } = {}) { tenantSeq += 1; const googleAuthId = await store.google_auth.add(email ?? `tenant-${tenantSeq}@example.com`); const company = await store.company.create({ name: name ?? `Tenant ${tenantSeq} GmbH`, iso639: 'de', taxrate: 19, reducedtaxrate: 7, googleAuthId, }); await store.google_auth.setSelectedCompany(googleAuthId, company.id); return { googleAuthId, company, rootCategoryId: company.rootCategoryId }; } let articleSeq = 0; /** Creates an article under the tenant's root category (or `parentId`). */ export async function createArticle(store, tenant, overrides = {}) { articleSeq += 1; return store.article.createUnderParent({ googleAuthId: tenant.googleAuthId, parentId: overrides.parentId ?? tenant.rootCategoryId, name: overrides.name ?? `Article ${articleSeq}`, ...overrides, }); } /** Returns the first customer group id of the tenant (needed for entity.create). */ export async function firstCustomerGroupId(store, tenant) { const groups = await store.customergroup.list(tenant.googleAuthId); return groups[0].id; } /** Creates a customer entity. */ export async function createCustomer(store, tenant, name = 'Customer') { return store.entity.create(tenant.googleAuthId, { customergroupId: await firstCustomerGroupId(store, tenant), name, }); } /** Generates a small solid-color PNG buffer for image tests. */ export async function makePng({ width = 64, height = 48, r = 200, g = 30, b = 60 } = {}) { const svg = ``; const res = await optimizeImage({ image: svg, format: 'png' }); return Buffer.from(res.data); } export const isoNow = () => new Date().toISOString();