@lensjs/core 1.0.7 → 1.0.10

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 (100) hide show
  1. package/dist/abstracts/adapter.cjs +70 -5
  2. package/dist/abstracts/adapter.js +37 -5
  3. package/dist/abstracts/store.cjs +26 -6
  4. package/dist/abstracts/store.js +3 -4
  5. package/dist/context/container.cjs +57 -6
  6. package/dist/context/container.js +34 -4
  7. package/dist/context/context.cjs +71 -7
  8. package/dist/context/context.js +42 -6
  9. package/dist/core/api_controller.cjs +148 -7
  10. package/dist/core/api_controller.js +121 -7
  11. package/dist/core/lens.cjs +404 -12
  12. package/dist/core/lens.js +370 -12
  13. package/dist/core/watcher.cjs +26 -6
  14. package/dist/core/watcher.js +3 -4
  15. package/dist/{index-D0Vszdac.d.ts → index-DiLfwsvc.d.cts} +2 -11
  16. package/dist/{index-D0Vszdac.d.cts → index-DiLfwsvc.d.ts} +2 -11
  17. package/dist/index.cjs +611 -55
  18. package/dist/index.d.cts +2 -4
  19. package/dist/index.d.ts +2 -4
  20. package/dist/index.js +556 -42
  21. package/dist/stores/better_sqlite.cjs +149 -7
  22. package/dist/stores/better_sqlite.js +116 -7
  23. package/dist/stores/index.cjs +153 -8
  24. package/dist/stores/index.js +116 -8
  25. package/dist/types/index.cjs +33 -6
  26. package/dist/types/index.js +6 -4
  27. package/dist/ui/assets/QueriesContainer-CAAsjjW5.js +2 -0
  28. package/dist/ui/assets/{QueryDetailsContainer-BkaktbOw.js → QueryDetailsContainer-E7P-IO7f.js} +19 -19
  29. package/dist/ui/assets/QueryTable-BcrtUssT.js +1 -0
  30. package/dist/ui/assets/RequestDetails-C2DZBu5H.js +1 -0
  31. package/dist/ui/assets/RequestDetailsContainer-DuDo-IqS.js +2 -0
  32. package/dist/ui/assets/{RequestsContainer-zoWMoB7o.js → RequestsContainer-DK3hQVz9.js} +2 -2
  33. package/dist/ui/assets/RequetsTable-DgP8p60b.js +1 -0
  34. package/dist/ui/assets/{StatusCode-DH20lQ6a.js → StatusCode-FQEjz7gK.js} +1 -1
  35. package/dist/ui/assets/TabbedDataViewer-cBDdPwIz.js +1 -0
  36. package/dist/ui/assets/{Table-HwlddLhp.js → Table-DYaXk80S.js} +2 -2
  37. package/dist/ui/assets/index-BS8XxorB.js +114 -0
  38. package/dist/ui/assets/index-CpP2Ap5X.js +1 -0
  39. package/dist/ui/assets/index-DzNHqeKh.css +1 -0
  40. package/dist/ui/assets/{useLensApi-Bmk2bGb0.js → useLensApi-DG6atd6d.js} +1 -1
  41. package/dist/ui/assets/{useLoadMore-CvIajdjM.js → useLoadMore-CJltToLI.js} +1 -1
  42. package/dist/ui/assets/{useQueries-DuyhGJyf.js → useQueries-C8mDDDc6.js} +1 -1
  43. package/dist/ui/index.html +2 -2
  44. package/dist/utils/event_emitter.cjs +42 -10
  45. package/dist/utils/event_emitter.d.cts +1 -11
  46. package/dist/utils/event_emitter.d.ts +1 -11
  47. package/dist/utils/event_emitter.js +6 -9
  48. package/dist/utils/index.cjs +163 -31
  49. package/dist/utils/index.d.cts +1 -2
  50. package/dist/utils/index.d.ts +1 -2
  51. package/dist/utils/index.js +109 -20
  52. package/dist/watchers/index.cjs +105 -10
  53. package/dist/watchers/index.js +79 -12
  54. package/dist/watchers/query_watcher.cjs +78 -8
  55. package/dist/watchers/query_watcher.js +55 -8
  56. package/dist/watchers/request_watcher.cjs +90 -8
  57. package/dist/watchers/request_watcher.js +67 -8
  58. package/package.json +18 -18
  59. package/README.md +0 -1
  60. package/dist/chunk-2HRVJRKV.cjs +0 -10
  61. package/dist/chunk-3R5QARPT.cjs +0 -14
  62. package/dist/chunk-4HLDYZJA.js +0 -34
  63. package/dist/chunk-5PYQWLAZ.js +0 -129
  64. package/dist/chunk-75ZPJI57.cjs +0 -9
  65. package/dist/chunk-7EKM5HB5.cjs +0 -1
  66. package/dist/chunk-AUDSBNLF.cjs +0 -122
  67. package/dist/chunk-BFFOUTTE.cjs +0 -32
  68. package/dist/chunk-BL4Z6JFH.cjs +0 -34
  69. package/dist/chunk-CQ2Z4TCR.js +0 -7
  70. package/dist/chunk-EHOWCXZV.cjs +0 -7
  71. package/dist/chunk-EJ5BW35V.js +0 -159
  72. package/dist/chunk-EKG3FVLV.cjs +0 -7
  73. package/dist/chunk-FCMQ3WE3.cjs +0 -129
  74. package/dist/chunk-FKMBNWX4.js +0 -7
  75. package/dist/chunk-FLOVBBFU.js +0 -10
  76. package/dist/chunk-GI7SJDNQ.cjs +0 -38
  77. package/dist/chunk-IPMTMCFP.js +0 -122
  78. package/dist/chunk-JZ2JLQXL.cjs +0 -87
  79. package/dist/chunk-MLKGABMK.js +0 -9
  80. package/dist/chunk-QRZUNYF6.cjs +0 -16
  81. package/dist/chunk-RMZ4UAQ2.js +0 -14
  82. package/dist/chunk-SJXZARBJ.cjs +0 -22
  83. package/dist/chunk-TJDE6AZM.js +0 -87
  84. package/dist/chunk-TPUVRGYT.js +0 -32
  85. package/dist/chunk-UF5HFNMI.js +0 -22
  86. package/dist/chunk-VD5IMUWL.js +0 -0
  87. package/dist/chunk-WU6IZUEV.cjs +0 -159
  88. package/dist/chunk-XXYRWHSQ.js +0 -0
  89. package/dist/chunk-XYXPHWEI.js +0 -16
  90. package/dist/chunk-XZFXXD3A.cjs +0 -1
  91. package/dist/chunk-YC6T4XWI.js +0 -38
  92. package/dist/ui/assets/QueriesContainer-DHnHEGG1.js +0 -2
  93. package/dist/ui/assets/QueryTable-DegVNDkJ.js +0 -1
  94. package/dist/ui/assets/RequestDetails-zrL0n6gL.js +0 -1
  95. package/dist/ui/assets/RequestDetailsContainer-CsHWDxn7.js +0 -2
  96. package/dist/ui/assets/RequetsTable-1K9hhs0W.js +0 -1
  97. package/dist/ui/assets/TabbedDataViewer-DDVxzZiW.js +0 -1
  98. package/dist/ui/assets/date-CZdBf-JH.js +0 -1
  99. package/dist/ui/assets/index-C-9tn0L6.js +0 -114
  100. package/dist/ui/assets/index-DaNx3ROH.css +0 -1
package/dist/index.cjs CHANGED
@@ -1,55 +1,611 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
-
4
-
5
- var _chunk3R5QARPTcjs = require('./chunk-3R5QARPT.cjs');
6
- require('./chunk-7EKM5HB5.cjs');
7
-
8
-
9
- var _chunkSJXZARBJcjs = require('./chunk-SJXZARBJ.cjs');
10
-
11
-
12
- var _chunkBL4Z6JFHcjs = require('./chunk-BL4Z6JFH.cjs');
13
-
14
-
15
- var _chunkBFFOUTTEcjs = require('./chunk-BFFOUTTE.cjs');
16
-
17
-
18
- var _chunkFCMQ3WE3cjs = require('./chunk-FCMQ3WE3.cjs');
19
- require('./chunk-XZFXXD3A.cjs');
20
-
21
-
22
- var _chunkAUDSBNLFcjs = require('./chunk-AUDSBNLF.cjs');
23
-
24
-
25
- var _chunkWU6IZUEVcjs = require('./chunk-WU6IZUEV.cjs');
26
-
27
-
28
- var _chunkEHOWCXZVcjs = require('./chunk-EHOWCXZV.cjs');
29
- require('./chunk-JZ2JLQXL.cjs');
30
-
31
-
32
- var _chunk2HRVJRKVcjs = require('./chunk-2HRVJRKV.cjs');
33
-
34
-
35
- var _chunkQRZUNYF6cjs = require('./chunk-QRZUNYF6.cjs');
36
- require('./chunk-GI7SJDNQ.cjs');
37
-
38
-
39
- var _chunkEKG3FVLVcjs = require('./chunk-EKG3FVLV.cjs');
40
- require('./chunk-75ZPJI57.cjs');
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
- exports.BetterSqliteStore = _chunkAUDSBNLFcjs.BetterSqliteStore; exports.Lens = _chunkFCMQ3WE3cjs.Lens; exports.LensAdapter = _chunkBFFOUTTEcjs.Adapter; exports.LensStore = _chunkEHOWCXZVcjs.Store; exports.LensWatcher = _chunkEKG3FVLVcjs.Watcher; exports.QueryWatcher = _chunkSJXZARBJcjs.QueryWatcher; exports.RequestWatcher = _chunkBL4Z6JFHcjs.RequestWatcher; exports.WatcherTypeEnum = _chunk2HRVJRKVcjs.WatcherTypeEnum; exports.createEmittery = _chunk3R5QARPTcjs.createEmittery; exports.getLensStore = _chunkQRZUNYF6cjs.getStore; exports.lensEmitter = _chunk3R5QARPTcjs.lensEmitter; exports.lensResource = _chunk3R5QARPTcjs.lensResource; exports.lensUtils = _chunkWU6IZUEVcjs.utils_exports;
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ BetterSqliteStore: () => BetterSqliteStore,
34
+ Lens: () => Lens,
35
+ LensAdapter: () => Adapter,
36
+ LensStore: () => Store,
37
+ LensWatcher: () => Watcher,
38
+ QueryWatcher: () => QueryWatcher,
39
+ RequestWatcher: () => RequestWatcher,
40
+ WatcherTypeEnum: () => WatcherTypeEnum,
41
+ createEmittery: () => createEmittery,
42
+ getLensStore: () => getStore,
43
+ lensUtils: () => utils_exports
44
+ });
45
+ module.exports = __toCommonJS(index_exports);
46
+
47
+ // src/context/container.ts
48
+ var Container = class {
49
+ static bindings = /* @__PURE__ */ new Map();
50
+ static singletons = /* @__PURE__ */ new Map();
51
+ static instances = /* @__PURE__ */ new Map();
52
+ static bind(key, factory) {
53
+ this.bindings.set(key, factory);
54
+ }
55
+ static singleton(key, factory) {
56
+ this.singletons.set(key, factory);
57
+ }
58
+ static make(key) {
59
+ if (this.instances.has(key)) {
60
+ return this.instances.get(key);
61
+ }
62
+ if (this.singletons.has(key)) {
63
+ const instance = this.singletons.get(key)();
64
+ this.instances.set(key, instance);
65
+ return instance;
66
+ }
67
+ if (this.bindings.has(key)) {
68
+ return this.bindings.get(key)();
69
+ }
70
+ throw new Error(`Service "${key}" is not bound in the container`);
71
+ }
72
+ static has(key) {
73
+ return this.bindings.has(key) || this.singletons.has(key) || this.instances.has(key);
74
+ }
75
+ static clear() {
76
+ this.bindings.clear();
77
+ this.singletons.clear();
78
+ this.instances.clear();
79
+ }
80
+ };
81
+
82
+ // src/context/context.ts
83
+ var getStore = () => {
84
+ return Container.make("store");
85
+ };
86
+ var getUiConfig = () => {
87
+ return Container.make("uiConfig");
88
+ };
89
+
90
+ // src/types/index.ts
91
+ var WatcherTypeEnum = /* @__PURE__ */ ((WatcherTypeEnum2) => {
92
+ WatcherTypeEnum2["REQUEST"] = "request";
93
+ WatcherTypeEnum2["QUERY"] = "query";
94
+ return WatcherTypeEnum2;
95
+ })(WatcherTypeEnum || {});
96
+
97
+ // src/core/api_controller.ts
98
+ var ApiController = class {
99
+ static async getRequests({ qs }) {
100
+ return this.paginatedResponse(
101
+ await getStore().getAllRequests(this.extractPaginationParams(qs))
102
+ );
103
+ }
104
+ static async getRequest({
105
+ params
106
+ }) {
107
+ const request = await getStore().find("request" /* REQUEST */, params.id);
108
+ if (!request) {
109
+ return this.notFoundResponse();
110
+ }
111
+ return this.resourceResponse(request);
112
+ }
113
+ static async getQueries({
114
+ qs
115
+ }) {
116
+ const queries = await getStore().getAllQueries(
117
+ this.extractPaginationParams(qs)
118
+ );
119
+ return this.paginatedResponse(queries);
120
+ }
121
+ static async getQuery({
122
+ params
123
+ }) {
124
+ const query = await getStore().find("query" /* QUERY */, params.id);
125
+ if (!query) {
126
+ return this.notFoundResponse();
127
+ }
128
+ return this.resourceResponse(query);
129
+ }
130
+ static async truncate() {
131
+ await getStore().truncate();
132
+ return this.baseResponse({}, 200, "All entries cleared");
133
+ }
134
+ static fetchUiConfig() {
135
+ return getUiConfig();
136
+ }
137
+ static extractPaginationParams(qs) {
138
+ if (!qs || Object.keys(qs).length === 0) {
139
+ return { page: 1, perPage: 100 };
140
+ }
141
+ let page = Number(qs.page);
142
+ let perPage = Number(qs.perPage);
143
+ if (!Number.isInteger(perPage) || perPage > 100 || perPage < 5) {
144
+ perPage = 100;
145
+ }
146
+ if (!Number.isInteger(page) || page < 1) {
147
+ page = 1;
148
+ }
149
+ return { page, perPage };
150
+ }
151
+ static resourceResponse(data) {
152
+ return this.baseResponse(data, 200, "Data fetched successfully");
153
+ }
154
+ static notFoundResponse(message = "Could not find the requested resource") {
155
+ return this.baseResponse(null, 404, message);
156
+ }
157
+ static paginatedResponse(data) {
158
+ return this.baseResponse(data, 200, "Data fetched successfully");
159
+ }
160
+ static baseResponse(data, status, message) {
161
+ if (!data) {
162
+ return { status, message, data: null };
163
+ }
164
+ if ("meta" in data) {
165
+ return {
166
+ status,
167
+ message,
168
+ data: data.data,
169
+ meta: data.meta
170
+ };
171
+ }
172
+ return { status, message, data };
173
+ }
174
+ };
175
+
176
+ // src/core/lens.ts
177
+ var path2 = __toESM(require("path"), 1);
178
+
179
+ // src/abstracts/store.ts
180
+ var Store = class {
181
+ };
182
+
183
+ // src/stores/better_sqlite.ts
184
+ var import_crypto = require("crypto");
185
+ var import_libsql = __toESM(require("libsql"), 1);
186
+ var import_date = require("@lensjs/date");
187
+ var TABLE_NAME = "lens_entries";
188
+ var BetterSqliteStore = class extends Store {
189
+ connection;
190
+ async initialize() {
191
+ this.connection = new import_libsql.default("lens.db");
192
+ this.setupSchema();
193
+ console.log("Connected to Lens (SQLite) database.");
194
+ }
195
+ async truncate() {
196
+ this.connection.prepare(`DELETE FROM ${TABLE_NAME};`).run();
197
+ }
198
+ async save(entry) {
199
+ this.connection.prepare(
200
+ `INSERT INTO ${TABLE_NAME} (id, data, type, created_at, lens_entry_id, minimal_data) values($id, $data, $type, $created_at, $lens_entry_id, $minimalData)`
201
+ ).run({
202
+ id: entry.id ?? (0, import_crypto.randomUUID)(),
203
+ data: JSON.stringify(entry.data),
204
+ type: entry.type,
205
+ created_at: entry.timestamp ?? (0, import_date.sqlDateTime)(),
206
+ lens_entry_id: entry.requestId || null,
207
+ minimalData: JSON.stringify(entry.minimal_data ?? {})
208
+ });
209
+ }
210
+ async getAllQueries(pagination) {
211
+ return await this.paginate("query" /* QUERY */, pagination);
212
+ }
213
+ async getAllRequests(pagination) {
214
+ return await this.paginate("request" /* REQUEST */, pagination, false);
215
+ }
216
+ async allByRequestId(requestId, type) {
217
+ const rows = this.connection.prepare(
218
+ `${this.getSelectedColumns()} FROM ${TABLE_NAME} WHERE type = $type AND lens_entry_id = $requestId ORDER BY created_at DESC`
219
+ ).all({ type, requestId });
220
+ return this.mapRows(rows);
221
+ }
222
+ async paginate(type, { page, perPage }, includeFullData = true) {
223
+ const offset = (page - 1) * perPage;
224
+ const query = `${this.getSelectedColumns(
225
+ includeFullData
226
+ )} FROM ${TABLE_NAME} WHERE type = ? ORDER BY created_at DESC LIMIT ? OFFSET ?`;
227
+ const count = await this.count(type);
228
+ const rows = this.connection.prepare(query).all(type, perPage, offset);
229
+ const mappedRows = this.mapRows(rows, includeFullData);
230
+ return {
231
+ meta: {
232
+ total: count,
233
+ lastPage: Math.ceil(count / perPage),
234
+ currentPage: page
235
+ },
236
+ data: mappedRows
237
+ };
238
+ }
239
+ async count(type) {
240
+ const result = this.connection.prepare(`SELECT count(*) as count FROM ${TABLE_NAME} WHERE type = ?`).get(type);
241
+ return Number(result.count);
242
+ }
243
+ async find(type, id) {
244
+ const row = this.connection.prepare(
245
+ `${this.getSelectedColumns()} FROM ${TABLE_NAME} WHERE id = ? AND type = ? LIMIT 1`
246
+ ).get(id, type);
247
+ if (!row) {
248
+ return null;
249
+ }
250
+ return this.mapRow(row, true);
251
+ }
252
+ setupSchema() {
253
+ const createTable = `
254
+ CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (
255
+ id TEXT PRIMARY KEY,
256
+ minimal_data TEXT,
257
+ data TEXT NOT NULL,
258
+ type TEXT NOT NULL,
259
+ created_at TEXT NOT NULL,
260
+ updated_at TEXT,
261
+ lens_entry_id TEXT NULL
262
+ );
263
+ `;
264
+ const createIndex = `
265
+ CREATE INDEX IF NOT EXISTS lens_entries_id_type_index
266
+ ON ${TABLE_NAME} (id, type);
267
+ `;
268
+ this.connection.exec(createTable);
269
+ this.connection.exec(createIndex);
270
+ }
271
+ mapRow(row, includeFullData = true) {
272
+ let data = includeFullData ? JSON.parse(row.data) : {};
273
+ if (!includeFullData) {
274
+ data = JSON.parse(row.minimal_data);
275
+ }
276
+ return {
277
+ id: row.id,
278
+ type: row.type,
279
+ created_at: row.created_at,
280
+ lens_entry_id: row.lens_entry_id,
281
+ data
282
+ };
283
+ }
284
+ mapRows(rows, includeFullData = true) {
285
+ let mappedRows = [];
286
+ for (const row of rows) {
287
+ mappedRows.push(this.mapRow(row, includeFullData));
288
+ }
289
+ return mappedRows;
290
+ }
291
+ getSelectedColumns(includeFullData = true) {
292
+ return `SELECT id, minimal_data, type, created_at, lens_entry_id ${includeFullData ? ",data" : ""}`;
293
+ }
294
+ };
295
+
296
+ // src/utils/index.ts
297
+ var utils_exports = {};
298
+ __export(utils_exports, {
299
+ formatSqlQuery: () => formatSqlQuery,
300
+ generateRandomUuid: () => generateRandomUuid,
301
+ getMeta: () => getMeta,
302
+ interpolateQuery: () => interpolateQuery,
303
+ isStaticFile: () => isStaticFile,
304
+ prepareIgnoredPaths: () => prepareIgnoredPaths,
305
+ prettyHrTime: () => prettyHrTime,
306
+ shouldIgnoreCurrentPath: () => shouldIgnoreCurrentPath,
307
+ stripBeforeAssetsPath: () => stripBeforeAssetsPath
308
+ });
309
+ var import_luxon = require("luxon");
310
+ var import_sql_formatter = require("sql-formatter");
311
+ var import_crypto2 = require("crypto");
312
+ var import_url = require("url");
313
+ var path = __toESM(require("path"), 1);
314
+ var generateRandomUuid = () => {
315
+ return (0, import_crypto2.randomUUID)();
316
+ };
317
+ function interpolateQuery(query, bindings) {
318
+ const formatValue = (value) => {
319
+ if (value === null || value === void 0) return "NULL";
320
+ if (typeof value === "string") return `'${value.replace(/'/g, "''")}'`;
321
+ if (value instanceof import_luxon.DateTime) return `'${value.toISO()}'`;
322
+ if (value instanceof Date) return `'${value.toISOString()}'`;
323
+ if (Array.isArray(value))
324
+ return value.map((v) => typeof v === "string" ? `'${v.replace(/'/g, "''")}'` : v).join(", ");
325
+ if (typeof value === "object")
326
+ return `'${JSON.stringify(value).replace(/'/g, "''")}'`;
327
+ return value.toString();
328
+ };
329
+ if (Array.isArray(bindings)) {
330
+ let i = 0;
331
+ return query.replace(/\?/g, () => {
332
+ if (i >= bindings.length)
333
+ throw new Error("Not enough bindings for placeholders");
334
+ return formatValue(bindings[i++]);
335
+ });
336
+ }
337
+ return query.replace(/(\$|\:)(\w+)/g, (match, prefix, keyOrIndex) => {
338
+ let value;
339
+ if (prefix === "$" && /^\d+$/.test(keyOrIndex)) {
340
+ const index = parseInt(keyOrIndex, 10) - 1;
341
+ const keys = Object.keys(bindings);
342
+ if (index < 0 || index >= keys.length)
343
+ throw new Error(`Missing binding for ${match}`);
344
+ value = bindings[keys[index]];
345
+ } else {
346
+ if (!(keyOrIndex in bindings))
347
+ throw new Error(`Missing binding for ${match}`);
348
+ value = bindings[keyOrIndex];
349
+ }
350
+ return formatValue(value);
351
+ });
352
+ }
353
+ var formatSqlQuery = (query, language) => {
354
+ return (0, import_sql_formatter.format)(query, {
355
+ language,
356
+ dataTypeCase: "upper",
357
+ keywordCase: "upper",
358
+ functionCase: "upper"
359
+ });
360
+ };
361
+ function getMeta(metaUrl) {
362
+ const isESM = typeof __dirname === "undefined";
363
+ if (isESM) {
364
+ if (!metaUrl) {
365
+ throw new Error("In ESM, you must pass import.meta.url to getMeta()");
366
+ }
367
+ const __filename2 = (0, import_url.fileURLToPath)(metaUrl);
368
+ const __dirname2 = path.dirname(__filename2);
369
+ return { __filename: __filename2, __dirname: __dirname2 };
370
+ } else {
371
+ return { __filename, __dirname };
372
+ }
373
+ }
374
+ function isStaticFile(params) {
375
+ return params.includes("assets");
376
+ }
377
+ function stripBeforeAssetsPath(url) {
378
+ const match = url.match(/assets.*/);
379
+ return match ? match[0] : url;
380
+ }
381
+ function prepareIgnoredPaths(path3, ignoredPaths) {
382
+ const normalizedPath = path3.replace(/^\/+|\/+$/g, "");
383
+ ignoredPaths = [
384
+ ...ignoredPaths,
385
+ new RegExp(`^/?${normalizedPath}(/|$)`),
386
+ /^\/?lens-config$/,
387
+ /^\/\.well-known\//
388
+ ];
389
+ return { ignoredPaths, normalizedPath };
390
+ }
391
+ function shouldIgnoreCurrentPath(path3, ignoredPaths, onlyPaths) {
392
+ if (onlyPaths.length > 0) {
393
+ return !onlyPaths.some((pattern) => pattern.test(path3));
394
+ }
395
+ return ignoredPaths.some((pattern) => pattern.test(path3));
396
+ }
397
+ function prettyHrTime(hrtime, verbose = false) {
398
+ const seconds = hrtime[0];
399
+ const nanoseconds = hrtime[1];
400
+ const ms = seconds * 1e3 + nanoseconds / 1e6;
401
+ if (verbose) {
402
+ if (seconds > 60) {
403
+ const minutes = Math.floor(seconds / 60);
404
+ const remainingSeconds = seconds % 60;
405
+ return `${minutes}m ${remainingSeconds}s`;
406
+ }
407
+ if (seconds >= 1) {
408
+ return `${seconds}.${Math.floor(nanoseconds / 1e7)}s`;
409
+ }
410
+ return `${ms.toFixed(3)} ms`;
411
+ }
412
+ if (ms < 1e3) {
413
+ return `${ms.toFixed(0)} ms`;
414
+ }
415
+ return `${(ms / 1e3).toFixed(1)} s`;
416
+ }
417
+
418
+ // src/core/lens.ts
419
+ var import_meta = {};
420
+ var Lens = class {
421
+ static watchers = /* @__PURE__ */ new Map();
422
+ static store;
423
+ static adapter;
424
+ static watch(watcher) {
425
+ this.watchers.set(watcher.name, watcher);
426
+ return this;
427
+ }
428
+ static setWatchers(watchers) {
429
+ this.watchers = new Map(watchers.map((watcher) => [watcher.name, watcher]));
430
+ return this;
431
+ }
432
+ static async start(config = {
433
+ basePath: "lens",
434
+ appName: "Lens",
435
+ enabled: true
436
+ }) {
437
+ if (!config.enabled) {
438
+ return;
439
+ }
440
+ await this.bindContainerDeps(config);
441
+ let adapter = this.getAdapter();
442
+ adapter.setWatchers(Array.from(this.watchers.values())).setup();
443
+ const { apiRoutes } = this.getRoutes({
444
+ basePath: config.basePath
445
+ });
446
+ adapter.registerRoutes(apiRoutes);
447
+ const { __dirname: __dirname2 } = getMeta(import_meta.url);
448
+ const uiPath = path2.resolve(this.normalizeDirName(__dirname2), "ui");
449
+ adapter.serveUI(uiPath, config.basePath, getUiConfig());
450
+ }
451
+ static setStore(store) {
452
+ this.store = store;
453
+ return this;
454
+ }
455
+ static async getStore() {
456
+ return this.store ?? await this.getDefaultStore();
457
+ }
458
+ static setAdapter(adapter) {
459
+ this.adapter = adapter;
460
+ return this;
461
+ }
462
+ static getAdapter() {
463
+ if (!this.adapter) {
464
+ throw new Error("No adapter has been set");
465
+ }
466
+ return this.adapter;
467
+ }
468
+ static async bindContainerDeps(config) {
469
+ const dbStore = await this.getStore();
470
+ Container.singleton("store", () => dbStore);
471
+ Container.singleton("uiConfig", () => {
472
+ return {
473
+ appName: config.appName,
474
+ path: `/${config.basePath}`,
475
+ api: {
476
+ requests: `/${config.basePath}/api/requests`,
477
+ queries: `/${config.basePath}/api/queries`,
478
+ truncate: `/${config.basePath}/api/truncate`
479
+ }
480
+ };
481
+ });
482
+ }
483
+ static getRoutes({ basePath }) {
484
+ const apiRoutes = [
485
+ {
486
+ method: "GET",
487
+ path: `/lens-config`,
488
+ handler: () => ApiController.fetchUiConfig()
489
+ },
490
+ {
491
+ method: "GET",
492
+ path: `${basePath}/api/requests`,
493
+ handler: async (data) => await ApiController.getRequests(data)
494
+ },
495
+ {
496
+ method: "GET",
497
+ path: `${basePath}/api/requests/:id`,
498
+ handler: async (data) => await ApiController.getRequest(data)
499
+ },
500
+ {
501
+ method: "GET",
502
+ path: `${basePath}/api/queries`,
503
+ handler: async (data) => await ApiController.getQueries(data)
504
+ },
505
+ {
506
+ method: "GET",
507
+ path: `${basePath}/api/queries/:id`,
508
+ handler: async (data) => await ApiController.getQuery(data)
509
+ },
510
+ {
511
+ method: "DELETE",
512
+ path: `${basePath}/api/truncate`,
513
+ handler: async () => await ApiController.truncate()
514
+ }
515
+ ];
516
+ return { apiRoutes };
517
+ }
518
+ static async getDefaultStore() {
519
+ const store = new BetterSqliteStore();
520
+ await store.initialize();
521
+ return store;
522
+ }
523
+ static normalizeDirName(path3) {
524
+ return path3.replace(/(\/packages\/)[^/]+(?=\/dist)/, "$1core");
525
+ }
526
+ };
527
+
528
+ // src/core/watcher.ts
529
+ var Watcher = class {
530
+ };
531
+
532
+ // src/watchers/query_watcher.ts
533
+ var QueryWatcher = class extends Watcher {
534
+ name = "query" /* QUERY */;
535
+ async log(entry) {
536
+ await getStore().save({
537
+ type: this.name,
538
+ data: entry.data,
539
+ requestId: entry.requestId ?? ""
540
+ });
541
+ }
542
+ };
543
+
544
+ // src/watchers/request_watcher.ts
545
+ var RequestWatcher = class extends Watcher {
546
+ name = "request" /* REQUEST */;
547
+ async log(data) {
548
+ await getStore().save({
549
+ id: data.request.id,
550
+ type: this.name,
551
+ minimal_data: {
552
+ id: data.request.id,
553
+ method: data.request.method,
554
+ path: data.request.path,
555
+ duration: data.request.duration,
556
+ createdAt: data.request.createdAt,
557
+ status: data.request.status
558
+ },
559
+ data: {
560
+ ...data.request,
561
+ user: data.user,
562
+ response: data.response
563
+ }
564
+ });
565
+ }
566
+ };
567
+
568
+ // src/abstracts/adapter.ts
569
+ var Adapter = class {
570
+ watchers = [];
571
+ ignoredPaths = [];
572
+ onlyPaths = [];
573
+ setWatchers(watchers) {
574
+ this.watchers = watchers;
575
+ return this;
576
+ }
577
+ setIgnoredPaths(paths) {
578
+ this.ignoredPaths = paths;
579
+ return this;
580
+ }
581
+ setOnlyPaths(paths) {
582
+ this.onlyPaths = paths;
583
+ return this;
584
+ }
585
+ getWatchers() {
586
+ return this.watchers;
587
+ }
588
+ shouldIgnorePath(path3) {
589
+ return shouldIgnoreCurrentPath(path3, this.ignoredPaths, this.onlyPaths);
590
+ }
591
+ };
592
+
593
+ // src/utils/event_emitter.ts
594
+ var import_emittery = __toESM(require("emittery"), 1);
595
+ var createEmittery = () => {
596
+ return new import_emittery.default();
597
+ };
598
+ // Annotate the CommonJS export names for ESM import in node:
599
+ 0 && (module.exports = {
600
+ BetterSqliteStore,
601
+ Lens,
602
+ LensAdapter,
603
+ LensStore,
604
+ LensWatcher,
605
+ QueryWatcher,
606
+ RequestWatcher,
607
+ WatcherTypeEnum,
608
+ createEmittery,
609
+ getLensStore,
610
+ lensUtils
611
+ });
package/dist/index.d.cts CHANGED
@@ -7,10 +7,8 @@ export { default as LensAdapter } from './abstracts/adapter.cjs';
7
7
  export { default as LensStore } from './abstracts/store.cjs';
8
8
  export { default as LensWatcher } from './core/watcher.cjs';
9
9
  export { getStore as getLensStore } from './context/context.cjs';
10
- export { i as lensUtils } from './index-D0Vszdac.cjs';
11
- export { createEmittery, lensEmitter, lensResource } from './utils/event_emitter.cjs';
10
+ export { i as lensUtils } from './index-DiLfwsvc.cjs';
11
+ export { createEmittery } from './utils/event_emitter.cjs';
12
12
  import 'libsql';
13
13
  import 'sql-formatter';
14
- import 'luxon';
15
14
  import 'emittery';
16
- import 'node:async_hooks';
package/dist/index.d.ts CHANGED
@@ -7,10 +7,8 @@ export { default as LensAdapter } from './abstracts/adapter.js';
7
7
  export { default as LensStore } from './abstracts/store.js';
8
8
  export { default as LensWatcher } from './core/watcher.js';
9
9
  export { getStore as getLensStore } from './context/context.js';
10
- export { i as lensUtils } from './index-D0Vszdac.js';
11
- export { createEmittery, lensEmitter, lensResource } from './utils/event_emitter.js';
10
+ export { i as lensUtils } from './index-DiLfwsvc.js';
11
+ export { createEmittery } from './utils/event_emitter.js';
12
12
  import 'libsql';
13
13
  import 'sql-formatter';
14
- import 'luxon';
15
14
  import 'emittery';
16
- import 'node:async_hooks';