# Creating Documents (CREATE)

Generate .docx files with JavaScript (docx-js), then validate.

## Step 0: Ensure docx-js is installed

**Run this ONCE before any CREATE operations.** If `node_modules/docx/` already exists, npm skips the install.

```bash
cd "$SKILL_DIR" && npm install
```

This reads `package.json` (which declares `docx` dependency) and installs to the skill's local `node_modules/`.

## JS File Rules

**Write the JS script to `/tmp/_tmp_docx_$$.js` (PID-based name, avoids multi-session conflicts). Delete only on success:**

```bash
cd "$SKILL_DIR" && node /tmp/_tmp_docx_$$.js && rm -f /tmp/_tmp_docx_$$.js
```

The `&&` (not `;`) keeps the JS file if node fails, so you can read it to debug. On skill startup, clean stale leftovers:

```bash
find /tmp/ -name '_tmp_docx_*.js' -mtime +1 -delete 2>/dev/null
```

**Run all `node` commands from `$SKILL_DIR`.**

## Setup Template

**Every JS script you write MUST include the self-cleanup line** (`fs.unlinkSync(__filename)`). This is a second-layer cleanup for the success path.

```javascript
const fs = require("fs");
const {
  Document,
  Packer,
  Paragraph,
  TextRun,
  Table,
  TableRow,
  TableCell,
  ImageRun,
  Header,
  Footer,
  AlignmentType,
  PageOrientation,
  LevelFormat,
  ExternalHyperlink,
  TableOfContents,
  HeadingLevel,
  BorderStyle,
  WidthType,
  ShadingType,
  VerticalAlign,
  PageNumber,
  PageBreak,
} = require("docx");

const doc = new Document({
  sections: [
    {
      children: [
        /* content */
      ],
    },
  ],
});
Packer.toBuffer(doc).then((buffer) => {
  fs.writeFileSync("/tmp/output.docx", buffer);
  // MANDATORY: self-cleanup — delete this script file
  try { fs.unlinkSync(__filename); } catch(e) {}
});
```

## Validation

After creating the file, validate it. If validation fails, unpack, fix the XML, and repack.

```bash
cd "$SKILL_DIR" && uv run --project . python scripts/office/validate.py /tmp/output.docx
```

## API Reference

For page sizes, styles, lists, tables, images, TOC, headers/footers and other docx-js API details, read:

```bash
cat "$SKILL_DIR/references/docx-js-api.md"
```

The reference covers: Page Size (US Letter vs A4, landscape), Styles (heading overrides, Arial default), Lists (bullet/number config), Tables (dual widths, DXA units, borders), Images, Page Breaks, Table of Contents, and Headers/Footers.
