Git Product home page Git Product logo

zbar-wasm's Introduction

A WebAssembly build of the ZBar Bar Code Reader

Open issues Vulnerabilities Total downloads Hits/month License

This project was forked from ZBar.wasm, a WebAssembly build of the ZBar Bar Code Reader written in C/C++.

Features

  • Provided as minified ES module, CommonJS module and plain script
  • Runs in modern browsers, in Node.js and also in workers
  • Deployment size approx. 330 kByte
  • Supports Code-39, Code-93, Code-128, Codabar, Databar/Expanded, EAN/GTIN-5/8/13, ISBN-10/13, ISBN-13+2, ISBN-13+5, ITF (Interleaved 2 of 5), QR Code, UPC-A/E.
  • Detects multiple barcodes per frame, also with different types
  • Barcodes may be oriented horizontally or vertically
  • Scans ImageData and RGB/grayscale ArrayBuffer objects
  • Outperforms pure JavaScript barcode scanners

⚠️ zbar-wasm versions 0.10 and above contain breaking changes with respect to version 0.9, please refer to section Bundling/deploying zbar-wasm.

Examples based on zbar-wasm

Getting started

Using zbar-wasm as <script type="module">

An example that scans a static image file:

<!DOCTYPE html>
<html>
<body>
  <img id="img" crossorigin="anonymous" src="https://raw.githubusercontent.com/undecaf/zbar-wasm/master/tests/img/qr_code.png">
  <pre id="result"></pre>

  <script type="module">
    import * as zbarWasm from 'https://cdn.jsdelivr.net/npm/@undecaf/[email protected]/dist/index.js'

    (async () => {
      const
        img = document.getElementById('img'),
        result = document.getElementById('result'),
        canvas = document.createElement('canvas'),
        context = canvas.getContext('2d');

      await img.decode()
      canvas.width = img.naturalWidth
      canvas.height = img.naturalHeight
      context.drawImage(img, 0, 0)

      const
        imageData = context.getImageData(0, 0, canvas.width, canvas.height),
        symbols = await zbarWasm.scanImageData(imageData);
      
      symbols.forEach(s => s.rawData = s.decode())
      result.innerText = JSON.stringify(symbols, null, 2)
    })()
  </script>
</body>
</html>

Using zbar-wasm as plain <script>

Almost identical to the snippet above, just replace the lines

<script type="module">
    import * as zbarWasm from 'https://cdn.jsdelivr.net/npm/@undecaf/[email protected]/dist/index.js'
    ⁝

with

<script src="https://cdn.jsdelivr.net/npm/@undecaf/[email protected]/dist/index.js"></script>
  <script>

Using zbar-wasm as an ESM or CommonJS module in Node.js

Installing:

$ npm install @undecaf/[email protected]
    or
$ yarn add @undecaf/[email protected]

Using:

import ... from '@undecaf/zbar-wasm' pulls the ES module from the package, require('@undecaf/zbar-wasm') pulls the CommonJS module.

Please refer to the API documentation for what can be imported/required.

A simple ES module that scans a static image file:

import { createCanvas, loadImage }  from 'canvas';
import { scanImageData } from '@undecaf/zbar-wasm';

(async (url) => {
  const
          img = await loadImage(url),
          canvas = createCanvas(img.width, img.height),
          ctx = canvas.getContext('2d');

  ctx.drawImage(img, 0, 0)

  const
          imageData = ctx.getImageData(0, 0, img.width, img.height),
          symbols = await scanImageData(imageData);

  console.log(symbols[0]?.typeName, symbols[0]?.decode())
})('https://raw.githubusercontent.com/undecaf/zbar-wasm/master/tests/img/qr_code.png')

For a CommonJS module, just replace the first lines with

const { createCanvas, loadImage } = require('canvas');
const { scanImageData } = require('@undecaf/zbar-wasm');

Bundling/deploying zbar-wasm

Barcode scanning is always delegated to the WebAssembly code in file zbar.wasm. zbar-wasm provides various functionally equivalent ESM and CommonJS modules for Node.js and for browsers that differ in how zbar.wasm is to be provided at runtime:

  • zbar.wasm can be loaded from a CDN by browsers.
  • zbar.wasm can be bundled as an asset. That asset should be served to browsers as application/wasm so that it can be compiled in parallel with being received.
  • Several zbar-wasm modules contain zbar.wasm as inline data.

The following overview shows the modules that are available in zbar-wasm. One of them needs to be bundled in your application.

Path in package Module type Node core modules polyfilled
(suitable for browsers)
zbar.wasm inlined
/dist/index.mjs ESM ✔️
/dist/index.js CommonJS ✔️
/dist/main.mjs ESM
/dist/main.cjs CommonJS
/dist/inlined/index.mjs ESM ✔️ ✔️
/dist/inlined/index.js CommonJS ✔️ ✔️
/dist/inlined/main.mjs ESM ✔️
/dist/inlined/main.cjs CommonJS ✔️

The package entry points of zbar-wasm have been chosen so that bundlers will emit the appropriate module by default in most cases. However, zbar.wasm as inline data requires a suitable export condition in the bundler configuration, typically 'zbar-inlined'. Please refer to the exports section of package.json for details.

Building zbar-wasm includes testing the bundling process with Webpack, Rollup and esbuild and also testing the resulting bundles. The bundler configuration files tests/{webpack,rollup,esbuild}.config.js may be used as a reference of how to achieve a particular bundling result. Each of them covers the following combinations of platforms, module types and zbar.wasm provisioning for the respective bundler:

zbar.wasm Node module types Browser module types
loaded from CDN ESM, plain <script>
bundled as asset ESM, CommonJS ESM
inlined in module ESM, CommonJS ESM, plain <script>

Loading zbar.wasm from a custom location

As a last resort, if you cannot make your bundler place zbar.wasm where it can be located by the script, you can specify an URL or path for that WASM file at runtime:

import { scanImageData, setModuleArgs } from '@undecaf/zbar-wasm';
    
// Call this function once at the beginning
setModuleArgs({
  /**
   * This function must return the URL or path of the WASM file.
   * 
   * @param filename default WASM filename ('zbar.wasm')
   * @param directory default WASM directory (URL or directory of the current script)
   * @returns {string} URL or path of the WASM file
   */
  locateFile: (filename, directory) => {
      return 'file:///your/wasm/directory/zbar.wasm'
  }   
});
    
// Then use the scanner
const symbols = await scanImageData(...);

API documentation

Owing to the predecessor of this project, samsam2310/zbar.wasm, a wiki and an extensive API Reference are already available. Many thanks to the author!

Please note that a few classes have been renamed compared to the documentation in order to avoid conflicts with built-in JavaScript class names:

  • SymbolZBarSymbol
  • ImageZBarImage
  • ImageScannerZBarScanner

The BarcodeDetector polyfill package (in this repository, by the same author) is based on zbar-wasm but provides a standardized, higher-level and more flexible API.

Building zbar-wasm from source

Prerequisites:

To build:

  • Clone this repository:
    $ git clone https://github.com/undecaf/zbar-wasm
    $ cd zbar-wasm
  • Enter your browser(s) in .testcaferc.json (supported browsers).
  • Enter two available port numbers in tests/src/ports.js.
  • If you prefer Docker over Podman as container engine then replace
    EM_ENGINE = $(EM_PODMAN)
    
    with
    EM_ENGINE = $(EM_DOCKER)
    
    in the provided Makefile.
  • Run the build process:
    $ make
    The make command runs emscripten in a container, compiling the C/C++ sources of the ZBar Bar Code Reader to WebAssembly. It also compiles and bundles the TypeScript glue code and runs the tests in Node.js and in the selected browser(s) on the host machine.

Credits to ...

License

Software: LGPL-2.1

Documentation: CC-BY-SA 4.0

zbar-wasm's People

Contributors

davidebriscese avatar lost-valley avatar lross2k avatar undecaf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

zbar-wasm's Issues

after 15 june this package giving an error

'Error: Corrupted zip: missing 48 bytes.\n at ZipEntries.readEndOfCentral (D:\codebase\iona\onboarding-dbmodel\node_modules\jszip\lib\zipEntries.js:243:19)\n at ZipEntries.load (D:\codebase\iona\onboarding-dbmodel\node_modules\jszip\lib\zipEntries.js:255:14)\n at D:\codebase\iona\onboarding-dbmodel\node_modules\jszip\lib\load.js:48:24'

loading zbar-wasm as ES module fails in Node

I am using it like this:

import { createCanvas, loadImage } from 'canvas';
import { scanImageData } from '@undecaf/zbar-wasm';

const getImageData = async (src) => {
  const img = await loadImage(src);
  const canvas = createCanvas(img.width, img.height);
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);
  return ctx.getImageData(0, 0, img.width, img.height);
};

const url = 'src/IMG_3361.jpg';
const main = async () => {
  const img = await getImageData(url);
  const res = await scanImageData(img);
  console.log(res[0]?.typeName);
  console.log(res[0]);
  console.log(res[0]?.decode());
};

main();

and getting

TypeError: t is not a function at n (file:///Users/Projects/scna/node_modules/@undecaf/zbar-wasm/dist/main.js:15:706)

[BUG] library not being recognized/provided by vite

Describe the bug

I created react project with vite typescript.
My problem's is using the library @undecaf/zbar-wasm.

BarcodeScanner.jsx

import { scanImageData } from "@undecaf/zbar-wasm"

const scanBarcode = useCallback(async () => {

                const context = canvasRef.current.getContext("2d")
		context.drawImage(videoRef.current, 0, 0, canvasRef.current.width, canvasRef.current.height)
		const imageData = context.getImageData(0, 0, canvasRef.current.width, canvasRef.current.height)
		try {

			const symbols = await scanImageData(imageData)
			if (symbols.length > 0) {
				const barcode = symbols[0].decode()
				const quality = symbols[0].quality
				updateScannedBarcodes(barcode, quality)
			}
		} catch (err) {
			console.error("Error scanning image data:", err)
		}
	}, [updateScannedBarcodes, isScanning])
[...]

My vite.config.ts

import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"
import path from "path"

export default defineConfig({
	plugins: [
		react(),
	],
	resolve: {
		alias: {
			src: path.resolve(__dirname, "src"),
		},
	},
	server: {
		port: 3000,
	},
	assetsInclude: ['**/*.wasm'],
});

Errors

wasm streaming compile failed: TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.
(anonymous) @ @undecaf_zbar-wasm.js?v=fd05e335:210
Promise.then (async)

failed to asynchronously prepare wasm: CompileError: WebAssembly.instantiate(): expected magic word 00 61 73 6d, found 3c 21 44 4f @+0

Error scanning image data: RuntimeError: Aborted(CompileError: WebAssembly.instantiate(): expected magic word 00 61 73 6d, found 3c 21 44 4f @+0). Build with -sASSERTIONS for more info.
    at P (@undecaf_zbar-wasm.js?v=fd05e335:70:14)
    at @undecaf_zbar-wasm.js?v=fd05e335:103:59

In my investigation I learned that vite does not provide .wasm .

Screenshot from 2024-05-28 18-41-33

My solution for the problem, which is not the preferred:

import { scanImageData, setModuleArgs } from "@undecaf/zbar-wasm"

setModuleArgs({
	locateFile: (filename) => `https://cdn.jsdelivr.net/npm/@undecaf/[email protected]/dist/${filename}`
})

The .wasm is provided this way, but not through the library loader :

Screenshot from 2024-05-28 18-54-20

[BUG] WebAssembly.Module doesn't parse at byte 1227: invalid opcode 192, in function at index 28

Describe the bug

On Ipad safari the webassembly script fails to compile due to the following error:

failed to asynchronously prepare wasm: CompileError: WebAssembly.Module doesn't parse at byte 1227: invalid opcode 192, in function at index 28

To Reproduce

Opening the example on an ipad and uploading an image file of a barcode https://undecaf.github.io/zbar-wasm/example/ will result in "Source not ready" with the specified error above.

Or else the environment in which the behavior occurs needs to be specified:

  • Which target environment (Node/browser/other)? IOS Safari (on Iphone/Ipad, Macbook works fine)
  • Which type of modules (ESM/CommonJS/other)? CommonJS Version 0.10.1, 0.9.16, 0.9.15, 0.9.14

[BUG] Combined scan symbol type not recognized

Describe the bug

The disable all but one symbol code sample on wiki works, but when flags are combined like zsType.ZBAR_CODE128 | zsType.ZBAR_EAN13, zsType.ZBAR_CODE128|zsType.ZBAR_QRCODE, no code can be detected.

To Reproduce

var scanner = zbarWasm.getDefaultScanner().then(_scanner => window.scanner = _scanner );
...
var zsType = zbarWasm.ZBarSymbolType;
var zcType = zbarWasm.ZBarConfigType;
var useBarcode = true;
scanner.setConfig(zsType.ZBAR_NONE, zcType.ZBAR_CFG_ENABLE, 0);
var zsTypeSet = useBarcode ?
    zsType.ZBAR_CODE128 | zsType.ZBAR_EAN13 //|zsType.ZBAR_QRCODE
    : 
    zsType.ZBAR_QRCODE
    ;
scanner.setConfig( zsTypeSet, zcType.ZBAR_CFG_ENABLE, 1);
...
let symbols = await zbarWasm.scanImageData(imageData, scanner);

Expected behavior
Should be able to scan only the combined types CODE128+EN13 etc.

How to bundle zbar.wasm in a module project?

I develop capacitor-community/barcode-scanner and want to make it support off-line, so zbar.wasm needs to be included.

I successfully included it in a dist of this module:

  plugins: [
    copy({
      targets: [
        { src: 'node_modules/@undecaf/zbar-wasm/dist/zbar.wasm', dest: 'dist' },
      ]
    })
  ],

But when I use barcode-scanner in my project (npm i "@capacitor-community/barcode-scanner@../barcode-scanner" for local development) and build it, resulting dist does not include zbar.wasm file.

I checked example-bundled, but this seems not intended for use in the module project (and also it is for old rollup 2).

Or it is really necessary to ask module's users to bundle zbar.wasm themself? How to make zbar-wasm to require it correctly then?

Thank you for your help.

Paused when failed to detect unsupported code type.

https://output.jsbin.com/nidonin
Please try my live sample based on zbar.wasm, which will detecting QR or other supported code types continuously. Just open it on your iPhone or Android phone then point & shoot. It outperforms other pure JavaScript QR detection libraries.

But sometime my live sample stops to detect from new video feed, even once it recognized correctly just seconds ago. I figured out one pattern to reproduce this bug:

  1. Point to some supported QR code/Barcode, worked fine to recognize all of them continuously.
  2. Include some unspported barcode in video feed, suddently it stops to recognize any more.
  3. (Sometime it seems that a failed try on supported code type will also cause consequent failure).
  4. (Misleading in title: not pause of live sample, but once worked well, sometime suddently stop to recognize from further new video feed. Reload will restart recognition again. Is it any way to recycle/recover consequent detection programtically?)

From https://github.com/mebjas/html5-qrcode, I printed out many different types of QR code and Barcode for testing.

image

[BUG] Not able to scan the barcode of this image using this library, however able to scan it with the phone app

Describe the bug

Not able to detect barcodes in certain cases like in the image attached, while it is completely working barcode and tried to scan the same with some online barcode readers and with my phone both worked fine.

To Reproduce

  1. Open demo website -> https://undecaf.github.io/zbar-wasm/example/
  2. and scan this below image with the barcode
    2024-04-15_14-37

A minimal working example that reproduces the behavior would be much appreciated.

Or else the environment in which the behavior occurs needs to be specified:

  • Which target environment (Node/browser/other)?
  • Browser
  • Which type of modules (ESM/CommonJS/other)?
  • Which framework(s)?
  • Which devtools, including their configuration files?
  • package.json content
  • Any other context about the problem

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

[BUG] On IOS Safari Iphone 12 - after background/sleep mode reactivation changes camera to fisheye

Describe the bug

When using the example on IOS Safari Iphone 12 initially the default hi-res rear camera is used. Leaving the web scanner on in background causes a different camera (fisheye) to be selected. Making scanning nearly impossible.

To Reproduce

Visit demo through Github

  • Put browser in background by flicking it out of screen (slide finger from bottom of screen to top)
  • Turn off screen with button on right side of iphone
  • Wait 10 seconds
  • Turn on screen
  • Put browser in foreground

Expected behavior

Expected behaviour would be to have the same camera active after returning from background/sleep.

Screenshots

Initial Cam Cam after BG

big images cannot be scanned succesfully, in the first attempt.

Hello, I am trying different images with the codepen demo site, but have a problem.
Files of very big images (40-50 MP) are returning with no results '[ ]', in the first try.

Same image, second attempt from same file, all is well, all qrcodes are correctly identified. If I resize down to something around 2000px width, instant result comes, no problems even in the first attempt with that file.

What might be causing this ?

Configure custom ZBarScanner instance

scanImageData, scanGrayBuffer, scanRGBABuffer all can take ZBarScanner as last argument. Is it possible to create custom ZBarScanner that looks only for QR codes? The idea is to get performance gain in situations where we don't need to support all barcode types.

TypeError: Failed to construct 'URL': Invalid URL

I am encountering the following error trying to integrate zbar-wasm in a Quasar + Vite project:

main.js:15  Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL
    at n (main.js:15:3357)
    at main.js:15:7714
    at Generator.next (<anonymous>)
    at main.js:15:283
    at new Promise (<anonymous>)
    at t (main.js:15:28)
    at main.js:15:7667

Please Help : Why i show this error when i tray import the package in Angular 16

iwhen i call import { scanImageData } from '@undecaf/zbar-wasm'; and use return scanImageData(imageData)
.then(symbols => { ...
I show this error, how can fixe that please
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Not allowed to load local resource: file:///D://node_modules/@undecaf/zbar-wasm/dist/zbar.wasm
Aborted([object ProgressEvent]). Build with -sASSERTIONS for more info.
RuntimeError: Aborted([object ProgressEvent]). Build with -sASSERTIONS for more info.
bug

Feature Suggestion: Allow Passing the Zbar Instance

Overview


I really appreciate all the documentation put into the bundles of ZBar, but the process is quite difficult still. I was wondering. Would be possible to pass the Zbar Instance to the library.

The benefits of this would be great considering the additional complexity it would add. Namely, it would allow the application to decide how the WASM in bundled and deployed into the application. It would put less work in trying to work around the tooling failings in currents stacks.

Looking over the code, I noticed the instance function could probably be easily modified to accommodate this. Some factory function or user config would need to be assed to propagate to it here though.

export const getInstance = async (customLoader?: () => Promise<ZBarInstance>): Promise<ZBarInstance> => {
  if (customLoader) {
     return await customLoader();
  }
    
  return await zbarInstancePromise
}

Side node

For better encapsulation, you can refactor the zbarInstancePromise function to something like below (hard to type code in comments). This is pure suggestion and can be completely ignored.

let zbarInstance: ZBarInstance

const zbarInstancePromise = (() => {
  let zbarInstance: ZBarInstance

  const instancePromise = async () => {
    zbarInstance = await zbarJs()
    if (!zbarInstance) {
      throw Error('WASM was not loaded')
    }
    return zbarInstance
  };
  
  return instancePromise
})()

Build fails when using in Next.js App directory router.

Describe the bug

Hello! I fail to build when trying to use this library within the Next.JS app directory router. I tried several methods like dynamic import, but none worked. Also, it works with npm run dev.
Thank you.
Next.js 14.0.2

To Reproduce
using node v20.8.0 (npm v10.1.0)
npx create-next-app@latest
** default settings ***
overwrite
src/app/page.tsx
as

'use client'
import { scanImageData } from "@undecaf/zbar-wasm";

export default function Home() {
  scanImageData(new ImageData(1, 1));
  return (
    <></>
  )
}

overwrite
next.config.ts
as

/** @type {import('next').NextConfig} */

const nextConfig = {
    transpilePackages: ['@undecaf/zbar-wasm'],
}

module.exports = nextConfig

and
npm run build

error message

Failed to compile.

static/media/index.33c29f02.mjs from Terser
  x 'import.meta' cannot be used outside of module code.
    ,-[24:1]
 24 |     });
 25 | }
 26 | "function" == typeof SuppressedError && SuppressedError;
 27 | var e, r = (e = import.meta.url, async function() {
    :                 ^^^^^^^^^^^
 28 |     let t = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
 29 |     var r, n, i = t;
 30 |     i.ready = new Promise((t, e)=>{
    `----

  x 'import.meta' cannot be used outside of module code.
    ,-[33:1]
 33 |     var o, s, a, c = Object.assign({}, i), _ = "object" == "object", u = "function" == typeof importScripts, A = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, f = "";
 34 |     if (A) {
 35 |         const { createRequire: t } = await Promise.resolve().then(()=>g);
 36 |         var h = t(import.meta.url), l = h("fs"), R = h("path");
    :                   ^^^^^^^^^^^
 37 |         f = u ? R.dirname(f) + "/" : h("url").fileURLToPath(new URL("./", import.meta.url)), o = (t, e)=>(t = U(t) ? new URL(t) : R.normalize(t), l.readFileSync(t, e ? void 0 : "utf8")), a = (t)=>{
 38 |             var e = o(t, !0);
 39 |             return e.buffer || (e = new Uint8Array(e)), e;
    `----

  x 'import.meta' cannot be used outside of module code.
    ,-[34:1]
 34 |     if (A) {
 35 |         const { createRequire: t } = await Promise.resolve().then(()=>g);
 36 |         var h = t(import.meta.url), l = h("fs"), R = h("path");
 37 |         f = u ? R.dirname(f) + "/" : h("url").fileURLToPath(new URL("./", import.meta.url)), o = (t, e)=>(t = U(t) ? new URL(t) : R.normalize(t), l.readFileSync(t, e ? void 0 : "utf8")), a = (t)=>{
    :                                                                           ^^^^^^^^^^^
 38 |             var e = o(t, !0);
 39 |             return e.buffer || (e = new Uint8Array(e)), e;
 40 |         }, s = function(t, e, r) {
    `----

  x 'import.meta' cannot be used outside of module code.
     ,-[98:1]
  98 |             B("failed to asynchronously prepare wasm: " + t), P(t);
  99 |         });
 100 |     }
 101 |     i.locateFile ? F(T = "zbar.wasm") || (O = T, T = i.locateFile ? i.locateFile(O, f) : f + O) : T = new URL("zbar.wasm", import.meta.url).href;
     :                                                                                                                            ^^^^^^^^^^^
 102 |     var L, M = (t)=>{
 103 |         for(; t.length > 0;)t.shift()(i);
 104 |     }, x = (t)=>{
     `----

  x 'import', and 'export' cannot be used outside of module code
     ,-[385:1]
 385 | }, Symbol.toStringTag, {
 386 |     value: "Module"
 387 | }));
 388 | export { a as ZBarConfigType, l as ZBarImage, c as ZBarOrientation, R as ZBarScanner, h as ZBarSymbol, s as ZBarSymbolType, d as getDefaultScanner, o as getInstance, y as scanGrayBuffer, E as scanImageData, B as scanRGBABuffer }; //# sourceMappingURL=index.mjs.map
     : ^^^^^^
     `----

Caused by:
    0: failed to parse input file
    1: Syntax Error
Error: 
  x 'import.meta' cannot be used outside of module code.
    ,-[24:1]
 24 |     });
 25 | }
 26 | "function" == typeof SuppressedError && SuppressedError;
 27 | var e, r = (e = import.meta.url, async function() {
    :                 ^^^^^^^^^^^
 28 |     let t = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
 29 |     var r, n, i = t;
 30 |     i.ready = new Promise((t, e)=>{
    `----

  x 'import.meta' cannot be used outside of module code.
    ,-[33:1]
 33 |     var o, s, a, c = Object.assign({}, i), _ = "object" == "object", u = "function" == typeof importScripts, A = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, f = "";
 34 |     if (A) {
 35 |         const { createRequire: t } = await Promise.resolve().then(()=>g);
 36 |         var h = t(import.meta.url), l = h("fs"), R = h("path");
    :                   ^^^^^^^^^^^
 37 |         f = u ? R.dirname(f) + "/" : h("url").fileURLToPath(new URL("./", import.meta.url)), o = (t, e)=>(t = U(t) ? new URL(t) : R.normalize(t), l.readFileSync(t, e ? void 0 : "utf8")), a = (t)=>{
 38 |             var e = o(t, !0);
 39 |             return e.buffer || (e = new Uint8Array(e)), e;
    `----

  x 'import.meta' cannot be used outside of module code.
    ,-[34:1]
 34 |     if (A) {
 35 |         const { createRequire: t } = await Promise.resolve().then(()=>g);
 36 |         var h = t(import.meta.url), l = h("fs"), R = h("path");
 37 |         f = u ? R.dirname(f) + "/" : h("url").fileURLToPath(new URL("./", import.meta.url)), o = (t, e)=>(t = U(t) ? new URL(t) : R.normalize(t), l.readFileSync(t, e ? void 0 : "utf8")), a = (t)=>{
    :                                                                           ^^^^^^^^^^^
 38 |             var e = o(t, !0);
 39 |             return e.buffer || (e = new Uint8Array(e)), e;
 40 |         }, s = function(t, e, r) {
    `----

  x 'import.meta' cannot be used outside of module code.
     ,-[98:1]
  98 |             B("failed to asynchronously prepare wasm: " + t), P(t);
  99 |         });
 100 |     }
 101 |     i.locateFile ? F(T = "zbar.wasm") || (O = T, T = i.locateFile ? i.locateFile(O, f) : f + O) : T = new URL("zbar.wasm", import.meta.url).href;
     :                                                                                                                            ^^^^^^^^^^^
 102 |     var L, M = (t)=>{
 103 |         for(; t.length > 0;)t.shift()(i);
 104 |     }, x = (t)=>{
     `----

  x 'import', and 'export' cannot be used outside of module code
     ,-[385:1]
 385 | }, Symbol.toStringTag, {
 386 |     value: "Module"
 387 | }));
 388 | export { a as ZBarConfigType, l as ZBarImage, c as ZBarOrientation, R as ZBarScanner, h as ZBarSymbol, s as ZBarSymbolType, d as getDefaultScanner, o as getInstance, y as scanGrayBuffer, E as scanImageData, B as scanRGBABuffer }; //# sourceMappingURL=index.mjs.map
     : ^^^^^^
     `----

Caused by:
    0: failed to parse input file
    1: Syntax Error


> Build failed because of webpack errors
   Creating an optimized production build  .%    

Or else the environment in which the behavior occurs needs to be specified:

  • Which target environment (Node/browser/other)?
  • Which type of modules (ESM/CommonJS/other)?
  • Which framework(s)?
  • Which devtools, including their configuration files?
  • package.json content
{
  "name": "test-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@undecaf/zbar-wasm": "^0.10.1",
    "next": "14.0.2",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.0.2",
    "postcss": "^8",
    "tailwindcss": "^3.3.0",
    "typescript": "^5"
  }
}
  • Any other context about the problem

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

[Enhancement] Allow specifying the URL of the WASM file

Describe the bug

I use Vite to build and bundle my project. In order to get the WASM file as a part of my build, I copy it to my site/ folder and it is treated as a static asset. When the imported code attempts to load the WASM file, it uses a path that is deeply nested, such as /.vite/deps/undecaf-zbar-wasm/zbar.wasm because the script is served from that location for development. In production, the file would be built into /assets/index-HASH.js, so it would look for /assets/zbar.wasm.

To Reproduce

I'm using Vite, TypeScript, and it appears that the ESM version is being used.

Expected behavior

Having a way to specify the URL to the WASM file would be ideal instead of having it automatically build a URL based on the imported file.

This is already done with zbar-wasi and I was hoping that something similar could be done with this build.

To work around this issue, I custom-compiled zbar-wasm's output to remove terser, then manually modified the path of "zbar.wasm" and changed it to "/zbar.wasm".

webpack error migrating from 0.9.15 -> 0.9.16

I get the following error with the latest version:

ERROR in ../../node_modules/@undecaf/zbar-wasm/dist/main.js 15:653-669
Module not found: Error: Can't resolve 'module' in '/myprj/node_modules/@undecaf/zbar-wasm/dist'
resolve 'module' in '/myprj/node_modules/@undecaf/zbar-wasm/dist'
  Parsed request is a module
  using description file: /myprj/node_modules/@undecaf/zbar-wasm/package.json (relative path: ./dist)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      looking for modules in /myprj/packages/sub-project/node_modules
        single file module
          using description file: /myprj/packages/sub-project/package.json (relative path: ./node_modules/module)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /myprj/packages/sub-project/node_modules/module doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /myprj/packages/sub-project/node_modules/module.js doesn't exist
        /myprj/packages/sub-project/node_modules/module doesn't exist
      looking for modules in /myprj/node_modules
        single file module
          using description file: /myprj/package.json (relative path: ./node_modules/module)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /myprj/node_modules/module doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /myprj/node_modules/module.js doesn't exist
        /myprj/node_modules/module doesn't exist
 @ ./out/file.js 1:0-51 14:22-35 21:22-35

webpack 5.88.2 compiled with 1 error in 1608 ms

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.