Initial public release
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "@genoffice/agent-core",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Generic ReAct agent loop: pluggable skills (tools + prompt + context), pluggable LLM transport; shared by AI Docs and future apps (Excel / PPT)",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type {
|
||||
AgentStreamRequest,
|
||||
AgentToolCall,
|
||||
AgentToolDef,
|
||||
AgentTransport,
|
||||
AgentMessage,
|
||||
} from './types'
|
||||
|
||||
/**
|
||||
* One streamed chunk pushed back over an Electron IPC bridge. Structurally
|
||||
* identical to ai-provider's AiStreamChunk; declared here so this package
|
||||
* stays dependency-free.
|
||||
*/
|
||||
export interface IpcStreamChunk {
|
||||
requestId: string
|
||||
type: 'delta' | 'tool-call' | 'done' | 'error'
|
||||
text?: string
|
||||
toolCall?: AgentToolCall
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** The request forwarded to the main process to start one streaming turn. */
|
||||
export interface IpcStreamStart<S> {
|
||||
requestId: string
|
||||
settings: S
|
||||
system: string
|
||||
messages: AgentMessage[]
|
||||
tools: AgentToolDef[]
|
||||
}
|
||||
|
||||
export interface IpcTransportOptions<S> {
|
||||
/** subscribe to stream chunks; returns the unsubscribe function */
|
||||
onStream(listener: (chunk: IpcStreamChunk) => void): () => void
|
||||
/** forward the start request to the main process */
|
||||
start(request: IpcStreamStart<S>): void
|
||||
/** abort the in-flight turn in the main process */
|
||||
cancel(requestId: string): void
|
||||
getSettings(): S
|
||||
/** localized fallback when an error chunk carries no message */
|
||||
unknownErrorText(): string
|
||||
}
|
||||
|
||||
/**
|
||||
* AgentTransport over an Electron IPC bridge: the main process talks to the
|
||||
* LLM providers (avoids renderer CORS) and streams chunks back per requestId.
|
||||
* Each app wires in its own preload bridge and i18n via the options.
|
||||
*/
|
||||
export function createIpcTransport<S>(options: IpcTransportOptions<S>): AgentTransport {
|
||||
return {
|
||||
stream(request: AgentStreamRequest, cb) {
|
||||
const requestId = crypto.randomUUID()
|
||||
const unsubscribe = options.onStream((chunk) => {
|
||||
if (chunk.requestId !== requestId) return
|
||||
if (chunk.type === 'delta') {
|
||||
cb.onDelta(chunk.text ?? '')
|
||||
} else if (chunk.type === 'tool-call') {
|
||||
if (chunk.toolCall) cb.onToolCall(chunk.toolCall)
|
||||
} else if (chunk.type === 'done') {
|
||||
unsubscribe()
|
||||
cb.onDone()
|
||||
} else {
|
||||
unsubscribe()
|
||||
cb.onError(chunk.error ?? options.unknownErrorText())
|
||||
}
|
||||
})
|
||||
options.start({
|
||||
requestId,
|
||||
settings: options.getSettings(),
|
||||
system: request.system,
|
||||
messages: request.messages,
|
||||
tools: request.tools,
|
||||
})
|
||||
return { cancel: () => options.cancel(requestId) }
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
export type {
|
||||
AgentImage,
|
||||
AgentMessage,
|
||||
AgentStreamCallbacks,
|
||||
AgentStreamHandle,
|
||||
AgentStreamRequest,
|
||||
AgentToolCall,
|
||||
AgentToolDef,
|
||||
AgentToolResult,
|
||||
AgentTransport,
|
||||
ToolDisplay,
|
||||
ToolExecution,
|
||||
} from './types'
|
||||
export { composeSkills } from './skill'
|
||||
export type { AgentSkill } from './skill'
|
||||
export { AgentLoop } from './loop'
|
||||
export type {
|
||||
AgentLoopEvents,
|
||||
AgentLoopOptions,
|
||||
AgentRunResult,
|
||||
CompactionOptions,
|
||||
ToolExecutedEvent,
|
||||
} from './loop'
|
||||
export { createIpcTransport } from './electron-transport'
|
||||
export type { IpcStreamChunk, IpcStreamStart, IpcTransportOptions } from './electron-transport'
|
||||
@@ -0,0 +1,580 @@
|
||||
import type { AgentSkill } from './skill'
|
||||
import type {
|
||||
AgentImage,
|
||||
AgentMessage,
|
||||
AgentStreamHandle,
|
||||
AgentToolCall,
|
||||
AgentToolResult,
|
||||
AgentTransport,
|
||||
ToolExecution,
|
||||
} from './types'
|
||||
|
||||
export interface ToolExecutedEvent<TSnapshot> {
|
||||
call: AgentToolCall
|
||||
execution: ToolExecution
|
||||
/**
|
||||
* Snapshot captured just before this tool ran; present only on the first
|
||||
* mutating tool of a run (hook for one-click rollback UIs).
|
||||
*/
|
||||
snapshotBefore?: TSnapshot | undefined
|
||||
}
|
||||
|
||||
export interface AgentRunResult {
|
||||
/** final assistant text of the run ('' when cut off) */
|
||||
text: string
|
||||
cancelled: boolean
|
||||
/** true when maxTurns was reached; text is the partial answer from the no-tools finalizing turn */
|
||||
turnLimit: boolean
|
||||
}
|
||||
|
||||
export interface AgentLoopEvents<TSnapshot> {
|
||||
/** cumulative assistant text of the current turn (call per delta) */
|
||||
onText?(text: string): void
|
||||
/** a tool is about to execute (UI shows a live "running" indicator; onToolExecuted always follows) */
|
||||
onToolStart?(call: AgentToolCall): void
|
||||
onToolExecuted?(event: ToolExecutedEvent<TSnapshot>): void
|
||||
/** a turn requested tools and they ran; the loop is going back to the model */
|
||||
onTurnEnd?(): void
|
||||
onDone?(result: AgentRunResult): void
|
||||
onError?(error: string): void
|
||||
}
|
||||
|
||||
/** Context compaction config (budget tracked in UTF-8 bytes rather than message count) */
|
||||
export interface CompactionOptions {
|
||||
/** History size that triggers compaction (UTF-8 bytes, default 256KB) */
|
||||
maxBytes?: number
|
||||
/** Size of recent messages kept after compaction (bytes, default 96KB, cut at a user boundary) */
|
||||
keepRecentBytes?: number
|
||||
/** Disable LLM summarization and use only the mechanical digest (for tests/offline) */
|
||||
disableLlmSummary?: boolean
|
||||
}
|
||||
|
||||
export interface AgentLoopOptions<TSnapshot = unknown> {
|
||||
transport: AgentTransport
|
||||
skill: AgentSkill
|
||||
events?: AgentLoopEvents<TSnapshot>
|
||||
/** hard cap on model round-trips per run (default 8) */
|
||||
maxTurns?: number
|
||||
/** history cap in messages, trimmed at user-turn boundaries (default 40) */
|
||||
maxHistory?: number
|
||||
/** Context compaction; false disables it (enabled by default with default thresholds) */
|
||||
compaction?: CompactionOptions | false
|
||||
/** capture rollback state; invoked right before tools run (see snapshotBefore) */
|
||||
captureSnapshot?(): TSnapshot
|
||||
/** wrap instruction + skill context into the user message text */
|
||||
formatUserMessage?(instruction: string, context: string): string
|
||||
/** appended to the system prompt each turn (e.g. reply-language directive following the UI language) */
|
||||
systemSuffix?(): string
|
||||
}
|
||||
|
||||
const COMPACT_MAX_BYTES = 256 * 1024
|
||||
const COMPACT_KEEP_RECENT_BYTES = 96 * 1024
|
||||
/** Pre-truncation of each tool output in the summary request (the compaction request itself must not blow up on huge outputs) */
|
||||
const SUMMARIZE_TOOL_OUTPUT_MAX = 2_000
|
||||
const SUMMARIZE_TIMEOUT_MS = 30_000
|
||||
/** When over budget mid-run, keep the last N tool messages verbatim and truncate earlier outputs to this length */
|
||||
const STALE_TOOL_KEEP_RECENT = 2
|
||||
const STALE_TOOL_OUTPUT_MAX = 1_000
|
||||
|
||||
/** Per-run retry cap for tool-input parse failures; abort beyond it (keeps the model from burning turns on bad JSON) */
|
||||
const MAX_INPUT_PARSE_RETRIES = 3
|
||||
|
||||
const TURN_LIMIT_NOTE =
|
||||
'[System] The tool-call turn limit for this request has been reached; no more tools may be called this turn. ' +
|
||||
'Answer directly from the information already gathered; if the task is unfinished, briefly state what is done and what remains.'
|
||||
|
||||
const SUMMARIZE_SYSTEM =
|
||||
'You are a conversation compressor. Compress this editing session between the user and the AI assistant into a concise summary so later turns can continue with context. ' +
|
||||
"Keep: the user's goals and key instructions, completed changes (which files/pages/elements were modified), important facts and data, and outstanding items. " +
|
||||
'For specific figures/statistics, mark their provenance: figures from the user or from tool results (e.g. web_search) keep their source; figures the assistant produced without a source must be marked "(unverified)" so later turns do not treat them as established facts. ' +
|
||||
'Omit: pleasantries, tool-call details, and intermediate trial and error. Use a bullet list of at most 400 words. Write the summary in the same language as the conversation. Output only the summary body, with no preamble.'
|
||||
|
||||
/** Prefix of the synthetic user message that carries the compacted-history summary */
|
||||
const COMPACT_SUMMARY_PREFIX = '[Summary of earlier conversation'
|
||||
const COMPACT_SUMMARY_HEADER = '[Summary of earlier conversation (auto-compacted)]'
|
||||
const COMPACT_SUMMARY_ACK = 'Understood, continuing from the progress so far.'
|
||||
|
||||
/** Approximate UTF-8 byte count (ASCII 1 byte, CJK etc. 3; surrogate pairs count as 6 — slight overestimate is harmless) */
|
||||
function utf8Size(s: string): number {
|
||||
let n = 0
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s.charCodeAt(i)
|
||||
n += c < 0x80 ? 1 : c < 0x800 ? 2 : 3
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
/** Approximate byte cost of one message (text + tool inputs/outputs + image base64) */
|
||||
function messageSize(m: AgentMessage): number {
|
||||
if (m.role === 'tool') {
|
||||
return m.results.reduce((n, r) => n + utf8Size(r.output) + 40, 0)
|
||||
}
|
||||
let n = utf8Size(m.text)
|
||||
if (m.role === 'user' && m.images) {
|
||||
n += m.images.reduce((s, img) => s + img.base64.length, 0)
|
||||
}
|
||||
if (m.role === 'assistant' && m.toolCalls) {
|
||||
for (const c of m.toolCalls) {
|
||||
try {
|
||||
n += utf8Size(JSON.stringify(c.input)) + 40
|
||||
} catch {
|
||||
n += 40
|
||||
}
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
function historySize(messages: readonly AgentMessage[]): number {
|
||||
return messages.reduce((n, m) => n + messageSize(m), 0)
|
||||
}
|
||||
|
||||
/** Mechanical digest when LLM summarization is unavailable: bullet list of user instructions + final replies */
|
||||
function mechanicalDigest(dropped: readonly AgentMessage[]): string {
|
||||
const lines: string[] = []
|
||||
for (const m of dropped) {
|
||||
if (m.role === 'user' && !m.text.startsWith(COMPACT_SUMMARY_PREFIX)) {
|
||||
lines.push(`- User: ${m.text.slice(0, 200)}`)
|
||||
} else if (m.role === 'assistant' && m.text && !m.toolCalls?.length) {
|
||||
lines.push(` Reply: ${m.text.slice(0, 200)}`)
|
||||
}
|
||||
}
|
||||
return lines.join('\n').slice(0, 4_000) || '(earlier conversation omitted)'
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic ReAct loop: user message -> model turn (text + tool calls) ->
|
||||
* execute tools -> feed results back -> repeat until the model answers with
|
||||
* plain text. History persists across runs, so follow-up questions work.
|
||||
*/
|
||||
export class AgentLoop<TSnapshot = unknown> {
|
||||
private readonly options: AgentLoopOptions<TSnapshot>
|
||||
private history: AgentMessage[] = []
|
||||
private handle: AgentStreamHandle | null = null
|
||||
private running = false
|
||||
private cancelled = false
|
||||
private turns = 0
|
||||
/** Finalizing turn after hitting the turn limit: no tools, let the model answer from what it has read */
|
||||
private finalizing = false
|
||||
private mutationSeen = false
|
||||
private inputParseFails = 0
|
||||
private turnText = ''
|
||||
private toolCalls: AgentToolCall[] = []
|
||||
/** user message of the in-flight run; a failed run rolls it (and everything after) back out of history */
|
||||
private runUserMsg: AgentMessage | null = null
|
||||
/** invalidates stale transport callbacks after cancel/reset */
|
||||
private generation = 0
|
||||
/** per-run abort: aborted on cancel(); long tools (e.g. generate_deck) use it to break internal loops */
|
||||
private abortController: AbortController | null = null
|
||||
|
||||
constructor(options: AgentLoopOptions<TSnapshot>) {
|
||||
this.options = options
|
||||
}
|
||||
|
||||
get busy(): boolean {
|
||||
return this.running
|
||||
}
|
||||
|
||||
get messages(): readonly AgentMessage[] {
|
||||
return this.history
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed the conversation with restored history (e.g. transcript reloaded from
|
||||
* disk when a document reopens), so follow-up instructions keep their context.
|
||||
* No-op unless the loop is idle with an empty history.
|
||||
* Old messages over the compaction budget fold into a mechanical digest
|
||||
* (no LLM request on restore, guaranteeing zero latency).
|
||||
*/
|
||||
restore(messages: readonly AgentMessage[]): void {
|
||||
if (this.running || this.history.length > 0 || messages.length === 0) return
|
||||
// Unanswered user messages (a failed or interrupted run persisted them without a
|
||||
// reply) must not re-enter the model context: trailing ones would pair with the
|
||||
// next instruction as one turn, adjacent ones read as a combined instruction (#92)
|
||||
this.history = messages.filter(
|
||||
(m, i) => m.role !== 'user' || (messages[i + 1] && messages[i + 1]!.role !== 'user'),
|
||||
)
|
||||
if (this.history.length === 0) return
|
||||
if (this.compactionEnabled()) {
|
||||
const { maxBytes, keepRecentBytes } = this.compactBudget()
|
||||
if (historySize(this.history) > maxBytes) {
|
||||
const cut = this.findCompactCut(keepRecentBytes)
|
||||
if (cut > 0) {
|
||||
const digest = mechanicalDigest(this.history.slice(0, cut))
|
||||
this.history = [
|
||||
{ role: 'user', text: `${COMPACT_SUMMARY_HEADER}\n${digest}` },
|
||||
{ role: 'assistant', text: COMPACT_SUMMARY_ACK },
|
||||
...this.history.slice(cut),
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
this.trimHistory()
|
||||
}
|
||||
|
||||
/** images: inline attachments for this user turn (vision input; see AgentImage) */
|
||||
run(instruction: string, images?: AgentImage[]): void {
|
||||
if (this.running || !instruction) return
|
||||
this.running = true
|
||||
this.cancelled = false
|
||||
this.turns = 0
|
||||
this.finalizing = false
|
||||
this.mutationSeen = false
|
||||
this.inputParseFails = 0
|
||||
this.abortController = new AbortController()
|
||||
const context = this.options.skill.buildContext?.() ?? ''
|
||||
const format =
|
||||
this.options.formatUserMessage ??
|
||||
((instr: string, ctx: string) => (ctx ? `${instr}\n\n${ctx}` : instr))
|
||||
const userMsg: AgentMessage = {
|
||||
role: 'user',
|
||||
text: format(instruction, context),
|
||||
...(images?.length ? { images } : {}),
|
||||
}
|
||||
void this.beginRun(userMsg)
|
||||
}
|
||||
|
||||
/** Compact (if needed), push the user message, then start the turn. Compaction failure doesn't block the run. */
|
||||
private async beginRun(userMsg: AgentMessage): Promise<void> {
|
||||
const generation = this.generation
|
||||
try {
|
||||
await this.maybeCompact()
|
||||
} catch {
|
||||
// Proceed with the run even if compaction fails (an over-budget history only costs more, it's still correct)
|
||||
}
|
||||
if (generation !== this.generation) return // reset during compaction
|
||||
if (this.cancelled) {
|
||||
this.running = false
|
||||
this.options.events?.onDone?.({ text: '', cancelled: true, turnLimit: false })
|
||||
return
|
||||
}
|
||||
// Leftover unanswered user message (a previous run failed before replying):
|
||||
// drop it so the model never sees two adjacent user turns as one combined instruction
|
||||
while (this.history.at(-1)?.role === 'user') this.history.pop()
|
||||
this.runUserMsg = userMsg
|
||||
this.history.push(userMsg)
|
||||
this.startTurn()
|
||||
}
|
||||
|
||||
/**
|
||||
* A run failed: remove its user message and every message after it, so the
|
||||
* failed instruction can't be silently re-executed by the next run (#92).
|
||||
*/
|
||||
private rollbackFailedRun(): void {
|
||||
const msg = this.runUserMsg
|
||||
this.runUserMsg = null
|
||||
if (!msg) return
|
||||
const i = this.history.lastIndexOf(msg)
|
||||
if (i >= 0) this.history.splice(i)
|
||||
}
|
||||
|
||||
// ── Context compaction: fold old conversation into a summary, keep recent messages verbatim ──
|
||||
|
||||
private compactionEnabled(): boolean {
|
||||
return this.options.compaction !== false
|
||||
}
|
||||
|
||||
private compactBudget(): { maxBytes: number; keepRecentBytes: number } {
|
||||
const opt = this.options.compaction === false ? undefined : this.options.compaction
|
||||
return {
|
||||
maxBytes: opt?.maxBytes ?? COMPACT_MAX_BYTES,
|
||||
keepRecentBytes: opt?.keepRecentBytes ?? COMPACT_KEEP_RECENT_BYTES,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the compaction cut at a user boundary: accumulate from the tail up to keepRecentBytes.
|
||||
* Returns the start index of the kept segment; if no suitable boundary exists,
|
||||
* fall back to keeping the last user turn.
|
||||
*/
|
||||
private findCompactCut(keepRecentBytes: number): number {
|
||||
let kept = 0
|
||||
let cut = -1
|
||||
for (let i = this.history.length - 1; i >= 0; i--) {
|
||||
kept += messageSize(this.history[i]!)
|
||||
if (kept > keepRecentBytes && cut >= 0) break
|
||||
if (this.history[i]!.role === 'user') cut = i
|
||||
}
|
||||
if (cut < 0) {
|
||||
for (let i = this.history.length - 1; i >= 0; i--) {
|
||||
if (this.history[i]!.role === 'user') return i
|
||||
}
|
||||
}
|
||||
return cut
|
||||
}
|
||||
|
||||
private async maybeCompact(): Promise<void> {
|
||||
if (!this.compactionEnabled()) return
|
||||
const { maxBytes, keepRecentBytes } = this.compactBudget()
|
||||
if (historySize(this.history) <= maxBytes) return
|
||||
const cut = this.findCompactCut(keepRecentBytes)
|
||||
if (cut <= 0) return // no foldable prefix
|
||||
const dropped = this.history.slice(0, cut)
|
||||
const opt = this.options.compaction === false ? undefined : this.options.compaction
|
||||
let summary: string | null = null
|
||||
if (!opt?.disableLlmSummary) summary = await this.summarizeViaLlm(dropped)
|
||||
if (!summary) summary = mechanicalDigest(dropped)
|
||||
this.history = [
|
||||
{ role: 'user', text: `${COMPACT_SUMMARY_HEADER}\n${summary}` },
|
||||
{ role: 'assistant', text: COMPACT_SUMMARY_ACK },
|
||||
...this.history.slice(cut),
|
||||
]
|
||||
}
|
||||
|
||||
/** Hand the folded conversation to the model for a summary; returns null on failure/timeout (falls back to the mechanical digest). */
|
||||
private summarizeViaLlm(dropped: readonly AgentMessage[]): Promise<string | null> {
|
||||
// Slim down the summary request itself: pre-truncate tool outputs, strip images
|
||||
const slim: AgentMessage[] = dropped.map((m) => {
|
||||
if (m.role === 'tool') {
|
||||
return {
|
||||
role: 'tool' as const,
|
||||
results: m.results.map((r) => ({
|
||||
...r,
|
||||
output: r.output.slice(0, SUMMARIZE_TOOL_OUTPUT_MAX),
|
||||
})),
|
||||
}
|
||||
}
|
||||
if (m.role === 'user' && m.images?.length) return { role: 'user' as const, text: m.text }
|
||||
return m
|
||||
})
|
||||
return new Promise((resolve) => {
|
||||
let text = ''
|
||||
let settled = false
|
||||
const finish = (v: string | null) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve(v)
|
||||
}
|
||||
const timer = setTimeout(() => finish(null), SUMMARIZE_TIMEOUT_MS)
|
||||
try {
|
||||
// Attach to this.handle so cancel() can abort the summary request when the user clicks stop
|
||||
this.handle = this.options.transport.stream(
|
||||
{
|
||||
system: SUMMARIZE_SYSTEM,
|
||||
messages: [
|
||||
...slim,
|
||||
{ role: 'user', text: 'Compress the conversation above as instructed.' },
|
||||
],
|
||||
tools: [],
|
||||
},
|
||||
{
|
||||
onDelta: (t) => {
|
||||
text += t
|
||||
},
|
||||
onToolCall: () => {
|
||||
/* the summary turn gets no tools */
|
||||
},
|
||||
onDone: () => finish(text.trim() || null),
|
||||
onError: () => finish(null),
|
||||
},
|
||||
)
|
||||
} catch {
|
||||
finish(null)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* When over budget mid-run (between tool turns), truncate stale tool outputs:
|
||||
* keep structure (tool_use/tool_result pairs intact), cut content only,
|
||||
* and keep the most recent N verbatim.
|
||||
*/
|
||||
private squashStaleToolOutputs(): void {
|
||||
if (!this.compactionEnabled()) return
|
||||
const { maxBytes } = this.compactBudget()
|
||||
if (historySize(this.history) <= maxBytes) return
|
||||
let recent = 0
|
||||
for (let i = this.history.length - 1; i >= 0; i--) {
|
||||
const m = this.history[i]!
|
||||
if (m.role !== 'tool') continue
|
||||
recent++
|
||||
if (recent <= STALE_TOOL_KEEP_RECENT) continue
|
||||
m.results = m.results.map((r) =>
|
||||
r.output.length > STALE_TOOL_OUTPUT_MAX
|
||||
? {
|
||||
...r,
|
||||
output: `${r.output.slice(0, STALE_TOOL_OUTPUT_MAX)}\n…(output truncated: too long)`,
|
||||
}
|
||||
: r,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
if (!this.running) return
|
||||
this.cancelled = true
|
||||
// abort lets long tools mid-execution (internal LLM loops etc.) stop promptly
|
||||
this.abortController?.abort()
|
||||
// the transport emits onDone after aborting, which finalizes the run
|
||||
this.handle?.cancel()
|
||||
}
|
||||
|
||||
/** drop the conversation (e.g. when a different document is opened) */
|
||||
reset(): void {
|
||||
this.generation++
|
||||
this.abortController?.abort()
|
||||
this.handle?.cancel()
|
||||
this.handle = null
|
||||
this.running = false
|
||||
this.cancelled = false
|
||||
this.history = []
|
||||
this.runUserMsg = null
|
||||
}
|
||||
|
||||
private trimHistory(): void {
|
||||
const max = this.options.maxHistory ?? 40
|
||||
if (this.history.length <= max) return
|
||||
// cut only at a user message so tool_use/tool_result pairs stay intact
|
||||
let i = this.history.length - max
|
||||
while (i < this.history.length && this.history[i]!.role !== 'user') i++
|
||||
this.history = this.history.slice(i)
|
||||
}
|
||||
|
||||
private startTurn(): void {
|
||||
const generation = this.generation
|
||||
this.trimHistory()
|
||||
this.turnText = ''
|
||||
this.toolCalls = []
|
||||
// Some transports emit an extra onDone after cancel — this turn may finalize only once
|
||||
let settled = false
|
||||
this.handle = this.options.transport.stream(
|
||||
{
|
||||
system: this.options.skill.systemPrompt + (this.options.systemSuffix?.() ?? ''),
|
||||
messages: [...this.history],
|
||||
tools: this.finalizing ? [] : this.options.skill.tools,
|
||||
},
|
||||
{
|
||||
onDelta: (text) => {
|
||||
if (generation !== this.generation || settled) return
|
||||
this.turnText += text
|
||||
this.options.events?.onText?.(this.turnText)
|
||||
},
|
||||
onToolCall: (call) => {
|
||||
if (generation !== this.generation || settled) return
|
||||
this.toolCalls.push(call)
|
||||
},
|
||||
onDone: () => {
|
||||
if (generation !== this.generation || settled) return
|
||||
settled = true
|
||||
void this.finishTurn()
|
||||
},
|
||||
onError: (error) => {
|
||||
if (generation !== this.generation || settled) return
|
||||
settled = true
|
||||
this.running = false
|
||||
this.rollbackFailedRun()
|
||||
this.options.events?.onError?.(error)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private async finishTurn(): Promise<void> {
|
||||
const { events, skill, captureSnapshot } = this.options
|
||||
const toolCalls = this.toolCalls
|
||||
|
||||
// final turn: no tools requested, the user stopped the run, or the
|
||||
// no-tools finalizing turn after hitting the limit
|
||||
// (a cancelled turn drops its tool calls — no results would follow)
|
||||
if (toolCalls.length === 0 || this.cancelled || this.finalizing) {
|
||||
this.history.push({ role: 'assistant', text: this.turnText })
|
||||
this.running = false
|
||||
this.runUserMsg = null
|
||||
events?.onDone?.({
|
||||
text: this.turnText,
|
||||
cancelled: this.cancelled,
|
||||
turnLimit: this.finalizing,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
this.history.push({ role: 'assistant', text: this.turnText, toolCalls })
|
||||
const generation = this.generation
|
||||
const results: AgentToolResult[] = []
|
||||
for (const call of toolCalls) {
|
||||
// The user hit stop while an earlier tool was running: skip remaining tools,
|
||||
// but fill in paired error results to keep tool_use/tool_result pairs valid for the next request
|
||||
if (this.cancelled) {
|
||||
results.push({
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
output: '(the user stopped the run; this tool was not executed)',
|
||||
isError: true,
|
||||
})
|
||||
continue
|
||||
}
|
||||
// The input JSON failed to parse: don't execute; feed the error back so the model fixes the args and retries
|
||||
if (call.inputError) {
|
||||
this.inputParseFails++
|
||||
results.push({
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
output: `Tool input JSON failed to parse; the tool was not executed: ${call.inputError}\nFix the arguments (make sure quotes inside strings are escaped) and call again.`,
|
||||
isError: true,
|
||||
})
|
||||
events?.onToolExecuted?.({
|
||||
call,
|
||||
execution: { output: call.inputError, isError: true, summary: call.name },
|
||||
})
|
||||
continue
|
||||
}
|
||||
events?.onToolStart?.(call)
|
||||
const snapshot = !this.mutationSeen ? captureSnapshot?.() : undefined
|
||||
let execution: ToolExecution
|
||||
try {
|
||||
execution = await skill.executeTool(call, this.abortController?.signal)
|
||||
} catch (e) {
|
||||
execution = {
|
||||
output: e instanceof Error ? e.message : String(e),
|
||||
isError: true,
|
||||
summary: call.name,
|
||||
}
|
||||
}
|
||||
if (generation !== this.generation) return // reset while a tool was running
|
||||
const firstMutation = !!execution.mutated && !this.mutationSeen
|
||||
if (execution.mutated) this.mutationSeen = true
|
||||
results.push({
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
output: execution.output,
|
||||
isError: execution.isError,
|
||||
})
|
||||
events?.onToolExecuted?.({
|
||||
call,
|
||||
execution,
|
||||
snapshotBefore: firstMutation ? snapshot : undefined,
|
||||
})
|
||||
}
|
||||
this.history.push({ role: 'tool', results })
|
||||
|
||||
// Cancelled while tools were executing: finish immediately, no further model request
|
||||
if (this.cancelled) {
|
||||
this.running = false
|
||||
this.runUserMsg = null
|
||||
events?.onDone?.({ text: this.turnText, cancelled: true, turnLimit: false })
|
||||
return
|
||||
}
|
||||
|
||||
// Bad-input retries hit the cap: abort instead of burning more turns
|
||||
if (this.inputParseFails >= MAX_INPUT_PARSE_RETRIES) {
|
||||
this.running = false
|
||||
this.rollbackFailedRun()
|
||||
events?.onError?.(
|
||||
`Tool input JSON failed to parse ${MAX_INPUT_PARSE_RETRIES} times in a row; retries stopped, please send the request again`,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
this.turns++
|
||||
if (this.turns >= (this.options.maxTurns ?? 8)) {
|
||||
// Don't throw away the context already gathered: append one no-tools turn for a partial answer
|
||||
this.finalizing = true
|
||||
this.history.push({ role: 'user', text: TURN_LIMIT_NOTE })
|
||||
}
|
||||
// Long runs (e.g. page-by-page generation) over budget mid-way: truncate stale tool outputs so each turn doesn't resend a huge payload
|
||||
this.squashStaleToolOutputs()
|
||||
events?.onTurnEnd?.()
|
||||
this.startTurn()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { AgentToolCall, AgentToolDef, ToolExecution } from './types'
|
||||
|
||||
/**
|
||||
* A skill packages one capability domain for the agent loop: its system
|
||||
* prompt section, its tools, per-turn context, and the tool executor.
|
||||
* AI Docs ships a docx skill; Excel / PPT skills plug in the same way.
|
||||
*/
|
||||
export interface AgentSkill {
|
||||
id: string
|
||||
/** system prompt section describing this skill's rules and tools */
|
||||
systemPrompt: string
|
||||
tools: AgentToolDef[]
|
||||
/**
|
||||
* Fresh context sections attached to every user turn (e.g. document
|
||||
* skeleton + selection). Return '' when there is nothing to attach.
|
||||
*/
|
||||
buildContext?(): string
|
||||
/**
|
||||
* signal: aborted when the user hits stop. Long-running tools (e.g.
|
||||
* generate_deck with internal LLM calls) should check signal.aborted in
|
||||
* their loops and stop promptly.
|
||||
*/
|
||||
executeTool(call: AgentToolCall, signal?: AbortSignal): ToolExecution | Promise<ToolExecution>
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge several skills into one (tool names must be globally unique).
|
||||
* `intro` becomes the shared preamble of the combined system prompt.
|
||||
*/
|
||||
export function composeSkills(id: string, intro: string, skills: AgentSkill[]): AgentSkill {
|
||||
const owner = new Map<string, AgentSkill>()
|
||||
for (const skill of skills) {
|
||||
for (const tool of skill.tools) {
|
||||
if (owner.has(tool.name)) throw new Error(`duplicate tool name: ${tool.name}`)
|
||||
owner.set(tool.name, skill)
|
||||
}
|
||||
}
|
||||
return {
|
||||
id,
|
||||
systemPrompt: [intro, ...skills.map((s) => s.systemPrompt)].filter(Boolean).join('\n\n'),
|
||||
tools: skills.flatMap((s) => s.tools),
|
||||
buildContext: () =>
|
||||
skills
|
||||
.map((s) => s.buildContext?.() ?? '')
|
||||
.filter(Boolean)
|
||||
.join('\n\n'),
|
||||
executeTool: (call, signal) => {
|
||||
const skill = owner.get(call.name)
|
||||
if (!skill) {
|
||||
return { output: `Unknown tool: ${call.name}`, isError: true, summary: call.name }
|
||||
}
|
||||
return skill.executeTool(call, signal)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/** JSON-Schema described tool exposed to the model */
|
||||
export interface AgentToolDef {
|
||||
name: string
|
||||
description: string
|
||||
/** JSON Schema (object) describing the tool input */
|
||||
inputSchema: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface AgentToolCall {
|
||||
id: string
|
||||
name: string
|
||||
input: Record<string, unknown>
|
||||
/** Parse error when the model emitted invalid input JSON; the loop feeds back an is_error result for retry instead of aborting the run */
|
||||
inputError?: string | undefined
|
||||
}
|
||||
|
||||
export interface AgentToolResult {
|
||||
id: string
|
||||
/** tool name (Gemini addresses function responses by name, not id) */
|
||||
name: string
|
||||
output: string
|
||||
isError?: boolean | undefined
|
||||
}
|
||||
|
||||
/** inline image attached to a user turn, fed to vision-capable providers as multimodal input */
|
||||
export interface AgentImage {
|
||||
/** raw base64 (no data: URL prefix) */
|
||||
base64: string
|
||||
/** e.g. "image/png" */
|
||||
mime: string
|
||||
}
|
||||
|
||||
export type AgentMessage =
|
||||
| { role: 'user'; text: string; images?: AgentImage[] | undefined }
|
||||
| { role: 'assistant'; text: string; toolCalls?: AgentToolCall[] | undefined }
|
||||
| { role: 'tool'; results: AgentToolResult[] }
|
||||
|
||||
/**
|
||||
* Side-channel display data: UI-only, never merged into messages sent to the LLM.
|
||||
* kind='images' → image grid; kind='links' → link list; kind='text' → extra text.
|
||||
*/
|
||||
export interface ToolDisplay {
|
||||
kind: 'images' | 'links' | 'text'
|
||||
/** entry list for images / links modes */
|
||||
items?: Array<{ url: string; title?: string; thumb?: string }>
|
||||
/** extra text for text mode */
|
||||
text?: string
|
||||
}
|
||||
|
||||
/** outcome of one tool execution */
|
||||
export interface ToolExecution {
|
||||
/** result text fed back to the model */
|
||||
output: string
|
||||
isError?: boolean
|
||||
/** true when the tool changed the underlying artifact (document / sheet / deck) */
|
||||
mutated?: boolean
|
||||
/** short human-readable label for activity UI */
|
||||
summary: string
|
||||
/**
|
||||
* Side-channel display: for UI only, never enters the LLM context.
|
||||
* Ignored when tool results are assembled into an AgentMessage.
|
||||
*/
|
||||
display?: ToolDisplay
|
||||
}
|
||||
|
||||
// ---- run phase (drives the in-progress status line in chat UIs) ----
|
||||
|
||||
export type AgentPhaseKind =
|
||||
/** request sent, waiting for the model's first content block */
|
||||
| 'requesting'
|
||||
| 'thinking'
|
||||
| 'responding'
|
||||
/** the model is streaming tool arguments (e.g. a full outline) with no visible text */
|
||||
| 'tool-input'
|
||||
| 'tool-running'
|
||||
|
||||
export interface AgentPhase {
|
||||
kind: AgentPhaseKind
|
||||
toolName?: string | undefined
|
||||
}
|
||||
|
||||
// ---- LLM transport (how one model turn is streamed; app supplies the impl) ----
|
||||
|
||||
export interface AgentStreamRequest {
|
||||
system: string
|
||||
messages: AgentMessage[]
|
||||
tools: AgentToolDef[]
|
||||
}
|
||||
|
||||
export interface AgentStreamCallbacks {
|
||||
onDelta(text: string): void
|
||||
/** complete parsed tool call (arguments finished streaming) */
|
||||
onToolCall(call: AgentToolCall): void
|
||||
/** Phase changes within the model stream (thinking / responding / tool-input); older transports may omit this */
|
||||
onPhase?(phase: AgentPhase): void
|
||||
onDone(): void
|
||||
onError(error: string): void
|
||||
}
|
||||
|
||||
export interface AgentStreamHandle {
|
||||
/** abort the in-flight turn; the transport must still emit onDone afterwards */
|
||||
cancel(): void
|
||||
}
|
||||
|
||||
export interface AgentTransport {
|
||||
stream(request: AgentStreamRequest, callbacks: AgentStreamCallbacks): AgentStreamHandle
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { createIpcTransport, type IpcStreamChunk, type IpcStreamStart } from '../src'
|
||||
|
||||
interface FakeSettings {
|
||||
provider: string
|
||||
}
|
||||
|
||||
function setup() {
|
||||
let listener: ((chunk: IpcStreamChunk) => void) | undefined
|
||||
const unsubscribe = vi.fn(() => {
|
||||
listener = undefined
|
||||
})
|
||||
const started: IpcStreamStart<FakeSettings>[] = []
|
||||
const cancelled: string[] = []
|
||||
const transport = createIpcTransport<FakeSettings>({
|
||||
onStream: (l) => {
|
||||
listener = l
|
||||
return unsubscribe
|
||||
},
|
||||
start: (request) => started.push(request),
|
||||
cancel: (requestId) => cancelled.push(requestId),
|
||||
getSettings: () => ({ provider: 'genspark' }),
|
||||
unknownErrorText: () => 'unknown error',
|
||||
})
|
||||
const cb = {
|
||||
onDelta: vi.fn(),
|
||||
onToolCall: vi.fn(),
|
||||
onDone: vi.fn(),
|
||||
onError: vi.fn(),
|
||||
}
|
||||
const handle = transport.stream({ system: 'sys', messages: [], tools: [] }, cb)
|
||||
const emit = (chunk: Omit<IpcStreamChunk, 'requestId'> & { requestId?: string }) =>
|
||||
listener?.({ requestId: started[0]!.requestId, ...chunk })
|
||||
return { started, cancelled, cb, handle, emit, unsubscribe }
|
||||
}
|
||||
|
||||
describe('createIpcTransport', () => {
|
||||
it('starts one request with settings and forwards deltas and tool calls', () => {
|
||||
const { started, cb, emit } = setup()
|
||||
expect(started).toHaveLength(1)
|
||||
expect(started[0]!.settings).toEqual({ provider: 'genspark' })
|
||||
expect(started[0]!.system).toBe('sys')
|
||||
|
||||
emit({ type: 'delta', text: 'hi' })
|
||||
emit({ type: 'delta' })
|
||||
emit({ type: 'tool-call', toolCall: { id: 'c1', name: 'read', input: {} } })
|
||||
expect(cb.onDelta).toHaveBeenNthCalledWith(1, 'hi')
|
||||
expect(cb.onDelta).toHaveBeenNthCalledWith(2, '')
|
||||
expect(cb.onToolCall).toHaveBeenCalledWith({ id: 'c1', name: 'read', input: {} })
|
||||
})
|
||||
|
||||
it('ignores chunks for other requestIds', () => {
|
||||
const { cb, emit } = setup()
|
||||
emit({ requestId: 'someone-else', type: 'delta', text: 'nope' })
|
||||
expect(cb.onDelta).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('unsubscribes on done', () => {
|
||||
const { cb, emit, unsubscribe } = setup()
|
||||
emit({ type: 'done' })
|
||||
expect(cb.onDone).toHaveBeenCalledTimes(1)
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('maps error chunks to onError with the localized fallback', () => {
|
||||
const { cb, emit, unsubscribe } = setup()
|
||||
emit({ type: 'error' })
|
||||
expect(cb.onError).toHaveBeenCalledWith('unknown error')
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('cancel forwards the requestId to the bridge', () => {
|
||||
const { started, cancelled, handle } = setup()
|
||||
handle.cancel()
|
||||
expect(cancelled).toEqual([started[0]!.requestId])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,702 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
AgentLoop,
|
||||
composeSkills,
|
||||
type AgentMessage,
|
||||
type AgentSkill,
|
||||
type AgentStreamCallbacks,
|
||||
type AgentToolCall,
|
||||
type AgentTransport,
|
||||
type ToolExecution,
|
||||
} from '../src'
|
||||
|
||||
/** transport scripted turn by turn; exposes the callbacks for manual driving */
|
||||
function scriptedTransport(
|
||||
script: Array<(cb: AgentStreamCallbacks) => void>,
|
||||
): AgentTransport & {
|
||||
requests: Array<{ messageCount: number; toolCount: number }>
|
||||
cancels: number
|
||||
} {
|
||||
let turn = 0
|
||||
const transport = {
|
||||
requests: [] as Array<{ messageCount: number; toolCount: number }>,
|
||||
cancels: 0,
|
||||
lastCallbacks: null as AgentStreamCallbacks | null,
|
||||
stream(request: { messages: AgentMessage[]; tools: unknown[] }, cb: AgentStreamCallbacks) {
|
||||
transport.requests.push({
|
||||
messageCount: request.messages.length,
|
||||
toolCount: request.tools.length,
|
||||
})
|
||||
transport.lastCallbacks = cb
|
||||
const step = script[turn++]
|
||||
if (step) queueMicrotask(() => step(cb))
|
||||
return {
|
||||
cancel: () => {
|
||||
transport.cancels++
|
||||
queueMicrotask(() => cb.onDone())
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
return transport
|
||||
}
|
||||
|
||||
function makeSkill(execute?: (call: AgentToolCall) => ToolExecution): AgentSkill {
|
||||
return {
|
||||
id: 'test',
|
||||
systemPrompt: 'system',
|
||||
tools: [{ name: 'do_thing', description: 'd', inputSchema: { type: 'object' } }],
|
||||
buildContext: () => 'CTX',
|
||||
executeTool: execute ?? (() => ({ output: 'ok', summary: 'done', mutated: true })),
|
||||
}
|
||||
}
|
||||
|
||||
const flush = () => new Promise((r) => setTimeout(r, 0))
|
||||
|
||||
describe('AgentLoop', () => {
|
||||
it('runs a plain-text turn to completion', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onDelta('Hello')
|
||||
cb.onDelta(', world')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const onDone = vi.fn()
|
||||
const onText = vi.fn()
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill(), events: { onDone, onText } })
|
||||
loop.run('question')
|
||||
await flush()
|
||||
expect(onText).toHaveBeenLastCalledWith('Hello, world')
|
||||
expect(onDone).toHaveBeenCalledWith({ text: 'Hello, world', cancelled: false, turnLimit: false })
|
||||
expect(loop.busy).toBe(false)
|
||||
// user message carries the skill context
|
||||
expect(loop.messages[0]).toEqual({ role: 'user', text: 'question\n\nCTX' })
|
||||
expect(loop.messages[1]).toEqual({ role: 'assistant', text: 'Hello, world' })
|
||||
})
|
||||
|
||||
it('attaches images to the user message (and omits the field without any)', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onDelta('I can see it')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill() })
|
||||
const images = [{ base64: 'AAAA', mime: 'image/png' }]
|
||||
loop.run('describe the image', images)
|
||||
await flush()
|
||||
expect(loop.messages[0]).toEqual({ role: 'user', text: 'describe the image\n\nCTX', images })
|
||||
expect('images' in (loop.messages[0] as object)).toBe(true)
|
||||
})
|
||||
|
||||
it('executes tools and loops back to the model', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onDelta('Let me edit the document first')
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: { a: 1 } })
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => {
|
||||
cb.onDelta('All done')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const executed: AgentToolCall[] = []
|
||||
const skill = makeSkill((call) => {
|
||||
executed.push(call)
|
||||
return { output: 'result-1', summary: 'changed 1 spot', mutated: true }
|
||||
})
|
||||
const onToolExecuted = vi.fn()
|
||||
const onDone = vi.fn()
|
||||
const loop = new AgentLoop({
|
||||
transport,
|
||||
skill,
|
||||
captureSnapshot: () => 'SNAP',
|
||||
events: { onToolExecuted, onDone },
|
||||
})
|
||||
loop.run('make a change')
|
||||
await flush()
|
||||
await flush()
|
||||
|
||||
expect(executed).toHaveLength(1)
|
||||
// first mutation carries the pre-tool snapshot
|
||||
expect(onToolExecuted).toHaveBeenCalledWith(expect.objectContaining({ snapshotBefore: 'SNAP' }))
|
||||
expect(onDone).toHaveBeenCalledWith({ text: 'All done', cancelled: false, turnLimit: false })
|
||||
// history: user / assistant+tools / tool results / assistant
|
||||
expect(loop.messages.map((m) => m.role)).toEqual(['user', 'assistant', 'tool', 'assistant'])
|
||||
const toolMsg = loop.messages[2] as Extract<AgentMessage, { role: 'tool' }>
|
||||
expect(toolMsg.results[0]).toEqual({
|
||||
id: 't1',
|
||||
name: 'do_thing',
|
||||
output: 'result-1',
|
||||
isError: undefined,
|
||||
})
|
||||
// second request included the tool round-trip
|
||||
expect(transport.requests[1].messageCount).toBe(3)
|
||||
})
|
||||
|
||||
it('emits onToolStart before each execution, paired with onToolExecuted', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: { a: 1 } })
|
||||
cb.onToolCall({ id: 't2', name: 'do_thing', input: { a: 2 } })
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => cb.onDone(),
|
||||
])
|
||||
const order: string[] = []
|
||||
const loop = new AgentLoop({
|
||||
transport,
|
||||
skill: makeSkill(() => {
|
||||
order.push('exec')
|
||||
return { output: 'ok', summary: 's' }
|
||||
}),
|
||||
events: {
|
||||
onToolStart: (call) => order.push(`start:${call.id}`),
|
||||
onToolExecuted: ({ call }) => order.push(`done:${call.id}`),
|
||||
},
|
||||
})
|
||||
loop.run('x')
|
||||
await flush()
|
||||
await flush()
|
||||
expect(order).toEqual(['start:t1', 'exec', 'done:t1', 'start:t2', 'exec', 'done:t2'])
|
||||
})
|
||||
|
||||
it('only the first mutating tool carries a snapshot', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: {} })
|
||||
cb.onToolCall({ id: 't2', name: 'do_thing', input: {} })
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => cb.onDone(),
|
||||
])
|
||||
const onToolExecuted = vi.fn()
|
||||
const loop = new AgentLoop({
|
||||
transport,
|
||||
skill: makeSkill(),
|
||||
captureSnapshot: () => 'SNAP',
|
||||
events: { onToolExecuted },
|
||||
})
|
||||
loop.run('x')
|
||||
await flush()
|
||||
await flush()
|
||||
expect(onToolExecuted).toHaveBeenCalledTimes(2)
|
||||
expect(onToolExecuted.mock.calls[0][0].snapshotBefore).toBe('SNAP')
|
||||
expect(onToolExecuted.mock.calls[1][0].snapshotBefore).toBeUndefined()
|
||||
})
|
||||
|
||||
it('after maxTurns, adds a final tool-less turn that yields a partial answer', async () => {
|
||||
const alwaysTool = (cb: AgentStreamCallbacks) => {
|
||||
cb.onToolCall({ id: 'x', name: 'do_thing', input: {} })
|
||||
cb.onDone()
|
||||
}
|
||||
const finalize = (cb: AgentStreamCallbacks) => {
|
||||
cb.onDelta('partial conclusion')
|
||||
cb.onDone()
|
||||
}
|
||||
const transport = scriptedTransport([alwaysTool, alwaysTool, finalize])
|
||||
const onDone = vi.fn()
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill(), maxTurns: 2, events: { onDone } })
|
||||
loop.run('x')
|
||||
await flush()
|
||||
await flush()
|
||||
await flush()
|
||||
await flush()
|
||||
// The third turn is the finalizing one: no tools, and a system note was inserted into history
|
||||
expect(transport.requests).toHaveLength(3)
|
||||
expect(transport.requests[2].toolCount).toBe(0)
|
||||
const note = loop.messages.find((m) => m.role === 'user' && m.text.includes('turn limit'))
|
||||
expect(note).toBeDefined()
|
||||
expect(onDone).toHaveBeenCalledWith({ text: 'partial conclusion', cancelled: false, turnLimit: true })
|
||||
})
|
||||
|
||||
it('cancel drops pending tool calls and finalizes the run', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onDelta('partial')
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: {} })
|
||||
// no onDone: waits for cancel
|
||||
},
|
||||
])
|
||||
const executed: AgentToolCall[] = []
|
||||
const skill = makeSkill((call) => {
|
||||
executed.push(call)
|
||||
return { output: 'ok', summary: 's' }
|
||||
})
|
||||
const onDone = vi.fn()
|
||||
const loop = new AgentLoop({ transport, skill, events: { onDone } })
|
||||
loop.run('x')
|
||||
await flush()
|
||||
loop.cancel()
|
||||
await flush()
|
||||
expect(transport.cancels).toBe(1)
|
||||
expect(executed).toHaveLength(0)
|
||||
expect(onDone).toHaveBeenCalledWith({ text: 'partial', cancelled: true, turnLimit: false })
|
||||
// assistant message stored without toolCalls (no results would follow)
|
||||
expect(loop.messages[1]).toEqual({ role: 'assistant', text: 'partial' })
|
||||
})
|
||||
|
||||
it('cancel during tool execution aborts the signal, skips remaining tools and starts no new turn', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: {} })
|
||||
cb.onToolCall({ id: 't2', name: 'do_thing', input: {} })
|
||||
cb.onDone()
|
||||
},
|
||||
// The second turn should never be requested (no return to the model after cancel)
|
||||
(cb) => cb.onDone(),
|
||||
])
|
||||
const seen: Array<{ id: string; abortedAfterCancel: boolean }> = []
|
||||
let loop: AgentLoop | null = null
|
||||
const skill = makeSkill()
|
||||
skill.executeTool = (call, signal) => {
|
||||
// Simulate the user hitting stop while a long tool is running
|
||||
loop?.cancel()
|
||||
seen.push({ id: call.id, abortedAfterCancel: signal?.aborted === true })
|
||||
return { output: 'ok', summary: 's', mutated: true }
|
||||
}
|
||||
const onDone = vi.fn()
|
||||
loop = new AgentLoop({ transport, skill, events: { onDone } })
|
||||
loop.run('x')
|
||||
await flush()
|
||||
await flush()
|
||||
// Only the first tool ran; after cancel the signal is aborted right away (long tools' inner loops break on it)
|
||||
expect(seen).toEqual([{ id: 't1', abortedAfterCancel: true }])
|
||||
// The second tool didn't run, but a paired error result was added (tool_use/tool_result stay paired)
|
||||
const toolMsg = loop.messages[2] as Extract<AgentMessage, { role: 'tool' }>
|
||||
expect(toolMsg.results.map((r) => r.id)).toEqual(['t1', 't2'])
|
||||
expect(toolMsg.results[1].isError).toBe(true)
|
||||
// No further model request; the run finishes as cancelled
|
||||
expect(transport.requests).toHaveLength(1)
|
||||
expect(onDone).toHaveBeenCalledTimes(1)
|
||||
expect(onDone).toHaveBeenCalledWith({ text: '', cancelled: true, turnLimit: false })
|
||||
expect(loop.busy).toBe(false)
|
||||
})
|
||||
|
||||
it('executeTool receives a live (non-aborted) signal during normal runs', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: {} })
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => cb.onDone(),
|
||||
])
|
||||
let sawSignal: AbortSignal | undefined
|
||||
const skill = makeSkill()
|
||||
skill.executeTool = (_call, signal) => {
|
||||
sawSignal = signal
|
||||
return { output: 'ok', summary: 's' }
|
||||
}
|
||||
const loop = new AgentLoop({ transport, skill })
|
||||
loop.run('x')
|
||||
await flush()
|
||||
await flush()
|
||||
expect(sawSignal).toBeInstanceOf(AbortSignal)
|
||||
expect(sawSignal?.aborted).toBe(false)
|
||||
})
|
||||
|
||||
it('trims history at user boundaries', async () => {
|
||||
const script = Array.from({ length: 4 }, () => (cb: AgentStreamCallbacks) => {
|
||||
cb.onDelta('answer')
|
||||
cb.onDone()
|
||||
})
|
||||
const transport = scriptedTransport(script)
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill(), maxHistory: 3 })
|
||||
for (let i = 0; i < 4; i++) {
|
||||
loop.run(`question${i}`)
|
||||
await flush()
|
||||
}
|
||||
// trimmed to start at a user message
|
||||
expect(loop.messages.length).toBeLessThanOrEqual(4)
|
||||
expect(loop.messages[0].role).toBe('user')
|
||||
})
|
||||
|
||||
it('restore seeds history and the next run sends it to the model', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onDelta('picking up from before')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill() })
|
||||
loop.restore([
|
||||
{ role: 'user', text: 'previous question' },
|
||||
{ role: 'assistant', text: 'previous answer' },
|
||||
])
|
||||
expect(loop.messages).toHaveLength(2)
|
||||
|
||||
loop.run('follow-up')
|
||||
await flush()
|
||||
// The request carries the 2 restored messages + the new user message
|
||||
expect(transport.requests[0].messageCount).toBe(3)
|
||||
expect(loop.messages[0]).toEqual({ role: 'user', text: 'previous question' })
|
||||
})
|
||||
|
||||
it('restore is a no-op when history exists or the loop is busy', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onDelta('answer')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill() })
|
||||
loop.run('opening message')
|
||||
await flush()
|
||||
const before = loop.messages.length
|
||||
loop.restore([{ role: 'user', text: 'should-not-be-injected' }])
|
||||
expect(loop.messages.length).toBe(before)
|
||||
expect(
|
||||
loop.messages.some((m) => m.role === 'user' && 'text' in m && m.text === 'should-not-be-injected'),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('a failed run rolls its user message back out of history (#92)', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => cb.onError('Not signed in'),
|
||||
(cb) => {
|
||||
cb.onDelta('answer to the second question')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const onError = vi.fn()
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill(), events: { onError } })
|
||||
loop.run('change all headings to red')
|
||||
await flush()
|
||||
expect(onError).toHaveBeenCalledWith('Not signed in')
|
||||
// the failed instruction is gone, so it can't be re-executed by the next run
|
||||
expect(loop.messages).toHaveLength(0)
|
||||
|
||||
loop.run('what does this report propose?')
|
||||
await flush()
|
||||
// the next request carries only the new user message — no adjacent user turns
|
||||
expect(transport.requests[1].messageCount).toBe(1)
|
||||
expect(loop.messages.map((m) => m.role)).toEqual(['user', 'assistant'])
|
||||
})
|
||||
|
||||
it('a mid-run failure after tool turns rolls back the whole run', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: {} })
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => cb.onError('network dropped'),
|
||||
])
|
||||
const onError = vi.fn()
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill(), events: { onError } })
|
||||
loop.restore([
|
||||
{ role: 'user', text: 'earlier question' },
|
||||
{ role: 'assistant', text: 'earlier answer' },
|
||||
])
|
||||
loop.run('do more work')
|
||||
await flush()
|
||||
await flush()
|
||||
expect(onError).toHaveBeenCalledWith('network dropped')
|
||||
// history is back to the pre-run state: no dangling user/assistant/tool from the failed run
|
||||
expect(loop.messages).toEqual([
|
||||
{ role: 'user', text: 'earlier question' },
|
||||
{ role: 'assistant', text: 'earlier answer' },
|
||||
])
|
||||
})
|
||||
|
||||
it('restore drops unanswered user messages (trailing and adjacent)', () => {
|
||||
const transport = scriptedTransport([])
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill() })
|
||||
loop.restore([
|
||||
{ role: 'user', text: 'failed and never answered' },
|
||||
{ role: 'user', text: 'answered question' },
|
||||
{ role: 'assistant', text: 'the answer' },
|
||||
{ role: 'user', text: 'trailing unanswered' },
|
||||
])
|
||||
expect(loop.messages).toEqual([
|
||||
{ role: 'user', text: 'answered question' },
|
||||
{ role: 'assistant', text: 'the answer' },
|
||||
])
|
||||
})
|
||||
|
||||
it('restore trims oversized history at a user boundary', () => {
|
||||
const transport = scriptedTransport([])
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill(), maxHistory: 2 })
|
||||
loop.restore([
|
||||
{ role: 'user', text: 'q1' },
|
||||
{ role: 'assistant', text: 'a1' },
|
||||
{ role: 'user', text: 'q2' },
|
||||
{ role: 'assistant', text: 'a2' },
|
||||
])
|
||||
expect(loop.messages.length).toBeLessThanOrEqual(2)
|
||||
expect(loop.messages[0]).toEqual({ role: 'user', text: 'q2' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('AgentLoop compaction', () => {
|
||||
it('over budget before run: folds old conversation via LLM summary; new request carries the summary, not the originals', async () => {
|
||||
const bigAnswer = 'old reply'.padEnd(800, 'y')
|
||||
const transport = scriptedTransport([
|
||||
// Two real turns first: turn 1 produces a long over-budget reply
|
||||
(cb) => {
|
||||
cb.onDelta(bigAnswer)
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => {
|
||||
cb.onDelta('second-turn reply')
|
||||
cb.onDone()
|
||||
},
|
||||
// The 3rd run triggers compaction: this stream call is the summary request
|
||||
(cb) => {
|
||||
cb.onDelta('Goal: build a deck; 5 slides done')
|
||||
cb.onDone()
|
||||
},
|
||||
// Only then comes the actual model turn for run 3
|
||||
(cb) => {
|
||||
cb.onDelta('continuing')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const loop = new AgentLoop({
|
||||
transport,
|
||||
skill: makeSkill(),
|
||||
compaction: { maxBytes: 500, keepRecentBytes: 100 },
|
||||
})
|
||||
loop.run('old instruction')
|
||||
await flush()
|
||||
loop.run('second question')
|
||||
await flush()
|
||||
loop.run('follow-up')
|
||||
await flush()
|
||||
expect(transport.requests).toHaveLength(4)
|
||||
const msgs = loop.messages
|
||||
expect(msgs[0]!.role).toBe('user')
|
||||
expect((msgs[0] as { text: string }).text).toContain('[Summary of earlier conversation')
|
||||
expect((msgs[0] as { text: string }).text).toContain('5 slides done')
|
||||
// The folded original text is gone from history
|
||||
expect(msgs.some((m) => 'text' in m && m.text === bigAnswer)).toBe(false)
|
||||
// The new user message comes after the summary
|
||||
expect(msgs.some((m) => m.role === 'user' && 'text' in m && m.text.includes('follow-up'))).toBe(true)
|
||||
})
|
||||
|
||||
it('falls back to a mechanical digest when the LLM summary fails; the turn proceeds normally', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onDelta('done'.padEnd(800, 'y'))
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => {
|
||||
cb.onDelta('second turn')
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => cb.onError('summary failed'),
|
||||
(cb) => {
|
||||
cb.onDelta('answer')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const onDone = vi.fn()
|
||||
const loop = new AgentLoop({
|
||||
transport,
|
||||
skill: makeSkill(),
|
||||
compaction: { maxBytes: 500, keepRecentBytes: 100 },
|
||||
events: { onDone },
|
||||
})
|
||||
loop.run('key instruction')
|
||||
await flush()
|
||||
loop.run('second question')
|
||||
await flush()
|
||||
loop.run('continue')
|
||||
await flush()
|
||||
expect(onDone).toHaveBeenLastCalledWith({ text: 'answer', cancelled: false, turnLimit: false })
|
||||
// The mechanical digest kept the gist of the user instruction
|
||||
expect((loop.messages[0] as { text: string }).text).toContain('key instruction')
|
||||
expect((loop.messages[0] as { text: string }).text).toContain(
|
||||
'[Summary of earlier conversation',
|
||||
)
|
||||
})
|
||||
|
||||
it('restore over budget folds mechanically (no LLM request)', () => {
|
||||
const transport = scriptedTransport([])
|
||||
const loop = new AgentLoop({
|
||||
transport,
|
||||
skill: makeSkill(),
|
||||
compaction: { maxBytes: 500, keepRecentBytes: 200 },
|
||||
})
|
||||
loop.restore([
|
||||
{ role: 'user', text: 'very old instruction'.padEnd(600, 'x') },
|
||||
{ role: 'assistant', text: 'early reply' },
|
||||
{ role: 'user', text: 'recent question' },
|
||||
{ role: 'assistant', text: 'recent answer' },
|
||||
])
|
||||
expect(transport.requests).toHaveLength(0)
|
||||
expect((loop.messages[0] as { text: string }).text).toContain(
|
||||
'[Summary of earlier conversation',
|
||||
)
|
||||
expect((loop.messages[0] as { text: string }).text).toContain('very old instruction')
|
||||
expect(loop.messages.some((m) => 'text' in m && m.text === 'recent question')).toBe(true)
|
||||
})
|
||||
|
||||
it('over budget mid-run truncates stale tool outputs (the 2 most recent keep the full text)', async () => {
|
||||
const big = 'z'.repeat(3_000)
|
||||
const script = Array.from({ length: 3 }, (_, i) => (cb: AgentStreamCallbacks) => {
|
||||
cb.onToolCall({ id: `t${i}`, name: 'do_thing', input: {} })
|
||||
cb.onDone()
|
||||
})
|
||||
script.push((cb) => {
|
||||
cb.onDelta('done')
|
||||
cb.onDone()
|
||||
})
|
||||
const transport = scriptedTransport(script)
|
||||
const loop = new AgentLoop({
|
||||
transport,
|
||||
skill: makeSkill(() => ({ output: big, summary: 'big output', mutated: false })),
|
||||
compaction: { maxBytes: 5_000, keepRecentBytes: 2_000, disableLlmSummary: true },
|
||||
})
|
||||
loop.run('do the work')
|
||||
await flush()
|
||||
await flush()
|
||||
await flush()
|
||||
await flush()
|
||||
const toolMsgs = loop.messages.filter((m) => m.role === 'tool')
|
||||
expect(toolMsgs).toHaveLength(3)
|
||||
const first = toolMsgs[0] as { results: Array<{ output: string }> }
|
||||
const last = toolMsgs[2] as { results: Array<{ output: string }> }
|
||||
expect(first.results[0]!.output).toContain('…(output truncated: too long)')
|
||||
expect(first.results[0]!.output.length).toBeLessThan(1_200)
|
||||
expect(last.results[0]!.output).toBe(big)
|
||||
})
|
||||
|
||||
it('compaction: false disables both folding and truncation', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onDelta('answer')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const loop = new AgentLoop({ transport, skill: makeSkill(), compaction: false })
|
||||
const bigText = 'x'.repeat(200_000)
|
||||
loop.restore([
|
||||
{ role: 'user', text: bigText },
|
||||
{ role: 'assistant', text: 'ok' },
|
||||
])
|
||||
loop.run('continue')
|
||||
await flush()
|
||||
// Only the real model turn, no summary request; the original text was not folded
|
||||
expect(transport.requests).toHaveLength(1)
|
||||
expect((loop.messages[0] as { text: string }).text).toBe(bigText)
|
||||
})
|
||||
|
||||
it('tool executor exceptions become error results and the loop continues', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: {} })
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => {
|
||||
cb.onDelta('OK')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const skill = makeSkill(() => {
|
||||
throw new Error('boom')
|
||||
})
|
||||
const onDone = vi.fn()
|
||||
const loop = new AgentLoop({ transport, skill, events: { onDone } })
|
||||
loop.run('x')
|
||||
await flush()
|
||||
await flush()
|
||||
const toolMsg = loop.messages[2] as Extract<AgentMessage, { role: 'tool' }>
|
||||
expect(toolMsg.results[0].isError).toBe(true)
|
||||
expect(toolMsg.results[0].output).toBe('boom')
|
||||
expect(onDone).toHaveBeenCalledWith({ text: 'OK', cancelled: false, turnLimit: false })
|
||||
})
|
||||
|
||||
it('calls with inputError are not executed; an is_error result is fed back so the model can retry', async () => {
|
||||
const transport = scriptedTransport([
|
||||
(cb) => {
|
||||
cb.onToolCall({ id: 't1', name: 'do_thing', input: {}, inputError: 'bad json' })
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => {
|
||||
cb.onToolCall({ id: 't2', name: 'do_thing', input: { a: 1 } })
|
||||
cb.onDone()
|
||||
},
|
||||
(cb) => {
|
||||
cb.onDelta('done')
|
||||
cb.onDone()
|
||||
},
|
||||
])
|
||||
const executed: AgentToolCall[] = []
|
||||
const skill = makeSkill((call) => {
|
||||
executed.push(call)
|
||||
return { output: 'ok', summary: 'ok' }
|
||||
})
|
||||
const onDone = vi.fn()
|
||||
const loop = new AgentLoop({ transport, skill, events: { onDone } })
|
||||
loop.run('x')
|
||||
await flush()
|
||||
await flush()
|
||||
await flush()
|
||||
expect(executed.map((c) => c.id)).toEqual(['t2'])
|
||||
const toolMsg = loop.messages[2] as Extract<AgentMessage, { role: 'tool' }>
|
||||
expect(toolMsg.results[0].isError).toBe(true)
|
||||
expect(toolMsg.results[0].output).toContain('bad json')
|
||||
expect(onDone).toHaveBeenCalledWith({ text: 'done', cancelled: false, turnLimit: false })
|
||||
})
|
||||
|
||||
it('terminates the run after consecutive input-parse failures hit the limit', async () => {
|
||||
const badTurn = (cb: AgentStreamCallbacks) => {
|
||||
cb.onToolCall({ id: 't', name: 'do_thing', input: {}, inputError: 'bad json' })
|
||||
cb.onDone()
|
||||
}
|
||||
const transport = scriptedTransport([badTurn, badTurn, badTurn, badTurn])
|
||||
const executed: AgentToolCall[] = []
|
||||
const skill = makeSkill((call) => {
|
||||
executed.push(call)
|
||||
return { output: 'ok', summary: 'ok' }
|
||||
})
|
||||
const onError = vi.fn()
|
||||
const onDone = vi.fn()
|
||||
const loop = new AgentLoop({ transport, skill, events: { onError, onDone } })
|
||||
loop.run('x')
|
||||
for (let i = 0; i < 6; i++) await flush()
|
||||
expect(executed).toHaveLength(0)
|
||||
expect(transport.requests).toHaveLength(3)
|
||||
expect(onError).toHaveBeenCalledWith(expect.stringContaining('retries stopped'))
|
||||
expect(onDone).not.toHaveBeenCalled()
|
||||
expect(loop.busy).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('composeSkills', () => {
|
||||
it('merges prompts, tools and context, and routes execution', async () => {
|
||||
const a: AgentSkill = {
|
||||
id: 'a',
|
||||
systemPrompt: 'PA',
|
||||
tools: [{ name: 'tool_a', description: '', inputSchema: {} }],
|
||||
buildContext: () => 'CA',
|
||||
executeTool: () => ({ output: 'from-a', summary: 'a' }),
|
||||
}
|
||||
const b: AgentSkill = {
|
||||
id: 'b',
|
||||
systemPrompt: 'PB',
|
||||
tools: [{ name: 'tool_b', description: '', inputSchema: {} }],
|
||||
executeTool: () => ({ output: 'from-b', summary: 'b' }),
|
||||
}
|
||||
const merged = composeSkills('ab', 'INTRO', [a, b])
|
||||
expect(merged.systemPrompt).toBe('INTRO\n\nPA\n\nPB')
|
||||
expect(merged.tools.map((t) => t.name)).toEqual(['tool_a', 'tool_b'])
|
||||
expect(merged.buildContext?.()).toBe('CA')
|
||||
expect((await merged.executeTool({ id: '1', name: 'tool_b', input: {} })).output).toBe('from-b')
|
||||
const unknown = await merged.executeTool({ id: '2', name: 'nope', input: {} })
|
||||
expect(unknown.isError).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects duplicate tool names', () => {
|
||||
const tool = { name: 'same', description: '', inputSchema: {} }
|
||||
const make = (id: string): AgentSkill => ({
|
||||
id,
|
||||
systemPrompt: '',
|
||||
tools: [tool],
|
||||
executeTool: () => ({ output: '', summary: '' }),
|
||||
})
|
||||
expect(() => composeSkills('x', '', [make('a'), make('b')])).toThrow(/duplicate/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["src", "tests", "vitest.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@genoffice/ai-provider",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Multi-provider LLM streaming + one-shot chat client (Claude/Gemini/DeepSeek/OpenAI/custom), shared by AI Docs and future apps (Excel / PPT)",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@genoffice/agent-core": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { httpBodyDetail } from './http-error'
|
||||
import { GENSPARK_LLM_BASE_URLS } from './providers'
|
||||
import type { AiChatResponse, AiProviderConfig, AiProviderId } from './types'
|
||||
|
||||
async function chatAnthropic(
|
||||
config: AiProviderConfig,
|
||||
system: string,
|
||||
user: string,
|
||||
baseUrl = 'https://api.anthropic.com',
|
||||
): Promise<AiChatResponse> {
|
||||
const response = await fetch(`${baseUrl.replace(/\/$/, '')}/v1/messages`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': config.apiKey,
|
||||
'anthropic-version': '2023-06-01',
|
||||
// Fetch in the Electron main process goes through Chromium's network stack; this header avoids 403.
|
||||
'anthropic-dangerous-direct-browser-access': 'true',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model,
|
||||
max_tokens: 8192,
|
||||
system,
|
||||
messages: [{ role: 'user', content: user }],
|
||||
}),
|
||||
})
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: `Claude HTTP ${response.status}: ${httpBodyDetail(await response.text())}` }
|
||||
}
|
||||
const json = (await response.json()) as { content?: Array<{ type: string; text?: string }> }
|
||||
const content = json.content
|
||||
?.filter((c) => c.type === 'text')
|
||||
.map((c) => c.text ?? '')
|
||||
.join('')
|
||||
if (!content) return { ok: false, error: 'Claude returned an empty response' }
|
||||
return { ok: true, content }
|
||||
}
|
||||
|
||||
async function chatGemini(
|
||||
config: AiProviderConfig,
|
||||
system: string,
|
||||
user: string,
|
||||
baseUrl = 'https://generativelanguage.googleapis.com/v1beta',
|
||||
): Promise<AiChatResponse> {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/models/${config.model}:generateContent`
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'x-goog-api-key': config.apiKey },
|
||||
body: JSON.stringify({
|
||||
systemInstruction: { parts: [{ text: system }] },
|
||||
contents: [{ role: 'user', parts: [{ text: user }] }],
|
||||
generationConfig: { temperature: 0.3 },
|
||||
}),
|
||||
})
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: `Gemini HTTP ${response.status}: ${httpBodyDetail(await response.text())}` }
|
||||
}
|
||||
const json = (await response.json()) as {
|
||||
candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>
|
||||
}
|
||||
const content = json.candidates?.[0]?.content?.parts?.map((p) => p.text ?? '').join('')
|
||||
if (!content) return { ok: false, error: 'Gemini returned an empty response' }
|
||||
return { ok: true, content }
|
||||
}
|
||||
|
||||
async function chatOpenAiCompatible(
|
||||
baseUrl: string,
|
||||
config: AiProviderConfig,
|
||||
system: string,
|
||||
user: string,
|
||||
): Promise<AiChatResponse> {
|
||||
const response = await fetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model,
|
||||
messages: [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: user },
|
||||
],
|
||||
temperature: 0.3,
|
||||
}),
|
||||
})
|
||||
if (!response.ok) {
|
||||
return { ok: false, error: `HTTP ${response.status}: ${httpBodyDetail(await response.text())}` }
|
||||
}
|
||||
const json = (await response.json()) as { choices?: Array<{ message?: { content?: string } }> }
|
||||
const content = json.choices?.[0]?.message?.content
|
||||
if (!content) return { ok: false, error: 'AI returned an empty response' }
|
||||
return { ok: true, content }
|
||||
}
|
||||
|
||||
const OPENAI_COMPATIBLE_BASE_URLS: Partial<Record<AiProviderId, string>> = {
|
||||
deepseek: 'https://api.deepseek.com/v1',
|
||||
openai: 'https://api.openai.com/v1',
|
||||
}
|
||||
|
||||
/** route a one-shot (non-streaming, non-tool-calling) chat call by provider id */
|
||||
export async function chatForProvider(
|
||||
provider: AiProviderId,
|
||||
config: AiProviderConfig,
|
||||
system: string,
|
||||
user: string,
|
||||
): Promise<AiChatResponse> {
|
||||
switch (provider) {
|
||||
case 'genspark':
|
||||
if (config.model.startsWith('claude')) {
|
||||
return chatAnthropic(config, system, user, GENSPARK_LLM_BASE_URLS.anthropic)
|
||||
}
|
||||
if (config.model.startsWith('gemini')) {
|
||||
return chatGemini(config, system, user, GENSPARK_LLM_BASE_URLS.gemini)
|
||||
}
|
||||
return chatOpenAiCompatible(GENSPARK_LLM_BASE_URLS.openai, config, system, user)
|
||||
case 'anthropic':
|
||||
return chatAnthropic(config, system, user)
|
||||
case 'gemini':
|
||||
return chatGemini(config, system, user)
|
||||
case 'deepseek':
|
||||
case 'openai':
|
||||
return chatOpenAiCompatible(OPENAI_COMPATIBLE_BASE_URLS[provider]!, config, system, user)
|
||||
case 'custom':
|
||||
if (!config.baseUrl) return { ok: false, error: 'A custom provider requires a Base URL' }
|
||||
return chatOpenAiCompatible(config.baseUrl, config, system, user)
|
||||
default:
|
||||
return { ok: false, error: `Unknown provider: ${provider}` }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Detail text for a non-OK HTTP response body. Real API errors (JSON/plain
|
||||
* text) are surfaced as-is, truncated. HTML bodies — an edge/WAF block page or
|
||||
* a login page served instead of an API response (e.g. Genspark's SPA shell on
|
||||
* a 403) — are replaced with a short readable note, since dumping raw markup
|
||||
* into the chat UI is useless to the user.
|
||||
*/
|
||||
export function httpBodyDetail(body: string): string {
|
||||
const head = body.trimStart().slice(0, 30).toLowerCase()
|
||||
const isHtml = ['<!doctype', '<html', '<head', '<body'].some((tag) => head.startsWith(tag))
|
||||
if (isHtml) {
|
||||
return 'the service returned a web page instead of an API response (likely a temporary network or gateway block) — check your connection and retry'
|
||||
}
|
||||
return body.slice(0, 500)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export type {
|
||||
AiChatRequest,
|
||||
AiChatResponse,
|
||||
AiProviderConfig,
|
||||
AiProviderId,
|
||||
AiProviderMeta,
|
||||
AiSettings,
|
||||
AiStreamChunk,
|
||||
AiStreamRequest,
|
||||
GenSparkAccountStatus,
|
||||
LegacyAiSettings,
|
||||
} from './types'
|
||||
export { AI_PROVIDERS, GENSPARK_LLM_BASE_URLS, defaultAiSettings, resolveAiSettings } from './providers'
|
||||
export { chatForProvider } from './chat'
|
||||
export { sseLines, streamForProvider } from './stream'
|
||||
export type { StreamCallbacks } from './stream'
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { AiProviderId, AiProviderMeta, AiSettings, LegacyAiSettings } from './types'
|
||||
|
||||
/**
|
||||
* Genspark server-side LLM proxy endpoints. All three protocols share the
|
||||
* api_key from the gsk login; model ids follow the proxy's own naming scheme,
|
||||
* which differs from the official vendor ids.
|
||||
*/
|
||||
export const GENSPARK_LLM_BASE_URLS = {
|
||||
anthropic: 'https://www.genspark.ai/api/anthropic',
|
||||
gemini: 'https://www.genspark.ai/api/llm_proxy/gemini/v1beta',
|
||||
openai: 'https://www.genspark.ai/api/llm_proxy/v1',
|
||||
} as const
|
||||
|
||||
export const AI_PROVIDERS: AiProviderMeta[] = [
|
||||
{
|
||||
id: 'genspark',
|
||||
label: 'Genspark',
|
||||
models: [
|
||||
'claude-opus-4-7',
|
||||
'claude-opus-4-8',
|
||||
'claude-sonnet-4-6',
|
||||
'claude-haiku-4-5',
|
||||
'gpt-5.2',
|
||||
'gemini-3.1-pro-preview',
|
||||
'gemini-3-flash-preview',
|
||||
],
|
||||
defaultModel: 'claude-opus-4-7',
|
||||
keyPlaceholder: 'Not required - sign in to Genspark',
|
||||
},
|
||||
{
|
||||
id: 'anthropic',
|
||||
label: 'Claude',
|
||||
models: [
|
||||
'claude-sonnet-5',
|
||||
'claude-opus-4-8',
|
||||
'claude-opus-4-7',
|
||||
'claude-sonnet-4-6',
|
||||
'claude-opus-4-6',
|
||||
'claude-opus-4-5-20251101',
|
||||
'claude-haiku-4-5-20251001',
|
||||
'claude-sonnet-4-5-20250929',
|
||||
],
|
||||
defaultModel: 'claude-opus-4-7',
|
||||
keyPlaceholder: 'sk-ant-api03-...',
|
||||
},
|
||||
{
|
||||
id: 'gemini',
|
||||
label: 'Gemini',
|
||||
models: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.0-flash'],
|
||||
defaultModel: 'gemini-2.5-flash',
|
||||
keyPlaceholder: 'AIza...',
|
||||
},
|
||||
{
|
||||
id: 'deepseek',
|
||||
label: 'DeepSeek',
|
||||
models: ['deepseek-chat', 'deepseek-reasoner'],
|
||||
defaultModel: 'deepseek-chat',
|
||||
keyPlaceholder: 'sk-...',
|
||||
},
|
||||
{
|
||||
id: 'openai',
|
||||
label: 'OpenAI',
|
||||
models: ['gpt-4.1', 'gpt-4.1-mini', 'gpt-4o', 'gpt-4o-mini'],
|
||||
defaultModel: 'gpt-4.1-mini',
|
||||
keyPlaceholder: 'sk-...',
|
||||
},
|
||||
{
|
||||
id: 'custom',
|
||||
label: 'Custom',
|
||||
models: [],
|
||||
defaultModel: '',
|
||||
keyPlaceholder: 'API Key',
|
||||
needsBaseUrl: true,
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* Fresh settings with every provider's default model and an empty key,
|
||||
* except providers listed in `defaultApiKeys` (e.g. an app-specific
|
||||
* preconfigured Anthropic key). Callers own that policy; this package
|
||||
* has no hardcoded keys.
|
||||
*/
|
||||
export function defaultAiSettings(
|
||||
defaultApiKeys?: Partial<Record<AiProviderId, string>>,
|
||||
): AiSettings {
|
||||
const providers = {} as AiSettings['providers']
|
||||
for (const meta of AI_PROVIDERS) {
|
||||
providers[meta.id] = {
|
||||
apiKey: defaultApiKeys?.[meta.id] ?? '',
|
||||
model: meta.defaultModel,
|
||||
baseUrl: meta.needsBaseUrl ? '' : undefined,
|
||||
}
|
||||
}
|
||||
return { provider: 'genspark', providers }
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge on-disk settings over freshly computed defaults, migrating the
|
||||
* pre-provider shape (a single OpenAI-compatible endpoint) into the
|
||||
* "custom" provider slot. `stored` is whatever the caller read from its
|
||||
* settings file (already JSON-parsed); this function does no file I/O.
|
||||
*/
|
||||
export function resolveAiSettings(
|
||||
stored: Partial<AiSettings> & LegacyAiSettings,
|
||||
defaults: AiSettings,
|
||||
): AiSettings {
|
||||
if (!stored.providers) {
|
||||
if (stored.apiKey) {
|
||||
defaults.providers.custom = {
|
||||
apiKey: stored.apiKey,
|
||||
model: stored.model ?? '',
|
||||
baseUrl: stored.baseUrl ?? 'https://api.openai.com/v1',
|
||||
}
|
||||
}
|
||||
return defaults
|
||||
}
|
||||
return {
|
||||
provider: stored.provider ?? defaults.provider,
|
||||
providers: { ...defaults.providers, ...stored.providers },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
import type { AgentMessage, AgentToolCall, AgentToolDef } from '@genoffice/agent-core'
|
||||
import { httpBodyDetail } from './http-error'
|
||||
import { GENSPARK_LLM_BASE_URLS } from './providers'
|
||||
import type { AiProviderConfig, AiProviderId } from './types'
|
||||
|
||||
// ---- streaming (SSE line splitting shared by all providers) ----
|
||||
|
||||
export async function* sseLines(
|
||||
body: NodeJS.ReadableStream | ReadableStream<Uint8Array>,
|
||||
): AsyncGenerator<string> {
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
const stream = body as ReadableStream<Uint8Array>
|
||||
const reader = stream.getReader()
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() ?? ''
|
||||
for (const line of lines) yield line
|
||||
}
|
||||
if (buffer) yield buffer
|
||||
}
|
||||
|
||||
export interface StreamCallbacks {
|
||||
onDelta: (text: string) => void
|
||||
onToolCall: (call: AgentToolCall) => void
|
||||
signal: AbortSignal
|
||||
}
|
||||
|
||||
/**
|
||||
* Models occasionally emit unescaped " inside string values (e.g. English quotes in Chinese copy).
|
||||
* Single-pass scan: a " inside a string whose next non-whitespace char is not structural gets escaped.
|
||||
*/
|
||||
function repairUnescapedQuotes(json: string): string {
|
||||
let out = ''
|
||||
let inStr = false
|
||||
for (let i = 0; i < json.length; i++) {
|
||||
const c = json[i]!
|
||||
if (!inStr) {
|
||||
if (c === '"') inStr = true
|
||||
out += c
|
||||
continue
|
||||
}
|
||||
if (c === '\\') {
|
||||
out += c + (json[++i] ?? '')
|
||||
continue
|
||||
}
|
||||
if (c === '"') {
|
||||
let j = i + 1
|
||||
while (j < json.length && ' \n\r\t'.includes(json[j]!)) j++
|
||||
const next = json[j]
|
||||
if (next === undefined || ',}]:'.includes(next)) {
|
||||
inStr = false
|
||||
out += c
|
||||
} else {
|
||||
out += '\\"'
|
||||
}
|
||||
continue
|
||||
}
|
||||
out += c
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Don't throw on parse failure (it would kill the whole stream); return error so the loop feeds it back for retry */
|
||||
function parseToolInput(json: string): { input: Record<string, unknown>; error?: string } {
|
||||
if (!json.trim()) return { input: {} }
|
||||
try {
|
||||
return { input: JSON.parse(json) as Record<string, unknown> }
|
||||
} catch (e) {
|
||||
try {
|
||||
return { input: JSON.parse(repairUnescapedQuotes(json)) as Record<string, unknown> }
|
||||
} catch {
|
||||
const msg = e instanceof Error ? e.message : String(e)
|
||||
return { input: {}, error: `${msg}; raw: ${json.slice(0, 500)}` }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Anthropic ----
|
||||
|
||||
function anthropicMessages(messages: AgentMessage[]): unknown[] {
|
||||
return messages.map((m) => {
|
||||
if (m.role === 'user') {
|
||||
// Keep plain-text content as a string; only upgrade to a content block array when images are present
|
||||
if (!m.images?.length) return { role: 'user', content: m.text }
|
||||
return {
|
||||
role: 'user',
|
||||
content: [
|
||||
...(m.text ? [{ type: 'text', text: m.text }] : []),
|
||||
...m.images.map((img) => ({
|
||||
type: 'image',
|
||||
source: { type: 'base64', media_type: img.mime, data: img.base64 },
|
||||
})),
|
||||
],
|
||||
}
|
||||
}
|
||||
if (m.role === 'assistant') {
|
||||
const content: unknown[] = []
|
||||
if (m.text) content.push({ type: 'text', text: m.text })
|
||||
for (const call of m.toolCalls ?? []) {
|
||||
content.push({ type: 'tool_use', id: call.id, name: call.name, input: call.input })
|
||||
}
|
||||
return { role: 'assistant', content }
|
||||
}
|
||||
// tool results travel back as a user message of tool_result blocks
|
||||
return {
|
||||
role: 'user',
|
||||
content: m.results.map((r) => ({
|
||||
type: 'tool_result',
|
||||
tool_use_id: r.id,
|
||||
content: r.output,
|
||||
...(r.isError ? { is_error: true } : {}),
|
||||
})),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function streamAnthropic(
|
||||
config: AiProviderConfig,
|
||||
system: string,
|
||||
messages: AgentMessage[],
|
||||
tools: AgentToolDef[],
|
||||
maxTokens: number,
|
||||
cb: StreamCallbacks,
|
||||
baseUrl = 'https://api.anthropic.com',
|
||||
): Promise<void> {
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(`${baseUrl.replace(/\/$/, '')}/v1/messages`, {
|
||||
method: 'POST',
|
||||
signal: cb.signal,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': config.apiKey,
|
||||
'anthropic-version': '2023-06-01',
|
||||
// Fetch in the Electron main process goes through Chromium's network stack, which adds
|
||||
// browser-semantics headers; Anthropic rejects those with 403 "Request not allowed". This
|
||||
// header is the official opt-in for direct access from browser/Electron environments.
|
||||
'anthropic-dangerous-direct-browser-access': 'true',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model,
|
||||
max_tokens: maxTokens,
|
||||
system,
|
||||
messages: anthropicMessages(messages),
|
||||
...(tools.length > 0
|
||||
? {
|
||||
tools: tools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
input_schema: t.inputSchema,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
stream: true,
|
||||
}),
|
||||
})
|
||||
} catch (e) {
|
||||
// When fetch fails in the Electron main process, the real reason lives in `cause`
|
||||
const err = e as { message?: unknown; cause?: { code?: unknown; message?: unknown } } | null
|
||||
const causeText = err?.cause
|
||||
? ` cause=${String(err.cause.code || err.cause.message || err.cause)}`
|
||||
: ''
|
||||
throw new Error(`Claude fetch failed: ${err?.message || String(e)}${causeText}`, { cause: e })
|
||||
}
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`Claude HTTP ${response.status}: ${httpBodyDetail(await response.text())}`)
|
||||
}
|
||||
// tool_use inputs stream as partial JSON per content block
|
||||
const pendingTools = new Map<number, { id: string; name: string; json: string }>()
|
||||
for await (const line of sseLines(response.body)) {
|
||||
if (!line.startsWith('data:')) continue
|
||||
const payload = line.slice(5).trim()
|
||||
if (!payload) continue
|
||||
const event = JSON.parse(payload) as {
|
||||
type: string
|
||||
index?: number
|
||||
content_block?: { type?: string; id?: string; name?: string }
|
||||
delta?: { type?: string; text?: string; partial_json?: string }
|
||||
error?: { message?: string }
|
||||
}
|
||||
if (event.type === 'content_block_start' && event.content_block?.type === 'tool_use') {
|
||||
pendingTools.set(event.index ?? 0, {
|
||||
id: event.content_block.id ?? crypto.randomUUID(),
|
||||
name: event.content_block.name ?? '',
|
||||
json: '',
|
||||
})
|
||||
} else if (event.type === 'content_block_delta') {
|
||||
if (event.delta?.type === 'text_delta' && event.delta.text) cb.onDelta(event.delta.text)
|
||||
else if (event.delta?.type === 'input_json_delta') {
|
||||
const pending = pendingTools.get(event.index ?? 0)
|
||||
if (pending) pending.json += event.delta.partial_json ?? ''
|
||||
}
|
||||
} else if (event.type === 'content_block_stop') {
|
||||
const pending = pendingTools.get(event.index ?? 0)
|
||||
if (pending) {
|
||||
pendingTools.delete(event.index ?? 0)
|
||||
const { input, error } = parseToolInput(pending.json)
|
||||
cb.onToolCall({ id: pending.id, name: pending.name, input, inputError: error })
|
||||
}
|
||||
} else if (event.type === 'error') {
|
||||
throw new Error(event.error?.message ?? 'Claude stream error')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Gemini ----
|
||||
|
||||
function geminiContents(messages: AgentMessage[]): unknown[] {
|
||||
return messages.map((m) => {
|
||||
if (m.role === 'user') {
|
||||
if (!m.images?.length) return { role: 'user', parts: [{ text: m.text }] }
|
||||
return {
|
||||
role: 'user',
|
||||
parts: [
|
||||
...(m.text ? [{ text: m.text }] : []),
|
||||
...m.images.map((img) => ({ inline_data: { mime_type: img.mime, data: img.base64 } })),
|
||||
],
|
||||
}
|
||||
}
|
||||
if (m.role === 'assistant') {
|
||||
const parts: unknown[] = []
|
||||
if (m.text) parts.push({ text: m.text })
|
||||
for (const call of m.toolCalls ?? []) {
|
||||
parts.push({ functionCall: { name: call.name, args: call.input } })
|
||||
}
|
||||
return { role: 'model', parts }
|
||||
}
|
||||
return {
|
||||
role: 'user',
|
||||
parts: m.results.map((r) => ({
|
||||
functionResponse: {
|
||||
name: r.name,
|
||||
response: r.isError ? { error: r.output } : { result: r.output },
|
||||
},
|
||||
})),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function streamGemini(
|
||||
config: AiProviderConfig,
|
||||
system: string,
|
||||
messages: AgentMessage[],
|
||||
tools: AgentToolDef[],
|
||||
maxTokens: number,
|
||||
cb: StreamCallbacks,
|
||||
baseUrl = 'https://generativelanguage.googleapis.com/v1beta',
|
||||
): Promise<void> {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/models/${config.model}:streamGenerateContent?alt=sse`
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
signal: cb.signal,
|
||||
headers: { 'Content-Type': 'application/json', 'x-goog-api-key': config.apiKey },
|
||||
body: JSON.stringify({
|
||||
systemInstruction: { parts: [{ text: system }] },
|
||||
contents: geminiContents(messages),
|
||||
...(tools.length > 0
|
||||
? {
|
||||
tools: [
|
||||
{
|
||||
functionDeclarations: tools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
parameters: t.inputSchema,
|
||||
})),
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
generationConfig: { temperature: 0.3, maxOutputTokens: maxTokens },
|
||||
}),
|
||||
})
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`Gemini HTTP ${response.status}: ${httpBodyDetail(await response.text())}`)
|
||||
}
|
||||
for await (const line of sseLines(response.body)) {
|
||||
if (!line.startsWith('data:')) continue
|
||||
const payload = line.slice(5).trim()
|
||||
if (!payload) continue
|
||||
const event = JSON.parse(payload) as {
|
||||
candidates?: Array<{
|
||||
content?: {
|
||||
parts?: Array<{
|
||||
text?: string
|
||||
functionCall?: { name?: string; args?: Record<string, unknown> }
|
||||
}>
|
||||
}
|
||||
}>
|
||||
}
|
||||
for (const part of event.candidates?.[0]?.content?.parts ?? []) {
|
||||
if (part.text) cb.onDelta(part.text)
|
||||
// Gemini emits function calls whole, never as partial JSON
|
||||
if (part.functionCall?.name) {
|
||||
cb.onToolCall({
|
||||
id: crypto.randomUUID(),
|
||||
name: part.functionCall.name,
|
||||
input: part.functionCall.args ?? {},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- OpenAI-compatible (openai / deepseek / custom) ----
|
||||
|
||||
function openAiMessages(system: string, messages: AgentMessage[]): unknown[] {
|
||||
const out: unknown[] = [{ role: 'system', content: system }]
|
||||
for (const m of messages) {
|
||||
if (m.role === 'user') {
|
||||
if (!m.images?.length) {
|
||||
out.push({ role: 'user', content: m.text })
|
||||
} else {
|
||||
out.push({
|
||||
role: 'user',
|
||||
content: [
|
||||
...(m.text ? [{ type: 'text', text: m.text }] : []),
|
||||
...m.images.map((img) => ({
|
||||
type: 'image_url',
|
||||
image_url: { url: `data:${img.mime};base64,${img.base64}` },
|
||||
})),
|
||||
],
|
||||
})
|
||||
}
|
||||
} else if (m.role === 'assistant') {
|
||||
out.push({
|
||||
role: 'assistant',
|
||||
content: m.text || null,
|
||||
...(m.toolCalls && m.toolCalls.length > 0
|
||||
? {
|
||||
tool_calls: m.toolCalls.map((call) => ({
|
||||
id: call.id,
|
||||
type: 'function',
|
||||
function: { name: call.name, arguments: JSON.stringify(call.input) },
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
} else {
|
||||
for (const r of m.results) {
|
||||
out.push({ role: 'tool', tool_call_id: r.id, content: r.output })
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export async function streamOpenAiCompatible(
|
||||
baseUrl: string,
|
||||
config: AiProviderConfig,
|
||||
system: string,
|
||||
messages: AgentMessage[],
|
||||
tools: AgentToolDef[],
|
||||
maxTokens: number,
|
||||
cb: StreamCallbacks,
|
||||
): Promise<void> {
|
||||
const response = await fetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
|
||||
method: 'POST',
|
||||
signal: cb.signal,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model,
|
||||
max_tokens: maxTokens,
|
||||
messages: openAiMessages(system, messages),
|
||||
...(tools.length > 0
|
||||
? {
|
||||
tools: tools.map((t) => ({
|
||||
type: 'function',
|
||||
function: { name: t.name, description: t.description, parameters: t.inputSchema },
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
temperature: 0.3,
|
||||
stream: true,
|
||||
}),
|
||||
})
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`HTTP ${response.status}: ${httpBodyDetail(await response.text())}`)
|
||||
}
|
||||
// tool call arguments stream in fragments keyed by index
|
||||
const pendingTools = new Map<number, { id: string; name: string; json: string }>()
|
||||
const flushTools = () => {
|
||||
for (const pending of pendingTools.values()) {
|
||||
if (pending.name) {
|
||||
const { input, error } = parseToolInput(pending.json)
|
||||
cb.onToolCall({ id: pending.id, name: pending.name, input, inputError: error })
|
||||
}
|
||||
}
|
||||
pendingTools.clear()
|
||||
}
|
||||
for await (const line of sseLines(response.body)) {
|
||||
if (!line.startsWith('data:')) continue
|
||||
const payload = line.slice(5).trim()
|
||||
if (!payload) continue
|
||||
if (payload === '[DONE]') break
|
||||
const event = JSON.parse(payload) as {
|
||||
choices?: Array<{
|
||||
delta?: {
|
||||
content?: string
|
||||
tool_calls?: Array<{
|
||||
index: number
|
||||
id?: string
|
||||
function?: { name?: string; arguments?: string }
|
||||
}>
|
||||
}
|
||||
finish_reason?: string | null
|
||||
}>
|
||||
}
|
||||
const choice = event.choices?.[0]
|
||||
if (!choice) continue
|
||||
if (choice.delta?.content) cb.onDelta(choice.delta.content)
|
||||
for (const tc of choice.delta?.tool_calls ?? []) {
|
||||
const pending = pendingTools.get(tc.index) ?? {
|
||||
id: tc.id ?? crypto.randomUUID(),
|
||||
name: '',
|
||||
json: '',
|
||||
}
|
||||
if (tc.id) pending.id = tc.id
|
||||
if (tc.function?.name) pending.name += tc.function.name
|
||||
if (tc.function?.arguments) pending.json += tc.function.arguments
|
||||
pendingTools.set(tc.index, pending)
|
||||
}
|
||||
if (choice.finish_reason) flushTools()
|
||||
}
|
||||
flushTools()
|
||||
}
|
||||
|
||||
const OPENAI_COMPATIBLE_BASE_URLS: Partial<Record<AiProviderId, string>> = {
|
||||
deepseek: 'https://api.deepseek.com/v1',
|
||||
openai: 'https://api.openai.com/v1',
|
||||
}
|
||||
|
||||
/** route a streaming, tool-calling-capable turn by provider id */
|
||||
export async function streamForProvider(
|
||||
provider: AiProviderId,
|
||||
config: AiProviderConfig,
|
||||
system: string,
|
||||
messages: AgentMessage[],
|
||||
tools: AgentToolDef[],
|
||||
maxTokens: number,
|
||||
cb: StreamCallbacks,
|
||||
): Promise<void> {
|
||||
switch (provider) {
|
||||
case 'genspark':
|
||||
// The proxy exposes three protocol-specific endpoints; route by model id prefix: claude uses
|
||||
// the Anthropic protocol (preserves image input fidelity), gemini uses Gemini, rest OpenAI-compatible
|
||||
if (config.model.startsWith('claude')) {
|
||||
return streamAnthropic(
|
||||
config,
|
||||
system,
|
||||
messages,
|
||||
tools,
|
||||
maxTokens,
|
||||
cb,
|
||||
GENSPARK_LLM_BASE_URLS.anthropic,
|
||||
)
|
||||
}
|
||||
if (config.model.startsWith('gemini')) {
|
||||
return streamGemini(
|
||||
config,
|
||||
system,
|
||||
messages,
|
||||
tools,
|
||||
maxTokens,
|
||||
cb,
|
||||
GENSPARK_LLM_BASE_URLS.gemini,
|
||||
)
|
||||
}
|
||||
return streamOpenAiCompatible(
|
||||
GENSPARK_LLM_BASE_URLS.openai,
|
||||
config,
|
||||
system,
|
||||
messages,
|
||||
tools,
|
||||
maxTokens,
|
||||
cb,
|
||||
)
|
||||
case 'anthropic':
|
||||
return streamAnthropic(config, system, messages, tools, maxTokens, cb)
|
||||
case 'gemini':
|
||||
return streamGemini(config, system, messages, tools, maxTokens, cb)
|
||||
case 'deepseek':
|
||||
case 'openai':
|
||||
return streamOpenAiCompatible(
|
||||
OPENAI_COMPATIBLE_BASE_URLS[provider]!,
|
||||
config,
|
||||
system,
|
||||
messages,
|
||||
tools,
|
||||
maxTokens,
|
||||
cb,
|
||||
)
|
||||
case 'custom':
|
||||
if (!config.baseUrl) throw new Error('A custom provider requires a Base URL')
|
||||
return streamOpenAiCompatible(config.baseUrl, config, system, messages, tools, maxTokens, cb)
|
||||
default:
|
||||
throw new Error(`Unknown provider: ${provider}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { AgentMessage, AgentToolCall, AgentToolDef } from '@genoffice/agent-core'
|
||||
|
||||
export type AiProviderId = 'genspark' | 'anthropic' | 'gemini' | 'deepseek' | 'openai' | 'custom'
|
||||
|
||||
/** Genspark account status (gsk login state; the sole auth source for AI features) */
|
||||
export interface GenSparkAccountStatus {
|
||||
loggedIn: boolean
|
||||
email?: string
|
||||
}
|
||||
|
||||
export interface AiProviderConfig {
|
||||
apiKey: string
|
||||
model: string
|
||||
/** only used by the custom (OpenAI-compatible) provider */
|
||||
baseUrl?: string | undefined
|
||||
}
|
||||
|
||||
export interface AiProviderMeta {
|
||||
id: AiProviderId
|
||||
label: string
|
||||
models: string[]
|
||||
defaultModel: string
|
||||
keyPlaceholder: string
|
||||
needsBaseUrl?: boolean
|
||||
}
|
||||
|
||||
export interface AiSettings {
|
||||
provider: AiProviderId
|
||||
providers: Record<AiProviderId, AiProviderConfig>
|
||||
}
|
||||
|
||||
/** pre-provider settings shape (single OpenAI-compatible endpoint); migrated into "custom" */
|
||||
export interface LegacyAiSettings {
|
||||
baseUrl?: string
|
||||
apiKey?: string
|
||||
model?: string
|
||||
}
|
||||
|
||||
export interface AiChatRequest {
|
||||
settings: AiSettings
|
||||
system: string
|
||||
user: string
|
||||
}
|
||||
|
||||
export interface AiChatResponse {
|
||||
ok: boolean
|
||||
content?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface AiStreamRequest {
|
||||
requestId: string
|
||||
settings: AiSettings
|
||||
system: string
|
||||
messages: AgentMessage[]
|
||||
tools?: AgentToolDef[]
|
||||
maxTokens?: number
|
||||
}
|
||||
|
||||
export interface AiStreamChunk {
|
||||
requestId: string
|
||||
type: 'delta' | 'tool-call' | 'done' | 'error'
|
||||
text?: string
|
||||
/** complete parsed tool call (emitted once its arguments finish streaming) */
|
||||
toolCall?: AgentToolCall
|
||||
error?: string
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { chatForProvider } from '../src/chat'
|
||||
import { errorResponse, jsonResponse } from './test-utils'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('chatForProvider', () => {
|
||||
it('anthropic: extracts joined text content blocks', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(jsonResponse({ content: [{ type: 'text', text: 'hello ' }, { type: 'text', text: 'world' }] })),
|
||||
)
|
||||
const result = await chatForProvider('anthropic', { apiKey: 'k', model: 'claude-sonnet-5' }, 'sys', 'hi')
|
||||
expect(result).toEqual({ ok: true, content: 'hello world' })
|
||||
})
|
||||
|
||||
it('anthropic: surfaces HTTP errors', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(errorResponse(401, 'bad key')))
|
||||
const result = await chatForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', 'hi')
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error).toMatch(/Claude HTTP 401/)
|
||||
})
|
||||
|
||||
it('anthropic: replaces an HTML error body with a readable note', async () => {
|
||||
const html = '<!doctype html>\n<html>\n<head><title>Genspark</title></head><body>app shell</body></html>'
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(errorResponse(403, html)))
|
||||
const result = await chatForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', 'hi')
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error).toMatch(/Claude HTTP 403/)
|
||||
expect(result.error).toMatch(/web page instead of an API response/)
|
||||
expect(result.error).not.toContain('<!doctype')
|
||||
})
|
||||
|
||||
it('gemini: extracts joined parts text', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(jsonResponse({ candidates: [{ content: { parts: [{ text: 'hi there' }] } }] })),
|
||||
)
|
||||
const result = await chatForProvider('gemini', { apiKey: 'k', model: 'gemini-2.5-flash' }, 'sys', 'hi')
|
||||
expect(result).toEqual({ ok: true, content: 'hi there' })
|
||||
})
|
||||
|
||||
it('deepseek and openai hit their fixed base URLs', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ choices: [{ message: { content: 'ok' } }] }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await chatForProvider('deepseek', { apiKey: 'k', model: 'deepseek-chat' }, 'sys', 'hi')
|
||||
expect(fetchMock).toHaveBeenCalledWith('https://api.deepseek.com/v1/chat/completions', expect.anything())
|
||||
})
|
||||
|
||||
it('custom: uses the configured base URL', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ choices: [{ message: { content: 'ok' } }] }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await chatForProvider(
|
||||
'custom',
|
||||
{ apiKey: 'k', model: 'm', baseUrl: 'https://my-endpoint.example.com/v1' },
|
||||
'sys',
|
||||
'hi',
|
||||
)
|
||||
expect(fetchMock).toHaveBeenCalledWith('https://my-endpoint.example.com/v1/chat/completions', expect.anything())
|
||||
})
|
||||
|
||||
it('custom: rejects without a base URL, without calling fetch', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const result = await chatForProvider('custom', { apiKey: 'k', model: 'm' }, 'sys', 'hi')
|
||||
expect(result).toEqual({ ok: false, error: 'A custom provider requires a Base URL' })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('genspark: routes by model prefix to the proxy endpoints', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ content: [{ type: 'text', text: 'ok' }] }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await chatForProvider('genspark', { apiKey: 'gsk-k', model: 'claude-opus-4-7' }, 'sys', 'hi')
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://www.genspark.ai/api/anthropic/v1/messages',
|
||||
expect.anything(),
|
||||
)
|
||||
fetchMock.mockResolvedValue(jsonResponse({ choices: [{ message: { content: 'ok' } }] }))
|
||||
await chatForProvider('genspark', { apiKey: 'gsk-k', model: 'gpt-5.2' }, 'sys', 'hi')
|
||||
expect(fetchMock).toHaveBeenLastCalledWith(
|
||||
'https://www.genspark.ai/api/llm_proxy/v1/chat/completions',
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
|
||||
it('treats an empty response body as an error', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ choices: [{ message: {} }] })))
|
||||
const result = await chatForProvider('openai', { apiKey: 'k', model: 'gpt-4.1-mini' }, 'sys', 'hi')
|
||||
expect(result).toEqual({ ok: false, error: 'AI returned an empty response' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentMessage } from '@genoffice/agent-core'
|
||||
import { streamForProvider } from '../src/stream'
|
||||
import { okResponse, sseStream } from './test-utils'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const config = { apiKey: 'test-key', model: 'test-model' }
|
||||
|
||||
function callbacks() {
|
||||
return {
|
||||
signal: new AbortController().signal,
|
||||
onDelta: () => {},
|
||||
onToolCall: () => {},
|
||||
}
|
||||
}
|
||||
|
||||
/** run one turn against a stubbed fetch and return the parsed request body */
|
||||
async function requestBodyFor(
|
||||
provider: 'anthropic' | 'gemini',
|
||||
messages: AgentMessage[],
|
||||
): Promise<any> {
|
||||
const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream([])))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await streamForProvider(provider, config, 'sys', messages, [], 1024, callbacks())
|
||||
return JSON.parse(fetchMock.mock.calls[0][1].body as string)
|
||||
}
|
||||
|
||||
const IMAGE = { base64: 'aGVsbG8=', mime: 'image/png' }
|
||||
|
||||
describe('anthropic user message with images', () => {
|
||||
it('sends a content array of text + image blocks', async () => {
|
||||
const body = await requestBodyFor('anthropic', [
|
||||
{ role: 'user', text: 'look at this image', images: [IMAGE] },
|
||||
])
|
||||
expect(body.messages[0]).toEqual({
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: 'look at this image' },
|
||||
{
|
||||
type: 'image',
|
||||
source: { type: 'base64', media_type: 'image/png', data: 'aGVsbG8=' },
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('omits the text block when text is empty', async () => {
|
||||
const body = await requestBodyFor('anthropic', [{ role: 'user', text: '', images: [IMAGE] }])
|
||||
expect(body.messages[0].content).toHaveLength(1)
|
||||
expect(body.messages[0].content[0].type).toBe('image')
|
||||
})
|
||||
|
||||
it('keeps plain string content when no images (existing behavior)', async () => {
|
||||
const body = await requestBodyFor('anthropic', [{ role: 'user', text: 'hi' }])
|
||||
expect(body.messages[0]).toEqual({ role: 'user', content: 'hi' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('gemini user message with images', () => {
|
||||
it('sends parts with text + inline_data', async () => {
|
||||
const body = await requestBodyFor('gemini', [
|
||||
{ role: 'user', text: 'look at this image', images: [IMAGE] },
|
||||
])
|
||||
expect(body.contents[0]).toEqual({
|
||||
role: 'user',
|
||||
parts: [
|
||||
{ text: 'look at this image' },
|
||||
{ inline_data: { mime_type: 'image/png', data: 'aGVsbG8=' } },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps single text part when no images (existing behavior)', async () => {
|
||||
const body = await requestBodyFor('gemini', [{ role: 'user', text: 'hi' }])
|
||||
expect(body.contents[0]).toEqual({ role: 'user', parts: [{ text: 'hi' }] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { AI_PROVIDERS, defaultAiSettings, resolveAiSettings } from '../src/providers'
|
||||
|
||||
describe('defaultAiSettings', () => {
|
||||
it('gives every provider its default model and an empty key by default', () => {
|
||||
const settings = defaultAiSettings()
|
||||
expect(settings.provider).toBe('genspark')
|
||||
for (const meta of AI_PROVIDERS) {
|
||||
expect(settings.providers[meta.id].apiKey).toBe('')
|
||||
expect(settings.providers[meta.id].model).toBe(meta.defaultModel)
|
||||
}
|
||||
expect(settings.providers.custom.baseUrl).toBe('')
|
||||
expect(settings.providers.anthropic.baseUrl).toBeUndefined()
|
||||
})
|
||||
|
||||
it('applies caller-supplied default keys only to the listed providers', () => {
|
||||
const settings = defaultAiSettings({ anthropic: 'sk-ant-preset' })
|
||||
expect(settings.providers.anthropic.apiKey).toBe('sk-ant-preset')
|
||||
expect(settings.providers.gemini.apiKey).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveAiSettings', () => {
|
||||
it('returns fresh defaults when nothing is stored', () => {
|
||||
const defaults = defaultAiSettings({ anthropic: 'sk-ant-preset' })
|
||||
expect(resolveAiSettings({}, defaults)).toEqual(defaults)
|
||||
})
|
||||
|
||||
it('migrates the pre-provider single-endpoint shape into the custom provider', () => {
|
||||
const defaults = defaultAiSettings()
|
||||
const resolved = resolveAiSettings(
|
||||
{ apiKey: 'legacy-key', model: 'legacy-model', baseUrl: 'https://legacy.example.com/v1' },
|
||||
defaults,
|
||||
)
|
||||
expect(resolved.providers.custom).toEqual({
|
||||
apiKey: 'legacy-key',
|
||||
model: 'legacy-model',
|
||||
baseUrl: 'https://legacy.example.com/v1',
|
||||
})
|
||||
// untouched providers keep their defaults
|
||||
expect(resolved.providers.anthropic).toEqual(defaults.providers.anthropic)
|
||||
})
|
||||
|
||||
it('defaults the legacy base URL to the OpenAI endpoint when omitted', () => {
|
||||
const resolved = resolveAiSettings({ apiKey: 'legacy-key' }, defaultAiSettings())
|
||||
expect(resolved.providers.custom.baseUrl).toBe('https://api.openai.com/v1')
|
||||
})
|
||||
|
||||
it('merges stored multi-provider settings over the defaults, provider by provider', () => {
|
||||
const defaults = defaultAiSettings({ anthropic: 'preset-key' })
|
||||
const resolved = resolveAiSettings(
|
||||
{
|
||||
provider: 'gemini',
|
||||
providers: {
|
||||
gemini: { apiKey: 'stored-gemini-key', model: 'gemini-2.5-pro' },
|
||||
} as never,
|
||||
},
|
||||
defaults,
|
||||
)
|
||||
expect(resolved.provider).toBe('gemini')
|
||||
expect(resolved.providers.gemini).toEqual({ apiKey: 'stored-gemini-key', model: 'gemini-2.5-pro' })
|
||||
// provider not mentioned in stored.providers keeps the computed default
|
||||
expect(resolved.providers.anthropic.apiKey).toBe('preset-key')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,283 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentToolCall } from '@genoffice/agent-core'
|
||||
import { sseLines, streamForProvider } from '../src/stream'
|
||||
import { okResponse, sseStream } from './test-utils'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
function collector() {
|
||||
const deltas: string[] = []
|
||||
const toolCalls: AgentToolCall[] = []
|
||||
return {
|
||||
deltas,
|
||||
toolCalls,
|
||||
cb: {
|
||||
signal: new AbortController().signal,
|
||||
onDelta: (text: string) => deltas.push(text),
|
||||
onToolCall: (call: AgentToolCall) => toolCalls.push(call),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('sseLines', () => {
|
||||
it('splits a stream into lines, including a trailing line with no newline', async () => {
|
||||
const encoder = new TextEncoder()
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(encoder.encode('data: a\ndata: b\n'))
|
||||
controller.enqueue(encoder.encode('data: c')) // no trailing newline
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
const lines: string[] = []
|
||||
for await (const line of sseLines(body)) lines.push(line)
|
||||
expect(lines).toEqual(['data: a', 'data: b', 'data: c'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('streamForProvider: anthropic', () => {
|
||||
it('emits text deltas and a completed tool call', async () => {
|
||||
const body = sseStream([
|
||||
'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello "}}',
|
||||
'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"t1","name":"do_thing"}}',
|
||||
'data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\\"a\\":"}}',
|
||||
'data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"1}"}}',
|
||||
'data: {"type":"content_block_stop","index":1}',
|
||||
'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"world"}}',
|
||||
])
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)))
|
||||
const { deltas, toolCalls, cb } = collector()
|
||||
await streamForProvider(
|
||||
'anthropic',
|
||||
{ apiKey: 'k', model: 'claude-sonnet-5' },
|
||||
'system',
|
||||
[{ role: 'user', text: 'hi' }],
|
||||
[],
|
||||
100,
|
||||
cb,
|
||||
)
|
||||
expect(deltas.join('')).toBe('hello world')
|
||||
expect(toolCalls).toEqual([{ id: 't1', name: 'do_thing', input: { a: 1 } }])
|
||||
})
|
||||
|
||||
it('repairs unescaped quotes inside tool input string values', async () => {
|
||||
const partial = JSON.stringify({
|
||||
type: 'content_block_delta',
|
||||
index: 1,
|
||||
delta: { type: 'input_json_delta', partial_json: '{"topic": "from "future" to "present""}' },
|
||||
})
|
||||
const body = sseStream([
|
||||
'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"t1","name":"gen"}}',
|
||||
`data: ${partial}`,
|
||||
'data: {"type":"content_block_stop","index":1}',
|
||||
])
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)))
|
||||
const { toolCalls, cb } = collector()
|
||||
await streamForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', [], [], 100, cb)
|
||||
expect(toolCalls).toEqual([
|
||||
{ id: 't1', name: 'gen', input: { topic: 'from "future" to "present"' } },
|
||||
])
|
||||
})
|
||||
|
||||
it('unparseable tool input becomes inputError instead of killing the stream', async () => {
|
||||
const partial = JSON.stringify({
|
||||
type: 'content_block_delta',
|
||||
index: 1,
|
||||
delta: { type: 'input_json_delta', partial_json: '{"a": 1,' }, // truncated JSON, unrepairable
|
||||
})
|
||||
const body = sseStream([
|
||||
'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"t1","name":"gen"}}',
|
||||
`data: ${partial}`,
|
||||
'data: {"type":"content_block_stop","index":1}',
|
||||
'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"after"}}',
|
||||
])
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)))
|
||||
const { deltas, toolCalls, cb } = collector()
|
||||
await streamForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', [], [], 100, cb)
|
||||
expect(toolCalls).toHaveLength(1)
|
||||
expect(toolCalls[0]!.input).toEqual({})
|
||||
expect(toolCalls[0]!.inputError).toContain('raw: {"a": 1,')
|
||||
expect(deltas.join('')).toBe('after') // the stream was not interrupted
|
||||
})
|
||||
|
||||
it('throws on a non-ok HTTP response', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('bad key', { status: 401 })))
|
||||
const { cb } = collector()
|
||||
await expect(
|
||||
streamForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', [], [], 100, cb),
|
||||
).rejects.toThrow(/Claude HTTP 401/)
|
||||
})
|
||||
|
||||
it('replaces an HTML error body (e.g. a gateway block page) with a readable note', async () => {
|
||||
const html = '<!doctype html>\n<html>\n<head><title>Genspark</title></head><body>app shell</body></html>'
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(html, { status: 403 })))
|
||||
const { cb } = collector()
|
||||
await expect(
|
||||
streamForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', [], [], 100, cb),
|
||||
).rejects.toThrow(/Claude HTTP 403: .*web page instead of an API response/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('streamForProvider: gemini', () => {
|
||||
it('emits text and a whole (non-partial) function call', async () => {
|
||||
const body = sseStream([
|
||||
'data: {"candidates":[{"content":{"parts":[{"text":"hi there"}]}}]}',
|
||||
'data: {"candidates":[{"content":{"parts":[{"functionCall":{"name":"set_cell","args":{"a1":"42"}}}]}}]}',
|
||||
])
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)))
|
||||
const { deltas, toolCalls, cb } = collector()
|
||||
await streamForProvider(
|
||||
'gemini',
|
||||
{ apiKey: 'k', model: 'gemini-2.5-flash' },
|
||||
'sys',
|
||||
[],
|
||||
[],
|
||||
100,
|
||||
cb,
|
||||
)
|
||||
expect(deltas.join('')).toBe('hi there')
|
||||
expect(toolCalls).toHaveLength(1)
|
||||
expect(toolCalls[0]).toMatchObject({ name: 'set_cell', input: { a1: '42' } })
|
||||
})
|
||||
})
|
||||
|
||||
describe('streamForProvider: openai-compatible', () => {
|
||||
it('reassembles fragmented tool call arguments and flushes on finish_reason', async () => {
|
||||
const body = sseStream([
|
||||
'data: {"choices":[{"delta":{"content":"partial "}}]}',
|
||||
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"replace"}}]}}]}',
|
||||
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"x\\":1}"}}]}}]}',
|
||||
'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}',
|
||||
'data: [DONE]',
|
||||
])
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)))
|
||||
const { deltas, toolCalls, cb } = collector()
|
||||
await streamForProvider(
|
||||
'openai',
|
||||
{ apiKey: 'k', model: 'gpt-4.1-mini' },
|
||||
'sys',
|
||||
[],
|
||||
[],
|
||||
100,
|
||||
cb,
|
||||
)
|
||||
expect(deltas.join('')).toBe('partial ')
|
||||
expect(toolCalls).toEqual([{ id: 'c1', name: 'replace', input: { x: 1 } }])
|
||||
})
|
||||
|
||||
it('routes deepseek and openai to their fixed base URLs', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream(['data: [DONE]'])))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const { cb } = collector()
|
||||
await streamForProvider(
|
||||
'deepseek',
|
||||
{ apiKey: 'k', model: 'deepseek-chat' },
|
||||
'sys',
|
||||
[],
|
||||
[],
|
||||
100,
|
||||
cb,
|
||||
)
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://api.deepseek.com/v1/chat/completions',
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the configured base URL for the custom provider', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream(['data: [DONE]'])))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const { cb } = collector()
|
||||
await streamForProvider(
|
||||
'custom',
|
||||
{ apiKey: 'k', model: 'm', baseUrl: 'https://my-endpoint.example.com/v1' },
|
||||
'sys',
|
||||
[],
|
||||
[],
|
||||
100,
|
||||
cb,
|
||||
)
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://my-endpoint.example.com/v1/chat/completions',
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects the custom provider without a base URL, without ever calling fetch', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const { cb } = collector()
|
||||
await expect(
|
||||
streamForProvider('custom', { apiKey: 'k', model: 'm' }, 'sys', [], [], 100, cb),
|
||||
).rejects.toThrow(/Base URL/)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('streamForProvider: genspark', () => {
|
||||
it('routes claude models to the Anthropic-compatible proxy endpoint', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream([])))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const { cb } = collector()
|
||||
await streamForProvider(
|
||||
'genspark',
|
||||
{ apiKey: 'gsk-k', model: 'claude-opus-4-7' },
|
||||
'sys',
|
||||
[],
|
||||
[],
|
||||
100,
|
||||
cb,
|
||||
)
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://www.genspark.ai/api/anthropic/v1/messages',
|
||||
expect.objectContaining({ headers: expect.objectContaining({ 'x-api-key': 'gsk-k' }) }),
|
||||
)
|
||||
})
|
||||
|
||||
it('routes gemini models to the Gemini proxy with header auth', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream([])))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const { cb } = collector()
|
||||
await streamForProvider(
|
||||
'genspark',
|
||||
{ apiKey: 'gsk-k', model: 'gemini-3-flash-preview' },
|
||||
'sys',
|
||||
[],
|
||||
[],
|
||||
100,
|
||||
cb,
|
||||
)
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://www.genspark.ai/api/llm_proxy/gemini/v1beta/models/gemini-3-flash-preview:streamGenerateContent?alt=sse',
|
||||
expect.objectContaining({ headers: expect.objectContaining({ 'x-goog-api-key': 'gsk-k' }) }),
|
||||
)
|
||||
})
|
||||
|
||||
it('routes other models to the OpenAI-compatible proxy', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream(['data: [DONE]'])))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const { cb } = collector()
|
||||
await streamForProvider(
|
||||
'genspark',
|
||||
{ apiKey: 'gsk-k', model: 'gpt-5.2' },
|
||||
'sys',
|
||||
[],
|
||||
[],
|
||||
100,
|
||||
cb,
|
||||
)
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://www.genspark.ai/api/llm_proxy/v1/chat/completions',
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects an unknown provider id', async () => {
|
||||
const { cb } = collector()
|
||||
await expect(
|
||||
streamForProvider('unknown' as never, { apiKey: 'k', model: 'm' }, 'sys', [], [], 100, cb),
|
||||
).rejects.toThrow(/Unknown provider/)
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
/** build a fake SSE response body from raw lines (each already includes "data: " if needed) */
|
||||
export function sseStream(lines: string[]): ReadableStream<Uint8Array> {
|
||||
const encoder = new TextEncoder()
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const line of lines) controller.enqueue(encoder.encode(`${line}\n`))
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function okResponse(body: ReadableStream<Uint8Array>): Response {
|
||||
return new Response(body, { status: 200 })
|
||||
}
|
||||
|
||||
export function jsonResponse(value: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(value), { status })
|
||||
}
|
||||
|
||||
export function errorResponse(status: number, text: string): Response {
|
||||
return new Response(text, { status })
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["src", "tests", "vitest.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@genoffice/ai-search",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Shared web/image search (Serper Google API + DuckDuckGo fallback) for docs/sheets/slides AI. No Electron deps; runs in main process (Node fetch).",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@genspark/cli": "^1.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
/**
|
||||
* Wrapper around gsk (Genspark CLI, @genspark/cli) — search / image generation /
|
||||
* media analysis / upload / transcription.
|
||||
*
|
||||
* Execution: the main process spawns the CLI's JS entry with
|
||||
* ELECTRON_RUN_AS_NODE=1 so Electron itself acts as Node (the variable is a
|
||||
* no-op in a plain Node environment), avoiding the Windows problem where
|
||||
* .cmd files cannot be passed to execFile.
|
||||
*
|
||||
* Auth: the api_key field in ~/.genspark-tool-cli/config.json written by
|
||||
* `gsk login`, or the GSK_API_KEY environment variable. When not logged in,
|
||||
* hasGskAuth() returns false and callers should fall back to other
|
||||
* implementations (e.g. Serper/DuckDuckGo search).
|
||||
*/
|
||||
|
||||
import { execFile } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { createRequire } from 'node:module'
|
||||
import {
|
||||
COPYRIGHT_HOSTS,
|
||||
asRecord,
|
||||
firstItem,
|
||||
safeHost,
|
||||
type ImageSearchResult,
|
||||
type WebSearchResult,
|
||||
} from './shared'
|
||||
|
||||
const SEARCH_TIMEOUT_MS = 60_000
|
||||
const GENERATE_TIMEOUT_MS = 600_000
|
||||
const MAX_BUFFER = 32 * 1024 * 1024
|
||||
|
||||
// ── CLI resolution & auth ───────────────────────────────────────────
|
||||
|
||||
let cachedEntry: string | null | undefined
|
||||
|
||||
/** JS entry of @genspark/cli (null if not found). Can be overridden via GSK_CLI_PATH. */
|
||||
export function resolveGskEntry(): string | null {
|
||||
if (process.env.GSK_CLI_PATH) return process.env.GSK_CLI_PATH
|
||||
if (cachedEntry !== undefined) return cachedEntry
|
||||
try {
|
||||
const require = createRequire(import.meta.url)
|
||||
cachedEntry = require.resolve('@genspark/cli/dist/index.js')
|
||||
} catch {
|
||||
// The packaged app has no node_modules; electron-builder extraResources
|
||||
// copies the CLI into Resources/gsk/
|
||||
const resourcesPath = (process as { resourcesPath?: string }).resourcesPath
|
||||
const packed = resourcesPath
|
||||
? join(resourcesPath, 'gsk', 'node_modules', '@genspark', 'cli', 'dist', 'index.js')
|
||||
: null
|
||||
cachedEntry = packed && existsSync(packed) ? packed : null
|
||||
}
|
||||
return cachedEntry
|
||||
}
|
||||
|
||||
let compatPath: string | null | undefined
|
||||
|
||||
/**
|
||||
* Under Electron-as-Node, Commander.js sees process.versions.electron and
|
||||
* parses argv with Electron conventions (skipping one argument fewer), so it
|
||||
* treats the entry path as a command and prints help. Workaround: --require a
|
||||
* script that deletes versions.electron. In a plain Node environment
|
||||
* (tests/tsx) no handling is needed and an empty array is returned.
|
||||
*/
|
||||
function electronCompatArgs(): string[] {
|
||||
if (!process.versions.electron) return []
|
||||
if (compatPath === undefined) {
|
||||
try {
|
||||
const dir = join(homedir(), '.genoffice', 'bin')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
compatPath = join(dir, 'electron-compat.js')
|
||||
writeFileSync(compatPath, 'delete process.versions.electron;\n')
|
||||
} catch {
|
||||
compatPath = null
|
||||
}
|
||||
}
|
||||
return compatPath ? ['--require', compatPath] : []
|
||||
}
|
||||
|
||||
/** API key written by gsk login (or GSK_API_KEY env var); '' when not logged in. Also used for Genspark LLM proxy auth. */
|
||||
export function gskApiKey(): string {
|
||||
if (process.env.GSK_API_KEY) return process.env.GSK_API_KEY
|
||||
try {
|
||||
const configPath = join(homedir(), '.genspark-tool-cli', 'config.json')
|
||||
if (!existsSync(configPath)) return ''
|
||||
const config = JSON.parse(readFileSync(configPath, 'utf-8')) as { api_key?: string }
|
||||
return config.api_key ?? ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether gsk is usable (CLI installed and logged in / has a key). Callers use this to decide fallback.
|
||||
* Set AI_SEARCH_DISABLE_GSK=1 to force-disable (test isolation / force Serper).
|
||||
*/
|
||||
export function hasGskAuth(): boolean {
|
||||
if (process.env.AI_SEARCH_DISABLE_GSK === '1') return false
|
||||
return !!gskApiKey() && resolveGskEntry() !== null
|
||||
}
|
||||
|
||||
// ── Low-level execution ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* gsk output may have [INFO] log lines mixed in before the JSON; scan from the
|
||||
* end for the first line starting with { or [ and parse from there.
|
||||
*/
|
||||
export function parseGskOutput(stdout: string): unknown {
|
||||
const trimmed = stdout.trim()
|
||||
try {
|
||||
return JSON.parse(trimmed)
|
||||
} catch {
|
||||
/* fall through to line-by-line scan */
|
||||
}
|
||||
const lines = trimmed.split('\n')
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
const line = lines[i]!.trim()
|
||||
if (line.startsWith('{') || line.startsWith('[')) {
|
||||
try {
|
||||
return JSON.parse(lines.slice(i).join('\n'))
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error(`No JSON found in gsk output: ${stdout.slice(0, 300)}`)
|
||||
}
|
||||
|
||||
function runGsk(args: string[], timeoutMs: number, signal?: AbortSignal): Promise<unknown> {
|
||||
const entry = resolveGskEntry()
|
||||
if (!entry) return Promise.reject(new Error('@genspark/cli is not installed'))
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
process.execPath,
|
||||
[...electronCompatArgs(), entry, ...args, '--output', 'json'],
|
||||
{
|
||||
timeout: timeoutMs,
|
||||
maxBuffer: MAX_BUFFER,
|
||||
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
|
||||
...(signal ? { signal } : {}),
|
||||
},
|
||||
(err, stdout, stderr) => {
|
||||
if (err) {
|
||||
// gsk's real failure reason (auth/network/quota) is in stderr; append it to ease debugging
|
||||
const errText = (stderr || '').toString().trim().slice(0, 500)
|
||||
reject(errText ? new Error(`${err.message} | stderr: ${errText}`) : err)
|
||||
return
|
||||
}
|
||||
try {
|
||||
const result = parseGskOutput(String(stdout))
|
||||
const rec = asRecord(result)
|
||||
if (rec.status && rec.status !== 'ok') {
|
||||
reject(new Error(`gsk returned an error: ${rec.message ?? rec.status}`))
|
||||
return
|
||||
}
|
||||
resolve(result)
|
||||
} catch (parseErr) {
|
||||
reject(parseErr)
|
||||
}
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// ── Search ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Parses the `gsk search` response shape data.organic_results[{title,link,snippet}] (exported for tests) */
|
||||
export function parseGskWebSearch(
|
||||
raw: unknown,
|
||||
maxResults: number,
|
||||
): { results: WebSearchResult[]; answer?: string } {
|
||||
const data = asRecord(asRecord(raw).data ?? raw)
|
||||
const organic: unknown[] = Array.isArray(data.organic_results) ? data.organic_results : []
|
||||
const results: WebSearchResult[] = organic.slice(0, maxResults).map((item) => {
|
||||
const o = asRecord(item)
|
||||
return {
|
||||
title: String(o.title ?? ''),
|
||||
url: String(o.link ?? ''),
|
||||
snippet: String(o.snippet ?? ''),
|
||||
}
|
||||
})
|
||||
const answer = typeof data.answer === 'string' && data.answer ? data.answer : undefined
|
||||
return answer !== undefined ? { results, answer } : { results }
|
||||
}
|
||||
|
||||
export async function gskWebSearch(
|
||||
query: string,
|
||||
maxResults = 6,
|
||||
): Promise<{ results: WebSearchResult[]; answer?: string }> {
|
||||
const raw = await runGsk(['search', query], SEARCH_TIMEOUT_MS)
|
||||
return parseGskWebSearch(raw, maxResults)
|
||||
}
|
||||
|
||||
/** Parses the `gsk img-search` response shape data[{image_url,title,source,link,width,height}] (exported for tests) */
|
||||
export function parseGskImageSearch(raw: unknown, maxResults: number): ImageSearchResult[] {
|
||||
const dataRaw = asRecord(raw).data
|
||||
const data: unknown[] = Array.isArray(dataRaw) ? dataRaw : []
|
||||
const images: ImageSearchResult[] = []
|
||||
for (const item of data) {
|
||||
const img = asRecord(item)
|
||||
const imageUrl = String(img.image_url ?? img.imageUrl ?? '')
|
||||
if (!imageUrl) continue
|
||||
if (COPYRIGHT_HOSTS.some((d) => imageUrl.toLowerCase().includes(d))) continue
|
||||
const width = Number(img.width)
|
||||
const height = Number(img.height)
|
||||
const entry: ImageSearchResult = {
|
||||
title: String(img.title ?? ''),
|
||||
imageUrl,
|
||||
sourceUrl: String(img.link ?? ''),
|
||||
source: String(img.source ?? safeHost(img.link)),
|
||||
}
|
||||
if (Number.isFinite(width) && width > 0) entry.width = width
|
||||
if (Number.isFinite(height) && height > 0) entry.height = height
|
||||
images.push(entry)
|
||||
if (images.length >= maxResults) break
|
||||
}
|
||||
return images
|
||||
}
|
||||
|
||||
export async function gskImageSearch(query: string, maxResults = 8): Promise<ImageSearchResult[]> {
|
||||
const raw = await runGsk(['img-search', query], SEARCH_TIMEOUT_MS)
|
||||
return parseGskImageSearch(raw, maxResults)
|
||||
}
|
||||
|
||||
// ── Image generation ────────────────────────────────────────────────
|
||||
|
||||
export interface GskGenerateImageOptions {
|
||||
/** Image description (English works better; text that must appear in the image stays verbatim) */
|
||||
prompt: string
|
||||
/** Generation model; defaults to the CLI default (nano-banana-2). Special-purpose: fal-bria-rmbg background removal, fal-ai/recraft-clarity-upscale upscaling, flux-pro/outpaint outpainting, fal-ai/image-editing/text-removal watermark text removal */
|
||||
model?: string
|
||||
/** Reference/edit-target image URLs (local paths also supported; the CLI uploads them automatically) */
|
||||
referenceImageUrls?: string[]
|
||||
/** 1:1 | 4:3 | 16:9 | 9:16 | 3:4 | 2:3 | 3:2 | auto */
|
||||
aspectRatio?: string
|
||||
/** auto | 0.5k | 1k | 2k | 3k | 4k */
|
||||
imageSize?: string
|
||||
}
|
||||
|
||||
export interface GskGeneratedImage {
|
||||
/** Watermark-free image URL (preferred); can be downloaded and inserted directly */
|
||||
url: string
|
||||
taskId: string
|
||||
}
|
||||
|
||||
/** Parses `gsk img` results: prefers data.generated_images[].image_urls_nowatermark (exported for tests) */
|
||||
export function parseGskGeneratedImage(raw: unknown): GskGeneratedImage {
|
||||
const data = asRecord(asRecord(raw).data ?? raw)
|
||||
const img = asRecord(firstItem(data.generated_images ?? data.images ?? []))
|
||||
const url = firstItem(img.image_urls_nowatermark) ?? firstItem(img.image_urls) ?? img.url ?? ''
|
||||
if (!url) {
|
||||
throw new Error(`gsk image generation returned no result: ${JSON.stringify(raw).slice(0, 200)}`)
|
||||
}
|
||||
return { url: String(url), taskId: String(img.task_id ?? '') }
|
||||
}
|
||||
|
||||
export async function gskGenerateImage(
|
||||
options: GskGenerateImageOptions,
|
||||
signal?: AbortSignal,
|
||||
): Promise<GskGeneratedImage> {
|
||||
const args = ['img', options.prompt]
|
||||
if (options.model) args.push('-m', options.model)
|
||||
if (options.referenceImageUrls?.length) args.push('--image_urls', ...options.referenceImageUrls)
|
||||
if (options.aspectRatio) args.push('--aspect_ratio', options.aspectRatio)
|
||||
if (options.imageSize) args.push('--image_size', options.imageSize)
|
||||
const raw = await runGsk(args, GENERATE_TIMEOUT_MS, signal)
|
||||
const result = parseGskGeneratedImage(raw)
|
||||
// Bare genspark file URLs (/api/files/) return 403; swap for a signed direct link with a token
|
||||
// so later plain fetch downloads (e.g. insert_web_image) need no auth
|
||||
result.url = await gskResolveDownloadUrl(result.url)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps a genspark file wrapper URL for an anonymously downloadable signed direct link (`gsk download`).
|
||||
* Non-genspark file URLs are returned as-is; on swap failure the URL is also returned as-is
|
||||
* (callers handle download failures themselves).
|
||||
*/
|
||||
export async function gskResolveDownloadUrl(url: string): Promise<string> {
|
||||
if (!url.includes('/api/files/')) return url
|
||||
try {
|
||||
const raw = asRecord(await runGsk(['download', url], SEARCH_TIMEOUT_MS))
|
||||
const downloadUrl = asRecord(raw.data).download_url ?? raw.download_url
|
||||
return downloadUrl ? String(downloadUrl) : url
|
||||
} catch {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cloud single-slide generation (Genspark slide_generate) ─────────
|
||||
|
||||
/**
|
||||
* Calls the tool_cli HTTP endpoint directly so structured params
|
||||
* (deck_context/images) are sent as JSON rather than through the CLI's
|
||||
* string-based argument passing.
|
||||
*/
|
||||
const GSK_TOOL_CLI_BASE = 'https://www.genspark.ai/api/tool_cli'
|
||||
const SLIDE_GENERATE_TIMEOUT_MS = 240_000
|
||||
|
||||
export interface GskSlideGenerateOptions {
|
||||
/** Content and layout brief for this page */
|
||||
brief: string
|
||||
title?: string
|
||||
/** Deck-level visual system / typography / palette rules (Style Skill text) */
|
||||
styleSkill?: string
|
||||
/** Deck topic, page index, total pages, neighboring-page context */
|
||||
deckContext?: Record<string, unknown>
|
||||
/** HTTPS image candidates for this page */
|
||||
images?: { url: string; caption?: string }[]
|
||||
width?: number
|
||||
height?: number
|
||||
/** Slides model tier: ultra = opus-class model, standard (server default) = lighter model */
|
||||
tier?: 'standard' | 'ultra'
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
/** Final NDJSON line = the result; heartbeat lines have no status field */
|
||||
export function parseToolCliNdjson(text: string): Record<string, unknown> {
|
||||
const lines = text.trim().split('\n')
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
const line = lines[i]!.trim()
|
||||
if (!line.startsWith('{')) continue
|
||||
try {
|
||||
const obj: unknown = JSON.parse(line)
|
||||
if (obj && typeof obj === 'object' && 'status' in obj) return obj as Record<string, unknown>
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
throw new Error(`No result line in tool_cli response: ${text.slice(0, 300)}`)
|
||||
}
|
||||
|
||||
async function toolCliPost(
|
||||
path: string,
|
||||
body: unknown,
|
||||
timeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> {
|
||||
const key = gskApiKey()
|
||||
if (!key) throw new Error('Not logged in to Genspark (gsk login)')
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
const onAbort = () => controller.abort()
|
||||
signal?.addEventListener('abort', onAbort, { once: true })
|
||||
try {
|
||||
const resp = await fetch(`${GSK_TOOL_CLI_BASE}${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'X-Api-Key': key, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
signal: controller.signal,
|
||||
})
|
||||
const text = await resp.text()
|
||||
if (!resp.ok) throw new Error(`tool_cli ${path} HTTP ${resp.status}: ${text.slice(0, 200)}`)
|
||||
const result = parseToolCliNdjson(text)
|
||||
if (result.status !== 'ok') {
|
||||
throw new Error(`tool_cli ${path} failed: ${result.message ?? result.status}`)
|
||||
}
|
||||
return result.data
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates one editable slide in the cloud (brief → HTML → one-slide PPTX)
|
||||
* and returns the downloaded PPTX bytes plus the model that produced it.
|
||||
*/
|
||||
export async function gskSlideGenerate(
|
||||
options: GskSlideGenerateOptions,
|
||||
): Promise<{ bytes: Uint8Array; model: string }> {
|
||||
const { signal } = options
|
||||
const body: Record<string, unknown> = { brief: options.brief }
|
||||
if (options.title) body.title = options.title
|
||||
if (options.styleSkill) body.style_skill = options.styleSkill
|
||||
if (options.deckContext) body.deck_context = options.deckContext
|
||||
if (options.images?.length) body.images = options.images
|
||||
if (options.width) body.width = options.width
|
||||
if (options.height) body.height = options.height
|
||||
if (options.tier) body.tier = options.tier
|
||||
const data = asRecord(
|
||||
await toolCliPost('/slide_generate', body, SLIDE_GENERATE_TIMEOUT_MS, signal),
|
||||
)
|
||||
const pptxUrl = data.pptx_url
|
||||
if (!pptxUrl)
|
||||
throw new Error(`slide_generate returned no pptx_url: ${JSON.stringify(data).slice(0, 200)}`)
|
||||
// The bare file-wrapper URL 403s on plain GET; swap for a signed direct link first
|
||||
const dl = asRecord(
|
||||
await toolCliPost('/file/download', { file_wrapper_url: pptxUrl }, SEARCH_TIMEOUT_MS, signal),
|
||||
)
|
||||
const downloadUrl = dl.download_url
|
||||
if (!downloadUrl) throw new Error('file/download returned no download_url')
|
||||
const resp = await fetch(String(downloadUrl), signal ? { signal } : undefined)
|
||||
if (!resp.ok) throw new Error(`PPTX download failed: HTTP ${resp.status}`)
|
||||
return { bytes: new Uint8Array(await resp.arrayBuffer()), model: String(data.model ?? '') }
|
||||
}
|
||||
|
||||
// ── Media analysis / transcription ──────────────────────────────────
|
||||
|
||||
/** Best-effort text extraction from gsk analysis-type command output (shape varies by task, so be lenient; exported for tests) */
|
||||
export function extractGskText(raw: unknown): string {
|
||||
const data = asRecord(raw).data ?? raw
|
||||
if (typeof data === 'string') return data
|
||||
if (data && typeof data === 'object') {
|
||||
for (const key of [
|
||||
'analysis',
|
||||
'analysis_result',
|
||||
'result',
|
||||
'content',
|
||||
'text',
|
||||
'answer',
|
||||
'transcript',
|
||||
]) {
|
||||
const v = (data as Record<string, unknown>)[key]
|
||||
if (typeof v === 'string' && v.trim()) return v
|
||||
}
|
||||
}
|
||||
return JSON.stringify(data ?? raw)
|
||||
}
|
||||
|
||||
export interface GskAnalyzeMediaOptions {
|
||||
/** Media URLs or local paths (image/audio/video; the CLI uploads local files automatically) */
|
||||
mediaUrls: string[]
|
||||
/** Analysis requirements (in English): what info to extract and what it's for */
|
||||
requirements: string
|
||||
}
|
||||
|
||||
export async function gskAnalyzeMedia(
|
||||
options: GskAnalyzeMediaOptions,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const args = [
|
||||
'media-analyze',
|
||||
'--media_urls',
|
||||
...options.mediaUrls,
|
||||
'--requirements',
|
||||
options.requirements,
|
||||
]
|
||||
const raw = await runGsk(args, GENERATE_TIMEOUT_MS, signal)
|
||||
return extractGskText(raw)
|
||||
}
|
||||
|
||||
export interface GskTranscribeOptions {
|
||||
/** Audio URLs or local paths */
|
||||
audioUrls: string[]
|
||||
/** Prompt (context / proper nouns; can improve recognition quality) */
|
||||
prompt?: string
|
||||
/** whisper-1 (default, with timestamps) | gemini-3-flash-preview | elevenlabs_scribe_v2 */
|
||||
model?: string
|
||||
}
|
||||
|
||||
export async function gskTranscribe(
|
||||
options: GskTranscribeOptions,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const args = ['transcribe', '--audio_urls', ...options.audioUrls]
|
||||
if (options.prompt) args.push('--prompt', options.prompt)
|
||||
if (options.model) args.push('-m', options.model)
|
||||
const raw = await runGsk(args, GENERATE_TIMEOUT_MS, signal)
|
||||
return extractGskText(raw)
|
||||
}
|
||||
|
||||
// ── File upload / login ─────────────────────────────────────────────
|
||||
|
||||
/** Uploads a local file and returns a file wrapper URL (usable as input to other gsk commands) */
|
||||
export async function gskUpload(filePath: string): Promise<string> {
|
||||
const raw = asRecord(await runGsk(['upload', filePath], GENERATE_TIMEOUT_MS))
|
||||
const dataRec = asRecord(raw.data)
|
||||
const url = dataRec.file_wrapper_url ?? raw.url ?? dataRec.url
|
||||
if (!url) throw new Error(`gsk upload did not return a URL: ${JSON.stringify(raw).slice(0, 200)}`)
|
||||
return String(url)
|
||||
}
|
||||
|
||||
export interface GskLoginInfo {
|
||||
email: string
|
||||
plan: string
|
||||
}
|
||||
|
||||
/** Current login info; null when not logged in */
|
||||
export async function gskLoginInfo(): Promise<GskLoginInfo | null> {
|
||||
try {
|
||||
const raw = await runGsk(['login-info'], SEARCH_TIMEOUT_MS)
|
||||
const d = asRecord(asRecord(raw).data ?? raw)
|
||||
if (!d.email) return null
|
||||
return { email: String(d.email), plan: String(d.plan ?? d.personal_plan ?? '') }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Triggers browser login (fire-and-forget; api_key is written to config.json on completion). Returns whether the CLI was launched. */
|
||||
export function gskLogin(): boolean {
|
||||
const entry = resolveGskEntry()
|
||||
if (!entry) return false
|
||||
execFile(
|
||||
process.execPath,
|
||||
[...electronCompatArgs(), entry, 'login'],
|
||||
{ timeout: 300_000, env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' } },
|
||||
() => {},
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Logs out (deletes the saved API key; note login state is shared globally with the terminal gsk CLI) */
|
||||
export function gskLogout(): Promise<void> {
|
||||
const entry = resolveGskEntry()
|
||||
if (!entry) return Promise.resolve()
|
||||
return new Promise((resolve) => {
|
||||
execFile(
|
||||
process.execPath,
|
||||
[...electronCompatArgs(), entry, 'logout'],
|
||||
{ timeout: 60_000, env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' } },
|
||||
() => resolve(),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* Search utilities (main process) — gsk (Genspark CLI) first, then Serper Google API,
|
||||
* with DuckDuckGo as the last resort. The Serper/DuckDuckGo logic mirrors an earlier
|
||||
* web_search / google_image_search implementation. Runs in the main process
|
||||
* (Node fetch / child process) to avoid renderer CORS; the Serper key reuses SERPER_API_KEY.
|
||||
* For gsk auth see ./gsk.ts (`gsk login` or GSK_API_KEY).
|
||||
*/
|
||||
|
||||
import {
|
||||
COPYRIGHT_HOSTS,
|
||||
asRecord,
|
||||
safeHost,
|
||||
type ImageSearchResult,
|
||||
type WebSearchResult,
|
||||
} from './shared'
|
||||
import { gskImageSearch, gskWebSearch, hasGskAuth } from './gsk'
|
||||
|
||||
export type { ImageSearchResult, WebSearchResult } from './shared'
|
||||
export * from './gsk'
|
||||
|
||||
const SERPER_KEY = () => process.env.SERPER_API_KEY ?? ''
|
||||
|
||||
// ── Web search ──────────────────────────────────────────────────────
|
||||
|
||||
export async function webSearch(query: string, maxResults = 6): Promise<{
|
||||
results: WebSearchResult[]
|
||||
answer?: string
|
||||
method: string
|
||||
}> {
|
||||
if (hasGskAuth()) {
|
||||
try {
|
||||
const r = await gskWebSearch(query, maxResults)
|
||||
if (r.results.length) return { ...r, method: 'gsk' }
|
||||
} catch {
|
||||
/* fall back to Serper/DuckDuckGo */
|
||||
}
|
||||
}
|
||||
const key = SERPER_KEY()
|
||||
if (key) {
|
||||
try {
|
||||
const resp = await fetchWithTimeout('https://google.serper.dev/search', {
|
||||
method: 'POST',
|
||||
headers: { 'X-API-KEY': key, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ q: query, num: maxResults, gl: 'us', hl: 'en' }),
|
||||
})
|
||||
if (resp.ok) {
|
||||
const data = asRecord(await resp.json())
|
||||
const organic: unknown[] = Array.isArray(data.organic) ? data.organic : []
|
||||
const results: WebSearchResult[] = organic.slice(0, maxResults).map((item) => {
|
||||
const o = asRecord(item)
|
||||
return {
|
||||
title: String(o.title ?? ''),
|
||||
url: String(o.link ?? ''),
|
||||
snippet: String(o.snippet ?? ''),
|
||||
}
|
||||
})
|
||||
const answerBox = asRecord(data.answerBox)
|
||||
const answerRaw =
|
||||
answerBox.answer || answerBox.snippet || asRecord(data.knowledgeGraph).description
|
||||
const answer = typeof answerRaw === 'string' && answerRaw ? answerRaw : undefined
|
||||
if (results.length) {
|
||||
return answer !== undefined
|
||||
? { results, answer, method: 'serper' }
|
||||
: { results, method: 'serper' }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* fall back to DuckDuckGo */
|
||||
}
|
||||
}
|
||||
return { ...(await duckWebSearch(query, maxResults)), method: 'duckduckgo' }
|
||||
}
|
||||
|
||||
// ── Image search ────────────────────────────────────────────────────
|
||||
|
||||
export async function imageSearch(query: string, maxResults = 8): Promise<{
|
||||
images: ImageSearchResult[]
|
||||
method: string
|
||||
}> {
|
||||
if (hasGskAuth()) {
|
||||
try {
|
||||
const images = await gskImageSearch(query, maxResults)
|
||||
if (images.length) return { images, method: 'gsk' }
|
||||
} catch {
|
||||
/* fall back to Serper/DuckDuckGo */
|
||||
}
|
||||
}
|
||||
const key = SERPER_KEY()
|
||||
if (key) {
|
||||
try {
|
||||
const resp = await fetchWithTimeout('https://google.serper.dev/images', {
|
||||
method: 'POST',
|
||||
headers: { 'X-API-KEY': key, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ q: query, num: Math.min(maxResults, 10), gl: 'us', hl: 'en' }),
|
||||
})
|
||||
if (resp.ok) {
|
||||
const data = asRecord(await resp.json())
|
||||
const raw: unknown[] = Array.isArray(data.images) ? data.images : []
|
||||
const images: ImageSearchResult[] = []
|
||||
for (const item of raw) {
|
||||
const img = asRecord(item)
|
||||
const imageUrl = String(img.imageUrl ?? img.original ?? '')
|
||||
if (!imageUrl) continue
|
||||
if (COPYRIGHT_HOSTS.some((d) => imageUrl.toLowerCase().includes(d))) continue
|
||||
const entry: ImageSearchResult = {
|
||||
title: String(img.title ?? ''),
|
||||
imageUrl,
|
||||
sourceUrl: String(img.link ?? ''),
|
||||
source: String(img.source ?? safeHost(img.link)),
|
||||
}
|
||||
if (typeof img.imageWidth === 'number') entry.width = img.imageWidth
|
||||
if (typeof img.imageHeight === 'number') entry.height = img.imageHeight
|
||||
images.push(entry)
|
||||
if (images.length >= maxResults) break
|
||||
}
|
||||
if (images.length) return { images, method: 'serper' }
|
||||
}
|
||||
} catch {
|
||||
/* fall back to DuckDuckGo */
|
||||
}
|
||||
}
|
||||
return { images: await duckImageSearch(query, maxResults), method: 'duckduckgo' }
|
||||
}
|
||||
|
||||
// ── DuckDuckGo fallback (no key / quota exhausted) ──────────────────
|
||||
|
||||
async function duckWebSearch(query: string, maxResults: number): Promise<{ results: WebSearchResult[] }> {
|
||||
try {
|
||||
// DuckDuckGo HTML endpoint (lightweight, no key needed)
|
||||
const resp = await fetchWithTimeout(
|
||||
`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`,
|
||||
{ headers: { 'User-Agent': 'Mozilla/5.0' } },
|
||||
)
|
||||
const html = await resp.text()
|
||||
const results: WebSearchResult[] = []
|
||||
const re = /<a[^>]*class="result__a"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/g
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(html)) !== null && results.length < maxResults) {
|
||||
const url = decodeDuckUrl(m[1]!)
|
||||
const title = stripTags(m[2]!)
|
||||
if (url && title) results.push({ title, url, snippet: '' })
|
||||
}
|
||||
return { results }
|
||||
} catch {
|
||||
return { results: [] }
|
||||
}
|
||||
}
|
||||
|
||||
async function duckImageSearch(query: string, maxResults: number): Promise<ImageSearchResult[]> {
|
||||
try {
|
||||
// DuckDuckGo i.js needs a vqd token, so it takes two steps
|
||||
const tokenResp = await fetchWithTimeout(
|
||||
`https://duckduckgo.com/?q=${encodeURIComponent(query)}`,
|
||||
{ headers: { 'User-Agent': 'Mozilla/5.0' } },
|
||||
)
|
||||
const tokenHtml = await tokenResp.text()
|
||||
const vqd = /vqd=["']?([\d-]+)["']?/.exec(tokenHtml)?.[1]
|
||||
if (!vqd) return []
|
||||
const resp = await fetchWithTimeout(
|
||||
`https://duckduckgo.com/i.js?l=us-en&o=json&q=${encodeURIComponent(query)}&vqd=${vqd}`,
|
||||
{ headers: { 'User-Agent': 'Mozilla/5.0', Referer: 'https://duckduckgo.com/' } },
|
||||
)
|
||||
const data = asRecord(await resp.json())
|
||||
const list: unknown[] = Array.isArray(data.results) ? data.results : []
|
||||
const out: ImageSearchResult[] = []
|
||||
for (const item of list.slice(0, maxResults)) {
|
||||
const img = asRecord(item)
|
||||
const imageUrl = String(img.image ?? '')
|
||||
if (!imageUrl || COPYRIGHT_HOSTS.some((d) => imageUrl.toLowerCase().includes(d))) continue
|
||||
const entry: ImageSearchResult = {
|
||||
title: String(img.title ?? ''),
|
||||
imageUrl,
|
||||
sourceUrl: String(img.url ?? ''),
|
||||
source: safeHost(img.url),
|
||||
}
|
||||
if (typeof img.width === 'number') entry.width = img.width
|
||||
if (typeof img.height === 'number') entry.height = img.height
|
||||
out.push(entry)
|
||||
}
|
||||
return out
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
// ── utils ───────────────────────────────────────────────────────────
|
||||
|
||||
async function fetchWithTimeout(url: string, init: RequestInit & { timeoutMs?: number } = {}): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const t = setTimeout(() => controller.abort(), init.timeoutMs ?? 15000)
|
||||
try {
|
||||
return await fetch(url, { ...init, signal: controller.signal })
|
||||
} finally {
|
||||
clearTimeout(t)
|
||||
}
|
||||
}
|
||||
|
||||
function stripTags(s: string): string {
|
||||
return s.replace(/<[^>]+>/g, '').replace(/&/g, '&').replace(/'/g, "'").trim()
|
||||
}
|
||||
|
||||
function decodeDuckUrl(href: string): string {
|
||||
// DuckDuckGo result links are often /l/?uddg=<encoded>
|
||||
const m = /[?&]uddg=([^&]+)/.exec(href)
|
||||
if (m) return decodeURIComponent(m[1]!)
|
||||
return href.startsWith('http') ? href : ''
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/** Search result types and shared constants (used by both the index and gsk backends) */
|
||||
|
||||
export interface WebSearchResult {
|
||||
title: string
|
||||
url: string
|
||||
snippet: string
|
||||
}
|
||||
|
||||
export interface ImageSearchResult {
|
||||
title: string
|
||||
imageUrl: string
|
||||
sourceUrl: string
|
||||
source: string
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
|
||||
// Known stock-photo hosts skipped during image search (matches the upstream filter list)
|
||||
export const COPYRIGHT_HOSTS = ['gettyimages', 'istockphoto', 'shutterstock', 'corbis']
|
||||
|
||||
export function safeHost(url: unknown): string {
|
||||
try {
|
||||
return new URL(String(url)).hostname
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* View untrusted JSON as a string-keyed record so properties can be probed
|
||||
* without `any`; non-object inputs read as an empty record.
|
||||
*/
|
||||
export function asRecord(v: unknown): Record<string, unknown> {
|
||||
return typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : {}
|
||||
}
|
||||
|
||||
/** First element when the value is an array, otherwise undefined (loose JSON probing). */
|
||||
export function firstItem(v: unknown): unknown {
|
||||
return Array.isArray(v) ? (v as unknown[])[0] : undefined
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
parseGskOutput,
|
||||
parseGskWebSearch,
|
||||
parseGskImageSearch,
|
||||
parseGskGeneratedImage,
|
||||
extractGskText,
|
||||
parseToolCliNdjson,
|
||||
} from '../src/gsk'
|
||||
|
||||
describe('parseGskOutput', () => {
|
||||
it('parses clean JSON', () => {
|
||||
expect(parseGskOutput('{"status":"ok"}')).toEqual({ status: 'ok' })
|
||||
})
|
||||
|
||||
it('skips [INFO] noise lines before JSON', () => {
|
||||
const out = '[INFO] Calling /tools...\n[INFO] cache hit\n{"status":"ok","data":[1,2]}'
|
||||
expect(parseGskOutput(out)).toEqual({ status: 'ok', data: [1, 2] })
|
||||
})
|
||||
|
||||
it('parses multi-line JSON after noise', () => {
|
||||
const out = '[INFO] x\n{\n "a": 1\n}'
|
||||
expect(parseGskOutput(out)).toEqual({ a: 1 })
|
||||
})
|
||||
|
||||
it('throws when no JSON present', () => {
|
||||
expect(() => parseGskOutput('[INFO] nothing here')).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseGskWebSearch', () => {
|
||||
it('maps organic_results and respects maxResults', () => {
|
||||
const raw = {
|
||||
status: 'ok',
|
||||
data: {
|
||||
organic_results: [
|
||||
{ title: 'A', link: 'https://a.com', snippet: 'sa' },
|
||||
{ title: 'B', link: 'https://b.com', snippet: 'sb' },
|
||||
{ title: 'C', link: 'https://c.com', snippet: 'sc' },
|
||||
],
|
||||
},
|
||||
}
|
||||
const r = parseGskWebSearch(raw, 2)
|
||||
expect(r.results).toEqual([
|
||||
{ title: 'A', url: 'https://a.com', snippet: 'sa' },
|
||||
{ title: 'B', url: 'https://b.com', snippet: 'sb' },
|
||||
])
|
||||
expect(r.answer).toBeUndefined()
|
||||
})
|
||||
|
||||
it('tolerates missing data', () => {
|
||||
expect(parseGskWebSearch({ status: 'ok' }, 5).results).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseGskImageSearch', () => {
|
||||
it('maps image entries with numeric size coercion', () => {
|
||||
const raw = {
|
||||
status: 'ok',
|
||||
data: [
|
||||
{
|
||||
image_url: 'https://sspark.genspark.ai/img1',
|
||||
title: 'T1',
|
||||
source: 'Site',
|
||||
link: 'https://site.com/page',
|
||||
width: '1000',
|
||||
height: '688',
|
||||
},
|
||||
],
|
||||
}
|
||||
const images = parseGskImageSearch(raw, 8)
|
||||
expect(images).toEqual([
|
||||
{
|
||||
title: 'T1',
|
||||
imageUrl: 'https://sspark.genspark.ai/img1',
|
||||
sourceUrl: 'https://site.com/page',
|
||||
source: 'Site',
|
||||
width: 1000,
|
||||
height: 688,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('filters copyright hosts and entries without url', () => {
|
||||
const raw = {
|
||||
data: [
|
||||
{ image_url: 'https://media.gettyimages.com/x.jpg', title: 'g' },
|
||||
{ title: 'no-url' },
|
||||
{ image_url: 'https://ok.com/a.jpg', title: 'ok' },
|
||||
],
|
||||
}
|
||||
const images = parseGskImageSearch(raw, 8)
|
||||
expect(images.map((i) => i.title)).toEqual(['ok'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseGskGeneratedImage', () => {
|
||||
it('prefers no-watermark url', () => {
|
||||
const raw = {
|
||||
data: {
|
||||
generated_images: [
|
||||
{
|
||||
image_urls: ['https://cdn/wm.png'],
|
||||
image_urls_nowatermark: ['https://cdn/clean.png'],
|
||||
task_id: 't1',
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
expect(parseGskGeneratedImage(raw)).toEqual({ url: 'https://cdn/clean.png', taskId: 't1' })
|
||||
})
|
||||
|
||||
it('falls back to image_urls, throws on empty', () => {
|
||||
expect(parseGskGeneratedImage({ data: { generated_images: [{ image_urls: ['https://cdn/a.png'] }] } }).url).toBe(
|
||||
'https://cdn/a.png',
|
||||
)
|
||||
expect(() => parseGskGeneratedImage({ data: { generated_images: [] } })).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractGskText', () => {
|
||||
it('returns string data directly', () => {
|
||||
expect(extractGskText({ data: 'hello' })).toBe('hello')
|
||||
})
|
||||
|
||||
it('picks known text fields', () => {
|
||||
expect(extractGskText({ data: { analysis: 'deep' } })).toBe('deep')
|
||||
expect(extractGskText({ data: { transcript: 'words' } })).toBe('words')
|
||||
})
|
||||
|
||||
it('stringifies unknown shapes', () => {
|
||||
expect(extractGskText({ data: { foo: 1 } })).toBe('{"foo":1}')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseToolCliNdjson', () => {
|
||||
it('skips heartbeat lines and returns the final status line', () => {
|
||||
const text =
|
||||
'{"version":1,"debug":true,"message":"Still processing... (5.0s)","heartbeat":1}\n' +
|
||||
'{"version":1,"debug":true,"message":"Still processing... (10.0s)","heartbeat":2}\n' +
|
||||
'{"version":1,"status":"ok","message":"success","data":{"pptx_url":"https://x/y","model":"claude-opus-4-7"}}'
|
||||
const r = parseToolCliNdjson(text)
|
||||
expect(r.status).toBe('ok')
|
||||
expect((r.data as { model: string }).model).toBe('claude-opus-4-7')
|
||||
})
|
||||
|
||||
it('returns error result lines as-is', () => {
|
||||
const r = parseToolCliNdjson('{"version":1,"status":"error","message":"deck_context must be an object","data":null}')
|
||||
expect(r.status).toBe('error')
|
||||
expect(r.message).toMatch(/deck_context/)
|
||||
})
|
||||
|
||||
it('throws when no result line exists', () => {
|
||||
expect(() => parseToolCliNdjson('{"heartbeat":1}\nnot json')).toThrow(/No result line/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
// Manual e2e verification script (calls gsk for real, requires login; not in CI): npx tsx tests/manual-gsk-e2e.mts
|
||||
import { webSearch, imageSearch, gskGenerateImage } from '../src/index'
|
||||
|
||||
const w = await webSearch('PowerPoint design trends 2026', 3)
|
||||
console.log('webSearch method:', w.method, '| results:', w.results.length, '| first:', w.results[0]?.title?.slice(0, 60))
|
||||
|
||||
const im = await imageSearch('minimalist gradient background', 3)
|
||||
console.log('imageSearch method:', im.method, '| images:', im.images.length, '| first:', im.images[0]?.imageUrl?.slice(0, 70))
|
||||
|
||||
const g = await gskGenerateImage({
|
||||
prompt: 'a simple flat vector icon of a lightbulb, blue background',
|
||||
aspectRatio: '1:1',
|
||||
imageSize: '0.5k',
|
||||
})
|
||||
console.log('generateImage url:', g.url.slice(0, 90))
|
||||
|
||||
// Verify the generated image is anonymously downloadable via plain fetch (image-insert flow depends on this)
|
||||
const resp = await fetch(g.url)
|
||||
console.log('download status:', resp.status, '| content-type:', resp.headers.get('content-type'))
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'
|
||||
import { webSearch, imageSearch } from '../src/index'
|
||||
|
||||
// These cases only test the Serper/DuckDuckGo paths; a local gsk login would take priority, so disable it explicitly
|
||||
beforeAll(() => {
|
||||
process.env.AI_SEARCH_DISABLE_GSK = '1'
|
||||
})
|
||||
|
||||
const realFetch = globalThis.fetch
|
||||
afterEach(() => {
|
||||
globalThis.fetch = realFetch
|
||||
delete process.env.SERPER_API_KEY
|
||||
})
|
||||
|
||||
function mockFetch(handler: (url: string, init?: RequestInit) => { ok: boolean; json?: any; text?: string }) {
|
||||
globalThis.fetch = vi.fn(async (url: any, init: any) => {
|
||||
const r = handler(String(url), init)
|
||||
return {
|
||||
ok: r.ok,
|
||||
status: r.ok ? 200 : 500,
|
||||
headers: new Map(),
|
||||
json: async () => r.json,
|
||||
text: async () => r.text ?? '',
|
||||
} as any
|
||||
}) as any
|
||||
}
|
||||
|
||||
describe('webSearch (Serper)', () => {
|
||||
it('parses organic results + answer box', async () => {
|
||||
process.env.SERPER_API_KEY = 'test-key'
|
||||
mockFetch((url) => {
|
||||
expect(url).toBe('https://google.serper.dev/search')
|
||||
return {
|
||||
ok: true,
|
||||
json: {
|
||||
answerBox: { answer: '42' },
|
||||
organic: [
|
||||
{ title: 'A', link: 'https://a.com', snippet: 'sa' },
|
||||
{ title: 'B', link: 'https://b.com', snippet: 'sb' },
|
||||
],
|
||||
},
|
||||
}
|
||||
})
|
||||
const r = await webSearch('meaning of life', 5)
|
||||
expect(r.method).toBe('serper')
|
||||
expect(r.answer).toBe('42')
|
||||
expect(r.results).toHaveLength(2)
|
||||
expect(r.results[0]).toEqual({ title: 'A', url: 'https://a.com', snippet: 'sa' })
|
||||
})
|
||||
|
||||
it('falls back to DuckDuckGo when no key', async () => {
|
||||
mockFetch((url) => {
|
||||
expect(url).toContain('duckduckgo.com')
|
||||
return {
|
||||
ok: true,
|
||||
text: '<a class="result__a" href="/l/?uddg=https%3A%2F%2Fx.com">X Title</a>',
|
||||
}
|
||||
})
|
||||
const r = await webSearch('q', 3)
|
||||
expect(r.method).toBe('duckduckgo')
|
||||
expect(r.results[0]?.url).toBe('https://x.com')
|
||||
expect(r.results[0]?.title).toBe('X Title')
|
||||
})
|
||||
})
|
||||
|
||||
describe('imageSearch (Serper)', () => {
|
||||
it('parses images + filters copyright hosts', async () => {
|
||||
process.env.SERPER_API_KEY = 'test-key'
|
||||
mockFetch((url) => {
|
||||
expect(url).toBe('https://google.serper.dev/images')
|
||||
return {
|
||||
ok: true,
|
||||
json: {
|
||||
images: [
|
||||
{ title: 'good', imageUrl: 'https://cdn.example.com/a.jpg', link: 'https://example.com', imageWidth: 800, imageHeight: 600 },
|
||||
{ title: 'paid', imageUrl: 'https://gettyimages.com/x.jpg', link: 'https://gettyimages.com' },
|
||||
],
|
||||
},
|
||||
}
|
||||
})
|
||||
const r = await imageSearch('cats', 8)
|
||||
expect(r.method).toBe('serper')
|
||||
expect(r.images).toHaveLength(1) // getty is filtered out
|
||||
expect(r.images[0]).toMatchObject({ imageUrl: 'https://cdn.example.com/a.jpg', width: 800, height: 600 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src", "tests"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: { include: ['tests/**/*.test.ts'] },
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@genoffice/docx-engine",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "docx parsing (Block tree with docxIndex anchors), OOXML fragment generation, paragraph-patch save",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"fixtures": "tsx scripts/generate-fixtures.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"fast-xml-parser": "^5.3.4",
|
||||
"jszip": "^3.10.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { mkdirSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { buildDocx, buildKitchenSinkDocx } from '../tests/helpers/build-docx'
|
||||
|
||||
const outDir = join(dirname(fileURLToPath(import.meta.url)), '../../../fixtures/generated')
|
||||
|
||||
async function main() {
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
|
||||
const kitchenSink = await buildKitchenSinkDocx()
|
||||
writeFileSync(join(outDir, 'kitchen-sink.docx'), kitchenSink)
|
||||
|
||||
const simple = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>标题</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>第一段。</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>第二段。</w:t></w:r></w:p>',
|
||||
})
|
||||
writeFileSync(join(outDir, 'simple.docx'), simple)
|
||||
|
||||
console.log(`fixtures written to ${outDir}`)
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
/** throwaway: build /tmp/revdemo.docx + /tmp/revdemo-v2.docx for manual review-mode verification */
|
||||
import { writeFileSync } from 'node:fs'
|
||||
import { buildDocx } from '../tests/helpers/build-docx'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
const COMMENTS_XML =
|
||||
XML_DECL +
|
||||
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:comment w:id="1" w:author="Alice" w:initials="A" w:date="2026-07-01T10:00:00Z">' +
|
||||
'<w:p><w:r><w:t>这个数据需要再核对一下</w:t></w:r></w:p></w:comment>' +
|
||||
'</w:comments>'
|
||||
|
||||
const body = [
|
||||
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>市场调研报告(修订演示)</w:t></w:r></w:p>',
|
||||
'<w:p><w:r><w:t xml:space="preserve">本季度销量同比增长 </w:t></w:r>' +
|
||||
'<w:commentRangeStart w:id="1"/><w:r><w:t>23%</w:t></w:r><w:commentRangeEnd w:id="1"/>' +
|
||||
'<w:r><w:commentReference w:id="1"/></w:r>' +
|
||||
'<w:r><w:t xml:space="preserve">,超出预期。</w:t></w:r></w:p>',
|
||||
'<w:p><w:r><w:t xml:space="preserve">市场规模预计达到 </w:t></w:r>' +
|
||||
'<w:del w:id="12" w:author="Bob" w:date="2026-07-02T08:30:00Z">' +
|
||||
'<w:r><w:delText>五千亿</w:delText></w:r></w:del>' +
|
||||
'<w:ins w:id="11" w:author="Alice" w:date="2026-07-01T10:00:00Z">' +
|
||||
'<w:r><w:t>六千亿</w:t></w:r></w:ins>' +
|
||||
'<w:r><w:t xml:space="preserve"> 元,竞争格局趋于集中。</w:t></w:r></w:p>',
|
||||
'<w:p><w:r><w:t>结论:建议加大渠道投入,关注头部厂商动态。</w:t></w:r></w:p>',
|
||||
].join('')
|
||||
|
||||
const bodyV2 = [
|
||||
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>市场调研报告(修订演示)</w:t></w:r></w:p>',
|
||||
'<w:p><w:r><w:t>本季度销量同比增长 23%,超出预期。</w:t></w:r></w:p>',
|
||||
'<w:p><w:r><w:t>新增:海外市场开始放量,值得关注。</w:t></w:r></w:p>',
|
||||
'<w:p><w:r><w:t>结论:建议聚焦高端产品线。</w:t></w:r></w:p>',
|
||||
].join('')
|
||||
|
||||
const main = async () => {
|
||||
writeFileSync(
|
||||
'/tmp/revdemo.docx',
|
||||
await buildDocx({
|
||||
bodyXml: body,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/comments.xml',
|
||||
xml: COMMENTS_XML,
|
||||
contentType:
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
writeFileSync('/tmp/revdemo-v2.docx', await buildDocx({ bodyXml: bodyV2 }))
|
||||
console.log('wrote /tmp/revdemo.docx and /tmp/revdemo-v2.docx')
|
||||
}
|
||||
|
||||
void main()
|
||||
@@ -0,0 +1,196 @@
|
||||
import JSZip from 'jszip'
|
||||
|
||||
/**
|
||||
* Blank document template for "new document" and AI from-scratch generation.
|
||||
*
|
||||
* The generate layer only references styles / numbering that already exist in
|
||||
* the package, so a fresh document must ship with the standard set: Normal,
|
||||
* Heading1-6, ListParagraph, Hyperlink, TOC1-9 (for generated TOC fields),
|
||||
* plus bullet (numId 1) and decimal (numId 2) numbering definitions.
|
||||
*/
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
const DOC_NS =
|
||||
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
|
||||
'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ' +
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
|
||||
'xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" ' +
|
||||
'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"'
|
||||
|
||||
/** numId of the template's bullet list definition */
|
||||
export const BLANK_BULLET_NUM_ID = '1'
|
||||
/** numId of the template's ordered (decimal) list definition */
|
||||
export const BLANK_ORDERED_NUM_ID = '2'
|
||||
|
||||
/** TOC entry styles referenced by generateTocFieldXml (indent grows per level) */
|
||||
function tocStyle(level: number): string {
|
||||
const ind = level > 1 ? `<w:ind w:left="${220 * (level - 1)}"/>` : ''
|
||||
return (
|
||||
`<w:style w:type="paragraph" w:styleId="TOC${level}"><w:name w:val="toc ${level}"/>` +
|
||||
'<w:basedOn w:val="Normal"/><w:next w:val="Normal"/>' +
|
||||
`<w:pPr><w:spacing w:after="100"/>${ind}</w:pPr></w:style>`
|
||||
)
|
||||
}
|
||||
|
||||
function headingStyle(level: number, sizeHalfPoints: number): string {
|
||||
return (
|
||||
`<w:style w:type="paragraph" w:styleId="Heading${level}"><w:name w:val="heading ${level}"/>` +
|
||||
'<w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>' +
|
||||
`<w:pPr><w:keepNext/><w:spacing w:before="${level <= 2 ? 240 : 160}" w:after="120"/><w:outlineLvl w:val="${level - 1}"/></w:pPr>` +
|
||||
`<w:rPr><w:b/><w:sz w:val="${sizeHalfPoints}"/><w:szCs w:val="${sizeHalfPoints}"/></w:rPr></w:style>`
|
||||
)
|
||||
}
|
||||
|
||||
const stylesXml = (eastAsiaFont?: string): string =>
|
||||
XML_DECL +
|
||||
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:docDefaults><w:rPrDefault><w:rPr>' +
|
||||
`<w:rFonts w:ascii="Calibri"${eastAsiaFont ? ` w:eastAsia="${eastAsiaFont}"` : ''} w:hAnsi="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/>` +
|
||||
'</w:rPr></w:rPrDefault>' +
|
||||
'<w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>' +
|
||||
'<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>' +
|
||||
headingStyle(1, 32) +
|
||||
headingStyle(2, 28) +
|
||||
headingStyle(3, 26) +
|
||||
headingStyle(4, 24) +
|
||||
headingStyle(5, 22) +
|
||||
headingStyle(6, 22) +
|
||||
'<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/>' +
|
||||
'<w:pPr><w:ind w:left="720"/><w:contextualSpacing/></w:pPr></w:style>' +
|
||||
'<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/>' +
|
||||
'<w:rPr><w:color w:val="0563C1"/><w:u w:val="single"/></w:rPr></w:style>' +
|
||||
Array.from({ length: 9 }, (_, i) => tocStyle(i + 1)).join('') +
|
||||
'</w:styles>'
|
||||
|
||||
function bulletLevels(): string {
|
||||
let xml = ''
|
||||
for (let ilvl = 0; ilvl < 5; ilvl++) {
|
||||
xml +=
|
||||
`<w:lvl w:ilvl="${ilvl}"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val=""/>` +
|
||||
`<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (ilvl + 1)}" w:hanging="360"/></w:pPr>` +
|
||||
'<w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol" w:hint="default"/></w:rPr></w:lvl>'
|
||||
}
|
||||
return xml
|
||||
}
|
||||
|
||||
function decimalLevels(): string {
|
||||
let xml = ''
|
||||
for (let ilvl = 0; ilvl < 5; ilvl++) {
|
||||
xml +=
|
||||
`<w:lvl w:ilvl="${ilvl}"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%${ilvl + 1}."/>` +
|
||||
`<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (ilvl + 1)}" w:hanging="360"/></w:pPr></w:lvl>`
|
||||
}
|
||||
return xml
|
||||
}
|
||||
|
||||
/** Custom numbering level (one level of a multilevel list / bullet library / numbering library definition) */
|
||||
export interface CustomNumberingLevel {
|
||||
/** w:numFmt:decimal/bullet/lowerLetter/upperRoman/chineseCountingThousand… */
|
||||
numFmt: string
|
||||
/** w:lvlText: a pattern like "%1." or a literal bullet symbol */
|
||||
lvlText: string
|
||||
/** w:ind w:left(twips) */
|
||||
indentLeft: number
|
||||
/** w:ind w:hanging (twips, default 360) */
|
||||
hanging?: number
|
||||
/** w:start (default 1) */
|
||||
start?: number
|
||||
}
|
||||
|
||||
const escAttr = (s: string): string =>
|
||||
s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
|
||||
function customLevels(levels: CustomNumberingLevel[]): string {
|
||||
return levels
|
||||
.map(
|
||||
(l, ilvl) =>
|
||||
`<w:lvl w:ilvl="${ilvl}"><w:start w:val="${l.start ?? 1}"/><w:numFmt w:val="${escAttr(l.numFmt)}"/>` +
|
||||
`<w:lvlText w:val="${escAttr(l.lvlText)}"/><w:lvlJc w:val="left"/>` +
|
||||
`<w:pPr><w:ind w:left="${Math.round(l.indentLeft)}" w:hanging="${Math.round(l.hanging ?? 360)}"/></w:pPr></w:lvl>`,
|
||||
)
|
||||
.join('')
|
||||
}
|
||||
|
||||
/** One abstractNum definition; uses custom levels when provided, otherwise the blank-template style (5 levels) */
|
||||
export function abstractNumXml(
|
||||
abstractNumId: string,
|
||||
kind: 'bullet' | 'ordered',
|
||||
levels?: CustomNumberingLevel[],
|
||||
): string {
|
||||
const body = levels?.length
|
||||
? customLevels(levels)
|
||||
: kind === 'bullet'
|
||||
? bulletLevels()
|
||||
: decimalLevels()
|
||||
return `<w:abstractNum w:abstractNumId="${abstractNumId}">${body}</w:abstractNum>`
|
||||
}
|
||||
|
||||
/** The blank template's numbering.xml (bullet numId 1 / decimal numId 2);
|
||||
* base content used when the document has no such part */
|
||||
export const BLANK_NUMBERING_XML =
|
||||
XML_DECL +
|
||||
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
`<w:abstractNum w:abstractNumId="0">${bulletLevels()}</w:abstractNum>` +
|
||||
`<w:abstractNum w:abstractNumId="1">${decimalLevels()}</w:abstractNum>` +
|
||||
`<w:num w:numId="${BLANK_BULLET_NUM_ID}"><w:abstractNumId w:val="0"/></w:num>` +
|
||||
`<w:num w:numId="${BLANK_ORDERED_NUM_ID}"><w:abstractNumId w:val="1"/></w:num>` +
|
||||
'</w:numbering>'
|
||||
|
||||
const NUMBERING_XML = BLANK_NUMBERING_XML
|
||||
|
||||
export interface BlankDocxOptions {
|
||||
/**
|
||||
* docDefaults East Asian font (w:eastAsia); pick per UI language so e.g.
|
||||
* Japanese/Korean users don't start with a Simplified-Chinese face.
|
||||
* When omitted no w:eastAsia is written — like an en-US Word document,
|
||||
* Word/our renderer then substitute per script when CJK text appears.
|
||||
*/
|
||||
eastAsiaFont?: string
|
||||
}
|
||||
|
||||
/** Build a minimal valid .docx: one empty paragraph, A4 portrait, standard styles. */
|
||||
export async function buildBlankDocx(options?: BlankDocxOptions): Promise<Uint8Array> {
|
||||
const zip = new JSZip()
|
||||
|
||||
zip.file(
|
||||
'[Content_Types].xml',
|
||||
`${XML_DECL}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
|
||||
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
||||
'<Default Extension="xml" ContentType="application/xml"/>' +
|
||||
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>' +
|
||||
'<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>' +
|
||||
'<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>' +
|
||||
'</Types>',
|
||||
)
|
||||
|
||||
zip.file(
|
||||
'_rels/.rels',
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
|
||||
zip.file(
|
||||
'word/_rels/document.xml.rels',
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' +
|
||||
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
|
||||
zip.file('word/styles.xml', stylesXml(options?.eastAsiaFont))
|
||||
zip.file('word/numbering.xml', NUMBERING_XML)
|
||||
|
||||
const sectPr =
|
||||
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>' +
|
||||
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
|
||||
'</w:sectPr>'
|
||||
zip.file(
|
||||
'word/document.xml',
|
||||
`${XML_DECL}<w:document ${DOC_NS}><w:body><w:p/>${sectPr}</w:body></w:document>`,
|
||||
)
|
||||
|
||||
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
import JSZip from 'jszip'
|
||||
import type { ChartDisplay, ChartSeries, NewChart } from './types'
|
||||
import {
|
||||
attrsOf,
|
||||
childrenOf,
|
||||
escapeXmlText,
|
||||
findChild,
|
||||
findChildren,
|
||||
nameOf,
|
||||
textOf,
|
||||
xmlParser,
|
||||
type XNode,
|
||||
} from './xml-utils'
|
||||
|
||||
const CHART_KINDS: Record<string, ChartDisplay['kind']> = {
|
||||
'c:barChart': 'bar',
|
||||
'c:bar3DChart': 'bar',
|
||||
'c:lineChart': 'line',
|
||||
'c:line3DChart': 'line',
|
||||
'c:pieChart': 'pie',
|
||||
'c:pie3DChart': 'pie',
|
||||
'c:doughnutChart': 'pie',
|
||||
'c:areaChart': 'area',
|
||||
'c:area3DChart': 'area',
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the display model of a chart part (word/charts/chartN.xml). Only the
|
||||
* caches Word writes next to the data references (c:strCache / c:numCache)
|
||||
* are read — the embedded workbook is never opened. Returns null when the
|
||||
* part has no series with cached values (e.g. scatter charts).
|
||||
*/
|
||||
export function parseChartPartXml(xml: string, partPath: string): ChartDisplay | null {
|
||||
const parsed = xmlParser.parse(xml) as XNode[]
|
||||
const space = parsed.find((n) => nameOf(n) === 'c:chartSpace')
|
||||
const chart = space ? findChild(space, 'c:chart') : undefined
|
||||
const plotArea = chart ? findChild(chart, 'c:plotArea') : undefined
|
||||
if (!chart || !plotArea) return null
|
||||
|
||||
// first plotted chart type wins (combo charts render their primary series)
|
||||
const plot = childrenOf(plotArea).find((c) => (nameOf(c) ?? '').endsWith('Chart'))
|
||||
if (!plot) return null
|
||||
const kind = CHART_KINDS[nameOf(plot) ?? ''] ?? 'other'
|
||||
|
||||
let categories: string[] = []
|
||||
const series: ChartSeries[] = []
|
||||
for (const ser of findChildren(plot, 'c:ser')) {
|
||||
const val = findChild(ser, 'c:val')
|
||||
const rawValues = val ? cachePoints(val) : []
|
||||
const values = rawValues.map((v) => {
|
||||
if (v === null || v.trim() === '') return null
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? n : null
|
||||
})
|
||||
if (values.length === 0) continue
|
||||
const cat = findChild(ser, 'c:cat')
|
||||
if (cat && categories.length === 0) {
|
||||
categories = cachePoints(cat).map((v) => v ?? '')
|
||||
}
|
||||
const name = seriesName(ser)
|
||||
series.push({ ...(name !== undefined ? { name } : {}), values })
|
||||
}
|
||||
if (series.length === 0) return null
|
||||
|
||||
const title = chartTitle(chart)
|
||||
return {
|
||||
partPath,
|
||||
kind,
|
||||
...(title !== undefined ? { title } : {}),
|
||||
categories,
|
||||
series,
|
||||
}
|
||||
}
|
||||
|
||||
/** cached point texts of a c:cat / c:val / c:tx container, in idx order */
|
||||
function cachePoints(container: XNode): (string | null)[] {
|
||||
const ref = findChild(container, 'c:strRef') ?? findChild(container, 'c:numRef')
|
||||
const cache = ref
|
||||
? (findChild(ref, 'c:strCache') ?? findChild(ref, 'c:numCache'))
|
||||
: (findChild(container, 'c:strLit') ?? findChild(container, 'c:numLit'))
|
||||
if (!cache) return []
|
||||
const count = parseInt(attrsOf(findChild(cache, 'c:ptCount') ?? {})['val'] ?? '', 10)
|
||||
const points: (string | null)[] = []
|
||||
for (const pt of findChildren(cache, 'c:pt')) {
|
||||
const idx = parseInt(attrsOf(pt)['idx'] ?? '', 10)
|
||||
if (!Number.isFinite(idx) || idx < 0) continue
|
||||
points[idx] = textOf(findChild(pt, 'c:v') ?? {})
|
||||
}
|
||||
const length = Number.isFinite(count) ? Math.max(count, points.length) : points.length
|
||||
const out: (string | null)[] = []
|
||||
for (let i = 0; i < length; i++) out.push(points[i] ?? null)
|
||||
return out
|
||||
}
|
||||
|
||||
function seriesName(ser: XNode): string | undefined {
|
||||
const tx = findChild(ser, 'c:tx')
|
||||
if (!tx) return undefined
|
||||
const literal = findChild(tx, 'c:v')
|
||||
if (literal) return textOf(literal)
|
||||
const cached = cachePoints(tx)
|
||||
return cached[0] ?? undefined
|
||||
}
|
||||
|
||||
function chartTitle(chart: XNode): string | undefined {
|
||||
const title = findChild(chart, 'c:title')
|
||||
if (!title) return undefined
|
||||
const texts: string[] = []
|
||||
const walk = (node: XNode) => {
|
||||
for (const child of childrenOf(node)) {
|
||||
if (nameOf(child) === 'a:t') texts.push(textOf(child))
|
||||
else walk(child)
|
||||
}
|
||||
}
|
||||
walk(title)
|
||||
return texts.join('')
|
||||
}
|
||||
|
||||
const _XLSX_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
export const CHART_WORKBOOK_REL_TYPE =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/package'
|
||||
|
||||
const colLetter = (i: number) => String.fromCharCode(66 + i) // B, C, D...
|
||||
|
||||
function strCacheXml(values: string[], f: string): string {
|
||||
return (
|
||||
`<c:strRef><c:f>${escapeXmlText(f)}</c:f><c:strCache><c:ptCount val="${values.length}"/>` +
|
||||
values.map((v, i) => `<c:pt idx="${i}"><c:v>${escapeXmlText(v)}</c:v></c:pt>`).join('') +
|
||||
'</c:strCache></c:strRef>'
|
||||
)
|
||||
}
|
||||
|
||||
function numCacheXml(values: (number | null)[], f: string): string {
|
||||
return (
|
||||
`<c:numRef><c:f>${escapeXmlText(f)}</c:f><c:numCache><c:formatCode>General</c:formatCode>` +
|
||||
`<c:ptCount val="${values.length}"/>` +
|
||||
values.map((v, i) => (v === null ? '' : `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`)).join('') +
|
||||
'</c:numCache></c:numRef>'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a complete chart part (word/charts/chartN.xml) from data. The chart
|
||||
* references an embedded workbook via c:externalData so Word's "Edit Data" works.
|
||||
* Pass `externalDataRId` to wire the c:externalData relationship; omit it when
|
||||
* the workbook will be added in a separate step.
|
||||
*/
|
||||
export function buildChartPartXml(chart: NewChart, externalDataRId?: string): string {
|
||||
const rows = chart.categories.length
|
||||
const sers = chart.series
|
||||
.map((ser, i) => {
|
||||
const col = colLetter(i)
|
||||
return (
|
||||
`<c:ser><c:idx val="${i}"/><c:order val="${i}"/>` +
|
||||
`<c:tx>${strCacheXml([ser.name], `Sheet1!$${col}$1`)}</c:tx>` +
|
||||
`<c:cat>${strCacheXml(chart.categories, `Sheet1!$A$2:$A$${rows + 1}`)}</c:cat>` +
|
||||
`<c:val>${numCacheXml(ser.values.slice(0, rows), `Sheet1!$${col}$2:$${col}$${rows + 1}`)}</c:val>` +
|
||||
'</c:ser>'
|
||||
)
|
||||
})
|
||||
.join('')
|
||||
|
||||
let plot: string
|
||||
if (chart.kind === 'pie') {
|
||||
plot = `<c:pieChart><c:varyColors val="1"/>${sers}<c:firstSliceAng val="0"/></c:pieChart>`
|
||||
} else {
|
||||
const axes =
|
||||
'<c:catAx><c:axId val="111111111"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
'<c:delete val="0"/><c:axPos val="b"/><c:crossAx val="222222222"/></c:catAx>' +
|
||||
'<c:valAx><c:axId val="222222222"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
'<c:delete val="0"/><c:axPos val="l"/><c:crossAx val="111111111"/></c:valAx>'
|
||||
const inner =
|
||||
chart.kind === 'bar'
|
||||
? `<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:varyColors val="0"/>${sers}` +
|
||||
'<c:axId val="111111111"/><c:axId val="222222222"/></c:barChart>'
|
||||
: `<c:lineChart><c:grouping val="standard"/><c:varyColors val="0"/>${sers}<c:marker val="1"/>` +
|
||||
'<c:axId val="111111111"/><c:axId val="222222222"/></c:lineChart>'
|
||||
plot = inner + axes
|
||||
}
|
||||
|
||||
const title = chart.title
|
||||
? '<c:title><c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p><a:r>' +
|
||||
`<a:t>${escapeXmlText(chart.title)}</a:t></a:r></a:p></c:rich></c:tx>` +
|
||||
'<c:overlay val="0"/></c:title><c:autoTitleDeleted val="0"/>'
|
||||
: ''
|
||||
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
'<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ' +
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
`<c:chart>${title}<c:plotArea><c:layout/>${plot}</c:plotArea>` +
|
||||
'<c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/></c:chart>' +
|
||||
(externalDataRId
|
||||
? `<c:externalData r:id="${externalDataRId}"><c:autoUpdate val="0"/></c:externalData>`
|
||||
: '') +
|
||||
'</c:chartSpace>'
|
||||
)
|
||||
}
|
||||
|
||||
export interface ChartSeriesPatch {
|
||||
name?: string
|
||||
/** aligned with ChartSeries.values; null = keep the original value */
|
||||
values?: (number | null)[]
|
||||
}
|
||||
|
||||
export interface ChartPatch {
|
||||
title?: string
|
||||
/** aligned with ChartDisplay.categories; null = keep */
|
||||
categories?: (string | null)[]
|
||||
/** aligned with ChartDisplay.series; null = keep that series untouched */
|
||||
series?: (ChartSeriesPatch | null)[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch cached texts/numbers of a chart part while keeping the structure —
|
||||
* data references (c:f), styling, layout — byte-identical. Anything the
|
||||
* patch cannot anchor (missing title, missing cache point) is left as-is.
|
||||
* The embedded workbook is intentionally not touched: Word renders from
|
||||
* these caches, but "Edit Data" will show the original sheet numbers.
|
||||
*/
|
||||
export function patchChartPartXml(xml: string, patch: ChartPatch): string {
|
||||
const edits: Array<{ start: number; end: number; text: string }> = []
|
||||
|
||||
if (patch.title !== undefined) {
|
||||
const title = tagRange(xml, 'c:title')
|
||||
if (title) {
|
||||
const texts = innerTextRanges(xml, 'a:t', title.start, title.end)
|
||||
// whole title into the first run, remaining runs blanked
|
||||
texts.forEach((range, i) => {
|
||||
edits.push({ ...range, text: i === 0 ? patch.title! : '' })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const serRanges = tagRanges(xml, 'c:ser')
|
||||
serRanges.forEach((ser, i) => {
|
||||
const serPatch = patch.series?.[i]
|
||||
if (serPatch?.name !== undefined) {
|
||||
const tx = tagRange(xml, 'c:tx', ser.start, ser.end)
|
||||
if (tx) {
|
||||
const texts = innerTextRanges(xml, 'c:v', tx.start, tx.end)
|
||||
if (texts.length > 0) edits.push({ ...texts[0], text: serPatch.name })
|
||||
}
|
||||
}
|
||||
if (serPatch?.values) {
|
||||
const val = tagRange(xml, 'c:val', ser.start, ser.end)
|
||||
if (val)
|
||||
pushPointEdits(
|
||||
xml,
|
||||
val,
|
||||
serPatch.values.map((v) => (v === null ? null : String(v))),
|
||||
edits,
|
||||
)
|
||||
}
|
||||
// categories are cached per series; every copy must agree
|
||||
if (patch.categories) {
|
||||
const cat = tagRange(xml, 'c:cat', ser.start, ser.end)
|
||||
if (cat) pushPointEdits(xml, cat, patch.categories, edits)
|
||||
}
|
||||
})
|
||||
|
||||
if (edits.length === 0) return xml
|
||||
let out = xml
|
||||
for (const edit of edits.sort((a, b) => b.start - a.start)) {
|
||||
out = out.slice(0, edit.start) + escapeXmlText(edit.text) + out.slice(edit.end)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** queue edits for the c:v of each indexed cache point present in [range] */
|
||||
function pushPointEdits(
|
||||
xml: string,
|
||||
range: { start: number; end: number },
|
||||
texts: (string | null)[],
|
||||
edits: Array<{ start: number; end: number; text: string }>,
|
||||
): void {
|
||||
const re = /<c:pt idx="(\d+)"[^>]*>([\s\S]*?)<\/c:pt>/g
|
||||
re.lastIndex = range.start
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null && m.index < range.end) {
|
||||
const idx = parseInt(m[1], 10)
|
||||
const text = texts[idx]
|
||||
if (text === null || text === undefined) continue
|
||||
const inner = innerTextRanges(xml, 'c:v', m.index, m.index + m[0].length)
|
||||
if (inner.length > 0) edits.push({ ...inner[0], text })
|
||||
}
|
||||
}
|
||||
|
||||
/** first depth-0 range of `tag` in [from, to); charts never nest these tags */
|
||||
function tagRange(
|
||||
xml: string,
|
||||
tag: string,
|
||||
from = 0,
|
||||
to = xml.length,
|
||||
): { start: number; end: number } | null {
|
||||
const openPrefix = '<' + tag
|
||||
let i = from
|
||||
while (i < to) {
|
||||
const o = xml.indexOf(openPrefix, i)
|
||||
if (o === -1 || o >= to) return null
|
||||
const after = xml.charAt(o + openPrefix.length)
|
||||
if (after !== '>' && after !== ' ' && after !== '/') {
|
||||
i = o + openPrefix.length // prefix of a longer tag (c:tx vs c:txPr)
|
||||
continue
|
||||
}
|
||||
const close = xml.indexOf('</' + tag + '>', o)
|
||||
if (close === -1 || close >= to) return null
|
||||
return { start: o, end: close + tag.length + 3 }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** all depth-0 ranges of `tag` (used for c:ser, which never nests) */
|
||||
function tagRanges(xml: string, tag: string): Array<{ start: number; end: number }> {
|
||||
const out: Array<{ start: number; end: number }> = []
|
||||
let from = 0
|
||||
let range: { start: number; end: number } | null
|
||||
while ((range = tagRange(xml, tag, from)) !== null) {
|
||||
out.push(range)
|
||||
from = range.end
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** inner-text ranges (between open and close tag) of every `tag` in [from, to) */
|
||||
function innerTextRanges(
|
||||
xml: string,
|
||||
tag: string,
|
||||
from: number,
|
||||
to: number,
|
||||
): Array<{ start: number; end: number }> {
|
||||
const out: Array<{ start: number; end: number }> = []
|
||||
const re = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, 'g')
|
||||
re.lastIndex = from
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null && m.index < to) {
|
||||
const openEnd = m.index + m[0].indexOf('>') + 1
|
||||
out.push({ start: openEnd, end: openEnd + m[1].length })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- embedded xlsx workbook ----
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
|
||||
|
||||
/** Excel column letter: A, B, C... */
|
||||
const xlsxColLetter = (i: number) => String.fromCharCode(65 + i)
|
||||
|
||||
/**
|
||||
* Build a minimal but valid xlsx file containing one Sheet1 with the chart
|
||||
* data (header row + data rows). Returns base64-encoded bytes.
|
||||
*
|
||||
* Layout:
|
||||
* A1 | B1 (ser 0 name) | C1 (ser 1 name) ...
|
||||
* A2 (cat0) | B2 (val 0,0) | C2 (val 1,0) ...
|
||||
* A3 (cat1) | B3 (val 0,1) | C3 (val 1,1) ...
|
||||
*/
|
||||
export async function buildChartWorkbookXlsxBase64(
|
||||
categories: string[],
|
||||
series: Array<{ name: string; values: (number | null)[] }>,
|
||||
): Promise<string> {
|
||||
const rows = categories.length
|
||||
const serCount = series.length
|
||||
|
||||
// shared strings: all text cells collected in order
|
||||
const strings: string[] = []
|
||||
const si = (s: string): number => {
|
||||
const idx = strings.indexOf(s)
|
||||
if (idx !== -1) return idx
|
||||
strings.push(s)
|
||||
return strings.length - 1
|
||||
}
|
||||
|
||||
// Build sheetData rows
|
||||
const headerCells: string[] = []
|
||||
// A1: empty label cell
|
||||
headerCells.push(`<c r="A1" t="s"><v>${si('')}</v></c>`)
|
||||
for (let j = 0; j < serCount; j++) {
|
||||
headerCells.push(`<c r="${xlsxColLetter(j + 1)}1" t="s"><v>${si(series[j].name)}</v></c>`)
|
||||
}
|
||||
const dataRows: string[] = []
|
||||
for (let i = 0; i < rows; i++) {
|
||||
const rowNum = i + 2
|
||||
const cells: string[] = []
|
||||
cells.push(`<c r="A${rowNum}" t="s"><v>${si(categories[i])}</v></c>`)
|
||||
for (let j = 0; j < serCount; j++) {
|
||||
const val = series[j].values[i]
|
||||
if (val !== null && val !== undefined) {
|
||||
cells.push(`<c r="${xlsxColLetter(j + 1)}${rowNum}"><v>${val}</v></c>`)
|
||||
}
|
||||
}
|
||||
dataRows.push(`<row r="${rowNum}">${cells.join('')}</row>`)
|
||||
}
|
||||
|
||||
const sheetXml =
|
||||
XML_DECL +
|
||||
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
|
||||
'<sheetData>' +
|
||||
`<row r="1">${headerCells.join('')}</row>` +
|
||||
dataRows.join('') +
|
||||
'</sheetData>' +
|
||||
'</worksheet>'
|
||||
|
||||
const sharedStringsXml =
|
||||
XML_DECL +
|
||||
`<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${strings.length}" uniqueCount="${strings.length}">` +
|
||||
strings.map((s) => `<si><t>${escapeXmlText(s)}</t></si>`).join('') +
|
||||
'</sst>'
|
||||
|
||||
const workbookXml =
|
||||
XML_DECL +
|
||||
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
'<sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets>' +
|
||||
'</workbook>'
|
||||
|
||||
const workbookRels =
|
||||
XML_DECL +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' +
|
||||
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
const topRels =
|
||||
XML_DECL +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
const contentTypes =
|
||||
XML_DECL +
|
||||
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
|
||||
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
||||
'<Default Extension="xml" ContentType="application/xml"/>' +
|
||||
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
|
||||
'<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>' +
|
||||
'<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>' +
|
||||
'</Types>'
|
||||
|
||||
const zip = new JSZip()
|
||||
zip.file('[Content_Types].xml', contentTypes)
|
||||
zip.file('_rels/.rels', topRels)
|
||||
zip.file('xl/workbook.xml', workbookXml)
|
||||
zip.file('xl/_rels/workbook.xml.rels', workbookRels)
|
||||
zip.file('xl/worksheets/sheet1.xml', sheetXml)
|
||||
zip.file('xl/sharedStrings.xml', sharedStringsXml)
|
||||
|
||||
return zipToBase64(zip)
|
||||
}
|
||||
|
||||
async function zipToBase64(zip: JSZip): Promise<string> {
|
||||
const bytes = await zip.generateAsync({
|
||||
type: 'uint8array',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: { level: 6 },
|
||||
})
|
||||
let binary = ''
|
||||
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i])
|
||||
return btoa(binary)
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch the Sheet1 sheetData inside an embedded xlsx file (base64).
|
||||
* Rewrites category column A and each series column with the provided values.
|
||||
* Returns the updated base64, or null on failure.
|
||||
*/
|
||||
export async function patchChartWorkbookXlsxBase64(
|
||||
base64: string,
|
||||
categories: string[],
|
||||
series: Array<{ name: string; values: (number | null)[] }>,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const binaryStr = atob(base64)
|
||||
const bytes = new Uint8Array(binaryStr.length)
|
||||
for (let i = 0; i < binaryStr.length; i++) bytes[i] = binaryStr.charCodeAt(i)
|
||||
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
const sheetFile = zip.file('xl/worksheets/sheet1.xml')
|
||||
if (!sheetFile) return null
|
||||
|
||||
// Replace only Sheet1's sheetData in place, using inline strings so
|
||||
// sharedStrings.xml (and every other part: styles, extra sheets, defined
|
||||
// names) survives untouched.
|
||||
const inlineStr = (ref: string, text: string) =>
|
||||
`<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${escapeXmlText(text)}</t></is></c>`
|
||||
const headerCells = [inlineStr('A1', '')]
|
||||
for (let j = 0; j < series.length; j++) {
|
||||
headerCells.push(inlineStr(`${xlsxColLetter(j + 1)}1`, series[j].name))
|
||||
}
|
||||
const dataRows: string[] = []
|
||||
for (let i = 0; i < categories.length; i++) {
|
||||
const rowNum = i + 2
|
||||
const cells = [inlineStr(`A${rowNum}`, categories[i])]
|
||||
for (let j = 0; j < series.length; j++) {
|
||||
const val = series[j].values[i]
|
||||
if (val !== null && val !== undefined) {
|
||||
cells.push(`<c r="${xlsxColLetter(j + 1)}${rowNum}"><v>${val}</v></c>`)
|
||||
}
|
||||
}
|
||||
dataRows.push(`<row r="${rowNum}">${cells.join('')}</row>`)
|
||||
}
|
||||
const newSheetData = `<sheetData><row r="1">${headerCells.join('')}</row>${dataRows.join('')}</sheetData>`
|
||||
|
||||
const sheetXml = await sheetFile.async('string')
|
||||
if (!/<sheetData\/>|<sheetData[\s>]/.test(sheetXml)) return null
|
||||
let updatedSheet = sheetXml.replace(
|
||||
/<sheetData\/>|<sheetData[^>]*>[\s\S]*?<\/sheetData>/,
|
||||
newSheetData,
|
||||
)
|
||||
const lastRef = `${xlsxColLetter(series.length)}${categories.length + 1}`
|
||||
updatedSheet = updatedSheet.replace(/<dimension[^>]*\/>/, `<dimension ref="A1:${lastRef}"/>`)
|
||||
|
||||
zip.file('xl/worksheets/sheet1.xml', updatedSheet)
|
||||
return await zipToBase64(zip)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,90 @@
|
||||
export * from './types'
|
||||
export { parseDocx, type ParseExtras } from './parse'
|
||||
export {
|
||||
saveDocx,
|
||||
findChartWorkbookPath,
|
||||
readDocxPartBase64,
|
||||
type SaveBlock,
|
||||
type SaveOptions,
|
||||
type StyleUpsert,
|
||||
type ParsedDocFull,
|
||||
} from './patch'
|
||||
export {
|
||||
TABLE_HEADER_FILL,
|
||||
WORDART_PRESETS,
|
||||
applyImageWrap,
|
||||
buildShapeParagraphXml,
|
||||
buildTextboxParagraphXml,
|
||||
buildWordArtParagraphXml,
|
||||
generateCaptionXml,
|
||||
generateIndexFieldXml,
|
||||
generateParagraphXml,
|
||||
generateTableModelXml,
|
||||
generateTableXml,
|
||||
generateTocFieldXml,
|
||||
mergePPrFormat,
|
||||
setPPrChange,
|
||||
stripPPrChange,
|
||||
patchFieldParagraphXml,
|
||||
patchImageParagraphXml,
|
||||
patchMathTokens,
|
||||
patchTableCellTexts,
|
||||
patchTextboxHeights,
|
||||
patchTextboxParas,
|
||||
type CellTextsPatch,
|
||||
type FieldTextPatch,
|
||||
type GenerateContext,
|
||||
type ImagePatch,
|
||||
type TextboxParaPatch,
|
||||
type TableGenOptions,
|
||||
type TocEntry,
|
||||
} from './generate'
|
||||
export {
|
||||
buildChartPartXml,
|
||||
buildChartWorkbookXlsxBase64,
|
||||
patchChartWorkbookXlsxBase64,
|
||||
parseChartPartXml,
|
||||
patchChartPartXml,
|
||||
CHART_WORKBOOK_REL_TYPE,
|
||||
type ChartPatch,
|
||||
type ChartSeriesPatch,
|
||||
} from './chart'
|
||||
export {
|
||||
latexToOmml,
|
||||
mathParagraphXml,
|
||||
mathTokensOf,
|
||||
ommlFragmentsOf,
|
||||
ommlToLatex,
|
||||
ommlToMathML,
|
||||
} from './math'
|
||||
export { scanBody, type BodyElement, type BodyScan } from './scan'
|
||||
export {
|
||||
BLANK_BULLET_NUM_ID,
|
||||
BLANK_ORDERED_NUM_ID,
|
||||
buildBlankDocx,
|
||||
type BlankDocxOptions,
|
||||
type CustomNumberingLevel,
|
||||
} from './blank'
|
||||
export {
|
||||
DEFAULT_SECTION,
|
||||
applySectionSettings,
|
||||
applyPageNumType,
|
||||
applySectionStartType,
|
||||
readPageColor,
|
||||
readSections,
|
||||
readSectionSettings,
|
||||
sectionSettingsFromXml,
|
||||
} from './section'
|
||||
export { nextNoteId, parseNotesXml, type NoteKind } from './notes'
|
||||
export { readWatermarkText } from './watermark'
|
||||
export {
|
||||
INK_NAME_PREFIX,
|
||||
anchoredInkRunXml,
|
||||
findInkRuns,
|
||||
injectInkRunsIntoParagraph,
|
||||
stripInkRuns,
|
||||
} from './ink'
|
||||
export { bibliographyLine, citationText, parseSourcesXml } from './sources'
|
||||
export { readThemeColors, readThemeFonts } from './theme'
|
||||
export { hashProtectionPassword, verifyProtectionPassword } from './protection'
|
||||
export { decodeSymbolChar, decodeSymbolText, isSymbolFont } from './symbol-fonts'
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { NewInkImage } from './types'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
|
||||
/**
|
||||
* Ink annotations (freehand strokes). Each saved annotation is a floating picture —
|
||||
* a run-level <w:drawing><wp:anchor> injected into its anchor paragraph:
|
||||
*
|
||||
* - wp:positionV relativeFrom="paragraph": the drawing moves with the
|
||||
* paragraph when content above it reflows.
|
||||
* - wp:positionH relativeFrom="column": offsets are measured from the text
|
||||
* column edge, independent of the paragraph's own indentation.
|
||||
* - behindDoc="0" + wp:wrapNone: floats in front of the text without
|
||||
* affecting layout.
|
||||
* - wp:docPr name starts with "aidocs-ink" so we can recognize our own
|
||||
* annotations when the file is reopened; descr carries the editor's
|
||||
* stroke vectors (opaque payload) so the layer stays re-editable.
|
||||
*
|
||||
* Word renders these as ordinary floating pictures; only our editor restores
|
||||
* them into live strokes.
|
||||
*/
|
||||
|
||||
export const INK_NAME_PREFIX = 'aidocs-ink'
|
||||
|
||||
/** media filename prefix for ink PNGs (distinct from inline-image aidocsN) */
|
||||
export const INK_MEDIA_PREFIX = 'aidocsink'
|
||||
|
||||
/** matches a document.xml.rels entry that targets an ink media part */
|
||||
export const INK_REL_RE = new RegExp(
|
||||
`<Relationship [^>]*Target="media/${INK_MEDIA_PREFIX}\\d+\\.png"[^>]*/>`,
|
||||
'g',
|
||||
)
|
||||
|
||||
/** matches an ink media part's zip path */
|
||||
export const INK_MEDIA_PATH_RE = new RegExp(`^word/media/${INK_MEDIA_PREFIX}\\d+\\.png$`)
|
||||
|
||||
const EMU_PER_PX = 9525
|
||||
|
||||
const A_NS = 'http://schemas.openxmlformats.org/drawingml/2006/main'
|
||||
const PIC_NS = 'http://schemas.openxmlformats.org/drawingml/2006/picture'
|
||||
const WP_NS = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'
|
||||
const R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
|
||||
/**
|
||||
* The anchored-picture run for one ink annotation. Namespaces are declared
|
||||
* inline so the fragment is valid regardless of what the document root
|
||||
* declares (w: is always present).
|
||||
*/
|
||||
export function anchoredInkRunXml(
|
||||
ink: Pick<NewInkImage, 'widthPx' | 'heightPx' | 'offsetXPx' | 'offsetYPx' | 'payload'>,
|
||||
rId: string,
|
||||
docPrId: number,
|
||||
): string {
|
||||
const cx = Math.max(1, Math.round(ink.widthPx * EMU_PER_PX))
|
||||
const cy = Math.max(1, Math.round(ink.heightPx * EMU_PER_PX))
|
||||
const x = Math.round(ink.offsetXPx * EMU_PER_PX)
|
||||
const y = Math.round(ink.offsetYPx * EMU_PER_PX)
|
||||
const name = `${INK_NAME_PREFIX} ${docPrId}`
|
||||
const descr = ink.payload ? ` descr="${escapeXmlAttr(ink.payload)}"` : ''
|
||||
return (
|
||||
'<w:r><w:drawing>' +
|
||||
`<wp:anchor xmlns:wp="${WP_NS}" distT="0" distB="0" distL="0" distR="0" simplePos="0"` +
|
||||
` relativeHeight="${251658240 + docPrId}" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">` +
|
||||
'<wp:simplePos x="0" y="0"/>' +
|
||||
`<wp:positionH relativeFrom="column"><wp:posOffset>${x}</wp:posOffset></wp:positionH>` +
|
||||
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>${y}</wp:posOffset></wp:positionV>` +
|
||||
`<wp:extent cx="${cx}" cy="${cy}"/>` +
|
||||
'<wp:effectExtent l="0" t="0" r="0" b="0"/>' +
|
||||
'<wp:wrapNone/>' +
|
||||
`<wp:docPr id="${docPrId}" name="${name}"${descr}/>` +
|
||||
'<wp:cNvGraphicFramePr/>' +
|
||||
`<a:graphic xmlns:a="${A_NS}">` +
|
||||
`<a:graphicData uri="${PIC_NS}">` +
|
||||
`<pic:pic xmlns:pic="${PIC_NS}">` +
|
||||
`<pic:nvPicPr><pic:cNvPr id="${docPrId}" name="${name}"/><pic:cNvPicPr/></pic:nvPicPr>` +
|
||||
`<pic:blipFill><a:blip xmlns:r="${R_NS}" r:embed="${rId}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>` +
|
||||
`<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>' +
|
||||
'</pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
|
||||
)
|
||||
}
|
||||
|
||||
const ANCHOR_RUN_RE = /<w:r><w:drawing><wp:anchor[\s\S]*?<\/wp:anchor><\/w:drawing><\/w:r>/g
|
||||
|
||||
const isInkRun = (run: string) => run.includes(`name="${INK_NAME_PREFIX}`)
|
||||
|
||||
/** Remove every aidocs-ink run from a body-element XML slice. */
|
||||
export function stripInkRuns(xml: string): string {
|
||||
if (!xml.includes(INK_NAME_PREFIX)) return xml
|
||||
return xml.replace(ANCHOR_RUN_RE, (run) => (isInkRun(run) ? '' : run))
|
||||
}
|
||||
|
||||
/** One raw ink run found in a paragraph's XML. */
|
||||
export interface InkRunMatch {
|
||||
/** the exact <w:r>...</w:r> slice, for stripping */
|
||||
xml: string
|
||||
offsetXPx: number
|
||||
offsetYPx: number
|
||||
widthPx: number
|
||||
heightPx: number
|
||||
payload: string | null
|
||||
/** relationship id of the embedded PNG */
|
||||
embedRId: string | null
|
||||
}
|
||||
|
||||
/** Find aidocs-ink anchored runs inside one paragraph's XML. */
|
||||
export function findInkRuns(paragraphXml: string): InkRunMatch[] {
|
||||
if (!paragraphXml.includes(INK_NAME_PREFIX)) return []
|
||||
const out: InkRunMatch[] = []
|
||||
for (const run of paragraphXml.match(ANCHOR_RUN_RE) ?? []) {
|
||||
if (!isInkRun(run)) continue
|
||||
const emu = (re: RegExp) => parseInt(re.exec(run)?.[1] ?? '0', 10) || 0
|
||||
const descr = /<wp:docPr [^>]*descr="([^"]*)"/.exec(run)?.[1]
|
||||
out.push({
|
||||
xml: run,
|
||||
offsetXPx: emu(/<wp:positionH[^>]*><wp:posOffset>(-?\d+)/) / EMU_PER_PX,
|
||||
offsetYPx: emu(/<wp:positionV[^>]*><wp:posOffset>(-?\d+)/) / EMU_PER_PX,
|
||||
widthPx: emu(/<wp:extent cx="(\d+)"/) / EMU_PER_PX,
|
||||
heightPx: emu(/<wp:extent cx="\d+" cy="(\d+)"/) / EMU_PER_PX,
|
||||
payload: descr ? decodeXmlEntities(descr) : null,
|
||||
embedRId: /r:embed="([^"]+)"/.exec(run)?.[1] ?? null,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert ink runs at the end of a paragraph fragment (after all content
|
||||
* runs). Returns null when the fragment's root is not a w:p — floating ink
|
||||
* can only anchor to paragraphs.
|
||||
*/
|
||||
export function injectInkRunsIntoParagraph(xml: string, runsXml: string): string | null {
|
||||
if (!/^<w:p[\s/>]/.test(xml)) return null
|
||||
if (xml.endsWith('/>')) return `${xml.slice(0, -2)}>${runsXml}</w:p>`
|
||||
const close = xml.lastIndexOf('</w:p>')
|
||||
if (close === -1) return null
|
||||
return xml.slice(0, close) + runsXml + xml.slice(close)
|
||||
}
|
||||
|
||||
function decodeXmlEntities(text: string): string {
|
||||
return text
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&')
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,200 @@
|
||||
import { patchParagraphTexts } from './text-patch'
|
||||
import type { NoteInfo, NoteRun } from './types'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
|
||||
/**
|
||||
* Footnotes / endnotes part handling (word/footnotes.xml, word/endnotes.xml).
|
||||
*
|
||||
* Both parts share one schema: a list of w:footnote / w:endnote elements.
|
||||
* Entries carrying a w:type attribute (separator, continuationSeparator, ...)
|
||||
* are structural and must be preserved; only typeless entries are real notes.
|
||||
*/
|
||||
|
||||
export type NoteKind = 'footnote' | 'endnote'
|
||||
|
||||
const ROOT: Record<NoteKind, string> = { footnote: 'w:footnotes', endnote: 'w:endnotes' }
|
||||
const ENTRY: Record<NoteKind, string> = { footnote: 'w:footnote', endnote: 'w:endnote' }
|
||||
|
||||
export const NOTE_PART_PATH: Record<NoteKind, string> = {
|
||||
footnote: 'word/footnotes.xml',
|
||||
endnote: 'word/endnotes.xml',
|
||||
}
|
||||
|
||||
export const NOTE_REL_TYPE: Record<NoteKind, string> = {
|
||||
footnote: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes',
|
||||
endnote: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes',
|
||||
}
|
||||
|
||||
export const NOTE_CONTENT_TYPE: Record<NoteKind, string> = {
|
||||
footnote: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml',
|
||||
endnote: 'application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml',
|
||||
}
|
||||
|
||||
const NOTE_NS =
|
||||
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'
|
||||
|
||||
/** real notes (separator entries excluded), in file order */
|
||||
export function parseNotesXml(xml: string, kind: NoteKind): NoteInfo[] {
|
||||
return noteEntriesOf(xml, kind).map(({ id, text, xml: entryXml }) => {
|
||||
const richParas = noteRichParas(entryXml)
|
||||
const hasFormat = richParas.some((paras) =>
|
||||
paras.some(
|
||||
(r) => r.bold || r.italic || r.underline || r.strike || r.color || r.sizeHalfPoints,
|
||||
),
|
||||
)
|
||||
return { id, text, ...(hasFormat ? { richParas } : {}) }
|
||||
})
|
||||
}
|
||||
|
||||
/** Display runs per paragraph (bold/italic/underline/strike, color, size); the footnote self-reference mark run is skipped */
|
||||
function noteRichParas(entryXml: string): NoteRun[][] {
|
||||
const out: NoteRun[][] = []
|
||||
const pRe = /<w:p[\s>][\s\S]*?<\/w:p>|<w:p\/>/g
|
||||
let p: RegExpExecArray | null
|
||||
const flag = (rPr: string, tag: string) =>
|
||||
new RegExp(`<w:${tag}(?:\\s*/>|\\s(?![^>]*w:val="(?:0|false|none)")[^>]*/>)`).test(rPr)
|
||||
while ((p = pRe.exec(entryXml)) !== null) {
|
||||
const runs: NoteRun[] = []
|
||||
const rRe = /<w:r(?:\s[^>]*)?>([\s\S]*?)<\/w:r>/g
|
||||
let r: RegExpExecArray | null
|
||||
while ((r = rRe.exec(p[0])) !== null) {
|
||||
const inner = r[1]
|
||||
if (/<w:footnoteRef\/>|<w:endnoteRef\/>/.test(inner)) continue
|
||||
const text = notePlainText(inner)
|
||||
if (!text) continue
|
||||
const rPr = /<w:rPr>[\s\S]*?<\/w:rPr>/.exec(inner)?.[0] ?? ''
|
||||
const run: NoteRun = { text }
|
||||
if (flag(rPr, 'b')) run.bold = true
|
||||
if (flag(rPr, 'i')) run.italic = true
|
||||
// w:u is not a boolean prop: underline needs an explicit non-"none" w:val
|
||||
const uVal = /<w:u\s[^>]*w:val="([^"]*)"/.exec(rPr)?.[1]
|
||||
if (uVal && uVal !== 'none') run.underline = true
|
||||
if (flag(rPr, 'strike')) run.strike = true
|
||||
const color = /<w:color [^>]*w:val="([0-9A-Fa-f]{6})"/.exec(rPr)?.[1]
|
||||
if (color) run.color = color.toUpperCase()
|
||||
const sz = /<w:sz [^>]*w:val="(\d+)"/.exec(rPr)?.[1]
|
||||
if (sz) run.sizeHalfPoints = parseInt(sz, 10)
|
||||
runs.push(run)
|
||||
}
|
||||
out.push(runs)
|
||||
}
|
||||
// Strip the first paragraph's leading space (spacer after the self-reference mark)
|
||||
if (out[0]?.[0]) out[0][0].text = out[0][0].text.replace(/^\s+/, '')
|
||||
return out
|
||||
}
|
||||
|
||||
/** typeless (real) note entries with their exact XML slice + plain text */
|
||||
function noteEntriesOf(
|
||||
xml: string,
|
||||
kind: NoteKind,
|
||||
): Array<{ id: string; text: string; xml: string }> {
|
||||
const out: Array<{ id: string; text: string; xml: string }> = []
|
||||
const entry = ENTRY[kind]
|
||||
const re = new RegExp(`<${entry}(\\s[^>]*)?>([\\s\\S]*?)</${entry}>`, 'g')
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
const attrs = m[1] ?? ''
|
||||
if (/w:type="/.test(attrs)) continue // separator / continuation entries
|
||||
const id = /w:id="([^"]+)"/.exec(attrs)?.[1]
|
||||
if (!id) continue
|
||||
const paras: string[] = []
|
||||
const pRe = /<w:p[\s>][\s\S]*?<\/w:p>|<w:p\/>/g
|
||||
let p: RegExpExecArray | null
|
||||
while ((p = pRe.exec(m[2])) !== null) paras.push(notePlainText(p[0]))
|
||||
// the first paragraph starts with the self-reference mark + a spacer
|
||||
if (paras.length > 0) paras[0] = paras[0].replace(/^\s+/, '')
|
||||
out.push({ id, text: paras.join('\n'), xml: m[0] })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function notePlainText(xml: string): string {
|
||||
const texts: string[] = []
|
||||
const re = /<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) texts.push(m[1])
|
||||
return texts
|
||||
.join('')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&')
|
||||
}
|
||||
|
||||
/** default separator entries required by Word when the part is created fresh */
|
||||
function separatorEntries(kind: NoteKind): string {
|
||||
const entry = ENTRY[kind]
|
||||
return (
|
||||
`<${entry} w:type="separator" w:id="-1"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:separator/></w:r></w:p></${entry}>` +
|
||||
`<${entry} w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></${entry}>`
|
||||
)
|
||||
}
|
||||
|
||||
function noteEntryXml(kind: NoteKind, note: NoteInfo): string {
|
||||
const entry = ENTRY[kind]
|
||||
const refTag = kind === 'footnote' ? 'w:footnoteRef' : 'w:endnoteRef'
|
||||
const paras = note.text.split('\n').map((line, i) => {
|
||||
// OOXML convention: the note body starts with the self-reference mark
|
||||
const refRun =
|
||||
i === 0
|
||||
? `<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><${refTag}/></w:r>` +
|
||||
'<w:r><w:t xml:space="preserve"> </w:t></w:r>'
|
||||
: ''
|
||||
const textRun =
|
||||
line === '' ? '' : `<w:r><w:t xml:space="preserve">${escapeXmlText(line)}</w:t></w:r>`
|
||||
return `<w:p>${refRun}${textRun}</w:p>`
|
||||
})
|
||||
return `<${entry} w:id="${escapeXmlAttr(note.id)}">${paras.join('')}</${entry}>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate the notes part from the full desired list. Structural entries
|
||||
* (separator/continuation) from the original part are kept byte-identical;
|
||||
* when there is no original part, standard separators are created.
|
||||
* Surgical: existing entries whose text is unchanged keep their original bytes (inline
|
||||
* formatting, images, and hyperlinks are preserved); entries with changed text first try
|
||||
* an in-paragraph w:t-level patch (formatting still preserved), and only fall back to a
|
||||
* plain-text rebuild when patching fails (paragraph count changed, etc.).
|
||||
*/
|
||||
export function buildNotesXml(
|
||||
kind: NoteKind,
|
||||
notes: NoteInfo[],
|
||||
originalXml: string | null,
|
||||
): string {
|
||||
const entry = ENTRY[kind]
|
||||
let structural = ''
|
||||
const originals = new Map<string, { text: string; xml: string }>()
|
||||
if (originalXml) {
|
||||
const re = new RegExp(`<${entry}\\s[^>]*w:type="[^"]*"[^>]*>[\\s\\S]*?</${entry}>`, 'g')
|
||||
structural = (originalXml.match(re) ?? []).join('')
|
||||
for (const e of noteEntriesOf(originalXml, kind)) originals.set(e.id, e)
|
||||
}
|
||||
if (!structural) structural = separatorEntries(kind)
|
||||
const body = notes
|
||||
.map((n) => {
|
||||
const orig = originals.get(n.id)
|
||||
if (!orig) return noteEntryXml(kind, n)
|
||||
if (orig.text === n.text) return orig.xml
|
||||
const patched = patchParagraphTexts(orig.xml, n.text, {
|
||||
stripFirstParaLeadingSpace: true,
|
||||
})
|
||||
return patched ?? noteEntryXml(kind, n)
|
||||
})
|
||||
.join('')
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
`<${ROOT[kind]} ${NOTE_NS}>${structural}${body}</${ROOT[kind]}>`
|
||||
)
|
||||
}
|
||||
|
||||
/** next free numeric note id (separator ids -1/0 and existing notes considered) */
|
||||
export function nextNoteId(notes: NoteInfo[]): string {
|
||||
let max = 0
|
||||
for (const note of notes) {
|
||||
const n = parseInt(note.id, 10)
|
||||
if (Number.isFinite(n)) max = Math.max(max, n)
|
||||
}
|
||||
return String(max + 1)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,79 @@
|
||||
import type { DocProtection } from './types'
|
||||
|
||||
/**
|
||||
* w:documentProtection password hash (Word 2013+ scheme, ECMA-376 iterated hash):
|
||||
* h0 = H(salt || UTF-16LE(password))
|
||||
* hi = H(h(i-1) || LE32(i)) i = 0..spinCount-1
|
||||
* sid 14 = SHA-512 (the only implemented algorithm). Uses WebCrypto, so it works in
|
||||
* both the renderer process and Node 20+.
|
||||
*/
|
||||
|
||||
function toBase64(bytes: Uint8Array): string {
|
||||
let bin = ''
|
||||
for (const b of bytes) bin += String.fromCharCode(b)
|
||||
return btoa(bin)
|
||||
}
|
||||
|
||||
function fromBase64(b64: string): Uint8Array {
|
||||
const bin = atob(b64)
|
||||
const out = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
||||
return out
|
||||
}
|
||||
|
||||
function utf16le(text: string): Uint8Array {
|
||||
const out = new Uint8Array(text.length * 2)
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const code = text.charCodeAt(i)
|
||||
out[i * 2] = code & 0xff
|
||||
out[i * 2 + 1] = code >> 8
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
|
||||
const out = new Uint8Array(a.length + b.length)
|
||||
out.set(a, 0)
|
||||
out.set(b, a.length)
|
||||
return out
|
||||
}
|
||||
|
||||
async function iteratedSha512(
|
||||
password: string,
|
||||
salt: Uint8Array,
|
||||
spinCount: number,
|
||||
): Promise<Uint8Array> {
|
||||
const subtle = globalThis.crypto.subtle
|
||||
const digest = async (bytes: Uint8Array) =>
|
||||
new Uint8Array(await subtle.digest('SHA-512', bytes as unknown as ArrayBuffer))
|
||||
let hash = await digest(concat(salt, utf16le(password)))
|
||||
const iter = new Uint8Array(4)
|
||||
const view = new DataView(iter.buffer)
|
||||
for (let i = 0; i < spinCount; i++) {
|
||||
view.setUint32(0, i, true)
|
||||
hash = await digest(concat(hash, iter))
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
/** Generate the protection password hash (random 16-byte salt, 100000 iterations by default) */
|
||||
export async function hashProtectionPassword(
|
||||
password: string,
|
||||
spinCount = 100000,
|
||||
): Promise<{ hash: string; salt: string; spinCount: number; algorithmSid: number }> {
|
||||
const salt = globalThis.crypto.getRandomValues(new Uint8Array(16))
|
||||
const hash = await iteratedSha512(password, salt, spinCount)
|
||||
return { hash: toBase64(hash), salt: toBase64(salt), spinCount, algorithmSid: 14 }
|
||||
}
|
||||
|
||||
/** Check whether the password matches the hash in documentProtection (no hash = no password, always true) */
|
||||
export async function verifyProtectionPassword(
|
||||
password: string,
|
||||
protection: Pick<DocProtection, 'hash' | 'salt' | 'spinCount' | 'algorithmSid'>,
|
||||
): Promise<boolean> {
|
||||
if (!protection.hash) return true
|
||||
if ((protection.algorithmSid ?? 14) !== 14) return false // only SHA-512 is supported
|
||||
const salt = protection.salt ? fromBase64(protection.salt) : new Uint8Array(0)
|
||||
const hash = await iteratedSha512(password, salt, protection.spinCount ?? 100000)
|
||||
return toBase64(hash) === protection.hash
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Byte-exact scanner for word/document.xml.
|
||||
*
|
||||
* We never re-serialize the whole XML (parse->serialize would silently change
|
||||
* untouched bytes: attribute order, self-closing forms, entity forms...).
|
||||
* Instead we locate the exact character range of every top-level element in
|
||||
* <w:body> so that patch-save can splice new fragments while copying untouched
|
||||
* elements as raw original substrings.
|
||||
*/
|
||||
|
||||
export interface BodyElement {
|
||||
/** tag name, e.g. "w:p", "w:tbl", "w:sectPr" */
|
||||
name: string
|
||||
/** range [start, end) in the document.xml string */
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
export interface BodyScan {
|
||||
elements: BodyElement[]
|
||||
/** range [innerStart, innerEnd) spanning from the first top-level element start to the last element end */
|
||||
innerStart: number
|
||||
innerEnd: number
|
||||
}
|
||||
|
||||
// Matches one XML tag, tolerating '>' inside quoted attribute values.
|
||||
const TAG_RE = /<\/?(?:[^<>"']|"[^"]*"|'[^']*')*>/g
|
||||
const NAME_RE = /^<\/?\s*([A-Za-z_][\w:.-]*)/
|
||||
|
||||
export function scanBody(documentXml: string): BodyScan {
|
||||
const bodyOpenMatch = /<w:body(?:\s(?:[^<>"']|"[^"]*"|'[^']*')*)?>/.exec(documentXml)
|
||||
if (!bodyOpenMatch) {
|
||||
throw new Error('document.xml has no <w:body> element')
|
||||
}
|
||||
const scanFrom = bodyOpenMatch.index + bodyOpenMatch[0].length
|
||||
|
||||
const elements: BodyElement[] = []
|
||||
TAG_RE.lastIndex = scanFrom
|
||||
let depth = 0
|
||||
let currentStart = -1
|
||||
let currentName = ''
|
||||
let match: RegExpExecArray | null
|
||||
|
||||
while ((match = TAG_RE.exec(documentXml)) !== null) {
|
||||
const tag = match[0]
|
||||
// Skip comments / CDATA / processing instructions (rare in Word output).
|
||||
if (tag.startsWith('<!--') || tag.startsWith('<![') || tag.startsWith('<?')) continue
|
||||
const isClosing = tag.startsWith('</')
|
||||
const isSelfClosing = !isClosing && tag.endsWith('/>')
|
||||
const name = NAME_RE.exec(tag)?.[1] ?? ''
|
||||
|
||||
if (isClosing) {
|
||||
if (depth === 0) {
|
||||
if (name === 'w:body') break
|
||||
throw new Error(`unexpected closing tag </${name}> at body level`)
|
||||
}
|
||||
depth--
|
||||
if (depth === 0) {
|
||||
elements.push({ name: currentName, start: currentStart, end: match.index + tag.length })
|
||||
}
|
||||
} else if (isSelfClosing) {
|
||||
if (depth === 0) {
|
||||
elements.push({ name, start: match.index, end: match.index + tag.length })
|
||||
}
|
||||
} else {
|
||||
if (depth === 0) {
|
||||
currentStart = match.index
|
||||
currentName = name
|
||||
}
|
||||
depth++
|
||||
}
|
||||
}
|
||||
|
||||
if (elements.length === 0) {
|
||||
return { elements, innerStart: scanFrom, innerEnd: scanFrom }
|
||||
}
|
||||
return {
|
||||
elements,
|
||||
innerStart: elements[0].start,
|
||||
innerEnd: elements[elements.length - 1].end,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import type { ParsedDoc, SectionInfo, SectionSettings, DocGrid } from './types'
|
||||
|
||||
/** US Letter, portrait, 1-inch margins */
|
||||
export const DEFAULT_SECTION: SectionSettings = {
|
||||
pageWidth: 12240,
|
||||
pageHeight: 15840,
|
||||
orientation: 'portrait',
|
||||
marginTop: 1440,
|
||||
marginRight: 1440,
|
||||
marginBottom: 1440,
|
||||
marginLeft: 1440,
|
||||
pageBorder: false,
|
||||
columns: 1,
|
||||
headerDist: 720,
|
||||
footerDist: 720,
|
||||
}
|
||||
|
||||
/** Vertical alignment of page content (sectPr w:vAlign); top/default returns undefined */
|
||||
function vAlignOf(xml: string): 'center' | 'both' | 'bottom' | undefined {
|
||||
const v = /<w:vAlign w:val="(center|both|bottom)"\s*\/>/.exec(xml)?.[1]
|
||||
return v as 'center' | 'both' | 'bottom' | undefined
|
||||
}
|
||||
|
||||
function intAttr(tag: string, name: string, fallback: number): number {
|
||||
const m = new RegExp(`${name}="(-?\\d+)"`).exec(tag)
|
||||
const v = m ? parseInt(m[1], 10) : NaN
|
||||
return Number.isFinite(v) ? v : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* True when w:pgBorders declares at least one visible side. Word writes explicit
|
||||
* "no border" as side elements with w:val="none" (or "nil"), so the mere presence
|
||||
* of w:pgBorders must not be treated as a drawn border.
|
||||
*/
|
||||
function hasVisiblePageBorder(xml: string): boolean {
|
||||
const pgBorders = /<w:pgBorders[^>]*\/>|<w:pgBorders[\s\S]*?<\/w:pgBorders>/.exec(xml)?.[0]
|
||||
if (!pgBorders) return false
|
||||
const sides = pgBorders.match(/<w:(?:top|left|bottom|right)\b[^>]*\/?>/g) ?? []
|
||||
return sides.some((side) => {
|
||||
const val = /w:val="([^"]*)"/.exec(side)?.[1]
|
||||
return val !== undefined && val !== 'none' && val !== 'nil'
|
||||
})
|
||||
}
|
||||
|
||||
/** Page setup from one w:sectPr XML slice. */
|
||||
export function sectionSettingsFromXml(xml: string): SectionSettings {
|
||||
const pgSz = /<w:pgSz[^>]*\/?>/.exec(xml)?.[0] ?? ''
|
||||
const pgMar = /<w:pgMar[^>]*\/?>/.exec(xml)?.[0] ?? ''
|
||||
|
||||
// Parse docGrid (w:docGrid)
|
||||
let docGrid: DocGrid | undefined
|
||||
const docGridTag = /<w:docGrid[^>]*\/?>/.exec(xml)?.[0]
|
||||
if (docGridTag) {
|
||||
const typeMatch = /w:type="([^"]+)"/.exec(docGridTag)
|
||||
const linePitchMatch = /w:linePitch="(\d+)"/.exec(docGridTag)
|
||||
const charSpaceMatch = /w:charSpace="(-?\d+)"/.exec(docGridTag)
|
||||
const gridType = (typeMatch?.[1] ?? 'default') as DocGrid['type']
|
||||
const validTypes: DocGrid['type'][] = ['default', 'lines', 'linesAndChars', 'snapToChars']
|
||||
docGrid = {
|
||||
type: validTypes.includes(gridType) ? gridType : 'default',
|
||||
...(linePitchMatch ? { linePitch: parseInt(linePitchMatch[1], 10) } : {}),
|
||||
...(charSpaceMatch ? { charSpace: parseInt(charSpaceMatch[1], 10) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pageWidth: intAttr(pgSz, 'w:w', DEFAULT_SECTION.pageWidth),
|
||||
pageHeight: intAttr(pgSz, 'w:h', DEFAULT_SECTION.pageHeight),
|
||||
orientation: pgSz.includes('w:orient="landscape"') ? 'landscape' : 'portrait',
|
||||
marginTop: intAttr(pgMar, 'w:top', DEFAULT_SECTION.marginTop),
|
||||
marginRight: intAttr(pgMar, 'w:right', DEFAULT_SECTION.marginRight),
|
||||
marginBottom: intAttr(pgMar, 'w:bottom', DEFAULT_SECTION.marginBottom),
|
||||
marginLeft: intAttr(pgMar, 'w:left', DEFAULT_SECTION.marginLeft),
|
||||
headerDist: intAttr(pgMar, 'w:header', 720),
|
||||
footerDist: intAttr(pgMar, 'w:footer', 720),
|
||||
...(vAlignOf(xml) ? { vAlign: vAlignOf(xml) } : {}),
|
||||
pageBorder: hasVisiblePageBorder(xml),
|
||||
columns: intAttr(/<w:cols[^>]*\/?>/.exec(xml)?.[0] ?? '', 'w:num', 1),
|
||||
colSpace: intAttr(/<w:cols[^>]*\/?>/.exec(xml)?.[0] ?? '', 'w:space', 720),
|
||||
...(docGrid ? { docGrid } : {}),
|
||||
...(textDirectionOf(xml) ? { textDirection: textDirectionOf(xml) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function textDirectionOf(xml: string): string | undefined {
|
||||
const val = /<w:textDirection[^>]*w:val="([^"]+)"/.exec(xml)?.[1]
|
||||
return val && val !== 'lrTb' ? val : undefined
|
||||
}
|
||||
|
||||
/** Read page setup from the trailing (hidden) w:sectPr. */
|
||||
export function readSectionSettings(parsed: ParsedDoc): SectionSettings {
|
||||
const sectBlock = parsed.blocks.find((b) => b.hidden && b.originalXml?.includes('<w:sectPr'))
|
||||
return sectionSettingsFromXml(sectBlock?.originalXml ?? '')
|
||||
}
|
||||
|
||||
const SECT_PR_RE = /<w:sectPr[^>]*\/>|<w:sectPr[\s\S]*?<\/w:sectPr>/
|
||||
|
||||
function hfRefs(
|
||||
xml: string,
|
||||
kind: 'header' | 'footer',
|
||||
): Partial<Record<'default' | 'first' | 'even', string>> {
|
||||
const refs: Partial<Record<'default' | 'first' | 'even', string>> = {}
|
||||
for (const ref of xml.match(new RegExp(`<w:${kind}Reference[^>]*/>`, 'g')) ?? []) {
|
||||
const type = /w:type="(default|first|even)"/.exec(ref)?.[1] ?? 'default'
|
||||
const rId = /r:id="([^"]+)"/.exec(ref)?.[1]
|
||||
if (rId) refs[type as 'default' | 'first' | 'even'] = rId
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
||||
function sectionFromSectPr(
|
||||
sectPrXml: string,
|
||||
firstBlockIndex: number,
|
||||
lastBlockIndex: number,
|
||||
): SectionInfo {
|
||||
const type = /<w:type[^>]*w:val="(nextPage|continuous|evenPage|oddPage|nextColumn)"/.exec(
|
||||
sectPrXml,
|
||||
)?.[1]
|
||||
const pgNumStart = /<w:pgNumType[^>]*w:start="(\d+)"/.exec(sectPrXml)?.[1]
|
||||
const pgNumFmt = /<w:pgNumType[^>]*w:fmt="([^"]+)"/.exec(sectPrXml)?.[1]
|
||||
return {
|
||||
settings: sectionSettingsFromXml(sectPrXml),
|
||||
// nextColumn is rare; treat it as continuous (no forced page break)
|
||||
startType:
|
||||
type === 'nextColumn' ? 'continuous' : ((type as SectionInfo['startType']) ?? 'nextPage'),
|
||||
firstBlockIndex,
|
||||
lastBlockIndex,
|
||||
sectPrXml,
|
||||
titlePg: /<w:titlePg\s*\/>/.test(sectPrXml),
|
||||
...(pgNumStart !== undefined ? { pageNumberStart: parseInt(pgNumStart, 10) } : {}),
|
||||
...(pgNumFmt !== undefined ? { pageNumberFmt: pgNumFmt } : {}),
|
||||
headerRefs: hfRefs(sectPrXml, 'header'),
|
||||
footerRefs: hfRefs(sectPrXml, 'footer'),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite the sectPr page numbering w:pgNumType (fmt = number format, start = starting
|
||||
* page number; undefined fields are omitted, and the tag is removed when both are unset).
|
||||
* Schema order: pgNumType comes after pgMar/pgBorders and before cols/docGrid.
|
||||
*/
|
||||
export function applyPageNumType(
|
||||
sectPrXml: string,
|
||||
fmt: string | undefined,
|
||||
start: number | undefined,
|
||||
): string {
|
||||
let xml = sectPrXml.replace(/<w:pgNumType[^>]*\/>/, '')
|
||||
if (fmt === undefined && start === undefined) return xml
|
||||
const tag = `<w:pgNumType${fmt !== undefined ? ` w:fmt="${fmt}"` : ''}${start !== undefined ? ` w:start="${start}"` : ''}/>`
|
||||
if (/<w:cols[\s/>]/.test(xml)) xml = xml.replace(/(<w:cols[\s/>])/, `${tag}$1`)
|
||||
else if (/<w:docGrid/.test(xml)) xml = xml.replace(/(<w:docGrid)/, `${tag}$1`)
|
||||
else xml = xml.replace(/<\/w:sectPr>/, `${tag}</w:sectPr>`)
|
||||
return xml
|
||||
}
|
||||
|
||||
/**
|
||||
* Enumerate every section in document order. A paragraph-level w:sectPr
|
||||
* (section-break paragraph) closes its section; the trailing hidden sectPr closes the last.
|
||||
* Block ranges use docxIndex (body child order), boundaries inclusive.
|
||||
*/
|
||||
export function readSections(parsed: ParsedDoc): SectionInfo[] {
|
||||
const sections: SectionInfo[] = []
|
||||
let first = 0
|
||||
for (const block of parsed.blocks) {
|
||||
const xml = block.originalXml ?? ''
|
||||
if (block.docxIndex == null || !xml.includes('<w:sectPr')) continue
|
||||
const sectPrXml = SECT_PR_RE.exec(xml)?.[0]
|
||||
if (!sectPrXml) continue
|
||||
sections.push(sectionFromSectPr(sectPrXml, first, block.docxIndex))
|
||||
first = block.docxIndex + 1
|
||||
}
|
||||
if (sections.length === 0) {
|
||||
const last = parsed.blocks[parsed.blocks.length - 1]?.docxIndex ?? 0
|
||||
sections.push(sectionFromSectPr('', 0, last))
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
/** Rewrite pgSz / pgMar inside a w:sectPr XML slice, preserving everything else. */
|
||||
export function applySectionSettings(sectPrXml: string, settings: SectionSettings): string {
|
||||
const orient = settings.orientation === 'landscape' ? ' w:orient="landscape"' : ''
|
||||
const pgSz = `<w:pgSz w:w="${settings.pageWidth}" w:h="${settings.pageHeight}"${orient}/>`
|
||||
let xml = sectPrXml
|
||||
if (/<w:pgSz[^>]*\/?>/.test(xml)) {
|
||||
xml = xml.replace(/<w:pgSz[^>]*\/?>/, pgSz)
|
||||
} else {
|
||||
xml = xml.replace(/(<w:sectPr[^>]*>)/, `$1${pgSz}`)
|
||||
}
|
||||
const replaceMarAttr = (tag: string, name: string, value: number): string => {
|
||||
if (new RegExp(`${name}="`).test(tag)) {
|
||||
return tag.replace(new RegExp(`${name}="-?\\d+"`), `${name}="${value}"`)
|
||||
}
|
||||
return tag.replace(/\/>$/, ` ${name}="${value}"/>`)
|
||||
}
|
||||
const marMatch = /<w:pgMar[^>]*\/>/.exec(xml)
|
||||
if (marMatch) {
|
||||
let tag = marMatch[0]
|
||||
tag = replaceMarAttr(tag, 'w:top', settings.marginTop)
|
||||
tag = replaceMarAttr(tag, 'w:right', settings.marginRight)
|
||||
tag = replaceMarAttr(tag, 'w:bottom', settings.marginBottom)
|
||||
tag = replaceMarAttr(tag, 'w:left', settings.marginLeft)
|
||||
xml = xml.replace(marMatch[0], tag)
|
||||
} else {
|
||||
const pgMar =
|
||||
`<w:pgMar w:top="${settings.marginTop}" w:right="${settings.marginRight}"` +
|
||||
` w:bottom="${settings.marginBottom}" w:left="${settings.marginLeft}"` +
|
||||
' w:header="708" w:footer="708" w:gutter="0"/>'
|
||||
xml = xml.replace(/<\/w:sectPr>/, `${pgMar}</w:sectPr>`)
|
||||
}
|
||||
|
||||
// page border: single-line box measured from the page edge (pgBorders sits
|
||||
// between pgMar and cols in CT_SectPr)
|
||||
xml = xml.replace(/<w:pgBorders[^>]*\/>|<w:pgBorders[\s\S]*?<\/w:pgBorders>/, '')
|
||||
if (settings.pageBorder) {
|
||||
const side = (name: string) =>
|
||||
`<w:${name} w:val="single" w:sz="4" w:space="24" w:color="auto"/>`
|
||||
const pgBorders =
|
||||
'<w:pgBorders w:offsetFrom="page">' +
|
||||
`${side('top')}${side('left')}${side('bottom')}${side('right')}` +
|
||||
'</w:pgBorders>'
|
||||
xml = xml.replace(/(<w:pgMar[^>]*\/>)/, `$1${pgBorders}`)
|
||||
}
|
||||
|
||||
// columns (w:cols may be self-closing or carry explicit <w:col> children)
|
||||
const colsMatch = /<w:cols[^>]*\/>|<w:cols[^>]*>[\s\S]*?<\/w:cols>/.exec(xml)
|
||||
const numAttr = settings.columns > 1 ? ` w:num="${settings.columns}"` : ''
|
||||
if (colsMatch) {
|
||||
const openTag = /^<w:cols[^>]*>/.exec(colsMatch[0])?.[0] ?? colsMatch[0]
|
||||
const selfClosing = colsMatch[0].endsWith('/>')
|
||||
const currentNum = / w:num="(\d+)"/.exec(openTag)?.[1] ?? '1'
|
||||
if (selfClosing || currentNum !== String(settings.columns)) {
|
||||
// explicit per-column widths only stay valid while the count is unchanged
|
||||
let tag = openTag.replace(/ w:num="\d+"/, '').replace(/\/?>$/, '/>')
|
||||
if (numAttr) tag = tag.replace(/^<w:cols/, `<w:cols${numAttr}`)
|
||||
xml = xml.replace(colsMatch[0], tag)
|
||||
}
|
||||
} else if (numAttr) {
|
||||
const anchor = /(<w:pgBorders[\s\S]*?<\/w:pgBorders>|<w:pgMar[^>]*\/>)/.exec(xml)
|
||||
const cols = `<w:cols${numAttr} w:space="425"/>`
|
||||
if (anchor) xml = xml.replace(anchor[0], `${anchor[0]}${cols}`)
|
||||
else xml = xml.replace(/<\/w:sectPr>/, `${cols}</w:sectPr>`)
|
||||
}
|
||||
return xml
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite the sectPr start type w:type (how this section starts relative to the previous
|
||||
* one). nextPage is the default and is written by removing the tag; w:type comes before
|
||||
* pgSz in CT_SectPr.
|
||||
*/
|
||||
export function applySectionStartType(
|
||||
sectPrXml: string,
|
||||
type: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage',
|
||||
): string {
|
||||
let xml = sectPrXml.replace(/<w:type[^>]*\/>/, '')
|
||||
if (type === 'nextPage') return xml
|
||||
const tag = `<w:type w:val="${type}"/>`
|
||||
if (/<w:pgSz/.test(xml)) xml = xml.replace(/(<w:pgSz)/, `${tag}$1`)
|
||||
else xml = xml.replace(/(<w:sectPr[^>]*>)/, `$1${tag}`)
|
||||
return xml
|
||||
}
|
||||
|
||||
/** Read the page color (w:background) from document.xml; null when unset. */
|
||||
export function readPageColor(parsed: ParsedDoc): string | null {
|
||||
const m = /<w:background[^>]*w:color="([0-9A-Fa-f]{6})"/.exec(parsed.internal.documentXml)
|
||||
return m ? m[1].toUpperCase() : null
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import type JSZip from 'jszip'
|
||||
import type { SourceInfo } from './types'
|
||||
import { escapeXmlText } from './xml-utils'
|
||||
|
||||
/**
|
||||
* Bibliography sources live in a customXml part using the Word b:Sources
|
||||
* schema, so sources added here appear in Word's own citation manager.
|
||||
*/
|
||||
|
||||
export const SOURCES_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/bibliography'
|
||||
|
||||
export const CUSTOM_XML_REL_TYPE =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml'
|
||||
|
||||
/** find the zip path of the existing b:Sources custom xml part, if any */
|
||||
export async function findSourcesPart(zip: JSZip): Promise<string | null> {
|
||||
for (const name of Object.keys(zip.files)) {
|
||||
if (!/^customXml\/item\d+\.xml$/.test(name)) continue
|
||||
const xml = await zip.file(name)!.async('string')
|
||||
if (xml.includes('Sources') && xml.includes(SOURCES_NS)) return name
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function parseSourcesXml(xml: string): SourceInfo[] {
|
||||
const out: SourceInfo[] = []
|
||||
const re = /<b:Source>([\s\S]*?)<\/b:Source>/g
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
const body = m[1]
|
||||
const field = (tag: string) => {
|
||||
const f = new RegExp(`<b:${tag}>([\\s\\S]*?)</b:${tag}>`).exec(body)?.[1]
|
||||
return f ? decodeEntities(f.trim()) : undefined
|
||||
}
|
||||
const tag = field('Tag')
|
||||
if (!tag) continue
|
||||
// author: person name list (Last, First) or corporate name
|
||||
let author = field('Corporate') ?? ''
|
||||
if (!author) {
|
||||
const last = field('Last') ?? ''
|
||||
const first = field('First') ?? ''
|
||||
author = [last, first].filter(Boolean).join(', ')
|
||||
}
|
||||
out.push({
|
||||
tag,
|
||||
type: field('SourceType') ?? 'Misc',
|
||||
author,
|
||||
title: field('Title') ?? '',
|
||||
year: field('Year') ?? '',
|
||||
publisher: field('Publisher') ?? field('JournalName') ?? field('InternetSiteTitle'),
|
||||
url: field('URL'),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function decodeEntities(text: string): string {
|
||||
return text
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&')
|
||||
}
|
||||
|
||||
function sourceEntryXml(source: SourceInfo): string {
|
||||
const t = (tag: string, value: string | undefined) =>
|
||||
value ? `<b:${tag}>${escapeXmlText(value)}</b:${tag}>` : ''
|
||||
// "Last, First" splits into Last/First; anything else is stored as Last
|
||||
const comma = source.author.indexOf(',')
|
||||
const last = comma === -1 ? source.author : source.author.slice(0, comma).trim()
|
||||
const first = comma === -1 ? '' : source.author.slice(comma + 1).trim()
|
||||
const authorXml = source.author
|
||||
? '<b:Author><b:Author><b:NameList><b:Person>' +
|
||||
t('Last', last) +
|
||||
t('First', first) +
|
||||
'</b:Person></b:NameList></b:Author></b:Author>'
|
||||
: ''
|
||||
const publisherTag =
|
||||
source.type === 'JournalArticle'
|
||||
? 'JournalName'
|
||||
: source.type === 'InternetSite'
|
||||
? 'InternetSiteTitle'
|
||||
: 'Publisher'
|
||||
return (
|
||||
'<b:Source>' +
|
||||
t('Tag', source.tag) +
|
||||
t('SourceType', source.type) +
|
||||
authorXml +
|
||||
t('Title', source.title) +
|
||||
t('Year', source.year) +
|
||||
t(publisherTag, source.publisher) +
|
||||
t('URL', source.url) +
|
||||
'</b:Source>'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Surgical rebuild of b:Sources: unchanged b:Source entries keep their original bytes
|
||||
* (unmodeled fields like Editor/Volume/Pages/DOI/multi-author lists are preserved), the
|
||||
* root element attributes (SelectedStyle citation style) come from the original document,
|
||||
* and only new/edited entries are rebuilt from the modeled fields.
|
||||
*/
|
||||
export function buildSourcesXml(sources: SourceInfo[], originalXml: string | null = null): string {
|
||||
const originals = new Map<string, { xml: string; parsed: SourceInfo }>()
|
||||
let rootOpen =
|
||||
`<b:Sources SelectedStyle="\\APASixthEditionOfficeOnline.xsl" StyleName="APA" Version="6" xmlns:b="${SOURCES_NS}" xmlns="${SOURCES_NS}">`
|
||||
if (originalXml) {
|
||||
const open = /<b:Sources(?:\s[^>]*)?>/.exec(originalXml)?.[0]
|
||||
if (open) rootOpen = open
|
||||
for (const m of originalXml.match(/<b:Source>[\s\S]*?<\/b:Source>/g) ?? []) {
|
||||
const parsed = parseSourcesXml(m)[0]
|
||||
if (parsed) originals.set(parsed.tag, { xml: m, parsed })
|
||||
}
|
||||
}
|
||||
const unchanged = (a: SourceInfo, b: SourceInfo) =>
|
||||
a.type === b.type && a.author === b.author && a.title === b.title && a.year === b.year &&
|
||||
(a.publisher ?? '') === (b.publisher ?? '') && (a.url ?? '') === (b.url ?? '')
|
||||
const body = sources
|
||||
.map((s) => {
|
||||
const orig = originals.get(s.tag)
|
||||
return orig && unchanged(orig.parsed, s) ? orig.xml : sourceEntryXml(s)
|
||||
})
|
||||
.join('')
|
||||
return rootOpen + body + '</b:Sources>'
|
||||
}
|
||||
|
||||
export function buildSourcesItemPropsXml(): string {
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
'<ds:datastoreItem ds:itemID="{4A8D2934-D5B1-4C15-A6F4-7A1B2C3D4E5F}"' +
|
||||
' xmlns:ds="http://schemas.openxmlformats.org/officeDocument/2006/customXml">' +
|
||||
`<ds:schemaRefs><ds:schemaRef ds:uri="${SOURCES_NS}"/></ds:schemaRefs>` +
|
||||
'</ds:datastoreItem>'
|
||||
)
|
||||
}
|
||||
|
||||
/** in-text citation, e.g. "(Smith, 2024)" */
|
||||
export function citationText(source: SourceInfo): string {
|
||||
const author = source.author || source.title
|
||||
return source.year ? `(${author}, ${source.year})` : `(${author})`
|
||||
}
|
||||
|
||||
/** one bibliography line in a simple APA-like format */
|
||||
export function bibliographyLine(source: SourceInfo): string {
|
||||
const parts: string[] = []
|
||||
if (source.author) parts.push(source.author + '.')
|
||||
if (source.year) parts.push(`(${source.year}).`)
|
||||
if (source.title) parts.push(source.title + '.')
|
||||
if (source.publisher) parts.push(source.publisher + '.')
|
||||
if (source.url) parts.push(source.url)
|
||||
return parts.join(' ')
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* Symbol-encoded legacy fonts (Symbol / Wingdings / Webdings) carry glyphs at
|
||||
* arbitrary byte positions, stored either as that byte or as U+F0xx (private
|
||||
* use). Without the font installed they render as the raw letter or tofu, so
|
||||
* map the common glyphs to their Unicode equivalents for display.
|
||||
*/
|
||||
|
||||
const SYMBOL: Record<number, string> = {
|
||||
// Greek (Adobe Symbol layout: Latin letter position -> Greek letter)
|
||||
0x41: 'Α',
|
||||
0x42: 'Β',
|
||||
0x43: 'Χ',
|
||||
0x44: 'Δ',
|
||||
0x45: 'Ε',
|
||||
0x46: 'Φ',
|
||||
0x47: 'Γ',
|
||||
0x48: 'Η',
|
||||
0x49: 'Ι',
|
||||
0x4b: 'Κ',
|
||||
0x4c: 'Λ',
|
||||
0x4d: 'Μ',
|
||||
0x4e: 'Ν',
|
||||
0x4f: 'Ο',
|
||||
0x50: 'Π',
|
||||
0x51: 'Θ',
|
||||
0x52: 'Ρ',
|
||||
0x53: 'Σ',
|
||||
0x54: 'Τ',
|
||||
0x55: 'Υ',
|
||||
0x57: 'Ω',
|
||||
0x58: 'Ξ',
|
||||
0x59: 'Ψ',
|
||||
0x5a: 'Ζ',
|
||||
0x61: 'α',
|
||||
0x62: 'β',
|
||||
0x63: 'χ',
|
||||
0x64: 'δ',
|
||||
0x65: 'ε',
|
||||
0x66: 'φ',
|
||||
0x67: 'γ',
|
||||
0x68: 'η',
|
||||
0x69: 'ι',
|
||||
0x6b: 'κ',
|
||||
0x6c: 'λ',
|
||||
0x6d: 'μ',
|
||||
0x6e: 'ν',
|
||||
0x6f: 'ο',
|
||||
0x70: 'π',
|
||||
0x71: 'θ',
|
||||
0x72: 'ρ',
|
||||
0x73: 'σ',
|
||||
0x74: 'τ',
|
||||
0x75: 'υ',
|
||||
0x77: 'ω',
|
||||
0x78: 'ξ',
|
||||
0x79: 'ψ',
|
||||
0x7a: 'ζ',
|
||||
// math / arrows
|
||||
0x22: '∀',
|
||||
0x24: '∃',
|
||||
0xa3: '≤',
|
||||
0xa5: '∞',
|
||||
0xab: '↔',
|
||||
0xac: '←',
|
||||
0xad: '↑',
|
||||
0xae: '→',
|
||||
0xaf: '↓',
|
||||
0xb0: '°',
|
||||
0xb1: '±',
|
||||
0xb3: '≥',
|
||||
0xb4: '×',
|
||||
0xb6: '∂',
|
||||
0xb7: '•',
|
||||
0xb8: '÷',
|
||||
0xb9: '≠',
|
||||
0xba: '≡',
|
||||
0xbb: '≈',
|
||||
0xbc: '…',
|
||||
0xc4: '⊗',
|
||||
0xc5: '⊕',
|
||||
0xc6: '∅',
|
||||
0xc7: '∩',
|
||||
0xc8: '∪',
|
||||
0xc9: '⊃',
|
||||
0xcc: '⊂',
|
||||
0xce: '∈',
|
||||
0xd1: '∇',
|
||||
0xd5: '∏',
|
||||
0xd6: '√',
|
||||
0xd7: '⋅',
|
||||
0xd8: '¬',
|
||||
0xd9: '∧',
|
||||
0xda: '∨',
|
||||
0xe5: '∑',
|
||||
0xf2: '∫',
|
||||
}
|
||||
|
||||
const WINGDINGS: Record<number, string> = {
|
||||
0x21: '✏',
|
||||
0x22: '✂',
|
||||
0x28: '☎',
|
||||
0x2a: '✉',
|
||||
0x45: '☜',
|
||||
0x46: '☞',
|
||||
0x47: '☝',
|
||||
0x48: '☟',
|
||||
0x4a: '☺',
|
||||
0x4b: '😐',
|
||||
0x4c: '☹',
|
||||
0x6c: '●',
|
||||
0x6d: '❍',
|
||||
0x6e: '■',
|
||||
0x6f: '❑',
|
||||
0x70: '❒',
|
||||
0x75: '◆',
|
||||
0x76: '❖',
|
||||
0x78: '⌧',
|
||||
0xa7: '▪',
|
||||
0xa8: '□',
|
||||
0xab: '★',
|
||||
0xd8: '➢',
|
||||
0xfb: '✗',
|
||||
0xfc: '✓',
|
||||
0xfd: '☒',
|
||||
0xfe: '☑',
|
||||
}
|
||||
|
||||
const SYMBOL_FONT_MAPS: Record<string, Record<number, string>> = {
|
||||
symbol: SYMBOL,
|
||||
wingdings: WINGDINGS,
|
||||
// recognized as symbol-encoded so unmapped glyphs get sane fallbacks, but no table yet
|
||||
'wingdings 2': {},
|
||||
'wingdings 3': {},
|
||||
webdings: {},
|
||||
}
|
||||
|
||||
export function isSymbolFont(font: string | null | undefined): boolean {
|
||||
return !!font && font.trim().toLowerCase() in SYMBOL_FONT_MAPS
|
||||
}
|
||||
|
||||
/** glyph code (raw byte or its U+F0xx private-use form) → Unicode equivalent, null when unknown */
|
||||
export function decodeSymbolChar(font: string, code: number): string | null {
|
||||
const map = SYMBOL_FONT_MAPS[font.trim().toLowerCase()]
|
||||
if (!map) return null
|
||||
const low = code >= 0xf000 && code <= 0xf0ff ? code - 0xf000 : code
|
||||
return map[low] ?? null
|
||||
}
|
||||
|
||||
/** whole string decode; null unless every non-whitespace char maps */
|
||||
export function decodeSymbolText(font: string, text: string): string | null {
|
||||
if (!isSymbolFont(font)) return null
|
||||
let out = ''
|
||||
for (const ch of text) {
|
||||
const code = ch.codePointAt(0) as number
|
||||
if (code <= 0x20 || code === 0xa0) {
|
||||
out += ch
|
||||
continue
|
||||
}
|
||||
const mapped = decodeSymbolChar(font, code)
|
||||
if (mapped === null) return null
|
||||
out += mapped
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { escapeXmlText } from './xml-utils'
|
||||
|
||||
/**
|
||||
* Paragraph-level surgical text patch (saving edits to rich-text entries such as
|
||||
* comments/footnotes).
|
||||
*
|
||||
* Maps the edited plain text ('\n' between paragraphs, each paragraph = concatenated w:t)
|
||||
* back onto the original entry XML:
|
||||
* - Paragraphs whose text is unchanged keep their original bytes (inline formatting,
|
||||
* hyperlinks, images, and fields are all preserved)
|
||||
* - Changed paragraphs get a minimal w:t replacement: only the w:t outside the common
|
||||
* prefix/suffix are rewritten, other run bytes stay untouched
|
||||
* - If the paragraph count changed, or a changed paragraph has no w:t to anchor to,
|
||||
* returns null and the caller falls back to rebuilding the whole entry
|
||||
*
|
||||
* stripFirstParaLeadingSpace: footnote/endnote first paragraphs start with a
|
||||
* self-reference mark + space run, which the plain-text model drops; when enabled,
|
||||
* that leading whitespace is treated as an immutable prefix.
|
||||
*/
|
||||
export function patchParagraphTexts(
|
||||
entryXml: string,
|
||||
newText: string,
|
||||
opts: { stripFirstParaLeadingSpace?: boolean } = {},
|
||||
): string | null {
|
||||
const paras = paragraphSlices(entryXml)
|
||||
if (paras.length === 0) return null
|
||||
const oldParaTexts = paras.map((p, i) =>
|
||||
i === 0 && opts.stripFirstParaLeadingSpace
|
||||
? decodedTextOf(p.xml).replace(/^\s+/, '')
|
||||
: decodedTextOf(p.xml),
|
||||
)
|
||||
if (oldParaTexts.join('\n') === newText) return entryXml
|
||||
const newParaTexts = newText.split('\n')
|
||||
if (newParaTexts.length !== paras.length) return null
|
||||
|
||||
let out = ''
|
||||
let cursor = 0
|
||||
for (let i = 0; i < paras.length; i++) {
|
||||
const para = paras[i]
|
||||
out += entryXml.slice(cursor, para.start)
|
||||
if (oldParaTexts[i] === newParaTexts[i]) {
|
||||
out += para.xml
|
||||
} else {
|
||||
const skipLeading = i === 0 && opts.stripFirstParaLeadingSpace === true
|
||||
const patched = patchOneParagraph(para.xml, newParaTexts[i], skipLeading)
|
||||
if (patched === null) return null
|
||||
out += patched
|
||||
}
|
||||
cursor = para.end
|
||||
}
|
||||
out += entryXml.slice(cursor)
|
||||
|
||||
// Self-check: re-extracted text must match the target, otherwise abandon the surgical patch
|
||||
const check = paragraphSlices(out).map((p, i) =>
|
||||
i === 0 && opts.stripFirstParaLeadingSpace
|
||||
? decodedTextOf(p.xml).replace(/^\s+/, '')
|
||||
: decodedTextOf(p.xml),
|
||||
)
|
||||
return check.join('\n') === newText ? out : null
|
||||
}
|
||||
|
||||
interface ParaSlice {
|
||||
start: number
|
||||
end: number
|
||||
xml: string
|
||||
}
|
||||
|
||||
function paragraphSlices(xml: string): ParaSlice[] {
|
||||
// depth-aware scan: a paragraph may legally nest more <w:p> inside embedded
|
||||
// textbox content (w:txbxContent), so a lazy open-to-first-close match would
|
||||
// truncate the outer paragraph
|
||||
const out: ParaSlice[] = []
|
||||
const re = /<w:p(?:\s[^>]*)?\/>|<w:p(?:\s[^>]*)?>|<\/w:p>/g
|
||||
let m: RegExpExecArray | null
|
||||
let depth = 0
|
||||
let start = -1
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
const token = m[0]
|
||||
if (token === '</w:p>') {
|
||||
if (depth === 0) continue
|
||||
depth--
|
||||
if (depth === 0 && start !== -1) {
|
||||
const end = m.index + token.length
|
||||
out.push({ start, end, xml: xml.slice(start, end) })
|
||||
start = -1
|
||||
}
|
||||
} else if (token.endsWith('/>')) {
|
||||
if (depth === 0) out.push({ start: m.index, end: m.index + token.length, xml: token })
|
||||
} else {
|
||||
if (depth === 0) start = m.index
|
||||
depth++
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
interface TSlice {
|
||||
/** offsets of the inner content within the paragraph XML */
|
||||
innerStart: number
|
||||
innerEnd: number
|
||||
/** offset of the opening <w:t ...> tag */
|
||||
tagStart: number
|
||||
text: string
|
||||
}
|
||||
|
||||
function tSlices(paraXml: string): TSlice[] {
|
||||
const out: TSlice[] = []
|
||||
const re = /<w:t(\s[^>]*)?>([\s\S]*?)<\/w:t>/g
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(paraXml)) !== null) {
|
||||
const inner = m[2]
|
||||
const innerStart = m.index + m[0].length - inner.length - '</w:t>'.length
|
||||
out.push({
|
||||
tagStart: m.index,
|
||||
innerStart,
|
||||
innerEnd: innerStart + inner.length,
|
||||
text: decodeEntities(inner),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function decodedTextOf(paraXml: string): string {
|
||||
return tSlices(paraXml)
|
||||
.map((t) => t.text)
|
||||
.join('')
|
||||
}
|
||||
|
||||
function decodeEntities(s: string): string {
|
||||
return s
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&')
|
||||
}
|
||||
|
||||
function patchOneParagraph(paraXml: string, newText: string, skipLeading: boolean): string | null {
|
||||
const slices = tSlices(paraXml)
|
||||
if (slices.length === 0) return null
|
||||
const raw = slices.map((t) => t.text).join('')
|
||||
// First paragraph's leading whitespace (spacer run after the self-reference mark) is
|
||||
// excluded from the diff and treated as an immutable prefix
|
||||
const lead = skipLeading ? raw.length - raw.replace(/^\s+/, '').length : 0
|
||||
const oldText = raw.slice(lead)
|
||||
if (oldText === newText) return paraXml
|
||||
|
||||
let prefix = 0
|
||||
const maxCommon = Math.min(oldText.length, newText.length)
|
||||
while (prefix < maxCommon && oldText[prefix] === newText[prefix]) prefix++
|
||||
let suffix = 0
|
||||
while (
|
||||
suffix < maxCommon - prefix &&
|
||||
oldText[oldText.length - 1 - suffix] === newText[newText.length - 1 - suffix]
|
||||
) {
|
||||
suffix++
|
||||
}
|
||||
// Changed range (relative to the full raw text)
|
||||
const changeStart = lead + prefix
|
||||
const changeEnd = lead + oldText.length - suffix
|
||||
const replacement = newText.slice(prefix, newText.length - suffix)
|
||||
|
||||
// Find the w:t intersecting the changed range; for pure insertion (changeStart ===
|
||||
// changeEnd), take the slice covering that point
|
||||
let acc = 0
|
||||
let first = -1
|
||||
let last = -1
|
||||
const bounds: Array<{ start: number; end: number }> = []
|
||||
for (let i = 0; i < slices.length; i++) {
|
||||
const start = acc
|
||||
const end = acc + slices[i].text.length
|
||||
bounds.push({ start, end })
|
||||
const touches =
|
||||
changeStart === changeEnd
|
||||
? start <= changeStart && changeStart <= end
|
||||
: start < changeEnd && end > changeStart
|
||||
if (touches) {
|
||||
if (first === -1) first = i
|
||||
last = i
|
||||
}
|
||||
acc = end
|
||||
}
|
||||
if (first === -1) {
|
||||
// Insertion point falls outside every w:t (in theory only an empty paragraph) —
|
||||
// no anchor, give up
|
||||
return null
|
||||
}
|
||||
|
||||
// Rewrite [first..last]: first takes the prefix remainder + replacement text + last's
|
||||
// suffix remainder; the rest are emptied
|
||||
const newInner: string[] = []
|
||||
for (let i = first; i <= last; i++) {
|
||||
if (i === first) {
|
||||
const head = slices[i].text.slice(0, changeStart - bounds[i].start)
|
||||
const tail = slices[last].text.slice(changeEnd - bounds[last].start)
|
||||
newInner.push(escapeXmlText(head + replacement + tail))
|
||||
} else {
|
||||
newInner.push('')
|
||||
}
|
||||
}
|
||||
|
||||
// Replace back-to-front so offsets stay valid; changed w:t all get xml:space="preserve"
|
||||
let out = paraXml
|
||||
for (let i = last; i >= first; i--) {
|
||||
const s = slices[i]
|
||||
const closeEnd = s.innerEnd + '</w:t>'.length
|
||||
out =
|
||||
out.slice(0, s.tagStart) +
|
||||
`<w:t xml:space="preserve">${newInner[i - first]}</w:t>` +
|
||||
out.slice(closeEnd)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import type { ThemeColors, ThemeFonts } from './types'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
|
||||
/**
|
||||
* Theme part support (word/theme/theme1.xml). Theme fonts rewrite the
|
||||
* major/minor font pair; theme colors rewrite the a:clrScheme entries. Documents
|
||||
* whose styles reference theme fonts/colors re-render in Word accordingly.
|
||||
*/
|
||||
|
||||
export const THEME_PART_PATH = 'word/theme/theme1.xml'
|
||||
|
||||
export const THEME_REL_TYPE =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme'
|
||||
|
||||
export const THEME_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.theme+xml'
|
||||
|
||||
/** read the latin major/minor typefaces (+major east-asian) from theme1.xml */
|
||||
export function readThemeFonts(themeXml: string): ThemeFonts | null {
|
||||
const major = fontOf(themeXml, 'a:majorFont')
|
||||
const minor = fontOf(themeXml, 'a:minorFont')
|
||||
if (!major && !minor) return null
|
||||
const eaMatch = sectionOf(themeXml, 'a:minorFont')?.match(/<a:ea typeface="([^"]*)"/)
|
||||
return {
|
||||
major: major ?? '',
|
||||
minor: minor ?? '',
|
||||
...(eaMatch?.[1] ? { eastAsia: eaMatch[1] } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function sectionOf(xml: string, tag: string): string | null {
|
||||
return new RegExp(`<${tag}(?:\\s[^>]*)?>[\\s\\S]*?</${tag}>`).exec(xml)?.[0] ?? null
|
||||
}
|
||||
|
||||
function fontOf(xml: string, tag: string): string | null {
|
||||
const section = sectionOf(xml, tag)
|
||||
return section ? (/<a:latin typeface="([^"]*)"/.exec(section)?.[1] ?? null) : null
|
||||
}
|
||||
|
||||
/** rewrite the latin (and optional east-asian) typefaces of one font group */
|
||||
function applyFontGroup(xml: string, tag: string, typeface: string, eastAsia?: string): string {
|
||||
const section = sectionOf(xml, tag)
|
||||
if (!section) return xml
|
||||
let next = section.replace(/(<a:latin typeface=")[^"]*(")/, `$1${escapeXmlAttr(typeface)}$2`)
|
||||
if (eastAsia !== undefined) {
|
||||
next = next.replace(/(<a:ea typeface=")[^"]*(")/, `$1${escapeXmlAttr(eastAsia)}$2`)
|
||||
}
|
||||
return xml.replace(section, next)
|
||||
}
|
||||
|
||||
export function applyThemeFonts(themeXml: string, fonts: ThemeFonts): string {
|
||||
let xml = applyFontGroup(themeXml, 'a:majorFont', fonts.major, fonts.eastAsia)
|
||||
xml = applyFontGroup(xml, 'a:minorFont', fonts.minor, fonts.eastAsia)
|
||||
return xml
|
||||
}
|
||||
|
||||
const COLOR_TAGS = ['dk2', 'lt2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6'] as const
|
||||
|
||||
/** all clrScheme slots, including read-only ones (dk1/lt1 may be sysClr) */
|
||||
const READ_TAGS = ['dk1', 'lt1', ...COLOR_TAGS, 'hlink', 'folHlink'] as const
|
||||
|
||||
export function readThemeColors(themeXml: string): ThemeColors | null {
|
||||
const scheme = sectionOf(themeXml, 'a:clrScheme')
|
||||
if (!scheme) return null
|
||||
const out: ThemeColors = {}
|
||||
const name = /<a:clrScheme name="([^"]*)"/.exec(themeXml)?.[1]
|
||||
if (name) out.name = name
|
||||
for (const tag of READ_TAGS) {
|
||||
const m = new RegExp(
|
||||
`<a:${tag}>\\s*<a:(?:srgbClr val|sysClr[^>]*? lastClr)="([0-9A-Fa-f]{6})"`,
|
||||
).exec(scheme)
|
||||
if (m) out[tag] = m[1].toUpperCase()
|
||||
}
|
||||
return Object.keys(out).length > 0 ? out : null
|
||||
}
|
||||
|
||||
/** w:themeColor attribute value -> clrScheme slot (default clrSchemeMapping) */
|
||||
const THEME_COLOR_SLOTS: Record<string, keyof ThemeColors> = {
|
||||
dark1: 'dk1',
|
||||
text1: 'dk1',
|
||||
light1: 'lt1',
|
||||
background1: 'lt1',
|
||||
dark2: 'dk2',
|
||||
text2: 'dk2',
|
||||
light2: 'lt2',
|
||||
background2: 'lt2',
|
||||
accent1: 'accent1',
|
||||
accent2: 'accent2',
|
||||
accent3: 'accent3',
|
||||
accent4: 'accent4',
|
||||
accent5: 'accent5',
|
||||
accent6: 'accent6',
|
||||
hyperlink: 'hlink',
|
||||
followedHyperlink: 'folHlink',
|
||||
}
|
||||
|
||||
const SLOT_FALLBACK: Partial<Record<keyof ThemeColors, string>> = { dk1: '000000', lt1: 'FFFFFF' }
|
||||
|
||||
/**
|
||||
* Resolve a w:themeColor reference (+ optional w:themeTint / w:themeShade,
|
||||
* hex 00-FF) against the palette. sRGB per-channel approximation of Word's
|
||||
* tint/shade math — close enough for display; w:val stays authoritative on save.
|
||||
*/
|
||||
export function resolveThemeColor(
|
||||
themeColor: string,
|
||||
colors: ThemeColors,
|
||||
tint?: string,
|
||||
shade?: string,
|
||||
): string | null {
|
||||
const slot = THEME_COLOR_SLOTS[themeColor]
|
||||
if (!slot) return null
|
||||
const base = (colors[slot] as string | undefined) ?? SLOT_FALLBACK[slot]
|
||||
if (!base || !/^[0-9A-Fa-f]{6}$/.test(base)) return null
|
||||
let rgb = [0, 2, 4].map((i) => parseInt(base.slice(i, i + 2), 16))
|
||||
const factorOf = (hex?: string) => {
|
||||
const v = hex ? parseInt(hex, 16) : NaN
|
||||
return Number.isFinite(v) ? Math.max(0, Math.min(255, v)) / 255 : null
|
||||
}
|
||||
const s = factorOf(shade)
|
||||
if (s !== null) rgb = rgb.map((c) => c * s)
|
||||
const t = factorOf(tint)
|
||||
if (t !== null) rgb = rgb.map((c) => c * t + 255 * (1 - t))
|
||||
return rgb.map((c) => Math.round(c).toString(16).padStart(2, '0').toUpperCase()).join('')
|
||||
}
|
||||
|
||||
export function applyThemeColors(themeXml: string, colors: ThemeColors): string {
|
||||
let scheme = sectionOf(themeXml, 'a:clrScheme')
|
||||
if (!scheme) return themeXml
|
||||
const original = scheme
|
||||
for (const tag of COLOR_TAGS) {
|
||||
const value = colors[tag]
|
||||
if (!value) continue
|
||||
scheme = scheme.replace(
|
||||
new RegExp(`(<a:${tag}>\\s*<a:srgbClr val=")[0-9A-Fa-f]{6}(")`),
|
||||
`$1${value}$2`,
|
||||
)
|
||||
// sysClr entries (windowText etc.) are left alone; dk2/lt2 are usually srgbClr
|
||||
}
|
||||
let xml = themeXml.replace(original, scheme)
|
||||
if (colors.name) {
|
||||
xml = xml.replace(/(<a:clrScheme name=")[^"]*(")/, `$1${escapeXmlAttr(colors.name)}$2`)
|
||||
}
|
||||
return xml
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal but complete theme part for documents that have none (e.g. the
|
||||
* blank template). Word requires fmtScheme; this ships the standard Office
|
||||
* format scheme skeleton.
|
||||
*/
|
||||
export function buildThemeXml(fonts: ThemeFonts, colors: ThemeColors): string {
|
||||
const c = (tag: (typeof COLOR_TAGS)[number], fallback: string) =>
|
||||
`<a:${tag}><a:srgbClr val="${colors[tag] ?? fallback}"/></a:${tag}>`
|
||||
const font = (tag: string, typeface: string) =>
|
||||
`<${tag}><a:latin typeface="${escapeXmlAttr(typeface)}"/>` +
|
||||
`<a:ea typeface="${escapeXmlAttr(fonts.eastAsia ?? '')}"/><a:cs typeface=""/></${tag}>`
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
'<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office">' +
|
||||
'<a:themeElements>' +
|
||||
`<a:clrScheme name="${escapeXmlAttr(colors.name ?? 'Office')}">` +
|
||||
'<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>' +
|
||||
'<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>' +
|
||||
c('dk2', '44546A') +
|
||||
c('lt2', 'E7E6E6') +
|
||||
c('accent1', '4472C4') +
|
||||
c('accent2', 'ED7D31') +
|
||||
c('accent3', 'A5A5A5') +
|
||||
c('accent4', 'FFC000') +
|
||||
c('accent5', '5B9BD5') +
|
||||
c('accent6', '70AD47') +
|
||||
'<a:hlink><a:srgbClr val="0563C1"/></a:hlink>' +
|
||||
'<a:folHlink><a:srgbClr val="954F72"/></a:folHlink>' +
|
||||
'</a:clrScheme>' +
|
||||
`<a:fontScheme name="Office">${font('a:majorFont', fonts.major)}${font('a:minorFont', fonts.minor)}</a:fontScheme>` +
|
||||
'<a:fmtScheme name="Office">' +
|
||||
'<a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:fillStyleLst>' +
|
||||
'<a:lnStyleLst>' +
|
||||
'<a:ln w="6350"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' +
|
||||
'<a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' +
|
||||
'<a:ln w="19050"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' +
|
||||
'</a:lnStyleLst>' +
|
||||
'<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle>' +
|
||||
'<a:effectStyle><a:effectLst/></a:effectStyle>' +
|
||||
'<a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>' +
|
||||
'<a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst>' +
|
||||
'</a:fmtScheme>' +
|
||||
'</a:themeElements></a:theme>'
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,61 @@
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
|
||||
/**
|
||||
* Text watermark support. Word implements watermarks as a VML shape with a
|
||||
* v:textpath inside the page header; the shape floats behind the body text
|
||||
* on every page that uses that header.
|
||||
*/
|
||||
|
||||
/** namespaces the header part root needs when it carries a VML watermark */
|
||||
export const WATERMARK_NS =
|
||||
' xmlns:v="urn:schemas-microsoft-com:vml"' +
|
||||
' xmlns:o="urn:schemas-microsoft-com:office:office"' +
|
||||
' xmlns:w10="urn:schemas-microsoft-com:office:word"'
|
||||
|
||||
/** read the watermark text from a header part; null when it has none */
|
||||
export function readWatermarkText(headerXml: string): string | null {
|
||||
if (!headerXml.includes('<v:textpath')) return null
|
||||
const m = /<v:textpath[^>]*\bstring="([^"]*)"/.exec(headerXml)
|
||||
if (!m) return null
|
||||
const text = m[1]
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&')
|
||||
return text || null
|
||||
}
|
||||
|
||||
/**
|
||||
* The diagonal gray text watermark paragraph Word generates (shapetype 136 =
|
||||
* text-on-path). Lives as the first paragraph of the header part.
|
||||
*/
|
||||
export function watermarkParagraphXml(text: string): string {
|
||||
const shape =
|
||||
'<v:shape id="PowerPlusWaterMarkObject1" o:spid="_x0000_s2049" type="#_x0000_t136"' +
|
||||
' style="position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;' +
|
||||
'width:412.4pt;height:247.45pt;rotation:315;z-index:-251656192;' +
|
||||
'mso-position-horizontal:center;mso-position-horizontal-relative:margin;' +
|
||||
'mso-position-vertical:center;mso-position-vertical-relative:margin"' +
|
||||
' o:allowincell="f" fillcolor="silver" stroked="f">' +
|
||||
'<v:fill opacity=".5"/>' +
|
||||
`<v:textpath style="font-family:"DengXian";font-size:1pt" string="${escapeXmlAttr(text)}"/>` +
|
||||
'</v:shape>'
|
||||
const shapetype =
|
||||
'<v:shapetype id="_x0000_t136" coordsize="21600,21600" o:spt="136" adj="10800"' +
|
||||
' path="m@7,l@8,m@5,21600l@6,21600e">' +
|
||||
'<v:formulas>' +
|
||||
'<v:f eqn="sum #0 0 10800"/><v:f eqn="prod #0 2 1"/><v:f eqn="sum 21600 0 @1"/>' +
|
||||
'<v:f eqn="sum 0 0 @2"/><v:f eqn="sum 21600 0 @3"/><v:f eqn="if @0 @3 0"/>' +
|
||||
'<v:f eqn="if @0 21600 @1"/><v:f eqn="if @0 0 @2"/><v:f eqn="if @0 @4 21600"/>' +
|
||||
'<v:f eqn="mid @5 @6"/><v:f eqn="mid @8 @5"/><v:f eqn="mid @7 @8"/>' +
|
||||
'<v:f eqn="mid @6 @7"/><v:f eqn="sum @6 0 @5"/>' +
|
||||
'</v:formulas>' +
|
||||
'<v:path textpathok="t" o:connecttype="custom" o:connectlocs="@9,0;@10,10800;@11,21600;@12,10800"' +
|
||||
' o:connectangles="270,180,90,0"/>' +
|
||||
'<v:textpath on="t" fitshape="t"/>' +
|
||||
'<v:handles><v:h position="#0,bottomRight" xrange="6629,14971"/></v:handles>' +
|
||||
'<o:lock v:ext="edit" text="t" shapetype="t"/>' +
|
||||
'</v:shapetype>'
|
||||
return `<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:pict>${shapetype}${shape}</w:pict></w:r></w:p>`
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
|
||||
/** preserveOrder node shape from fast-xml-parser */
|
||||
export type XNode = Record<string, unknown>
|
||||
|
||||
export const xmlParser = new XMLParser({
|
||||
preserveOrder: true,
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '',
|
||||
trimValues: false,
|
||||
parseTagValue: false,
|
||||
parseAttributeValue: false,
|
||||
})
|
||||
|
||||
export function nameOf(node: XNode): string | undefined {
|
||||
return Object.keys(node).find((k) => k !== ':@' && k !== '#text')
|
||||
}
|
||||
|
||||
export function childrenOf(node: XNode): XNode[] {
|
||||
const name = nameOf(node)
|
||||
if (!name) return []
|
||||
const value = node[name]
|
||||
return Array.isArray(value) ? (value as XNode[]) : []
|
||||
}
|
||||
|
||||
export function attrsOf(node: XNode): Record<string, string> {
|
||||
return (node[':@'] as Record<string, string>) ?? {}
|
||||
}
|
||||
|
||||
export function textOf(node: XNode): string {
|
||||
let out = ''
|
||||
for (const child of childrenOf(node)) {
|
||||
if ('#text' in child) out += String(child['#text'])
|
||||
else out += textOf(child)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function findChild(node: XNode, name: string): XNode | undefined {
|
||||
return childrenOf(node).find((c) => nameOf(c) === name)
|
||||
}
|
||||
|
||||
export function findChildren(node: XNode, name: string): XNode[] {
|
||||
return childrenOf(node).filter((c) => nameOf(c) === name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Direct children with `name`, looking through w:sdt → w:sdtContent wrappers
|
||||
* (nested sdt included). Structured document tags may wrap table rows, cells
|
||||
* or paragraphs at any level; for display purposes the wrapper is transparent
|
||||
* (research-report templates wrap every field in an sdt).
|
||||
*/
|
||||
export function childrenThroughSdt(node: XNode, name: string): XNode[] {
|
||||
const out: XNode[] = []
|
||||
const visit = (n: XNode): void => {
|
||||
for (const child of childrenOf(n)) {
|
||||
const cn = nameOf(child)
|
||||
if (cn === name) out.push(child)
|
||||
else if (cn === 'w:sdt') {
|
||||
const content = findChild(child, 'w:sdtContent')
|
||||
if (content) visit(content)
|
||||
}
|
||||
}
|
||||
}
|
||||
visit(node)
|
||||
return out
|
||||
}
|
||||
|
||||
/** OOXML boolean property: present => true unless w:val says otherwise */
|
||||
export function boolProp(parent: XNode, name: string): boolean {
|
||||
const child = findChild(parent, name)
|
||||
if (!child) return false
|
||||
const val = attrsOf(child)['w:val']
|
||||
if (val === undefined) return true
|
||||
return !['0', 'false', 'none', 'off'].includes(val.toLowerCase())
|
||||
}
|
||||
|
||||
/**
|
||||
* w:u is NOT an OOXML boolean (CT_OnOff) — it is CT_Underline, where the
|
||||
* underline pattern lives entirely in w:val. A <w:u> with no w:val (e.g.
|
||||
* `<w:u w:color="415461"/>` as emitted by Pages/LibreOffice) means no
|
||||
* underline, matching how Word renders it.
|
||||
*/
|
||||
export function underlineProp(parent: XNode): boolean {
|
||||
const child = findChild(parent, 'w:u')
|
||||
if (!child) return false
|
||||
const val = attrsOf(child)['w:val']
|
||||
return val !== undefined && val !== 'none'
|
||||
}
|
||||
|
||||
/**
|
||||
* XNode → XML text (attribute order = parse order, empty elements self-close). Semantic
|
||||
* fidelity, not byte fidelity: used to store parse-tree fragments (e.g. a run's rPr) as
|
||||
* writable source slices.
|
||||
*/
|
||||
export function serializeXNode(node: XNode): string {
|
||||
if ('#text' in node) return escapeXmlText(String(node['#text']))
|
||||
const name = nameOf(node)
|
||||
if (!name) return ''
|
||||
const attrs = Object.entries(attrsOf(node))
|
||||
.map(([k, v]) => ` ${k}="${escapeXmlAttr(String(v))}"`)
|
||||
.join('')
|
||||
const inner = childrenOf(node).map(serializeXNode).join('')
|
||||
return inner === '' ? `<${name}${attrs}/>` : `<${name}${attrs}>${inner}</${name}>`
|
||||
}
|
||||
|
||||
// Control characters outside \t \n \r are illegal in XML 1.0 even when escaped
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ILLEGAL_XML_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g
|
||||
|
||||
export function escapeXmlText(text: string): string {
|
||||
return text
|
||||
.replace(ILLEGAL_XML_CHARS, '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
}
|
||||
|
||||
export function escapeXmlAttr(text: string): string {
|
||||
return escapeXmlText(text).replace(/"/g, '"')
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { mergePPrFormat, parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const BIDI_BODY =
|
||||
'<w:p><w:pPr><w:bidi/><w:jc w:val="right"/></w:pPr><w:r><w:t>כותרת</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:bidi/><w:jc w:val="left"/></w:pPr><w:r><w:t>שמאל</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:bidi/></w:pPr><w:r><w:t>ברירת מחדל</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>LTR right</w:t></w:r></w:p>'
|
||||
|
||||
describe('RTL paragraphs (w:bidi + Word jc left/right swap)', () => {
|
||||
it('parses bidi and stores the visual alignment (jc left/right swapped)', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: BIDI_BODY }))
|
||||
expect(doc.blocks[0].format).toMatchObject({ bidi: true, align: 'left' })
|
||||
expect(doc.blocks[1].format).toMatchObject({ bidi: true, align: 'right' })
|
||||
expect(doc.blocks[2].format?.bidi).toBe(true)
|
||||
expect(doc.blocks[2].format?.align).toBeUndefined()
|
||||
// non-bidi paragraphs are not swapped
|
||||
expect(doc.blocks[3].format?.bidi).toBeUndefined()
|
||||
expect(doc.blocks[3].format?.align).toBe('right')
|
||||
})
|
||||
|
||||
it('keeps untouched bidi paragraphs byte-identical', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: BIDI_BODY })
|
||||
const doc = await parseDocx(bytes)
|
||||
const blocks = doc.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
|
||||
expect(await saveDocx(doc, blocks)).toEqual(bytes)
|
||||
})
|
||||
|
||||
it('mergePPrFormat writes the logical jc back and keeps a single w:bidi', () => {
|
||||
const out = mergePPrFormat('<w:pPr><w:bidi/><w:jc w:val="right"/></w:pPr>', {
|
||||
bidi: true,
|
||||
align: 'left',
|
||||
})
|
||||
expect(out.match(/<w:bidi\/>/g)).toHaveLength(1)
|
||||
expect(out).toContain('<w:jc w:val="right"/>')
|
||||
// visual right maps back to logical left
|
||||
const out2 = mergePPrFormat('<w:pPr><w:bidi/><w:jc w:val="left"/></w:pPr>', {
|
||||
bidi: true,
|
||||
align: 'right',
|
||||
})
|
||||
expect(out2).toContain('<w:jc w:val="left"/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('RTL tables (tblPr w:bidiVisual)', () => {
|
||||
it('parses bidiVisual into the table model', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblPr><w:bidiVisual/><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>א</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(doc.blocks[0].table?.bidiVisual).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
BLANK_BULLET_NUM_ID,
|
||||
BLANK_ORDERED_NUM_ID,
|
||||
buildBlankDocx,
|
||||
parseDocx,
|
||||
saveDocx,
|
||||
type SaveBlock,
|
||||
} from '../src/index'
|
||||
|
||||
describe('blank document template (new-document / AI generation base)', () => {
|
||||
it('parses to a single empty paragraph with standard heading styles available', async () => {
|
||||
const bytes = await buildBlankDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
expect(visible).toHaveLength(1)
|
||||
expect(visible[0].type).toBe('paragraph')
|
||||
for (const styleId of ['Heading1', 'Heading2', 'Heading3', 'Heading6']) {
|
||||
expect(doc.styles.has(styleId), styleId).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('AI-generated content (headings, paragraphs, lists) saves and reparses correctly', async () => {
|
||||
const bytes = await buildBlankDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
|
||||
const generated: SaveBlock[] = [
|
||||
{ kind: 'generated', block: { type: 'heading', level: 1, runs: [{ text: '生成的标题' }] } },
|
||||
{ kind: 'generated', block: { type: 'paragraph', runs: [{ text: '正文段落,', bold: false }, { text: '重点', bold: true }] } },
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'listItem',
|
||||
list: { kind: 'bullet', numId: BLANK_BULLET_NUM_ID, ilvl: 0 },
|
||||
runs: [{ text: '无序项' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'listItem',
|
||||
list: { kind: 'ordered', numId: BLANK_ORDERED_NUM_ID, ilvl: 0 },
|
||||
runs: [{ text: '有序项' }],
|
||||
},
|
||||
},
|
||||
]
|
||||
const saved = await saveDocx(doc, generated)
|
||||
const reparsed = await parseDocx(saved)
|
||||
const visible = reparsed.blocks.filter((b) => !b.hidden)
|
||||
|
||||
expect(visible.map((b) => b.type)).toEqual(['heading', 'paragraph', 'listItem', 'listItem'])
|
||||
expect(visible[0].level).toBe(1)
|
||||
expect(visible[0].runs?.map((r) => r.text).join('')).toBe('生成的标题')
|
||||
expect(visible[1].runs?.some((r) => r.bold && r.text === '重点')).toBe(true)
|
||||
expect(visible[2].list?.kind).toBe('bullet')
|
||||
expect(visible[3].list?.kind).toBe('ordered')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateParagraphXml, parseDocx, saveDocx, type GenerateContext } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const GEN_CTX: GenerateContext = {
|
||||
headingStyleIds: new Map([[1, 'Heading1']]),
|
||||
allocateHyperlinkRel: () => 'rId999',
|
||||
}
|
||||
|
||||
const BOOKMARKED_PARA =
|
||||
'<w:p><w:bookmarkStart w:id="3" w:name="市场规模"/><w:bookmarkEnd w:id="3"/>' +
|
||||
'<w:bookmarkStart w:id="4" w:name="_GoBack"/><w:bookmarkEnd w:id="4"/>' +
|
||||
'<w:r><w:t>2025 年市场规模达到 1200 亿。</w:t></w:r></w:p>'
|
||||
|
||||
const REF_PARA =
|
||||
'<w:p><w:r><w:t xml:space="preserve">详见</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> REF 市场规模 \\h </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:t>2025 年市场规模达到 1200 亿。</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'<w:r><w:t xml:space="preserve">一节。</w:t></w:r></w:p>'
|
||||
|
||||
describe('bookmarks', () => {
|
||||
it('parses user bookmarks and splits Word internals into hiddenBookmarks', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: BOOKMARKED_PARA }))
|
||||
expect(doc.blocks[0].type).toBe('paragraph')
|
||||
expect(doc.blocks[0].bookmarks).toEqual(['市场规模'])
|
||||
expect(doc.blocks[0].hiddenBookmarks).toEqual(['_GoBack'])
|
||||
})
|
||||
|
||||
it('re-emits hidden (_Ref/_Toc) bookmarks on regeneration so REF anchors survive editing', async () => {
|
||||
const body =
|
||||
'<w:p><w:bookmarkStart w:id="7" w:name="_Ref12345"/><w:bookmarkEnd w:id="7"/>' +
|
||||
'<w:r><w:t>被引用的段落。</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.hiddenBookmarks).toEqual(['_Ref12345'])
|
||||
// Rebuild after editing the paragraph text → the _Ref bookmark survives (lost here
|
||||
// before the broken-link fix)
|
||||
const saved = await saveDocx(doc, [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
hiddenBookmarks: block.hiddenBookmarks,
|
||||
runs: [{ text: '改过的段落。' }],
|
||||
},
|
||||
},
|
||||
])
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.blocks[0].hiddenBookmarks).toEqual(['_Ref12345'])
|
||||
})
|
||||
|
||||
it('re-emits bookmarkStart/End pairs on regeneration', () => {
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', bookmarks: ['目标位置'], runs: [{ text: '正文' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
const id = /<w:bookmarkStart w:id="(\d+)" w:name="目标位置"\/>/.exec(xml)?.[1]
|
||||
expect(id).toBeTruthy()
|
||||
expect(xml).toContain(`<w:bookmarkEnd w:id="${id}"/>`)
|
||||
expect(xml.indexOf('<w:bookmarkStart')).toBeLessThan(xml.indexOf('<w:r>'))
|
||||
})
|
||||
|
||||
it('round-trips bookmarks through generate -> parse', async () => {
|
||||
const para = generateParagraphXml(
|
||||
{ type: 'paragraph', bookmarks: ['章节A'], runs: [{ text: 'x' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
expect(doc.blocks[0].bookmarks).toEqual(['章节A'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('cross-references (REF fields)', () => {
|
||||
it('keeps REF paragraphs editable and folds the field into Run.refField', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: REF_PARA }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('paragraph')
|
||||
const runs = block.runs!
|
||||
expect(runs.map((r) => r.text)).toEqual(['详见', '2025 年市场规模达到 1200 亿。', '一节。'])
|
||||
expect(runs[1].refField).toBe('市场规模')
|
||||
expect(runs[0].refField).toBeUndefined()
|
||||
})
|
||||
|
||||
it('regenerates the full REF field with cached display text', () => {
|
||||
const xml = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
runs: [{ text: '见' }, { text: '第一章', refField: 'chap1' }, { text: '。' }],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:instrText xml:space="preserve"> REF chap1 \\h </w:instrText>')
|
||||
expect(xml).toContain('<w:fldChar w:fldCharType="separate"/>')
|
||||
expect(xml).toContain('<w:t xml:space="preserve">第一章</w:t>')
|
||||
expect(xml.indexOf('fldCharType="begin"')).toBeLessThan(xml.indexOf('第一章'))
|
||||
expect(xml.indexOf('第一章')).toBeLessThan(xml.indexOf('fldCharType="end"'))
|
||||
})
|
||||
|
||||
it('round-trips a REF run through generate -> parse', async () => {
|
||||
const para = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ text: '目标内容', refField: 'target' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
expect(doc.blocks[0].runs![0]).toMatchObject({ text: '目标内容', refField: 'target' })
|
||||
})
|
||||
|
||||
it('keeps untouched bookmark/REF paragraphs byte-identical on save', async () => {
|
||||
const source = await buildDocx({ bodyXml: BOOKMARKED_PARA + REF_PARA })
|
||||
const parsed = await parseDocx(source)
|
||||
const saved = await saveDocx(parsed, [
|
||||
{ kind: 'original', docxIndex: 0 },
|
||||
{ kind: 'original', docxIndex: 1 },
|
||||
])
|
||||
expect(saved).toEqual(source)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,127 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applySectionSettings,
|
||||
buildChartWorkbookXlsxBase64,
|
||||
latexToOmml,
|
||||
nextNoteId,
|
||||
ommlToLatex,
|
||||
parseDocx,
|
||||
patchChartWorkbookXlsxBase64,
|
||||
readSections,
|
||||
saveDocx,
|
||||
sectionSettingsFromXml,
|
||||
type SaveBlock,
|
||||
} from '../src/index'
|
||||
import { patchParagraphTexts } from '../src/text-patch'
|
||||
import { escapeXmlText } from '../src/xml-utils'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const P = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
|
||||
|
||||
describe('saveDocx isUnchanged short-circuit', () => {
|
||||
it('a sectionStartType-only edit is not silently dropped', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: P('a') + P('b') })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const visible: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
const saved = await saveDocx(parsed, visible, { sectionStartType: 'continuous' })
|
||||
expect(saved).not.toBe(bytes)
|
||||
const sections = readSections(await parseDocx(saved))
|
||||
expect(sections[0].startType).toBe('continuous')
|
||||
})
|
||||
})
|
||||
|
||||
describe('applySectionSettings w:cols', () => {
|
||||
const SECT_PR =
|
||||
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>' +
|
||||
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
|
||||
'<w:cols w:num="3" w:space="720">' +
|
||||
'<w:col w:w="3000" w:space="720"/><w:col w:w="3600" w:space="720"/><w:col w:w="2000"/>' +
|
||||
'</w:cols></w:sectPr>'
|
||||
|
||||
it('keeps explicit column widths when the count is unchanged', () => {
|
||||
const settings = sectionSettingsFromXml(SECT_PR)
|
||||
expect(settings.columns).toBe(3)
|
||||
const out = applySectionSettings(SECT_PR, settings)
|
||||
expect(out.match(/<w:cols[\s>]/g)?.length).toBe(1)
|
||||
expect(out).toContain('<w:col w:w="3000"')
|
||||
})
|
||||
|
||||
it('replaces the open-form element without duplicating it when the count changes', () => {
|
||||
const settings = sectionSettingsFromXml(SECT_PR)
|
||||
const out = applySectionSettings(SECT_PR, { ...settings, columns: 2 })
|
||||
expect(out.match(/<w:cols[\s>]/g)?.length).toBe(1)
|
||||
expect(out).toContain('w:num="2"')
|
||||
expect(out).not.toContain('<w:col w:w=')
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchParagraphTexts with nested textbox paragraphs', () => {
|
||||
const ENTRY =
|
||||
'<w:comment w:id="1">' +
|
||||
'<w:p><w:r><w:t xml:space="preserve">outer </w:t></w:r>' +
|
||||
'<w:r><w:drawing><wps:txbx><w:txbxContent>' +
|
||||
'<w:p><w:r><w:t>inside box</w:t></w:r></w:p>' +
|
||||
'</w:txbxContent></wps:txbx></w:drawing></w:r>' +
|
||||
'<w:r><w:t>tail</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>second</w:t></w:r></w:p>' +
|
||||
'</w:comment>'
|
||||
|
||||
it('slices the outer paragraph past the embedded w:p and patches surgically', () => {
|
||||
const out = patchParagraphTexts(ENTRY, 'outer inside boxtail\nsecond edited')
|
||||
expect(out).not.toBeNull()
|
||||
// the textbox structure of the untouched paragraph survives byte-for-byte
|
||||
expect(out).toContain(
|
||||
'<w:txbxContent><w:p><w:r><w:t>inside box</w:t></w:r></w:p></w:txbxContent>',
|
||||
)
|
||||
expect(out).toContain('second edited')
|
||||
expect(out).toContain('<w:rPr><w:b/></w:rPr>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('escapeXmlText', () => {
|
||||
it('strips control characters that are illegal in XML 1.0 but keeps tab/newline', () => {
|
||||
expect(escapeXmlText('a\u0000b\u000Bc\td\ne')).toBe('abc\td\ne')
|
||||
expect(escapeXmlText('<a & b>')).toBe('<a & b>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('nextNoteId', () => {
|
||||
it('starts at 1 for a document with no existing notes', () => {
|
||||
expect(nextNoteId([])).toBe('1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ommlToLatex matrix environments', () => {
|
||||
it('recovers the named pmatrix environment instead of generic delimiters', () => {
|
||||
const omml = `<m:oMath>${latexToOmml('\\begin{pmatrix} 1 & 0 \\\\ 0 & 1 \\end{pmatrix}')}</m:oMath>`
|
||||
expect(ommlToLatex(omml)).toContain('\\begin{pmatrix}')
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchChartWorkbookXlsxBase64', () => {
|
||||
it('preserves unrelated workbook parts and updates Sheet1 in place', async () => {
|
||||
const base = await buildChartWorkbookXlsxBase64(['a', 'b'], [{ name: 'S1', values: [1, 2] }])
|
||||
const zip = await JSZip.loadAsync(Buffer.from(base, 'base64'))
|
||||
zip.file('xl/styles.xml', '<styleSheet/>')
|
||||
zip.file('xl/worksheets/sheet2.xml', '<worksheet><sheetData/></worksheet>')
|
||||
const withExtras = Buffer.from(await zip.generateAsync({ type: 'uint8array' })).toString(
|
||||
'base64',
|
||||
)
|
||||
|
||||
const patched = await patchChartWorkbookXlsxBase64(
|
||||
withExtras,
|
||||
['x', 'y'],
|
||||
[{ name: 'S1', values: [9, 8] }],
|
||||
)
|
||||
expect(patched).not.toBeNull()
|
||||
const outZip = await JSZip.loadAsync(Buffer.from(patched!, 'base64'))
|
||||
expect(outZip.file('xl/styles.xml')).toBeTruthy()
|
||||
expect(outZip.file('xl/worksheets/sheet2.xml')).toBeTruthy()
|
||||
const sheet = await outZip.file('xl/worksheets/sheet1.xml')!.async('string')
|
||||
expect(sheet).toContain('<v>9</v>')
|
||||
expect(sheet).toContain('>x</t>')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,198 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateParagraphXml, parseDocx, type GenerateContext } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const GEN_CTX: GenerateContext = {
|
||||
headingStyleIds: new Map([[1, 'Heading1']]),
|
||||
allocateHyperlinkRel: () => 'rId999',
|
||||
}
|
||||
|
||||
const EMPHASIS_STYLES =
|
||||
'<w:style w:type="character" w:styleId="Strong"><w:name w:val="Strong"/>' +
|
||||
'<w:rPr><w:b/><w:color w:val="C00000"/></w:rPr></w:style>' +
|
||||
'<w:style w:type="character" w:styleId="Emphasis"><w:name w:val="Emphasis"/><w:basedOn w:val="Strong"/>' +
|
||||
'<w:rPr><w:i/><w:u w:val="single"/></w:rPr></w:style>'
|
||||
|
||||
describe('character styles (w:rStyle)', () => {
|
||||
it('parses character styles into the styles map with resolved basedOn display', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
extraStylesXml: EMPHASIS_STYLES,
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const strong = doc.styles.get('Strong')!
|
||||
expect(strong.type).toBe('character')
|
||||
expect(strong.display).toMatchObject({ bold: true, color: 'C00000' })
|
||||
const emphasis = doc.styles.get('Emphasis')!
|
||||
// inherits bold/color from Strong, adds its own italic/underline
|
||||
expect(emphasis.display).toMatchObject({
|
||||
bold: true,
|
||||
color: 'C00000',
|
||||
italic: true,
|
||||
underline: true,
|
||||
})
|
||||
expect(doc.styles.get('Hyperlink')!.display).toMatchObject({ underline: true, color: '0563C1' })
|
||||
})
|
||||
|
||||
it('captures w:rStyle on runs, except the implied Hyperlink style', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:rStyle w:val="Emphasis"/></w:rPr><w:t>styled</w:t></w:r>' +
|
||||
'<w:r><w:t>plain</w:t></w:r>' +
|
||||
'<w:hyperlink r:id="rId20"><w:r><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>link</w:t></w:r></w:hyperlink></w:p>',
|
||||
extraStylesXml: EMPHASIS_STYLES,
|
||||
extraRels:
|
||||
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/" TargetMode="External"/>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const runs = doc.blocks[0].runs!
|
||||
expect(runs[0].styleId).toBe('Emphasis')
|
||||
expect(runs[1].styleId).toBeUndefined()
|
||||
expect(runs[2].link?.href).toBe('https://example.com/')
|
||||
expect(runs[2].styleId).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not merge adjacent runs with different character styles', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:rStyle w:val="Strong"/></w:rPr><w:t>a</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:rStyle w:val="Emphasis"/></w:rPr><w:t>b</w:t></w:r></w:p>',
|
||||
extraStylesXml: EMPHASIS_STYLES,
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].runs!.map((r) => r.styleId)).toEqual(['Strong', 'Emphasis'])
|
||||
})
|
||||
|
||||
it('regenerates w:rStyle first in rPr schema order', () => {
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ text: 'x', styleId: 'Emphasis', bold: true, font: '宋体' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:rStyle w:val="Emphasis"/>')
|
||||
expect(xml.indexOf('<w:rStyle')).toBeLessThan(xml.indexOf('<w:rFonts'))
|
||||
})
|
||||
|
||||
it('round-trips styleId through generate -> parse', async () => {
|
||||
const para = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ text: '强调', styleId: 'Emphasis' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
const bytes = await buildDocx({ bodyXml: para, extraStylesXml: EMPHASIS_STYLES })
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].runs![0].styleId).toBe('Emphasis')
|
||||
})
|
||||
|
||||
it('resolves paragraph style basedOn chains and survives cycles', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
extraStylesXml:
|
||||
'<w:style w:type="paragraph" w:styleId="Base"><w:name w:val="Base"/>' +
|
||||
'<w:rPr><w:rFonts w:ascii="Georgia"/><w:sz w:val="20"/></w:rPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Base"/>' +
|
||||
'<w:rPr><w:i/></w:rPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="CycA"><w:name w:val="CycA"/><w:basedOn w:val="CycB"/></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="CycB"><w:name w:val="CycB"/><w:basedOn w:val="CycA"/></w:style>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.styles.get('Quote')!.display).toMatchObject({
|
||||
italic: true,
|
||||
font: 'Georgia',
|
||||
sizeHalfPoints: 20,
|
||||
})
|
||||
expect(doc.styles.get('CycA')).toBeDefined()
|
||||
expect(doc.styles.get('CycB')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('linkedStyle (w:link) and docDefaults backfill', () => {
|
||||
it('when a character-style shell has no rPr, run-level display attributes come from the linked paragraph style', async () => {
|
||||
const styles =
|
||||
'<w:style w:type="paragraph" w:styleId="Heading9"><w:name w:val="heading 9"/>' +
|
||||
'<w:link w:val="Heading9Char"/>' +
|
||||
'<w:rPr><w:b/><w:color w:val="2F5496"/><w:sz w:val="24"/></w:rPr></w:style>' +
|
||||
'<w:style w:type="character" w:styleId="Heading9Char"><w:name w:val="标题 9 字符"/>' +
|
||||
'<w:link w:val="Heading9"/></w:style>'
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>', extraStylesXml: styles }),
|
||||
)
|
||||
expect(doc.styles.get('Heading9Char')!.display).toMatchObject({
|
||||
bold: true,
|
||||
color: '2F5496',
|
||||
sizeHalfPoints: 24,
|
||||
})
|
||||
// A style's own properties are not overridden by the link
|
||||
const styles2 =
|
||||
'<w:style w:type="paragraph" w:styleId="Quote2"><w:name w:val="Quote2"/>' +
|
||||
'<w:link w:val="Quote2Char"/><w:rPr><w:i/><w:color w:val="404040"/></w:rPr></w:style>' +
|
||||
'<w:style w:type="character" w:styleId="Quote2Char"><w:name w:val="Quote2 Char"/>' +
|
||||
'<w:link w:val="Quote2"/><w:rPr><w:color w:val="FF0000"/></w:rPr></w:style>'
|
||||
const doc2 = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>', extraStylesXml: styles2 }),
|
||||
)
|
||||
expect(doc2.styles.get('Quote2Char')!.display).toMatchObject({ italic: true, color: 'FF0000' })
|
||||
})
|
||||
|
||||
it('docDefaults parses bold/italic/color from rPrDefault', async () => {
|
||||
const zipBytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' })
|
||||
// buildDocx's styles.xml has no docDefaults: inject it manually
|
||||
const JSZip = (await import('jszip')).default
|
||||
const zip = await JSZip.loadAsync(zipBytes)
|
||||
const stylesXml = await zip.file('word/styles.xml')!.async('string')
|
||||
zip.file(
|
||||
'word/styles.xml',
|
||||
stylesXml.replace(
|
||||
/(<w:styles[^>]*>)/,
|
||||
'$1<w:docDefaults><w:rPrDefault><w:rPr>' +
|
||||
'<w:b/><w:i w:val="0"/><w:color w:val="333333"/><w:sz w:val="21"/>' +
|
||||
'</w:rPr></w:rPrDefault></w:docDefaults>',
|
||||
),
|
||||
)
|
||||
const doc = await parseDocx(await zip.generateAsync({ type: 'uint8array' }))
|
||||
expect(doc.docDefaults).toMatchObject({ bold: true, color: '333333', sizeHalfPoints: 21 })
|
||||
expect(doc.docDefaults?.italic).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('styleUpserts style write-back', () => {
|
||||
it('new styles are appended, modified styles are replaced in place', async () => {
|
||||
const { saveDocx } = await import('../src/index')
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const blocks = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
|
||||
const saved = await saveDocx(parsed, blocks, {
|
||||
styleUpserts: [
|
||||
{
|
||||
styleId: 'MyQuote',
|
||||
type: 'paragraph',
|
||||
name: '我的引用',
|
||||
basedOn: 'Normal',
|
||||
rPr: { italic: true, color: '595959', sizeHalfPoints: 20 },
|
||||
pPr: { align: 'center', spaceBeforeTwips: 120, spaceAfterTwips: 120 },
|
||||
},
|
||||
],
|
||||
})
|
||||
const reparsed = await parseDocx(saved)
|
||||
const st = reparsed.styles.get('MyQuote')!
|
||||
expect(st.name).toBe('我的引用')
|
||||
expect(st.display).toMatchObject({ italic: true, color: '595959', sizeHalfPoints: 20 })
|
||||
// Modify: upsert the same styleId again — replaces instead of duplicating
|
||||
const parsed2 = await parseDocx(saved)
|
||||
const blocks2 = parsed2.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
|
||||
const saved2 = await saveDocx(parsed2, blocks2, {
|
||||
styleUpserts: [
|
||||
{ styleId: 'MyQuote', type: 'paragraph', name: '我的引用', rPr: { bold: true } },
|
||||
],
|
||||
})
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved2)
|
||||
const stylesXml = await zip.file('word/styles.xml')!.async('string')
|
||||
expect(stylesXml.match(/w:styleId="MyQuote"/g)).toHaveLength(1)
|
||||
const reparsed2 = await parseDocx(saved2)
|
||||
expect(reparsed2.styles.get('MyQuote')!.display).toMatchObject({ bold: true })
|
||||
expect(reparsed2.styles.get('MyQuote')!.display?.italic).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseChartPartXml, parseDocx, patchChartPartXml, saveDocx } from '../src/index'
|
||||
import { CHART_PART_XML, buildChartDocx } from './helpers/build-docx'
|
||||
|
||||
describe('chart part parsing', () => {
|
||||
it('reads kind, title, categories and cached series values', () => {
|
||||
const display = parseChartPartXml(CHART_PART_XML, 'word/charts/chart1.xml')
|
||||
expect(display).toMatchObject({
|
||||
partPath: 'word/charts/chart1.xml',
|
||||
kind: 'bar',
|
||||
title: '销售统计',
|
||||
categories: ['一月', '二月', '三月'],
|
||||
})
|
||||
expect(display?.series).toEqual([
|
||||
{ name: '华东', values: [120, 88.5, 96] },
|
||||
{ name: '华南', values: [70, null, 110] },
|
||||
])
|
||||
})
|
||||
|
||||
it('surfaces the chart model on the protected block and keeps the part XML', async () => {
|
||||
const parsed = await parseDocx(await buildChartDocx())
|
||||
const block = parsed.blocks.find((b) => b.label === 'Chart')
|
||||
expect(block?.type).toBe('passthrough')
|
||||
expect(block?.chartDisplay?.title).toBe('销售统计')
|
||||
expect(block?.chartDisplay?.series[0].values).toEqual([120, 88.5, 96])
|
||||
expect(parsed.extras.chartParts['word/charts/chart1.xml']).toBe(CHART_PART_XML)
|
||||
})
|
||||
|
||||
it('returns null for parts without cached series', () => {
|
||||
const empty =
|
||||
'<c:chartSpace xmlns:c="x"><c:chart><c:plotArea><c:scatterChart>' +
|
||||
'<c:ser><c:idx val="0"/></c:ser></c:scatterChart></c:plotArea></c:chart></c:chartSpace>'
|
||||
expect(parseChartPartXml(empty, 'word/charts/chart2.xml')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchChartPartXml', () => {
|
||||
it('patches title, series name, values and categories; keeps refs and structure', () => {
|
||||
const patched = patchChartPartXml(CHART_PART_XML, {
|
||||
title: '2026 营收 & 目标',
|
||||
categories: [null, '2月', null],
|
||||
series: [{ name: '华东大区', values: [null, 99, null] }, null],
|
||||
})
|
||||
// structure and data references stay byte-identical
|
||||
expect(patched).toContain('<c:f>Sheet1!$B$2:$B$4</c:f>')
|
||||
expect(patched).toContain('<c:formatCode>General</c:formatCode>')
|
||||
expect(patched).toContain('<c:barDir val="col"/>')
|
||||
// title collapses into the first run, second run blanked, entities escaped
|
||||
expect(patched).toContain('<a:t>2026 营收 & 目标</a:t>')
|
||||
expect(patched).toContain('<a:t></a:t>')
|
||||
// targeted cache edits only
|
||||
expect(patched).toContain('<c:v>华东大区</c:v>')
|
||||
expect(patched).toContain('<c:v>华南</c:v>')
|
||||
expect(patched).toContain('<c:v>99</c:v>')
|
||||
expect(patched).toContain('<c:v>120</c:v>')
|
||||
expect(patched).toContain('<c:v>2月</c:v>')
|
||||
expect(patched).not.toContain('<c:v>88.5</c:v>')
|
||||
|
||||
const reparsed = parseChartPartXml(patched, 'word/charts/chart1.xml')
|
||||
expect(reparsed?.title).toBe('2026 营收 & 目标')
|
||||
expect(reparsed?.categories).toEqual(['一月', '2月', '三月'])
|
||||
expect(reparsed?.series).toEqual([
|
||||
{ name: '华东大区', values: [120, 99, 96] },
|
||||
{ name: '华南', values: [70, null, 110] },
|
||||
])
|
||||
})
|
||||
|
||||
it('ignores edits it cannot anchor (gap points, missing title) and empty patches', () => {
|
||||
// idx 1 of series 2 has no cached pt: the edit is skipped, not invented
|
||||
const gap = patchChartPartXml(CHART_PART_XML, { series: [null, { values: [null, 42, null] }] })
|
||||
expect(gap).toBe(CHART_PART_XML)
|
||||
const noTitle = CHART_PART_XML.replace(/<c:title>[\s\S]*?<\/c:title>/, '')
|
||||
expect(patchChartPartXml(noTitle, { title: '新标题' })).toBe(noTitle)
|
||||
expect(patchChartPartXml(CHART_PART_XML, {})).toBe(CHART_PART_XML)
|
||||
})
|
||||
})
|
||||
|
||||
describe('chart save round-trip', () => {
|
||||
it('saves a patched chart part via partXml and leaves everything else untouched', async () => {
|
||||
const source = await buildChartDocx()
|
||||
const parsed = await parseDocx(source)
|
||||
const originalPart = parsed.extras.chartParts['word/charts/chart1.xml']
|
||||
const patchedPart = patchChartPartXml(originalPart, {
|
||||
title: '更新后的标题',
|
||||
series: [{ values: [200, null, null] }, null],
|
||||
})
|
||||
|
||||
const visible = parsed.blocks.filter((b) => !b.hidden)
|
||||
const saved = await saveDocx(
|
||||
parsed,
|
||||
visible.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
|
||||
{ partXml: { 'word/charts/chart1.xml': patchedPart } },
|
||||
)
|
||||
|
||||
const reparsed = await parseDocx(saved)
|
||||
const block = reparsed.blocks.find((b) => b.label === 'Chart')
|
||||
expect(block?.chartDisplay?.title).toBe('更新后的标题')
|
||||
expect(block?.chartDisplay?.series[0].values).toEqual([200, 88.5, 96])
|
||||
// the body paragraph is byte-identical; only the chart part changed
|
||||
const [oldZip, newZip] = await Promise.all([JSZip.loadAsync(source), JSZip.loadAsync(saved)])
|
||||
expect(await newZip.file('word/document.xml')!.async('string')).toBe(
|
||||
await oldZip.file('word/document.xml')!.async('string'),
|
||||
)
|
||||
expect(await newZip.file('word/styles.xml')!.async('string')).toBe(
|
||||
await oldZip.file('word/styles.xml')!.async('string'),
|
||||
)
|
||||
})
|
||||
|
||||
it('stays byte-stable when no chart edit is made', async () => {
|
||||
const source = await buildChartDocx()
|
||||
const parsed = await parseDocx(source)
|
||||
const visible = parsed.blocks.filter((b) => !b.hidden)
|
||||
const saved = await saveDocx(
|
||||
parsed,
|
||||
visible.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
|
||||
)
|
||||
expect(saved).toEqual(source)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildChartPartXml,
|
||||
buildChartWorkbookXlsxBase64,
|
||||
parseChartPartXml,
|
||||
parseDocx,
|
||||
patchChartWorkbookXlsxBase64,
|
||||
saveDocx,
|
||||
} from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const SPEC = {
|
||||
kind: 'bar' as const,
|
||||
title: '季度销售',
|
||||
categories: ['Q1', 'Q2', 'Q3'],
|
||||
series: [
|
||||
{ name: '华东', values: [120, 88.5, 96] },
|
||||
{ name: '华南', values: [70, null, 110] },
|
||||
],
|
||||
}
|
||||
|
||||
describe('buildChartPartXml', () => {
|
||||
it('produces a part our own parser reads back', () => {
|
||||
const xml = buildChartPartXml(SPEC)
|
||||
const display = parseChartPartXml(xml, 'word/charts/chart1.xml')!
|
||||
expect(display.kind).toBe('bar')
|
||||
expect(display.title).toBe('季度销售')
|
||||
expect(display.categories).toEqual(['Q1', 'Q2', 'Q3'])
|
||||
expect(display.series).toEqual([
|
||||
{ name: '华东', values: [120, 88.5, 96] },
|
||||
{ name: '华南', values: [70, null, 110] },
|
||||
])
|
||||
})
|
||||
|
||||
it('emits axes for bar/line and none for pie', () => {
|
||||
expect(buildChartPartXml(SPEC)).toContain('<c:catAx>')
|
||||
expect(buildChartPartXml({ ...SPEC, kind: 'line' })).toContain('<c:lineChart>')
|
||||
const pie = buildChartPartXml({ ...SPEC, kind: 'pie', series: [SPEC.series[0]] })
|
||||
expect(pie).toContain('<c:pieChart>')
|
||||
expect(pie).not.toContain('<c:catAx>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveDocx kind:chart', () => {
|
||||
it('creates the part, relationship, content type and drawing paragraph', async () => {
|
||||
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>前文</w:t></w:r></w:p>' })
|
||||
const parsed = await parseDocx(source)
|
||||
const saved = await saveDocx(parsed, [
|
||||
{ kind: 'original', docxIndex: 0 },
|
||||
{ kind: 'chart', chart: SPEC },
|
||||
])
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
expect(zip.file('word/charts/chart1.xml')).toBeTruthy()
|
||||
const contentTypes = await zip.file('[Content_Types].xml')!.async('string')
|
||||
expect(contentTypes).toContain('/word/charts/chart1.xml')
|
||||
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
expect(rels).toContain('charts/chart1.xml')
|
||||
|
||||
const reparsed = await parseDocx(saved)
|
||||
const chartBlock = reparsed.blocks.find((b) => b.chartDisplay)
|
||||
expect(chartBlock?.chartDisplay?.title).toBe('季度销售')
|
||||
expect(chartBlock?.chartDisplay?.series[1].values).toEqual([70, null, 110])
|
||||
})
|
||||
|
||||
it('allocates distinct part names for multiple charts in one save', async () => {
|
||||
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' })
|
||||
const parsed = await parseDocx(source)
|
||||
const saved = await saveDocx(parsed, [
|
||||
{ kind: 'original', docxIndex: 0 },
|
||||
{ kind: 'chart', chart: SPEC },
|
||||
{ kind: 'chart', chart: { ...SPEC, kind: 'pie', title: '占比' } },
|
||||
])
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
expect(zip.file('word/charts/chart1.xml')).toBeTruthy()
|
||||
expect(zip.file('word/charts/chart2.xml')).toBeTruthy()
|
||||
const reparsed = await parseDocx(saved)
|
||||
const charts = reparsed.blocks.filter((b) => b.chartDisplay)
|
||||
expect(charts).toHaveLength(2)
|
||||
expect(charts[1].chartDisplay?.kind).toBe('pie')
|
||||
})
|
||||
})
|
||||
|
||||
describe('chart embedded workbook', () => {
|
||||
it('buildChartWorkbookXlsxBase64 produces a valid xlsx with correct sheet data', async () => {
|
||||
const base64 = await buildChartWorkbookXlsxBase64(
|
||||
['Q1', 'Q2', 'Q3'],
|
||||
[
|
||||
{ name: '华东', values: [120, 88, 96] },
|
||||
{ name: '华南', values: [70, 80, 110] },
|
||||
],
|
||||
)
|
||||
expect(typeof base64).toBe('string')
|
||||
expect(base64.length).toBeGreaterThan(0)
|
||||
// Decode and verify it's a valid zip with the expected parts
|
||||
const binaryStr = atob(base64)
|
||||
const bytes = new Uint8Array(binaryStr.length)
|
||||
for (let i = 0; i < binaryStr.length; i++) bytes[i] = binaryStr.charCodeAt(i)
|
||||
const xlsx = await JSZip.loadAsync(bytes)
|
||||
expect(xlsx.file('xl/workbook.xml')).toBeTruthy()
|
||||
expect(xlsx.file('xl/worksheets/sheet1.xml')).toBeTruthy()
|
||||
expect(xlsx.file('xl/sharedStrings.xml')).toBeTruthy()
|
||||
const sheet = await xlsx.file('xl/worksheets/sheet1.xml')!.async('string')
|
||||
// Sheet uses shared string indices (t="s"), numeric values are inline
|
||||
expect(sheet).toContain('<v>120</v>')
|
||||
const ss = await xlsx.file('xl/sharedStrings.xml')!.async('string')
|
||||
// Category labels Q1/Q2/Q3 live in the shared strings table
|
||||
expect(ss).toContain('Q1')
|
||||
expect(ss).toContain('华东')
|
||||
expect(ss).toContain('华南')
|
||||
})
|
||||
|
||||
it('saveDocx kind:chart embeds the workbook file and chart rels', async () => {
|
||||
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>前文</w:t></w:r></w:p>' })
|
||||
const parsed = await parseDocx(source)
|
||||
const saved = await saveDocx(parsed, [
|
||||
{ kind: 'original', docxIndex: 0 },
|
||||
{ kind: 'chart', chart: SPEC },
|
||||
])
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
// Workbook file must exist
|
||||
expect(zip.file('word/charts/embeddings/workbook1.xlsx')).toBeTruthy()
|
||||
// Chart rels must reference it
|
||||
const relsXml = await zip.file('word/charts/_rels/chart1.xml.rels')!.async('string')
|
||||
expect(relsXml).toContain('embeddings/workbook1.xlsx')
|
||||
// Chart XML must have c:externalData reference
|
||||
const chartXml = await zip.file('word/charts/chart1.xml')!.async('string')
|
||||
expect(chartXml).toContain('c:externalData')
|
||||
// Content types must register the workbook
|
||||
const ct = await zip.file('[Content_Types].xml')!.async('string')
|
||||
expect(ct).toContain('spreadsheetml.sheet')
|
||||
})
|
||||
|
||||
it('patchChartWorkbookXlsxBase64 updates cell values', async () => {
|
||||
const original = await buildChartWorkbookXlsxBase64(
|
||||
['Q1', 'Q2'],
|
||||
[{ name: '华东', values: [100, 200] }],
|
||||
)
|
||||
const patched = await patchChartWorkbookXlsxBase64(original, ['A', 'B'], [
|
||||
{ name: '华东', values: [999, 888] },
|
||||
])
|
||||
expect(patched).toBeTruthy()
|
||||
const binaryStr = atob(patched!)
|
||||
const bytes = new Uint8Array(binaryStr.length)
|
||||
for (let i = 0; i < binaryStr.length; i++) bytes[i] = binaryStr.charCodeAt(i)
|
||||
const xlsx = await JSZip.loadAsync(bytes)
|
||||
const sheet = await xlsx.file('xl/worksheets/sheet1.xml')!.async('string')
|
||||
expect(sheet).toContain('999')
|
||||
expect(sheet).toContain('888')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, readSections, sectionSettingsFromXml } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
describe('emphasis marks (w:em)', () => {
|
||||
it('parses dot/circle emphasis onto runs and skips none', async () => {
|
||||
const p =
|
||||
'<w:p><w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>重点</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:em w:val="circle"/></w:rPr><w:t>圈点</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:em w:val="none"/></w:rPr><w:t>普通</w:t></w:r></w:p>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
|
||||
const runs = parsed.blocks[0].runs!
|
||||
expect(runs[0].em).toBe('dot')
|
||||
expect(runs[1].em).toBe('circle')
|
||||
expect(runs[2].em).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the w:em bytes via rawRPr for untouched-style saves', async () => {
|
||||
const p = '<w:p><w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>重点</w:t></w:r></w:p>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
|
||||
expect(parsed.blocks[0].runs![0].rawRPr).toContain('<w:em w:val="dot"/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('section textDirection (w:textDirection)', () => {
|
||||
it('reads vertical tbRl from sectPr and omits horizontal lrTb', () => {
|
||||
expect(
|
||||
sectionSettingsFromXml('<w:sectPr><w:textDirection w:val="tbRl"/></w:sectPr>').textDirection,
|
||||
).toBe('tbRl')
|
||||
expect(
|
||||
sectionSettingsFromXml('<w:sectPr><w:textDirection w:val="lrTb"/></w:sectPr>').textDirection,
|
||||
).toBeUndefined()
|
||||
expect(sectionSettingsFromXml('<w:sectPr/>').textDirection).toBeUndefined()
|
||||
})
|
||||
|
||||
it('readSections surfaces per-section columns and direction from a real doc', async () => {
|
||||
const body =
|
||||
'<w:p><w:r><w:t>one</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:sectPr><w:type w:val="continuous"/><w:pgSz w:w="11906" w:h="16838"/>' +
|
||||
'<w:cols w:num="2" w:space="425"/></w:sectPr></w:pPr></w:p>' +
|
||||
'<w:p><w:r><w:t>two</w:t></w:r></w:p>'
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: body, sectPrExtra: '<w:textDirection w:val="tbRl"/>' }),
|
||||
)
|
||||
const sections = readSections(parsed)
|
||||
expect(sections).toHaveLength(2)
|
||||
expect(sections[0].settings.columns).toBe(2)
|
||||
expect(sections[0].startType).toBe('continuous')
|
||||
expect(sections[1].settings.textDirection).toBe('tbRl')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,276 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
const COMMENTS_XML =
|
||||
XML_DECL +
|
||||
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:comment w:id="1" w:author="Alice" w:initials="A" w:date="2026-07-01T10:00:00Z">' +
|
||||
'<w:p><w:r><w:t>第一条批注</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>第二段</w:t></w:r></w:p>' +
|
||||
'</w:comment>' +
|
||||
'<w:comment w:id="2" w:author="Bob">' +
|
||||
'<w:p><w:r><w:t>cross-para note</w:t></w:r></w:p>' +
|
||||
'</w:comment>' +
|
||||
'</w:comments>'
|
||||
|
||||
/** paragraph with an in-paragraph comment range over its middle run */
|
||||
const COMMENTED_P =
|
||||
'<w:p><w:r><w:t>before </w:t></w:r>' +
|
||||
'<w:commentRangeStart w:id="1"/>' +
|
||||
'<w:r><w:t>marked</w:t></w:r>' +
|
||||
'<w:commentRangeEnd w:id="1"/>' +
|
||||
'<w:r><w:commentReference w:id="1"/></w:r>' +
|
||||
'<w:r><w:t> after</w:t></w:r></w:p>'
|
||||
|
||||
/** comment 2 spans two paragraphs: start in one, end in the next */
|
||||
const CROSS_P_A = '<w:p><w:commentRangeStart w:id="2"/><w:r><w:t>range opens here</w:t></w:r></w:p>'
|
||||
const CROSS_P_B =
|
||||
'<w:p><w:r><w:t>range closes here</w:t></w:r><w:commentRangeEnd w:id="2"/>' +
|
||||
'<w:r><w:commentReference w:id="2"/></w:r></w:p>'
|
||||
|
||||
async function buildCommentedDocx(): Promise<Uint8Array> {
|
||||
return buildDocx({
|
||||
bodyXml: COMMENTED_P + CROSS_P_A + CROSS_P_B,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/comments.xml',
|
||||
xml: COMMENTS_XML,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
describe('comment parsing', () => {
|
||||
it('reads word/comments.xml into the display list', async () => {
|
||||
const doc = await parseDocx(await buildCommentedDocx())
|
||||
expect(doc.comments).toEqual([
|
||||
{
|
||||
id: '1',
|
||||
author: 'Alice',
|
||||
initials: 'A',
|
||||
date: '2026-07-01T10:00:00Z',
|
||||
text: '第一条批注\n第二段',
|
||||
},
|
||||
{ id: '2', author: 'Bob', initials: undefined, date: undefined, text: 'cross-para note' },
|
||||
])
|
||||
})
|
||||
|
||||
it('has no comments array entries for documents without comments.xml', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }))
|
||||
expect(doc.comments).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps commented paragraphs editable and marks covered runs', async () => {
|
||||
const doc = await parseDocx(await buildCommentedDocx())
|
||||
const p = doc.blocks[0]
|
||||
expect(p.type).toBe('paragraph')
|
||||
expect(p.runs).toEqual([
|
||||
{ text: 'before ' },
|
||||
{ text: 'marked', commentIds: ['1'] },
|
||||
{ text: ' after' },
|
||||
])
|
||||
})
|
||||
|
||||
it('leaves runs of a cross-paragraph range unmarked (markers preserved by passthrough)', async () => {
|
||||
const doc = await parseDocx(await buildCommentedDocx())
|
||||
expect(doc.blocks[1].type).toBe('paragraph')
|
||||
expect(doc.blocks[1].runs).toEqual([{ text: 'range opens here' }])
|
||||
expect(doc.blocks[2].runs).toEqual([{ text: 'range closes here' }])
|
||||
// Cross-paragraph endpoints go into the block-level passthrough fields
|
||||
expect(doc.blocks[1].commentStarts).toEqual(['2'])
|
||||
expect(doc.blocks[1].commentEnds).toBeUndefined()
|
||||
expect(doc.blocks[2].commentEnds).toEqual(['2'])
|
||||
// A range fully inside one paragraph stays out of the cross-paragraph fields
|
||||
// (handled by run.commentIds)
|
||||
expect(doc.blocks[0].commentStarts).toBeUndefined()
|
||||
expect(doc.blocks[0].commentEnds).toBeUndefined()
|
||||
})
|
||||
|
||||
it('editing a paragraph inside a cross-paragraph range re-emits its marker (no orphan end)', async () => {
|
||||
const bytes = await buildCommentedDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const finalBlocks: SaveBlock[] = doc.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) =>
|
||||
b.docxIndex === 1
|
||||
? {
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
commentStarts: b.commentStarts,
|
||||
commentEnds: b.commentEnds,
|
||||
runs: [{ text: 'range opens here (edited)' }],
|
||||
},
|
||||
}
|
||||
: { kind: 'original', docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
const docXml = await (await JSZip.loadAsync(saved)).file('word/document.xml')!.async('string')
|
||||
// Before the fix: the edited paragraph lost its commentRangeStart, leaving an
|
||||
// orphaned commentRangeEnd in the later paragraph
|
||||
expect(docXml).toContain('<w:commentRangeStart w:id="2"/>')
|
||||
expect(docXml).toContain('range opens here (edited)')
|
||||
expect(docXml).toContain('<w:commentRangeEnd w:id="2"/>')
|
||||
// Editing the closing paragraph → end + reference are written back together
|
||||
const doc2 = await parseDocx(saved)
|
||||
const finalBlocks2: SaveBlock[] = doc2.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) =>
|
||||
b.runs?.some((r) => r.text.includes('range closes here'))
|
||||
? {
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
commentStarts: b.commentStarts,
|
||||
commentEnds: b.commentEnds,
|
||||
runs: [{ text: 'closes edited' }],
|
||||
},
|
||||
}
|
||||
: { kind: 'original', docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved2 = await saveDocx(doc2, finalBlocks2)
|
||||
const docXml2 = await (await JSZip.loadAsync(saved2)).file('word/document.xml')!.async('string')
|
||||
expect(docXml2).toContain('closes edited')
|
||||
expect(docXml2).toContain(
|
||||
'<w:commentRangeEnd w:id="2"/><w:r><w:commentReference w:id="2"/></w:r>',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('comment save fidelity', () => {
|
||||
it('no edits -> byte-identical output including comments.xml', async () => {
|
||||
const bytes = await buildCommentedDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
|
||||
const saved = await saveDocx(
|
||||
doc,
|
||||
visible.map((docxIndex): SaveBlock => ({ kind: 'original', docxIndex })),
|
||||
)
|
||||
expect(saved).toBe(bytes)
|
||||
})
|
||||
|
||||
it('editing a commented paragraph re-emits its range markers and reference', async () => {
|
||||
const bytes = await buildCommentedDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const finalBlocks: SaveBlock[] = doc.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) =>
|
||||
b.docxIndex === 0
|
||||
? {
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [
|
||||
{ text: 'BEFORE ' },
|
||||
{ text: 'marked edited', commentIds: ['1'] },
|
||||
{ text: ' AFTER' },
|
||||
],
|
||||
},
|
||||
}
|
||||
: { kind: 'original', docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
const docXml = await zip.file('word/document.xml')!.async('string')
|
||||
expect(docXml).toContain(
|
||||
'<w:commentRangeStart w:id="1"/><w:r><w:t xml:space="preserve">marked edited</w:t></w:r>' +
|
||||
'<w:commentRangeEnd w:id="1"/><w:r><w:commentReference w:id="1"/></w:r>',
|
||||
)
|
||||
// comments.xml itself is untouched
|
||||
expect(await zip.file('word/comments.xml')!.async('string')).toBe(COMMENTS_XML)
|
||||
})
|
||||
|
||||
it('editing one comment keeps the other rich comment entry byte-identical (surgical rebuild)', async () => {
|
||||
const RICH_COMMENTS =
|
||||
XML_DECL +
|
||||
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:comment w:id="1" w:author="Alice" w:initials="A">' +
|
||||
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>加粗观点</w:t></w:r>' +
|
||||
'<w:r><w:t>与普通文字</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:rPr><w:i/><w:highlight w:val="yellow"/></w:rPr><w:t>第二段斜体高亮</w:t></w:r></w:p>' +
|
||||
'</w:comment>' +
|
||||
'<w:comment w:id="2" w:author="Bob"><w:p><w:r><w:t>待编辑的批注</w:t></w:r></w:p></w:comment>' +
|
||||
'</w:comments>'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: COMMENTED_P + CROSS_P_A + CROSS_P_B,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/comments.xml',
|
||||
xml: RICH_COMMENTS,
|
||||
contentType:
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
|
||||
},
|
||||
],
|
||||
extraRels:
|
||||
'<Relationship Id="rId50" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
// Only comment 2's text changes; comment 1 (rich formatting) stays untouched
|
||||
const edited = doc.comments.map((c) => (c.id === '2' ? { ...c, text: '已改写的批注' } : c))
|
||||
const saved = await saveDocx(
|
||||
doc,
|
||||
doc.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b): SaveBlock => ({ kind: 'original', docxIndex: b.docxIndex! })),
|
||||
{ comments: edited },
|
||||
)
|
||||
const commentsXml = await (
|
||||
await JSZip.loadAsync(saved)
|
||||
)
|
||||
.file('word/comments.xml')!
|
||||
.async('string')
|
||||
// Before the surgical fix: comment 1 was rebuilt as plain text, losing its
|
||||
// bold/italic/highlight
|
||||
expect(commentsXml).toContain(
|
||||
'<w:comment w:id="1" w:author="Alice" w:initials="A">' +
|
||||
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>加粗观点</w:t></w:r>' +
|
||||
'<w:r><w:t>与普通文字</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:rPr><w:i/><w:highlight w:val="yellow"/></w:rPr><w:t>第二段斜体高亮</w:t></w:r></w:p>' +
|
||||
'</w:comment>',
|
||||
)
|
||||
expect(commentsXml).toContain('已改写的批注')
|
||||
expect(commentsXml).not.toContain('待编辑的批注')
|
||||
})
|
||||
})
|
||||
|
||||
describe('comment replies/resolution (commentsExtended)', () => {
|
||||
it('round-trips new replies and the resolved state', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:commentRangeStart w:id="1"/><w:r><w:t>被批注文字</w:t></w:r>' +
|
||||
'<w:commentRangeEnd w:id="1"/><w:r><w:commentReference w:id="1"/></w:r></w:p>',
|
||||
}),
|
||||
)
|
||||
const blocks = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
|
||||
const comments = [
|
||||
{ id: '1', author: '甲', text: '主批注' },
|
||||
{ id: '2', author: '乙', text: '回复一下', parentId: '1' },
|
||||
]
|
||||
const saved = await saveDocx(parsed, blocks, { comments })
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.comments).toHaveLength(2)
|
||||
const reply = reparsed.comments.find((c) => c.id === '2')!
|
||||
expect(reply.parentId).toBe('1')
|
||||
expect(reply.paraId).toBeTruthy()
|
||||
// Resolve the main comment → done round-trips
|
||||
const resolved = reparsed.comments.map((c) => ({ ...c, done: true }))
|
||||
const saved2 = await saveDocx(await parseDocx(saved), blocks, { comments: resolved })
|
||||
const reparsed2 = await parseDocx(saved2)
|
||||
expect(reparsed2.comments.every((c) => c.done)).toBe(true)
|
||||
// Part/relationship/ContentType wired together
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved2)
|
||||
expect(zip.file('word/commentsExtended.xml')).toBeTruthy()
|
||||
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
expect(rels).toContain('commentsExtended.xml')
|
||||
const ct = await zip.file('[Content_Types].xml')!.async('string')
|
||||
expect(ct).toContain('commentsExtended+xml')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/parse'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
/**
|
||||
* Documents produced by design tools (and Word itself) pair every DrawingML
|
||||
* shape with a legacy VML fallback:
|
||||
* <mc:AlternateContent><mc:Choice><w:drawing>…</mc:Choice>
|
||||
* <mc:Fallback><w:pict>…</mc:Fallback></mc:AlternateContent>
|
||||
* The raw bytes therefore contain <w:pict> even for a plain decorated text
|
||||
* paragraph — classification must ignore fallback content or whole documents
|
||||
* degrade into embedded-object chips.
|
||||
*/
|
||||
|
||||
const THIN_RULE_DRAWING =
|
||||
'<w:r><mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
|
||||
'<mc:Choice Requires="wps"><w:drawing>' +
|
||||
'<wp:anchor behindDoc="1" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="2" locked="0" layoutInCell="1" allowOverlap="1">' +
|
||||
'<wp:simplePos x="0" y="0"/><wp:extent cx="6048375" cy="9525"/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
|
||||
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
|
||||
'<wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="6048375" cy="9525"/></a:xfrm></wps:spPr>' +
|
||||
'</wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></mc:Choice>' +
|
||||
'<mc:Fallback><w:pict>' +
|
||||
'<v:rect xmlns:v="urn:schemas-microsoft-com:vml" style="position:absolute" id="rule1" filled="true"/>' +
|
||||
'</w:pict></mc:Fallback></mc:AlternateContent></w:r>'
|
||||
|
||||
describe('paragraphs with decorative shapes + VML fallbacks', () => {
|
||||
it('keeps text of a decorated heading editable (fallback w:pict must not trigger Embedded object)', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
`<w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr>${THIN_RULE_DRAWING}` +
|
||||
'<w:r><w:t>Mandatory Story Header Format</w:t></w:r></w:p>',
|
||||
}),
|
||||
)
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('heading')
|
||||
expect(block.level).toBe(2)
|
||||
expect(block.runs?.map((r) => r.text).join('')).toBe('Mandatory Story Header Format')
|
||||
})
|
||||
|
||||
it('keeps decorated list items as listItem', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr>' +
|
||||
`${THIN_RULE_DRAWING}<w:r><w:t>Include new date only on a time skip</w:t></w:r></w:p>`,
|
||||
withNumbering: true,
|
||||
}),
|
||||
)
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('listItem')
|
||||
expect(block.runs?.map((r) => r.text).join('')).toBe('Include new date only on a time skip')
|
||||
})
|
||||
|
||||
it('marks a text-less thin shape as a decorative rule', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: `<w:p>${THIN_RULE_DRAWING}</w:p>` }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.label).toBe('Drawing object')
|
||||
expect(block.decorative).toBe(true)
|
||||
})
|
||||
|
||||
it('still protects real VML embedded objects (w:pict outside mc:Fallback)', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:pict>' +
|
||||
'<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="ole1" style="width:100pt;height:100pt"/>' +
|
||||
'</w:pict></w:r></w:p>',
|
||||
}),
|
||||
)
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.label).toBe('Embedded object')
|
||||
})
|
||||
|
||||
it('extracts anchored textbox content as a display-only model (code box)', async () => {
|
||||
const textboxDrawing =
|
||||
'<w:r><w:drawing><wp:anchor behindDoc="1" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">' +
|
||||
'<wp:simplePos x="0" y="0"/><wp:extent cx="6038850" cy="1704975"/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
|
||||
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
|
||||
'<wps:spPr><a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' +
|
||||
'<a:solidFill><a:srgbClr val="F5F5F5"/></a:solidFill>' +
|
||||
'<a:ln w="9524"><a:solidFill><a:srgbClr val="CCCCCC"/></a:solidFill></a:ln></wps:spPr>' +
|
||||
'<wps:txbx><w:txbxContent>' +
|
||||
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Courier New"/><w:color w:val="415461"/><w:sz w:val="22"/></w:rPr>' +
|
||||
'<w:t>**Current date:** {Month}</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>CRITICAL</w:t></w:r></w:p>' +
|
||||
'</w:txbxContent></wps:txbx></wps:wsp>' +
|
||||
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: `<w:p>${textboxDrawing}</w:p>` }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.label).toBe('Text box')
|
||||
const box = block.textboxes?.[0]
|
||||
expect(box?.fill).toBe('F5F5F5')
|
||||
expect(box?.borderColor).toBe('CCCCCC')
|
||||
expect(box?.paras).toHaveLength(2)
|
||||
expect(box?.paras[0].runs[0]).toMatchObject({
|
||||
text: '**Current date:** {Month}',
|
||||
color: '415461',
|
||||
font: 'Courier New',
|
||||
})
|
||||
expect(box?.paras[1].align).toBe('center')
|
||||
expect(box?.paras[1].runs[0]).toMatchObject({ text: 'CRITICAL', bold: true })
|
||||
})
|
||||
|
||||
it('preserves the original XML slice for decorated paragraphs (byte-level patch anchor)', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: `<w:p>${THIN_RULE_DRAWING}<w:r><w:t>text</w:t></w:r></w:p>`,
|
||||
}),
|
||||
)
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('paragraph')
|
||||
expect(block.originalXml).toContain('<mc:Fallback>')
|
||||
expect(block.originalXml).toContain('<w:pict>')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const CORE_XML =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ' +
|
||||
'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" ' +
|
||||
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
|
||||
'<dc:title>测试文档</dc:title><dc:creator>作者甲</dc:creator>' +
|
||||
'<cp:lastModifiedBy>作者甲</cp:lastModifiedBy><cp:revision>3</cp:revision>' +
|
||||
'<dcterms:created xsi:type="dcterms:W3CDTF">2020-01-01T00:00:00Z</dcterms:created>' +
|
||||
'<dcterms:modified xsi:type="dcterms:W3CDTF">2020-01-02T00:00:00Z</dcterms:modified>' +
|
||||
'</cp:coreProperties>'
|
||||
|
||||
const BODY = '<w:p><w:r><w:t>正文</w:t></w:r></w:p>'
|
||||
|
||||
const docxWithCore = () =>
|
||||
buildDocx({
|
||||
bodyXml: BODY,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'docProps/core.xml',
|
||||
xml: CORE_XML,
|
||||
contentType: 'application/vnd.openxmlformats-package.core-properties+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const originalOrder = (doc: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] =>
|
||||
doc.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
|
||||
describe('docProps/core.xml on save', () => {
|
||||
it('a real save updates dcterms:modified and bumps cp:revision, keeping other fields', async () => {
|
||||
const doc = await parseDocx(await docxWithCore())
|
||||
const out = await saveDocx(doc, originalOrder(doc), {
|
||||
watermark: '草稿',
|
||||
savedAt: '2026-07-28T08:30:00Z',
|
||||
})
|
||||
const core = await (await JSZip.loadAsync(out)).file('docProps/core.xml')!.async('string')
|
||||
expect(core).toContain(
|
||||
'<dcterms:modified xsi:type="dcterms:W3CDTF">2026-07-28T08:30:00Z</dcterms:modified>',
|
||||
)
|
||||
expect(core).toContain('<cp:revision>4</cp:revision>')
|
||||
expect(core).toContain('<dc:title>测试文档</dc:title>')
|
||||
expect(core).toContain('<dcterms:created xsi:type="dcterms:W3CDTF">2020-01-01T00:00:00Z</dcterms:created>')
|
||||
})
|
||||
|
||||
it('an unedited save still returns the original bytes untouched', async () => {
|
||||
const bytes = await docxWithCore()
|
||||
const doc = await parseDocx(bytes)
|
||||
const out = await saveDocx(doc, originalOrder(doc), { savedAt: '2026-07-28T08:30:00Z' })
|
||||
expect(out).toEqual(bytes)
|
||||
})
|
||||
|
||||
it('a document without docProps saves fine (nothing injected)', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
|
||||
const out = await saveDocx(doc, originalOrder(doc), { watermark: '草稿' })
|
||||
expect((await JSZip.loadAsync(out)).file('docProps/core.xml')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
// ---- fixture XML fragments ----
|
||||
|
||||
/** Paragraph with a drop cap (Word OOXML: framePr dropCap="drop") */
|
||||
const DROP_CAP_P =
|
||||
'<w:p>' +
|
||||
'<w:pPr>' +
|
||||
'<w:framePr w:dropCap="drop" w:lines="3" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/>' +
|
||||
'</w:pPr>' +
|
||||
'<w:r><w:t xml:space="preserve">Lorem ipsum dolor sit amet.</w:t></w:r>' +
|
||||
'</w:p>'
|
||||
|
||||
/** Paragraph with margin drop cap */
|
||||
const MARGIN_CAP_P =
|
||||
'<w:p>' +
|
||||
'<w:pPr>' +
|
||||
'<w:framePr w:dropCap="margin" w:lines="4" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/>' +
|
||||
'</w:pPr>' +
|
||||
'<w:r><w:t xml:space="preserve">Dropped margin cap text here.</w:t></w:r>' +
|
||||
'</w:p>'
|
||||
|
||||
const PLAIN_P = '<w:p><w:r><w:t>plain paragraph no dropcap</w:t></w:r></w:p>'
|
||||
|
||||
describe('drop cap parsing', () => {
|
||||
it('parses w:framePr dropCap="drop" into block.format.dropCap', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: DROP_CAP_P }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.format?.dropCap).toBeDefined()
|
||||
expect(block.format!.dropCap!.type).toBe('drop')
|
||||
expect(block.format!.dropCap!.lines).toBe(3)
|
||||
})
|
||||
|
||||
it('parses w:framePr dropCap="margin" correctly', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: MARGIN_CAP_P }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.format?.dropCap).toBeDefined()
|
||||
expect(block.format!.dropCap!.type).toBe('margin')
|
||||
expect(block.format!.dropCap!.lines).toBe(4)
|
||||
})
|
||||
|
||||
it('plain paragraph has no dropCap', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: PLAIN_P }))
|
||||
expect(doc.blocks[0].format?.dropCap).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('drop cap roundtrip', () => {
|
||||
it('untouched drop-cap paragraph saves byte-identical', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: DROP_CAP_P })
|
||||
const doc = await parseDocx(bytes)
|
||||
const saved = await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.blocks[0].format?.dropCap?.type).toBe('drop')
|
||||
expect(reparsed.internal.documentXml).toContain('w:dropCap="drop"')
|
||||
expect(reparsed.internal.documentXml).toContain('w:lines="3"')
|
||||
})
|
||||
|
||||
it('setting dropCap via format regenerates correct pPr with framePr', async () => {
|
||||
const { generateParagraphXml } = await import('../src/generate')
|
||||
const block = {
|
||||
type: 'paragraph' as const,
|
||||
runs: [{ text: 'Hello world' }],
|
||||
format: { dropCap: { type: 'drop' as const, lines: 3 } },
|
||||
}
|
||||
const xml = generateParagraphXml(block, {
|
||||
headingStyleIds: new Map(),
|
||||
allocateHyperlinkRel: () => 'rId1',
|
||||
})
|
||||
expect(xml).toContain('w:framePr')
|
||||
expect(xml).toContain('w:dropCap="drop"')
|
||||
expect(xml).toContain('w:lines="3"')
|
||||
})
|
||||
|
||||
it('clearing dropCap removes framePr from rawPPr', async () => {
|
||||
const { mergePPrFormat } = await import('../src/generate')
|
||||
const rawPPr =
|
||||
'<w:pPr><w:framePr w:dropCap="drop" w:lines="3" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/></w:pPr>'
|
||||
// format with dropCap=undefined → should remove framePr
|
||||
const merged = mergePPrFormat(rawPPr, { dropCap: undefined })
|
||||
// dropCap undefined means it's not managed; framePr is preserved
|
||||
expect(merged).toContain('w:framePr')
|
||||
// explicitly set dropCap: undefined won't remove because undefined fields skip the managed set
|
||||
// To actually clear it, you'd set dropCap to a falsy value; test that null clears it:
|
||||
// NOTE: the format type has dropCap?: {...}, so passing null would need to be cast.
|
||||
// Instead test that passing a new dropCap replaces the old framePr:
|
||||
const replaced = mergePPrFormat(rawPPr, { dropCap: { type: 'margin', lines: 2 } })
|
||||
expect(replaced).toContain('w:dropCap="margin"')
|
||||
expect(replaced).toContain('w:lines="2"')
|
||||
expect(replaced).not.toContain('w:dropCap="drop"')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateTocFieldXml, parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
// TOC entry paragraph as Word writes it: TOC field begin + hyperlink entry
|
||||
// with a dot-leader tab and a nested PAGEREF field for the page number.
|
||||
const TOC_ENTRY_PARAGRAPH =
|
||||
'<w:p><w:pPr><w:pStyle w:val="TOC1"/>' +
|
||||
'<w:tabs><w:tab w:val="right" w:leader="dot" w:pos="9350"/></w:tabs></w:pPr>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" \\h </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:hyperlink w:anchor="_Toc1" w:history="1">' +
|
||||
'<w:r><w:t>第一章 概述</w:t></w:r>' +
|
||||
'<w:r><w:tab/></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> PAGEREF _Toc1 \\h </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:t>2</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'</w:hyperlink></w:p>'
|
||||
|
||||
const FIELD_END_PAGEBREAK_PARAGRAPH =
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:br w:type="page"/></w:r></w:p>'
|
||||
|
||||
const PAGE_FIELD_PARAGRAPH =
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:t>- 8 -</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
|
||||
|
||||
describe('field paragraph display model', () => {
|
||||
it('TOC entry becomes a tocLine with title, page number and level', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_ENTRY_PARAGRAPH }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.fieldDisplay).toEqual({
|
||||
kind: 'tocLine',
|
||||
left: '第一章 概述',
|
||||
right: '2',
|
||||
level: 1,
|
||||
anchor: '_Toc1',
|
||||
})
|
||||
})
|
||||
|
||||
it('field-end + page break paragraph shows as a pageBreak marker', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: FIELD_END_PAGEBREAK_PARAGRAPH }))
|
||||
expect(doc.blocks[0].fieldDisplay).toEqual({ kind: 'pageBreak' })
|
||||
})
|
||||
|
||||
it('PAGE field paragraphs collapse into an editable inline field run (cached result as display text)', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: PAGE_FIELD_PARAGRAPH }))
|
||||
expect(doc.blocks[0].type).toBe('paragraph')
|
||||
expect(doc.blocks[0].runs?.[0]).toMatchObject({ text: '- 8 -', instrField: 'PAGE' })
|
||||
})
|
||||
|
||||
it('TOC entry carries its hyperlink anchor for click-to-jump', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_ENTRY_PARAGRAPH }))
|
||||
expect(doc.blocks[0].fieldDisplay?.anchor).toBe('_Toc1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('generateTocFieldXml', () => {
|
||||
const entries = [
|
||||
{ level: 1, text: '第一章 概述' },
|
||||
{ level: 2, text: '1.1 背景 <特殊&字符>' },
|
||||
{ level: 1, text: '第二章 分析' },
|
||||
]
|
||||
|
||||
it('emits a dirty TOC field spanning one paragraph per entry', () => {
|
||||
const frags = generateTocFieldXml(entries)
|
||||
expect(frags).toHaveLength(3)
|
||||
// field structure: dirty begin + instruction in the first, single end in the last
|
||||
expect(frags[0]).toContain('w:fldCharType="begin" w:dirty="true"')
|
||||
expect(frags[0]).toContain(' TOC \\o "1-2" \\h \\z \\u ')
|
||||
expect(frags[0]).toContain('<w:pStyle w:val="TOC1"/>')
|
||||
expect(frags[1]).toContain('<w:pStyle w:val="TOC2"/>')
|
||||
expect(frags[1]).toContain('<特殊&字符>')
|
||||
expect(frags[2]).toContain('w:fldCharType="end"')
|
||||
const joined = frags.join('')
|
||||
expect(joined.match(/w:fldCharType="end"/g)).toHaveLength(1)
|
||||
expect(joined.match(/w:fldCharType="begin"/g)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('round-trips through the parser as tocLine display blocks', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: generateTocFieldXml(entries).join('') }))
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
expect(visible).toHaveLength(3)
|
||||
for (const [i, block] of visible.entries()) {
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.fieldDisplay?.kind).toBe('tocLine')
|
||||
expect(block.fieldDisplay?.left).toBe(entries[i].text)
|
||||
expect(block.fieldDisplay?.level).toBe(entries[i].level)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,182 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateParagraphXml, parseDocx, type GenerateContext } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const GEN_CTX: GenerateContext = {
|
||||
headingStyleIds: new Map([[1, 'Heading1']]),
|
||||
allocateHyperlinkRel: () => 'rId999',
|
||||
}
|
||||
|
||||
describe('run-level formatting (font / highlight / vertAlign)', () => {
|
||||
it('parses rFonts, highlight and vertAlign from runs', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Georgia" w:hAnsi="Georgia"/></w:rPr><w:t>font</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:highlight w:val="yellow"/></w:rPr><w:t>hl</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:t>sup</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:vertAlign w:val="subscript"/></w:rPr><w:t>sub</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const runs = doc.blocks[0].runs!
|
||||
expect(runs[0].font).toBe('Georgia')
|
||||
expect(runs[1].highlight).toBe('yellow')
|
||||
expect(runs[2].vertAlign).toBe('superscript')
|
||||
expect(runs[3].vertAlign).toBe('subscript')
|
||||
})
|
||||
|
||||
it('prefers eastAsia font name when present', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Calibri" w:eastAsia="宋体"/></w:rPr><w:t>文字</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].runs![0].font).toBe('宋体')
|
||||
})
|
||||
|
||||
it('generates rPr children for the new run props', () => {
|
||||
const xml = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
runs: [
|
||||
{ text: 'x', font: '宋体', highlight: 'yellow', vertAlign: 'superscript', bold: true },
|
||||
],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体" w:cs="宋体"/>')
|
||||
expect(xml).toContain('<w:highlight w:val="yellow"/>')
|
||||
expect(xml).toContain('<w:vertAlign w:val="superscript"/>')
|
||||
// schema order: rFonts before b, highlight after sz-position, vertAlign last
|
||||
expect(xml.indexOf('<w:rFonts')).toBeLessThan(xml.indexOf('<w:b/>'))
|
||||
expect(xml.indexOf('<w:highlight')).toBeLessThan(xml.indexOf('<w:vertAlign'))
|
||||
})
|
||||
|
||||
it('round-trips run formatting through generate -> parse', async () => {
|
||||
const para = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
runs: [{ text: '重点', font: '黑体', highlight: 'green', vertAlign: 'subscript' }],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
const bytes = await buildDocx({ bodyXml: para })
|
||||
const doc = await parseDocx(bytes)
|
||||
const run = doc.blocks[0].runs![0]
|
||||
expect(run).toMatchObject({
|
||||
text: '重点',
|
||||
font: '黑体',
|
||||
highlight: 'green',
|
||||
vertAlign: 'subscript',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('paragraph-level formatting (align / line spacing / indent)', () => {
|
||||
it('parses w:jc, w:spacing line and w:ind left', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>centered</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:spacing w:line="360" w:lineRule="auto"/></w:pPr><w:r><w:t>1.5x</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:ind w:left="720"/><w:jc w:val="both"/></w:pPr><w:r><w:t>indented justify</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>plain</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].format).toEqual({ align: 'center' })
|
||||
// F1: parser now exposes lineRawTwips + lineRule + lineSpacing for auto-mode spacing
|
||||
expect(doc.blocks[1].format).toMatchObject({
|
||||
lineSpacing: 1.5,
|
||||
lineRawTwips: 360,
|
||||
lineRule: 'auto',
|
||||
})
|
||||
expect(doc.blocks[2].format).toEqual({ align: 'justify', indentLeft: 720 })
|
||||
expect(doc.blocks[3].format).toBeUndefined()
|
||||
})
|
||||
|
||||
it('parses and generates first-line and hanging indents', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:ind w:firstLine="440"/></w:pPr><w:r><w:t>首行缩进</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr><w:r><w:t>悬挂缩进</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].format).toEqual({ indentFirstLine: 440 })
|
||||
expect(doc.blocks[1].format).toEqual({ indentLeft: 720, indentFirstLine: -360 })
|
||||
|
||||
const firstLineXml = generateParagraphXml(
|
||||
{ type: 'paragraph', format: { indentFirstLine: 440 }, runs: [{ text: 'a' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(firstLineXml).toContain('<w:ind w:firstLine="440"/>')
|
||||
const hangingXml = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
format: { indentLeft: 720, indentFirstLine: -360 },
|
||||
runs: [{ text: 'a' }],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(hangingXml).toContain('<w:ind w:left="720" w:hanging="360"/>')
|
||||
})
|
||||
|
||||
it('exposes exact/atLeast spacing as lineRawTwips+lineRule (F1)', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:spacing w:line="360" w:lineRule="exact"/></w:pPr><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
// F1: exact/atLeast spacing is now exposed via lineRawTwips+lineRule instead of being ignored
|
||||
expect(doc.blocks[0].format).toMatchObject({ lineRawTwips: 360, lineRule: 'exact' })
|
||||
})
|
||||
|
||||
it('generates pPr with schema-ordered children', () => {
|
||||
const xml = generateParagraphXml(
|
||||
{
|
||||
type: 'heading',
|
||||
level: 1,
|
||||
format: { align: 'justify', lineSpacing: 1.15, indentLeft: 360 },
|
||||
runs: [{ text: 'title' }],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:pStyle w:val="Heading1"/>')
|
||||
expect(xml).toContain('<w:spacing w:line="276" w:lineRule="auto"/>')
|
||||
expect(xml).toContain('<w:ind w:left="360"/>')
|
||||
expect(xml).toContain('<w:jc w:val="both"/>')
|
||||
expect(xml.indexOf('<w:pStyle')).toBeLessThan(xml.indexOf('<w:spacing'))
|
||||
expect(xml.indexOf('<w:spacing')).toBeLessThan(xml.indexOf('<w:ind'))
|
||||
expect(xml.indexOf('<w:ind')).toBeLessThan(xml.indexOf('<w:jc'))
|
||||
})
|
||||
|
||||
it('round-trips paragraph formatting through generate -> parse', async () => {
|
||||
const para = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
format: { align: 'right', lineSpacing: 2, indentLeft: 720 },
|
||||
runs: [{ text: 'formatted' }],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
const bytes = await buildDocx({ bodyXml: para })
|
||||
const doc = await parseDocx(bytes)
|
||||
// F1: parser now exposes lineRawTwips+lineRule+lineSpacing for full accuracy
|
||||
expect(doc.blocks[0].format).toMatchObject({
|
||||
align: 'right',
|
||||
lineSpacing: 2,
|
||||
lineRawTwips: 480,
|
||||
lineRule: 'auto',
|
||||
indentLeft: 720,
|
||||
})
|
||||
})
|
||||
|
||||
it('round-trips exact/atLeast line rule (previously only auto was recognized, so edits lost line spacing)', async () => {
|
||||
for (const lineRule of ['exact', 'atLeast'] as const) {
|
||||
const para = generateParagraphXml(
|
||||
{ type: 'paragraph', format: { lineRule, lineRawTwips: 216 }, runs: [{ text: 'x' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(para).toContain(`<w:spacing w:line="216" w:lineRule="${lineRule}"/>`)
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
expect(doc.blocks[0].format).toMatchObject({ lineRule, lineRawTwips: 216 })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,212 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx, TOTAL_PAGES_MARK, type SaveBlock } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
/** rich header/footer paragraphs: save (paras) -> reparse (headerParas) round trip */
|
||||
|
||||
async function base() {
|
||||
const bytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>正文</w:t></w:r></w:p>' })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const saveBlocks: SaveBlock[] = [{ kind: 'original', docxIndex: parsed.blocks[0].docxIndex! }]
|
||||
return { parsed, saveBlocks }
|
||||
}
|
||||
|
||||
describe('rich header / footer', () => {
|
||||
it('saves multi-paragraph styled header and reparses it as headerParas', async () => {
|
||||
const { parsed, saveBlocks } = await base()
|
||||
const saved = await saveDocx(parsed, saveBlocks, {
|
||||
header: {
|
||||
text: '',
|
||||
paras: [
|
||||
{ align: 'right', runs: [{ text: '机密', bold: true, color: 'FF0000' }] },
|
||||
{ runs: [{ text: '年度报告 ' }, { text: '2026', italic: true }] },
|
||||
],
|
||||
},
|
||||
})
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.headerParas).toHaveLength(2)
|
||||
expect(reparsed.headerParas![0].align).toBe('right')
|
||||
expect(reparsed.headerParas![0].runs[0]).toMatchObject({
|
||||
text: '机密',
|
||||
bold: true,
|
||||
color: 'FF0000',
|
||||
})
|
||||
expect(reparsed.headerParas![1].runs.map((r) => r.text).join('')).toBe('年度报告 2026')
|
||||
expect(reparsed.headerText).toBe('机密年度报告 2026')
|
||||
})
|
||||
|
||||
it('footer paras with # keep a real PAGE field', async () => {
|
||||
const { parsed, saveBlocks } = await base()
|
||||
const saved = await saveDocx(parsed, saveBlocks, {
|
||||
footer: {
|
||||
text: '',
|
||||
pageNumber: true,
|
||||
paras: [{ align: 'center', runs: [{ text: '第 # 页' }] }],
|
||||
},
|
||||
})
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.footerHasPageNumber).toBe(true)
|
||||
expect(reparsed.footerParas![0].runs.map((r) => r.text).join('')).toBe('第 # 页')
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const names = Object.keys(zip.files).filter((n) => /word\/footer\d+\.xml/.test(n))
|
||||
const xml = await zip.file(names[0])!.async('string')
|
||||
expect(xml).toContain('<w:instrText xml:space="preserve"> PAGE </w:instrText>')
|
||||
})
|
||||
|
||||
it('footer NUMPAGES field parses to TOTAL_PAGES_MARK and saves back as a field', async () => {
|
||||
const { parsed, saveBlocks } = await base()
|
||||
const saved = await saveDocx(parsed, saveBlocks, {
|
||||
footer: {
|
||||
text: '',
|
||||
pageNumber: true,
|
||||
paras: [{ align: 'center', runs: [{ text: `Seite # von ${TOTAL_PAGES_MARK}` }] }],
|
||||
},
|
||||
})
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const names = Object.keys(zip.files).filter((n) => /word\/footer\d+\.xml/.test(n))
|
||||
const xml = await zip.file(names[0])!.async('string')
|
||||
expect(xml).toContain('<w:instrText xml:space="preserve"> NUMPAGES </w:instrText>')
|
||||
expect(xml).not.toContain(TOTAL_PAGES_MARK)
|
||||
// Re-parse: the NUMPAGES field returns to the placeholder (no cached result lingers)
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.footerParas!.flatMap((p) => p.runs.map((r) => r.text)).join('')).toBe(
|
||||
`Seite # von ${TOTAL_PAGES_MARK}`,
|
||||
)
|
||||
})
|
||||
|
||||
it('rich header edit keeps the watermark paragraph', async () => {
|
||||
const { parsed, saveBlocks } = await base()
|
||||
const withWm = await saveDocx(parsed, saveBlocks, {
|
||||
header: { text: '旧页眉' },
|
||||
watermark: '草稿',
|
||||
})
|
||||
const reparsed = await parseDocx(withWm)
|
||||
expect(reparsed.watermarkText).toBe('草稿')
|
||||
// rich rewrite carries the watermark through (options.watermark undefined)
|
||||
const again = await saveDocx(
|
||||
reparsed,
|
||||
reparsed.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! })),
|
||||
{ header: { text: '', paras: [{ runs: [{ text: '新页眉', bold: true }] }] } },
|
||||
)
|
||||
const final = await parseDocx(again)
|
||||
expect(final.watermarkText).toBe('草稿')
|
||||
expect(final.headerParas![0].runs[0]).toMatchObject({ text: '新页眉', bold: true })
|
||||
// the watermark paragraph is not part of the text paras
|
||||
expect(final.headerText).toBe('新页眉')
|
||||
})
|
||||
})
|
||||
|
||||
describe('surgical header rewrite (real Word headers carry tables/logos)', () => {
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const HEADER_TBL =
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
|
||||
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>ACME 公司</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
|
||||
'<w:p><w:r><w:t>Logo 占位</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const RICH_HEADER =
|
||||
XML_DECL +
|
||||
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
|
||||
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
HEADER_TBL +
|
||||
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>公司内部资料</w:t></w:r></w:p>' +
|
||||
'</w:hdr>'
|
||||
|
||||
async function richHeaderDocx() {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>正文</w:t></w:r></w:p>',
|
||||
extraRels:
|
||||
'<Relationship Id="rId60" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: RICH_HEADER,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
],
|
||||
sectPrExtra: '<w:headerReference w:type="default" r:id="rId60"/>',
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
const saveBlocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
return { parsed, saveBlocks }
|
||||
}
|
||||
|
||||
it('watermark-only change keeps the header table and paragraphs byte-identical', async () => {
|
||||
const { parsed, saveBlocks } = await richHeaderDocx()
|
||||
const saved = await saveDocx(parsed, saveBlocks, { watermark: '机密' })
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const hdr = await zip.file('word/header1.xml')!.async('string')
|
||||
// Before the surgical fix: the whole part was rebuilt, losing the table and the
|
||||
// right-aligned italic paragraph
|
||||
expect(hdr).toContain(HEADER_TBL)
|
||||
expect(hdr).toContain(
|
||||
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>公司内部资料</w:t></w:r></w:p>',
|
||||
)
|
||||
expect(hdr).toContain('v:textpath')
|
||||
expect(hdr).toContain('string="机密"')
|
||||
// Then remove the watermark: the table remains, the watermark paragraph is gone
|
||||
const removed = await saveDocx(await parseDocx(saved), saveBlocks, { watermark: null })
|
||||
const hdr2 = await (
|
||||
await (await import('jszip')).default.loadAsync(removed)
|
||||
)
|
||||
.file('word/header1.xml')!
|
||||
.async('string')
|
||||
expect(hdr2).toContain(HEADER_TBL)
|
||||
expect(hdr2).not.toContain('v:textpath')
|
||||
})
|
||||
|
||||
it('header text edit replaces paragraphs but keeps the table', async () => {
|
||||
const { parsed, saveBlocks } = await richHeaderDocx()
|
||||
const saved = await saveDocx(parsed, saveBlocks, { header: { text: '新版页眉' } })
|
||||
const hdr = await (
|
||||
await (await import('jszip')).default.loadAsync(saved)
|
||||
)
|
||||
.file('word/header1.xml')!
|
||||
.async('string')
|
||||
expect(hdr).toContain(HEADER_TBL) // the table (invisible in the user's model) is kept
|
||||
expect(hdr).toContain('新版页眉')
|
||||
expect(hdr).not.toContain('公司内部资料') // the text-paragraph set was replaced
|
||||
})
|
||||
})
|
||||
|
||||
describe('header edits keep image paragraphs', () => {
|
||||
it('the logo paragraph with w:drawing keeps its original bytes; text paragraphs are replaced', async () => {
|
||||
const LOGO_P =
|
||||
'<w:p><w:pPr><w:jc w:val="left"/></w:pPr><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/></wp:inline></w:drawing></w:r></w:p>'
|
||||
const HDR =
|
||||
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
|
||||
' xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"' +
|
||||
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
LOGO_P +
|
||||
'<w:p><w:r><w:t>旧页眉文字</w:t></w:r></w:p>' +
|
||||
'</w:hdr>'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>正文</w:t></w:r></w:p>',
|
||||
extraRels:
|
||||
'<Relationship Id="rId61" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: HDR,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
],
|
||||
sectPrExtra: '<w:headerReference w:type="default" r:id="rId61"/>',
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
const saveBlocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
const saved = await saveDocx(parsed, saveBlocks, { header: { text: '新页眉文字' } })
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const hdr = await zip.file('word/header1.xml')!.async('string')
|
||||
expect(hdr).toContain(LOGO_P) // the logo paragraph keeps its original bytes
|
||||
expect(hdr).toContain('新页眉文字')
|
||||
expect(hdr).not.toContain('旧页眉文字')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
/**
|
||||
* Chinese government documents (repro) place the footer page number
|
||||
* inside a VML textbox: w:p > w:r > w:pict > v:shape > v:textbox > w:txbxContent,
|
||||
* with a complex PAGE field ("— PAGE —") whose cached result is a literal digit.
|
||||
* The parser must surface the textbox paragraphs instead of dropping the footer.
|
||||
*/
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const FTR_NS =
|
||||
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
|
||||
'xmlns:v="urn:schemas-microsoft-com:vml" ' +
|
||||
'xmlns:o="urn:schemas-microsoft-com:office:office" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'
|
||||
|
||||
const RPR =
|
||||
'<w:rPr><w:rFonts w:ascii="SimSun" w:hAnsi="SimSun" w:cs="SimSun"/><w:sz w:val="28"/><w:szCs w:val="28"/></w:rPr>'
|
||||
|
||||
/** structure copied from the repro document's word/footer1.xml (fonts renamed, ids shortened) */
|
||||
const GOV_TEXTBOX_FOOTER =
|
||||
XML_DECL +
|
||||
`<w:ftr ${FTR_NS}><w:p><w:pPr><w:pStyle w:val="6"/></w:pPr><w:r><w:pict>` +
|
||||
'<v:shape id="Text Box 8" o:spid="_x0000_s4096" o:spt="202" type="#_x0000_t202" ' +
|
||||
'style="position:absolute;left:0pt;margin-top:0pt;height:144pt;width:144pt;mso-position-horizontal:outside;mso-position-horizontal-relative:margin;mso-wrap-style:none;z-index:251659264;" ' +
|
||||
'filled="f" stroked="f" coordsize="21600,21600">' +
|
||||
'<v:path/><v:fill on="f" focussize="0,0"/><v:stroke on="f"/><v:imagedata o:title=""/>' +
|
||||
'<o:lock v:ext="edit" aspectratio="f"/>' +
|
||||
'<v:textbox inset="0mm,0mm,0mm,0mm" style="mso-fit-shape-to-text:t;"><w:txbxContent>' +
|
||||
'<w:p><w:pPr><w:pStyle w:val="6"/><w:ind w:left="315" w:leftChars="150" w:right="315" w:rightChars="150"/>' +
|
||||
`${RPR}</w:pPr>` +
|
||||
`<w:r>${RPR}<w:t xml:space="preserve">\u2014 </w:t></w:r>` +
|
||||
`<w:r>${RPR}<w:fldChar w:fldCharType="begin"/></w:r>` +
|
||||
`<w:r>${RPR}<w:instrText xml:space="preserve"> PAGE \\* MERGEFORMAT </w:instrText></w:r>` +
|
||||
`<w:r>${RPR}<w:fldChar w:fldCharType="separate"/></w:r>` +
|
||||
`<w:r>${RPR}<w:t>1</w:t></w:r>` +
|
||||
`<w:r>${RPR}<w:fldChar w:fldCharType="end"/></w:r>` +
|
||||
`<w:r>${RPR}<w:t xml:space="preserve"> \u2014</w:t></w:r>` +
|
||||
'</w:p></w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:p></w:ftr>'
|
||||
|
||||
async function parseWithFooter(footerXml: string) {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
|
||||
extraRels:
|
||||
'<Relationship Id="rId70" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/footer1.xml',
|
||||
xml: footerXml,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml',
|
||||
},
|
||||
],
|
||||
sectPrExtra: '<w:footerReference w:type="default" r:id="rId70"/>',
|
||||
})
|
||||
return parseDocx(bytes)
|
||||
}
|
||||
|
||||
describe('footer content inside a VML textbox', () => {
|
||||
it('parses the textbox paragraph into non-empty footer content with the PAGE marker', async () => {
|
||||
const parsed = await parseWithFooter(GOV_TEXTBOX_FOOTER)
|
||||
expect(parsed.footerHasPageNumber).toBe(true)
|
||||
// the "\u2014 N \u2014" literal runs survive; the PAGE field becomes the '#' marker
|
||||
expect(parsed.footerText).toBe('\u2014 # \u2014')
|
||||
expect(parsed.footerParas).not.toBeNull()
|
||||
expect(parsed.footerParas!.length).toBeGreaterThan(0)
|
||||
const line = parsed.footerParas!.flatMap((p) => p.runs.map((r) => r.text)).join('')
|
||||
expect(line).toBe('\u2014 # \u2014')
|
||||
// run formatting from inside the textbox is preserved
|
||||
const firstRun = parsed.footerParas![0].runs[0]
|
||||
expect(firstRun.font).toBe('SimSun')
|
||||
expect(firstRun.sizeHalfPoints).toBe(28)
|
||||
})
|
||||
|
||||
it('hfParts (multi-section lookup path) also carries the textbox paragraphs', async () => {
|
||||
const parsed = await parseWithFooter(GOV_TEXTBOX_FOOTER)
|
||||
const part = parsed.hfParts?.rId70
|
||||
expect(part).toBeDefined()
|
||||
expect(part!.hasPageNumber).toBe(true)
|
||||
expect(part!.paras.length).toBeGreaterThan(0)
|
||||
expect(part!.paras.flatMap((p) => p.runs.map((r) => r.text)).join('')).toBe('\u2014 # \u2014')
|
||||
})
|
||||
|
||||
it('footer PAGE field with a cached result drops the stale number and keeps literal runs', async () => {
|
||||
// same field structure but as a plain paragraph (no textbox): cached "7" must
|
||||
// not leak into the display text; the marker takes its place
|
||||
const plainFooter =
|
||||
XML_DECL +
|
||||
`<w:ftr ${FTR_NS}><w:p>` +
|
||||
'<w:r><w:t xml:space="preserve">\u2014 </w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> PAGE \\* MERGEFORMAT </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:t>7</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'<w:r><w:t xml:space="preserve"> \u2014</w:t></w:r>' +
|
||||
'</w:p></w:ftr>'
|
||||
const parsed = await parseWithFooter(plainFooter)
|
||||
expect(parsed.footerHasPageNumber).toBe(true)
|
||||
expect(parsed.footerText).toBe('\u2014 # \u2014')
|
||||
expect(parsed.footerParas!.flatMap((p) => p.runs.map((r) => r.text)).join('')).toBe(
|
||||
'\u2014 # \u2014',
|
||||
)
|
||||
})
|
||||
|
||||
it('an empty decorative textbox still contributes no footer paragraphs', async () => {
|
||||
const emptyTextboxFooter =
|
||||
XML_DECL +
|
||||
`<w:ftr ${FTR_NS}><w:p><w:r><w:pict>` +
|
||||
'<v:shape id="s1" o:spt="202" type="#_x0000_t202" style="position:absolute;" filled="t" stroked="f">' +
|
||||
'<v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox>' +
|
||||
'</v:shape></w:pict></w:r></w:p></w:ftr>'
|
||||
const parsed = await parseWithFooter(emptyTextboxFooter)
|
||||
expect(parsed.footerParas ?? []).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,245 @@
|
||||
import JSZip from 'jszip'
|
||||
|
||||
/** 1x1 red PNG */
|
||||
export const TINY_PNG_BASE64 =
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
|
||||
|
||||
export interface BuildDocxOptions {
|
||||
/** raw XML of <w:body> children (without w:sectPr; one is appended automatically) */
|
||||
bodyXml: string
|
||||
/** extra <w:style> entries appended to the default styles.xml */
|
||||
extraStylesXml?: string
|
||||
withNumbering?: boolean
|
||||
/** full word/numbering.xml content (implies withNumbering) */
|
||||
numberingXml?: string
|
||||
withImage?: boolean
|
||||
/** extra Relationship entries for word/_rels/document.xml.rels */
|
||||
extraRels?: string
|
||||
/** extra zip parts (charts etc.) with their [Content_Types].xml override */
|
||||
extraParts?: Array<{ path: string; xml: string; contentType: string }>
|
||||
/** extra sectPr children inserted first (headerReference/footerReference…) */
|
||||
sectPrExtra?: string
|
||||
}
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
const DOC_NS =
|
||||
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
|
||||
'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ' +
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
|
||||
'xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" ' +
|
||||
'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"'
|
||||
|
||||
const STYLES_XML_OPEN =
|
||||
XML_DECL +
|
||||
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/>' +
|
||||
'<w:pPr><w:outlineLvl w:val="0"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/></w:rPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/>' +
|
||||
'<w:pPr><w:outlineLvl w:val="1"/></w:pPr><w:rPr><w:b/><w:sz w:val="28"/></w:rPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/></w:style>' +
|
||||
'<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/>' +
|
||||
'<w:rPr><w:color w:val="0563C1"/><w:u w:val="single"/></w:rPr></w:style>'
|
||||
|
||||
const NUMBERING_XML =
|
||||
XML_DECL +
|
||||
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val=""/></w:lvl></w:abstractNum>' +
|
||||
'<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>' +
|
||||
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
|
||||
'<w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>' +
|
||||
'</w:numbering>'
|
||||
|
||||
export async function buildDocx(options: BuildDocxOptions): Promise<Uint8Array> {
|
||||
const zip = new JSZip()
|
||||
const withNumbering = options.withNumbering || options.numberingXml !== undefined
|
||||
|
||||
const contentTypes = [
|
||||
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>',
|
||||
'<Default Extension="xml" ContentType="application/xml"/>',
|
||||
options.withImage ? '<Default Extension="png" ContentType="image/png"/>' : '',
|
||||
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>',
|
||||
'<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>',
|
||||
withNumbering
|
||||
? '<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>'
|
||||
: '',
|
||||
...(options.extraParts ?? []).map(
|
||||
(p) => `<Override PartName="/${p.path}" ContentType="${p.contentType}"/>`,
|
||||
),
|
||||
].join('')
|
||||
zip.file(
|
||||
'[Content_Types].xml',
|
||||
`${XML_DECL}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${contentTypes}</Types>`,
|
||||
)
|
||||
|
||||
zip.file(
|
||||
'_rels/.rels',
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
|
||||
const docRels = [
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>',
|
||||
withNumbering
|
||||
? '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>'
|
||||
: '',
|
||||
options.withImage
|
||||
? '<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>'
|
||||
: '',
|
||||
options.extraRels ?? '',
|
||||
].join('')
|
||||
zip.file(
|
||||
'word/_rels/document.xml.rels',
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${docRels}</Relationships>`,
|
||||
)
|
||||
|
||||
zip.file('word/styles.xml', `${STYLES_XML_OPEN}${options.extraStylesXml ?? ''}</w:styles>`)
|
||||
if (withNumbering) zip.file('word/numbering.xml', options.numberingXml ?? NUMBERING_XML)
|
||||
if (options.withImage) zip.file('word/media/image1.png', TINY_PNG_BASE64, { base64: true })
|
||||
for (const part of options.extraParts ?? []) zip.file(part.path, part.xml)
|
||||
|
||||
const sectPr =
|
||||
`<w:sectPr>${options.sectPrExtra ?? ''}<w:pgSz w:w="11906" w:h="16838"/>` +
|
||||
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
|
||||
'</w:sectPr>'
|
||||
zip.file(
|
||||
'word/document.xml',
|
||||
`${XML_DECL}<w:document ${DOC_NS}><w:body>${options.bodyXml}${sectPr}</w:body></w:document>`,
|
||||
)
|
||||
|
||||
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
|
||||
}
|
||||
|
||||
export const IMAGE_PARAGRAPH_XML =
|
||||
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
|
||||
|
||||
export const MATH_PARAGRAPH_XML =
|
||||
'<w:p><m:oMath><m:r><m:t>E=mc^2</m:t></m:r></m:oMath></w:p>'
|
||||
|
||||
export const CHART_PARAGRAPH_XML =
|
||||
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="5486400" cy="3200400"/>' +
|
||||
'<wp:docPr id="1" name="图表 1"/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/chart">' +
|
||||
'<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId30"/>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
|
||||
|
||||
const chartStrCache = (values: string[], f: string) =>
|
||||
`<c:strRef><c:f>${f}</c:f><c:strCache><c:ptCount val="${values.length}"/>` +
|
||||
values.map((v, i) => `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`).join('') +
|
||||
'</c:strCache></c:strRef>'
|
||||
|
||||
const chartNumCache = (values: (number | null)[], f: string) =>
|
||||
`<c:numRef><c:f>${f}</c:f><c:numCache><c:formatCode>General</c:formatCode>` +
|
||||
`<c:ptCount val="${values.length}"/>` +
|
||||
values
|
||||
.map((v, i) => (v === null ? '' : `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`))
|
||||
.join('') +
|
||||
'</c:numCache></c:numRef>'
|
||||
|
||||
/** bar chart part: title, 2 series over 3 categories, with a gap in series 2 */
|
||||
export const CHART_PART_XML =
|
||||
XML_DECL +
|
||||
'<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ' +
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
'<c:chart><c:title><c:tx><c:rich><a:bodyPr/><a:p><a:r><a:t>销售</a:t></a:r><a:r><a:t>统计</a:t></a:r></a:p></c:rich></c:tx><c:overlay val="0"/></c:title>' +
|
||||
'<c:plotArea><c:layout/><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>' +
|
||||
'<c:ser><c:idx val="0"/><c:order val="0"/>' +
|
||||
`<c:tx>${chartStrCache(['华东'], 'Sheet1!$B$1')}</c:tx>` +
|
||||
`<c:cat>${chartStrCache(['一月', '二月', '三月'], 'Sheet1!$A$2:$A$4')}</c:cat>` +
|
||||
`<c:val>${chartNumCache([120, 88.5, 96], 'Sheet1!$B$2:$B$4')}</c:val>` +
|
||||
'</c:ser>' +
|
||||
'<c:ser><c:idx val="1"/><c:order val="1"/>' +
|
||||
`<c:tx>${chartStrCache(['华南'], 'Sheet1!$C$1')}</c:tx>` +
|
||||
`<c:cat>${chartStrCache(['一月', '二月', '三月'], 'Sheet1!$A$2:$A$4')}</c:cat>` +
|
||||
`<c:val>${chartNumCache([70, null, 110], 'Sheet1!$C$2:$C$4')}</c:val>` +
|
||||
'</c:ser>' +
|
||||
'<c:axId val="111"/><c:axId val="222"/></c:barChart></c:plotArea></c:chart></c:chartSpace>'
|
||||
|
||||
export const CHART_RELS =
|
||||
'<Relationship Id="rId30" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="charts/chart1.xml"/>'
|
||||
|
||||
/** a document whose only body content is one embedded bar chart */
|
||||
export async function buildChartDocx(bodyPrefixXml = ''): Promise<Uint8Array> {
|
||||
return buildDocx({
|
||||
bodyXml: bodyPrefixXml + CHART_PARAGRAPH_XML,
|
||||
extraRels: CHART_RELS,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/charts/chart1.xml',
|
||||
xml: CHART_PART_XML,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
export const TABLE_XML =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>A2</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>B2</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'</w:tbl>'
|
||||
|
||||
/** A representative document exercising every block type the engine supports. */
|
||||
export function kitchenSinkBody(): string {
|
||||
return [
|
||||
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>第一章 概述</w:t></w:r></w:p>',
|
||||
'<w:p><w:r><w:t xml:space="preserve">普通段落,包含</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:b/></w:rPr><w:t>加粗</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:i/></w:rPr><w:t>斜体</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>下划线</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:strike/></w:rPr><w:t>删除线</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:color w:val="FF0000"/><w:sz w:val="28"/></w:rPr><w:t>红色14号</w:t></w:r>' +
|
||||
'<w:r><w:t xml:space="preserve">与特殊字符 & < > 结束。</w:t></w:r></w:p>',
|
||||
'<w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>1.1 列表</w:t></w:r></w:p>',
|
||||
'<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>无序项一</w:t></w:r></w:p>',
|
||||
'<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>无序项二</w:t></w:r></w:p>',
|
||||
'<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>有序项一</w:t></w:r></w:p>',
|
||||
'<w:p><w:r><w:t xml:space="preserve">链接示例:</w:t></w:r>' +
|
||||
'<w:hyperlink r:id="rId20"><w:r><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>示例网站</w:t></w:r></w:hyperlink></w:p>',
|
||||
TABLE_XML,
|
||||
IMAGE_PARAGRAPH_XML,
|
||||
MATH_PARAGRAPH_XML,
|
||||
'<w:p><w:r><w:t>尾段。</w:t></w:r></w:p>',
|
||||
].join('')
|
||||
}
|
||||
|
||||
export async function buildKitchenSinkDocx(): Promise<Uint8Array> {
|
||||
return buildDocx({
|
||||
bodyXml: kitchenSinkBody(),
|
||||
withNumbering: true,
|
||||
withImage: true,
|
||||
extraRels:
|
||||
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/" TargetMode="External"/>',
|
||||
})
|
||||
}
|
||||
|
||||
/** 2x3 table: row 2 has a whole-row delete revision (trPr w:del + delText), row 3 cell A has cellIns */
|
||||
export const REVISION_TABLE_XML =
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'<w:tr><w:trPr><w:del w:id="11" w:author="Alice" w:date="2026-01-01T00:00:00Z"/></w:trPr>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:del w:id="13" w:author="Alice" w:date="2026-01-01T00:00:00Z"><w:r><w:delText>A2del</w:delText></w:r></w:del></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:del w:id="14" w:author="Alice" w:date="2026-01-01T00:00:00Z"><w:r><w:delText>B2del</w:delText></w:r></w:del></w:p></w:tc></w:tr>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/><w:cellIns w:id="15" w:author="Alice" w:date="2026-01-01T00:00:00Z"/></w:tcPr><w:p><w:r><w:t>A3</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>B3</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'</w:tbl>'
|
||||
|
||||
/** outer 1x2 table, cell A contains a 2x1 nested table (InnerA/InnerB) + trailing empty paragraph */
|
||||
export const NESTED_TABLE_XML =
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="3000"/><w:gridCol w:w="3000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>Outer</w:t></w:r></w:p>' +
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr><w:tblGrid><w:gridCol w:w="1000"/><w:gridCol w:w="1000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>InnerA</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>InnerB</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'</w:tbl><w:p/></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>RightCell</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'</w:tbl>'
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const HEADER_XML =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
|
||||
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"' +
|
||||
' xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"' +
|
||||
' xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"' +
|
||||
' xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<w:p><w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0">' +
|
||||
'<wp:extent cx="381000" cy="190500"/><wp:docPr id="1" name="Logo"/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>Confidential</w:t></w:r></w:p>' +
|
||||
'</w:hdr>'
|
||||
|
||||
const HEADER_RELS =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
async function buildHeaderLogoDocx(): Promise<Uint8Array> {
|
||||
return buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>Body</w:t></w:r></w:p>',
|
||||
withImage: true,
|
||||
extraRels:
|
||||
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
|
||||
sectPrExtra: '<w:headerReference w:type="default" r:id="rId20"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: HEADER_XML,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
{
|
||||
path: 'word/_rels/header1.xml.rels',
|
||||
xml: HEADER_RELS,
|
||||
contentType: 'application/vnd.openxmlformats-package.relationships+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
describe('header/footer images (display-only Logo)', () => {
|
||||
it('parses header images with size, text paragraphs unaffected', async () => {
|
||||
const doc = await parseDocx(await buildHeaderLogoDocx())
|
||||
expect(doc.headerImages).toHaveLength(1)
|
||||
const img = doc.headerImages![0]
|
||||
expect(img.dataUrl.startsWith('data:image/png;base64,')).toBe(true)
|
||||
expect(img.widthPx).toBe(40)
|
||||
expect(img.heightPx).toBe(20)
|
||||
expect(img.floating).toBeUndefined()
|
||||
// text paragraphs enter the model as usual; image paragraphs produce no empty text paragraph
|
||||
expect(doc.headerText).toBe('Confidential')
|
||||
// hfParts (multi-section path) carries images too
|
||||
const part = Object.values(doc.hfParts ?? {}).find((p) => p.text === 'Confidential')
|
||||
expect(part?.images).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('untouched round-trip stays byte-identical', async () => {
|
||||
const bytes = await buildHeaderLogoDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const blocks = doc.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
|
||||
expect(await saveDocx(doc, blocks)).toEqual(bytes)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const BODY = '<w:p><w:r><w:t>正文</w:t></w:r></w:p>'
|
||||
|
||||
async function zipText(bytes: Uint8Array, path: string): Promise<string | null> {
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
const file = zip.file(path)
|
||||
return file ? file.async('string') : null
|
||||
}
|
||||
|
||||
describe('first-page / even-page headers & footers', () => {
|
||||
it('creates typed parts, references and flags; round-trips through parse', async () => {
|
||||
const source = await buildDocx({ bodyXml: BODY })
|
||||
const parsed = await parseDocx(source)
|
||||
expect(parsed.titlePg).toBe(false)
|
||||
expect(parsed.evenAndOddHeaders).toBe(false)
|
||||
expect(parsed.headerFirst).toBeNull()
|
||||
|
||||
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
|
||||
header: { text: '默认页眉' },
|
||||
headerFirst: { text: '首页页眉' },
|
||||
headerEven: { text: '偶数页页眉' },
|
||||
footerEven: { text: '偶 #', pageNumber: true },
|
||||
titlePg: true,
|
||||
evenAndOddHeaders: true,
|
||||
})
|
||||
|
||||
const docXml = (await zipText(saved, 'word/document.xml'))!
|
||||
expect(docXml).toContain('<w:titlePg/>')
|
||||
expect(docXml).toMatch(/<w:headerReference w:type="first"/)
|
||||
expect(docXml).toMatch(/<w:headerReference w:type="even"/)
|
||||
expect(docXml).toMatch(/<w:footerReference w:type="even"/)
|
||||
const settingsXml = (await zipText(saved, 'word/settings.xml'))!
|
||||
expect(settingsXml).toContain('<w:evenAndOddHeaders/>')
|
||||
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.titlePg).toBe(true)
|
||||
expect(reparsed.evenAndOddHeaders).toBe(true)
|
||||
expect(reparsed.headerText).toBe('默认页眉')
|
||||
expect(reparsed.headerFirst?.text).toBe('首页页眉')
|
||||
expect(reparsed.headerEven?.text).toBe('偶数页页眉')
|
||||
expect(reparsed.footerEven?.text).toBe('偶 #')
|
||||
expect(reparsed.footerEven?.hasPageNumber).toBe(true)
|
||||
expect(reparsed.footerFirst).toBeNull()
|
||||
})
|
||||
|
||||
it('gives each new part a distinct filename in a single save', async () => {
|
||||
const source = await buildDocx({ bodyXml: BODY })
|
||||
const parsed = await parseDocx(source)
|
||||
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
|
||||
header: { text: 'a' },
|
||||
headerFirst: { text: 'b' },
|
||||
headerEven: { text: 'c' },
|
||||
})
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
const headers = Object.keys(zip.files).filter((n) => /^word\/header\d+\.xml$/.test(n))
|
||||
expect(headers.sort()).toEqual(['word/header1.xml', 'word/header2.xml', 'word/header3.xml'])
|
||||
})
|
||||
|
||||
it('rewrites only the edited variant; the others stay byte-identical', async () => {
|
||||
const source = await buildDocx({ bodyXml: BODY })
|
||||
const parsed = await parseDocx(source)
|
||||
const withBoth = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
|
||||
header: { text: '默认' },
|
||||
headerFirst: { text: '首页' },
|
||||
titlePg: true,
|
||||
})
|
||||
const p2 = await parseDocx(withBoth)
|
||||
const firstPartBefore = await zipText(withBoth, 'word/header2.xml')
|
||||
const edited = await saveDocx(p2, [{ kind: 'original', docxIndex: 0 }], {
|
||||
header: { text: '默认已改' },
|
||||
})
|
||||
expect(await zipText(edited, 'word/header2.xml')).toBe(firstPartBefore)
|
||||
const p3 = await parseDocx(edited)
|
||||
expect(p3.headerText).toBe('默认已改')
|
||||
expect(p3.headerFirst?.text).toBe('首页')
|
||||
expect(p3.titlePg).toBe(true)
|
||||
})
|
||||
|
||||
it('removes titlePg and evenAndOddHeaders when toggled off', async () => {
|
||||
const source = await buildDocx({ bodyXml: BODY })
|
||||
const parsed = await parseDocx(source)
|
||||
const on = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
|
||||
titlePg: true,
|
||||
evenAndOddHeaders: true,
|
||||
})
|
||||
const p2 = await parseDocx(on)
|
||||
const off = await saveDocx(p2, [{ kind: 'original', docxIndex: 0 }], {
|
||||
titlePg: false,
|
||||
evenAndOddHeaders: false,
|
||||
})
|
||||
const p3 = await parseDocx(off)
|
||||
expect(p3.titlePg).toBe(false)
|
||||
expect(p3.evenAndOddHeaders).toBe(false)
|
||||
expect(await zipText(off, 'word/document.xml')).not.toContain('<w:titlePg/>')
|
||||
})
|
||||
|
||||
it('keeps titlePg before w:docGrid in schema order', async () => {
|
||||
const source = await buildDocx({ bodyXml: BODY })
|
||||
// inject a docGrid into the trailing sectPr
|
||||
const zip = await JSZip.loadAsync(source)
|
||||
const docXml = (await zip.file('word/document.xml')!.async('string')).replace(
|
||||
'</w:sectPr>',
|
||||
'<w:docGrid w:linePitch="360"/></w:sectPr>',
|
||||
)
|
||||
zip.file('word/document.xml', docXml)
|
||||
const parsed = await parseDocx(await zip.generateAsync({ type: 'uint8array' }))
|
||||
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], { titlePg: true })
|
||||
const out = (await zipText(saved, 'word/document.xml'))!
|
||||
expect(out.indexOf('<w:titlePg/>')).toBeGreaterThan(-1)
|
||||
expect(out.indexOf('<w:titlePg/>')).toBeLessThan(out.indexOf('<w:docGrid'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { applyImageWrap, parseDocx, patchImageParagraphXml } from '../src/index'
|
||||
import { buildDocx, IMAGE_PARAGRAPH_XML } from './helpers/build-docx'
|
||||
|
||||
/** A minimal floating image paragraph with numeric posOffset */
|
||||
const ANCHOR_IMAGE_XML =
|
||||
'<w:p><w:r><w:drawing>' +
|
||||
'<wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="251658240" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">' +
|
||||
'<wp:simplePos x="0" y="0"/>' +
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>914400</wp:posOffset></wp:positionH>' +
|
||||
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>457200</wp:posOffset></wp:positionV>' +
|
||||
'<wp:extent cx="914400" cy="914400"/>' +
|
||||
'<wp:wrapSquare wrapText="bothSides"/>' +
|
||||
'<wp:docPr id="1" name="图片 1"/>' +
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic>' +
|
||||
'</wp:anchor>' +
|
||||
'</w:drawing></w:r></w:p>'
|
||||
|
||||
describe('image metadata parsing', () => {
|
||||
it('exposes display size from wp:extent', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true }))
|
||||
const img = doc.blocks[0]
|
||||
expect(img.type).toBe('image')
|
||||
// 914400 EMU = 96 px
|
||||
expect(img.imageWidthPx).toBe(96)
|
||||
expect(img.imageHeightPx).toBe(96)
|
||||
expect(img.imageAlign).toBeUndefined()
|
||||
})
|
||||
|
||||
it('exposes centered alignment', async () => {
|
||||
const centered = IMAGE_PARAGRAPH_XML.replace(
|
||||
'<w:p>',
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr>',
|
||||
)
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: centered, withImage: true }))
|
||||
expect(doc.blocks[0].imageAlign).toBe('center')
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchImageParagraphXml', () => {
|
||||
it('rewrites wp:extent and a:ext size', () => {
|
||||
const xml =
|
||||
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="457200"/>' +
|
||||
'<a:graphic><pic:pic><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm></pic:spPr></pic:pic></a:graphic>' +
|
||||
'</wp:inline></w:drawing></w:r></w:p>'
|
||||
const out = patchImageParagraphXml(xml, { widthPx: 192, heightPx: 96 })
|
||||
expect(out).toContain('<wp:extent cx="1828800" cy="914400"/>')
|
||||
expect(out).toContain('<a:ext cx="1828800" cy="914400"/>')
|
||||
})
|
||||
|
||||
it('adds, replaces and removes w:jc', () => {
|
||||
const xml = '<w:p><w:r><w:t>x</w:t></w:r></w:p>'
|
||||
const centered = patchImageParagraphXml(xml, { align: 'center' })
|
||||
expect(centered).toContain('<w:pPr><w:jc w:val="center"/></w:pPr>')
|
||||
|
||||
const right = patchImageParagraphXml(centered, { align: 'right' })
|
||||
expect(right).toContain('<w:jc w:val="right"/>')
|
||||
expect(right).not.toContain('w:val="center"')
|
||||
|
||||
const cleared = patchImageParagraphXml(right, { align: null })
|
||||
expect(cleared).not.toContain('<w:jc')
|
||||
})
|
||||
|
||||
it('inserts w:jc before the paragraph-mark rPr', () => {
|
||||
const xml = '<w:p><w:pPr><w:rPr><w:b/></w:rPr></w:pPr><w:r><w:t>x</w:t></w:r></w:p>'
|
||||
const out = patchImageParagraphXml(xml, { align: 'center' })
|
||||
expect(out).toContain('<w:pPr><w:jc w:val="center"/><w:rPr><w:b/></w:rPr></w:pPr>')
|
||||
})
|
||||
|
||||
it('round-trips size + align through the parser', async () => {
|
||||
const patched = patchImageParagraphXml(IMAGE_PARAGRAPH_XML, {
|
||||
widthPx: 200,
|
||||
heightPx: 150,
|
||||
align: 'center',
|
||||
})
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: patched, withImage: true }))
|
||||
expect(doc.blocks[0].imageWidthPx).toBe(200)
|
||||
expect(doc.blocks[0].imageHeightPx).toBe(150)
|
||||
expect(doc.blocks[0].imageAlign).toBe('center')
|
||||
})
|
||||
})
|
||||
|
||||
describe('image posOffset (free-position drag)', () => {
|
||||
it('parses posOffset from anchor images', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: ANCHOR_IMAGE_XML, withImage: true }))
|
||||
const img = doc.blocks[0]
|
||||
expect(img.type).toBe('image')
|
||||
expect(img.imageOffsetXEmu).toBe(914400)
|
||||
expect(img.imageOffsetYEmu).toBe(457200)
|
||||
expect(img.imageWrap).toBe('square-left')
|
||||
})
|
||||
|
||||
it('patchImageParagraphXml rewrites posOffset values', () => {
|
||||
const out = patchImageParagraphXml(ANCHOR_IMAGE_XML, {
|
||||
posOffsetX: 1828800,
|
||||
posOffsetY: 914400,
|
||||
})
|
||||
expect(out).toContain('<wp:positionH relativeFrom="column"><wp:posOffset>1828800</wp:posOffset></wp:positionH>')
|
||||
expect(out).toContain('<wp:positionV relativeFrom="paragraph"><wp:posOffset>914400</wp:posOffset></wp:positionV>')
|
||||
// Original structure untouched
|
||||
expect(out).toContain('relativeHeight="251658240"')
|
||||
})
|
||||
|
||||
it('patchImageParagraphXml leaves images without posOffset unchanged', () => {
|
||||
// IMAGE_PARAGRAPH_XML is inline (no posOffset) — no rewrite should happen
|
||||
const unchanged = patchImageParagraphXml(IMAGE_PARAGRAPH_XML, {
|
||||
posOffsetX: 100000,
|
||||
})
|
||||
expect(unchanged).toBe(IMAGE_PARAGRAPH_XML)
|
||||
})
|
||||
|
||||
it('applyImageWrap with posOffset uses numeric posOffset instead of align', () => {
|
||||
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left', { x: 914400, y: 457200 })
|
||||
expect(out).toContain('<wp:positionH relativeFrom="column"><wp:posOffset>914400</wp:posOffset></wp:positionH>')
|
||||
expect(out).toContain('<wp:positionV relativeFrom="paragraph"><wp:posOffset>457200</wp:posOffset></wp:positionV>')
|
||||
expect(out).not.toContain('<wp:align>')
|
||||
})
|
||||
|
||||
it('applyImageWrap without posOffset uses named alignment', () => {
|
||||
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left')
|
||||
expect(out).toContain('<wp:align>left</wp:align>')
|
||||
// V position uses posOffset(0) when no numeric offset provided (existing behavior)
|
||||
expect(out).toContain('<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>')
|
||||
// H position uses named align, not posOffset
|
||||
expect(out).not.toContain('<wp:positionH relativeFrom="column"><wp:posOffset>')
|
||||
})
|
||||
|
||||
it('round-trips posOffset through the parser', async () => {
|
||||
// Apply wrap with posOffset, then parse back
|
||||
const wrapped = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left', { x: 1828800, y: 914400 })
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: wrapped, withImage: true }))
|
||||
const img = doc.blocks[0]
|
||||
expect(img.imageWrap).toBe('square-left')
|
||||
expect(img.imageOffsetXEmu).toBe(1828800)
|
||||
expect(img.imageOffsetYEmu).toBe(914400)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { applyImageWrap, parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx, IMAGE_PARAGRAPH_XML } from './helpers/build-docx'
|
||||
|
||||
const ANCHOR_SQUARE_RIGHT_XML =
|
||||
'<w:p><w:r><w:drawing>' +
|
||||
'<wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="1" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">' +
|
||||
'<wp:simplePos x="0" y="0"/>' +
|
||||
'<wp:positionH relativeFrom="column"><wp:align>right</wp:align></wp:positionH>' +
|
||||
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>' +
|
||||
'<wp:extent cx="914400" cy="914400"/>' +
|
||||
'<wp:wrapSquare wrapText="bothSides"/>' +
|
||||
'<wp:docPr id="1" name="图片 1"/>' +
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>'
|
||||
|
||||
describe('image text wrap (wp:anchor)', () => {
|
||||
it('parses wrap mode from anchored images', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: ANCHOR_SQUARE_RIGHT_XML, withImage: true })
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].type).toBe('image')
|
||||
expect(doc.blocks[0].imageWrap).toBe('square-right')
|
||||
})
|
||||
|
||||
it('parses behind / topAndBottom / front variants', async () => {
|
||||
const behind = ANCHOR_SQUARE_RIGHT_XML.replace('behindDoc="0"', 'behindDoc="1"')
|
||||
const topBottom = ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'<wp:wrapSquare wrapText="bothSides"/>',
|
||||
'<wp:wrapTopAndBottom/>',
|
||||
)
|
||||
const front = ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'<wp:wrapSquare wrapText="bothSides"/>',
|
||||
'<wp:wrapNone/>',
|
||||
)
|
||||
for (const [xml, expected] of [
|
||||
[behind, 'behind'],
|
||||
[topBottom, 'topBottom'],
|
||||
[front, 'front'],
|
||||
] as const) {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml, withImage: true }))
|
||||
expect(doc.blocks[0].imageWrap).toBe(expected)
|
||||
}
|
||||
const inline = await parseDocx(
|
||||
await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true }),
|
||||
)
|
||||
expect(inline.blocks[0].imageWrap).toBeUndefined()
|
||||
})
|
||||
|
||||
it('converts inline -> square anchor with position and wrap elements', () => {
|
||||
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left')
|
||||
expect(out).toContain('<wp:anchor')
|
||||
expect(out).not.toContain('<wp:inline')
|
||||
expect(out).toContain('behindDoc="0"')
|
||||
expect(out).toContain('<wp:align>left</wp:align>')
|
||||
expect(out).toContain('<wp:wrapSquare wrapText="bothSides"/>')
|
||||
// schema order: positionH before extent, wrap after extent and before the graphic
|
||||
expect(out.indexOf('<wp:positionH')).toBeLessThan(out.indexOf('<wp:extent'))
|
||||
expect(out.indexOf('<wp:wrapSquare')).toBeGreaterThan(out.indexOf('<wp:extent'))
|
||||
expect(out.indexOf('<wp:wrapSquare')).toBeLessThan(out.indexOf('<a:graphic'))
|
||||
})
|
||||
|
||||
it('converts anchor -> inline', () => {
|
||||
const out = applyImageWrap(ANCHOR_SQUARE_RIGHT_XML, null)
|
||||
expect(out).toContain('<wp:inline')
|
||||
expect(out).not.toContain('<wp:anchor')
|
||||
expect(out).not.toContain('wp:positionH')
|
||||
expect(out).not.toContain('wp:wrapSquare')
|
||||
expect(out).toContain('<wp:extent cx="914400"')
|
||||
})
|
||||
|
||||
it('changes wrap on an existing anchor', () => {
|
||||
const out = applyImageWrap(ANCHOR_SQUARE_RIGHT_XML, 'behind')
|
||||
expect(out).toContain('behindDoc="1"')
|
||||
expect(out).toContain('<wp:wrapNone/>')
|
||||
expect(out).not.toContain('wp:wrapSquare')
|
||||
})
|
||||
|
||||
it('applies margin-relative position presets (Word position gallery)', () => {
|
||||
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-right', undefined, {
|
||||
h: 'center',
|
||||
v: 'bottom',
|
||||
})
|
||||
expect(out).toContain(
|
||||
'<wp:positionH relativeFrom="margin"><wp:align>center</wp:align></wp:positionH>',
|
||||
)
|
||||
expect(out).toContain(
|
||||
'<wp:positionV relativeFrom="margin"><wp:align>bottom</wp:align></wp:positionV>',
|
||||
)
|
||||
expect(out).toContain('<wp:wrapSquare wrapText="bothSides"/>')
|
||||
})
|
||||
|
||||
it('round-trips a position preset through saveDocx + reparse', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const saved = await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'xml',
|
||||
xml: applyImageWrap(parsed.blocks[0].originalXml!, 'square-left', undefined, {
|
||||
h: 'left',
|
||||
v: 'top',
|
||||
}),
|
||||
},
|
||||
])
|
||||
const p2 = await parseDocx(saved)
|
||||
expect(p2.blocks[0].imageWrap).toBe('square-left')
|
||||
expect(p2.blocks[0].imagePosH).toBe('left')
|
||||
expect(p2.blocks[0].imagePosV).toBe('top')
|
||||
// numeric posOffset must not leak in from the align-based position
|
||||
expect(p2.blocks[0].imageOffsetXEmu).toBeUndefined()
|
||||
})
|
||||
|
||||
it('round-trips wrap changes through saveDocx', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const floated = await saveDocx(parsed, [
|
||||
{ kind: 'xml', xml: applyImageWrap(parsed.blocks[0].originalXml!, 'square-right') },
|
||||
])
|
||||
const p2 = await parseDocx(floated)
|
||||
expect(p2.blocks[0].imageWrap).toBe('square-right')
|
||||
const backInline = await saveDocx(p2, [
|
||||
{ kind: 'xml', xml: applyImageWrap(p2.blocks[0].originalXml!, null) },
|
||||
])
|
||||
const p3 = await parseDocx(backInline)
|
||||
expect(p3.blocks[0].imageWrap).toBeUndefined()
|
||||
expect(p3.blocks[0].imageDataUrl).toBeTruthy()
|
||||
})
|
||||
|
||||
it('embeds new images as anchors when NewImage.wrap is set', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const saved = await saveDocx(parsed, [
|
||||
{ kind: 'original', docxIndex: 0 },
|
||||
{
|
||||
kind: 'image',
|
||||
image: {
|
||||
base64:
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
|
||||
mime: 'image/png',
|
||||
widthPx: 100,
|
||||
heightPx: 80,
|
||||
wrap: 'square-left',
|
||||
},
|
||||
},
|
||||
])
|
||||
const p2 = await parseDocx(saved)
|
||||
const img = p2.blocks.find((b) => b.type === 'image')!
|
||||
expect(img.imageWrap).toBe('square-left')
|
||||
expect(img.imageWidthPx).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
const WRAP_TIGHT_POLYGON =
|
||||
'<wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="0">' +
|
||||
'<wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/>' +
|
||||
'<wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapTight>'
|
||||
|
||||
describe('tight / through wrap (wrapPolygon fidelity)', () => {
|
||||
const tightXml = ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'<wp:wrapSquare wrapText="bothSides"/>',
|
||||
WRAP_TIGHT_POLYGON,
|
||||
)
|
||||
const throughXml = ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'<wp:wrapSquare wrapText="bothSides"/>',
|
||||
'<wp:wrapThrough wrapText="bothSides"><wp:wrapPolygon><wp:start x="1" y="2"/></wp:wrapPolygon></wp:wrapThrough>',
|
||||
)
|
||||
|
||||
it('parses tight / through as their own modes (no square downgrade)', async () => {
|
||||
const tight = await parseDocx(await buildDocx({ bodyXml: tightXml, withImage: true }))
|
||||
expect(tight.blocks[0].imageWrap).toBe('tight-right')
|
||||
const through = await parseDocx(await buildDocx({ bodyXml: throughXml, withImage: true }))
|
||||
expect(through.blocks[0].imageWrap).toBe('through-right')
|
||||
})
|
||||
|
||||
it('re-applying the same tight wrap keeps the original wrapPolygon bytes', () => {
|
||||
const out = applyImageWrap(tightXml, 'tight-right')
|
||||
expect(out).toContain(WRAP_TIGHT_POLYGON)
|
||||
expect(out).not.toContain('wp:wrapSquare')
|
||||
})
|
||||
|
||||
it('free-position drag (posOffset) on a tight image keeps the polygon', () => {
|
||||
const out = applyImageWrap(tightXml, 'tight-right', { x: 12345, y: 67890 })
|
||||
expect(out).toContain('<wp:posOffset>12345</wp:posOffset>')
|
||||
expect(out).toContain(WRAP_TIGHT_POLYGON)
|
||||
})
|
||||
|
||||
it('explicitly switching a tight image to square rebuilds as wrapSquare', () => {
|
||||
const out = applyImageWrap(tightXml, 'square-left')
|
||||
expect(out).toContain('<wp:wrapSquare wrapText="bothSides"/>')
|
||||
expect(out).not.toContain('wp:wrapTight')
|
||||
})
|
||||
|
||||
it('tight wrap round-trips through save + reparse', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: tightXml, withImage: true })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const saved = await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'xml',
|
||||
xml: applyImageWrap(parsed.blocks[0].originalXml!, 'tight-right', { x: 100, y: 200 }),
|
||||
},
|
||||
])
|
||||
const p2 = await parseDocx(saved)
|
||||
expect(p2.blocks[0].imageWrap).toBe('tight-left')
|
||||
expect(p2.blocks[0].imageOffsetXEmu).toBe(100)
|
||||
expect(p2.blocks[0].originalXml).toContain('<wp:wrapPolygon')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,191 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
INK_NAME_PREFIX,
|
||||
injectInkRunsIntoParagraph,
|
||||
parseDocx,
|
||||
saveDocx,
|
||||
stripInkRuns,
|
||||
type NewInkImage,
|
||||
type SaveBlock,
|
||||
} from '../src/index'
|
||||
import { buildDocx, TINY_PNG_BASE64 } from './helpers/build-docx'
|
||||
|
||||
const TWO_PARAS = '<w:p><w:r><w:t>第一段</w:t></w:r></w:p><w:p><w:r><w:t>第二段</w:t></w:r></w:p>'
|
||||
|
||||
function asOriginal(doc: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] {
|
||||
return doc.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
}
|
||||
|
||||
function makeInk(blockIndex: number, extra: Partial<NewInkImage> = {}): NewInkImage {
|
||||
return {
|
||||
blockIndex,
|
||||
base64: TINY_PNG_BASE64,
|
||||
widthPx: 200,
|
||||
heightPx: 80,
|
||||
offsetXPx: 40,
|
||||
offsetYPx: -10,
|
||||
payload: '{"strokes":[{"tool":"pen","color":"C00000"}]}',
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
|
||||
async function docXmlOf(bytes: Uint8Array): Promise<string> {
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
return zip.file('word/document.xml')!.async('string')
|
||||
}
|
||||
|
||||
describe('ink save (wp:anchor floating picture)', () => {
|
||||
it('writes an anchored in-front-of-text picture into the anchor paragraph', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TWO_PARAS }))
|
||||
const saved = await saveDocx(doc, asOriginal(doc), { inks: [makeInk(1)] })
|
||||
const xml = await docXmlOf(saved)
|
||||
|
||||
// second paragraph carries the anchored run; the first is untouched
|
||||
expect(xml).toContain('<w:p><w:r><w:t>第一段</w:t></w:r></w:p>')
|
||||
const second = /<w:p><w:r><w:t>第二段[\s\S]*?<\/wp:anchor><\/w:drawing><\/w:r><\/w:p>/.exec(xml)
|
||||
expect(second).not.toBeNull()
|
||||
expect(second![0]).toContain('behindDoc="0"')
|
||||
expect(second![0]).toContain('<wp:wrapNone/>')
|
||||
expect(second![0]).toContain('<wp:positionH relativeFrom="column"><wp:posOffset>381000</wp:posOffset>')
|
||||
expect(second![0]).toContain('<wp:positionV relativeFrom="paragraph"><wp:posOffset>-95250</wp:posOffset>')
|
||||
expect(second![0]).toContain(`name="${INK_NAME_PREFIX} `)
|
||||
expect(second![0]).toContain('descr="{"strokes"')
|
||||
|
||||
// media part + relationship + png content type all present
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
expect(zip.file('word/media/aidocsink1.png')).not.toBeNull()
|
||||
expect(await zip.file('word/_rels/document.xml.rels')!.async('string')).toContain(
|
||||
'Target="media/aidocsink1.png"',
|
||||
)
|
||||
expect(await zip.file('[Content_Types].xml')!.async('string')).toContain('Extension="png"')
|
||||
})
|
||||
|
||||
it('anchors into a self-closing empty paragraph', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p/>' }))
|
||||
const saved = await saveDocx(doc, asOriginal(doc), { inks: [makeInk(0)] })
|
||||
const xml = await docXmlOf(saved)
|
||||
expect(xml).toContain(`name="${INK_NAME_PREFIX} `)
|
||||
expect(xml).not.toContain('<w:p/><w:r>')
|
||||
})
|
||||
|
||||
it('skips a non-paragraph anchor without leaving orphan media/relationships', async () => {
|
||||
const table =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="5000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: table }))
|
||||
const saved = await saveDocx(doc, asOriginal(doc), { inks: [makeInk(0)] })
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
expect(zip.file('word/media/aidocsink1.png')).toBeNull()
|
||||
expect(await zip.file('word/_rels/document.xml.rels')!.async('string')).not.toContain('aidocsink')
|
||||
expect(await docXmlOf(saved)).not.toContain(INK_NAME_PREFIX)
|
||||
})
|
||||
|
||||
it('inks undefined keeps the file byte-identical (no-op save)', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: TWO_PARAS })
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(await saveDocx(doc, asOriginal(doc))).toBe(bytes)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ink reopen (ParsedDoc.inks)', () => {
|
||||
async function savedWithInk(): Promise<Uint8Array> {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TWO_PARAS }))
|
||||
return saveDocx(doc, asOriginal(doc), { inks: [makeInk(1)] })
|
||||
}
|
||||
|
||||
it('round-trips placement, payload and image bytes', async () => {
|
||||
const reopened = await parseDocx(await savedWithInk())
|
||||
expect(reopened.inks).toHaveLength(1)
|
||||
const ink = reopened.inks[0]
|
||||
expect(ink.anchorIndex).toBe(1)
|
||||
expect(ink.offsetXPx).toBeCloseTo(40, 1)
|
||||
expect(ink.offsetYPx).toBeCloseTo(-10, 1)
|
||||
expect(ink.widthPx).toBeCloseTo(200, 1)
|
||||
expect(ink.heightPx).toBeCloseTo(80, 1)
|
||||
expect(ink.payload).toBe('{"strokes":[{"tool":"pen","color":"C00000"}]}')
|
||||
expect(ink.dataUrl).toContain('data:image/png;base64,')
|
||||
})
|
||||
|
||||
it('the annotated paragraph stays an editable text paragraph', async () => {
|
||||
const reopened = await parseDocx(await savedWithInk())
|
||||
const para = reopened.blocks[1]
|
||||
expect(para.type).toBe('paragraph')
|
||||
expect(para.runs?.map((r) => r.text).join('')).toBe('第二段')
|
||||
})
|
||||
|
||||
it('saving with inks: [] removes the annotation, its media part and its relationship', async () => {
|
||||
const reopened = await parseDocx(await savedWithInk())
|
||||
const cleared = await saveDocx(reopened, asOriginal(reopened), { inks: [] })
|
||||
const xml = await docXmlOf(cleared)
|
||||
expect(xml).not.toContain(INK_NAME_PREFIX)
|
||||
expect(xml).toContain('第二段')
|
||||
expect((await parseDocx(cleared)).inks).toHaveLength(0)
|
||||
const zip = await JSZip.loadAsync(cleared)
|
||||
expect(zip.file('word/media/aidocsink1.png')).toBeNull()
|
||||
expect(await zip.file('word/_rels/document.xml.rels')!.async('string')).not.toContain('aidocsink')
|
||||
})
|
||||
|
||||
it('re-saving does not accumulate media parts or relationships', async () => {
|
||||
const reopened = await parseDocx(await savedWithInk())
|
||||
const ink = reopened.inks[0]
|
||||
const resaved = await saveDocx(reopened, asOriginal(reopened), {
|
||||
inks: [
|
||||
{
|
||||
blockIndex: 1,
|
||||
base64: TINY_PNG_BASE64,
|
||||
widthPx: ink.widthPx,
|
||||
heightPx: ink.heightPx,
|
||||
offsetXPx: ink.offsetXPx,
|
||||
offsetYPx: ink.offsetYPx,
|
||||
payload: ink.payload ?? undefined,
|
||||
},
|
||||
],
|
||||
})
|
||||
const zip = await JSZip.loadAsync(resaved)
|
||||
const inkMedia = Object.keys(zip.files).filter((n) => n.includes('aidocsink'))
|
||||
expect(inkMedia).toEqual(['word/media/aidocsink1.png'])
|
||||
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
expect(rels.match(/aidocsink/g)).toHaveLength(1)
|
||||
expect((await parseDocx(resaved)).inks).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('re-saving moves the annotation to a new anchor without duplicating runs', async () => {
|
||||
const reopened = await parseDocx(await savedWithInk())
|
||||
const ink = reopened.inks[0]
|
||||
const moved = await saveDocx(reopened, asOriginal(reopened), {
|
||||
inks: [
|
||||
{
|
||||
blockIndex: 0,
|
||||
base64: TINY_PNG_BASE64,
|
||||
widthPx: ink.widthPx,
|
||||
heightPx: ink.heightPx,
|
||||
offsetXPx: ink.offsetXPx,
|
||||
offsetYPx: ink.offsetYPx,
|
||||
payload: ink.payload ?? undefined,
|
||||
},
|
||||
],
|
||||
})
|
||||
const again = await parseDocx(moved)
|
||||
expect(again.inks).toHaveLength(1)
|
||||
expect(again.inks[0].anchorIndex).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ink XML helpers', () => {
|
||||
it('stripInkRuns leaves foreign anchored drawings alone', () => {
|
||||
const foreign =
|
||||
'<w:p><w:r><w:drawing><wp:anchor behindDoc="1"><wp:docPr id="5" name="图片 5"/>' +
|
||||
'</wp:anchor></w:drawing></w:r><w:r><w:t>x</w:t></w:r></w:p>'
|
||||
expect(stripInkRuns(foreign)).toBe(foreign)
|
||||
})
|
||||
|
||||
it('injectInkRunsIntoParagraph rejects non-paragraph roots', () => {
|
||||
expect(injectInkRunsIntoParagraph('<w:tbl></w:tbl>', '<w:r/>')).toBeNull()
|
||||
expect(injectInkRunsIntoParagraph('<w:p><w:r><w:t>a</w:t></w:r></w:p>', '<w:r/>')).toBe(
|
||||
'<w:p><w:r><w:t>a</w:t></w:r><w:r/></w:p>',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
generateParagraphXml,
|
||||
generateTableXml,
|
||||
parseDocx,
|
||||
readPageColor,
|
||||
readSectionSettings,
|
||||
saveDocx,
|
||||
type GenerateContext,
|
||||
type SaveBlock,
|
||||
} from '../src/index'
|
||||
import { TINY_PNG_BASE64, buildKitchenSinkDocx } from './helpers/build-docx'
|
||||
|
||||
const GEN_CTX: GenerateContext = {
|
||||
headingStyleIds: new Map(),
|
||||
allocateHyperlinkRel: () => 'rId999',
|
||||
}
|
||||
|
||||
async function docXmlOf(bytes: Uint8Array): Promise<string> {
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
return zip.file('word/document.xml')!.async('string')
|
||||
}
|
||||
|
||||
function originals(indexes: number[]): SaveBlock[] {
|
||||
return indexes.map((docxIndex) => ({ kind: 'original', docxIndex }))
|
||||
}
|
||||
|
||||
describe('new paragraph format props', () => {
|
||||
it('round-trips spaceBefore/spaceAfter/indentRight/pageBreakBefore', async () => {
|
||||
const para = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
format: { spaceBefore: 240, spaceAfter: 120, indentRight: 360, pageBreakBefore: true },
|
||||
runs: [{ text: 'x' }],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(para).toContain('<w:pageBreakBefore/>')
|
||||
expect(para).toContain('<w:spacing w:before="240" w:after="120"/>')
|
||||
expect(para).toContain('<w:ind w:right="360"/>')
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
|
||||
const saved = await saveDocx(doc, [...originals(visible), { kind: 'xml', xml: para }])
|
||||
const reparsed = await parseDocx(saved)
|
||||
const last = reparsed.blocks.filter((b) => !b.hidden).at(-1)!
|
||||
expect(last.format).toEqual({
|
||||
spaceBefore: 240,
|
||||
spaceAfter: 120,
|
||||
indentRight: 360,
|
||||
pageBreakBefore: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('inserting new tables (xml save blocks)', () => {
|
||||
it('generates a bordered fixed table and reparses it as a table block', async () => {
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
|
||||
const saved = await saveDocx(doc, [
|
||||
{ kind: 'xml', xml: generateTableXml(3, 4) },
|
||||
...originals(visible),
|
||||
])
|
||||
const xml = await docXmlOf(saved)
|
||||
expect(xml).toContain('<w:tblBorders>')
|
||||
const reparsed = await parseDocx(saved)
|
||||
const first = reparsed.blocks.filter((b) => !b.hidden)[0]
|
||||
expect(first.type).toBe('table')
|
||||
expect(first.label).toBe('Table 3×4')
|
||||
})
|
||||
})
|
||||
|
||||
describe('inserting new images', () => {
|
||||
it('adds media, relationship and content-type default', async () => {
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
|
||||
const saved = await saveDocx(doc, [
|
||||
...originals(visible),
|
||||
{
|
||||
kind: 'image',
|
||||
image: { base64: TINY_PNG_BASE64, mime: 'image/png', widthPx: 100, heightPx: 60 },
|
||||
},
|
||||
])
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
const media = Object.keys(zip.files).filter((n) => n.startsWith('word/media/aidocs'))
|
||||
expect(media).toHaveLength(1)
|
||||
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
expect(rels).toContain(`Target="${media[0].replace('word/', '')}"`)
|
||||
const xml = await docXmlOf(saved)
|
||||
expect(xml).toContain(`<wp:extent cx="${100 * 9525}" cy="${60 * 9525}"/>`)
|
||||
const reparsed = await parseDocx(saved)
|
||||
const last = reparsed.blocks.filter((b) => !b.hidden).at(-1)!
|
||||
expect(last.type).toBe('image')
|
||||
expect(last.imageDataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('section settings (page setup)', () => {
|
||||
it('parses sectPr vAlign and in-paragraph page breaks / hyperlink tooltip', async () => {
|
||||
const { sectionSettingsFromXml } = await import('../src/section')
|
||||
expect(sectionSettingsFromXml('<w:sectPr><w:vAlign w:val="center"/></w:sectPr>').vAlign).toBe(
|
||||
'center',
|
||||
)
|
||||
expect(sectionSettingsFromXml('<w:sectPr/>').vAlign).toBeUndefined()
|
||||
|
||||
const { buildDocx } = await import('./helpers/build-docx')
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:t>上半</w:t><w:br w:type="page"/><w:t>下半</w:t></w:r></w:p>' +
|
||||
'<w:p><w:hyperlink r:id="rIdLink" w:tooltip="提示语"><w:r><w:t>链</w:t></w:r></w:hyperlink></w:p>'
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml,
|
||||
extraRels:
|
||||
'<Relationship Id="rIdLink" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://a.cn" TargetMode="External"/>',
|
||||
}),
|
||||
)
|
||||
expect(doc.blocks[0].runs?.[0].text).toBe('上半\f下半')
|
||||
const linkRun = doc.blocks[1].runs?.find((r) => r.link)
|
||||
expect(linkRun?.link?.tooltip).toBe('提示语')
|
||||
})
|
||||
|
||||
it('reads defaults from the kitchen sink sectPr (A4 portrait)', async () => {
|
||||
const doc = await parseDocx(await buildKitchenSinkDocx())
|
||||
const section = readSectionSettings(doc)
|
||||
expect(section).toEqual({
|
||||
pageWidth: 11906,
|
||||
pageHeight: 16838,
|
||||
orientation: 'portrait',
|
||||
marginTop: 1440,
|
||||
marginRight: 1440,
|
||||
marginBottom: 1440,
|
||||
marginLeft: 1440,
|
||||
headerDist: 708,
|
||||
footerDist: 708,
|
||||
pageBorder: false,
|
||||
columns: 1,
|
||||
colSpace: 720,
|
||||
})
|
||||
})
|
||||
|
||||
it('rewrites pgSz and pgMar while keeping header/footer attrs', async () => {
|
||||
const doc = await parseDocx(await buildKitchenSinkDocx())
|
||||
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
|
||||
const saved = await saveDocx(doc, originals(visible), {
|
||||
section: {
|
||||
pageWidth: 16838,
|
||||
pageHeight: 11906,
|
||||
orientation: 'landscape',
|
||||
marginTop: 720,
|
||||
marginRight: 720,
|
||||
marginBottom: 720,
|
||||
marginLeft: 720,
|
||||
pageBorder: false,
|
||||
columns: 1,
|
||||
},
|
||||
})
|
||||
const xml = await docXmlOf(saved)
|
||||
expect(xml).toContain('<w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/>')
|
||||
expect(xml).toMatch(
|
||||
/<w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720" w:header="708"/,
|
||||
)
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(readSectionSettings(reparsed).orientation).toBe('landscape')
|
||||
expect(readSectionSettings(reparsed).marginLeft).toBe(720)
|
||||
})
|
||||
})
|
||||
|
||||
describe('page color', () => {
|
||||
it('sets, reads back and removes w:background', async () => {
|
||||
const doc = await parseDocx(await buildKitchenSinkDocx())
|
||||
expect(readPageColor(doc)).toBeNull()
|
||||
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
|
||||
|
||||
const colored = await saveDocx(doc, originals(visible), { pageColor: 'FFF2CC' })
|
||||
const coloredXml = await docXmlOf(colored)
|
||||
expect(coloredXml).toMatch(/<w:document[^>]*><w:background w:color="FFF2CC"\/>/)
|
||||
const reparsedColored = await parseDocx(colored)
|
||||
expect(readPageColor(reparsedColored)).toBe('FFF2CC')
|
||||
|
||||
const cleared = await saveDocx(
|
||||
reparsedColored,
|
||||
reparsedColored.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
|
||||
{ pageColor: null },
|
||||
)
|
||||
expect(readPageColor(await parseDocx(cleared))).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const LINKED_IMAGE_URL = 'https://example.com/cfimages?u1=abc&width=2560'
|
||||
|
||||
const LINKED_IMAGE_PARAGRAPH =
|
||||
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:link="rId30"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
|
||||
|
||||
const IMAGE_REL = `<Relationship Id="rId30" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="${LINKED_IMAGE_URL.replace(/&/g, '&')}" TargetMode="External"/>`
|
||||
|
||||
/** INCLUDEPICTURE field whose cached result is the linked drawing (as produced by some converters) */
|
||||
const INCLUDEPICTURE_PARAGRAPH =
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
`<w:r><w:instrText xml:space="preserve"> INCLUDEPICTURE \\d "${LINKED_IMAGE_URL.replace(/&/g, '&')}" \\y </w:instrText></w:r>` +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:link="rId30"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
|
||||
|
||||
describe('linked (external) pictures', () => {
|
||||
it('exposes the external URL as imageDataUrl instead of degrading to Drawing object', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: LINKED_IMAGE_PARAGRAPH, extraRels: IMAGE_REL })
|
||||
const doc = await parseDocx(bytes)
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('image')
|
||||
expect(block.imageDataUrl).toBe(LINKED_IMAGE_URL)
|
||||
})
|
||||
|
||||
it('shows the picture for INCLUDEPICTURE field paragraphs instead of a field chip', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: INCLUDEPICTURE_PARAGRAPH, extraRels: IMAGE_REL })
|
||||
const doc = await parseDocx(bytes)
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('image')
|
||||
expect(block.imageDataUrl).toBe(LINKED_IMAGE_URL)
|
||||
// still protected: saving must keep the original field XML byte-identical
|
||||
expect(block.originalXml).toContain('INCLUDEPICTURE')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,285 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
latexToOmml,
|
||||
mathParagraphXml,
|
||||
mathTokensOf,
|
||||
ommlFragmentsOf,
|
||||
ommlToLatex,
|
||||
ommlToMathML,
|
||||
parseDocx,
|
||||
patchMathTokens,
|
||||
saveDocx,
|
||||
} from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const FRACTION_OMATH =
|
||||
'<m:oMath><m:f><m:num><m:r><m:t>a</m:t></m:r></m:num>' +
|
||||
'<m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></m:oMath>'
|
||||
|
||||
describe('ommlToMathML', () => {
|
||||
it('converts fractions', () => {
|
||||
const mathml = ommlToMathML(FRACTION_OMATH)
|
||||
expect(mathml).toContain('<mfrac>')
|
||||
expect(mathml).toContain('<mi>a</mi>')
|
||||
expect(mathml).toContain('<mi>b</mi>')
|
||||
})
|
||||
|
||||
it('converts scripts, radicals and delimiters', () => {
|
||||
const omml =
|
||||
'<m:oMath>' +
|
||||
'<m:sSup><m:e><m:r><m:t>x</m:t></m:r></m:e><m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup>' +
|
||||
'<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/><m:e><m:r><m:t>y</m:t></m:r></m:e></m:rad>' +
|
||||
'<m:d><m:e><m:r><m:t>z</m:t></m:r></m:e></m:d>' +
|
||||
'</m:oMath>'
|
||||
const mathml = ommlToMathML(omml)
|
||||
expect(mathml).toContain('<msup>')
|
||||
expect(mathml).toContain('<mn>2</mn>')
|
||||
expect(mathml).toContain('<msqrt>')
|
||||
expect(mathml).toContain('<mo stretchy="true">(</mo>')
|
||||
})
|
||||
|
||||
it('converts n-ary operators with under/over limits', () => {
|
||||
const omml =
|
||||
'<m:oMath><m:nary><m:naryPr><m:chr m:val="∑"/><m:limLoc m:val="undOvr"/></m:naryPr>' +
|
||||
'<m:sub><m:r><m:t>k=0</m:t></m:r></m:sub><m:sup><m:r><m:t>n</m:t></m:r></m:sup>' +
|
||||
'<m:e><m:r><m:t>k</m:t></m:r></m:e></m:nary></m:oMath>'
|
||||
const mathml = ommlToMathML(omml)
|
||||
expect(mathml).toContain('<munderover>')
|
||||
expect(mathml).toContain('∑')
|
||||
})
|
||||
|
||||
it('converts matrices', () => {
|
||||
const omml =
|
||||
'<m:oMath><m:m>' +
|
||||
'<m:mr><m:e><m:r><m:t>1</m:t></m:r></m:e><m:e><m:r><m:t>0</m:t></m:r></m:e></m:mr>' +
|
||||
'<m:mr><m:e><m:r><m:t>0</m:t></m:r></m:e><m:e><m:r><m:t>1</m:t></m:r></m:e></m:mr>' +
|
||||
'</m:m></m:oMath>'
|
||||
const mathml = ommlToMathML(omml)
|
||||
expect(mathml.match(/<mtr>/g)).toHaveLength(2)
|
||||
expect(mathml.match(/<mtd>/g)).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('classifies run text into mn / mi / mo tokens', () => {
|
||||
const omml = '<m:oMath><m:r><m:t>2x+1</m:t></m:r></m:oMath>'
|
||||
const mathml = ommlToMathML(omml)
|
||||
expect(mathml).toContain('<mn>2</mn>')
|
||||
expect(mathml).toContain('<mi>x</mi>')
|
||||
expect(mathml).toContain('<mo>+</mo>')
|
||||
expect(mathml).toContain('<mn>1</mn>')
|
||||
})
|
||||
|
||||
it('handles multiple oMath fragments in one paragraph', () => {
|
||||
const xml = `<w:p>${FRACTION_OMATH}${FRACTION_OMATH}</w:p>`
|
||||
expect(ommlFragmentsOf(xml)).toHaveLength(2)
|
||||
expect(ommlToMathML(xml).match(/<math /g)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('unwraps oMathPara', () => {
|
||||
const xml = `<w:p><m:oMathPara>${FRACTION_OMATH}</m:oMathPara></w:p>`
|
||||
expect(ommlFragmentsOf(xml)).toHaveLength(1)
|
||||
expect(ommlToMathML(xml)).toContain('<mfrac>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('latexToOmml', () => {
|
||||
it('builds fractions, scripts and radicals', () => {
|
||||
const omml = latexToOmml('x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}')
|
||||
expect(omml).toContain('<m:f><m:num>')
|
||||
expect(omml).toContain('<m:rad>')
|
||||
expect(omml).toContain('±')
|
||||
const mathml = ommlToMathML(`<m:oMath>${omml}</m:oMath>`)
|
||||
expect(mathml).toContain('<mfrac>')
|
||||
expect(mathml).toContain('<msqrt>')
|
||||
expect(mathml).toContain('<msup>')
|
||||
})
|
||||
|
||||
it('builds n-ary sums with limits and binomials', () => {
|
||||
const omml = latexToOmml('\\sum_{k=0}^{n} \\binom{n}{k} x^k')
|
||||
expect(omml).toContain('<m:nary>')
|
||||
expect(omml).toContain('m:val="∑"')
|
||||
expect(omml).toContain('m:val="noBar"')
|
||||
})
|
||||
|
||||
it('builds matrices with delimiters', () => {
|
||||
const omml = latexToOmml('\\begin{pmatrix} 1 & 0 \\\\ 0 & 1 \\end{pmatrix}')
|
||||
expect(omml).toContain('<m:m>')
|
||||
expect(omml.match(/<m:mr>/g)).toHaveLength(2)
|
||||
expect(omml).toContain('m:begChr m:val="("')
|
||||
})
|
||||
|
||||
it('maps greek letters and functions', () => {
|
||||
const omml = latexToOmml('A = \\pi r^2, \\sin \\alpha')
|
||||
expect(omml).toContain('π')
|
||||
expect(omml).toContain('α')
|
||||
expect(omml).toContain('<m:sty m:val="p"/>')
|
||||
expect(omml).toContain('sin')
|
||||
})
|
||||
|
||||
it('binds a script to the last character of a text run', () => {
|
||||
const omml = latexToOmml('ab^2')
|
||||
// the base of the superscript must be "b", not "ab"
|
||||
expect(omml).toContain('<m:t xml:space="preserve">a</m:t>')
|
||||
expect(omml).toMatch(/<m:sSup><m:e><m:r><m:t[^>]*>b<\/m:t>/)
|
||||
})
|
||||
|
||||
it('supports \\left \\right stretchy delimiters', () => {
|
||||
const omml = latexToOmml('\\left( \\frac{a}{b} \\right)')
|
||||
expect(omml).toContain('<m:d>')
|
||||
expect(omml).toContain('<m:f>')
|
||||
})
|
||||
|
||||
it('rejects unsupported commands with a helpful error', () => {
|
||||
expect(() => latexToOmml('\\unknowncmd{x}')).toThrow(/Unsupported command/)
|
||||
expect(() => latexToOmml('{unclosed')).toThrow(/Missing matching/)
|
||||
})
|
||||
|
||||
it('token edits round-trip through patchMathTokens', () => {
|
||||
const omml = `<m:oMath>${latexToOmml('\\frac{a}{b}')}</m:oMath>`
|
||||
const tokens = mathTokensOf(omml)
|
||||
expect(tokens).toEqual(['a', 'b'])
|
||||
const patched = patchMathTokens(omml, ['x', 'y'])
|
||||
expect(mathTokensOf(patched)).toEqual(['x', 'y'])
|
||||
expect(ommlToMathML(patched)).toContain('<mi>x</mi>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ommlToLatex', () => {
|
||||
const CASES = [
|
||||
'x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}',
|
||||
'(x+a)^n = \\sum_{k=0}^{n} \\binom{n}{k} x^k a^{n-k}',
|
||||
'f(x) = a_0 + \\sum_{n=1}^{\\infty} \\left( a_n \\cos \\frac{n\\pi x}{L} + b_n \\sin \\frac{n\\pi x}{L} \\right)',
|
||||
'a^2 + b^2 = c^2',
|
||||
'e^x = 1 + \\frac{x}{1!} + \\frac{x^2}{2!} + \\cdots',
|
||||
'\\begin{pmatrix} 1 & 0 \\\\ 0 & 1 \\end{pmatrix}',
|
||||
'\\begin{cases} x & x > 0 \\\\ -x & x \\le 0 \\end{cases}',
|
||||
'\\lim_{x \\to 0} \\frac{\\sin x}{x} = 1',
|
||||
'\\sqrt[3]{x} + \\hat{y} + \\overline{z}',
|
||||
'\\int_{0}^{1} x^2 dx',
|
||||
'\\underbrace{a + b}',
|
||||
'\\text{速度} = \\frac{s}{t}',
|
||||
]
|
||||
|
||||
it.each(CASES)('round-trips through latexToOmml: %s', (latex) => {
|
||||
const omml = `<m:oMath>${latexToOmml(latex)}</m:oMath>`
|
||||
const decompiled = ommlToLatex(omml)
|
||||
expect(decompiled).toBeTruthy()
|
||||
// semantic equivalence: recompiling the decompiled LaTeX renders the same
|
||||
const omml2 = `<m:oMath>${latexToOmml(decompiled!)}</m:oMath>`
|
||||
expect(ommlToMathML(omml2)).toBe(ommlToMathML(omml))
|
||||
// and the visible tokens survive
|
||||
expect(mathTokensOf(omml2).join('')).toBe(mathTokensOf(omml).join(''))
|
||||
})
|
||||
|
||||
it('decompiles Word-authored OMML (attrs and property bags present)', () => {
|
||||
const omml =
|
||||
'<m:oMath xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math">' +
|
||||
'<m:sSup><m:sSupPr><m:ctrlPr/></m:sSupPr>' +
|
||||
'<m:e><m:r><m:rPr><m:sty m:val="i"/></m:rPr><m:t>x</m:t></m:r></m:e>' +
|
||||
'<m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup>' +
|
||||
'<m:r><m:t>+1=0</m:t></m:r></m:oMath>'
|
||||
expect(ommlToLatex(omml)).toBe('{x}^{2}+1=0')
|
||||
})
|
||||
|
||||
it('returns null for structures outside the subset', () => {
|
||||
expect(
|
||||
ommlToLatex('<m:oMath><m:sPre><m:sub><m:r><m:t>a</m:t></m:r></m:sub><m:e><m:r><m:t>X</m:t></m:r></m:e></m:sPre></m:oMath>'),
|
||||
).toBeNull()
|
||||
expect(ommlToLatex(`<m:oMath>${latexToOmml('a')}</m:oMath><m:oMath>${latexToOmml('b')}</m:oMath>`)).toBeNull()
|
||||
})
|
||||
|
||||
it('escapes parser-special characters', () => {
|
||||
const omml = '<m:oMath><m:r><m:t>100%_x</m:t></m:r></m:oMath>'
|
||||
const latex = ommlToLatex(omml)
|
||||
expect(latex).toBeTruthy()
|
||||
const round = `<m:oMath>${latexToOmml(latex!)}</m:oMath>`
|
||||
expect(mathTokensOf(round).join('')).toBe('100%_x')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formula parse + save integration', () => {
|
||||
it('parseDocx fills mathml and omml for display equations', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: `<w:p>${FRACTION_OMATH}</w:p>` }))
|
||||
const formula = parsed.blocks[0].formulaDisplay
|
||||
expect(formula?.tokens).toEqual(['a', 'b'])
|
||||
expect(formula?.mathml).toContain('<mfrac>')
|
||||
expect(formula?.omml).toContain('<m:oMath>')
|
||||
})
|
||||
|
||||
it('parses paragraphs mixing math and text into editable runs with math runs', async () => {
|
||||
const mixed = `<w:p><w:r><w:t>see </w:t></w:r>${FRACTION_OMATH}<w:r><w:t> here</w:t></w:r></w:p>`
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: mixed }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.type).toBe('paragraph')
|
||||
expect(block.runs?.map((r) => r.text)).toEqual(['see ', 'ab', ' here'])
|
||||
expect(block.runs?.[1].math?.omml).toBe(FRACTION_OMATH)
|
||||
})
|
||||
|
||||
it('a mixed paragraph regenerates with the math run emitted verbatim', async () => {
|
||||
const mixed = `<w:p><w:r><w:t>see </w:t></w:r>${FRACTION_OMATH}</w:p>`
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: mixed }))
|
||||
const block = parsed.blocks[0]
|
||||
const bytes = await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [{ text: 'edited ' }, ...block.runs!.filter((r) => r.math)],
|
||||
},
|
||||
},
|
||||
])
|
||||
const reparsed = await parseDocx(bytes)
|
||||
const rb = reparsed.blocks[0]
|
||||
expect(rb.type).toBe('paragraph')
|
||||
expect(rb.runs?.map((r) => r.text)).toEqual(['edited ', 'ab'])
|
||||
expect(rb.runs?.[1].math?.omml).toBe(FRACTION_OMATH)
|
||||
})
|
||||
|
||||
it('display equations (oMathPara) still parse as protected formula blocks', async () => {
|
||||
const display = `<w:p><m:oMathPara>${FRACTION_OMATH}</m:oMathPara></w:p>`
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: display }))
|
||||
expect(parsed.blocks[0].type).toBe('passthrough')
|
||||
expect(parsed.blocks[0].formulaDisplay?.mathml).toContain('<mfrac>')
|
||||
})
|
||||
|
||||
it('an inserted equation paragraph survives save and reparse', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>hi</w:t></w:r></w:p>' }))
|
||||
const omml = latexToOmml('a^2 + b^2 = c^2')
|
||||
const bytes = await saveDocx(parsed, [
|
||||
{ kind: 'original', docxIndex: parsed.blocks[0].docxIndex! },
|
||||
{ kind: 'xml', xml: mathParagraphXml(omml) },
|
||||
])
|
||||
const reparsed = await parseDocx(bytes)
|
||||
const formula = reparsed.blocks[1].formulaDisplay
|
||||
expect(formula?.mathml).toContain('<msup>')
|
||||
expect(formula?.tokens.join('')).toContain('=')
|
||||
})
|
||||
|
||||
it('declares xmlns:m when the original document root lacks it', async () => {
|
||||
const JSZip = (await import('jszip')).default
|
||||
// rebuild a docx whose document.xml root omits xmlns:m (non-Word generators)
|
||||
const base = await buildDocx({ bodyXml: '<w:p><w:r><w:t>hi</w:t></w:r></w:p>' })
|
||||
const baseZip = await JSZip.loadAsync(base)
|
||||
const baseDocXml = await baseZip.file('word/document.xml')!.async('string')
|
||||
expect(baseDocXml).toContain('xmlns:m=')
|
||||
baseZip.file(
|
||||
'word/document.xml',
|
||||
baseDocXml.replace(
|
||||
' xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"',
|
||||
'',
|
||||
),
|
||||
)
|
||||
const stripped = await parseDocx(await baseZip.generateAsync({ type: 'uint8array' }))
|
||||
|
||||
const omml = latexToOmml('E = mc^2')
|
||||
const bytes = await saveDocx(stripped, [
|
||||
{ kind: 'original', docxIndex: stripped.blocks[0].docxIndex! },
|
||||
{ kind: 'xml', xml: mathParagraphXml(omml) },
|
||||
])
|
||||
const outZip = await JSZip.loadAsync(bytes)
|
||||
const docXml = await outZip.file('word/document.xml')!.async('string')
|
||||
expect(/<w:document[^>]*xmlns:m=/.test(docXml)).toBe(true)
|
||||
// reparse must still see the formula
|
||||
const reparsed = await parseDocx(bytes)
|
||||
expect(reparsed.blocks[1].formulaDisplay?.tokens.join('')).toContain('=')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildShapeParagraphXml,
|
||||
buildTextboxParagraphXml,
|
||||
buildWordArtParagraphXml,
|
||||
} from '../src/generate'
|
||||
|
||||
/**
|
||||
* ECMA-376 Part 3 (MCE): every prefix named in mc:Choice Requires must be
|
||||
* resolvable at the AlternateContent scope. Word treats an unresolvable
|
||||
* prefix as file corruption ("unreadable content", issue #155), so the
|
||||
* builders must declare the wps namespace on mc:AlternateContent itself.
|
||||
*/
|
||||
|
||||
const BUILDERS: Array<[string, string]> = [
|
||||
['wordart', buildWordArtParagraphXml({ text: 'Hi' })],
|
||||
['textbox', buildTextboxParagraphXml()],
|
||||
['shape', buildShapeParagraphXml({ prst: 'ellipse' })],
|
||||
]
|
||||
|
||||
describe('MCE Requires prefixes resolve at AlternateContent scope', () => {
|
||||
for (const [name, xml] of BUILDERS) {
|
||||
it(`${name} declares every Requires prefix on mc:AlternateContent`, () => {
|
||||
const acTag = /<mc:AlternateContent[^>]*>/.exec(xml)?.[0]
|
||||
expect(acTag).toBeDefined()
|
||||
for (const m of xml.matchAll(/Requires="([^"]+)"/g)) {
|
||||
for (const prefix of m[1].split(/\s+/)) {
|
||||
expect(acTag, `prefix ${prefix} in ${name}`).toContain(`xmlns:${prefix}=`)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for (const [name, xml] of BUILDERS) {
|
||||
it(`${name} emits the required wps:cNvSpPr child`, () => {
|
||||
const wsp = /<wps:wsp[^>]*>([\s\S]*?)<wps:spPr>/.exec(xml)?.[1] ?? ''
|
||||
expect(wsp, name).toContain('<wps:cNvSpPr')
|
||||
})
|
||||
}
|
||||
|
||||
it('VML fallback sizes are points, not pixels', () => {
|
||||
const xml = buildWordArtParagraphXml({ widthEmu: 2700000, heightEmu: 720000 })
|
||||
const style = /<v:rect[^>]*style="([^"]*)"/.exec(xml)?.[1] ?? ''
|
||||
expect(style).toContain(`width:${2700000 / 12700}pt`)
|
||||
expect(style).toContain(`height:${720000 / 12700}pt`)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateTableModelXml, parseDocx, patchTableCellTexts, saveDocx } from '../src/index'
|
||||
import { buildDocx, NESTED_TABLE_XML } from './helpers/build-docx'
|
||||
|
||||
describe('nested table editing (surgical text patch + regeneration)', () => {
|
||||
it('patches nested cell texts and keeps the outer cell bytes', () => {
|
||||
const out = patchTableCellTexts(NESTED_TABLE_XML, [
|
||||
[{ nested: [[[['EditedInnerA'], null]]] }, null],
|
||||
])
|
||||
expect(out).toContain('EditedInnerA')
|
||||
expect(out).toContain('<w:t>InnerB</w:t>')
|
||||
expect(out).toContain('<w:t>Outer</w:t>')
|
||||
expect(out).toContain('<w:t>RightCell</w:t>')
|
||||
// outer structure is not rearranged
|
||||
expect(out.indexOf('<w:tbl>')).toBe(0)
|
||||
})
|
||||
|
||||
it('plain-array cell patches still skip cells containing nested tables', () => {
|
||||
const out = patchTableCellTexts(NESTED_TABLE_XML, [[['ShouldNotApply'], null]])
|
||||
expect(out).toBe(NESTED_TABLE_XML)
|
||||
})
|
||||
|
||||
it('regenerating a table model keeps nested tables (structure edits no longer drop them)', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: NESTED_TABLE_XML }))
|
||||
const model = doc.blocks[0].table!
|
||||
const xml = generateTableModelXml(model, doc.blocks[0].originalXml ?? undefined)
|
||||
expect(xml).toContain('InnerA')
|
||||
expect(xml).toContain('InnerB')
|
||||
// nested table is followed by an empty paragraph (OOXML: tc must end with w:p)
|
||||
expect(/<\/w:tbl><w:p\/><\/w:tc>/.test(xml)).toBe(true)
|
||||
// reparsing still yields the nested structure
|
||||
const saved = await saveDocx(doc, [{ kind: 'xml', xml }])
|
||||
const reparsed = await parseDocx(saved)
|
||||
const nested = reparsed.blocks[0].table!.rows[0][0].nestedTables
|
||||
expect(nested?.[0]?.rows[0].map((c) => c.paras[0])).toEqual(['InnerA', 'InnerB'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,281 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
generateCaptionXml,
|
||||
generateIndexFieldXml,
|
||||
nextNoteId,
|
||||
parseDocx,
|
||||
saveDocx,
|
||||
type SaveBlock,
|
||||
} from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
const FOOTNOTES_XML =
|
||||
XML_DECL +
|
||||
'<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>' +
|
||||
'<w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>' +
|
||||
'<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r><w:r><w:t>这是脚注正文</w:t></w:r></w:p></w:footnote>' +
|
||||
'</w:footnotes>'
|
||||
|
||||
const FOOTNOTE_P =
|
||||
'<w:p><w:r><w:t>正文</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteReference w:id="2"/></w:r>' +
|
||||
'<w:r><w:t>继续</w:t></w:r></w:p>'
|
||||
|
||||
const FOOTNOTES_REL =
|
||||
'<Relationship Id="rId40" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/>'
|
||||
|
||||
async function buildFootnoteDocx(): Promise<Uint8Array> {
|
||||
return buildDocx({
|
||||
bodyXml: FOOTNOTE_P,
|
||||
extraRels: FOOTNOTES_REL,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/footnotes.xml',
|
||||
xml: FOOTNOTES_XML,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
const originalOrder = (doc: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] =>
|
||||
doc.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
|
||||
describe('footnotes / endnotes', () => {
|
||||
it('parses word/footnotes.xml and keeps the reference paragraph editable', async () => {
|
||||
const doc = await parseDocx(await buildFootnoteDocx())
|
||||
expect(doc.footnotes).toEqual([{ id: '2', text: '这是脚注正文' }])
|
||||
expect(doc.endnotes).toEqual([])
|
||||
const p = doc.blocks[0]
|
||||
expect(p.type).toBe('paragraph')
|
||||
expect(p.runs).toEqual([
|
||||
{ text: '正文' },
|
||||
{ text: '1', noteRef: { kind: 'footnote', id: '2' } },
|
||||
{ text: '继续' },
|
||||
])
|
||||
})
|
||||
|
||||
it('adding a note keeps the untouched rich footnote entry byte-identical (surgical rebuild)', async () => {
|
||||
// Existing footnote with rich formatting (bold run): after adding a new footnote and
|
||||
// regenerating the part, the original entry keeps its bytes
|
||||
const RICH_FOOTNOTES =
|
||||
XML_DECL +
|
||||
'<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>' +
|
||||
'<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r>' +
|
||||
'<w:r><w:rPr><w:b/><w:color w:val="C00000"/></w:rPr><w:t>加粗红字脚注</w:t></w:r></w:p></w:footnote>' +
|
||||
'</w:footnotes>'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: FOOTNOTE_P,
|
||||
extraRels: FOOTNOTES_REL,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/footnotes.xml',
|
||||
xml: RICH_FOOTNOTES,
|
||||
contentType:
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const out = await saveDocx(doc, originalOrder(doc), {
|
||||
footnotes: [...doc.footnotes, { id: '3', text: '新脚注' }],
|
||||
})
|
||||
const fnXml = await (await JSZip.loadAsync(out)).file('word/footnotes.xml')!.async('string')
|
||||
// Before the surgical fix: the original entry was rebuilt as plain text, losing
|
||||
// <w:b/> and the color
|
||||
expect(fnXml).toContain(
|
||||
'<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r>' +
|
||||
'<w:r><w:rPr><w:b/><w:color w:val="C00000"/></w:rPr><w:t>加粗红字脚注</w:t></w:r></w:p></w:footnote>',
|
||||
)
|
||||
expect(fnXml).toContain('新脚注')
|
||||
})
|
||||
|
||||
it('untouched footnote paragraphs still save byte-identical', async () => {
|
||||
const bytes = await buildFootnoteDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const out = await saveDocx(doc, originalOrder(doc))
|
||||
expect(out).toBe(doc.internal.originalBytes)
|
||||
})
|
||||
|
||||
it('regenerates footnotes.xml preserving separators, and round-trips a new note', async () => {
|
||||
const doc = await parseDocx(await buildFootnoteDocx())
|
||||
const newId = nextNoteId(doc.footnotes)
|
||||
expect(newId).toBe('3')
|
||||
const notes = [...doc.footnotes, { id: newId, text: '新脚注' }]
|
||||
const out = await saveDocx(
|
||||
doc,
|
||||
[
|
||||
...originalOrder(doc),
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [{ text: '新段落' }, { text: '2', noteRef: { kind: 'footnote', id: newId } }],
|
||||
},
|
||||
},
|
||||
],
|
||||
{ footnotes: notes },
|
||||
)
|
||||
const zip = await JSZip.loadAsync(out)
|
||||
const fnXml = await zip.file('word/footnotes.xml')!.async('string')
|
||||
expect(fnXml).toContain('w:type="separator"')
|
||||
expect(fnXml).toContain('新脚注')
|
||||
|
||||
const reparsed = await parseDocx(out)
|
||||
expect(reparsed.footnotes).toEqual([
|
||||
{ id: '2', text: '这是脚注正文' },
|
||||
{ id: '3', text: '新脚注' },
|
||||
])
|
||||
const last = reparsed.blocks.filter((b) => !b.hidden).at(-1)!
|
||||
expect(last.runs).toEqual([
|
||||
{ text: '新段落' },
|
||||
{ text: '2', noteRef: { kind: 'footnote', id: '3' } },
|
||||
])
|
||||
})
|
||||
|
||||
it('creates word/endnotes.xml with rel + content type when the part is missing', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>正文</w:t></w:r></w:p>' })
|
||||
const doc = await parseDocx(bytes)
|
||||
const out = await saveDocx(
|
||||
doc,
|
||||
[
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [{ text: '正文' }, { text: '1', noteRef: { kind: 'endnote', id: '2' } }],
|
||||
},
|
||||
},
|
||||
],
|
||||
{ endnotes: [{ id: '2', text: '尾注内容' }] },
|
||||
)
|
||||
const zip = await JSZip.loadAsync(out)
|
||||
const enXml = await zip.file('word/endnotes.xml')!.async('string')
|
||||
expect(enXml).toContain('尾注内容')
|
||||
expect(enXml).toContain('w:type="separator"')
|
||||
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
expect(rels).toContain('endnotes.xml')
|
||||
const ct = await zip.file('[Content_Types].xml')!.async('string')
|
||||
expect(ct).toContain('/word/endnotes.xml')
|
||||
|
||||
const reparsed = await parseDocx(out)
|
||||
expect(reparsed.endnotes).toEqual([{ id: '2', text: '尾注内容' }])
|
||||
expect(reparsed.blocks[0].runs).toEqual([
|
||||
{ text: '正文' },
|
||||
{ text: '1', noteRef: { kind: 'endnote', id: '2' } },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('index entries (XE)', () => {
|
||||
const XE_P =
|
||||
'<w:p><w:r><w:t>人工智能是研究热点</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> XE "人工智能" </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'<w:r><w:t>,继续。</w:t></w:r></w:p>'
|
||||
|
||||
it('keeps XE-only field paragraphs editable and parses the term', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: XE_P }))
|
||||
const p = doc.blocks[0]
|
||||
expect(p.type).toBe('paragraph')
|
||||
expect(p.runs).toEqual([
|
||||
{ text: '人工智能是研究热点' },
|
||||
{ text: '', xeTerm: '人工智能' },
|
||||
{ text: ',继续。' },
|
||||
])
|
||||
})
|
||||
|
||||
it('regenerates the XE field when the paragraph is edited', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: XE_P })
|
||||
const doc = await parseDocx(bytes)
|
||||
const out = await saveDocx(doc, [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [{ text: '改过的文本' }, { text: '', xeTerm: '人工智能' }],
|
||||
},
|
||||
},
|
||||
])
|
||||
const reparsed = await parseDocx(out)
|
||||
expect(reparsed.blocks[0].runs).toEqual([
|
||||
{ text: '改过的文本' },
|
||||
{ text: '', xeTerm: '人工智能' },
|
||||
])
|
||||
})
|
||||
|
||||
it('PAGE field paragraphs collapse into an editable inline field (no longer whole-paragraph protected)', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGE </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>',
|
||||
}),
|
||||
)
|
||||
expect(doc.blocks[0].type).toBe('paragraph')
|
||||
expect(doc.blocks[0].runs?.[0]?.instrField).toBe('PAGE')
|
||||
})
|
||||
|
||||
it('generateIndexFieldXml sorts, dedupes and wraps in one dirty INDEX field', () => {
|
||||
const paras = generateIndexFieldXml(['术语B', '术语A', '术语A'])
|
||||
expect(paras).toHaveLength(2)
|
||||
expect(paras[0]).toContain('fldCharType="begin" w:dirty="true"')
|
||||
expect(paras[0]).toContain('INDEX')
|
||||
expect(paras[0]).toContain('术语A')
|
||||
expect(paras[1]).toContain('术语B')
|
||||
expect(paras[1]).toContain('fldCharType="end"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('captions', () => {
|
||||
it('generateCaptionXml emits a dirty SEQ field with the static number', () => {
|
||||
const xml = generateCaptionXml('图', 3, '系统架构')
|
||||
expect(xml).toContain(' SEQ 图 \\* ARABIC ')
|
||||
expect(xml).toContain('w:dirty="true"')
|
||||
expect(xml).toContain('<w:t>3</w:t>')
|
||||
expect(xml).toContain('系统架构')
|
||||
})
|
||||
|
||||
it('caption paragraphs parse as protected SEQ field blocks with visible text', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: generateCaptionXml('图', 1, '测试') }))
|
||||
const p = doc.blocks[0]
|
||||
expect(p.type).toBe('passthrough')
|
||||
expect(p.fieldDisplay).toEqual({ kind: 'text', left: '图 1 测试' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('rich-text footnote display runs', () => {
|
||||
it('parses bold/italic/color/size runs; plain-text footnotes carry no richParas', async () => {
|
||||
const footnotesXml =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>' +
|
||||
'<w:footnote w:id="1"><w:p>' +
|
||||
'<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteRef/></w:r>' +
|
||||
'<w:r><w:t xml:space="preserve"> 见</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:b/><w:color w:val="c00000"/></w:rPr><w:t>重要文献</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:i/><w:sz w:val="16"/></w:rPr><w:t>(斜体小字)</w:t></w:r>' +
|
||||
'</w:p></w:footnote>' +
|
||||
'<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r><w:r><w:t>纯文本</w:t></w:r></w:p></w:footnote>' +
|
||||
'</w:footnotes>'
|
||||
const { parseNotesXml } = await import('../src/notes')
|
||||
const notes = parseNotesXml(footnotesXml, 'footnote')
|
||||
expect(notes).toHaveLength(2)
|
||||
const rich = notes[0]
|
||||
expect(rich.richParas?.[0]).toEqual([
|
||||
{ text: '见' },
|
||||
{ text: '重要文献', bold: true, color: 'C00000' },
|
||||
{ text: '(斜体小字)', italic: true, sizeHalfPoints: 16 },
|
||||
])
|
||||
expect(notes[1].richParas).toBeUndefined()
|
||||
expect(notes[1].text).toBe('纯文本')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
const MULTILEVEL_NUMBERING =
|
||||
XML_DECL +
|
||||
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:abstractNum w:abstractNumId="0">' +
|
||||
'<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl>' +
|
||||
'<w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2"/></w:lvl>' +
|
||||
'<w:lvl w:ilvl="2"><w:start w:val="3"/><w:numFmt w:val="lowerLetter"/><w:lvlText w:val="%3)"/></w:lvl>' +
|
||||
'</w:abstractNum>' +
|
||||
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
|
||||
'<w:num w:numId="2"><w:abstractNumId w:val="0"/>' +
|
||||
'<w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride>' +
|
||||
'<w:lvlOverride w:ilvl="1"><w:lvl w:ilvl="1"><w:start w:val="5"/><w:numFmt w:val="upperRoman"/><w:lvlText w:val="%2:"/></w:lvl></w:lvlOverride>' +
|
||||
'</w:num>' +
|
||||
'</w:numbering>'
|
||||
|
||||
describe('numbering definitions (word/numbering.xml)', () => {
|
||||
it('parses per-level numFmt / lvlText / start and lvlOverrides', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
numberingXml: MULTILEVEL_NUMBERING,
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
|
||||
const num1 = doc.numbering.get('1')!
|
||||
expect(num1.abstractNumId).toBe('0')
|
||||
expect(num1.levels[0]).toEqual({ numFmt: 'decimal', lvlText: '%1.', start: 1 })
|
||||
expect(num1.levels[1]).toEqual({ numFmt: 'decimal', lvlText: '%1.%2', start: 1 })
|
||||
expect(num1.levels[2]).toEqual({ numFmt: 'lowerLetter', lvlText: '%3)', start: 3 })
|
||||
expect(num1.startOverrides).toEqual({})
|
||||
|
||||
const num2 = doc.numbering.get('2')!
|
||||
expect(num2.startOverrides).toEqual({ 0: 1 })
|
||||
// A full w:lvl inside lvlOverride replaces that level's definition; other levels
|
||||
// follow the abstractNum
|
||||
expect(num2.levels[1]).toEqual({ numFmt: 'upperRoman', lvlText: '%2:', start: 5 })
|
||||
expect(num2.levels[0]).toEqual({ numFmt: 'decimal', lvlText: '%1.', start: 1 })
|
||||
})
|
||||
|
||||
it('keeps the bullet/ordered classification for list blocks', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>b</w:t></w:r></w:p>',
|
||||
withNumbering: true,
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].list?.kind).toBe('bullet')
|
||||
expect(doc.blocks[1].list?.kind).toBe('ordered')
|
||||
expect(doc.numbering.get('2')?.levels[0]?.lvlText).toBe('%1.')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildKitchenSinkDocx } from './helpers/build-docx'
|
||||
|
||||
describe('parseDocx', () => {
|
||||
it('parses the kitchen-sink document into anchored blocks', async () => {
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
expect(visible.map((b) => b.type)).toEqual([
|
||||
'heading',
|
||||
'paragraph',
|
||||
'heading',
|
||||
'listItem',
|
||||
'listItem',
|
||||
'listItem',
|
||||
'paragraph',
|
||||
'table',
|
||||
'image',
|
||||
'passthrough',
|
||||
'paragraph',
|
||||
])
|
||||
|
||||
// every block anchored to its top-level element index with exact XML slice
|
||||
doc.blocks.forEach((block, i) => {
|
||||
expect(block.docxIndex).toBe(i)
|
||||
expect(block.originalXml).toBeTruthy()
|
||||
expect(doc.internal.documentXml).toContain(block.originalXml!)
|
||||
})
|
||||
|
||||
const h1 = visible[0]
|
||||
expect(h1.level).toBe(1)
|
||||
expect(h1.runs?.[0].text).toBe('第一章 概述')
|
||||
|
||||
const rich = visible[1]
|
||||
const runs = rich.runs!
|
||||
expect(runs.find((r) => r.bold)?.text).toBe('加粗')
|
||||
expect(runs.find((r) => r.italic)?.text).toBe('斜体')
|
||||
expect(runs.find((r) => r.underline)?.text).toBe('下划线')
|
||||
expect(runs.find((r) => r.strike)?.text).toBe('删除线')
|
||||
const colored = runs.find((r) => r.color === 'FF0000')
|
||||
expect(colored?.text).toBe('红色14号')
|
||||
expect(colored?.sizeHalfPoints).toBe(28)
|
||||
// XML entities decoded
|
||||
expect(runs[runs.length - 1].text).toContain('& < >')
|
||||
|
||||
const bullets = visible.filter((b) => b.type === 'listItem')
|
||||
expect(bullets[0].list).toEqual({ kind: 'bullet', numId: '1', ilvl: 0 })
|
||||
expect(bullets[2].list).toEqual({ kind: 'ordered', numId: '2', ilvl: 0 })
|
||||
|
||||
const linkPara = visible[6]
|
||||
const linkRun = linkPara.runs!.find((r) => r.link)
|
||||
expect(linkRun?.link?.href).toBe('https://example.com/')
|
||||
expect(linkRun?.link?.rId).toBe('rId20')
|
||||
|
||||
const table = visible[7]
|
||||
expect(table.label).toBe('Table 2×2')
|
||||
expect(table.previewText).toContain('A1')
|
||||
|
||||
const image = visible[8]
|
||||
expect(image.imageDataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
|
||||
const math = visible[9]
|
||||
expect(math.label).toBe('Equation')
|
||||
|
||||
// trailing sectPr is hidden
|
||||
const hidden = doc.blocks.filter((b) => b.hidden)
|
||||
expect(hidden).toHaveLength(1)
|
||||
expect(hidden[0].originalXml).toContain('<w:sectPr>')
|
||||
|
||||
// style metadata for generation
|
||||
expect(doc.headingStyleIds.get(1)).toBe('Heading1')
|
||||
expect(doc.headingStyleIds.get(2)).toBe('Heading2')
|
||||
expect(doc.listParagraphStyleId).toBe('ListParagraph')
|
||||
})
|
||||
|
||||
it('protects structural paragraphs (section break / fields) as passthrough', async () => {
|
||||
const { buildDocx } = await import('./helpers/build-docx')
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: [
|
||||
// mid-document section break lives inside w:pPr
|
||||
'<w:p><w:pPr><w:sectPr><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/></w:sectPr></w:pPr></w:p>',
|
||||
// TOC field (complex fields still protect the whole paragraph; simple inline
|
||||
// fields PAGE/DATE are already editable)
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>',
|
||||
'<w:p><w:r><w:t>带脚注的段落</w:t></w:r><w:r><w:footnoteReference w:id="2"/></w:r></w:p>',
|
||||
// comments stay editable: they are tracked at run level, not as passthrough
|
||||
'<w:p><w:commentRangeStart w:id="0"/><w:r><w:t>有批注</w:t></w:r><w:commentRangeEnd w:id="0"/></w:p>',
|
||||
'<w:p><w:r><w:t>普通可编辑段落</w:t></w:r></w:p>',
|
||||
].join(''),
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
expect(visible.map((b) => b.type)).toEqual([
|
||||
'passthrough',
|
||||
'passthrough',
|
||||
'paragraph',
|
||||
'paragraph',
|
||||
'paragraph',
|
||||
])
|
||||
expect(visible[0].label).toBe('Section break paragraph')
|
||||
expect(visible[1].label).toBe('Auto TOC (updates when opened in Word)')
|
||||
// footnote references stay editable as atomic noteRef runs
|
||||
expect(visible[2].runs).toEqual([
|
||||
{ text: '带脚注的段落' },
|
||||
{ text: '*', noteRef: { kind: 'footnote', id: '2' } },
|
||||
])
|
||||
expect(visible[3].runs).toEqual([{ text: '有批注', commentIds: ['0'] }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
parseDocx,
|
||||
patchFieldParagraphXml,
|
||||
patchMathTokens,
|
||||
} from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const TOC_ENTRY =
|
||||
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" \\h </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:hyperlink w:anchor="_Toc1"><w:r><w:rPr><w:b/></w:rPr><w:t>First </w:t></w:r>' +
|
||||
'<w:r><w:t>chapter</w:t></w:r><w:r><w:tab/></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText> PAGEREF _Toc1 \\h </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>3</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:hyperlink></w:p>'
|
||||
|
||||
const FORMULA =
|
||||
'<w:p><m:oMath><m:f><m:num><m:r><m:t>a</m:t></m:r></m:num>' +
|
||||
'<m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></m:oMath></w:p>'
|
||||
|
||||
describe('protected visible-text patching', () => {
|
||||
it('edits TOC title and page while preserving field structure and run formatting', async () => {
|
||||
const patched = patchFieldParagraphXml(TOC_ENTRY, {
|
||||
left: 'Updated & chapter',
|
||||
right: '12',
|
||||
})
|
||||
|
||||
expect(patched).toContain('<w:instrText xml:space="preserve"> TOC \\o "1-3" \\h </w:instrText>')
|
||||
expect(patched).toContain('<w:instrText> PAGEREF _Toc1 \\h </w:instrText>')
|
||||
expect(patched).toContain('<w:rPr><w:b/></w:rPr>')
|
||||
expect(patched).toContain('& chapter')
|
||||
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: patched }))
|
||||
expect(parsed.blocks[0].fieldDisplay?.left).toBe('Updated & chapter')
|
||||
expect(parsed.blocks[0].fieldDisplay?.right).toBe('12')
|
||||
})
|
||||
|
||||
it('edits OMML tokens while preserving the formula tree', async () => {
|
||||
const patched = patchMathTokens(FORMULA, ['x & 1', 'y'])
|
||||
expect(patched).toContain('<m:f><m:num>')
|
||||
expect(patched).toContain('<m:t>x & 1</m:t>')
|
||||
expect(patched).toContain('<m:den><m:r><m:t>y</m:t>')
|
||||
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: patched }))
|
||||
expect(parsed.blocks[0].formulaDisplay?.tokens).toEqual(['x & 1', 'y'])
|
||||
expect(parsed.blocks[0].formulaDisplay?.mathml).toContain('<mfrac>')
|
||||
expect(parsed.blocks[0].previewText).toBe('x & 1y')
|
||||
})
|
||||
|
||||
it('refuses a formula patch when token count changes', () => {
|
||||
expect(patchMathTokens(FORMULA, ['only-one'])).toBe(FORMULA)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* rawRPr passthrough: run-level unmodeled properties (caps/vanish/dstrike/bdr/double
|
||||
* underline/themeColor/character spacing/all four rFonts slots…) survive paragraph
|
||||
* rebuilds; editing a modeled field rebuilds only its group.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateParagraphXml, parseDocx, saveDocx, type GenerateContext, type SaveBlock } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join, dirname } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const GEN_CTX: GenerateContext = {
|
||||
headingStyleIds: new Map([[1, 'Heading1']]),
|
||||
allocateHyperlinkRel: () => 'rId999',
|
||||
}
|
||||
|
||||
// A run packed with unmodeled properties: double underline, caps, hidden text, double
|
||||
// strikethrough, character border, run-level shading, character spacing, horizontal
|
||||
// scale, position, kern, lang, themeColor, szCs≠sz, all four rFonts slots
|
||||
const RICH_RPR =
|
||||
'<w:rPr>' +
|
||||
'<w:rFonts w:ascii="Georgia" w:eastAsia="宋体" w:hAnsi="Georgia" w:cs="Arial"/>' +
|
||||
'<w:caps/><w:dstrike/><w:vanish/>' +
|
||||
'<w:color w:val="4472C4" w:themeColor="accent1"/>' +
|
||||
'<w:spacing w:val="20"/><w:w w:val="90"/><w:kern w:val="24"/><w:position w:val="6"/>' +
|
||||
'<w:sz w:val="28"/><w:szCs w:val="32"/>' +
|
||||
'<w:u w:val="double"/>' +
|
||||
'<w:bdr w:val="single" w:sz="4" w:space="1" w:color="auto"/>' +
|
||||
'<w:shd w:val="clear" w:color="auto" w:fill="FFF2CC"/>' +
|
||||
'<w:lang w:val="en-US" w:eastAsia="zh-CN"/>' +
|
||||
'</w:rPr>'
|
||||
const RICH_PARA = `<w:p><w:r>${RICH_RPR}<w:t>富格式文本</w:t></w:r></w:p>`
|
||||
|
||||
const UNMODELED_TAGS = [
|
||||
'<w:caps/>', '<w:dstrike/>', '<w:vanish/>',
|
||||
'w:themeColor="accent1"',
|
||||
'<w:spacing w:val="20"/>', '<w:w w:val="90"/>', '<w:kern w:val="24"/>', '<w:position w:val="6"/>',
|
||||
'<w:szCs w:val="32"/>',
|
||||
'<w:u w:val="double"/>',
|
||||
'<w:bdr w:val="single" w:sz="4" w:space="1" w:color="auto"/>',
|
||||
'<w:shd w:val="clear" w:color="auto" w:fill="FFF2CC"/>',
|
||||
'<w:lang w:val="en-US" w:eastAsia="zh-CN"/>',
|
||||
'w:cs="Arial"',
|
||||
]
|
||||
|
||||
describe('rawRPr passthrough', () => {
|
||||
it('text-only edit keeps every unmodeled rPr property', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: RICH_PARA }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
expect(run.rawRPr).toBeTruthy()
|
||||
// Text-only edit: formatting fields carry over verbatim
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, text: '改过的文字' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
for (const tag of UNMODELED_TAGS) expect(xml, tag).toContain(tag)
|
||||
expect(xml).toContain('<w:t xml:space="preserve">改过的文字</w:t>')
|
||||
})
|
||||
|
||||
it('editing a modeled field rebuilds only that group, keeps the rest', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: RICH_PARA }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
// Add bold (not there originally): w:b is inserted at its schema position, the other
|
||||
// groups keep their original bytes
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, bold: true }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:b/>')
|
||||
// schema order: rFonts < b < caps
|
||||
expect(xml.indexOf('<w:rFonts')).toBeLessThan(xml.indexOf('<w:b/>'))
|
||||
expect(xml.indexOf('<w:b/>')).toBeLessThan(xml.indexOf('<w:caps/>'))
|
||||
for (const tag of UNMODELED_TAGS) expect(xml, tag).toContain(tag)
|
||||
})
|
||||
|
||||
it('double underline survives while modeled underline stays true, drops when cleared', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: RICH_PARA }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
expect(run.underline).toBe(true) // the parse side counts double as underline
|
||||
const kept = generateParagraphXml({ type: 'paragraph', runs: [{ ...run }] }, GEN_CTX)
|
||||
expect(kept).toContain('<w:u w:val="double"/>') // not edited → double is kept
|
||||
const cleared = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, underline: false }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(cleared).not.toContain('<w:u') // underline cleared → whole group removed
|
||||
})
|
||||
|
||||
it('changing size rebuilds sz+szCs together; changing color drops stale themeColor', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: RICH_PARA }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
const resized = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, sizeHalfPoints: 36 }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(resized).toContain('<w:sz w:val="36"/>')
|
||||
expect(resized).toContain('<w:szCs w:val="36"/>')
|
||||
expect(resized).not.toContain('w:val="32"')
|
||||
const recolored = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, color: 'FF0000' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(recolored).toContain('<w:color w:val="FF0000"/>')
|
||||
expect(recolored).not.toContain('themeColor') // after an explicit recolor the theme-color reference no longer holds
|
||||
})
|
||||
|
||||
it('adjacent runs with different unmodeled props are not merged at parse', async () => {
|
||||
const body =
|
||||
'<w:p><w:r><w:rPr><w:caps/></w:rPr><w:t>大写</w:t></w:r>' +
|
||||
'<w:r><w:t>普通</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
|
||||
expect(doc.blocks[0].runs).toHaveLength(2) // modeled fields all equal, but rawRPr differs → no merge
|
||||
})
|
||||
})
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const REAL = join(here, '..', '..', '..', 'example', 'docx', 'OpenClaw开源项目调研分析报告文档.docx')
|
||||
|
||||
// Runs only when the local (gitignored) sample document is present.
|
||||
describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', () => {
|
||||
it('edit one paragraph: all other zip entries and w:p slices stay byte-identical, edited one keeps char spacing', async () => {
|
||||
const bytes = new Uint8Array(readFileSync(REAL))
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
// Pick the first editable paragraph with a run-level w:spacing (character spacing, unmodeled)
|
||||
const target = visible.find(
|
||||
(b) =>
|
||||
(b.type === 'paragraph' || b.type === 'heading') &&
|
||||
b.runs?.length &&
|
||||
b.runs.some((r) => r.rawRPr?.includes('<w:spacing')),
|
||||
)!
|
||||
expect(target).toBeTruthy()
|
||||
|
||||
const finalBlocks: SaveBlock[] = visible.map((b) =>
|
||||
b === target
|
||||
? {
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: b.type as 'paragraph' | 'heading',
|
||||
...(b.level ? { level: b.level } : {}),
|
||||
...(b.styleId ? { styleId: b.styleId } : {}),
|
||||
...(b.rawPPr !== undefined ? { rawPPr: b.rawPPr } : {}),
|
||||
...(b.bookmarks ? { bookmarks: b.bookmarks } : {}),
|
||||
...(b.hiddenBookmarks ? { hiddenBookmarks: b.hiddenBookmarks } : {}),
|
||||
runs: b.runs!.map((r, i) => (i === 0 ? { ...r, text: '【已编辑】' + r.text } : r)),
|
||||
},
|
||||
}
|
||||
: { kind: 'original', docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
|
||||
// Other zip entries stay byte-identical
|
||||
const JSZip = (await import('jszip')).default
|
||||
const [zBefore, zAfter] = await Promise.all([JSZip.loadAsync(bytes), JSZip.loadAsync(saved)])
|
||||
const fileNames = (z: InstanceType<typeof JSZip>) =>
|
||||
Object.keys(z.files).filter((n) => !z.files[n].dir).sort()
|
||||
expect(fileNames(zAfter)).toEqual(fileNames(zBefore))
|
||||
for (const name of fileNames(zBefore)) {
|
||||
// core.xml is the exception: a real save updates dcterms:modified / cp:revision
|
||||
if (name === 'word/document.xml' || name === 'docProps/core.xml') continue
|
||||
const [a, b] = await Promise.all([
|
||||
zBefore.files[name].async('uint8array'),
|
||||
zAfter.files[name].async('uint8array'),
|
||||
])
|
||||
expect(b, name).toEqual(a)
|
||||
}
|
||||
|
||||
// Untouched paragraphs' original slices remain; the edited one keeps its character spacing
|
||||
const newXml = new TextDecoder().decode(await zAfter.files['word/document.xml'].async('uint8array'))
|
||||
let checked = 0
|
||||
for (const b of visible) {
|
||||
if (b === target || !b.originalXml || b.originalXml.length < 40) continue
|
||||
expect(newXml.includes(b.originalXml), `block docxIndex=${b.docxIndex}`).toBe(true)
|
||||
checked++
|
||||
}
|
||||
expect(checked).toBeGreaterThan(10)
|
||||
expect(newXml).toContain('【已编辑】')
|
||||
const spacingVal = /<w:spacing w:val="[^"]+"\/>/.exec(target.runs![0].rawRPr!)?.[0]
|
||||
expect(spacingVal).toBeTruthy()
|
||||
// Character spacing is still in the edited paragraph (lost here before the rawRPr fix)
|
||||
const editedPara = /<w:p>(?:(?!<\/w:p>).)*【已编辑】(?:(?!<\/w:p>).)*<\/w:p>/s.exec(newXml)?.[0]
|
||||
expect(editedPara).toBeTruthy()
|
||||
expect(editedPara!).toContain(spacingVal!)
|
||||
|
||||
// The saved output can be re-parsed
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.blocks.length).toBe(doc.blocks.length)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,436 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { mergePPrFormat, parseDocx, saveDocx, setPPrChange, type SaveBlock } from '../src/index'
|
||||
import { buildDocx, TABLE_XML } from './helpers/build-docx'
|
||||
|
||||
/** paragraph with a tracked insertion and a tracked deletion */
|
||||
const REVISED_P =
|
||||
'<w:p><w:r><w:t xml:space="preserve">保留 </w:t></w:r>' +
|
||||
'<w:ins w:id="11" w:author="Alice" w:date="2026-07-01T10:00:00Z">' +
|
||||
'<w:r><w:t>新增文字</w:t></w:r>' +
|
||||
'</w:ins>' +
|
||||
'<w:del w:id="12" w:author="Bob" w:date="2026-07-02T08:30:00Z">' +
|
||||
'<w:r><w:delText xml:space="preserve">被删文字</w:delText></w:r>' +
|
||||
'</w:del>' +
|
||||
'<w:r><w:t xml:space="preserve"> 结尾</w:t></w:r></w:p>'
|
||||
|
||||
/** an insertion that was later deleted: w:del nested in w:ins */
|
||||
const NESTED_P =
|
||||
'<w:p><w:ins w:id="21" w:author="Alice">' +
|
||||
'<w:del w:id="22" w:author="Bob">' +
|
||||
'<w:r><w:delText>插了又删</w:delText></w:r>' +
|
||||
'</w:del></w:ins></w:p>'
|
||||
|
||||
/** paragraph-mark revision lives in pPr — editable via rawPPr passthrough */
|
||||
const PARA_MARK_P =
|
||||
'<w:p><w:pPr><w:rPr><w:del w:id="31" w:author="Alice"/></w:rPr></w:pPr>' +
|
||||
'<w:r><w:t>段落标记被删</w:t></w:r></w:p>'
|
||||
|
||||
/** tracked paragraph-property change (pPrChange nests the old pPr) */
|
||||
const PPR_CHANGE_P =
|
||||
'<w:p><w:pPr><w:jc w:val="center"/><w:keepNext/>' +
|
||||
'<w:pPrChange w:id="51" w:author="Alice" w:date="2026-07-01T10:00:00Z">' +
|
||||
'<w:pPr><w:jc w:val="left"/></w:pPr></w:pPrChange></w:pPr>' +
|
||||
'<w:r><w:t>对齐方式被改过</w:t></w:r></w:p>'
|
||||
|
||||
/** move-from revision: content was moved away (shown with del marks) */
|
||||
const MOVE_P =
|
||||
'<w:p><w:moveFrom w:id="41" w:author="Alice" w:name="move1">' +
|
||||
'<w:r><w:delText>moved away</w:delText></w:r></w:moveFrom></w:p>'
|
||||
|
||||
/** move-to revision: content was moved here (shown with ins marks) */
|
||||
const MOVE_TO_P =
|
||||
'<w:p><w:moveTo w:id="42" w:author="Bob" w:name="move2">' +
|
||||
'<w:r><w:t>moved here</w:t></w:r></w:moveTo></w:p>'
|
||||
|
||||
describe('tracked change parsing', () => {
|
||||
it('parses run-level w:ins / w:del into editable runs', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: REVISED_P }))
|
||||
const p = doc.blocks[0]
|
||||
expect(p.type).toBe('paragraph')
|
||||
expect(p.runs).toEqual([
|
||||
{ text: '保留 ' },
|
||||
{
|
||||
text: '新增文字',
|
||||
ins: { author: 'Alice', date: '2026-07-01T10:00:00Z', id: '11' },
|
||||
},
|
||||
{
|
||||
text: '被删文字',
|
||||
del: { author: 'Bob', date: '2026-07-02T08:30:00Z', id: '12' },
|
||||
},
|
||||
{ text: ' 结尾' },
|
||||
])
|
||||
})
|
||||
|
||||
it('parses an insertion later deleted with both markers', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: NESTED_P }))
|
||||
const p = doc.blocks[0]
|
||||
expect(p.type).toBe('paragraph')
|
||||
expect(p.runs).toEqual([
|
||||
{
|
||||
text: '插了又删',
|
||||
ins: { author: 'Alice', id: '21' },
|
||||
del: { author: 'Bob', id: '22' },
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('paragraph-mark / pPrChange revisions parse as editable paragraphs with rawPPr', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: PARA_MARK_P + PPR_CHANGE_P }))
|
||||
expect(doc.blocks[0].type).toBe('paragraph')
|
||||
expect(doc.blocks[0].rawPPr).toContain('<w:del w:id="31"')
|
||||
expect(doc.blocks[1].type).toBe('paragraph')
|
||||
expect(doc.blocks[1].rawPPr).toContain('<w:pPrChange')
|
||||
expect(doc.blocks[1].format?.align).toBe('center')
|
||||
// pPrChangeInfo is extracted from pPrChange for UI badge/navigation
|
||||
expect(doc.blocks[1].pPrChangeInfo).toBeDefined()
|
||||
expect(doc.blocks[1].pPrChangeInfo!.author).toBe('Alice')
|
||||
expect(doc.blocks[1].pPrChangeInfo!.id).toBe('51')
|
||||
})
|
||||
|
||||
it('move revisions parse as editable paragraphs with moveRevision marker', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: MOVE_P }))
|
||||
expect(doc.blocks[0].type).toBe('paragraph')
|
||||
expect(doc.blocks[0].moveRevision).toBe('from')
|
||||
// The run text is extracted from w:delText inside w:moveFrom with del mark
|
||||
const delRun = doc.blocks[0].runs?.find((r) => r.del !== undefined)
|
||||
expect(delRun).toBeDefined()
|
||||
})
|
||||
|
||||
it('moveTo revision parses as editable with moveRevision "to" and ins mark', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: MOVE_TO_P }))
|
||||
expect(doc.blocks[0].type).toBe('paragraph')
|
||||
expect(doc.blocks[0].moveRevision).toBe('to')
|
||||
const insRun = doc.blocks[0].runs?.find((r) => r.ins !== undefined)
|
||||
expect(insRun).toBeDefined()
|
||||
expect(insRun!.text).toBe('moved here')
|
||||
})
|
||||
|
||||
it('a text edit regenerates with the pPr (incl. pPrChange) byte-identical', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: PPR_CHANGE_P }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.rawPPr).toBeDefined()
|
||||
const out = await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: { type: 'paragraph', rawPPr: block.rawPPr, runs: [{ text: '改过的文字' }] },
|
||||
},
|
||||
])
|
||||
const zip = await JSZip.loadAsync(out)
|
||||
const xml = await zip.file('word/document.xml')!.async('string')
|
||||
expect(xml).toContain('改过的文字')
|
||||
expect(xml).toContain(block.rawPPr!)
|
||||
expect(xml).toContain('<w:keepNext/>')
|
||||
expect(xml).toContain('<w:pPrChange w:id="51"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tracked change save fidelity', () => {
|
||||
it('writes and reopens top-level paragraph and table revision wrappers', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>base</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const revision = {
|
||||
kind: 'ins' as const,
|
||||
author: 'Structural Reviewer',
|
||||
date: '2026-07-30T10:00:00Z',
|
||||
}
|
||||
const paragraph = await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: { type: 'paragraph', runs: [{ text: 'inserted paragraph' }] },
|
||||
revision,
|
||||
},
|
||||
])
|
||||
const reopenedParagraph = await parseDocx(paragraph)
|
||||
expect(reopenedParagraph.blocks[0].blockRevision).toMatchObject(revision)
|
||||
expect(reopenedParagraph.blocks[0].runs?.[0].text).toBe('inserted paragraph')
|
||||
|
||||
const table = await saveDocx(parsed, [{ kind: 'xml', xml: TABLE_XML, revision }])
|
||||
const reopenedTable = await parseDocx(table)
|
||||
expect(reopenedTable.blocks[0].type).toBe('table')
|
||||
expect(reopenedTable.blocks[0].blockRevision).toMatchObject(revision)
|
||||
})
|
||||
|
||||
it('re-emits w:ins / w:del wrappers when the paragraph is regenerated', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: REVISED_P }))
|
||||
const block = parsed.blocks[0]
|
||||
if (block.type !== 'paragraph') throw new Error('expected paragraph')
|
||||
// edit the plain leading run, keep the revised runs untouched
|
||||
const runs = block.runs!.map((r, i) => (i === 0 ? { ...r, text: '改过 ' } : r))
|
||||
const saveBlocks: SaveBlock[] = [{ kind: 'generated', block: { type: 'paragraph', runs } }]
|
||||
const out = await saveDocx(parsed, saveBlocks)
|
||||
|
||||
const zip = await JSZip.loadAsync(out)
|
||||
const xml = await zip.file('word/document.xml')!.async('string')
|
||||
expect(xml).toContain('改过 ')
|
||||
expect(xml).toContain('<w:ins w:id="11" w:author="Alice" w:date="2026-07-01T10:00:00Z">')
|
||||
expect(xml).toContain('<w:del w:id="12" w:author="Bob" w:date="2026-07-02T08:30:00Z">')
|
||||
expect(xml).toContain('<w:delText xml:space="preserve">被删文字</w:delText>')
|
||||
|
||||
// round-trip: parse the saved file again
|
||||
const again = await parseDocx(out)
|
||||
expect(again.blocks[0].runs).toEqual([
|
||||
{ text: '改过 ' },
|
||||
{ text: '新增文字', ins: { author: 'Alice', date: '2026-07-01T10:00:00Z', id: '11' } },
|
||||
{ text: '被删文字', del: { author: 'Bob', date: '2026-07-02T08:30:00Z', id: '12' } },
|
||||
{ text: ' 结尾' },
|
||||
])
|
||||
})
|
||||
|
||||
it('mints ids for new revisions without one', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>base</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const saveBlocks: SaveBlock[] = [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [
|
||||
{ text: 'base' },
|
||||
{ text: '新输入', ins: { author: '用户', date: '2026-07-22T04:00:00Z' } },
|
||||
{ text: '被删掉', del: { author: '用户', date: '2026-07-22T04:00:00Z' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
const out = await saveDocx(parsed, saveBlocks)
|
||||
const zip = await JSZip.loadAsync(out)
|
||||
const xml = await zip.file('word/document.xml')!.async('string')
|
||||
expect(xml).toMatch(/<w:ins w:id="\d+" w:author="用户" w:date="2026-07-22T04:00:00Z">/)
|
||||
expect(xml).toMatch(/<w:del w:id="\d+" w:author="用户" w:date="2026-07-22T04:00:00Z">/)
|
||||
expect(xml).toContain('<w:delText xml:space="preserve">被删掉</w:delText>')
|
||||
})
|
||||
|
||||
it('leaves untouched revised paragraphs byte-identical', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: REVISED_P })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const saveBlocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
const out = await saveDocx(parsed, saveBlocks)
|
||||
expect(out).toBe(bytes)
|
||||
})
|
||||
})
|
||||
|
||||
describe('comment writing', () => {
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const COMMENTS_XML =
|
||||
XML_DECL +
|
||||
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:comment w:id="1" w:author="Alice"><w:p><w:r><w:t>已有批注</w:t></w:r></w:p></w:comment>' +
|
||||
'</w:comments>'
|
||||
|
||||
it('creates word/comments.xml with rel + content type when absent', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>hello</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const block = parsed.blocks[0]
|
||||
if (block.type !== 'paragraph') throw new Error('expected paragraph')
|
||||
const runs = [{ ...block.runs![0], commentIds: ['1'] }]
|
||||
const out = await saveDocx(
|
||||
parsed,
|
||||
[{ kind: 'generated', block: { type: 'paragraph', runs } }],
|
||||
{
|
||||
comments: [
|
||||
{ id: '1', author: '用户', date: '2026-07-22T04:00:00Z', text: '第一条\n第二行' },
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
const zip = await JSZip.loadAsync(out)
|
||||
const comments = await zip.file('word/comments.xml')!.async('string')
|
||||
expect(comments).toContain('w:id="1"')
|
||||
expect(comments).toContain('w:author="用户"')
|
||||
expect(comments).toContain('<w:t xml:space="preserve">第一条</w:t>')
|
||||
expect(comments).toContain('<w:t xml:space="preserve">第二行</w:t>')
|
||||
|
||||
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
expect(rels).toContain('relationships/comments')
|
||||
expect(rels).toContain('Target="comments.xml"')
|
||||
|
||||
const types = await zip.file('[Content_Types].xml')!.async('string')
|
||||
expect(types).toContain('PartName="/word/comments.xml"')
|
||||
|
||||
const docXml = await zip.file('word/document.xml')!.async('string')
|
||||
expect(docXml).toContain('<w:commentRangeStart w:id="1"/>')
|
||||
expect(docXml).toContain('<w:commentReference w:id="1"/>')
|
||||
|
||||
// the saved file parses back with the comment attached
|
||||
const again = await parseDocx(out)
|
||||
expect(again.comments).toHaveLength(1)
|
||||
expect(again.comments[0].text).toBe('第一条\n第二行')
|
||||
expect(again.blocks[0].runs![0].commentIds).toEqual(['1'])
|
||||
})
|
||||
|
||||
it('rewrites an existing comments.xml from the full list', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>hello</w:t></w:r></w:p>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/comments.xml',
|
||||
xml: COMMENTS_XML,
|
||||
contentType:
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
const out = await saveDocx(
|
||||
parsed,
|
||||
parsed.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! })),
|
||||
{
|
||||
comments: [
|
||||
{ id: '1', author: 'Alice', text: '已有批注' },
|
||||
{ id: '2', author: '用户', text: '新加的' },
|
||||
],
|
||||
},
|
||||
)
|
||||
const zip = await JSZip.loadAsync(out)
|
||||
const comments = await zip.file('word/comments.xml')!.async('string')
|
||||
expect(comments).toContain('w:id="1"')
|
||||
expect(comments).toContain('w:id="2"')
|
||||
expect(comments).toContain('新加的')
|
||||
})
|
||||
})
|
||||
|
||||
describe('document protection', () => {
|
||||
const SETTINGS_XML =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
|
||||
'<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:zoom w:percent="100"/></w:settings>'
|
||||
|
||||
const withSettings = () =>
|
||||
buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/settings.xml',
|
||||
xml: SETTINGS_XML,
|
||||
contentType:
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
it('reports no protection for an unprotected document', async () => {
|
||||
const doc = await parseDocx(await withSettings())
|
||||
expect(doc.protection).toBeNull()
|
||||
})
|
||||
|
||||
it('writes and re-reads w:documentProtection', async () => {
|
||||
const parsed = await parseDocx(await withSettings())
|
||||
const blocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
const out = await saveDocx(parsed, blocks, {
|
||||
protection: { edit: 'readOnly', enforced: true },
|
||||
})
|
||||
const again = await parseDocx(out)
|
||||
expect(again.protection).toEqual({ edit: 'readOnly', enforced: true })
|
||||
|
||||
// removing it round-trips too
|
||||
const cleared = await saveDocx(again, blocks, { protection: null })
|
||||
expect((await parseDocx(cleared)).protection).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mergePPrFormat', () => {
|
||||
const RAW =
|
||||
'<w:pPr><w:pStyle w:val="Body"/><w:keepNext/><w:tabs><w:tab w:val="left" w:pos="420"/></w:tabs>' +
|
||||
'<w:spacing w:before="120" w:beforeAutospacing="1"/><w:jc w:val="left"/>' +
|
||||
'<w:rPr><w:del w:id="31" w:author="Alice"/></w:rPr>' +
|
||||
'<w:pPrChange w:id="51" w:author="Alice"><w:pPr><w:jc w:val="left"/></w:pPr></w:pPrChange></w:pPr>'
|
||||
|
||||
it('replaces managed children in place, keeps everything else byte-identical', () => {
|
||||
const merged = mergePPrFormat(RAW, { align: 'center', spaceBefore: 240 })
|
||||
expect(merged).toContain('<w:pStyle w:val="Body"/>')
|
||||
expect(merged).toContain('<w:keepNext/>')
|
||||
expect(merged).toContain('<w:tabs><w:tab w:val="left" w:pos="420"/></w:tabs>')
|
||||
expect(merged).toContain('<w:rPr><w:del w:id="31" w:author="Alice"/></w:rPr>')
|
||||
expect(merged).toContain('<w:pPrChange w:id="51"')
|
||||
// rebuilt from the format model (old spacing/jc replaced)
|
||||
expect(merged).toContain('<w:spacing w:before="240"/>')
|
||||
expect(merged).toContain('<w:jc w:val="center"/>')
|
||||
expect(merged).not.toContain('beforeAutospacing')
|
||||
// schema order: tabs < spacing < jc < rPr
|
||||
const order = [
|
||||
'<w:keepNext/>',
|
||||
'<w:tabs>',
|
||||
'<w:spacing',
|
||||
'<w:jc',
|
||||
'<w:rPr>',
|
||||
'<w:pPrChange',
|
||||
].map((t) => merged.indexOf(t))
|
||||
expect([...order].sort((a, b) => a - b)).toEqual(order)
|
||||
})
|
||||
|
||||
it('clearing all format keeps only unmanaged children', () => {
|
||||
const merged = mergePPrFormat(RAW, undefined)
|
||||
expect(merged).toContain('<w:keepNext/>')
|
||||
expect(merged).not.toContain('<w:spacing')
|
||||
// the only remaining jc is the old value recorded inside pPrChange
|
||||
expect(merged.indexOf('<w:jc')).toBeGreaterThan(merged.indexOf('<w:pPrChange'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('stripPPrChange', () => {
|
||||
it('removes pPrChange from a raw pPr slice', async () => {
|
||||
const { stripPPrChange } = await import('../src/generate')
|
||||
const raw =
|
||||
'<w:pPr><w:jc w:val="center"/>' +
|
||||
'<w:pPrChange w:id="51" w:author="Alice">' +
|
||||
'<w:pPr><w:jc w:val="left"/></w:pPr>' +
|
||||
'</w:pPrChange></w:pPr>'
|
||||
const result = stripPPrChange(raw)
|
||||
expect(result).toContain('<w:jc w:val="center"/>')
|
||||
expect(result).not.toContain('<w:pPrChange')
|
||||
expect(result).not.toContain('Alice')
|
||||
})
|
||||
|
||||
it('returns unchanged string if no pPrChange', async () => {
|
||||
const { stripPPrChange } = await import('../src/generate')
|
||||
const raw = '<w:pPr><w:jc w:val="left"/></w:pPr>'
|
||||
expect(stripPPrChange(raw)).toBe(raw)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setPPrChange', () => {
|
||||
it('writes a schema-ordered paragraph revision that parses after reopen', async () => {
|
||||
const raw = '<w:pPr><w:spacing w:after="240"/><w:jc w:val="center"/></w:pPr>'
|
||||
const revised = setPPrChange(
|
||||
raw,
|
||||
JSON.stringify({
|
||||
author: 'Paragraph Reviewer',
|
||||
date: '2026-07-30T09:00:00Z',
|
||||
old: {
|
||||
type: 'docParagraph',
|
||||
styleId: 'BodyText',
|
||||
format: {
|
||||
align: 'left',
|
||||
indentLeft: 120,
|
||||
lineSpacing: 1,
|
||||
spaceAfter: 80,
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
expect(revised.indexOf('<w:pPrChange')).toBeGreaterThan(revised.indexOf('<w:jc'))
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: `<w:p>${revised}<w:r><w:t>paragraph</w:t></w:r></w:p>` }),
|
||||
)
|
||||
expect(parsed.blocks[0].pPrChangeInfo).toMatchObject({
|
||||
author: 'Paragraph Reviewer',
|
||||
old: {
|
||||
align: 'left',
|
||||
indentLeft: 120,
|
||||
lineSpacing: 1,
|
||||
spaceAfter: 80,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,159 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
|
||||
import { buildKitchenSinkDocx } from './helpers/build-docx'
|
||||
|
||||
async function entryBytes(bytes: Uint8Array): Promise<Map<string, Uint8Array>> {
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
const out = new Map<string, Uint8Array>()
|
||||
for (const [name, entry] of Object.entries(zip.files)) {
|
||||
if (!entry.dir) out.set(name, await entry.async('uint8array'))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function asOriginal(indexes: number[]): SaveBlock[] {
|
||||
return indexes.map((docxIndex) => ({ kind: 'original', docxIndex }))
|
||||
}
|
||||
|
||||
describe('paragraph-patch save fidelity', () => {
|
||||
it('no edits -> output is the exact original file (byte identical)', async () => {
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
|
||||
const saved = await saveDocx(doc, asOriginal(visible))
|
||||
expect(saved).toBe(bytes)
|
||||
})
|
||||
|
||||
it('editing one paragraph leaves every other entry and every other w:p byte-identical', async () => {
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
|
||||
// replace paragraph at docxIndex 1 (the rich text paragraph)
|
||||
const finalBlocks: SaveBlock[] = visible.map((b) =>
|
||||
b.docxIndex === 1
|
||||
? {
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [{ text: 'AI 重写后的段落。', bold: false }],
|
||||
},
|
||||
}
|
||||
: { kind: 'original', docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
|
||||
const before = await entryBytes(bytes)
|
||||
const after = await entryBytes(saved)
|
||||
expect([...after.keys()].sort()).toEqual([...before.keys()].sort())
|
||||
for (const [name, content] of before) {
|
||||
if (name === 'word/document.xml') continue
|
||||
expect(after.get(name), name).toEqual(content)
|
||||
}
|
||||
|
||||
// untouched top-level elements keep their exact original XML slices
|
||||
const newDocXml = new TextDecoder().decode(after.get('word/document.xml')!)
|
||||
for (const block of doc.blocks) {
|
||||
if (block.docxIndex === 1) continue
|
||||
expect(newDocXml).toContain(block.originalXml!)
|
||||
}
|
||||
expect(newDocXml).toContain('AI 重写后的段落。')
|
||||
expect(newDocXml).not.toContain('红色14号')
|
||||
|
||||
// and the patched file still parses
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.blocks.filter((b) => !b.hidden)).toHaveLength(visible.length)
|
||||
})
|
||||
|
||||
it('supports insert / delete / heading generation with existing styles', async () => {
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
|
||||
const finalBlocks: SaveBlock[] = []
|
||||
for (const b of visible) {
|
||||
if (b.docxIndex === 10) continue // delete the trailing paragraph
|
||||
finalBlocks.push({ kind: 'original', docxIndex: b.docxIndex! })
|
||||
if (b.docxIndex === 0) {
|
||||
finalBlocks.push({
|
||||
kind: 'generated',
|
||||
block: { type: 'heading', level: 2, runs: [{ text: '新增小节', bold: true }] },
|
||||
})
|
||||
finalBlocks.push({
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'listItem',
|
||||
list: { kind: 'bullet', numId: '1', ilvl: 0 },
|
||||
runs: [{ text: '新增列表项' }],
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
const newDocXml = new TextDecoder().decode(
|
||||
(await entryBytes(saved)).get('word/document.xml')!,
|
||||
)
|
||||
expect(newDocXml).toContain('<w:pStyle w:val="Heading2"/>')
|
||||
expect(newDocXml).toContain('<w:pStyle w:val="ListParagraph"/>')
|
||||
expect(newDocXml).toContain('<w:numId w:val="1"/>')
|
||||
expect(newDocXml).not.toContain('尾段。')
|
||||
// sectPr survives exactly once, at the end of the body
|
||||
expect(newDocXml.match(/<w:sectPr>/g)).toHaveLength(1)
|
||||
expect(newDocXml).toMatch(/<w:sectPr>[\s\S]*<\/w:sectPr><\/w:body>/)
|
||||
|
||||
const reparsed = await parseDocx(saved)
|
||||
const types = reparsed.blocks.filter((b) => !b.hidden).map((b) => b.type)
|
||||
expect(types[1]).toBe('heading')
|
||||
expect(types[2]).toBe('listItem')
|
||||
})
|
||||
|
||||
it('new hyperlinks get relationships appended to document.xml.rels', async () => {
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
|
||||
const finalBlocks: SaveBlock[] = visible.map((b) =>
|
||||
b.docxIndex === 10
|
||||
? {
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [
|
||||
{ text: '访问 ' },
|
||||
{ text: '新链接', link: { href: 'https://new.example.org/' } },
|
||||
],
|
||||
},
|
||||
}
|
||||
: { kind: 'original', docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
const entries = await entryBytes(saved)
|
||||
const rels = new TextDecoder().decode(entries.get('word/_rels/document.xml.rels')!)
|
||||
expect(rels).toContain('Target="https://new.example.org/"')
|
||||
expect(rels).toContain('TargetMode="External"')
|
||||
|
||||
const relId = /<Relationship Id="(rId\d+)"[^>]*new\.example\.org/.exec(rels)![1]
|
||||
const docXml = new TextDecoder().decode(entries.get('word/document.xml')!)
|
||||
expect(docXml).toContain(`<w:hyperlink r:id="${relId}">`)
|
||||
|
||||
const reparsed = await parseDocx(saved)
|
||||
const lastPara = reparsed.blocks.filter((b) => !b.hidden).at(-1)!
|
||||
expect(lastPara.runs?.find((r) => r.link)?.link?.href).toBe('https://new.example.org/')
|
||||
})
|
||||
|
||||
it('passthrough blocks (table / image / math) can be moved as whole units', async () => {
|
||||
const bytes = await buildKitchenSinkDocx()
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
const tableIdx = visible.find((b) => b.type === 'table')!.docxIndex!
|
||||
const order = visible.map((b) => b.docxIndex!).filter((i) => i !== tableIdx)
|
||||
order.unshift(tableIdx) // move table to the top
|
||||
|
||||
const saved = await saveDocx(doc, asOriginal(order))
|
||||
const reparsed = await parseDocx(saved)
|
||||
const newVisible = reparsed.blocks.filter((b) => !b.hidden)
|
||||
expect(newVisible[0].type).toBe('table')
|
||||
expect(newVisible[0].originalXml).toBe(doc.blocks[tableIdx].originalXml)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
function rubyXml(base: string, rt: string): string {
|
||||
return (
|
||||
'<w:ruby><w:rubyPr><w:rubyAlign w:val="distributeSpace"/><w:hps w:val="12"/>' +
|
||||
'<w:hpsRaise w:val="22"/><w:hpsBaseText w:val="24"/><w:lid w:val="zh-CN"/></w:rubyPr>' +
|
||||
`<w:rt><w:r><w:rPr><w:sz w:val="12"/></w:rPr><w:t>${rt}</w:t></w:r></w:rt>` +
|
||||
`<w:rubyBase><w:r><w:t>${base}</w:t></w:r></w:rubyBase></w:ruby>`
|
||||
)
|
||||
}
|
||||
|
||||
describe('phonetic guide (w:ruby)', () => {
|
||||
it('parses ruby runs keeping the base characters and phonetic text', async () => {
|
||||
const p =
|
||||
`<w:p><w:r>${rubyXml('床', 'chuáng')}</w:r><w:r>${rubyXml('前', 'qián')}</w:r>` +
|
||||
'<w:r><w:t>,</w:t></w:r></w:p>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.type).toBe('paragraph')
|
||||
expect(block.runs?.map((r) => r.text)).toEqual(['床', '前', ','])
|
||||
expect(block.runs?.[0].ruby).toEqual({ rt: 'chuáng', xml: rubyXml('床', 'chuáng') })
|
||||
expect(block.runs?.[1].ruby?.rt).toBe('qián')
|
||||
expect(block.runs?.[2].ruby).toBeUndefined()
|
||||
})
|
||||
|
||||
it('an edited paragraph re-emits ruby fragments verbatim', async () => {
|
||||
const p = `<w:p><w:r>${rubyXml('月', 'yuè')}</w:r><w:r><w:t>。</w:t></w:r></w:p>`
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
|
||||
const block = parsed.blocks[0]
|
||||
const bytes = await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: { type: 'paragraph', runs: [{ text: 'edited ' }, ...block.runs!.filter((r) => r.ruby)] },
|
||||
},
|
||||
])
|
||||
const reparsed = await parseDocx(bytes)
|
||||
const rb = reparsed.blocks[0]
|
||||
expect(rb.runs?.map((r) => r.text)).toEqual(['edited ', '月'])
|
||||
expect(rb.runs?.[1].ruby).toEqual({ rt: 'yuè', xml: rubyXml('月', 'yuè') })
|
||||
})
|
||||
|
||||
it('an untouched ruby paragraph round-trips byte-preserving', async () => {
|
||||
const p = `<w:p><w:r>${rubyXml('霜', 'shuāng')}</w:r></w:p>`
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
|
||||
const bytes = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
|
||||
const reparsed = await parseDocx(bytes)
|
||||
expect(reparsed.blocks[0].runs?.[0].text).toBe('霜')
|
||||
expect(reparsed.blocks[0].runs?.[0].ruby?.xml).toBe(rubyXml('霜', 'shuāng'))
|
||||
})
|
||||
|
||||
it('multi-run ruby base and rt concatenate', async () => {
|
||||
const ruby =
|
||||
'<w:ruby><w:rubyPr/><w:rt><w:r><w:t>gù</w:t></w:r><w:r><w:t>xiāng</w:t></w:r></w:rt>' +
|
||||
'<w:rubyBase><w:r><w:t>故</w:t></w:r><w:r><w:t>乡</w:t></w:r></w:rubyBase></w:ruby>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: `<w:p><w:r>${ruby}</w:r></w:p>` }))
|
||||
const run = parsed.blocks[0].runs?.[0]
|
||||
expect(run?.text).toBe('故乡')
|
||||
expect(run?.ruby?.rt).toBe('gùxiāng')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* OOXML schema-order gatekeeper: in the output of mergeRPrModel/mergePPrFormat, known
|
||||
* children must appear in CT_RPr/CT_PPr sequence — wrong order makes Word show the
|
||||
* "repair" dialog.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
mergePPrFormat,
|
||||
mergeRPrModel,
|
||||
PPR_CHILD_ORDER,
|
||||
RPR_CHILD_ORDER,
|
||||
splitXmlChildren,
|
||||
} from '../src/generate'
|
||||
|
||||
/** Assert the ranks of known children inside the fragment are non-decreasing (unknown elements skipped) */
|
||||
function assertSchemaOrder(fragment: string, rootTag: string, order: readonly string[]) {
|
||||
const open = new RegExp(`^<${rootTag}(?: [^>]*)?>`).exec(fragment)?.[0]
|
||||
if (!open) return // empty or self-closing: no children to verify
|
||||
const inner = fragment.slice(open.length, fragment.length - `</${rootTag}>`.length)
|
||||
let prev = -1
|
||||
let prevName = ''
|
||||
for (const child of splitXmlChildren(inner)) {
|
||||
const rank = order.indexOf(child.name)
|
||||
if (rank === -1) continue
|
||||
expect(rank, `${child.name} appears after ${prevName}, violating the ${rootTag} schema order`).toBeGreaterThanOrEqual(prev)
|
||||
prev = rank
|
||||
prevName = child.name
|
||||
}
|
||||
}
|
||||
|
||||
describe('rPr schema order (mergeRPrModel)', () => {
|
||||
const RAW =
|
||||
'<w:rPr><w:rFonts w:ascii="Georgia"/><w:caps/><w:strike/><w:color w:val="112233"/>' +
|
||||
'<w:sz w:val="24"/><w:u w:val="double"/><w:bdr w:val="single"/><w:lang w:val="en-US"/></w:rPr>'
|
||||
|
||||
it.each([
|
||||
['add bold', { text: 'x', bold: true }],
|
||||
['add italic + highlight', { text: 'x', italic: true, highlight: 'yellow' }],
|
||||
['change color + size', { text: 'x', color: 'FF0000', sizeHalfPoints: 36 }],
|
||||
['add style + vertAlign', { text: 'x', styleId: 'Emphasis', vertAlign: 'superscript' as const }],
|
||||
['clear underline + add font', { text: 'x', underline: false, font: '微软雅黑' }],
|
||||
])('%s keeps CT_RPr child order', (_label, run) => {
|
||||
const out = mergeRPrModel(RAW, { ...run }, false)
|
||||
assertSchemaOrder(out, 'w:rPr', RPR_CHILD_ORDER)
|
||||
})
|
||||
|
||||
it('hyperlink rStyle lands first even with raw children present', () => {
|
||||
// font matches raw (a parsed run always carries font) → the rFonts group keeps its
|
||||
// original bytes
|
||||
const out = mergeRPrModel(RAW, { text: 'x', bold: true, font: 'Georgia' }, true)
|
||||
assertSchemaOrder(out, 'w:rPr', RPR_CHILD_ORDER)
|
||||
expect(out.indexOf('<w:rStyle')).toBeLessThan(out.indexOf('<w:rFonts'))
|
||||
})
|
||||
|
||||
it('raw children in unusual-but-valid subsets still merge in order', () => {
|
||||
const sparse = '<w:rPr><w:vanish/><w:vertAlign w:val="subscript"/></w:rPr>'
|
||||
const out = mergeRPrModel(sparse, { text: 'x', bold: true, color: 'AA0000' }, false)
|
||||
assertSchemaOrder(out, 'w:rPr', RPR_CHILD_ORDER)
|
||||
expect(out.indexOf('<w:b/>')).toBeLessThan(out.indexOf('<w:vanish/>'))
|
||||
expect(out.indexOf('<w:vanish/>')).toBeLessThan(out.indexOf('<w:color'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('pPr schema order (mergePPrFormat)', () => {
|
||||
const RAW =
|
||||
'<w:pPr><w:pStyle w:val="Heading1"/><w:keepNext/><w:tabs><w:tab w:val="left" w:pos="420"/></w:tabs>' +
|
||||
'<w:rPr><w:b/></w:rPr></w:pPr>'
|
||||
|
||||
it.each([
|
||||
['spacing + align', { spaceBefore: 120, align: 'center' as const }],
|
||||
['borders + shading', { borders: 'tb', shadingFill: 'EEEEEE' }],
|
||||
['indent + pageBreak', { indentLeft: 720, pageBreakBefore: true }],
|
||||
])('%s keeps CT_PPr child order', (_label, format) => {
|
||||
const out = mergePPrFormat(RAW, format)
|
||||
assertSchemaOrder(out, 'w:pPr', PPR_CHILD_ORDER)
|
||||
// The paragraph-mark rPr must still sit at the end (one of the highest-ranked known
|
||||
// elements inside pPr)
|
||||
expect(out).toContain('<w:rPr><w:b/></w:rPr>')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,257 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
// ---- SDT fixture XML fragments ----
|
||||
|
||||
/** Block-level SDT wrapping a text paragraph with alias "Author" */
|
||||
const BLOCK_SDT_P =
|
||||
'<w:sdt>' +
|
||||
'<w:sdtPr>' +
|
||||
'<w:alias w:val="Author Name"/>' +
|
||||
'<w:tag w:val="author"/>' +
|
||||
'<w:text/>' +
|
||||
'</w:sdtPr>' +
|
||||
'<w:sdtEndPr/>' +
|
||||
'<w:sdtContent>' +
|
||||
'<w:p><w:r><w:t>Jane Doe</w:t></w:r></w:p>' +
|
||||
'</w:sdtContent>' +
|
||||
'</w:sdt>'
|
||||
|
||||
/** Block-level SDT with date picker */
|
||||
const DATE_SDT_P =
|
||||
'<w:sdt>' +
|
||||
'<w:sdtPr>' +
|
||||
'<w:alias w:val="Date"/>' +
|
||||
'<w:date>' +
|
||||
'<w:dateFormat w:val="yyyy-MM-dd"/>' +
|
||||
'</w:date>' +
|
||||
'</w:sdtPr>' +
|
||||
'<w:sdtContent>' +
|
||||
'<w:p><w:r><w:t>2026-07-26</w:t></w:r></w:p>' +
|
||||
'</w:sdtContent>' +
|
||||
'</w:sdt>'
|
||||
|
||||
/** Block-level SDT with dropdown */
|
||||
const DROPDOWN_SDT_P =
|
||||
'<w:sdt>' +
|
||||
'<w:sdtPr>' +
|
||||
'<w:alias w:val="Status"/>' +
|
||||
'<w:dropDownList>' +
|
||||
'<w:listItem w:value="Draft" w:displayText="Draft"/>' +
|
||||
'<w:listItem w:value="Final" w:displayText="Final"/>' +
|
||||
'</w:dropDownList>' +
|
||||
'</w:sdtPr>' +
|
||||
'<w:sdtContent>' +
|
||||
'<w:p><w:r><w:t>Draft</w:t></w:r></w:p>' +
|
||||
'</w:sdtContent>' +
|
||||
'</w:sdt>'
|
||||
|
||||
/** Plain paragraph (no SDT) */
|
||||
const PLAIN_P = '<w:p><w:r><w:t>plain text no sdt</w:t></w:r></w:p>'
|
||||
|
||||
describe('SDT parsing', () => {
|
||||
it('parses block-level w:sdt and exposes alias/tag/controlType', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: BLOCK_SDT_P }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.sdtShell).toBeDefined()
|
||||
expect(block.sdtShell!.alias).toBe('Author Name')
|
||||
expect(block.sdtShell!.tag).toBe('author')
|
||||
expect(block.sdtShell!.controlType).toBe('text')
|
||||
})
|
||||
|
||||
it('parses date SDT as controlType "date"', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: DATE_SDT_P }))
|
||||
expect(doc.blocks[0].sdtShell?.controlType).toBe('date')
|
||||
expect(doc.blocks[0].sdtShell?.alias).toBe('Date')
|
||||
})
|
||||
|
||||
it('parses dropdown SDT as controlType "dropdown"', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: DROPDOWN_SDT_P }))
|
||||
expect(doc.blocks[0].sdtShell?.controlType).toBe('dropdown')
|
||||
})
|
||||
|
||||
it('extracts the sdtContent paragraph runs as editable block runs', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: BLOCK_SDT_P }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.runs?.some((r) => r.text.includes('Jane Doe'))).toBe(true)
|
||||
})
|
||||
|
||||
it('plain paragraph has no sdtShell', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: PLAIN_P }))
|
||||
expect(doc.blocks[0].sdtShell).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SDT roundtrip', () => {
|
||||
it('untouched SDT block saves byte-identical (sdt shell preserved)', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: BLOCK_SDT_P })
|
||||
const doc = await parseDocx(bytes)
|
||||
const saved = await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])
|
||||
const reparsed = await parseDocx(saved)
|
||||
// The shell must be preserved
|
||||
expect(reparsed.blocks[0].sdtShell?.alias).toBe('Author Name')
|
||||
// sdtContent text must be preserved
|
||||
expect(reparsed.blocks[0].runs?.some((r) => r.text.includes('Jane Doe'))).toBe(true)
|
||||
// Re-saved XML must contain the sdt shell elements
|
||||
expect(reparsed.internal.documentXml).toContain('<w:sdt>')
|
||||
expect(reparsed.internal.documentXml).toContain('w:val="Author Name"')
|
||||
expect(reparsed.internal.documentXml).toContain('Jane Doe')
|
||||
})
|
||||
|
||||
it('sdt shell openXml contains original sdtPr bytes', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: BLOCK_SDT_P }))
|
||||
const shell = doc.blocks[0].sdtShell!
|
||||
expect(shell.openXml).toContain('<w:sdt>')
|
||||
expect(shell.openXml).toContain('<w:sdtPr>')
|
||||
expect(shell.openXml).toContain('Author Name')
|
||||
expect(shell.openXml).toContain('<w:sdtContent>')
|
||||
expect(shell.closeXml).toBe('</w:sdtContent></w:sdt>')
|
||||
})
|
||||
})
|
||||
|
||||
// ---- Multi-paragraph SDT (Word automatic TOC) ----
|
||||
|
||||
const TOC_ENTRY = (n: number) =>
|
||||
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
|
||||
`<w:r><w:t>Chapter ${n}</w:t></w:r>` +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
`<w:r><w:instrText xml:space="preserve"> PAGEREF _Toc${n} \\h </w:instrText></w:r>` +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
`<w:r><w:t>${n}</w:t></w:r>` +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'</w:p>'
|
||||
|
||||
const TOC_SDT =
|
||||
'<w:sdt>' +
|
||||
'<w:sdtPr><w:id w:val="-1"/>' +
|
||||
'<w:docPartObj><w:docPartGallery w:val="Table of Contents"/><w:docPartUnique/></w:docPartObj>' +
|
||||
'</w:sdtPr>' +
|
||||
'<w:sdtEndPr/>' +
|
||||
'<w:sdtContent>' +
|
||||
'<w:p><w:pPr><w:pStyle w:val="TOCHeading"/></w:pPr><w:r><w:t>Contents</w:t></w:r></w:p>' +
|
||||
Array.from({ length: 13 }, (_, i) => TOC_ENTRY(i + 1)).join('') +
|
||||
'<w:p><w:r><w:t>tail</w:t></w:r></w:p>' +
|
||||
'</w:sdtContent>' +
|
||||
'</w:sdt>'
|
||||
|
||||
const sdtOpenCount = (xml: string) => (xml.match(/<w:sdt>/g) ?? []).length
|
||||
const sdtCloseCount = (xml: string) => (xml.match(/<\/w:sdt>/g) ?? []).length
|
||||
|
||||
describe('multi-paragraph SDT (TOC)', () => {
|
||||
it('yields one block per sdtContent child paragraph', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_SDT }))
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
expect(visible.length).toBe(15)
|
||||
expect(visible[0].runs?.some((r) => r.text.includes('Contents'))).toBe(true)
|
||||
for (let n = 1; n <= 13; n++) {
|
||||
expect(visible[n].type).toBe('passthrough')
|
||||
expect(visible[n].previewText).toContain(`Chapter ${n}`)
|
||||
}
|
||||
expect(visible.map((b) => b.docxIndex)).toEqual(visible.map((_, i) => i))
|
||||
})
|
||||
|
||||
it('splits the shell: first block opens, last block closes, middles carry none', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_SDT }))
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
const shells = visible.map((b) => b.sdtShell!)
|
||||
expect(shells.every((s) => s !== undefined)).toBe(true)
|
||||
expect(new Set(shells.map((s) => s.group)).size).toBe(1)
|
||||
expect(shells[0].group).not.toBeUndefined()
|
||||
expect(shells[0].openXml).toContain('<w:sdt>')
|
||||
expect(shells[0].openXml).toContain('Table of Contents')
|
||||
expect(shells[0].openXml).toContain('<w:sdtContent>')
|
||||
expect(shells[0].closeXml).toBe('')
|
||||
for (const s of shells.slice(1, -1)) {
|
||||
expect(s.openXml).toBe('')
|
||||
expect(s.closeXml).toBe('')
|
||||
}
|
||||
expect(shells[14].openXml).toBe('')
|
||||
expect(shells[14].closeXml).toBe('</w:sdtContent></w:sdt>')
|
||||
})
|
||||
|
||||
it('untouched multi-paragraph sdt saves byte-identical', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: TOC_SDT })
|
||||
const doc = await parseDocx(bytes)
|
||||
const saved = await saveDocx(
|
||||
doc,
|
||||
doc.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
|
||||
)
|
||||
expect(Buffer.from(saved).equals(Buffer.from(bytes))).toBe(true)
|
||||
})
|
||||
|
||||
it('regenerating a middle paragraph keeps a single balanced sdt', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: TOC_SDT })
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
const finalBlocks = visible.map((b, i) =>
|
||||
i === 7
|
||||
? {
|
||||
kind: 'generated' as const,
|
||||
block: {
|
||||
type: 'paragraph' as const,
|
||||
runs: [{ text: 'edited entry' }],
|
||||
sdtShell: b.sdtShell,
|
||||
},
|
||||
}
|
||||
: { kind: 'original' as const, docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
const reparsed = await parseDocx(saved)
|
||||
const xml = reparsed.internal.documentXml
|
||||
expect(sdtOpenCount(xml)).toBe(1)
|
||||
expect(sdtCloseCount(xml)).toBe(1)
|
||||
const contentOpen = xml.indexOf('<w:sdtContent>')
|
||||
const contentClose = xml.indexOf('</w:sdtContent>')
|
||||
const edited = xml.indexOf('edited entry')
|
||||
expect(edited).toBeGreaterThan(contentOpen)
|
||||
expect(edited).toBeLessThan(contentClose)
|
||||
expect(reparsed.blocks.filter((b) => !b.hidden).length).toBe(15)
|
||||
})
|
||||
|
||||
it('regenerating the first and last paragraphs re-emits their shell halves', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: TOC_SDT })
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
const finalBlocks = visible.map((b, i) =>
|
||||
i === 0 || i === visible.length - 1
|
||||
? {
|
||||
kind: 'generated' as const,
|
||||
block: {
|
||||
type: 'paragraph' as const,
|
||||
runs: [{ text: i === 0 ? 'New Title' : 'new tail' }],
|
||||
sdtShell: b.sdtShell,
|
||||
},
|
||||
}
|
||||
: { kind: 'original' as const, docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
const xml = (await parseDocx(saved)).internal.documentXml
|
||||
expect(sdtOpenCount(xml)).toBe(1)
|
||||
expect(sdtCloseCount(xml)).toBe(1)
|
||||
expect(xml.indexOf('New Title')).toBeGreaterThan(xml.indexOf('<w:sdtContent>'))
|
||||
expect(xml.indexOf('new tail')).toBeLessThan(xml.indexOf('</w:sdtContent>'))
|
||||
})
|
||||
|
||||
it('sdt wrapping a table plus a paragraph yields a table block and a paragraph block', async () => {
|
||||
const MIXED_SDT =
|
||||
'<w:sdt><w:sdtPr><w:alias w:val="Report"/></w:sdtPr><w:sdtContent>' +
|
||||
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:tcPr/><w:p><w:r><w:t>cell A</w:t></w:r></w:p></w:tc></w:tr></w:tbl>' +
|
||||
'<w:p><w:r><w:t>after table</w:t></w:r></w:p>' +
|
||||
'</w:sdtContent></w:sdt>'
|
||||
const bytes = await buildDocx({ bodyXml: MIXED_SDT })
|
||||
const doc = await parseDocx(bytes)
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
expect(visible.length).toBe(2)
|
||||
expect(visible[0].type).toBe('table')
|
||||
expect(visible[1].runs?.some((r) => r.text.includes('after table'))).toBe(true)
|
||||
const saved = await saveDocx(
|
||||
doc,
|
||||
visible.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
|
||||
)
|
||||
expect(Buffer.from(saved).equals(Buffer.from(bytes))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,431 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applySectionSettings,
|
||||
applySectionStartType,
|
||||
parseDocx,
|
||||
readSections,
|
||||
readSectionSettings,
|
||||
saveDocx,
|
||||
type SaveBlock,
|
||||
} from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const P = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
|
||||
|
||||
/** Paragraph-level sectPr (section break): landscape A4 + narrow margins + optional continuous */
|
||||
const sectBreakPara = (
|
||||
opts: { landscape?: boolean; continuous?: boolean; extra?: string } = {},
|
||||
) => {
|
||||
const size = opts.landscape
|
||||
? '<w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/>'
|
||||
: '<w:pgSz w:w="11906" w:h="16838"/>'
|
||||
return (
|
||||
'<w:p><w:pPr><w:sectPr>' +
|
||||
(opts.continuous ? '<w:type w:val="continuous"/>' : '') +
|
||||
size +
|
||||
'<w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720" w:header="708" w:footer="708" w:gutter="0"/>' +
|
||||
(opts.extra ?? '') +
|
||||
'</w:sectPr></w:pPr></w:p>'
|
||||
)
|
||||
}
|
||||
|
||||
describe('readSections enumerates all sections', () => {
|
||||
it('single-section document: one section covers all blocks, trailing sectPr provides settings', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: P('a') + P('b') }))
|
||||
const sections = readSections(parsed)
|
||||
expect(sections.length).toBe(1)
|
||||
expect(sections[0].firstBlockIndex).toBe(0)
|
||||
expect(sections[0].settings.pageWidth).toBe(11906)
|
||||
expect(sections[0].startType).toBe('nextPage')
|
||||
expect(sections[0].settings).toEqual(readSectionSettings(parsed))
|
||||
})
|
||||
|
||||
it('two sections: paragraph-level sectPr ends section 1 with correct block ranges', async () => {
|
||||
const bodyXml = P('第一节') + sectBreakPara({ landscape: true }) + P('第二节') + P('尾段')
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const sections = readSections(parsed)
|
||||
expect(sections.length).toBe(2)
|
||||
// Section 1: block 0 (paragraph) + block 1 (section-break paragraph), landscape narrow margins
|
||||
expect(sections[0].firstBlockIndex).toBe(0)
|
||||
expect(sections[0].lastBlockIndex).toBe(1)
|
||||
expect(sections[0].settings.orientation).toBe('landscape')
|
||||
expect(sections[0].settings.pageWidth).toBe(16838)
|
||||
expect(sections[0].settings.marginTop).toBe(720)
|
||||
// Section 2: blocks 2..3 + the trailing hidden section-properties block, portrait A4 default margins
|
||||
expect(sections[1].firstBlockIndex).toBe(2)
|
||||
expect(sections[1].settings.orientation).toBe('portrait')
|
||||
expect(sections[1].settings.pageWidth).toBe(11906)
|
||||
expect(sections[1].settings.marginTop).toBe(1440)
|
||||
expect(sections[1].firstBlockIndex).toBe(sections[0].lastBlockIndex + 1)
|
||||
})
|
||||
|
||||
it('parses startType/titlePg/pgNumType/header-footer references per section', async () => {
|
||||
const extra =
|
||||
'<w:headerReference w:type="default" r:id="rId7"/>' +
|
||||
'<w:footerReference w:type="first" r:id="rId8"/>' +
|
||||
'<w:titlePg/><w:pgNumType w:start="5"/>'
|
||||
const bodyXml = P('a') + sectBreakPara({ continuous: true, extra }) + P('b')
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const sections = readSections(parsed)
|
||||
expect(sections[0].startType).toBe('continuous')
|
||||
expect(sections[0].titlePg).toBe(true)
|
||||
expect(sections[0].pageNumberStart).toBe(5)
|
||||
expect(sections[0].headerRefs.default).toBe('rId7')
|
||||
expect(sections[0].footerRefs.first).toBe('rId8')
|
||||
expect(sections[1].startType).toBe('nextPage')
|
||||
expect(sections[1].titlePg).toBe(false)
|
||||
expect(sections[1].pageNumberStart).toBeUndefined()
|
||||
})
|
||||
|
||||
it('three sections with mixed portrait/landscape', async () => {
|
||||
const bodyXml =
|
||||
P('纵向一') + sectBreakPara() + P('横向二') + sectBreakPara({ landscape: true }) + P('纵向三')
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const sections = readSections(parsed)
|
||||
expect(sections.map((s) => s.settings.orientation)).toEqual([
|
||||
'portrait',
|
||||
'landscape',
|
||||
'portrait',
|
||||
])
|
||||
expect(sections.map((s) => s.firstBlockIndex)).toEqual([0, 2, 4])
|
||||
})
|
||||
|
||||
it('hfParts: parses all header/footer parts by rId (PAGE field displayed as #)', async () => {
|
||||
const XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
|
||||
const headerXml = `${XML}<w:hdr ${W}><w:p><w:r><w:t>第一节页眉</w:t></w:r></w:p></w:hdr>`
|
||||
const footerXml =
|
||||
`${XML}<w:ftr ${W}><w:p><w:r><w:t>第 </w:t></w:r>` +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGE </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t> 页</w:t></w:r></w:p></w:ftr>'
|
||||
const REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
P('a') +
|
||||
sectBreakPara({
|
||||
extra:
|
||||
'<w:headerReference w:type="default" r:id="rId20"/><w:footerReference w:type="default" r:id="rId21"/>',
|
||||
}) +
|
||||
P('b'),
|
||||
extraRels:
|
||||
`<Relationship Id="rId20" Type="${REL}/header" Target="header1.xml"/>` +
|
||||
`<Relationship Id="rId21" Type="${REL}/footer" Target="footer1.xml"/>`,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: headerXml,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
{
|
||||
path: 'word/footer1.xml',
|
||||
xml: footerXml,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
expect(parsed.hfParts?.rId20?.text).toBe('第一节页眉')
|
||||
expect(parsed.hfParts?.rId21?.hasPageNumber).toBe(true)
|
||||
expect(parsed.hfParts?.rId21?.text).toContain('#')
|
||||
const sections = readSections(parsed)
|
||||
expect(sections[0].headerRefs.default).toBe('rId20')
|
||||
expect(sections[0].footerRefs.default).toBe('rId21')
|
||||
expect(sections[1].headerRefs.default).toBeUndefined()
|
||||
})
|
||||
|
||||
it('applySectionStartType: inserts/replaces/removes w:type', () => {
|
||||
const base = '<w:sectPr><w:pgSz w:w="1" w:h="2"/></w:sectPr>'
|
||||
expect(applySectionStartType(base, 'continuous')).toBe(
|
||||
'<w:sectPr><w:type w:val="continuous"/><w:pgSz w:w="1" w:h="2"/></w:sectPr>',
|
||||
)
|
||||
const cont = '<w:sectPr><w:type w:val="continuous"/><w:pgSz w:w="1" w:h="2"/></w:sectPr>'
|
||||
expect(applySectionStartType(cont, 'evenPage')).toContain('<w:type w:val="evenPage"/>')
|
||||
expect(applySectionStartType(cont, 'nextPage')).toBe(base)
|
||||
// Without pgSz, insert at the start of sectPr
|
||||
expect(applySectionStartType('<w:sectPr></w:sectPr>', 'oddPage')).toBe(
|
||||
'<w:sectPr><w:type w:val="oddPage"/></w:sectPr>',
|
||||
)
|
||||
})
|
||||
|
||||
it('section edit round-trip: non-final sectPr rewritten via kind:xml, final section via options.section', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: P('第一节') + sectBreakPara({ landscape: true }) + P('第二节'),
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
const sections = readSections(parsed)
|
||||
// Section 1: landscape → change to portrait narrow margins (simulating layout applied
|
||||
// to the section under the cursor)
|
||||
const edited = {
|
||||
...sections[0].settings,
|
||||
orientation: 'portrait' as const,
|
||||
pageWidth: sections[0].settings.pageHeight,
|
||||
pageHeight: sections[0].settings.pageWidth,
|
||||
marginTop: 567,
|
||||
}
|
||||
const breakBlock = parsed.blocks.find((b) => b.docxIndex === sections[0].lastBlockIndex)!
|
||||
const newXml = breakBlock.originalXml!.replace(
|
||||
sections[0].sectPrXml,
|
||||
applySectionStartType(applySectionSettings(sections[0].sectPrXml, edited), 'continuous'),
|
||||
)
|
||||
const finalBlocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) =>
|
||||
b.docxIndex === sections[0].lastBlockIndex
|
||||
? { kind: 'xml', xml: newXml }
|
||||
: { kind: 'original', docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(parsed, finalBlocks, {
|
||||
section: { ...sections[1].settings, marginLeft: 999 },
|
||||
})
|
||||
const reparsed = readSections(await parseDocx(saved))
|
||||
expect(reparsed[0].settings.orientation).toBe('portrait')
|
||||
expect(reparsed[0].settings.marginTop).toBe(567)
|
||||
expect(reparsed[0].startType).toBe('continuous')
|
||||
expect(reparsed[1].settings.marginLeft).toBe(999)
|
||||
})
|
||||
|
||||
it('insert section break: new break paragraph via kind:xml + trailing sectPr gets w:type', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: P('a') + P('b') })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const sections = readSections(parsed)
|
||||
expect(sections.length).toBe(1)
|
||||
const breakXml = `<w:p><w:pPr>${'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/></w:sectPr>'}</w:pPr></w:p>`
|
||||
const visible = parsed.blocks.filter((b) => !b.hidden)
|
||||
const finalBlocks: SaveBlock[] = [
|
||||
{ kind: 'original', docxIndex: visible[0].docxIndex! },
|
||||
{ kind: 'xml', xml: breakXml },
|
||||
{ kind: 'original', docxIndex: visible[1].docxIndex! },
|
||||
]
|
||||
const saved = await saveDocx(parsed, finalBlocks, { sectionStartType: 'continuous' })
|
||||
const reparsed = readSections(await parseDocx(saved))
|
||||
expect(reparsed.length).toBe(2)
|
||||
expect(reparsed[0].lastBlockIndex).toBe(1)
|
||||
expect(reparsed[1].startType).toBe('continuous')
|
||||
expect(reparsed[1].firstBlockIndex).toBe(2)
|
||||
})
|
||||
|
||||
it('unedited multi-section document saves byte-identical', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: P('第一节') + sectBreakPara({ landscape: true }) + P('第二节'),
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
readSections(parsed)
|
||||
const visible: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
expect(await saveDocx(parsed, visible)).toBe(bytes)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sectionHf per-section headers/footers', () => {
|
||||
const visibleBlocks = (parsed: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] =>
|
||||
parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
|
||||
it('section without references: new part + reference injected into that sectPr, neighbors unaffected', async () => {
|
||||
const bodyXml = P('第一节') + sectBreakPara() + P('第二节')
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const sections = readSections(parsed)
|
||||
expect(sections[0].headerRefs.default).toBeUndefined()
|
||||
|
||||
const saved = await saveDocx(parsed, visibleBlocks(parsed), {
|
||||
sectionHf: [
|
||||
{ lastBlockIndex: sections[0].lastBlockIndex, kind: 'header', hf: { text: '第一节页眉' } },
|
||||
],
|
||||
})
|
||||
const reparsed = await parseDocx(saved)
|
||||
const secs = readSections(reparsed)
|
||||
const rId = secs[0].headerRefs.default
|
||||
expect(rId).toBeDefined()
|
||||
expect(reparsed.hfParts?.[rId!]?.text).toContain('第一节页眉')
|
||||
// The last section did not get a reference stuffed in
|
||||
expect(secs[1].headerRefs.default).toBeUndefined()
|
||||
// The reference is the first child of that section's sectPr
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const docXml = await zip.file('word/document.xml')!.async('string')
|
||||
expect(docXml).toMatch(/<w:sectPr[^>]*><w:headerReference w:type="default"/)
|
||||
})
|
||||
|
||||
it('section with an existing reference: rewrites the referenced part instead of creating one', async () => {
|
||||
const HDR =
|
||||
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:p><w:r><w:t>旧页眉</w:t></w:r></w:p></w:hdr>'
|
||||
const bodyXml =
|
||||
P('第一节') +
|
||||
sectBreakPara({ extra: '<w:headerReference w:type="default" r:id="rId60"/>' }) +
|
||||
P('第二节')
|
||||
const bytes = await buildDocx({
|
||||
bodyXml,
|
||||
extraRels:
|
||||
'<Relationship Id="rId60" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: HDR,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
const sections = readSections(parsed)
|
||||
expect(sections[0].headerRefs.default).toBe('rId60')
|
||||
|
||||
const saved = await saveDocx(parsed, visibleBlocks(parsed), {
|
||||
sectionHf: [
|
||||
{ lastBlockIndex: sections[0].lastBlockIndex, kind: 'header', hf: { text: '新页眉' } },
|
||||
],
|
||||
})
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const hdr = await zip.file('word/header1.xml')!.async('string')
|
||||
expect(hdr).toContain('新页眉')
|
||||
expect(zip.file('word/header2.xml')).toBeNull()
|
||||
// Reference count unchanged (no duplicate injection)
|
||||
const docXml = await zip.file('word/document.xml')!.async('string')
|
||||
expect(docXml.match(/<w:headerReference/g)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('kind:xml section-break block (layout rewritten in the same pass) can also receive references', async () => {
|
||||
const bodyXml = P('第一节') + sectBreakPara({ landscape: true }) + P('第二节')
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const sections = readSections(parsed)
|
||||
const breakBlock = parsed.blocks.find((b) => b.docxIndex === sections[0].lastBlockIndex)!
|
||||
const rewritten = applySectionSettings(sections[0].sectPrXml, {
|
||||
...sections[0].settings,
|
||||
marginTop: 720,
|
||||
})
|
||||
const finalBlocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) =>
|
||||
b.docxIndex === sections[0].lastBlockIndex
|
||||
? {
|
||||
kind: 'xml' as const,
|
||||
xml: breakBlock.originalXml!.replace(sections[0].sectPrXml, rewritten),
|
||||
docxIndex: b.docxIndex!,
|
||||
}
|
||||
: { kind: 'original' as const, docxIndex: b.docxIndex! },
|
||||
)
|
||||
const saved = await saveDocx(parsed, finalBlocks, {
|
||||
sectionHf: [
|
||||
{ lastBlockIndex: sections[0].lastBlockIndex, kind: 'footer', hf: { text: '第一节页脚' } },
|
||||
],
|
||||
})
|
||||
const reparsed = await parseDocx(saved)
|
||||
const secs = readSections(reparsed)
|
||||
expect(secs[0].settings.marginTop).toBe(720)
|
||||
const rId = secs[0].footerRefs.default
|
||||
expect(rId).toBeDefined()
|
||||
expect(reparsed.hfParts?.[rId!]?.text).toContain('第一节页脚')
|
||||
})
|
||||
})
|
||||
|
||||
describe('pgNumType page numbering', () => {
|
||||
it('applyPageNumType inserts/replaces/removes', async () => {
|
||||
const { applyPageNumType } = await import('../src/index')
|
||||
const base =
|
||||
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/><w:cols w:space="425"/></w:sectPr>'
|
||||
const withFmt = applyPageNumType(base, 'lowerRoman', 3)
|
||||
expect(withFmt).toContain('<w:pgNumType w:fmt="lowerRoman" w:start="3"/><w:cols')
|
||||
// Replacement does not duplicate
|
||||
const replaced = applyPageNumType(withFmt, 'upperLetter', undefined)
|
||||
expect(replaced.match(/<w:pgNumType/g)).toHaveLength(1)
|
||||
expect(replaced).toContain('w:fmt="upperLetter"')
|
||||
expect(replaced).not.toContain('w:start=')
|
||||
// All-unset removes the tag
|
||||
expect(applyPageNumType(withFmt, undefined, undefined)).not.toContain('pgNumType')
|
||||
// Without cols it lands right before </w:sectPr>
|
||||
const noCols = base.replace('<w:cols w:space="425"/>', '')
|
||||
expect(applyPageNumType(noCols, 'decimal', undefined)).toContain(
|
||||
'<w:pgNumType w:fmt="decimal"/></w:sectPr>',
|
||||
)
|
||||
})
|
||||
|
||||
it('SaveOptions.pgNumType writes the final section and round-trips', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: P('正文') }))
|
||||
const blocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
const saved = await saveDocx(parsed, blocks, { pgNumType: { fmt: 'upperRoman', start: 5 } })
|
||||
const secs = readSections(await parseDocx(saved))
|
||||
expect(secs[0].pageNumberFmt).toBe('upperRoman')
|
||||
expect(secs[0].pageNumberStart).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SaveOptions.numbering write-back', () => {
|
||||
const P2 = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
|
||||
const LI = (numId: number, text: string) =>
|
||||
`<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="${numId}"/></w:numPr></w:pPr><w:r><w:t>${text}</w:t></w:r></w:p>`
|
||||
const NUMBERING =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
|
||||
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:abstractNum w:abstractNumId="3"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>' +
|
||||
'<w:num w:numId="5"><w:abstractNumId w:val="3"/></w:num>' +
|
||||
'</w:numbering>'
|
||||
|
||||
it('restartNums: appends a w:num pointing at an existing abstractNum + startOverride', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: LI(5, '一') + LI(5, '二'),
|
||||
numberingXml: NUMBERING,
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
const blocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
const saved = await saveDocx(parsed, blocks, {
|
||||
numbering: { restartNums: [{ numId: '6', abstractNumId: '3', startOverrides: { 0: 1 } }] },
|
||||
})
|
||||
const reparsed = await parseDocx(saved)
|
||||
const def = reparsed.numbering.get('6')
|
||||
expect(def).toBeDefined()
|
||||
expect(def!.abstractNumId).toBe('3')
|
||||
expect(def!.startOverrides[0]).toBe(1)
|
||||
// Existing entries keep their original bytes
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const numXml = await zip.file('word/numbering.xml')!.async('string')
|
||||
expect(numXml).toContain('<w:num w:numId="5"><w:abstractNumId w:val="3"/></w:num>')
|
||||
})
|
||||
|
||||
it('newDefs: allocates a new abstractNum; creates part/rel/ContentType when numbering.xml is missing', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: P2('正文') })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const blocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
const saved = await saveDocx(parsed, blocks, {
|
||||
numbering: { newDefs: [{ numId: '10', kind: 'ordered' }] },
|
||||
})
|
||||
const reparsed = await parseDocx(saved)
|
||||
const def = reparsed.numbering.get('10')
|
||||
expect(def).toBeDefined()
|
||||
expect(def!.levels[0].numFmt).toBe('decimal')
|
||||
// numIds 1/2 from the blank-template base are also present
|
||||
expect(reparsed.numbering.get('1')!.levels[0].numFmt).toBe('bullet')
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
expect(rels).toContain('Target="numbering.xml"')
|
||||
const ct = await zip.file('[Content_Types].xml')!.async('string')
|
||||
expect(ct).toContain('PartName="/word/numbering.xml"')
|
||||
// The abstract id does not clash with the template's 0/1
|
||||
const numXml = await zip.file('word/numbering.xml')!.async('string')
|
||||
expect(numXml).toContain('<w:num w:numId="10"><w:abstractNumId w:val="2"/></w:num>')
|
||||
})
|
||||
|
||||
it('with an existing numbering.xml, newDefs abstracts are inserted before w:num entries', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: LI(5, '一'), numberingXml: NUMBERING })
|
||||
const parsed = await parseDocx(bytes)
|
||||
const blocks: SaveBlock[] = parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
|
||||
const saved = await saveDocx(parsed, blocks, {
|
||||
numbering: { newDefs: [{ numId: '9', kind: 'bullet' }] },
|
||||
})
|
||||
const zip = await (await import('jszip')).default.loadAsync(saved)
|
||||
const numXml = await zip.file('word/numbering.xml')!.async('string')
|
||||
// The new abstract (id=4) comes before the first w:num; the new num goes at the end
|
||||
expect(numXml.indexOf('w:abstractNumId="4"')).toBeLessThan(numXml.indexOf('<w:num '))
|
||||
expect(numXml).toContain('<w:num w:numId="9"><w:abstractNumId w:val="4"/></w:num>')
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.numbering.get('9')!.levels[0].numFmt).toBe('bullet')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const DIAGRAM_DATA_XML =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<dgm:dataModel xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram" ' +
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><dgm:ptLst>' +
|
||||
['总经理办', '研发部', '产品部', '销售部', '运营部']
|
||||
.map(
|
||||
(t, i) =>
|
||||
`<dgm:pt modelId="{${i}}"><dgm:t><a:bodyPr/><a:p><a:r><a:t>${t}</a:t></a:r></a:p></dgm:t></dgm:pt>`,
|
||||
)
|
||||
.join('') +
|
||||
'</dgm:ptLst></dgm:dataModel>'
|
||||
|
||||
const SMARTART_P =
|
||||
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="5486400" cy="419100"/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/diagram">' +
|
||||
'<dgm:relIds xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram" ' +
|
||||
'r:dm="rId40" r:lo="rId41" r:qs="rId42" r:cs="rId43"/>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
|
||||
|
||||
const OLE_P =
|
||||
'<w:p><w:r><w:object><v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="_x0000_i1025" ' +
|
||||
'style="width:32pt;height:32pt"><v:imagedata r:id="rId10" o:title=""/></v:shape>' +
|
||||
'<o:OLEObject xmlns:o="urn:schemas-microsoft-com:office:office" Type="Embed" ' +
|
||||
'ProgID="Excel.Sheet.12" ShapeID="_x0000_i1025" DrawAspect="Icon" ObjectID="_1"/>' +
|
||||
'</w:object></w:r></w:p>'
|
||||
|
||||
async function buildFixture(): Promise<Uint8Array> {
|
||||
return buildDocx({
|
||||
bodyXml: SMARTART_P + OLE_P,
|
||||
withImage: true,
|
||||
extraRels:
|
||||
'<Relationship Id="rId40" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramData" Target="diagrams/data1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/diagrams/data1.xml',
|
||||
xml: DIAGRAM_DATA_XML,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
describe('SmartArt / OLE visible degrade (#220)', () => {
|
||||
it('SmartArt preview lists the diagram node texts', async () => {
|
||||
const parsed = await parseDocx(await buildFixture())
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.label).toBe('SmartArt')
|
||||
expect(block.previewText).toBe('总经理办\n研发部\n产品部\n销售部\n运营部')
|
||||
})
|
||||
|
||||
it('OLE embed surfaces the packaged preview picture and ProgID', async () => {
|
||||
const parsed = await parseDocx(await buildFixture())
|
||||
const block = parsed.blocks[1]
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.label).toBe('Embedded object')
|
||||
expect(block.oleProgId).toBe('Excel.Sheet.12')
|
||||
expect(block.imageDataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
})
|
||||
|
||||
it('a missing diagram part degrades to the bare label, not an error', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: SMARTART_P }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.label).toBe('SmartArt')
|
||||
expect(block.previewText ?? '').toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeSymbolChar, decodeSymbolText, isSymbolFont, parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
describe('symbol font decoding helpers', () => {
|
||||
it('recognizes symbol-encoded fonts case-insensitively', () => {
|
||||
expect(isSymbolFont('Wingdings')).toBe(true)
|
||||
expect(isSymbolFont('symbol')).toBe(true)
|
||||
expect(isSymbolFont('Webdings')).toBe(true)
|
||||
expect(isSymbolFont('Calibri')).toBe(false)
|
||||
expect(isSymbolFont(null)).toBe(false)
|
||||
})
|
||||
|
||||
it('maps raw bytes and their U+F0xx private-use forms alike', () => {
|
||||
expect(decodeSymbolChar('Wingdings', 0x6c)).toBe('●')
|
||||
expect(decodeSymbolChar('Wingdings', 0xf06c)).toBe('●')
|
||||
expect(decodeSymbolChar('Symbol', 0xf0b7)).toBe('•')
|
||||
expect(decodeSymbolChar('Wingdings', 0xf000)).toBeNull()
|
||||
})
|
||||
|
||||
it('decodes whole strings only when every glyph maps', () => {
|
||||
expect(decodeSymbolText('Symbol', 'abg')).toBe('αβγ')
|
||||
expect(decodeSymbolText('Wingdings', 'l e')).toBeNull()
|
||||
expect(decodeSymbolText('Calibri', 'abc')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('symbol runs in document.xml', () => {
|
||||
it('converts w:sym to the Unicode equivalent', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:t>勾:</w:t></w:r><w:r><w:sym w:font="Wingdings" w:char="F0FC"/></w:r>' +
|
||||
'<w:r><w:sym w:font="Wingdings" w:char="6C"/></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('勾:✓●')
|
||||
})
|
||||
|
||||
it('keeps unknown w:sym glyphs as private-use characters', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:sym w:font="Wingdings 2" w:char="F045"/></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('\uF045')
|
||||
})
|
||||
|
||||
it('decodes text runs carrying a symbol font and drops the font', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol"/></w:rPr><w:t></w:t></w:r>' +
|
||||
'<w:r><w:t> 后文</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const run = doc.blocks[0].runs![0]
|
||||
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('• 后文')
|
||||
expect(run.font).toBeUndefined()
|
||||
expect(run.rawRPr ?? '').not.toContain('w:rFonts')
|
||||
})
|
||||
|
||||
it('leaves undecodable symbol-font runs untouched', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Wingdings" w:hAnsi="Wingdings"/></w:rPr><w:t>le</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const run = doc.blocks[0].runs![0]
|
||||
expect(run.text).toBe('le')
|
||||
expect(run.font).toBe('Wingdings')
|
||||
})
|
||||
|
||||
it('decodes numeric character references in w:t', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>✓A</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('✓A')
|
||||
})
|
||||
})
|
||||
|
||||
describe('numbering level marker font', () => {
|
||||
it('parses w:rPr/w:rFonts of a bullet level', async () => {
|
||||
const numberingXml =
|
||||
XML_DECL +
|
||||
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:abstractNum w:abstractNumId="0">' +
|
||||
'<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="l"/>' +
|
||||
'<w:rPr><w:rFonts w:ascii="Wingdings" w:hAnsi="Wingdings"/></w:rPr></w:lvl>' +
|
||||
'</w:abstractNum>' +
|
||||
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
|
||||
'</w:numbering>'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>项</w:t></w:r></w:p>',
|
||||
numberingXml,
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.numbering.get('1')!.levels[0].font).toBe('Wingdings')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const STYLED_TABLE_XML =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="4000"/><w:gridCol w:w="2000"/></w:tblGrid>' +
|
||||
// header row: shaded cells, bold white text, centered
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>排名</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>品牌</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>份额</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr>' +
|
||||
// data row with colSpan
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:p><w:r><w:t>1</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:gridSpan w:val="2"/></w:tcPr><w:p><w:r><w:t>比亚迪</w:t></w:r></w:p><w:p><w:r><w:t>第二段</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr>' +
|
||||
// vertical merge pair
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:tcPr><w:vMerge w:val="restart"/></w:tcPr><w:p><w:r><w:t>竖排</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>b</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr>' +
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:tcPr><w:vMerge/></w:tcPr><w:p/></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>c</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>d</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr>' +
|
||||
'</w:tbl>'
|
||||
|
||||
describe('table display model', () => {
|
||||
it('extracts rows, shading, bold, alignment, spans and column widths', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: STYLED_TABLE_XML }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('table')
|
||||
const table = block.table!
|
||||
expect(table.rows).toHaveLength(4)
|
||||
|
||||
const header = table.rows[0]
|
||||
expect(header.map((c) => c.paras[0])).toEqual(['排名', '品牌', '份额'])
|
||||
expect(header[0]).toMatchObject({ fill: '1F3864', color: 'FFFFFF', bold: true, align: 'center' })
|
||||
|
||||
const dataRow = table.rows[1]
|
||||
expect(dataRow[1].colSpan).toBe(2)
|
||||
expect(dataRow[1].paras).toEqual(['比亚迪', '第二段'])
|
||||
expect(dataRow[0].bold).toBeUndefined()
|
||||
|
||||
expect(table.rows[2][0].vMerge).toBe('restart')
|
||||
expect(table.rows[3][0].vMerge).toBe('continue')
|
||||
|
||||
expect(table.colWidthsPct).toHaveLength(3)
|
||||
expect(Math.round(table.colWidthsPct![0])).toBe(25)
|
||||
expect(Math.round(table.colWidthsPct![1])).toBe(50)
|
||||
})
|
||||
|
||||
it('original table XML is still saved byte-identical (display model is read-only)', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: STYLED_TABLE_XML })
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].originalXml).toContain('<w:tbl>')
|
||||
})
|
||||
|
||||
it('parses table-level borders / alignment / cell margins / nested tables', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblPr>' +
|
||||
'<w:tblW w:w="0" w:type="auto"/><w:jc w:val="center"/><w:tblInd w:w="120" w:type="dxa"/>' +
|
||||
'<w:tblBorders><w:top w:val="single" w:sz="12" w:space="0" w:color="FF0000"/>' +
|
||||
'<w:insideH w:val="none"/><w:insideV w:val="single" w:sz="4"/></w:tblBorders>' +
|
||||
'<w:tblCellMar><w:top w:w="0" w:type="dxa"/><w:left w:w="0" w:type="dxa"/></w:tblCellMar>' +
|
||||
'</w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="3000"/><w:gridCol w:w="3000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>外层</w:t></w:r></w:p>' +
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="1000"/><w:gridCol w:w="1000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>内A</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>内B</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'</w:tbl><w:p/></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>右格</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'</w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const table = doc.blocks[0].table!
|
||||
expect(table.align).toBe('center')
|
||||
// tblInd is still parsed with jc=center (the renderer only applies it for left alignment)
|
||||
expect(table.indentTwips).toBe(120)
|
||||
expect(table.borders?.top).toMatchObject({ style: 'single', szEighths: 12, color: 'FF0000' })
|
||||
expect(table.borders?.insideH).toMatchObject({ style: 'none' })
|
||||
expect(table.borders?.insideV).toMatchObject({ style: 'single', szEighths: 4 })
|
||||
expect(table.cellMarTwips).toEqual({ top: 0, left: 0 })
|
||||
expect(table.colWidthsTwips).toEqual([3000, 3000])
|
||||
const outerCell = table.rows[0][0]
|
||||
expect(outerCell.paras[0]).toBe('外层')
|
||||
const nested = outerCell.nestedTables![0]
|
||||
expect(nested.rows[0].map((c) => c.paras[0])).toEqual(['内A', '内B'])
|
||||
expect(nested.colWidthsTwips).toEqual([1000, 1000])
|
||||
})
|
||||
|
||||
it('parses cell textDirection and falls back to tcW when tblGrid is unusable', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="0"/><w:gridCol w:w="0"/></w:tblGrid>' +
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:textDirection w:val="tbRlV"/></w:tcPr><w:p><w:r><w:t>竖</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="6000" w:type="dxa"/><w:textDirection w:val="btLr"/></w:tcPr><w:p><w:r><w:t>横转</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const table = doc.blocks[0].table!
|
||||
expect(table.colWidthsTwips).toEqual([2000, 6000])
|
||||
expect(Math.round(table.colWidthsPct![0])).toBe(25)
|
||||
expect(table.rows[0][0].textDirection).toBe('tbRl')
|
||||
expect(table.rows[0][1].textDirection).toBe('btLr')
|
||||
})
|
||||
|
||||
it('merges legacy w:hMerge continue cells into the restart cell', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid>' +
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:tcPr><w:hMerge w:val="restart"/></w:tcPr><w:p><w:r><w:t>合并头</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:hMerge/></w:tcPr><w:p/></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>右</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const row = doc.blocks[0].table!.rows[0]
|
||||
expect(row).toHaveLength(2)
|
||||
expect(row[0].colSpan).toBe(2)
|
||||
expect(row[0].paras[0]).toBe('合并头')
|
||||
expect(row[1].paras[0]).toBe('右')
|
||||
})
|
||||
|
||||
it('inherits tblBorders / tblCellMar from the referenced table style', async () => {
|
||||
const styleXml =
|
||||
'<w:style w:type="table" w:styleId="GridStyled"><w:name w:val="Grid Styled"/>' +
|
||||
'<w:tblPr><w:tblBorders><w:top w:val="single" w:sz="16" w:color="00FF00"/>' +
|
||||
'<w:insideH w:val="dashed" w:sz="4"/></w:tblBorders>' +
|
||||
'<w:tblCellMar><w:left w:w="200" w:type="dxa"/><w:right w:w="200" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>'
|
||||
const xml =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="GridStyled"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>甲</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml, extraStylesXml: styleXml }))
|
||||
const table = doc.blocks[0].table!
|
||||
expect(table.borders?.top).toMatchObject({ style: 'single', szEighths: 16, color: '00FF00' })
|
||||
expect(table.borders?.insideH).toMatchObject({ style: 'dashed' })
|
||||
expect(table.cellMarTwips).toEqual({ left: 200, right: 200 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,245 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateTableModelXml, parseDocx, patchTableCellTexts } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const TABLE_XML =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>标题A</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>标题B</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr>' +
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:p><w:r><w:t>甲</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>乙</w:t></w:r></w:p><w:p><w:r><w:t>第二段</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr>' +
|
||||
'</w:tbl>'
|
||||
|
||||
describe('patchTableCellTexts', () => {
|
||||
it('replaces a single cell text and keeps the rest byte-identical', () => {
|
||||
const out = patchTableCellTexts(TABLE_XML, [null, [['已修改'], null]])
|
||||
expect(out).toContain('<w:t xml:space="preserve">已修改</w:t>')
|
||||
expect(out).not.toContain('<w:t>甲</w:t>')
|
||||
// untouched cells keep exact original bytes
|
||||
expect(out).toContain('<w:t>标题A</w:t>')
|
||||
expect(out).toContain('<w:t>标题B</w:t>')
|
||||
expect(out).toContain('<w:t>乙</w:t>')
|
||||
})
|
||||
|
||||
it('preserves tcPr, first-paragraph pPr and first-run rPr of the edited cell', () => {
|
||||
const out = patchTableCellTexts(TABLE_XML, [[['新标题'], null], null])
|
||||
const cell = /<w:tc>[\s\S]*?<\/w:tc>/.exec(out)![0]
|
||||
expect(cell).toContain('<w:shd w:val="clear" w:fill="1F3864"/>')
|
||||
expect(cell).toContain('<w:jc w:val="center"/>')
|
||||
expect(cell).toContain('<w:b/>')
|
||||
expect(cell).toContain('<w:color w:val="FFFFFF"/>')
|
||||
expect(cell).toContain('<w:t xml:space="preserve">新标题</w:t>')
|
||||
})
|
||||
|
||||
it('writes multiple paragraphs per cell and escapes XML entities', () => {
|
||||
const out = patchTableCellTexts(TABLE_XML, [null, [null, ['A<B', '&C']]])
|
||||
expect(out).toContain('<w:t xml:space="preserve">A<B</w:t>')
|
||||
expect(out).toContain('<w:t xml:space="preserve">&C</w:t>')
|
||||
})
|
||||
|
||||
it('round-trips through the parser with the new text', async () => {
|
||||
const patched = patchTableCellTexts(TABLE_XML, [null, [['改甲'], ['改乙一', '改乙二']]])
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: patched }))
|
||||
const table = doc.blocks[0].table!
|
||||
expect(table.rows[1][0].paras).toEqual(['改甲'])
|
||||
expect(table.rows[1][1].paras).toEqual(['改乙一', '改乙二'])
|
||||
// header styles survived
|
||||
expect(table.rows[0][0]).toMatchObject({ fill: '1F3864', bold: true, align: 'center' })
|
||||
})
|
||||
|
||||
it('skips cells containing nested tables', () => {
|
||||
const nested =
|
||||
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>外层</w:t></w:r></w:p>' +
|
||||
'<w:tbl><w:tr><w:tc><w:p><w:r><w:t>内层</w:t></w:r></w:p></w:tc></w:tr></w:tbl>' +
|
||||
'<w:p/></w:tc></w:tr></w:tbl>'
|
||||
const out = patchTableCellTexts(nested, [[['不应生效']]])
|
||||
expect(out).toBe(nested)
|
||||
})
|
||||
|
||||
it('handles vertical merges: continue cells stay untouched', () => {
|
||||
const merged =
|
||||
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:vMerge w:val="restart"/></w:tcPr><w:p><w:r><w:t>合并首</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:vMerge/></w:tcPr><w:p/></w:tc></w:tr>' +
|
||||
'</w:tbl>'
|
||||
const out = patchTableCellTexts(merged, [[['新合并首']], null])
|
||||
expect(out).toContain('<w:t xml:space="preserve">新合并首</w:t>')
|
||||
expect(out).toContain('<w:vMerge w:val="restart"/>')
|
||||
expect(out).toContain('<w:vMerge/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('generateTableModelXml', () => {
|
||||
it('round-trips structural rows, columns, styling, and merged cells', async () => {
|
||||
const xml = generateTableModelXml({
|
||||
colWidthsPct: [25, 35, 40],
|
||||
rows: [
|
||||
[
|
||||
{
|
||||
paras: ['Merged header'],
|
||||
colSpan: 2,
|
||||
vMerge: 'restart',
|
||||
fill: '1F3864',
|
||||
color: 'FFFFFF',
|
||||
bold: true,
|
||||
align: 'center',
|
||||
},
|
||||
{ paras: ['C'] },
|
||||
],
|
||||
[{ paras: [''], colSpan: 2, vMerge: 'continue', fill: '1F3864' }, { paras: ['D'] }],
|
||||
[{ paras: ['A'] }, { paras: ['B'] }, { paras: ['C'] }],
|
||||
],
|
||||
})
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const model = parsed.blocks[0].table!
|
||||
|
||||
expect(model.rows).toHaveLength(3)
|
||||
expect(model.rows[0][0]).toMatchObject({
|
||||
paras: ['Merged header'],
|
||||
colSpan: 2,
|
||||
vMerge: 'restart',
|
||||
fill: '1F3864',
|
||||
color: 'FFFFFF',
|
||||
bold: true,
|
||||
align: 'center',
|
||||
})
|
||||
expect(model.rows[1][0]).toMatchObject({ colSpan: 2, vMerge: 'continue' })
|
||||
expect(model.rows[2].map((cell) => cell.paras[0])).toEqual(['A', 'B', 'C'])
|
||||
expect(model.colWidthsPct?.map(Math.round)).toEqual([25, 35, 40])
|
||||
})
|
||||
|
||||
it('reuses the imported tblPr while regenerating rows and rich runs', async () => {
|
||||
const template =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/>' +
|
||||
'<w:tblCellMar><w:left w:w="120" w:type="dxa"/></w:tblCellMar></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="8000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>Old</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const xml = generateTableModelXml(
|
||||
{
|
||||
rows: [
|
||||
[
|
||||
{
|
||||
paras: ['Rich'],
|
||||
richParas: [
|
||||
{
|
||||
runs: [
|
||||
{
|
||||
text: 'Rich',
|
||||
bold: true,
|
||||
color: 'C00000',
|
||||
font: 'Arial',
|
||||
sizeHalfPoints: 30,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{ paras: ['New'] },
|
||||
],
|
||||
],
|
||||
},
|
||||
template,
|
||||
)
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const run = parsed.blocks[0].table?.rows[0][0].richParas?.[0].runs[0]
|
||||
|
||||
expect(xml).toContain('<w:tblStyle w:val="TableGrid"/>')
|
||||
expect(xml).toContain('<w:tblCellMar><w:left w:w="120" w:type="dxa"/></w:tblCellMar>')
|
||||
expect(run).toMatchObject({
|
||||
text: 'Rich',
|
||||
bold: true,
|
||||
color: 'C00000',
|
||||
font: 'Arial',
|
||||
sizeHalfPoints: 30,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('tcPr/trPr fidelity and new attributes', () => {
|
||||
it('generateTableModelXml: unmodeled rawTcPr attributes are kept; vAlign/borders are written from the model', async () => {
|
||||
const { generateTableModelXml } = await import('../src/index')
|
||||
const model = {
|
||||
rows: [
|
||||
[
|
||||
{
|
||||
paras: ['a'],
|
||||
vAlign: 'center' as const,
|
||||
borders: {
|
||||
top: { style: 'single', szEighths: 8, color: 'FF0000' },
|
||||
bottom: { style: 'none' },
|
||||
},
|
||||
rawTcPr:
|
||||
'<w:tcPr><w:tcW w:w="4000" w:type="dxa"/><w:tcMar><w:left w:w="200" w:type="dxa"/></w:tcMar><w:textDirection w:val="btLr"/></w:tcPr>',
|
||||
},
|
||||
{ paras: ['b'] },
|
||||
],
|
||||
],
|
||||
rowHeightsTwips: [600],
|
||||
rawTrPrs: ['<w:trPr><w:cantSplit/></w:trPr>'],
|
||||
}
|
||||
const xml = generateTableModelXml(model)
|
||||
// Unmodeled properties are kept
|
||||
expect(xml).toContain('<w:tcMar><w:left w:w="200" w:type="dxa"/></w:tcMar>')
|
||||
expect(xml).toContain('<w:textDirection w:val="btLr"/>')
|
||||
// vAlign comes after textDirection (schema order); borders sit in the shd position range
|
||||
expect(xml).toContain('<w:vAlign w:val="center"/>')
|
||||
expect(xml.indexOf('<w:tcBorders>')).toBeLessThan(xml.indexOf('<w:tcMar>'))
|
||||
expect(xml).toContain('<w:top w:val="single" w:sz="8" w:space="0" w:color="FF0000"/>')
|
||||
expect(xml).toContain('<w:bottom w:val="none"/>')
|
||||
// trPr: cantSplit kept + trHeight injected
|
||||
expect(xml).toContain(
|
||||
'<w:trPr><w:cantSplit/><w:trHeight w:val="600" w:hRule="atLeast"/></w:trPr>',
|
||||
)
|
||||
})
|
||||
|
||||
it('parse read-back: vAlign/tcBorders/trHeight/rawTcPr/rawTrPr', async () => {
|
||||
const { parseDocx } = await import('../src/index')
|
||||
const { buildDocx } = await import('./helpers/build-docx')
|
||||
const tbl =
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="8000" w:type="dxa"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:trPr><w:trHeight w:val="500"/><w:cantSplit/></w:trPr>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/><w:vAlign w:val="bottom"/>' +
|
||||
'<w:tcBorders><w:top w:val="dashed" w:sz="12" w:color="00FF00"/></w:tcBorders>' +
|
||||
'<w:tcMar><w:left w:w="100" w:type="dxa"/></w:tcMar></w:tcPr>' +
|
||||
'<w:p><w:r><w:t>x</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>y</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr></w:tbl>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: tbl }))
|
||||
const table = parsed.blocks.find((b) => b.type === 'table')!
|
||||
const model = table.table!
|
||||
const cell = model.rows[0][0]
|
||||
expect(cell.vAlign).toBe('bottom')
|
||||
expect(cell.borders?.top).toEqual({ style: 'dashed', szEighths: 12, color: '00FF00' })
|
||||
expect(cell.rawTcPr).toContain('<w:tcMar>')
|
||||
expect(model.rowHeightsTwips).toEqual([500])
|
||||
expect(model.rawTrPrs?.[0]).toContain('<w:cantSplit/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tblStyleId table style reference', () => {
|
||||
it('replaces/inserts/removes w:tblStyle, adding a default tblLook when missing', async () => {
|
||||
const { generateTableModelXml } = await import('../src/index')
|
||||
const model = { rows: [[{ paras: ['x'] }]], tblStyleId: 'FancyTable' }
|
||||
const orig =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="8000" w:type="dxa"/></w:tblPr><w:tblGrid><w:gridCol w:w="8000"/></w:tblGrid><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl>'
|
||||
const xml = generateTableModelXml(model, orig)
|
||||
expect(xml).toContain('<w:tblPr><w:tblStyle w:val="FancyTable"/><w:tblW')
|
||||
expect(xml.match(/<w:tblStyle/g)).toHaveLength(1)
|
||||
expect(xml).toContain('<w:tblLook w:val="04A0"')
|
||||
// Removal
|
||||
const removed = generateTableModelXml({ rows: [[{ paras: ['x'] }]], tblStyleId: '' }, orig)
|
||||
expect(removed).not.toContain('<w:tblStyle')
|
||||
// undefined leaves it untouched
|
||||
const kept = generateTableModelXml({ rows: [[{ paras: ['x'] }]] }, orig)
|
||||
expect(kept).toContain('<w:tblStyle w:val="TableGrid"/>')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx, REVISION_TABLE_XML } from './helpers/build-docx'
|
||||
|
||||
describe('table row / cell revisions (trPr w:ins/w:del, tcPr w:cellIns/w:cellDel)', () => {
|
||||
it('parses row and cell revisions into the table model', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: REVISION_TABLE_XML }))
|
||||
const model = doc.blocks[0].table!
|
||||
expect(doc.blocks[0].type).toBe('table')
|
||||
expect(model.rowRevisions).toEqual([
|
||||
null,
|
||||
{ kind: 'del', author: 'Alice', date: '2026-01-01T00:00:00Z', id: '11' },
|
||||
null,
|
||||
])
|
||||
expect(model.rows[2][0].cellRevision).toEqual({
|
||||
kind: 'ins',
|
||||
author: 'Alice',
|
||||
date: '2026-01-01T00:00:00Z',
|
||||
id: '15',
|
||||
})
|
||||
// deleted-row text arrives as del-marked runs, still part of the editable model
|
||||
expect(model.rows[1][0].richParas?.[0]?.runs?.[0]?.del?.author).toBe('Alice')
|
||||
})
|
||||
|
||||
it('keeps an untouched revision table byte-identical', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: REVISION_TABLE_XML })
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])).toEqual(bytes)
|
||||
})
|
||||
|
||||
it('parses row insertion (trPr w:ins)', async () => {
|
||||
const xml = REVISION_TABLE_XML.replace('<w:del w:id="11"', '<w:ins w:id="11"')
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(doc.blocks[0].table!.rowRevisions?.[1]?.kind).toBe('ins')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const GRID_STYLE =
|
||||
'<w:style w:type="table" w:styleId="GridBlue"><w:name w:val="Grid Table Blue"/>' +
|
||||
'<w:tblStylePr w:type="firstRow"><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr>' +
|
||||
'<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="4472C4"/></w:tcPr></w:tblStylePr>' +
|
||||
'<w:tblStylePr w:type="band1Horz"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="D9E2F3"/></w:tcPr></w:tblStylePr>' +
|
||||
'</w:style>' +
|
||||
'<w:style w:type="table" w:styleId="GridBlueChild"><w:name w:val="Child"/><w:basedOn w:val="GridBlue"/>' +
|
||||
'<w:tblStylePr w:type="band1Horz"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="EEEEEE"/></w:tcPr></w:tblStylePr>' +
|
||||
'</w:style>'
|
||||
|
||||
const row = (a: string, b: string, shd = '') =>
|
||||
`<w:tr><w:tc>${shd ? `<w:tcPr>${shd}</w:tcPr>` : ''}<w:p><w:r><w:t>${a}</w:t></w:r></w:p></w:tc>` +
|
||||
`<w:tc><w:p><w:r><w:t>${b}</w:t></w:r></w:p></w:tc></w:tr>`
|
||||
|
||||
function styledTable(look: string, extra = ''): string {
|
||||
return (
|
||||
`<w:tbl><w:tblPr><w:tblStyle w:val="GridBlue"/>${look}</w:tblPr>` +
|
||||
row('表头A', '表头B') +
|
||||
row('一1', '一2', extra) +
|
||||
row('二1', '二2') +
|
||||
row('三1', '三2') +
|
||||
'</w:tbl>'
|
||||
)
|
||||
}
|
||||
|
||||
describe('table styles (tblStyle display)', () => {
|
||||
it('parses table styles with firstRow / banding and applies them per tblLook', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: styledTable('<w:tblLook w:firstRow="1" w:noHBand="0"/>'),
|
||||
extraStylesXml: GRID_STYLE,
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const info = doc.styles.get('GridBlue')!
|
||||
expect(info.type).toBe('table')
|
||||
expect(info.tableDisplay).toMatchObject({
|
||||
firstRow: { fill: '4472C4', bold: true, color: 'FFFFFF' },
|
||||
band1Fill: 'D9E2F3',
|
||||
})
|
||||
|
||||
const rows = doc.blocks[0].table!.rows
|
||||
expect(rows[0][0]).toMatchObject({ fill: '4472C4', bold: true, color: 'FFFFFF' })
|
||||
// body rows: band1 / none / band1
|
||||
expect(rows[1][0].fill).toBe('D9E2F3')
|
||||
expect(rows[2][0].fill).toBeUndefined()
|
||||
expect(rows[3][0].fill).toBe('D9E2F3')
|
||||
})
|
||||
|
||||
it('honors noHBand and firstRow=0 flags', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: styledTable('<w:tblLook w:firstRow="0" w:noHBand="1"/>'),
|
||||
extraStylesXml: GRID_STYLE,
|
||||
}),
|
||||
)
|
||||
const rows = doc.blocks[0].table!.rows
|
||||
expect(rows[0][0].fill).toBeUndefined()
|
||||
expect(rows[0][0].bold).toBeUndefined()
|
||||
expect(rows[1][0].fill).toBeUndefined()
|
||||
})
|
||||
|
||||
it('explicit cell shading beats the style', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: styledTable(
|
||||
'<w:tblLook w:firstRow="1" w:noHBand="0"/>',
|
||||
'<w:shd w:val="clear" w:color="auto" w:fill="FF0000"/>',
|
||||
),
|
||||
extraStylesXml: GRID_STYLE,
|
||||
}),
|
||||
)
|
||||
expect(doc.blocks[0].table!.rows[1][0].fill).toBe('FF0000')
|
||||
expect(doc.blocks[0].table!.rows[1][1].fill).toBe('D9E2F3')
|
||||
})
|
||||
|
||||
it('resolves basedOn chains between table styles', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
extraStylesXml: GRID_STYLE,
|
||||
}),
|
||||
)
|
||||
const child = doc.styles.get('GridBlueChild')!
|
||||
expect(child.tableDisplay).toMatchObject({
|
||||
firstRow: { fill: '4472C4', bold: true },
|
||||
band1Fill: 'EEEEEE',
|
||||
})
|
||||
})
|
||||
|
||||
it('style-derived display keeps untouched tables byte-identical', async () => {
|
||||
const source = await buildDocx({
|
||||
bodyXml: styledTable('<w:tblLook w:firstRow="1" w:noHBand="0"/>'),
|
||||
extraStylesXml: GRID_STYLE,
|
||||
})
|
||||
const parsed = await parseDocx(source)
|
||||
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
|
||||
expect(saved).toEqual(source)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx, type TabStop } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
// ---- fixture XML fragments ----
|
||||
|
||||
/** paragraph with left + center tab stops and dot leader */
|
||||
const TABS_P =
|
||||
'<w:p>' +
|
||||
'<w:pPr><w:tabs>' +
|
||||
'<w:tab w:val="left" w:pos="720"/>' +
|
||||
'<w:tab w:val="center" w:pos="2160" w:leader="dot"/>' +
|
||||
'<w:tab w:val="right" w:pos="4320"/>' +
|
||||
'<w:tab w:val="decimal" w:pos="5040"/>' +
|
||||
'</w:tabs></w:pPr>' +
|
||||
'<w:r><w:t xml:space="preserve">A\tB\tC</w:t></w:r>' +
|
||||
'</w:p>'
|
||||
|
||||
/** paragraph with NO tabs (control) */
|
||||
const PLAIN_P = '<w:p><w:r><w:t>plain</w:t></w:r></w:p>'
|
||||
|
||||
describe('tab stops parsing', () => {
|
||||
it('parses w:tabs into block.format.tabStops', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TABS_P }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.format?.tabStops).toBeDefined()
|
||||
const stops = block.format!.tabStops!
|
||||
expect(stops).toHaveLength(4)
|
||||
expect(stops[0]).toMatchObject({ pos: 720, val: 'left' })
|
||||
expect(stops[1]).toMatchObject({ pos: 2160, val: 'center', leader: 'dot' })
|
||||
expect(stops[2]).toMatchObject({ pos: 4320, val: 'right' })
|
||||
expect(stops[3]).toMatchObject({ pos: 5040, val: 'decimal' })
|
||||
})
|
||||
|
||||
it('plain paragraph has no tabStops', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: PLAIN_P }))
|
||||
expect(doc.blocks[0].format?.tabStops).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('tab stops roundtrip', () => {
|
||||
it('untouched tabs paragraph saves byte-identical', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: TABS_P })
|
||||
const doc = await parseDocx(bytes)
|
||||
const saved = await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.blocks[0].format?.tabStops).toEqual(doc.blocks[0].format?.tabStops)
|
||||
expect(reparsed.internal.documentXml).toContain('<w:tabs>')
|
||||
expect(reparsed.internal.documentXml).toContain('w:val="center"')
|
||||
expect(reparsed.internal.documentXml).toContain('w:leader="dot"')
|
||||
})
|
||||
|
||||
it('writing new tabStops via format regenerates correct pPr', async () => {
|
||||
const { generateParagraphXml } = await import('../src/generate')
|
||||
const newStops: TabStop[] = [
|
||||
{ pos: 1440, val: 'right', leader: 'dot' },
|
||||
{ pos: 2880, val: 'left' },
|
||||
]
|
||||
const block = {
|
||||
type: 'paragraph' as const,
|
||||
runs: [{ text: 'test' }],
|
||||
format: { tabStops: newStops },
|
||||
}
|
||||
const xml = generateParagraphXml(block, {
|
||||
headingStyleIds: new Map(),
|
||||
allocateHyperlinkRel: () => 'rId1',
|
||||
})
|
||||
expect(xml).toContain('<w:tabs>')
|
||||
expect(xml).toContain('w:val="right"')
|
||||
expect(xml).toContain('w:pos="1440"')
|
||||
expect(xml).toContain('w:leader="dot"')
|
||||
expect(xml).toContain('w:val="left"')
|
||||
expect(xml).toContain('w:pos="2880"')
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user