@docx-editor.dev/core/export

@docx-editor.dev/core/export — DOM-free semantic export sessions and shared resources.

Exporters consume the same published SemanticLayout records as the browser painter. They do not parse OOXML or independently derive document semantics.

Functions (9)

acquireSharedExportShapingfunctionSource ↗

Acquire one process-wide shaped measurement substrate for a host configuration.

Failed initialization is evicted so a corrected transient resource can retry. Successful native shaping and admitted font bytes intentionally live for the process lifetime; export sessions retain only their own layout caches and remain independently disposable.

declare function acquireSharedExportShaping(prepared: PreparedLayoutFontConfiguration, instrumentation?: LayoutShapingInstrumentation): Promise<SharedExportShapingCapabilities>;

createNodeImageDecodePortfunctionSource ↗

Decode raster dimensions from validated headers, with no native image dependency or DOM. SVG sizing is handled by the resource registry; preserved formats stay placeholders unless the caller supplies convertPreserved.

declare function createNodeImageDecodePort(options?: {
    readonly convertPreserved?: PreservedImageConverter;
}): ImageDecodePort;

createPackagedFileFetchfunctionSource ↗

Build the packaged-asset fetch adapter shared by headless exporters. File reads stay inside the host-chosen trustedRoot list and never allocate more than maxBytes. Kept injectable for lifecycle and host-fetch tests.

declare function createPackagedFileFetch(options: PackagedFileFetchOptions): typeof fetch;

exportDestinationNamedfunctionSource ↗

Resolve one internal destination name from a Core-produced export layout.

declare function exportDestinationNamed(layout: {
    readonly destinations?: readonly ExportDestinationGeometry[];
}, name: string): ExportDestinationGeometry | undefined;

hasExportAdmittedFontfunctionSource ↗

Whether a value publishes [ExportAdmittedFontApi](ExportAdmittedFontApi).

declare function hasExportAdmittedFont<T extends object>(value: T): value is T & ExportAdmittedFontApi;

hasExportLaidOutTextfunctionSource ↗

Whether a value publishes [ExportLaidOutTextApi](ExportLaidOutTextApi).

declare function hasExportLaidOutText<T extends object>(value: T): value is T & ExportLaidOutTextApi;

hasFontBackedExportCapabilitiesfunctionSource ↗

Whether a value publishes both font-backed session capabilities.

declare function hasFontBackedExportCapabilities<T extends object>(value: T): value is T & ExportAdmittedFontApi & ExportLaidOutTextApi;

openDocumentForExportfunctionSource ↗

Open bytes or a live neutral view into one reusable layout session.

declare function openDocumentForExport(source: ExportDocumentSource, options?: OpenDocumentForExportOptions): OpenDocumentForExportResult;

openFontBackedDocumentForExportfunctionSource ↗

Open immutable DOCX bytes with document-aware, session-owned font shaping.

This is the composition root exporters should use. It parses before requesting fonts, applies cancellation/deadlines to provisioning, atomically binds the resulting measurer to that parsed view, and releases the document-specific font lease with the returned session. When best-effort resolution admits no source, the session retains Core's deterministic fixed measurer; strict policy already refuses that incomplete coverage. Mutable views are intentionally excluded: a live editor host must supply its own revision-stable measurer.

declare function openFontBackedDocumentForExport(source: Uint8Array, options: OpenFontBackedDocumentForExportOptions): Promise<OpenFontBackedDocumentForExportResult>;

Classes (1)

ExportResourceErrorclassSource ↗

Bounded failure from a headless export session.

declare class ExportResourceError extends Error
MemberTypeSummary
(constructor)Constructs a new instance of the `ExportResourceError` class
code'aborted' | 'timedOut' | 'nonConvergent' | 'disposed' | 'layoutInvariant' | 'layoutFailed'

Interfaces (22)

ExportAdmittedFontApiinterfaceSource ↗

Session capability that yields admitted face bytes on demand.

interface ExportAdmittedFontApi
MemberTypeSummary
admittedFontFaceExact admitted face bytes and identity used by this session's measurer. Stops after disposal or abort; resolution evidence on `fontResolution` remains.

ExportAdmittedFontFaceinterfaceSource ↗

Session-visible admitted face whose bytes are shared with the session shaper and content-hashed shaping cache. Treat [ExportAdmittedFontFace.bytes](ExportAdmittedFontFace.bytes) as strictly read-only; in-place mutation can corrupt later shaping after cache eviction or before the first shape for that face.

interface ExportAdmittedFontFace extends ExportAdmittedFontIdentity
MemberTypeSummary
bytesUint8ArrayShared font bytes owned by the session shaper and shaping cache. Not a copy. Must be treated as read-only.

ExportAdmittedFontIdentityinterfaceSource ↗

Byte-free admitted face identity for laid-out text and evidence.

interface ExportAdmittedFontIdentity
MemberTypeSummary
byteLengthnumber
faceIndexnumber
familystring
hashstring
idstring
identitystring
requestFontRequest
substitutionFontSubstitution | null

ExportDestinationAnchorinterfaceSource ↗

Model address shared by bookmarks and internal hyperlinks.

interface ExportDestinationAnchor
MemberTypeSummary
namestring
offsetnumber
paragraphIdstring

ExportDestinationGeometryinterfaceSource ↗

Laid-out jump target in the coordinate spaces export traversal uses.

interface ExportDestinationGeometry
MemberTypeSummary
anchorExportDestinationAnchor
pageContentReadonly<{ readonly x: number; readonly y: number; readonly height: number; }>Caret geometry in page-content coordinates (same space as line boxes).
pageIndexnumber
pageStackReadonly<{ readonly x: number; readonly y: number; }>Top-left of the caret in stacked page coordinates.

ExportDroppedEmbeddedFontinterfaceSource ↗

One document-embedded face the export mapper refused before composition.

interface ExportDroppedEmbeddedFont
MemberTypeSummary
partNamestring
reason'overLimit' | 'malformed'
requestFontRequest

ExportFontFaceResolutioninterfaceSource ↗

One paintable face in an export font-resolution report.

interface ExportFontFaceResolution
MemberTypeSummary
faceIndex?number
hash?string
id?string
identity?stringAdmitted face identity (`hash#faceIndex`); remains after session disposal.
sourceFamilystring
style'normal' | 'italic'
substitution?FontSubstitution | nullFull substitution evidence; `null` when the admitted face answers the request directly.
via'direct' | 'substitution'
weight400 | 700

ExportFontFamilyResolutioninterfaceSource ↗

Coverage of one family Core layout may request.

interface ExportFontFamilyResolution
MemberTypeSummary
coverage'complete' | 'partial' | 'none'
facesreadonly ExportFontFaceResolution[]
familystring

ExportFontResolutionReportinterfaceSource ↗

Exporter-neutral evidence for the font policy behind one layout session.

interface ExportFontResolutionReport
MemberTypeSummary
defaultFamilystring
droppedEmbeddedFonts?readonly ExportDroppedEmbeddedFont[]Bounded drop evidence from the document-embedded font origin; omitted on legacy mocks.
familiesreadonly ExportFontFamilyResolution[]
originFailuresreadonly FontOriginFailure[]
requestedFamiliesreadonly string[]

ExportLaidOutTextinterfaceSource ↗

Exact shaped glyph run and admitted font identity for one published span.

The run is shaped at the base size measurement uses. Callers apply the span's drawn-size factor, horizontal scale, and character spacing from [StyleSpanRecord.style](StyleSpanRecord.style). font is a frozen byte-free descriptor; obtain bytes from the session font capability.

interface ExportLaidOutText
MemberTypeSummary
fixedPointScalenumber
fontExportAdmittedFontIdentity
runShapedRun

ExportLaidOutTextApiinterfaceSource ↗

Additive laid-out text shaping for font-backed export sessions and shared shaping.

interface ExportLaidOutTextApi
MemberTypeSummary
shapeLaidOutTextShape one published span with the same configuration and policy as measurement. Returns null when measurement used the bounded fallback.

ExportSemanticLayoutinterfaceSource ↗

Export-ready semantic snapshot. Core guarantees normalized review artifacts for every session, including an empty immutable array when the source has none. A resolved snapshot is recursively immutable and remains traversable after its producer session is disposed; disposal only revokes session-owned work and capabilities such as [ExportSession.validatedImageBytes](ExportSession.validatedImageBytes).

interface ExportSemanticLayout extends SemanticLayout
MemberTypeSummary
destinations?readonly ExportDestinationGeometry[]
documentMetadata?ExportDocumentMetadata
reviewArtifactsreadonly SemanticReviewArtifactRecord[]

ExportSessioninterfaceSource ↗

A single semantic-layout substrate reusable by Markdown and later exporters. Pagination fidelity is determined by the session's measurer; core's default is deterministic, not font-accurate.

interface ExportSession
MemberTypeSummary
disposeRelease per-document caches, pending resource work, and image-byte capabilities. Idempotent. Previously resolved layout snapshots remain immutable and traversable after disposal.
layoutSettle resources and return the default revision projection.
layoutForSettle resources and cache one explicit revision projection.
validatedImageBytesMint a defensive copy only for a ready drawing from this session.

FontBackedExportCapabilitiesinterfaceSource ↗

Core-produced font-backed session with admitted-face and laid-out-text capabilities.

interface FontBackedExportCapabilities extends FontBackedExportSession, ExportAdmittedFontApi, ExportLaidOutTextApi

FontBackedExportSessioninterfaceSource ↗

Export session retaining the exact font evidence used to construct its measurer.

interface FontBackedExportSession extends ExportSession
MemberTypeSummary
fontResolutionExportFontResolutionReportImmutable font-resolution evidence; remains readable after session disposal.

FontOriginFailureinterfaceSource ↗

One font origin that could not contribute a valid fragment.

interface FontOriginFailure
MemberTypeSummary
causeunknown
originIndexnumberZero-based position in the first-wins origin list.
originName?stringResolver function name when one is safely available.

FontRequestinterfaceSource ↗

A face, as something asks for it: family plus the two axes this engine admits.

Only static weights and slants. Variable-font axes are deliberately outside this vocabulary — the shaper refuses variation axes, and a variable file admitted here would render bold at regular weight.

interface FontRequest
MemberTypeSummary
familystring
style'normal' | 'italic'
weightnumber

FontSubstitutioninterfaceSource ↗

A request that was answered by a DIFFERENT face than the one asked for.

Recorded rather than silently applied, because a substitution changes measurement: it is part of the shaping fingerprint, so a cached run shaped against a substitute is never reused for the real face.

interface FontSubstitution
MemberTypeSummary
lineMetrics?{ readonly heightEm: number; readonly baselineEm: number; }
requestedFontRequest
resolvedFontRequest

OpenDocumentForExportOptionsinterfaceSource ↗

Shared session options; translators add their own format-specific options.

interface OpenDocumentForExportOptions
MemberTypeSummary
convertPreservedImage?PreservedImageConverterOptional converter for preserved image formats the default decoder cannot inspect.
displayMode?RevisionDisplayModeRevision projection applied before records reach an exporter. Default: `all-markup`.
imageDecodePort?ImageDecodePortHost image metadata decoder; omit for the bounded DOM-free Node decoder.
measurer?TextMeasurerText measurement used for line wrapping and pagination. Omit only when deterministic approximate pagination is acceptable. Core then uses a fixed-width fallback that neither resolves nor shapes the document's fonts, so line and page breaks can differ from Word. Exporters promising physical-page fidelity must supply a font-backed measurer. For immutable DOCX bytes with document-aware font origins, use [openFontBackedDocumentForExport](openFontBackedDocumentForExport); [acquireSharedExportShaping](acquireSharedExportShaping) is for process-static prepared configurations or a live host that already owns revision-stable shaping.
producer?stringStable measurement implementation identity used by layout caches and diagnostics. Pair it with the exact shaping policy behind `measurer`; it is not a substitute for matching metrics.
resourceTimeoutMs?numberMaximum time spent waiting for image resources in one layout call. Default: 60 seconds.
reuseAcrossRevisions?booleanRetain incremental state for a live view. Defaults to true for views and false for bytes.
signal?AbortSignalCancels resource waits and subsequent layouts.

OpenFontBackedDocumentForExportOptionsinterfaceSource ↗

Font-backed one-shot session options shared by Markdown and future exporters.

interface OpenFontBackedDocumentForExportOptions extends Omit<OpenDocumentForExportOptions, 'measurer' | 'reuseAcrossRevisions'>
MemberTypeSummary
fontPolicy?'best-effort' | 'strict'`strict` refuses incomplete face coverage or any failed origin. Default: `best-effort`.
fontResolutionTimeoutMs?numberFont provisioning deadline; defaults to `resourceTimeoutMs`, then 60 seconds.
fontsFontOrigin | readonly FontOrigin[]Ordered first-wins font origins resolved against this immutable DOCX.
onFontResolution?(report: ExportFontResolutionReport) => voidFire-and-forget diagnostics; returned promises are observed but do not delay export.
reuseAcrossRevisions?falseImmutable font-backed byte sessions reject incremental revision reuse.

PackagedFileFetchOptionsinterfaceSource ↗

Bounds for [createPackagedFileFetch](createPackagedFileFetch). trustedRoot is one directory or a short host-chosen list of directories of allowed file: URLs. maxBytes is the per-file allocation ceiling and cannot exceed the engine font-byte ceiling.

interface PackagedFileFetchOptions
MemberTypeSummary
maxBytesnumber
networkFetch?typeof fetch
read?PackagedFileRead
trustedRootstring | URL | readonly (string | URL)[]

SharedExportShapinginterfaceSource ↗

Immutable handle over process-wide measurement state reusable by every exporter.

interface SharedExportShaping
MemberTypeSummary
createMeasurerCreate one document-scoped measurement cache over the process-wide immutable substrate.
extensionFingerprintstringFont and substitution identity shared with browser layout caches.
producerstringStable cache/diagnostic producer identity for export layout sessions.

Type aliases (8)

ExportDocumentMetadatatypeSource ↗

Bounded package metadata for exporter output dictionaries.

type ExportDocumentMetadata = Readonly<DocumentProperties>;

ExportDocumentSourcetypeSource ↗

Source accepted by every exporter: untrusted bytes or an already-open live view.

type ExportDocumentSource = Uint8Array | HeadlessDocumentView;

FontOrigintypeSource ↗

ONE font origin, in the one shape every origin takes: a finished configuration, a fragment, a promise for either, or a marked resolver that answers per document.

The point of the union is that packagedFonts(), googleFonts(), await defaultFonts() and a hand-built { sources } are all the same kind of thing, so a list of them needs no ordering rule beyond "first wins".

The resolver arm is [MarkedFontResolver](MarkedFontResolver), not bare FontResolver: a list may also hold a zero-argument loader, and only the mark separates the two.

type FontOrigin = FontConfiguration | FontConfigurationFragment | MarkedFontResolver | Promise<FontConfiguration | FontConfigurationFragment | undefined> | undefined;

OpenDocumentForExportResulttypeSource ↗

Typed refusal for bytes that cannot become a document view, or an already-aborted open.

type OpenDocumentForExportResult = {
    readonly ok: true;
    readonly session: ExportSession;
} | {
    readonly ok: false;
    readonly reason: HeadlessDocumentRejection | 'aborted';
    readonly detail?: string;
};

OpenFontBackedDocumentForExportResulttypeSource ↗

Result of opening immutable bytes through Core's document-aware font composition root.

type OpenFontBackedDocumentForExportResult = {
    readonly ok: true;
    readonly session: FontBackedExportCapabilities;
} | Exclude<OpenDocumentForExportResult, {
    readonly ok: true;
}>;

PackagedFileReadtypeSource ↗

Read packaged bytes from a confined local file: URL. Kept injectable for tests.

type PackagedFileRead = (path: string | URL, options: {
    readonly signal?: AbortSignal;
    readonly maxBytes: number;
}) => Promise<Uint8Array>;

PreservedImageConvertertypeSource ↗

Optional caller conversion for preserved formats such as EMF/WMF/TIFF.

type PreservedImageConverter = (bytes: Uint8Array, mime: PreservedImageMime, limits: ImageResourceLimits, 
signal?: AbortSignal) => Promise<Readonly<{
    bytes: Uint8Array;
    mime: SupportedImageMime;
}> | null>;

SharedExportShapingCapabilitiestypeSource ↗

Core-produced shared shaping with exact laid-out text.

type SharedExportShapingCapabilities = SharedExportShaping & ExportLaidOutTextApi;

Variables (1)

MAX_SHARED_EXPORT_SHAPING_CONFIGURATIONSconstSource ↗

Process-wide ceiling preventing host-derived cache keys from retaining unbounded font sets.

MAX_SHARED_EXPORT_SHAPING_CONFIGURATIONS = 32

On this page