@kky42/pievo-server 2.4.14 → 3.0.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.
Files changed (90) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/{actionUi-5PtES4q0.js → actionUi-BZrLpgHT.js} +1 -1
  3. package/.output/public/assets/app-DXLuQNb9.css +2 -0
  4. package/.output/public/assets/index-Di_wpAtL.js +10 -0
  5. package/.output/public/assets/loops._loopId-X3ClNPMY.js +67 -0
  6. package/.output/public/assets/loops._loopId_.runs._runId-ByU2BSyF.js +3 -0
  7. package/.output/public/assets/preload-helper-hRTYB_ju.js +3 -0
  8. package/.output/public/assets/{routes-Dm_3J2aV.js → routes-BIOJZsig.js} +1 -1
  9. package/.output/public/assets/routes-K8D5uBiV.js +1 -0
  10. package/.output/server/_chunks/ssr-renderer.mjs +1 -1
  11. package/.output/server/_libs/{drizzle-orm+postgres.mjs → drizzle-orm.mjs} +93 -2218
  12. package/.output/server/_ssr/{MachinesModal-BaEtzycr.mjs → MachinesModal-CmVMec6B.mjs} +46 -46
  13. package/.output/server/_ssr/{actionUi-5HOCZnom.mjs → actionUi-DE-Pb2tv.mjs} +1 -2
  14. package/.output/server/_ssr/{artifactFiles-DO43wwXA.mjs → artifactFiles-Di1xDKvX.mjs} +5 -8
  15. package/.output/server/_ssr/{artifactKind-DwDr8IYc.mjs → artifactKind-DqpmtxDU.mjs} +3 -9
  16. package/.output/server/_ssr/{boot-C472kLwY.mjs → boot-CYRi-wez.mjs} +2152 -351
  17. package/.output/server/_ssr/lifecycleUi-BsbUsi5K.mjs +106 -0
  18. package/.output/server/_ssr/{loopApi-DT751TJA.mjs → loopApi-Bez1rHV0.mjs} +50 -66
  19. package/.output/server/_ssr/{loopProjection-qaD2I48a.mjs → loopProjection-esCjyZJg.mjs} +4 -23
  20. package/.output/server/_ssr/{loops._loopId-CXgw2Rz1.mjs → loops._loopId-KUezNY69.mjs} +8 -23
  21. package/.output/server/_ssr/{loops._loopId_.runs._runId-Dk94Z0Jq.mjs → loops._loopId_.runs._runId-BFP9oMrp.mjs} +2 -7
  22. package/.output/server/_ssr/{loops._loopId_.runs._runId-SASSqOfy.mjs → loops._loopId_.runs._runId-DOkUEesG.mjs} +18 -33
  23. package/.output/server/_ssr/{machineFns-BSrIgn3f.mjs → machineFns-CniGcY8s.mjs} +13 -50
  24. package/.output/server/_ssr/networkAccess-CIlK3ION.mjs +30 -0
  25. package/.output/server/_ssr/router-BFIH2UAE.mjs +362 -0
  26. package/.output/server/_ssr/routes-BSVBANI3.mjs +12 -0
  27. package/.output/server/_ssr/{routes-Cr-9yDEH.mjs → routes-DnE7XDe_.mjs} +91 -50
  28. package/.output/server/_ssr/{routes-DRBS4Zi4.mjs → routes-ngpX7h8D.mjs} +2 -4
  29. package/.output/server/_ssr/ssr.mjs +25 -34
  30. package/.output/server/_ssr/start-B5_9Z5W-.mjs +35 -0
  31. package/.output/server/{_tanstack-start-manifest_v-DxLIQ0cc.mjs → _tanstack-start-manifest_v-DnwAupbZ.mjs} +8 -13
  32. package/.output/server/drizzle/0000_baseline.sql +6 -97
  33. package/.output/server/drizzle/meta/_journal.json +2 -23
  34. package/.output/server/index.mjs +45 -52
  35. package/drizzle/0000_baseline.sql +6 -97
  36. package/drizzle/meta/_journal.json +2 -23
  37. package/package.json +4 -8
  38. package/scripts/pievo-server.mjs +49 -47
  39. package/scripts/server-cli-lib.mjs +21 -12
  40. package/scripts/server-network.mjs +139 -0
  41. package/.output/public/assets/SignIn-CIFwnZtF.js +0 -1
  42. package/.output/public/assets/app-DvHMhs7S.css +0 -2
  43. package/.output/public/assets/index-CRX2pu0W.js +0 -10
  44. package/.output/public/assets/loops._loopId-BsuV-Rmf.js +0 -67
  45. package/.output/public/assets/loops._loopId_.runs._runId-DpK_fzmZ.js +0 -3
  46. package/.output/public/assets/preload-helper-sAZOZb3G.js +0 -5
  47. package/.output/public/assets/routes-DxF_s3cD.js +0 -1
  48. package/.output/server/_libs/@aws-crypto/crc32+[...].mjs +0 -419
  49. package/.output/server/_libs/@aws-sdk/checksums+[...].mjs +0 -10732
  50. package/.output/server/_libs/@aws-sdk/client-s3+[...].mjs +0 -9475
  51. package/.output/server/_libs/@aws-sdk/credential-provider-http+[...].mjs +0 -137
  52. package/.output/server/_libs/@aws-sdk/credential-provider-ini+[...].mjs +0 -440
  53. package/.output/server/_libs/@aws-sdk/credential-provider-process+[...].mjs +0 -62
  54. package/.output/server/_libs/@aws-sdk/credential-provider-sso+[...].mjs +0 -818
  55. package/.output/server/_libs/@aws-sdk/credential-provider-web-identity+[...].mjs +0 -59
  56. package/.output/server/_libs/@smithy/credential-provider-imds+[...].mjs +0 -342
  57. package/.output/server/_libs/aws-crypto__crc32c.mjs +0 -314
  58. package/.output/server/_libs/aws-sdk__nested-clients.mjs +0 -2671
  59. package/.output/server/_ssr/SignIn-sHQaBQJC.mjs +0 -53
  60. package/.output/server/_ssr/artifacts-Cd7Qx3Qp.mjs +0 -2
  61. package/.output/server/_ssr/auth-0AamrwHo.mjs +0 -38355
  62. package/.output/server/_ssr/auth-client-lSMb_Idt.mjs +0 -1070
  63. package/.output/server/_ssr/bun-sqlite-dialect-BW9W1_Ps-DLIXocA0.mjs +0 -162
  64. package/.output/server/_ssr/core-RrmWoKne.mjs +0 -5
  65. package/.output/server/_ssr/d1-sqlite-dialect-BLC8LXE6-BoFMIPr_.mjs +0 -112
  66. package/.output/server/_ssr/db-BzvMQ2kx.mjs +0 -2
  67. package/.output/server/_ssr/dist-ClzqkwxD.mjs +0 -342
  68. package/.output/server/_ssr/factory-ixUjZqJn.mjs +0 -6903
  69. package/.output/server/_ssr/kysely-adapter-DkZbmKgV.mjs +0 -2
  70. package/.output/server/_ssr/kysely-migration-tables-JkVUjPF_-bPAX9LR_.mjs +0 -19
  71. package/.output/server/_ssr/logger-DDjsYB2X.mjs +0 -2
  72. package/.output/server/_ssr/loopTags-CXx5UdGf.mjs +0 -3356
  73. package/.output/server/_ssr/node-sqlite-dialect-BbUqnnYv.mjs +0 -162
  74. package/.output/server/_ssr/router-BlLlhfJe.mjs +0 -543
  75. package/.output/server/_ssr/routes-DTBltabU.mjs +0 -27
  76. package/.output/server/_ssr/start-4ifArtKx.mjs +0 -4
  77. package/.output/server/_ssr/store-vDZ9INSa.mjs +0 -2
  78. package/.output/server/_ssr/tokens-BHiCElYD.mjs +0 -2
  79. package/.output/server/drizzle/0001_add_pi_agent.sql +0 -9
  80. package/.output/server/drizzle/0002_remove_teams.sql +0 -15
  81. package/.output/server/drizzle/0003_add_loop_tags.sql +0 -5
  82. package/.output/server/node_modules/tslib/modules/index.js +0 -70
  83. package/.output/server/node_modules/tslib/modules/package.json +0 -3
  84. package/.output/server/node_modules/tslib/package.json +0 -47
  85. package/.output/server/node_modules/tslib/tslib.js +0 -484
  86. package/.output/server/package.json +0 -9
  87. package/drizzle/0001_add_pi_agent.sql +0 -9
  88. package/drizzle/0002_remove_teams.sql +0 -15
  89. package/drizzle/0003_add_loop_tags.sql +0 -5
  90. package/scripts/prestart.mjs +0 -66
@@ -1,162 +0,0 @@
1
- import { n as DefaultQueryCompiler, o as CompiledQuery, s as sql$1 } from "./auth-0AamrwHo.mjs";
2
- import { n as DEFAULT_MIGRATION_TABLE, t as DEFAULT_MIGRATION_LOCK_TABLE } from "./kysely-migration-tables-JkVUjPF_-bPAX9LR_.mjs";
3
- //#region node_modules/.nitro/vite/services/ssr/assets/bun-sqlite-dialect-BW9W1_Ps-DLIXocA0.js
4
- var BunSqliteAdapter = class {
5
- get supportsCreateIfNotExists() {
6
- return true;
7
- }
8
- get supportsTransactionalDdl() {
9
- return false;
10
- }
11
- get supportsMultipleConnections() {
12
- return false;
13
- }
14
- get supportsReturning() {
15
- return true;
16
- }
17
- async acquireMigrationLock() {}
18
- async releaseMigrationLock() {}
19
- get supportsOutput() {
20
- return true;
21
- }
22
- };
23
- var BunSqliteDriver = class {
24
- #config;
25
- #connectionMutex = new ConnectionMutex();
26
- #db;
27
- #connection;
28
- constructor(config) {
29
- this.#config = { ...config };
30
- }
31
- async init() {
32
- this.#db = this.#config.database;
33
- this.#connection = new BunSqliteConnection(this.#db);
34
- if (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);
35
- }
36
- async acquireConnection() {
37
- await this.#connectionMutex.lock();
38
- return this.#connection;
39
- }
40
- async beginTransaction(connection) {
41
- await connection.executeQuery(CompiledQuery.raw("begin"));
42
- }
43
- async commitTransaction(connection) {
44
- await connection.executeQuery(CompiledQuery.raw("commit"));
45
- }
46
- async rollbackTransaction(connection) {
47
- await connection.executeQuery(CompiledQuery.raw("rollback"));
48
- }
49
- async releaseConnection() {
50
- this.#connectionMutex.unlock();
51
- }
52
- async destroy() {
53
- this.#db?.close();
54
- }
55
- };
56
- var BunSqliteConnection = class {
57
- #db;
58
- constructor(db) {
59
- this.#db = db;
60
- }
61
- executeQuery(compiledQuery) {
62
- const { sql, parameters } = compiledQuery;
63
- const stmt = this.#db.prepare(sql);
64
- const params = parameters;
65
- if (stmt.columnNames.length > 0) return Promise.resolve({ rows: stmt.all(...params) });
66
- const { changes, lastInsertRowid } = stmt.run(...params);
67
- return Promise.resolve({
68
- rows: [],
69
- numAffectedRows: BigInt(changes),
70
- insertId: typeof lastInsertRowid === "bigint" ? lastInsertRowid : BigInt(lastInsertRowid)
71
- });
72
- }
73
- async *streamQuery() {
74
- throw new Error("Streaming query is not supported by SQLite driver.");
75
- }
76
- };
77
- var ConnectionMutex = class {
78
- #promise;
79
- #resolve;
80
- async lock() {
81
- while (this.#promise !== void 0) await this.#promise;
82
- this.#promise = new Promise((resolve) => {
83
- this.#resolve = resolve;
84
- });
85
- }
86
- unlock() {
87
- const resolve = this.#resolve;
88
- this.#promise = void 0;
89
- this.#resolve = void 0;
90
- resolve?.();
91
- }
92
- };
93
- var BunSqliteIntrospector = class {
94
- #db;
95
- constructor(db) {
96
- this.#db = db;
97
- }
98
- async getSchemas() {
99
- return [];
100
- }
101
- async getTables(options = { withInternalKyselyTables: false }) {
102
- let query = this.#db.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo();
103
- if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
104
- const tables = await query.execute();
105
- return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));
106
- }
107
- async #getTableMetadata(table) {
108
- const db = this.#db;
109
- const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, "");
110
- return {
111
- name: table,
112
- columns: (await db.selectFrom(sql$1`pragma_table_info(${table})`.as("table_info")).select([
113
- "name",
114
- "type",
115
- "notnull",
116
- "dflt_value"
117
- ]).execute()).map((col) => ({
118
- name: col.name,
119
- dataType: col.type,
120
- isNullable: !col.notnull,
121
- isAutoIncrementing: col.name === autoIncrementCol,
122
- hasDefaultValue: col.dflt_value != null
123
- })),
124
- isView: false,
125
- isForeign: false
126
- };
127
- }
128
- };
129
- var BunSqliteQueryCompiler = class extends DefaultQueryCompiler {
130
- getCurrentParameterPlaceholder() {
131
- return "?";
132
- }
133
- getLeftIdentifierWrapper() {
134
- return "\"";
135
- }
136
- getRightIdentifierWrapper() {
137
- return "\"";
138
- }
139
- getAutoIncrement() {
140
- return "autoincrement";
141
- }
142
- };
143
- var BunSqliteDialect = class {
144
- #config;
145
- constructor(config) {
146
- this.#config = { ...config };
147
- }
148
- createDriver() {
149
- return new BunSqliteDriver(this.#config);
150
- }
151
- createQueryCompiler() {
152
- return new BunSqliteQueryCompiler();
153
- }
154
- createAdapter() {
155
- return new BunSqliteAdapter();
156
- }
157
- createIntrospector(db) {
158
- return new BunSqliteIntrospector(db);
159
- }
160
- };
161
- //#endregion
162
- export { BunSqliteDialect };
@@ -1,5 +0,0 @@
1
- //#region node_modules/.nitro/vite/services/ssr/assets/core-RrmWoKne.js
2
- var core_default = {};
3
- throw new Error(`Could not resolve "@opentelemetry/api" imported by "@better-auth/core". Is it installed?`);
4
- //#endregion
5
- export { core_default as default };
@@ -1,112 +0,0 @@
1
- import { a as SqliteQueryCompiler, i as SqliteAdapter } from "./auth-0AamrwHo.mjs";
2
- import { n as DEFAULT_MIGRATION_TABLE, t as DEFAULT_MIGRATION_LOCK_TABLE } from "./kysely-migration-tables-JkVUjPF_-bPAX9LR_.mjs";
3
- //#region node_modules/.nitro/vite/services/ssr/assets/d1-sqlite-dialect-BLC8LXE6-BoFMIPr_.js
4
- var D1SqliteAdapter = class extends SqliteAdapter {};
5
- var D1SqliteDriver = class {
6
- #config;
7
- #connection;
8
- constructor(config) {
9
- this.#config = { ...config };
10
- }
11
- async init() {
12
- this.#connection = new D1SqliteConnection(this.#config.database);
13
- if (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);
14
- }
15
- async acquireConnection() {
16
- return this.#connection;
17
- }
18
- async beginTransaction() {
19
- throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead.");
20
- }
21
- async commitTransaction() {
22
- throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead.");
23
- }
24
- async rollbackTransaction() {
25
- throw new Error("D1 does not support interactive transactions. Use the D1 batch() API instead.");
26
- }
27
- async releaseConnection() {}
28
- async destroy() {}
29
- };
30
- var D1SqliteConnection = class {
31
- #db;
32
- constructor(db) {
33
- this.#db = db;
34
- }
35
- async executeQuery(compiledQuery) {
36
- const results = await this.#db.prepare(compiledQuery.sql).bind(...compiledQuery.parameters).all();
37
- const numAffectedRows = results.meta.changes != null ? BigInt(results.meta.changes) : void 0;
38
- return {
39
- insertId: results.meta.last_row_id === void 0 || results.meta.last_row_id === null ? void 0 : BigInt(results.meta.last_row_id),
40
- rows: results?.results || [],
41
- numAffectedRows
42
- };
43
- }
44
- async *streamQuery() {
45
- throw new Error("D1 does not support streaming queries.");
46
- }
47
- };
48
- var D1SqliteIntrospector = class {
49
- #db;
50
- #d1;
51
- constructor(db, d1) {
52
- this.#db = db;
53
- this.#d1 = d1;
54
- }
55
- async getSchemas() {
56
- return [];
57
- }
58
- async getTables(options = { withInternalKyselyTables: false }) {
59
- let query = this.#db.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").where("name", "not like", "_cf_%").select([
60
- "name",
61
- "type",
62
- "sql"
63
- ]).$castTo();
64
- if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
65
- const tables = await query.execute();
66
- if (tables.length === 0) return [];
67
- const statements = tables.map((table) => this.#d1.prepare("SELECT * FROM pragma_table_info(?)").bind(table.name));
68
- const batchResults = await this.#d1.batch(statements);
69
- return tables.map((table, index) => {
70
- const columnInfo = batchResults[index]?.results ?? [];
71
- let autoIncrementCol = table.sql?.split(/[(),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.filter(Boolean)?.[0]?.replace(/["`]/g, "");
72
- if (!autoIncrementCol) {
73
- const pkCols = columnInfo.filter((r) => r.pk > 0);
74
- const singlePk = pkCols.length === 1 ? pkCols[0] : void 0;
75
- if (singlePk && singlePk.type.toLowerCase() === "integer") autoIncrementCol = singlePk.name;
76
- }
77
- return {
78
- name: table.name,
79
- isView: table.type === "view",
80
- isForeign: false,
81
- columns: columnInfo.map((col) => ({
82
- name: col.name,
83
- dataType: col.type,
84
- isNullable: !col.notnull,
85
- isAutoIncrementing: col.name === autoIncrementCol,
86
- hasDefaultValue: col.dflt_value != null
87
- }))
88
- };
89
- });
90
- }
91
- };
92
- var D1SqliteQueryCompiler = class extends SqliteQueryCompiler {};
93
- var D1SqliteDialect = class {
94
- #config;
95
- constructor(config) {
96
- this.#config = { ...config };
97
- }
98
- createDriver() {
99
- return new D1SqliteDriver(this.#config);
100
- }
101
- createQueryCompiler() {
102
- return new D1SqliteQueryCompiler();
103
- }
104
- createAdapter() {
105
- return new D1SqliteAdapter();
106
- }
107
- createIntrospector(db) {
108
- return new D1SqliteIntrospector(db, this.#config.database);
109
- }
110
- };
111
- //#endregion
112
- export { D1SqliteDialect };
@@ -1,2 +0,0 @@
1
- import { N as db } from "./loopTags-CXx5UdGf.mjs";
2
- export { db };
@@ -1,342 +0,0 @@
1
- import { _ as logger, o as createAdapterFactory } from "./factory-ixUjZqJn.mjs";
2
- //#region node_modules/.nitro/vite/services/ssr/assets/dist-ClzqkwxD.js
3
- /**
4
- * Case-insensitive in-memory comparison helpers.
5
- * Used when evaluating where clauses in the memory adapter.
6
- */
7
- function insensitiveCompare(a, b) {
8
- if (typeof a === "string" && typeof b === "string") return a.toLowerCase() === b.toLowerCase();
9
- return a === b;
10
- }
11
- function insensitiveIn(recordVal, values) {
12
- if (typeof recordVal !== "string") return values.includes(recordVal);
13
- return values.some((v) => typeof v === "string" && recordVal.toLowerCase() === v.toLowerCase());
14
- }
15
- function insensitiveNotIn(recordVal, values) {
16
- return !insensitiveIn(recordVal, values);
17
- }
18
- function insensitiveContains(recordVal, value) {
19
- if (typeof recordVal !== "string" || typeof value !== "string") return false;
20
- return recordVal.toLowerCase().includes(value.toLowerCase());
21
- }
22
- function insensitiveStartsWith(recordVal, value) {
23
- if (typeof recordVal !== "string" || typeof value !== "string") return false;
24
- return recordVal.toLowerCase().startsWith(value.toLowerCase());
25
- }
26
- function insensitiveEndsWith(recordVal, value) {
27
- if (typeof recordVal !== "string" || typeof value !== "string") return false;
28
- return recordVal.toLowerCase().endsWith(value.toLowerCase());
29
- }
30
- /**
31
- * Index a table's rows by their `id` for row-level reconciliation. Every
32
- * better-auth row carries an `id` (the adapter's join logic already keys on
33
- * `record.id`), so the id is a stable identity for the three-way merge.
34
- */
35
- function indexById(rows) {
36
- const byId = /* @__PURE__ */ new Map();
37
- for (const row of rows) byId.set(row.id, row);
38
- return byId;
39
- }
40
- /**
41
- * Commit a transaction onto the live database with a three-way merge so a
42
- * concurrent write that interleaved at an `await` point survives.
43
- *
44
- * `base` is the snapshot taken when the transaction started; `clone` is that
45
- * snapshot after the transaction mutated it; `target` is the live database as
46
- * it stands now (possibly carrying concurrent writes). Replaying only the
47
- * `base -> clone` delta onto `target` applies the transaction's own creates,
48
- * updates, and deletes without disturbing rows or tables the transaction never
49
- * touched. A row the transaction did not change keeps the live version, so a
50
- * concurrent edit to a different row is preserved. A row the transaction did
51
- * change wins last-writer-wins over a concurrent edit to the same row, which is
52
- * acceptable for an in-memory development adapter; isolation is guaranteed only
53
- * at row/table granularity.
54
- *
55
- * `target` is mutated in place so any reference held elsewhere (for example the
56
- * `db` object the caller passed to `memoryAdapter`) stays valid.
57
- */
58
- function mergeTransactionInto(target, base, clone) {
59
- const models = new Set([...Object.keys(base), ...Object.keys(clone)]);
60
- for (const model of models) {
61
- if (!(model in clone)) {
62
- delete target[model];
63
- continue;
64
- }
65
- const baseById = indexById(base[model] ?? []);
66
- const cloneRows = clone[model] ?? [];
67
- const cloneById = indexById(cloneRows);
68
- const liveRows = target[model] ?? [];
69
- const merged = [];
70
- const placed = /* @__PURE__ */ new Set();
71
- for (const liveRow of liveRows) {
72
- const id = liveRow.id;
73
- const baseRow = baseById.get(id);
74
- const cloneRow = cloneById.get(id);
75
- if (baseRow !== void 0 && cloneRow === void 0) continue;
76
- if (cloneRow !== void 0 && rowChanged(baseRow, cloneRow)) merged.push(cloneRow);
77
- else merged.push(liveRow);
78
- placed.add(id);
79
- }
80
- for (const cloneRow of cloneRows) if (!baseById.has(cloneRow.id) && !placed.has(cloneRow.id)) merged.push(cloneRow);
81
- target[model] = merged;
82
- }
83
- }
84
- /**
85
- * Whether the transaction mutated a row, comparing its pre-transaction
86
- * snapshot to its post-transaction state. Rows hold scalar columns and
87
- * adapter-serializable values, so JSON equality reliably tells a
88
- * transaction-made edit apart from an untouched row.
89
- */
90
- function rowChanged(baseRow, cloneRow) {
91
- if (baseRow === void 0) return true;
92
- return JSON.stringify(baseRow) !== JSON.stringify(cloneRow);
93
- }
94
- var memoryAdapter = (db, config) => {
95
- let lazyOptions = null;
96
- /**
97
- * Build an adapter factory whose operations read and write `activeDb`.
98
- * The non-transactional adapter targets the live `db`. A transaction
99
- * targets an isolated clone so its uncommitted writes are invisible to
100
- * concurrent operations against the live `db`. A failed transaction leaves
101
- * the live `db` untouched, and a committed one replays only its own
102
- * row/table changes, so a concurrent write that interleaved at an `await`
103
- * point survives either outcome. Isolation is at row/table granularity:
104
- * the in-memory adapter does not serialize writes, so two operations that
105
- * edit the same row resolve last-writer-wins. It is built for development
106
- * and tests, not production concurrency control.
107
- */
108
- const buildAdapterFactory = (activeDb) => createAdapterFactory({
109
- config: {
110
- adapterId: "memory",
111
- adapterName: "Memory Adapter",
112
- usePlural: false,
113
- debugLogs: config?.debugLogs || false,
114
- supportsArrays: true,
115
- customTransformInput(props) {
116
- if (props.options.advanced?.database?.generateId === "serial" && props.field === "id" && props.action === "create") return activeDb[props.model].length + 1;
117
- return props.data;
118
- },
119
- transaction: async (cb) => {
120
- const base = structuredClone(activeDb);
121
- const clone = structuredClone(activeDb);
122
- const result = await cb(buildAdapterFactory(clone)(lazyOptions));
123
- mergeTransactionInto(activeDb, base, clone);
124
- return result;
125
- }
126
- },
127
- adapter: ({ getFieldName, getDefaultFieldName, options, getModelName }) => {
128
- const applySortToRecords = (records, sortBy, model) => {
129
- if (!sortBy) return records;
130
- return records.sort((a, b) => {
131
- const field = getFieldName({
132
- model,
133
- field: sortBy.field
134
- });
135
- const aValue = a[field];
136
- const bValue = b[field];
137
- let comparison = 0;
138
- if (aValue == null && bValue == null) comparison = 0;
139
- else if (aValue == null) comparison = -1;
140
- else if (bValue == null) comparison = 1;
141
- else if (typeof aValue === "string" && typeof bValue === "string") comparison = aValue.localeCompare(bValue);
142
- else if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime();
143
- else if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue;
144
- else if (typeof aValue === "boolean" && typeof bValue === "boolean") comparison = aValue === bValue ? 0 : aValue ? 1 : -1;
145
- else comparison = String(aValue).localeCompare(String(bValue));
146
- return sortBy.direction === "asc" ? comparison : -comparison;
147
- });
148
- };
149
- function convertWhereClause(where, model, join, select) {
150
- const baseRecords = (() => {
151
- const table = activeDb[model];
152
- if (!table) {
153
- logger.error(`[MemoryAdapter] Model ${model} not found in the DB`, Object.keys(activeDb));
154
- throw new Error(`Model ${model} not found`);
155
- }
156
- const evalClause = (record, clause) => {
157
- const { field, value, operator, mode = "sensitive" } = clause;
158
- const isInsensitive = mode === "insensitive" && (typeof value === "string" || Array.isArray(value) && value.every((v) => typeof v === "string"));
159
- switch (operator) {
160
- case "in":
161
- if (!Array.isArray(value)) throw new Error("Value must be an array");
162
- if (isInsensitive) return insensitiveIn(record[field], value);
163
- return value.includes(record[field]);
164
- case "not_in":
165
- if (!Array.isArray(value)) throw new Error("Value must be an array");
166
- if (isInsensitive) return insensitiveNotIn(record[field], value);
167
- return !value.includes(record[field]);
168
- case "contains":
169
- if (isInsensitive) return insensitiveContains(record[field], value);
170
- return record[field]?.includes(value);
171
- case "starts_with":
172
- if (isInsensitive) return insensitiveStartsWith(record[field], value);
173
- return record[field].startsWith(value);
174
- case "ends_with":
175
- if (isInsensitive) return insensitiveEndsWith(record[field], value);
176
- return record[field].endsWith(value);
177
- case "ne": return isInsensitive ? !insensitiveCompare(record[field], value) : record[field] !== value;
178
- case "gt": return value != null && Boolean(record[field] > value);
179
- case "gte": return value != null && Boolean(record[field] >= value);
180
- case "lt": return value != null && Boolean(record[field] < value);
181
- case "lte": return value != null && Boolean(record[field] <= value);
182
- default:
183
- if (isInsensitive) return insensitiveCompare(record[field], value);
184
- if (value === null) return record[field] == null;
185
- return record[field] === value;
186
- }
187
- };
188
- let records = table.filter((record) => {
189
- if (!where.length || where.length === 0) return true;
190
- let result = evalClause(record, where[0]);
191
- for (const clause of where) {
192
- const clauseResult = evalClause(record, clause);
193
- if (clause.connector === "OR") result = result || clauseResult;
194
- else result = result && clauseResult;
195
- }
196
- return result;
197
- });
198
- if (select?.length && select.length > 0) records = records.map((record) => Object.fromEntries(Object.entries(record).filter(([key]) => select.includes(getDefaultFieldName({
199
- model,
200
- field: key
201
- })))));
202
- return records;
203
- })();
204
- if (!join) return baseRecords;
205
- const grouped = /* @__PURE__ */ new Map();
206
- const seenIds = /* @__PURE__ */ new Map();
207
- for (const baseRecord of baseRecords) {
208
- const baseId = String(baseRecord.id);
209
- if (!grouped.has(baseId)) {
210
- const nested = { ...baseRecord };
211
- for (const [joinModel, joinAttr] of Object.entries(join)) {
212
- const joinModelName = getModelName(joinModel);
213
- if (joinAttr.relation === "one-to-one") nested[joinModelName] = null;
214
- else {
215
- nested[joinModelName] = [];
216
- seenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set());
217
- }
218
- }
219
- grouped.set(baseId, nested);
220
- }
221
- const nestedEntry = grouped.get(baseId);
222
- for (const [joinModel, joinAttr] of Object.entries(join)) {
223
- const joinModelName = getModelName(joinModel);
224
- const joinTable = activeDb[joinModelName];
225
- if (!joinTable) {
226
- logger.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(activeDb));
227
- throw new Error(`JoinOption model ${joinModelName} not found`);
228
- }
229
- const matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]);
230
- if (joinAttr.relation === "one-to-one") nestedEntry[joinModelName] = matchingRecords[0] || null;
231
- else {
232
- const seenSet = seenIds.get(`${baseId}-${joinModel}`);
233
- const limit = joinAttr.limit ?? 100;
234
- let count = 0;
235
- for (const matchingRecord of matchingRecords) {
236
- if (count >= limit) break;
237
- if (!seenSet.has(matchingRecord.id)) {
238
- nestedEntry[joinModelName].push(matchingRecord);
239
- seenSet.add(matchingRecord.id);
240
- count++;
241
- }
242
- }
243
- }
244
- }
245
- }
246
- return Array.from(grouped.values());
247
- }
248
- return {
249
- create: async ({ model, data }) => {
250
- if (options.advanced?.database?.generateId === "serial") data.id = activeDb[getModelName(model)].length + 1;
251
- if (!activeDb[model]) activeDb[model] = [];
252
- activeDb[model].push(data);
253
- return data;
254
- },
255
- findOne: async ({ model, where, select, join }) => {
256
- const res = convertWhereClause(where, model, join, select);
257
- if (join) {
258
- const resArray = res;
259
- if (!resArray.length) return null;
260
- return resArray[0];
261
- }
262
- return res[0] || null;
263
- },
264
- findMany: async ({ model, where, sortBy, limit, select, offset, join }) => {
265
- const res = convertWhereClause(where || [], model, join, select);
266
- if (join) {
267
- const resArray = res;
268
- if (!resArray.length) return [];
269
- applySortToRecords(resArray, sortBy, model);
270
- let paginatedRecords = resArray;
271
- if (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset);
272
- if (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit);
273
- return paginatedRecords;
274
- }
275
- let table = applySortToRecords(res, sortBy, model);
276
- if (offset !== void 0) table = table.slice(offset);
277
- if (limit !== void 0) table = table.slice(0, limit);
278
- return table || [];
279
- },
280
- count: async ({ model, where }) => {
281
- if (where) return convertWhereClause(where, model).length;
282
- return activeDb[model].length;
283
- },
284
- update: async ({ model, where, update }) => {
285
- if (where.length === 0) return null;
286
- const res = convertWhereClause(where, model);
287
- res.forEach((record) => {
288
- Object.assign(record, update);
289
- });
290
- return res[0] || null;
291
- },
292
- delete: async ({ model, where }) => {
293
- if (where.length === 0) return;
294
- const table = activeDb[model];
295
- const res = convertWhereClause(where, model);
296
- activeDb[model] = table.filter((record) => !res.includes(record));
297
- },
298
- deleteMany: async ({ model, where }) => {
299
- const table = activeDb[model];
300
- const res = convertWhereClause(where, model);
301
- let count = 0;
302
- activeDb[model] = table.filter((record) => {
303
- if (res.includes(record)) {
304
- count++;
305
- return false;
306
- }
307
- return !res.includes(record);
308
- });
309
- return count;
310
- },
311
- consumeOne: async ({ model, where }) => {
312
- const table = activeDb[model];
313
- const target = convertWhereClause(where, model)[0];
314
- if (!target) return null;
315
- activeDb[model] = table.filter((record) => record !== target);
316
- return target;
317
- },
318
- incrementOne: async ({ model, where, increment, set }) => {
319
- const target = convertWhereClause(where, model)[0];
320
- if (!target) return null;
321
- for (const [field, delta] of Object.entries(increment)) target[field] = (typeof target[field] === "number" ? target[field] : 0) + delta;
322
- if (set) Object.assign(target, set);
323
- return target;
324
- },
325
- updateMany: async ({ model, where, update }) => {
326
- const res = convertWhereClause(where, model);
327
- res.forEach((record) => {
328
- Object.assign(record, update);
329
- });
330
- return res.length;
331
- }
332
- };
333
- }
334
- });
335
- const adapterCreator = buildAdapterFactory(db);
336
- return (options) => {
337
- lazyOptions = options;
338
- return adapterCreator(options);
339
- };
340
- };
341
- //#endregion
342
- export { memoryAdapter };