Debian Codegraph @

node/opencc.js

raw symbols SCIP
1 /**
2 * @file
3 * Node.js API.
4 *
5 * @license
6 * Open Chinese Convert
7 *
8 * Copyright 2010-2026 Carbo Kuo and contributors
9 *
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 * http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 */
22
23 /**
24 * @defgroup node_api Node.js API
25 *
26 * Node.js language binding
27 */
28
29 const path = require('path');
30 const fs = require('fs');
31 const packageRoot = path.join(__dirname, '..');
32
33 function requireOptionalPackage(packageName) {
34 try {
35 return require(packageName);
36 } catch (error) {
37 if (error && error.code === 'MODULE_NOT_FOUND') {
38 return null;
39 }
40 throw error;
41 }
42 }
43
44 function resolveBindingPath() {
45 // The addon is always named opencc.node and ships either as a local build
46 // (build/Release, also used by the node-gyp source build and the Bazel
47 // sandbox), as a prebuild under prebuilds/<platform>-<arch>/, or via an
48 // @opencc/opencc-<platform>-<arch> scoped package. A direct filesystem lookup
49 // replaces node-gyp-build (OpenCC ships a single N-API build per platform).
50 const candidates = [
51 path.join(packageRoot, 'build', 'Release', 'opencc.node'),
52 path.join(
53 packageRoot, 'prebuilds', `${process.platform}-${process.arch}`, 'opencc.node'
54 ),
55 ];
56 for (const candidate of candidates) {
57 if (fs.existsSync(candidate)) {
58 return candidate;
59 }
60 }
61 const scopedBinaryPackage = requireOptionalPackage(
62 `@opencc/opencc-${process.platform}-${process.arch}`
63 );
64 if (scopedBinaryPackage && scopedBinaryPackage.binaryPath) {
65 return scopedBinaryPackage.binaryPath;
66 }
67 throw new Error(
68 'Could not locate the opencc native addon (looked in build/Release, ' +
69 'prebuilds/, and @opencc/opencc-* scoped packages)'
70 );
71 }
72
73 const bindingPath = resolveBindingPath();
74 const binding = require(bindingPath);
75
76 const getAssetsPath = function (bindingPath) {
77 const packageAssetsPath = path.join(packageRoot, 'prebuilds', 'assets');
78 if (fs.existsSync(packageAssetsPath)) {
79 return packageAssetsPath;
80 }
81
82 const bindingDir = path.dirname(bindingPath);
83 const prebuildsDir = path.dirname(bindingDir);
84 if (path.basename(prebuildsDir) === 'prebuilds') {
85 const sharedAssetsPath = path.join(prebuildsDir, 'assets');
86 if (fs.existsSync(sharedAssetsPath)) {
87 return sharedAssetsPath;
88 }
89 }
90 return bindingDir;
91 };
92
93 function requireOptionalPeer(packageName) {
94 const searchPaths = [
95 process.cwd(),
96 path.join(__dirname, '..'),
97 __dirname,
98 ];
99 for (const searchPath of searchPaths) {
100 try {
101 return require(require.resolve(packageName, { paths: [searchPath] }));
102 } catch (e) {
103 // Try the next search path.
104 }
105 }
106 return null;
107 }
108
109 // Detect optional opencc-jieba plugin package.
110 // When installed, jieba-based configs (e.g. s2twp_jieba.json) become available.
111 const jiebaInfo = requireOptionalPeer('opencc-jieba');
112
113 const assetsPath = getAssetsPath(bindingPath);
114 const isAbsolutePath = function (filePath) {
115 return path.isAbsolute(filePath) || /^[A-Za-z]:[\\/]/.test(filePath);
116 };
117
118 const getConfigPath = function (config) {
119 let configPath = config;
120 if (!isAbsolutePath(config)) {
121 // Resolve relative path
122 configPath = path.join(assetsPath, config);
123 }
124 return configPath;
125 };
126
127 /**
128 * Recursively resolve all dict "file" paths in a config object to absolute
129 * paths under the given base directory.
130 * @param {Object} dict - A dict node from the config JSON.
131 * @param {string} baseDir - Directory to resolve relative paths against.
132 */
133 function patchDictPaths(dict, baseDir) {
134 if (!dict) return;
135 if (dict.type === 'group' && Array.isArray(dict.dicts)) {
136 for (const d of dict.dicts) {
137 patchDictPaths(d, baseDir);
138 }
139 } else if (dict.file && !path.isAbsolute(dict.file)) {
140 dict.file = path.join(baseDir, dict.file);
141 }
142 }
143
144 function filterTofuRiskDicts(dict, includeTofuRiskDictionaries) {
145 if (!dict) return null;
146 if (dict.type === 'inline') {
147 return dict;
148 }
149 if (dict.may_output_tofu && !includeTofuRiskDictionaries) {
150 return null;
151 }
152 if (dict.type === 'group' && Array.isArray(dict.dicts)) {
153 dict.dicts = dict.dicts
154 .map((d) => filterTofuRiskDicts(d, includeTofuRiskDictionaries))
155 .filter(Boolean);
156 if (dict.dicts.length === 0) {
157 return null;
158 }
159 }
160 return dict;
161 }
162
163 function filterTofuRiskConversionChain(config, includeTofuRiskDictionaries) {
164 if (!Array.isArray(config.conversion_chain)) return;
165 config.conversion_chain = config.conversion_chain
166 .map((step) => {
167 if (!step || !step.dict) return step;
168 step.dict = filterTofuRiskDicts(step.dict, includeTofuRiskDictionaries);
169 return step.dict ? step : null;
170 })
171 .filter(Boolean);
172 }
173
174 function isConfigObject(config) {
175 return config && typeof config === 'object' && !Array.isArray(config);
176 }
177
178 function cloneConfigObject(config) {
179 return JSON.parse(JSON.stringify(config));
180 }
181
182 function createFromConfigObject(config, options) {
183 if (!isConfigObject(config)) {
184 throw new TypeError('OpenCC config must be an object');
185 }
186 if (options.resourceZip) {
187 throw new TypeError('resourceZip is only supported with config file names');
188 }
189
190 const raw = cloneConfigObject(config);
191 const includeTofuRiskDictionaries =
192 options.includeTofuRiskDictionaries !== false;
193 filterTofuRiskConversionChain(raw, includeTofuRiskDictionaries);
194
195 const configDirectory = options.configDirectory || assetsPath;
196 return new binding.Opencc(
197 JSON.stringify(raw),
198 configDirectory + (/[\\/]$/.test(configDirectory) ? '' : path.sep)
199 );
200 }
201
202 /**
203 * Patch all relative paths in a config JSON object to absolute paths.
204 *
205 * - segmentation resources + __plugin_library → jieba package
206 * - conversion_chain dict files → main opencc package assets
207 *
208 * @param {Object} config - Parsed config JSON object (modified in-place).
209 * @param {Object} jieba - Info from the opencc-jieba package.
210 * @param {string} mainAssetsDir - Main opencc package assets directory.
211 */
212 function patchConfigPaths(config, jieba, mainAssetsDir) {
213 // Inject explicit plugin library path (skips dlopen search in C++)
214 if (jieba && config.segmentation) {
215 config.segmentation.__plugin_library = jieba.pluginLibrary;
216 // Absolutify segmentation resource paths (dict_path, model_path, etc.)
217 if (config.segmentation.resources) {
218 const res = config.segmentation.resources;
219 for (const key of Object.keys(res)) {
220 if (!path.isAbsolute(res[key])) {
221 res[key] = path.join(jieba.dataDir, res[key]);
222 }
223 }
224 }
225 }
226 // Absolutify normalization and conversion_chain dict file paths
227 if (Array.isArray(config.normalization)) {
228 for (const step of config.normalization) {
229 patchDictPaths(step.dict, mainAssetsDir);
230 }
231 }
232 if (Array.isArray(config.conversion_chain)) {
233 for (const step of config.conversion_chain) {
234 patchDictPaths(step.dict, mainAssetsDir);
235 }
236 }
237 }
238
239 function resolveJiebaConfigPath(config, jieba) {
240 if (!jieba || isAbsolutePath(config)) {
241 return null;
242 }
243 if (typeof jieba.resolveConfigPath === 'function') {
244 return jieba.resolveConfigPath(config);
245 }
246 const candidates = [config];
247 if (!config.endsWith('.json')) {
248 candidates.push(config + '.json');
249 }
250 for (const candidate of candidates) {
251 if (candidate.includes('/') || candidate.includes('\\')) {
252 continue;
253 }
254 const configPath = path.join(jieba.dataDir, candidate);
255 if (fs.existsSync(configPath)) {
256 return configPath;
257 }
258 }
259 return null;
260 }
261
262 /**
263 * OpenCC Node.js API
264 *
265 * @class OpenCC
266 * @constructor
267 * @ingroup node_api
268 */
269 const OpenCC = module.exports = function (config, options) {
270 if (!config) {
271 config = 's2t.json';
272 }
273 if (!options) {
274 options = {};
275 }
276
277 if (isConfigObject(config)) {
278 this.handler = createFromConfigObject(config, options);
279 return;
280 }
281
282 const includeTofuRiskDictionaries =
283 options.includeTofuRiskDictionaries !== false;
284
285 if (options.resourceZip) {
286 this.handler = new binding.Opencc(
287 config,
288 options.resourceZip,
289 includeTofuRiskDictionaries
290 );
291 return;
292 }
293
294 // When opencc-jieba is installed, check if the requested config is a jieba
295 // config. If so, load its JSON, patch all paths to absolute, and pass the
296 // patched JSON string directly to the C++ layer via NewFromString.
297 const jiebaConfigPath = resolveJiebaConfigPath(config, jiebaInfo);
298 if (jiebaConfigPath) {
299 const raw = parseJSON(fs.readFileSync(jiebaConfigPath, 'utf-8'));
300 filterTofuRiskConversionChain(raw, includeTofuRiskDictionaries);
301 patchConfigPaths(raw, jiebaInfo, assetsPath);
302 this.handler = new binding.Opencc(
303 JSON.stringify(raw),
304 jiebaInfo.dataDir + '/'
305 );
306 return;
307 }
308
309 config = getConfigPath(config);
310 if (!includeTofuRiskDictionaries) {
311 const raw = parseJSON(fs.readFileSync(config, 'utf-8'));
312 filterTofuRiskConversionChain(raw, includeTofuRiskDictionaries);
313 const configDir = path.dirname(config);
314 if (raw.segmentation && raw.segmentation.dict) {
315 patchDictPaths(raw.segmentation.dict, configDir);
316 }
317 if (Array.isArray(raw.conversion_chain)) {
318 for (const step of raw.conversion_chain) {
319 patchDictPaths(step.dict, configDir);
320 }
321 }
322 this.handler = new binding.Opencc(
323 JSON.stringify(raw),
324 configDir + path.sep
325 );
326 return;
327 }
328 this.handler = new binding.Opencc(config);
329 };
330
331 function parseJSON(str) {
332 const cleanStr = str.replace(/"(?:[^"\\]|\\.)*"|(\/\/.*|\/\*[\s\S]*?\*\/)|(,\s*(?=[\]}]))/g, (m, g1, g2) => (g1 || g2) ? "" : m);
333 return JSON.parse(cleanStr);
334 }
335
336 // This is to support both CommonJS and ES module.
337 OpenCC.OpenCC = OpenCC;
338 OpenCC._parseJSON = parseJSON;
339
340 // Resolved native addon path and its adjacent assets (config/dictionary)
341 // directory, exported so tooling/tests can locate them without re-deriving the
342 // lookup (and without depending on node-gyp-build).
343 OpenCC._bindingPath = bindingPath;
344 OpenCC._assetsPath = assetsPath;
345
346 /**
347 * The version of OpenCC library.
348 *
349 * @fn OpenCC.version
350 * @memberof OpenCC
351 * @ingroup node_api
352 */
353 OpenCC.version = binding.Opencc.version();
354
355 OpenCC.fromConfig = function (config, options) {
356 return new OpenCC(config, options);
357 };
358
359 /**
360 * Generates dictionary from another format.
361 *
362 * @fn string generateDict(string inputFileName, string outputFileName, string formatFrom, string formatTo)
363 * @memberof OpenCC
364 * @param inputFileName Input dictionary filename.
365 * @param outputFileName Output dictionary filename.
366 * @param formatFrom Input dictionary format.
367 * @param formatTo Input dictionary format.
368 * @ingroup node_api
369 */
370 OpenCC.generateDict = function (inputFileName, outputFileName,
371 formatFrom, formatTo) {
372 return binding.Opencc.generateDict(inputFileName, outputFileName,
373 formatFrom, formatTo);
374 }
375
376 /**
377 * Converts input text.
378 *
379 * @fn void convert(string input, function callback)
380 * @memberof OpenCC
381 * @param input Input text.
382 * @param callback Callback function(err, convertedText).
383 * @ingroup node_api
384 */
385 OpenCC.prototype.convert = function (input, callback) {
386 return this.handler.convert(input.toString(), callback);
387 };
388
389 /**
390 * Converts input text.
391 *
392 * @fn string convertSync(string input)
393 * @memberof OpenCC
394 * @param input Input text.
395 * @return Converted text.
396 * @ingroup node_api
397 */
398 OpenCC.prototype.convertSync = function (input) {
399 return this.handler.convertSync(input.toString());
400 };
401
402 /**
403 * Converts input text asynchronously and returns a Promise.
404 *
405 * @fn Promise convertPromise(string input)
406 * @memberof OpenCC
407 * @param input Input text.
408 * @return The Promise that will yield the converted text.
409 * @ingroup node_api
410 */
411 OpenCC.prototype.convertPromise = function (input) {
412 const self = this;
413 return new Promise(function (resolve, reject) {
414 self.handler.convert(input.toString(), function (err, text) {
415 if (err) reject(err);
416 else resolve(text);
417 });
418 });
419 };
420
421 OpenCC.prototype._createConverterStream = function () {
422 return new binding.OpenccStream(this.handler);
423 };