@kition/kit-sheet-ui 0.0.0-stage → 0.1.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 (46) hide show
  1. package/package.json +40 -4
  2. package/sheet-ui/LICENSE +177 -0
  3. package/sheet-ui/NOTICE +73 -0
  4. package/sheet-ui/THIRD_PARTY_NOTICES.txt +8905 -0
  5. package/sheet-ui/agent/checks.json +56 -0
  6. package/sheet-ui/agent/guide.md +340 -0
  7. package/sheet-ui/assets/dev-D8UCHOb0.js +1 -0
  8. package/sheet-ui/assets/index-CcQhqOwu.css +1 -0
  9. package/sheet-ui/assets/index-DblcoJ90.js +1 -0
  10. package/sheet-ui/assets/index-Dl4Hu9Cv.js +98 -0
  11. package/sheet-ui/assets/kitEngine.worker-9PIHJagj-Dwbox6hp.js +13020 -0
  12. package/sheet-ui/assets/ko-Fe7YrdBh.js +274 -0
  13. package/sheet-ui/assets/pt-BK3ToRXt.js +275 -0
  14. package/sheet-ui/assets/ru-Di_jxcA2.js +274 -0
  15. package/sheet-ui/assets/symbolNames--e2SA9f6.js +3120 -0
  16. package/sheet-ui/assets/zh-C0AkZS0b.js +274 -0
  17. package/sheet-ui/engine/kition_sheet_kit.js +1126 -0
  18. package/sheet-ui/engine/kition_sheet_kit_bg.wasm +0 -0
  19. package/sheet-ui/fonts/Arimo-Italic-Variable.ttf +0 -0
  20. package/sheet-ui/fonts/Arimo-Variable.ttf +0 -0
  21. package/sheet-ui/fonts/Caladea-Bold.ttf +0 -0
  22. package/sheet-ui/fonts/Caladea-BoldItalic.ttf +0 -0
  23. package/sheet-ui/fonts/Caladea-Italic.ttf +0 -0
  24. package/sheet-ui/fonts/Caladea-Regular.ttf +0 -0
  25. package/sheet-ui/fonts/Carlito-Bold.ttf +0 -0
  26. package/sheet-ui/fonts/Carlito-BoldItalic.ttf +0 -0
  27. package/sheet-ui/fonts/Carlito-Italic.ttf +0 -0
  28. package/sheet-ui/fonts/Carlito-Regular.ttf +0 -0
  29. package/sheet-ui/fonts/Cousine-Regular.ttf +0 -0
  30. package/sheet-ui/fonts/DroidSansFallback-NOTICE.txt +190 -0
  31. package/sheet-ui/fonts/DroidSansFallbackFull.ttf +0 -0
  32. package/sheet-ui/fonts/MaShanZheng-Regular.ttf +0 -0
  33. package/sheet-ui/fonts/Tinos-Bold.ttf +0 -0
  34. package/sheet-ui/fonts/Tinos-Italic.ttf +0 -0
  35. package/sheet-ui/fonts/Tinos-Regular.ttf +0 -0
  36. package/sheet-ui/fonts/arimo-OFL.txt +93 -0
  37. package/sheet-ui/fonts/caladea-OFL.txt +93 -0
  38. package/sheet-ui/fonts/carlito-OFL.txt +94 -0
  39. package/sheet-ui/fonts/cousine-OFL.txt +93 -0
  40. package/sheet-ui/fonts/ma-shan-zheng-OFL.txt +93 -0
  41. package/sheet-ui/fonts/tinos-OFL.txt +93 -0
  42. package/sheet-ui/index.html +14 -0
  43. package/sheet-ui/kit-ui.json +1 -0
  44. package/sheet-ui/kit.json +244 -0
  45. package/sheet-ui/model/schema.json +275 -0
  46. package/README.md +0 -3
@@ -0,0 +1,56 @@
1
+ [
2
+ {
3
+ "code": "sheet.formula-error",
4
+ "severity": "error",
5
+ "summary": "A formula ends in an error value (#DIV/0!, #VALUE!, #REF!, \u2026); #N/A is reported as a warning.",
6
+ "fixture": "check-formula-error.xlsx"
7
+ },
8
+ {
9
+ "code": "sheet.circular-reference",
10
+ "severity": "error",
11
+ "summary": "A formula refers to itself, directly or through other cells.",
12
+ "fixture": "check-circular-reference.xlsx"
13
+ },
14
+ {
15
+ "code": "sheet.broken-name",
16
+ "severity": "error",
17
+ "summary": "A defined name points nowhere: #REF!, a missing sheet, or a scope sheet that does not exist.",
18
+ "fixture": "check-broken-name.xlsx"
19
+ },
20
+ {
21
+ "code": "sheet.overlapping-merges",
22
+ "severity": "error",
23
+ "summary": "Two merged ranges overlap, which Excel refuses to open cleanly.",
24
+ "fixture": "check-overlapping-merges.xlsx"
25
+ },
26
+ {
27
+ "code": "sheet.merge-hides-data",
28
+ "severity": "warning",
29
+ "summary": "A merged range covers cells with values that only its top-left cell shows.",
30
+ "fixture": "check-merge-hides-data.xlsx"
31
+ },
32
+ {
33
+ "code": "sheet.reference-outside-data",
34
+ "severity": "warning",
35
+ "summary": "A formula reads a single empty cell beyond its sheet's data, often a typo in a reference.",
36
+ "fixture": "check-reference-outside-data.xlsx"
37
+ },
38
+ {
39
+ "code": "sheet.font-substituted",
40
+ "severity": "info",
41
+ "summary": "Cells are set in a font the renderer has no face for, so they are drawn in its built-in face and take other widths than in Excel: add the font, or for an Office font its metric-compatible stand-in (Carlito for Calibri). An Office font drawn in the built-in face while the host has added no fonts at all is the kit's own fallback and is not reported.",
42
+ "fixture": "check-font-substituted.xlsx"
43
+ },
44
+ {
45
+ "code": "sheet.missing-glyph",
46
+ "severity": "warning",
47
+ "summary": "A cell's text has characters no face the renderer has draws (such as \u2713 or \u2717 in Carlito); they show as empty boxes.",
48
+ "fixture": "check-missing-glyph.xlsx"
49
+ },
50
+ {
51
+ "code": "sheet.truncated",
52
+ "severity": "info",
53
+ "summary": "A code was found more than 100 times; the rest are counted, not listed.",
54
+ "fixture": "check-truncated.xlsx"
55
+ }
56
+ ]
@@ -0,0 +1,340 @@
1
+ # Sheet kit
2
+
3
+ The Sheet kit opens, edits and checks Excel workbooks (`.xlsx`) with Excel's commands and formula
4
+ engine. An agent can read and write cells and formulas, format, sort and filter ranges, work with
5
+ tables, charts and pivot tables, check the workbook for formula errors and broken names, and export
6
+ it to PDF, CSV or HTML.
7
+
8
+ ## Tools
9
+
10
+ The kit's prefix is `sheet`. Its tools are:
11
+
12
+ | Tool | Does |
13
+ |---|---|
14
+ | `sheet_inspect` | The workbook as JSON (its sheets, the used range and the values), with a preview |
15
+ | `sheet_query` | Reads objects of the workbook's object model by id, or by following fields from the root |
16
+ | `sheet_commands` | Finds commands by keywords, each with its parameter schema |
17
+ | `sheet_run` | Runs a list of command steps |
18
+ | `sheet_batch` | Runs one batch of object-model operations |
19
+ | `sheet_check` | What is wrong with the workbook, as diagnostics |
20
+ | `sheet_create` | Makes a new `.xlsx` workbook |
21
+ | `sheet_export` | Writes the workbook to a new PDF, CSV or HTML file |
22
+ | `sheet_draft_ready`, `sheet_draft_reopen` | Asks the person to review your draft, or takes it back to edit |
23
+
24
+ Every tool takes `path`, the workbook's path in the workspace. With `draft: true` your edits go to
25
+ your draft of the workbook and leave the file as it is; only the person merges or discards a draft.
26
+
27
+ The kit reads and writes only the workbook Kition opened for you. Commands that name a file by
28
+ path (`file.open`, `file.save`, `data.getData`, `insert.picture`, …) are not offered: enter data
29
+ with `range.setValues`, or CSV text with `data.fromTextCsv {text}`, and write files with
30
+ `sheet_export`. A stored script (`automate.runScript`) runs only steps you could run yourself; one
31
+ that names a file is refused before any step runs. Spelling (`review.spelling`) is not available.
32
+
33
+ ## Addressing, ids and coordinates
34
+
35
+ - **Sheets have ids.** `sheet_inspect` lists every sheet in `details.workbook.sheets`, whatever
36
+ sheet the person has open: `{"id": 2, "toolId": "sheet:2", "name": "Notes", "index": 1, "hidden":
37
+ false, "used": "A1:D9", "drawings": [{"id": 5, "toolId": "drawing:5", "kind": "chart", "at":
38
+ "E2"}]}`. The id stays when the sheet is renamed or moved and when the file is saved and opened
39
+ again; the name and the position (`index`, from 0) do not. Name a sheet by its tool id
40
+ (`"sheet:2"`) or its name, never by its position.
41
+ - **Drawing objects have ids.** Shapes, text boxes, groups, charts and pictures are
42
+ `drawing:<id>`, unique in the workbook and kept through save and reopen. Groups are member
43
+ sets with a read-only identity object, without a stored parent transform. Commands' `id`, `ids`
44
+ and `chart` take the tool id (`"drawing:5"`), and a tool id names its sheet.
45
+ - **Cells are addressed in A1 notation** on a sheet: `B2`, `A1:D10`, a cell of another sheet
46
+ `Data!B2` (`'My Sheet'!B2` when the name has spaces). Rows count from **1** and columns from
47
+ **A**, as in Excel; no command takes a 0-based cell index. An address is a position: inserting
48
+ or deleting rows or columns moves the cells after them, and their addresses with them. A
49
+ receipt names the rows or columns created or deleted, on which sheet, at which index.
50
+ It currently also lists changed cell address/label metadata; read the range again after a shift.
51
+ Object-model cells use positional tool addresses (`cell:1!B7`, with the sheet id), and labels
52
+ such as `Data!B7`. These are addresses, not identities that follow cell content across a shift.
53
+ - **Defined names** have `name:<id>` tool ids, preserved on rename and save/reopen.
54
+ Names, row/column identities, deleted axis markers and cell provenance are stored in the
55
+ workbook's Kition identity part. Row/column ids follow the axis; a cell tool address remains positional.
56
+ - **Tables and pivots** have `table:<sheetId>:<id>` and `pivot:<sheetId>:<id>` tool ids.
57
+ Sheet `tableObjects`, `pivotObjects` and `groups` expose read-only identity indexes; their
58
+ authoritative content remains in sheet feature registers. Commands accept table/pivot tool ids
59
+ through rename and save/reopen. Workbook `styleObjects` names immutable interned styles by
60
+ content hash (`style:<hash>`), named cell styles by definition name (`style:cell:<hash>`), and
61
+ named table styles by their native UID (`style:table:<uid>`). Table-style rename preserves
62
+ that UID; redefining a cell style preserves its id. Commands that apply or modify existing
63
+ styles take those named tool ids. Cell styles have no rename command. Named-style keys follow
64
+ the engine's ASCII case comparison, so distinct non-ASCII names remain independent.
65
+ - **Commands' `sheet`** takes a sheet's name or tool id (or a position from 0, which changes when
66
+ sheets move: avoid it). A range with a sheet (`Data!B2`) names its sheet too.
67
+ - `sheet_inspect` answers a sheet's values as `content.rows`: each row starts with its row number,
68
+ counted from 1, then the cell **values**. A formula cell shows its computed value, not its
69
+ formula: `[5, "Total", 300.0]` may be `=SUM(B2:B4)`. Without `target` it shows the start of the
70
+ sheet the file opens on; `target: {"sheet": "sheet:2", "range": "A1:F40"}` shows that sheet and
71
+ range without making the sheet active.
72
+ - Diagnostics name their `sheet` and `cell` (or range) in `target`.
73
+
74
+ ## Where a step acts: `target`, `at` and `on`
75
+
76
+ Nothing a call does depends on, or leaves behind, the sheet or cells the person has active or
77
+ selected: name them.
78
+
79
+ - A `sheet_run` step is `{command, params?, on?, at?}`. The run's `target` (`{"sheet": …}`) is the
80
+ sheet every step acts in; a step's `at.part` (`{"sheet": …}`) overrides it for that step. A
81
+ sheet is `{"sheet": 2}` (its id), `{"sheet": "sheet:2"}` or `{"sheet": "Notes"}`; never a
82
+ position.
83
+ - `on` names what the step acts on: **cells** as A1 ranges (`["B2:D10"]`, or `["Notes!B2:D10"]`,
84
+ whose sheet must be the step's) **or drawing objects** by id (`["drawing:5"]`), never both in one
85
+ step. It goes into the command's own parameter for it (`range`, `cell`, `ids`, `id` or `chart`:
86
+ `sheet_commands` with `detail` marks it as the command's `targets`; then do not give that
87
+ parameter too), or, for a command that acts on the selection (`reads: selection`), it is
88
+ selected for that step only. Cells in `on` without a sheet need `target` or `at.part` when the
89
+ workbook has more than one sheet. A command whose parameter takes one range takes one `on` item.
90
+ - A command given its sheet or range (`sheet`, `Data!B2`, a drawing's tool id) acts there and
91
+ leaves the active sheet and the selection as they were, also when it fails. Only the commands
92
+ whose work is moving the editor (`sheet.activate`, `selection.set`, `view.*`) move it, and the
93
+ editor is put back after the call: a later call starts again from the person's sheet.
94
+ - A sheet you insert (`home.insertSheet`) is where the next steps of the same run land when they
95
+ name no sheet, so "insert a sheet, then fill it" works in one run; name it in later calls.
96
+ - The file saves the person's active sheet and cell, never where the run worked.
97
+
98
+ ## Previews of a named range
99
+
100
+ `sheet_inspect` with `"preview": true` draws `target`: `{"sheet": "sheet:2", "range": "A1:H30"}`
101
+ (the sheet's name or tool id; the range in A1). Without a sheet it draws the first sheet, never the
102
+ active one; without a range, the sheet's used range, cut to 5000 cells (`preview.capped` says so,
103
+ with `usedRange`). The picture has the row numbers and column letters, so read addresses off it.
104
+ `scale` (at most 4) and `maxSize` (the longest side in pixels) set its size. A range of more than
105
+ 5000 cells is refused: ask for a smaller one, and read values with `sheet.read`. The same call
106
+ answers the same picture.
107
+
108
+ ## What a call changed, and what others changed
109
+
110
+ - **Receipts.** A successful `sheet_run` or `sheet_batch` answers `changes`: `created`, `changed`
111
+ (with `edits` and available field `before`/`after` values), `moved` and `deleted`, naming sheets
112
+ (`sheet:2`) and drawing objects (`drawing:5`) by the ids `sheet_inspect` lists, and
113
+ `diagnostics: {new, resolved}`. Cell edits name their positional cell object; read the range
114
+ back with `sheet.read` to see the values. Inserted rows have `row:` ids and an `at` location
115
+ with their parent sheet and index. Positional cell address/label edits accompany the shift.
116
+ - **Pass the latest `revision` as `basis`.** Every answer of inspect, query, run and batch has a
117
+ short `revision`. Pass the last one you were given as `basis` on your next call: the answer then
118
+ says what others (people, other agents, changes made in the file) changed since, in `others`
119
+ (with `by`).
120
+ - **A `conflict`** (retryable) means others changed what the write acts on since your `basis` (it
121
+ was `deleted`, `relocated` or `changed`, or the file changed in a way the server cannot describe
122
+ object by object, `unknown`). Nothing was run. Read `others` and `conflicts`, inspect again if you
123
+ need to, decide again, and send the call with the `revision` the refusal gives as `basis`. Do not
124
+ undo others' changes. The same-field decision includes the value an absolute assignment
125
+ replaces. Another unassigned field is unrelated to that assignment; the coverage limits below
126
+ describe remaining conservative premises. Your own earlier edits are accounted for when
127
+ checking premises. If rereading the file deletes the observed recipient, a stale write
128
+ refuses `deleted` even when the reread was triggered by your own call.
129
+
130
+ ## Premise coverage and limits
131
+
132
+ The engine uses the public kition-sdk revision pinned in its Cargo manifest.
133
+ Commands declare typed references, editor reads, source and destination values,
134
+ and address windows. Bounded entry, formatting, table, filter, outline and drawing
135
+ paths have narrower holds; complex operations retain conservative workbook holds.
136
+ Those holds can refuse changes outside the actual inputs. The fact comparison
137
+ projects every retained handler-reading path into content, identity, position
138
+ and address facts and compares both directions against its declaration.
139
+ Every registered write is represented. The binding entry supplement is labelled
140
+ separately from the original blind families. Missing facts are rejected;
141
+ conservative excess holds have decreasing per-path and per-class limits.
142
+
143
+ Receipts include proven public derived changes. Private comparison facts remain
144
+ available to conflict checks; their names and values are excluded from public
145
+ creation, change and deletion receipts.
146
+ Replica commands that replace the workbook continue with the replacement.
147
+ Conditional-rule clears compare historical coverage even when an outside axis shift
148
+ moves a previously selected rule out of the requested range.
149
+
150
+ Picking up the format painter holds its source range rather than unrelated drawing
151
+ objects. Setting an object's anchor mode holds the observed mode while permitting
152
+ geometry changes. Arithmetic formula entry holds source values without holding their display
153
+ formatting; metadata queries such as `CELL` retain the formats they read.
154
+
155
+ Automatic row fitting holds height contributions, wrapping inputs and assigned styles;
156
+ plain neighboring values and colors can remain unrelated. Checkbox creation on a named
157
+ sheet follows that sheet through unrelated tab insertion. Alignment holds source frames
158
+ and the row and column prefixes used to convert its result anchors, while permitting
159
+ unrelated fill changes and geometry edits beyond those prefixes.
160
+ Multi-cell Bold retains a conservative whole-row guard. Duplicate removal also
161
+ holds comparison columns outside its table, and image alignment holds image anchors.
162
+
163
+ Absolute assignments hold the observed value they replace. When a colleague
164
+ changes that field after observation, assigning it again refuses `changed`.
165
+ A field the command preserves can remain unrelated. An address whose occupant
166
+ moves refuses `relocated`; deletion of the observed recipient refuses `deleted`.
167
+ Reobserve and decide again after either refusal.
168
+
169
+ Formula entry holds referenced cells, names, table definitions and the address
170
+ windows needed to interpret them. Source creation in a previously empty cell is
171
+ also a change. Positional insertion windows detect removals and moves before a
172
+ gap while allowing changes after an addressed window.
173
+
174
+ `chart.shapeFill` has conditional parameters: use `id` with
175
+ `kind:"shape"`, and `chart` for the chart-series branch. Its ambiguous
176
+ `on` form with `kind:"shape"` is refused. Chart-series `on` remains supported.
177
+ Explicit tool IDs remain the clearest way to name the
178
+ recipient.
179
+
180
+ Outside file rereads reconcile the canonical file model into the retained
181
+ replica. Persisted row and object identities, editor state and undo histories
182
+ survive that import. A deleted active sheet or selected drawing refuses rather
183
+ than selecting an unrelated replacement. Undo after reobservation reverses the
184
+ agent's own edit while retaining unrelated outside edits.
185
+
186
+ Planning dependent steps uses an isolated replica with editor state, blobs,
187
+ clipboard content and the captured Format Painter source.
188
+ Earlier creation and selection steps determine later steps' premises. The
189
+ planned copy is discarded before the real write. Unsupported or unprovable
190
+ inputs can still refuse conservatively.
191
+
192
+ Owning cell maps declare their member type, translate references to public tool
193
+ IDs and participate in environment snapshots. Sampling excludes image
194
+ containers. Environment replay supplies the recorded identity bindings when a
195
+ creation allocates fresh IDs.
196
+
197
+ Raw object-model operations declare premise contracts. Raw `Cell.input`
198
+ assignments use `cell.set`'s source premises, while execution remains a raw
199
+ assignment followed by model settling. Use commands for semantic operations;
200
+ read-only identity indexes remain read-only.
201
+
202
+ A successful close can return `{closed:true}` without a document view. A
203
+ receipt edit may omit `before` or `after` when that value is unavailable;
204
+ an absent value does not mean JSON `null`. Query the affected range or object
205
+ when a complete value is needed.
206
+
207
+ ## Workflow
208
+
209
+ 1. Inspect the workbook and retain its revision.
210
+ 2. Find the command and check its parameter schema.
211
+ 3. Run the intended steps with explicit sheets or object IDs and the revision as
212
+ `basis`.
213
+ 4. Read back the affected range or objects, including formulas when relevant.
214
+ 5. Run `sheet_check` and resolve relevant diagnostics.
215
+
216
+ ## Common tasks
217
+
218
+ - [`range.setValues`](/kits/sheet/commands/range.setValues/) `{ "range": "C1", "values": [[...], ...] }`
219
+ writes rows starting at the range's top-left cell. Values are numbers, strings, booleans and
220
+ `null`; a string that starts with `=` is a formula. It is the fastest way to write a block.
221
+ - [`cell.set`](/kits/sheet/commands/cell.set/) `{ "cell": "B2", "input": "..." }` enters one cell as
222
+ if typed. `input` is always a string: `"42"` and `"=A1*2"` are a number and a formula, typed the
223
+ way a person would.
224
+ - Write a **formula** when the value depends on other cells (totals, ratios, lookups). Write a
225
+ number only when the person gave a number. A total typed as `300` instead of `=SUM(B2:B4)` stops
226
+ updating.
227
+ - [`sheet.read`](/kits/sheet/commands/sheet.read/) answers values; with `"formulas": true` it
228
+ answers formulas.
229
+
230
+ ## Example 1: add a target column and a share formula
231
+
232
+ The workbook's sheet `Data` has `Region` / `Sales` in A1:B1, three regions in rows 2–4, and
233
+ `Total` with `=SUM(B2:B4)` in row 5.
234
+
235
+ ```json
236
+ sheet_run {
237
+ "path": "sales.xlsx",
238
+ "steps": [
239
+ { "command": "range.setValues", "params": { "range": "C1", "values": [["Target"], [100], [100], [100], ["=SUM(C2:C4)"]] } },
240
+ { "command": "range.setValues", "params": { "range": "D1", "values": [["Share"], ["=B2/C2"], ["=B3/C3"], ["=B4/C4"], ["=B5/C5"]] } }
241
+ ]
242
+ }
243
+ ```
244
+
245
+ Each step answers `{ "cells": 5 }`. Then read the values back:
246
+
247
+ ```json
248
+ sheet_run { "path": "sales.xlsx", "steps": [{ "command": "sheet.read", "params": { "range": "D2:D5" } }] }
249
+ ```
250
+
251
+ It answers `"values": [[1.2], [0.8], [1.0], [1.0]]`, and `sheet_check` finds nothing wrong.
252
+
253
+ ## Example 2: fix a division by zero the check reports
254
+
255
+ After [`cell.set`](/kits/sheet/commands/cell.set/) `{ "cell": "C3", "input": "0" }`, `sheet_check`
256
+ answers:
257
+
258
+ ```json
259
+ { "diagnostics": [{ "code": "sheet.formula-error", "severity": "error",
260
+ "message": "Data!D3 evaluates to #DIV/0!: =B3/C3", "target": { "sheet": "Data", "cell": "D3" } }] }
261
+ ```
262
+
263
+ Guard the formula instead of deleting it:
264
+
265
+ ```json
266
+ sheet_run {
267
+ "path": "sales.xlsx",
268
+ "steps": [{ "command": "cell.set", "params": { "cell": "D3", "input": "=IF(C3=0,\"\",B3/C3)" } }]
269
+ }
270
+ ```
271
+
272
+ `sheet_check` then answers `the kit found nothing wrong`.
273
+
274
+ ## Example 3: format a range on a named sheet without activating it
275
+
276
+ `sheet_inspect` lists `{"id": 2, "toolId": "sheet:2", "name": "Notes", …}`, and the person has the
277
+ `Summary` sheet open. Bold Notes' header row and give it a fill:
278
+
279
+ ```json
280
+ sheet_run {
281
+ "path": "budget.xlsx", "basis": "qx7", "target": { "sheet": "sheet:2" },
282
+ "steps": [
283
+ { "command": "home.bold", "on": ["A1:D1"], "params": { "on": true } },
284
+ { "command": "home.fillColor", "on": ["A1:D1"], "params": { "color": "#DDEBF7" } }
285
+ ]
286
+ }
287
+ ```
288
+
289
+ `on` goes into each command's `range`. The person stays on `Summary`, and the file opens there.
290
+ Check it with `sheet_inspect {"target": {"sheet": "sheet:2", "range": "A1:D5"}, "preview": true}`.
291
+
292
+ ## Example 4: edit two sheets in one run
293
+
294
+ ```json
295
+ sheet_run {
296
+ "path": "budget.xlsx",
297
+ "steps": [
298
+ { "command": "range.setValues", "at": { "part": { "sheet": "Data" } },
299
+ "params": { "range": "A5", "values": [["Total", "=SUM(B2:B4)"]] } },
300
+ { "command": "cell.set", "at": { "part": { "sheet": "Notes" } }, "on": ["A1"],
301
+ "params": { "input": "Checked" } }
302
+ ]
303
+ }
304
+ ```
305
+
306
+ Each step lands on its own sheet; nothing else moves. The same with ranges that name their sheet:
307
+ `{"command": "range.setValues", "params": {"range": "Data!A5", "values": [...]}}`.
308
+
309
+ ## Pitfalls
310
+
311
+ - **Values or formulas:** `sheet_inspect` and a plain [`sheet.read`](/kits/sheet/commands/sheet.read/)
312
+ show computed values. Read with `"formulas": true` before you change a formula.
313
+ - **Name the sheet:** a step with no `target`, `at.part`, `sheet` or `Sheet!` range acts on the
314
+ sheet the file opens on (or one the run inserted). Name the sheet when the workbook has more than
315
+ one; `sheet.activate` is never needed to edit another sheet.
316
+ - **Positions move:** a sheet's `index` changes when sheets move, and A1 addresses below inserted
317
+ or deleted rows change; ids (`sheet:2`, `drawing:5`) do not.
318
+ - **Merges:** a merged range shows only its top-left value.
319
+
320
+ ## Checks
321
+
322
+ `sheet_check` lists what is wrong with the workbook. Each diagnostic has a stable `code`, a
323
+ `severity` (`error`, `warning` or `info`), a `message`, a `target` and, for some, a `fix`: a
324
+ command step to run as it is. Act on the code, not on the message. A `fix` is a suggestion: run it
325
+ only when it is what the person asked for. Every code the kit reports is on the
326
+ [checks page](/kits/sheet/checks/).
327
+
328
+ - `sheet.formula-error` (error): a formula ends in `#DIV/0!`, `#VALUE!` or `#REF!`. `#N/A` is
329
+ reported as a warning, since lookups use it on purpose. Fix the formula or guard it.
330
+ - `sheet.circular-reference` (error): a formula refers to itself.
331
+ - `sheet.broken-name` (error): a defined name points nowhere (`#REF!`, a deleted sheet). Fix the
332
+ name's formula or delete it.
333
+ - `sheet.merge-hides-data` (warning): a merge hides other values. Its `fix` is
334
+ [`home.unmergeCells`](/kits/sheet/commands/home.unmergeCells/) on that range.
335
+ - `sheet.reference-outside-data` (warning): a formula reads one empty cell beyond the sheet's data,
336
+ often a typo (`Z900` instead of `B9`). Ranges such as `SUM(A1:A1000)` are not reported.
337
+ - `sheet.missing-glyph` (warning): a cell's text has characters no font the renderer has draws
338
+ (✓ and ✗ in Carlito); they show as empty boxes. Use other characters or add a font that has them.
339
+ - `sheet.font-substituted` (info): cells are set in a font the renderer has no face for, so their
340
+ text takes other widths than in Excel; the host adds the font (for Calibri, Carlito).
@@ -0,0 +1 @@
1
+ import{e as $e,j as Se,r as xe,t as Le,F as ie,G as Ce,c as C,h as qe,v as Ae,i as Oe,s as ze,u as Ue,f as Ie,a as je,Z as Ee,O as ve,o as Pe,y as Re,b as Ne,J as be}from"./index-DblcoJ90.js";function v(e,t){return new C(-32e3,t,{reason:e})}const _=e=>new C(-32602,e),fe=e=>Object.prototype.toString.call(e)==="[object ArrayBuffer]";function G(e){const t=e.lastIndexOf(".");return t>0?e.slice(t+1).toLowerCase():""}const Be=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;function he(e){let t=(e.split(/[\\/]/).pop()??"").replace(/[\u0000-\u001f\u007f<>:"|?*]/g,"").trim().replace(/^\.+/,"").replace(/[. ]+$/,"");const n=t.indexOf("."),s=n<0?t:t.slice(0,n);if(Be.test(s)&&(t=`${s}_${t.slice(s.length)}`),t.length>255){const r=G(t);t=r?`${t.slice(0,254-r.length)}.${r}`:t.slice(0,255)}return t||"Untitled"}async function We(e,t){const n=e.lastIndexOf("."),[s,r]=n>0?[e.slice(0,n),e.slice(n)]:[e,""];for(let c=1;c<1e4;c+=1){const u=c===1?e:`${s} ${c}${r}`;if(!await t(u))return u}throw v("io-error","no unused name is left for this file")}function pe(){const e=new Uint8Array(16);return crypto.getRandomValues(e),be+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}const Me=e=>e.split(/[\\/]/).filter(Boolean).pop()??e,Fe=()=>{var e,t;return((t=(e=globalThis.navigator)==null?void 0:e.userActivation)==null?void 0:t.isActive)??!0},oe=e=>(e??[]).map(t=>t.replace(/^\./,"").toLowerCase());function Je(e,t,n){let s=[];return{append:async r=>void s.push(r),commit:async()=>{const r=new Uint8Array(s.reduce((y,k)=>y+k.byteLength,0));let c=0;for(const y of s)r.set(y,c),c+=y.byteLength;const u=await e.commit(t(),r,n());return s=[],u},abort:async()=>{s=[]}}}const Te=["files/pick","files/create","files/stat","files/read","files/list","files/write","files/release","files/print"];function De(e){var Z,te,X,H;const{storage:t}=e,n=pe().slice(be.length),s={read:oe((Z=e.manifest)==null?void 0:Z.read),create:oe((te=e.manifest)==null?void 0:te.create),folders:((X=e.manifest)==null?void 0:X.folders)===!0,print:((H=e.manifest)==null?void 0:H.print)===!0},r=t.name??Me,c=e.gesture??Fe,u=new Map;let y=!1,k=0;const L=["files",...e.pick?["files-pick"]:[],...e.print?["print"]:[]],b=i=>({handle:i.handle,name:i.name,kind:i.kind,...i.size!==void 0?{size:i.size}:{},...i.mime!==void 0?{mime:i.mime}:{},version:i.version,rights:[...i.rights]}),q=(i,a,d,g,f={})=>{var j;const m={handle:pe(),session:n,kit:e.kit,principal:e.principal,flow:g,rights:d,kind:(a==null?void 0:a.kind)??"file",name:f.name??r(i),ref:i,folder:f.folder??null,accept:f.accept??[],mime:f.mime??(a==null?void 0:a.mime),version:(a==null?void 0:a.version)??null,size:a==null?void 0:a.size,committed:!1,staging:null,staged:0,written:0,expected:null};u.set(m.handle,m);const{handle:U,session:M,kit:D,principal:ne,kind:h,name:A}=m;return(j=e.log)==null||j.call(e,{handle:U,session:M,kit:D,principal:ne,flow:g,rights:[...d],kind:h,name:A}),m},$=(i,a,d)=>{if(y)throw v("file-not-granted","the session has ended");const g=typeof i=="string"?u.get(i):void 0;if(!g)throw v("file-not-granted","this handle was not granted to this session");if(a&&!g.rights.includes(a))throw v("file-not-granted",`this handle has no ${a} right`);if(d&&g.kind!==d)throw v("file-not-granted",`this handle is not a ${d}`);return g},p=async i=>{try{return await i()}catch(a){throw a instanceof C?a:v("io-error","the host could not reach the file")}},z=async i=>{u.delete(i.handle);const a=i.staging;i.staging=null,a&&await a.abort().catch(()=>{})},P=i=>{if(!c())throw v("no-gesture",`${i} needs a person's gesture in the kit`)},R=async(i,a)=>{const d=new Set([...u.values()].filter(f=>f.rights.includes("create")&&f.kind==="file"&&!f.committed).map(f=>f.ref)),g=await We(a,async f=>{const m=t.child(i,f);return d.has(m)||await t.stat(m)!==null});return{name:g,ref:t.child(i,g)}},N=(i,a=s.read)=>{const d=G(i);if(!s.read.includes(d)||!a.includes(d))throw v("not-allowed",`the kit may not read .${d||"(none)"} files`)},B=i=>{const a=G(i);if(!s.create.includes(a))throw v("not-allowed",`the kit may not create .${a||"(none)"} files`)},J=(i,a)=>{const d=oe(i);if(d.some(g=>!a.includes(g)))throw v("not-allowed","the kit asked for a file type its manifest does not declare");return d.length?d:a},T=async i=>{if(!e.pick)throw v("unsupported","this host has no picker");if((i==null?void 0:i.mode)!=="open"&&(i==null?void 0:i.mode)!=="folder"&&(i==null?void 0:i.mode)!=="save")throw _("mode is open, folder, or save");if(P("files/pick"),i.mode==="folder"&&!s.folders)throw v("not-allowed","the kit may not ask for folders");const a=J(i.accept,i.mode==="save"?s.create:s.read);i.mode==="save"&&i.suggestedName!=null&&B(he(i.suggestedName));const d=await p(()=>e.pick(i)),g=[];for(const f of i.mode==="open"&&!i.multiple?d.slice(0,1):d){const m=await p(()=>t.stat(f));if(i.mode==="folder"){if((m==null?void 0:m.kind)!=="folder")continue;const U=s.create.length?["read","create"]:["read"];g.push(b(q(f,m,U,"pick",{accept:a})))}else if(i.mode==="open"){if((m==null?void 0:m.kind)!=="file"||!a.includes(G(r(f))))continue;g.push(b(q(f,m,["read"],"pick")))}else{if(!a.includes(G(r(f))))throw v("not-allowed","the kit may not create this file type");if((m==null?void 0:m.kind)==="folder")continue;if(m&&e.readOnly)throw v("not-allowed","a read-only session replaces no file");g.push(b(q(f,m,m?["write"]:["create"],"pick")));break}}return{files:g}},o=async i=>{if(typeof(i==null?void 0:i.suggestedName)!="string")throw _("suggestedName is a string");const a=i.folder===void 0?null:$(i.folder,"create","folder"),d=he(i.suggestedName);B(d);const{name:g,ref:f}=await p(()=>R((a==null?void 0:a.ref)??null,d));return b(q(f,null,["create"],"create",{name:g,folder:(a==null?void 0:a.ref)??null,mime:typeof i.mime=="string"?i.mime:void 0}))},l=async({handle:i,offset:a,length:d})=>{const g=$(i,"read","file"),f=a??0;if(!Number.isSafeInteger(f)||f<0||d!==void 0&&(!Number.isSafeInteger(d)||d<0))throw _("offset and length are whole numbers");const m=await p(()=>t.read(g.ref,f,d));return g.version=m.version,g.size=m.size,m},S=async({handle:i})=>{const a=$(i,"read","folder"),d=await p(()=>t.list(a.ref)),g=[];for(const f of d){if(!a.accept.includes(G(r(f)))||!s.read.includes(G(r(f))))continue;const m=await p(()=>t.stat(f));(m==null?void 0:m.kind)==="file"&&g.push(b(q(f,m,["read"],"list")))}return{files:g}},W=async i=>{var U,M;const a=$(i==null?void 0:i.handle,void 0,"file"),d=a.rights.includes("create");if(!d&&!a.rights.includes("write"))throw v("file-not-granted","this handle has no create or write right");if(d&&a.committed)throw v("already-committed","this file was already committed");if(!fe(i.bytes))throw _("bytes is an ArrayBuffer");if(i.offset!==a.staged)throw _(`offset is ${a.staged}, the bytes staged so far`);const g=i.bytes.byteLength;if(((U=e.quota)==null?void 0:U.perGrant)!==void 0&&a.written+g>e.quota.perGrant||((M=e.quota)==null?void 0:M.perSession)!==void 0&&k+g>e.quota.perSession)throw v("quota","this write passes the host's cap");if(i.final&&!d){if(typeof i.expected!="string")throw v("conflict","the final chunk carries the version it replaces");if(await p(()=>{var D;return((D=t.unsaved)==null?void 0:D.call(t,a.ref))??!1}))throw v("unsaved-edits","the file is open with unsaved edits");a.expected=i.expected}if(!a.staging){const D=()=>d?{mode:"create"}:{mode:"replace",expected:a.expected??""};a.staging=t.stage?t.stage(a.ref,D):Je(t,()=>a.ref,D)}const f=a.staging;if(await p(()=>f.append(new Uint8Array(i.bytes.slice(0)))),a.staged+=g,a.written+=g,k+=g,!i.final)return{};const m=await O(a,f,d);return a.staging=null,a.staged=0,a.expected=null,a.version=m.version,d&&(a.committed=!0),{version:m.version}},O=async(i,a,d)=>{var g;for(let f=0;;f+=1)try{return await p(()=>a.commit())}catch(m){const U=m instanceof C&&((g=m.data)==null?void 0:g.reason)==="conflict";if(!d||!U||i.flow!=="create"||t.stage||f>=8)throw m;const M=await p(()=>R(i.folder,i.name));i.ref=M.ref,i.name=M.name}},V=async({handles:i})=>{for(const a of Array.isArray(i)?i:[]){const d=typeof a=="string"?u.get(a):void 0;d&&await z(d)}return{}},ee=async i=>{if(!e.print)throw v("unsupported","this host does not print");if(!s.print)throw v("not-allowed","the kit may not print");P("files/print");let a;if(!i||typeof i!="object")throw _("a print takes PDF bytes or a handle");if("handle"in i){const g=$(i.handle,"read","file");if(G(g.name)!=="pdf"&&g.mime!=="application/pdf")throw v("not-allowed","only a PDF prints");a=await K(g.ref)}else{if(i.mime!=="application/pdf"||!fe(i.bytes))throw _("a print takes PDF bytes or a handle");a=new Uint8Array(i.bytes.slice(0))}const d=typeof i.title=="string"?i.title:"";return{printed:await p(()=>e.print({bytes:a,title:d}))===!0}},K=async i=>{const a=[];let d=0;for(;;){const{bytes:m,size:U}=await p(()=>t.read(i,d,void 0));if(a.push(new Uint8Array(m)),d+=m.byteLength,d>=U||m.byteLength===0)break}const g=new Uint8Array(d);let f=0;for(const m of a)g.set(m,f),f+=m.byteLength;return g},Q={"files/pick":T,"files/create":o,"files/stat":async({handle:i})=>{const a=$(i);if(a.rights.includes("create")&&!a.committed&&a.kind==="file")return b(a);const d=await p(()=>t.stat(a.ref));if(!d)throw v("file-not-granted","the file is gone");return Object.assign(a,{version:d.version,size:d.size,mime:d.mime??a.mime}),b(a)},"files/read":l,"files/list":S,"files/write":W,"files/release":V,"files/print":ee};return{id:n,capabilities:L,grant:async(i,a,{flow:d,approved:g})=>{if(y)throw v("file-not-granted","the session has ended");const f=await p(()=>t.stat(i)),m=r(i);if(a.includes("write")){if(e.readOnly)throw v("not-allowed","a read-only session replaces no file");if(d==="agent"&&g!==!0)throw v("not-allowed","an agent replaces a file only through a draft or the person's approval");if((f==null?void 0:f.kind)!=="file")throw v("not-allowed","there is no such file to replace");B(m)}if(a.includes("read")){if(!f)throw v("not-allowed","there is no such file");if(f.kind==="file")N(m);else if(!s.folders)throw v("not-allowed","the kit may not read folders")}if(a.includes("create")&&(!f||f.kind==="file")){if(f)throw v("not-allowed","a create grant never names an existing file");B(m)}return b(q(i,f,[...new Set(a)],d,(f==null?void 0:f.kind)==="folder"?{accept:s.read}:{}))},revoke:async i=>{var d;const a=[];for(const g of i){const f=u.get(g);f&&(await z(f),a.push(g))}a.length&&((d=e.revoked)==null||d.call(e,a))},grants:()=>[...u.values()].map(({handle:i,session:a,kit:d,principal:g,flow:f,rights:m,kind:U,name:M})=>({handle:i,session:a,kit:d,principal:g,flow:f,rights:[...m],kind:U,name:M})),serve:async(i,a)=>{var d;if((d=e.trace)==null||d.call(e,i,a),y)throw v("file-not-granted","the session has ended");return Q[i](a)},end:async()=>{y=!0;for(const i of[...u.values()])await z(i)}}}function ue(e){if(/^([A-Za-z]:)?[\\/]/.test(e))return null;const t=[];for(const n of e.replace(/\\/g,"/").split("/"))if(!(!n||n==="."))if(n===".."){if(!t.length)return null;t.pop()}else t.push(n);return t.length?t.join("/"):null}function He(e,t,n){const s=ue(e),r=[];for(const c of n){const u=typeof(c==null?void 0:c.path)=="string"?ue(c.path):null;if(!u||u===s||u.split("/").some(b=>b.startsWith(".")))continue;const y=u.split("/").pop(),k=y.includes(".")?y.slice(y.lastIndexOf(".")+1).toLowerCase():"";if(!t.accept.includes(k))continue;const L={path:Ne(e,u),name:y,version:typeof c.version=="string"?c.version:null};if(r.some(b=>b.path===L.path)||r.push(L),!t.multiple)break}return r}function E(e){throw new C(-32601,`${e} is not supported by this host`)}function Ge(e,t){const{handlers:n}=t,s={agent:n.openAgent,"pick-file":n.pick,replica:n.replicaRead&&n.replicaWrite,customize:n.customize,lease:n.leases,presence:n.presence},r=Object.entries(s).filter(([,b])=>b).map(([b])=>b);n.generate&&r.push("generate"),n.open&&r.push("open-file"),n.openUrl&&r.push("open-url");const c=t.document.readOnly===!0;n.pickLinks&&!c&&r.push("links-pick"),n.fetchImage&&!c&&r.push("fetch-image");const u=Object.entries(n.actions??{}).filter(([,b])=>typeof b=="function");r.push(...u.map(([b])=>`${$e}${b}`));const y=Object.entries(n.services??{}).filter(([b,q])=>typeof q=="function"&&Se.includes(b)&&xe(b,t.document));r.push(...y.map(([b])=>`${Le}${b}`)),n.comments&&r.push("comment-anchors"),t.files&&r.push("files",...t.files.pick?["files-pick"]:[],...t.files.print?["print"]:[]);const k=t.timeoutMs??12e4,L=(b,q)=>{var T;const $=new MessageChannel,p=new qe($.port1,"h");let z=null;p.handle("host/read",o=>n.read(o)),p.handle("host/stamp",o=>n.stamp(o)),p.handle("host/write",o=>n.write(o)),p.handle("host/pick",o=>n.pick?n.pick(o):E("host/pick")),p.handle("host/openAgent",async o=>(n.openAgent||E("host/openAgent"),await n.openAgent(o),{}));const{replicaRead:P,replicaWrite:R}=n;p.handle("host/replicaRead",o=>P&&R?P(o):E("host/replicaRead")),p.handle("host/replicaWrite",async o=>((!P||!R)&&E("host/replicaWrite"),await R(o),{})),p.handle("host/customize",async o=>(n.customize||E("host/customize"),await n.customize(o),{})),p.handle("host/leaseAcquire",o=>n.leases?n.leases.acquire(o):E("host/leaseAcquire")),p.handle("host/leaseRelease",async o=>(n.leases||E("host/leaseRelease"),await n.leases.release(o),{})),p.handle("host/leases",async()=>(n.leases||E("host/leases"),{leases:await n.leases.list()})),p.handle("host/generate",o=>{if(n.generate||E("host/generate"),!Ae(o==null?void 0:o.purpose,z))throw new C(-32e3,`a kit may not generate for ${JSON.stringify(o==null?void 0:o.purpose)}`,{reason:"not-allowed"});return n.generate(o)}),p.handle("host/action",o=>{var S;const l=typeof(o==null?void 0:o.id)=="string"?(S=u.find(([W])=>W===o.id))==null?void 0:S[1]:void 0;if(!l)throw new C(-32e3,`this host does not serve the action ${String(o==null?void 0:o.id)}`,{reason:"not-allowed"});return l(o.params&&typeof o.params=="object"?o.params:{})}),p.handle("host/open",async o=>{var S;n.open||E("host/open");const l=Oe(o);if(!l)throw new C(-32602,"host/open needs a link with a path, a name, or a docId");return{opened:((S=await n.open(l))==null?void 0:S.opened)!==!1}}),p.handle("host/openUrl",async o=>{var l;if(n.openUrl||E("host/openUrl"),!ze(o==null?void 0:o.url))throw new C(-32e3,"a host opens only https:, http:, and mailto: addresses",{reason:"not-allowed"});return{opened:((l=await n.openUrl({url:o.url}))==null?void 0:l.opened)!==!1}}),p.handle("host/fetchImage",async o=>{if(n.fetchImage||E("host/fetchImage"),c)throw new C(-32e3,"a read-only document fetches no pictures",{reason:"read-only"});if(!Ue(o==null?void 0:o.url))throw new C(-32e3,"a host fetches only https: and http: addresses",{reason:"not-allowed"});const l=await n.fetchImage({url:o.url});if(!((l==null?void 0:l.bytes)instanceof ArrayBuffer)||!Ie.includes(l.mime))throw new C(-32e3,`${o.url} is not a picture`,{reason:"unsupported"});return{bytes:l.bytes,mime:l.mime}}),p.handle("links/pick",async o=>{if(n.pickLinks||E("links/pick"),c)throw new C(-32e3,"a read-only document links no files",{reason:"read-only"});const l=je(o);if(!l)throw new C(-32602,"links/pick needs a purpose and at least one extension without the dot");return{links:He(t.document.path,l,await n.pickLinks(l)??[])}});const N=t.files?De({...t.files,readOnly:c,revoked:o=>p.notify("files/revoked",{handles:o})}):null;if(N)for(const o of Te)p.handle(o,l=>N.serve(o,l));p.on("document/conflicts",o=>{var l;return(l=n.conflicts)==null?void 0:l.call(n,o)}),p.on("document/schema",o=>{var S;const l=Ee(o);l&&((S=n.schema)==null||S.call(n,l))}),p.on("draft/changed",o=>{var l;return(l=n.draftChanged)==null?void 0:l.call(n,o)}),p.on("presence/set",o=>{var S;const l=ve(o);l&&((S=n.presence)==null||S.call(n,l))}),p.on("document/changed",o=>n.changed(o)),p.on("replica/changed",o=>{var l;return(l=n.replicaChanged)==null?void 0:l.call(n,o)}),p.on("host/notify",o=>{var l;return(l=n.notify)==null?void 0:l.call(n,o)}),p.on("host/shortcut",o=>{var l;return(l=n.shortcut)==null?void 0:l.call(n,o)}),p.on("ui/action",o=>{var l;return(l=n.action)==null?void 0:l.call(n,o)}),p.handle("host/service",o=>{var O;const l=o==null?void 0:o.service,S=(O=y.find(([V])=>V===l))==null?void 0:O[1];if(!S)throw new C(-32e3,`this host does not serve ${String(l)}`,{reason:"not-allowed"});const W=Pe(o);if(!W)throw new C(-32602,`bad params for ${String(l)}`);return S(W.params)}),p.on("comments/activated",o=>{var l;typeof(o==null?void 0:o.id)=="string"&&o.id&&((l=n.comments)==null||l.activated(o.id))}),b.postMessage({kitionKitUi:1,protocol:ie,id:q},t.origin,[$.port2]);const B={...t.document,bytes:(T=t.document.bytes)==null?void 0:T.slice(0)},J=p.request("ui/initialize",{protocol:ie,host:t.host,document:B,theme:t.theme,locale:t.locale,shortcuts:t.shortcuts,capabilities:r,capabilitySets:t.capabilitySets??[],ui:t.ui},{transfer:!0});return J.then(o=>{var l;z=typeof((l=o==null?void 0:o.kit)==null?void 0:l.id)=="string"?o.kit.id:null},()=>{}),{peer:p,files:N,initialized:J}};return new Promise((b,q)=>{var B,J,T;let $=null;const p=o=>{var l;o==null||o.peer.close(),(l=o==null?void 0:o.files)==null||l.end()},z=()=>{var o;clearTimeout(R),window.removeEventListener("message",N),(o=t.signal)==null||o.removeEventListener("abort",P)},P=()=>{z(),p($),q(new Error("the kit mount was abandoned"))};if((B=t.signal)!=null&&B.aborted){q(new Error("the kit mount was abandoned"));return}(J=t.signal)==null||J.addEventListener("abort",P);const R=setTimeout(()=>{z(),p($),q(new Error("the kit did not open the document in time"))},k),N=o=>{if(o.source!==e.contentWindow||!Ce(o.data)||o.data.ready!==ie||t.origin!=="*"&&o.origin!==t.origin||($==null?void 0:$.id)===o.data.id)return;p($);const{peer:l,files:S,initialized:W}=L(o.source,o.data.id);$={peer:l,files:S,id:o.data.id},W.then(O=>{($==null?void 0:$.peer)===l&&(z(),b(_e(l,O,S)))},O=>{($==null?void 0:$.peer)===l&&(z(),S==null||S.end(),q(O instanceof Error?O:new Error(String(O))))})};window.addEventListener("message",N),(T=e.contentWindow)==null||T.postMessage({kitionKitUi:1,hello:ie},t.origin)})}function _e(e,t,n){return{kit:t.kit,capabilities:t.capabilities,state:()=>e.request("document/state",{}),save:()=>e.request("document/save",{}),fileChanged:s=>e.notify("document/fileChanged",{version:s}),fileHeld:s=>e.notify("document/held",{version:s}),setTheme:s=>e.notify("ui/theme",{theme:s}),setLocale:s=>e.notify("ui/locale",{locale:s}),focus:()=>e.notify("ui/focus",{}),configure:s=>e.notify("ui/configure",{ui:s}),leasesChanged:s=>e.notify("lease/changed",{leases:s}),peersChanged:s=>e.notify("presence/peers",{peers:s}),reveal:s=>e.notify("document/reveal",{view:s}),showComments:s=>{const r=s.flatMap(c=>{const u=Re(c.anchor);return u&&typeof c.id=="string"?[{id:c.id,anchor:u,resolved:c.resolved===!0,count:Number.isSafeInteger(c.count)?c.count:0}]:[]});e.notify("comments/show",{threads:r})},locateComments:async s=>{if(!t.capabilities.includes("comment-anchors"))return s.map(()=>!1);const{found:r}=await e.request("comments/locate",{anchors:s});return s.map((c,u)=>(r==null?void 0:r[u])===!0)},onPresence:s=>e.on("presence/set",r=>{const c=ve(r);c&&s(c)}),elements:()=>e.request("ui/elements",{}),check:async s=>t.capabilities.includes("check")?(await e.request("document/check",s!=null&&s.draft?{draft:!0}:{})).diagnostics:[],ai:{inspect:s=>e.request("ai/inspect",s??{}),commands:s=>e.request("ai/commands",{query:s}),run:(s,r,c)=>e.request("ai/run",{steps:s,save:r,...c!=null&&c.draft?{draft:!0}:{},...c!=null&&c.origin?{origin:c.origin}:{},...(c==null?void 0:c.originLabel)!=null?{originLabel:c.originLabel}:{}}),preview:(s,r)=>e.request("ai/preview",r!=null&&r.draft?{maxSize:s,draft:!0}:{maxSize:s}),version:async()=>(await e.request("ai/version",{})).version,premise:(s,r)=>e.request("ai/premise",{method:s,params:r}),changes:(s,r)=>e.request("ai/changes",r?{since:s,schema:r}:{since:s})},draft:{state:()=>e.request("draft/state",{}),ready:()=>e.request("draft/ready",{}),reopen:()=>e.request("draft/reopen",{}),compare:s=>e.request("draft/compare",s??{}),merge:(s,r)=>e.request("draft/merge",r?{origin:s,schema:r}:{origin:s}),discard:()=>e.request("draft/discard",{})},replica:{version:async()=>(await e.request("replica/version",{})).version,exportChanges:s=>e.request("replica/export",{since:s}),importChanges:(s,r)=>e.request("replica/import",{changes:s,blobs:r}),info:async()=>(await e.request("replica/info",{})).docId,onChanged:s=>e.on("replica/changed",r=>s(r.version))},model:{describe:s=>e.request("model/describe",s?{schema:s}:{}),batch:s=>e.request("model/batch",s)},files:n&&{grant:n.grant,revoke:n.revoke,grants:n.grants},close:()=>{e.close(),n==null||n.end()}}}const Ve=new Set(["purpose","title"]),Ze=new Set(["mime"]),Ke=/^(application|audio|example|font|haptics|image|message|model|multipart|text|video)\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(\s*;\s*[a-z0-9!#$&^_.+-]+=("[^"\\/]*"|[^\s;"\\/]+))*$/i,Qe=/(^|[\s"'(=])(\/(?:Users|home|root|var|tmp|private|Volumes|mnt|media|etc|opt|srv|data|workspace)\b|[A-Za-z]:[\\/]|\\\\[^\\\s]|~[\\/]|file:)/i;function me(e,t=!1){return Qe.test(e)?!0:!t&&(/[\\/]/.test(e)||/^\.\.?$/.test(e))}function Xe(e){return Ke.test(e)}function ce(e,t,n,s,r=0){if(typeof e=="string"){(n==="mime"?!Xe(e)&&me(e):me(e,n==="free"))&&s.push({at:t,value:e});return}if(!(e===null||typeof e!="object"||r>8||e instanceof ArrayBuffer||ArrayBuffer.isView(e)))if(Array.isArray(e))e.forEach((c,u)=>ce(c,`${t}[${u}]`,n,s,r+1));else for(const[c,u]of Object.entries(e))ce(u,t?`${t}.${c}`:c,Ve.has(c)?"free":Ze.has(c)?"mime":"name",s,r+1)}function Ye(e){const t=[];for(const{method:n,params:s}of e){if(!n.startsWith("files/"))continue;const r=[];ce(s,"","name",r);for(const c of r)t.push({method:n,...c})}return t}const et={pdf:"application/pdf",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",txt:"text/plain",json:"application/json"},ae=e=>e.split("/").some(t=>t.startsWith(".")||t===""),re=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")):"";function tt(e,t,n=new Set){const s=r=>n.has(r)||[...e.keys()].some(c=>c.startsWith(`${r}/`));return{stat:r=>{var u;if(ae(r))return null;const c=e.get(r);if(c){const y=et[((u=r.split(".").pop())==null?void 0:u.toLowerCase())??""];return{kind:"file",size:c.bytes.byteLength,version:String(c.version),...y?{mime:y}:{}}}return s(r)?{kind:"folder",version:null}:null},read:async(r,c,u)=>{const y=ae(r)?void 0:e.get(r);if(!y)throw v("file-not-granted","the file is gone");const k=u===void 0?y.bytes.byteLength:Math.min(y.bytes.byteLength,c+u);return{bytes:y.bytes.slice(c,k),version:String(y.version),size:y.bytes.byteLength}},list:r=>{const c=new Set;for(const u of[...e.keys(),...n]){if(!u.startsWith(`${r}/`)||ae(u))continue;const y=u.slice(r.length+1);c.add(`${r}/${y.split("/")[0]}`)}return[...c].sort()},child:(r,c)=>{const u=r??t();return u?`${u}/${c}`:c},commit:async(r,c,u)=>{const y=e.get(r);if(u.mode==="create"&&(y||s(r)))throw v("conflict","a file with this name exists");if(u.mode==="replace"&&(!y||String(y.version)!==u.expected))throw v("conflict","the file changed since it was read");!s(re(r))&&re(r)!==""&&n.add(re(r));const k=((y==null?void 0:y.version)??0)+1;return e.set(r,{bytes:c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength),version:k}),{version:String(k)}}}}const ge={light:{colorScheme:"light",tokens:{"--kit-primary":"#5645d4","--kit-surface":"#ffffff","--kit-surface-muted":"#fafaf9","--kit-canvas":"#f6f5f4","--kit-text":"#1a1a1a","--kit-text-muted":"#5d5b54","--kit-border":"#e5e3df"}},dark:{colorScheme:"dark",tokens:{"--kit-primary":"#8b7ff0","--kit-surface":"#1b1e23","--kit-surface-muted":"#22262c","--kit-canvas":"#15171b","--kit-text":"#eceff1","--kit-text-muted":"#a9b0ba","--kit-border":"#33373e"}}};function we(e,t){var s;const n=((s=t.split(".").pop())==null?void 0:s.toLowerCase())??"";return!(e!=null&&e.length)||e.some(r=>r.replace(/^\./,"").toLowerCase()===n)}function nt(e){return e!=="viewer"&&e!=="commenter"?{}:{readOnly:!0,comments:{me:`dev-${e}`,name:e==="viewer"?"Viewer":"Commenter",canComment:e==="commenter",othersReadOnly:!1}}}function ye(e){const t=[];for(const n of e.split("/"))if(!(!n||n==="."))if(n===".."){if(!t.length)return null;t.pop()}else t.push(n);return t.join("/")}function st(e,t,n){const s=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"";if(e.path){const L=ye(e.path.startsWith("/")?e.path:`${s}/${e.path}`);return L?{path:L,exists:n.has(L)}:null}if(!e.name||e.name.includes("/"))return null;const r=t.includes(".")?t.slice(t.lastIndexOf(".")):"",c=L=>(L.split("/").pop()??"").replace(/\.[^.]*$/,"").toLowerCase(),u=[...n.keys()].filter(L=>c(L)===e.name.toLowerCase()),y=u.find(L=>L.endsWith(r))??u[0];if(y)return{path:y,exists:!0};const k=ye(`${s}/${e.name}${r}`);return k?{path:k,exists:!1}:null}const ke=["menus","line","classic","focus"];function it(e){const t=[];for(const n of(e??"").split(",").map(s=>s.trim()).filter(Boolean))ke.includes(n)?t.push(n):console.warn(`kit-dev-host: ?modes= names an unknown display mode "${n}" (one of ${ke.join(", ")})`);return t.length?{allowed:t,default:t[0]}:void 0}function ot(e={}){var ne;const t=new Map,n=document.getElementById("kit"),s=document.getElementById("status"),r=document.getElementById("file"),c=[],u=e.entry??"./index.html",y=e.pickable??/\.(png|jpe?g|gif|svg|webp)$/i;let k=null;const L=e.presence===!0||new URLSearchParams(location.search).get("presence")==="1",b=[],q=[];let $=[];const p=new Set,z=[],P=[],R=[],N=[],B=e.generate===!0||new URLSearchParams(location.search).get("generate")==="1",J=[],T=[],o=e.open===!0||new URLSearchParams(location.search).get("open")==="1",l=[],S=[],W=[];let O="";const V=`kit-dev-host:personal:${location.pathname}`,ee=[];let K=new URLSearchParams(location.search).get("scheme")==="dark"?"dark":"light";const Q=it(new URLSearchParams(location.search).get("modes"));let Z=Q?{modes:Q}:{};const te=()=>{try{return JSON.parse(localStorage.getItem(V)??"[]")}catch{return[]}},X=()=>({...Z,personal:{hide:te()}}),H=document.createElement("details");H.innerHTML='<summary>UI configuration</summary><textarea rows="6" cols="60" spellcheck="false">{}</textarea><button type="button">Apply</button><select><option value="light">Light</option><option value="dark">Dark</option></select>',(ne=s.parentElement)==null||ne.append(H);const i=H.querySelector("textarea"),a=H.querySelector("select");a.value=K,H.querySelector("button").addEventListener("click",()=>{try{d(JSON.parse(i.value))}catch(h){s.textContent=`configuration: ${h instanceof Error?h.message:String(h)}`}}),a.addEventListener("change",()=>g(a.value==="dark"?"dark":"light"));function d(h){Z={hide:h.hide,disable:h.disable,add:h.add,modes:h.modes??Q},i.value=JSON.stringify(Z,null,2),k==null||k.configure(X())}function g(h){K=h,a.value=h,k==null||k.setTheme(ge[h])}async function f(h,A,j={}){k==null||k.close(),O=h,t.set(h,{bytes:A,version:1}),s.textContent=`opening ${h}…`,n.src=`${u}?${Date.now()}`;const se=t.get(h);try{k=await Ge(n,{origin:location.origin,host:{name:"Development host",version:"1"},document:{path:h,name:h.split("/").pop()??h,bytes:se.bytes.slice(0),version:String(se.version),lend:e.lend?{root:new URL(e.lend.root,location.href).href,folder:e.lend.folder}:void 0,...nt(new URLSearchParams(location.search).get("role")),...j.view?{view:j.view}:{}},theme:ge[K],locale:new URLSearchParams(location.search).get("locale")??navigator.language,shortcuts:["Cmd+W","Cmd+N","Cmd+O","Cmd+,"],ui:X(),handlers:{read:({path:w,offset:x,length:I})=>{const F=t.get(w);if(!F)throw new Error(`${w} is not in the workspace`);const Y=x??0;return{bytes:x!=null||I!=null?F.bytes.slice(Y,I!=null?Y+I:void 0):F.bytes.slice(0),version:String(F.version),size:F.bytes.byteLength}},stamp:({path:w})=>({version:t.has(w)?String(t.get(w).version):null}),write:({path:w,bytes:x,mode:I})=>{var le;let F=w;if(I!=="save")for(let de=2;t.has(F);de+=1)F=w.replace(/(\.[^./]+)?$/,` ${de}$1`);const Y=(((le=t.get(F))==null?void 0:le.version)??0)+1;return t.set(F,{bytes:x,version:Y}),{path:F,version:String(Y)}},pick:({accept:w})=>({path:[...t.keys()].find(x=>y.test(x)&&we(w,x))??null}),pickLinks:w=>{W.push(w);const x=S.shift();return(x?typeof x=="function"?x(w):x:[...t.keys()].filter(I=>I!==h&&y.test(I)&&we(w.accept,I))).filter(I=>t.has(I)).map(I=>({path:I,version:String(t.get(I).version)}))},openAgent:()=>{s.textContent="the editor asked for the agent"},changed:w=>{c.push(w),s.textContent=`${h}: revision ${w.revision}${w.dirty?", unsaved":""}`},notify:w=>{s.textContent=`${w.level}: ${w.title}`},shortcut:w=>{s.textContent=`host shortcut ${w.key}`},customize:({personal:w})=>{localStorage.setItem(V,JSON.stringify(w.hide))},action:w=>{ee.push(w),s.textContent=`host button ${w.id}`},schema:w=>{q.push(w)},...L?{presence:w=>void b.push(w)}:{},...B?{generate:w=>m(w)}:{},...o?{open:w=>U(w),openUrl:w=>M(w)}:{}},...e.kitFiles?{files:{storage:tt(t,()=>O.includes("/")?O.slice(0,O.lastIndexOf("/")):"",p),kit:"dev-kit",principal:"dev-person",manifest:e.kitFiles,pick:async w=>{const x=z.shift();return typeof x=="function"?x(w):x??[]},print:async({bytes:w,title:x})=>(N.push({title:x,size:w.byteLength}),window.devHost.printAnswer),log:w=>void P.push(w),trace:(w,x)=>void R.push({method:w,params:x})}}:{}}),L&&$.length&&k.peersChanged($),s.textContent=`${h} open in ${k.kit.id} ${k.kit.version}`}catch(w){s.textContent=`could not open ${h}: ${w instanceof Error?w.message:String(w)}`}}async function m(h){J.push(h),s.textContent=`the editor asked to generate for ${h.purpose}`;const A=T.shift()??{refuse:"unavailable"},j=typeof A=="function"?await A(h):A;if("refuse"in j)throw new C(-32e3,`the development host refused: ${j.refuse}`,{reason:j.refuse});return j}async function U(h){l.push({method:"host/open",params:h}),s.textContent=`the editor asked to open ${JSON.stringify(h.link)}`;const A=st(h.link,O,t);if(!A)throw new C(-32e3,"the link is not in the workspace",{reason:"not-found"});if(!A.exists){if(!h.create)throw new C(-32e3,`${A.path} is not in the workspace`,{reason:"not-found"});t.set(A.path,{bytes:new ArrayBuffer(0),version:1})}return{opened:window.devHost.openAnswer}}async function M(h){return l.push({method:"host/openUrl",params:h}),s.textContent=`the editor asked to open ${h.url}`,{opened:window.devHost.openAnswer}}function D(h){$=h,L&&(k==null||k.peersChanged(h))}window.devHost={files:t,connection:()=>k,open:f,changes:c,configure:d,actions:ee,setScheme:g,presences:b,setPeers:D,schemas:q,folders:p,scriptPick:(...h)=>void z.push(...h),grants:P,fileRequests:R,prints:N,printAnswer:!0,checkNoPaths:()=>Ye(R),generated:J,scriptGenerate:(...h)=>void T.push(...h),opens:l,openAnswer:!0,scriptLinkPick:(...h)=>void S.push(...h),linkPicks:W},r==null||r.addEventListener("change",async()=>{var A;const h=(A=r.files)==null?void 0:A[0];h&&await f(h.name,await h.arrayBuffer())}),(async()=>{var j;for(const[se,w]of Object.entries(e.files??{})){const x=await fetch(w).catch(()=>null);x!=null&&x.ok&&t.set(se,{bytes:await x.arrayBuffer(),version:1})}if(!e.sample){s.textContent="choose a file";return}const h=await fetch(e.sample).catch(()=>null);if(!(h!=null&&h.ok)){s.textContent="choose a file";return}const A=decodeURIComponent(e.sample.split("/").pop()??"Sample");await f((j=e.lend)!=null&&j.folder?`${e.lend.folder}/${A}`:A,await h.arrayBuffer())})()}ot({sample:"./sample/Sample.xlsx"});