@octane-xplat/barcode-scanner 0.0.0-nightly.g52542a7

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 (36) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +27 -0
  3. package/package.json +98 -0
  4. package/platforms/android/AndroidManifest.xml +3 -0
  5. package/platforms/ios/Info.plist +8 -0
  6. package/src/BarcodeScanner.tsrx +102 -0
  7. package/src/BarcodeScanner.web.tsrx +116 -0
  8. package/src/barcode-scanner.linux.ts +2 -0
  9. package/src/barcode-scanner.macos.ts +12 -0
  10. package/src/barcode-scanner.ts +119 -0
  11. package/src/barcode-scanner.web.ts +56 -0
  12. package/src/barcode-scanner.windows.ts +11 -0
  13. package/src/format-map.ts +31 -0
  14. package/src/format-map.web.ts +30 -0
  15. package/src/index.macos.ts +3 -0
  16. package/src/index.ts +4 -0
  17. package/src/index.web.ts +4 -0
  18. package/src/native-elements.d.ts +8 -0
  19. package/src/props.ts +34 -0
  20. package/src/types.ts +41 -0
  21. package/types/generated/.tsrx-typegen-manifest.json +20 -0
  22. package/types/generated/BarcodeScanner.d.ts +4 -0
  23. package/types/generated/BarcodeScanner.web.d.ts +5 -0
  24. package/types/generated/barcode-scanner.d.ts +2 -0
  25. package/types/generated/barcode-scanner.linux.d.ts +1 -0
  26. package/types/generated/barcode-scanner.macos.d.ts +2 -0
  27. package/types/generated/barcode-scanner.web.d.ts +2 -0
  28. package/types/generated/barcode-scanner.windows.d.ts +2 -0
  29. package/types/generated/format-map.d.ts +4 -0
  30. package/types/generated/format-map.web.d.ts +3 -0
  31. package/types/generated/index.d.ts +4 -0
  32. package/types/generated/index.macos.d.ts +3 -0
  33. package/types/generated/index.web.d.ts +4 -0
  34. package/types/generated/native-elements.d.ts +8 -0
  35. package/types/generated/props.d.ts +38 -0
  36. package/types/generated/types.d.ts +29 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Alec Larson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,27 @@
1
+ # `@octane-xplat/barcode-scanner`
2
+
3
+ ```sh
4
+ pnpm add @octane-xplat/barcode-scanner
5
+ ```
6
+
7
+ Barcode and QR decoding — a live scanning view plus a headless still-image
8
+ decoder. ML Kit (`@nativescript/mlkit-core`) on iOS/Android, the
9
+ `BarcodeDetector` API on web. Decoding only: photo capture stays in
10
+ `@octane-xplat/camera`, gallery picking in `@octane-xplat/media`.
11
+
12
+ ```tsx
13
+ import { BarcodeScanner, barcodeScanner } from '@octane-xplat/barcode-scanner'
14
+
15
+ <BarcodeScanner
16
+ formats={['qr', 'ean13']}
17
+ onCodeScanned={({ type, data }) => openCode(data)}
18
+ torch={false}
19
+ />
20
+
21
+ // Still-image decode — no camera needed.
22
+ const codes = await barcodeScanner.scanImage(fileRef.uri, ['qr'])
23
+ ```
24
+
25
+ `barcodeScanner.ensure()` requests camera permission (registered as the
26
+ `'camera'` kind on the platform `permissions` seam). Web support depends on
27
+ `BarcodeDetector` — absent on Firefox; `supported` reflects it.
package/package.json ADDED
@@ -0,0 +1,98 @@
1
+ {
2
+ "name": "@octane-xplat/barcode-scanner",
3
+ "version": "0.0.0-nightly.g52542a7",
4
+ "description": "Barcode and QR scanning for Octane xplat — ML Kit camera preview + still decode on iOS/Android, BarcodeDetector on web",
5
+ "keywords": [
6
+ "android",
7
+ "cross-platform",
8
+ "nativescript",
9
+ "octane",
10
+ "xplat",
11
+ "barcode",
12
+ "qr",
13
+ "scanner",
14
+ "mlkit"
15
+ ],
16
+ "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/barcode-scanner",
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/octane-xplat/octane-xplat",
21
+ "directory": "packages/barcode-scanner"
22
+ },
23
+ "files": [
24
+ "src",
25
+ "platforms",
26
+ "types",
27
+ "!src/**/*.test.*",
28
+ "!src/**/*.spec.*"
29
+ ],
30
+ "type": "module",
31
+ "exports": {
32
+ ".": {
33
+ "macos": {
34
+ "types": "./types/generated/index.macos.d.ts",
35
+ "default": "./src/index.macos.ts"
36
+ },
37
+ "web": {
38
+ "types": "./types/generated/index.web.d.ts",
39
+ "default": "./src/index.web.ts"
40
+ },
41
+ "native": {
42
+ "types": "./types/generated/index.d.ts",
43
+ "default": "./src/index.ts"
44
+ },
45
+ "types": "./types/generated/index.d.ts",
46
+ "default": "./src/index.ts"
47
+ },
48
+ "./*": {
49
+ "types": "./types/generated/*.d.ts",
50
+ "default": "./src/*"
51
+ },
52
+ "./*.ts": {
53
+ "types": "./types/generated/*.d.ts",
54
+ "default": "./src/*.ts"
55
+ }
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "devDependencies": {
61
+ "@nativescript-community/octane": "0.2.5",
62
+ "@nativescript/core": "9.1.3",
63
+ "@nativescript/types": "9.1.4",
64
+ "@tsrx/typescript-plugin": "0.4.11",
65
+ "octane": "0.14.0",
66
+ "tsrx-typegen": "0.4.0",
67
+ "typescript": "5.9.3"
68
+ },
69
+ "peerDependencies": {
70
+ "@nativescript-community/octane": ">=0.2.1 <1",
71
+ "@nativescript/core": ">=9.1.0 <10",
72
+ "octane": ">=0.6.3 <1"
73
+ },
74
+ "peerDependenciesMeta": {
75
+ "@nativescript-community/octane": {
76
+ "optional": true
77
+ },
78
+ "@nativescript/core": {
79
+ "optional": true
80
+ }
81
+ },
82
+ "nativescript": {
83
+ "platforms": {
84
+ "android": "9.1.0",
85
+ "ios": "9.1.0"
86
+ }
87
+ },
88
+ "dependencies": {
89
+ "@nativescript/mlkit-barcode-scanning": "3.0.4",
90
+ "@nativescript/mlkit-core": "3.0.4",
91
+ "@octane-xplat/platform": "0.0.0-nightly.g52542a7"
92
+ },
93
+ "scripts": {
94
+ "typegen": "tsrx-typegen --target octane",
95
+ "pack:check": "tsrx-typegen --pack-check",
96
+ "typecheck": "node ../../scripts/typecheck.ts"
97
+ }
98
+ }
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.CAMERA" />
3
+ </manifest>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>NSCameraUsageDescription</key>
6
+ <string>Camera access is required to scan codes.</string>
7
+ </dict>
8
+ </plist>
@@ -0,0 +1,102 @@
1
+ /** @jsxImportSource @nativescript-community/octane */
2
+ import { useImperativeHandle, useCallback, useEffect, useRef } from 'octane'
3
+ import { isAndroid } from '@nativescript/core'
4
+ import { registerElement } from '@nativescript-community/octane'
5
+ import { CameraPosition, DetectionType, MLKitView } from '@nativescript/mlkit-core'
6
+ import type { BarcodeScannerHandle, BarcodeScannerProps } from './props'
7
+ import { fromNativeFormat, toNativeFormats } from './format-map'
8
+
9
+ registerElement('xplatbarcodescanner', MLKitView)
10
+
11
+ function applyEscapeProps(view: any, props: BarcodeScannerProps): void {
12
+ const bag = isAndroid ? props.android : props.ios
13
+ if (bag) {
14
+ Object.assign(view, bag)
15
+ }
16
+ }
17
+
18
+ /** Live barcode/QR scanner — ML Kit's camera preview with `detectionType:
19
+ * barcode`. Decoding only; photo capture stays in @octane-xplat/camera. */
20
+ export function BarcodeScanner(props: BarcodeScannerProps) @{
21
+ const host = useRef<MLKitView | null>(null)
22
+
23
+ const bindHost = useCallback((v: MLKitView | null) => {
24
+ host.current = v
25
+ }, [])
26
+
27
+ useImperativeHandle(
28
+ props.ref,
29
+ (): BarcodeScannerHandle => ({
30
+ setPaused: (paused) => {
31
+ if (host.current) {
32
+ host.current.pause = paused
33
+ }
34
+ },
35
+ toggleCamera: () => host.current?.toggleCamera(),
36
+ native: host.current?.nativeViewProtected ?? host.current,
37
+ }),
38
+ [],
39
+ )
40
+
41
+ // Mount wiring — listeners before any prop assignment.
42
+ useEffect(() => {
43
+ const v = host.current
44
+ if (!v) {
45
+ return
46
+ }
47
+ v.detectionType = DetectionType.Barcode
48
+ v.on(MLKitView.detectionEvent, (e: any) => {
49
+ const data = e?.data ?? e?.data?.data ?? e
50
+ const list = Array.isArray(data) ? data : [data]
51
+ for (const item of list) {
52
+ if (!item) {
53
+ continue
54
+ }
55
+ const bounds = item.bounds
56
+ props.onCodeScanned?.({
57
+ type: fromNativeFormat(item.format),
58
+ data: String(item.rawValue ?? item.displayValue ?? ''),
59
+ bounds: bounds
60
+ ? {
61
+ x: bounds.origin?.x ?? bounds.x ?? 0,
62
+ y: bounds.origin?.y ?? bounds.y ?? 0,
63
+ width: bounds.size?.width ?? bounds.width ?? 0,
64
+ height: bounds.size?.height ?? bounds.height ?? 0,
65
+ }
66
+ : undefined,
67
+ })
68
+ }
69
+ })
70
+ applyEscapeProps(v, props)
71
+ }, [])
72
+
73
+ useEffect(() => {
74
+ const v = host.current
75
+ if (v) {
76
+ v.barcodeFormats = toNativeFormats(props.formats)
77
+ }
78
+ }, [JSON.stringify(props.formats)])
79
+
80
+ useEffect(() => {
81
+ const v = host.current
82
+ if (v) {
83
+ v.cameraPosition = props.facing === 'front' ? CameraPosition.FRONT : CameraPosition.BACK
84
+ }
85
+ }, [props.facing])
86
+
87
+ useEffect(() => {
88
+ const v = host.current
89
+ if (v) {
90
+ v.pause = props.paused ?? false
91
+ }
92
+ }, [props.paused])
93
+
94
+ useEffect(() => {
95
+ const v = host.current
96
+ if (v) {
97
+ v.torchOn = props.torch ?? false
98
+ }
99
+ }, [props.torch])
100
+
101
+ <xplatbarcodescanner ref={bindHost} style={props.style} className={props.className} />
102
+ }
@@ -0,0 +1,116 @@
1
+ import { useImperativeHandle, useEffect, useRef } from 'octane'
2
+ import type { BarcodeScannerHandle, BarcodeScannerProps } from './props'
3
+ import { fromDetectorFormat, toDetectorFormats } from './format-map.web'
4
+
5
+ /** Live barcode/QR scanner — getUserMedia + the BarcodeDetector API
6
+ * (Chromium/Safari 18.4+; Firefox lacks the detector). Polling runs on
7
+ * requestVideoFrameCallback where available, else a 250ms interval. */
8
+ export function BarcodeScanner(props: BarcodeScannerProps) @{
9
+ const video = useRef<HTMLVideoElement | null>(null)
10
+ const latest = useRef(props)
11
+ latest.current = props
12
+
13
+ const handle = (v: HTMLVideoElement | null): BarcodeScannerHandle => ({
14
+ setPaused: () => {},
15
+ toggleCamera: () => {},
16
+ native: v,
17
+ })
18
+ useImperativeHandle(props.ref, () => handle(video.current), [])
19
+
20
+ useEffect(() => {
21
+ const Detector = (globalThis as any).BarcodeDetector
22
+ const mediaDevices = (globalThis as any).navigator?.mediaDevices
23
+ if (!Detector || typeof mediaDevices?.getUserMedia !== 'function') {
24
+ props.onError?.({ message: 'unsupported: BarcodeDetector/getUserMedia is not available' })
25
+ return
26
+ }
27
+ const el = video.current
28
+ if (!el) {
29
+ return
30
+ }
31
+
32
+ let detector: any
33
+ try {
34
+ detector = new Detector({ formats: toDetectorFormats(props.formats) })
35
+ } catch {
36
+ detector = new Detector()
37
+ }
38
+
39
+ let stream: MediaStream | null = null
40
+ let timer: any = null
41
+ let cancelled = false
42
+ const pausedRef = { current: false }
43
+
44
+ const poll = async () => {
45
+ if (cancelled || !el || pausedRef.current) {
46
+ return
47
+ }
48
+ try {
49
+ const codes = await detector.detect(el)
50
+ for (const code of codes ?? []) {
51
+ const box = code.boundingBox
52
+ latest.current.onCodeScanned?.({
53
+ type: fromDetectorFormat(code.format),
54
+ data: String(code.rawValue ?? ''),
55
+ bounds: box ? { x: box.x, y: box.y, width: box.width, height: box.height } : undefined,
56
+ })
57
+ }
58
+ } catch {
59
+ // A transient frame failure ends detection for this tick only.
60
+ }
61
+ schedule()
62
+ }
63
+
64
+ const schedule = () => {
65
+ if (cancelled) {
66
+ return
67
+ }
68
+ const rvfc = (el as any).requestVideoFrameCallback
69
+ if (typeof rvfc === 'function') {
70
+ rvfc.call(el, () => poll())
71
+ } else {
72
+ timer = setTimeout(poll, 250)
73
+ }
74
+ }
75
+
76
+ // props.paused is read through latest in the poll loop.
77
+ Object.defineProperty(pausedRef, 'current', {
78
+ get: () => latest.current.paused ?? false,
79
+ })
80
+
81
+ mediaDevices
82
+ .getUserMedia({ video: { facingMode: props.facing === 'front' ? 'user' : 'environment' }, audio: false })
83
+ .then((s: MediaStream) => {
84
+ if (cancelled) {
85
+ s.getTracks().forEach((t) => t.stop())
86
+ return
87
+ }
88
+ stream = s
89
+ el.srcObject = s
90
+ el.play().catch(() => {})
91
+ schedule()
92
+ })
93
+ .catch((e: any) => {
94
+ latest.current.onError?.({ message: e?.message ?? 'camera unavailable' })
95
+ })
96
+
97
+ return () => {
98
+ cancelled = true
99
+ if (timer) {
100
+ clearTimeout(timer)
101
+ }
102
+ stream?.getTracks().forEach((t) => t.stop())
103
+ el.srcObject = null
104
+ }
105
+ }, [props.facing, JSON.stringify(props.formats)])
106
+
107
+ <video
108
+ ref={(el: HTMLVideoElement | null) => {
109
+ video.current = el
110
+ }}
111
+ muted
112
+ playsInline
113
+ style={props.style}
114
+ className={props.className}
115
+ />
116
+ }
@@ -0,0 +1,2 @@
1
+ // Linux's system webview runs the shared web implementation.
2
+ export { barcodeScanner } from './barcode-scanner.web'
@@ -0,0 +1,12 @@
1
+ // Barcode scanner — macOS leaf. Vision's VNDetectBarcodesRequest is
2
+ // bridgeable but not wired; report unsupported rather than leaving a hole.
3
+ import type { BarcodeScannerService, PermissionResult } from './types'
4
+
5
+ export const barcodeScanner: BarcodeScannerService = {
6
+ supported: false,
7
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
8
+ scanImage: () => Promise.reject(new Error('unsupported: barcode scanning is not wired on macOS')),
9
+ }
10
+
11
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
12
+ permissionOwners.camera = () => barcodeScanner.ensure()
@@ -0,0 +1,119 @@
1
+ // Barcode scanner — native service leaf. Live scanning is the <BarcodeScanner>
2
+ // component (mlkit-core's MLKitView); this file owns the camera permission
3
+ // ensure (platform primitives, media's pattern) and headless still decode.
4
+ import { Application, ImageSource } from '@nativescript/core'
5
+ import { DetectionType, detectWithStillImage } from '@nativescript/mlkit-core'
6
+ import { android } from '@octane-xplat/platform/android'
7
+ import type { BarcodeFormat, BarcodeScannerService, PermissionResult, ScannedCode } from './types'
8
+ import { fromNativeFormat, toNativeFormats } from './format-map'
9
+
10
+ let scanRequestCode = 7723
11
+
12
+ async function ensure(): Promise<PermissionResult> {
13
+ try {
14
+ if (Application.ios) {
15
+ const av = (globalThis as any).AVCaptureDevice
16
+ const video = (globalThis as any).AVMediaTypeVideo
17
+ // 0=notDetermined 1=restricted 2=denied 3=authorized
18
+ const status = av?.authorizationStatusForMediaType?.(video)
19
+ if (status === 3) {
20
+ return 'granted'
21
+ }
22
+ if (status === 1 || status === 2) {
23
+ return 'denied'
24
+ }
25
+ if (typeof av?.requestAccessForMediaTypeCompletionHandler !== 'function') {
26
+ return 'unsupported'
27
+ }
28
+ return await new Promise<PermissionResult>((resolve) => {
29
+ av.requestAccessForMediaTypeCompletionHandler(video, (granted: boolean) =>
30
+ resolve(granted ? 'granted' : 'denied'),
31
+ )
32
+ })
33
+ }
34
+
35
+ const perm = 'android.permission.CAMERA'
36
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
37
+ if (
38
+ activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
39
+ ) {
40
+ return 'granted'
41
+ }
42
+ if (!activity) {
43
+ return 'denied'
44
+ }
45
+ return await new Promise<PermissionResult>((resolve) => {
46
+ const requestCode = scanRequestCode++
47
+ const event = Application.android.activityRequestPermissionsEvent
48
+ const onResult = (args: any) => {
49
+ if (args.requestCode !== requestCode) {
50
+ return
51
+ }
52
+ Application.android.off(event, onResult)
53
+ resolve(
54
+ args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
55
+ ? 'granted'
56
+ : 'denied',
57
+ )
58
+ }
59
+ Application.android.on(event, onResult)
60
+ try {
61
+ activity.requestPermissions([perm], requestCode)
62
+ } catch {
63
+ Application.android.off(event, onResult)
64
+ resolve('denied')
65
+ }
66
+ })
67
+ } catch {
68
+ return 'denied'
69
+ }
70
+ }
71
+
72
+ async function toImageSource(image: unknown): Promise<any> {
73
+ if (image instanceof ImageSource) {
74
+ return image
75
+ }
76
+ if (typeof image === 'string') {
77
+ return ImageSource.fromFile(image)
78
+ }
79
+ if (image && typeof (image as { uri?: string }).uri === 'string') {
80
+ return ImageSource.fromFile((image as { uri: string }).uri)
81
+ }
82
+ throw new Error('barcodeScanner.scanImage: expected an ImageSource, file path, or {uri} ref')
83
+ }
84
+
85
+ export const barcodeScanner: BarcodeScannerService = {
86
+ supported: true,
87
+
88
+ ensure,
89
+
90
+ async scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]> {
91
+ const source = await toImageSource(image)
92
+ const result = await detectWithStillImage(source, {
93
+ detectorType: DetectionType.Barcode,
94
+ barcodeScanning: { barcodeFormat: toNativeFormats(formats) as [any] },
95
+ })
96
+ const list = Array.isArray(result) ? result : Object.values(result ?? {})
97
+ return list
98
+ .flat()
99
+ .filter((item: any) => item && (item.rawValue !== undefined || item.format !== undefined))
100
+ .map((item: any) => ({
101
+ type: fromNativeFormat(item.format),
102
+ data: String(item.rawValue ?? item.displayValue ?? ''),
103
+ bounds: item.bounds
104
+ ? {
105
+ x: item.bounds.origin?.x ?? item.bounds.x ?? 0,
106
+ y: item.bounds.origin?.y ?? item.bounds.y ?? 0,
107
+ width: item.bounds.size?.width ?? item.bounds.width ?? 0,
108
+ height: item.bounds.size?.height ?? item.bounds.height ?? 0,
109
+ }
110
+ : undefined,
111
+ }))
112
+ },
113
+ }
114
+
115
+ // Scanning needs camera access — register the kind this leaf owns for the
116
+ // platform dispatcher (same 'camera' kind media registers; both leafs' owners
117
+ // run identical ensure logic, and the leaf must work with media absent).
118
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
119
+ permissionOwners.camera = () => barcodeScanner.ensure()
@@ -0,0 +1,56 @@
1
+ // Barcode scanner — web service leaf over the BarcodeDetector API. Live
2
+ // scanning is <BarcodeScanner> (getUserMedia + detector poll); this owns
3
+ // still-image decode and the availability flag.
4
+ import type { BarcodeFormat, BarcodeScannerService, PermissionResult, ScannedCode } from './types'
5
+ import { fromDetectorFormat, toDetectorFormats } from './format-map.web'
6
+
7
+ const detector = () => {
8
+ const Detector = (globalThis as any).BarcodeDetector
9
+ return typeof Detector === 'function' ? Detector : null
10
+ }
11
+
12
+ async function toImageSource(image: unknown): Promise<any> {
13
+ if (typeof image === 'string') {
14
+ const response = await fetch(image)
15
+ return createImageBitmap(await response.blob())
16
+ }
17
+ return image
18
+ }
19
+
20
+ export const barcodeScanner: BarcodeScannerService = {
21
+ supported: detector() !== null,
22
+
23
+ ensure(): Promise<PermissionResult> {
24
+ return Promise.resolve(detector() ? 'granted' : 'unsupported')
25
+ },
26
+
27
+ async scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]> {
28
+ const Detector = detector()
29
+ if (!Detector) {
30
+ throw new Error('unsupported: BarcodeDetector is not available')
31
+ }
32
+ let d: any
33
+ try {
34
+ d = new Detector({ formats: toDetectorFormats(formats) })
35
+ } catch {
36
+ d = new Detector()
37
+ }
38
+ const source = await toImageSource(image)
39
+ const codes = await d.detect(source)
40
+ return (codes ?? []).map((code: any) => ({
41
+ type: fromDetectorFormat(code.format),
42
+ data: String(code.rawValue ?? ''),
43
+ bounds: code.boundingBox
44
+ ? {
45
+ x: code.boundingBox.x,
46
+ y: code.boundingBox.y,
47
+ width: code.boundingBox.width,
48
+ height: code.boundingBox.height,
49
+ }
50
+ : undefined,
51
+ }))
52
+ },
53
+ }
54
+
55
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
56
+ permissionOwners.camera = () => barcodeScanner.ensure()
@@ -0,0 +1,11 @@
1
+ // Windows leaf — no ML Kit/BarcodeDetector backend; report unsupported.
2
+ import type { BarcodeScannerService, PermissionResult } from './types'
3
+
4
+ export const barcodeScanner: BarcodeScannerService = {
5
+ supported: false,
6
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
7
+ scanImage: () => Promise.reject(new Error('unsupported: barcode scanning is not available on windows')),
8
+ }
9
+
10
+ const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
11
+ permissionOwners.camera = () => barcodeScanner.ensure()
@@ -0,0 +1,31 @@
1
+ // Shared BarcodeFormat ↔ native-vocabulary mapping.
2
+ import { BarcodeFormats } from '@nativescript/mlkit-core'
3
+ import type { BarcodeFormat } from './types'
4
+
5
+ const TO_MLKIT: Record<BarcodeFormat, BarcodeFormats> = {
6
+ qr: BarcodeFormats.QR_CODE,
7
+ ean13: BarcodeFormats.EAN_13,
8
+ ean8: BarcodeFormats.EAN_8,
9
+ upc_a: BarcodeFormats.UPC_A,
10
+ upc_e: BarcodeFormats.UPC_E,
11
+ code128: BarcodeFormats.CODE_128,
12
+ code39: BarcodeFormats.CODE_39,
13
+ code93: BarcodeFormats.CODE_93,
14
+ codabar: BarcodeFormats.CODABAR,
15
+ itf: BarcodeFormats.ITF,
16
+ datamatrix: BarcodeFormats.DATA_MATRIX,
17
+ pdf417: BarcodeFormats.PDF417,
18
+ aztec: BarcodeFormats.AZTEC,
19
+ }
20
+
21
+ const FROM_MLKIT: Record<string, string> = Object.fromEntries(
22
+ Object.entries(TO_MLKIT).map(([ours, theirs]) => [String(theirs), ours]),
23
+ )
24
+
25
+ export function toNativeFormats(formats?: BarcodeFormat[]): BarcodeFormats[] {
26
+ return formats?.length ? formats.map((f) => TO_MLKIT[f]) : [BarcodeFormats.ALL]
27
+ }
28
+
29
+ export function fromNativeFormat(format: unknown): string {
30
+ return FROM_MLKIT[String(format)] ?? String(format ?? 'unknown')
31
+ }
@@ -0,0 +1,30 @@
1
+ // Shared BarcodeFormat ↔ web BarcodeDetector-vocabulary mapping.
2
+ import type { BarcodeFormat } from './types'
3
+
4
+ const TO_DETECTOR: Record<BarcodeFormat, string> = {
5
+ qr: 'qr_code',
6
+ ean13: 'ean_13',
7
+ ean8: 'ean_8',
8
+ upc_a: 'upc_a',
9
+ upc_e: 'upc_e',
10
+ code128: 'code_128',
11
+ code39: 'code_39',
12
+ code93: 'code_93',
13
+ codabar: 'codabar',
14
+ itf: 'itf',
15
+ datamatrix: 'data_matrix',
16
+ pdf417: 'pdf417',
17
+ aztec: 'aztec',
18
+ }
19
+
20
+ const FROM_DETECTOR: Record<string, string> = Object.fromEntries(
21
+ Object.entries(TO_DETECTOR).map(([ours, theirs]) => [theirs, ours]),
22
+ )
23
+
24
+ export function toDetectorFormats(formats?: BarcodeFormat[]): string[] | undefined {
25
+ return formats?.length ? formats.map((f) => TO_DETECTOR[f]) : undefined
26
+ }
27
+
28
+ export function fromDetectorFormat(format: unknown): string {
29
+ return FROM_DETECTOR[String(format)] ?? String(format ?? 'unknown')
30
+ }
@@ -0,0 +1,3 @@
1
+ export * from './types'
2
+ export * from './props'
3
+ export { barcodeScanner } from './barcode-scanner.macos'
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './types'
2
+ export * from './props'
3
+ export { barcodeScanner } from './barcode-scanner'
4
+ export { BarcodeScanner } from './BarcodeScanner.tsrx'
@@ -0,0 +1,4 @@
1
+ export * from './types'
2
+ export * from './props'
3
+ export { barcodeScanner } from './barcode-scanner.web'
4
+ export { BarcodeScanner } from './BarcodeScanner.web.tsrx'
@@ -0,0 +1,8 @@
1
+ import { MLKitView } from '@nativescript/mlkit-core'
2
+ import type { Attributes } from '@nativescript-community/octane/intrinsics'
3
+
4
+ declare module '@nativescript-community/octane/intrinsics' {
5
+ interface NativeScriptElements {
6
+ xplatbarcodescanner: Attributes<typeof MLKitView>
7
+ }
8
+ }
package/src/props.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { Octane } from 'octane/jsx-runtime'
2
+ import type { BarcodeFormat, ScannedCode } from './types'
3
+
4
+ export interface BarcodeScannerHandle {
5
+ /** Pause/resume preview processing (not the camera feed itself). */
6
+ setPaused(paused: boolean): void
7
+ toggleCamera(): void
8
+ /** The underlying MLKitView on native, the <video> element on web. */
9
+ native: unknown
10
+ }
11
+
12
+ /** Live barcode/QR scanning view — ML Kit on native, BarcodeDetector on web.
13
+ * Decoding only: photo capture stays in `@octane-xplat/camera`, gallery
14
+ * picking in `@octane-xplat/media`. */
15
+ export interface BarcodeScannerProps {
16
+ className?: any
17
+ style?: any
18
+ /** Restrict decoded symbologies — all supported formats by default. */
19
+ formats?: BarcodeFormat[]
20
+ /** Fires for each detected code (the OS may deliver batches). */
21
+ onCodeScanned?: (e: { type: string; data: string; bounds?: ScannedCode['bounds'] }) => void
22
+ /** Freeze detection; preview keeps running. Default false. */
23
+ paused?: boolean
24
+ /** Illuminate the camera torch while scanning. Default false. */
25
+ torch?: boolean
26
+ /** 'back' | 'front'. Default 'back'. */
27
+ facing?: 'back' | 'front'
28
+ onError?: (e: { message: string }) => void
29
+ ref?: Octane.Ref<BarcodeScannerHandle>
30
+ /** Platform escape hatches, applied after the shared props. */
31
+ ios?: Record<string, any>
32
+ android?: Record<string, any>
33
+ web?: Record<string, any>
34
+ }
package/src/types.ts ADDED
@@ -0,0 +1,41 @@
1
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported'
2
+
3
+ /** Code symbologies — expo-camera spellings; each platform maps them onto
4
+ * its own detector vocabulary (ML Kit BarcodeFormats / BarcodeDetector). */
5
+ export type BarcodeFormat =
6
+ | 'qr'
7
+ | 'ean13'
8
+ | 'ean8'
9
+ | 'upc_a'
10
+ | 'upc_e'
11
+ | 'code128'
12
+ | 'code39'
13
+ | 'code93'
14
+ | 'codabar'
15
+ | 'itf'
16
+ | 'datamatrix'
17
+ | 'pdf417'
18
+ | 'aztec'
19
+
20
+ export interface ScannedCode {
21
+ /** The symbology, in our BarcodeFormat spelling. */
22
+ type: string
23
+ /** Decoded payload. */
24
+ data: string
25
+ /** Corner points / bounding rect where the detector reports it. */
26
+ bounds?: { x: number; y: number; width: number; height: number }
27
+ }
28
+
29
+ /** Headless decode + permission service — the scanning view is
30
+ * `<BarcodeScanner>` from the same package. */
31
+ export interface BarcodeScannerService {
32
+ readonly supported: boolean
33
+ /** Ensure camera permission for live scanning. */
34
+ ensure(): Promise<PermissionResult>
35
+ /** Decode codes from a still image (platform image ref: a path or
36
+ * ImageSource on native, Blob/HTMLImageElement/data URL on web).
37
+ * Returns [] when the detector finds nothing. */
38
+ scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]>
39
+ }
40
+
41
+ export declare const barcodeScanner: BarcodeScannerService
@@ -0,0 +1,20 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
4
+ "BarcodeScanner.d.ts",
5
+ "BarcodeScanner.web.d.ts",
6
+ "barcode-scanner.d.ts",
7
+ "barcode-scanner.linux.d.ts",
8
+ "barcode-scanner.macos.d.ts",
9
+ "barcode-scanner.web.d.ts",
10
+ "barcode-scanner.windows.d.ts",
11
+ "format-map.d.ts",
12
+ "format-map.web.d.ts",
13
+ "index.d.ts",
14
+ "index.macos.d.ts",
15
+ "index.web.d.ts",
16
+ "native-elements.d.ts",
17
+ "props.d.ts",
18
+ "types.d.ts"
19
+ ]
20
+ }
@@ -0,0 +1,4 @@
1
+ import type { BarcodeScannerProps } from './props.js';
2
+ /** Live barcode/QR scanner — ML Kit's camera preview with `detectionType:
3
+ * barcode`. Decoding only; photo capture stays in @octane-xplat/camera. */
4
+ export declare function BarcodeScanner(props: BarcodeScannerProps): unknown;
@@ -0,0 +1,5 @@
1
+ import type { BarcodeScannerProps } from './props.js';
2
+ /** Live barcode/QR scanner — getUserMedia + the BarcodeDetector API
3
+ * (Chromium/Safari 18.4+; Firefox lacks the detector). Polling runs on
4
+ * requestVideoFrameCallback where available, else a 250ms interval. */
5
+ export declare function BarcodeScanner(props: BarcodeScannerProps): import("octane/jsx-runtime").JSX.Element;
@@ -0,0 +1,2 @@
1
+ import type { BarcodeScannerService } from './types.js';
2
+ export declare const barcodeScanner: BarcodeScannerService;
@@ -0,0 +1 @@
1
+ export { barcodeScanner } from './barcode-scanner.web.js';
@@ -0,0 +1,2 @@
1
+ import type { BarcodeScannerService } from './types.js';
2
+ export declare const barcodeScanner: BarcodeScannerService;
@@ -0,0 +1,2 @@
1
+ import type { BarcodeScannerService } from './types.js';
2
+ export declare const barcodeScanner: BarcodeScannerService;
@@ -0,0 +1,2 @@
1
+ import type { BarcodeScannerService } from './types.js';
2
+ export declare const barcodeScanner: BarcodeScannerService;
@@ -0,0 +1,4 @@
1
+ import { BarcodeFormats } from '@nativescript/mlkit-core';
2
+ import type { BarcodeFormat } from './types.js';
3
+ export declare function toNativeFormats(formats?: BarcodeFormat[]): BarcodeFormats[];
4
+ export declare function fromNativeFormat(format: unknown): string;
@@ -0,0 +1,3 @@
1
+ import type { BarcodeFormat } from './types.js';
2
+ export declare function toDetectorFormats(formats?: BarcodeFormat[]): string[] | undefined;
3
+ export declare function fromDetectorFormat(format: unknown): string;
@@ -0,0 +1,4 @@
1
+ export * from './types.js';
2
+ export * from './props.js';
3
+ export { barcodeScanner } from './barcode-scanner.js';
4
+ export { BarcodeScanner } from './BarcodeScanner.js';
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './props.js';
3
+ export { barcodeScanner } from './barcode-scanner.macos.js';
@@ -0,0 +1,4 @@
1
+ export * from './types.js';
2
+ export * from './props.js';
3
+ export { barcodeScanner } from './barcode-scanner.web.js';
4
+ export { BarcodeScanner } from './BarcodeScanner.web.js';
@@ -0,0 +1,8 @@
1
+ import { MLKitView } from '@nativescript/mlkit-core'
2
+ import type { Attributes } from '@nativescript-community/octane/intrinsics'
3
+
4
+ declare module '@nativescript-community/octane/intrinsics' {
5
+ interface NativeScriptElements {
6
+ xplatbarcodescanner: Attributes<typeof MLKitView>
7
+ }
8
+ }
@@ -0,0 +1,38 @@
1
+ import type { Octane } from 'octane/jsx-runtime';
2
+ import type { BarcodeFormat, ScannedCode } from './types.js';
3
+ export interface BarcodeScannerHandle {
4
+ /** Pause/resume preview processing (not the camera feed itself). */
5
+ setPaused(paused: boolean): void;
6
+ toggleCamera(): void;
7
+ /** The underlying MLKitView on native, the <video> element on web. */
8
+ native: unknown;
9
+ }
10
+ /** Live barcode/QR scanning view — ML Kit on native, BarcodeDetector on web.
11
+ * Decoding only: photo capture stays in `@octane-xplat/camera`, gallery
12
+ * picking in `@octane-xplat/media`. */
13
+ export interface BarcodeScannerProps {
14
+ className?: any;
15
+ style?: any;
16
+ /** Restrict decoded symbologies — all supported formats by default. */
17
+ formats?: BarcodeFormat[];
18
+ /** Fires for each detected code (the OS may deliver batches). */
19
+ onCodeScanned?: (e: {
20
+ type: string;
21
+ data: string;
22
+ bounds?: ScannedCode['bounds'];
23
+ }) => void;
24
+ /** Freeze detection; preview keeps running. Default false. */
25
+ paused?: boolean;
26
+ /** Illuminate the camera torch while scanning. Default false. */
27
+ torch?: boolean;
28
+ /** 'back' | 'front'. Default 'back'. */
29
+ facing?: 'back' | 'front';
30
+ onError?: (e: {
31
+ message: string;
32
+ }) => void;
33
+ ref?: Octane.Ref<BarcodeScannerHandle>;
34
+ /** Platform escape hatches, applied after the shared props. */
35
+ ios?: Record<string, any>;
36
+ android?: Record<string, any>;
37
+ web?: Record<string, any>;
38
+ }
@@ -0,0 +1,29 @@
1
+ export type PermissionResult = 'granted' | 'denied' | 'unsupported';
2
+ /** Code symbologies — expo-camera spellings; each platform maps them onto
3
+ * its own detector vocabulary (ML Kit BarcodeFormats / BarcodeDetector). */
4
+ export type BarcodeFormat = 'qr' | 'ean13' | 'ean8' | 'upc_a' | 'upc_e' | 'code128' | 'code39' | 'code93' | 'codabar' | 'itf' | 'datamatrix' | 'pdf417' | 'aztec';
5
+ export interface ScannedCode {
6
+ /** The symbology, in our BarcodeFormat spelling. */
7
+ type: string;
8
+ /** Decoded payload. */
9
+ data: string;
10
+ /** Corner points / bounding rect where the detector reports it. */
11
+ bounds?: {
12
+ x: number;
13
+ y: number;
14
+ width: number;
15
+ height: number;
16
+ };
17
+ }
18
+ /** Headless decode + permission service — the scanning view is
19
+ * `<BarcodeScanner>` from the same package. */
20
+ export interface BarcodeScannerService {
21
+ readonly supported: boolean;
22
+ /** Ensure camera permission for live scanning. */
23
+ ensure(): Promise<PermissionResult>;
24
+ /** Decode codes from a still image (platform image ref: a path or
25
+ * ImageSource on native, Blob/HTMLImageElement/data URL on web).
26
+ * Returns [] when the detector finds nothing. */
27
+ scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]>;
28
+ }
29
+ export declare const barcodeScanner: BarcodeScannerService;