@fiduswriter/books 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +87 -2
  3. package/css/book.css +219 -0
  4. package/dist/exporter/bits/index.d.ts +42 -0
  5. package/dist/exporter/bits/index.d.ts.map +1 -0
  6. package/dist/exporter/bits/index.js +113 -0
  7. package/dist/exporter/bits/index.js.map +1 -0
  8. package/dist/exporter/bits/templates.d.ts +7 -0
  9. package/dist/exporter/bits/templates.d.ts.map +1 -0
  10. package/dist/exporter/bits/templates.js +78 -0
  11. package/dist/exporter/bits/templates.js.map +1 -0
  12. package/dist/exporter/docx/index.d.ts +33 -0
  13. package/dist/exporter/docx/index.d.ts.map +1 -0
  14. package/dist/exporter/docx/index.js +139 -0
  15. package/dist/exporter/docx/index.js.map +1 -0
  16. package/dist/exporter/docx/render.d.ts +19 -0
  17. package/dist/exporter/docx/render.d.ts.map +1 -0
  18. package/dist/exporter/docx/render.js +123 -0
  19. package/dist/exporter/docx/render.js.map +1 -0
  20. package/dist/exporter/epub/index.d.ts +70 -0
  21. package/dist/exporter/epub/index.d.ts.map +1 -0
  22. package/dist/exporter/epub/index.js +310 -0
  23. package/dist/exporter/epub/index.js.map +1 -0
  24. package/dist/exporter/epub/templates.d.ts +65 -0
  25. package/dist/exporter/epub/templates.d.ts.map +1 -0
  26. package/dist/exporter/epub/templates.js +224 -0
  27. package/dist/exporter/epub/templates.js.map +1 -0
  28. package/dist/exporter/epub/tools.d.ts +5 -0
  29. package/dist/exporter/epub/tools.d.ts.map +1 -0
  30. package/dist/exporter/epub/tools.js +59 -0
  31. package/dist/exporter/epub/tools.js.map +1 -0
  32. package/dist/exporter/html/index.d.ts +70 -0
  33. package/dist/exporter/html/index.d.ts.map +1 -0
  34. package/dist/exporter/html/index.js +320 -0
  35. package/dist/exporter/html/index.js.map +1 -0
  36. package/dist/exporter/html/templates.d.ts +40 -0
  37. package/dist/exporter/html/templates.d.ts.map +1 -0
  38. package/dist/exporter/html/templates.js +225 -0
  39. package/dist/exporter/html/templates.js.map +1 -0
  40. package/dist/exporter/html/tools.d.ts +2 -0
  41. package/dist/exporter/html/tools.d.ts.map +1 -0
  42. package/dist/exporter/html/tools.js +23 -0
  43. package/dist/exporter/html/tools.js.map +1 -0
  44. package/dist/exporter/latex/index.d.ts +36 -0
  45. package/dist/exporter/latex/index.d.ts.map +1 -0
  46. package/dist/exporter/latex/index.js +116 -0
  47. package/dist/exporter/latex/index.js.map +1 -0
  48. package/dist/exporter/latex/templates.d.ts +4 -0
  49. package/dist/exporter/latex/templates.d.ts.map +1 -0
  50. package/dist/exporter/latex/templates.js +26 -0
  51. package/dist/exporter/latex/templates.js.map +1 -0
  52. package/dist/exporter/native/index.d.ts +22 -0
  53. package/dist/exporter/native/index.d.ts.map +1 -0
  54. package/dist/exporter/native/index.js +141 -0
  55. package/dist/exporter/native/index.js.map +1 -0
  56. package/dist/exporter/odt/index.d.ts +33 -0
  57. package/dist/exporter/odt/index.d.ts.map +1 -0
  58. package/dist/exporter/odt/index.js +133 -0
  59. package/dist/exporter/odt/index.js.map +1 -0
  60. package/dist/exporter/odt/render.d.ts +21 -0
  61. package/dist/exporter/odt/render.d.ts.map +1 -0
  62. package/dist/exporter/odt/render.js +126 -0
  63. package/dist/exporter/odt/render.js.map +1 -0
  64. package/dist/exporter/pretty.d.ts +17 -0
  65. package/dist/exporter/pretty.d.ts.map +1 -0
  66. package/dist/exporter/pretty.js +55 -0
  67. package/dist/exporter/pretty.js.map +1 -0
  68. package/dist/exporter/print/index.d.ts +25 -0
  69. package/dist/exporter/print/index.d.ts.map +1 -0
  70. package/dist/exporter/print/index.js +46 -0
  71. package/dist/exporter/print/index.js.map +1 -0
  72. package/dist/exporter/print/templates.d.ts +2 -0
  73. package/dist/exporter/print/templates.d.ts.map +1 -0
  74. package/dist/exporter/print/templates.js +5 -0
  75. package/dist/exporter/print/templates.js.map +1 -0
  76. package/dist/exporter/tools.d.ts +31 -0
  77. package/dist/exporter/tools.d.ts.map +1 -0
  78. package/dist/exporter/tools.js +177 -0
  79. package/dist/exporter/tools.js.map +1 -0
  80. package/dist/i18n.d.ts +7 -0
  81. package/dist/i18n.d.ts.map +1 -0
  82. package/dist/i18n.js +918 -0
  83. package/dist/i18n.js.map +1 -0
  84. package/dist/ids.d.ts +19 -0
  85. package/dist/ids.d.ts.map +1 -0
  86. package/dist/ids.js +27 -0
  87. package/dist/ids.js.map +1 -0
  88. package/dist/importer/native/index.d.ts +45 -0
  89. package/dist/importer/native/index.d.ts.map +1 -0
  90. package/dist/importer/native/index.js +166 -0
  91. package/dist/importer/native/index.js.map +1 -0
  92. package/dist/importer/native/reader.d.ts +32 -0
  93. package/dist/importer/native/reader.d.ts.map +1 -0
  94. package/dist/importer/native/reader.js +170 -0
  95. package/dist/importer/native/reader.js.map +1 -0
  96. package/dist/index.d.ts +4 -0
  97. package/dist/index.d.ts.map +1 -0
  98. package/dist/index.js +3 -0
  99. package/dist/index.js.map +1 -0
  100. package/dist/schema/index.d.ts +7 -0
  101. package/dist/schema/index.d.ts.map +1 -0
  102. package/dist/schema/index.js +8 -0
  103. package/dist/schema/index.js.map +1 -0
  104. package/dist/types.d.ts +171 -0
  105. package/dist/types.d.ts.map +1 -0
  106. package/dist/types.js +5 -0
  107. package/dist/types.js.map +1 -0
  108. package/dist/ui/book_dialog/dialog.d.ts +161 -0
  109. package/dist/ui/book_dialog/dialog.d.ts.map +1 -0
  110. package/dist/ui/book_dialog/dialog.js +750 -0
  111. package/dist/ui/book_dialog/dialog.js.map +1 -0
  112. package/dist/ui/book_dialog/export.d.ts +95 -0
  113. package/dist/ui/book_dialog/export.d.ts.map +1 -0
  114. package/dist/ui/book_dialog/export.js +217 -0
  115. package/dist/ui/book_dialog/export.js.map +1 -0
  116. package/dist/ui/book_dialog/index.d.ts +38 -0
  117. package/dist/ui/book_dialog/index.d.ts.map +1 -0
  118. package/dist/ui/book_dialog/index.js +36 -0
  119. package/dist/ui/book_dialog/index.js.map +1 -0
  120. package/dist/ui/book_dialog/sanity_check.d.ts +22 -0
  121. package/dist/ui/book_dialog/sanity_check.d.ts.map +1 -0
  122. package/dist/ui/book_dialog/sanity_check.js +109 -0
  123. package/dist/ui/book_dialog/sanity_check.js.map +1 -0
  124. package/dist/ui/book_dialog/templates.d.ts +76 -0
  125. package/dist/ui/book_dialog/templates.d.ts.map +1 -0
  126. package/dist/ui/book_dialog/templates.js +542 -0
  127. package/dist/ui/book_dialog/templates.js.map +1 -0
  128. package/dist/ui/book_dialog/types.d.ts +258 -0
  129. package/dist/ui/book_dialog/types.d.ts.map +1 -0
  130. package/dist/ui/book_dialog/types.js +15 -0
  131. package/dist/ui/book_dialog/types.js.map +1 -0
  132. package/locale/ar/messages.json +49 -0
  133. package/locale/bg/messages.json +49 -0
  134. package/locale/cs/messages.json +49 -0
  135. package/locale/da/messages.json +49 -0
  136. package/locale/de/messages.json +49 -0
  137. package/locale/en/messages.json +49 -0
  138. package/locale/en_US/messages.json +49 -0
  139. package/locale/es/messages.json +49 -0
  140. package/locale/fr/messages.json +49 -0
  141. package/locale/it/messages.json +49 -0
  142. package/locale/ja/messages.json +49 -0
  143. package/locale/ko/messages.json +49 -0
  144. package/locale/nb/messages.json +49 -0
  145. package/locale/nl/messages.json +49 -0
  146. package/locale/pl/messages.json +49 -0
  147. package/locale/pt_BR/messages.json +49 -0
  148. package/locale/pt_PT/messages.json +49 -0
  149. package/locale/ru/messages.json +49 -0
  150. package/locale/sv/messages.json +49 -0
  151. package/locale/tr/messages.json +49 -0
  152. package/locale/zh_Hans/messages.json +49 -0
  153. package/logo.svg +10 -0
  154. package/package.json +150 -5
  155. package/src/exporter/bits/index.ts +184 -0
  156. package/src/exporter/bits/templates.ts +107 -0
  157. package/src/exporter/docx/index.ts +258 -0
  158. package/src/exporter/docx/render.ts +177 -0
  159. package/src/exporter/epub/index.ts +496 -0
  160. package/src/exporter/epub/templates.ts +403 -0
  161. package/src/exporter/epub/tools.ts +68 -0
  162. package/src/exporter/html/index.ts +479 -0
  163. package/src/exporter/html/templates.ts +362 -0
  164. package/src/exporter/html/tools.ts +26 -0
  165. package/src/exporter/latex/index.ts +190 -0
  166. package/src/exporter/latex/templates.ts +35 -0
  167. package/src/exporter/native/index.ts +238 -0
  168. package/src/exporter/odt/index.ts +230 -0
  169. package/src/exporter/odt/render.ts +181 -0
  170. package/src/exporter/pretty.ts +75 -0
  171. package/src/exporter/print/index.ts +76 -0
  172. package/src/exporter/print/templates.ts +8 -0
  173. package/src/exporter/tools.ts +270 -0
  174. package/src/global.d.ts +2 -0
  175. package/src/i18n.ts +936 -0
  176. package/src/ids.ts +27 -0
  177. package/src/importer/native/index.ts +269 -0
  178. package/src/importer/native/reader.ts +247 -0
  179. package/src/index.ts +20 -0
  180. package/src/modules.d.ts +7 -0
  181. package/src/schema/index.ts +8 -0
  182. package/src/types.ts +208 -0
  183. package/src/ui/book_dialog/dialog.ts +940 -0
  184. package/src/ui/book_dialog/export.ts +449 -0
  185. package/src/ui/book_dialog/index.ts +84 -0
  186. package/src/ui/book_dialog/sanity_check.ts +208 -0
  187. package/src/ui/book_dialog/templates.ts +736 -0
  188. package/src/ui/book_dialog/types.ts +283 -0
package/src/ids.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Stable document ids for file-based hosts.
3
+ *
4
+ * The server assigns every chapter document a numeric id in its database.
5
+ * File-based hosts (the desktop app, WebDAV) have no such database: a chapter
6
+ * there is a standalone `.fidus` file, so its id is derived from the file's
7
+ * location instead. The derivation is deterministic, so the id a chapter gets
8
+ * when it is added is the same id every later load computes from the path
9
+ * stored in `book.json`.
10
+ */
11
+
12
+ /**
13
+ * Derive the document id of an external chapter file from its path.
14
+ *
15
+ * FNV-1a over the path with separators normalized to `/`, folded to an
16
+ * unsigned 32-bit integer. Windows and POSIX spellings of the same location
17
+ * therefore produce the same id.
18
+ */
19
+ export function chapterIdFromPath(path: string): number {
20
+ const normalized = path.replace(/\\/g, "/")
21
+ let hash = 0x811c9dc5
22
+ for (let i = 0; i < normalized.length; i++) {
23
+ hash ^= normalized.charCodeAt(i)
24
+ hash = Math.imul(hash, 0x01000193)
25
+ }
26
+ return hash >>> 0
27
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Native `.fidusbook` importer.
3
+ *
4
+ * Uses `NativeImporter` from `@fiduswriter/document/importer/native` for each
5
+ * chapter and delegates creation of the book record to a `BookImporterBackend`.
6
+ */
7
+
8
+ import type {E2EEOptions, NativeImporterBackend} from "@fiduswriter/document"
9
+ import {NativeImporter} from "@fiduswriter/document/importer/native"
10
+ import {addAlert} from "fwtoolkit"
11
+
12
+ import type {BookImporterBackend, Chapter, User} from "../../types.js"
13
+
14
+ export {FIDUSBOOK_VERSION} from "./reader.js"
15
+ export {readFidusBookFile, FidusBookReader} from "./reader.js"
16
+ import {
17
+ FIDUSBOOK_MIMETYPES,
18
+ MIN_FIDUSBOOK_VERSION,
19
+ MAX_FIDUSBOOK_VERSION
20
+ } from "./reader.js"
21
+
22
+ export interface E2EEOptionsResult {
23
+ options: E2EEOptions
24
+ password: string
25
+ }
26
+
27
+ export interface NativeBookImporterOptions {
28
+ path?: string
29
+ getE2EEOptions?: () => Promise<E2EEOptionsResult | null>
30
+ onChapterImported?: (
31
+ doc: Record<string, unknown>,
32
+ password: string
33
+ ) => Promise<void>
34
+ }
35
+
36
+ export class NativeBookImporter {
37
+ file: Blob
38
+ user: User
39
+ path: string
40
+ nativeBackend: NativeImporterBackend
41
+ bookBackend: BookImporterBackend
42
+ getE2EEOptions?: () => Promise<E2EEOptionsResult | null>
43
+ onChapterImported?: (
44
+ doc: Record<string, unknown>,
45
+ password: string
46
+ ) => Promise<void>
47
+
48
+ ok: boolean
49
+ statusText: string
50
+ bookId: number | null
51
+
52
+ constructor(
53
+ file: Blob,
54
+ user: User,
55
+ nativeBackend: NativeImporterBackend,
56
+ bookBackend: BookImporterBackend,
57
+ options: string | NativeBookImporterOptions = "/"
58
+ ) {
59
+ const opts = typeof options === "string" ? {path: options} : options
60
+ this.file = file
61
+ this.user = user
62
+ this.path = opts.path?.endsWith("/") ? opts.path : `${opts.path || "/"}/`
63
+ this.nativeBackend = nativeBackend
64
+ this.bookBackend = bookBackend
65
+ this.getE2EEOptions = opts.getE2EEOptions
66
+ this.onChapterImported = opts.onChapterImported
67
+
68
+ this.ok = false
69
+ this.statusText = ""
70
+ this.bookId = null
71
+ }
72
+
73
+ /**
74
+ * Entry point. Validates the file is a ZIP, then delegates to the reader.
75
+ */
76
+ init(): Promise<NativeBookImporter> {
77
+ return new Promise(resolve => {
78
+ const reader = new FileReader()
79
+ reader.onloadend = () => {
80
+ if (
81
+ reader.result &&
82
+ (reader.result as string).length > 60 &&
83
+ (reader.result as string).substring(0, 2) === "PK"
84
+ ) {
85
+ this.readZip().then(() => resolve(this))
86
+ } else {
87
+ this.statusText = gettext(
88
+ "The uploaded file does not appear to be a Fidusbook file."
89
+ )
90
+ resolve(this)
91
+ }
92
+ }
93
+ reader.readAsText(this.file.slice(0, 64))
94
+ })
95
+ }
96
+
97
+ async readZip(): Promise<void> {
98
+ let textFiles: Array<{filename: string; content: string}> = []
99
+ let binaryFiles: Array<{filename: string; content: Blob}> = []
100
+
101
+ try {
102
+ const JSZip = (await import("jszip")).default
103
+ const zipfs = await JSZip.loadAsync(this.file)
104
+
105
+ const filenames: string[] = []
106
+ zipfs.forEach(filename => filenames.push(filename))
107
+
108
+ await Promise.all(
109
+ filenames
110
+ .filter(f => !f.endsWith("/"))
111
+ .map(async filename => {
112
+ const isText =
113
+ filename.endsWith(".json") ||
114
+ filename === "filetype-version" ||
115
+ filename === "mimetype"
116
+ const content = await zipfs.files[filename].async(
117
+ isText ? "string" : "blob"
118
+ )
119
+ if (isText) {
120
+ textFiles.push({
121
+ filename,
122
+ content: content as string
123
+ })
124
+ } else {
125
+ binaryFiles.push({
126
+ filename,
127
+ content: content as Blob
128
+ })
129
+ }
130
+ })
131
+ )
132
+ } catch (_error) {
133
+ this.statusText = gettext(
134
+ "The uploaded file does not appear to be a Fidusbook file."
135
+ )
136
+ return
137
+ }
138
+
139
+ return this.processFidusbookFile(textFiles, binaryFiles)
140
+ }
141
+
142
+ async processFidusbookFile(
143
+ textFiles: Array<{filename: string; content: string}>,
144
+ binaryFiles: Array<{filename: string; content: Blob}>
145
+ ): Promise<void> {
146
+ const versionEntry = textFiles.find(
147
+ f => f.filename === "filetype-version"
148
+ )
149
+ const filetypeVersion = Number.parseFloat(versionEntry?.content || "")
150
+
151
+ if (
152
+ filetypeVersion < MIN_FIDUSBOOK_VERSION ||
153
+ filetypeVersion > MAX_FIDUSBOOK_VERSION
154
+ ) {
155
+ this.statusText =
156
+ gettext(
157
+ "The Fidusbook file version is not supported by this server: "
158
+ ) + (versionEntry?.content || "")
159
+ return
160
+ }
161
+
162
+ const mimetypeEntry = textFiles.find(f => f.filename === "mimetype")
163
+ if (
164
+ mimetypeEntry &&
165
+ !FIDUSBOOK_MIMETYPES.includes(mimetypeEntry.content)
166
+ ) {
167
+ this.statusText = gettext(
168
+ "The uploaded file does not appear to be a Fidusbook file."
169
+ )
170
+ return
171
+ }
172
+
173
+ const bookData = JSON.parse(
174
+ textFiles.find(f => f.filename === "book.json")?.content || "{}"
175
+ ) as Record<string, unknown>
176
+
177
+ const sortedChapters = [...(bookData.chapters as Array<{chapter_index: number; number: number; part?: string}>)].sort(
178
+ (a, b) => a.chapter_index - b.chapter_index
179
+ )
180
+
181
+ const importedDocIds: Record<number, number> = {}
182
+
183
+ for (const chapter of sortedChapters) {
184
+ const ci = chapter.chapter_index
185
+
186
+ const docFile = textFiles.find(
187
+ f => f.filename === `chapters/${ci}/document.json`
188
+ )
189
+ const imagesFile = textFiles.find(
190
+ f => f.filename === `chapters/${ci}/images.json`
191
+ )
192
+ const bibFile = textFiles.find(
193
+ f => f.filename === `chapters/${ci}/bibliography.json`
194
+ )
195
+
196
+ if (!docFile || !imagesFile || !bibFile) {
197
+ addAlert(
198
+ "error",
199
+ gettext("Fidusbook file is missing data for chapter ") +
200
+ (sortedChapters.indexOf(chapter) + 1)
201
+ )
202
+ throw new Error(`Missing chapter data for index ${ci}`)
203
+ }
204
+
205
+ const docJson = JSON.parse(docFile.content) as Record<string, unknown>
206
+ const imagesJson = JSON.parse(imagesFile.content) as Record<string, unknown>
207
+ const bibJson = JSON.parse(bibFile.content) as Record<string, unknown>
208
+
209
+ const chapterPrefix = `chapters/${ci}/images/`
210
+ const chapterOtherFiles = binaryFiles
211
+ .filter(f => f.filename.startsWith(chapterPrefix))
212
+ .map(f => ({
213
+ filename: `images/${f.filename.slice(chapterPrefix.length)}`,
214
+ content: f.content
215
+ }))
216
+
217
+ const safeBookTitle = (bookData.title as string) || "Untitled"
218
+ const chapterPath = `${this.path}${safeBookTitle}/${(docJson.title as string) || "Untitled"}`
219
+
220
+ let e2eeResult: E2EEOptionsResult | null = null
221
+ if (this.getE2EEOptions) {
222
+ e2eeResult = await this.getE2EEOptions()
223
+ }
224
+
225
+ const importer = new NativeImporter(
226
+ docJson,
227
+ bibJson,
228
+ {db: imagesJson as unknown as import("@fiduswriter/document").ImageDB["db"]},
229
+ chapterOtherFiles,
230
+ this.user,
231
+ this.nativeBackend,
232
+ {
233
+ requestedPath: chapterPath,
234
+ e2eeOptions: e2eeResult?.options ?? null
235
+ }
236
+ )
237
+
238
+ let doc
239
+ try {
240
+ ;({doc} = await importer.init())
241
+ } catch (error) {
242
+ addAlert(
243
+ "error",
244
+ gettext("Could not import chapter ") +
245
+ ((docJson.title as string) ||
246
+ sortedChapters.indexOf(chapter) + 1)
247
+ )
248
+ throw error
249
+ }
250
+
251
+ importedDocIds[ci] = doc.id as number
252
+
253
+ if (e2eeResult && this.onChapterImported) {
254
+ await this.onChapterImported(doc, e2eeResult.password)
255
+ }
256
+ }
257
+
258
+ const chapters: Chapter[] = sortedChapters.map(chapter => ({
259
+ text: importedDocIds[chapter.chapter_index],
260
+ number: chapter.number,
261
+ part: chapter.part || ""
262
+ }))
263
+
264
+ const book = await this.bookBackend.createBook(bookData, chapters, false)
265
+ this.bookId = book.id || null
266
+ this.ok = true
267
+ this.statusText = `"${bookData.title}" ${gettext("successfully imported.")}`
268
+ }
269
+ }
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Pure reader for `.fidusbook` archives.
3
+ *
4
+ * Reads the ZIP file, validates the mimetype/version, and returns the raw
5
+ * book metadata plus a `documentList` shaped like the one used by the
6
+ * exporters. No server interaction.
7
+ */
8
+
9
+ import type {BibDBEntry, FidusDoc, ImageDBEntries} from "@fiduswriter/document"
10
+ import type {DocumentListEntry} from "../../types.js"
11
+ import {FW_DOCUMENT_VERSION} from "@fiduswriter/document/schema"
12
+ import {
13
+ MAX_FW_DOCUMENT_VERSION,
14
+ updateFile
15
+ } from "@fiduswriter/document/importer/native"
16
+
17
+ export const FIDUSBOOK_MIMETYPES = [
18
+ "application/fidusbook+zip",
19
+ "application/vnd.fiduswriter.book+zip"
20
+ ]
21
+ /**
22
+ * The Fidus Writer book archive version tracks the document version; there is
23
+ * no independent book version. Legacy book archives (before the unification)
24
+ * used version 1.0, which is still accepted for reading.
25
+ */
26
+ export const FIDUSBOOK_VERSION = FW_DOCUMENT_VERSION
27
+ export const MIN_FIDUSBOOK_VERSION = 1.0
28
+ export const MAX_FIDUSBOOK_VERSION = MAX_FW_DOCUMENT_VERSION
29
+
30
+ interface ArchiveFile {
31
+ filename: string
32
+ content: string | Blob
33
+ }
34
+
35
+ export interface FidusBookReaderResult {
36
+ book: Record<string, unknown>
37
+ documentList: DocumentListEntry[]
38
+ }
39
+
40
+ /**
41
+ * Read a `.fidusbook` archive and return its contents.
42
+ *
43
+ * @param file - A File/Blob/ArrayBuffer containing the archive.
44
+ * @returns The parsed book and document list.
45
+ */
46
+ export async function readFidusBookFile(
47
+ file: Blob | ArrayBuffer
48
+ ): Promise<FidusBookReaderResult> {
49
+ const JSZip = (await import("jszip")).default
50
+ const zipfs = await JSZip.loadAsync(file)
51
+
52
+ const filenames: string[] = []
53
+ zipfs.forEach(filename => filenames.push(filename))
54
+
55
+ if (
56
+ !filenames.includes("book.json") ||
57
+ !filenames.includes("filetype-version")
58
+ ) {
59
+ throw new Error("The file does not appear to be a Fidusbook file.")
60
+ }
61
+
62
+ const textFiles: ArchiveFile[] = []
63
+ const binaryFiles: ArchiveFile[] = []
64
+
65
+ await Promise.all(
66
+ filenames
67
+ .filter(f => !f.endsWith("/"))
68
+ .map(async filename => {
69
+ const isText =
70
+ filename.endsWith(".json") ||
71
+ filename === "filetype-version" ||
72
+ filename === "mimetype"
73
+ const content = await zipfs.files[filename].async(
74
+ isText ? "string" : "blob"
75
+ )
76
+ const entry = {filename, content}
77
+ if (isText) {
78
+ textFiles.push(entry as ArchiveFile)
79
+ } else {
80
+ binaryFiles.push(entry as ArchiveFile)
81
+ }
82
+ })
83
+ )
84
+
85
+ const versionEntry = textFiles.find(f => f.filename === "filetype-version")
86
+ const filetypeVersion = Number.parseFloat(versionEntry?.content as string)
87
+
88
+ if (
89
+ filetypeVersion < MIN_FIDUSBOOK_VERSION ||
90
+ filetypeVersion > MAX_FIDUSBOOK_VERSION
91
+ ) {
92
+ throw new Error(
93
+ `The Fidusbook file version is not supported by this reader: ${String(
94
+ versionEntry?.content
95
+ )}`
96
+ )
97
+ }
98
+
99
+ const mimetypeEntry = textFiles.find(f => f.filename === "mimetype")
100
+ if (
101
+ mimetypeEntry &&
102
+ !FIDUSBOOK_MIMETYPES.includes(mimetypeEntry.content as string)
103
+ ) {
104
+ throw new Error("The file does not appear to be a Fidusbook file.")
105
+ }
106
+
107
+ const bookData = JSON.parse(
108
+ textFiles.find(f => f.filename === "book.json")?.content as string
109
+ ) as Record<string, unknown>
110
+
111
+ const sortedChapters = [
112
+ ...(bookData.chapters as Array<{
113
+ chapter_index: number
114
+ text?: number
115
+ path?: string
116
+ }>)
117
+ ].sort((a, b) => a.chapter_index - b.chapter_index)
118
+
119
+ const documentList: DocumentListEntry[] = []
120
+
121
+ for (const chapter of sortedChapters) {
122
+ const ci = chapter.chapter_index
123
+
124
+ const docFile = textFiles.find(
125
+ f => f.filename === `chapters/${ci}/document.json`
126
+ )
127
+ const imagesFile = textFiles.find(
128
+ f => f.filename === `chapters/${ci}/images.json`
129
+ )
130
+ const bibFile = textFiles.find(
131
+ f => f.filename === `chapters/${ci}/bibliography.json`
132
+ )
133
+
134
+ if (!docFile || !imagesFile || !bibFile) {
135
+ if (chapter.path) {
136
+ // The chapter is a reference to a standalone `.fidus` file and
137
+ // carries no snapshot in this container. The host resolves the
138
+ // live file; the entry is a placeholder until then.
139
+ documentList.push({
140
+ id: chapter.text ?? 0,
141
+ title: "",
142
+ path: chapter.path,
143
+ external: true,
144
+ missing: true,
145
+ content: {type: "doc", content: []},
146
+ settings: {},
147
+ comments: {},
148
+ images: {},
149
+ bibliography: {}
150
+ } as DocumentListEntry)
151
+ continue
152
+ }
153
+ throw new Error(`Missing chapter data for index ${ci}`)
154
+ }
155
+
156
+ const docJson = JSON.parse(docFile.content as string) as Record<string, unknown>
157
+ const imagesJson = JSON.parse(imagesFile.content as string) as Record<string, {image: string; file?: Blob}>
158
+ const bibJson = JSON.parse(bibFile.content as string) as Record<string, unknown>
159
+
160
+ // Chapter snapshots written by older Fidus Writer versions carry
161
+ // content in the schema of that version (e.g. an "article" top node,
162
+ // a "contents" key, renamed citation styles). Migrate the snapshot
163
+ // through the same updateFile chain the standalone .fidus importer
164
+ // uses so exporters always see the current schema. Best-effort: a
165
+ // snapshot that does not migrate is passed through unchanged.
166
+ let migratedDoc = docJson
167
+ if (filetypeVersion < MAX_FIDUSBOOK_VERSION) {
168
+ try {
169
+ const nodeLike =
170
+ typeof docJson?.type === "string" &&
171
+ Array.isArray(
172
+ (docJson as {content?: unknown}).content
173
+ )
174
+ let candidate: Record<string, unknown> | null = docJson
175
+ if (!nodeLike && docJson.content == null) {
176
+ const contents = (docJson as {contents?: unknown})
177
+ .contents
178
+ candidate =
179
+ contents != null
180
+ ? {...docJson, content: contents}
181
+ : null
182
+ }
183
+ if (candidate) {
184
+ const updated = updateFile(
185
+ candidate as unknown as FidusDoc,
186
+ filetypeVersion,
187
+ bibJson as Record<string, BibDBEntry>,
188
+ imagesJson as unknown as ImageDBEntries
189
+ )
190
+ const updatedDoc = updated.doc as unknown as Record<
191
+ string,
192
+ unknown
193
+ >
194
+ migratedDoc = nodeLike
195
+ ? {content: updatedDoc}
196
+ : updatedDoc
197
+ }
198
+ } catch {
199
+ migratedDoc = docJson
200
+ }
201
+ }
202
+
203
+ const chapterPrefix = `chapters/${ci}/images/`
204
+ const chapterImages: Record<string, Blob> = {}
205
+ binaryFiles
206
+ .filter(f => f.filename.startsWith(chapterPrefix))
207
+ .forEach(f => {
208
+ chapterImages[
209
+ `images/${f.filename.slice(chapterPrefix.length)}`
210
+ ] = f.content as Blob
211
+ })
212
+
213
+ Object.entries(imagesJson).forEach(([, image]) => {
214
+ if (chapterImages[image.image]) {
215
+ image.file = chapterImages[image.image]
216
+ }
217
+ })
218
+
219
+ documentList.push({
220
+ id: (migratedDoc.id as number) || 0,
221
+ title: (migratedDoc.title as string) || "",
222
+ path: (migratedDoc.path as string) || "",
223
+ content: (migratedDoc.content || {
224
+ type: "doc",
225
+ content: []
226
+ }) as DocumentListEntry["content"],
227
+ settings: (migratedDoc.settings || {}) as DocumentListEntry["settings"],
228
+ comments: ((migratedDoc.comments ||
229
+ migratedDoc.comment ||
230
+ {}) as DocumentListEntry["comments"]),
231
+ images: imagesJson as DocumentListEntry["images"],
232
+ bibliography: bibJson as DocumentListEntry["bibliography"],
233
+ rawContent: migratedDoc.rawContent as DocumentListEntry["rawContent"],
234
+ e2ee: migratedDoc.e2ee as boolean | undefined,
235
+ e2ee_salt: migratedDoc.e2ee_salt as string | undefined,
236
+ e2ee_iterations: migratedDoc.e2ee_iterations as number | undefined
237
+ } as DocumentListEntry)
238
+ }
239
+
240
+ return {book: bookData, documentList}
241
+ }
242
+
243
+ export class FidusBookReader {
244
+ async read(file: Blob | ArrayBuffer): Promise<FidusBookReaderResult> {
245
+ return readFidusBookFile(file)
246
+ }
247
+ }
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ export {FIDUSBOOK_VERSION} from "./schema/index.js"
2
+ export {chapterIdFromPath} from "./ids.js"
3
+ export type {
4
+ Book,
5
+ BookBaseMetadata,
6
+ BookCoverImage,
7
+ BookExporterOptions,
8
+ BookImporterBackend,
9
+ BookMetadata,
10
+ BookSettings,
11
+ BookStyle,
12
+ BookStyles,
13
+ BookTexTemplateParams,
14
+ BitsTemplateParams,
15
+ Chapter,
16
+ DocumentListEntry,
17
+ E2EEStrategy,
18
+ ChapterLoader,
19
+ FidusBookArchive
20
+ } from "./types.js"
@@ -0,0 +1,7 @@
1
+ declare module "js-beautify" {
2
+ function jsBeautify(source: string, options?: Record<string, unknown>): string
3
+ namespace jsBeautify {
4
+ function html(source: string, options?: Record<string, unknown>): string
5
+ }
6
+ export default jsBeautify
7
+ }
@@ -0,0 +1,8 @@
1
+ export * from "@fiduswriter/document/schema"
2
+ import {FW_DOCUMENT_VERSION} from "@fiduswriter/document/schema"
3
+
4
+ /** The Fidus Writer book archive version tracks the document version.
5
+ * Book archives use the same version number as documents; there is no
6
+ * independent book version.
7
+ */
8
+ export const FIDUSBOOK_VERSION = FW_DOCUMENT_VERSION