@hot-updater/plugin-core 1.0.0-rc.14 → 1.0.0-rc.16

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/dist/bundleEventRow.cjs +42 -0
  2. package/dist/bundleEventRow.mjs +41 -0
  3. package/dist/bundleStorageLayout.cjs +7 -0
  4. package/dist/bundleStorageLayout.d.cts +5 -1
  5. package/dist/bundleStorageLayout.d.mts +5 -1
  6. package/dist/bundleStorageLayout.mjs +7 -1
  7. package/dist/contentType.cjs +9 -0
  8. package/dist/contentType.d.cts +4 -0
  9. package/dist/contentType.d.mts +4 -0
  10. package/dist/contentType.mjs +7 -0
  11. package/dist/coreApi.d.cts +131 -0
  12. package/dist/coreApi.d.mts +131 -0
  13. package/dist/database/adapter.cjs +37 -0
  14. package/dist/database/adapter.d.cts +150 -0
  15. package/dist/database/adapter.d.mts +150 -0
  16. package/dist/database/adapter.mjs +30 -0
  17. package/dist/database/memoryAdapter.cjs +102 -0
  18. package/dist/database/memoryAdapter.d.cts +16 -0
  19. package/dist/database/memoryAdapter.d.mts +16 -0
  20. package/dist/database/memoryAdapter.mjs +102 -0
  21. package/dist/database/values.cjs +110 -0
  22. package/dist/database/values.d.cts +30 -0
  23. package/dist/database/values.d.mts +30 -0
  24. package/dist/database/values.mjs +100 -0
  25. package/dist/database/verifyAdapter.cjs +129 -0
  26. package/dist/database/verifyAdapter.d.cts +29 -0
  27. package/dist/database/verifyAdapter.d.mts +29 -0
  28. package/dist/database/verifyAdapter.mjs +128 -0
  29. package/dist/databaseErrors.cjs +30 -0
  30. package/dist/databaseErrors.d.cts +21 -0
  31. package/dist/databaseErrors.d.mts +21 -0
  32. package/dist/databaseErrors.mjs +28 -0
  33. package/dist/databaseMetadata.cjs +2 -2
  34. package/dist/databaseMetadata.mjs +1 -1
  35. package/dist/databaseRows.cjs +0 -6
  36. package/dist/databaseRows.mjs +0 -6
  37. package/dist/index.cjs +14 -41
  38. package/dist/index.d.cts +15 -19
  39. package/dist/index.d.mts +15 -19
  40. package/dist/index.mjs +10 -16
  41. package/dist/insightsContract.cjs +65 -17
  42. package/dist/insightsContract.d.cts +6 -1
  43. package/dist/insightsContract.d.mts +6 -1
  44. package/dist/insightsContract.mjs +52 -5
  45. package/dist/insightsDistinctSummary.cjs +73 -0
  46. package/dist/insightsDistinctSummary.d.cts +12 -0
  47. package/dist/insightsDistinctSummary.d.mts +12 -0
  48. package/dist/insightsDistinctSummary.mjs +69 -0
  49. package/dist/insightsOverview.cjs +139 -0
  50. package/dist/insightsOverview.d.cts +42 -0
  51. package/dist/insightsOverview.d.mts +42 -0
  52. package/dist/insightsOverview.mjs +134 -0
  53. package/dist/internal.cjs +44 -8
  54. package/dist/internal.d.cts +12 -9
  55. package/dist/internal.d.mts +12 -9
  56. package/dist/internal.mjs +9 -4
  57. package/dist/releaseCatalogCompiler.cjs +1 -1
  58. package/dist/releaseCatalogCompiler.mjs +2 -2
  59. package/dist/releaseCatalogMutation.cjs +0 -292
  60. package/dist/releaseCatalogMutation.d.cts +4 -45
  61. package/dist/releaseCatalogMutation.d.mts +4 -45
  62. package/dist/releaseCatalogMutation.mjs +1 -288
  63. package/dist/releaseManagement.cjs +0 -221
  64. package/dist/releaseManagement.d.cts +4 -28
  65. package/dist/releaseManagement.d.mts +4 -28
  66. package/dist/releaseManagement.mjs +1 -216
  67. package/dist/types/databaseConfig.cjs +5 -0
  68. package/dist/types/databaseConfig.d.cts +33 -0
  69. package/dist/types/databaseConfig.d.mts +33 -0
  70. package/dist/types/databaseConfig.mjs +5 -0
  71. package/dist/types/databaseOperations.d.cts +5 -172
  72. package/dist/types/databaseOperations.d.mts +5 -172
  73. package/dist/types/databaseRows.d.cts +3 -6
  74. package/dist/types/databaseRows.d.mts +3 -6
  75. package/dist/types/index.cjs +2 -0
  76. package/dist/types/index.d.cts +9 -86
  77. package/dist/types/index.d.mts +9 -86
  78. package/dist/types/index.mjs +2 -1
  79. package/dist/types/insights.d.cts +172 -0
  80. package/dist/types/insights.d.mts +172 -0
  81. package/dist/types/internal.d.cts +4 -7
  82. package/dist/types/internal.d.mts +4 -7
  83. package/dist/types/models.d.cts +24 -0
  84. package/dist/types/models.d.mts +24 -0
  85. package/dist/types/public.d.cts +4 -2
  86. package/dist/types/public.d.mts +4 -2
  87. package/package.json +2 -2
  88. package/dist/calculatePagination.cjs +0 -25
  89. package/dist/calculatePagination.d.cts +0 -12
  90. package/dist/calculatePagination.d.mts +0 -12
  91. package/dist/calculatePagination.mjs +0 -25
  92. package/dist/compressionFormat.cjs +0 -62
  93. package/dist/compressionFormat.d.cts +0 -33
  94. package/dist/compressionFormat.d.mts +0 -33
  95. package/dist/compressionFormat.mjs +0 -58
  96. package/dist/createDatabasePlugin.cjs +0 -873
  97. package/dist/createDatabasePlugin.d.cts +0 -28
  98. package/dist/createDatabasePlugin.d.mts +0 -28
  99. package/dist/createDatabasePlugin.mjs +0 -869
  100. package/dist/databaseClient.cjs +0 -117
  101. package/dist/databaseClient.d.cts +0 -32
  102. package/dist/databaseClient.d.mts +0 -32
  103. package/dist/databaseClient.mjs +0 -114
  104. package/dist/databaseClientReads.cjs +0 -115
  105. package/dist/databaseClientReads.mjs +0 -113
  106. package/dist/databaseClientUpdates.cjs +0 -40
  107. package/dist/databaseClientUpdates.d.cts +0 -11
  108. package/dist/databaseClientUpdates.d.mts +0 -11
  109. package/dist/databaseClientUpdates.mjs +0 -38
  110. package/dist/databasePluginCrud.cjs +0 -87
  111. package/dist/databasePluginCrud.d.cts +0 -4
  112. package/dist/databasePluginCrud.d.mts +0 -4
  113. package/dist/databasePluginCrud.mjs +0 -86
  114. package/dist/databasePluginCrudValidation.d.cts +0 -6
  115. package/dist/databasePluginCrudValidation.d.mts +0 -6
  116. package/dist/databasePluginCrudValidationErrors.cjs +0 -11
  117. package/dist/databasePluginCrudValidationErrors.d.cts +0 -9
  118. package/dist/databasePluginCrudValidationErrors.d.mts +0 -9
  119. package/dist/databasePluginCrudValidationErrors.mjs +0 -11
  120. package/dist/databasePluginCrudValidationFields.cjs +0 -293
  121. package/dist/databasePluginCrudValidationFields.d.cts +0 -1
  122. package/dist/databasePluginCrudValidationFields.d.mts +0 -1
  123. package/dist/databasePluginCrudValidationFields.mjs +0 -281
  124. package/dist/databasePluginCrudValidationMutations.cjs +0 -88
  125. package/dist/databasePluginCrudValidationMutations.d.cts +0 -1
  126. package/dist/databasePluginCrudValidationMutations.d.mts +0 -1
  127. package/dist/databasePluginCrudValidationMutations.mjs +0 -82
  128. package/dist/databasePluginCrudValidationQueries.cjs +0 -103
  129. package/dist/databasePluginCrudValidationQueries.d.cts +0 -2
  130. package/dist/databasePluginCrudValidationQueries.d.mts +0 -2
  131. package/dist/databasePluginCrudValidationQueries.mjs +0 -97
  132. package/dist/databasePluginCrudValidationRows.cjs +0 -55
  133. package/dist/databasePluginCrudValidationRows.d.cts +0 -1
  134. package/dist/databasePluginCrudValidationRows.d.mts +0 -1
  135. package/dist/databasePluginCrudValidationRows.mjs +0 -53
  136. package/dist/databasePluginTransaction.cjs +0 -7
  137. package/dist/databasePluginTransaction.mjs +0 -7
  138. package/dist/insightsLatestQueries.cjs +0 -53
  139. package/dist/insightsLatestQueries.d.cts +0 -13
  140. package/dist/insightsLatestQueries.d.mts +0 -13
  141. package/dist/insightsLatestQueries.mjs +0 -52
  142. package/dist/paginateBundles.cjs +0 -53
  143. package/dist/paginateBundles.d.cts +0 -13
  144. package/dist/paginateBundles.d.mts +0 -13
  145. package/dist/paginateBundles.mjs +0 -53
  146. package/dist/queryBundles.cjs +0 -34
  147. package/dist/queryBundles.d.cts +0 -9
  148. package/dist/queryBundles.d.mts +0 -9
  149. package/dist/queryBundles.mjs +0 -32
  150. package/dist/requestBundleCache.cjs +0 -22
  151. package/dist/requestBundleCache.d.cts +0 -8
  152. package/dist/requestBundleCache.d.mts +0 -8
  153. package/dist/requestBundleCache.mjs +0 -22
  154. package/dist/types/database.d.cts +0 -5
  155. package/dist/types/database.d.mts +0 -5
  156. package/dist/types/databaseFields.cjs +0 -88
  157. package/dist/types/databaseFields.d.cts +0 -12
  158. package/dist/types/databaseFields.d.mts +0 -12
  159. package/dist/types/databaseFields.mjs +0 -88
  160. package/dist/types/databasePlugin.d.cts +0 -304
  161. package/dist/types/databasePlugin.d.mts +0 -304
  162. package/dist/types/databaseQuery.d.cts +0 -46
  163. package/dist/types/databaseQuery.d.mts +0 -46
@@ -0,0 +1,100 @@
1
+ import { findPhysicalColumn, indexOrderColumns } from "./adapter.mjs";
2
+ //#region src/database/values.ts
3
+ var DatabaseValueError = class extends Error {
4
+ name = "DatabaseValueError";
5
+ };
6
+ /** Compares strings in UTF-8 byte order, which is Unicode code point order. */
7
+ const compareUtf8 = (left, right) => {
8
+ let leftIndex = 0;
9
+ let rightIndex = 0;
10
+ while (leftIndex < left.length && rightIndex < right.length) {
11
+ const leftPoint = left.codePointAt(leftIndex);
12
+ const rightPoint = right.codePointAt(rightIndex);
13
+ if (leftPoint !== rightPoint) return leftPoint < rightPoint ? -1 : 1;
14
+ leftIndex += leftPoint > 65535 ? 2 : 1;
15
+ rightIndex += rightPoint > 65535 ? 2 : 1;
16
+ }
17
+ const leftDone = leftIndex >= left.length;
18
+ return leftDone === rightIndex >= right.length ? 0 : leftDone ? -1 : 1;
19
+ };
20
+ /** Orders strings by UTF-8 bytes, numbers numerically, and false before true. */
21
+ const compareKeyValues = (left, right) => {
22
+ if (typeof left === "string" && typeof right === "string") return compareUtf8(left, right);
23
+ if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
24
+ if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
25
+ throw new DatabaseValueError(`Cannot compare ${typeof left} with ${typeof right}.`);
26
+ };
27
+ /** Compares tuples element by element; a shorter equal prefix sorts first. */
28
+ const compareTuples = (left, right) => {
29
+ for (let index = 0; index < Math.min(left.length, right.length); index += 1) {
30
+ const result = compareKeyValues(left[index], right[index]);
31
+ if (result !== 0) return result;
32
+ }
33
+ return left.length - right.length;
34
+ };
35
+ /** JSON text with object keys sorted, so a value compares equal after a store reorders map keys. */
36
+ const canonicalJson = (value) => JSON.stringify(value ?? null, (_, inner) => inner !== null && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.entries(inner).sort(([left], [right]) => compareUtf8(left, right))) : inner);
37
+ const isKeyValue = (value) => typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
38
+ /** Every `eq` tuple a row is indexed under; none when an index field is null. */
39
+ const indexEntries = (table, index, row) => {
40
+ if (index.sort.some((column) => !isKeyValue(row[column]))) return [];
41
+ let entries = [[]];
42
+ for (const column of index.eq) {
43
+ const value = row[column];
44
+ const values = findPhysicalColumn(table, column).multi ? Array.isArray(value) ? value.filter(isKeyValue) : [] : isKeyValue(value) ? [value] : [];
45
+ if (values.length === 0) return [];
46
+ entries = entries.flatMap((entry) => [...new Set(values)].map((item) => [...entry, item]));
47
+ }
48
+ return entries;
49
+ };
50
+ /** The row's position in an index read, following `indexOrderColumns`. */
51
+ const indexOrderTuple = (table, index, row) => indexOrderColumns(table, index).map((column) => {
52
+ const value = row[column];
53
+ if (!isKeyValue(value)) throw new DatabaseValueError(`${table.name}.${column} is not orderable for index ${index.name}.`);
54
+ return value;
55
+ });
56
+ const satisfiesBound = (tuple, bound, side) => {
57
+ if (bound === void 0) return true;
58
+ const result = compareTuples(tuple.slice(0, bound.values.length), bound.values);
59
+ if (result === 0) return bound.inclusive;
60
+ return side === "lower" ? result > 0 : result < 0;
61
+ };
62
+ /** Whether a stored row belongs to the result range of a query. */
63
+ const matchesQuery = (table, index, request, row) => indexEntries(table, index, row).some((entry) => compareTuples(entry, request.eq) === 0) && satisfiesBound(indexOrderTuple(table, index, row), request.lower, "lower") && satisfiesBound(indexOrderTuple(table, index, row), request.upper, "upper");
64
+ const INTEGER_TEXT = /^-?\d+$/u;
65
+ const NUMBER_TEXT = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/iu;
66
+ const toNumber = (raw, integer) => {
67
+ const text = typeof raw === "bigint" ? raw.toString() : typeof raw === "string" ? raw : typeof raw === "object" && raw !== null && "toString" in raw ? String(raw) : void 0;
68
+ const value = typeof raw === "number" ? raw : text !== void 0 && (integer ? INTEGER_TEXT : NUMBER_TEXT).test(text) ? Number(text) : NaN;
69
+ if (integer ? !Number.isSafeInteger(value) : !Number.isFinite(value)) throw new DatabaseValueError(`Expected a ${integer ? "safe integer" : "finite number"}.`);
70
+ return value;
71
+ };
72
+ const toBoolean = (raw) => {
73
+ if (raw === true || raw === 1 || raw === 1n || raw === "1" || raw === "t") return true;
74
+ if (raw === false || raw === 0 || raw === 0n || raw === "0" || raw === "f") return false;
75
+ if (raw === "true" || raw === "false") return raw === "true";
76
+ throw new DatabaseValueError("Expected a boolean.");
77
+ };
78
+ const toScalar = (column, raw) => {
79
+ switch (column.type) {
80
+ case "string":
81
+ if (typeof raw !== "string") throw new DatabaseValueError(`Expected a string in ${column.name}.`);
82
+ return raw;
83
+ case "integer":
84
+ case "number": return toNumber(raw, column.type === "integer");
85
+ case "boolean": return toBoolean(raw);
86
+ case "json": return raw;
87
+ }
88
+ };
89
+ /** Converts a backend value (int8 text, BigInt, Decimal, 0/1, JSON text) to a stored value. */
90
+ const normalizeStoredValue = (column, raw, options) => {
91
+ if (raw === null || raw === void 0) return null;
92
+ const parsed = options.jsonText && (column.multi || column.type === "json") && typeof raw === "string" ? JSON.parse(raw) : raw;
93
+ if (!column.multi) return toScalar(column, parsed);
94
+ if (!Array.isArray(parsed) || parsed.length > 16) throw new DatabaseValueError(`Expected at most 16 values in ${column.name}.`);
95
+ return parsed.map((item) => toScalar(column, item));
96
+ };
97
+ /** Converts every column of a backend row; unknown backend columns are dropped. */
98
+ const normalizeStoredRow = (table, raw, options) => Object.fromEntries(table.columns.map((column) => [column.name, normalizeStoredValue(column, raw[column.name], options)]));
99
+ //#endregion
100
+ export { DatabaseValueError, canonicalJson, compareKeyValues, compareTuples, compareUtf8, indexEntries, indexOrderTuple, isKeyValue, matchesQuery, normalizeStoredRow, normalizeStoredValue };
@@ -0,0 +1,129 @@
1
+ const require_adapter = require("./adapter.cjs");
2
+ const require_values = require("./values.cjs");
3
+ //#region src/database/verifyAdapter.ts
4
+ var DatabaseAdapterContractError = class extends Error {
5
+ name = "DatabaseAdapterContractError";
6
+ };
7
+ const EMPTY = {
8
+ gets: 0,
9
+ keys: 0,
10
+ queries: 0,
11
+ rows: 0
12
+ };
13
+ const createReadMeter = () => {
14
+ const tables = /* @__PURE__ */ new Map();
15
+ const add = (table, count) => {
16
+ const current = tables.get(table) ?? EMPTY;
17
+ tables.set(table, {
18
+ gets: current.gets + (count.gets ?? 0),
19
+ keys: current.keys + (count.keys ?? 0),
20
+ queries: current.queries + (count.queries ?? 0),
21
+ rows: current.rows + (count.rows ?? 0)
22
+ });
23
+ };
24
+ return {
25
+ add,
26
+ meter: {
27
+ total: () => [...tables.values()].reduce((sum, count) => ({
28
+ gets: sum.gets + count.gets,
29
+ keys: sum.keys + count.keys,
30
+ queries: sum.queries + count.queries,
31
+ rows: sum.rows + count.rows
32
+ }), EMPTY),
33
+ byTable: (table) => tables.get(table) ?? EMPTY,
34
+ reset: () => tables.clear()
35
+ }
36
+ };
37
+ };
38
+ const fail = (message) => {
39
+ throw new DatabaseAdapterContractError(message);
40
+ };
41
+ const sameKey = (left, right) => left.length === right.length && require_values.compareTuples(left, right) === 0;
42
+ const verifyRequest = (table, request) => {
43
+ const index = require_adapter.findPhysicalIndex(table, request.index);
44
+ if (!Number.isSafeInteger(request.limit) || request.limit < 1 || request.limit > 500) fail(`query limit must be 1–500.`);
45
+ if (request.eq.length !== index.eq.length || !request.eq.every(require_values.isKeyValue)) fail(`query on ${table.name}.${index.name} must bind every eq column.`);
46
+ return index;
47
+ };
48
+ const verifyRows = (table, request, rows) => {
49
+ const index = require_adapter.findPhysicalIndex(table, request.index);
50
+ if (rows.length > request.limit) fail(`${table.name}.${index.name} returned more than ${request.limit} rows.`);
51
+ let previous;
52
+ for (const row of rows) {
53
+ if (!require_values.matchesQuery(table, index, request, row)) fail(`${table.name}.${index.name} returned a row outside the request.`);
54
+ const tuple = require_values.indexOrderTuple(table, index, row);
55
+ if (previous !== void 0) {
56
+ const order = require_values.compareTuples(previous, tuple);
57
+ if (request.order === "asc" ? order >= 0 : order <= 0) fail(`${table.name}.${index.name} returned rows out of order.`);
58
+ }
59
+ previous = tuple;
60
+ }
61
+ return previous;
62
+ };
63
+ const verifyWrite = (adapter, ops) => {
64
+ if (ops.length === 0) fail("write needs at least one op.");
65
+ const seen = /* @__PURE__ */ new Set();
66
+ for (const op of ops) {
67
+ const key = op.type === "insert" ? require_adapter.rowKey(op.table, op.row) : op.key;
68
+ const id = JSON.stringify([op.table.name, key]);
69
+ if (seen.has(id)) fail(`write touches ${op.table.name} ${id} twice.`);
70
+ seen.add(id);
71
+ if (op.type === "insert" && typeof op.row["_v"] !== "number") fail(`insert into ${op.table.name} must set _v.`);
72
+ if (op.type === "patch" && Object.keys(op.set).some((column) => column === "_v" || op.table.key.includes(column))) fail(`patch of ${op.table.name} may not set key columns or _v.`);
73
+ }
74
+ if (!adapter.fits(ops)) fail("write does not fit in one atomic write.");
75
+ };
76
+ /** Wraps an adapter to check the contract at its boundary and count reads. */
77
+ const verifyAdapter = (adapter, options = {}) => {
78
+ const { add, meter } = createReadMeter();
79
+ return {
80
+ ...adapter,
81
+ id: adapter.id,
82
+ reads: meter,
83
+ fits: (ops) => adapter.fits(ops),
84
+ async get(table, keys) {
85
+ const rows = await adapter.get(table, keys);
86
+ add(table.name, {
87
+ gets: 1,
88
+ keys: keys.length
89
+ });
90
+ if (rows.length !== keys.length) fail(`${table.name} get returned ${rows.length} rows for ${keys.length} keys.`);
91
+ rows.forEach((row, position) => {
92
+ if (row !== null && !sameKey(require_adapter.rowKey(table, row), keys[position])) fail(`${table.name} get returned a row for another key.`);
93
+ });
94
+ return rows;
95
+ },
96
+ async query(table, request) {
97
+ const index = verifyRequest(table, request);
98
+ const rows = await adapter.query(table, request);
99
+ add(table.name, {
100
+ queries: 1,
101
+ rows: rows.length
102
+ });
103
+ const last = verifyRows(table, request, rows);
104
+ if (options.probeShortPages && last !== void 0 && rows.length < request.limit) {
105
+ const bound = {
106
+ values: last,
107
+ inclusive: false
108
+ };
109
+ if ((await adapter.query(table, {
110
+ ...request,
111
+ limit: 1,
112
+ ...request.order === "asc" ? { lower: bound } : { upper: bound }
113
+ })).length > 0) fail(`${table.name}.${index.name} returned a short page before the range ended.`);
114
+ }
115
+ return rows;
116
+ },
117
+ async write(ops) {
118
+ verifyWrite(adapter, ops);
119
+ const result = await adapter.write(ops);
120
+ if (!result.ok && "failedOp" in result) {
121
+ if (!Number.isSafeInteger(result.failedOp) || result.failedOp < 0 || result.failedOp >= ops.length) fail(`write reported failedOp ${result.failedOp} for ${ops.length} ops.`);
122
+ }
123
+ return result;
124
+ }
125
+ };
126
+ };
127
+ //#endregion
128
+ exports.DatabaseAdapterContractError = DatabaseAdapterContractError;
129
+ exports.verifyAdapter = verifyAdapter;
@@ -0,0 +1,29 @@
1
+ import { DatabaseAdapter } from "./adapter.cjs";
2
+ //#region src/database/verifyAdapter.d.ts
3
+ declare class DatabaseAdapterContractError extends Error {
4
+ readonly name = "DatabaseAdapterContractError";
5
+ }
6
+ interface DatabaseReadCount {
7
+ /** `get` calls and the keys they asked for, found or not. */
8
+ readonly gets: number;
9
+ readonly keys: number;
10
+ /** `query` calls, zero-row calls included, and the rows they returned. */
11
+ readonly queries: number;
12
+ readonly rows: number;
13
+ }
14
+ interface DatabaseReadMeter {
15
+ total(): DatabaseReadCount;
16
+ byTable(table: string): DatabaseReadCount;
17
+ reset(): void;
18
+ }
19
+ interface VerifiedDatabaseAdapter extends DatabaseAdapter {
20
+ readonly reads: DatabaseReadMeter;
21
+ }
22
+ interface VerifyAdapterOptions {
23
+ /** After a short page, probe once past its last row to prove the range ended. */
24
+ readonly probeShortPages?: boolean;
25
+ }
26
+ /** Wraps an adapter to check the contract at its boundary and count reads. */
27
+ declare const verifyAdapter: (adapter: DatabaseAdapter, options?: VerifyAdapterOptions) => VerifiedDatabaseAdapter;
28
+ //#endregion
29
+ export { DatabaseAdapterContractError, DatabaseReadCount, DatabaseReadMeter, VerifiedDatabaseAdapter, VerifyAdapterOptions, verifyAdapter };
@@ -0,0 +1,29 @@
1
+ import { DatabaseAdapter } from "./adapter.mjs";
2
+ //#region src/database/verifyAdapter.d.ts
3
+ declare class DatabaseAdapterContractError extends Error {
4
+ readonly name = "DatabaseAdapterContractError";
5
+ }
6
+ interface DatabaseReadCount {
7
+ /** `get` calls and the keys they asked for, found or not. */
8
+ readonly gets: number;
9
+ readonly keys: number;
10
+ /** `query` calls, zero-row calls included, and the rows they returned. */
11
+ readonly queries: number;
12
+ readonly rows: number;
13
+ }
14
+ interface DatabaseReadMeter {
15
+ total(): DatabaseReadCount;
16
+ byTable(table: string): DatabaseReadCount;
17
+ reset(): void;
18
+ }
19
+ interface VerifiedDatabaseAdapter extends DatabaseAdapter {
20
+ readonly reads: DatabaseReadMeter;
21
+ }
22
+ interface VerifyAdapterOptions {
23
+ /** After a short page, probe once past its last row to prove the range ended. */
24
+ readonly probeShortPages?: boolean;
25
+ }
26
+ /** Wraps an adapter to check the contract at its boundary and count reads. */
27
+ declare const verifyAdapter: (adapter: DatabaseAdapter, options?: VerifyAdapterOptions) => VerifiedDatabaseAdapter;
28
+ //#endregion
29
+ export { DatabaseAdapterContractError, DatabaseReadCount, DatabaseReadMeter, VerifiedDatabaseAdapter, VerifyAdapterOptions, verifyAdapter };
@@ -0,0 +1,128 @@
1
+ import { findPhysicalIndex, rowKey } from "./adapter.mjs";
2
+ import { compareTuples, indexOrderTuple, isKeyValue, matchesQuery } from "./values.mjs";
3
+ //#region src/database/verifyAdapter.ts
4
+ var DatabaseAdapterContractError = class extends Error {
5
+ name = "DatabaseAdapterContractError";
6
+ };
7
+ const EMPTY = {
8
+ gets: 0,
9
+ keys: 0,
10
+ queries: 0,
11
+ rows: 0
12
+ };
13
+ const createReadMeter = () => {
14
+ const tables = /* @__PURE__ */ new Map();
15
+ const add = (table, count) => {
16
+ const current = tables.get(table) ?? EMPTY;
17
+ tables.set(table, {
18
+ gets: current.gets + (count.gets ?? 0),
19
+ keys: current.keys + (count.keys ?? 0),
20
+ queries: current.queries + (count.queries ?? 0),
21
+ rows: current.rows + (count.rows ?? 0)
22
+ });
23
+ };
24
+ return {
25
+ add,
26
+ meter: {
27
+ total: () => [...tables.values()].reduce((sum, count) => ({
28
+ gets: sum.gets + count.gets,
29
+ keys: sum.keys + count.keys,
30
+ queries: sum.queries + count.queries,
31
+ rows: sum.rows + count.rows
32
+ }), EMPTY),
33
+ byTable: (table) => tables.get(table) ?? EMPTY,
34
+ reset: () => tables.clear()
35
+ }
36
+ };
37
+ };
38
+ const fail = (message) => {
39
+ throw new DatabaseAdapterContractError(message);
40
+ };
41
+ const sameKey = (left, right) => left.length === right.length && compareTuples(left, right) === 0;
42
+ const verifyRequest = (table, request) => {
43
+ const index = findPhysicalIndex(table, request.index);
44
+ if (!Number.isSafeInteger(request.limit) || request.limit < 1 || request.limit > 500) fail(`query limit must be 1–500.`);
45
+ if (request.eq.length !== index.eq.length || !request.eq.every(isKeyValue)) fail(`query on ${table.name}.${index.name} must bind every eq column.`);
46
+ return index;
47
+ };
48
+ const verifyRows = (table, request, rows) => {
49
+ const index = findPhysicalIndex(table, request.index);
50
+ if (rows.length > request.limit) fail(`${table.name}.${index.name} returned more than ${request.limit} rows.`);
51
+ let previous;
52
+ for (const row of rows) {
53
+ if (!matchesQuery(table, index, request, row)) fail(`${table.name}.${index.name} returned a row outside the request.`);
54
+ const tuple = indexOrderTuple(table, index, row);
55
+ if (previous !== void 0) {
56
+ const order = compareTuples(previous, tuple);
57
+ if (request.order === "asc" ? order >= 0 : order <= 0) fail(`${table.name}.${index.name} returned rows out of order.`);
58
+ }
59
+ previous = tuple;
60
+ }
61
+ return previous;
62
+ };
63
+ const verifyWrite = (adapter, ops) => {
64
+ if (ops.length === 0) fail("write needs at least one op.");
65
+ const seen = /* @__PURE__ */ new Set();
66
+ for (const op of ops) {
67
+ const key = op.type === "insert" ? rowKey(op.table, op.row) : op.key;
68
+ const id = JSON.stringify([op.table.name, key]);
69
+ if (seen.has(id)) fail(`write touches ${op.table.name} ${id} twice.`);
70
+ seen.add(id);
71
+ if (op.type === "insert" && typeof op.row["_v"] !== "number") fail(`insert into ${op.table.name} must set _v.`);
72
+ if (op.type === "patch" && Object.keys(op.set).some((column) => column === "_v" || op.table.key.includes(column))) fail(`patch of ${op.table.name} may not set key columns or _v.`);
73
+ }
74
+ if (!adapter.fits(ops)) fail("write does not fit in one atomic write.");
75
+ };
76
+ /** Wraps an adapter to check the contract at its boundary and count reads. */
77
+ const verifyAdapter = (adapter, options = {}) => {
78
+ const { add, meter } = createReadMeter();
79
+ return {
80
+ ...adapter,
81
+ id: adapter.id,
82
+ reads: meter,
83
+ fits: (ops) => adapter.fits(ops),
84
+ async get(table, keys) {
85
+ const rows = await adapter.get(table, keys);
86
+ add(table.name, {
87
+ gets: 1,
88
+ keys: keys.length
89
+ });
90
+ if (rows.length !== keys.length) fail(`${table.name} get returned ${rows.length} rows for ${keys.length} keys.`);
91
+ rows.forEach((row, position) => {
92
+ if (row !== null && !sameKey(rowKey(table, row), keys[position])) fail(`${table.name} get returned a row for another key.`);
93
+ });
94
+ return rows;
95
+ },
96
+ async query(table, request) {
97
+ const index = verifyRequest(table, request);
98
+ const rows = await adapter.query(table, request);
99
+ add(table.name, {
100
+ queries: 1,
101
+ rows: rows.length
102
+ });
103
+ const last = verifyRows(table, request, rows);
104
+ if (options.probeShortPages && last !== void 0 && rows.length < request.limit) {
105
+ const bound = {
106
+ values: last,
107
+ inclusive: false
108
+ };
109
+ if ((await adapter.query(table, {
110
+ ...request,
111
+ limit: 1,
112
+ ...request.order === "asc" ? { lower: bound } : { upper: bound }
113
+ })).length > 0) fail(`${table.name}.${index.name} returned a short page before the range ended.`);
114
+ }
115
+ return rows;
116
+ },
117
+ async write(ops) {
118
+ verifyWrite(adapter, ops);
119
+ const result = await adapter.write(ops);
120
+ if (!result.ok && "failedOp" in result) {
121
+ if (!Number.isSafeInteger(result.failedOp) || result.failedOp < 0 || result.failedOp >= ops.length) fail(`write reported failedOp ${result.failedOp} for ${ops.length} ops.`);
122
+ }
123
+ return result;
124
+ }
125
+ };
126
+ };
127
+ //#endregion
128
+ export { DatabaseAdapterContractError, verifyAdapter };
@@ -0,0 +1,30 @@
1
+ //#region src/databaseErrors.ts
2
+ /** A bundle an operation names is not stored. */
3
+ var DatabaseBundleNotFoundError = class extends Error {
4
+ bundleId;
5
+ name = "DatabaseBundleNotFoundError";
6
+ constructor(bundleId) {
7
+ super(`Bundle "${bundleId}" was not found.`);
8
+ this.bundleId = bundleId;
9
+ }
10
+ };
11
+ /** A row a delete names is still referenced, such as a bundle a release uses. */
12
+ var DatabaseRowReferencedError = class extends Error {
13
+ name = "DatabaseRowReferencedError";
14
+ constructor() {
15
+ super("The database row is still referenced.");
16
+ }
17
+ };
18
+ /** Input a database operation refuses before touching storage. */
19
+ var DatabasePluginInputError = class extends Error {
20
+ code;
21
+ name = "DatabasePluginInputError";
22
+ constructor(code) {
23
+ super(`Invalid database plugin input: ${code}`);
24
+ this.code = code;
25
+ }
26
+ };
27
+ //#endregion
28
+ exports.DatabaseBundleNotFoundError = DatabaseBundleNotFoundError;
29
+ exports.DatabasePluginInputError = DatabasePluginInputError;
30
+ exports.DatabaseRowReferencedError = DatabaseRowReferencedError;
@@ -0,0 +1,21 @@
1
+ //#region src/databaseErrors.d.ts
2
+ /** A bundle an operation names is not stored. */
3
+ declare class DatabaseBundleNotFoundError extends Error {
4
+ readonly bundleId: string;
5
+ readonly name = "DatabaseBundleNotFoundError";
6
+ constructor(bundleId: string);
7
+ }
8
+ /** A row a delete names is still referenced, such as a bundle a release uses. */
9
+ declare class DatabaseRowReferencedError extends Error {
10
+ readonly name = "DatabaseRowReferencedError";
11
+ constructor();
12
+ }
13
+ type DatabasePluginInputErrorCode = "invalid-data" | "invalid-field" | "invalid-pagination" | "invalid-query" | "invalid-result";
14
+ /** Input a database operation refuses before touching storage. */
15
+ declare class DatabasePluginInputError extends Error {
16
+ readonly code: DatabasePluginInputErrorCode;
17
+ readonly name = "DatabasePluginInputError";
18
+ constructor(code: DatabasePluginInputErrorCode);
19
+ }
20
+ //#endregion
21
+ export { DatabaseBundleNotFoundError, DatabasePluginInputError, DatabasePluginInputErrorCode, DatabaseRowReferencedError };
@@ -0,0 +1,21 @@
1
+ //#region src/databaseErrors.d.ts
2
+ /** A bundle an operation names is not stored. */
3
+ declare class DatabaseBundleNotFoundError extends Error {
4
+ readonly bundleId: string;
5
+ readonly name = "DatabaseBundleNotFoundError";
6
+ constructor(bundleId: string);
7
+ }
8
+ /** A row a delete names is still referenced, such as a bundle a release uses. */
9
+ declare class DatabaseRowReferencedError extends Error {
10
+ readonly name = "DatabaseRowReferencedError";
11
+ constructor();
12
+ }
13
+ type DatabasePluginInputErrorCode = "invalid-data" | "invalid-field" | "invalid-pagination" | "invalid-query" | "invalid-result";
14
+ /** Input a database operation refuses before touching storage. */
15
+ declare class DatabasePluginInputError extends Error {
16
+ readonly code: DatabasePluginInputErrorCode;
17
+ readonly name = "DatabasePluginInputError";
18
+ constructor(code: DatabasePluginInputErrorCode);
19
+ }
20
+ //#endregion
21
+ export { DatabaseBundleNotFoundError, DatabasePluginInputError, DatabasePluginInputErrorCode, DatabaseRowReferencedError };
@@ -0,0 +1,28 @@
1
+ //#region src/databaseErrors.ts
2
+ /** A bundle an operation names is not stored. */
3
+ var DatabaseBundleNotFoundError = class extends Error {
4
+ bundleId;
5
+ name = "DatabaseBundleNotFoundError";
6
+ constructor(bundleId) {
7
+ super(`Bundle "${bundleId}" was not found.`);
8
+ this.bundleId = bundleId;
9
+ }
10
+ };
11
+ /** A row a delete names is still referenced, such as a bundle a release uses. */
12
+ var DatabaseRowReferencedError = class extends Error {
13
+ name = "DatabaseRowReferencedError";
14
+ constructor() {
15
+ super("The database row is still referenced.");
16
+ }
17
+ };
18
+ /** Input a database operation refuses before touching storage. */
19
+ var DatabasePluginInputError = class extends Error {
20
+ code;
21
+ name = "DatabasePluginInputError";
22
+ constructor(code) {
23
+ super(`Invalid database plugin input: ${code}`);
24
+ this.code = code;
25
+ }
26
+ };
27
+ //#endregion
28
+ export { DatabaseBundleNotFoundError, DatabasePluginInputError, DatabaseRowReferencedError };
@@ -1,11 +1,11 @@
1
- const require_databasePluginCrudValidationErrors = require("./databasePluginCrudValidationErrors.cjs");
1
+ const require_databaseErrors = require("./databaseErrors.cjs");
2
2
  const require_databaseJsonValue = require("./databaseJsonValue.cjs");
3
3
  let _hot_updater_core = require("@hot-updater/core");
4
4
  //#region src/databaseMetadata.ts
5
5
  const bundleMetadataToRow = (metadata) => {
6
6
  const value = (0, _hot_updater_core.stripBundleArtifactMetadata)(metadata);
7
7
  if (value === void 0) return {};
8
- if (!require_databaseJsonValue.isDatabaseMetadataObject(value)) throw new require_databasePluginCrudValidationErrors.DatabasePluginInputError("invalid-data");
8
+ if (!require_databaseJsonValue.isDatabaseMetadataObject(value)) throw new require_databaseErrors.DatabasePluginInputError("invalid-data");
9
9
  return value;
10
10
  };
11
11
  //#endregion
@@ -1,4 +1,4 @@
1
- import { DatabasePluginInputError } from "./databasePluginCrudValidationErrors.mjs";
1
+ import { DatabasePluginInputError } from "./databaseErrors.mjs";
2
2
  import { isDatabaseMetadataObject } from "./databaseJsonValue.mjs";
3
3
  import { stripBundleArtifactMetadata } from "@hot-updater/core";
4
4
  //#region src/databaseMetadata.ts
@@ -64,10 +64,7 @@ const bundleToRow = (bundle) => {
64
64
  return {
65
65
  id: bundle.id,
66
66
  platform: bundle.platform,
67
- file_hash: bundle.fileHash,
68
67
  git_commit_hash: bundle.gitCommitHash,
69
- storage_uri: bundle.storageUri,
70
- archive_byte_size: bundle.archiveByteSize,
71
68
  metadata,
72
69
  manifest_storage_uri: (0, _hot_updater_core.getManifestStorageUri)(bundle),
73
70
  manifest_file_hash: (0, _hot_updater_core.getManifestFileHash)(bundle),
@@ -97,10 +94,7 @@ const rowToBundle = (row, patchRows = []) => {
97
94
  return {
98
95
  id: row.id,
99
96
  platform: row.platform,
100
- fileHash: row.file_hash,
101
97
  gitCommitHash: row.git_commit_hash,
102
- storageUri: row.storage_uri,
103
- archiveByteSize: row.archive_byte_size,
104
98
  metadata: (0, _hot_updater_core.stripBundleArtifactMetadata)(row.metadata),
105
99
  manifestStorageUri: row.manifest_storage_uri,
106
100
  manifestFileHash: row.manifest_file_hash,
@@ -64,10 +64,7 @@ const bundleToRow = (bundle) => {
64
64
  return {
65
65
  id: bundle.id,
66
66
  platform: bundle.platform,
67
- file_hash: bundle.fileHash,
68
67
  git_commit_hash: bundle.gitCommitHash,
69
- storage_uri: bundle.storageUri,
70
- archive_byte_size: bundle.archiveByteSize,
71
68
  metadata,
72
69
  manifest_storage_uri: getManifestStorageUri(bundle),
73
70
  manifest_file_hash: getManifestFileHash(bundle),
@@ -97,10 +94,7 @@ const rowToBundle = (row, patchRows = []) => {
97
94
  return {
98
95
  id: row.id,
99
96
  platform: row.platform,
100
- fileHash: row.file_hash,
101
97
  gitCommitHash: row.git_commit_hash,
102
- storageUri: row.storage_uri,
103
- archiveByteSize: row.archive_byte_size,
104
98
  metadata: stripBundleArtifactMetadata(row.metadata),
105
99
  manifestStorageUri: row.manifest_storage_uri,
106
100
  manifestFileHash: row.manifest_file_hash,