@noy-db/as-xlsx 0.2.0-pre.8 → 0.3.0-pre.1

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.
package/dist/index.d.ts CHANGED
@@ -39,7 +39,39 @@ import { DictEntry, VaultDiff, Vault } from '@noy-db/hub';
39
39
  *
40
40
  * @module
41
41
  */
42
- /** One row in a sheet. Values are coerced per type at emit time. */
42
+ /**
43
+ * A formula cell. Emits `<f>` so the spreadsheet recomputes live; `v` is an
44
+ * optional cached result (what the formula currently evaluates to) so the value
45
+ * shows immediately on open and survives a round-trip read. Build via
46
+ * {@link formula}. The formula string must NOT include a leading `=`.
47
+ */
48
+ interface XlsxFormulaCell {
49
+ readonly __xlsxFormula: string;
50
+ readonly v?: string | number | boolean;
51
+ }
52
+ /** Build a {@link XlsxFormulaCell}. `f` is the formula body without a leading `=`. */
53
+ declare function formula(f: string, cachedValue?: string | number | boolean): XlsxFormulaCell;
54
+ /**
55
+ * A value cell carrying a number-format code (e.g. `'#,##0.00'` for currency,
56
+ * `'yyyy-mm-dd'` for dates). Build via {@link styled}. The format only renders
57
+ * meaningfully on numeric values.
58
+ */
59
+ interface XlsxStyledCell {
60
+ readonly __xlsxStyle: string;
61
+ readonly v: string | number | boolean | null;
62
+ }
63
+ /** Build a {@link XlsxStyledCell} — a value plus an Excel number-format code. */
64
+ declare function styled(value: string | number | boolean | null, numberFormat: string): XlsxStyledCell;
65
+ /** A data-validation rule (dropdown) over a cell range. */
66
+ interface XlsxValidation {
67
+ /** Target range in A1 notation, e.g. `'B2:B100'`. */
68
+ readonly sqref: string;
69
+ /** Inline allowed values → a `"a,b,c"` list. Mutually exclusive with `formula1`. */
70
+ readonly values?: readonly string[];
71
+ /** Explicit `formula1` (e.g. a range ref `Clients!$A$2:$A$999`). */
72
+ readonly formula1?: string;
73
+ }
74
+ /** One row in a sheet. A cell is a primitive value or an {@link XlsxFormulaCell}. */
43
75
  type XlsxRow = ReadonlyArray<unknown>;
44
76
  /** One sheet in a workbook. */
45
77
  interface XlsxSheet {
@@ -60,12 +92,19 @@ interface XlsxSheet {
60
92
  * for "auto" columns and a number for explicit widths.
61
93
  */
62
94
  readonly widths?: ReadonlyArray<number | undefined>;
95
+ /** Data-validation dropdowns applied to ranges on this sheet. */
96
+ readonly validations?: readonly XlsxValidation[];
63
97
  }
64
98
  /**
65
99
  * Build a complete `.xlsx` byte stream from the supplied sheet data.
66
100
  * Pure — no I/O beyond the internal zip concatenation.
67
101
  */
68
- declare function writeXlsx(sheets: readonly XlsxSheet[]): Promise<Uint8Array>;
102
+ declare function writeXlsx(sheets: readonly XlsxSheet[], options?: {
103
+ definedNames?: ReadonlyArray<{
104
+ readonly name: string;
105
+ readonly ref: string;
106
+ }>;
107
+ }): Promise<Uint8Array>;
69
108
  /**
70
109
  * Convert a 1-based column index to Excel A1 letter notation.
71
110
  * 1 → A, 26 → Z, 27 → AA, 702 → ZZ, 703 → AAA.
@@ -115,6 +154,30 @@ interface ReadXlsxResult {
115
154
  */
116
155
  declare function readXlsx(bytes: Uint8Array): Promise<ReadXlsxResult>;
117
156
 
157
+ type InferredType = 'string' | 'number' | 'boolean' | 'date';
158
+ interface InferredField {
159
+ readonly type: InferredType;
160
+ /** Target collection (sheet) name when this field looks like a foreign key. */
161
+ readonly references?: string;
162
+ }
163
+ interface InferredCollection {
164
+ readonly idField: string;
165
+ readonly fields: Record<string, InferredField>;
166
+ }
167
+ interface InferredSchema {
168
+ readonly collections: Record<string, InferredCollection>;
169
+ }
170
+ /**
171
+ * Infer a {@link InferredSchema} from an `.xlsx` byte stream. Sheets whose name
172
+ * starts with `_` (our smart-export meta sheets) are skipped; pass `skipSheets`
173
+ * to exclude more (e.g. summary sheets).
174
+ */
175
+ declare function inferSchema(bytes: Uint8Array, options?: {
176
+ skipSheets?: readonly string[];
177
+ }): Promise<InferredSchema>;
178
+ /** Emit a Zod schema snippet (guidance) from an {@link InferredSchema}. */
179
+ declare function zodSourceFor(schema: InferredSchema): string;
180
+
118
181
  /**
119
182
  * **@noy-db/as-xlsx** — Excel spreadsheet plaintext export for noy-db.
120
183
  *
@@ -179,11 +242,123 @@ interface AsXlsxSheetOptions {
179
242
  * mirrors `XlsxSheet.widths`, which it threads through.
180
243
  */
181
244
  readonly widths?: ReadonlyArray<number | undefined>;
245
+ /**
246
+ * Smart mode only: per-field Excel number-format codes (e.g.
247
+ * `{ amount: '#,##0.00' }` for currency). The value is coerced to a number so
248
+ * the format renders. Money has no introspection signal, so currency
249
+ * formatting is opt-in here.
250
+ */
251
+ readonly numberFormats?: Record<string, string>;
252
+ /**
253
+ * Smart mode only: per-field explicit dropdown value lists. Overrides the
254
+ * auto-detected enum/ref dropdown for that field.
255
+ */
256
+ readonly dropdowns?: Record<string, readonly string[]>;
257
+ /**
258
+ * Smart mode only: fields whose stored value is a multi-locale i18n map
259
+ * (`{ en: '…', th: '…' }`). Each becomes per-locale columns plus a display
260
+ * column resolved **live by the global LANG cell** (change LANG → every label
261
+ * re-renders). Read raw, so open the export vault without an active locale.
262
+ */
263
+ readonly i18nFields?: readonly string[];
264
+ /**
265
+ * Smart mode only: map a dict-backed (code) field to its dictionary name, e.g.
266
+ * `{ status: 'status' }`. Emits a hidden `_Lookups_<dict>` sheet (code +
267
+ * per-locale labels) and a `<field>__label` display column resolved by the
268
+ * global LANG cell via `VLOOKUP(code, …, MATCH(LANG, …))`.
269
+ */
270
+ readonly dictFields?: Record<string, string>;
271
+ /**
272
+ * Multi-vault export only: pull FK-referenced fields from a supporting vault
273
+ * into this sheet as extra columns. Each entry resolves `localField` on the
274
+ * primary record against the `keyField` of another vault's collection (matched
275
+ * by `from.label`/`from.collection`), and emits the `pick` field value as
276
+ * `column`. Appended AFTER the declared `columns` in declaration order.
277
+ * Unresolved FK (row not in the supporting-vault index) → empty cell.
278
+ * Ignored by single-vault `toBytes`.
279
+ */
280
+ readonly denormalize?: readonly MultiVaultDenormColumn[];
281
+ }
282
+ /**
283
+ * One denormalized column in a multi-vault export: pulls a field from a
284
+ * supporting vault into the primary sheet via an in-memory join.
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * {
289
+ * column: 'entityName', // new column header in the primary sheet
290
+ * localField: 'entityId', // FK field on the primary record
291
+ * from: { label: 'directory', collection: 'entities', keyField: 'id', pick: 'name' },
292
+ * }
293
+ * ```
294
+ */
295
+ interface MultiVaultDenormColumn {
296
+ /** Header of the new column to append to the primary sheet. */
297
+ readonly column: string;
298
+ /** Field on the primary record whose value is the FK. */
299
+ readonly localField: string;
300
+ readonly from: {
301
+ /** Label of the supporting vault entry (matches `MultiVaultXlsxEntry.label`). */
302
+ readonly label: string;
303
+ /** Collection in the supporting vault. */
304
+ readonly collection: string;
305
+ /** Field in the supporting record that is the join key (usually `'id'`). */
306
+ readonly keyField: string;
307
+ /** Field in the supporting record to copy as the denorm value. */
308
+ readonly pick: string;
309
+ };
310
+ }
311
+ /** One aggregate column in a smart-mode summary sheet (#414 P3). */
312
+ interface AsXlsxSummaryAggregate {
313
+ /** Column header for this aggregate. */
314
+ readonly label: string;
315
+ readonly op: 'sum' | 'count' | 'avg';
316
+ /** Field to aggregate — required for `sum`/`avg`, ignored for `count`. */
317
+ readonly field?: string;
318
+ }
319
+ /**
320
+ * A groupBy summary sheet (#414 P3): groups the source collection's sheet by
321
+ * `groupBy` and emits live SUMIFS/COUNTIFS/AVERAGEIFS columns (values cached at
322
+ * export). The source value columns must be numeric for the live formulas to
323
+ * compute (apply `numberFormats` to money fields).
324
+ */
325
+ interface AsXlsxSummarySpec {
326
+ /** Summary sheet name. */
327
+ readonly name: string;
328
+ /** Source collection (must be exported as a sheet). */
329
+ readonly from: string;
330
+ /** Field to group by. */
331
+ readonly groupBy: string;
332
+ readonly aggregates: readonly AsXlsxSummaryAggregate[];
182
333
  }
183
334
  /** Single-collection convenience — passed where a sheet-list is accepted. */
184
335
  interface AsXlsxOptions {
185
336
  /** One or more sheets. At least one required. */
186
337
  readonly sheets: readonly AsXlsxSheetOptions[];
338
+ /** Smart mode only: groupBy summary sheets (live SUMIFS/COUNTIFS/AVERAGEIFS). */
339
+ readonly summaries?: readonly AsXlsxSummarySpec[];
340
+ /**
341
+ * Smart mode only: summary formula dialect. `'excel'` (default) emits
342
+ * cross-compatible per-row SUMIFS/COUNTIFS/AVERAGEIFS. `'sheets'` emits a
343
+ * single Google-Sheets `QUERY` formula per summary — **Sheets-only** (QUERY
344
+ * errors in Excel); use when the target is Google Sheets.
345
+ */
346
+ readonly dialect?: 'excel' | 'sheets';
347
+ /**
348
+ * Smart-workbook mode (#414). Emits a relational workbook instead of a flat
349
+ * dump:
350
+ * - every sheet is **id-first** (record `id` in column A);
351
+ * - each foreign-key field (auto-detected via `vault.dumpSchema()`) gets a
352
+ * `<field>__label` column — a cross-sheet `VLOOKUP` that resolves the
353
+ * reference to the target's first field, carrying a **cached** label so it
354
+ * shows immediately and recomputes live on edit;
355
+ * - a `_manifest` index sheet lists every collection, its row count, and
356
+ * its refs.
357
+ *
358
+ * Requires unique sheet names ≤ 31 chars (so cross-sheet refs resolve) and an
359
+ * `id` field on records. Defaults to the existing flat export when omitted.
360
+ */
361
+ readonly smart?: boolean;
187
362
  }
188
363
  /** Options for `download()` — adds optional filename. */
189
364
  interface AsXlsxDownloadOptions extends AsXlsxOptions {
@@ -215,6 +390,61 @@ declare function download(vault: Vault, options: AsXlsxDownloadOptions): Promise
215
390
  * plaintext xlsx persists past the process (Tier 3 egress).
216
391
  */
217
392
  declare function write(vault: Vault, path: string, options: AsXlsxWriteOptions): Promise<void>;
393
+ /**
394
+ * One vault entry in a multi-vault export. Supplies the pre-opened
395
+ * vault, the sheet specs to render for it, and an optional closure
396
+ * (per-collection id allowlist computed externally by the orchestrator).
397
+ */
398
+ interface MultiVaultXlsxEntry {
399
+ readonly vault: Vault;
400
+ readonly sheets: readonly AsXlsxSheetOptions[];
401
+ /**
402
+ * Optional per-collection id allowlist (e.g. from walkCrossVaultClosure).
403
+ * When set, only rows whose `id` appears in the set are exported for that
404
+ * collection. Omit to export all rows.
405
+ */
406
+ readonly closure?: ReadonlyMap<string, ReadonlySet<string>>;
407
+ /**
408
+ * Optional display label for sheet-name prefixing.
409
+ * Defaults to `vault.name`.
410
+ */
411
+ readonly label?: string;
412
+ }
413
+ /** Options for {@link toBytesMultiVault}. */
414
+ interface MultiVaultXlsxOptions {
415
+ /**
416
+ * Separator inserted between the vault label and the sheet name when
417
+ * building tab names. Default `'_'`. Names are then truncated to 31 chars
418
+ * (Excel limit) by `writeXlsx`.
419
+ */
420
+ readonly sheetSeparator?: string;
421
+ }
422
+ /**
423
+ * Build an `.xlsx` byte stream spanning **multiple vaults**. Each entry
424
+ * supplies a pre-opened vault with its sheet specs and an optional
425
+ * per-collection id-closure (rows filtered to exactly those ids). A
426
+ * `_manifest` sheet is prepended that lists every vault-collection pair
427
+ * and its exported record count.
428
+ *
429
+ * ## Auth
430
+ * Every vault in `entries` must independently hold `assertCanExport('plaintext','xlsx')`.
431
+ * The check fires fail-fast before any rows are materialised.
432
+ *
433
+ * ## Architecture
434
+ * This function is **edge-pure** — it takes pre-opened vaults and a
435
+ * pre-computed closure; it performs no cross-vault FK walk itself.
436
+ * Cross-vault orchestration lives in the outward orchestration layer (allowed direction).
437
+ *
438
+ * ## Two-pass execution (when `denormalize` is declared)
439
+ * **Pass 1** — load and closure-filter ALL entries' rows, building a
440
+ * `Map<"${label}/${collection}", Map<keyValue, row>>` index keyed by each
441
+ * sheet's `keyField` (default `'id'`). Only closure-filtered rows are indexed,
442
+ * so an FK pointing outside the closure yields an empty cell (correct: that
443
+ * row was not referenced / not exported).
444
+ * **Pass 2** — emit each sheet; for sheets with `denormalize`, append each
445
+ * denorm column AFTER the declared columns by resolving the index lookup.
446
+ */
447
+ declare function toBytesMultiVault(entries: readonly MultiVaultXlsxEntry[], options?: MultiVaultXlsxOptions): Promise<Uint8Array>;
218
448
 
219
449
  type ImportPolicy = 'merge' | 'replace' | 'insert-only';
220
450
  /**
@@ -267,6 +497,14 @@ interface AsXlsxImportOptions {
267
497
  * Unknown labels (no match in any locale) pass through as-is.
268
498
  */
269
499
  readonly dicts?: Readonly<Record<string, readonly DictEntry[]>>;
500
+ /**
501
+ * Read a sheet produced by smart export (#414 P4). Reverses the smart layout:
502
+ * reconstructs i18n fields from their per-locale columns (`<f>__<loc>` →
503
+ * `{ loc: value }`), and drops derived columns — the i18n display column and
504
+ * every `<f>__label` (FK/dict) formula column. Code columns (the real values)
505
+ * pass through. Maps onto the existing collection schema (Mode A).
506
+ */
507
+ readonly smart?: boolean;
270
508
  }
271
509
  interface AsXlsxImportPlan {
272
510
  readonly plan: VaultDiff;
@@ -297,4 +535,4 @@ interface AsXlsxImportPlan {
297
535
  */
298
536
  declare function fromBytes(vault: Vault, bytes: Uint8Array, options: AsXlsxImportOptions): Promise<AsXlsxImportPlan>;
299
537
 
300
- export { type AsXlsxDownloadOptions, type AsXlsxImportOptions, type AsXlsxImportPlan, type AsXlsxOptions, type AsXlsxSheetOptions, type AsXlsxWriteOptions, type ImportPolicy, type ReadXlsxResult, type ReadXlsxRow, type ReadXlsxSheet, XlsxDictAmbiguityError, type XlsxRow, type XlsxSheet, colLetter, download, fromBytes, readXlsx, toBytes, toBytesFromCollection, write, writeXlsx };
538
+ export { type AsXlsxDownloadOptions, type AsXlsxImportOptions, type AsXlsxImportPlan, type AsXlsxOptions, type AsXlsxSheetOptions, type AsXlsxSummaryAggregate, type AsXlsxSummarySpec, type AsXlsxWriteOptions, type ImportPolicy, type InferredCollection, type InferredField, type InferredSchema, type InferredType, type MultiVaultDenormColumn, type MultiVaultXlsxEntry, type MultiVaultXlsxOptions, type ReadXlsxResult, type ReadXlsxRow, type ReadXlsxSheet, XlsxDictAmbiguityError, type XlsxFormulaCell, type XlsxRow, type XlsxSheet, type XlsxStyledCell, type XlsxValidation, colLetter, download, formula, fromBytes, inferSchema, readXlsx, styled, toBytes, toBytesFromCollection, toBytesMultiVault, write, writeXlsx, zodSourceFor };