-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathciteproc-js-based-replacer.js
271 lines (232 loc) · 7.4 KB
/
citeproc-js-based-replacer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
const fs = require("fs");
const path = require("path");
const citeproc = require("citeproc-js-node");
const debugMode = false;
/**
* Outputs debug log messages when debugMode is true.
* debugModeがtrueの場合、デバッグログメッセージを出力します。
*
* @function debugLog
* @param {...any} args - Arguments to pass to console.log
*/
function debugLog(...args) {
if (debugMode) {
console.log(...args);
}
}
/**
* Collects citation keys and citation objects from the input object.
* 入力オブジェクトから引用キーと引用オブジェクトを収集します。
*
* @function collectCitations
* @param {any} obj - The input object to scan for citations
* @returns {any} The input object with citations collected
*/
function collectCitations(obj) {
if (Array.isArray(obj)) {
return obj.map(collectCitations);
} else if (typeof obj === "object" && obj !== null) {
if (obj.t === "Cite") {
for (const item of obj.c[0]) {
const citationId = item.citationId;
const noteIndex = citationKeys.length;
citationKeys.push(citationId);
const citationSuffix = item.citationSuffix;
let locator = "";
if (citationSuffix.length > 0) {
const suffixes = citationSuffix
.filter((suffix) => suffix.t === "Str")
.map((suffix) => suffix.c.replace(/^\[\s*|\s*\]$/g, ""));
locator = suffixes.join("|");
}
const citationItem = { id: citationId };
if (locator) {
citationItem.locator = locator;
}
citationObjects.push({
citationID: `${citationId}_${noteIndex}`,
citationItems: [citationItem],
properties: { noteIndex: noteIndex },
});
}
return;
} else {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
key,
collectCitations(value),
])
);
}
} else {
return;
}
}
/**
* Replaces citations in the input object with their formatted text.
* 入力オブジェクト内の引用を、整形されたテキストに置き換えます。
*
* @function replaceCitations
* @param {any} obj - The input object containing citations to replace
* @returns {any} The input object with citations replaced
*/
function replaceCitations(obj) {
if (Array.isArray(obj)) {
return obj.map(replaceCitations);
} else if (typeof obj === "object" && obj !== null) {
if (obj.t === "Cite") {
const formattedItems = obj.c[0].map(() => {
const formattedCitation = formattedCitations
.shift()
.trim()
.replace(/<i>/g, "*")
.replace(/<\/i>/g, "*")
.replace(/<div class="csl-entry">/g, "")
.replace(/<\/div>/g, "")
.replace(/–/g, "--")
.replace(/—/g, "---")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/”/g, "”\\");
return formattedCitation;
});
const concatenatedFormattedItems = formattedItems.join("; ");
return {
t: "RawInline",
c: ["markdown", concatenatedFormattedItems],
};
} else {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
key,
replaceCitations(value),
])
);
}
} else {
return obj;
}
}
/**
* Converts the bibliography result from citeproc-js to a Pandoc-formatted object.
* citeproc-jsからの参考文献結果をPandoc形式のオブジェクトに変換します。
*
* @function convertBibResultToPandoc
* @param {Array} bibResult - The bibliography result from citeproc-js
* @returns {Array} A Pandoc-formatted object representing the bibliography
*/
function convertBibResultToPandoc(bibResult) {
return bibResult[1].map((bibEntry) => {
const markdownBibEntry = bibEntry
.trim()
.replace(/<i>/g, "*")
.replace(/<\/i>/g, "*")
.replace(/<div class="csl-entry">/g, "")
.replace(/<\/div>/g, "")
.replace(/–/g, "--")
.replace(/—/g, "---")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/”/g, "”\\");
return {
t: "Para",
c: [
{
t: "RawInline",
c: ["markdown", markdownBibEntry],
},
],
};
});
}
process.stdin.setEncoding("utf8");
let inputData = "";
process.stdin.on("data", (chunk) => {
inputData += chunk;
});
const citationKeys = [];
const citationObjects = [];
let citeprocEngine = undefined;
let formattedCitations = undefined;
process.stdin.on("end", () => {
let dataObj = JSON.parse(inputData);
const languageCodes = ["en-US", "ja-JP"];
let locales = {};
languageCodes.forEach((languageCode) => {
const localeFilePath = path.join(__dirname, `locales-${languageCode}.xml`);
try {
const data = fs.readFileSync(localeFilePath, "utf8");
locales[languageCode] = data;
} catch (err) {
console.error(`Error reading locale file: ${localeFilePath}`, err);
}
});
const cslFile = dataObj.meta.csl.c[0].c;
debugLog(`cslFile: ${cslFile}`);
const style = fs.readFileSync(cslFile, "utf-8");
const bibliographyFile = dataObj.meta.bibliography.c[0].c;
debugLog(`bibliographyFile: ${bibliographyFile}`);
const bibliography = JSON.parse(fs.readFileSync(bibliographyFile));
const sys = {
retrieveItem: function (itemID) {
const foundItem = bibliography.find((entry) => entry.id === itemID);
if (!foundItem) {
throw new Error(
`Item with ID "${itemID}" not found in the bibliography.`
);
}
return foundItem;
},
retrieveLocale: function (lang) {
return locales[lang];
},
};
citeprocEngine = new citeproc.CSL.Engine(sys, style);
citeprocEngine.setOutputFormat("html");
const citableItemIds = bibliography.map((item) => item.id);
debugLog(`citableItemIds: ${JSON.stringify(citableItemIds)}`);
citeprocEngine.updateItems(citableItemIds);
const uncitedItemIds = dataObj.meta.nocite
? dataObj.meta.nocite.c.map((para) => para.c[0].c[0][0].citationId)
: [];
debugLog(`uncitedItemIds: ${JSON.stringify(uncitedItemIds)}`);
if (uncitedItemIds.length > 0) {
citeprocEngine.updateUncitedItems(uncitedItemIds);
}
collectCitations(dataObj.blocks);
formattedCitations = citationObjects.map((citation, index) => {
const predecessor = citationObjects
.slice(0, index)
.map((prevCitation) => [
prevCitation.citationID,
prevCitation.properties.noteIndex,
]);
const successor = [];
const result = citeprocEngine.processCitationCluster(
citation,
predecessor,
successor
);
if (result[0].bibchange === false) {
return result[1][1] && result[1][1][1]
? result[1][1][1]
: result[1][0][1];
}
return result[1][0][1];
});
dataObj.blocks = replaceCitations(dataObj.blocks);
const bibliographyHeaderIndex = dataObj.blocks.findIndex(
(block) =>
block.t === "Header" &&
(block.c[1][0] === "参考文献" || block.c[1][0] === "Bibliography")
);
if (bibliographyHeaderIndex >= 0) {
const bibResult = citeprocEngine.makeBibliography();
const pandocBibResult = convertBibResultToPandoc(bibResult);
dataObj.blocks.splice(bibliographyHeaderIndex + 1, 0, ...pandocBibResult);
}
process.stdout.write(JSON.stringify(dataObj));
});
process.stdin.resume();