mirror of
https://github.com/dolanmiu/docx.git
synced 2026-11-30 16:47:55 +01:00
* feat: write macro-enabled documents with VBA macros, from docx/macros (#471) A document's macros, the macros option, make it a macro-enabled document (.docm): its main part has the macro-enabled content type, it has the VBA project, word/vbaProject.bin, and Packer gives it a .docm's MIME type. The events of the document the macros handle, such as Document_Open, are listed in word/vbaData.xml, as Word only runs the handlers of the events listed there. createMacros, in a new entry, docx/macros, writes the macros from VBA code: ThisDocument's, modules and class modules. It writes the VBA project as [MS-OVBA] describes, in a compound file ([MS-CFB]), without a compiled cache, so Word compiles the code when it first runs it, and lists the events ThisDocument has handlers for. A vbaProject.bin from a .docm Word saved goes in macros too, with the events it handles. Checked in Word for Mac 16.114: Document_Open runs when the document opens, and so do macros in modules that use class modules and Office's library. LibreOffice imports the modules, and the Open XML SDK validator passes the demos for each version of Office since 2010. The demos workflow now validates a .docm as it does a .docx. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * fix: give a character beyond U+FFFF as two ChrW in createMacros' error createMacros' error for a character Windows-1252 doesn't have said to write it with ChrW and its code point, such as ChrW(&H1F600) for an emoji. ChrW only takes a UTF-16 code unit, up to &HFFFF, so that fails in Word. The error now gives one ChrW for each code unit: the surrogate pair, ChrW(&HD83D) & ChrW(&HDE00), which Word for Mac turns into the emoji. The docs say so too. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * docs: say how to run the macros of a .docm downloaded in Word for Windows The macros docs said Word asks whether to enable a .docm's macros when it opens. Word for Windows doesn't for a file from the internet, such as a .docm a web page made with docx and the browser downloaded: it blocks its macros without an Enable Content button. The docs now say to unblock the file in its Properties, that an organization's policy can still block macros, and that Word for Mac isn't affected. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -47,6 +47,7 @@
|
||||
"ondata",
|
||||
"onfile",
|
||||
"ooxml",
|
||||
"OVBA",
|
||||
"panose",
|
||||
"pmatrix",
|
||||
"rels",
|
||||
|
||||
@@ -24,11 +24,11 @@ jobs:
|
||||
# Microsoft's Open XML SDK validator. It's installed only here, as it is 80 MB
|
||||
- name: Install the Open XML SDK validator
|
||||
run: npm install --no-save --no-audit --no-fund @xarsh/ooxml-validator@0.3.0
|
||||
# Each shard runs every fourth demo, and checks the document it writes with the Open XML SDK validator, which
|
||||
# checks every part against Office's schemas, including Word 2010's extensions. It's checked as each version of
|
||||
# Office since 2010 reads it: older versions skip the newer extensions and read their fallbacks. Office 2007 is
|
||||
# left out, as it only knows the standard's first edition, from before ISO/IEC 29500, and rejects what Word
|
||||
# itself writes.
|
||||
# Each shard runs every fourth demo, and checks the document it writes, a .docx or, with macros, a .docm, with the
|
||||
# Open XML SDK validator, which checks every part against Office's schemas, including Word 2010's extensions.
|
||||
# It's checked as each version of Office since 2010 reads it: older versions skip the newer extensions and read
|
||||
# their fallbacks. Office 2007 is left out, as it only knows the standard's first edition, from before ISO/IEC
|
||||
# 29500, and rejects what Word itself writes.
|
||||
# The validator checks only the first file it's given (each demo writes one), and its option is
|
||||
# --officeVersion, not the --office-version its README gives. It reads a version it doesn't know as Microsoft365.
|
||||
# It doesn't look inside the workbooks that charts embed, so each is checked on its own. unzip exits with 11
|
||||
@@ -38,12 +38,12 @@ jobs:
|
||||
run: |
|
||||
for demo in $(find demo -mindepth 2 -name "*.ts" -not -path "demo/assets/*" | sort | awk -v n=${{ strategy.job-total }} -v i=${{ strategy.job-index }} 'NR % n == i'); do
|
||||
echo "::group::$demo"
|
||||
rm -rf ./*.docx embeddings
|
||||
rm -rf ./*.doc[xm] embeddings
|
||||
npm run --silent run-ts -- "$demo"
|
||||
unzip -q ./*.docx "word/embeddings/*.xlsx" -d embeddings || [ $? -eq 11 ]
|
||||
unzip -q ./*.doc[xm] "word/embeddings/*.xlsx" -d embeddings || [ $? -eq 11 ]
|
||||
for version in Office2010 Office2013 Office2016 Office2019 Office2021 Microsoft365; do
|
||||
echo "$version"
|
||||
npx ooxml-validator ./*.docx --officeVersion "$version"
|
||||
npx ooxml-validator ./*.doc[xm] --officeVersion "$version"
|
||||
for workbook in $(find embeddings -name "*.xlsx" 2>/dev/null); do
|
||||
npx ooxml-validator "$workbook" --officeVersion "$version"
|
||||
done
|
||||
|
||||
@@ -107,6 +107,24 @@ const doc = new Document({
|
||||
|
||||
In a page without a bundler, load `dist/html.umd.cjs` after `dist/index.umd.cjs` and `dist/math.umd.cjs`. It adds the `docxHtml` global. See the [HTML](https://docx.js.org/#/usage/html) documentation.
|
||||
|
||||
# Macros
|
||||
|
||||
VBA macros, written from their code, make a document a macro-enabled document (`.docm`), with `docx/macros`:
|
||||
|
||||
```ts
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { createMacros } from "docx/macros";
|
||||
|
||||
const doc = new Document({
|
||||
macros: createMacros({
|
||||
modules: [{ name: "Greetings", code: 'Sub SayHello()\n MsgBox "Hello"\nEnd Sub' }],
|
||||
}),
|
||||
sections: [{ children: [new Paragraph("Run SayHello from View > Macros")] }],
|
||||
});
|
||||
```
|
||||
|
||||
In a page without a bundler, load `dist/macros.umd.cjs` after `dist/index.umd.cjs`. It adds the `docxMacros` global. See the [macros](https://docx.js.org/#/usage/macros) documentation.
|
||||
|
||||
# Playground
|
||||
|
||||
Experience `docx` in action through [Docx.js Editor][docxjs-editor-url], an interactive playground where you can code and preview the results in real-time.
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,24 @@
|
||||
// A macro-enabled document with the macros of a .docm Word saved: its word/vbaProject.bin
|
||||
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
macros: {
|
||||
project: fs.readFileSync("./demo/assets/vbaProject.bin"),
|
||||
// The events its ThisDocument handles, which its .docm lists in word/vbaData.xml: Document_Open
|
||||
events: ["open"],
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph("Enable macros when Word asks, and the document says where its macros came from below."),
|
||||
new Paragraph("Run SayHello from View > Macros to say hello."),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Packer.toBuffer(doc).then((buffer) => {
|
||||
fs.writeFileSync("My Document.docm", buffer);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// A macro-enabled document: VBA macros written from their code, which Word runs from the .docm
|
||||
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph, TextRun } from "docx";
|
||||
import { createMacros } from "docx/macros";
|
||||
|
||||
const doc = new Document({
|
||||
macros: createMacros({
|
||||
// The document's own module, which handles its events. Word runs Document_Open when the document opens
|
||||
thisDocument: `
|
||||
Private Sub Document_Open()
|
||||
ActiveDocument.Content.InsertParagraphAfter
|
||||
ActiveDocument.Content.InsertAfter "Opened on " & Format(Date, "d mmmm yyyy") & "."
|
||||
End Sub
|
||||
`,
|
||||
modules: [
|
||||
{
|
||||
name: "Formatting",
|
||||
code: `
|
||||
' Run from View > Macros
|
||||
Sub HighlightNumbers()
|
||||
Dim item As Range
|
||||
For Each item In ActiveDocument.Words
|
||||
If IsNumeric(Trim(item.Text)) Then item.HighlightColorIndex = wdYellow
|
||||
Next
|
||||
End Sub
|
||||
`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({ children: [new TextRun({ text: "A document with macros", bold: true })] }),
|
||||
new Paragraph("Enable macros when Word asks, and the document adds the date it was opened below."),
|
||||
new Paragraph("Then run HighlightNumbers from View > Macros to highlight 3, 14 and 159 in this sentence."),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Packer.toBuffer(doc).then((buffer) => {
|
||||
fs.writeFileSync("My Document.docm", buffer);
|
||||
});
|
||||
@@ -68,6 +68,7 @@
|
||||
- [Math](usage/math.md)
|
||||
- [Math from LaTeX](usage/math-latex.md)
|
||||
- [HTML](usage/html.md)
|
||||
- [Macros](usage/macros.md)
|
||||
- [Comments](usage/comments.md)
|
||||
- [Footnotes](usage/footnotes.md)
|
||||
- [Endnotes](usage/endnotes.md)
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
"docx/layout": { file: "layout", global: "docxLayout" },
|
||||
// docx/html writes math with docx/math, so it is loaded after it
|
||||
"docx/html": { file: "html", global: "docxHtml", after: ["docx/math"] },
|
||||
"docx/macros": { file: "macros", global: "docxMacros" },
|
||||
};
|
||||
|
||||
// Packages from npm an example can import too, from jsDelivr at the version the docs are written for: where each is, and
|
||||
@@ -48,6 +49,10 @@
|
||||
// docx-preview draws these as empty space
|
||||
const NOT_DRAWN = { "docx/shapes": "shapes", "docx/charts": "charts", "docx/watermarks": "watermarks" };
|
||||
|
||||
// The type of a document with macros, a .docm, which Word doesn't open as a .docx. A blob's type is in lower case
|
||||
const DOCM = "application/vnd.ms-word.document.macroenabled.12";
|
||||
const extensionOf = (blob) => (blob.type === DOCM ? "docm" : "docx");
|
||||
|
||||
// The editor's types for what docx's types use from Node, and for the parts of Node an example can use
|
||||
const NODE_TYPES = `
|
||||
declare class Buffer extends Uint8Array {
|
||||
@@ -184,7 +189,10 @@ declare module "stream" {
|
||||
|
||||
const AsyncFunction = (async () => {}).constructor;
|
||||
|
||||
/** Runs an example, and returns the .docx it makes: the one it writes with fs.writeFileSync, or else its last Document */
|
||||
/**
|
||||
* Runs an example, and returns the .docx or .docm it makes: the one it writes with fs.writeFileSync, or else its last
|
||||
* Document
|
||||
*/
|
||||
const make = async (source) => {
|
||||
const imports = importsOf(source).filter((name) => name in MODULES);
|
||||
const packageNames = importsOf(source).filter((name) => name in PACKAGES);
|
||||
@@ -235,8 +243,8 @@ declare module "stream" {
|
||||
return encoding ? new FileBuffer(bytes).toString(encoding) : new FileBuffer(bytes);
|
||||
},
|
||||
writeFileSync: (path, data, encoding) => {
|
||||
if (/\.docx$/i.test(path)) {
|
||||
written = bytesOf(data, encoding);
|
||||
if (/\.doc[xm]$/i.test(path)) {
|
||||
written = new Blob([bytesOf(data, encoding)], /\.docm$/i.test(path) ? { type: DOCM } : {});
|
||||
}
|
||||
},
|
||||
createWriteStream: () => ({}),
|
||||
@@ -265,7 +273,7 @@ declare module "stream" {
|
||||
await new Promise((resolve) => setTimeout(resolve));
|
||||
|
||||
if (written) {
|
||||
return new Blob([written]);
|
||||
return written;
|
||||
}
|
||||
const failure = results.find((result) => result.status === "rejected");
|
||||
if (failure) {
|
||||
@@ -397,7 +405,7 @@ declare module "stream" {
|
||||
const download = button("Download .docx", () => {
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(example.blob);
|
||||
link.download = "example.docx";
|
||||
link.download = `example.${extensionOf(example.blob)}`;
|
||||
link.click();
|
||||
// Some browsers start the download after click() returns
|
||||
setTimeout(() => URL.revokeObjectURL(link.href), 60_000);
|
||||
@@ -469,13 +477,18 @@ declare module "stream" {
|
||||
pages.classList.remove("drawing");
|
||||
fit();
|
||||
example.blob = blob;
|
||||
download.textContent = `Download .${extensionOf(blob)}`;
|
||||
download.disabled = false;
|
||||
preview.classList.remove("live-example__preview--stale");
|
||||
const notDrawn = importsOf(source)
|
||||
.filter((name) => name in NOT_DRAWN)
|
||||
.map((name) => NOT_DRAWN[name]);
|
||||
setStatus(
|
||||
notDrawn.length > 0 ? `The preview can't draw ${notDrawn.join(" or ")}. Download the file to see them in Word.` : "",
|
||||
notDrawn.length > 0
|
||||
? `The preview can't draw ${notDrawn.join(" or ")}. Download the file to see them in Word.`
|
||||
: blob.type === DOCM
|
||||
? "The preview doesn't run macros. Download the .docm to run them in Word."
|
||||
: "",
|
||||
);
|
||||
} catch (error) {
|
||||
if (runNumber === example.runs) {
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
# Macros
|
||||
|
||||
<!-- cspell:ignore docm -->
|
||||
|
||||
A document can have VBA macros: code that Word runs from its Macros dialog, or when something happens to the document, such as when it opens. A document with macros is a macro-enabled document, saved as a `.docm`.
|
||||
|
||||
`createMacros` writes a document's macros from their VBA code. It comes with the `docx` package, from `docx/macros`, and the macros go in the document's `macros`:
|
||||
|
||||
```ts
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
import { createMacros } from "docx/macros";
|
||||
```
|
||||
|
||||
In a page without a bundler, load `dist/macros.umd.cjs` after `dist/index.umd.cjs` (or `dist/macros.iife.js` after `dist/index.iife.js`). It adds a `docxMacros` global, such as `docxMacros.createMacros({ ... })`.
|
||||
|
||||
## Example
|
||||
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
import { createMacros } from "docx/macros";
|
||||
|
||||
const doc = new Document({
|
||||
macros: createMacros({
|
||||
modules: [
|
||||
{
|
||||
name: "Greetings",
|
||||
code: `
|
||||
Sub SayHello()
|
||||
MsgBox "Hello from docx"
|
||||
End Sub
|
||||
`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [{ children: [new Paragraph("Run SayHello from View > Macros.")] }],
|
||||
});
|
||||
|
||||
Packer.toBuffer(doc).then((buffer) => {
|
||||
fs.writeFileSync("My Document.docm", buffer);
|
||||
});
|
||||
```
|
||||
|
||||
Save a document with macros as a `.docm`. Word won't open it from a `.docx`, the extension of a document without macros. `Packer.toBlob` gives it a `.docm`'s type, `application/vnd.ms-word.document.macroEnabled.12`.
|
||||
|
||||
Word disables the macros of a document from elsewhere until they are enabled, as for any `.docm`. Word for Mac asks when the document opens, and Word for Windows shows a bar with **Enable Content**. Word for Windows [blocks the macros of a file from the internet](https://learn.microsoft.com/en-us/microsoft-365-apps/security/internet-macros-blocked), though, such as a `.docm` a web page made and the browser downloaded, without **Enable Content**. To run them, right-click the file, choose **Properties** and tick **Unblock** on the **General** tab. An organization's policy can block macros all the same. Word for the web doesn't run macros.
|
||||
|
||||
## Options
|
||||
|
||||
| Property | Type | Notes | Description |
|
||||
| -------------- | --------------- | -------- | -------------------------------------------------------------------------------------------------------------- |
|
||||
| `thisDocument` | `string` | Optional | The code of the document's own module, ThisDocument in the VBA editor, where the document's events are handled |
|
||||
| `modules` | `MacroModule[]` | Optional | Modules, with the macros Word lists in its Macros dialog, and the procedures and functions they use |
|
||||
| `classModules` | `MacroModule[]` | Optional | Class modules, which define classes of objects |
|
||||
|
||||
Each module is:
|
||||
|
||||
| Property | Type | Notes | Description |
|
||||
| -------- | -------- | -------- | --------------------------------------------------------------------------------------------------------- |
|
||||
| `name` | `string` | Required | The module's name, such as `Formatting`. A letter, then letters, digits and underscores, up to 31 of them |
|
||||
| `code` | `string` | Required | The module's code, as it is typed in the VBA editor |
|
||||
|
||||
A module can't have the name of another, ignoring case, or a name the project has already: `ThisDocument`, `Project`, and the libraries it uses, `VBA`, `Word`, `stdole`, `Normal` and `Office`.
|
||||
|
||||
Word compiles the code when it first runs a macro, so a mistake in it shows then, in the VBA editor.
|
||||
|
||||
## The document's events
|
||||
|
||||
ThisDocument handles the document's events, such as `Document_Open` when it opens and `Document_Close` when it closes. Word only runs the handler of an event the document lists, and `createMacros` lists those `thisDocument` has.
|
||||
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
import { createMacros } from "docx/macros";
|
||||
|
||||
const doc = new Document({
|
||||
macros: createMacros({
|
||||
thisDocument: `
|
||||
Private Sub Document_Open()
|
||||
ActiveDocument.Content.InsertParagraphAfter
|
||||
ActiveDocument.Content.InsertAfter "Opened on " & Format(Date, "d mmmm yyyy") & "."
|
||||
End Sub
|
||||
`,
|
||||
}),
|
||||
sections: [{ children: [new Paragraph("Enable macros when Word asks, and the date it opened is added below.")] }],
|
||||
});
|
||||
|
||||
Packer.toBuffer(doc).then((buffer) => {
|
||||
fs.writeFileSync("My Document.docm", buffer);
|
||||
});
|
||||
```
|
||||
|
||||
## Class modules
|
||||
|
||||
A class module defines a class, which code in the other modules makes objects of with `New`:
|
||||
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
import { createMacros } from "docx/macros";
|
||||
|
||||
const doc = new Document({
|
||||
macros: createMacros({
|
||||
modules: [
|
||||
{
|
||||
name: "Counting",
|
||||
code: `
|
||||
Sub CountParagraphs()
|
||||
Dim tally As New Counter
|
||||
Dim item As Paragraph
|
||||
For Each item In ActiveDocument.Paragraphs
|
||||
tally.Add
|
||||
Next
|
||||
MsgBox "This document has " & tally.Value & " paragraphs"
|
||||
End Sub
|
||||
`,
|
||||
},
|
||||
],
|
||||
classModules: [
|
||||
{
|
||||
name: "Counter",
|
||||
code: `
|
||||
Private count As Long
|
||||
|
||||
Public Sub Add()
|
||||
count = count + 1
|
||||
End Sub
|
||||
|
||||
Public Property Get Value() As Long
|
||||
Value = count
|
||||
End Property
|
||||
`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [{ children: [new Paragraph("Run CountParagraphs from View > Macros."), new Paragraph("This is the second.")] }],
|
||||
});
|
||||
|
||||
Packer.toBuffer(doc).then((buffer) => {
|
||||
fs.writeFileSync("My Document.docm", buffer);
|
||||
});
|
||||
```
|
||||
|
||||
## Characters in the code
|
||||
|
||||
VBA keeps code in Windows-1252, the code page of Word in English and the other Western European languages. It has the accented letters of those languages, and `createMacros` throws for a character it doesn't have. Write one in a string with `ChrW` and its code in hexadecimal instead, such as `ChrW(&H4E2D)` for "中". `ChrW` goes up to `&HFFFF`, so a character beyond that, such as an emoji, is two, its UTF-16 surrogate pair: `ChrW(&HD83D) & ChrW(&HDE00)` for "😀". The error `createMacros` throws gives the `ChrW` to write.
|
||||
|
||||
## Macros from a .docm
|
||||
|
||||
A `.docm` Word saved keeps its macros in its `word/vbaProject.bin`. A `.docm` is a zip, so the file is in it, as it is in a `.docx`. Give the document it as `macros.project`, with the events its ThisDocument handles:
|
||||
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
macros: {
|
||||
project: fs.readFileSync("./demo/assets/vbaProject.bin"),
|
||||
events: ["open"],
|
||||
},
|
||||
sections: [{ children: [new Paragraph("Enable macros when Word asks, and the document says where its macros came from.")] }],
|
||||
});
|
||||
|
||||
Packer.toBuffer(doc).then((buffer) => {
|
||||
fs.writeFileSync("My Document.docm", buffer);
|
||||
});
|
||||
```
|
||||
|
||||
The `.docm` lists the events in its `word/vbaData.xml`, in `<wne:docEvents>`:
|
||||
|
||||
| Handler in ThisDocument | In `events` | In `word/vbaData.xml` |
|
||||
| -------------------------------------------- | ------------------------------------- | ----------------------------------------- |
|
||||
| `Document_New` | `"new"` | `wne:eventDocNew` |
|
||||
| `Document_Open` | `"open"` | `wne:eventDocOpen` |
|
||||
| `Document_Close` | `"close"` | `wne:eventDocClose` |
|
||||
| `Document_Sync` | `"sync"` | `wne:eventDocSync` |
|
||||
| `Document_XMLAfterInsert` | `"xmlAfterInsert"` | `wne:eventDocXmlAfterInsert` |
|
||||
| `Document_XMLBeforeDelete` | `"xmlBeforeDelete"` | `wne:eventDocXmlBeforeDelete` |
|
||||
| `Document_ContentControlAfterAdd` | `"contentControlAfterAdd"` | `wne:eventDocContentControlAfterInsert` |
|
||||
| `Document_ContentControlBeforeDelete` | `"contentControlBeforeDelete"` | `wne:eventDocContentControlBeforeDelete` |
|
||||
| `Document_ContentControlOnExit` | `"contentControlOnExit"` | `wne:eventDocContentControlOnExit` |
|
||||
| `Document_ContentControlOnEnter` | `"contentControlOnEnter"` | `wne:eventDocContentControlOnEnter` |
|
||||
| `Document_ContentControlBeforeStoreUpdate` | `"contentControlBeforeStoreUpdate"` | `wne:eventDocStoreUpdate` |
|
||||
| `Document_ContentControlBeforeContentUpdate` | `"contentControlBeforeContentUpdate"` | `wne:eventDocContentControlContentUpdate` |
|
||||
| `Document_BuildingBlockInsert` | `"buildingBlockInsert"` | `wne:eventDocBuildingBlockAfterInsert` |
|
||||
|
||||
## Examples
|
||||
|
||||
### Macros from their code
|
||||
|
||||
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/macros/macros.ts ":include")
|
||||
|
||||
_Source: https://github.com/dolanmiu/docx/blob/master/demo/macros/macros.ts_
|
||||
|
||||
### Macros from a .docm
|
||||
|
||||
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/macros/macros-from-docm.ts ":include")
|
||||
|
||||
_Source: https://github.com/dolanmiu/docx/blob/master/demo/macros/macros-from-docm.ts_
|
||||
+5
-2
@@ -397,7 +397,8 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
// and the package has one copy of each class and id counter. docx doesn't import them. Specs may import docx's
|
||||
// internals, such as the Formatter. docx/math (src/math) re-exports docx's math, which docx still exports and keeps in
|
||||
// src/file/paragraph/math. src/text-layout measures text for docx/shapes and docx/layout, and each bundles a copy.
|
||||
// docx/html (src/html) imports docx/math by name too, for the math in HTML
|
||||
// docx/html (src/html) imports docx/math by name too, for the math in HTML. docx/macros (src/macros) writes VBA
|
||||
// projects for docx's macros
|
||||
{
|
||||
files: ["src/**/*.ts"],
|
||||
ignores: [
|
||||
@@ -407,6 +408,7 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
"src/math/**",
|
||||
"src/layout/**",
|
||||
"src/html/**",
|
||||
"src/macros/**",
|
||||
"src/text-layout/**",
|
||||
"**/*.spec.ts",
|
||||
],
|
||||
@@ -418,7 +420,7 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
patterns: [
|
||||
{ group: ["docx/*"], message: "docx doesn't import its optional entries, such as docx/shapes" },
|
||||
{
|
||||
regex: "(^|/)(shapes|watermarks|charts|layout|html|text-layout)(/|$)",
|
||||
regex: "(^|/)(shapes|watermarks|charts|layout|html|macros|text-layout)(/|$)",
|
||||
message: "docx doesn't import its optional entries, such as docx/shapes",
|
||||
},
|
||||
],
|
||||
@@ -434,6 +436,7 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
"src/math/*.ts",
|
||||
"src/layout/*.ts",
|
||||
"src/html/*.ts",
|
||||
"src/macros/*.ts",
|
||||
"src/text-layout/*.ts",
|
||||
],
|
||||
ignores: ["**/*.spec.ts"],
|
||||
|
||||
+15
-2
@@ -76,6 +76,16 @@
|
||||
"types": "./dist/html.d.cts",
|
||||
"default": "./dist/html.cjs"
|
||||
}
|
||||
},
|
||||
"./macros": {
|
||||
"import": {
|
||||
"types": "./dist/macros.d.ts",
|
||||
"default": "./dist/macros.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/macros.d.cts",
|
||||
"default": "./dist/macros.cjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"typesVersions": {
|
||||
@@ -97,6 +107,9 @@
|
||||
],
|
||||
"html": [
|
||||
"./dist/html.d.ts"
|
||||
],
|
||||
"macros": [
|
||||
"./dist/macros.d.ts"
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -104,14 +117,14 @@
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc && vite build && vite build --config vite.entries.config.ts --mode shapes && vite build --config vite.entries.config.ts --mode watermarks && vite build --config vite.entries.config.ts --mode charts && vite build --config vite.entries.config.ts --mode math && vite build --config vite.entries.config.ts --mode layout && vite build --config vite.entries.config.ts --mode html",
|
||||
"build": "tsc && vite build && vite build --config vite.entries.config.ts --mode shapes && vite build --config vite.entries.config.ts --mode watermarks && vite build --config vite.entries.config.ts --mode charts && vite build --config vite.entries.config.ts --mode math && vite build --config vite.entries.config.ts --mode layout && vite build --config vite.entries.config.ts --mode html && vite build --config vite.entries.config.ts --mode macros",
|
||||
"test": "vitest --ui --coverage",
|
||||
"test:ci": "vitest run --coverage",
|
||||
"prepublishOnly": "npm run build --omit=dev",
|
||||
"lint": "eslint --config eslint.config.ts",
|
||||
"predemo": "npm run build",
|
||||
"demo": "tsx ./demo/index.ts",
|
||||
"typedoc": "typedoc src/index.ts src/shapes/index.ts src/watermarks/index.ts src/charts/index.ts src/math/index.ts src/layout/index.ts src/html/index.ts --tsconfig tsconfig.typedoc.json",
|
||||
"typedoc": "typedoc src/index.ts src/shapes/index.ts src/watermarks/index.ts src/charts/index.ts src/math/index.ts src/layout/index.ts src/html/index.ts src/macros/index.ts --tsconfig tsconfig.typedoc.json",
|
||||
"prettier": "prettier -l \"{src,scripts,demo,docs}/**/*.{ts,html,md}\"",
|
||||
"prettier:fix": "npm run prettier -- --write",
|
||||
"cspell": "cspell \"{src,demo,docs,scripts}/**/*.{ts,scss,html,md}\" && cspell \"./*.*\"",
|
||||
|
||||
@@ -84,6 +84,35 @@ describe("Compiler", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("macros", () => {
|
||||
// The start of a compound file, which is all the document checks a VBA project for
|
||||
const project = Uint8Array.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 0x00]);
|
||||
|
||||
it("should pack the VBA project, without the events part when the macros handle no events", async () => {
|
||||
const zipFile = compiler.compile(new File({ sections: [], macros: { project } }));
|
||||
const fileNames = Object.keys(zipFile.files);
|
||||
|
||||
expect(await zipFile.file("word/vbaProject.bin")?.async("uint8array")).toEqual(project);
|
||||
expect(fileNames).not.toContain("word/vbaData.xml");
|
||||
expect(fileNames).not.toContain("word/_rels/vbaProject.bin.rels");
|
||||
expect(await zipFile.file("word/_rels/document.xml.rels")?.async("text")).toContain(
|
||||
'Type="http://schemas.microsoft.com/office/2006/relationships/vbaProject" Target="vbaProject.bin"',
|
||||
);
|
||||
});
|
||||
|
||||
it("should pack the events the macros handle, and the VBA project's relationship to them", async () => {
|
||||
const zipFile = compiler.compile(new File({ sections: [], macros: { project, events: ["open"] } }));
|
||||
|
||||
expect(await zipFile.file("word/vbaData.xml")?.async("text")).toBe(
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<wne:vbaSuppData xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml"><wne:docEvents><wne:eventDocOpen/></wne:docEvents></wne:vbaSuppData>',
|
||||
);
|
||||
expect(await zipFile.file("word/_rels/vbaProject.bin.rels")?.async("text")).toContain(
|
||||
'<Relationship Id="rId1" Type="http://schemas.microsoft.com/office/2006/relationships/wordVbaData" Target="vbaData.xml"/>',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should give an image in a comment a relationship from the comments part", async () => {
|
||||
const image = new ImageRun({ type: "png", data: Buffer.from("", "base64"), transformation: { width: 10, height: 10 } });
|
||||
const zipFile = compiler.compile(
|
||||
|
||||
@@ -87,6 +87,10 @@ type IXmlifyedFileMapping = {
|
||||
readonly Theme: IXmlifyedFile;
|
||||
/** Parts added by the document's content, such as charts (word/charts/chart1.xml), and their relationships */
|
||||
readonly PackageParts: readonly PackagePartFile[];
|
||||
/** The events of the document its macros handle (word/vbaData.xml) */
|
||||
readonly MacroEvents?: IXmlifyedFile;
|
||||
/** The relationships of the macros' VBA project (word/_rels/vbaProject.bin.rels), to their events */
|
||||
readonly MacroRelationships?: IXmlifyedFile;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -160,6 +164,10 @@ export class Compiler {
|
||||
zip.file(subFile.path, encodeUtf8(subFile.data));
|
||||
}
|
||||
|
||||
if (file.Macros !== undefined) {
|
||||
zip.file("word/vbaProject.bin", file.Macros.project);
|
||||
}
|
||||
|
||||
for (const data of file.Media.Array) {
|
||||
if (data.type !== "svg") {
|
||||
zip.file(`word/media/${data.fileName}`, data.data);
|
||||
@@ -750,6 +758,43 @@ export class Compiler {
|
||||
),
|
||||
path: "word/theme/theme1.xml",
|
||||
},
|
||||
...(file.Macros?.events
|
||||
? {
|
||||
MacroEvents: {
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.Macros.events, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
stack: [],
|
||||
}),
|
||||
{
|
||||
indent: prettify,
|
||||
declaration: {
|
||||
standalone: "yes",
|
||||
encoding: "UTF-8",
|
||||
},
|
||||
},
|
||||
),
|
||||
path: "word/vbaData.xml",
|
||||
},
|
||||
MacroRelationships: {
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.Macros.relationships, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
stack: [],
|
||||
}),
|
||||
{
|
||||
indent: prettify,
|
||||
declaration: {
|
||||
encoding: "UTF-8",
|
||||
},
|
||||
},
|
||||
),
|
||||
path: "word/_rels/vbaProject.bin.rels",
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
// After every part that can refer to them, which adds them to the package as it is written
|
||||
PackageParts: xmlifyPackageParts(file, prettify),
|
||||
// After every part that can have lists, such as headers and footers, as the lists they use are added to the
|
||||
|
||||
@@ -149,6 +149,18 @@ describe("Packer", () => {
|
||||
});
|
||||
|
||||
describe("#toBlob()", () => {
|
||||
it("should give a document the type of a .docx", async () => {
|
||||
expect((await Packer.toBlob(file)).type).toBe("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
|
||||
});
|
||||
|
||||
it("should give a document with macros the type of a .docm", async () => {
|
||||
const project = Uint8Array.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 0x00]);
|
||||
const blob = await Packer.toBlob(new File({ sections: [], macros: { project } }));
|
||||
|
||||
// A blob's type is in lower case
|
||||
expect(blob.type).toBe("application/vnd.ms-word.document.macroenabled.12");
|
||||
});
|
||||
|
||||
it("should create a standard docx file", async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn((Packer as any).compiler, "compile").mockReturnValue({
|
||||
|
||||
@@ -34,6 +34,12 @@ const convertPrettifyType = (
|
||||
): (typeof PrettifyType)[keyof typeof PrettifyType] | undefined =>
|
||||
prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify;
|
||||
|
||||
// A document with macros is a .docm, whose type isn't a .docx's
|
||||
const mimeTypeOf = (file: File): string =>
|
||||
file.Macros === undefined
|
||||
? "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
: "application/vnd.ms-word.document.macroEnabled.12";
|
||||
|
||||
/**
|
||||
* Exports documents to various output formats.
|
||||
*
|
||||
@@ -75,7 +81,7 @@ export class Packer {
|
||||
const zip = this.compiler.compile(file, convertPrettifyType(prettify), overrides);
|
||||
return zip.generateAsync({
|
||||
type,
|
||||
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
mimeType: mimeTypeOf(file),
|
||||
compression: "DEFLATE",
|
||||
});
|
||||
}
|
||||
@@ -178,7 +184,7 @@ export class Packer {
|
||||
|
||||
zip.generateAsync({
|
||||
type: "nodebuffer",
|
||||
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
mimeType: mimeTypeOf(file),
|
||||
compression: "DEFLATE",
|
||||
}).then((z) => {
|
||||
stream.emit("data", z);
|
||||
|
||||
@@ -30,7 +30,11 @@ import { createOverride } from "./override/override";
|
||||
* ```
|
||||
*/
|
||||
export class ContentTypes extends XmlComponent {
|
||||
public constructor() {
|
||||
/**
|
||||
* @param options.macros - Whether the document has VBA macros, which makes its main part a macro-enabled document
|
||||
* and adds the VBA project (word/vbaProject.bin)
|
||||
*/
|
||||
public constructor({ macros = false }: { readonly macros?: boolean } = {}) {
|
||||
super("Types");
|
||||
|
||||
this.root.push(
|
||||
@@ -50,7 +54,12 @@ export class ContentTypes extends XmlComponent {
|
||||
this.root.push(createDefault("application/vnd.openxmlformats-officedocument.obfuscatedFont", "odttf"));
|
||||
|
||||
this.root.push(
|
||||
createOverride("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", "/word/document.xml"),
|
||||
createOverride(
|
||||
macros
|
||||
? "application/vnd.ms-word.document.macroEnabled.main+xml"
|
||||
: "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
|
||||
"/word/document.xml",
|
||||
),
|
||||
);
|
||||
|
||||
this.root.push(createOverride("application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", "/word/styles.xml"));
|
||||
@@ -69,6 +78,10 @@ export class ContentTypes extends XmlComponent {
|
||||
createOverride("application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", "/word/fontTable.xml"),
|
||||
);
|
||||
this.root.push(createOverride("application/vnd.openxmlformats-officedocument.theme+xml", "/word/theme/theme1.xml"));
|
||||
|
||||
if (macros) {
|
||||
this.root.push(createOverride("application/vnd.ms-office.vbaProject", "/word/vbaProject.bin"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -17,6 +17,7 @@ import { dateTimeValue } from "@util/values";
|
||||
import type { ICustomPropertyOptions } from "../custom-properties";
|
||||
import type { IDocumentBackgroundOptions, PageNumberEstimator } from "../document";
|
||||
import { DocumentAttributes } from "../document/document-attributes";
|
||||
import type { DocumentMacros } from "../document-macros";
|
||||
import type { ISectionOptions } from "../file";
|
||||
import type { INumberingOptions } from "../numbering";
|
||||
import type { Paragraph } from "../paragraph";
|
||||
@@ -50,6 +51,7 @@ import type { IThemeOptions } from "../theme";
|
||||
* @property hyphenation - Hyphenation settings
|
||||
* @property theme - The document's theme: its colors, and its fonts for headings and body text
|
||||
* @property pageNumbers - Works out the page each bookmark is on, so the page numbers of tables of contents and page references are written with the document
|
||||
* @property macros - The document's VBA macros, which make it a macro-enabled document (.docm)
|
||||
*/
|
||||
export type IPropertiesOptions = {
|
||||
readonly sections: readonly ISectionOptions[];
|
||||
@@ -103,6 +105,11 @@ export type IPropertiesOptions = {
|
||||
* from `docx/layout`, which lays out the document's pages as Word would
|
||||
*/
|
||||
readonly pageNumbers?: PageNumberEstimator;
|
||||
/**
|
||||
* The document's VBA macros. `createMacros` from `docx/macros` writes them from VBA code. A document with macros is a
|
||||
* macro-enabled document, which Word only opens from a .docm file
|
||||
*/
|
||||
readonly macros?: DocumentMacros;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Document macros module: a document's VBA macros, which make it a macro-enabled document (.docm).
|
||||
*
|
||||
* The macros are a VBA project, which Word keeps in word/vbaProject.bin. The events of the document that the project
|
||||
* handles are listed in word/vbaData.xml, as Word only runs a handler, such as `Document_Open`, for an event listed
|
||||
* there.
|
||||
*
|
||||
* Reference: ooxml-schemas/microsoft/wml-2006.xsd (CT_VbaSuppData), [MS-OFFMACRO2]
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { BuilderElement, type XmlComponent } from "@file/xml-components";
|
||||
|
||||
/**
|
||||
* An event of a document that its macros can handle, in the document's own module, ThisDocument. Each is the event's
|
||||
* name in VBA, after "Document_", such as "open" for `Document_Open`.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type DocumentMacroEvent =
|
||||
| "new"
|
||||
| "open"
|
||||
| "close"
|
||||
| "sync"
|
||||
| "xmlAfterInsert"
|
||||
| "xmlBeforeDelete"
|
||||
| "contentControlAfterAdd"
|
||||
| "contentControlBeforeDelete"
|
||||
| "contentControlOnExit"
|
||||
| "contentControlOnEnter"
|
||||
| "contentControlBeforeStoreUpdate"
|
||||
| "contentControlBeforeContentUpdate"
|
||||
| "buildingBlockInsert";
|
||||
|
||||
/**
|
||||
* A document's VBA macros, for the document's `macros`.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type DocumentMacros = {
|
||||
/**
|
||||
* The VBA project, the file Word keeps a document's macros in. `createMacros` from `docx/macros` writes it from VBA
|
||||
* code. Or it is the word/vbaProject.bin of a .docm Word saved
|
||||
*/
|
||||
readonly project: Uint8Array | ArrayBuffer;
|
||||
/**
|
||||
* The events of the document that the project handles in ThisDocument, such as "open" for `Document_Open`. Word only
|
||||
* runs the handlers of the events listed. `createMacros` lists them from the code. For a project from a .docm, they
|
||||
* are the `wne:docEvents` in its word/vbaData.xml
|
||||
*/
|
||||
readonly events?: readonly DocumentMacroEvent[];
|
||||
};
|
||||
|
||||
// Each event's element in word/vbaData.xml, in the schema's order
|
||||
const EVENT_ELEMENTS: Readonly<Record<DocumentMacroEvent, string>> = {
|
||||
new: "wne:eventDocNew",
|
||||
open: "wne:eventDocOpen",
|
||||
close: "wne:eventDocClose",
|
||||
sync: "wne:eventDocSync",
|
||||
xmlAfterInsert: "wne:eventDocXmlAfterInsert",
|
||||
xmlBeforeDelete: "wne:eventDocXmlBeforeDelete",
|
||||
contentControlAfterAdd: "wne:eventDocContentControlAfterInsert",
|
||||
contentControlBeforeDelete: "wne:eventDocContentControlBeforeDelete",
|
||||
contentControlOnExit: "wne:eventDocContentControlOnExit",
|
||||
contentControlOnEnter: "wne:eventDocContentControlOnEnter",
|
||||
contentControlBeforeStoreUpdate: "wne:eventDocStoreUpdate",
|
||||
contentControlBeforeContentUpdate: "wne:eventDocContentControlContentUpdate",
|
||||
buildingBlockInsert: "wne:eventDocBuildingBlockAfterInsert",
|
||||
};
|
||||
|
||||
/**
|
||||
* The events of a document that its macros handle (word/vbaData.xml).
|
||||
*
|
||||
* ## XSD Schema
|
||||
* ```xml
|
||||
* <xsd:complexType name="CT_VbaSuppData">
|
||||
* <xsd:sequence>
|
||||
* <xsd:element name="docEvents" type="CT_DocEvents" minOccurs="0" maxOccurs="1"/>
|
||||
* <xsd:element name="mcds" type="CT_Mcds" minOccurs="0" maxOccurs="1"/>
|
||||
* </xsd:sequence>
|
||||
* </xsd:complexType>
|
||||
* ```
|
||||
*/
|
||||
export const createMacroEvents = (events: readonly DocumentMacroEvent[]): XmlComponent =>
|
||||
new BuilderElement<{ readonly namespace: string }>({
|
||||
name: "wne:vbaSuppData",
|
||||
attributes: { namespace: { key: "xmlns:wne", value: "http://schemas.microsoft.com/office/word/2006/wordml" } },
|
||||
children: [
|
||||
new BuilderElement({
|
||||
name: "wne:docEvents",
|
||||
children: Object.entries(EVENT_ELEMENTS)
|
||||
.filter(([event]) => events.includes(event as DocumentMacroEvent))
|
||||
.map(([, name]) => new BuilderElement({ name })),
|
||||
}),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
export { type DocumentMacroEvent, type DocumentMacros } from "./document-macros";
|
||||
@@ -602,6 +602,85 @@ describe("File", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("#macros", () => {
|
||||
// The start of a compound file, which is all the document checks a VBA project for
|
||||
const project = Uint8Array.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 0x00]);
|
||||
const VBA_PROJECT = "http://schemas.microsoft.com/office/2006/relationships/vbaProject";
|
||||
|
||||
it("should leave a document without macros a .docx, with no VBA project", () => {
|
||||
const doc = new File({ sections: [] });
|
||||
|
||||
expect(doc.Macros).toBeUndefined();
|
||||
expect(JSON.stringify(new Formatter().format(doc.Document.Relationships))).not.toContain(VBA_PROJECT);
|
||||
expect(JSON.stringify(new Formatter().format(doc.ContentTypes))).toContain(
|
||||
JSON.stringify({
|
||||
ContentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
|
||||
PartName: "/word/document.xml",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should make a document with macros macro-enabled, with a relationship to its VBA project after the theme's", () => {
|
||||
const doc = new File({ macros: { project }, sections: [] });
|
||||
const contentTypes = JSON.stringify(new Formatter().format(doc.ContentTypes));
|
||||
|
||||
expect(doc.Macros?.project).toBe(project);
|
||||
expect(doc.Macros?.events).toBeUndefined();
|
||||
expect(doc.Macros?.relationships.RelationshipCount).toBe(0);
|
||||
expect(JSON.stringify(new Formatter().format(doc.Document.Relationships))).toContain(
|
||||
JSON.stringify({ Id: "rId7", Type: VBA_PROJECT, Target: "vbaProject.bin" }),
|
||||
);
|
||||
expect(contentTypes).toContain(
|
||||
JSON.stringify({ ContentType: "application/vnd.ms-word.document.macroEnabled.main+xml", PartName: "/word/document.xml" }),
|
||||
);
|
||||
expect(contentTypes).not.toContain("wordprocessingml.document.main+xml");
|
||||
expect(contentTypes).toContain(
|
||||
JSON.stringify({ ContentType: "application/vnd.ms-office.vbaProject", PartName: "/word/vbaProject.bin" }),
|
||||
);
|
||||
expect(contentTypes).not.toContain("vbaData");
|
||||
});
|
||||
|
||||
it("should list the events the macros handle, with a relationship to them from the VBA project", () => {
|
||||
const doc = new File({ macros: { project, events: ["close", "open"] }, sections: [] });
|
||||
|
||||
expect(new Formatter().format(doc.Macros!.events!)).toEqual({
|
||||
"wne:vbaSuppData": [
|
||||
{ _attr: { "xmlns:wne": "http://schemas.microsoft.com/office/word/2006/wordml" } },
|
||||
{ "wne:docEvents": [{ "wne:eventDocOpen": {} }, { "wne:eventDocClose": {} }] },
|
||||
],
|
||||
});
|
||||
expect(new Formatter().format(doc.Macros!.relationships)).toEqual({
|
||||
Relationships: [
|
||||
{ _attr: { xmlns: "http://schemas.openxmlformats.org/package/2006/relationships" } },
|
||||
{
|
||||
Relationship: {
|
||||
_attr: {
|
||||
Id: "rId1",
|
||||
Type: "http://schemas.microsoft.com/office/2006/relationships/wordVbaData",
|
||||
Target: "vbaData.xml",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(new Formatter().format(doc.ContentTypes))).toContain(
|
||||
JSON.stringify({ ContentType: "application/vnd.ms-word.vbaData+xml", PartName: "/word/vbaData.xml" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("should take a VBA project as an ArrayBuffer", () => {
|
||||
const doc = new File({ macros: { project: project.buffer }, sections: [] });
|
||||
|
||||
expect(doc.Macros?.project).toEqual(project);
|
||||
});
|
||||
|
||||
it("should throw for macros that aren't a VBA project, such as a .docm", () => {
|
||||
expect(() => new File({ macros: { project: Uint8Array.from([0x50, 0x4b, 0x03, 0x04]) }, sections: [] })).toThrow(
|
||||
"macros.project isn't a VBA project",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("#theme", () => {
|
||||
it("should write a theme with the given colors and fonts, and a relationship to it after the headers' and footers'", () => {
|
||||
const doc = new File({
|
||||
|
||||
+55
-1
@@ -11,6 +11,7 @@ import { ContentTypes } from "./content-types/content-types";
|
||||
import { CoreProperties, type IPropertiesOptions } from "./core-properties";
|
||||
import { CustomProperties } from "./custom-properties";
|
||||
import { HeaderFooterReferenceType, type ISectionPropertiesOptions } from "./document/body/section-properties";
|
||||
import { createMacroEvents } from "./document-macros/document-macros";
|
||||
import { DocumentWrapper } from "./document-wrapper";
|
||||
import { EndnotesWrapper } from "./endnotes-wrapper";
|
||||
import type { FileChild } from "./file-child";
|
||||
@@ -73,6 +74,21 @@ export type ISectionOptions = {
|
||||
readonly children: readonly FileChild[];
|
||||
};
|
||||
|
||||
// The first bytes of a compound file, the format of a VBA project
|
||||
const COMPOUND_FILE_SIGNATURE = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
|
||||
|
||||
/**
|
||||
* A document's macros, as the document writes them.
|
||||
*/
|
||||
type FileMacros = {
|
||||
/** The VBA project (word/vbaProject.bin) */
|
||||
readonly project: Uint8Array;
|
||||
/** The events of the document the project handles (word/vbaData.xml), if it handles any */
|
||||
readonly events?: XmlComponent;
|
||||
/** The project's relationships (word/_rels/vbaProject.bin.rels), to its events */
|
||||
readonly relationships: Relationships;
|
||||
};
|
||||
|
||||
/**
|
||||
* Represents a Word document file.
|
||||
*
|
||||
@@ -175,8 +191,27 @@ export class File {
|
||||
private readonly fontWrapper: FontWrapper;
|
||||
private readonly theme: Theme;
|
||||
private readonly packageParts: PackageParts;
|
||||
private readonly macros?: FileMacros;
|
||||
|
||||
public constructor(options: IPropertiesOptions) {
|
||||
if (options.macros !== undefined) {
|
||||
const { project, events = [] } = options.macros;
|
||||
const bytes = project instanceof Uint8Array ? project : new Uint8Array(project);
|
||||
// Every VBA project is a compound file, which starts with this signature. The .docm itself, a zip, is the
|
||||
// likeliest mistake
|
||||
if (!COMPOUND_FILE_SIGNATURE.every((byte, index) => bytes[index] === byte)) {
|
||||
throw new Error(
|
||||
"macros.project isn't a VBA project. Use createMacros from docx/macros, or the word/vbaProject.bin in a .docm rather than the .docm itself",
|
||||
);
|
||||
}
|
||||
// The events are in their own part, which the project's relationships point to
|
||||
const relationships = new Relationships();
|
||||
if (events.length > 0) {
|
||||
relationships.addRelationship(1, "http://schemas.microsoft.com/office/2006/relationships/wordVbaData", "vbaData.xml");
|
||||
}
|
||||
this.macros = { project: bytes, events: events.length > 0 ? createMacroEvents(events) : undefined, relationships };
|
||||
}
|
||||
|
||||
this.coreProperties = new CoreProperties({
|
||||
...options,
|
||||
creator: options.creator ?? "Un-named",
|
||||
@@ -200,7 +235,10 @@ export class File {
|
||||
this.appProperties = new AppProperties();
|
||||
this.footnotesWrapper = new FootnotesWrapper();
|
||||
this.endnotesWrapper = new EndnotesWrapper();
|
||||
this.contentTypes = new ContentTypes();
|
||||
this.contentTypes = new ContentTypes({ macros: this.macros !== undefined });
|
||||
if (this.macros?.events !== undefined) {
|
||||
this.contentTypes.addOverride("application/vnd.ms-word.vbaData+xml", "/word/vbaData.xml");
|
||||
}
|
||||
this.packageParts = new PackageParts(this.contentTypes);
|
||||
this.documentWrapper = new DocumentWrapper({ background: options.background, pageNumbers: options.pageNumbers });
|
||||
this.settings = new Settings({
|
||||
@@ -287,6 +325,14 @@ export class File {
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
|
||||
"theme/theme1.xml",
|
||||
);
|
||||
if (this.macros !== undefined) {
|
||||
this.documentWrapper.Relationships.addRelationship(
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
this.currentRelationshipId++,
|
||||
"http://schemas.microsoft.com/office/2006/relationships/vbaProject",
|
||||
"vbaProject.bin",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private addSection({ headers = {}, footers = {}, children, properties }: ISectionOptions): void {
|
||||
@@ -528,4 +574,12 @@ export class File {
|
||||
public get PackageParts(): PackageParts {
|
||||
return this.packageParts;
|
||||
}
|
||||
|
||||
/**
|
||||
* The document's macros, when it has any: its VBA project (word/vbaProject.bin), the events of the document it
|
||||
* handles (word/vbaData.xml), and the project's relationships, to the events.
|
||||
*/
|
||||
public get Macros(): FileMacros | undefined {
|
||||
return this.macros;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ export * from "./checkbox";
|
||||
export * from "./fonts";
|
||||
export * from "./textbox";
|
||||
export * from "./theme";
|
||||
export * from "./document-macros";
|
||||
// Parts that drawings add to the package when it is written, such as docx/charts' charts
|
||||
export * from "./package-part";
|
||||
export { type RelationshipType } from "./relationships/relationship/relationship";
|
||||
|
||||
@@ -30,6 +30,14 @@ export type RelationshipType =
|
||||
| "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart"
|
||||
| "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package";
|
||||
|
||||
/**
|
||||
* The types of the relationships to a document's macros: to its VBA project, and from that to the events it handles.
|
||||
* Only the document adds these, so a package part's relationship can't be one of them.
|
||||
*/
|
||||
export type MacroRelationshipType =
|
||||
| "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
|
||||
| "http://schemas.microsoft.com/office/2006/relationships/wordVbaData";
|
||||
|
||||
/**
|
||||
* Target mode types for relationships.
|
||||
*
|
||||
@@ -42,7 +50,7 @@ export const TargetModeType = {
|
||||
|
||||
type IRelationshipAttributes = {
|
||||
readonly id: string;
|
||||
readonly type: RelationshipType;
|
||||
readonly type: RelationshipType | MacroRelationshipType;
|
||||
readonly target: string;
|
||||
readonly targetMode?: (typeof TargetModeType)[keyof typeof TargetModeType];
|
||||
};
|
||||
@@ -65,7 +73,7 @@ type IRelationshipAttributes = {
|
||||
|
||||
export const createRelationship = (
|
||||
id: string,
|
||||
type: RelationshipType,
|
||||
type: RelationshipType | MacroRelationshipType,
|
||||
target: string,
|
||||
targetMode?: (typeof TargetModeType)[keyof typeof TargetModeType],
|
||||
): XmlComponent =>
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import { XmlComponent } from "@file/xml-components";
|
||||
|
||||
import { RelationshipsAttributes } from "./attributes";
|
||||
import { type RelationshipType, type TargetModeType, createRelationship } from "./relationship/relationship";
|
||||
import { type MacroRelationshipType, type RelationshipType, type TargetModeType, createRelationship } from "./relationship/relationship";
|
||||
|
||||
/**
|
||||
* Represents a collection of relationships in an OPC package.
|
||||
@@ -51,7 +51,7 @@ export class Relationships extends XmlComponent {
|
||||
*/
|
||||
public addRelationship(
|
||||
id: number | string,
|
||||
type: RelationshipType,
|
||||
type: RelationshipType | MacroRelationshipType,
|
||||
target: string,
|
||||
targetMode?: (typeof TargetModeType)[keyof typeof TargetModeType],
|
||||
): void {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { encodeWindows1252 } from "./code-page";
|
||||
|
||||
describe("encodeWindows1252", () => {
|
||||
it("should keep ASCII as it is", () => {
|
||||
expect(encodeWindows1252('MsgBox "Hi"\r\n', "Code")).toEqual(
|
||||
Uint8Array.from('MsgBox "Hi"\r\n', (character) => character.charCodeAt(0)),
|
||||
);
|
||||
});
|
||||
|
||||
it("should encode every character Windows-1252 has as the byte the code page decodes to it", () => {
|
||||
const decoder = new TextDecoder("windows-1252");
|
||||
// The bytes Windows-1252 has no character for, which decoders give as the C1 control characters
|
||||
const unused = new Set([0x81, 0x8d, 0x8f, 0x90, 0x9d]);
|
||||
const all = Array.from({ length: 256 }, (_, byte) => byte).filter((byte) => !unused.has(byte));
|
||||
|
||||
expect(encodeWindows1252(decoder.decode(Uint8Array.from(all)), "Code")).toEqual(Uint8Array.from(all));
|
||||
});
|
||||
|
||||
it("should encode the characters Windows-1252 has where Latin-1 has control characters", () => {
|
||||
expect(encodeWindows1252("€‘’“”–—™", "Code")).toEqual(Uint8Array.from([0x80, 0x91, 0x92, 0x93, 0x94, 0x96, 0x97, 0x99]));
|
||||
});
|
||||
|
||||
it("should throw for a character Windows-1252 doesn't have, saying how to write it", () => {
|
||||
expect(() => encodeWindows1252('MsgBox "中"', "The code of Greetings")).toThrow(
|
||||
'The code of Greetings has "中", which VBA can\'t keep in its code page, Windows-1252. Write it with ChrW instead, such as ChrW(&H4E2D) in a string',
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw for a control character Windows-1252 has no byte for", () => {
|
||||
expect(() => encodeWindows1252("\u0081", "Code")).toThrow("ChrW(&H81)");
|
||||
});
|
||||
|
||||
it("should say to write a character beyond U+FFFF, which ChrW can't take, as its two UTF-16 halves", () => {
|
||||
expect(() => encodeWindows1252('MsgBox "😀"', "Code")).toThrow("such as ChrW(&HD83D) & ChrW(&HDE00) in a string");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* The code page the VBA project's text is written in: its code, and the names of the project and its modules.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/**
|
||||
* Windows-1252, the code page of VBA in Word set to English and the other Western European languages. Its number goes in
|
||||
* the project, which is how VBA knows it.
|
||||
*/
|
||||
export const CODE_PAGE = 1252;
|
||||
|
||||
// Windows-1252's characters from 0x80 to 0x9F, where Latin-1 has control characters. It has none at 0x81, 0x8D, 0x8F,
|
||||
// 0x90 and 0x9D. From 0xA0 on, it has Latin-1's characters, as Unicode has them
|
||||
const CHARACTERS_FROM_0X80 = "€_‚ƒ„…†‡ˆ‰Š‹Œ_Ž__‘’“”•–—˜™š›œ_žŸ";
|
||||
|
||||
const BYTES = new Map([...CHARACTERS_FROM_0X80].flatMap((character, index) => (character === "_" ? [] : [[character, 0x80 + index]])));
|
||||
|
||||
/**
|
||||
* Encodes text in Windows-1252.
|
||||
*
|
||||
* @param what - What the text is, for the error, such as `The code of module "Greetings"`
|
||||
* @throws If the text has a character Windows-1252 doesn't
|
||||
*/
|
||||
export const encodeWindows1252 = (text: string, what: string): Uint8Array =>
|
||||
Uint8Array.from([...text], (character) => {
|
||||
const code = character.codePointAt(0)!;
|
||||
const byte = code < 0x80 || (code >= 0xa0 && code <= 0xff) ? code : BYTES.get(character);
|
||||
if (byte === undefined) {
|
||||
// ChrW takes a UTF-16 code unit, up to U+FFFF, so a character beyond that is two: its surrogate pair
|
||||
const chrW = Array.from(
|
||||
{ length: character.length },
|
||||
(_, index) => `ChrW(&H${character.charCodeAt(index).toString(16).toUpperCase()})`,
|
||||
);
|
||||
throw new Error(
|
||||
`${what} has "${character}", which VBA can't keep in its code page, Windows-1252. ` +
|
||||
`Write it with ChrW instead, such as ${chrW.join(" & ")} in a string`,
|
||||
);
|
||||
}
|
||||
return byte;
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type CompoundFileDirectoryEntry, readCompoundFile } from "tests/macros";
|
||||
|
||||
import { createCompoundFile } from "./compound-file";
|
||||
|
||||
const NO_STREAM = 0xffffffff;
|
||||
|
||||
const bytes = (length: number, value: number): Uint8Array => new Uint8Array(length).fill(value);
|
||||
|
||||
// The order of a storage's tree: a shorter name first, then by the names in capitals
|
||||
const compareNames = (a: string, b: string): number =>
|
||||
a.length - b.length || (a.toUpperCase() < b.toUpperCase() ? -1 : a.toUpperCase() > b.toUpperCase() ? 1 : 0);
|
||||
|
||||
/**
|
||||
* Checks that the tree of a storage's entries, from the entry with the id, is a binary search tree in the file's order
|
||||
* and a red-black tree, returning its names in order and the number of black entries on each path down it.
|
||||
*/
|
||||
const checkTree = (
|
||||
entries: readonly CompoundFileDirectoryEntry[],
|
||||
id: number,
|
||||
parentRed = false,
|
||||
): { readonly names: readonly string[]; readonly blackHeight: number } => {
|
||||
if (id === NO_STREAM) {
|
||||
return { names: [], blackHeight: 0 };
|
||||
}
|
||||
const entry = entries[id];
|
||||
const red = entry.color === 0;
|
||||
expect(red && parentRed, `${entry.name} is red under a red entry`).toBe(false);
|
||||
const left = checkTree(entries, entry.left, red);
|
||||
const right = checkTree(entries, entry.right, red);
|
||||
expect(left.blackHeight, `the paths down from ${entry.name} have as many black entries`).toBe(right.blackHeight);
|
||||
const names = [...left.names, entry.name, ...right.names];
|
||||
for (let index = 1; index < names.length; index++) {
|
||||
expect(compareNames(names[index - 1], names[index])).toBeLessThan(0);
|
||||
}
|
||||
return { names, blackHeight: left.blackHeight + (red ? 0 : 1) };
|
||||
};
|
||||
|
||||
describe("createCompoundFile", () => {
|
||||
it("should write a version 3 file with 512-byte sectors and 64-byte mini sectors", () => {
|
||||
const { header } = readCompoundFile(createCompoundFile([{ name: "PROJECT", data: bytes(10, 1) }]));
|
||||
|
||||
expect(header).toEqual({
|
||||
minorVersion: 0x003e,
|
||||
majorVersion: 3,
|
||||
byteOrder: 0xfffe,
|
||||
sectorShift: 9,
|
||||
miniSectorShift: 6,
|
||||
miniStreamCutoff: 4096,
|
||||
});
|
||||
});
|
||||
|
||||
it("should write each stream, in its storage, to be read back", () => {
|
||||
const file = readCompoundFile(
|
||||
createCompoundFile([
|
||||
{ name: "VBA", children: [{ name: "dir", data: bytes(545, 2) }] },
|
||||
{ name: "PROJECT", data: bytes(64, 3) },
|
||||
{ name: "PROJECTwm", data: bytes(1, 4) },
|
||||
]),
|
||||
);
|
||||
|
||||
expect(file.streams).toEqual(
|
||||
new Map([
|
||||
["PROJECT", bytes(64, 3)],
|
||||
["PROJECTwm", bytes(1, 4)],
|
||||
["VBA/dir", bytes(545, 2)],
|
||||
]),
|
||||
);
|
||||
expect(file.entries[0]).toMatchObject({ name: "Root Entry", type: 5, color: 1 });
|
||||
expect(file.entries.find((entry) => entry.name === "VBA")).toMatchObject({ type: 1, start: 0, size: 0 });
|
||||
});
|
||||
|
||||
it("should write a stream of 4096 bytes or more in the file's own sectors, and a shorter one in the mini stream", () => {
|
||||
const file = readCompoundFile(
|
||||
createCompoundFile([
|
||||
{ name: "Large", data: bytes(4096, 5) },
|
||||
{ name: "Larger", data: bytes(10000, 6) },
|
||||
{ name: "Small", data: bytes(4095, 7) },
|
||||
]),
|
||||
);
|
||||
|
||||
expect(file.streams.get("Large")).toEqual(bytes(4096, 5));
|
||||
expect(file.streams.get("Larger")).toEqual(bytes(10000, 6));
|
||||
expect(file.streams.get("Small")).toEqual(bytes(4095, 7));
|
||||
// The root's stream is the mini stream, which only the small stream is in
|
||||
expect(file.entries[0].size).toBe(4096);
|
||||
});
|
||||
|
||||
it("should write a file without a mini stream when every stream is large", () => {
|
||||
const file = readCompoundFile(createCompoundFile([{ name: "Large", data: bytes(5000, 8) }]));
|
||||
|
||||
expect(file.streams.get("Large")).toEqual(bytes(5000, 8));
|
||||
expect(file.entries[0]).toMatchObject({ start: 0xfffffffe, size: 0 });
|
||||
});
|
||||
|
||||
it("should link each storage's entries into a red-black tree in the file's order", () => {
|
||||
// Names of different lengths and cases, in no order, so the tree has to sort them
|
||||
const names = ["_VBA_PROJECT", "dir", "ThisDocument", "Module1", "a", "B", "Counter", "Formatting", "__SRP_0", "Zeta", "x1"];
|
||||
const file = readCompoundFile(
|
||||
createCompoundFile([{ name: "VBA", children: names.map((name, index) => ({ name, data: bytes(index + 1, index) })) }]),
|
||||
);
|
||||
const vba = file.entries.find((entry) => entry.name === "VBA")!;
|
||||
const tree = checkTree(file.entries, vba.child);
|
||||
|
||||
expect(tree.names).toEqual([...names].sort(compareNames));
|
||||
expect(file.entries[vba.child].color).toBe(1);
|
||||
for (const [index, name] of names.entries()) {
|
||||
expect(file.streams.get(`VBA/${name}`)).toEqual(bytes(index + 1, index));
|
||||
}
|
||||
});
|
||||
|
||||
it("should write a directory and a FAT of more than one sector each", () => {
|
||||
const children = Array.from({ length: 40 }, (_, index) => ({ name: `Stream${index}`, data: bytes(4096 + index, index) }));
|
||||
const file = readCompoundFile(createCompoundFile(children));
|
||||
|
||||
expect(file.streams.size).toBe(40);
|
||||
for (const [index, { name }] of children.entries()) {
|
||||
expect(file.streams.get(name)).toEqual(bytes(4096 + index, index));
|
||||
}
|
||||
checkTree(file.entries, file.entries[0].child);
|
||||
});
|
||||
|
||||
it("should write an empty storage", () => {
|
||||
const file = readCompoundFile(createCompoundFile([{ name: "VBA", children: [] }]));
|
||||
|
||||
expect(file.streams.size).toBe(0);
|
||||
expect(file.entries.find((entry) => entry.name === "VBA")).toMatchObject({ type: 1, child: NO_STREAM });
|
||||
});
|
||||
|
||||
it("should throw for a file too large for the sectors of the FAT the header lists", () => {
|
||||
// 109 sectors of the FAT, of 128 sector numbers each, are 109 × 128 sectors of 512 bytes
|
||||
expect(() => createCompoundFile([{ name: "Large", data: new Uint8Array(109 * 128 * 512) }])).toThrow(
|
||||
"A compound file of more than 7143424 bytes isn't supported",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw for two entries of a storage with the same name, ignoring case", () => {
|
||||
expect(() =>
|
||||
createCompoundFile([
|
||||
{ name: "Module1", data: bytes(1, 0) },
|
||||
{ name: "MODULE1", data: bytes(1, 0) },
|
||||
]),
|
||||
).toThrow('Two compound file entries in a storage are named "MODULE1"');
|
||||
});
|
||||
|
||||
it.each(["", "a".repeat(32), "a/b", "a\\b", "a:b", "a!b"])("should throw for the name %j", (name) => {
|
||||
expect(() => createCompoundFile([{ name, data: bytes(1, 0) }])).toThrow(`Invalid compound file entry name "${name}"`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,280 @@
|
||||
/**
|
||||
* Writes a compound file, the format a VBA project is kept in: a file system in a file, with storages, its folders, and
|
||||
* streams, its files.
|
||||
*
|
||||
* Reference: [MS-CFB] Compound File Binary File Format
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/**
|
||||
* A stream of a compound file: a file in it.
|
||||
*/
|
||||
export type CompoundFileStream = {
|
||||
readonly name: string;
|
||||
readonly data: Uint8Array;
|
||||
};
|
||||
|
||||
/**
|
||||
* A storage of a compound file: a folder in it.
|
||||
*/
|
||||
export type CompoundFileStorage = {
|
||||
readonly name: string;
|
||||
readonly children: readonly CompoundFileEntry[];
|
||||
};
|
||||
|
||||
export type CompoundFileEntry = CompoundFileStream | CompoundFileStorage;
|
||||
|
||||
// Version 3 files have 512-byte sectors. Streams shorter than 4096 bytes are kept in the mini stream instead, in 64-byte
|
||||
// mini sectors, which the root's stream holds
|
||||
const SECTOR_SIZE = 512;
|
||||
const MINI_SECTOR_SIZE = 64;
|
||||
const MINI_STREAM_CUTOFF = 4096;
|
||||
const DIRECTORY_ENTRY_SIZE = 128;
|
||||
// The number of sector numbers a sector of the FAT holds, and the number of FAT sectors the header lists
|
||||
const SECTOR_NUMBERS_PER_SECTOR = SECTOR_SIZE / 4;
|
||||
const HEADER_FAT_SECTORS = 109;
|
||||
|
||||
const FREE_SECTOR = 0xffffffff;
|
||||
const END_OF_CHAIN = 0xfffffffe;
|
||||
const FAT_SECTOR = 0xfffffffd;
|
||||
const NO_STREAM = 0xffffffff;
|
||||
|
||||
const STORAGE = 1;
|
||||
const STREAM = 2;
|
||||
const ROOT_STORAGE = 5;
|
||||
const RED = 0;
|
||||
const BLACK = 1;
|
||||
|
||||
type DirectoryEntry = {
|
||||
readonly name: string;
|
||||
readonly type: typeof STORAGE | typeof STREAM | typeof ROOT_STORAGE;
|
||||
readonly data?: Uint8Array;
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
left: number;
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
right: number;
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
child: number;
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
color: typeof RED | typeof BLACK;
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
start: number;
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
size: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Orders the entries of a storage as the file's red-black trees do: a shorter name first, then by the names in capitals.
|
||||
*/
|
||||
const compareNames = (a: string, b: string): number => {
|
||||
if (a.length !== b.length) {
|
||||
return a.length - b.length;
|
||||
}
|
||||
const upperA = a.toUpperCase();
|
||||
const upperB = b.toUpperCase();
|
||||
return upperA < upperB ? -1 : upperA > upperB ? 1 : 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Links a storage's entries, in order, into a balanced tree that is a valid red-black tree: the entries on its deepest
|
||||
* level are red, and the rest black.
|
||||
*
|
||||
* @returns The id of the tree's root
|
||||
*/
|
||||
const linkTree = (entries: readonly DirectoryEntry[], ids: readonly number[]): number => {
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const depths: number[] = [];
|
||||
const link = (from: number, to: number, depth: number): number => {
|
||||
if (from > to) {
|
||||
return NO_STREAM;
|
||||
}
|
||||
const middle = Math.floor((from + to) / 2);
|
||||
const entry = entries[ids[middle]];
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
depths[middle] = depth;
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
entry.left = link(from, middle - 1, depth + 1);
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
entry.right = link(middle + 1, to, depth + 1);
|
||||
return ids[middle];
|
||||
};
|
||||
const root = link(0, ids.length - 1, 0);
|
||||
const deepest = Math.max(...depths);
|
||||
for (const [index, id] of ids.entries()) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
entries[id].color = depths[index] === deepest && deepest > 0 ? RED : BLACK;
|
||||
}
|
||||
return root;
|
||||
};
|
||||
|
||||
/**
|
||||
* The directory's entries, the root first, with each storage's entries linked into its tree.
|
||||
*/
|
||||
const createDirectory = (children: readonly CompoundFileEntry[]): readonly DirectoryEntry[] => {
|
||||
const entry = (name: string, type: DirectoryEntry["type"], data?: Uint8Array): DirectoryEntry => {
|
||||
// A name has at most 31 UTF-16 code units, and none of "/", "\", ":" and "!"
|
||||
if (name.length === 0 || name.length > 31 || /[/\\:!]/.test(name)) {
|
||||
throw new Error(`Invalid compound file entry name "${name}"`);
|
||||
}
|
||||
return { name, type, data, left: NO_STREAM, right: NO_STREAM, child: NO_STREAM, color: BLACK, start: 0, size: 0 };
|
||||
};
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const entries: DirectoryEntry[] = [entry("Root Entry", ROOT_STORAGE)];
|
||||
const addChildren = (parent: DirectoryEntry, storageChildren: readonly CompoundFileEntry[]): void => {
|
||||
const sorted = [...storageChildren].sort((a, b) => compareNames(a.name, b.name));
|
||||
for (const [index, child] of sorted.entries()) {
|
||||
if (index > 0 && compareNames(sorted[index - 1].name, child.name) === 0) {
|
||||
throw new Error(`Two compound file entries in a storage are named "${child.name}"`);
|
||||
}
|
||||
}
|
||||
const ids = sorted.map((child) => {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
entries.push("children" in child ? entry(child.name, STORAGE) : entry(child.name, STREAM, child.data));
|
||||
return entries.length - 1;
|
||||
});
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
parent.child = ids.length === 0 ? NO_STREAM : linkTree(entries, ids);
|
||||
for (const [index, child] of sorted.entries()) {
|
||||
if ("children" in child) {
|
||||
addChildren(entries[ids[index]], child.children);
|
||||
}
|
||||
}
|
||||
};
|
||||
addChildren(entries[0], children);
|
||||
return entries;
|
||||
};
|
||||
|
||||
/**
|
||||
* Lays out a chain of sectors, each pointing to the next, in a table of sector numbers, such as the FAT.
|
||||
*
|
||||
* @returns The chain's first sector, or END_OF_CHAIN for none
|
||||
*/
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const addChain = (table: number[], count: number, value?: number): number => {
|
||||
if (count === 0) {
|
||||
return END_OF_CHAIN;
|
||||
}
|
||||
const start = table.length;
|
||||
for (let index = 0; index < count; index++) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
table.push(value ?? (index === count - 1 ? END_OF_CHAIN : start + index + 1));
|
||||
}
|
||||
return start;
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes a compound file of version 3, as Office writes VBA projects.
|
||||
*
|
||||
* @param children - The root storage's streams and storages
|
||||
* @throws If two entries of a storage have the same name, ignoring case, or a name is empty, longer than 31 characters or
|
||||
* has "/", "\", ":" or "!"
|
||||
*/
|
||||
export const createCompoundFile = (children: readonly CompoundFileEntry[]): Uint8Array => {
|
||||
const entries = createDirectory(children);
|
||||
const streams = entries.filter((entry) => entry.type === STREAM);
|
||||
const miniStreams = streams.filter((entry) => entry.data!.length < MINI_STREAM_CUTOFF);
|
||||
const largeStreams = streams.filter((entry) => entry.data!.length >= MINI_STREAM_CUTOFF);
|
||||
|
||||
// The mini stream, with its own table of mini sectors, the mini FAT
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const miniFat: number[] = [];
|
||||
for (const stream of miniStreams) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
stream.start = addChain(miniFat, Math.ceil(stream.data!.length / MINI_SECTOR_SIZE));
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
stream.size = stream.data!.length;
|
||||
}
|
||||
const miniStreamSize = miniFat.length * MINI_SECTOR_SIZE;
|
||||
|
||||
// The sectors: the directory, the mini FAT, the mini stream, the large streams, then the FAT, which counts itself
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const fat: number[] = [];
|
||||
const directoryStart = addChain(fat, Math.ceil(entries.length / (SECTOR_SIZE / DIRECTORY_ENTRY_SIZE)));
|
||||
const miniFatSectors = Math.ceil(miniFat.length / SECTOR_NUMBERS_PER_SECTOR);
|
||||
const miniFatStart = addChain(fat, miniFatSectors);
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
entries[0].start = addChain(fat, Math.ceil(miniStreamSize / SECTOR_SIZE));
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
entries[0].size = miniStreamSize;
|
||||
for (const stream of largeStreams) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
stream.start = addChain(fat, Math.ceil(stream.data!.length / SECTOR_SIZE));
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
stream.size = stream.data!.length;
|
||||
}
|
||||
let fatSectors = 0;
|
||||
while (fatSectors * SECTOR_NUMBERS_PER_SECTOR < fat.length + fatSectors) {
|
||||
fatSectors++;
|
||||
}
|
||||
if (fatSectors > HEADER_FAT_SECTORS) {
|
||||
throw new Error(
|
||||
`A compound file of more than ${HEADER_FAT_SECTORS * SECTOR_NUMBERS_PER_SECTOR * SECTOR_SIZE} bytes isn't supported`,
|
||||
);
|
||||
}
|
||||
const fatStart = addChain(fat, fatSectors, FAT_SECTOR);
|
||||
|
||||
const file = new Uint8Array(SECTOR_SIZE + fat.length * SECTOR_SIZE);
|
||||
const view = new DataView(file.buffer);
|
||||
const sectorOffset = (sector: number): number => SECTOR_SIZE + sector * SECTOR_SIZE;
|
||||
|
||||
// The header
|
||||
file.set([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]);
|
||||
view.setUint16(24, 0x003e, true);
|
||||
view.setUint16(26, 0x0003, true);
|
||||
view.setUint16(28, 0xfffe, true);
|
||||
view.setUint16(30, 9, true);
|
||||
view.setUint16(32, 6, true);
|
||||
view.setUint32(44, fatSectors, true);
|
||||
view.setUint32(48, directoryStart, true);
|
||||
view.setUint32(56, MINI_STREAM_CUTOFF, true);
|
||||
view.setUint32(60, miniFatStart, true);
|
||||
view.setUint32(64, miniFatSectors, true);
|
||||
view.setUint32(68, END_OF_CHAIN, true);
|
||||
for (let index = 0; index < HEADER_FAT_SECTORS; index++) {
|
||||
view.setUint32(76 + index * 4, index < fatSectors ? fatStart + index : FREE_SECTOR, true);
|
||||
}
|
||||
|
||||
// The directory. Its unused entries are zeros, but for their links
|
||||
for (let index = 0; index < Math.ceil(entries.length / 4) * 4; index++) {
|
||||
const offset = sectorOffset(directoryStart) + index * DIRECTORY_ENTRY_SIZE;
|
||||
const entry = entries[index];
|
||||
if (entry === undefined) {
|
||||
view.setUint32(offset + 68, NO_STREAM, true);
|
||||
view.setUint32(offset + 72, NO_STREAM, true);
|
||||
view.setUint32(offset + 76, NO_STREAM, true);
|
||||
continue;
|
||||
}
|
||||
for (let position = 0; position < entry.name.length; position++) {
|
||||
view.setUint16(offset + position * 2, entry.name.charCodeAt(position), true);
|
||||
}
|
||||
view.setUint16(offset + 64, (entry.name.length + 1) * 2, true);
|
||||
view.setUint8(offset + 66, entry.type);
|
||||
view.setUint8(offset + 67, entry.color);
|
||||
view.setUint32(offset + 68, entry.left, true);
|
||||
view.setUint32(offset + 72, entry.right, true);
|
||||
view.setUint32(offset + 76, entry.child, true);
|
||||
view.setUint32(offset + 116, entry.type === STORAGE ? 0 : entry.start, true);
|
||||
view.setUint32(offset + 120, entry.size, true);
|
||||
}
|
||||
|
||||
// The mini FAT, with its unused sector numbers free
|
||||
for (let index = 0; index < miniFatSectors * SECTOR_NUMBERS_PER_SECTOR; index++) {
|
||||
view.setUint32(sectorOffset(miniFatStart) + index * 4, miniFat[index] ?? FREE_SECTOR, true);
|
||||
}
|
||||
|
||||
// The mini stream, then the large streams
|
||||
for (const stream of miniStreams) {
|
||||
file.set(stream.data!, sectorOffset(entries[0].start) + stream.start * MINI_SECTOR_SIZE);
|
||||
}
|
||||
for (const stream of largeStreams) {
|
||||
file.set(stream.data!, sectorOffset(stream.start));
|
||||
}
|
||||
|
||||
// The FAT, with its unused sector numbers free
|
||||
for (let index = 0; index < fatSectors * SECTOR_NUMBERS_PER_SECTOR; index++) {
|
||||
view.setUint32(sectorOffset(fatStart) + index * 4, fat[index] ?? FREE_SECTOR, true);
|
||||
}
|
||||
|
||||
return file;
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decompress } from "tests/macros";
|
||||
|
||||
import { compress } from "./compression";
|
||||
|
||||
const bytes = (text: string): Uint8Array => Uint8Array.from(text, (character) => character.charCodeAt(0));
|
||||
const hex = (text: string): Uint8Array => Uint8Array.from(text.split(" "), (byte) => parseInt(byte, 16));
|
||||
|
||||
describe("compress", () => {
|
||||
// [MS-OVBA] 3.2 Compression/Decompression Examples
|
||||
it("should compress text with nothing repeated as [MS-OVBA]'s example does", () => {
|
||||
expect(compress(bytes("abcdefghijklmnopqrstuv."))).toEqual(
|
||||
hex("01 19 B0 00 61 62 63 64 65 66 67 68 00 69 6A 6B 6C 6D 6E 6F 70 00 71 72 73 74 75 76 2E"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should compress text with runs repeated as [MS-OVBA]'s example does", () => {
|
||||
expect(compress(bytes("#aaabcdefaaaaghijaaaaaklaaamnopqaaaaaaaaaaaarstuvwxyzaaa"))).toEqual(
|
||||
hex(
|
||||
"01 2F B0 00 23 61 61 61 62 63 64 65 82 66 00 70 61 67 68 69 6A 01 38 08 61 6B 6C 00 20 6D 6E 6F 70 06 71 02 70 04 00 72 73 74 75 76 10 77 78 79 7A 00 2C",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("should compress a repeated character into one copy as [MS-OVBA]'s example does", () => {
|
||||
expect(compress(bytes("a".repeat(73)))).toEqual(hex("01 03 B0 02 61 45 00"));
|
||||
});
|
||||
|
||||
it("should write only the signature for nothing", () => {
|
||||
expect(compress(new Uint8Array())).toEqual(Uint8Array.from([0x01]));
|
||||
});
|
||||
|
||||
it("should compress data longer than a chunk in chunks of 4096 bytes, which decompress to it", () => {
|
||||
const text = bytes(Array.from({ length: 500 }, (_, index) => ` Debug.Print "Line ${index}"\r\n`).join(""));
|
||||
const compressed = compress(text);
|
||||
|
||||
expect(text.length).toBeGreaterThan(3 * 4096);
|
||||
expect(compressed.length).toBeLessThan(text.length / 2);
|
||||
expect(decompress(compressed)).toEqual(text);
|
||||
});
|
||||
|
||||
it("should write a chunk that doesn't compress as it is, padding the last one to 4096 bytes", () => {
|
||||
// Bytes that don't repeat a run of 3, so each is a literal, and a chunk of them grows by its flag bytes. The last
|
||||
// chunk, of 3700, grows to more than 4096 bytes too
|
||||
let seed = 1;
|
||||
const random = Uint8Array.from({ length: 4096 + 3700 }, () => {
|
||||
seed = (seed * 1103515245 + 12345) % 2 ** 31;
|
||||
return Math.floor(seed / 65536);
|
||||
});
|
||||
const compressed = compress(random);
|
||||
|
||||
// The signature, then two uncompressed chunks, each a header with the size 4095 and no compressed flag
|
||||
expect(compressed.length).toBe(1 + 2 * (2 + 4096));
|
||||
expect([compressed[1], compressed[2]]).toEqual([0xff, 0x3f]);
|
||||
expect([compressed[4099], compressed[4100]]).toEqual([0xff, 0x3f]);
|
||||
expect(decompress(compressed)).toEqual(Uint8Array.from([...random, ...new Uint8Array(4096 - 3700)]));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* The compression VBA uses for a project's module information and for each module's code, a run length encoding.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.4.1 Compression and Decompression
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
/* eslint-disable no-bitwise -- the compressed data is made of bit fields */
|
||||
|
||||
// Data is compressed in chunks of this many bytes, and each chunk's compressed bytes, after its header, are at most this
|
||||
// many too. A chunk that doesn't compress to fewer is written as it is
|
||||
const CHUNK_SIZE = 4096;
|
||||
|
||||
// The bits of a chunk's header after its size: the signature, 0b011, and whether the chunk is compressed
|
||||
const CHUNK_SIGNATURE = 0x3000;
|
||||
const CHUNK_COMPRESSED = 0x8000;
|
||||
|
||||
/**
|
||||
* The bits of a copy token that hold the copy's length, the rest holding its offset. The further into its chunk a copy
|
||||
* is, the more bits its offset can need.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.4.1.3.19.1 CopyToken Help
|
||||
*
|
||||
* @param position - How far into its chunk the copy is, at least 1
|
||||
*/
|
||||
const lengthBitsAt = (position: number): number => 16 - Math.max(32 - Math.clz32(position - 1), 4);
|
||||
|
||||
/**
|
||||
* The longest earlier run of bytes in the chunk that the bytes from `current` repeat, the nearest of the longest.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.4.1.3.19.4 Matching
|
||||
*
|
||||
* @returns How far back the run starts and how long it is, or `undefined` for none of at least 3 bytes
|
||||
*/
|
||||
const findMatch = (
|
||||
data: Uint8Array,
|
||||
chunkStart: number,
|
||||
current: number,
|
||||
chunkEnd: number,
|
||||
): { readonly offset: number; readonly length: number } | undefined => {
|
||||
let bestLength = 0;
|
||||
let bestCandidate = 0;
|
||||
for (let candidate = current - 1; candidate >= chunkStart; candidate--) {
|
||||
let length = 0;
|
||||
// A run can overlap the bytes it is copied to, as a repeated character does
|
||||
while (current + length < chunkEnd && data[current + length] === data[candidate + length]) {
|
||||
length++;
|
||||
}
|
||||
if (length > bestLength) {
|
||||
bestLength = length;
|
||||
bestCandidate = candidate;
|
||||
}
|
||||
}
|
||||
if (bestLength < 3) {
|
||||
return undefined;
|
||||
}
|
||||
const maximumLength = (1 << lengthBitsAt(current - chunkStart)) - 1 + 3;
|
||||
return { offset: current - bestCandidate, length: Math.min(bestLength, maximumLength) };
|
||||
};
|
||||
|
||||
/**
|
||||
* Compresses a chunk: groups of up to eight tokens, each group after a byte whose bits say which of its tokens are a
|
||||
* byte as it is and which copy earlier bytes.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.4.1.3.7 Compressing a DecompressedChunk
|
||||
*/
|
||||
const compressChunk = (data: Uint8Array, chunkStart: number, chunkEnd: number): readonly number[] => {
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const tokens: number[] = [];
|
||||
let current = chunkStart;
|
||||
while (current < chunkEnd) {
|
||||
const flagIndex = tokens.length;
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
tokens.push(0);
|
||||
for (let index = 0; index < 8 && current < chunkEnd; index++) {
|
||||
const match = findMatch(data, chunkStart, current, chunkEnd);
|
||||
if (match === undefined) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
tokens.push(data[current]);
|
||||
current++;
|
||||
} else {
|
||||
const lengthBits = lengthBitsAt(current - chunkStart);
|
||||
const token = ((match.offset - 1) << lengthBits) | (match.length - 3);
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
tokens.push(token & 0xff, token >> 8);
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
tokens[flagIndex] |= 1 << index;
|
||||
current += match.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The header has the chunk's size, with the header, less 3
|
||||
if (tokens.length <= CHUNK_SIZE) {
|
||||
const compressedHeader = CHUNK_COMPRESSED | CHUNK_SIGNATURE | (tokens.length + 2 - 3);
|
||||
return [compressedHeader & 0xff, compressedHeader >> 8, ...tokens];
|
||||
}
|
||||
|
||||
// An uncompressed chunk is always 4096 bytes, so a short last one is padded with zeros
|
||||
const header = CHUNK_SIGNATURE | (CHUNK_SIZE + 2 - 3);
|
||||
const raw = new Uint8Array(CHUNK_SIZE);
|
||||
raw.set(data.subarray(chunkStart, chunkEnd));
|
||||
return [header & 0xff, header >> 8, ...raw];
|
||||
};
|
||||
|
||||
/**
|
||||
* Compresses data as VBA does.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.4.1.3.6 Compression algorithm
|
||||
*/
|
||||
export const compress = (data: Uint8Array): Uint8Array => {
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const output: number[] = [0x01];
|
||||
for (let chunkStart = 0; chunkStart < data.length; chunkStart += CHUNK_SIZE) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
output.push(...compressChunk(data, chunkStart, Math.min(chunkStart + CHUNK_SIZE, data.length)));
|
||||
}
|
||||
return Uint8Array.from(output);
|
||||
};
|
||||
@@ -0,0 +1,373 @@
|
||||
import JSZip from "jszip";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
import { decompress, readCompoundFile } from "tests/macros";
|
||||
|
||||
import { createMacros } from "./create-macros";
|
||||
|
||||
const text = (bytes: Uint8Array): string => String.fromCharCode(...bytes);
|
||||
|
||||
/** The streams of the project, by their paths */
|
||||
const streamsOf = (options: Parameters<typeof createMacros>[0]): ReadonlyMap<string, Uint8Array> =>
|
||||
readCompoundFile(createMacros(options).project).streams;
|
||||
|
||||
/** A module's code, as VBA reads it from its stream */
|
||||
const sourceOf = (streams: ReadonlyMap<string, Uint8Array>, name: string): string => text(decompress(streams.get(`VBA/${name}`)!));
|
||||
|
||||
type Record = { readonly id: number; readonly data: Uint8Array };
|
||||
|
||||
/**
|
||||
* The records of the dir stream, each its id and data. PROJECTVERSION's size is always 4, before 6 bytes of data.
|
||||
*/
|
||||
const dirRecordsOf = (streams: ReadonlyMap<string, Uint8Array>): readonly Record[] => {
|
||||
const dir = decompress(streams.get("VBA/dir")!);
|
||||
const view = new DataView(dir.buffer);
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const records: Record[] = [];
|
||||
for (let offset = 0; offset < dir.length;) {
|
||||
const id = view.getUint16(offset, true);
|
||||
const size = id === 0x0009 ? 6 : view.getUint32(offset + 2, true);
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
records.push({ id, data: dir.subarray(offset + 6, offset + 6 + size) });
|
||||
offset += 6 + size;
|
||||
}
|
||||
return records;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverses VBA's obfuscation of one of the project's properties, given as hexadecimal digits.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.4.3.3 Decryption
|
||||
*/
|
||||
const deobfuscate = (
|
||||
digits: string,
|
||||
projectId: string,
|
||||
): { readonly version: number; readonly keyMatches: boolean; readonly length: number; readonly data: readonly number[] } => {
|
||||
/* eslint-disable no-bitwise */
|
||||
const bytes = digits.match(/../g)!.map((pair) => parseInt(pair, 16));
|
||||
const [seed, versionEncrypted, projectKeyEncrypted, ...rest] = bytes;
|
||||
const projectKey = seed ^ projectKeyEncrypted;
|
||||
let unencrypted = projectKey;
|
||||
let encrypted = projectKeyEncrypted;
|
||||
let previousEncrypted = versionEncrypted;
|
||||
const plain = rest.map((byteEncrypted) => {
|
||||
const byte = byteEncrypted ^ ((previousEncrypted + unencrypted) & 0xff);
|
||||
previousEncrypted = encrypted;
|
||||
encrypted = byteEncrypted;
|
||||
unencrypted = byte;
|
||||
return byte;
|
||||
});
|
||||
const [length0, length1, length2, length3, ...data] = plain.slice((seed & 6) / 2);
|
||||
return {
|
||||
version: seed ^ versionEncrypted,
|
||||
keyMatches: [...projectId].reduce((sum, character) => (sum + character.charCodeAt(0)) & 0xff, 0) === projectKey,
|
||||
length: length0 | (length1 << 8) | (length2 << 16) | (length3 << 24),
|
||||
data,
|
||||
};
|
||||
/* eslint-enable no-bitwise */
|
||||
};
|
||||
|
||||
describe("deobfuscate", () => {
|
||||
// [MS-OVBA] 3.1.6 PROJECT Stream Example, which checks the test's own deobfuscation
|
||||
it("should read [MS-OVBA]'s example project's properties", () => {
|
||||
const id = "{917DED54-440B-4FD1-A5C1-74ACF261E600}";
|
||||
|
||||
expect(deobfuscate("0705D8E3D8EDDBF1DBF1DBF1DBF1", id)).toMatchObject({ version: 2, keyMatches: true, length: 4 });
|
||||
expect(deobfuscate("0E0CD1ECDFF4E7F5E7F5E7", id)).toEqual({ version: 2, keyMatches: true, length: 1, data: [0x00] });
|
||||
expect(deobfuscate("1517CAF1D6F9D7F9D706", id)).toEqual({ version: 2, keyMatches: true, length: 1, data: [0xff] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("createMacros", () => {
|
||||
it("should write a VBA project with the document's module, ThisDocument, and the given modules, in a compound file", () => {
|
||||
const streams = streamsOf({
|
||||
modules: [{ name: "Formatting", code: "Sub MakeBold()\nEnd Sub" }],
|
||||
classModules: [{ name: "Counter", code: "Public Count As Long" }],
|
||||
});
|
||||
|
||||
expect([...streams.keys()].sort()).toEqual([
|
||||
"PROJECT",
|
||||
"PROJECTwm",
|
||||
"VBA/Counter",
|
||||
"VBA/Formatting",
|
||||
"VBA/ThisDocument",
|
||||
"VBA/_VBA_PROJECT",
|
||||
"VBA/dir",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should write no compiled cache, so VBA compiles the code again", () => {
|
||||
// Reserved1, Version 0xFFFF, which tells VBA the cache isn't its own, Reserved2 and Reserved3
|
||||
expect(streamsOf({}).get("VBA/_VBA_PROJECT")).toEqual(Uint8Array.from([0xcc, 0x61, 0xff, 0xff, 0x00, 0x01, 0x00]));
|
||||
});
|
||||
|
||||
it("should write the project's properties, with each module, unlocked, without a password, and shown", () => {
|
||||
const project = text(
|
||||
streamsOf({
|
||||
modules: [{ name: "Formatting", code: "" }],
|
||||
classModules: [{ name: "Counter", code: "" }],
|
||||
}).get("PROJECT")!,
|
||||
);
|
||||
const lines = project.split("\r\n");
|
||||
const property = (name: string): string => lines.find((line) => line.startsWith(`${name}=`))!.slice(name.length + 2, -1);
|
||||
const id = property("ID");
|
||||
|
||||
expect(project.endsWith("\r\n")).toBe(true);
|
||||
expect(lines).toEqual([
|
||||
expect.stringMatching(/^ID="\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}"$/),
|
||||
"Document=ThisDocument/&H00000000",
|
||||
"Module=Formatting",
|
||||
"Class=Counter",
|
||||
'Name="Project"',
|
||||
'HelpContextID="0"',
|
||||
'VersionCompatible32="393222000"',
|
||||
expect.stringMatching(/^CMG="[0-9A-F]{22,28}"$/),
|
||||
expect.stringMatching(/^DPB="[0-9A-F]{16,}"$/),
|
||||
expect.stringMatching(/^GC="[0-9A-F]{16,22}"$/),
|
||||
"",
|
||||
"[Host Extender Info]",
|
||||
"&H00000001={3832D640-CF90-11CF-8E43-00A0C911005A};VBE;&H00000000",
|
||||
"",
|
||||
"[Workspace]",
|
||||
"ThisDocument=0, 0, 0, 0, C",
|
||||
"Formatting=0, 0, 0, 0, C",
|
||||
"Counter=0, 0, 0, 0, C",
|
||||
"",
|
||||
]);
|
||||
expect(deobfuscate(property("CMG"), id)).toEqual({ version: 2, keyMatches: true, length: 4, data: [0, 0, 0, 0] });
|
||||
expect(deobfuscate(property("DPB"), id)).toEqual({ version: 2, keyMatches: true, length: 1, data: [0x00] });
|
||||
expect(deobfuscate(property("GC"), id)).toEqual({ version: 2, keyMatches: true, length: 1, data: [0xff] });
|
||||
});
|
||||
|
||||
it("should write the modules' names in Unicode too, in their order, then a terminator", () => {
|
||||
const names = streamsOf({ modules: [{ name: "Formatting", code: "" }] }).get("PROJECTwm")!;
|
||||
const utf16 = (name: string): readonly number[] => [...name].flatMap((character) => [character.charCodeAt(0), 0]);
|
||||
|
||||
expect([...names]).toEqual([
|
||||
...Uint8Array.from("ThisDocument", (character) => character.charCodeAt(0)),
|
||||
0,
|
||||
...utf16("ThisDocument"),
|
||||
0,
|
||||
0,
|
||||
...Uint8Array.from("Formatting", (character) => character.charCodeAt(0)),
|
||||
0,
|
||||
...utf16("Formatting"),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
]);
|
||||
});
|
||||
|
||||
it("should write the project's information, its references, and each module's, as Word does", () => {
|
||||
const records = dirRecordsOf(
|
||||
streamsOf({ modules: [{ name: "Formatting", code: "" }], classModules: [{ name: "Counter", code: "" }] }),
|
||||
);
|
||||
const ids = records.map(({ id }) => id);
|
||||
const data = (id: number): readonly string[] => records.filter((record) => record.id === id).map((record) => text(record.data));
|
||||
|
||||
// PROJECTINFORMATION, the references, PROJECTMODULES, then a MODULE record for each module and the terminator
|
||||
expect(ids).toEqual([
|
||||
0x0001,
|
||||
0x0002,
|
||||
0x0014,
|
||||
0x0003,
|
||||
0x0004,
|
||||
0x0005,
|
||||
0x0040,
|
||||
0x0006,
|
||||
0x003d,
|
||||
0x0007,
|
||||
0x0008,
|
||||
0x0009,
|
||||
0x000c,
|
||||
0x003c,
|
||||
...[0x0016, 0x003e, 0x000d],
|
||||
...[0x0016, 0x003e, 0x000e],
|
||||
...[0x0016, 0x003e, 0x000d],
|
||||
0x000f,
|
||||
0x0013,
|
||||
...[0x0019, 0x0047, 0x001a, 0x0032, 0x001c, 0x0048, 0x0031, 0x001e, 0x002c, 0x0022, 0x002b],
|
||||
...[0x0019, 0x0047, 0x001a, 0x0032, 0x001c, 0x0048, 0x0031, 0x001e, 0x002c, 0x0021, 0x002b],
|
||||
...[0x0019, 0x0047, 0x001a, 0x0032, 0x001c, 0x0048, 0x0031, 0x001e, 0x002c, 0x0022, 0x002b],
|
||||
0x0010,
|
||||
]);
|
||||
// Windows-1252, the project's name, and its three modules
|
||||
expect([...records.find(({ id }) => id === 0x0003)!.data]).toEqual([0xe4, 0x04]);
|
||||
expect(data(0x0004)).toEqual(["Project"]);
|
||||
expect([...records.find(({ id }) => id === 0x000f)!.data]).toEqual([3, 0]);
|
||||
expect(data(0x0016)).toEqual(["stdole", "Normal", "Office"]);
|
||||
expect(data(0x0019)).toEqual(["ThisDocument", "Formatting", "Counter"]);
|
||||
expect(data(0x001a)).toEqual(["ThisDocument", "Formatting", "Counter"]);
|
||||
// Each module's code starts at the start of its stream
|
||||
expect(records.filter(({ id }) => id === 0x0031).map((record) => [...record.data])).toEqual([
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
]);
|
||||
});
|
||||
|
||||
it("should write each module's attributes before its code, with its lines ending in CR LF", () => {
|
||||
const streams = streamsOf({
|
||||
thisDocument: 'Private Sub Document_Open()\n MsgBox "Hi"\nEnd Sub\n',
|
||||
modules: [{ name: "Formatting", code: "Sub MakeBold()\r\n Selection.Font.Bold = True\rEnd Sub" }],
|
||||
classModules: [{ name: "Counter", code: "Public Count As Long" }],
|
||||
});
|
||||
|
||||
expect(sourceOf(streams, "ThisDocument")).toBe(
|
||||
[
|
||||
'Attribute VB_Name = "ThisDocument"',
|
||||
'Attribute VB_Base = "1Normal.ThisDocument"',
|
||||
"Attribute VB_GlobalNameSpace = False",
|
||||
"Attribute VB_Creatable = False",
|
||||
"Attribute VB_PredeclaredId = True",
|
||||
"Attribute VB_Exposed = True",
|
||||
"Attribute VB_TemplateDerived = True",
|
||||
"Attribute VB_Customizable = True",
|
||||
"Private Sub Document_Open()",
|
||||
' MsgBox "Hi"',
|
||||
"End Sub",
|
||||
"",
|
||||
].join("\r\n"),
|
||||
);
|
||||
expect(sourceOf(streams, "Formatting")).toBe(
|
||||
['Attribute VB_Name = "Formatting"', "Sub MakeBold()", " Selection.Font.Bold = True", "End Sub", ""].join("\r\n"),
|
||||
);
|
||||
expect(sourceOf(streams, "Counter")).toBe(
|
||||
[
|
||||
'Attribute VB_Name = "Counter"',
|
||||
'Attribute VB_Base = "0{FCFB3D2A-A0FA-1068-A738-08002B3371B5}"',
|
||||
"Attribute VB_GlobalNameSpace = False",
|
||||
"Attribute VB_Creatable = False",
|
||||
"Attribute VB_PredeclaredId = False",
|
||||
"Attribute VB_Exposed = False",
|
||||
"Attribute VB_TemplateDerived = False",
|
||||
"Attribute VB_Customizable = False",
|
||||
"Public Count As Long",
|
||||
"",
|
||||
].join("\r\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should write ThisDocument with only its attributes when it has no code", () => {
|
||||
expect(sourceOf(streamsOf({}), "ThisDocument").split("\r\n")).toHaveLength(9);
|
||||
});
|
||||
|
||||
it("should write code in Windows-1252", () => {
|
||||
const source = decompress(streamsOf({ modules: [{ name: "Text", code: 'Const Name = "Café"' }] }).get("VBA/Text")!);
|
||||
|
||||
expect([...source.subarray(-4, -3)]).toEqual([0xe9]);
|
||||
});
|
||||
|
||||
describe("events", () => {
|
||||
it("should list the events of the document that ThisDocument handles", () => {
|
||||
const { events } = createMacros({
|
||||
thisDocument: [
|
||||
"Private Sub Document_Open()",
|
||||
"End Sub",
|
||||
"public sub document_close()",
|
||||
"End Sub",
|
||||
"Sub Document_New()",
|
||||
"End Sub",
|
||||
" Private Static Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)",
|
||||
"End Sub",
|
||||
"Private Sub Document_ContentControlBeforeStoreUpdate (ByVal ContentControl As ContentControl, Content As String)",
|
||||
"End Sub",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
expect(events).toEqual(["open", "close", "new", "contentControlOnExit", "contentControlBeforeStoreUpdate"]);
|
||||
});
|
||||
|
||||
it("should list every event Word has, once", () => {
|
||||
const names = [
|
||||
"New",
|
||||
"Open",
|
||||
"Close",
|
||||
"Sync",
|
||||
"XMLAfterInsert",
|
||||
"XMLBeforeDelete",
|
||||
"ContentControlAfterAdd",
|
||||
"ContentControlBeforeDelete",
|
||||
"ContentControlOnExit",
|
||||
"ContentControlOnEnter",
|
||||
"ContentControlBeforeStoreUpdate",
|
||||
"ContentControlBeforeContentUpdate",
|
||||
"BuildingBlockInsert",
|
||||
];
|
||||
const thisDocument = [...names, "Open"].map((name) => `Private Sub Document_${name}()\nEnd Sub`).join("\n");
|
||||
|
||||
expect(createMacros({ thisDocument }).events).toEqual([
|
||||
"new",
|
||||
"open",
|
||||
"close",
|
||||
"sync",
|
||||
"xmlAfterInsert",
|
||||
"xmlBeforeDelete",
|
||||
"contentControlAfterAdd",
|
||||
"contentControlBeforeDelete",
|
||||
"contentControlOnExit",
|
||||
"contentControlOnEnter",
|
||||
"contentControlBeforeStoreUpdate",
|
||||
"contentControlBeforeContentUpdate",
|
||||
"buildingBlockInsert",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave out a commented out handler, a handler in another module, and a procedure that isn't an event", () => {
|
||||
const { events } = createMacros({
|
||||
thisDocument:
|
||||
"' Private Sub Document_Open()\nPrivate Sub Document_Print()\nEnd Sub\nPrivate Function Document_Close()\nEnd Function",
|
||||
modules: [{ name: "Events", code: "Sub Document_Open()\nEnd Sub" }],
|
||||
});
|
||||
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("module names", () => {
|
||||
it.each(["1Module", "My Module", "Café", "_Private", "A".repeat(32), ""])("should throw for the name %j", (name) => {
|
||||
expect(() => createMacros({ modules: [{ name, code: "" }] })).toThrow(
|
||||
`Invalid module name "${name}". Expected a letter, then letters, digits and underscores, up to 31 of them, such as "Formatting"`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should allow a name of 31 letters, digits and underscores", () => {
|
||||
const name = `A_1${"b".repeat(28)}`;
|
||||
|
||||
expect(readCompoundFile(createMacros({ modules: [{ name, code: "" }] }).project).streams.has(`VBA/${name}`)).toBe(true);
|
||||
});
|
||||
|
||||
it("should throw for two modules with the same name, ignoring case, even when one is a class module", () => {
|
||||
expect(() =>
|
||||
createMacros({ modules: [{ name: "Formatting", code: "" }], classModules: [{ name: "FORMATTING", code: "" }] }),
|
||||
).toThrow('Invalid module name "FORMATTING". Formatting is already a name in the project');
|
||||
});
|
||||
|
||||
it.each(["ThisDocument", "thisdocument", "Project", "VBA", "Word", "stdole", "Normal", "Office"])(
|
||||
"should throw for %j, a name the project has already",
|
||||
(name) => {
|
||||
expect(() => createMacros({ modules: [{ name, code: "" }] })).toThrow(`Invalid module name "${name}".`);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw for code with a character Windows-1252 doesn't have, saying which module it is in", () => {
|
||||
expect(() => createMacros({ modules: [{ name: "Greetings", code: 'MsgBox "你好"' }] })).toThrow(
|
||||
'The code of Greetings has "你", which VBA can\'t keep in its code page, Windows-1252.',
|
||||
);
|
||||
});
|
||||
|
||||
it("should give a document a VBA project and the events it handles, as a .docm", async () => {
|
||||
const macros = createMacros({ thisDocument: 'Private Sub Document_Open()\n MsgBox "Hi"\nEnd Sub' });
|
||||
const doc = new Document({ macros, sections: [{ children: [new Paragraph("Hello")] }] });
|
||||
const zip = await JSZip.loadAsync(await Packer.toArrayBuffer(doc));
|
||||
|
||||
expect(await zip.file("word/vbaProject.bin")!.async("uint8array")).toEqual(macros.project);
|
||||
expect(await zip.file("word/vbaData.xml")!.async("string")).toContain("<wne:docEvents><wne:eventDocOpen/></wne:docEvents>");
|
||||
expect(await zip.file("[Content_Types].xml")!.async("string")).toContain(
|
||||
'<Override ContentType="application/vnd.ms-word.document.macroEnabled.main+xml" PartName="/word/document.xml"/>',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,378 @@
|
||||
/**
|
||||
* Writes a document's VBA macros from their code: the VBA project file Word keeps them in, vbaProject.bin.
|
||||
*
|
||||
* Reference: [MS-OVBA] Office VBA File Format Structure
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
/* eslint-disable no-bitwise -- the project's records and its obfuscated properties are bytes */
|
||||
import type { DocumentMacroEvent, DocumentMacros } from "docx";
|
||||
|
||||
import { CODE_PAGE, encodeWindows1252 } from "./code-page";
|
||||
import { createCompoundFile } from "./compound-file";
|
||||
import { compress } from "./compression";
|
||||
|
||||
/**
|
||||
* A module of VBA code, as the VBA editor shows it.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type MacroModule = {
|
||||
/**
|
||||
* The module's name, such as "Formatting". A macro in it is "Formatting.MacroName" when the macro's name alone could
|
||||
* be another module's too. It starts with a letter, then has letters, digits and underscores, up to 31 of them
|
||||
*/
|
||||
readonly name: string;
|
||||
/** The module's code, as it is typed in the VBA editor */
|
||||
readonly code: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Options for {@link createMacros}.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type MacrosOptions = {
|
||||
/**
|
||||
* The code of the document's own module, ThisDocument in the VBA editor, where the document's events are handled,
|
||||
* such as `Document_Open` when it opens
|
||||
*/
|
||||
readonly thisDocument?: string;
|
||||
/** Modules, with the macros Word lists in its Macros dialog, and the procedures and functions they use */
|
||||
readonly modules?: readonly MacroModule[];
|
||||
/** Class modules, which define classes of objects */
|
||||
readonly classModules?: readonly MacroModule[];
|
||||
};
|
||||
|
||||
type ProjectModule = {
|
||||
readonly name: string;
|
||||
readonly kind: "document" | "module" | "class";
|
||||
readonly source: Uint8Array;
|
||||
};
|
||||
|
||||
// The project's name, as Word names a document's project. Word lists macros under it, such as
|
||||
// Project.Formatting.MacroName
|
||||
const PROJECT_NAME = "Project";
|
||||
|
||||
// The id of the project's type library. Word gives each project its own, but VBA doesn't need it to be unique: copies of
|
||||
// a .docm, open together, share theirs
|
||||
const PROJECT_ID = "{6D8A8E5B-1C9F-4E2B-9A4D-3B5F7C2E1D60}";
|
||||
|
||||
// The libraries Word's projects refer to: OLE Automation, the document's template, Normal, and Office's library. VBA and
|
||||
// Word's own libraries are always there, without a reference
|
||||
const REFERENCES = [
|
||||
{
|
||||
name: "stdole",
|
||||
registered: "*\\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\\Windows\\System32\\stdole2.tlb#OLE Automation",
|
||||
},
|
||||
{ name: "Normal", project: "*\\CNormal" },
|
||||
{
|
||||
name: "Office",
|
||||
registered:
|
||||
"*\\G{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}#2.0#0#C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE16\\MSO.DLL#Microsoft Office 16.0 Object Library",
|
||||
},
|
||||
] as const;
|
||||
|
||||
// The names of the project and of the libraries it refers to, which a module can't have too
|
||||
const TAKEN_NAMES = ["ThisDocument", PROJECT_NAME, "VBA", "Word", ...REFERENCES.map(({ name }) => name)];
|
||||
|
||||
// The attributes VBA keeps at the top of each kind of module, which the VBA editor doesn't show. VB_Base is what the
|
||||
// module extends: ThisDocument extends the ThisDocument of the document's template, Normal, and a class module VBA's
|
||||
// class
|
||||
const ATTRIBUTES: Readonly<Record<ProjectModule["kind"], (name: string) => string>> = {
|
||||
document: (name) =>
|
||||
[
|
||||
`Attribute VB_Name = "${name}"`,
|
||||
'Attribute VB_Base = "1Normal.ThisDocument"',
|
||||
"Attribute VB_GlobalNameSpace = False",
|
||||
"Attribute VB_Creatable = False",
|
||||
"Attribute VB_PredeclaredId = True",
|
||||
"Attribute VB_Exposed = True",
|
||||
"Attribute VB_TemplateDerived = True",
|
||||
"Attribute VB_Customizable = True",
|
||||
].join("\r\n"),
|
||||
module: (name) => `Attribute VB_Name = "${name}"`,
|
||||
class: (name) =>
|
||||
[
|
||||
`Attribute VB_Name = "${name}"`,
|
||||
'Attribute VB_Base = "0{FCFB3D2A-A0FA-1068-A738-08002B3371B5}"',
|
||||
"Attribute VB_GlobalNameSpace = False",
|
||||
"Attribute VB_Creatable = False",
|
||||
"Attribute VB_PredeclaredId = False",
|
||||
"Attribute VB_Exposed = False",
|
||||
"Attribute VB_TemplateDerived = False",
|
||||
"Attribute VB_Customizable = False",
|
||||
].join("\r\n"),
|
||||
};
|
||||
|
||||
const uint16 = (value: number): readonly number[] => [value & 0xff, (value >> 8) & 0xff];
|
||||
const uint32 = (value: number): readonly number[] => [value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >>> 24) & 0xff];
|
||||
const utf16 = (text: string): readonly number[] => [...text].flatMap((character) => uint16(character.charCodeAt(0)));
|
||||
|
||||
/**
|
||||
* A record of the project's module information: its id, the size of its data, then its data.
|
||||
*/
|
||||
const record = (id: number, data: readonly number[] | Uint8Array): readonly number[] => [...uint16(id), ...uint32(data.length), ...data];
|
||||
|
||||
/**
|
||||
* Obfuscates one of the project's properties as VBA does, as hexadecimal digits: whether it is locked, its password and
|
||||
* whether it is shown.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.4.3.2 Encryption
|
||||
*
|
||||
* @param seed - Any byte. Its bits 1 and 2 are how many bytes of padding go before the data
|
||||
*/
|
||||
const obfuscate = (data: readonly number[], seed: number): string => {
|
||||
const version = 2;
|
||||
// The sum of the bytes of the project's id, to a byte
|
||||
const projectKey = [...PROJECT_ID].reduce((sum, character) => (sum + character.charCodeAt(0)) & 0xff, 0);
|
||||
const versionEncrypted = seed ^ version;
|
||||
const projectKeyEncrypted = seed ^ projectKey;
|
||||
const output = [seed, versionEncrypted, projectKeyEncrypted];
|
||||
let unencrypted = projectKey;
|
||||
let encrypted = projectKeyEncrypted;
|
||||
let previousEncrypted = versionEncrypted;
|
||||
const write = (byte: number): void => {
|
||||
const value = (byte ^ ((previousEncrypted + unencrypted) & 0xff)) & 0xff;
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
output.push(value);
|
||||
previousEncrypted = encrypted;
|
||||
encrypted = value;
|
||||
unencrypted = byte;
|
||||
};
|
||||
const padding = (seed & 6) / 2;
|
||||
for (let index = 0; index < padding; index++) {
|
||||
write(0);
|
||||
}
|
||||
for (const byte of [...uint32(data.length), ...data]) {
|
||||
write(byte);
|
||||
}
|
||||
return output.map((byte) => byte.toString(16).toUpperCase().padStart(2, "0")).join("");
|
||||
};
|
||||
|
||||
/**
|
||||
* The PROJECT stream: the project's properties, as text.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.3.1 PROJECT Stream
|
||||
*/
|
||||
const createProjectStream = (modules: readonly ProjectModule[]): Uint8Array => {
|
||||
const items = modules.map(({ name, kind }) =>
|
||||
kind === "document" ? `Document=${name}/&H00000000` : kind === "module" ? `Module=${name}` : `Class=${name}`,
|
||||
);
|
||||
const lines = [
|
||||
`ID="${PROJECT_ID}"`,
|
||||
...items,
|
||||
`Name="${PROJECT_NAME}"`,
|
||||
'HelpContextID="0"',
|
||||
'VersionCompatible32="393222000"',
|
||||
// Not locked, with no password, and shown
|
||||
`CMG="${obfuscate(uint32(0), 0x8a)}"`,
|
||||
`DPB="${obfuscate([0x00], 0xa3)}"`,
|
||||
`GC="${obfuscate([0xff], 0xbc)}"`,
|
||||
"",
|
||||
"[Host Extender Info]",
|
||||
"&H00000001={3832D640-CF90-11CF-8E43-00A0C911005A};VBE;&H00000000",
|
||||
"",
|
||||
// The modules' windows in the VBA editor, closed
|
||||
"[Workspace]",
|
||||
...modules.map(({ name }) => `${name}=0, 0, 0, 0, C`),
|
||||
];
|
||||
return encodeWindows1252(lines.map((line) => `${line}\r\n`).join(""), "The project");
|
||||
};
|
||||
|
||||
/**
|
||||
* The PROJECTwm stream: the modules' names in Unicode too.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.3.3 PROJECTwm Stream
|
||||
*/
|
||||
const createNamesStream = (modules: readonly ProjectModule[]): Uint8Array =>
|
||||
Uint8Array.from([...modules.flatMap(({ name }) => [...encodeWindows1252(name, "A module's name"), 0, ...utf16(name), 0, 0]), 0, 0]);
|
||||
|
||||
/**
|
||||
* The dir stream: the project's information, the libraries it refers to and its modules, compressed.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.3.4.2 dir Stream
|
||||
*/
|
||||
const createDirStream = (modules: readonly ProjectModule[]): Uint8Array => {
|
||||
const name = (text: string): readonly number[] => [...encodeWindows1252(text, "A name")];
|
||||
const information = [
|
||||
// For 32-bit Windows, which VBA compiles the project for again on any other
|
||||
...record(0x0001, uint32(1)),
|
||||
// English, which VBA keeps the project in on any system
|
||||
...record(0x0002, uint32(0x0409)),
|
||||
...record(0x0014, uint32(0x0409)),
|
||||
...record(0x0003, uint16(CODE_PAGE)),
|
||||
...record(0x0004, name(PROJECT_NAME)),
|
||||
// No description or help file, in the code page then in Unicode
|
||||
...record(0x0005, []),
|
||||
...record(0x0040, []),
|
||||
...record(0x0006, []),
|
||||
...record(0x003d, []),
|
||||
...record(0x0007, uint32(0)),
|
||||
...record(0x0008, uint32(0)),
|
||||
// The project's version, its major version then its minor, after a size that is always 4
|
||||
...uint16(0x0009),
|
||||
...uint32(4),
|
||||
...uint32(1),
|
||||
...uint16(0),
|
||||
// No compilation constants
|
||||
...record(0x000c, []),
|
||||
...record(0x003c, []),
|
||||
];
|
||||
const references = REFERENCES.flatMap((reference) => {
|
||||
const referenceName = [...record(0x0016, name(reference.name)), ...record(0x003e, utf16(reference.name))];
|
||||
if ("project" in reference) {
|
||||
const projectId = name(reference.project);
|
||||
// Its absolute and relative paths, then the version of the project it refers to
|
||||
return [
|
||||
...referenceName,
|
||||
...record(0x000e, [
|
||||
...uint32(projectId.length),
|
||||
...projectId,
|
||||
...uint32(projectId.length),
|
||||
...projectId,
|
||||
...uint32(1),
|
||||
...uint16(0),
|
||||
]),
|
||||
];
|
||||
}
|
||||
const libraryId = name(reference.registered);
|
||||
return [...referenceName, ...record(0x000d, [...uint32(libraryId.length), ...libraryId, ...uint32(0), ...uint16(0)])];
|
||||
});
|
||||
const moduleRecords = modules.flatMap((module) => [
|
||||
...record(0x0019, name(module.name)),
|
||||
...record(0x0047, utf16(module.name)),
|
||||
// The module's stream, which has its name
|
||||
...record(0x001a, name(module.name)),
|
||||
...record(0x0032, utf16(module.name)),
|
||||
...record(0x001c, []),
|
||||
...record(0x0048, []),
|
||||
// Where the module's code starts in its stream, after a cache of the compiled code, which there is none of
|
||||
...record(0x0031, uint32(0)),
|
||||
...record(0x001e, uint32(0)),
|
||||
...record(0x002c, uint16(0xffff)),
|
||||
...record(module.kind === "module" ? 0x0021 : 0x0022, []),
|
||||
...record(0x002b, []),
|
||||
]);
|
||||
return compress(
|
||||
Uint8Array.from([
|
||||
...information,
|
||||
...references,
|
||||
...record(0x000f, uint16(modules.length)),
|
||||
...record(0x0013, uint16(0xffff)),
|
||||
...moduleRecords,
|
||||
...record(0x0010, []),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
const NAME = /^[A-Za-z][A-Za-z0-9_]{0,30}$/;
|
||||
|
||||
// The document's events, by their names in VBA after "Document_", in capitals
|
||||
const EVENTS = new Map<string, DocumentMacroEvent>(
|
||||
(
|
||||
[
|
||||
"new",
|
||||
"open",
|
||||
"close",
|
||||
"sync",
|
||||
"xmlAfterInsert",
|
||||
"xmlBeforeDelete",
|
||||
"contentControlAfterAdd",
|
||||
"contentControlBeforeDelete",
|
||||
"contentControlOnExit",
|
||||
"contentControlOnEnter",
|
||||
"contentControlBeforeStoreUpdate",
|
||||
"contentControlBeforeContentUpdate",
|
||||
"buildingBlockInsert",
|
||||
] as const
|
||||
).map((event) => [event.toUpperCase(), event]),
|
||||
);
|
||||
|
||||
// A Sub that handles an event of the document, such as "Private Sub Document_Open()"
|
||||
const EVENT_HANDLER = /^[ \t]*(?:(?:Private|Public|Friend)[ \t]+)?(?:Static[ \t]+)?Sub[ \t]+Document_(\w+)[ \t]*\(/gim;
|
||||
|
||||
/**
|
||||
* The events of the document that ThisDocument's code has a handler for, which Word runs the handlers of.
|
||||
*/
|
||||
const findEvents = (code: string): readonly DocumentMacroEvent[] => [
|
||||
...new Set([...code.matchAll(EVENT_HANDLER)].flatMap(([, name]) => EVENTS.get(name.toUpperCase()) ?? [])),
|
||||
];
|
||||
|
||||
/**
|
||||
* Writes a document's VBA macros from their code, for the document's `macros`: the VBA project, and the events of the
|
||||
* document that ThisDocument's code handles, such as `Document_Open`. The document is then a macro-enabled document,
|
||||
* which Word opens from a .docm file. Word asks whether to enable its macros, as for any document with macros from
|
||||
* elsewhere.
|
||||
*
|
||||
* VBA keeps code in Windows-1252, the code page of Word in English and the other Western European languages, so a
|
||||
* character it doesn't have goes in a string as `ChrW`, such as `ChrW(&H4E2D)` for "中", or two for a character beyond
|
||||
* U+FFFF, such as `ChrW(&HD83D) & ChrW(&HDE00)` for "😀".
|
||||
*
|
||||
* Word compiles the code when it first runs a macro, so a mistake in it shows then, in the VBA editor.
|
||||
*
|
||||
* @publicApi
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const doc = new Document({
|
||||
* macros: createMacros({
|
||||
* thisDocument: 'Private Sub Document_Open()\n MsgBox "Hello"\nEnd Sub',
|
||||
* modules: [{ name: "Formatting", code: "Sub MakeBold()\n Selection.Font.Bold = True\nEnd Sub" }],
|
||||
* }),
|
||||
* sections: [{ children: [new Paragraph("Hello World")] }],
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @throws If a module's name isn't a VBA name of up to 31 characters, or is taken: by another module, ignoring case, or
|
||||
* by ThisDocument, the project, Project, or a library it uses, VBA, Word, stdole, Normal or Office
|
||||
* @returns The document's macros, for its `macros`: the VBA project, and the events of the document it handles
|
||||
* @throws If code has a character Windows-1252 doesn't
|
||||
*/
|
||||
export const createMacros = ({ thisDocument = "", modules = [], classModules = [] }: MacrosOptions = {}): DocumentMacros & {
|
||||
readonly project: Uint8Array;
|
||||
readonly events: readonly DocumentMacroEvent[];
|
||||
} => {
|
||||
const given = [
|
||||
...modules.map((module) => ({ ...module, kind: "module" as const })),
|
||||
...classModules.map((module) => ({ ...module, kind: "class" as const })),
|
||||
];
|
||||
for (const [index, { name }] of given.entries()) {
|
||||
if (!NAME.test(name)) {
|
||||
throw new Error(
|
||||
`Invalid module name "${name}". Expected a letter, then letters, digits and underscores, up to 31 of them, such as "Formatting"`,
|
||||
);
|
||||
}
|
||||
const taken = [...TAKEN_NAMES, ...given.slice(0, index).map((module) => module.name)].find(
|
||||
(takenName) => takenName.toLowerCase() === name.toLowerCase(),
|
||||
);
|
||||
if (taken !== undefined) {
|
||||
throw new Error(`Invalid module name "${name}". ${taken} is already a name in the project`);
|
||||
}
|
||||
}
|
||||
|
||||
const projectModules: readonly ProjectModule[] = [
|
||||
{ name: "ThisDocument", kind: "document" as const, code: thisDocument },
|
||||
...given,
|
||||
].map(({ name, kind, code }) => {
|
||||
// VBA's lines end with CR LF, the last one too
|
||||
const lines = code.replace(/\r\n?/g, "\n").replace(/\n$/, "");
|
||||
const text = `${ATTRIBUTES[kind](name)}\r\n${lines === "" ? "" : `${lines.replace(/\n/g, "\r\n")}\r\n`}`;
|
||||
return { name, kind, source: encodeWindows1252(text, `The code of ${name}`) };
|
||||
});
|
||||
|
||||
const project = createCompoundFile([
|
||||
{
|
||||
name: "VBA",
|
||||
children: [
|
||||
// The cache of the compiled project, which there is none of: VBA compiles the code again
|
||||
{ name: "_VBA_PROJECT", data: Uint8Array.from([0xcc, 0x61, 0xff, 0xff, 0x00, 0x01, 0x00]) },
|
||||
{ name: "dir", data: createDirStream(projectModules) },
|
||||
...projectModules.map(({ name, source }) => ({ name, data: compress(source) })),
|
||||
],
|
||||
},
|
||||
{ name: "PROJECT", data: createProjectStream(projectModules) },
|
||||
{ name: "PROJECTwm", data: createNamesStream(projectModules) },
|
||||
]);
|
||||
return { project, events: findEvents(thisDocument) };
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* VBA macros for docx documents, written from their code. A document with macros is a macro-enabled document, which
|
||||
* Word opens from a .docm file.
|
||||
*
|
||||
* Macros come with the `docx` package, from `docx/macros`. Everything else, such as the document and its paragraphs,
|
||||
* comes from `docx`. The macros go in the document's `macros`.
|
||||
*
|
||||
* @module
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Document, Packer, Paragraph } from "docx";
|
||||
* import { createMacros } from "docx/macros";
|
||||
*
|
||||
* const doc = new Document({
|
||||
* macros: createMacros({
|
||||
* modules: [{ name: "Greetings", code: 'Sub SayHello()\n MsgBox "Hello"\nEnd Sub' }],
|
||||
* }),
|
||||
* sections: [{ children: [new Paragraph("Run SayHello from View > Macros")] }],
|
||||
* });
|
||||
*
|
||||
* const buffer = await Packer.toBuffer(doc); // Saved as a .docm
|
||||
* ```
|
||||
*/
|
||||
export { type MacroModule, type MacrosOptions, createMacros } from "./create-macros";
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Helpers for tests of docx/macros: they read the VBA projects it writes back, as Word does, from the specifications
|
||||
* rather than from docx/macros' own code.
|
||||
*/
|
||||
/* eslint-disable no-bitwise -- the formats are bit fields */
|
||||
|
||||
/**
|
||||
* Decompresses data VBA compressed.
|
||||
*
|
||||
* Reference: [MS-OVBA] 2.4.1.3.1 Decompression Algorithm
|
||||
*/
|
||||
export const decompress = (data: Uint8Array): Uint8Array => {
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const output: number[] = [];
|
||||
// After the signature byte, 0x01
|
||||
let chunkStart = 1;
|
||||
while (chunkStart < data.length) {
|
||||
const header = data[chunkStart] | (data[chunkStart + 1] << 8);
|
||||
const chunkEnd = Math.min(data.length, chunkStart + (header & 0x0fff) + 3);
|
||||
const decompressedStart = output.length;
|
||||
let current = chunkStart + 2;
|
||||
if ((header & 0x8000) === 0) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
output.push(...data.subarray(current, current + 4096));
|
||||
} else {
|
||||
while (current < chunkEnd) {
|
||||
const flags = data[current++];
|
||||
for (let index = 0; index < 8 && current < chunkEnd; index++) {
|
||||
if ((flags & (1 << index)) === 0) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
output.push(data[current++]);
|
||||
continue;
|
||||
}
|
||||
const token = data[current] | (data[current + 1] << 8);
|
||||
current += 2;
|
||||
const difference = output.length - decompressedStart;
|
||||
const bitCount = Math.max(Math.ceil(Math.log2(difference)), 4);
|
||||
const length = (token & (0xffff >> bitCount)) + 3;
|
||||
const offset = (token >> (16 - bitCount)) + 1;
|
||||
for (let copied = 0; copied < length; copied++) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
output.push(output[output.length - offset]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
chunkStart = chunkEnd;
|
||||
}
|
||||
return Uint8Array.from(output);
|
||||
};
|
||||
|
||||
/**
|
||||
* An entry of a compound file's directory, as written.
|
||||
*/
|
||||
export type CompoundFileDirectoryEntry = {
|
||||
readonly name: string;
|
||||
/** 1 for a storage, 2 for a stream and 5 for the root. 0 is an unused entry */
|
||||
readonly type: number;
|
||||
/** 0 for red and 1 for black */
|
||||
readonly color: number;
|
||||
readonly left: number;
|
||||
readonly right: number;
|
||||
readonly child: number;
|
||||
readonly start: number;
|
||||
readonly size: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A compound file, as read: its header's fields, its directory, and each stream, by its path, such as "VBA/dir".
|
||||
*/
|
||||
export type ReadCompoundFile = {
|
||||
readonly header: {
|
||||
readonly minorVersion: number;
|
||||
readonly majorVersion: number;
|
||||
readonly byteOrder: number;
|
||||
readonly sectorShift: number;
|
||||
readonly miniSectorShift: number;
|
||||
readonly miniStreamCutoff: number;
|
||||
};
|
||||
readonly entries: readonly CompoundFileDirectoryEntry[];
|
||||
readonly streams: ReadonlyMap<string, Uint8Array>;
|
||||
};
|
||||
|
||||
const END_OF_CHAIN = 0xfffffffe;
|
||||
const NO_STREAM = 0xffffffff;
|
||||
|
||||
/**
|
||||
* Reads a compound file of version 3, following its FAT, its directory and its mini stream.
|
||||
*
|
||||
* Reference: [MS-CFB] Compound File Binary File Format
|
||||
*/
|
||||
export const readCompoundFile = (file: Uint8Array): ReadCompoundFile => {
|
||||
const view = new DataView(file.buffer, file.byteOffset, file.byteLength);
|
||||
const sectorSize = 1 << view.getUint16(30, true);
|
||||
const miniSectorSize = 1 << view.getUint16(32, true);
|
||||
const miniStreamCutoff = view.getUint32(56, true);
|
||||
const sectorOffset = (sector: number): number => (sector + 1) * sectorSize;
|
||||
|
||||
const fatSectors = Array.from({ length: view.getUint32(44, true) }, (_, index) => view.getUint32(76 + index * 4, true));
|
||||
const fat = fatSectors.flatMap((sector) =>
|
||||
Array.from({ length: sectorSize / 4 }, (_, index) => view.getUint32(sectorOffset(sector) + index * 4, true)),
|
||||
);
|
||||
const chain = (table: readonly number[], start: number): readonly number[] => {
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const sectors: number[] = [];
|
||||
// No longer than the table, so a chain that loops ends
|
||||
for (let sector = start; sector !== END_OF_CHAIN && sectors.length < table.length; sector = table[sector]) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
sectors.push(sector);
|
||||
}
|
||||
return sectors;
|
||||
};
|
||||
const readChain = (start: number): Uint8Array => {
|
||||
const sectors = chain(fat, start);
|
||||
const bytes = new Uint8Array(sectors.length * sectorSize);
|
||||
for (const [index, sector] of sectors.entries()) {
|
||||
bytes.set(file.subarray(sectorOffset(sector), sectorOffset(sector) + sectorSize), index * sectorSize);
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const directory = readChain(view.getUint32(48, true));
|
||||
const directoryView = new DataView(directory.buffer);
|
||||
const entries = Array.from({ length: directory.length / 128 }, (_, index): CompoundFileDirectoryEntry => {
|
||||
const offset = index * 128;
|
||||
const nameLength = directoryView.getUint16(offset + 64, true);
|
||||
const name = String.fromCharCode(
|
||||
...Array.from({ length: Math.max(nameLength / 2 - 1, 0) }, (__, position) =>
|
||||
directoryView.getUint16(offset + position * 2, true),
|
||||
),
|
||||
);
|
||||
return {
|
||||
name,
|
||||
type: directory[offset + 66],
|
||||
color: directory[offset + 67],
|
||||
left: directoryView.getUint32(offset + 68, true),
|
||||
right: directoryView.getUint32(offset + 72, true),
|
||||
child: directoryView.getUint32(offset + 76, true),
|
||||
start: directoryView.getUint32(offset + 116, true),
|
||||
size: directoryView.getUint32(offset + 120, true),
|
||||
};
|
||||
});
|
||||
|
||||
const miniFatStart = view.getUint32(60, true);
|
||||
const miniFatBytes = miniFatStart === END_OF_CHAIN ? new Uint8Array() : readChain(miniFatStart);
|
||||
const miniFat = Array.from({ length: miniFatBytes.length / 4 }, (_, index) =>
|
||||
new DataView(miniFatBytes.buffer).getUint32(index * 4, true),
|
||||
);
|
||||
const miniStream = entries[0].start === END_OF_CHAIN ? new Uint8Array() : readChain(entries[0].start);
|
||||
|
||||
const readStream = (entry: CompoundFileDirectoryEntry): Uint8Array => {
|
||||
if (entry.size >= miniStreamCutoff) {
|
||||
return readChain(entry.start).subarray(0, entry.size);
|
||||
}
|
||||
const bytes = new Uint8Array(entry.size);
|
||||
for (const [index, sector] of chain(miniFat, entry.start).entries()) {
|
||||
const part = miniStream.subarray(sector * miniSectorSize, (sector + 1) * miniSectorSize);
|
||||
bytes.set(part.subarray(0, Math.min(miniSectorSize, entry.size - index * miniSectorSize)), index * miniSectorSize);
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
|
||||
// Each storage's entries are a tree, read in order
|
||||
const streams = new Map<string, Uint8Array>();
|
||||
const walk = (id: number, folder: string): void => {
|
||||
if (id === NO_STREAM) {
|
||||
return;
|
||||
}
|
||||
const entry = entries[id];
|
||||
walk(entry.left, folder);
|
||||
if (entry.type === 1) {
|
||||
walk(entry.child, `${folder}${entry.name}/`);
|
||||
} else {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
streams.set(`${folder}${entry.name}`, readStream(entry));
|
||||
}
|
||||
walk(entry.right, folder);
|
||||
};
|
||||
walk(entries[0].child, "");
|
||||
|
||||
return {
|
||||
header: {
|
||||
minorVersion: view.getUint16(24, true),
|
||||
majorVersion: view.getUint16(26, true),
|
||||
byteOrder: view.getUint16(28, true),
|
||||
sectorShift: view.getUint16(30, true),
|
||||
miniSectorShift: view.getUint16(32, true),
|
||||
miniStreamCutoff,
|
||||
},
|
||||
entries,
|
||||
streams,
|
||||
};
|
||||
};
|
||||
@@ -40,6 +40,7 @@
|
||||
"AppProperties",
|
||||
"ContentTypes",
|
||||
"PackageParts",
|
||||
"FileMacros",
|
||||
"CoreProperties",
|
||||
"CustomProperties",
|
||||
"DocumentWrapper",
|
||||
|
||||
@@ -26,6 +26,7 @@ const ENTRIES: Readonly<Record<string, Entry>> = {
|
||||
math: { name: "math", global: "docxMath" },
|
||||
layout: { name: "layout", global: "docxLayout" },
|
||||
html: { name: "html", global: "docxHtml" },
|
||||
macros: { name: "macros", global: "docxMacros" },
|
||||
};
|
||||
|
||||
// API Extractor, which bundles the declarations, copies in those of any module that isn't a library, so it would copy
|
||||
|
||||
Reference in New Issue
Block a user