dynamsoft-barcode-reader-bundle
Version:
Dynamsoft Barcode Reader JS is a recognition SDK which enables you to embed barcode reading functionality in your web, desktop, and mobile applications. With a few lines of JavaScript code, you can develop a robust application to scan a linear barcode, QR
12 lines (11 loc) • 16.3 kB
JavaScript
/*!
* Dynamsoft JavaScript Library
* @product Dynamsoft Barcode Reader JS Edition Bundle
* @website http://www.dynamsoft.com
* @copyright Copyright 2025, Dynamsoft Corporation
* @author Dynamsoft
* @version 10.5.3000
* @fileoverview Dynamsoft JavaScript Library for Barcode Reader
* More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/
*/
import{CoreModule as e,EnumCapturedResultItemType as t,_toCanvas as i,EnumImagePixelFormat as s}from"dynamsoft-core";export*from"dynamsoft-core";import{CaptureVisionRouter as n,CapturedResultReceiver as o}from"dynamsoft-capture-vision-router";export*from"dynamsoft-capture-vision-router";import{CameraView as r,CameraEnhancer as a}from"dynamsoft-camera-enhancer";export*from"dynamsoft-camera-enhancer";import{LicenseManager as c}from"dynamsoft-license";export*from"dynamsoft-license";import{MultiFrameResultCrossFilter as l}from"dynamsoft-utility";export*from"dynamsoft-utility";export*from"dynamsoft-barcode-reader";function d(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)}function u(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i}"function"==typeof SuppressedError&&SuppressedError;const h="undefined"==typeof self,f="function"==typeof importScripts,m=(()=>{if(!f){if(!h&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"}})(),g=e=>{if(null==e&&(e="./"),h||f);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e};var p,y,w;!function(e){e[e.SM_SINGLE=0]="SM_SINGLE",e[e.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE"}(p||(p={})),function(e){e[e.OM_NONE=0]="OM_NONE",e[e.OM_SPEED=1]="OM_SPEED",e[e.OM_COVERAGE=2]="OM_COVERAGE",e[e.OM_BALANCE=3]="OM_BALANCE",e[e.OM_DPM=4]="OM_DPM",e[e.OM_DENSE=5]="OM_DENSE"}(y||(y={})),function(e){e[e.RS_SUCCESS=0]="RS_SUCCESS",e[e.RS_CANCELLED=1]="RS_CANCELLED",e[e.RS_FAILED=2]="RS_FAILED"}(w||(w={}));var S={license:"",scanMode:p.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadSingleBarcode",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:{rootDirectory:m},barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:!1,showUploadImageButton:!1,removePoweredByMessage:!1,uiPath:m,scannerViewConfig:{container:void 0,showCloseButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const _=e=>e&&"object"==typeof e&&"function"==typeof e.then,b=(async()=>{})().constructor;class E extends b{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,_(e)?t=e:"function"==typeof e&&(t=new b(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let t,i;super(((e,s)=>{t=e,i=s})),this._s="pending",this.resolve=e=>{this.isPending&&(_(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}}const v=()=>window.matchMedia("(orientation: landscape)").matches;function R(e,t){for(const s in t)"Object"===(i=t[s],Object.prototype.toString.call(i).slice(8,-1))&&s in e?R(e[s],t[s]):e[s]=t[s];var i;return e}var C,I,x,M,N,q,L,T,O,A,V,B,k,D,F,P,U,j,G,H,W;class z{constructor(e){if(C.add(this),M.set(this,void 0),N.set(this,{status:{code:w.RS_SUCCESS,message:"Success."},barcodeResults:[]}),q.set(this,!1),L.set(this,void 0),T.set(this,void 0),this.config=S,e&&"object"!=typeof e||Array.isArray(e))throw"Invalid config.";R(this.config,e)}async launch(){if(d(this,q,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(d(z,I,"f",x)&&!d(z,I,"f",x).isFulfilled)throw new Error("Cannot call `launch()` while a previous task is still running.");return u(z,I,new E,"f",x),await d(this,C,"m",O).call(this),d(z,I,"f",x)}async decode(e,t="ReadBarcodes_Default"){return u(this,T,t,"f"),await d(this,C,"m",A).call(this,!0),this._cvRouter.capture(e,t)}dispose(){u(this,q,!0,"f"),d(z,I,"f",x)&&d(z,I,"f",x).isPending&&d(z,I,"f",x).resolve(d(this,N,"f")),this._cameraEnhancer?.dispose(),this._cameraView?.dispose(),this._cvRouter?.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",d(this,M,"f")),document.querySelector(".scanner-view-container")?.remove(),document.querySelector(".result-view-container")?.remove(),document.querySelector(".barcode-scanner-container")?.remove(),document.querySelector(".loading-page")?.remove()}}I=z,M=new WeakMap,N=new WeakMap,q=new WeakMap,L=new WeakMap,T=new WeakMap,C=new WeakSet,O=async function(){try{await d(this,C,"m",A).call(this);try{await this._cameraEnhancer.open()}catch(e){d(this,C,"m",W).call(this);document.querySelector(".no-camera-view").style.display="flex"}await this._cvRouter.startCapturing(d(this,T,"f"))}catch(e){d(this,N,"f").status={code:w.RS_FAILED,message:e.message||e},d(z,I,"f",x).reject(new Error(d(this,N,"f").status.message)),this.dispose()}finally{const e=document.querySelector(".loading-page");e&&(e.style.display="none")}},A=async function(t=!1){e.engineResourcePaths=this.config.engineResourcePaths,t||(this._cameraView=await r.createInstance(),this.config.scanMode===p.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),await d(this,C,"m",B).call(this)),await c.initLicense(this.config.license||"",{executeNow:!0}),this._cvRouter=this._cvRouter||await n.createInstance(),await d(this,C,"m",V).call(this,t),t||(this._cameraEnhancer=await a.createInstance(this._cameraView),this._cvRouter.setInput(this._cameraEnhancer),d(this,C,"m",k).call(this),await d(this,C,"m",D).call(this))},V=async function(e=!1){e||(this.config.scanMode===p.SM_SINGLE?u(this,T,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===p.SM_MULTI_UNIQUE&&u(this,T,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&await this._cvRouter.initSettings(this.config.templateFilePath);const i=await this._cvRouter.getSimplifiedSettings(d(this,T,"f"));e||this.config.scanMode!==p.SM_SINGLE||(i.capturedResultItemTypes=t.CRIT_ORIGINAL_IMAGE|t.CRIT_BARCODE);let s=this.config.barcodeFormats;if(s){Array.isArray(s)||(s=[s]),i.barcodeSettings.barcodeFormatIds=BigInt(0);for(let e=0;e<s.length;e++)i.barcodeSettings.barcodeFormatIds|=s[e]}if(await this._cvRouter.updateSettings(d(this,T,"f"),i),this.config.scanMode===p.SM_SINGLE){const e=await this._cvRouter.outputSettings("*");for(let t of e.CaptureVisionTemplates){const e=await this._cvRouter.getSimplifiedSettings(t.Name);e.barcodeSettings.expectedBarcodesCount=1,await this._cvRouter.updateSettings(t.Name,e)}}},B=async function(){const e=this.config.uiPath,t=e.endsWith("/")?g(e)+"barcode-scanner.ui.xml":g(e).slice(0,-1),i=await(async e=>{if("string"!=typeof e)throw new TypeError("Invalid url.");const t=await fetch(e);if(!t.ok)throw Error("Network Error: "+t.statusText);const i=await t.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const s=document.createElement("div");if(s.insertAdjacentHTML("beforeend",i),1===s.childElementCount&&s.firstChild instanceof HTMLTemplateElement)return s.firstChild.content;const n=new DocumentFragment;for(let e of s.children)n.append(e);return n})(t);i.querySelectorAll("style").forEach((e=>{document.head.appendChild(e.cloneNode(!0))})),u(this,L,i.querySelector(".result-item"),"f");const s=i.querySelector(".btn-clear");if(s&&(s.addEventListener("click",(()=>{d(this,N,"f").barcodeResults=[],d(this,C,"m",G).call(this)})),this.config?.resultViewConfig?.toolbarButtonsConfig?.clear)){const e=this.config.resultViewConfig.toolbarButtonsConfig.clear;s.style.display=e.isHidden?"none":"flex",s.className=e.className?e.className:"btn-clear",s.innerText=e.label?e.label:"Clear",e.isHidden&&(i.querySelector(".toolbar-btns").style.justifyContent="center")}const n=i.querySelector(".btn-done");if(n&&(n.addEventListener("click",(()=>{const e=document.querySelector(".loading-page");e&&"none"===getComputedStyle(e).display&&this.dispose()})),this.config?.resultViewConfig?.toolbarButtonsConfig?.done)){const e=this.config.resultViewConfig.toolbarButtonsConfig.done;n.style.display=e.isHidden?"none":"flex",n.className=e.className?e.className:"btn-done",n.innerText=e.label?e.label:"Done",e.isHidden&&(i.querySelector(".toolbar-btns").style.justifyContent="center")}const o=this.config?.scannerViewConfig?.showCloseButton;if(o){const e=i.querySelector(".btn-close");e&&(e.style.display="",e.addEventListener("click",(()=>{d(this,N,"f").barcodeResults=[],d(this,N,"f").status={code:w.RS_CANCELLED,message:"Cancelled."},this.dispose()})))}this.config.showUploadImageButton&&d(this,C,"m",W).call(this,i.querySelector(".btn-upload-image"));const r=this._cameraView.getUIElement();r.shadowRoot.querySelector(".dce-sel-camera").remove(),r.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const a=i.querySelector(".barcode-scanner-container");a.style.display=v()?"flex":"";const c=this.config.showResultView&&this.config.scanMode!==p.SM_SINGLE;let l;if(this.config.container?(a.style.position="relative",l=this.config.container):l=document.body,"string"==typeof l&&(l=document.querySelector(l),null===l))throw new Error("Failed to get the container");let h=this.config.scannerViewConfig.container;if("string"==typeof h&&(h=document.querySelector(h),null===h))throw new Error("Failed to get the container of the scanner view.");let f=this.config.resultViewConfig.container;if("string"==typeof f&&(f=document.querySelector(f),null===f))throw new Error("Failed to get the container of the result view.");const m=i.querySelector(".scanner-view-container"),y=i.querySelector(".result-view-container"),S=i.querySelector(".loading-page");m.append(S),h&&(m.append(r),h.append(m)),f&&f.append(y),h||f?h&&!f?(this.config.container||(y.style.position="absolute"),f=y,l.append(y)):!h&&f&&(this.config.container||(m.style.position="absolute"),h=m,m.append(r),l.append(m)):(h=m,f=y,c&&(Object.assign(m.style,{width:v()?"50%":"100%",height:v()?"100%":"50%"}),Object.assign(y.style,{width:v()?"50%":"100%",height:v()?"100%":"50%"})),m.append(r),l.append(a)),document.querySelector(".result-view-container").style.display=c?"":"none",this.config.removePoweredByMessage&&(r.shadowRoot.querySelector(".dce-msg-poweredby").style.display="none",document.querySelector(".no-result-svg").style.display="none"),u(this,M,(()=>{Object.assign(a.style,{display:v()?"flex":""}),!c||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(h.style,{width:v()?"50%":"100%",height:v()?"100%":"50%"}),Object.assign(f.style,{width:v()?"50%":"100%",height:v()?"100%":"50%"}))}),"f"),window.addEventListener("resize",d(this,M,"f")),this._cameraView._createDrawingLayer(2)},k=function(){const e=new o;let t=0;e.onCapturedResultReceived=async e=>{e.barcodeResultItems&&(this.config.scanMode===p.SM_SINGLE?2==++t&&d(this,C,"m",F).call(this,e):d(this,C,"m",P).call(this,e))},this._cvRouter.addResultReceiver(e)},D=async function(){const e=new l;e.enableResultCrossVerification(2,!0),e.enableResultDeduplication(2,!0),e.setDuplicateForgetTime(2,this.config.duplicateForgetTime),e.onDecodedBarcodesReceived=()=>{},await this._cvRouter.addResultFilter(e)},F=function(e){const n=this._cameraView.getUIElement().shadowRoot;new Promise((t=>{if(e.barcodeResultItems.length>1){d(this,C,"m",j).call(this);for(let i of e.barcodeResultItems){let e=0,s=0;for(let t=0;t<4;++t){let n=i.location.points[t];e+=n.x,s+=n.y}let o=this._cameraEnhancer.convertToClientCoordinates({x:e/4,y:s/4}),r=document.createElement("div");r.className="single-barcode-result-option",Object.assign(r.style,{position:"fixed",width:"32px",height:"32px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),r.style.left=o.x+"px",r.style.top=o.y+"px",r.addEventListener("click",(()=>{t(i)})),n.append(r)}}else t(e.barcodeResultItems[0])})).then((n=>{const o=e.items.filter((e=>e.type===t.CRIT_ORIGINAL_IMAGE))[0].imageData,r={status:{code:w.RS_SUCCESS,message:"Success."},originalImageResult:o,barcodeImage:(()=>{const e=i(o),t=n.location.points,r=Math.min(...t.map((e=>e.x))),a=Math.min(...t.map((e=>e.y))),c=Math.max(...t.map((e=>e.x)))-r,l=Math.max(...t.map((e=>e.y)))-a,d=document.createElement("canvas");d.width=c,d.height=l;const u=d.getContext("2d");u.beginPath(),u.moveTo(t[0].x-r,t[0].y-a);for(let e=1;e<t.length;e++)u.lineTo(t[e].x-r,t[e].y-a);u.closePath(),u.clip(),u.drawImage(e,-r,-a);const h=u.getImageData(0,0,d.width,d.height);return{bytes:new Uint8Array(h.data),width:h.width,height:h.height,stride:4*h.width,format:s.IPF_ARGB_8888}})(),barcodeResults:[n]};d(z,I,"f",x).resolve(r),this.dispose()}))},P=function(e){const t=[...document.querySelectorAll(".main-list .result-item")];for(let i of e.barcodeResultItems){if(!1!==i.duplicate)continue;const e=t.findIndex((e=>e.id===`${i.formatString}_${i.text}`));-1===e?(i.count=1,d(this,N,"f").barcodeResults.unshift(i),d(this,C,"m",G).call(this,i)):(d(this,N,"f").barcodeResults[e].count++,d(this,C,"m",H).call(this,e)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(i)}},U=function(e){const t=d(this,L,"f").cloneNode(!0);t.querySelector(".format-string").innerText=e.formatString;t.querySelector(".text-string").innerText=e.text.replace(/\n|\r/g,""),t.id=`${e.formatString}_${e.text}`;return t.querySelector(".delete-icon").addEventListener("click",(()=>{const t=[...document.querySelectorAll(".main-list .result-item")],i=t.findIndex((t=>t.id===`${e.formatString}_${e.text}`));d(this,N,"f").barcodeResults.splice(i,1),t[i].remove()})),t},j=function(){const e=this._cameraView.getUIElement().shadowRoot;if(e.querySelector(".single-mode-mask"))return;const t=document.createElement("div");t.className="single-mode-mask",Object.assign(t.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),e.append(t),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},G=function(e){const t=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==p.SM_SINGLE))return;const i=document.querySelector(".main-list");if(!e)return i.textContent="",void(t.style.display="");t.style.display="none";const s=d(this,C,"m",U).call(this,e);i.insertBefore(s,document.querySelector(".result-item"))},H=function(e){const t=document.querySelectorAll(".main-list .result-item"),i=t[e].querySelector(".result-count");let s=parseInt(i.textContent.replace("x",""));t[e].querySelector(".result-count").textContent="x"+ ++s},W=function(e){e||(e=document.querySelector(".btn-upload-image")),e&&(e.style.display="",e.addEventListener("change",(async e=>{const t=e.target.files,i={status:{code:w.RS_SUCCESS,message:"Success."},barcodeResults:[]};for(let e of t)try{const t=await this.decode(e,this.config.utilizedTemplateNames.image);t.barcodeResultItems&&i.barcodeResults.push(...t.barcodeResultItems)}catch(e){i.status={code:w.RS_FAILED,message:e.message||e},d(z,I,"f",x).reject(i.status.message),this.dispose()}d(z,I,"f",x).resolve(i),this.dispose()})))},x={value:null},n._defaultTemplate="ReadSingleBarcode";export{z as BarcodeScanner,y as EnumOptimizationMode,w as EnumResultStatus,p as EnumScanMode};