@sfxcode/nuxt-ui-mongocamp 1.3.1 → 1.3.2

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 (49) hide show
  1. package/README.md +1 -1
  2. package/dist/module.json +1 -1
  3. package/dist/runtime/components/MongocampAggregationBuilder.d.vue.ts +6 -0
  4. package/dist/runtime/components/MongocampAggregationBuilder.vue +390 -0
  5. package/dist/runtime/components/MongocampAggregationBuilder.vue.d.ts +6 -0
  6. package/dist/runtime/components/MongocampBulkDelete.d.vue.ts +11 -1
  7. package/dist/runtime/components/MongocampBulkDelete.vue +1 -0
  8. package/dist/runtime/components/MongocampBulkDelete.vue.d.ts +11 -1
  9. package/dist/runtime/components/MongocampBulkEdit.d.vue.ts +29 -0
  10. package/dist/runtime/components/MongocampBulkEdit.vue +138 -0
  11. package/dist/runtime/components/MongocampBulkEdit.vue.d.ts +29 -0
  12. package/dist/runtime/components/MongocampCollectionData.vue +100 -1
  13. package/dist/runtime/components/MongocampCollectionInfos.vue +162 -0
  14. package/dist/runtime/components/MongocampFilterBuilder.d.vue.ts +1 -0
  15. package/dist/runtime/components/MongocampFilterBuilder.vue +33 -2
  16. package/dist/runtime/components/MongocampFilterBuilder.vue.d.ts +1 -0
  17. package/dist/runtime/components/MongocampImport.d.vue.ts +10 -0
  18. package/dist/runtime/components/MongocampImport.vue +479 -0
  19. package/dist/runtime/components/MongocampImport.vue.d.ts +10 -0
  20. package/dist/runtime/composables/useMongocampAggregation.d.ts +28 -0
  21. package/dist/runtime/composables/useMongocampAggregation.js +99 -0
  22. package/dist/runtime/composables/useMongocampBulkDelete.d.ts +1 -1
  23. package/dist/runtime/composables/useMongocampImport.d.ts +14 -0
  24. package/dist/runtime/composables/useMongocampImport.js +25 -0
  25. package/dist/runtime/locales/de.json +140 -2
  26. package/dist/runtime/locales/en.json +140 -2
  27. package/dist/runtime/utils/aggregationErrors.d.ts +10 -0
  28. package/dist/runtime/utils/aggregationErrors.js +17 -0
  29. package/dist/runtime/utils/aggregationPipeline.d.ts +42 -0
  30. package/dist/runtime/utils/aggregationPipeline.js +118 -0
  31. package/dist/runtime/utils/aggregationResult.d.ts +5 -0
  32. package/dist/runtime/utils/aggregationResult.js +17 -0
  33. package/dist/runtime/utils/analyzeSamples.d.ts +27 -0
  34. package/dist/runtime/utils/analyzeSamples.js +92 -0
  35. package/dist/runtime/utils/batchInsert.d.ts +22 -0
  36. package/dist/runtime/utils/batchInsert.js +24 -0
  37. package/dist/runtime/utils/bulkDelete.d.ts +6 -1
  38. package/dist/runtime/utils/bulkDelete.js +28 -4
  39. package/dist/runtime/utils/bulkEdit.d.ts +27 -0
  40. package/dist/runtime/utils/bulkEdit.js +45 -0
  41. package/dist/runtime/utils/filterSuggestions.d.ts +8 -0
  42. package/dist/runtime/utils/filterSuggestions.js +15 -0
  43. package/dist/runtime/utils/importPipeline.d.ts +21 -0
  44. package/dist/runtime/utils/importPipeline.js +52 -0
  45. package/dist/runtime/utils/importRows.d.ts +36 -0
  46. package/dist/runtime/utils/importRows.js +228 -0
  47. package/dist/runtime/utils/objectId.d.ts +1 -0
  48. package/dist/runtime/utils/objectId.js +4 -0
  49. package/package.json +1 -1
@@ -0,0 +1,22 @@
1
+ export interface BatchInsertFailure {
2
+ start: number;
3
+ count: number;
4
+ error: unknown;
5
+ mayBePartial: boolean;
6
+ }
7
+ export interface BatchInsertResult {
8
+ inserted: number;
9
+ failedBatches: BatchInsertFailure[];
10
+ skipped: number;
11
+ aborted: boolean;
12
+ }
13
+ export interface BatchInsertOptions {
14
+ batchSize?: number;
15
+ signal?: AbortSignal;
16
+ onProgress?: (progress: {
17
+ done: number;
18
+ total: number;
19
+ }) => void;
20
+ isAtomicFailure?: (error: unknown) => boolean;
21
+ }
22
+ export declare function runBatchInsert<T>(rows: T[], insert: (batch: T[]) => Promise<unknown>, options?: BatchInsertOptions): Promise<BatchInsertResult>;
@@ -0,0 +1,24 @@
1
+ const DEFAULT_BATCH_SIZE = 1e3;
2
+ const MAX_BATCH_SIZE = 1e4;
3
+ export async function runBatchInsert(rows, insert, options = {}) {
4
+ 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 };
6
+ let done = 0;
7
+ for (let start = 0; start < rows.length; start += batchSize) {
8
+ if (options.signal?.aborted) {
9
+ result.aborted = true;
10
+ result.skipped = rows.length - start;
11
+ break;
12
+ }
13
+ const batch = rows.slice(start, start + batchSize);
14
+ try {
15
+ await insert(batch);
16
+ result.inserted += batch.length;
17
+ } catch (error) {
18
+ result.failedBatches.push({ start, count: batch.length, error, mayBePartial: !(options.isAtomicFailure?.(error) ?? false) });
19
+ }
20
+ done += batch.length;
21
+ options.onProgress?.({ done, total: rows.length });
22
+ }
23
+ return result;
24
+ }
@@ -5,4 +5,9 @@ export interface BulkDeleteResult<T> {
5
5
  error: unknown;
6
6
  }[];
7
7
  }
8
- export declare function runBulkDelete<T>(items: T[], remove: (item: T) => Promise<unknown>, concurrency?: number): Promise<BulkDeleteResult<T>>;
8
+ export interface BulkRemoveMany<T> {
9
+ run: (items: T[]) => Promise<number | undefined>;
10
+ canHandle?: (item: T) => boolean;
11
+ chunkSize?: number;
12
+ }
13
+ export declare function runBulkDelete<T>(items: T[], remove: (item: T) => Promise<unknown>, concurrency?: number, removeMany?: BulkRemoveMany<T>): Promise<BulkDeleteResult<T>>;
@@ -1,9 +1,33 @@
1
- export async function runBulkDelete(items, remove, concurrency = 5) {
1
+ const DEFAULT_CHUNK_SIZE = 100;
2
+ export async function runBulkDelete(items, remove, concurrency = 5, removeMany) {
2
3
  const outcomes = Array.from({ length: items.length });
4
+ const individually = [];
5
+ if (removeMany) {
6
+ const chunkSize = Math.max(1, Math.floor(removeMany.chunkSize ?? DEFAULT_CHUNK_SIZE) || DEFAULT_CHUNK_SIZE);
7
+ const batched = [];
8
+ items.forEach((item, index) => {
9
+ if (removeMany.canHandle?.(item) ?? true) batched.push(index);
10
+ else individually.push(index);
11
+ });
12
+ for (let start = 0; start < batched.length; start += chunkSize) {
13
+ const indexes = batched.slice(start, start + chunkSize);
14
+ try {
15
+ const deletedCount = await removeMany.run(indexes.map((i) => items[i]));
16
+ if (typeof deletedCount === "number" && deletedCount >= indexes.length) {
17
+ for (const i of indexes) outcomes[i] = { ok: true };
18
+ continue;
19
+ }
20
+ } catch {
21
+ }
22
+ individually.push(...indexes);
23
+ }
24
+ } else {
25
+ individually.push(...items.keys());
26
+ }
3
27
  let next = 0;
4
28
  async function worker() {
5
- while (next < items.length) {
6
- const index = next++;
29
+ while (next < individually.length) {
30
+ const index = individually[next++];
7
31
  try {
8
32
  await remove(items[index]);
9
33
  outcomes[index] = { ok: true };
@@ -12,7 +36,7 @@ export async function runBulkDelete(items, remove, concurrency = 5) {
12
36
  }
13
37
  }
14
38
  }
15
- await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
39
+ await Promise.all(Array.from({ length: Math.min(concurrency, individually.length) }, worker));
16
40
  const result = { deleted: [], failed: [] };
17
41
  items.forEach((item, index) => {
18
42
  const outcome = outcomes[index];
@@ -0,0 +1,27 @@
1
+ export declare class BulkMatchShortfall extends Error {
2
+ matched: number;
3
+ expected: number;
4
+ constructor(matched: number, expected: number);
5
+ }
6
+ export declare class BulkUnaddressableId extends Error {
7
+ id: string;
8
+ constructor(id: string);
9
+ }
10
+ export interface BulkUpdateFailure {
11
+ ids: string[];
12
+ error: unknown;
13
+ }
14
+ export interface BulkUpdateResult {
15
+ updated: string[];
16
+ failed: BulkUpdateFailure[];
17
+ }
18
+ export interface BulkUpdateOptions {
19
+ chunkSize?: number;
20
+ }
21
+ export declare function isEditableField(field: string): boolean;
22
+ export declare function buildIdFilter(ids: string[]): {
23
+ $or: {
24
+ _id: string;
25
+ }[];
26
+ };
27
+ export declare function runBulkUpdate(ids: string[], updateMany: (ids: string[]) => Promise<unknown>, options?: BulkUpdateOptions): Promise<BulkUpdateResult>;
@@ -0,0 +1,45 @@
1
+ import { isObjectIdHex } from "./objectId.js";
2
+ export class BulkMatchShortfall extends Error {
3
+ constructor(matched, expected) {
4
+ super(`Only ${matched} of ${expected} documents were found`);
5
+ this.matched = matched;
6
+ this.expected = expected;
7
+ this.name = "BulkMatchShortfall";
8
+ }
9
+ }
10
+ export class BulkUnaddressableId extends Error {
11
+ constructor(id) {
12
+ super(`Document id "${id}" cannot be used in a bulk filter`);
13
+ this.id = id;
14
+ this.name = "BulkUnaddressableId";
15
+ }
16
+ }
17
+ const DEFAULT_CHUNK_SIZE = 100;
18
+ export function isEditableField(field) {
19
+ return field !== "" && field !== "_id" && !field.startsWith("$") && !field.includes(".");
20
+ }
21
+ export function buildIdFilter(ids) {
22
+ if (ids.length === 0) throw new Error("buildIdFilter needs at least one id");
23
+ const bad = ids.find((id) => !isObjectIdHex(id));
24
+ if (bad !== void 0) throw new BulkUnaddressableId(bad);
25
+ return { $or: ids.map((id) => ({ _id: id })) };
26
+ }
27
+ export async function runBulkUpdate(ids, updateMany, options = {}) {
28
+ const chunkSize = Math.max(1, Math.floor(options.chunkSize ?? DEFAULT_CHUNK_SIZE) || DEFAULT_CHUNK_SIZE);
29
+ const result = { updated: [], failed: [] };
30
+ const addressable = ids.filter((id) => isObjectIdHex(id));
31
+ const others = ids.filter((id) => !isObjectIdHex(id));
32
+ for (let start = 0; start < addressable.length; start += chunkSize) {
33
+ const chunk = addressable.slice(start, start + chunkSize);
34
+ try {
35
+ const response = await updateMany(chunk);
36
+ const matched = response?.matchedCount;
37
+ if (typeof matched === "number" && matched < chunk.length) result.failed.push({ ids: chunk, error: new BulkMatchShortfall(matched, chunk.length) });
38
+ else result.updated.push(...chunk);
39
+ } catch (error) {
40
+ result.failed.push({ ids: chunk, error });
41
+ }
42
+ }
43
+ for (const id of others) result.failed.push({ ids: [id], error: new BulkUnaddressableId(id) });
44
+ return result;
45
+ }
@@ -0,0 +1,8 @@
1
+ import type { FilterFieldType, FilterOperator } from './filterBuilder.js';
2
+ export interface SuggestionOption {
3
+ value: string;
4
+ label: string;
5
+ }
6
+ export declare function isSuggestable(value: string, operator: FilterOperator): boolean;
7
+ export declare function wantsSuggestions(type: FilterFieldType, operator: FilterOperator): boolean;
8
+ export declare function suggestionOptions(values: string[], operator: FilterOperator, text: string): SuggestionOption[];
@@ -0,0 +1,15 @@
1
+ const SUGGESTION_OPERATORS = ["equals", "notEquals", "oneOf"];
2
+ const UNFILTERABLE = /[:*?()\\]/;
3
+ export function isSuggestable(value, operator) {
4
+ if (value.trim() === "" || UNFILTERABLE.test(value)) return false;
5
+ return operator !== "oneOf" || !value.includes(",");
6
+ }
7
+ export function wantsSuggestions(type, operator) {
8
+ return type === "string" && SUGGESTION_OPERATORS.includes(operator);
9
+ }
10
+ export function suggestionOptions(values, operator, text) {
11
+ const unique = [...new Set(values)].filter((value) => isSuggestable(value, operator));
12
+ if (operator !== "oneOf") return unique.map((value) => ({ value, label: value }));
13
+ const entered = text.split(",").slice(0, -1).map((item) => item.trim()).filter((item) => item.length > 0);
14
+ return unique.filter((value) => !entered.includes(value)).map((value) => ({ value: [...entered, value].join(", "), label: value }));
15
+ }
@@ -0,0 +1,21 @@
1
+ import type { CoerceOptions, ImportColumnType, ImportError, ImportLimits } from './importRows.js';
2
+ export type ImportFormat = 'json' | 'csv';
3
+ export interface PrepareImportInput {
4
+ format: ImportFormat;
5
+ text: string;
6
+ delimiter?: string;
7
+ columnTypes?: Record<string, ImportColumnType>;
8
+ emptyCells?: CoerceOptions['emptyCells'];
9
+ limits?: ImportLimits;
10
+ }
11
+ export interface PreparedImport {
12
+ rows: Record<string, unknown>[];
13
+ sourceIndexes: number[];
14
+ columns: string[];
15
+ columnTypes: Record<string, ImportColumnType>;
16
+ errors: ImportError[];
17
+ truncated: boolean;
18
+ sourceRowCount: number;
19
+ }
20
+ export declare function detectImportFormat(fileName: string, text: string): ImportFormat;
21
+ export declare function prepareImport(input: PrepareImportInput): PreparedImport;
@@ -0,0 +1,52 @@
1
+ import { unwrapExtendedJson } from "../composables/useMongocampExtendedJson.js";
2
+ import { DEFAULT_IMPORT_LIMITS, coerceRow, inferColumnTypes, parseCsvRows, parseJsonRows, validateRows } from "./importRows.js";
3
+ const PREVIEW_KEY_ROWS = 100;
4
+ export function detectImportFormat(fileName, text) {
5
+ const lower = fileName.toLowerCase();
6
+ if (lower.endsWith(".json")) return "json";
7
+ if (lower.endsWith(".csv") || lower.endsWith(".tsv")) return "csv";
8
+ const first = text.replace(/^\uFEFF/, "").trimStart()[0];
9
+ return first === "[" || first === "{" ? "json" : "csv";
10
+ }
11
+ function collectKeys(rows) {
12
+ const keys = /* @__PURE__ */ new Set();
13
+ for (const row of rows.slice(0, PREVIEW_KEY_ROWS)) for (const key of Object.keys(row)) keys.add(key);
14
+ return [...keys];
15
+ }
16
+ export function prepareImport(input) {
17
+ const limits = input.limits ?? DEFAULT_IMPORT_LIMITS;
18
+ const parsed = input.format === "json" ? parseJsonRows(input.text, limits) : parseCsvRows(input.text, input.delimiter, limits);
19
+ const errors = [...parsed.errors];
20
+ const parsedSources = parsed.sourceIndexes ?? parsed.rows.map((_, i) => i);
21
+ const columns = parsed.columns ?? collectKeys(parsed.rows);
22
+ const sourceRowCount = parsed.rows.length + parsed.errors.filter((e) => e.rowIndex >= 0).length;
23
+ let columnTypes = {};
24
+ let candidates = [];
25
+ let candidateSources = [];
26
+ if (input.format === "csv") {
27
+ columnTypes = input.columnTypes ?? inferColumnTypes(parsed.rows, columns);
28
+ parsed.rows.forEach((row, i) => {
29
+ const { row: typed, errors: cellErrors } = coerceRow(row, columnTypes, { emptyCells: input.emptyCells });
30
+ if (cellErrors.length > 0) {
31
+ for (const e of cellErrors) errors.push({ rowIndex: parsedSources[i], ...e });
32
+ return;
33
+ }
34
+ candidates.push(typed);
35
+ candidateSources.push(parsedSources[i]);
36
+ });
37
+ } else {
38
+ candidates = parsed.rows.map((row) => unwrapExtendedJson(row));
39
+ candidateSources = parsedSources;
40
+ }
41
+ const validated = validateRows(candidates, limits);
42
+ for (const e of validated.errors) errors.push(e.rowIndex >= 0 ? { ...e, rowIndex: candidateSources[e.rowIndex] } : e);
43
+ return {
44
+ rows: validated.rows,
45
+ sourceIndexes: (validated.sourceIndexes ?? []).map((i) => candidateSources[i]),
46
+ columns,
47
+ columnTypes,
48
+ errors,
49
+ truncated: validated.truncated,
50
+ sourceRowCount
51
+ };
52
+ }
@@ -0,0 +1,36 @@
1
+ export type ImportColumnType = 'string' | 'number' | 'boolean' | 'date-time' | 'json';
2
+ export type ImportErrorCode = 'file-too-large' | 'invalid-json' | 'not-array' | 'not-object' | 'invalid-delimiter' | 'invalid-csv' | 'invalid-header' | 'field-count' | 'too-many-rows' | 'empty-row' | 'forbidden-key' | 'too-deep' | 'invalid-number' | 'unsafe-integer' | 'invalid-id' | 'invalid-boolean' | 'invalid-date' | 'invalid-json-value';
3
+ export interface ImportError {
4
+ rowIndex: number;
5
+ column?: string;
6
+ code: ImportErrorCode;
7
+ message: string;
8
+ }
9
+ export interface ImportLimits {
10
+ maxRows: number;
11
+ maxBytes: number;
12
+ }
13
+ export interface ImportReport<T = Record<string, unknown>> {
14
+ rows: T[];
15
+ columns?: string[];
16
+ errors: ImportError[];
17
+ truncated: boolean;
18
+ sourceIndexes?: number[];
19
+ }
20
+ export interface CoerceOptions {
21
+ emptyCells?: 'omit' | 'empty-string';
22
+ }
23
+ export interface CoerceResult {
24
+ row: Record<string, unknown>;
25
+ errors: {
26
+ column: string;
27
+ code: ImportErrorCode;
28
+ message: string;
29
+ }[];
30
+ }
31
+ export declare const DEFAULT_IMPORT_LIMITS: ImportLimits;
32
+ export declare function parseJsonRows(text: string, limits?: ImportLimits): ImportReport;
33
+ export declare function parseCsvRows(text: string, delimiter?: string, limits?: ImportLimits): ImportReport<Record<string, string>>;
34
+ export declare function validateRows<T extends Record<string, unknown>>(rows: T[], limits?: ImportLimits): ImportReport<T>;
35
+ export declare function coerceRow(row: Record<string, unknown>, columnTypes: Record<string, ImportColumnType>, options?: CoerceOptions): CoerceResult;
36
+ export declare function inferColumnTypes(rows: Record<string, unknown>[], columns: string[]): Record<string, ImportColumnType>;
@@ -0,0 +1,228 @@
1
+ import { isIsoDateTimeString } from "./isoDate.js";
2
+ import { isObjectIdHex } from "./objectId.js";
3
+ export const DEFAULT_IMPORT_LIMITS = { maxRows: 1e4, maxBytes: 5 * 1024 * 1024 };
4
+ const MAX_DEPTH = 64;
5
+ function isPlainObject(value) {
6
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7
+ }
8
+ function stripBom(text) {
9
+ return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
10
+ }
11
+ function fileError(code, message) {
12
+ return { rows: [], errors: [{ rowIndex: -1, code, message }], truncated: false };
13
+ }
14
+ export function parseJsonRows(text, limits = DEFAULT_IMPORT_LIMITS) {
15
+ if (text.length > limits.maxBytes) return fileError("file-too-large", `File is larger than ${limits.maxBytes} bytes`);
16
+ let parsed;
17
+ try {
18
+ parsed = JSON.parse(stripBom(text));
19
+ } catch (e) {
20
+ return fileError("invalid-json", `Invalid JSON: ${e instanceof Error ? e.message : String(e)}`);
21
+ }
22
+ if (!Array.isArray(parsed)) return fileError("not-array", "Expected a JSON array of objects");
23
+ const report = { rows: [], errors: [], truncated: false, sourceIndexes: [] };
24
+ parsed.forEach((item, rowIndex) => {
25
+ if (isPlainObject(item)) {
26
+ report.rows.push(item);
27
+ report.sourceIndexes.push(rowIndex);
28
+ } else report.errors.push({ rowIndex, code: "not-object", message: "Row is not an object" });
29
+ });
30
+ return report;
31
+ }
32
+ function splitCsv(text, delimiter) {
33
+ const records = [];
34
+ let record = [];
35
+ let field = "";
36
+ let inQuotes = false;
37
+ let fieldStart = true;
38
+ for (let i = 0; i < text.length; i++) {
39
+ const ch = text[i];
40
+ if (inQuotes) {
41
+ if (ch === '"') {
42
+ if (text[i + 1] === '"') {
43
+ field += '"';
44
+ i++;
45
+ } else {
46
+ inQuotes = false;
47
+ }
48
+ } else {
49
+ field += ch;
50
+ }
51
+ continue;
52
+ }
53
+ if (ch === '"' && fieldStart) {
54
+ inQuotes = true;
55
+ fieldStart = false;
56
+ } else if (ch === delimiter) {
57
+ record.push(field);
58
+ field = "";
59
+ fieldStart = true;
60
+ } else if (ch === "\r" || ch === "\n") {
61
+ if (ch === "\r" && text[i + 1] === "\n") i++;
62
+ record.push(field);
63
+ records.push(record);
64
+ record = [];
65
+ field = "";
66
+ fieldStart = true;
67
+ } else {
68
+ field += ch;
69
+ fieldStart = false;
70
+ }
71
+ }
72
+ if (inQuotes) return null;
73
+ if (field !== "" || record.length > 0) {
74
+ record.push(field);
75
+ records.push(record);
76
+ }
77
+ return records.filter((r) => !(r.length === 1 && r[0] === ""));
78
+ }
79
+ export function parseCsvRows(text, delimiter = ",", limits = DEFAULT_IMPORT_LIMITS) {
80
+ const fail = (code, message) => ({ rows: [], errors: [{ rowIndex: -1, code, message }], truncated: false });
81
+ if (delimiter.length !== 1 || /["\r\n]/.test(delimiter)) return fail("invalid-delimiter", "Delimiter must be a single character other than a quote or line break");
82
+ if (text.length > limits.maxBytes) return fail("file-too-large", `File is larger than ${limits.maxBytes} bytes`);
83
+ const records = splitCsv(stripBom(text), delimiter);
84
+ if (!records) return fail("invalid-csv", "A quoted field is not closed");
85
+ const [headerRecord, ...dataRecords] = records;
86
+ if (!headerRecord) return fail("invalid-csv", "The file has no header row");
87
+ const columns = headerRecord.map((name) => name.trim());
88
+ if (columns.includes("")) return fail("invalid-header", "The header row has an empty column name");
89
+ const duplicate = columns.find((name, i) => columns.indexOf(name) !== i);
90
+ if (duplicate !== void 0) return fail("invalid-header", `Duplicate column name "${duplicate}"`);
91
+ const report = { rows: [], columns, errors: [], truncated: false, sourceIndexes: [] };
92
+ dataRecords.forEach((fields, rowIndex) => {
93
+ if (fields.length > columns.length) {
94
+ report.errors.push({ rowIndex, code: "field-count", message: `Row has ${fields.length} fields, expected ${columns.length}` });
95
+ return;
96
+ }
97
+ const row = {};
98
+ columns.forEach((name, i) => {
99
+ row[name] = fields[i] ?? "";
100
+ });
101
+ report.rows.push(row);
102
+ report.sourceIndexes.push(rowIndex);
103
+ });
104
+ return report;
105
+ }
106
+ function forbiddenKeyPath(value, path, depth) {
107
+ if (depth > MAX_DEPTH) return { path, tooDeep: true };
108
+ if (Array.isArray(value)) {
109
+ for (let i = 0; i < value.length; i++) {
110
+ const found = forbiddenKeyPath(value[i], `${path}[${i}]`, depth + 1);
111
+ if (found) return found;
112
+ }
113
+ return void 0;
114
+ }
115
+ if (!isPlainObject(value)) return void 0;
116
+ for (const [key, inner] of Object.entries(value)) {
117
+ const keyPath = path ? `${path}.${key}` : key;
118
+ if (key === "__proto__" || key.startsWith("$")) return { path: keyPath, tooDeep: false };
119
+ const found = forbiddenKeyPath(inner, keyPath, depth + 1);
120
+ if (found) return found;
121
+ }
122
+ return void 0;
123
+ }
124
+ export function validateRows(rows, limits = DEFAULT_IMPORT_LIMITS) {
125
+ const report = { rows: [], errors: [], truncated: false, sourceIndexes: [] };
126
+ rows.forEach((row, rowIndex) => {
127
+ if (rowIndex >= limits.maxRows) return;
128
+ if (Object.keys(row).length === 0) {
129
+ report.errors.push({ rowIndex, code: "empty-row", message: "Row has no fields" });
130
+ return;
131
+ }
132
+ if ("_id" in row && !isObjectIdHex(row._id)) {
133
+ report.errors.push({ rowIndex, column: "_id", code: "invalid-id", message: "_id must be a 24-character hex string" });
134
+ return;
135
+ }
136
+ const bad = forbiddenKeyPath(row, "", 0);
137
+ if (bad) {
138
+ report.errors.push(bad.tooDeep ? { rowIndex, column: bad.path, code: "too-deep", message: `Row is nested deeper than ${MAX_DEPTH} levels` } : { rowIndex, column: bad.path, code: "forbidden-key", message: `Key "${bad.path}" is not allowed` });
139
+ return;
140
+ }
141
+ report.rows.push(row);
142
+ report.sourceIndexes.push(rowIndex);
143
+ });
144
+ if (rows.length > limits.maxRows) {
145
+ report.truncated = true;
146
+ report.errors.push({ rowIndex: -1, code: "too-many-rows", message: `Only the first ${limits.maxRows} of ${rows.length} rows are kept` });
147
+ }
148
+ return report;
149
+ }
150
+ const TRUE_VALUES = ["true", "1", "yes"];
151
+ const FALSE_VALUES = ["false", "0", "no"];
152
+ const NUMBER_PATTERN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
153
+ const INTEGER_PATTERN = /^[+-]?\d+$/;
154
+ function coerceDate(text) {
155
+ if (!isIsoDateTimeString(text)) throw new Error("not an ISO date");
156
+ let iso = text.replace(" ", "T");
157
+ const timePart = iso.split("T")[1];
158
+ if (timePart === void 0) iso += "T00:00:00Z";
159
+ else if (!/(?:Z|[+-]\d{2}:?\d{2})$/.test(timePart)) iso += "Z";
160
+ return new Date(iso).toISOString();
161
+ }
162
+ function coerceValue(text, type) {
163
+ try {
164
+ switch (type) {
165
+ case "number": {
166
+ if (!NUMBER_PATTERN.test(text)) return { error: { code: "invalid-number", message: "Not a number" } };
167
+ const asNumber = Number(text);
168
+ if (!Number.isFinite(asNumber)) return { error: { code: "invalid-number", message: "Number out of range" } };
169
+ if (INTEGER_PATTERN.test(text) && !Number.isSafeInteger(asNumber)) {
170
+ return { error: { code: "unsafe-integer", message: "Integer is beyond \xB1(2^53 \u2212 1) and would lose precision; import it as text" } };
171
+ }
172
+ return { value: asNumber };
173
+ }
174
+ case "boolean": {
175
+ const lower = text.toLowerCase();
176
+ if (TRUE_VALUES.includes(lower)) return { value: true };
177
+ if (FALSE_VALUES.includes(lower)) return { value: false };
178
+ return { error: { code: "invalid-boolean", message: "Expected true/false, 1/0 or yes/no" } };
179
+ }
180
+ case "date-time":
181
+ return { value: coerceDate(text) };
182
+ case "json":
183
+ return { value: JSON.parse(text) };
184
+ default:
185
+ return { value: text };
186
+ }
187
+ } catch (e) {
188
+ const message = e instanceof Error ? e.message : String(e);
189
+ const code = type === "date-time" ? "invalid-date" : "invalid-json-value";
190
+ return { error: { code, message } };
191
+ }
192
+ }
193
+ export function coerceRow(row, columnTypes, options = {}) {
194
+ const result = { row: {}, errors: [] };
195
+ for (const [column, value] of Object.entries(row)) {
196
+ if (typeof value !== "string") {
197
+ result.row[column] = value;
198
+ continue;
199
+ }
200
+ const type = columnTypes[column] ?? "string";
201
+ const text = type === "string" ? value : value.trim();
202
+ if (text === "") {
203
+ if (type === "string" && options.emptyCells === "empty-string") result.row[column] = "";
204
+ continue;
205
+ }
206
+ const { value: converted, error } = coerceValue(text, type);
207
+ if (error) result.errors.push({ column, ...error });
208
+ else result.row[column] = converted;
209
+ }
210
+ return result;
211
+ }
212
+ export function inferColumnTypes(rows, columns) {
213
+ const types = {};
214
+ for (const column of columns) {
215
+ const values = rows.map((row) => row[column]).filter((value) => typeof value === "string" && value.trim() !== "").map((value) => value.trim());
216
+ if (values.length === 0) types[column] = "string";
217
+ else if (values.every((v) => /^(?:true|false|yes|no)$/i.test(v))) types[column] = "boolean";
218
+ else if (values.every(isPlainNumberText)) types[column] = "number";
219
+ else if (values.every(isIsoDateTimeString)) types[column] = "date-time";
220
+ else types[column] = "string";
221
+ }
222
+ return types;
223
+ }
224
+ function isPlainNumberText(text) {
225
+ if (!NUMBER_PATTERN.test(text)) return false;
226
+ if (/^[+-]?0\d/.test(text)) return false;
227
+ return !INTEGER_PATTERN.test(text) || Number.isSafeInteger(Number(text));
228
+ }
@@ -0,0 +1 @@
1
+ export declare function isObjectIdHex(value: unknown): value is string;
@@ -0,0 +1,4 @@
1
+ const OBJECT_ID_PATTERN = /^[0-9a-f]{24}$/i;
2
+ export function isObjectIdHex(value) {
3
+ return typeof value === "string" && OBJECT_ID_PATTERN.test(value);
4
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/nuxt-ui-mongocamp",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "description": "A Nuxt module that wraps @sfxcode/nuxt-mongocamp-server with ready-made UI components, composables, and a runtime plugin",
5
5
  "repository": "sfxcode/nuxt-ui-mongocamp",
6
6
  "homepage": "https://sfxcode.github.io/nuxt-ui-mongocamp/",