@sfxcode/nuxt-ui-mongocamp 1.3.5 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/README.md +1 -1
  2. package/dist/module.d.mts +8 -0
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +6 -0
  5. package/dist/runtime/components/MongocampAggregationBuilder.d.vue.ts +1 -0
  6. package/dist/runtime/components/MongocampAggregationBuilder.vue +331 -5
  7. package/dist/runtime/components/MongocampAggregationBuilder.vue.d.ts +1 -0
  8. package/dist/runtime/components/MongocampAggregationChart.d.vue.ts +6 -0
  9. package/dist/runtime/components/MongocampAggregationChart.vue +93 -0
  10. package/dist/runtime/components/MongocampAggregationChart.vue.d.ts +6 -0
  11. package/dist/runtime/components/MongocampAggregationStagePreview.d.vue.ts +10 -0
  12. package/dist/runtime/components/MongocampAggregationStagePreview.vue +149 -0
  13. package/dist/runtime/components/MongocampAggregationStagePreview.vue.d.ts +10 -0
  14. package/dist/runtime/components/MongocampBucketFiles.vue +230 -48
  15. package/dist/runtime/components/MongocampBulkDelete.d.vue.ts +9 -0
  16. package/dist/runtime/components/MongocampBulkDelete.vue +94 -25
  17. package/dist/runtime/components/MongocampBulkDelete.vue.d.ts +9 -0
  18. package/dist/runtime/components/MongocampBulkEdit.d.vue.ts +5 -0
  19. package/dist/runtime/components/MongocampBulkEdit.vue +41 -3
  20. package/dist/runtime/components/MongocampBulkEdit.vue.d.ts +5 -0
  21. package/dist/runtime/components/MongocampChart.d.vue.ts +29 -0
  22. package/dist/runtime/components/MongocampChart.vue +129 -0
  23. package/dist/runtime/components/MongocampChart.vue.d.ts +29 -0
  24. package/dist/runtime/components/MongocampCollectionCharts.d.vue.ts +17 -0
  25. package/dist/runtime/components/MongocampCollectionCharts.vue +200 -0
  26. package/dist/runtime/components/MongocampCollectionCharts.vue.d.ts +17 -0
  27. package/dist/runtime/components/MongocampCollectionCopy.d.vue.ts +23 -0
  28. package/dist/runtime/components/MongocampCollectionCopy.vue +206 -0
  29. package/dist/runtime/components/MongocampCollectionCopy.vue.d.ts +23 -0
  30. package/dist/runtime/components/MongocampCollectionData.d.vue.ts +6 -0
  31. package/dist/runtime/components/MongocampCollectionData.vue +423 -138
  32. package/dist/runtime/components/MongocampCollectionData.vue.d.ts +6 -0
  33. package/dist/runtime/components/MongocampCollectionInfos.vue +106 -238
  34. package/dist/runtime/components/MongocampCollectionRename.d.vue.ts +22 -0
  35. package/dist/runtime/components/MongocampCollectionRename.vue +116 -0
  36. package/dist/runtime/components/MongocampCollectionRename.vue.d.ts +22 -0
  37. package/dist/runtime/components/MongocampCollections.vue +93 -12
  38. package/dist/runtime/components/MongocampCommandPalette.d.vue.ts +40 -0
  39. package/dist/runtime/components/MongocampCommandPalette.vue +135 -0
  40. package/dist/runtime/components/MongocampCommandPalette.vue.d.ts +40 -0
  41. package/dist/runtime/components/MongocampConfirmByName.vue +2 -2
  42. package/dist/runtime/components/MongocampDashboard.d.vue.ts +3 -1
  43. package/dist/runtime/components/MongocampDashboard.vue +39 -5
  44. package/dist/runtime/components/MongocampDashboard.vue.d.ts +3 -1
  45. package/dist/runtime/components/MongocampDatabases.vue +35 -2
  46. package/dist/runtime/components/MongocampDocumentCompare.d.vue.ts +20 -0
  47. package/dist/runtime/components/MongocampDocumentCompare.vue +146 -0
  48. package/dist/runtime/components/MongocampDocumentCompare.vue.d.ts +20 -0
  49. package/dist/runtime/components/MongocampDocumentView.d.vue.ts +22 -0
  50. package/dist/runtime/components/MongocampDocumentView.vue +202 -0
  51. package/dist/runtime/components/MongocampDocumentView.vue.d.ts +22 -0
  52. package/dist/runtime/components/MongocampErrorAlert.vue +12 -4
  53. package/dist/runtime/components/MongocampExportAll.d.vue.ts +18 -0
  54. package/dist/runtime/components/MongocampExportAll.vue +191 -0
  55. package/dist/runtime/components/MongocampExportAll.vue.d.ts +18 -0
  56. package/dist/runtime/components/MongocampFilePreview.d.vue.ts +16 -0
  57. package/dist/runtime/components/MongocampFilePreview.vue +162 -0
  58. package/dist/runtime/components/MongocampFilePreview.vue.d.ts +16 -0
  59. package/dist/runtime/components/MongocampFilterBuilder.vue +11 -0
  60. package/dist/runtime/components/MongocampImport.vue +171 -13
  61. package/dist/runtime/components/MongocampIndexes.d.vue.ts +18 -0
  62. package/dist/runtime/components/MongocampIndexes.vue +496 -0
  63. package/dist/runtime/components/MongocampIndexes.vue.d.ts +18 -0
  64. package/dist/runtime/components/MongocampJobs.d.vue.ts +6 -1
  65. package/dist/runtime/components/MongocampJobs.vue +36 -5
  66. package/dist/runtime/components/MongocampJobs.vue.d.ts +6 -1
  67. package/dist/runtime/components/MongocampPermissionMatrix.d.vue.ts +12 -0
  68. package/dist/runtime/components/MongocampPermissionMatrix.vue +301 -0
  69. package/dist/runtime/components/MongocampPermissionMatrix.vue.d.ts +12 -0
  70. package/dist/runtime/components/MongocampQueryBar.d.vue.ts +26 -0
  71. package/dist/runtime/components/MongocampQueryBar.vue +398 -0
  72. package/dist/runtime/components/MongocampQueryBar.vue.d.ts +26 -0
  73. package/dist/runtime/components/MongocampRoleGrants.vue +18 -5
  74. package/dist/runtime/components/MongocampRoles.vue +16 -5
  75. package/dist/runtime/components/MongocampServerOverview.d.vue.ts +20 -0
  76. package/dist/runtime/components/MongocampServerOverview.vue +420 -0
  77. package/dist/runtime/components/MongocampServerOverview.vue.d.ts +20 -0
  78. package/dist/runtime/components/MongocampSettings.d.vue.ts +28 -1
  79. package/dist/runtime/components/MongocampSettings.vue +83 -10
  80. package/dist/runtime/components/MongocampSettings.vue.d.ts +28 -1
  81. package/dist/runtime/components/MongocampUsers.vue +19 -6
  82. package/dist/runtime/composables/useMongocampAdmin.d.ts +2 -1
  83. package/dist/runtime/composables/useMongocampAdmin.js +6 -1
  84. package/dist/runtime/composables/useMongocampAdminGate.d.ts +12 -0
  85. package/dist/runtime/composables/useMongocampAdminGate.js +12 -0
  86. package/dist/runtime/composables/useMongocampAggregation.d.ts +23 -1
  87. package/dist/runtime/composables/useMongocampAggregation.js +41 -26
  88. package/dist/runtime/composables/useMongocampAutoRefresh.d.ts +26 -0
  89. package/dist/runtime/composables/useMongocampAutoRefresh.js +78 -0
  90. package/dist/runtime/composables/useMongocampBucket.d.ts +13 -1
  91. package/dist/runtime/composables/useMongocampBucket.js +34 -0
  92. package/dist/runtime/composables/useMongocampBulkByFilter.d.ts +15 -0
  93. package/dist/runtime/composables/useMongocampBulkByFilter.js +32 -0
  94. package/dist/runtime/composables/useMongocampClientApi.js +2 -1
  95. package/dist/runtime/composables/useMongocampCollectionCopy.d.ts +45 -0
  96. package/dist/runtime/composables/useMongocampCollectionCopy.js +48 -0
  97. package/dist/runtime/composables/useMongocampCollectionStats.d.ts +10 -0
  98. package/dist/runtime/composables/useMongocampCollectionStats.js +17 -0
  99. package/dist/runtime/composables/useMongocampError.d.ts +2 -1
  100. package/dist/runtime/composables/useMongocampError.js +16 -1
  101. package/dist/runtime/composables/useMongocampExportAll.d.ts +53 -0
  102. package/dist/runtime/composables/useMongocampExportAll.js +57 -0
  103. package/dist/runtime/composables/useMongocampExtendedJson.d.ts +7 -2
  104. package/dist/runtime/composables/useMongocampExtendedJson.js +44 -11
  105. package/dist/runtime/composables/useMongocampFetchAll.d.ts +25 -0
  106. package/dist/runtime/composables/useMongocampFetchAll.js +27 -0
  107. package/dist/runtime/composables/useMongocampFieldTypes.d.ts +24 -0
  108. package/dist/runtime/composables/useMongocampFieldTypes.js +44 -0
  109. package/dist/runtime/composables/useMongocampImport.d.ts +4 -0
  110. package/dist/runtime/composables/useMongocampImport.js +5 -2
  111. package/dist/runtime/composables/useMongocampIndex.d.ts +6 -1
  112. package/dist/runtime/composables/useMongocampIndex.js +7 -1
  113. package/dist/runtime/composables/useMongocampPermissions.d.ts +17 -0
  114. package/dist/runtime/composables/useMongocampPermissions.js +43 -0
  115. package/dist/runtime/composables/useMongocampPersistedState.d.ts +15 -0
  116. package/dist/runtime/composables/useMongocampPersistedState.js +21 -0
  117. package/dist/runtime/composables/useMongocampProxyApi.js +2 -1
  118. package/dist/runtime/composables/useMongocampQuery.d.ts +50 -2
  119. package/dist/runtime/composables/useMongocampQuery.js +72 -1
  120. package/dist/runtime/composables/useMongocampSavedPipelines.d.ts +25 -0
  121. package/dist/runtime/composables/useMongocampSavedPipelines.js +23 -0
  122. package/dist/runtime/composables/useMongocampSavedQueries.d.ts +37 -0
  123. package/dist/runtime/composables/useMongocampSavedQueries.js +50 -0
  124. package/dist/runtime/composables/useMongocampServerOverview.d.ts +35 -0
  125. package/dist/runtime/composables/useMongocampServerOverview.js +51 -0
  126. package/dist/runtime/composables/useMongocampSession.d.ts +2 -0
  127. package/dist/runtime/composables/useMongocampSession.js +16 -2
  128. package/dist/runtime/composables/useMongocampSystem.d.ts +7 -2
  129. package/dist/runtime/composables/useMongocampSystem.js +6 -2
  130. package/dist/runtime/locales/de.json +509 -25
  131. package/dist/runtime/locales/en.json +509 -25
  132. package/dist/runtime/plugin.js +6 -3
  133. package/dist/runtime/utils/aggregationErrors.d.ts +4 -0
  134. package/dist/runtime/utils/aggregationErrors.js +7 -0
  135. package/dist/runtime/utils/aggregationPipeline.d.ts +5 -4
  136. package/dist/runtime/utils/aggregationPipeline.js +23 -9
  137. package/dist/runtime/utils/aggregationPreview.d.ts +13 -0
  138. package/dist/runtime/utils/aggregationPreview.js +10 -0
  139. package/dist/runtime/utils/aggregationResult.d.ts +5 -0
  140. package/dist/runtime/utils/aggregationResult.js +4 -0
  141. package/dist/runtime/utils/aggregationTemplates.d.ts +34 -0
  142. package/dist/runtime/utils/aggregationTemplates.js +47 -0
  143. package/dist/runtime/utils/analyzeSamples.d.ts +1 -0
  144. package/dist/runtime/utils/analyzeSamples.js +1 -1
  145. package/dist/runtime/utils/autoRefresh.d.ts +14 -0
  146. package/dist/runtime/utils/autoRefresh.js +15 -0
  147. package/dist/runtime/utils/batchInsert.d.ts +6 -0
  148. package/dist/runtime/utils/batchInsert.js +31 -3
  149. package/dist/runtime/utils/bigIntJson.d.ts +15 -0
  150. package/dist/runtime/utils/bigIntJson.js +55 -0
  151. package/dist/runtime/utils/bsonTypes.d.ts +10 -0
  152. package/dist/runtime/utils/bsonTypes.js +42 -0
  153. package/dist/runtime/utils/bulkDelete.d.ts +9 -1
  154. package/dist/runtime/utils/bulkDelete.js +15 -3
  155. package/dist/runtime/utils/bulkEdit.d.ts +6 -0
  156. package/dist/runtime/utils/bulkEdit.js +7 -0
  157. package/dist/runtime/utils/chartData.d.ts +11 -0
  158. package/dist/runtime/utils/chartData.js +9 -0
  159. package/dist/runtime/utils/collectionChart.d.ts +36 -0
  160. package/dist/runtime/utils/collectionChart.js +73 -0
  161. package/dist/runtime/utils/collectionCopy.d.ts +24 -0
  162. package/dist/runtime/utils/collectionCopy.js +37 -0
  163. package/dist/runtime/utils/collectionStats.d.ts +31 -0
  164. package/dist/runtime/utils/collectionStats.js +42 -0
  165. package/dist/runtime/utils/commandPalette.d.ts +48 -0
  166. package/dist/runtime/utils/commandPalette.js +39 -0
  167. package/dist/runtime/utils/configRows.d.ts +7 -0
  168. package/dist/runtime/utils/configRows.js +4 -0
  169. package/dist/runtime/utils/documentCompare.d.ts +31 -0
  170. package/dist/runtime/utils/documentCompare.js +71 -0
  171. package/dist/runtime/utils/documentDiff.d.ts +19 -0
  172. package/dist/runtime/utils/documentDiff.js +71 -0
  173. package/dist/runtime/utils/documentPaths.d.ts +41 -0
  174. package/dist/runtime/utils/documentPaths.js +139 -0
  175. package/dist/runtime/utils/documentTree.d.ts +40 -0
  176. package/dist/runtime/utils/documentTree.js +102 -0
  177. package/dist/runtime/utils/exportDocuments.d.ts +33 -0
  178. package/dist/runtime/utils/exportDocuments.js +53 -0
  179. package/dist/runtime/utils/exportRows.d.ts +2 -0
  180. package/dist/runtime/utils/exportRows.js +6 -3
  181. package/dist/runtime/utils/fieldDetails.d.ts +51 -0
  182. package/dist/runtime/utils/fieldDetails.js +113 -0
  183. package/dist/runtime/utils/filePreview.d.ts +27 -0
  184. package/dist/runtime/utils/filePreview.js +50 -0
  185. package/dist/runtime/utils/filterBuilder.d.ts +6 -1
  186. package/dist/runtime/utils/filterBuilder.js +6 -5
  187. package/dist/runtime/utils/formatBytes.d.ts +2 -0
  188. package/dist/runtime/utils/formatBytes.js +11 -0
  189. package/dist/runtime/utils/grantMatching.d.ts +8 -0
  190. package/dist/runtime/utils/grantMatching.js +15 -0
  191. package/dist/runtime/utils/importRows.js +12 -2
  192. package/dist/runtime/utils/indexForm.d.ts +83 -0
  193. package/dist/runtime/utils/indexForm.js +74 -0
  194. package/dist/runtime/utils/luceneExpression.d.ts +15 -0
  195. package/dist/runtime/utils/luceneExpression.js +74 -0
  196. package/dist/runtime/utils/pagedFetch.d.ts +46 -0
  197. package/dist/runtime/utils/pagedFetch.js +58 -0
  198. package/dist/runtime/utils/paginationHeaders.d.ts +4 -0
  199. package/dist/runtime/utils/paginationHeaders.js +4 -0
  200. package/dist/runtime/utils/permissionDenied.d.ts +10 -0
  201. package/dist/runtime/utils/permissionDenied.js +23 -0
  202. package/dist/runtime/utils/permissionMatrix.d.ts +55 -0
  203. package/dist/runtime/utils/permissionMatrix.js +85 -0
  204. package/dist/runtime/utils/persistedState.d.ts +25 -0
  205. package/dist/runtime/utils/persistedState.js +47 -0
  206. package/dist/runtime/utils/queryState.d.ts +45 -0
  207. package/dist/runtime/utils/queryState.js +75 -0
  208. package/dist/runtime/utils/requestLimits.d.ts +2 -0
  209. package/dist/runtime/utils/requestLimits.js +4 -0
  210. package/dist/runtime/utils/resultChart.d.ts +32 -0
  211. package/dist/runtime/utils/resultChart.js +59 -0
  212. package/dist/runtime/utils/savedPipelines.d.ts +22 -0
  213. package/dist/runtime/utils/savedPipelines.js +46 -0
  214. package/dist/runtime/utils/savedQueries.d.ts +60 -0
  215. package/dist/runtime/utils/savedQueries.js +143 -0
  216. package/dist/runtime/utils/schemaAnalysis.d.ts +16 -0
  217. package/dist/runtime/utils/schemaAnalysis.js +57 -0
  218. package/dist/runtime/utils/serverError.d.ts +19 -0
  219. package/dist/runtime/utils/serverError.js +19 -0
  220. package/dist/runtime/utils/serverOverview.d.ts +47 -0
  221. package/dist/runtime/utils/serverOverview.js +40 -0
  222. package/dist/runtime/utils/sessionGuard.d.ts +3 -0
  223. package/dist/runtime/utils/sessionGuard.js +18 -1
  224. package/package.json +15 -14
@@ -1,24 +1,27 @@
1
1
  import { defineNuxtPlugin, addRouteMiddleware, navigateTo, useAsyncData, useRuntimeConfig } from "#app";
2
- import { useMongocampAuth, useMongocampClientApi } from "#imports";
2
+ import { useMongocampAuth, useMongocampClientApi, useMongocampStorage } from "#imports";
3
3
  import { useMongocampRoles } from "./composables/useMongocampRoles.js";
4
4
  import { useMongocampSession } from "./composables/useMongocampSession.js";
5
- import { runSessionGuard } from "./utils/sessionGuard.js";
5
+ import { createVerifyCache, runSessionGuard } from "./utils/sessionGuard.js";
6
6
  export default defineNuxtPlugin(async (_nuxtApp) => {
7
7
  const { systemApi } = useMongocampClientApi();
8
8
  const config = useRuntimeConfig();
9
9
  const useGlobalAuthMiddleware = config.public.nuxtUiMongocampOptions.useGlobalAuthMiddleware ?? false;
10
10
  const useServerProxy = config.public.nuxtUiMongocampOptions.useServerProxy ?? false;
11
11
  const sessionGuard = config.public.nuxtUiMongocampOptions.sessionGuard ?? false;
12
+ const sessionGuardVerify = (config.public.nuxtUiMongocampOptions.sessionGuardVerify ?? false) && import.meta.client;
13
+ const verifyCache = createVerifyCache(3e4);
12
14
  const { data: version } = await useAsyncData("version", () => systemApi.version());
13
15
  if (sessionGuard && !useServerProxy) {
14
16
  addRouteMiddleware("session-guard", async (to) => {
15
- const { checkExpiry, invalidateSession } = useMongocampSession();
17
+ const { checkExpiry, invalidateSession, verify } = useMongocampSession();
16
18
  const { loginPath } = useMongocampRoles();
17
19
  const outcome = await runSessionGuard({
18
20
  path: to.path,
19
21
  loginPath,
20
22
  checkExpiry,
21
23
  invalidate: invalidateSession,
24
+ verify: sessionGuardVerify ? () => verifyCache(String(useMongocampStorage().value?.token ?? ""), verify) : void 0,
22
25
  // a fresh call: it must read the session as it is after the invalidation
23
26
  isAllowed: (path) => useMongocampRoles().isAllowedPathForRoute(path)
24
27
  });
@@ -3,6 +3,10 @@ export declare class ForbiddenPipelineError extends Error {
3
3
  findings: ForbiddenUse[];
4
4
  constructor(findings: ForbiddenUse[]);
5
5
  }
6
+ export declare class FilterTooLongError extends Error {
7
+ max: number;
8
+ constructor(max: number);
9
+ }
6
10
  export interface ServerErrorInfo {
7
11
  kind: 'mongo' | 'other';
8
12
  message: string;
@@ -5,6 +5,13 @@ export class ForbiddenPipelineError extends Error {
5
5
  this.name = "ForbiddenPipelineError";
6
6
  }
7
7
  }
8
+ export class FilterTooLongError extends Error {
9
+ constructor(max) {
10
+ super(`The filter is longer than ${max} characters`);
11
+ this.max = max;
12
+ this.name = "FilterTooLongError";
13
+ }
14
+ }
8
15
  const MONGO_COMMAND_FAILED = /^Command failed with error \d+ \([^)]*\): '([\s\S]*?)' on server \S+?\.\s+The full response is[\s\S]*$/;
9
16
  const SERVER_ADDRESS = / on server \S+?(?=\.(?:\s|$)|\s|$)/g;
10
17
  const BARE_ADDRESS = /\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b|\b[a-z0-9-]+(?:\.[a-z0-9-]+)+:\d{2,5}\b/gi;
@@ -1,5 +1,6 @@
1
- export declare const FORBIDDEN_OPERATORS: readonly ["$out", "$merge", "$function", "$accumulator", "$where", "$lookup", "$unionWith", "$graphLookup"];
2
- export declare const VISUAL_STAGE_TYPES: readonly ["$match", "$group", "$sort", "$project", "$limit"];
1
+ export declare const FORBIDDEN_OPERATORS: readonly ["$out", "$merge", "$function", "$accumulator", "$where", "$lookup", "$unionWith", "$graphLookup", "$collStats", "$indexStats"];
2
+ export declare const STATS_OPERATORS: readonly ["$collStats", "$indexStats"];
3
+ export declare const VISUAL_STAGE_TYPES: readonly ["$match", "$group", "$sort", "$project", "$limit", "$unwind", "$addFields", "$count", "$bucketAuto"];
3
4
  export type AggregationStageType = typeof VISUAL_STAGE_TYPES[number];
4
5
  export interface AggregationStage {
5
6
  id: string;
@@ -29,12 +30,12 @@ export type ParsedPipeline = {
29
30
  ok: false;
30
31
  error: PipelineError;
31
32
  };
32
- export type StageIssueCode = 'not-object' | 'invalid-limit' | 'invalid-sort' | 'group-needs-id';
33
+ export type StageIssueCode = 'not-object' | 'invalid-limit' | 'invalid-sort' | 'group-needs-id' | 'invalid-unwind' | 'invalid-count' | 'bucket-needs-fields';
33
34
  export interface StageIssue {
34
35
  stageIndex: number;
35
36
  code: StageIssueCode;
36
37
  }
37
- export declare function findForbidden(pipeline: RequestStage[]): ForbiddenUse[];
38
+ export declare function findForbidden(pipeline: RequestStage[], allowed?: readonly string[]): ForbiddenUse[];
38
39
  export declare function buildPipeline(stages: AggregationStage[]): RequestStage[];
39
40
  export declare function validateStages(stages: AggregationStage[]): StageIssue[];
40
41
  export declare function parsePipeline(text: string): ParsedPipeline;
@@ -6,9 +6,12 @@ export const FORBIDDEN_OPERATORS = [
6
6
  "$where",
7
7
  "$lookup",
8
8
  "$unionWith",
9
- "$graphLookup"
9
+ "$graphLookup",
10
+ "$collStats",
11
+ "$indexStats"
10
12
  ];
11
- export const VISUAL_STAGE_TYPES = ["$match", "$group", "$sort", "$project", "$limit"];
13
+ export const STATS_OPERATORS = ["$collStats", "$indexStats"];
14
+ export const VISUAL_STAGE_TYPES = ["$match", "$group", "$sort", "$project", "$limit", "$unwind", "$addFields", "$count", "$bucketAuto"];
12
15
  const MAX_TEXT_LENGTH = 2e5;
13
16
  const MAX_STAGES = 50;
14
17
  const MAX_DEPTH = 64;
@@ -17,28 +20,29 @@ const FORBIDDEN = new Set(FORBIDDEN_OPERATORS);
17
20
  function isPlainObject(value) {
18
21
  return typeof value === "object" && value !== null && !Array.isArray(value);
19
22
  }
20
- function scan(value, path, depth, stageIndex, found) {
23
+ function scan(value, path, depth, stageIndex, found, forbidden) {
21
24
  if (found.length >= MAX_FINDINGS) return;
22
25
  if (depth > MAX_DEPTH) {
23
26
  found.push({ stageIndex, operator: "too-deep", path });
24
27
  return;
25
28
  }
26
29
  if (Array.isArray(value)) {
27
- value.forEach((item, i) => scan(item, `${path}[${i}]`, depth + 1, stageIndex, found));
30
+ value.forEach((item, i) => scan(item, `${path}[${i}]`, depth + 1, stageIndex, found, forbidden));
28
31
  return;
29
32
  }
30
33
  if (!isPlainObject(value)) return;
31
34
  for (const [key, inner] of Object.entries(value)) {
32
35
  const keyPath = `${path}.${key}`;
33
- if (FORBIDDEN.has(key)) found.push({ stageIndex, operator: key, path: keyPath });
34
- scan(inner, keyPath, depth + 1, stageIndex, found);
36
+ if (forbidden.has(key)) found.push({ stageIndex, operator: key, path: keyPath });
37
+ scan(inner, keyPath, depth + 1, stageIndex, found, forbidden);
35
38
  }
36
39
  }
37
- export function findForbidden(pipeline) {
40
+ export function findForbidden(pipeline, allowed = []) {
41
+ const forbidden = allowed.length > 0 ? new Set([...FORBIDDEN].filter((operator) => !allowed.includes(operator))) : FORBIDDEN;
38
42
  const found = [];
39
43
  pipeline.forEach((stage, stageIndex) => {
40
- if (FORBIDDEN.has(stage.stage)) found.push({ stageIndex, operator: stage.stage, path: stage.stage });
41
- scan(stage.value, stage.stage, 0, stageIndex, found);
44
+ if (forbidden.has(stage.stage)) found.push({ stageIndex, operator: stage.stage, path: stage.stage });
45
+ scan(stage.value, stage.stage, 0, stageIndex, found, forbidden);
42
46
  });
43
47
  return found;
44
48
  }
@@ -66,12 +70,22 @@ export function validateStages(stages) {
66
70
  if (typeof value !== "number" || !Number.isInteger(value) || value < 1) issues.push({ stageIndex, code: "invalid-limit" });
67
71
  return;
68
72
  }
73
+ if (type === "$unwind") {
74
+ const path = typeof value === "string" ? value : isPlainObject(value) ? value.path : void 0;
75
+ if (typeof path !== "string" || !path.startsWith("$") || path.length < 2) issues.push({ stageIndex, code: "invalid-unwind" });
76
+ return;
77
+ }
78
+ if (type === "$count") {
79
+ if (typeof value !== "string" || value.startsWith("$") || value.includes(".")) issues.push({ stageIndex, code: "invalid-count" });
80
+ return;
81
+ }
69
82
  if (!isPlainObject(value)) {
70
83
  issues.push({ stageIndex, code: "not-object" });
71
84
  return;
72
85
  }
73
86
  if (type === "$group" && !("_id" in value)) issues.push({ stageIndex, code: "group-needs-id" });
74
87
  if (type === "$sort" && !Object.values(value).every((direction) => direction === 1 || direction === -1)) issues.push({ stageIndex, code: "invalid-sort" });
88
+ if (type === "$bucketAuto" && (!("groupBy" in value) || typeof value.buckets !== "number" || !Number.isInteger(value.buckets) || value.buckets < 1)) issues.push({ stageIndex, code: "bucket-needs-fields" });
75
89
  });
76
90
  return issues;
77
91
  }
@@ -0,0 +1,13 @@
1
+ import type { AggregationStage, RequestStage } from './aggregationPipeline.js';
2
+ /** Documents shown under a stage. */
3
+ export declare const PREVIEW_LIMIT = 5;
4
+ /** Wait after the last keystroke before a preview is run again. */
5
+ export declare const PREVIEW_DEBOUNCE_MS = 500;
6
+ /**
7
+ * The request pipeline for the preview after stage `upTo` (0-based): every stage up to it, with stages that have nothing in
8
+ * them yet left out (as when running), then a `$limit` so the server never builds more than a few documents. A stage that
9
+ * is itself a `$limit` is kept as it is — the appended one only ever makes the result shorter.
10
+ */
11
+ export declare function previewPipeline(stages: AggregationStage[], upTo: number, limit?: number): RequestStage[];
12
+ /** A stable text for a pipeline, to tell whether a preview is out of date. */
13
+ export declare function pipelineKey(pipeline: RequestStage[]): string;
@@ -0,0 +1,10 @@
1
+ import { buildPipeline } from "./aggregationPipeline.js";
2
+ export const PREVIEW_LIMIT = 5;
3
+ export const PREVIEW_DEBOUNCE_MS = 500;
4
+ export function previewPipeline(stages, upTo, limit = PREVIEW_LIMIT) {
5
+ const prefix = buildPipeline(stages.slice(0, upTo + 1));
6
+ return [...prefix, { stage: "$limit", value: Math.max(1, Math.floor(limit)) }];
7
+ }
8
+ export function pipelineKey(pipeline) {
9
+ return JSON.stringify(pipeline);
10
+ }
@@ -3,3 +3,8 @@ export declare function formatCell(value: unknown): {
3
3
  text: string;
4
4
  full: string;
5
5
  };
6
+ /**
7
+ * Drops the server-only keys from the top level of every row. Meant for the results of a stats stage — a user document
8
+ * may legitimately have a `host` field, so this is not applied to ordinary aggregation results.
9
+ */
10
+ export declare function stripServerFields(rows: Record<string, unknown>[]): Record<string, unknown>[];
@@ -15,3 +15,7 @@ export function formatCell(value) {
15
15
  const full = value === void 0 ? "" : typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
16
16
  return { text: full.length > MAX_CELL_LENGTH ? `${full.slice(0, MAX_CELL_LENGTH - 1)}\u2026` : full, full };
17
17
  }
18
+ const SERVER_ONLY_KEYS = ["host", "ns"];
19
+ export function stripServerFields(rows) {
20
+ return rows.map((row) => Object.fromEntries(Object.entries(row).filter(([key]) => !SERVER_ONLY_KEYS.includes(key))));
21
+ }
@@ -0,0 +1,34 @@
1
+ import type { AggregationStageType } from './aggregationPipeline.js';
2
+ export type TemplateKey = 'count-by-field' | 'top-values' | 'date-histogram' | 'sum-avg-by-group';
3
+ export interface TemplateStage {
4
+ type: AggregationStageType;
5
+ value: unknown;
6
+ }
7
+ export type DateUnit = 'year' | 'month' | 'day';
8
+ export interface TemplateInput {
9
+ field: string;
10
+ /** `sum-avg-by-group`: the numeric field to add up and average. */
11
+ valueField?: string;
12
+ /** `top-values`: how many values to keep (default 10). */
13
+ top?: number;
14
+ /** `date-histogram`: the bucket size (default month). */
15
+ unit?: DateUnit;
16
+ }
17
+ export interface TemplateInfo {
18
+ key: TemplateKey;
19
+ /** Which inputs it needs besides `field`. */
20
+ needsValueField: boolean;
21
+ needsTop: boolean;
22
+ needsUnit: boolean;
23
+ }
24
+ export declare const TEMPLATES: readonly TemplateInfo[];
25
+ export declare const DEFAULT_TOP = 10;
26
+ export declare const MAX_TOP = 1000;
27
+ export declare const DATE_FORMATS: Record<DateUnit, string>;
28
+ /** A field name that can be written as `$name` in a pipeline: not empty, no `$`, no NUL, no leading/trailing/double dot. */
29
+ export declare function isTemplateField(field: string): boolean;
30
+ export type TemplateProblem = 'field' | 'value-field' | 'top';
31
+ /** What is wrong with the input of a template, or `undefined`. */
32
+ export declare function validateTemplateInput(key: TemplateKey, input: TemplateInput): TemplateProblem | undefined;
33
+ /** The stages of a template. Throws for invalid input — check `validateTemplateInput` first. */
34
+ export declare function templateStages(key: TemplateKey, input: TemplateInput): TemplateStage[];
@@ -0,0 +1,47 @@
1
+ export const TEMPLATES = [
2
+ { key: "count-by-field", needsValueField: false, needsTop: false, needsUnit: false },
3
+ { key: "top-values", needsValueField: false, needsTop: true, needsUnit: false },
4
+ { key: "date-histogram", needsValueField: false, needsTop: false, needsUnit: true },
5
+ { key: "sum-avg-by-group", needsValueField: true, needsTop: false, needsUnit: false }
6
+ ];
7
+ export const DEFAULT_TOP = 10;
8
+ export const MAX_TOP = 1e3;
9
+ export const DATE_FORMATS = { year: "%Y", month: "%Y-%m", day: "%Y-%m-%d" };
10
+ export function isTemplateField(field) {
11
+ return field.trim() !== "" && !field.includes("$") && !field.includes("\0") && !/^\.|\.$|\.\./.test(field.trim());
12
+ }
13
+ export function validateTemplateInput(key, input) {
14
+ if (!isTemplateField(input.field)) return "field";
15
+ const info = TEMPLATES.find((t) => t.key === key);
16
+ if (info.needsValueField && !isTemplateField(input.valueField ?? "")) return "value-field";
17
+ if (info.needsTop && input.top !== void 0 && (!Number.isInteger(input.top) || input.top < 1 || input.top > MAX_TOP)) return "top";
18
+ return void 0;
19
+ }
20
+ export function templateStages(key, input) {
21
+ const problem = validateTemplateInput(key, input);
22
+ if (problem) throw new Error(`Invalid template input: ${problem}`);
23
+ const field = `$${input.field.trim()}`;
24
+ switch (key) {
25
+ case "count-by-field":
26
+ return [
27
+ { type: "$group", value: { _id: field, count: { $sum: 1 } } },
28
+ { type: "$sort", value: { count: -1 } }
29
+ ];
30
+ case "top-values":
31
+ return [
32
+ { type: "$group", value: { _id: field, count: { $sum: 1 } } },
33
+ { type: "$sort", value: { count: -1 } },
34
+ { type: "$limit", value: input.top ?? DEFAULT_TOP }
35
+ ];
36
+ case "date-histogram":
37
+ return [
38
+ { type: "$group", value: { _id: { $dateToString: { format: DATE_FORMATS[input.unit ?? "month"], date: field } }, count: { $sum: 1 } } },
39
+ { type: "$sort", value: { _id: 1 } }
40
+ ];
41
+ case "sum-avg-by-group":
42
+ return [
43
+ { type: "$group", value: { _id: field, total: { $sum: `$${input.valueField.trim()}` }, avg: { $avg: `$${input.valueField.trim()}` }, count: { $sum: 1 } } },
44
+ { type: "$sort", value: { _id: 1 } }
45
+ ];
46
+ }
47
+ }
@@ -24,4 +24,5 @@ export interface AnalyzeOptions {
24
24
  maxDistinctForTop?: number;
25
25
  }
26
26
  export declare function kindOf(value: unknown): ValueKind;
27
+ export declare function comparePaths(a: string, b: string): number;
27
28
  export declare function analyzeSamples(rows: unknown[], options?: AnalyzeOptions): SampleAnalysis;
@@ -15,7 +15,7 @@ export function kindOf(value) {
15
15
  function shorten(text) {
16
16
  return text.length > MAX_VALUE_LENGTH ? `${text.slice(0, MAX_VALUE_LENGTH - 1)}\u2026` : text;
17
17
  }
18
- function comparePaths(a, b) {
18
+ export function comparePaths(a, b) {
19
19
  if (a === "_id") return b === "_id" ? 0 : -1;
20
20
  if (b === "_id") return 1;
21
21
  const left = a.split(".");
@@ -0,0 +1,14 @@
1
+ /** A refresh interval below this is raised to it: a live view must not hammer the server. */
2
+ export declare const MIN_REFRESH_INTERVAL_MS = 1000;
3
+ export declare const DEFAULT_BACKOFF_FACTOR = 2;
4
+ /** Default ceiling of the delay after repeated failures. */
5
+ export declare const DEFAULT_BACKOFF_MAX_MS: number;
6
+ export interface BackoffOptions {
7
+ /** Delay multiplier per consecutive failure (default 2). */
8
+ factor?: number;
9
+ /** The delay never grows beyond this (default 5 minutes, never below the interval). */
10
+ maxMs?: number;
11
+ }
12
+ export declare function clampInterval(intervalMs: number): number;
13
+ /** The wait before the next load: the interval, multiplied per consecutive failure up to the ceiling. */
14
+ export declare function nextDelay(intervalMs: number, failures: number, backoff?: BackoffOptions | false): number;
@@ -0,0 +1,15 @@
1
+ export const MIN_REFRESH_INTERVAL_MS = 1e3;
2
+ export const DEFAULT_BACKOFF_FACTOR = 2;
3
+ export const DEFAULT_BACKOFF_MAX_MS = 5 * 60 * 1e3;
4
+ export function clampInterval(intervalMs) {
5
+ return Number.isFinite(intervalMs) ? Math.max(MIN_REFRESH_INTERVAL_MS, Math.floor(intervalMs)) : MIN_REFRESH_INTERVAL_MS;
6
+ }
7
+ export function nextDelay(intervalMs, failures, backoff = {}) {
8
+ const base = clampInterval(intervalMs);
9
+ if (backoff === false || failures <= 0) return base;
10
+ const factor = Number.isFinite(backoff.factor) && backoff.factor > 1 ? backoff.factor : DEFAULT_BACKOFF_FACTOR;
11
+ const max = Math.max(base, backoff.maxMs ?? DEFAULT_BACKOFF_MAX_MS);
12
+ let delay = base;
13
+ for (let i = 0; i < failures && delay < max; i++) delay = Math.min(max, delay * factor);
14
+ return delay;
15
+ }
@@ -4,9 +4,15 @@ export interface BatchInsertFailure {
4
4
  error: unknown;
5
5
  mayBePartial: boolean;
6
6
  }
7
+ export interface BatchInsertRowError {
8
+ index: number;
9
+ code?: number;
10
+ message: string;
11
+ }
7
12
  export interface BatchInsertResult {
8
13
  inserted: number;
9
14
  failedBatches: BatchInsertFailure[];
15
+ rowErrors: BatchInsertRowError[];
10
16
  skipped: number;
11
17
  aborted: boolean;
12
18
  }
@@ -1,8 +1,34 @@
1
1
  const DEFAULT_BATCH_SIZE = 1e3;
2
2
  const MAX_BATCH_SIZE = 1e4;
3
+ function rowErrorsAsFailures(rowErrors) {
4
+ const failures = [];
5
+ for (const e of [...rowErrors].sort((a, b) => a.index - b.index)) {
6
+ const last = failures.at(-1);
7
+ const lastMessage = last?.error?.message;
8
+ if (last && last.start + last.count === e.index && lastMessage === e.message) {
9
+ last.count++;
10
+ continue;
11
+ }
12
+ failures.push({ start: e.index, count: 1, error: Object.assign(new Error(e.message), { code: e.code }), mayBePartial: false });
13
+ }
14
+ return failures;
15
+ }
16
+ function readSummary(value) {
17
+ if (typeof value !== "object" || value === null) return void 0;
18
+ const { insertedCount, errors } = value;
19
+ if (typeof insertedCount !== "number") return void 0;
20
+ const list = Array.isArray(errors) ? errors : [];
21
+ return {
22
+ insertedCount,
23
+ errors: list.flatMap((e) => {
24
+ const { index, code, message } = e ?? {};
25
+ return typeof index === "number" ? [{ index, code: typeof code === "number" ? code : void 0, message: typeof message === "string" ? message : "" }] : [];
26
+ })
27
+ };
28
+ }
3
29
  export async function runBatchInsert(rows, insert, options = {}) {
4
30
  const batchSize = Math.min(Math.max(Math.floor(options.batchSize ?? DEFAULT_BATCH_SIZE) || DEFAULT_BATCH_SIZE, 1), MAX_BATCH_SIZE);
5
- const result = { inserted: 0, failedBatches: [], skipped: 0, aborted: false };
31
+ const result = { inserted: 0, failedBatches: [], rowErrors: [], skipped: 0, aborted: false };
6
32
  let done = 0;
7
33
  for (let start = 0; start < rows.length; start += batchSize) {
8
34
  if (options.signal?.aborted) {
@@ -12,13 +38,15 @@ export async function runBatchInsert(rows, insert, options = {}) {
12
38
  }
13
39
  const batch = rows.slice(start, start + batchSize);
14
40
  try {
15
- await insert(batch);
16
- result.inserted += batch.length;
41
+ const summary = readSummary(await insert(batch));
42
+ result.inserted += summary ? summary.insertedCount : batch.length;
43
+ for (const e of summary?.errors ?? []) result.rowErrors.push({ index: start + e.index, code: e.code, message: e.message });
17
44
  } catch (error) {
18
45
  result.failedBatches.push({ start, count: batch.length, error, mayBePartial: !(options.isAtomicFailure?.(error) ?? false) });
19
46
  }
20
47
  done += batch.length;
21
48
  options.onProgress?.({ done, total: rows.length });
22
49
  }
50
+ if (result.rowErrors.length > 0) result.failedBatches = [...result.failedBatches, ...rowErrorsAsFailures(result.rowErrors)].sort((a, b) => a.start - b.start);
23
51
  return result;
24
52
  }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `JSON.parse` that does not round integers a JS number cannot hold: every such integer literal outside a string
3
+ * becomes `{ "$numberLong": "<digits>" }`. Decimals, exponents, safe integers and everything inside strings are
4
+ * untouched. Throws like `JSON.parse` for invalid JSON.
5
+ */
6
+ export declare function parseJsonKeepingLongs(text: string): unknown;
7
+ /**
8
+ * The parsed body of an API response with large integers kept exact. Reads the text of a clone of the raw response, so
9
+ * the generated client's own `value()` still works; falls back to `value()` when there is no readable raw response
10
+ * (or the text is not JSON), which is also what a test double without a body gets.
11
+ */
12
+ export declare function readJsonKeepingLongs<T = unknown>(response: {
13
+ raw?: Response;
14
+ value: () => Promise<unknown>;
15
+ }): Promise<T>;
@@ -0,0 +1,55 @@
1
+ const MIN_UNSAFE_DIGITS = 16;
2
+ function isDigit(char) {
3
+ return char !== void 0 && char >= "0" && char <= "9";
4
+ }
5
+ export function parseJsonKeepingLongs(text) {
6
+ let result = "";
7
+ let copiedUpTo = 0;
8
+ let inString = false;
9
+ let i = 0;
10
+ while (i < text.length) {
11
+ const char = text[i];
12
+ if (inString) {
13
+ i += char === "\\" ? 2 : 1;
14
+ if (char === '"') inString = false;
15
+ continue;
16
+ }
17
+ if (char === '"') {
18
+ inString = true;
19
+ i++;
20
+ continue;
21
+ }
22
+ if (char !== "-" && !isDigit(char)) {
23
+ i++;
24
+ continue;
25
+ }
26
+ const start = i;
27
+ let end = char === "-" ? i + 1 : i;
28
+ const digitsStart = end;
29
+ while (isDigit(text[end])) end++;
30
+ const integerEnd = end;
31
+ if (text[end] === "." || text[end] === "e" || text[end] === "E") {
32
+ end++;
33
+ while (end < text.length && (isDigit(text[end]) || text[end] === "+" || text[end] === "-" || text[end] === "." || text[end] === "e" || text[end] === "E")) end++;
34
+ i = end;
35
+ continue;
36
+ }
37
+ const token = text.slice(start, integerEnd);
38
+ if (integerEnd - digitsStart >= MIN_UNSAFE_DIGITS && !Number.isSafeInteger(Number(token))) {
39
+ result += `${text.slice(copiedUpTo, start)}{"$numberLong":"${token}"}`;
40
+ copiedUpTo = integerEnd;
41
+ }
42
+ i = integerEnd;
43
+ }
44
+ return JSON.parse(result + text.slice(copiedUpTo));
45
+ }
46
+ export async function readJsonKeepingLongs(response) {
47
+ const raw = response.raw;
48
+ if (raw && typeof raw.clone === "function") {
49
+ try {
50
+ return parseJsonKeepingLongs(await raw.clone().text());
51
+ } catch {
52
+ }
53
+ }
54
+ return await response.value();
55
+ }
@@ -0,0 +1,10 @@
1
+ export type BsonType = 'string' | 'int' | 'long' | 'double' | 'decimal' | 'bool' | 'date' | 'objectId' | 'null';
2
+ /** Dotted path of a field → the type to write it as (array elements as `tags[]`). */
3
+ export type TypeHints = Record<string, BsonType>;
4
+ export declare const BSON_TYPES: readonly BsonType[];
5
+ /**
6
+ * `value` written as `type`. A value that does not fit the type (2.5 as an int, text that is no id as an objectId, a long
7
+ * beyond 2^53 given as a number) is returned **unchanged** — the server then picks the type, which is what a plain value
8
+ * would have got anyway. Never throws.
9
+ */
10
+ export declare function wireValue(type: BsonType, value: unknown): unknown;
@@ -0,0 +1,42 @@
1
+ export const BSON_TYPES = ["string", "int", "long", "double", "decimal", "bool", "date", "objectId", "null"];
2
+ const INT32_MIN = -(2 ** 31);
3
+ const INT32_MAX = 2 ** 31 - 1;
4
+ const INTEGER_TEXT = /^-?\d+$/;
5
+ const DECIMAL_TEXT = /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
6
+ const OBJECT_ID_TEXT = /^[0-9a-f]{24}$/i;
7
+ const FULL_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/;
8
+ const isFullTimestamp = (value) => FULL_TIMESTAMP.test(value) && !Number.isNaN(Date.parse(value));
9
+ function toNumber(value) {
10
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : Number.NaN;
11
+ return Number.isFinite(n) ? n : void 0;
12
+ }
13
+ export function wireValue(type, value) {
14
+ switch (type) {
15
+ case "int": {
16
+ const n = toNumber(value);
17
+ return n !== void 0 && Number.isInteger(n) && n >= INT32_MIN && n <= INT32_MAX ? { $numberInt: String(n) } : value;
18
+ }
19
+ case "long": {
20
+ if (typeof value === "string" && INTEGER_TEXT.test(value.trim())) return { $numberLong: value.trim() };
21
+ const n = toNumber(value);
22
+ return n !== void 0 && Number.isSafeInteger(n) ? { $numberLong: String(n) } : value;
23
+ }
24
+ case "double": {
25
+ const n = toNumber(value);
26
+ return n !== void 0 ? { $numberDouble: String(n) } : value;
27
+ }
28
+ case "decimal": {
29
+ if (typeof value === "string" && DECIMAL_TEXT.test(value.trim())) return { $numberDecimal: value.trim() };
30
+ const n = toNumber(value);
31
+ return n !== void 0 ? { $numberDecimal: String(n) } : value;
32
+ }
33
+ case "date":
34
+ return typeof value === "string" && isFullTimestamp(value) ? { $date: value } : value;
35
+ case "objectId":
36
+ return typeof value === "string" && OBJECT_ID_TEXT.test(value) ? { $oid: value } : value;
37
+ case "string":
38
+ return typeof value === "string" && isFullTimestamp(value) ? { $string: value } : value;
39
+ default:
40
+ return value;
41
+ }
42
+ }
@@ -4,10 +4,18 @@ export interface BulkDeleteResult<T> {
4
4
  item: T;
5
5
  error: unknown;
6
6
  }[];
7
+ /** Only present after an abort: items that were never tried, so they are known to be untouched. */
8
+ notAttempted?: T[];
9
+ }
10
+ export interface BulkRunOptions {
11
+ /** Aborting stops before the next request; what already ran stays done and is reported. */
12
+ signal?: AbortSignal;
13
+ /** Called after every chunk / item with how many items have been dealt with so far. */
14
+ onProgress?: (done: number, total: number) => void;
7
15
  }
8
16
  export interface BulkRemoveMany<T> {
9
17
  run: (items: T[]) => Promise<number | undefined>;
10
18
  canHandle?: (item: T) => boolean;
11
19
  chunkSize?: number;
12
20
  }
13
- export declare function runBulkDelete<T>(items: T[], remove: (item: T) => Promise<unknown>, concurrency?: number, removeMany?: BulkRemoveMany<T>): Promise<BulkDeleteResult<T>>;
21
+ export declare function runBulkDelete<T>(items: T[], remove: (item: T) => Promise<unknown>, concurrency?: number, removeMany?: BulkRemoveMany<T>, options?: BulkRunOptions): Promise<BulkDeleteResult<T>>;
@@ -1,6 +1,12 @@
1
1
  const DEFAULT_CHUNK_SIZE = 100;
2
- export async function runBulkDelete(items, remove, concurrency = 5, removeMany) {
2
+ export async function runBulkDelete(items, remove, concurrency = 5, removeMany, options = {}) {
3
3
  const outcomes = Array.from({ length: items.length });
4
+ const { signal, onProgress } = options;
5
+ let done = 0;
6
+ const advance = (count) => {
7
+ done += count;
8
+ onProgress?.(done, items.length);
9
+ };
4
10
  const individually = [];
5
11
  if (removeMany) {
6
12
  const chunkSize = Math.max(1, Math.floor(removeMany.chunkSize ?? DEFAULT_CHUNK_SIZE) || DEFAULT_CHUNK_SIZE);
@@ -10,11 +16,13 @@ export async function runBulkDelete(items, remove, concurrency = 5, removeMany)
10
16
  else individually.push(index);
11
17
  });
12
18
  for (let start = 0; start < batched.length; start += chunkSize) {
19
+ if (signal?.aborted) break;
13
20
  const indexes = batched.slice(start, start + chunkSize);
14
21
  try {
15
22
  const deletedCount = await removeMany.run(indexes.map((i) => items[i]));
16
23
  if (typeof deletedCount === "number" && deletedCount >= indexes.length) {
17
24
  for (const i of indexes) outcomes[i] = { ok: true };
25
+ advance(indexes.length);
18
26
  continue;
19
27
  }
20
28
  } catch {
@@ -26,7 +34,7 @@ export async function runBulkDelete(items, remove, concurrency = 5, removeMany)
26
34
  }
27
35
  let next = 0;
28
36
  async function worker() {
29
- while (next < individually.length) {
37
+ while (next < individually.length && !signal?.aborted) {
30
38
  const index = individually[next++];
31
39
  try {
32
40
  await remove(items[index]);
@@ -34,14 +42,18 @@ export async function runBulkDelete(items, remove, concurrency = 5, removeMany)
34
42
  } catch (error) {
35
43
  outcomes[index] = { ok: false, error };
36
44
  }
45
+ advance(1);
37
46
  }
38
47
  }
39
48
  await Promise.all(Array.from({ length: Math.min(concurrency, individually.length) }, worker));
40
49
  const result = { deleted: [], failed: [] };
50
+ const notAttempted = [];
41
51
  items.forEach((item, index) => {
42
52
  const outcome = outcomes[index];
43
- if (outcome.ok) result.deleted.push(item);
53
+ if (!outcome) notAttempted.push(item);
54
+ else if (outcome.ok) result.deleted.push(item);
44
55
  else result.failed.push({ item, error: outcome.error });
45
56
  });
57
+ if (notAttempted.length > 0) result.notAttempted = notAttempted;
46
58
  return result;
47
59
  }
@@ -14,9 +14,15 @@ export interface BulkUpdateFailure {
14
14
  export interface BulkUpdateResult {
15
15
  updated: string[];
16
16
  failed: BulkUpdateFailure[];
17
+ /** Only present after an abort: ids that were never tried, so they are known to be untouched. */
18
+ notAttempted?: string[];
17
19
  }
18
20
  export interface BulkUpdateOptions {
19
21
  chunkSize?: number;
22
+ /** Aborting stops before the next chunk; what already ran stays done and is reported. */
23
+ signal?: AbortSignal;
24
+ /** Called after every chunk with how many ids have been dealt with so far. */
25
+ onProgress?: (done: number, total: number) => void;
20
26
  }
21
27
  export declare function isEditableField(field: string): boolean;
22
28
  export declare function buildIdFilter(ids: string[]): {