From ff540555e6a55fcd4e7c69a8702167a1f9abfe1e Mon Sep 17 00:00:00 2001 From: Nicolas Froidure Date: Sat, 20 Jul 2024 22:53:41 +0200 Subject: [PATCH] feat(core): better choice between builds also allow to debug the version that is in use with the `DEBUG=ttf2woff2` env var. fix #22 fix #46 --- package-lock.json | 4 +++- package.json | 6 ++++-- src/index.ts | 44 ++++++++++++++++++++++++++++++++++++++------ 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index d2d572f..603ed99 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,8 +12,10 @@ "dependencies": { "bindings": "^1.5.0", "bufferstreams": "^4.0.0", + "debug": "^4.3.5", "nan": "^2.20.0", - "node-gyp": "^10.2.0" + "node-gyp": "^10.2.0", + "yerror": "^8.0.0" }, "bin": { "ttf2woff2": "bin/ttf2woff2.js" diff --git a/package.json b/package.json index 547ac5c..15657c8 100644 --- a/package.json +++ b/package.json @@ -81,8 +81,10 @@ "dependencies": { "bindings": "^1.5.0", "bufferstreams": "^4.0.0", + "debug": "^4.3.5", "nan": "^2.20.0", - "node-gyp": "^10.2.0" + "node-gyp": "^10.2.0", + "yerror": "^8.0.0" }, "devDependencies": { "@eslint/js": "^9.7.0", @@ -192,4 +194,4 @@ "overrides": { "eslint": "^9.7.0" } -} \ No newline at end of file +} diff --git a/src/index.ts b/src/index.ts index 7b0a221..4b801c1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,41 @@ -let ttf2woff2: (input: Buffer) => Buffer; +import { YError, printStackTrace } from 'yerror'; +import debug from 'debug'; +import { env } from 'node:process'; -try { - ttf2woff2 = (await import('bindings'))('addon.node').convert; -} catch (err) { - ttf2woff2 = (await import('../jssrc/index.js')).default; +const doDebug = debug('ttf2woff2'); +let ttf2woff2: undefined | ((input: Buffer) => Buffer) = undefined; + +if ( + !env.TTF2WOFF2_VERSION || + env.TTF2WOFF2_VERSION?.toLowerCase() === 'native' +) { + try { + ttf2woff2 = (await import('bindings'))('addon.node').convert; + doDebug('✅ Using native version.'); + } catch (err) { + doDebug( + '❌ Could not load the native version.', + printStackTrace(err as Error), + ); + } +} + +if (!env.TTF2WOFF2_VERSION || env.TTF2WOFF2_VERSION?.toLowerCase() === 'wasm') { + if (!ttf2woff2) { + try { + ttf2woff2 = (await import('../jssrc/index.js')).default; + doDebug('✅ Using WASM version.'); + } catch (err) { + doDebug( + '❌ Could not load the WASM version.', + printStackTrace(err as Error), + ); + } + } +} + +if (!ttf2woff2) { + throw new YError('E_UNABLE_TO_LOAD_TTF2WOFF2', env.TTF2WOFF2_VERSION); } -export default ttf2woff2; +export default ttf2woff2 as NonNullable;