@sfxcode/nuxt-ui-mongocamp 1.3.1 → 1.3.3

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 (94) hide show
  1. package/README.md +1 -1
  2. package/dist/module.d.mts +12 -0
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +18 -5
  5. package/dist/runtime/components/MongocampAggregationBuilder.d.vue.ts +6 -0
  6. package/dist/runtime/components/MongocampAggregationBuilder.vue +390 -0
  7. package/dist/runtime/components/MongocampAggregationBuilder.vue.d.ts +6 -0
  8. package/dist/runtime/components/MongocampBulkDelete.d.vue.ts +11 -1
  9. package/dist/runtime/components/MongocampBulkDelete.vue +1 -0
  10. package/dist/runtime/components/MongocampBulkDelete.vue.d.ts +11 -1
  11. package/dist/runtime/components/MongocampBulkEdit.d.vue.ts +29 -0
  12. package/dist/runtime/components/MongocampBulkEdit.vue +138 -0
  13. package/dist/runtime/components/MongocampBulkEdit.vue.d.ts +29 -0
  14. package/dist/runtime/components/MongocampCollectionData.d.vue.ts +4 -1
  15. package/dist/runtime/components/MongocampCollectionData.vue +167 -4
  16. package/dist/runtime/components/MongocampCollectionData.vue.d.ts +4 -1
  17. package/dist/runtime/components/MongocampCollectionInfos.vue +266 -8
  18. package/dist/runtime/components/MongocampCollections.d.vue.ts +8 -1
  19. package/dist/runtime/components/MongocampCollections.vue +84 -72
  20. package/dist/runtime/components/MongocampCollections.vue.d.ts +8 -1
  21. package/dist/runtime/components/MongocampConfirmByName.d.vue.ts +23 -0
  22. package/dist/runtime/components/MongocampConfirmByName.vue +92 -0
  23. package/dist/runtime/components/MongocampConfirmByName.vue.d.ts +23 -0
  24. package/dist/runtime/components/MongocampErrorAlert.vue +28 -5
  25. package/dist/runtime/components/MongocampFilterBuilder.d.vue.ts +1 -0
  26. package/dist/runtime/components/MongocampFilterBuilder.vue +33 -2
  27. package/dist/runtime/components/MongocampFilterBuilder.vue.d.ts +1 -0
  28. package/dist/runtime/components/MongocampGrantList.d.vue.ts +7 -0
  29. package/dist/runtime/components/MongocampGrantList.vue +38 -0
  30. package/dist/runtime/components/MongocampGrantList.vue.d.ts +7 -0
  31. package/dist/runtime/components/MongocampImport.d.vue.ts +10 -0
  32. package/dist/runtime/components/MongocampImport.vue +479 -0
  33. package/dist/runtime/components/MongocampImport.vue.d.ts +10 -0
  34. package/dist/runtime/components/MongocampRoles.vue +45 -0
  35. package/dist/runtime/components/MongocampSettings.d.vue.ts +3 -0
  36. package/dist/runtime/components/MongocampSettings.vue +179 -0
  37. package/dist/runtime/components/MongocampSettings.vue.d.ts +3 -0
  38. package/dist/runtime/components/MongocampUsers.vue +183 -3
  39. package/dist/runtime/composables/useMongocampAdmin.d.ts +7 -1
  40. package/dist/runtime/composables/useMongocampAdmin.js +24 -1
  41. package/dist/runtime/composables/useMongocampAggregation.d.ts +28 -0
  42. package/dist/runtime/composables/useMongocampAggregation.js +100 -0
  43. package/dist/runtime/composables/useMongocampBucket.js +1 -1
  44. package/dist/runtime/composables/useMongocampBulkDelete.d.ts +1 -1
  45. package/dist/runtime/composables/useMongocampImport.d.ts +14 -0
  46. package/dist/runtime/composables/useMongocampImport.js +25 -0
  47. package/dist/runtime/composables/useMongocampIndex.d.ts +1 -0
  48. package/dist/runtime/composables/useMongocampIndex.js +8 -1
  49. package/dist/runtime/composables/useMongocampRoles.d.ts +1 -0
  50. package/dist/runtime/composables/useMongocampRoles.js +3 -2
  51. package/dist/runtime/composables/useMongocampSession.d.ts +8 -0
  52. package/dist/runtime/composables/useMongocampSession.js +45 -0
  53. package/dist/runtime/composables/useMongocampSystem.d.ts +15 -3
  54. package/dist/runtime/composables/useMongocampSystem.js +19 -2
  55. package/dist/runtime/locales/de.json +200 -3
  56. package/dist/runtime/locales/en.json +200 -3
  57. package/dist/runtime/plugin.js +19 -0
  58. package/dist/runtime/utils/aggregationErrors.d.ts +10 -0
  59. package/dist/runtime/utils/aggregationErrors.js +17 -0
  60. package/dist/runtime/utils/aggregationPipeline.d.ts +42 -0
  61. package/dist/runtime/utils/aggregationPipeline.js +118 -0
  62. package/dist/runtime/utils/aggregationResult.d.ts +5 -0
  63. package/dist/runtime/utils/aggregationResult.js +17 -0
  64. package/dist/runtime/utils/analyzeSamples.d.ts +27 -0
  65. package/dist/runtime/utils/analyzeSamples.js +92 -0
  66. package/dist/runtime/utils/batchInsert.d.ts +22 -0
  67. package/dist/runtime/utils/batchInsert.js +24 -0
  68. package/dist/runtime/utils/bulkDelete.d.ts +6 -1
  69. package/dist/runtime/utils/bulkDelete.js +28 -4
  70. package/dist/runtime/utils/bulkEdit.d.ts +27 -0
  71. package/dist/runtime/utils/bulkEdit.js +45 -0
  72. package/dist/runtime/utils/collectionProtection.d.ts +3 -0
  73. package/dist/runtime/utils/collectionProtection.js +7 -0
  74. package/dist/runtime/utils/configRows.d.ts +11 -0
  75. package/dist/runtime/utils/configRows.js +53 -0
  76. package/dist/runtime/utils/failureKind.d.ts +3 -0
  77. package/dist/runtime/utils/failureKind.js +11 -0
  78. package/dist/runtime/utils/filterSuggestions.d.ts +8 -0
  79. package/dist/runtime/utils/filterSuggestions.js +15 -0
  80. package/dist/runtime/utils/importPipeline.d.ts +21 -0
  81. package/dist/runtime/utils/importPipeline.js +52 -0
  82. package/dist/runtime/utils/importRows.d.ts +36 -0
  83. package/dist/runtime/utils/importRows.js +228 -0
  84. package/dist/runtime/utils/jwtExpiry.d.ts +3 -0
  85. package/dist/runtime/utils/jwtExpiry.js +31 -0
  86. package/dist/runtime/utils/objectId.d.ts +1 -0
  87. package/dist/runtime/utils/objectId.js +4 -0
  88. package/dist/runtime/utils/serverProbe.d.ts +10 -0
  89. package/dist/runtime/utils/serverProbe.js +25 -0
  90. package/dist/runtime/utils/sessionGuard.d.ts +10 -0
  91. package/dist/runtime/utils/sessionGuard.js +10 -0
  92. package/dist/runtime/utils/throttled.d.ts +6 -0
  93. package/dist/runtime/utils/throttled.js +16 -0
  94. package/package.json +1 -1
@@ -1,5 +1,8 @@
1
1
  {
2
2
  "nuxtUiMongocamp": {
3
+ "confirmByName": {
4
+ "prompt": "Type \"{name}\" to confirm"
5
+ },
3
6
  "common": {
4
7
  "cancel": "Cancel",
5
8
  "delete": "Delete",
@@ -27,6 +30,15 @@
27
30
  "addUser": "Add User",
28
31
  "editUserTitle": "Edit User: {userId}",
29
32
  "deleteUserTitle": "Delete User",
33
+ "detailsTooltip": "Details",
34
+ "detailsTitle": "User: {userId}",
35
+ "detailsRoles": "Roles",
36
+ "detailsNoRoles": "No roles assigned",
37
+ "detailsGrants": "Effective grants",
38
+ "regenerateKeyTooltip": "Regenerate API key",
39
+ "regenerateKeyTitle": "Regenerate API Key: {userId}",
40
+ "confirmRegenerateKey": "Are you sure you want to regenerate the API key of {userId}? Their current key stops working immediately, and anything still using it will be rejected.",
41
+ "newApiKeyLabel": "New API key",
30
42
  "confirmDelete": "Are you sure you want to delete user {userId}? This action cannot be undone.",
31
43
  "email": "Email",
32
44
  "password": "Password",
@@ -52,6 +64,9 @@
52
64
  "addRole": "Add Role",
53
65
  "editRoleTitle": "Edit Role: {roleName}",
54
66
  "deleteRoleTitle": "Delete Role",
67
+ "detailsTooltip": "Details",
68
+ "detailsTitle": "Role: {roleName}",
69
+ "detailsGrants": "Grants",
55
70
  "confirmDelete": "Are you sure you want to delete role {roleName}? This action cannot be undone.",
56
71
  "roleName": "Role Name",
57
72
  "adminRole": "Admin Role",
@@ -105,7 +120,18 @@
105
120
  "clearBucketTitle": "Clear Bucket",
106
121
  "confirmClearBucket": "Are you sure you want to delete every file in the \"{bucketName}\" bucket? The bucket itself is kept, but all files in it are permanently removed. This action cannot be undone.",
107
122
  "deleteBucketTitle": "Delete Bucket",
108
- "confirmDeleteBucket": "Are you sure you want to delete the \"{bucketName}\" bucket? This permanently removes both the \"{bucketName}.files\" and \"{bucketName}.chunks\" collections. This action cannot be undone."
123
+ "confirmDeleteBucket": "Are you sure you want to delete the \"{bucketName}\" bucket? This permanently removes both the \"{bucketName}.files\" and \"{bucketName}.chunks\" collections. This action cannot be undone.",
124
+ "clearTooltip": "Clear collection",
125
+ "dropTooltip": "Drop collection",
126
+ "clearTitle": "Clear Collection",
127
+ "dropTitle": "Drop Collection",
128
+ "confirmClear": "This permanently deletes every document in \"{name}\". The collection itself is kept. This action cannot be undone.",
129
+ "confirmDrop": "This permanently deletes the collection \"{name}\" together with all its documents and indexes. This action cannot be undone.",
130
+ "clearedTitle": "Collection cleared",
131
+ "clearedDescription": "Every document in \"{name}\" was deleted.",
132
+ "droppedTitle": "Collection dropped",
133
+ "droppedDescription": "The collection \"{name}\" was deleted.",
134
+ "bucketActionFailed": "The action on the bucket \"{bucketName}\" failed."
109
135
  },
110
136
  "collectionInfos": {
111
137
  "documents": "Documents",
@@ -119,6 +145,11 @@
119
145
  "copyAsTs": "Copy as TS Interface",
120
146
  "copiedTitle": "Copied to clipboard",
121
147
  "copiedDescription": "TypeScript interface copied.",
148
+ "jsonSchema": "JSON schema",
149
+ "jsonSchemaTitle": "JSON schema of {name}",
150
+ "jsonSchemaFailedTitle": "The JSON schema could not be loaded",
151
+ "downloadSchema": "Download",
152
+ "schemaCopiedDescription": "JSON schema copied.",
122
153
  "fieldsCount": "{count} fields",
123
154
  "columnField": "Field",
124
155
  "columnType": "Type",
@@ -137,7 +168,19 @@
137
168
  "confirmDeleteIndex": "Are you sure you want to delete the index \"{indexName}\"? This action cannot be undone.",
138
169
  "errorCreateIndex": "Error creating index",
139
170
  "errorDeleteIndex": "Error deleting index",
140
- "typeStandard": "standard"
171
+ "typeStandard": "standard",
172
+ "statsTitle": "Field statistics",
173
+ "statsAnalyze": "Analyze fields",
174
+ "statsSampleSize": "Sample size",
175
+ "statsSampled": "{sampled} of {total} documents sampled",
176
+ "statsHint": "Counts how often each field occurs and which values it holds, from a random sample of documents.",
177
+ "statsNote": "Computed from a random sample, not from the whole collection.",
178
+ "statsTruncated": "Only the first {count} fields are shown.",
179
+ "statsColumnPresent": "Present",
180
+ "statsPresentTitle": "In {present} of {sampled} sampled documents",
181
+ "statsColumnValues": "Common values",
182
+ "statsEmpty": "No documents to analyze",
183
+ "statsFailed": "The field statistics could not be loaded"
141
184
  },
142
185
  "collectionData": {
143
186
  "filterPlaceholder": "Filter rows...",
@@ -145,6 +188,13 @@
145
188
  "uploadFileTooltip": "Upload file",
146
189
  "insertDocumentTooltip": "Insert document",
147
190
  "reloadTooltip": "Reload",
191
+ "indexFieldTooltip": "Index {field}",
192
+ "indexAscending": "Create ascending index",
193
+ "indexDescending": "Create descending index",
194
+ "indexCreatedTitle": "Index created",
195
+ "indexCreatedDescription": "Index {name} on {collection} was created.",
196
+ "viewIndexes": "View indexes",
197
+ "indexFailedTitle": "Could not index {field}",
148
198
  "detailsTitle": "Details",
149
199
  "insertDocumentTitle": "Insert Document",
150
200
  "editDocumentTitle": "Edit Document",
@@ -244,6 +294,25 @@
244
294
  "changeFailedTitle": "Change failed",
245
295
  "changeFailedFallback": "Could not change your password."
246
296
  },
297
+ "settings": {
298
+ "heading": "Server settings",
299
+ "loadFailedTitle": "Failed to load the server settings",
300
+ "adminOnly": "Only administrators can view the server settings.",
301
+ "pluginsHeading": "Plugins",
302
+ "routesPlugins": "Route plugins",
303
+ "filePlugins": "File plugins",
304
+ "ignoredPlugins": "Ignored plugins",
305
+ "noPlugins": "None",
306
+ "searchPlaceholder": "Search settings...",
307
+ "maskedNote": "Secret values (passwords, keys, credentials, hosts) are never shown.",
308
+ "maskedHint": "Hidden: this value is a secret",
309
+ "columnKey": "Setting",
310
+ "columnValue": "Value",
311
+ "columnType": "Type",
312
+ "columnRestart": "Restart",
313
+ "restartNeeded": "needs restart",
314
+ "empty": "No settings found"
315
+ },
247
316
  "databases": {
248
317
  "heading": "Databases",
249
318
  "columnDatabase": "Database",
@@ -286,6 +355,7 @@
286
355
  "forbidden": "You do not have permission to do this.",
287
356
  "generic": "Something went wrong.",
288
357
  "loginAgain": "Log in again",
358
+ "requestRefused": "The server is reachable and your session is valid, but it refused this request. Try again, or change what you asked for.",
289
359
  "filterRejectedTitle": "The filter could not be applied",
290
360
  "filterRejected": "The server rejected the current search or filters, although the collection itself loads. Clear them, or remove the last condition, and try again.",
291
361
  "clearFilters": "Clear filters"
@@ -319,7 +389,21 @@
319
389
  "selectAll": "Select all rows on this page",
320
390
  "selectRow": "Select row",
321
391
  "partialFailure": "{failed} of {total} could not be deleted: {reason}",
322
- "cannotSelectSelf": "You cannot delete your own account"
392
+ "cannotSelectSelf": "You cannot delete your own account",
393
+ "editSelected": "Edit selected",
394
+ "editTitle": "Edit {count} selected document | Edit {count} selected documents",
395
+ "editDescription": "Set one field to the same value on every selected document.",
396
+ "editField": "Field",
397
+ "editType": "Value type",
398
+ "editValue": "Value",
399
+ "editTrue": "true",
400
+ "editFalse": "false",
401
+ "editValueRequired": "Enter a value",
402
+ "editSummary": "Sets \"{field}\" on {count} document. | Sets \"{field}\" on {count} documents.",
403
+ "confirmEdit": "Update {count}",
404
+ "editPartialFailure": "{failed} of {total} could not be updated: {reason}",
405
+ "editShortfall": "only {matched} of {expected} selected documents were found",
406
+ "editUnaddressable": "this document id cannot be updated in bulk"
323
407
  },
324
408
  "filterBuilder": {
325
409
  "matchLabel": "Match",
@@ -357,6 +441,119 @@
357
441
  "isEmpty": "does not exist",
358
442
  "isNotEmpty": "exists"
359
443
  }
444
+ },
445
+ "import": {
446
+ "trigger": "Import documents",
447
+ "title": "Import documents",
448
+ "chooseFile": "Choose a JSON or CSV file",
449
+ "hint": "A JSON array of objects, or a CSV file with a header row. Up to {maxRows} rows and {maxMb} MB.",
450
+ "chooseButton": "Choose file",
451
+ "readError": "The file could not be read",
452
+ "format": "Format",
453
+ "formatJson": "JSON",
454
+ "formatCsv": "CSV",
455
+ "delimiter": "Delimiter",
456
+ "delimiterComma": "Comma (,)",
457
+ "delimiterSemicolon": "Semicolon (;)",
458
+ "delimiterTab": "Tab",
459
+ "columnTypes": "Column types",
460
+ "typeString": "Text",
461
+ "typeNumber": "Number",
462
+ "typeBoolean": "Boolean",
463
+ "typeDate": "Date",
464
+ "typeJson": "JSON",
465
+ "emptyAsText": "Keep empty text cells as empty strings",
466
+ "stampMetadata": "Add created/updated information",
467
+ "summary": "{ready} of {total} rows ready to import",
468
+ "problems": "1 row has a problem and will be skipped | {count} rows have problems and will be skipped",
469
+ "truncated": "Only the first {maxRows} rows are imported.",
470
+ "previewTitle": "Preview (first {count} rows)",
471
+ "moreErrors": "…and {count} more",
472
+ "errorRow": "Row {row}",
473
+ "errorRowColumn": "Row {row}, column {column}",
474
+ "back": "Choose another file",
475
+ "close": "Close",
476
+ "importButton": "Import {count} row | Import {count} rows",
477
+ "importing": "Importing… {done} of {total}",
478
+ "stop": "Stop",
479
+ "result": "{count} row imported | {count} rows imported",
480
+ "failedBatch": "Rows {from}–{to} could not be imported: {reason}",
481
+ "maybePartial": "Part of these rows may already have been added — retrying could create duplicates.",
482
+ "retryFailed": "Retry failed rows",
483
+ "aborted": "Import stopped. {count} rows were not sent.",
484
+ "error": {
485
+ "file-too-large": "The file is too large",
486
+ "invalid-json": "The file is not valid JSON",
487
+ "not-array": "Expected a JSON array of objects",
488
+ "not-object": "This entry is not an object",
489
+ "invalid-delimiter": "Invalid delimiter",
490
+ "invalid-csv": "The CSV file could not be read (unclosed quote or empty file)",
491
+ "invalid-header": "The header row has an empty or duplicate column name",
492
+ "field-count": "This row has more fields than the header",
493
+ "too-many-rows": "Too many rows — the extra rows are ignored",
494
+ "empty-row": "This row has no fields",
495
+ "forbidden-key": "Field names must not start with $ or be __proto__",
496
+ "too-deep": "This row is nested too deeply",
497
+ "invalid-number": "Not a valid number",
498
+ "unsafe-integer": "Integer too large to store exactly — import it as text",
499
+ "invalid-id": "_id must be a 24-character hex string",
500
+ "invalid-boolean": "Expected true/false, yes/no or 1/0",
501
+ "invalid-date": "Not a valid ISO date",
502
+ "invalid-json-value": "Not valid JSON"
503
+ }
504
+ },
505
+ "aggregation": {
506
+ "errors": {
507
+ "forbidden": "This pipeline uses {operator}, which is not allowed here.",
508
+ "retryable": "The request was blocked on its way to the server. Try again.",
509
+ "unavailable": "The server did not answer this request. The pipeline may simply have no results; try again or loosen the filter."
510
+ },
511
+ "modeVisual": "Stages",
512
+ "modeJson": "JSON",
513
+ "addStage": "Add stage",
514
+ "newStageType": "Stage type",
515
+ "stageTitle": "Stage {n}",
516
+ "stageValue": "JSON of the {type} stage",
517
+ "moveUp": "Move stage up",
518
+ "moveDown": "Move stage down",
519
+ "removeStage": "Remove stage",
520
+ "jsonLabel": "Pipeline (JSON array)",
521
+ "run": "Run",
522
+ "resultsCount": "{count} result | {count} results",
523
+ "pageSize": "Rows per page",
524
+ "exportTooltip": "Export this page",
525
+ "exportJson": "Export page as JSON",
526
+ "exportCsv": "Export page as CSV",
527
+ "noResults": "The pipeline returned no results",
528
+ "precisionNote": "Results are plain JSON: dates appear as ISO text and whole numbers beyond 2^53 may be rounded.",
529
+ "runFailedTitle": "The pipeline could not be run",
530
+ "fixStages": "Fix the stages marked below first.",
531
+ "fixStagesFirst": "Fix the stages with errors before switching to JSON.",
532
+ "cannotShowVisually": "This pipeline uses stages the stage editor has no form for. Stay in the JSON view.",
533
+ "stageTypes": {
534
+ "$match": "$match — filter documents",
535
+ "$group": "$group — group and aggregate",
536
+ "$sort": "$sort — order",
537
+ "$project": "$project — choose or compute fields",
538
+ "$limit": "$limit — keep the first N"
539
+ },
540
+ "stageErrors": {
541
+ "invalid-json": "Not valid JSON",
542
+ "not-object": "This stage needs a JSON object",
543
+ "invalid-limit": "The limit must be a whole number of 1 or more",
544
+ "invalid-sort": "Sort directions must be 1 or -1",
545
+ "group-needs-id": "$group needs an _id (use null to group everything)",
546
+ "forbidden": "{operator} is not allowed"
547
+ },
548
+ "pipelineErrors": {
549
+ "too-large": "The pipeline is too large",
550
+ "invalid-json": "The pipeline is not valid JSON",
551
+ "not-array": "The pipeline must be a JSON array of stages",
552
+ "too-many-stages": "A pipeline can have at most 50 stages",
553
+ "stage-shape": "Stage {n} must be an object with exactly one key that starts with $, for example \"$match\"",
554
+ "forbidden-operator": "{operator} is not allowed (stage {n})",
555
+ "too-deep": "Stage {n} is nested too deeply"
556
+ }
360
557
  }
361
558
  }
362
559
  }
@@ -1,11 +1,30 @@
1
1
  import { defineNuxtPlugin, addRouteMiddleware, navigateTo, useAsyncData, useRuntimeConfig } from "#app";
2
2
  import { useMongocampAuth, useMongocampClientApi } from "#imports";
3
3
  import { useMongocampRoles } from "./composables/useMongocampRoles.js";
4
+ import { useMongocampSession } from "./composables/useMongocampSession.js";
5
+ import { runSessionGuard } from "./utils/sessionGuard.js";
4
6
  export default defineNuxtPlugin(async (_nuxtApp) => {
5
7
  const { informationApi } = useMongocampClientApi();
6
8
  const config = useRuntimeConfig();
7
9
  const useGlobalAuthMiddleware = config.public.nuxtUiMongocampOptions.useGlobalAuthMiddleware ?? false;
10
+ const useServerProxy = config.public.nuxtUiMongocampOptions.useServerProxy ?? false;
11
+ const sessionGuard = config.public.nuxtUiMongocampOptions.sessionGuard ?? false;
8
12
  const { data: version } = await useAsyncData("version", () => informationApi.version());
13
+ if (sessionGuard && !useServerProxy) {
14
+ addRouteMiddleware("session-guard", async (to) => {
15
+ const { checkExpiry, invalidateSession } = useMongocampSession();
16
+ const { loginPath } = useMongocampRoles();
17
+ const outcome = await runSessionGuard({
18
+ path: to.path,
19
+ loginPath,
20
+ checkExpiry,
21
+ invalidate: invalidateSession,
22
+ // a fresh call: it must read the session as it is after the invalidation
23
+ isAllowed: (path) => useMongocampRoles().isAllowedPathForRoute(path)
24
+ });
25
+ if (outcome === "redirect") return navigateTo(loginPath);
26
+ }, { global: true });
27
+ }
9
28
  if (useGlobalAuthMiddleware) {
10
29
  addRouteMiddleware("global-auth", async (to) => {
11
30
  const { logout } = useMongocampAuth();
@@ -0,0 +1,10 @@
1
+ import type { ForbiddenUse } from './aggregationPipeline.js';
2
+ export declare class ForbiddenPipelineError extends Error {
3
+ findings: ForbiddenUse[];
4
+ constructor(findings: ForbiddenUse[]);
5
+ }
6
+ export interface ServerErrorInfo {
7
+ kind: 'mongo' | 'empty-result' | 'other';
8
+ message: string;
9
+ }
10
+ export declare function parseServerError(msg: string): ServerErrorInfo;
@@ -0,0 +1,17 @@
1
+ export class ForbiddenPipelineError extends Error {
2
+ constructor(findings) {
3
+ super(`The pipeline uses ${findings[0]?.operator ?? "a forbidden operator"}`);
4
+ this.findings = findings;
5
+ this.name = "ForbiddenPipelineError";
6
+ }
7
+ }
8
+ const MONGO_COMMAND_FAILED = /^Command failed with error \d+ \([^)]*\): '([\s\S]*?)' on server \S+?\.\s+The full response is[\s\S]*$/;
9
+ const SERVER_ADDRESS = / on server \S+?(?=\.(?:\s|$)|\s|$)/g;
10
+ 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;
11
+ export function parseServerError(msg) {
12
+ const text = msg.trim();
13
+ const command = MONGO_COMMAND_FAILED.exec(text);
14
+ if (command) return { kind: "mongo", message: command[1].trim() };
15
+ if (/^Index 0 out of bounds for length 0$/.test(text)) return { kind: "empty-result", message: text };
16
+ return { kind: "other", message: text.replace(SERVER_ADDRESS, "").replace(BARE_ADDRESS, "").replace(/\s{2,}/g, " ").trim() };
17
+ }
@@ -0,0 +1,42 @@
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"];
3
+ export type AggregationStageType = typeof VISUAL_STAGE_TYPES[number];
4
+ export interface AggregationStage {
5
+ id: string;
6
+ type: AggregationStageType;
7
+ value: unknown;
8
+ }
9
+ export interface RequestStage {
10
+ stage: string;
11
+ value: unknown;
12
+ }
13
+ export interface ForbiddenUse {
14
+ stageIndex: number;
15
+ operator: string;
16
+ path: string;
17
+ }
18
+ export type PipelineErrorCode = 'too-large' | 'invalid-json' | 'not-array' | 'too-many-stages' | 'stage-shape' | 'forbidden-operator' | 'too-deep';
19
+ export interface PipelineError {
20
+ code: PipelineErrorCode;
21
+ stageIndex?: number;
22
+ operator?: string;
23
+ path?: string;
24
+ }
25
+ export type ParsedPipeline = {
26
+ ok: true;
27
+ pipeline: RequestStage[];
28
+ } | {
29
+ ok: false;
30
+ error: PipelineError;
31
+ };
32
+ export type StageIssueCode = 'not-object' | 'invalid-limit' | 'invalid-sort' | 'group-needs-id';
33
+ export interface StageIssue {
34
+ stageIndex: number;
35
+ code: StageIssueCode;
36
+ }
37
+ export declare function findForbidden(pipeline: RequestStage[]): ForbiddenUse[];
38
+ export declare function buildPipeline(stages: AggregationStage[]): RequestStage[];
39
+ export declare function validateStages(stages: AggregationStage[]): StageIssue[];
40
+ export declare function parsePipeline(text: string): ParsedPipeline;
41
+ export declare function pipelineToText(pipeline: RequestStage[]): string;
42
+ export declare function toVisualStages(pipeline: RequestStage[], makeId?: (index: number) => string): AggregationStage[] | null;
@@ -0,0 +1,118 @@
1
+ export const FORBIDDEN_OPERATORS = [
2
+ "$out",
3
+ "$merge",
4
+ "$function",
5
+ "$accumulator",
6
+ "$where",
7
+ "$lookup",
8
+ "$unionWith",
9
+ "$graphLookup"
10
+ ];
11
+ export const VISUAL_STAGE_TYPES = ["$match", "$group", "$sort", "$project", "$limit"];
12
+ const MAX_TEXT_LENGTH = 2e5;
13
+ const MAX_STAGES = 50;
14
+ const MAX_DEPTH = 64;
15
+ const MAX_FINDINGS = 20;
16
+ const FORBIDDEN = new Set(FORBIDDEN_OPERATORS);
17
+ function isPlainObject(value) {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+ function scan(value, path, depth, stageIndex, found) {
21
+ if (found.length >= MAX_FINDINGS) return;
22
+ if (depth > MAX_DEPTH) {
23
+ found.push({ stageIndex, operator: "too-deep", path });
24
+ return;
25
+ }
26
+ if (Array.isArray(value)) {
27
+ value.forEach((item, i) => scan(item, `${path}[${i}]`, depth + 1, stageIndex, found));
28
+ return;
29
+ }
30
+ if (!isPlainObject(value)) return;
31
+ for (const [key, inner] of Object.entries(value)) {
32
+ const keyPath = `${path}.${key}`;
33
+ if (FORBIDDEN.has(key)) found.push({ stageIndex, operator: key, path: keyPath });
34
+ scan(inner, keyPath, depth + 1, stageIndex, found);
35
+ }
36
+ }
37
+ export function findForbidden(pipeline) {
38
+ const found = [];
39
+ 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);
42
+ });
43
+ return found;
44
+ }
45
+ function isEmptyValue(value) {
46
+ return value === void 0 || value === null || value === "" || isPlainObject(value) && Object.keys(value).length === 0;
47
+ }
48
+ function normaliseValue(type, value) {
49
+ if (type === "$limit" && typeof value === "string" && /^\d+$/.test(value.trim())) return Number(value.trim());
50
+ return value;
51
+ }
52
+ export function buildPipeline(stages) {
53
+ const pipeline = [];
54
+ for (const { type, value } of stages) {
55
+ const normalised = normaliseValue(type, value);
56
+ if (!isEmptyValue(normalised)) pipeline.push({ stage: type, value: normalised });
57
+ }
58
+ return pipeline;
59
+ }
60
+ export function validateStages(stages) {
61
+ const issues = [];
62
+ stages.forEach(({ type, value: raw }, stageIndex) => {
63
+ const value = normaliseValue(type, raw);
64
+ if (isEmptyValue(value)) return;
65
+ if (type === "$limit") {
66
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) issues.push({ stageIndex, code: "invalid-limit" });
67
+ return;
68
+ }
69
+ if (!isPlainObject(value)) {
70
+ issues.push({ stageIndex, code: "not-object" });
71
+ return;
72
+ }
73
+ if (type === "$group" && !("_id" in value)) issues.push({ stageIndex, code: "group-needs-id" });
74
+ if (type === "$sort" && !Object.values(value).every((direction) => direction === 1 || direction === -1)) issues.push({ stageIndex, code: "invalid-sort" });
75
+ });
76
+ return issues;
77
+ }
78
+ export function parsePipeline(text) {
79
+ if (text.length > MAX_TEXT_LENGTH) return { ok: false, error: { code: "too-large" } };
80
+ let data;
81
+ try {
82
+ data = JSON.parse(text);
83
+ } catch {
84
+ return { ok: false, error: { code: "invalid-json" } };
85
+ }
86
+ if (!Array.isArray(data)) return { ok: false, error: { code: "not-array" } };
87
+ if (data.length > MAX_STAGES) return { ok: false, error: { code: "too-many-stages" } };
88
+ const pipeline = [];
89
+ for (const [stageIndex, item] of data.entries()) {
90
+ const keys = isPlainObject(item) ? Object.keys(item) : [];
91
+ if (isPlainObject(item) && keys.length === 1 && keys[0].startsWith("$")) {
92
+ pipeline.push({ stage: keys[0], value: item[keys[0]] });
93
+ } else if (isPlainObject(item) && keys.length === 2 && keys.includes("stage") && keys.includes("value") && typeof item.stage === "string" && item.stage.startsWith("$")) {
94
+ pipeline.push({ stage: item.stage, value: item.value });
95
+ } else {
96
+ return { ok: false, error: { code: "stage-shape", stageIndex } };
97
+ }
98
+ }
99
+ const forbidden = findForbidden(pipeline)[0];
100
+ if (forbidden) {
101
+ return {
102
+ ok: false,
103
+ error: { code: forbidden.operator === "too-deep" ? "too-deep" : "forbidden-operator", stageIndex: forbidden.stageIndex, operator: forbidden.operator, path: forbidden.path }
104
+ };
105
+ }
106
+ return { ok: true, pipeline };
107
+ }
108
+ export function pipelineToText(pipeline) {
109
+ return JSON.stringify(pipeline.map((stage) => ({ [stage.stage]: stage.value })), null, 2);
110
+ }
111
+ export function toVisualStages(pipeline, makeId = (index) => `stage-${index}`) {
112
+ const stages = [];
113
+ for (const [index, { stage, value }] of pipeline.entries()) {
114
+ if (!VISUAL_STAGE_TYPES.includes(stage)) return null;
115
+ stages.push({ id: makeId(index), type: stage, value });
116
+ }
117
+ return stages;
118
+ }
@@ -0,0 +1,5 @@
1
+ export declare function resultColumns(rows: Record<string, unknown>[]): string[];
2
+ export declare function formatCell(value: unknown): {
3
+ text: string;
4
+ full: string;
5
+ };
@@ -0,0 +1,17 @@
1
+ const MAX_COLUMNS = 100;
2
+ const MAX_ROWS_FOR_COLUMNS = 200;
3
+ const MAX_CELL_LENGTH = 80;
4
+ export function resultColumns(rows) {
5
+ const keys = /* @__PURE__ */ new Set();
6
+ for (const row of rows.slice(0, MAX_ROWS_FOR_COLUMNS)) {
7
+ for (const key of Object.keys(row)) {
8
+ keys.add(key);
9
+ if (keys.size >= MAX_COLUMNS) break;
10
+ }
11
+ }
12
+ return keys.has("_id") ? ["_id", ...[...keys].filter((key) => key !== "_id")] : [...keys];
13
+ }
14
+ export function formatCell(value) {
15
+ const full = value === void 0 ? "" : typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
16
+ return { text: full.length > MAX_CELL_LENGTH ? `${full.slice(0, MAX_CELL_LENGTH - 1)}\u2026` : full, full };
17
+ }
@@ -0,0 +1,27 @@
1
+ export type ValueKind = 'string' | 'number' | 'boolean' | 'date' | 'object' | 'array' | 'null';
2
+ export interface FieldStatistic {
3
+ path: string;
4
+ present: number;
5
+ share: number;
6
+ types: {
7
+ type: ValueKind;
8
+ count: number;
9
+ }[];
10
+ topValues?: {
11
+ value: string;
12
+ count: number;
13
+ }[];
14
+ }
15
+ export interface SampleAnalysis {
16
+ sampled: number;
17
+ fields: FieldStatistic[];
18
+ truncated: boolean;
19
+ }
20
+ export interface AnalyzeOptions {
21
+ maxDepth?: number;
22
+ maxFields?: number;
23
+ topValues?: number;
24
+ maxDistinctForTop?: number;
25
+ }
26
+ export declare function kindOf(value: unknown): ValueKind;
27
+ export declare function analyzeSamples(rows: unknown[], options?: AnalyzeOptions): SampleAnalysis;
@@ -0,0 +1,92 @@
1
+ import { isIsoDateTimeString } from "./isoDate.js";
2
+ const DEFAULTS = { maxDepth: 3, maxFields: 200, topValues: 5, maxDistinctForTop: 20 };
3
+ const MAX_VALUE_LENGTH = 40;
4
+ function isPlainObject(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ export function kindOf(value) {
8
+ if (value === null || value === void 0) return "null";
9
+ if (Array.isArray(value)) return "array";
10
+ if (typeof value === "string") return isIsoDateTimeString(value) ? "date" : "string";
11
+ if (typeof value === "number" || typeof value === "bigint") return "number";
12
+ if (typeof value === "boolean") return "boolean";
13
+ return "object";
14
+ }
15
+ function shorten(text) {
16
+ return text.length > MAX_VALUE_LENGTH ? `${text.slice(0, MAX_VALUE_LENGTH - 1)}\u2026` : text;
17
+ }
18
+ function comparePaths(a, b) {
19
+ if (a === "_id") return b === "_id" ? 0 : -1;
20
+ if (b === "_id") return 1;
21
+ const left = a.split(".");
22
+ const right = b.split(".");
23
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
24
+ const order = left[i].localeCompare(right[i]);
25
+ if (order !== 0) return order;
26
+ }
27
+ return left.length - right.length;
28
+ }
29
+ export function analyzeSamples(rows, options = {}) {
30
+ const { maxDepth, maxFields, topValues, maxDistinctForTop } = { ...DEFAULTS, ...options };
31
+ const stats = /* @__PURE__ */ new Map();
32
+ let sampled = 0;
33
+ function visit(value, path, depth, seen) {
34
+ const kind = kindOf(value);
35
+ let entry = seen.get(path);
36
+ if (!entry) {
37
+ entry = /* @__PURE__ */ new Map();
38
+ seen.set(path, entry);
39
+ }
40
+ const values = entry.get(kind) ?? /* @__PURE__ */ new Set();
41
+ entry.set(kind, values);
42
+ if (kind === "string" || kind === "number" || kind === "boolean" || kind === "date") values.add(String(value));
43
+ if (depth >= maxDepth) return;
44
+ if (isPlainObject(value)) {
45
+ for (const [key, inner] of Object.entries(value)) visit(inner, `${path}.${key}`, depth + 1, seen);
46
+ } else if (Array.isArray(value)) {
47
+ for (const item of value) if (isPlainObject(item)) {
48
+ for (const [key, inner] of Object.entries(item)) visit(inner, `${path}[].${key}`, depth + 1, seen);
49
+ }
50
+ }
51
+ }
52
+ for (const row of rows) {
53
+ if (!isPlainObject(row)) continue;
54
+ sampled++;
55
+ const seen = /* @__PURE__ */ new Map();
56
+ for (const [key, value] of Object.entries(row)) visit(value, key, 1, seen);
57
+ for (const [path, kinds] of seen) {
58
+ let acc = stats.get(path);
59
+ if (!acc) {
60
+ acc = { present: 0, types: /* @__PURE__ */ new Map(), values: /* @__PURE__ */ new Map(), highCardinality: false };
61
+ stats.set(path, acc);
62
+ }
63
+ acc.present++;
64
+ for (const [kind, values] of kinds) {
65
+ acc.types.set(kind, (acc.types.get(kind) ?? 0) + 1);
66
+ for (const text of values) {
67
+ if (acc.highCardinality) break;
68
+ acc.values.set(text, (acc.values.get(text) ?? 0) + 1);
69
+ if (acc.values.size > maxDistinctForTop) {
70
+ acc.highCardinality = true;
71
+ acc.values.clear();
72
+ }
73
+ }
74
+ }
75
+ }
76
+ }
77
+ const paths = [...stats.keys()].sort(comparePaths);
78
+ const fields = paths.slice(0, maxFields).map((path) => {
79
+ const acc = stats.get(path);
80
+ const field = {
81
+ path,
82
+ present: acc.present,
83
+ share: sampled === 0 ? 0 : acc.present / sampled,
84
+ types: [...acc.types].map(([type, count]) => ({ type, count })).sort((a, b) => b.count - a.count || a.type.localeCompare(b.type))
85
+ };
86
+ if (!acc.highCardinality && acc.values.size > 0) {
87
+ field.topValues = [...acc.values].map(([value, count]) => ({ value: shorten(value), count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value)).slice(0, topValues);
88
+ }
89
+ return field;
90
+ });
91
+ return { sampled, fields, truncated: paths.length > maxFields };
92
+ }