refactor(api): fix cyclic dependencies (#6809)

* refactor(api): defineConfig vitest, api-helpers, drop vite.api build

- Wrap api vitest.config with defineConfig for typing/IDE
- Add loot-core api-helpers, use in YNAB4/YNAB5 importers
- Remove vite.api.config, build-api, injected.js; simplify api package

* refactor(api): update package structure and build scripts

- Change main entry point and types definition paths in package.json to reflect new structure.
- Simplify build script by removing migration and default database copy commands.
- Adjust tsconfig.dist.json to maintain declaration directory.
- Add typings for external modules in a new typings.ts file.
- Update comments in schedules.ts to improve clarity and maintainability.

* chore(api): update dependencies and build configuration

- Replace tsc-alias with rollup-plugin-visualizer in package.json.
- Update build script to use vite for building the API package.
- Add vite configuration file for improved build process and visualization.
- Adjust tsconfig.dist.json to exclude additional configuration files from the build.

* fix(api): update visualizer output path in vite configuration

- Change the output filename for the visualizer plugin from 'dist/stats.json' to 'app/stats.json' to align with the new directory structure.

* refactor(api): streamline Vite configuration and remove vitest.config.ts

- Remove vitest.config.ts as its configuration is now integrated into vite.config.ts.
- Update vite.config.ts to include sourcemap generation and adjust CRDT path resolution.
- Modify vitest.setup.ts to correct the import path for the CRDT proto file.

* feat(api): enhance build scripts and add file system utilities

- Update build scripts in package.json to include separate commands for building node, migrations, and default database.
- Introduce a new file system utility module in loot-core to handle file operations such as reading, writing, and directory management.
- Implement error handling and logging for file operations to improve robustness.

* Refactor typecheck script in api package and enhance api-helpers with new schedule and rule update functions. The typecheck command was simplified by removing the strict check, and new API methods for creating schedules and updating rules were added to improve functionality.

* Refactor API integration in loot-core by removing api-helpers and directly invoking handlers. Update typecheck script in api package to include strict checks, and refine TypeScript configurations across multiple packages for improved type safety and build processes.

* Refactor imports and enhance code readability across multiple files in loot-core. Simplified import statements in the API and adjusted formatting in YNAB importers for consistency. Updated type annotations to improve type safety and maintainability.

* Refactor handler invocation in YNAB importers to use the new send function from main-app. This change improves code consistency and readability by standardizing the method of invoking handlers across different modules.

* Refactor schedule configuration in loot-core to enhance type safety by introducing a new ScheduleRuleOptions type. This change improves the clarity of the recurring schedule configuration and ensures better type checking for frequency and interval properties.

* Update TypeScript configuration in api package to include path mapping for loot-core. This change enhances module resolution and improves type safety by allowing direct imports from the loot-core source directory.

* Update TypeScript configuration in api package to reposition the typescript-strict-plugin entry. This change improves the organization of the tsconfig.json file while maintaining the existing path mapping for loot-core, ensuring consistent type checking across the project.

* Update TypeScript configurations across multiple packages to enable noEmit option. This change enhances build processes by preventing unnecessary output files during compilation. Additionally, remove the obsolete tsconfig.api.json file from loot-core to streamline project structure.

* Update TypeScript configuration in sync-server package to enable noEmit option. This change allows for the generation of output files during compilation, facilitating the build process.

* Update api package configuration to streamline build process and enhance type safety. Removed unnecessary build scripts, integrated vite-plugin-dts for type declaration generation, and added migration and default database copying functionality. Adjusted vitest setup to comment out CRDT proto file import for improved test isolation.

* Update TypeScript configurations in desktop-client and desktop-electron packages to enable noEmit option, allowing for output file generation during compilation. Additionally, add ts-strict-ignore comments in YNAB importers to suppress strict type checking, improving compatibility with embedded API usage.

* Refactor api package configuration to update type declaration paths and enhance build process. Changed type definitions reference in package.json, streamlined tsconfig.json exclusions, and added functionality to copy inlined types during the build. Removed obsolete vitest setup file for improved test isolation.

* Revert to solution without types

* Update TypeScript configuration in API package to use ES2022 module and bundler resolution. This change enhances compatibility with modern JavaScript features and improves the build process.

* Update yarn.lock and API package to enhance TypeScript build process and add new dependencies

* Refactor inline-loot-core-types script to streamline TypeScript declaration handling and improve output organization. Remove legacy code and directly copy loot-core declaration tree, updating index.d.ts to reference local imports.

* Add internal export to API and enhance Vite configuration for migration handling

* Update Vite configuration in API package to target Node 18, enhancing compatibility with the latest Node features.

* Enhance inline-loot-core-types script to improve TypeScript declaration handling by separating source and typings directories. Update the copy process to include emitted typings, ensuring no declarations are dropped and maintaining better organization of loot-core types.

* Enhance migration handling by allowing both .sql and .js files to be copied during the migration process. Refactor file system operations in loot-core to improve error handling and streamline file management, including new methods for reading, writing, and removing files and directories.

* Refactor rootPath determination in Electron file system module by removing legacy case for 'bundle.api.js'. This simplifies the path management for the Electron app.

* Update API tests to mock file system paths for migration handling and change Vite configuration to target Node 20 for improved compatibility.

* Add promise-retry dependency to loot-core package and update yarn.lock

* Fix lint

* Refactor build script order in package.json for improved execution flow

* Feedback: API changes for "internal"
This commit is contained in:
Matiss Janis Aboltins
2026-03-12 17:43:39 +00:00
committed by GitHub
parent d30162672c
commit 3a22f1a153
21 changed files with 842 additions and 238 deletions

View File

@@ -3,26 +3,18 @@ import type {
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
import { init as initLootCore } from 'loot-core/server/main';
import type { InitConfig, lib } from 'loot-core/server/main';
// oxlint-disable-next-line typescript/ban-ts-comment
// @ts-ignore: bundle not available until we build it
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
/** @deprecated Please use return value of `init` instead */
export let internal: typeof lib | null = null;
export async function init(config: InitConfig = {}) {
validateNodeVersion();
if (!globalThis.fetch) {
@@ -33,21 +25,19 @@ export async function init(config: InitConfig = {}) {
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
internal = await initLootCore(config);
return internal;
}
export async function shutdown() {
if (actualApp) {
if (internal) {
try {
await actualApp.send('sync');
await internal.send('sync');
} catch {
// most likely that no budget is loaded, so the sync failed
}
await actualApp.send('close-budget');
actualApp = null;
await internal.send('close-budget');
internal = null;
}
}

View File

@@ -1,7 +0,0 @@
// TODO: comment on why it works this way
export let send;
export function override(sendImplementation) {
send = sendImplementation;
}

View File

@@ -1,10 +1,29 @@
import * as fs from 'fs/promises';
import * as path from 'path';
import { vi } from 'vitest';
import type { RuleEntity } from 'loot-core/types/models';
import * as api from './index';
// In tests we run from source; loot-core's API fs uses __dirname (for the built dist/).
// Mock the fs so path constants point at loot-core package root where migrations live.
vi.mock(
'../loot-core/src/platform/server/fs/index.api',
async importOriginal => {
const actual = (await importOriginal()) as Record<string, unknown>;
const pathMod = await import('path');
const lootCoreRoot = pathMod.join(__dirname, '..', 'loot-core');
return {
...actual,
migrationsPath: pathMod.join(lootCoreRoot, 'migrations'),
bundledDatabasePath: pathMod.join(lootCoreRoot, 'default-db.sqlite'),
demoBudgetPath: pathMod.join(lootCoreRoot, 'demo-budget'),
};
},
);
const budgetName = 'test-budget';
global.IS_TESTING = true;

View File

@@ -7,6 +7,7 @@ import type {
APIScheduleEntity,
APITagEntity,
} from 'loot-core/server/api-models';
import { lib } from 'loot-core/server/main';
import type { Query } from 'loot-core/shared/query';
import type { ImportTransactionsOpts } from 'loot-core/types/api-handlers';
import type { Handlers } from 'loot-core/types/handlers';
@@ -16,15 +17,13 @@ import type {
TransactionEntity,
} from 'loot-core/types/models';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
return lib.send(name, args);
}
export async function runImport(

View File

@@ -10,27 +10,25 @@
"main": "dist/index.js",
"types": "@types/index.d.ts",
"scripts": {
"build:app": "yarn workspace loot-core build:api",
"build:crdt": "yarn workspace @actual-app/crdt build",
"build:node": "tsc && tsc-alias",
"build:migrations": "cp migrations/*.sql dist/migrations",
"build:default-db": "cp default-db.sqlite dist/",
"build": "yarn run clean && yarn run build:app && yarn run build:node && yarn run build:migrations && yarn run build:default-db",
"test": "yarn run clean && yarn run build:app && yarn run build:crdt && vitest --run",
"clean": "rm -rf dist @types",
"typecheck": "yarn build && tsc --noEmit && tsc-strict"
"build": "yarn workspace loot-core exec tsc && vite build && node scripts/inline-loot-core-types.mjs",
"test": "vitest --run",
"typecheck": "tsc --noEmit && tsc-strict"
},
"dependencies": {
"@actual-app/crdt": "workspace:^",
"better-sqlite3": "^12.6.2",
"compare-versions": "^6.1.1",
"loot-core": "workspace:^",
"node-fetch": "^3.3.2",
"uuid": "^13.0.0"
},
"devDependencies": {
"tsc-alias": "^1.8.16",
"rollup-plugin-visualizer": "^6.0.5",
"typescript": "^5.9.3",
"typescript-strict-plugin": "^2.4.4",
"vite": "^7.3.1",
"vite-plugin-dts": "^4.5.4",
"vite-plugin-peggy-loader": "^2.0.1",
"vitest": "^4.0.18"
},
"engines": {

View File

@@ -0,0 +1,60 @@
/**
* Post-build script: copies loot-core declaration tree into @types/loot-core
* and rewrites index.d.ts to reference it so the published package is self-contained.
* Run after vite build; requires loot-core declarations (yarn workspace loot-core exec tsc).
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const apiRoot = path.resolve(__dirname, '..');
const typesDir = path.join(apiRoot, '@types');
const indexDts = path.join(typesDir, 'index.d.ts');
const lootCoreDeclRoot = path.resolve(apiRoot, '../loot-core/lib-dist/decl');
const lootCoreDeclSrc = path.join(lootCoreDeclRoot, 'src');
const lootCoreDeclTypings = path.join(lootCoreDeclRoot, 'typings');
const lootCoreTypesDir = path.join(typesDir, 'loot-core');
function main() {
if (!fs.existsSync(indexDts)) {
console.error('Missing @types/index.d.ts; run vite build first.');
process.exit(1);
}
if (!fs.existsSync(lootCoreDeclSrc)) {
console.error(
'Missing loot-core declarations; run: yarn workspace loot-core exec tsc',
);
process.exit(1);
}
// Remove existing loot-core output (dir or legacy single file)
if (fs.existsSync(lootCoreTypesDir)) {
fs.rmSync(lootCoreTypesDir, { recursive: true });
}
const legacyDts = path.join(typesDir, 'loot-core.d.ts');
if (fs.existsSync(legacyDts)) {
fs.rmSync(legacyDts);
}
// Copy declaration tree: src (main exports) plus emitted typings so no declarations are dropped
fs.cpSync(lootCoreDeclSrc, lootCoreTypesDir, { recursive: true });
if (fs.existsSync(lootCoreDeclTypings)) {
fs.cpSync(lootCoreDeclTypings, path.join(lootCoreTypesDir, 'typings'), {
recursive: true,
});
}
// Rewrite index.d.ts: remove reference, point imports at local ./loot-core/
let indexContent = fs.readFileSync(indexDts, 'utf8');
indexContent = indexContent.replace(
/\/\/\/ <reference path="\.\/loot-core\.d\.ts" \/>\n?/,
'',
);
indexContent = indexContent
.replace(/'loot-core\//g, "'./loot-core/")
.replace(/"loot-core\//g, '"./loot-core/');
fs.writeFileSync(indexDts, indexContent, 'utf8');
}
main();

View File

@@ -5,8 +5,8 @@
// Using ES2021 because that's the newest version where
// the latest Node 16.x release supports all of the features
"target": "ES2021",
"module": "CommonJS",
"moduleResolution": "node10",
"module": "es2022",
"moduleResolution": "bundler",
"noEmit": false,
"declaration": true,
"declarationMap": true,
@@ -14,13 +14,9 @@
"rootDir": ".",
"declarationDir": "@types",
"tsBuildInfoFile": "dist/.tsbuildinfo",
"paths": {
// TEMPORARY
"loot-core/*": ["../loot-core/src/*"]
},
"plugins": [{ "name": "typescript-strict-plugin", "paths": ["."] }]
},
"references": [{ "path": "../crdt" }, { "path": "../loot-core" }],
"include": ["."],
"exclude": ["**/node_modules/*", "dist", "@types", "*.test.ts"]
"exclude": ["**/node_modules/*", "dist", "@types", "*.test.ts", "*.config.ts"]
}

2
packages/api/typings.ts Normal file
View File

@@ -0,0 +1,2 @@
declare module 'hyperformula/i18n/languages/enUS';
declare module '*.pegjs';

View File

@@ -1,6 +1,4 @@
// oxlint-disable-next-line typescript/ban-ts-comment
// @ts-ignore: bundle not available until we build it
import * as bundle from './app/bundle.api.js';
import { lib } from 'loot-core/server/main';
export const amountToInteger = bundle.lib.amountToInteger;
export const integerToAmount = bundle.lib.integerToAmount;
export const amountToInteger = lib.amountToInteger;
export const integerToAmount = lib.integerToAmount;

View File

@@ -0,0 +1,99 @@
import fs from 'fs';
import path from 'path';
import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';
import peggyLoader from 'vite-plugin-peggy-loader';
const lootCoreRoot = path.resolve(__dirname, '../loot-core');
const distDir = path.resolve(__dirname, 'dist');
const typesDir = path.resolve(__dirname, '@types');
function cleanOutputDirs() {
return {
name: 'clean-output-dirs',
buildStart() {
if (fs.existsSync(distDir)) fs.rmSync(distDir, { recursive: true });
if (fs.existsSync(typesDir)) fs.rmSync(typesDir, { recursive: true });
},
};
}
function copyMigrationsAndDefaultDb() {
return {
name: 'copy-migrations-and-default-db',
closeBundle() {
const migrationsSrc = path.join(lootCoreRoot, 'migrations');
const defaultDbPath = path.join(lootCoreRoot, 'default-db.sqlite');
if (!fs.existsSync(migrationsSrc)) {
throw new Error(`migrations directory not found at ${migrationsSrc}`);
}
const migrationsStat = fs.statSync(migrationsSrc);
if (!migrationsStat.isDirectory()) {
throw new Error(`migrations path is not a directory: ${migrationsSrc}`);
}
const migrationsDest = path.join(distDir, 'migrations');
fs.mkdirSync(migrationsDest, { recursive: true });
for (const name of fs.readdirSync(migrationsSrc)) {
if (name.endsWith('.sql') || name.endsWith('.js')) {
fs.copyFileSync(
path.join(migrationsSrc, name),
path.join(migrationsDest, name),
);
}
}
if (!fs.existsSync(defaultDbPath)) {
throw new Error(`default-db.sqlite not found at ${defaultDbPath}`);
}
fs.copyFileSync(defaultDbPath, path.join(distDir, 'default-db.sqlite'));
},
};
}
export default defineConfig({
ssr: { noExternal: true, external: ['better-sqlite3'] },
build: {
ssr: true,
target: 'node20',
outDir: distDir,
emptyOutDir: true,
sourcemap: true,
lib: {
entry: path.resolve(__dirname, 'index.ts'),
formats: ['cjs'],
fileName: () => 'index.js',
},
},
plugins: [
cleanOutputDirs(),
peggyLoader(),
dts({
tsconfigPath: path.resolve(__dirname, 'tsconfig.json'),
outDir: path.resolve(__dirname, '@types'),
rollupTypes: true,
}),
copyMigrationsAndDefaultDb(),
visualizer({ template: 'raw-data', filename: 'app/stats.json' }),
],
resolve: {
extensions: ['.api.ts', '.js', '.ts', '.tsx', '.json'],
alias: [
{
find: /^@actual-app\/crdt(\/.*)?$/,
replacement: path.resolve(__dirname, '../crdt/src') + '$1',
},
],
},
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
return type === 'stderr';
},
maxWorkers: 2,
},
});

View File

@@ -1,10 +0,0 @@
export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
return type === 'stderr';
},
maxWorkers: 2,
},
};

View File

@@ -1,11 +0,0 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")/.." || exit 1
ROOT="$(pwd -P)"
# Emit declarations to lib-dist/decl so api package (and tsc -b) can consume them
yarn tsc -p tsconfig.json
yarn vite build --config ./vite.api.config.ts
./bin/copy-migrations ../api

View File

@@ -55,7 +55,6 @@
"scripts": {
"build:node": "cross-env NODE_ENV=production vite build --config ./vite.desktop.config.ts",
"watch:node": "cross-env NODE_ENV=development vite build --config ./vite.desktop.config.ts --watch",
"build:api": "cross-env NODE_ENV=development ./bin/build-api",
"build:browser": "cross-env NODE_ENV=production ./bin/build-browser",
"watch:browser": "cross-env NODE_ENV=development ./bin/build-browser",
"generate:i18n": "i18next",
@@ -82,6 +81,7 @@
"md5": "^2.3.0",
"memoize-one": "^6.0.0",
"mitt": "^3.0.1",
"promise-retry": "^2.0.1",
"slash": "5.1.0",
"typescript": "^5.9.3",
"typescript-strict-plugin": "^2.4.4",
@@ -89,7 +89,6 @@
"uuid": "^13.0.0"
},
"devDependencies": {
"@actual-app/api": "workspace:^",
"@actual-app/crdt": "workspace:^",
"@swc/core": "^1.15.11",
"@types/adm-zip": "^0.5.7",

View File

@@ -1,2 +1,198 @@
// oxlint-disable-next-line no-restricted-imports
export * from './index.electron';
// @ts-strict-ignore
import * as fs from 'fs';
import * as path from 'path';
import promiseRetry from 'promise-retry';
import { logger } from '../log';
import type * as T from './index';
export { getDocumentDir, getBudgetDir, _setDocumentDir } from './shared';
export const init: typeof T.init = async () => {
// Nothing to do
};
export const getDataDir: typeof T.getDataDir = () => {
if (!process.env.ACTUAL_DATA_DIR) {
throw new Error('ACTUAL_DATA_DIR env variable is required');
}
return process.env.ACTUAL_DATA_DIR;
};
export const bundledDatabasePath: typeof T.bundledDatabasePath = path.join(
__dirname,
'default-db.sqlite',
);
export const migrationsPath: typeof T.migrationsPath = path.join(
__dirname,
'migrations',
);
export const demoBudgetPath: typeof T.demoBudgetPath = path.join(
__dirname,
'demo-budget',
);
export const join: typeof T.join = (...args: Parameters<typeof path.join>) =>
path.join(...args);
export const basename: typeof T.basename = filepath => path.basename(filepath);
export const listDir: typeof T.listDir = filepath =>
new Promise((resolve, reject) => {
fs.readdir(filepath, (err, files) => {
if (err) {
reject(err);
} else {
resolve(files);
}
});
});
export const exists: typeof T.exists = filepath =>
new Promise(resolve => {
fs.access(filepath, fs.constants.F_OK, err => {
return resolve(!err);
});
});
export const mkdir: typeof T.mkdir = filepath =>
new Promise((resolve, reject) => {
fs.mkdir(filepath, err => {
if (err) {
reject(err);
} else {
resolve(undefined);
}
});
});
export const size: typeof T.size = filepath =>
new Promise((resolve, reject) => {
fs.stat(filepath, (err, stats) => {
if (err) {
reject(err);
} else {
resolve(stats.size);
}
});
});
export const copyFile: typeof T.copyFile = (frompath, topath) => {
return new Promise<boolean>((resolve, reject) => {
const readStream = fs.createReadStream(frompath);
const writeStream = fs.createWriteStream(topath);
readStream.on('error', reject);
writeStream.on('error', reject);
writeStream.on('open', () => readStream.pipe(writeStream));
writeStream.once('close', () => resolve(true));
});
};
export const readFile: typeof T.readFile = (
filepath: string,
encoding: 'utf8' | 'binary' | null = 'utf8',
) => {
if (encoding === 'binary') {
// `binary` is not actually a valid encoding, you pass `null` into node if
// you want a buffer
encoding = null;
}
// `any` as cannot refine return with two function overrides
// oxlint-disable-next-line typescript/no-explicit-any
return new Promise<any>((resolve, reject) => {
fs.readFile(filepath, encoding, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
export const writeFile: typeof T.writeFile = async (filepath, contents) => {
try {
await promiseRetry(
(retry, attempt) => {
return new Promise((resolve, reject) => {
fs.writeFile(filepath, contents, 'utf8', err => {
if (err) {
logger.error(
`Failed to write to ${filepath}. Attempted ${attempt} times. Something is locking the file - potentially a virus scanner or backup software.`,
);
reject(err);
} else {
if (attempt > 1) {
logger.info(
`Successfully recovered from file lock. It took ${attempt} retries`,
);
}
resolve(undefined);
}
});
}).catch(retry);
},
{
retries: 20,
minTimeout: 100,
maxTimeout: 500,
factor: 1.5,
},
);
return undefined;
} catch (err) {
logger.error(`Unable to recover from file lock on file ${filepath}`);
throw err;
}
};
export const removeFile: typeof T.removeFile = filepath => {
return new Promise(function (resolve, reject) {
fs.unlink(filepath, err => {
return err ? reject(err) : resolve(undefined);
});
});
};
export const removeDir: typeof T.removeDir = dirpath => {
return new Promise(function (resolve, reject) {
fs.rmdir(dirpath, err => {
return err ? reject(err) : resolve(undefined);
});
});
};
export const removeDirRecursively: typeof T.removeDirRecursively =
async dirpath => {
if (await exists(dirpath)) {
for (const file of await listDir(dirpath)) {
const fullpath = join(dirpath, file);
if (fs.statSync(fullpath).isDirectory()) {
await removeDirRecursively(fullpath);
} else {
await removeFile(fullpath);
}
}
await removeDir(dirpath);
}
};
export const getModifiedTime: typeof T.getModifiedTime = filepath => {
return new Promise(function (resolve, reject) {
fs.stat(filepath, (err, stats) => {
if (err) {
reject(err);
} else {
resolve(new Date(stats.mtime));
}
});
});
};

View File

@@ -13,9 +13,6 @@ export { getDocumentDir, getBudgetDir, _setDocumentDir } from './shared';
let rootPath = path.join(__dirname, '..', '..', '..', '..');
switch (path.basename(__filename)) {
case 'bundle.api.js': // api bundle uses the electron bundle - account for its file structure
rootPath = path.join(__dirname, '..');
break;
case 'bundle.desktop.js': // electron app
rootPath = path.join(__dirname, '..', '..');
break;

View File

@@ -1,7 +1,5 @@
// @ts-strict-ignore
import './polyfills';
import * as injectAPI from '@actual-app/api/injected';
import * as asyncStorage from '../platform/server/asyncStorage';
import * as connection from '../platform/server/connection';
import * as fs from '../platform/server/fs';
@@ -126,8 +124,6 @@ handlers['app-focused'] = async function () {
handlers = installAPI(handlers) as Handlers;
injectAPI.override((name, args) => runHandler(app.handlers[name], args));
// A hack for now until we clean up everything
app.handlers = handlers;
app.combine(

View File

@@ -147,15 +147,29 @@ function checkDatabaseValidity(
appliedIds: number[],
available: string[],
): void {
for (let i = 0; i < appliedIds.length; i++) {
if (
i >= available.length ||
appliedIds[i] !== getMigrationId(available[i])
) {
logger.error('Database is out of sync with migrations:', {
if (appliedIds.length > available.length) {
logger.error(
'Database is out of sync with migrations (index past available):',
{
appliedIds,
available,
});
},
);
throw new Error('out-of-sync-migrations');
}
for (let i = 0; i < appliedIds.length; i++) {
if (appliedIds[i] !== getMigrationId(available[i])) {
logger.error(
'Database is out of sync with migrations (migration id mismatch):',
{
appliedIds,
available,
missing: available.filter(
m => !appliedIds.includes(getMigrationId(m)),
),
},
);
throw new Error('out-of-sync-migrations');
}
}

View File

@@ -1,58 +0,0 @@
import path from 'path';
import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig } from 'vite';
import peggyLoader from 'vite-plugin-peggy-loader';
export default defineConfig(({ mode }) => {
const outDir = path.resolve(__dirname, '../api/app');
const crdtDir = path.resolve(__dirname, '../crdt');
return {
mode,
ssr: { noExternal: true, external: ['better-sqlite3'] },
build: {
target: 'node18',
outDir,
emptyOutDir: false,
ssr: true,
lib: {
entry: path.resolve(__dirname, 'src/server/main.ts'),
formats: ['cjs'],
},
sourcemap: true,
rollupOptions: {
output: {
entryFileNames: 'bundle.api.js',
format: 'cjs',
name: 'api',
},
},
},
resolve: {
extensions: [
'.api.js',
'.api.ts',
'.api.tsx',
'.js',
'.ts',
'.tsx',
'.json',
],
alias: [
{
find: 'handlebars',
replacement: require.resolve('handlebars/dist/handlebars.js'),
},
{
find: /^@actual-app\/crdt(\/.*)?$/,
replacement: path.resolve(crdtDir, 'src') + '$1',
},
],
},
plugins: [
peggyLoader(),
visualizer({ template: 'raw-data', filename: `${outDir}/stats.json` }),
],
};
});