@aigne/afs-sqlite 1.1.0 → 1.11.0-beta.1

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 (163) hide show
  1. package/LICENSE.md +17 -84
  2. package/README.md +51 -39
  3. package/dist/actions/built-in.cjs +142 -0
  4. package/dist/actions/built-in.d.cts +10 -0
  5. package/dist/actions/built-in.d.cts.map +1 -0
  6. package/dist/actions/built-in.d.mts +10 -0
  7. package/dist/actions/built-in.d.mts.map +1 -0
  8. package/dist/actions/built-in.mjs +143 -0
  9. package/dist/actions/built-in.mjs.map +1 -0
  10. package/dist/actions/registry.cjs +91 -0
  11. package/dist/actions/registry.d.cts +54 -0
  12. package/dist/actions/registry.d.cts.map +1 -0
  13. package/dist/actions/registry.d.mts +54 -0
  14. package/dist/actions/registry.d.mts.map +1 -0
  15. package/dist/actions/registry.mjs +91 -0
  16. package/dist/actions/registry.mjs.map +1 -0
  17. package/dist/actions/types.d.cts +56 -0
  18. package/dist/actions/types.d.cts.map +1 -0
  19. package/dist/actions/types.d.mts +56 -0
  20. package/dist/actions/types.d.mts.map +1 -0
  21. package/dist/config.cjs +27 -0
  22. package/dist/config.d.cts +81 -0
  23. package/dist/config.d.cts.map +1 -0
  24. package/dist/config.d.mts +81 -0
  25. package/dist/config.d.mts.map +1 -0
  26. package/dist/config.mjs +28 -0
  27. package/dist/config.mjs.map +1 -0
  28. package/dist/index.cjs +38 -0
  29. package/dist/index.d.cts +14 -0
  30. package/dist/index.d.mts +14 -0
  31. package/dist/index.mjs +12 -0
  32. package/dist/node/builder.cjs +179 -0
  33. package/dist/node/builder.d.cts +48 -0
  34. package/dist/node/builder.d.cts.map +1 -0
  35. package/dist/node/builder.d.mts +48 -0
  36. package/dist/node/builder.d.mts.map +1 -0
  37. package/dist/node/builder.mjs +172 -0
  38. package/dist/node/builder.mjs.map +1 -0
  39. package/dist/operations/crud.cjs +176 -0
  40. package/dist/operations/crud.d.cts +69 -0
  41. package/dist/operations/crud.d.cts.map +1 -0
  42. package/dist/operations/crud.d.mts +69 -0
  43. package/dist/operations/crud.d.mts.map +1 -0
  44. package/dist/operations/crud.mjs +177 -0
  45. package/dist/operations/crud.mjs.map +1 -0
  46. package/dist/operations/query-builder.cjs +77 -0
  47. package/dist/operations/query-builder.d.cts +34 -0
  48. package/dist/operations/query-builder.d.cts.map +1 -0
  49. package/dist/operations/query-builder.d.mts +34 -0
  50. package/dist/operations/query-builder.d.mts.map +1 -0
  51. package/dist/operations/query-builder.mjs +72 -0
  52. package/dist/operations/query-builder.mjs.map +1 -0
  53. package/dist/operations/search.cjs +141 -0
  54. package/dist/operations/search.d.cts +79 -0
  55. package/dist/operations/search.d.cts.map +1 -0
  56. package/dist/operations/search.d.mts +79 -0
  57. package/dist/operations/search.d.mts.map +1 -0
  58. package/dist/operations/search.mjs +141 -0
  59. package/dist/operations/search.mjs.map +1 -0
  60. package/dist/router/path-router.cjs +79 -0
  61. package/{lib/dts/router/path-router.d.ts → dist/router/path-router.d.cts} +12 -8
  62. package/dist/router/path-router.d.cts.map +1 -0
  63. package/{lib/cjs/router/path-router.d.ts → dist/router/path-router.d.mts} +12 -8
  64. package/dist/router/path-router.d.mts.map +1 -0
  65. package/dist/router/path-router.mjs +76 -0
  66. package/dist/router/path-router.mjs.map +1 -0
  67. package/dist/router/types.d.cts +34 -0
  68. package/dist/router/types.d.cts.map +1 -0
  69. package/dist/router/types.d.mts +34 -0
  70. package/dist/router/types.d.mts.map +1 -0
  71. package/dist/schema/introspector.cjs +160 -0
  72. package/dist/schema/introspector.d.cts +49 -0
  73. package/dist/schema/introspector.d.cts.map +1 -0
  74. package/dist/schema/introspector.d.mts +49 -0
  75. package/dist/schema/introspector.d.mts.map +1 -0
  76. package/dist/schema/introspector.mjs +161 -0
  77. package/dist/schema/introspector.mjs.map +1 -0
  78. package/dist/schema/types.cjs +15 -0
  79. package/dist/schema/types.d.cts +104 -0
  80. package/dist/schema/types.d.cts.map +1 -0
  81. package/dist/schema/types.d.mts +104 -0
  82. package/dist/schema/types.d.mts.map +1 -0
  83. package/dist/schema/types.mjs +15 -0
  84. package/dist/schema/types.mjs.map +1 -0
  85. package/dist/sqlite-afs.cjs +264 -0
  86. package/dist/sqlite-afs.d.cts +152 -0
  87. package/dist/sqlite-afs.d.cts.map +1 -0
  88. package/dist/sqlite-afs.d.mts +152 -0
  89. package/dist/sqlite-afs.d.mts.map +1 -0
  90. package/dist/sqlite-afs.mjs +265 -0
  91. package/dist/sqlite-afs.mjs.map +1 -0
  92. package/package.json +31 -44
  93. package/CHANGELOG.md +0 -73
  94. package/lib/cjs/actions/built-in.d.ts +0 -5
  95. package/lib/cjs/actions/built-in.js +0 -165
  96. package/lib/cjs/actions/registry.d.ts +0 -49
  97. package/lib/cjs/actions/registry.js +0 -102
  98. package/lib/cjs/actions/types.d.ts +0 -51
  99. package/lib/cjs/actions/types.js +0 -2
  100. package/lib/cjs/config.d.ts +0 -89
  101. package/lib/cjs/config.js +0 -33
  102. package/lib/cjs/index.d.ts +0 -13
  103. package/lib/cjs/index.js +0 -47
  104. package/lib/cjs/node/builder.d.ts +0 -43
  105. package/lib/cjs/node/builder.js +0 -187
  106. package/lib/cjs/operations/crud.d.ts +0 -64
  107. package/lib/cjs/operations/crud.js +0 -225
  108. package/lib/cjs/operations/query-builder.d.ts +0 -37
  109. package/lib/cjs/operations/query-builder.js +0 -102
  110. package/lib/cjs/operations/search.d.ts +0 -75
  111. package/lib/cjs/operations/search.js +0 -172
  112. package/lib/cjs/package.json +0 -3
  113. package/lib/cjs/router/path-router.js +0 -90
  114. package/lib/cjs/router/types.d.ts +0 -30
  115. package/lib/cjs/router/types.js +0 -2
  116. package/lib/cjs/schema/introspector.d.ts +0 -48
  117. package/lib/cjs/schema/introspector.js +0 -186
  118. package/lib/cjs/schema/types.d.ts +0 -104
  119. package/lib/cjs/schema/types.js +0 -13
  120. package/lib/cjs/sqlite-afs.d.ts +0 -144
  121. package/lib/cjs/sqlite-afs.js +0 -337
  122. package/lib/dts/actions/built-in.d.ts +0 -5
  123. package/lib/dts/actions/registry.d.ts +0 -49
  124. package/lib/dts/actions/types.d.ts +0 -51
  125. package/lib/dts/config.d.ts +0 -89
  126. package/lib/dts/index.d.ts +0 -13
  127. package/lib/dts/node/builder.d.ts +0 -43
  128. package/lib/dts/operations/crud.d.ts +0 -64
  129. package/lib/dts/operations/query-builder.d.ts +0 -37
  130. package/lib/dts/operations/search.d.ts +0 -75
  131. package/lib/dts/router/types.d.ts +0 -30
  132. package/lib/dts/schema/introspector.d.ts +0 -48
  133. package/lib/dts/schema/types.d.ts +0 -104
  134. package/lib/dts/sqlite-afs.d.ts +0 -144
  135. package/lib/esm/actions/built-in.d.ts +0 -5
  136. package/lib/esm/actions/built-in.js +0 -162
  137. package/lib/esm/actions/registry.d.ts +0 -49
  138. package/lib/esm/actions/registry.js +0 -98
  139. package/lib/esm/actions/types.d.ts +0 -51
  140. package/lib/esm/actions/types.js +0 -1
  141. package/lib/esm/config.d.ts +0 -89
  142. package/lib/esm/config.js +0 -30
  143. package/lib/esm/index.d.ts +0 -13
  144. package/lib/esm/index.js +0 -17
  145. package/lib/esm/node/builder.d.ts +0 -43
  146. package/lib/esm/node/builder.js +0 -177
  147. package/lib/esm/operations/crud.d.ts +0 -64
  148. package/lib/esm/operations/crud.js +0 -221
  149. package/lib/esm/operations/query-builder.d.ts +0 -37
  150. package/lib/esm/operations/query-builder.js +0 -92
  151. package/lib/esm/operations/search.d.ts +0 -75
  152. package/lib/esm/operations/search.js +0 -167
  153. package/lib/esm/package.json +0 -3
  154. package/lib/esm/router/path-router.d.ts +0 -38
  155. package/lib/esm/router/path-router.js +0 -83
  156. package/lib/esm/router/types.d.ts +0 -30
  157. package/lib/esm/router/types.js +0 -1
  158. package/lib/esm/schema/introspector.d.ts +0 -48
  159. package/lib/esm/schema/introspector.js +0 -182
  160. package/lib/esm/schema/types.d.ts +0 -104
  161. package/lib/esm/schema/types.js +0 -10
  162. package/lib/esm/sqlite-afs.d.ts +0 -144
  163. package/lib/esm/sqlite-afs.js +0 -333
package/LICENSE.md CHANGED
@@ -1,93 +1,26 @@
1
- Elastic License 2.0
1
+ # Proprietary License
2
2
 
3
- URL: https://www.elastic.co/licensing/elastic-license
3
+ Copyright (c) 2024-2025 ArcBlock, Inc. All Rights Reserved.
4
4
 
5
- ## Acceptance
5
+ This software and associated documentation files (the "Software") are proprietary
6
+ and confidential. Unauthorized copying, modification, distribution, or use of
7
+ this Software, via any medium, is strictly prohibited.
6
8
 
7
- By using the software, you agree to all of the terms and conditions below.
9
+ The Software is provided for internal use only within ArcBlock, Inc. and its
10
+ authorized affiliates.
8
11
 
9
- ## Copyright License
12
+ ## No License Granted
10
13
 
11
- The licensor grants you a non-exclusive, royalty-free, worldwide,
12
- non-sublicensable, non-transferable license to use, copy, distribute, make
13
- available, and prepare derivative works of the software, in each case subject to
14
- the limitations and conditions below.
14
+ No license, express or implied, is granted to any party for any purpose.
15
+ All rights are reserved by ArcBlock, Inc.
15
16
 
16
- ## Limitations
17
+ ## Public Artifact Distribution
17
18
 
18
- You may not provide the software to third parties as a hosted or managed
19
- service, where the service provides users with access to any substantial set of
20
- the features or functionality of the software.
19
+ Portions of this Software may be released publicly under separate open-source
20
+ licenses (such as MIT License) through designated public repositories. Such
21
+ public releases are governed by their respective licenses and do not affect
22
+ the proprietary nature of this repository.
21
23
 
22
- You may not move, change, disable, or circumvent the license key functionality
23
- in the software, and you may not remove or obscure any functionality in the
24
- software that is protected by the license key.
24
+ ## Contact
25
25
 
26
- You may not alter, remove, or obscure any licensing, copyright, or other notices
27
- of the licensor in the software. Any use of the licensor’s trademarks is subject
28
- to applicable law.
29
-
30
- ## Patents
31
-
32
- The licensor grants you a license, under any patent claims the licensor can
33
- license, or becomes able to license, to make, have made, use, sell, offer for
34
- sale, import and have imported the software, in each case subject to the
35
- limitations and conditions in this license. This license does not cover any
36
- patent claims that you cause to be infringed by modifications or additions to
37
- the software. If you or your company make any written claim that the software
38
- infringes or contributes to infringement of any patent, your patent license for
39
- the software granted under these terms ends immediately. If your company makes
40
- such a claim, your patent license ends immediately for work on behalf of your
41
- company.
42
-
43
- ## Notices
44
-
45
- You must ensure that anyone who gets a copy of any part of the software from you
46
- also gets a copy of these terms.
47
-
48
- If you modify the software, you must include in any modified copies of the
49
- software prominent notices stating that you have modified the software.
50
-
51
- ## No Other Rights
52
-
53
- These terms do not imply any licenses other than those expressly granted in
54
- these terms.
55
-
56
- ## Termination
57
-
58
- If you use the software in violation of these terms, such use is not licensed,
59
- and your licenses will automatically terminate. If the licensor provides you
60
- with a notice of your violation, and you cease all violation of this license no
61
- later than 30 days after you receive that notice, your licenses will be
62
- reinstated retroactively. However, if you violate these terms after such
63
- reinstatement, any additional violation of these terms will cause your licenses
64
- to terminate automatically and permanently.
65
-
66
- ## No Liability
67
-
68
- *As far as the law allows, the software comes as is, without any warranty or
69
- condition, and the licensor will not be liable to you for any damages arising
70
- out of these terms or the use or nature of the software, under any kind of
71
- legal claim.*
72
-
73
- ## Definitions
74
-
75
- The **licensor** is the entity offering these terms, and the **software** is the
76
- software the licensor makes available under these terms, including any portion
77
- of it.
78
-
79
- **you** refers to the individual or entity agreeing to these terms.
80
-
81
- **your company** is any legal entity, sole proprietorship, or other kind of
82
- organization that you work for, plus all organizations that have control over,
83
- are under the control of, or are under common control with that
84
- organization. **control** means ownership of substantially all the assets of an
85
- entity, or the power to direct its management and policies by vote, contract, or
86
- otherwise. Control can be direct or indirect.
87
-
88
- **your licenses** are all the licenses granted to you for the software under
89
- these terms.
90
-
91
- **use** means anything you do with the software requiring one of your licenses.
92
-
93
- **trademark** means trademarks, service marks, and similar rights.
26
+ For licensing inquiries, contact: legal@arcblock.io
package/README.md CHANGED
@@ -36,10 +36,12 @@ import { SQLiteAFS } from "@aigne/afs-sqlite";
36
36
  const afs = new AFS();
37
37
 
38
38
  // Mount SQLite module
39
- afs.mount(new SQLiteAFS({
40
- url: "file:./database.sqlite3",
41
- accessMode: "readwrite"
42
- }));
39
+ afs.mount(
40
+ new SQLiteAFS({
41
+ url: "file:./database.sqlite3",
42
+ accessMode: "readwrite",
43
+ }),
44
+ );
43
45
 
44
46
  // List all tables
45
47
  const tables = await afs.list("/modules/sqlite-afs");
@@ -52,12 +54,12 @@ const user = await afs.read("/modules/sqlite-afs/users/1");
52
54
 
53
55
  // Create a new row
54
56
  await afs.write("/modules/sqlite-afs/users", {
55
- content: { name: "John", email: "john@example.com" }
57
+ content: { name: "John", email: "john@example.com" },
56
58
  });
57
59
 
58
60
  // Update an existing row
59
61
  await afs.write("/modules/sqlite-afs/users/1", {
60
- content: { name: "John Doe" }
62
+ content: { name: "John Doe" },
61
63
  });
62
64
 
63
65
  // Delete a row
@@ -104,17 +106,17 @@ interface SQLiteAFSOptions {
104
106
 
105
107
  The module exposes the following path patterns:
106
108
 
107
- | Path | Description |
108
- |------|-------------|
109
- | `/` | List all tables |
110
- | `/:table` | List rows in table or create new row |
111
- | `/:table/@schema` | Get table schema |
112
- | `/:table/:pk` | Read/update/delete specific row |
113
- | `/:table/:pk/@attr` | List row attributes (columns) |
114
- | `/:table/:pk/@attr/:column` | Get specific column value |
115
- | `/:table/:pk/@meta` | Get row metadata |
116
- | `/:table/:pk/@actions` | List available actions |
117
- | `/:table/:pk/@actions/:action` | Execute an action |
109
+ | Path | Description |
110
+ | ------------------------------ | ------------------------------------ |
111
+ | `/` | List all tables |
112
+ | `/:table` | List rows in table or create new row |
113
+ | `/:table/@schema` | Get table schema |
114
+ | `/:table/:pk` | Read/update/delete specific row |
115
+ | `/:table/:pk/@attr` | List row attributes (columns) |
116
+ | `/:table/:pk/@attr/:column` | Get specific column value |
117
+ | `/:table/:pk/@meta` | Get row metadata |
118
+ | `/:table/:pk/@actions` | List available actions |
119
+ | `/:table/:pk/@actions/:action` | Execute an action |
118
120
 
119
121
  ## Built-in Actions
120
122
 
@@ -131,14 +133,20 @@ The module exposes the following path patterns:
131
133
 
132
134
  ```typescript
133
135
  // Validate a row
134
- const result = await afs.write("/modules/sqlite-afs/users/1/@actions/validate", {
135
- content: {}
136
- });
136
+ const result = await afs.write(
137
+ "/modules/sqlite-afs/users/1/@actions/validate",
138
+ {
139
+ content: {},
140
+ },
141
+ );
137
142
 
138
143
  // Duplicate a row
139
- const result = await afs.write("/modules/sqlite-afs/users/1/@actions/duplicate", {
140
- content: {}
141
- });
144
+ const result = await afs.write(
145
+ "/modules/sqlite-afs/users/1/@actions/duplicate",
146
+ {
147
+ content: {},
148
+ },
149
+ );
142
150
 
143
151
  // Export table data
144
152
  const jsonData = await sqliteAfs.exportTable("users", "json");
@@ -156,14 +164,16 @@ sqliteAfs.registerAction(
156
164
  "archive",
157
165
  async (ctx, params) => {
158
166
  // ctx contains: db, schemas, table, pk, row, module
159
- await ctx.db.run(sql.raw(`UPDATE "${ctx.table}" SET archived = 1 WHERE id = '${ctx.pk}'`));
167
+ await ctx.db.run(
168
+ sql.raw(`UPDATE "${ctx.table}" SET archived = 1 WHERE id = '${ctx.pk}'`),
169
+ );
160
170
  return { archived: true };
161
171
  },
162
172
  {
163
173
  description: "Archive the row",
164
174
  rowLevel: true,
165
- tableLevel: false
166
- }
175
+ tableLevel: false,
176
+ },
167
177
  );
168
178
  ```
169
179
 
@@ -178,16 +188,19 @@ const sqliteAfs = new SQLiteAFS({
178
188
  enabled: true,
179
189
  tables: {
180
190
  posts: ["title", "content"],
181
- users: ["name", "bio"]
182
- }
183
- }
191
+ users: ["name", "bio"],
192
+ },
193
+ },
184
194
  });
185
195
 
186
196
  // Search across all FTS-enabled tables
187
197
  const results = await afs.search("/modules/sqlite-afs", "search query");
188
198
 
189
199
  // Search within a specific table
190
- const postResults = await afs.search("/modules/sqlite-afs/posts", "search query");
200
+ const postResults = await afs.search(
201
+ "/modules/sqlite-afs/posts",
202
+ "search query",
203
+ );
191
204
  ```
192
205
 
193
206
  ## Advanced Usage
@@ -223,19 +236,21 @@ import { AFS } from "@aigne/afs";
223
236
  import { SQLiteAFS } from "@aigne/afs-sqlite";
224
237
 
225
238
  const afs = new AFS();
226
- afs.mount(new SQLiteAFS({
227
- url: "file:./database.sqlite3",
228
- accessMode: "readwrite"
229
- }));
239
+ afs.mount(
240
+ new SQLiteAFS({
241
+ url: "file:./database.sqlite3",
242
+ accessMode: "readwrite",
243
+ }),
244
+ );
230
245
 
231
246
  const agent = AIAgent.from({
232
247
  name: "database-assistant",
233
- afs: afs
248
+ afs: afs,
234
249
  });
235
250
 
236
251
  const context = aigne.newContext();
237
252
  const result = await context.invoke(agent, {
238
- message: "Show me all users in the database"
253
+ message: "Show me all users in the database",
239
254
  });
240
255
  ```
241
256
 
@@ -272,6 +287,3 @@ afs:
272
287
 
273
288
  This package includes full TypeScript type definitions.
274
289
 
275
- ## License
276
-
277
- [Elastic-2.0](../../LICENSE.md)
@@ -0,0 +1,142 @@
1
+ let _aigne_sqlite = require("@aigne/sqlite");
2
+
3
+ //#region src/actions/built-in.ts
4
+ /**
5
+ * Executes a raw SQL query and returns all rows
6
+ */
7
+ async function execAll(db, query) {
8
+ return db.all(_aigne_sqlite.sql.raw(query)).execute();
9
+ }
10
+ /**
11
+ * Executes a raw SQL query (for INSERT, UPDATE, DELETE)
12
+ */
13
+ async function execRun(db, query) {
14
+ await db.run(_aigne_sqlite.sql.raw(query)).execute();
15
+ }
16
+ /**
17
+ * Registers built-in actions to the registry
18
+ */
19
+ function registerBuiltInActions(registry) {
20
+ registry.register({
21
+ name: "refresh",
22
+ description: "Refresh the schema cache for this module",
23
+ tableLevel: true,
24
+ rowLevel: false,
25
+ handler: async (ctx) => {
26
+ await ctx.module.refreshSchema();
27
+ return {
28
+ success: true,
29
+ message: "Schema refreshed successfully"
30
+ };
31
+ }
32
+ });
33
+ registry.register({
34
+ name: "export",
35
+ description: "Export table data in specified format (json, csv)",
36
+ tableLevel: true,
37
+ rowLevel: false,
38
+ inputSchema: {
39
+ type: "object",
40
+ properties: { format: {
41
+ type: "string",
42
+ enum: ["json", "csv"],
43
+ default: "json"
44
+ } }
45
+ },
46
+ handler: async (ctx, params) => {
47
+ const format = params.format ?? "json";
48
+ return {
49
+ success: true,
50
+ data: await ctx.module.exportTable(ctx.table, format)
51
+ };
52
+ }
53
+ });
54
+ registry.register({
55
+ name: "count",
56
+ description: "Get the total row count for this table",
57
+ tableLevel: true,
58
+ rowLevel: false,
59
+ handler: async (ctx) => {
60
+ return {
61
+ success: true,
62
+ data: { count: (await execAll(ctx.db, `SELECT COUNT(*) as count FROM "${ctx.table}"`))[0]?.count ?? 0 }
63
+ };
64
+ }
65
+ });
66
+ registry.register({
67
+ name: "duplicate",
68
+ description: "Create a copy of this row",
69
+ tableLevel: false,
70
+ rowLevel: true,
71
+ handler: async (ctx) => {
72
+ if (!ctx.row) return {
73
+ success: false,
74
+ message: "Row data not available"
75
+ };
76
+ const schema = ctx.schemas.get(ctx.table);
77
+ if (!schema) return {
78
+ success: false,
79
+ message: `Table '${ctx.table}' not found`
80
+ };
81
+ const pkColumn = schema.primaryKey[0] ?? "rowid";
82
+ const rowCopy = { ...ctx.row };
83
+ delete rowCopy[pkColumn];
84
+ delete rowCopy.rowid;
85
+ const columns = Object.keys(rowCopy);
86
+ const values = columns.map((col) => formatValueForSQL(rowCopy[col]));
87
+ await execRun(ctx.db, `INSERT INTO "${ctx.table}" (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${values.join(", ")})`);
88
+ return {
89
+ success: true,
90
+ data: { newId: (await execAll(ctx.db, "SELECT last_insert_rowid() as id"))[0]?.id },
91
+ message: "Row duplicated successfully"
92
+ };
93
+ }
94
+ });
95
+ registry.register({
96
+ name: "validate",
97
+ description: "Validate row data against schema constraints",
98
+ tableLevel: false,
99
+ rowLevel: true,
100
+ handler: async (ctx) => {
101
+ if (!ctx.row) return {
102
+ success: false,
103
+ message: "Row data not available"
104
+ };
105
+ const schema = ctx.schemas.get(ctx.table);
106
+ if (!schema) return {
107
+ success: false,
108
+ message: `Table '${ctx.table}' not found`
109
+ };
110
+ const errors = [];
111
+ for (const col of schema.columns) if (col.notnull && (ctx.row[col.name] === null || ctx.row[col.name] === void 0)) errors.push(`Column '${col.name}' cannot be null`);
112
+ for (const fk of schema.foreignKeys) {
113
+ const value = ctx.row[fk.from];
114
+ if (value !== null && value !== void 0) {
115
+ if ((await execAll(ctx.db, `SELECT COUNT(*) as count FROM "${fk.table}" WHERE "${fk.to}" = '${String(value).replace(/'/g, "''")}'`))[0]?.count === 0) errors.push(`Foreign key violation: ${fk.from} references non-existent ${fk.table}.${fk.to}`);
116
+ }
117
+ }
118
+ return {
119
+ success: errors.length === 0,
120
+ data: {
121
+ errors,
122
+ valid: errors.length === 0
123
+ },
124
+ message: errors.length > 0 ? `Validation failed: ${errors.join("; ")}` : "Row is valid"
125
+ };
126
+ }
127
+ });
128
+ }
129
+ /**
130
+ * Formats a value for SQL insertion
131
+ */
132
+ function formatValueForSQL(value) {
133
+ if (value === null || value === void 0) return "NULL";
134
+ if (typeof value === "number") return String(value);
135
+ if (typeof value === "boolean") return value ? "1" : "0";
136
+ if (value instanceof Date) return `'${value.toISOString()}'`;
137
+ if (typeof value === "object") return `'${JSON.stringify(value).replace(/'/g, "''")}'`;
138
+ return `'${String(value).replace(/'/g, "''")}'`;
139
+ }
140
+
141
+ //#endregion
142
+ exports.registerBuiltInActions = registerBuiltInActions;
@@ -0,0 +1,10 @@
1
+ import { ActionsRegistry } from "./registry.cjs";
2
+
3
+ //#region src/actions/built-in.d.ts
4
+ /**
5
+ * Registers built-in actions to the registry
6
+ */
7
+ declare function registerBuiltInActions(registry: ActionsRegistry): void;
8
+ //#endregion
9
+ export { registerBuiltInActions };
10
+ //# sourceMappingURL=built-in.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"built-in.d.cts","names":[],"sources":["../../src/actions/built-in.ts"],"mappings":";;;;AAsBA;;iBAAgB,sBAAA,CAAA,QAAA,EAAiC,eAAA"}
@@ -0,0 +1,10 @@
1
+ import { ActionsRegistry } from "./registry.mjs";
2
+
3
+ //#region src/actions/built-in.d.ts
4
+ /**
5
+ * Registers built-in actions to the registry
6
+ */
7
+ declare function registerBuiltInActions(registry: ActionsRegistry): void;
8
+ //#endregion
9
+ export { registerBuiltInActions };
10
+ //# sourceMappingURL=built-in.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"built-in.d.mts","names":[],"sources":["../../src/actions/built-in.ts"],"mappings":";;;;AAsBA;;iBAAgB,sBAAA,CAAA,QAAA,EAAiC,eAAA"}
@@ -0,0 +1,143 @@
1
+ import { sql } from "@aigne/sqlite";
2
+
3
+ //#region src/actions/built-in.ts
4
+ /**
5
+ * Executes a raw SQL query and returns all rows
6
+ */
7
+ async function execAll(db, query) {
8
+ return db.all(sql.raw(query)).execute();
9
+ }
10
+ /**
11
+ * Executes a raw SQL query (for INSERT, UPDATE, DELETE)
12
+ */
13
+ async function execRun(db, query) {
14
+ await db.run(sql.raw(query)).execute();
15
+ }
16
+ /**
17
+ * Registers built-in actions to the registry
18
+ */
19
+ function registerBuiltInActions(registry) {
20
+ registry.register({
21
+ name: "refresh",
22
+ description: "Refresh the schema cache for this module",
23
+ tableLevel: true,
24
+ rowLevel: false,
25
+ handler: async (ctx) => {
26
+ await ctx.module.refreshSchema();
27
+ return {
28
+ success: true,
29
+ message: "Schema refreshed successfully"
30
+ };
31
+ }
32
+ });
33
+ registry.register({
34
+ name: "export",
35
+ description: "Export table data in specified format (json, csv)",
36
+ tableLevel: true,
37
+ rowLevel: false,
38
+ inputSchema: {
39
+ type: "object",
40
+ properties: { format: {
41
+ type: "string",
42
+ enum: ["json", "csv"],
43
+ default: "json"
44
+ } }
45
+ },
46
+ handler: async (ctx, params) => {
47
+ const format = params.format ?? "json";
48
+ return {
49
+ success: true,
50
+ data: await ctx.module.exportTable(ctx.table, format)
51
+ };
52
+ }
53
+ });
54
+ registry.register({
55
+ name: "count",
56
+ description: "Get the total row count for this table",
57
+ tableLevel: true,
58
+ rowLevel: false,
59
+ handler: async (ctx) => {
60
+ return {
61
+ success: true,
62
+ data: { count: (await execAll(ctx.db, `SELECT COUNT(*) as count FROM "${ctx.table}"`))[0]?.count ?? 0 }
63
+ };
64
+ }
65
+ });
66
+ registry.register({
67
+ name: "duplicate",
68
+ description: "Create a copy of this row",
69
+ tableLevel: false,
70
+ rowLevel: true,
71
+ handler: async (ctx) => {
72
+ if (!ctx.row) return {
73
+ success: false,
74
+ message: "Row data not available"
75
+ };
76
+ const schema = ctx.schemas.get(ctx.table);
77
+ if (!schema) return {
78
+ success: false,
79
+ message: `Table '${ctx.table}' not found`
80
+ };
81
+ const pkColumn = schema.primaryKey[0] ?? "rowid";
82
+ const rowCopy = { ...ctx.row };
83
+ delete rowCopy[pkColumn];
84
+ delete rowCopy.rowid;
85
+ const columns = Object.keys(rowCopy);
86
+ const values = columns.map((col) => formatValueForSQL(rowCopy[col]));
87
+ await execRun(ctx.db, `INSERT INTO "${ctx.table}" (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${values.join(", ")})`);
88
+ return {
89
+ success: true,
90
+ data: { newId: (await execAll(ctx.db, "SELECT last_insert_rowid() as id"))[0]?.id },
91
+ message: "Row duplicated successfully"
92
+ };
93
+ }
94
+ });
95
+ registry.register({
96
+ name: "validate",
97
+ description: "Validate row data against schema constraints",
98
+ tableLevel: false,
99
+ rowLevel: true,
100
+ handler: async (ctx) => {
101
+ if (!ctx.row) return {
102
+ success: false,
103
+ message: "Row data not available"
104
+ };
105
+ const schema = ctx.schemas.get(ctx.table);
106
+ if (!schema) return {
107
+ success: false,
108
+ message: `Table '${ctx.table}' not found`
109
+ };
110
+ const errors = [];
111
+ for (const col of schema.columns) if (col.notnull && (ctx.row[col.name] === null || ctx.row[col.name] === void 0)) errors.push(`Column '${col.name}' cannot be null`);
112
+ for (const fk of schema.foreignKeys) {
113
+ const value = ctx.row[fk.from];
114
+ if (value !== null && value !== void 0) {
115
+ if ((await execAll(ctx.db, `SELECT COUNT(*) as count FROM "${fk.table}" WHERE "${fk.to}" = '${String(value).replace(/'/g, "''")}'`))[0]?.count === 0) errors.push(`Foreign key violation: ${fk.from} references non-existent ${fk.table}.${fk.to}`);
116
+ }
117
+ }
118
+ return {
119
+ success: errors.length === 0,
120
+ data: {
121
+ errors,
122
+ valid: errors.length === 0
123
+ },
124
+ message: errors.length > 0 ? `Validation failed: ${errors.join("; ")}` : "Row is valid"
125
+ };
126
+ }
127
+ });
128
+ }
129
+ /**
130
+ * Formats a value for SQL insertion
131
+ */
132
+ function formatValueForSQL(value) {
133
+ if (value === null || value === void 0) return "NULL";
134
+ if (typeof value === "number") return String(value);
135
+ if (typeof value === "boolean") return value ? "1" : "0";
136
+ if (value instanceof Date) return `'${value.toISOString()}'`;
137
+ if (typeof value === "object") return `'${JSON.stringify(value).replace(/'/g, "''")}'`;
138
+ return `'${String(value).replace(/'/g, "''")}'`;
139
+ }
140
+
141
+ //#endregion
142
+ export { registerBuiltInActions };
143
+ //# sourceMappingURL=built-in.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"built-in.mjs","names":[],"sources":["../../src/actions/built-in.ts"],"sourcesContent":["import { sql } from \"@aigne/sqlite\";\nimport type { LibSQLDatabase } from \"drizzle-orm/libsql\";\nimport type { ActionsRegistry } from \"./registry.js\";\nimport type { ActionContext, ActionResult } from \"./types.js\";\n\n/**\n * Executes a raw SQL query and returns all rows\n */\nasync function execAll<T>(db: LibSQLDatabase, query: string): Promise<T[]> {\n return db.all<T>(sql.raw(query)).execute();\n}\n\n/**\n * Executes a raw SQL query (for INSERT, UPDATE, DELETE)\n */\nasync function execRun(db: LibSQLDatabase, query: string): Promise<void> {\n await db.run(sql.raw(query)).execute();\n}\n\n/**\n * Registers built-in actions to the registry\n */\nexport function registerBuiltInActions(registry: ActionsRegistry): void {\n // Refresh schema action (table level)\n registry.register({\n name: \"refresh\",\n description: \"Refresh the schema cache for this module\",\n tableLevel: true,\n rowLevel: false,\n handler: async (ctx: ActionContext): Promise<ActionResult> => {\n await ctx.module.refreshSchema();\n return {\n success: true,\n message: \"Schema refreshed successfully\",\n };\n },\n });\n\n // Export table action (table level)\n registry.register({\n name: \"export\",\n description: \"Export table data in specified format (json, csv)\",\n tableLevel: true,\n rowLevel: false,\n inputSchema: {\n type: \"object\",\n properties: {\n format: {\n type: \"string\",\n enum: [\"json\", \"csv\"],\n default: \"json\",\n },\n },\n },\n handler: async (ctx: ActionContext, params): Promise<ActionResult> => {\n const format = (params.format as string) ?? \"json\";\n const data = await ctx.module.exportTable(ctx.table, format);\n return {\n success: true,\n data,\n };\n },\n });\n\n // Count rows action (table level)\n registry.register({\n name: \"count\",\n description: \"Get the total row count for this table\",\n tableLevel: true,\n rowLevel: false,\n handler: async (ctx: ActionContext): Promise<ActionResult> => {\n const result = await execAll<{ count: number }>(\n ctx.db,\n `SELECT COUNT(*) as count FROM \"${ctx.table}\"`,\n );\n return {\n success: true,\n data: { count: result[0]?.count ?? 0 },\n };\n },\n });\n\n // Duplicate row action (row level)\n registry.register({\n name: \"duplicate\",\n description: \"Create a copy of this row\",\n tableLevel: false,\n rowLevel: true,\n handler: async (ctx: ActionContext): Promise<ActionResult> => {\n if (!ctx.row) {\n return { success: false, message: \"Row data not available\" };\n }\n\n const schema = ctx.schemas.get(ctx.table);\n if (!schema) {\n return { success: false, message: `Table '${ctx.table}' not found` };\n }\n\n // Create a copy without the primary key\n const pkColumn = schema.primaryKey[0] ?? \"rowid\";\n const rowCopy = { ...ctx.row };\n delete rowCopy[pkColumn];\n delete rowCopy.rowid;\n\n // Build insert query\n const columns = Object.keys(rowCopy);\n const values = columns.map((col) => formatValueForSQL(rowCopy[col]));\n\n await execRun(\n ctx.db,\n `INSERT INTO \"${ctx.table}\" (${columns.map((c) => `\"${c}\"`).join(\", \")}) VALUES (${values.join(\", \")})`,\n );\n\n // Get the new row's ID\n const lastIdResult = await execAll<{ id: number }>(\n ctx.db,\n \"SELECT last_insert_rowid() as id\",\n );\n\n return {\n success: true,\n data: { newId: lastIdResult[0]?.id },\n message: \"Row duplicated successfully\",\n };\n },\n });\n\n // Validate row action (row level)\n registry.register({\n name: \"validate\",\n description: \"Validate row data against schema constraints\",\n tableLevel: false,\n rowLevel: true,\n handler: async (ctx: ActionContext): Promise<ActionResult> => {\n if (!ctx.row) {\n return { success: false, message: \"Row data not available\" };\n }\n\n const schema = ctx.schemas.get(ctx.table);\n if (!schema) {\n return { success: false, message: `Table '${ctx.table}' not found` };\n }\n\n const errors: string[] = [];\n\n // Check NOT NULL constraints\n for (const col of schema.columns) {\n if (col.notnull && (ctx.row[col.name] === null || ctx.row[col.name] === undefined)) {\n errors.push(`Column '${col.name}' cannot be null`);\n }\n }\n\n // Check foreign key references\n for (const fk of schema.foreignKeys) {\n const value = ctx.row[fk.from];\n if (value !== null && value !== undefined) {\n const refResult = await execAll<{ count: number }>(\n ctx.db,\n `SELECT COUNT(*) as count FROM \"${fk.table}\" WHERE \"${fk.to}\" = '${String(value).replace(/'/g, \"''\")}'`,\n );\n if (refResult[0]?.count === 0) {\n errors.push(\n `Foreign key violation: ${fk.from} references non-existent ${fk.table}.${fk.to}`,\n );\n }\n }\n }\n\n return {\n success: errors.length === 0,\n data: { errors, valid: errors.length === 0 },\n message: errors.length > 0 ? `Validation failed: ${errors.join(\"; \")}` : \"Row is valid\",\n };\n },\n });\n}\n\n/**\n * Formats a value for SQL insertion\n */\nfunction formatValueForSQL(value: unknown): string {\n if (value === null || value === undefined) {\n return \"NULL\";\n }\n if (typeof value === \"number\") {\n return String(value);\n }\n if (typeof value === \"boolean\") {\n return value ? \"1\" : \"0\";\n }\n if (value instanceof Date) {\n return `'${value.toISOString()}'`;\n }\n if (typeof value === \"object\") {\n return `'${JSON.stringify(value).replace(/'/g, \"''\")}'`;\n }\n return `'${String(value).replace(/'/g, \"''\")}'`;\n}\n"],"mappings":";;;;;;AAQA,eAAe,QAAW,IAAoB,OAA6B;AACzE,QAAO,GAAG,IAAO,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS;;;;;AAM5C,eAAe,QAAQ,IAAoB,OAA8B;AACvE,OAAM,GAAG,IAAI,IAAI,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