@x-tech-laboratories/x-app 0.101.0 → 0.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,10 +9,11 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
9
9
 
10
10
  | Import | What it holds |
11
11
  | ---------------------------------------- | ----------------------------------------------------------------------------- |
12
- | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store`, `needs_upgrade`, `bind_methods` recording versions and announcing writes, `is_read_only`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. |
13
- | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts, the calls, OpenAPI, MCP, the server's backups and its sync peer; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; `build_server`, `start_daemon`, `open_app_database` and `register_app_calls` for tests and apps that add their own. |
12
+ | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. |
13
+ | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. |
14
+ | `app/services` | An app's own work beside its calls, run by both hosts: `StartServices` gets a `HostContext` (`kind`, `database()`, `profile`, `device_name`, the server's raw `config`, `plugins_folder`, `declared_file` from `<PREFIX>_DECLARED_FILE` or `/etc/<id>/declared.json`, `announce`, `emit(event, data)` for the page's `on_event`, `side_database(name)` for a never-backed-up file such as `<base>-index.db`, `back_up`) and returns `HostServices` (`before_restore`, `after_restore`, `stop`), stopped before sync and the database. |
14
15
  | `app/desktop`, `app/preload` | `run_desktop(app, electron, { main_dir })`: Electron's main process as a portal onto this computer's daemon or a server, with the window, the login entry, a second launch and `--daemon`; `run_preload(app, electron)` puts every bridge on the page. Electron is handed in, so neither imports it. |
15
- | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. |
16
+ | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. |
16
17
  | `config/vite`, `config/electron_vite`, `config/vitest`, `config/tsconfig/*.json` | An X-app's configs as presets: `web_vite_config({ port })` and `android_vite_config()` for the page, `desktop_vite_config()` for electron-vite's window, daemon, preload and page, `vitest_config()` for tests in `tests/` in UTC with coverage of `src/` to the terminal, merged with the app's own floor so `autoUpdate` still raises it, and `base`, `node`, `web` and `tests` tsconfigs to extend. |
17
18
  | `app_new` | The `x-app-new <X-Name>` command: a new X-app's files written once, laid out as the Application Standard asks, on the base app, the presets, X-App's Nix lib and its CI actions, with an example notes feature; `--port`, `--folder`, `--no-desktop` and `--no-android`. |
18
19
  | `durations` | `parse_duration` for settings such as `"2h30m"`, `format_duration` in months down to seconds and "less than a second" below one, `format_age`, and `format_clock` for a playing time such as `"3:07"`, with `{ hours: "always" }` writing `"0:03:07"` so a column of times lines up and `empty` for no time. |
@@ -31,6 +32,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
31
32
  | `i18n` | Words in the reader's language: `create_translator` looks each key up in catalogs in turn, so a missing translation falls back to the next, with `{name}` placeholders filled; `merge_messages`; `best_locale`, the available locale that best fits the reader's preferred ones, an exact tag before the same language; `text_direction` for the `dir` attribute. |
32
33
  | `sql` | `SqlDatabase`, the part of a synchronous SQLite connection the apps use, met by node:sqlite and by `web/sqlite_wasm`; `in_transaction`, and `migrate`, each step once in its own transaction, through `user_version` or, with an `owner` such as a feature or plugin, its own row in `schema_versions`. |
33
34
  | `settings` | An app's settings feature: one synced `settings (key, value)` table of JSON values, the same table and first step (`settings_migration` under the owner `"settings"`) every app already ran. Each feature declares a `SettingSpec` per key (`default`, `user_only`, `local` for this device alone, `secret` for another service's key, or its own `hide` and `keep`), `settings_of` giving every key of a defaults table the same spec; `create_settings_store(tables, { app })` merges them, refusing a key declared twice, and gives the migration, the synced table entry with its `local_keys`, `defaults`, the `user_only` set, `is_user_only_call` for `page_only_calls` (a user-only write, an import holding one, an export with secrets), `is_device_only` for `register_sync_routes`, `value_of`, and `get_settings`, `set_setting`, `export_settings` and `import_settings` with their api specs. Secrets read as `hidden_secret` and are kept when it comes back; the settings file is the standard's `{ app, kind: "settings", version, exported_at, settings }`, an import ignoring unknown keys and those of one device. `read_setting`, `write_setting` and `read_stored_settings` reach rows directly. No `node:` or DOM imports. |
35
+ | `caller` | Who is making the call in hand: `as_caller("page" \| "program" \| "engine", work)` around a call's synchronous part, `current_caller()` read by a store, and `caller_of(request)` (a token is a program). |
34
36
  | `api_spec` | An app's calls described once for other programs: `ApiSpec` gives each method its words and a JSON Schema per argument, so a method without one fails to compile; `input_schema` takes the arguments as one object, `positional_args` puts named arguments back in the method's order from a spec or any `NamedParams`, `openapi_document` writes an OpenAPI 3.1 document with one POST per call, and `route_openapi_document` one for REST routes such as `server/mcp`'s `route_tools` serves, each under its own path and verb with its path, query and body arguments; `check_known_ids` refuses a call naming an id that does not exist, such as "no such track a1", before it acts, `unknown_ids` lists them, and `keep_known_ids` cuts a remembered list, such as picked columns, down to the ids that still exist. A spec marked `page_only: true` is a call only the user may make at the app's own page (a signed-in browser, or a desktop window through its daemon's socket), such as approving what an assistant proposed: `page_only_calls(api, { rule?, refusal? })` gives the `PageOnlyCalls` the other modules take (`is_page_only(method)` for the marks, `is_page_only_call(method, args)` adding the app's `rule(method, args)` such as a write to some settings, `is_page_only_request(method, body)` for arguments as a list or by name, unchecked so a call with wrong names is left to refuse them itself, and the `refusal` text, `default_page_only_refusal` unless set), and both OpenAPI documents mark such a call with `x-page-only: true` and a 403. |
35
37
  | `filter`, `filter_sql` | Filters as one JSON tree of conditions under and, or and not, over fields the app lists in a catalogue (`define_catalogue`): a column, an SQL expression over the row, a related table matched when any of its rows matches, a set of values in a link table, kept as they are or once in a table of their own, or a `custom` field; tables and columns named as text or as the Drizzle schema's own objects. `compile_filter` makes one parameterised query for any `SqlDatabase` (`query_rows`), missing values last whichever way it sorts and ties broken by id so pages never shift, and a `random` sort key's whole-number `seed` giving the same shuffle each time, in SQL and in memory (`shuffle_position`); `compile_group_by` counts and sums each value of a field for panes; `evaluate` and `select_ids` check records in memory and `sort_records` sorts them, with exactly the same answers and order, which a property test holds them to; text, number, set and date operators, `top` and `bottom`, `in_last` in milliseconds, seconds or ISO dates, `in_filter` for a saved filter with `find_cycle`, the app's own `operators` such as full-text search, `regexp_matches` for the REGEXP a `regex` calls, and `FilterStack`, the removable chips a view shows. |
36
38
  | `filter_query` | `parse_filter_query`: search text such as `artist:beatles rating:>3 year:1965..1970 -live played:<30d` read into one filter over the fields the app lists (text, set, number or date, each with the names users type), so one search box serves every field. A text field takes `:` for contains, `=` for exact, `a,b` for either and `/pattern/` (matched with case, as `regex` is); a set field finds its listed values whatever their case; numbers take `>`, `>=`, `<`, `<=` and `a..b` through the field's own `parse_number`, such as stars into a rating; dates take `<30d` and `>6m` (h, d, w, m, y) and whole years, months or days such as `2024-03`, in the field's clock. A leading `-` leaves a term out. Each term comes back with where it is, its filter and a label for a chip, and `without_term` takes one out of the text; anything not readable as a field's condition is searched as words through the app's own text filter, never an error. |
@@ -95,7 +97,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
95
97
  | `server/backup_routes`, `web/backups` | A server's backups for the page's `BackupSettings`: `register_backup_routes` serves the list, backing up now, the daily schedule, restoring and deleting, with the schedule in a JSON file through `json_backup_schedule`; `backup_client` is the page's side. |
96
98
  | `server/sign_in`, `server/login_page` | `register_token_sign_in`: a server with one secret signs browsers in on its own login page, keeps them in by an HMAC-derived cookie, takes the secret as a bearer header, waits after a wrong try, answers 429 with Retry-After once an address has `address_tries_allowed` (20) wrong tries in `address_try_window_seconds` (300), on the login page or as a bearer header on a guarded path, the right ones not counted and a request without one never, and turns the rest away (401 in text or JSON under the API prefix, 303 to the login page elsewhere, with open paths); `register_sign_in_guard` is the turning-away alone, for an app with its own sessions, and given `address_tries` it counts a bearer header that does not sign in against that `AttemptLimit`. Both judge the path as the router reads it, count any route matched under the API prefix as the API, and answer 400 to a path that reads two ways (see `server/request_path`). |
97
99
  | `server/request_path` | `path_of`: a request's path as Fastify's router reads it (escapes decoded as it decodes them, its semicolon, trailing-slash, duplicate-slash and case options followed); `route_of`: the matched route's pattern; `is_plain_path`: false for a path that reads two ways (an escaped letter, digit or `-._~`, a `#`, a target not starting with `/`, an empty, `.` or `..` segment, or a path not beginning as its route does), which the sign-in guards refuse. Escapes such as `%20` and `%2F` stay allowed. |
98
- | `server/account_store` | `AccountStore`: users with the app's ordered roles and its own access rules, checked by `check_access`, the accounts file's users declared at the highest role, second factor with recovery codes, sessions and tokens, all in the app's SQLite database under `account_*` tables. Request handlers call `authenticate_async`, `change_password_async`, `create_user_async` and `update_user_async`, which hash in `password_hashes` (`shared_password_hashes` unless set); the synchronous ones stay for scripts and tests. A user gets `secret_tries_allowed` (5) wrong second-factor or recovery codes, signing in or turning the second factor off, in `secret_try_window_seconds` (300), and as many wrong current passwords apart from those, before waiting: `authenticate` then answers `retry_after_seconds` and the others throw a 429 `AccountError` carrying it. `token_scopes` names the narrower tokens the app offers beside full and read-only ones, such as `{ add_items: { label: "Add items", hint, calls: ["add_item"] } }`: a token made with `create_token(owner, { name, read_only, scope })` reads as a read-only one does and may also make its scope's calls. A token lasts `days` when given; `longest_token_days` caps that and is how long a token lasts without it, and an ended token no longer signs in. Each token has a `kind`: `device` when the device sign-in made it (`create_token(..., { kind: "device" })`, always a full token), `program` for one made on the account page; a full, unscoped token made before kinds were kept counts as a device, so no device is cut off, and the token lists show a device chip so a program's token from then can be revoked. |
100
+ | `server/account_store` | `AccountStore`: users with the app's ordered roles and its own access rules, checked by `check_access`, the accounts file's users declared at the highest role, second factor with recovery codes, sessions and tokens, all in the app's SQLite database under `account_*` tables. `move_accounts(from, to)` moves them, as they are, out of an app's own database into their own once, and `holds_accounts` says whether a database keeps them. Request handlers call `authenticate_async`, `change_password_async`, `create_user_async` and `update_user_async`, which hash in `password_hashes` (`shared_password_hashes` unless set); the synchronous ones stay for scripts and tests. A user gets `secret_tries_allowed` (5) wrong second-factor or recovery codes, signing in or turning the second factor off, in `secret_try_window_seconds` (300), and as many wrong current passwords apart from those, before waiting: `authenticate` then answers `retry_after_seconds` and the others throw a 429 `AccountError` carrying it. `token_scopes` names the narrower tokens the app offers beside full and read-only ones, such as `{ add_items: { label: "Add items", hint, calls: ["add_item"] } }`: a token made with `create_token(owner, { name, read_only, scope })` reads as a read-only one does and may also make its scope's calls. A token lasts `days` when given; `longest_token_days` caps that and is how long a token lasts without it, and an ended token no longer signs in. Each token has a `kind`: `device` when the device sign-in made it (`create_token(..., { kind: "device" })`, always a full token), `program` for one made on the account page; a full, unscoped token made before kinds were kept counts as a device, so no device is cut off, and the token lists show a device chip so a program's token from then can be revoked. |
99
101
  | `server/account_sign_in` | `register_accounts`: the standard sign-in. A name and password (then the code when the user has a second factor), single sign-on or a trusted proxy opens a session kept in the database; "Keep me signed in" unticked ends it with the browser, ticked keeps it until revoked, both bounded by `session_seconds` and `remembered_seconds`. One name from one address gets `tries_allowed` (5) tries in `try_window` ("5 minutes"), and one address gets `address_tries_allowed` (20) failing or running sign-ins in `address_try_window_seconds` (300) whatever names it gives, a right password not counted, with each wrong bearer token on a guarded path counted in the same limit and a right one refused too once it is used up; either answers 429 `{ error }` with Retry-After, the same for a name that exists and one that does not, and a code refused by the store's own limit adds `code_needed` (see [Accounts](#accounts)). `second_factor_from` names the lowest role that must use a second factor: until such a user sets one up, their session only reads, signs out and sets up the second factor or password, and cannot make tokens or sign in devices; `/api/me` says so with `second_factor_needed`. A device signs in with `device` and gets a token of kind `device` instead; a request's `viewer.token_kind` says which kind of token it came with (a declared token's is `program`), and `is_user_or_device(viewer)` whether it is the user at the page or on one of their devices rather than a program. It also serves the account routes (password, second factor, sessions, tokens), the admin's users and tokens, and checks each app route, and any `guarded_paths` outside the API such as `/metrics`, against `needed(method, path, route)`, which gets the path as the router reads it and the matched route's pattern (such as `/api/builds/:id`, or null); `open_prefixes` leaves routes that check their own credentials, such as a push URL, open; a read-only token only reads, except on `read_only_paths` such as `/api/mcp` that keep it to reading themselves. Given `call_of` (such as `calls_under("/api/call")` for a call table) and `is_read_only`, a read-only token may also POST the calls that only read, and a scoped token its scope's calls, on the API as over MCP; `GET <api>/account/token_scopes` lists the scopes for the token form. Given `call_of` and `page_only` (from `api_spec`'s `page_only_calls`), every token, a device's included, is refused the calls only the user at the page may make, by their marks before the body is read and by the app's rule once it is; a session or the trusted proxy makes them. |
100
102
  | `server/account_prefs` | Each signed-in user's own preferences kept on the server, so they follow the user between devices, such as their dashboards: `register_accounts` given `prefs: { keys, largest_bytes }` serves `GET` and `PUT <api>/account/prefs/<key>` (`{ value }` in, `{ key, value, changed_epoch }` out, a null value and time when none is kept), each key the app allows with a check that hands back the value to keep or throws, an unknown key refused (404), a stored value its check no longer passes read as none, a value over `largest_bytes` (`default_largest_pref_bytes`, 256 KB) refused (413); a user only reaches their own, a token may read them but only a full one write, a read-only token or a session waiting for its second factor only reads, and a token from the config has none. They live in `account_prefs`, one row per user and key, and go with the user; `read_account_pref` and `write_account_pref` do the same from the app's own code. |
101
103
  | `server/totp`, `server/oidc` | Authenticator-app codes (RFC 6238) and their `otpauth://` links; `OidcClient`, single sign-on by the code flow with PKCE and a checked ID token, set up from `<PREFIX>_OIDC_*` by `oidc_from_environment`. |
@@ -1,4 +1,5 @@
1
1
  import type { App } from "./define.ts";
2
+ import { type StartServices } from "./services.ts";
2
3
  export interface DaemonOptions {
3
4
  database_path: string;
4
5
  socket_path: string;
@@ -6,9 +7,13 @@ export interface DaemonOptions {
6
7
  unused_exit_ms?: number;
7
8
  unused_check_ms?: number;
8
9
  default_peer_port?: number;
10
+ services?: StartServices;
11
+ declared_file?: string;
9
12
  }
10
13
  export interface Daemon {
11
14
  shut_down: () => Promise<void>;
12
15
  }
13
16
  export declare function start_daemon(app: App, options: DaemonOptions): Promise<Daemon | null>;
14
- export declare function run_daemon(app: App, env?: NodeJS.ProcessEnv): Promise<void>;
17
+ export declare function run_daemon(app: App, env?: NodeJS.ProcessEnv, extra?: {
18
+ services?: StartServices;
19
+ }): Promise<void>;
@@ -14,6 +14,7 @@ import { register_error_replies, register_lenient_json_body } from "../server/re
14
14
  import { file_sync_storage } from "../sync_file_storage.js";
15
15
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
16
16
  import { keep_listening_for_peers } from "../sync_peer_listening.js";
17
+ import { declared_file_of, no_services, side_databases } from "./services.js";
17
18
  import { read_desktop_settings } from "./protocol.js";
18
19
  import { call_body_limit, open_app_database, register_app_calls } from "./server.js";
19
20
  // ── Daemon ───────────────────────────────────────────────────────────────────
@@ -72,12 +73,16 @@ export async function start_daemon(app, options) {
72
73
  // ── Lifecycle ──────────────────────────────────────────────────────
73
74
  let stopping = null;
74
75
  let unused_timer;
76
+ const sides = side_databases(database_path);
77
+ let services = no_services;
75
78
  function shut_down() {
76
79
  stopping ??= (async () => {
77
80
  clearInterval(unused_timer);
81
+ await services.stop();
78
82
  sync.stop();
79
83
  await daemon.close();
80
84
  await listening.stop();
85
+ sides.close_all();
81
86
  opened.close();
82
87
  options.on_stopped();
83
88
  })();
@@ -96,6 +101,22 @@ export async function start_daemon(app, options) {
96
101
  }
97
102
  await listening.start();
98
103
  sync.start();
104
+ if (options.services) {
105
+ services = await options.services({
106
+ kind: "desktop",
107
+ database: opened.database,
108
+ profile,
109
+ device_name: `${app.name} on ${hostname()}`,
110
+ config: {},
111
+ plugins_folder: join(profile, "plugins"),
112
+ declared_file: options.declared_file ?? `/etc/${app.id}/declared.json`,
113
+ announce: (client_id) => changes.announce_change(client_id),
114
+ emit: (event, data) => changes.send(JSON.stringify(data), { event }),
115
+ side_database: sides.open,
116
+ back_up: opened.back_up,
117
+ });
118
+ opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
119
+ }
99
120
  // Without "Keep running in the background", the daemon stops a while after its last window has gone.
100
121
  let unused_since = Date.now();
101
122
  unused_timer = setInterval(() => {
@@ -109,7 +130,7 @@ export async function start_daemon(app, options) {
109
130
  // ── Running ──────────────────────────────────────────────────────────────────
110
131
  // Starts the daemon on the database and socket the window names in <PREFIX>_DB and <PREFIX>_SOCKET, and ends the
111
132
  // process once it stops.
112
- export async function run_daemon(app, env = process.env) {
133
+ export async function run_daemon(app, env = process.env, extra = {}) {
113
134
  const database_path = env[`${app.env_prefix}_DB`];
114
135
  if (!database_path) {
115
136
  console.error(`${app.id} daemon: ${app.env_prefix}_DB must name the database`);
@@ -118,7 +139,7 @@ export async function run_daemon(app, env = process.env) {
118
139
  // A run on another database has a socket of its own.
119
140
  const socket_path = env[`${app.env_prefix}_SOCKET`] || daemon_socket_path({ app: app.id, data_file: database_path });
120
141
  try {
121
- const daemon = await start_daemon(app, { database_path, socket_path, on_stopped: () => process.exit(0) });
142
+ const daemon = await start_daemon(app, { database_path, socket_path, on_stopped: () => process.exit(0), declared_file: declared_file_of(app, env), ...extra });
122
143
  // Another daemon on this database got there first, which is all that was asked for.
123
144
  if (!daemon)
124
145
  process.exit(0);
@@ -1,6 +1,7 @@
1
- import type { ApiSpec } from "../api_spec.ts";
1
+ import { type ApiSpec, type PageOnlyCalls } from "../api_spec.ts";
2
2
  import { type BackupMethods, type Backups, type BackupNaming } from "../backups.ts";
3
3
  import type { BackupSchedule } from "../backup_protocol.ts";
4
+ import { type Caller } from "../caller.ts";
4
5
  import { type CertificateMethods } from "../certificate_protocol.ts";
5
6
  import { type ConnectionMethods } from "../connection_protocol.ts";
6
7
  import { type Bridge } from "../electron/bridge.ts";
@@ -21,6 +22,8 @@ export interface Feature<Methods extends Record<string, StoreMethod> = Record<st
21
22
  api: ApiSpec<Methods>;
22
23
  settings?: Record<string, SettingSpec>;
23
24
  histories?: readonly KeptHistory[];
25
+ on_open?: (database: SqlDatabase) => void;
26
+ after_write?: (database: SqlDatabase) => void;
24
27
  }
25
28
  export declare function define_feature<Methods extends Record<string, StoreMethod>>(feature: Feature<Methods>): Feature<Methods>;
26
29
  export declare function is_read_only(method: string): boolean;
@@ -49,6 +52,8 @@ export interface AppOptions<Features extends readonly Feature[]> {
49
52
  settings?: Record<string, SettingSpec>;
50
53
  settings_descriptions?: SettingsStoreOptions["descriptions"];
51
54
  setting_key_example?: string;
55
+ page_only_refusal?: string;
56
+ token_prefix?: string;
52
57
  }
53
58
  export declare const base_setting_defaults: {
54
59
  history_days: number;
@@ -61,6 +66,10 @@ export interface Restorable extends Backups {
61
66
  export type AppEvents = {
62
67
  changed: null;
63
68
  sync_status: SyncStatus;
69
+ app_event: {
70
+ event: string;
71
+ data: unknown;
72
+ };
64
73
  };
65
74
  export interface AppBridges<Methods extends Record<keyof Methods, (...args: never[]) => unknown>> {
66
75
  calls: Bridge<Methods>;
@@ -90,6 +99,8 @@ export declare function define_app<const Features extends readonly Feature[]>(op
90
99
  settings?: Record<string, SettingSpec>;
91
100
  settings_descriptions?: SettingsStoreOptions["descriptions"];
92
101
  setting_key_example?: string;
102
+ page_only_refusal?: string;
103
+ token_prefix?: string;
93
104
  features: readonly Feature<Record<string, StoreMethod>>[];
94
105
  settings_store: SettingsStore;
95
106
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -117,7 +128,8 @@ export declare function define_app<const Features extends readonly Feature[]>(op
117
128
  method_names: ((keyof UnionToIntersection<Features[number]["methods"]> | keyof SettingsMethods) & string)[];
118
129
  api_spec: ApiSpec<Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>>;
119
130
  is_read_only: typeof is_read_only;
120
- bind_methods: (database: () => SqlDatabase, on_change: () => void) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
131
+ page_only: PageOnlyCalls;
132
+ bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
121
133
  backup_naming: BackupNaming;
122
134
  read_backup_schedule: (database: SqlDatabase) => BackupSchedule;
123
135
  backup_methods: (kept: Restorable, database: () => SqlDatabase, check_schedule: () => void) => BackupMethods;
@@ -126,7 +138,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
126
138
  type ErasedCalls = any;
127
139
  export type App = Omit<ReturnType<typeof define_app<readonly Feature[]>>, "bridges" | "bind_methods" | "api_spec" | "method_names"> & {
128
140
  bridges: AppBridges<ErasedCalls>;
129
- bind_methods: (database: () => SqlDatabase, on_change: () => void) => ErasedCalls;
141
+ bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => ErasedCalls;
130
142
  api_spec: ApiSpec<ErasedCalls>;
131
143
  method_names: readonly string[];
132
144
  };
@@ -2,7 +2,10 @@
2
2
  // and settings. define_app puts them together into the one database every device keeps, the calls the page makes
3
3
  // through whichever host it runs on, and the names every host shares, so the server, the daemon, the desktop window and
4
4
  // the page are all run from the same object.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { page_only_calls } from "../api_spec.js";
5
7
  import { backup_naming, default_backup_schedule } from "../backups.js";
8
+ import { as_caller } from "../caller.js";
6
9
  import { certificate_method_names } from "../certificate_protocol.js";
7
10
  import { connection_method_names } from "../connection_protocol.js";
8
11
  import { define_bridge } from "../electron/bridge.js";
@@ -71,6 +74,8 @@ export function define_app(options) {
71
74
  for (const history of histories)
72
75
  history.install(database);
73
76
  sync_engine.install(database);
77
+ for (const feature of features)
78
+ feature.on_open?.(database);
74
79
  prune_history(database);
75
80
  }
76
81
  // Versions older than the days set go, each item keeping its newest; 0 keeps them all.
@@ -87,15 +92,21 @@ export function define_app(options) {
87
92
  const method_names = Object.keys(all_methods);
88
93
  // Every call described once, for MCP and OpenAPI.
89
94
  const api_spec = Object.assign({}, ...features.map((feature) => feature.api));
90
- // The calls run on the database given, telling on_change after each write so the other pages and devices hear of it.
91
- function bind_methods(database, on_change) {
95
+ // The calls a spec marks page-only and the writes of settings only the user may change, which every host refuses a
96
+ // token and an MCP client.
97
+ const page_only = page_only_calls(api_spec, { rule: settings_store.is_user_only_call, ...(options.page_only_refusal ? { refusal: options.page_only_refusal } : {}) });
98
+ // The calls run on the database given as the caller given, telling on_change after each write so the other pages
99
+ // and devices hear of it.
100
+ function bind_methods(database, on_change, caller = "page") {
92
101
  const bound = method_names.map((name) => {
93
102
  const method = all_methods[name];
94
103
  const call = (...args) => {
95
- const result = method(database(), ...args);
104
+ const result = as_caller(caller, () => method(database(), ...args));
96
105
  if (is_read_only(name))
97
106
  return result;
98
107
  const done = (value) => {
108
+ for (const feature of features)
109
+ feature.after_write?.(database());
99
110
  for (const history of histories)
100
111
  history.record(database());
101
112
  on_change();
@@ -160,6 +171,7 @@ export function define_app(options) {
160
171
  method_names,
161
172
  api_spec,
162
173
  is_read_only,
174
+ page_only,
163
175
  bind_methods,
164
176
  backup_naming: naming,
165
177
  read_backup_schedule,
@@ -66,6 +66,8 @@ export function run_desktop(app, electron, options) {
66
66
  void apply_window_settings().catch(() => undefined);
67
67
  },
68
68
  on_sync_status: (status) => app.bridges.events.emit(windows(), "sync_status", status),
69
+ // The app's own events, such as a reply as it is written, go to every window by name.
70
+ on_event: (event, data) => app.bridges.events.emit(windows(), "app_event", { event, data: data === "" ? null : JSON.parse(data) }),
69
71
  on_switch: () => {
70
72
  for (const window of windows())
71
73
  window.webContents.reload();
@@ -36,4 +36,5 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
36
36
  peer_listening?: PeerListeningClient;
37
37
  desktop?: Client<DesktopMethods>;
38
38
  on_change: (listener: () => void) => () => void;
39
+ on_event?: (event: string, listener: (data: unknown) => void) => () => void;
39
40
  }
@@ -6,10 +6,15 @@ import { EventStream } from "../server/events.ts";
6
6
  import type { SqlDatabase } from "../sql.ts";
7
7
  import { type SyncPeer } from "../sync_peer.ts";
8
8
  import type { App } from "./define.ts";
9
+ import { type StartServices } from "./services.ts";
9
10
  export interface AppDatabase {
10
11
  database: () => DatabaseSync;
11
12
  back_up: () => Promise<void>;
12
13
  backup_methods: BackupMethods;
14
+ on_restore: (hooks: {
15
+ before?: () => void;
16
+ after?: () => void;
17
+ }) => void;
13
18
  close: () => void;
14
19
  }
15
20
  export declare function open_app_database(app: App, path: string, backups_folder: string): AppDatabase;
@@ -24,11 +29,13 @@ export interface ServerOptions {
24
29
  changes: EventStream;
25
30
  backup_methods: BackupMethods;
26
31
  }
32
+ export declare const user_only_backup_calls: ReadonlySet<string>;
27
33
  export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
28
34
  export interface RunServerOptions {
29
35
  web_folder: URL;
30
36
  argv?: string[];
31
37
  env?: NodeJS.ProcessEnv;
38
+ services?: StartServices;
32
39
  }
33
40
  export interface RunningServer {
34
41
  server: FastifyInstance;
@@ -10,8 +10,9 @@ import { fileURLToPath } from "node:url";
10
10
  import fastify, {} from "fastify";
11
11
  import { openapi_document, positional_args } from "../api_spec.js";
12
12
  import { keep_backing_up } from "../backups.js";
13
- import { register_accounts } from "../server/account_sign_in.js";
14
- import { AccountStore } from "../server/account_store.js";
13
+ import { calls_under, register_accounts } from "../server/account_sign_in.js";
14
+ import { caller_of } from "../caller.js";
15
+ import { AccountStore, holds_accounts, move_accounts } from "../server/account_store.js";
15
16
  import { register_call_table } from "../server/call_table.js";
16
17
  import { read_server_config } from "../server/config.js";
17
18
  import { EventStream } from "../server/events.js";
@@ -23,21 +24,27 @@ import { register_sync_peer_routes } from "../server/sync_peer_routes.js";
23
24
  import { register_web_folder } from "../server/web_folder.js";
24
25
  import { file_sync_storage } from "../sync_file_storage.js";
25
26
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
27
+ import { declared_file_of, no_services, side_databases } from "./services.js";
26
28
  // The app's database as the server and the desktop daemon keep it: a file opened and brought up to date, backed up
27
29
  // before its schema is upgraded, before another copy replaces it, and daily, and restored from a backup.
28
30
  export function open_app_database(app, path, backups_folder) {
29
31
  mkdirSync(dirname(path), { recursive: true });
30
32
  const existed = existsSync(path);
31
33
  let database = new DatabaseSync(path);
34
+ let restore_hooks = {};
32
35
  const kept = sqlite_backups({
33
36
  folder: () => (mkdirSync(backups_folder, { recursive: true }), backups_folder),
34
37
  naming: app.backup_naming,
35
38
  database: () => database,
36
39
  database_path: () => path,
37
- close: () => database.close(),
40
+ close: () => {
41
+ restore_hooks.before?.();
42
+ database.close();
43
+ },
38
44
  open: () => {
39
45
  database = new DatabaseSync(path);
40
46
  start(database);
47
+ restore_hooks.after?.();
41
48
  },
42
49
  // The restored data no longer matches other devices', so sync asks again which copy wins.
43
50
  after_restore: (restored) => app.sync_engine.forget_history(restored),
@@ -56,6 +63,7 @@ export function open_app_database(app, path, backups_folder) {
56
63
  database: () => database,
57
64
  back_up: async () => void (await kept.create()),
58
65
  backup_methods: app.backup_methods(kept, () => database, () => void keeper.check()),
66
+ on_restore: (hooks) => void (restore_hooks = hooks),
59
67
  close: () => {
60
68
  keeper.stop();
61
69
  database.close();
@@ -86,7 +94,7 @@ export function register_app_calls(api, app, database, changes) {
86
94
  catch (error) {
87
95
  return send_text(reply, 400, error.message);
88
96
  }
89
- const methods = app.bind_methods(database, () => changes.announce_change(changes.client_id_of(request)));
97
+ const methods = app.bind_methods(database, () => changes.announce_change(changes.client_id_of(request)), caller_of(request));
90
98
  const result = await app.bridges.calls.dispatch(methods, request.params.method, args);
91
99
  if (result === undefined)
92
100
  return reply.code(204).send();
@@ -99,6 +107,8 @@ export function register_app_calls(api, app, database, changes) {
99
107
  }
100
108
  // The server's backups and its sync peer's pairings, which only an admin reaches.
101
109
  const admin_paths = ["/api/backups/", "/api/sync/"];
110
+ // Backup calls only the user at the page may make, since a restored backup could undo what only the user may change.
111
+ export const user_only_backup_calls = new Set(["restore_backup", "remove_backup", "set_backup_schedule"]);
102
112
  export async function build_server(app, options) {
103
113
  const server = fastify({ forceCloseConnections: true });
104
114
  register_lenient_json_body(server);
@@ -111,6 +121,10 @@ export async function build_server(app, options) {
111
121
  // A read-only token may still list and read through MCP, which posts every request.
112
122
  read_only_paths: ["/api/mcp"],
113
123
  needed: (_method, path) => (admin_paths.some((admin_path) => path.startsWith(admin_path)) ? { role: options.accounts.top_role } : "any"),
124
+ // A token is refused the calls only the user at the page may make; a read-only one may make the calls that only read.
125
+ call_of: calls_under("/api/call"),
126
+ is_read_only: app.is_read_only,
127
+ page_only: app.page_only,
114
128
  });
115
129
  const { changes, database } = options;
116
130
  const description = { title: app.name, version: app.version, description: app.instructions };
@@ -125,10 +139,14 @@ export async function build_server(app, options) {
125
139
  instructions: app.instructions,
126
140
  api: app.api_spec,
127
141
  is_read_only: app.is_read_only,
128
- call: (method, args) => app.bridges.calls.dispatch(app.bind_methods(database, () => changes.announce_change()), method, args),
142
+ page_only: app.page_only,
143
+ call: (method, args) => app.bridges.calls.dispatch(app.bind_methods(database, () => changes.announce_change(), "program"), method, args),
129
144
  });
130
145
  // The server's backups, as the page's Settings reach them.
131
146
  api.post("/backups/:method", async (request, reply) => {
147
+ const via = request.viewer?.via;
148
+ if (user_only_backup_calls.has(request.params.method) && via !== "session" && via !== "proxy")
149
+ return send_text(reply, 403, app.page_only.refusal);
132
150
  const args = request.body ?? [];
133
151
  if (args === BAD_JSON || !Array.isArray(args))
134
152
  return send_text(reply, 400, "send the arguments as a JSON list");
@@ -166,9 +184,15 @@ export async function run_server(app, options) {
166
184
  const opened = open_app_database(app, database_path, resolve(config.backups_folder));
167
185
  // Accounts are a file of their own beside the data, so restoring it never changes who can sign in.
168
186
  const accounts_database = new DatabaseSync(join(dirname(database_path), "accounts.db"));
187
+ // An older version kept them in the data's own file; they move out once, after a backup of the file as it was.
188
+ if (holds_accounts(opened.database()) && !holds_accounts(accounts_database)) {
189
+ await opened.back_up();
190
+ move_accounts(opened.database(), accounts_database);
191
+ }
169
192
  const accounts = new AccountStore({
170
193
  database: accounts_database,
171
194
  app_name: app.name,
195
+ ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
172
196
  declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
173
197
  });
174
198
  // Every page hears of a change, whether a page or another device made it.
@@ -186,10 +210,29 @@ export async function run_server(app, options) {
186
210
  const server = await build_server(app, { database: opened.database, accounts, web_folder: server_config.web_folder, sync, changes, backup_methods: opened.backup_methods });
187
211
  const address = await server.listen({ host: server_config.host, port: server_config.port });
188
212
  sync.start();
213
+ const sides = side_databases(database_path);
214
+ const services = options.services
215
+ ? await options.services({
216
+ kind: "server",
217
+ database: opened.database,
218
+ profile: dirname(database_path),
219
+ device_name: `${app.name} server on ${hostname()}`,
220
+ config: config,
221
+ plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
222
+ declared_file: declared_file_of(app, options.env ?? process.env),
223
+ announce: (client_id) => changes.announce_change(client_id),
224
+ emit: (event, data) => changes.send(JSON.stringify(data), { event }),
225
+ side_database: sides.open,
226
+ back_up: opened.back_up,
227
+ })
228
+ : no_services;
229
+ opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
189
230
  console.info(`${app.name} is serving ${address}/`);
190
231
  let stopping = null;
191
- const stop = () => (stopping ??= server.close().then(() => {
232
+ const stop = () => (stopping ??= server.close().then(async () => {
233
+ await services.stop();
192
234
  sync.stop();
235
+ sides.close_all();
193
236
  opened.close();
194
237
  accounts_database.close();
195
238
  }));
@@ -0,0 +1,28 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import type { App } from "./define.ts";
3
+ export interface HostContext {
4
+ kind: "server" | "desktop";
5
+ database: () => DatabaseSync;
6
+ profile: string;
7
+ device_name: string;
8
+ config: Readonly<Record<string, unknown>>;
9
+ plugins_folder: string | null;
10
+ declared_file: string;
11
+ announce: (client_id?: string) => void;
12
+ emit: (event: string, data: unknown) => void;
13
+ side_database: (name: string) => DatabaseSync;
14
+ back_up: () => Promise<void>;
15
+ }
16
+ export interface HostServices {
17
+ before_restore?: () => void;
18
+ after_restore?: () => void;
19
+ stop: () => void | Promise<void>;
20
+ }
21
+ export type StartServices = (context: HostContext) => HostServices | Promise<HostServices>;
22
+ export declare function declared_file_of(app: Pick<App, "id" | "env_prefix">, env: NodeJS.ProcessEnv): string;
23
+ export interface SideDatabases {
24
+ open: (name: string) => DatabaseSync;
25
+ close_all: () => void;
26
+ }
27
+ export declare function side_databases(database_path: string): SideDatabases;
28
+ export declare const no_services: HostServices;
@@ -0,0 +1,37 @@
1
+ // An app's own work beside its calls, which the web server and the desktop daemon both run: background jobs, an
2
+ // index kept in a file of its own, collectors reading other apps, an assistant. The host hands the services what it
3
+ // has, starts them once the database is open, tells them around a restore, and stops them before sync and the
4
+ // database close.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { DatabaseSync } from "node:sqlite";
7
+ // ── Files ────────────────────────────────────────────────────────────────────
8
+ // The declarations file a host reads: <PREFIX>_DECLARED_FILE when it is set, even empty for none, else the NixOS
9
+ // module's /etc/<id>/declared.json.
10
+ export function declared_file_of(app, env) {
11
+ return env[`${app.env_prefix}_DECLARED_FILE`] ?? `/etc/${app.id}/declared.json`;
12
+ }
13
+ // The side databases beside the main file, named after it, such as notes-index.db beside notes.db; each opens once.
14
+ export function side_databases(database_path) {
15
+ const opened = new Map();
16
+ const base = database_path.replace(/\.db$/, "");
17
+ return {
18
+ open: (name) => {
19
+ if (!/^[a-z0-9_-]+$/.test(name))
20
+ throw new Error(`A side database's name is letters, digits, - and _, not '${name}'.`);
21
+ let database = opened.get(name);
22
+ if (!database) {
23
+ database = new DatabaseSync(`${base}-${name}.db`);
24
+ database.exec("PRAGMA journal_mode = WAL");
25
+ opened.set(name, database);
26
+ }
27
+ return database;
28
+ },
29
+ close_all: () => {
30
+ for (const database of opened.values())
31
+ database.close();
32
+ opened.clear();
33
+ },
34
+ };
35
+ }
36
+ // The services when the app has none.
37
+ export const no_services = { stop: () => undefined };
@@ -13,10 +13,21 @@ const events_path = "api/events";
13
13
  const client_id_header = "x-client-id";
14
14
  const reconnect_delay_ms = 5000;
15
15
  // A greeting after the first means the stream reconnected and may have missed changes, so the page reloads too.
16
- function follow_changes(on_change, on_client_id) {
16
+ // Returns how to listen for one of the app's own events on the stream as it is now and after every reconnect.
17
+ function follow_changes(on_change, on_client_id, named) {
17
18
  let has_connected = false;
19
+ let current = null;
20
+ const listen = (events, event) => events.addEventListener(event, (message) => {
21
+ const text = message.data;
22
+ const data = text === "" ? null : JSON.parse(text);
23
+ for (const listener of named.get(event) ?? [])
24
+ listener(data);
25
+ });
18
26
  const connect = () => {
19
27
  const events = new EventSource(events_path);
28
+ current = events;
29
+ for (const event of named.keys())
30
+ listen(events, event);
20
31
  events.addEventListener("hello", (event) => {
21
32
  on_client_id(event.data);
22
33
  if (has_connected)
@@ -31,6 +42,10 @@ function follow_changes(on_change, on_client_id) {
31
42
  });
32
43
  };
33
44
  connect();
45
+ return (event) => {
46
+ if (current)
47
+ listen(current, event);
48
+ };
34
49
  }
35
50
  export function web_api(app) {
36
51
  // Given by the server when the page connects, so the page is not told about its own changes.
@@ -50,10 +65,11 @@ export function web_api(app) {
50
65
  return text === "" ? undefined : JSON.parse(text);
51
66
  }
52
67
  const listeners = new Set();
53
- follow_changes(() => {
68
+ const named = new Map();
69
+ const listen_for = follow_changes(() => {
54
70
  for (const listener of listeners)
55
71
  listener();
56
- }, (given) => (client_id = given));
72
+ }, (given) => (client_id = given), named);
57
73
  const { bridges } = app;
58
74
  return {
59
75
  host: "web",
@@ -65,6 +81,15 @@ export function web_api(app) {
65
81
  listeners.add(listener);
66
82
  return () => listeners.delete(listener);
67
83
  },
84
+ on_event: (event, listener) => {
85
+ let kept = named.get(event);
86
+ if (!kept) {
87
+ named.set(event, (kept = new Set()));
88
+ listen_for(event);
89
+ }
90
+ kept.add(listener);
91
+ return () => void kept.delete(listener);
92
+ },
68
93
  };
69
94
  }
70
95
  // ── Desktop ──────────────────────────────────────────────────────────────────
@@ -89,6 +114,7 @@ export async function desktop_api(app) {
89
114
  connections,
90
115
  desktop: exposed[bridges.desktop.api_name],
91
116
  on_change: (listener) => events.on("changed", listener),
117
+ on_event: (event, listener) => events.on("app_event", (sent) => sent.event === event && listener(sent.data)),
92
118
  };
93
119
  }
94
120
  // ── Phone ────────────────────────────────────────────────────────────────────
@@ -0,0 +1,4 @@
1
+ export type Caller = "page" | "program" | "engine";
2
+ export declare function as_caller<Result>(caller: Caller, work: () => Result): Result;
3
+ export declare function current_caller(): Caller;
4
+ export declare function caller_of(request: object): Caller;
package/dist/caller.js ADDED
@@ -0,0 +1,23 @@
1
+ // Who is making the call in hand: the user at the app's own page (a signed-in browser or the desktop window), the
2
+ // app's own assistant or background work acting on its own, or another program through a token or MCP. It is set
3
+ // around each call's synchronous part, which is where a store reads it.
4
+ let current = "page";
5
+ // Runs the work as the caller given; the caller before comes back once its synchronous part ends.
6
+ export function as_caller(caller, work) {
7
+ const before = current;
8
+ current = caller;
9
+ try {
10
+ return work();
11
+ }
12
+ finally {
13
+ current = before;
14
+ }
15
+ }
16
+ export function current_caller() {
17
+ return current;
18
+ }
19
+ // The caller a server request is: a token is a program, a browser signed in itself or through a proxy is the user.
20
+ export function caller_of(request) {
21
+ const viewer = request.viewer;
22
+ return viewer?.via === "token" ? "program" : "page";
23
+ }
@@ -84,6 +84,8 @@ export interface AccountStoreOptions {
84
84
  secret_try_window_seconds?: number;
85
85
  password_hashes?: PasswordHashSlots;
86
86
  }
87
+ export declare function holds_accounts(database: SqlDatabase): boolean;
88
+ export declare function move_accounts(from: SqlDatabase, to: SqlDatabase): boolean;
87
89
  export declare class AccountStore {
88
90
  readonly app_name: string;
89
91
  readonly roles: readonly string[];
@@ -75,6 +75,54 @@ const schema = [`
75
75
  PRIMARY KEY (name, key)
76
76
  );
77
77
  `];
78
+ // ── Moving ───────────────────────────────────────────────────────────────────
79
+ function has_table(database, name) {
80
+ return database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== undefined;
81
+ }
82
+ // Whether a database keeps accounts, as an older version kept them in the app's own.
83
+ export function holds_accounts(database) {
84
+ return has_table(database, "account_users");
85
+ }
86
+ // Moves the accounts an older version kept in the app's own database into their own, once: their tables, indexes, rows
87
+ // and schema version go across as they are and leave the app's database, so a restored backup no longer holds them.
88
+ // Does nothing when the accounts database already has accounts or the app's has none; says whether it moved them.
89
+ export function move_accounts(from, to) {
90
+ if (!holds_accounts(from) || holds_accounts(to))
91
+ return false;
92
+ const objects = from.prepare("SELECT type, name, sql FROM sqlite_master WHERE name LIKE 'account\\_%' ESCAPE '\\' AND sql IS NOT NULL ORDER BY type = 'index', rowid").all();
93
+ const versions = from.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'schema_versions'").get();
94
+ to.exec("BEGIN");
95
+ try {
96
+ if (versions && !has_table(to, "schema_versions"))
97
+ to.exec(versions.sql);
98
+ for (const object of objects) {
99
+ to.exec(object.sql);
100
+ if (object.type !== "table")
101
+ continue;
102
+ for (const row of from.prepare(`SELECT * FROM "${object.name}"`).all()) {
103
+ const columns = Object.keys(row);
104
+ to.prepare(`INSERT INTO "${object.name}" (${columns.map((column) => `"${column}"`).join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`).run(...columns.map((column) => row[column]));
105
+ }
106
+ }
107
+ const version = versions ? from.prepare("SELECT * FROM schema_versions WHERE owner = 'accounts'").get() : undefined;
108
+ if (version) {
109
+ const columns = Object.keys(version);
110
+ to.prepare(`INSERT INTO schema_versions (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`).run(...columns.map((column) => version[column]));
111
+ }
112
+ to.exec("COMMIT");
113
+ }
114
+ catch (error) {
115
+ to.exec("ROLLBACK");
116
+ throw error;
117
+ }
118
+ from.exec("BEGIN");
119
+ for (const object of objects.filter((each) => each.type === "table"))
120
+ from.exec(`DROP TABLE "${object.name}"`);
121
+ if (versions)
122
+ from.prepare("DELETE FROM schema_versions WHERE owner = 'accounts'").run();
123
+ from.exec("COMMIT");
124
+ return true;
125
+ }
78
126
  // ── Store ────────────────────────────────────────────────────────────────────
79
127
  export class AccountStore {
80
128
  app_name;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.101.0",
3
+ "version": "0.103.0",
4
4
  "description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {