@shbernal/ts-xlsx 1.0.3 → 1.2.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 (136) hide show
  1. package/README.md +21 -0
  2. package/dist/core/address.js +0 -33
  3. package/dist/core/autofilter.js +0 -9
  4. package/dist/core/cell.d.ts +10 -0
  5. package/dist/core/cell.js +4 -123
  6. package/dist/core/color-resolution.js +0 -60
  7. package/dist/core/column.d.ts +9 -1
  8. package/dist/core/column.js +0 -52
  9. package/dist/core/comment-thread.js +0 -45
  10. package/dist/core/conditional-formatting-overlay.js +0 -11
  11. package/dist/core/conditional-formatting.js +0 -10
  12. package/dist/core/containers.js +0 -15
  13. package/dist/core/data-validation-overlay.js +0 -25
  14. package/dist/core/data-validation.js +0 -7
  15. package/dist/core/date.js +0 -39
  16. package/dist/core/formula.js +0 -117
  17. package/dist/core/grid-edits.js +0 -38
  18. package/dist/core/image.js +0 -25
  19. package/dist/core/internal.js +0 -27
  20. package/dist/core/limits.d.ts +30 -0
  21. package/dist/core/limits.js +2 -0
  22. package/dist/core/merge.d.ts +18 -0
  23. package/dist/core/merge.js +22 -7
  24. package/dist/core/modern-functions.js +0 -17
  25. package/dist/core/page-setup.js +0 -5
  26. package/dist/core/pivot-table.d.ts +1 -1
  27. package/dist/core/pivot-table.js +0 -44
  28. package/dist/core/preserved.js +0 -4
  29. package/dist/core/protection.js +0 -26
  30. package/dist/core/range.js +0 -112
  31. package/dist/core/row-input.d.ts +24 -0
  32. package/dist/core/row-input.js +29 -0
  33. package/dist/core/row.d.ts +9 -1
  34. package/dist/core/row.js +0 -58
  35. package/dist/core/style.js +0 -26
  36. package/dist/core/table-style.js +0 -28
  37. package/dist/core/table.js +0 -97
  38. package/dist/core/text-metrics.d.ts +20 -0
  39. package/dist/core/text-metrics.js +10 -0
  40. package/dist/core/theme.js +0 -85
  41. package/dist/core/value.d.ts +40 -0
  42. package/dist/core/value.js +30 -48
  43. package/dist/core/workbook-protection.js +0 -13
  44. package/dist/core/workbook.d.ts +13 -0
  45. package/dist/core/workbook.js +11 -368
  46. package/dist/core/worksheet-model.js +2 -23
  47. package/dist/core/worksheet.d.ts +22 -0
  48. package/dist/core/worksheet.js +14 -485
  49. package/dist/customui/errors.js +0 -10
  50. package/dist/customui/index.js +0 -5
  51. package/dist/customui/ribbon.js +0 -43
  52. package/dist/entries/core.d.ts +3 -1
  53. package/dist/entries/core.js +3 -7
  54. package/dist/entries/csv.js +0 -4
  55. package/dist/entries/customui.js +0 -2
  56. package/dist/entries/errors.js +0 -13
  57. package/dist/entries/vba.js +0 -5
  58. package/dist/entries/xlsb.js +0 -6
  59. package/dist/entries/xlsx.js +0 -13
  60. package/dist/errors.d.ts +14 -0
  61. package/dist/errors.js +5 -56
  62. package/dist/index.js +0 -12
  63. package/dist/io/csv/read.js +0 -18
  64. package/dist/io/csv/write.js +5 -35
  65. package/dist/io/opc/errors.js +0 -30
  66. package/dist/io/opc/inflate.js +0 -35
  67. package/dist/io/opc/namespaces.js +0 -15
  68. package/dist/io/opc/part-paths.js +0 -11
  69. package/dist/io/opc/read-opc.js +0 -31
  70. package/dist/io/opc/read-options.js +0 -6
  71. package/dist/io/opc/rels.js +0 -13
  72. package/dist/io/opc/sniff-format.js +0 -50
  73. package/dist/io/style/xf-style.js +0 -31
  74. package/dist/io/xlsb/errors.js +0 -10
  75. package/dist/io/xlsb/formula.js +1 -99
  76. package/dist/io/xlsb/primitives.js +1 -83
  77. package/dist/io/xlsb/ptg-functions.js +0 -34
  78. package/dist/io/xlsb/read-shared-strings.js +0 -7
  79. package/dist/io/xlsb/read-styles.js +3 -66
  80. package/dist/io/xlsb/read-worksheet.js +4 -87
  81. package/dist/io/xlsb/read.js +2 -60
  82. package/dist/io/xlsb/record-stream.js +0 -28
  83. package/dist/io/xlsb/record-types.js +0 -19
  84. package/dist/io/xlsx/cell-accumulator.js +0 -32
  85. package/dist/io/xlsx/cell-value.js +0 -29
  86. package/dist/io/xlsx/color-xml.d.ts +6 -0
  87. package/dist/io/xlsx/color-xml.js +42 -0
  88. package/dist/io/xlsx/comments.js +0 -84
  89. package/dist/io/xlsx/conditional-formatting.d.ts +1 -1
  90. package/dist/io/xlsx/conditional-formatting.js +1 -97
  91. package/dist/io/xlsx/data-validation.js +0 -56
  92. package/dist/io/xlsx/edit-vba.js +0 -54
  93. package/dist/io/xlsx/errors.js +0 -12
  94. package/dist/io/xlsx/hyperlinks.js +0 -40
  95. package/dist/io/xlsx/images.js +0 -32
  96. package/dist/io/xlsx/namespaces.js +0 -42
  97. package/dist/io/xlsx/package-plan.js +0 -47
  98. package/dist/io/xlsx/pivot.js +0 -22
  99. package/dist/io/xlsx/{pivot-read.js → read-pivot.js} +0 -30
  100. package/dist/io/xlsx/read-rows.js +1 -83
  101. package/dist/io/xlsx/{shared-strings-read.js → read-shared-strings.js} +0 -11
  102. package/dist/io/xlsx/read-styles.d.ts +25 -1
  103. package/dist/io/xlsx/read-styles.js +61 -108
  104. package/dist/io/xlsx/read-worksheet.js +1 -88
  105. package/dist/io/xlsx/read.js +3 -211
  106. package/dist/io/xlsx/relationships.js +0 -11
  107. package/dist/io/xlsx/rich-runs.js +0 -16
  108. package/dist/io/xlsx/rich-text.js +0 -12
  109. package/dist/io/xlsx/shared-formulas.js +0 -7
  110. package/dist/io/xlsx/shared-strings.js +0 -21
  111. package/dist/io/xlsx/sheet-properties.js +1 -64
  112. package/dist/io/xlsx/styles.d.ts +1 -29
  113. package/dist/io/xlsx/styles.js +2 -366
  114. package/dist/io/xlsx/tables.js +5 -52
  115. package/dist/io/xlsx/threaded-comments.js +0 -103
  116. package/dist/io/xlsx/workbook-xml.js +0 -94
  117. package/dist/io/xlsx/worksheet-xml.js +0 -174
  118. package/dist/io/xlsx/write-stream.js +0 -137
  119. package/dist/io/xlsx/write.js +1 -134
  120. package/dist/io/xlsx/x14-ext.js +0 -8
  121. package/dist/vba/cfb-writer.js +12 -59
  122. package/dist/vba/cfb.js +2 -32
  123. package/dist/vba/codepage.js +1 -23
  124. package/dist/vba/errors.js +0 -15
  125. package/dist/vba/index.js +0 -10
  126. package/dist/vba/ms-ovba.js +3 -46
  127. package/dist/vba/project-editor.js +4 -89
  128. package/dist/vba/project.js +2 -34
  129. package/dist/vba/vba-encoding.js +1 -17
  130. package/dist/xml/errors.js +0 -10
  131. package/dist/xml/xml-read.js +3 -82
  132. package/dist/xml/xml.js +0 -39
  133. package/package.json +9 -10
  134. package/skills/ts-xlsx-upstream/SKILL.md +178 -0
  135. /package/dist/io/xlsx/{pivot-read.d.ts → read-pivot.d.ts} +0 -0
  136. /package/dist/io/xlsx/{shared-strings-read.d.ts → read-shared-strings.d.ts} +0 -0
@@ -1,24 +1,4 @@
1
- // The workbook theme's colour scheme — the twelve colours a `theme="n"` reference resolves against.
2
- //
3
- // The theme part itself is carried opaquely by the model (see `Workbook.restoreThemePart`); this
4
- // module reads just the `<a:clrScheme>` out of it, because that is the only piece a colour reference
5
- // needs. Everything else in a theme (the format scheme's gradients, line and effect styles) is
6
- // nobody's business here.
7
1
  import { AuthoringError } from '../errors.js';
8
- /**
9
- * The twelve colour-scheme slots **in the order a `theme="n"` attribute indexes them**.
10
- *
11
- * This order is not the order the slots appear in the theme part. ISO/IEC 29500 §20.1.6.2 documents
12
- * the `<a:clrScheme>` child sequence as `dk1, lt1, dk2, lt2, accent1…6, hlink, folHlink`, and that is
13
- * how the XML is written — but SpreadsheetML's `theme="n"` does **not** index that sequence. Excel
14
- * swaps each dark/light pair: index 0 is `lt1`, 1 is `dk1`, 2 is `lt2`, 3 is `dk2`.
15
- *
16
- * Verified against Excel Desktop rather than inferred, because the two orders differ only in the
17
- * first four entries and reading either one into the other silently inverts text against background
18
- * — see `docs/knowledge/specs/theme-color-index-order.md` and the recorded observation in
19
- * `test/corpus/fixtures/excel-oracle/theme-color-index-order.json`. The stylesheet's own default font
20
- * is the everyday witness: it carries `<color theme="1"/>` and renders black, which is `dk1`.
21
- */
22
2
  export const THEME_COLOR_SLOTS = [
23
3
  'lt1',
24
4
  'dk1',
@@ -33,7 +13,6 @@ export const THEME_COLOR_SLOTS = [
33
13
  'hlink',
34
14
  'folHlink',
35
15
  ];
36
- /** The Office default colour scheme, matching the theme part the writer emits for a workbook with none. */
37
16
  export const DEFAULT_THEME_COLOR_SCHEME = {
38
17
  lt1: 'FFFFFF',
39
18
  dk1: '000000',
@@ -48,21 +27,7 @@ export const DEFAULT_THEME_COLOR_SCHEME = {
48
27
  hlink: '0563C1',
49
28
  folHlink: '954F72',
50
29
  };
51
- // One `<a:slot>` of a `<a:clrScheme>` and the colour element inside it. Two colour models appear in
52
- // practice: `<a:srgbClr val="RRGGBB"/>` states the colour directly, while `<a:sysClr val="windowText"
53
- // lastClr="000000"/>` defers to an operating-system colour and records what it last resolved to.
54
- // `dk1`/`lt1` are almost always the sysClr form, so a reader that only understands srgbClr resolves
55
- // nothing for the two most-referenced slots in any workbook.
56
30
  const SCHEME_SLOT = new RegExp('<a:(dk1|lt1|dk2|lt2|accent[1-6]|hlink|folHlink)\\b[^>]*>' + '\\s*<a:(srgbClr|sysClr)\\b([^>]*)>', 'g');
57
- /**
58
- * Extract the colour scheme from a theme part. Returns only the slots the part actually declares in a
59
- * colour model this reader understands; an unrecognised one is dropped rather than guessed at, so a
60
- * caller can tell "the theme says nothing here" from "the theme says black".
61
- *
62
- * Reads the `<a:clrScheme>` block alone. A theme carries a font scheme and a format scheme too, but
63
- * neither participates in resolving a colour, and scanning the whole part would let a `<a:srgbClr>`
64
- * buried in a gradient stop masquerade as a scheme slot.
65
- */
66
31
  export function parseThemeColorScheme(themeXml) {
67
32
  const block = /<a:clrScheme\b[^>]*>([\s\S]*?)<\/a:clrScheme>/.exec(themeXml);
68
33
  if (block === null)
@@ -71,9 +36,6 @@ export function parseThemeColorScheme(themeXml) {
71
36
  for (const match of (block[1] ?? '').matchAll(SCHEME_SLOT)) {
72
37
  const slot = match[1];
73
38
  const attrs = match[3] ?? '';
74
- // A sysClr's `val` is a system-colour name ("windowText"), not a colour — its `lastClr` is the
75
- // concrete value the authoring application last resolved that name to, and is the only thing here
76
- // a consumer without the same OS theme can use.
77
39
  const source = match[2] === 'sysClr' ? /\blastClr="([^"]*)"/ : /\bval="([^"]*)"/;
78
40
  const value = source.exec(attrs)?.[1];
79
41
  if (value !== undefined && /^[0-9a-fA-F]{6}$/.test(value))
@@ -81,19 +43,11 @@ export function parseThemeColorScheme(themeXml) {
81
43
  }
82
44
  return scheme;
83
45
  }
84
- /**
85
- * The body typeface a workbook falls back to when neither its theme nor its styles part names one —
86
- * the face the default theme nominates, and so the face every `scheme="minor"` font resolves to.
87
- * Named rather than inlined because it is also the last resort of the default-font chain
88
- * ({@link Workbook.defaultFont}), and the two must not drift.
89
- */
90
46
  export const OFFICE_BODY_FACE = 'Calibri';
91
- /** The Office default typefaces, matching the theme part the writer emits for a workbook with none. */
92
47
  export const DEFAULT_THEME_FONTS = {
93
48
  major: 'Calibri Light',
94
49
  minor: OFFICE_BODY_FACE,
95
50
  };
96
- /** Extract the major/minor latin typefaces from a theme part's `<a:fontScheme>`. */
97
51
  export function parseThemeFontScheme(themeXml) {
98
52
  const block = /<a:fontScheme\b[^>]*>([\s\S]*?)<\/a:fontScheme>/.exec(themeXml);
99
53
  if (block === null)
@@ -111,9 +65,6 @@ export function parseThemeFontScheme(themeXml) {
111
65
  scheme.minor = minor;
112
66
  return scheme;
113
67
  }
114
- // The `<a:clrScheme>` child order — dk1, lt1, dk2, lt2, accent1..6, hlink, folHlink. Not the order
115
- // `theme="n"` indexes (see THEME_COLOR_SLOTS); this is the sequence CT_ColorScheme requires the
116
- // elements to be written in, and writing them in index order would be schema-invalid.
117
68
  const SCHEME_ELEMENT_ORDER = [
118
69
  'dk1',
119
70
  'lt1',
@@ -128,20 +79,6 @@ const SCHEME_ELEMENT_ORDER = [
128
79
  'hlink',
129
80
  'folHlink',
130
81
  ];
131
- /**
132
- * Apply authored colour/font overrides to a theme part, returning the new part text.
133
- *
134
- * Surgical by design: the base part rides through untouched except for the `<a:clrScheme>` and
135
- * `<a:fontScheme>` blocks, and within those, only what the caller actually named. The format scheme —
136
- * the gradients, line styles and effect styles that make a theme look like a theme — is left exactly
137
- * as it was, because nobody hand-authors `fillStyleLst` gradient stops from a spreadsheet API and
138
- * regenerating it would replace a designer's work with the Office default.
139
- *
140
- * A slot the caller did not override keeps its **verbatim source element**, not a re-serialisation of
141
- * its value. That matters for `dk1`/`lt1`, which Excel writes as `<a:sysClr val="windowText"
142
- * lastClr="000000"/>`: rewriting those as `<a:srgbClr>` would pin them to one machine's resolved
143
- * window colours and break dark-mode following.
144
- */
145
82
  export function applyThemeOverrides(baseXml, overrides) {
146
83
  let xml = baseXml;
147
84
  const colors = overrides.colors ?? {};
@@ -164,11 +101,6 @@ export function applyThemeOverrides(baseXml, overrides) {
164
101
  xml = replaceLatinTypeface(xml, 'minorFont', minor);
165
102
  return xml;
166
103
  }
167
- /**
168
- * Each colour slot's verbatim inner element from a theme part — `<a:srgbClr val="…"/>` or
169
- * `<a:sysClr val="…" lastClr="…"/>`. The value-level counterpart is {@link parseThemeColorScheme};
170
- * this keeps the *encoding* so an untouched slot can be re-emitted exactly as the source wrote it.
171
- */
172
104
  export function parseThemeColorElements(themeXml) {
173
105
  const block = /<a:clrScheme\b[^>]*>([\s\S]*?)<\/a:clrScheme>/.exec(themeXml);
174
106
  if (block === null)
@@ -183,10 +115,6 @@ export function parseThemeColorElements(themeXml) {
183
115
  }
184
116
  return elements;
185
117
  }
186
- // A theme colour is a bare 6-hex RGB — DrawingML has no alpha channel on `<a:srgbClr val>`. The two
187
- // conveniences the rest of the library accepts (a leading '#', an 8-hex ARGB) are accepted and
188
- // reduced here; anything else is a caller's bug and is refused rather than written as corrupt XML,
189
- // which Excel does not report — it renders the slot as flat black.
190
118
  function normalizeSchemeValue(value) {
191
119
  const hex = value.startsWith('#') ? value.slice(1) : value;
192
120
  const rgb = hex.length === 8 ? hex.slice(2) : hex;
@@ -195,15 +123,10 @@ function normalizeSchemeValue(value) {
195
123
  }
196
124
  return rgb.toUpperCase();
197
125
  }
198
- // Replace the body of `<a:name>…</a:name>`, keeping the element's own attributes (the scheme's
199
- // display name). A base with no such block is left alone: this authors an existing theme, and a theme
200
- // that declares no colour scheme at all is not one an override can repair.
201
126
  function replaceBlockBody(xml, name, body) {
202
127
  const pattern = new RegExp(`(<a:${name}\\b[^>]*>)[\\s\\S]*?(</a:${name}>)`);
203
128
  return xml.replace(pattern, (_all, open, close) => `${open}${body}${close}`);
204
129
  }
205
- // Swap just the `<a:latin typeface="…"/>` inside one of the two font slots, leaving its `panose` and
206
- // the east-asian/complex-script faces beside it as they were.
207
130
  function replaceLatinTypeface(xml, which, typeface) {
208
131
  const pattern = new RegExp(`(<a:${which}\\b[^>]*>[\\s\\S]*?<a:latin\\b)[^>]*(/>)`);
209
132
  return xml.replace(pattern, (_all, open, close) => `${open} typeface="${escapeXmlAttr(typeface)}"${close}`);
@@ -215,14 +138,6 @@ function escapeXmlAttr(value) {
215
138
  .replace(/>/g, '&gt;')
216
139
  .replace(/"/g, '&quot;');
217
140
  }
218
- /**
219
- * The theme part a workbook with no theme of its own ships — the standard Office theme.
220
- *
221
- * A spreadsheet must carry one even when nobody configured it: the stylesheet's own default font
222
- * references `theme="1"`, which a consumer can only resolve against this part, so the two travel
223
- * together. It is also the base {@link applyThemeOverrides} authors on top of when a workbook was
224
- * built from scratch rather than read from a file.
225
- */
226
141
  export const DEFAULT_THEME_XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
227
142
  '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">' +
228
143
  '<a:themeElements>' +
@@ -81,11 +81,32 @@ export interface DataTableFormulaValue {
81
81
  }
82
82
  /** Everything a cell's value can be. `null` is the empty cell. */
83
83
  export type CellValue = null | number | string | boolean | Date | ErrorValue | FormulaValue | SharedFormulaValue | DataTableFormulaValue | RichTextValue | HyperlinkValue;
84
+ /**
85
+ * Whether a value is an in-cell error ({@link ErrorValue}). The narrowing counterpart of
86
+ * `detectValueType(value) === ValueType.Error`: use this one when the branch goes on to read
87
+ * `.error`, and {@link detectValueType} when it dispatches over all nine kinds at once.
88
+ */
84
89
  export declare function isErrorValue(value: CellValue): value is ErrorValue;
90
+ /**
91
+ * Whether a value is a cell's own formula ({@link FormulaValue}) — a master, or a formula
92
+ * belonging to no shared group. A shared-formula clone is **not** one of these; see
93
+ * {@link isSharedFormulaValue}. Both report as `ValueType.Formula`, so a caller that means "any
94
+ * formula-shaped cell" wants {@link detectValueType}, not this.
95
+ */
85
96
  export declare function isFormulaValue(value: CellValue): value is FormulaValue;
97
+ /** Whether a value is a clone participating in a shared formula ({@link SharedFormulaValue}). */
86
98
  export declare function isSharedFormulaValue(value: CellValue): value is SharedFormulaValue;
99
+ /** Whether a value is a What-If-Analysis data-table formula ({@link DataTableFormulaValue}). */
87
100
  export declare function isDataTableFormulaValue(value: CellValue): value is DataTableFormulaValue;
101
+ /**
102
+ * Whether a value is composed of formatted runs ({@link RichTextValue}). This is the test to
103
+ * make before {@link richTextToPlain}, which accepts nothing else.
104
+ */
88
105
  export declare function isRichTextValue(value: CellValue): value is RichTextValue;
106
+ /**
107
+ * Whether a value is a hyperlink ({@link HyperlinkValue}). Note that its `text` is itself either
108
+ * a string or a {@link RichTextValue}, so reading the label out means one more narrowing.
109
+ */
89
110
  export declare function isHyperlinkValue(value: CellValue): value is HyperlinkValue;
90
111
  /**
91
112
  * Flatten a rich-text value to its plain text by concatenating every run's text in order. This is the
@@ -93,6 +114,25 @@ export declare function isHyperlinkValue(value: CellValue): value is HyperlinkVa
93
114
  * the string a rich cell reads as when its formatting is discarded.
94
115
  */
95
116
  export declare function richTextToPlain(value: RichTextValue): string;
117
+ /**
118
+ * The plain text of any cell value — total over {@link CellValue}, so a caller reading a sheet
119
+ * whose cells it did not write never has to switch on the union itself.
120
+ *
121
+ * This is the *value's* text, not the cell's *display* text: a number renders as JavaScript
122
+ * renders it, with no number format applied (`0.1 + 0.2` is `"0.30000000000000004"`, a currency
123
+ * cell has no currency sign), because the format lives on the style and this function is given
124
+ * only the value. What each kind yields:
125
+ *
126
+ * - the empty cell (`null`) and an invalid `Date` → `""`, the two ways a cell has no text
127
+ * - a boolean → `"TRUE"` / `"FALSE"`, Excel's own literals rather than JavaScript's
128
+ * - a `Date` → a full ISO-8601 timestamp
129
+ * - an error → its literal, e.g. `"#REF!"` — the same string the grid shows
130
+ * - rich text → every run concatenated ({@link richTextToPlain})
131
+ * - a hyperlink → its label, never its destination
132
+ * - any of the three formula kinds → the text of the *cached result*, and `""` when the cell
133
+ * carries no cached result: the formula source is not text the sheet ever displayed
134
+ */
135
+ export declare function cellValueToText(value: CellValue): string;
96
136
  /**
97
137
  * Classify a value into its observable {@link ValueType}. This is total over
98
138
  * {@link CellValue}: every legal value has exactly one type. A `Date` is a date even
@@ -1,13 +1,3 @@
1
- // The cell value model — the second bedrock primitive after addressing.
2
- //
3
- // A cell holds exactly one value, and that value's *type* is observable and drives
4
- // everything downstream (serialization, number-format application, formula results).
5
- // The honest shape here is a discriminated union: a value is either a JS primitive
6
- // (null / number / string / boolean / Date) or one of the structural OOXML value
7
- // shapes (error, formula, shared formula, rich text, hyperlink). There is no
8
- // stringly-typed sentinel and no silent coercion between kinds — a numeric-looking
9
- // string stays a string, because the caller's chosen type is the source of truth.
10
- /** The observable kind of a cell's value. Both formula shapes report as `Formula`. */
11
1
  export const ValueType = {
12
2
  Null: 'null',
13
3
  Number: 'number',
@@ -19,7 +9,6 @@ export const ValueType = {
19
9
  RichText: 'richText',
20
10
  Hyperlink: 'hyperlink',
21
11
  };
22
- /** The canonical Excel error literals a cell (or formula result) can carry. */
23
12
  export const ERROR_CODES = [
24
13
  '#N/A',
25
14
  '#REF!',
@@ -33,8 +22,6 @@ export const ERROR_CODES = [
33
22
  '#GETTING_DATA',
34
23
  ];
35
24
  const ERROR_SET = new Set(ERROR_CODES);
36
- // Whether a value is a non-null object carrying `key` — the object-shaped {@link CellValue} kinds are all
37
- // discriminated by the presence of a single property, so every guard below narrows through this one test.
38
25
  function hasKey(value, key) {
39
26
  return typeof value === 'object' && value !== null && key in value;
40
27
  }
@@ -42,8 +29,6 @@ export function isErrorValue(value) {
42
29
  return hasKey(value, 'error');
43
30
  }
44
31
  export function isFormulaValue(value) {
45
- // A shared-formula clone resolved on read carries both its master address (`sharedFormula`) and the
46
- // translated `formula`; it is a SharedFormulaValue, so exclude it here to keep the two kinds distinct.
47
32
  return hasKey(value, 'formula') && !('sharedFormula' in value);
48
33
  }
49
34
  export function isSharedFormulaValue(value) {
@@ -58,20 +43,36 @@ export function isRichTextValue(value) {
58
43
  export function isHyperlinkValue(value) {
59
44
  return hasKey(value, 'hyperlink');
60
45
  }
61
- /**
62
- * Flatten a rich-text value to its plain text by concatenating every run's text in order. This is the
63
- * text a consumer that cannot render per-run formatting (a CSV field, a pivot cache entry) sees, and
64
- * the string a rich cell reads as when its formatting is discarded.
65
- */
66
46
  export function richTextToPlain(value) {
67
47
  return value.richText.map((run) => run.text).join('');
68
48
  }
69
- /**
70
- * Classify a value into its observable {@link ValueType}. This is total over
71
- * {@link CellValue}: every legal value has exactly one type. A `Date` is a date even
72
- * when its time is `NaN` (an invalid date is still a date-typed cell); serialization,
73
- * not the model, decides what to do with it.
74
- */
49
+ export function cellValueToText(value) {
50
+ if (value === null)
51
+ return '';
52
+ switch (typeof value) {
53
+ case 'number':
54
+ return String(value);
55
+ case 'string':
56
+ return value;
57
+ case 'boolean':
58
+ return value ? 'TRUE' : 'FALSE';
59
+ default:
60
+ break;
61
+ }
62
+ if (value instanceof Date)
63
+ return Number.isNaN(value.getTime()) ? '' : value.toISOString();
64
+ if (isHyperlinkValue(value)) {
65
+ return typeof value.text === 'string' ? value.text : richTextToPlain(value.text);
66
+ }
67
+ if (isFormulaValue(value) || isSharedFormulaValue(value) || isDataTableFormulaValue(value)) {
68
+ return value.result === undefined ? '' : cellValueToText(value.result);
69
+ }
70
+ if (isRichTextValue(value))
71
+ return richTextToPlain(value);
72
+ if (isErrorValue(value))
73
+ return value.error;
74
+ return unsupportedValue(value);
75
+ }
75
76
  export function detectValueType(value) {
76
77
  if (value === null)
77
78
  return ValueType.Null;
@@ -87,8 +88,6 @@ export function detectValueType(value) {
87
88
  }
88
89
  if (value instanceof Date)
89
90
  return ValueType.Date;
90
- // Order matters: a hyperlink whose text is rich must classify as Hyperlink, and a
91
- // formula carrying a result must classify as Formula — check the outer shape first.
92
91
  if (isHyperlinkValue(value))
93
92
  return ValueType.Hyperlink;
94
93
  if (isFormulaValue(value) || isSharedFormulaValue(value) || isDataTableFormulaValue(value)) {
@@ -98,9 +97,11 @@ export function detectValueType(value) {
98
97
  return ValueType.RichText;
99
98
  if (isErrorValue(value))
100
99
  return ValueType.Error;
100
+ return unsupportedValue(value);
101
+ }
102
+ function unsupportedValue(value) {
101
103
  throw new TypeError(`unsupported cell value: ${describe(value)}`);
102
104
  }
103
- /** Whether a string is one of Excel's canonical error literals. */
104
105
  export function isErrorCode(text) {
105
106
  return ERROR_SET.has(text);
106
107
  }
@@ -110,35 +111,16 @@ function describe(value) {
110
111
  }
111
112
  return String(value);
112
113
  }
113
- /**
114
- * Normalise a raw assignment into a stored {@link CellValue}. `undefined` becomes the
115
- * empty cell (`null`); every other kind is validated by {@link detectValueType}. The
116
- * model never rewrites one value *kind* into another (a numeric-looking string stays a
117
- * string) — the single exception is formula text, which is canonicalised to the OOXML
118
- * stored form (no leading `=`) so round-trips are idempotent regardless of how the
119
- * caller supplied it.
120
- *
121
- * @throws {TypeError} if the value is not a recognised cell-value shape.
122
- */
123
114
  export function coerceCellValue(value) {
124
115
  if (value === undefined)
125
116
  return null;
126
- // detectValueType throws on an unrecognised object shape, so this both validates
127
- // and gives a precise error at the assignment site rather than deep in serialization.
128
117
  detectValueType(value);
129
118
  if (isFormulaValue(value)) {
130
119
  const formula = stripLeadingEquals(value.formula);
131
120
  return formula === value.formula ? value : { ...value, formula };
132
121
  }
133
- // A shared formula's `sharedFormula` is a master cell address, not formula text, so there is no
134
- // leading `=` to canonicalise — it passes through as given.
135
122
  return value;
136
123
  }
137
- /**
138
- * OOXML stores a formula's text in `<f>` without the UI's leading `=`. Strip a single
139
- * leading `=` so the stored form is canonical and a strict consumer (Google Sheets,
140
- * WPS) — which rejects a stored formula beginning with `=` — accepts the file.
141
- */
142
124
  function stripLeadingEquals(formula) {
143
125
  return formula.startsWith('=') ? formula.slice(1) : formula;
144
126
  }
@@ -1,16 +1,3 @@
1
- // Workbook-level protection: the `<workbookProtection>` element in CT_Workbook that locks the
2
- // workbook's *structure* (sheets cannot be added, deleted, reordered, or unhidden) and/or its
3
- // *windows*. It is distinct from worksheet-level `<sheetProtection>` — that guards a single sheet's
4
- // cells; this guards the workbook shell. A weak integrity signal, but a real one: dropping it on a
5
- // passthrough save silently unlocks a file the author locked, so the model preserves it faithfully.
6
- /**
7
- * The password/agile-hash attributes a `<workbookProtection>` element may carry, preserved verbatim
8
- * so a hash-guarded workbook round-trips without the library ever interpreting the credential. Both
9
- * the legacy 16-bit `*Password` hashes and the modern agile `*AlgorithmName`/`*HashValue`/
10
- * `*SaltValue`/`*SpinCount` quartets appear here, for the structure guard (`workbook*`) and the
11
- * revisions guard (`revisions*`). The reader accepts only these names, so a hostile or unknown
12
- * attribute is never echoed back into the output.
13
- */
14
1
  export const WORKBOOK_PROTECTION_CREDENTIAL_ATTRS = [
15
2
  'workbookPassword',
16
3
  'workbookAlgorithmName',
@@ -444,6 +444,19 @@ export declare class Workbook {
444
444
  addWorksheet(name: string, options?: AddWorksheetOptions): Worksheet;
445
445
  /** Look up a worksheet by name (case-insensitive) or by numeric id. */
446
446
  getWorksheet(nameOrId: string | number): Worksheet | undefined;
447
+ /**
448
+ * {@link getWorksheet}, for a caller who knows the sheet is there — the miss throws instead of
449
+ * returning `undefined`, and the message names every sheet the workbook does have.
450
+ *
451
+ * The partial lookup is the right primitive for asking *whether* a sheet exists, and the wrong
452
+ * one for reaching a sheet a template is expected to carry: `undefined` flows on into a `?.`
453
+ * chain and fails several steps later with nothing left to say about which name was missing.
454
+ * That listing is the whole point — a lookup miss is a typo, a stale template or a renamed tab,
455
+ * and all three are answered by seeing the real names.
456
+ *
457
+ * @throws {AuthoringError} if no worksheet has that name (case-insensitive) or numeric id.
458
+ */
459
+ requireWorksheet(nameOrId: string | number): Worksheet;
447
460
  /**
448
461
  * The codec's channel into this workbook — see `core/internal.ts` for why these are not public
449
462
  * methods. Declared last so every private field it closes over is already in scope.