@fedify/sqlite 2.0.0-dev.1604 → 2.0.0-dev.1641

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/deno.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/sqlite",
3
- "version": "2.0.0-dev.1604+23a1ea67",
3
+ "version": "2.0.0-dev.1641+6b0c942c",
4
4
  "license": "MIT",
5
5
  "exports": {
6
6
  ".": "./src/mod.ts",
@@ -0,0 +1,42 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+
4
+ //#region rolldown:runtime
5
+ var __create = Object.create;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __commonJS = (cb, mod) => function() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
16
+ key = keys[i];
17
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
18
+ get: ((k) => from[k]).bind(null, key),
19
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
+ });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
25
+ value: mod,
26
+ enumerable: true
27
+ }) : target, mod));
28
+
29
+ //#endregion
30
+
31
+ Object.defineProperty(exports, '__commonJS', {
32
+ enumerable: true,
33
+ get: function () {
34
+ return __commonJS;
35
+ }
36
+ });
37
+ Object.defineProperty(exports, '__toESM', {
38
+ enumerable: true,
39
+ get: function () {
40
+ return __toESM;
41
+ }
42
+ });
@@ -1,6 +1,6 @@
1
1
 
2
- import { Temporal } from "@js-temporal/polyfill";
3
-
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+
4
4
  //#region rolldown:runtime
5
5
  var __create = Object.create;
6
6
  var __defProp = Object.defineProperty;
@@ -0,0 +1,45 @@
1
+ //#region src/adapter.d.ts
2
+ /**
3
+ * SQLite database adapter.
4
+ *
5
+ * An abstract interface for SQLite database for different runtime environments.
6
+ */
7
+ interface SqliteDatabaseAdapter {
8
+ /**
9
+ * Prepares a SQL statement.
10
+ * @param sql - The SQL statement to prepare.
11
+ */
12
+ prepare(sql: string): SqliteStatementAdapter;
13
+ /**
14
+ * Executes a SQL statement.
15
+ * @param sql - The SQL statement to execute.
16
+ */
17
+ exec(sql: string): void;
18
+ /**
19
+ * Closes the database connection.
20
+ */
21
+ close(): void;
22
+ }
23
+ interface SqliteStatementAdapter {
24
+ /**
25
+ * Executes a SQL statement and returns the number of changes made to the database.
26
+ * @param params - The parameters to bind to the SQL statement.
27
+ */
28
+ run(...params: unknown[]): {
29
+ changes: number;
30
+ lastInsertRowid: number;
31
+ };
32
+ /**
33
+ * Executes a SQL statement and returns the first row of the result set.
34
+ * @param params - The parameters to bind to the SQL statement.
35
+ * @returns The first row of the result set, or `undefined` if the result set is empty.
36
+ */
37
+ get(...params: unknown[]): unknown | undefined;
38
+ /**
39
+ * Executes a SQL statement and returns all rows of the result set.
40
+ * @param params - The parameters to bind to the SQL statement.
41
+ */
42
+ all(...params: unknown[]): unknown[];
43
+ }
44
+ //#endregion
45
+ export { SqliteDatabaseAdapter, SqliteStatementAdapter };
@@ -0,0 +1,2 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ export { DatabaseSync };
package/dist/kv.cjs ADDED
@@ -0,0 +1,189 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+
4
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
5
+ const require_index_esm = require('./node_modules/.pnpm/@js-temporal_polyfill@0.5.1/node_modules/@js-temporal/polyfill/dist/index.esm.cjs');
6
+ const __sqlite = require_rolldown_runtime.__toESM(require("#sqlite"));
7
+ const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
8
+ const es_toolkit = require_rolldown_runtime.__toESM(require("es-toolkit"));
9
+
10
+ //#region src/kv.ts
11
+ const logger = (0, __logtape_logtape.getLogger)([
12
+ "fedify",
13
+ "sqlite",
14
+ "kv"
15
+ ]);
16
+ /**
17
+ * A key–value store that uses SQLite as the underlying storage.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { createFederation } from "@fedify/fedify";
22
+ * import { SqliteKvStore } from "@fedify/sqlite";
23
+ * import { DatabaseSync } from "node:sqlite";
24
+ *
25
+ * const db = new DatabaseSync(":memory:");
26
+ * const federation = createFederation({
27
+ * // ...
28
+ * kv: new SqliteKvStore(db),
29
+ * });
30
+ * ```
31
+ */
32
+ var SqliteKvStore = class SqliteKvStore {
33
+ static #defaultTableName = "fedify_kv";
34
+ static #tableNameRegex = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
35
+ #db;
36
+ #tableName;
37
+ #initialized;
38
+ /**
39
+ * Creates a new SQLite key–value store.
40
+ * @param db The SQLite database to use. Supports `node:sqlite` and `bun:sqlite`.
41
+ * @param options The options for the key–value store.
42
+ */
43
+ constructor(db, options = {}) {
44
+ this.db = db;
45
+ this.options = options;
46
+ this.#db = new __sqlite.SqliteDatabase(db);
47
+ this.#initialized = options.initialized ?? false;
48
+ this.#tableName = options.tableName ?? SqliteKvStore.#defaultTableName;
49
+ if (!SqliteKvStore.#tableNameRegex.test(this.#tableName)) throw new Error(`Invalid table name for the key–value store: ${this.#tableName}`);
50
+ }
51
+ /**
52
+ * {@inheritDoc KvStore.get}
53
+ */
54
+ async get(key) {
55
+ this.initialize();
56
+ const encodedKey = this.#encodeKey(key);
57
+ const now = require_index_esm.qi.Now.instant().epochMilliseconds;
58
+ const result = this.#db.prepare(`
59
+ SELECT value
60
+ FROM "${this.#tableName}"
61
+ WHERE key = ? AND (expires IS NULL OR expires > ?)
62
+ `).get(encodedKey, now);
63
+ if (!result) return void 0;
64
+ return this.#decodeValue(result.value);
65
+ }
66
+ /**
67
+ * {@inheritDoc KvStore.set}
68
+ */
69
+ async set(key, value, options) {
70
+ this.initialize();
71
+ if (value === void 0) return;
72
+ const encodedKey = this.#encodeKey(key);
73
+ const encodedValue = this.#encodeValue(value);
74
+ const now = require_index_esm.qi.Now.instant().epochMilliseconds;
75
+ const expiresAt = options?.ttl !== void 0 ? now + options.ttl.total({ unit: "milliseconds" }) : null;
76
+ this.#db.prepare(`INSERT INTO "${this.#tableName}" (key, value, created, expires)
77
+ VALUES (?, ?, ?, ?)
78
+ ON CONFLICT(key) DO UPDATE SET
79
+ value = excluded.value,
80
+ expires = excluded.expires`).run(encodedKey, encodedValue, now, expiresAt);
81
+ this.#expire();
82
+ return;
83
+ }
84
+ /**
85
+ * {@inheritDoc KvStore.delete}
86
+ */
87
+ async delete(key) {
88
+ this.initialize();
89
+ const encodedKey = this.#encodeKey(key);
90
+ this.#db.prepare(`
91
+ DELETE FROM "${this.#tableName}" WHERE key = ?
92
+ `).run(encodedKey);
93
+ this.#expire();
94
+ return Promise.resolve();
95
+ }
96
+ /**
97
+ * {@inheritDoc KvStore.cas}
98
+ */
99
+ async cas(key, expectedValue, newValue, options) {
100
+ this.initialize();
101
+ const encodedKey = this.#encodeKey(key);
102
+ const now = require_index_esm.qi.Now.instant().epochMilliseconds;
103
+ const expiresAt = options?.ttl !== void 0 ? now + options.ttl.total({ unit: "milliseconds" }) : null;
104
+ try {
105
+ this.#db.exec("BEGIN IMMEDIATE");
106
+ const currentResult = this.#db.prepare(`
107
+ SELECT value
108
+ FROM "${this.#tableName}"
109
+ WHERE key = ? AND (expires IS NULL OR expires > ?)
110
+ `).get(encodedKey, now);
111
+ const currentValue = currentResult === void 0 ? void 0 : this.#decodeValue(currentResult.value);
112
+ if (!(0, es_toolkit.isEqual)(currentValue, expectedValue)) {
113
+ this.#db.exec("ROLLBACK");
114
+ return false;
115
+ }
116
+ if (newValue === void 0) this.#db.prepare(`
117
+ DELETE FROM "${this.#tableName}" WHERE key = ?
118
+ `).run(encodedKey);
119
+ else {
120
+ const newValueJson = this.#encodeValue(newValue);
121
+ this.#db.prepare(`
122
+ INSERT INTO "${this.#tableName}" (key, value, created, expires)
123
+ VALUES (?, ?, ?, ?)
124
+ ON CONFLICT(key) DO UPDATE SET
125
+ value = excluded.value,
126
+ expires = excluded.expires
127
+ `).run(encodedKey, newValueJson, now, expiresAt);
128
+ }
129
+ this.#db.exec("COMMIT");
130
+ this.#expire();
131
+ return true;
132
+ } catch (error) {
133
+ this.#db.exec("ROLLBACK");
134
+ throw error;
135
+ }
136
+ }
137
+ /**
138
+ * Creates the table used by the key–value store if it does not already exist.
139
+ * Does nothing if the table already exists.
140
+ */
141
+ initialize() {
142
+ if (this.#initialized) return;
143
+ logger.debug("Initializing the key–value store table {tableName}...", { tableName: this.#tableName });
144
+ this.#db.exec(`
145
+ CREATE TABLE IF NOT EXISTS "${this.#tableName}" (
146
+ key TEXT PRIMARY KEY,
147
+ value TEXT NOT NULL,
148
+ created INTEGER NOT NULL,
149
+ expires INTEGER
150
+ )
151
+ `);
152
+ this.#db.exec(`
153
+ CREATE INDEX IF NOT EXISTS "idx_${this.#tableName}_expires"
154
+ ON "${this.#tableName}" (expires)
155
+ `);
156
+ this.#initialized = true;
157
+ logger.debug("Initialized the key–value store table {tableName}.", { tableName: this.#tableName });
158
+ }
159
+ #expire() {
160
+ const now = require_index_esm.qi.Now.instant().epochMilliseconds;
161
+ this.#db.prepare(`
162
+ DELETE FROM "${this.#tableName}"
163
+ WHERE expires IS NOT NULL AND expires <= ?
164
+ `).run(now);
165
+ }
166
+ /**
167
+ * Drops the table used by the key–value store. Does nothing if the table
168
+ * does not exist.
169
+ */
170
+ drop() {
171
+ this.#db.exec(`DROP TABLE IF EXISTS "${this.#tableName}"`);
172
+ this.#initialized = false;
173
+ }
174
+ #encodeKey(key) {
175
+ return JSON.stringify(key);
176
+ }
177
+ #decodeKey(key) {
178
+ return JSON.parse(key);
179
+ }
180
+ #encodeValue(value) {
181
+ return JSON.stringify(value);
182
+ }
183
+ #decodeValue(value) {
184
+ return JSON.parse(value);
185
+ }
186
+ };
187
+
188
+ //#endregion
189
+ exports.SqliteKvStore = SqliteKvStore;
package/dist/kv.d.cts ADDED
@@ -0,0 +1,76 @@
1
+ import { DatabaseSync } from "./dist/sqlite.node.cjs";
2
+ import { KvKey, KvStore, KvStoreSetOptions } from "@fedify/fedify";
3
+
4
+ //#region src/kv.d.ts
5
+ /**
6
+ * Options for the SQLite key–value store.
7
+ */
8
+ interface SqliteKvStoreOptions {
9
+ /**
10
+ * The table name to use for the key–value store.
11
+ * Only letters, digits, and underscores are allowed.
12
+ * `"fedify_kv"` by default.
13
+ * @default `"fedify_kv"`
14
+ */
15
+ tableName?: string;
16
+ /**
17
+ * Whether the table has been initialized. `false` by default.
18
+ * @default `false`
19
+ */
20
+ initialized?: boolean;
21
+ }
22
+ /**
23
+ * A key–value store that uses SQLite as the underlying storage.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * import { createFederation } from "@fedify/fedify";
28
+ * import { SqliteKvStore } from "@fedify/sqlite";
29
+ * import { DatabaseSync } from "node:sqlite";
30
+ *
31
+ * const db = new DatabaseSync(":memory:");
32
+ * const federation = createFederation({
33
+ * // ...
34
+ * kv: new SqliteKvStore(db),
35
+ * });
36
+ * ```
37
+ */
38
+ declare class SqliteKvStore implements KvStore {
39
+ #private;
40
+ readonly db: DatabaseSync;
41
+ readonly options: SqliteKvStoreOptions;
42
+ /**
43
+ * Creates a new SQLite key–value store.
44
+ * @param db The SQLite database to use. Supports `node:sqlite` and `bun:sqlite`.
45
+ * @param options The options for the key–value store.
46
+ */
47
+ constructor(db: DatabaseSync, options?: SqliteKvStoreOptions);
48
+ /**
49
+ * {@inheritDoc KvStore.get}
50
+ */
51
+ get<T = unknown>(key: KvKey): Promise<T | undefined>;
52
+ /**
53
+ * {@inheritDoc KvStore.set}
54
+ */
55
+ set(key: KvKey, value: unknown, options?: KvStoreSetOptions): Promise<void>;
56
+ /**
57
+ * {@inheritDoc KvStore.delete}
58
+ */
59
+ delete(key: KvKey): Promise<void>;
60
+ /**
61
+ * {@inheritDoc KvStore.cas}
62
+ */
63
+ cas(key: KvKey, expectedValue: unknown, newValue: unknown, options?: KvStoreSetOptions): Promise<boolean>;
64
+ /**
65
+ * Creates the table used by the key–value store if it does not already exist.
66
+ * Does nothing if the table already exists.
67
+ */
68
+ initialize(): void;
69
+ /**
70
+ * Drops the table used by the key–value store. Does nothing if the table
71
+ * does not exist.
72
+ */
73
+ drop(): void;
74
+ }
75
+ //#endregion
76
+ export { SqliteKvStore, SqliteKvStoreOptions };
package/dist/kv.js CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { Temporal } from "@js-temporal/polyfill";
3
-
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+
4
4
  import { qi } from "./node_modules/.pnpm/@js-temporal_polyfill@0.5.1/node_modules/@js-temporal/polyfill/dist/index.esm.js";
5
5
  import { SqliteDatabase } from "#sqlite";
6
6
  import { getLogger } from "@logtape/logtape";
package/dist/mod.cjs ADDED
@@ -0,0 +1,6 @@
1
+
2
+ const { Temporal } = require("@js-temporal/polyfill");
3
+
4
+ const require_kv = require('./kv.cjs');
5
+
6
+ exports.SqliteKvStore = require_kv.SqliteKvStore;
package/dist/mod.d.cts ADDED
@@ -0,0 +1,2 @@
1
+ import { SqliteKvStore } from "./kv.cjs";
2
+ export { SqliteKvStore };
package/dist/mod.js CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { Temporal } from "@js-temporal/polyfill";
3
-
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+
4
4
  import { SqliteKvStore } from "./kv.js";
5
5
 
6
6
  export { SqliteKvStore };