@internetarchive/bookreader 5.0.0-113 → 5.0.0-115

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 (42) hide show
  1. package/BookReader/474.js.map +1 -1
  2. package/BookReader/BookReader.css +34 -10
  3. package/BookReader/BookReader.js +1 -1
  4. package/BookReader/BookReader.js.map +1 -1
  5. package/BookReader/ia-bookreader-bundle.js +20 -38
  6. package/BookReader/ia-bookreader-bundle.js.map +1 -1
  7. package/BookReader/plugins/plugin.archive_analytics.js.map +1 -1
  8. package/BookReader/plugins/plugin.autoplay.js.map +1 -1
  9. package/BookReader/plugins/plugin.chapters.js +1 -1
  10. package/BookReader/plugins/plugin.chapters.js.map +1 -1
  11. package/BookReader/plugins/plugin.experiments.js +1 -1
  12. package/BookReader/plugins/plugin.experiments.js.map +1 -1
  13. package/BookReader/plugins/plugin.iframe.js +1 -1
  14. package/BookReader/plugins/plugin.iframe.js.map +1 -1
  15. package/BookReader/plugins/plugin.iiif.js.map +1 -1
  16. package/BookReader/plugins/plugin.resume.js.map +1 -1
  17. package/BookReader/plugins/plugin.search.js +1 -1
  18. package/BookReader/plugins/plugin.search.js.map +1 -1
  19. package/BookReader/plugins/plugin.text_selection.js +1 -1
  20. package/BookReader/plugins/plugin.text_selection.js.map +1 -1
  21. package/BookReader/plugins/plugin.translate.js +1 -1
  22. package/BookReader/plugins/plugin.translate.js.map +1 -1
  23. package/BookReader/plugins/plugin.tts.js +1 -1
  24. package/BookReader/plugins/plugin.tts.js.map +1 -1
  25. package/BookReader/plugins/plugin.url.js.map +1 -1
  26. package/BookReader/plugins/plugin.vendor-fullscreen.js.map +1 -1
  27. package/BookReader/plugins/translator-worker.js.map +1 -1
  28. package/BookReader/webcomponents-bundle.js.map +1 -1
  29. package/package.json +37 -31
  30. package/src/BookReader/utils/SelectionObserver.js +4 -2
  31. package/src/BookReader.js +2 -1
  32. package/src/css/_TextSelection.scss +32 -11
  33. package/src/ia-bookreader/ia-bookreader.js +13 -2
  34. package/src/plugins/plugin.experiments.js +13 -3
  35. package/src/plugins/plugin.iiif.js +7 -1
  36. package/src/plugins/plugin.text_selection.js +8 -1
  37. package/src/plugins/tts/WebTTSEngine.js +2 -2
  38. package/src/plugins/tts/plugin.tts.js +3 -3
  39. package/src/plugins/tts/utils.js +0 -19
  40. package/src/util/TextSelectionManager.js +276 -110
  41. package/src/util/browserSniffing.js +9 -0
  42. package/src/util/strings.js +10 -0
@@ -1 +1 @@
1
- {"version":3,"file":"474.js","mappings":"yBACA,IAAIA,EAAsB,CAAC,ECD3BA,EAAoBC,EAAI,WACvB,GAA0B,iBAAfC,WAAyB,OAAOA,WAC3C,IACC,OAAOC,MAAQ,IAAIC,SAAS,cAAb,EAChB,CAAE,MAAOC,GACR,GAAsB,iBAAXC,OAAqB,OAAOA,MACxC,CACA,CAPuB,GCKxB,IAAIC,EAAS,CAAC,EAMM,oBAATC,OACP,EAAAP,EAAOM,OAASA,EAEhB,EAAAN,EAAOO,KAAO,IAAI,MAEd,GAEA,WAAAC,GACI,MAAM,WAACC,GAAcC,QAAkC,uBACvDR,MAAK,EAAQO,CACjB,CAOA,gBAAAE,CAAiBC,EAAWC,GACxBX,MAAK,EAAMY,GAAGF,EAAYG,GAASF,EAAS,CAACE,SACjD,CAMA,WAAAC,CAAYC,GACRf,MAAK,EAAMc,YAAYC,EAC3B,CAKA,aAAAC,IAAiBC,GACb,MAAM,aAACC,GAAgBV,QAAkC,YACnD,KAACW,GAAQX,QAAkC,aACjD,IAAK,IAAIY,KAAYH,EAAS,CAC1B,MAAMI,EAASH,EAAaC,EAAKG,UAAWF,GAAW,CAACG,SAAU,UAClEC,KAAKC,KAAK,EAAA3B,EAAQuB,EACtB,CACJ,CASA,WAAMK,CAAMC,EAAKC,GACb,GAAqB,UAAjBD,EAAIE,SAAsB,CAC1B,MAAM,SAACC,GAAYtB,QAAkC,oBAC/CuB,QAAeD,EAASH,EAAIP,UAC5BY,EAAO,IAAIC,K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,iBAAiB,UAAWsF,gBAAgBlF,MAAM,GAAC4J,EAAE,KAAE9E,EAAI,KAAEC,KACzD6E,GACD3F,QAAQwF,MAAM,8BAA+BI,UAAU,IAE3D,IACI,GAA4B,mBAAjBF,EAAO7E,GACd,MAAMgF,UAAU,UAAUhF,wBAI9B,MAAMiF,QAAe9E,QAAQE,QAAQ6E,QAAQC,MAAMN,EAAO7E,GAAO6E,EAAQ5E,IACzEvF,KAAKS,YAAY,CAAC2J,KAAIG,UAC1B,CAAE,MAAON,GACLjK,KAAKS,YAAY,CACb2J,KACAH,MAAOD,EAAWC,IAE1B,CACJ,E","sources":["webpack://@internetarchive/bookreader/webpack/bootstrap","webpack://@internetarchive/bookreader/webpack/runtime/global","webpack://@internetarchive/bookreader/./node_modules/@internetarchive/bergamot-translator/worker/translator-worker.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","/**\n * Wrapper around the dirty bits of Bergamot's WASM bindings.\n */\n\n// Global because importScripts is global.\nvar Module = {};\n\n/**\n * node.js compatibility: Fake GlobalWorkerScope that emulates being inside a\n * WebWorker\n */\nif (typeof self === 'undefined') {\n global.Module = Module;\n\n global.self = new class GlobalWorkerScope {\n /** @type {import(\"node:worker_threads\").MessagePort} */\n #port;\n\n constructor() {\n const {parentPort} = require(/* webpackIgnore: true */ 'node:worker_threads');\n this.#port = parentPort;\n }\n\n /**\n * Add event listener to listen for messages posted to the worker.\n * @param {string} eventName\n * @param {(object)} callback\n */\n addEventListener(eventName, callback) {\n this.#port.on(eventName, (data) => callback({data}));\n }\n\n /**\n * Post message outside, to the owner of the Worker.\n * @param {any} message\n */\n postMessage(message) {\n this.#port.postMessage(message);\n }\n\n /**\n * @param {...string} scripts - Paths to scripts to import in that order\n */\n importScripts(...scripts) {\n const {readFileSync} = require(/* webpackIgnore: true */ 'node:fs');\n const {join} = require(/* webpackIgnore: true */ 'node:path');\n for (let pathname of scripts) {\n const script = readFileSync(join(__dirname, pathname), {encoding: 'utf-8'});\n eval.call(global, script);\n }\n }\n\n /**\n * Adds support for local file urls. Assumes anything that doesn't start\n * with \"http\" to be a local path.\n * @param {string} url - path or url\n * @param {object?} options - See `fetch()` options\n * @return {Promise<Response>}\n */\n async fetch(url, options) {\n if (url.protocol === 'file:') {\n const {readFile} = require(/* webpackIgnore: true */ 'node:fs/promises');\n const buffer = await readFile(url.pathname);\n const blob = new Blob([buffer]);\n return new Response(blob, {\n status: 200,\n statusText: 'OK',\n headers: {\n 'Content-Type': 'application/wasm',\n 'Content-Length': blob.size.toString()\n }\n });\n }\n\n return await fetch(url, options);\n }\n\n get location() {\n return new URL(`file://${__filename}`);\n }\n }\n}\n\nclass YAML {\n /**\n * Parses YAML into dictionary. Does not interpret types, all values are a\n * string or a list of strings. No support for objects other than the top\n * level.\n * @param {string} yaml\n * @return {{[string]: string | string[]}}\n */\n static parse(yaml) {\n const out = {};\n\n yaml.split('\\n').reduce((key, line, i) => {\n let match;\n if (match = line.match(/^\\s*-\\s+(.+?)$/)) {\n if (!Array.isArray(out[key]))\n out[key] = out[key].trim() ? [out[key]] : [];\n out[key].push(match[1].trim());\n }\n else if (match = line.match(/^\\s*([A-Za-z0-9_][A-Za-z0-9_-]*):\\s*(.*)$/)) {\n key = match[1];\n out[key] = match[2].trim();\n }\n else if (!line.trim()) {\n // whitespace, ignore\n }\n else {\n throw Error(`Could not parse line ${i+1}: \"${line}\"`);\n }\n return key;\n }, null);\n\n return out;\n }\n\n /**\n * Turns an object into a YAML string. No support for objects, only simple\n * types and lists of simple types.\n * @param {{[string]: string | number | boolean | string[]}} data\n * @return {string}\n */\n static stringify(data) {\n return Object.entries(data).reduce((str, [key, value]) => {\n let valstr = '';\n if (Array.isArray(value))\n valstr = value.map(val => `\\n - ${val}`).join('');\n else if (typeof value === 'number' || typeof value === 'boolean' || value.match(/^\\d*(\\.\\d+)?$/))\n valstr = `${value}`;\n else\n valstr = `${value}`; // Quote?\n\n return `${str}${key}: ${valstr}\\n`;\n }, '');\n }\n}\n\n/**\n * Wrapper around the bergamot-translator exported module that hides the need\n * of working with C++ style data structures and does model management.\n */\nclass BergamotTranslatorWorker {\n /**\n * Map of expected symbol -> name of fallback symbol for functions that can\n * be swizzled for a faster implementation. Firefox Nightly makes use of\n * this.\n */\n static GEMM_TO_FALLBACK_FUNCTIONS_MAP = {\n 'int8_prepare_a': 'int8PrepareAFallback',\n 'int8_prepare_b': 'int8PrepareBFallback',\n 'int8_prepare_b_from_transposed': 'int8PrepareBFromTransposedFallback',\n 'int8_prepare_b_from_quantized_transposed': 'int8PrepareBFromQuantizedTransposedFallback',\n 'int8_prepare_bias': 'int8PrepareBiasFallback',\n 'int8_multiply_and_add_bias': 'int8MultiplyAndAddBiasFallback',\n 'int8_select_columns_of_b': 'int8SelectColumnsOfBFallback'\n };\n\n /**\n * Name of module exported by Firefox Nightly that exports an optimised\n * implementation of the symbols mentioned above.\n */\n static NATIVE_INT_GEMM = 'mozIntGemm';\n\n /**\n * Empty because we can't do async constructors yet. It is the\n * responsibility of whoever owns this WebWorker to call `initialize()`.\n */\n constructor(options) {}\n\n /**\n * Instantiates a new translation worker with optional options object.\n * If this call succeeds, the WASM runtime is loaded and ready.\n * \n * Available options are:\n * useNativeIntGemm: {true | false} defaults to false. If true, it will\n * attempt to link to the intgemm module available in\n * Firefox Nightly which makes translations much faster.\n * cacheSize: {Number} defaults to 0 which disables translation\n * cache entirely. Note that this is a theoretical\n * upper bound. In practice it will use about 1/3th of\n * the cache specified here. 2^14 is not a bad starting\n * value.\n * @param {{useNativeIntGemm: boolean, cacheSize: number}} options\n */\n async initialize(options) {\n this.options = options || {};\n this.models = new Map(); // Map<str,Promise<TranslationModel>>\n this.module = await this.loadModule();\n this.service = await this.loadTranslationService();\n }\n\n /**\n * Tries to load native IntGEMM module for bergamot-translator. If that\n * fails because it or any of the expected functions is not available, it\n * falls back to using the naive implementations that come with the wasm\n * binary itself through `linkFallbackIntGemm()`.\n * @param {{env: {memory: WebAssembly.Memory}}} info\n * @return {{[method:string]: (...any) => any}}\n */\n linkNativeIntGemm(info) {\n if (!WebAssembly['mozIntGemm']) {\n console.warn('Native gemm requested but not available, falling back to embedded gemm');\n return this.linkFallbackIntGemm(info);\n }\n\n const instance = new WebAssembly.Instance(WebAssembly['mozIntGemm'](), {\n '': {memory: info['env']['memory']}\n });\n\n if (!Array.from(Object.keys(BergamotTranslatorWorker.GEMM_TO_FALLBACK_FUNCTIONS_MAP)).every(fun => instance.exports[fun])) {\n console.warn('Native gemm is missing expected functions, falling back to embedded gemm');\n return this.linkFallbackIntGemm(info);\n }\n\n return instance.exports;\n }\n\n /**\n * Links intgemm functions that are already available in the wasm binary,\n * but just exports them under the name that is expected by\n * bergamot-translator.\n * @param {{env: {memory: WebAssembly.Memory}}} info\n * @return {{[method:string]: (...any) => any}}\n */\n linkFallbackIntGemm(info) {\n const mapping = Object.entries(BergamotTranslatorWorker.GEMM_TO_FALLBACK_FUNCTIONS_MAP).map(([key, name]) => {\n return [key, (...args) => Module['asm'][name](...args)]\n });\n\n return Object.fromEntries(mapping);\n }\n\n /**\n * Internal method. Reads and instantiates the WASM binary. Returns a\n * promise for the exported Module object that contains all the classes\n * and functions exported by bergamot-translator.\n * @return {Promise<BergamotTranslator>}\n */\n loadModule() {\n return new Promise(async (resolve, reject) => {\n try {\n const response = await self.fetch(new URL('./bergamot-translator-worker.wasm', self.location));\n\n Object.assign(Module, {\n instantiateWasm: (info, accept) => {\n try {\n WebAssembly.instantiateStreaming(response, {\n ...info,\n 'wasm_gemm': this.options.useNativeIntGemm\n ? this.linkNativeIntGemm(info)\n : this.linkFallbackIntGemm(info)\n }).then(({instance}) => accept(instance)).catch(reject);\n } catch (err) {\n reject(err);\n }\n return {};\n },\n onRuntimeInitialized: () => {\n resolve(Module);\n }\n });\n\n // Emscripten glue code. Webpack et al. should not mangle the `Module` property name!\n self.Module = Module;\n self.importScripts('bergamot-translator-worker.js');\n } catch (err) {\n reject(err);\n }\n });\n }\n\n /**\n * Internal method. Instantiates a BlockingService()\n * @return {BergamotTranslator.BlockingService}\n */\n loadTranslationService() {\n return new this.module.BlockingService({\n cacheSize: Math.max(this.options.cacheSize || 0, 0)\n });\n }\n\n /**\n * Returns whether a model has already been loaded in this worker. Marked\n * async because the message passing interface we use expects async methods.\n * @param {{from:string, to:string}}\n * @return boolean\n */ \n hasTranslationModel({from,to}) {\n const key = JSON.stringify({from,to});\n return this.models.has(key);\n }\n\n /**\n * Loads a translation model from a set of file buffers. After this, the\n * model is available to translate with and `hasTranslationModel()` will\n * return true for this pair.\n * @param {{from:string, to:string}}\n * @param {{\n * model: ArrayBuffer,\n * shortlist: ArrayBuffer,\n * vocabs: ArrayBuffer[],\n * qualityModel: ArrayBuffer?,\n * config?: {\n * [key:string]: string\n * }\n * }} buffers\n */ \n loadTranslationModel({from, to}, buffers) {\n // This because service_bindings.cpp:prepareVocabsSmartMemories :(\n const uniqueVocabs = buffers.vocabs.filter((vocab, index, vocabs) => {\n return !vocabs.slice(0, index).includes(vocab);\n });\n\n const [modelMemory, shortlistMemory, qualityModel, ...vocabMemory] = [\n this.prepareAlignedMemoryFromBuffer(buffers.model, 256),\n this.prepareAlignedMemoryFromBuffer(buffers.shortlist, 64),\n buffers.qualityModel // optional quality model\n ? this.prepareAlignedMemoryFromBuffer(buffers.qualityModel, 64)\n : null,\n ...uniqueVocabs.map(vocab => this.prepareAlignedMemoryFromBuffer(vocab, 64))\n ];\n\n const vocabs = new this.module.AlignedMemoryList();\n vocabMemory.forEach(vocab => vocabs.push_back(vocab));\n\n // Defaults\n let modelConfig = YAML.parse(`\n beam-size: 1\n normalize: 1.0\n word-penalty: 0\n cpu-threads: 0\n gemm-precision: int8shiftAlphaAll\n skip-cost: true\n `);\n\n if (buffers.config)\n Object.assign(modelConfig, buffers.config);\n\n // WASM marian is only compiled with support for shiftedAll.\n if (modelConfig['gemm-precision'] === 'int8')\n modelConfig['gemm-precision'] = 'int8shiftAll';\n\n // Override these\n Object.assign(modelConfig, YAML.parse(`\n alignment: soft\n quiet: true\n quiet-translation: true\n max-length-break: 128\n mini-batch-words: 1024\n workspace: 128\n max-length-factor: 2.0\n `));\n\n const key = JSON.stringify({from,to});\n this.models.set(key, new this.module.TranslationModel(YAML.stringify(modelConfig), modelMemory, shortlistMemory, vocabs, qualityModel));\n }\n\n /**\n * Frees up memory used by old translation model. Does nothing if model is\n * already deleted.\n * @param {{from:string, to:string}}\n */\n freeTranslationModel({from, to}) {\n const key = JSON.stringify({from,to});\n \n if (!this.models.has(key))\n return;\n \n const model = this.models.get(key);\n this.models.delete(key);\n\n model.delete();\n }\n\n /**\n * Internal function. Copies the data from an ArrayBuffer into memory that\n * can be used inside the WASM vm by Marian.\n * @param {{ArrayBuffer}} buffer\n * @param {number} alignmentSize\n * @return {BergamotTranslator.AlignedMemory}\n */\n prepareAlignedMemoryFromBuffer(buffer, alignmentSize) {\n const bytes = new Int8Array(buffer);\n const memory = new this.module.AlignedMemory(bytes.byteLength, alignmentSize);\n memory.getByteArrayView().set(bytes);\n return memory;\n }\n\n /**\n * Public. Does actual translation work. You have to make sure that the\n * models necessary for translating text are already loaded before calling\n * this method. Returns a promise with translation responses.\n * @param {{models: {from:string, to:string}[], texts: {text: string, html: boolean}[]}}\n * @return {Promise<{target: {text: string}}[]>}\n */\n translate({models, texts}) {\n // Convert texts array into a std::vector<std::string>.\n let input = new this.module.VectorString();\n texts.forEach(({text}) => input.push_back(text));\n\n // Extracts the texts[].html options into ResponseOption objects\n let options = new this.module.VectorResponseOptions();\n texts.forEach(({html, qualityScores}) => options.push_back({alignment: false, html, qualityScores}));\n\n // Turn our model names into a list of TranslationModel pointers\n const translationModels = models.map(({from,to}) => {\n const key = JSON.stringify({from,to});\n return this.models.get(key);\n });\n\n // translate the input, which is a vector<String>; the result is a vector<Response>\n const responses = models.length > 1\n ? this.service.translateViaPivoting(...translationModels, input, options)\n : this.service.translate(...translationModels, input, options);\n \n input.delete();\n options.delete();\n\n // Convert the Response WASM wrappers into native JavaScript types we\n // can send over the 'wire' (message passing) in the same format as we\n // use in bergamot-translator.\n const translations = texts.map((_, i) => ({\n target: {\n text: responses.get(i).getTranslatedText()\n }\n }));\n\n responses.delete();\n\n return translations;\n }\n}\n\n/**\n * Because you can't put an Error object in a message. But you can post a\n * generic object!\n * @param {Error} error\n * @return {{\n * name: string?,\n * message: string?,\n * stack: string?\n * }}\n */\nfunction cloneError(error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n}\n\n// (Constructor doesn't really do anything, we need to call `initialize()`\n// first before using it. That happens from outside the worker.)\nconst worker = new BergamotTranslatorWorker();\n\nself.addEventListener('message', async function({data: {id, name, args}}) {\n if (!id)\n console.error('Received message without id', arguments[0]);\n\n try {\n if (typeof worker[name] !== 'function')\n throw TypeError(`worker[${name}] is not a function`);\n\n // Using `Promise.resolve` to await any promises that worker[name]\n // possibly returns.\n const result = await Promise.resolve(Reflect.apply(worker[name], worker, args));\n self.postMessage({id, result});\n } catch (error) {\n self.postMessage({\n id,\n error: cloneError(error)\n })\n }\n});\n"],"names":["__webpack_require__","g","globalThis","this","Function","e","window","Module","self","constructor","parentPort","require","addEventListener","eventName","callback","on","data","postMessage","message","importScripts","scripts","readFileSync","join","pathname","script","__dirname","encoding","eval","call","fetch","url","options","protocol","readFile","buffer","blob","Blob","Response","status","statusText","headers","size","toString","location","URL","__filename","YAML","parse","yaml","out","split","reduce","key","line","i","match","Array","isArray","trim","push","Error","stringify","Object","entries","str","value","valstr","map","val","BergamotTranslatorWorker","static","initialize","models","Map","module","loadModule","service","loadTranslationService","linkNativeIntGemm","info","WebAssembly","console","warn","linkFallbackIntGemm","instance","Instance","memory","from","keys","GEMM_TO_FALLBACK_FUNCTIONS_MAP","every","fun","exports","mapping","name","args","fromEntries","Promise","async","resolve","reject","response","assign","instantiateWasm","accept","instantiateStreaming","useNativeIntGemm","then","catch","err","onRuntimeInitialized","BlockingService","cacheSize","Math","max","hasTranslationModel","to","JSON","has","loadTranslationModel","buffers","uniqueVocabs","vocabs","filter","vocab","index","slice","includes","modelMemory","shortlistMemory","qualityModel","vocabMemory","prepareAlignedMemoryFromBuffer","model","shortlist","AlignedMemoryList","forEach","push_back","modelConfig","config","set","TranslationModel","freeTranslationModel","get","delete","alignmentSize","bytes","Int8Array","AlignedMemory","byteLength","getByteArrayView","translate","texts","input","VectorString","text","VectorResponseOptions","html","qualityScores","alignment","translationModels","responses","length","translateViaPivoting","translations","_","target","getTranslatedText","cloneError","error","stack","worker","id","arguments","TypeError","result","Reflect","apply"],"sourceRoot":""}
1
+ {"version":3,"file":"474.js","mappings":"yBACA,IAAAA,EAAA,GCDAA,EAAAC,EAAA,WACA,oBAAAC,WAAA,OAAAA,WACA,IACA,OAAAC,MAAA,IAAAC,SAAA,gBACA,CAAG,MAAAC,GACH,oBAAAC,OAAA,OAAAA,MACA,CACC,CAPD,GCKA,IAAAC,EAAA,GAMA,oBAAAC,OACIR,EAAAC,EAAMM,OAAAA,EAENP,EAAAC,EAAMO,KAAA,UAEVC,GAEA,WAAAC,GACA,MAAAC,WAAmBA,GAAYC,QAAA,uBAC/BT,MAAAM,EAAAE,CACA,CAOA,gBAAAE,CAAAC,EAAAC,GACAZ,MAAAM,EAAAO,GAAAF,EAAAG,GAAAF,EAAA,CAAyDE,SACzD,CAMA,WAAAC,CAAAC,GACAhB,MAAAM,EAAAS,YAAAC,EACA,CAKA,aAAAC,IAAAC,GACA,MAAAC,aAAmBA,GAAcV,QAAA,YACjCW,KAAmBA,GAAMX,QAAA,aACzB,QAAAY,KAAAH,EAAA,CACA,MAAAI,EAAAH,EAAAC,EAAAG,UAAAF,GAAA,CAAwEG,SAAA,UACxEC,KAAAC,KAA0B7B,EAAAC,EAAMwB,EAChC,CACA,CASA,WAAAK,CAAAC,EAAAC,GACA,aAAAD,EAAAE,SAAA,CACA,MAAAC,S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A,MAAAiF,UAAA,UAAsCjF,wBAItC,MAAAkF,QAAA/E,QAAAE,QAAA8E,QAAAC,MAAAN,EAAA9E,GAAA8E,EAAA7E,IACA/F,KAAAU,YAAA,CAA0BmK,KAAAG,UAC1B,CAAM,MAAAN,GACN1K,KAAAU,YAAA,CACAmK,KACAH,MAAAD,EAAAC,IAEA,CACA","sources":["webpack://@internetarchive/bookreader/webpack/bootstrap","webpack://@internetarchive/bookreader/webpack/runtime/global","webpack://@internetarchive/bookreader/./node_modules/@internetarchive/bergamot-translator/worker/translator-worker.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","/**\n * Wrapper around the dirty bits of Bergamot's WASM bindings.\n */\n\n// Global because importScripts is global.\nvar Module = {};\n\n/**\n * node.js compatibility: Fake GlobalWorkerScope that emulates being inside a\n * WebWorker\n */\nif (typeof self === 'undefined') {\n global.Module = Module;\n\n global.self = new class GlobalWorkerScope {\n /** @type {import(\"node:worker_threads\").MessagePort} */\n #port;\n\n constructor() {\n const {parentPort} = require(/* webpackIgnore: true */ 'node:worker_threads');\n this.#port = parentPort;\n }\n\n /**\n * Add event listener to listen for messages posted to the worker.\n * @param {string} eventName\n * @param {(object)} callback\n */\n addEventListener(eventName, callback) {\n this.#port.on(eventName, (data) => callback({data}));\n }\n\n /**\n * Post message outside, to the owner of the Worker.\n * @param {any} message\n */\n postMessage(message) {\n this.#port.postMessage(message);\n }\n\n /**\n * @param {...string} scripts - Paths to scripts to import in that order\n */\n importScripts(...scripts) {\n const {readFileSync} = require(/* webpackIgnore: true */ 'node:fs');\n const {join} = require(/* webpackIgnore: true */ 'node:path');\n for (let pathname of scripts) {\n const script = readFileSync(join(__dirname, pathname), {encoding: 'utf-8'});\n eval.call(global, script);\n }\n }\n\n /**\n * Adds support for local file urls. Assumes anything that doesn't start\n * with \"http\" to be a local path.\n * @param {string} url - path or url\n * @param {object?} options - See `fetch()` options\n * @return {Promise<Response>}\n */\n async fetch(url, options) {\n if (url.protocol === 'file:') {\n const {readFile} = require(/* webpackIgnore: true */ 'node:fs/promises');\n const buffer = await readFile(url.pathname);\n const blob = new Blob([buffer]);\n return new Response(blob, {\n status: 200,\n statusText: 'OK',\n headers: {\n 'Content-Type': 'application/wasm',\n 'Content-Length': blob.size.toString()\n }\n });\n }\n\n return await fetch(url, options);\n }\n\n get location() {\n return new URL(`file://${__filename}`);\n }\n }\n}\n\nclass YAML {\n /**\n * Parses YAML into dictionary. Does not interpret types, all values are a\n * string or a list of strings. No support for objects other than the top\n * level.\n * @param {string} yaml\n * @return {{[string]: string | string[]}}\n */\n static parse(yaml) {\n const out = {};\n\n yaml.split('\\n').reduce((key, line, i) => {\n let match;\n if (match = line.match(/^\\s*-\\s+(.+?)$/)) {\n if (!Array.isArray(out[key]))\n out[key] = out[key].trim() ? [out[key]] : [];\n out[key].push(match[1].trim());\n }\n else if (match = line.match(/^\\s*([A-Za-z0-9_][A-Za-z0-9_-]*):\\s*(.*)$/)) {\n key = match[1];\n out[key] = match[2].trim();\n }\n else if (!line.trim()) {\n // whitespace, ignore\n }\n else {\n throw Error(`Could not parse line ${i+1}: \"${line}\"`);\n }\n return key;\n }, null);\n\n return out;\n }\n\n /**\n * Turns an object into a YAML string. No support for objects, only simple\n * types and lists of simple types.\n * @param {{[string]: string | number | boolean | string[]}} data\n * @return {string}\n */\n static stringify(data) {\n return Object.entries(data).reduce((str, [key, value]) => {\n let valstr = '';\n if (Array.isArray(value))\n valstr = value.map(val => `\\n - ${val}`).join('');\n else if (typeof value === 'number' || typeof value === 'boolean' || value.match(/^\\d*(\\.\\d+)?$/))\n valstr = `${value}`;\n else\n valstr = `${value}`; // Quote?\n\n return `${str}${key}: ${valstr}\\n`;\n }, '');\n }\n}\n\n/**\n * Wrapper around the bergamot-translator exported module that hides the need\n * of working with C++ style data structures and does model management.\n */\nclass BergamotTranslatorWorker {\n /**\n * Map of expected symbol -> name of fallback symbol for functions that can\n * be swizzled for a faster implementation. Firefox Nightly makes use of\n * this.\n */\n static GEMM_TO_FALLBACK_FUNCTIONS_MAP = {\n 'int8_prepare_a': 'int8PrepareAFallback',\n 'int8_prepare_b': 'int8PrepareBFallback',\n 'int8_prepare_b_from_transposed': 'int8PrepareBFromTransposedFallback',\n 'int8_prepare_b_from_quantized_transposed': 'int8PrepareBFromQuantizedTransposedFallback',\n 'int8_prepare_bias': 'int8PrepareBiasFallback',\n 'int8_multiply_and_add_bias': 'int8MultiplyAndAddBiasFallback',\n 'int8_select_columns_of_b': 'int8SelectColumnsOfBFallback'\n };\n\n /**\n * Name of module exported by Firefox Nightly that exports an optimised\n * implementation of the symbols mentioned above.\n */\n static NATIVE_INT_GEMM = 'mozIntGemm';\n\n /**\n * Empty because we can't do async constructors yet. It is the\n * responsibility of whoever owns this WebWorker to call `initialize()`.\n */\n constructor(options) {}\n\n /**\n * Instantiates a new translation worker with optional options object.\n * If this call succeeds, the WASM runtime is loaded and ready.\n * \n * Available options are:\n * useNativeIntGemm: {true | false} defaults to false. If true, it will\n * attempt to link to the intgemm module available in\n * Firefox Nightly which makes translations much faster.\n * cacheSize: {Number} defaults to 0 which disables translation\n * cache entirely. Note that this is a theoretical\n * upper bound. In practice it will use about 1/3th of\n * the cache specified here. 2^14 is not a bad starting\n * value.\n * @param {{useNativeIntGemm: boolean, cacheSize: number}} options\n */\n async initialize(options) {\n this.options = options || {};\n this.models = new Map(); // Map<str,Promise<TranslationModel>>\n this.module = await this.loadModule();\n this.service = await this.loadTranslationService();\n }\n\n /**\n * Tries to load native IntGEMM module for bergamot-translator. If that\n * fails because it or any of the expected functions is not available, it\n * falls back to using the naive implementations that come with the wasm\n * binary itself through `linkFallbackIntGemm()`.\n * @param {{env: {memory: WebAssembly.Memory}}} info\n * @return {{[method:string]: (...any) => any}}\n */\n linkNativeIntGemm(info) {\n if (!WebAssembly['mozIntGemm']) {\n console.warn('Native gemm requested but not available, falling back to embedded gemm');\n return this.linkFallbackIntGemm(info);\n }\n\n const instance = new WebAssembly.Instance(WebAssembly['mozIntGemm'](), {\n '': {memory: info['env']['memory']}\n });\n\n if (!Array.from(Object.keys(BergamotTranslatorWorker.GEMM_TO_FALLBACK_FUNCTIONS_MAP)).every(fun => instance.exports[fun])) {\n console.warn('Native gemm is missing expected functions, falling back to embedded gemm');\n return this.linkFallbackIntGemm(info);\n }\n\n return instance.exports;\n }\n\n /**\n * Links intgemm functions that are already available in the wasm binary,\n * but just exports them under the name that is expected by\n * bergamot-translator.\n * @param {{env: {memory: WebAssembly.Memory}}} info\n * @return {{[method:string]: (...any) => any}}\n */\n linkFallbackIntGemm(info) {\n const mapping = Object.entries(BergamotTranslatorWorker.GEMM_TO_FALLBACK_FUNCTIONS_MAP).map(([key, name]) => {\n return [key, (...args) => Module['asm'][name](...args)]\n });\n\n return Object.fromEntries(mapping);\n }\n\n /**\n * Internal method. Reads and instantiates the WASM binary. Returns a\n * promise for the exported Module object that contains all the classes\n * and functions exported by bergamot-translator.\n * @return {Promise<BergamotTranslator>}\n */\n loadModule() {\n return new Promise(async (resolve, reject) => {\n try {\n const response = await self.fetch(new URL('./bergamot-translator-worker.wasm', self.location));\n\n Object.assign(Module, {\n instantiateWasm: (info, accept) => {\n try {\n WebAssembly.instantiateStreaming(response, {\n ...info,\n 'wasm_gemm': this.options.useNativeIntGemm\n ? this.linkNativeIntGemm(info)\n : this.linkFallbackIntGemm(info)\n }).then(({instance}) => accept(instance)).catch(reject);\n } catch (err) {\n reject(err);\n }\n return {};\n },\n onRuntimeInitialized: () => {\n resolve(Module);\n }\n });\n\n // Emscripten glue code. Webpack et al. should not mangle the `Module` property name!\n self.Module = Module;\n self.importScripts('bergamot-translator-worker.js');\n } catch (err) {\n reject(err);\n }\n });\n }\n\n /**\n * Internal method. Instantiates a BlockingService()\n * @return {BergamotTranslator.BlockingService}\n */\n loadTranslationService() {\n return new this.module.BlockingService({\n cacheSize: Math.max(this.options.cacheSize || 0, 0)\n });\n }\n\n /**\n * Returns whether a model has already been loaded in this worker. Marked\n * async because the message passing interface we use expects async methods.\n * @param {{from:string, to:string}}\n * @return boolean\n */ \n hasTranslationModel({from,to}) {\n const key = JSON.stringify({from,to});\n return this.models.has(key);\n }\n\n /**\n * Loads a translation model from a set of file buffers. After this, the\n * model is available to translate with and `hasTranslationModel()` will\n * return true for this pair.\n * @param {{from:string, to:string}}\n * @param {{\n * model: ArrayBuffer,\n * shortlist: ArrayBuffer,\n * vocabs: ArrayBuffer[],\n * qualityModel: ArrayBuffer?,\n * config?: {\n * [key:string]: string\n * }\n * }} buffers\n */ \n loadTranslationModel({from, to}, buffers) {\n // This because service_bindings.cpp:prepareVocabsSmartMemories :(\n const uniqueVocabs = buffers.vocabs.filter((vocab, index, vocabs) => {\n return !vocabs.slice(0, index).includes(vocab);\n });\n\n const [modelMemory, shortlistMemory, qualityModel, ...vocabMemory] = [\n this.prepareAlignedMemoryFromBuffer(buffers.model, 256),\n this.prepareAlignedMemoryFromBuffer(buffers.shortlist, 64),\n buffers.qualityModel // optional quality model\n ? this.prepareAlignedMemoryFromBuffer(buffers.qualityModel, 64)\n : null,\n ...uniqueVocabs.map(vocab => this.prepareAlignedMemoryFromBuffer(vocab, 64))\n ];\n\n const vocabs = new this.module.AlignedMemoryList();\n vocabMemory.forEach(vocab => vocabs.push_back(vocab));\n\n // Defaults\n let modelConfig = YAML.parse(`\n beam-size: 1\n normalize: 1.0\n word-penalty: 0\n cpu-threads: 0\n gemm-precision: int8shiftAlphaAll\n skip-cost: true\n `);\n\n if (buffers.config)\n Object.assign(modelConfig, buffers.config);\n\n // WASM marian is only compiled with support for shiftedAll.\n if (modelConfig['gemm-precision'] === 'int8')\n modelConfig['gemm-precision'] = 'int8shiftAll';\n\n // Override these\n Object.assign(modelConfig, YAML.parse(`\n alignment: soft\n quiet: true\n quiet-translation: true\n max-length-break: 128\n mini-batch-words: 1024\n workspace: 128\n max-length-factor: 2.0\n `));\n\n const key = JSON.stringify({from,to});\n this.models.set(key, new this.module.TranslationModel(YAML.stringify(modelConfig), modelMemory, shortlistMemory, vocabs, qualityModel));\n }\n\n /**\n * Frees up memory used by old translation model. Does nothing if model is\n * already deleted.\n * @param {{from:string, to:string}}\n */\n freeTranslationModel({from, to}) {\n const key = JSON.stringify({from,to});\n \n if (!this.models.has(key))\n return;\n \n const model = this.models.get(key);\n this.models.delete(key);\n\n model.delete();\n }\n\n /**\n * Internal function. Copies the data from an ArrayBuffer into memory that\n * can be used inside the WASM vm by Marian.\n * @param {{ArrayBuffer}} buffer\n * @param {number} alignmentSize\n * @return {BergamotTranslator.AlignedMemory}\n */\n prepareAlignedMemoryFromBuffer(buffer, alignmentSize) {\n const bytes = new Int8Array(buffer);\n const memory = new this.module.AlignedMemory(bytes.byteLength, alignmentSize);\n memory.getByteArrayView().set(bytes);\n return memory;\n }\n\n /**\n * Public. Does actual translation work. You have to make sure that the\n * models necessary for translating text are already loaded before calling\n * this method. Returns a promise with translation responses.\n * @param {{models: {from:string, to:string}[], texts: {text: string, html: boolean}[]}}\n * @return {Promise<{target: {text: string}}[]>}\n */\n translate({models, texts}) {\n // Convert texts array into a std::vector<std::string>.\n let input = new this.module.VectorString();\n texts.forEach(({text}) => input.push_back(text));\n\n // Extracts the texts[].html options into ResponseOption objects\n let options = new this.module.VectorResponseOptions();\n texts.forEach(({html, qualityScores}) => options.push_back({alignment: false, html, qualityScores}));\n\n // Turn our model names into a list of TranslationModel pointers\n const translationModels = models.map(({from,to}) => {\n const key = JSON.stringify({from,to});\n return this.models.get(key);\n });\n\n // translate the input, which is a vector<String>; the result is a vector<Response>\n const responses = models.length > 1\n ? this.service.translateViaPivoting(...translationModels, input, options)\n : this.service.translate(...translationModels, input, options);\n \n input.delete();\n options.delete();\n\n // Convert the Response WASM wrappers into native JavaScript types we\n // can send over the 'wire' (message passing) in the same format as we\n // use in bergamot-translator.\n const translations = texts.map((_, i) => ({\n target: {\n text: responses.get(i).getTranslatedText()\n }\n }));\n\n responses.delete();\n\n return translations;\n }\n}\n\n/**\n * Because you can't put an Error object in a message. But you can post a\n * generic object!\n * @param {Error} error\n * @return {{\n * name: string?,\n * message: string?,\n * stack: string?\n * }}\n */\nfunction cloneError(error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n}\n\n// (Constructor doesn't really do anything, we need to call `initialize()`\n// first before using it. That happens from outside the worker.)\nconst worker = new BergamotTranslatorWorker();\n\nself.addEventListener('message', async function({data: {id, name, args}}) {\n if (!id)\n console.error('Received message without id', arguments[0]);\n\n try {\n if (typeof worker[name] !== 'function')\n throw TypeError(`worker[${name}] is not a function`);\n\n // Using `Promise.resolve` to await any promises that worker[name]\n // possibly returns.\n const result = await Promise.resolve(Reflect.apply(worker[name], worker, args));\n self.postMessage({id, result});\n } catch (error) {\n self.postMessage({\n id,\n error: cloneError(error)\n })\n }\n});\n"],"names":["__webpack_require__","g","globalThis","this","Function","e","window","Module","self","port","constructor","parentPort","require","addEventListener","eventName","callback","on","data","postMessage","message","importScripts","scripts","readFileSync","join","pathname","script","__dirname","encoding","eval","call","fetch","url","options","protocol","readFile","buffer","blob","Blob","Response","status","statusText","headers","size","toString","location","URL","__filename","YAML","parse","yaml","out","split","reduce","key","line","i","match","Array","isArray","trim","push","Error","stringify","Object","entries","str","value","valstr","map","val","BergamotTranslatorWorker","static","int8_prepare_a","int8_prepare_b","int8_prepare_b_from_transposed","int8_prepare_b_from_quantized_transposed","int8_prepare_bias","int8_multiply_and_add_bias","int8_select_columns_of_b","initialize","models","Map","module","loadModule","service","loadTranslationService","linkNativeIntGemm","info","WebAssembly","console","warn","linkFallbackIntGemm","instance","Instance","memory","from","keys","GEMM_TO_FALLBACK_FUNCTIONS_MAP","every","fun","exports","mapping","name","args","fromEntries","Promise","async","resolve","reject","response","assign","instantiateWasm","accept","instantiateStreaming","wasm_gemm","useNativeIntGemm","then","catch","err","onRuntimeInitialized","BlockingService","cacheSize","Math","max","hasTranslationModel","to","JSON","has","loadTranslationModel","buffers","uniqueVocabs","vocabs","filter","vocab","index","slice","includes","modelMemory","shortlistMemory","qualityModel","vocabMemory","prepareAlignedMemoryFromBuffer","model","shortlist","AlignedMemoryList","forEach","push_back","modelConfig","config","set","TranslationModel","freeTranslationModel","get","delete","alignmentSize","bytes","Int8Array","AlignedMemory","byteLength","getByteArrayView","translate","texts","input","VectorString","text","VectorResponseOptions","html","qualityScores","alignment","translationModels","responses","length","translateViaPivoting","translations","_","target","getTranslatedText","cloneError","error","stack","worker","id","arguments","TypeError","result","Reflect","apply"],"sourceRoot":""}
@@ -2286,10 +2286,22 @@ ia-bookreader .BRtoolbar {
2286
2286
  display: none;
2287
2287
  border-radius: 20px;
2288
2288
  background-color: #333;
2289
+ color: white;
2289
2290
  color-scheme: dark;
2290
2291
  padding: 2px;
2291
2292
  overflow: hidden;
2292
- transition: border-radius 0.2s;
2293
+ opacity: 1;
2294
+ transition: border-radius 0.2s, opacity 0.2s;
2295
+ }
2296
+ @starting-style {
2297
+ .br-select-menu__root {
2298
+ opacity: 0;
2299
+ }
2300
+ }
2301
+
2302
+ .br-select-menu__root--scrolling {
2303
+ opacity: 0;
2304
+ pointer-events: none;
2293
2305
  }
2294
2306
 
2295
2307
  .br-select-menu__root:hover {
@@ -2309,6 +2321,7 @@ ia-bookreader .BRtoolbar {
2309
2321
  align-items: center;
2310
2322
  border-radius: 20px;
2311
2323
  font-family: inherit;
2324
+ color: inherit;
2312
2325
  border: 0;
2313
2326
  transition: background-color 0.2s, border-radius 0.2s;
2314
2327
  cursor: pointer;
@@ -2328,28 +2341,39 @@ ia-bookreader .BRtoolbar {
2328
2341
  }
2329
2342
 
2330
2343
  .br-select-menu__label {
2331
- width: 0px;
2332
- opacity: 0;
2333
- interpolate-size: allow-keywords;
2334
- transition: width 0.2s;
2344
+ margin-left: 4px;
2335
2345
  font-size: 12px;
2336
2346
  }
2337
2347
 
2338
- .br-select-menu__root:hover .br-select-menu__label {
2339
- width: auto;
2340
- margin-left: 4px;
2341
- opacity: 1;
2348
+ @media (hover: hover) {
2349
+ .br-select-menu__label {
2350
+ width: 0px;
2351
+ margin-left: 0;
2352
+ opacity: 0;
2353
+ interpolate-size: allow-keywords;
2354
+ transition: width 0.2s;
2355
+ }
2356
+ .br-select-menu__root:hover .br-select-menu__label {
2357
+ width: auto;
2358
+ margin-left: 4px;
2359
+ opacity: 1;
2360
+ }
2342
2361
  }
2343
-
2344
2362
  .BRtextLayer .BRhighlight {
2345
2363
  background-color: yellow;
2346
2364
  pointer-events: all;
2347
2365
  color: transparent;
2348
2366
  }
2349
2367
 
2368
+ @keyframes highlightTargetFlash {
2369
+ to {
2370
+ background-color: hsl(45, 80%, 66%);
2371
+ }
2372
+ }
2350
2373
  .BRtextLayer .BRhighlight--target-text, .BRtextLayer ::target-text {
2351
2374
  background-color: hsla(45, 80%, 66%, 0.6);
2352
2375
  color: transparent;
2376
+ animation: highlightTargetFlash 600ms 1 reverse;
2353
2377
  }
2354
2378
 
2355
2379
  /**