oconv-ir/v2→.odtbytes, tier 2, composing@awacloud/odf's typed body model and typed named styles.
Module oconvIrToOdt | Source packages/front/office/oconv/src/write/ir-to-odt.js | Deps oconvIr, odt | Worker-safe yes
Resolve
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/oconv';
const runtime = new ModuleRuntime();
runtime.registerAll(fw_require);
runtime.registerAll(modules);
const oconvIrToOdt = runtime.resolve('oconvIrToOdt');
Reached in practice through oconv.fromMd({ markdown, target: 'odt' }) or
oconv.convert({ ..., target: 'odt' }) (../oconv.md).
API
| Member | Signature | Returns | Throws |
|---|---|---|---|
irToOdt |
(ir: object, opts?: {assets?: Object<string, Uint8Array>}) => IrToOdtResult |
{bytes: Uint8Array, losses: IrToOdtLoss[]} |
Error oconv: invalid ir (<code> at <path>) when ir fails oconvIr.validate |
opts.assets is the same manifest oconvIrToDocx/oconvIrToPdf take
({ <markdown image destination>: Uint8Array }, keyed verbatim). An image
whose bytes are reachable is placed as a Pictures/ package part at
its intrinsic size (a default box and image/size-defaulted when no size can
be read from its header), with its alt text as the frame title; an image
with no reachable bytes keeps its place as an empty frame (no content
child, the default box, its name and alt text) and records
image/placeholder (see Notes).
Examples
Write a heading + paragraph to .odt
// Build the IR with the oconvIr helpers: a bare-literal node tree does not
// pass `oconvIr.validate`.
const { node, doc } = runtime.resolve('oconvIr');
const ir = doc([
node('heading', { level: 1 }, [node('run', { text: 'Title' })]),
node('paragraph', {}, [node('run', { text: 'Hello world' })])
]);
const { bytes, losses } = oconvIrToOdt.irToOdt(ir);
// bytes — a non-empty .odt (package/ZIP) Uint8Array; losses === []
const odt = runtime.resolve('odt');
odt.read(bytes).body[0];
// { type: 'heading', outlineLevel: 1, styleName: 'Heading_20_1', runs: [...] }
Executed against the live package (2026-10-12):
bytes.length > 0, losses is [], styles.xml defines the twelve named
styles Standard, Text_20_body, Heading, Heading_20_1..Heading_20_6, Preformatted_20_Text, Quotations, Horizontal_20_Line, and
odt.read(bytes).body[0] reads back styleName: 'Heading_20_1',
outlineLevel: 1.
Place an image from opts.assets
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); // PNG signature
const withImage = doc([
node('paragraph', {}, [
node('run', { text: 'Logo: ' }),
node('image', { name: 'logo', alt: 'Logo' })
])
]);
const placed = oconvIrToOdt.irToOdt(withImage, { assets: { logo: png } });
placed.losses;
// [{ code: 'image/size-defaulted', detail: 'logo' }]
const zip = runtime.resolve('zip');
Object.keys(zip.unzipSync(placed.bytes)).filter((p) => p.startsWith('Pictures/'));
// ['Pictures/image1.png']
oconvIrToOdt.irToOdt(withImage).losses; // no assets, no carried bytes
// [{ code: 'image/placeholder', detail: 'logo' }]
Executed against the live package (2026-10-12): the 8 signature bytes
carry no IHDR, so no size is read and the placed write's
losses is [{ code: 'image/size-defaulted', detail: 'logo' }], its only
Pictures/ entry is Pictures/image1.png holding the 8 input bytes, its
content.xml carries one <draw:frame text:anchor-type="as-char" svg:width="5.08cm" svg:height="3.81cm"> whose draw:image has
xlink:href="Pictures/image1.png" followed by the svg:title Logo, and
the write without assets records
[{ code: 'image/placeholder', detail: 'logo' }] (its frame holds no
draw:image, only the svg:title; checked 2026-11-01).
Notes
- Styles part — fixed, caller-invisible: every write emits
styles.xmlthroughodt.write(doc, { styles }), headings or not, with exactly twelve typed named paragraph styles, in this order:Standard;Text_20_body(Text body, based onStandard, 0 / 0.247 cm margins);Heading(based onStandard, nextText_20_body, keep-with-next, 0.423 / 0.141 cm margins);Heading_20_1..Heading_20_6(Heading 1..Heading 6, based onHeading, nextText_20_body,style:default-outline-levelN, bold, 16/14/13/12/11/11 pt — the same sizes as the docx writer's 32/28/26/24/22/22 half-points);Preformatted_20_Text(Preformatted Text,Liberation Mono— genericmodern, fixed pitch — 10 pt, no margins);Quotations(1 cm left and right margins);Horizontal_20_Line(Horizontal Line, a 0.5 pt grey bottom border) — LibreOffice's built-in names. Everytext:hnamesHeading_20_<level>(_20_is LibreOffice's encoding of a space in the programmatic style name), so every referenced style is defined. The name is presentation only: the read leg recovers the level fromoutlineLevel, and a read heading simply carries the extrastyleName. There is no option to supply or alter styles — tier 3 (caller styling) is still not promised; heading sizes are fixed points, not LibreOffice's percentages. - Bordered tables: every table is written with
grid: true.@awacloud/odfthen synthesises the bordered cell styleawa-c-b(fo:bordersingle line) and the margins-aligned table styleawa-tb-m(table:align="margins") as automatic styles; this module still builds neither. On read,odt.readconsumes and drops those styles: the table reads backgrid: true, its cells carry nostyleName, andautoStylesstays undefined. List levels carry the label-alignmentstyle:list-level-propertiesgeometry (also odf's) and the bullet no font. - The odf typed write model expresses run emphasis, hyperlinks, ordered
vs. bullet lists and text-body tables WITHOUT loss —
odt.write(body plus the fixed{ styles }above) synthesizes the automatic styles (awa-t-*/awa-l-*,awa-c-b/awa-tb-mforgridtables) and font-face declarations itself; this module never buildsautoStyles/fontFacesexplicitly. What remains genuinely inexpressible through the typed model is degraded with an exact, non-silent loss ledger entry per occurrence — never a raw-XML passthrough node (compose-never-reimplement). - No empty paragraphs are emitted. A code block writes one paragraph
per source line and drops exactly ONE trailing newline first (the text
of a CommonMark code block ends with one), so there is no trailing empty
paragraph; an interior empty line is kept (
'a\n\nb\n'writesa, an empty paragraph,b). An empty odt paragraph would collapse on the next markdown parse, so this is what keeps md → odt → md stable on a second pass. Every image is a frame run, with bytes or without, so an image-only paragraph does produce a paragraph. - A table without a row is not written: ODF needs one, and there is nothing to keep (no loss); a docx table without a row reads as one.
- Headers and footers (
oconv-ir/v2document.header,document.footer, T80) are written in the master pageStandard, in the schema's order:style:header(the default slot),style:header-left(even),style:header-first(first), then the footers'. A slot is mapped as the body is (its images in the samePictures/, frame names unique across the document) and handed toodt.writeas the element'scontent; its automatic styles arestyles.xml'sMP<n>andMT<n>. A region without a page names a page layoutpm1with no properties. Afieldis written astext:page-number(text:select-page="current") ortext:page-count, holding its text. - Notes (
note, T81) are written as@awacloud/odf's typed note run (text:note):idftn<k>/edn<k>, the class, the citation (the custom mark, also itstext:label, else the note's number among its class's automatic notes), the body mapped as the body is. A note inside a note's body is not written (note/dropped, detailnested). codemaps tomonospaceon aspanrun (mapRunFlags); a run with no truthy flag is a plaintextrun, never aspan.- Code blocks, quotes and rules are styled, and read back: a
codeBlockis onePreformatted_20_Textparagraph per source line (an empty line is an empty paragraph, the text's one trailing newline writes none); a run of two or more spaces, or a space that starts a line or follows a tab, is written astext:s(ODF collapses plain spaces), a tab astext:tab; theinfostring is not written. Ablockquote's paragraphs areQuotationsparagraphs; a nested quote's paragraphs too (block/degraded,blockquote:nested), and any other block inside a quote keeps its own mapping (block/degraded,blockquote-child:<kind>). Anhris an emptyHorizontal_20_Lineparagraph.../read/odt-to-ir.jsreads the three styles back, somd → odt → mdkeeps a fenced code block (indentation included, without its info string), a quote and a rule. - Ordered lists carry
numFormat: '1'(md ordered lists are decimal); nesting is preserved structurally throughitems[].children. - Images are placed when their bytes are reachable. The bytes are
looked up as in the docx writer:
opts.assets[name](or its percent-decoded form) first, then the bytes a reader carried inescapes.docx.bytes/escapes.odt.bytes/escapes.pdf.bytes/escapes.pptx.bytes. With bytes, the image becomes an odtframerun of@awacloud/odf's typed write model —{ type: 'frame', anchorType: 'as-char', width, height, child: { kind: 'image', href } }, rendered as<draw:frame text:anchor-type="as-char"> <draw:image/></draw:frame>— inline in place within its paragraph, or as its own paragraph at block position (also inside a table cell or a list item), and the bytes travel inodt.write'sdoc.picturesmap as a package part. Without bytes, the image keeps its place as a frame with no content child — ODF allows adraw:frameto hold none — in the default 2 in × 1.5 in box, with itsdraw:nameand its alt text as below, and recordsimage/placeholder(no picture part is written for it).../read/odt-to-ir.jsreads such a frame back as an image without bytes, somd → odt → mdkeepsand a docx chart, shape or SmartArt (an image reference without bytes) survivesdocx → odt.- Size: its size is read from the image header (PNG
IHDR+pHYs, JPEGSOFn+ JFIF density, GIF screen size; 96 dpi when the file states none), scaled down to fit 6 in × 8 in with its aspect kept — the docx writer's rule (src/write/image-extent-drift.test.jskeeps the two copies byte-identical), written in centimetres to three decimals. A header that cannot be read keeps the default 2 in × 1.5 in box (5.08cm×3.81cm) and recordsimage/size-defaulted— a degrade, never a drop. - Alt text: a non-empty IR
altis written as the frame'ssvg:title, after thedraw:image.@awacloud/odftypes no frame title, so it rides in the frame run's raw children (_extras.children), whereodt.readputs it. - Part naming:
Pictures/image<k>.<ext>.kis the 1-based index of each distinct IRnamein order of its first placed occurrence; the samenametwice gives one part, written once (the first occurrence's bytes win), and two frames pointing at it.<ext>is sniffed from the leading bytes — PNG signature →png,FF D8 FF→jpg,GIF8→gif, anything else →bin. The path is never derived from thename, which may carry spaces, slashes and no extension (a docx image is typically namedGrafik 1).@awacloud/odfdeclares each part in the manifest with the media type it sniffs from the same bytes. - When no image is placed,
odt.writereceives nopictureskey. - Round trip: reading the written
.odtback throughoconvOdtToIr(withframesInRuns, asoconvdoes) recovers the image, its bytes and its alt text, but not its name — this writer writes nodraw:name, so the reader names the image after its picture path (image1.gif).
- Size: its size is read from the image header (PNG
- Byte-reproducible:
@awacloud/odfstamps every zip entry with a fixed 1980-01-01 00:00 timestamp (itswritedefault formtime; this writer passes none), so two calls on the same IR give byte-identical containers at any instant (src/write/ir-to-odt.test.js"md -> odt is byte-reproducible", which moves the clock between the two runs). This module is pure — no clock, no I/O, no randomness of its own. - Determinism of the parts:
content.xmlandstyles.xmlare byte-identical across two writes of the same IR (the styles are built from constants, no input reaches them), and so is the whole container. - Capture-free (
fw/no-factory-capture), pure object mapping +odt.write(pure JS), hence worker-safe by construction. - See the loss matrix for the published Preserved/Degraded/Dropped classification of every code below.
Loss codes emitted by this module
| Code | Detail | Meaning |
|---|---|---|
list/task-marker-dropped |
'[x]' or '[ ]' |
a GFM task item (listItem.escapes.md.task) whose first block is not a paragraph; otherwise the checkbox is a leading ☐ / ☒ text run of the first paragraph, no loss |
block/degraded |
'blockquote:nested' |
a quote nested in a quote was written as more Quotations paragraphs — the return leg reads one flat quote (one loss per nested quote) |
block/degraded |
'blockquote-child:<kind>' |
a non-paragraph, non-quote block inside a quote was written with its own mapping, outside the quote style |
image/size-defaulted |
the image name |
bytes were reachable and the image is placed, but no size could be read from its header, so it sits in the default 2 in × 1.5 in box |
image/placeholder |
the image name |
no bytes were reachable for the image — neither opts.assets[name] (or its percent-decoded form) nor a reader's escapes.docx.bytes / escapes.odt.bytes / escapes.pdf.bytes / escapes.pptx.bytes — so it keeps its place as a frame with no content child, in the default 2 in × 1.5 in box, with its name and alt text and no picture part; the odt reader reads it back as the image reference (image/bytes-unavailable) |
See also
ir-to-docx— the equivalent.docxwriter.ir-to-md/ir-to-pdf— the other two IR writers.- Loss matrix — published fidelity classification.