@chipmobilesdk/rn-camera 0.2.0 → 0.3.0

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.
@@ -1,518 +1,522 @@
1
- /**
2
- * Camera controller — the object consuming apps actually drive.
3
- *
4
- * It owns observable state and orchestrates the three ports (engine,
5
- * permissions, artifact store). All I/O lives here; the decisions live in
6
- * `sessionMachine` and `captureController`, which stay pure so they can be
7
- * tested without a camera.
8
- */
9
-
10
- import {
11
- type CameraPermissionState,
12
- type CameraPosition,
13
- type CameraState,
14
- type CapabilityProfile,
15
- type CapturedImage,
16
- type CaptureRequest,
17
- type FlashMode,
18
- type StartOptions,
19
- } from '../config/types';
20
- import { CameraError, isCameraError } from '../diagnostics/errors';
21
- import { silentLogger, type CameraLogger } from '../diagnostics/logger';
22
- import type { CameraEngine } from '../native/cameraEngine';
23
- import type { PermissionPort } from '../permissions/permissionPort';
24
- import type { ArtifactStore } from '../storage/artifactStore';
25
- import { EMPTY_CAPABILITIES, assertSupported, supportsTorch } from './capabilities';
26
- import {
27
- SingleFlight,
28
- assertCaptureAllowed,
29
- finalizeResult,
30
- type CaptureContext,
31
- } from './captureController';
32
- import { canStart, initialSession, sessionReducer, type SessionSnapshot } from './sessionMachine';
33
-
34
- /** 24 hours (FR-029). */
35
- export const DEFAULT_TEMPORARY_TTL_MS = 24 * 60 * 60 * 1000;
36
-
37
- export type AppStatus = 'active' | 'background';
38
-
39
- export interface CameraControllerOptions {
40
- readonly engine?: CameraEngine;
41
- readonly permissions?: PermissionPort;
42
- readonly store?: ArtifactStore;
43
- readonly logger?: CameraLogger;
44
- readonly temporaryTtlMs?: number;
45
- /**
46
- * App foreground/background source. Defaults to React Native `AppState`.
47
- * Injectable so lifecycle rules are testable without an app (FR-015).
48
- */
49
- readonly subscribeToAppState?: (listener: (status: AppStatus) => void) => () => void;
50
- /**
51
- * Set false to skip the sweep that runs when the controller is first used
52
- * (tests). Defaults to true.
53
- */
54
- readonly sweepOnInit?: boolean;
55
- }
56
-
57
- export interface CameraController {
58
- readonly state: CameraState;
59
- subscribe(listener: (state: CameraState) => void): () => void;
60
-
61
- getPermission(): Promise<CameraPermissionState>;
62
- requestPermission(): Promise<CameraPermissionState>;
63
-
64
- start(options?: StartOptions): Promise<void>;
65
- pause(): Promise<void>;
66
- resume(): Promise<void>;
67
- stop(): Promise<void>;
68
-
69
- capture(request?: CaptureRequest): Promise<CapturedImage>;
70
- cleanup(image: CapturedImage | string): Promise<void>;
71
-
72
- getCapabilities(): Promise<CapabilityProfile>;
73
- setFlashMode(mode: FlashMode): void;
74
- setTorch(enabled: boolean): Promise<void>;
75
-
76
- /** Marks the preview surface mounted, enabling foreground auto-restart. */
77
- setSurfaceMounted(mounted: boolean): void;
78
- /**
79
- * Releases ports, listeners, and the camera. Safe to call twice. Afterwards
80
- * `start`, `resume`, `capture` and the permission and capability reads reject
81
- * with `notReady`; `stop`, `pause` and `cleanup` stay safe no-ops so teardown
82
- * code never has to check.
83
- */
84
- dispose(): Promise<void>;
85
- }
86
-
87
- function defaultAppStateSubscribe(listener: (status: AppStatus) => void): () => void {
88
- // Lazy require so importing the package outside React Native (for example in
89
- // a Node-based test runner) does not pull in the RN runtime.
90
- const { AppState } = require('react-native');
91
- const subscription = AppState.addEventListener('change', (next: string) => {
92
- listener(next === 'active' ? 'active' : 'background');
93
- });
94
- return () => subscription.remove();
95
- }
96
-
97
- export function createCameraController(
98
- options: CameraControllerOptions = {},
99
- ): CameraController {
100
- if (!options.engine || !options.permissions) {
101
- throw new CameraError(
102
- 'unsupportedCapability',
103
- 'createCameraController requires `engine` and `permissions` ports. Use the ' +
104
- 'default adapters, or createTestCamera() in tests.',
105
- );
106
- }
107
-
108
- // Bound after the guard so the closures below see non-optional ports.
109
- const engine: CameraEngine = options.engine;
110
- const permissions: PermissionPort = options.permissions;
111
- const store = options.store;
112
- const logger = options.logger ?? silentLogger;
113
- const ttlMs = options.temporaryTtlMs ?? DEFAULT_TEMPORARY_TTL_MS;
114
-
115
- let session: SessionSnapshot = initialSession;
116
- let permission: CameraPermissionState = 'undetermined';
117
- let capabilities: CapabilityProfile | null = null;
118
- let cameraPosition: CameraPosition = 'back';
119
- let flashMode: FlashMode = 'off';
120
- let torchEnabled = false;
121
- let surfaceMounted = false;
122
- let disposed = false;
123
- let appStatus: AppStatus = 'active';
124
- // Set only when backgrounding cut a running session short. Foregrounding
125
- // used to restart from any idle or stopped session, so a camera the user had
126
- // stopped — or never started, or no longer had permission for — came back on
127
- // with the app.
128
- let resumeOnForeground = false;
129
- let releasing: Promise<void> | null = null;
130
- let warnedUnmanaged = false;
131
- let detach: (() => void) | null = null;
132
-
133
- const capture = new SingleFlight();
134
- const listeners = new Set<(state: CameraState) => void>();
135
-
136
- function snapshot(): CameraState {
137
- return {
138
- session: session.status,
139
- permission,
140
- capabilities,
141
- cameraPosition,
142
- flashMode,
143
- torchEnabled,
144
- capturing: capture.busy,
145
- error: session.error
146
- ? {
147
- code: session.error.code,
148
- recoverable: session.error.recoverable,
149
- message: session.error.message,
150
- }
151
- : null,
152
- };
153
- }
154
-
155
- let current = snapshot();
156
-
157
- function emit(): void {
158
- current = snapshot();
159
- for (const listener of listeners) {
160
- // One throwing subscriber must not starve the others, nor unwind into
161
- // the transition that emitted — that left the controller half-updated.
162
- try {
163
- listener(current);
164
- } catch {
165
- logger.log({ type: 'session', code: 'listener-threw' });
166
- }
167
- }
168
- }
169
-
170
- function dispatch(event: Parameters<typeof sessionReducer>[1]): void {
171
- const next = sessionReducer(session, event);
172
- if (next !== session) {
173
- session = next;
174
- logger.log({
175
- type: 'session',
176
- code: session.status,
177
- recoverable: session.error?.recoverable,
178
- });
179
- emit();
180
- }
181
- }
182
-
183
- /** Torch must never survive leaving the active state (FR-034b). */
184
- async function forceTorchOff(): Promise<void> {
185
- if (!torchEnabled) {
186
- return;
187
- }
188
- torchEnabled = false;
189
- try {
190
- await engine.setTorch(false);
191
- } catch {
192
- // Torch-off is best effort; the session is going away regardless.
193
- }
194
- emit();
195
- }
196
-
197
- async function releaseCamera(): Promise<void> {
198
- await forceTorchOff();
199
- // Nothing to release. Going through STOP/STOPPED here turned an idle
200
- // controller into `stopped` on every preview unmount.
201
- if (session.status === 'idle' || session.status === 'stopped') {
202
- return;
203
- }
204
- dispatch({ type: 'STOP' });
205
- try {
206
- await engine.stop();
207
- dispatch({ type: 'STOPPED' });
208
- } catch (error) {
209
- dispatch({ type: 'FAIL', code: isCameraError(error) ? error.code : 'captureFailed' });
210
- }
211
- }
212
-
213
- async function startEngine(startOptions: StartOptions = {}): Promise<void> {
214
- try {
215
- await engine.start({ cameraPosition: startOptions.cameraPosition ?? cameraPosition });
216
- dispatch({ type: 'STARTED' });
217
- } catch (error) {
218
- dispatch({ type: 'FAIL', code: isCameraError(error) ? error.code : 'cameraUnavailable' });
219
- }
220
- }
221
-
222
- function resumeAfterForeground(): void {
223
- if (disposed || appStatus !== 'active' || !resumeOnForeground) {
224
- return;
225
- }
226
- resumeOnForeground = false;
227
- if (!surfaceMounted || permission !== 'granted') {
228
- return;
229
- }
230
- dispatch({ type: 'FOREGROUND', surfaceMounted });
231
- if (session.status === 'starting') {
232
- startEngine().catch(() => undefined);
233
- }
234
- }
235
-
236
- function onAppState(status: AppStatus): void {
237
- appStatus = status;
238
- if (status === 'background') {
239
- resumeOnForeground ||= session.status === 'active' || session.status === 'starting';
240
- dispatch({ type: 'BACKGROUND' });
241
- releasing = releaseCamera().catch(() => undefined);
242
- } else {
243
- // Wait for a release still in flight, or the restart lands on a
244
- // `stopping` session and is dropped.
245
- (releasing ?? Promise.resolve()).then(resumeAfterForeground).catch(() => undefined);
246
- }
247
- }
248
-
249
- /**
250
- * Subscribes to permission and app-state changes and runs the sweep, on first
251
- * use rather than at construction. React may build a controller during a
252
- * render it then throws away (StrictMode does so on purpose); construction
253
- * that subscribed leaked a listener pair every time.
254
- */
255
- function attach(): void {
256
- if (detach || disposed) {
257
- return;
258
- }
259
- const unsubscribePermission = permissions.subscribe(next => {
260
- permission = next;
261
- logger.log({ type: 'permission', code: next });
262
- emit();
263
- // A revocation while running must tear the session down, not leave a
264
- // frozen preview on screen (FR-007).
265
- if (next !== 'granted') {
266
- resumeOnForeground = false;
267
- if (session.status !== 'idle' && session.status !== 'stopped') {
268
- releaseCamera().catch(() => undefined);
269
- }
270
- }
271
- });
272
- const unsubscribeAppState = (options.subscribeToAppState ?? defaultAppStateSubscribe)(
273
- onAppState,
274
- );
275
- detach = () => {
276
- unsubscribePermission();
277
- unsubscribeAppState();
278
- };
279
-
280
- // FR-029: sweep our own temp directory once, asynchronously, so it can
281
- // never add latency to the capture path or the preview start.
282
- if (store && options.sweepOnInit !== false) {
283
- store
284
- .sweep(ttlMs)
285
- .then(removed => {
286
- if (removed > 0) {
287
- logger.log({ type: 'cleanup', code: `swept:${removed}` });
288
- }
289
- })
290
- .catch(() => {
291
- // A failed sweep must never block startup.
292
- });
293
- }
294
- }
295
-
296
- /** Entry guard for operations that need a live controller. */
297
- function live(operation: string): void {
298
- if (disposed) {
299
- throw new CameraError('notReady', `${operation}() called on a disposed camera controller`);
300
- }
301
- attach();
302
- }
303
-
304
- /**
305
- * Puts a package-temporary capture under the store so `cleanup()` and the
306
- * sweep can reach it. Never throws: the capture itself succeeded, and a file
307
- * the store cannot manage is still a usable photo.
308
- */
309
- async function manage(image: CapturedImage): Promise<CapturedImage> {
310
- if (image.ownership !== 'packageTemporary') {
311
- return image;
312
- }
313
- if (store?.adopt) {
314
- try {
315
- return { ...image, uri: await store.adopt(image.uri) };
316
- } catch {
317
- logger.log({ type: 'cleanup', code: 'adopt-failed' });
318
- return image;
319
- }
320
- }
321
- if (!store?.owns(image.uri) && !warnedUnmanaged) {
322
- warnedUnmanaged = true;
323
- logger.log({ type: 'cleanup', code: store ? 'unmanaged:store-cannot-adopt' : 'unmanaged:no-store' });
324
- }
325
- return image;
326
- }
327
-
328
- const controller: CameraController = {
329
- get state() {
330
- return current;
331
- },
332
-
333
- subscribe(listener) {
334
- if (disposed) {
335
- return () => undefined;
336
- }
337
- attach();
338
- listeners.add(listener);
339
- return () => {
340
- listeners.delete(listener);
341
- };
342
- },
343
-
344
- async getPermission() {
345
- live('getPermission');
346
- permission = await permissions.getStatus();
347
- emit();
348
- return permission;
349
- },
350
-
351
- async requestPermission() {
352
- live('requestPermission');
353
- permission = 'requesting';
354
- emit();
355
- permission = await permissions.request();
356
- emit();
357
- return permission;
358
- },
359
-
360
- async start(startOptions: StartOptions = {}) {
361
- live('start');
362
- if (permission !== 'granted') {
363
- dispatch({ type: 'FAIL', code: 'permissionDenied' });
364
- throw new CameraError('permissionDenied', 'Camera permission is not granted');
365
- }
366
- if (!canStart(session.status)) {
367
- throw new CameraError('sessionConflict', `Session already ${session.status}`);
368
- }
369
- if (startOptions.cameraPosition) {
370
- cameraPosition = startOptions.cameraPosition;
371
- }
372
- dispatch({ type: 'START' });
373
- await startEngine(startOptions);
374
- if (session.error) {
375
- throw session.error;
376
- }
377
- },
378
-
379
- async pause() {
380
- if (disposed) {
381
- return;
382
- }
383
- await forceTorchOff();
384
- dispatch({ type: 'PAUSE' });
385
- },
386
-
387
- async resume() {
388
- live('resume');
389
- dispatch({ type: 'RESUME' });
390
- if (session.status === 'starting') {
391
- await startEngine();
392
- }
393
- },
394
-
395
- async stop() {
396
- // An explicit stop is the user's decision; foregrounding must not undo it.
397
- resumeOnForeground = false;
398
- if (disposed) {
399
- return;
400
- }
401
- await releaseCamera();
402
- },
403
-
404
- async capture(request: CaptureRequest = {}) {
405
- live('capture');
406
- const context: CaptureContext = {
407
- engine,
408
- sessionStatus: session.status,
409
- permissionGranted: permission === 'granted',
410
- capabilities,
411
- cameraPosition,
412
- flashMode,
413
- };
414
- // Guards run before the single-flight slot is taken so a rejected
415
- // request cannot block a subsequent legal one.
416
- assertCaptureAllowed(context, request);
417
-
418
- try {
419
- const result = await capture.run(async () => {
420
- emit();
421
- const raw = await engine.capture({
422
- ...request,
423
- flashMode: request.flashMode ?? flashMode,
424
- cameraPosition: request.cameraPosition ?? cameraPosition,
425
- });
426
- return manage(finalizeResult(raw, request, context));
427
- });
428
- logger.log({ type: 'capture', code: 'succeeded' });
429
- return result;
430
- } catch (error) {
431
- // The contract promises a CameraError; a raw native error carries
432
- // no code to branch on and its message may hold a file path.
433
- const failure = isCameraError(error)
434
- ? error
435
- : new CameraError('captureFailed', 'The camera failed to capture a photo');
436
- logger.log({ type: 'capture', code: failure.code, recoverable: failure.recoverable });
437
- throw failure;
438
- } finally {
439
- // Without this a failed capture left `capturing: true` published
440
- // until some unrelated change emitted again.
441
- emit();
442
- }
443
- },
444
-
445
- async cleanup(image: CapturedImage | string) {
446
- const uri = typeof image === 'string' ? image : image.uri;
447
- if (!store) {
448
- return;
449
- }
450
- // Refuse anything we did not create rather than deleting an arbitrary
451
- // path, which also covers every appOwned artifact (FR-026b, FR-028).
452
- if (!store.owns(uri)) {
453
- logger.log({ type: 'cleanup', code: 'refused-not-owned' });
454
- return;
455
- }
456
- await store.remove(uri);
457
- logger.log({ type: 'cleanup', code: 'removed' });
458
- },
459
-
460
- async getCapabilities() {
461
- live('getCapabilities');
462
- try {
463
- capabilities = await engine.getCapabilities();
464
- } catch {
465
- capabilities = EMPTY_CAPABILITIES;
466
- }
467
- logger.log({
468
- type: 'capability',
469
- code: capabilities.hasCameraHardware ? 'available' : 'no-hardware',
470
- });
471
- emit();
472
- return capabilities;
473
- },
474
-
475
- setFlashMode(mode: FlashMode) {
476
- assertSupported(
477
- mode === 'off' || capabilities?.hasFlash === true,
478
- `flash mode "${mode}"`,
479
- );
480
- flashMode = mode;
481
- emit();
482
- },
483
-
484
- async setTorch(enabled: boolean) {
485
- if (disposed && !enabled) {
486
- return;
487
- }
488
- live('setTorch');
489
- if (enabled) {
490
- assertSupported(supportsTorch(capabilities), 'torch');
491
- }
492
- await engine.setTorch(enabled);
493
- torchEnabled = enabled;
494
- emit();
495
- },
496
-
497
- setSurfaceMounted(mounted: boolean) {
498
- if (disposed) {
499
- return;
500
- }
501
- surfaceMounted = mounted;
502
- },
503
-
504
- async dispose() {
505
- if (disposed) {
506
- return;
507
- }
508
- disposed = true;
509
- resumeOnForeground = false;
510
- detach?.();
511
- detach = null;
512
- await releaseCamera();
513
- listeners.clear();
514
- },
515
- };
516
-
517
- return controller;
518
- }
1
+ /**
2
+ * Camera controller — the object consuming apps actually drive.
3
+ *
4
+ * It owns observable state and orchestrates the three ports (engine,
5
+ * permissions, artifact store). All I/O lives here; the decisions live in
6
+ * `sessionMachine` and `captureController`, which stay pure so they can be
7
+ * tested without a camera.
8
+ */
9
+
10
+ import { appLifecycle, createListenerSet } from '@chipmobilesdk/rn-core';
11
+
12
+ import {
13
+ type CameraPermissionState,
14
+ type CameraPosition,
15
+ type CameraState,
16
+ type CapabilityProfile,
17
+ type CapturedImage,
18
+ type CaptureRequest,
19
+ type FlashMode,
20
+ type StartOptions,
21
+ } from '../config/types';
22
+ import { CameraError, isCameraError } from '../diagnostics/errors';
23
+ import { silentLogger, withSdkSinks, type CameraLogger } from '../diagnostics/logger';
24
+ import type { CameraEngine } from '../native/cameraEngine';
25
+ import type { PermissionPort } from '../permissions/permissionPort';
26
+ import type { ArtifactStore } from '../storage/artifactStore';
27
+ import { EMPTY_CAPABILITIES, assertSupported, supportsTorch } from './capabilities';
28
+ import {
29
+ SingleFlight,
30
+ assertCaptureAllowed,
31
+ finalizeResult,
32
+ type CaptureContext,
33
+ } from './captureController';
34
+ import { canStart, initialSession, sessionReducer, type SessionSnapshot } from './sessionMachine';
35
+
36
+ /** 24 hours (FR-029). */
37
+ export const DEFAULT_TEMPORARY_TTL_MS = 24 * 60 * 60 * 1000;
38
+
39
+ export type AppStatus = 'active' | 'background';
40
+
41
+ export interface CameraControllerOptions {
42
+ readonly engine?: CameraEngine;
43
+ readonly permissions?: PermissionPort;
44
+ readonly store?: ArtifactStore | undefined;
45
+ readonly logger?: CameraLogger | undefined;
46
+ readonly temporaryTtlMs?: number;
47
+ /**
48
+ * App foreground/background source. Defaults to rn-core's shared `appLifecycle()`,
49
+ * where `inactive` counts as background. Injectable so lifecycle rules are
50
+ * testable without an app (FR-015).
51
+ */
52
+ readonly subscribeToAppState?: (listener: (status: AppStatus) => void) => () => void;
53
+ /**
54
+ * Set false to skip the sweep that runs when the controller is first used
55
+ * (tests). Defaults to true.
56
+ */
57
+ readonly sweepOnInit?: boolean;
58
+ }
59
+
60
+ export interface CameraController {
61
+ readonly state: CameraState;
62
+ subscribe(listener: (state: CameraState) => void): () => void;
63
+
64
+ getPermission(): Promise<CameraPermissionState>;
65
+ requestPermission(): Promise<CameraPermissionState>;
66
+
67
+ start(options?: StartOptions): Promise<void>;
68
+ pause(): Promise<void>;
69
+ resume(): Promise<void>;
70
+ stop(): Promise<void>;
71
+
72
+ capture(request?: CaptureRequest): Promise<CapturedImage>;
73
+ cleanup(image: CapturedImage | string): Promise<void>;
74
+
75
+ getCapabilities(): Promise<CapabilityProfile>;
76
+ setFlashMode(mode: FlashMode): void;
77
+ setTorch(enabled: boolean): Promise<void>;
78
+
79
+ /** Marks the preview surface mounted, enabling foreground auto-restart. */
80
+ setSurfaceMounted(mounted: boolean): void;
81
+ /**
82
+ * Called by `CameraPreview` when the native preview surface cannot load (the
83
+ * VisionCamera module is missing or unlinked). Fails the session with
84
+ * `cameraUnavailable` rather than leaving a black preview and no error.
85
+ */
86
+ reportSurfaceUnavailable(): void;
87
+ /**
88
+ * Releases ports, listeners, and the camera. Safe to call twice. Afterwards
89
+ * `start`, `resume`, `capture` and the permission and capability reads reject
90
+ * with `notReady`; `stop`, `pause` and `cleanup` stay safe no-ops so teardown
91
+ * code never has to check.
92
+ */
93
+ dispose(): Promise<void>;
94
+ }
95
+
96
+ function defaultAppStateSubscribe(listener: (status: AppStatus) => void): () => void {
97
+ // rn-core's one lifecycle subscription, shared with every other package; it
98
+ // requires react-native only on first subscribe (PERF-07).
99
+ return appLifecycle().subscribe(state => listener(state === 'active' ? 'active' : 'background'));
100
+ }
101
+
102
+ export function createCameraController(options: CameraControllerOptions = {}): CameraController {
103
+ if (!options.engine || !options.permissions) {
104
+ throw new CameraError(
105
+ 'unsupportedCapability',
106
+ 'createCameraController requires `engine` and `permissions` ports. Use the ' +
107
+ 'default adapters, or createTestCamera() in tests.',
108
+ );
109
+ }
110
+
111
+ // Bound after the guard so the closures below see non-optional ports.
112
+ const engine: CameraEngine = options.engine;
113
+ const permissions: PermissionPort = options.permissions;
114
+ const store = options.store;
115
+ const logger = withSdkSinks(options.logger ?? silentLogger);
116
+ const ttlMs = options.temporaryTtlMs ?? DEFAULT_TEMPORARY_TTL_MS;
117
+
118
+ let session: SessionSnapshot = initialSession;
119
+ let permission: CameraPermissionState = 'undetermined';
120
+ let capabilities: CapabilityProfile | null = null;
121
+ let cameraPosition: CameraPosition = 'back';
122
+ let flashMode: FlashMode = 'off';
123
+ let torchEnabled = false;
124
+ let surfaceMounted = false;
125
+ let disposed = false;
126
+ let appStatus: AppStatus = 'active';
127
+ // Set only when backgrounding cut a running session short. Foregrounding
128
+ // used to restart from any idle or stopped session, so a camera the user had
129
+ // stopped — or never started, or no longer had permission for — came back on
130
+ // with the app.
131
+ let resumeOnForeground = false;
132
+ let releasing: Promise<void> | null = null;
133
+ let warnedUnmanaged = false;
134
+ let detach: (() => void) | null = null;
135
+
136
+ const capture = new SingleFlight();
137
+ const listeners = createListenerSet<[CameraState]>({
138
+ onListenerError: () => logger.log({ type: 'session', code: 'listener-threw' }),
139
+ });
140
+
141
+ function snapshot(): CameraState {
142
+ return {
143
+ session: session.status,
144
+ permission,
145
+ capabilities,
146
+ cameraPosition,
147
+ flashMode,
148
+ torchEnabled,
149
+ capturing: capture.busy,
150
+ error: session.error
151
+ ? {
152
+ code: session.error.code,
153
+ recoverable: session.error.recoverable,
154
+ message: session.error.message,
155
+ }
156
+ : null,
157
+ };
158
+ }
159
+
160
+ let current = snapshot();
161
+
162
+ function emit(): void {
163
+ current = snapshot();
164
+ // Isolated: one throwing subscriber neither starves the others nor unwinds
165
+ // into the transition that emitted, which left the controller half-updated.
166
+ listeners.notify(current);
167
+ }
168
+
169
+ function dispatch(event: Parameters<typeof sessionReducer>[1]): void {
170
+ const next = sessionReducer(session, event);
171
+ if (next !== session) {
172
+ session = next;
173
+ logger.log({
174
+ type: 'session',
175
+ code: session.status,
176
+ recoverable: session.error?.recoverable,
177
+ });
178
+ emit();
179
+ }
180
+ }
181
+
182
+ /** Torch must never survive leaving the active state (FR-034b). */
183
+ async function forceTorchOff(): Promise<void> {
184
+ if (!torchEnabled) {
185
+ return;
186
+ }
187
+ torchEnabled = false;
188
+ try {
189
+ await engine.setTorch(false);
190
+ } catch {
191
+ // Torch-off is best effort; the session is going away regardless.
192
+ }
193
+ emit();
194
+ }
195
+
196
+ async function releaseCamera(): Promise<void> {
197
+ await forceTorchOff();
198
+ // Nothing to release. Going through STOP/STOPPED here turned an idle
199
+ // controller into `stopped` on every preview unmount.
200
+ if (session.status === 'idle' || session.status === 'stopped') {
201
+ return;
202
+ }
203
+ dispatch({ type: 'STOP' });
204
+ try {
205
+ await engine.stop();
206
+ dispatch({ type: 'STOPPED' });
207
+ } catch (error) {
208
+ dispatch({ type: 'FAIL', code: isCameraError(error) ? error.code : 'captureFailed' });
209
+ }
210
+ }
211
+
212
+ async function startEngine(startOptions: StartOptions = {}): Promise<void> {
213
+ try {
214
+ await engine.start({ cameraPosition: startOptions.cameraPosition ?? cameraPosition });
215
+ dispatch({ type: 'STARTED' });
216
+ } catch (error) {
217
+ dispatch({ type: 'FAIL', code: isCameraError(error) ? error.code : 'cameraUnavailable' });
218
+ }
219
+ }
220
+
221
+ function resumeAfterForeground(): void {
222
+ if (disposed || appStatus !== 'active' || !resumeOnForeground) {
223
+ return;
224
+ }
225
+ resumeOnForeground = false;
226
+ if (!surfaceMounted || permission !== 'granted') {
227
+ return;
228
+ }
229
+ dispatch({ type: 'FOREGROUND', surfaceMounted });
230
+ if (session.status === 'starting') {
231
+ startEngine().catch(() => undefined);
232
+ }
233
+ }
234
+
235
+ function onAppState(status: AppStatus): void {
236
+ appStatus = status;
237
+ if (status === 'background') {
238
+ resumeOnForeground ||= session.status === 'active' || session.status === 'starting';
239
+ dispatch({ type: 'BACKGROUND' });
240
+ releasing = releaseCamera().catch(() => undefined);
241
+ } else {
242
+ // Wait for a release still in flight, or the restart lands on a
243
+ // `stopping` session and is dropped.
244
+ (releasing ?? Promise.resolve()).then(resumeAfterForeground).catch(() => undefined);
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Subscribes to permission and app-state changes and runs the sweep, on first
250
+ * use rather than at construction. React may build a controller during a
251
+ * render it then throws away (StrictMode does so on purpose); construction
252
+ * that subscribed leaked a listener pair every time.
253
+ */
254
+ function attach(): void {
255
+ if (detach || disposed) {
256
+ return;
257
+ }
258
+ const unsubscribePermission = permissions.subscribe(next => {
259
+ permission = next;
260
+ logger.log({ type: 'permission', code: next });
261
+ emit();
262
+ // A revocation while running must tear the session down, not leave a
263
+ // frozen preview on screen (FR-007).
264
+ if (next !== 'granted') {
265
+ resumeOnForeground = false;
266
+ if (session.status !== 'idle' && session.status !== 'stopped') {
267
+ releaseCamera().catch(() => undefined);
268
+ }
269
+ }
270
+ });
271
+ const unsubscribeAppState = (options.subscribeToAppState ?? defaultAppStateSubscribe)(
272
+ onAppState,
273
+ );
274
+ detach = () => {
275
+ unsubscribePermission();
276
+ unsubscribeAppState();
277
+ };
278
+
279
+ // FR-029: sweep our own temp directory once, asynchronously, so it can
280
+ // never add latency to the capture path or the preview start.
281
+ if (store && options.sweepOnInit !== false) {
282
+ store
283
+ .sweep(ttlMs)
284
+ .then(removed => {
285
+ if (removed > 0) {
286
+ logger.log({ type: 'cleanup', code: `swept:${removed}` });
287
+ }
288
+ })
289
+ .catch(() => {
290
+ // A failed sweep must never block startup.
291
+ });
292
+ }
293
+ }
294
+
295
+ /** Entry guard for operations that need a live controller. */
296
+ function live(operation: string): void {
297
+ if (disposed) {
298
+ throw new CameraError('notReady', `${operation}() called on a disposed camera controller`);
299
+ }
300
+ attach();
301
+ }
302
+
303
+ /**
304
+ * Puts a package-temporary capture under the store so `cleanup()` and the
305
+ * sweep can reach it. Never throws: the capture itself succeeded, and a file
306
+ * the store cannot manage is still a usable photo.
307
+ */
308
+ async function manage(image: CapturedImage): Promise<CapturedImage> {
309
+ if (image.ownership !== 'packageTemporary') {
310
+ return image;
311
+ }
312
+ if (store?.adopt) {
313
+ try {
314
+ return { ...image, uri: await store.adopt(image.uri) };
315
+ } catch {
316
+ logger.log({ type: 'cleanup', code: 'adopt-failed' });
317
+ return image;
318
+ }
319
+ }
320
+ if (!store?.owns(image.uri) && !warnedUnmanaged) {
321
+ warnedUnmanaged = true;
322
+ logger.log({
323
+ type: 'cleanup',
324
+ code: store ? 'unmanaged:store-cannot-adopt' : 'unmanaged:no-store',
325
+ });
326
+ }
327
+ return image;
328
+ }
329
+
330
+ const controller: CameraController = {
331
+ get state() {
332
+ return current;
333
+ },
334
+
335
+ subscribe(listener) {
336
+ if (disposed) {
337
+ return () => undefined;
338
+ }
339
+ attach();
340
+ return listeners.add(listener);
341
+ },
342
+
343
+ async getPermission() {
344
+ live('getPermission');
345
+ permission = await permissions.getStatus();
346
+ emit();
347
+ return permission;
348
+ },
349
+
350
+ async requestPermission() {
351
+ live('requestPermission');
352
+ permission = 'requesting';
353
+ emit();
354
+ permission = await permissions.request();
355
+ emit();
356
+ return permission;
357
+ },
358
+
359
+ async start(startOptions: StartOptions = {}) {
360
+ live('start');
361
+ if (permission !== 'granted') {
362
+ dispatch({ type: 'FAIL', code: 'permissionDenied' });
363
+ throw new CameraError('permissionDenied', 'Camera permission is not granted');
364
+ }
365
+ if (!canStart(session.status)) {
366
+ throw new CameraError('sessionConflict', `Session already ${session.status}`);
367
+ }
368
+ if (startOptions.cameraPosition) {
369
+ cameraPosition = startOptions.cameraPosition;
370
+ }
371
+ dispatch({ type: 'START' });
372
+ await startEngine(startOptions);
373
+ if (session.error) {
374
+ throw session.error;
375
+ }
376
+ },
377
+
378
+ async pause() {
379
+ if (disposed) {
380
+ return;
381
+ }
382
+ await forceTorchOff();
383
+ dispatch({ type: 'PAUSE' });
384
+ },
385
+
386
+ async resume() {
387
+ live('resume');
388
+ dispatch({ type: 'RESUME' });
389
+ if (session.status === 'starting') {
390
+ await startEngine();
391
+ }
392
+ },
393
+
394
+ async stop() {
395
+ // An explicit stop is the user's decision; foregrounding must not undo it.
396
+ resumeOnForeground = false;
397
+ if (disposed) {
398
+ return;
399
+ }
400
+ await releaseCamera();
401
+ },
402
+
403
+ async capture(request: CaptureRequest = {}) {
404
+ live('capture');
405
+ const context: CaptureContext = {
406
+ engine,
407
+ sessionStatus: session.status,
408
+ permissionGranted: permission === 'granted',
409
+ capabilities,
410
+ cameraPosition,
411
+ flashMode,
412
+ };
413
+ // Guards run before the single-flight slot is taken so a rejected
414
+ // request cannot block a subsequent legal one.
415
+ assertCaptureAllowed(context, request);
416
+
417
+ try {
418
+ const result = await capture.run(async () => {
419
+ emit();
420
+ const raw = await engine.capture({
421
+ ...request,
422
+ flashMode: request.flashMode ?? flashMode,
423
+ cameraPosition: request.cameraPosition ?? cameraPosition,
424
+ });
425
+ return manage(finalizeResult(raw, request, context));
426
+ });
427
+ logger.log({ type: 'capture', code: 'succeeded' });
428
+ return result;
429
+ } catch (error) {
430
+ // The contract promises a CameraError; a raw native error carries
431
+ // no code to branch on and its message may hold a file path.
432
+ const failure = isCameraError(error)
433
+ ? error
434
+ : new CameraError('captureFailed', 'The camera failed to capture a photo');
435
+ logger.log({ type: 'capture', code: failure.code, recoverable: failure.recoverable });
436
+ throw failure;
437
+ } finally {
438
+ // Without this a failed capture left `capturing: true` published
439
+ // until some unrelated change emitted again.
440
+ emit();
441
+ }
442
+ },
443
+
444
+ async cleanup(image: CapturedImage | string) {
445
+ const uri = typeof image === 'string' ? image : image.uri;
446
+ if (!store) {
447
+ return;
448
+ }
449
+ // Refuse anything we did not create rather than deleting an arbitrary
450
+ // path, which also covers every appOwned artifact (FR-026b, FR-028).
451
+ if (!store.owns(uri)) {
452
+ logger.log({ type: 'cleanup', code: 'refused-not-owned' });
453
+ return;
454
+ }
455
+ await store.remove(uri);
456
+ logger.log({ type: 'cleanup', code: 'removed' });
457
+ },
458
+
459
+ async getCapabilities() {
460
+ live('getCapabilities');
461
+ try {
462
+ capabilities = await engine.getCapabilities();
463
+ } catch {
464
+ capabilities = EMPTY_CAPABILITIES;
465
+ }
466
+ logger.log({
467
+ type: 'capability',
468
+ code: capabilities.hasCameraHardware ? 'available' : 'no-hardware',
469
+ });
470
+ emit();
471
+ return capabilities;
472
+ },
473
+
474
+ setFlashMode(mode: FlashMode) {
475
+ assertSupported(mode === 'off' || capabilities?.hasFlash === true, `flash mode "${mode}"`);
476
+ flashMode = mode;
477
+ emit();
478
+ },
479
+
480
+ async setTorch(enabled: boolean) {
481
+ if (disposed && !enabled) {
482
+ return;
483
+ }
484
+ live('setTorch');
485
+ if (enabled) {
486
+ assertSupported(supportsTorch(capabilities), 'torch');
487
+ }
488
+ await engine.setTorch(enabled);
489
+ torchEnabled = enabled;
490
+ emit();
491
+ },
492
+
493
+ reportSurfaceUnavailable() {
494
+ if (disposed) {
495
+ return;
496
+ }
497
+ logger.log({ type: 'session', code: 'surface-unavailable', recoverable: false });
498
+ dispatch({ type: 'FAIL', code: 'cameraUnavailable' });
499
+ },
500
+
501
+ setSurfaceMounted(mounted: boolean) {
502
+ if (disposed) {
503
+ return;
504
+ }
505
+ surfaceMounted = mounted;
506
+ },
507
+
508
+ async dispose() {
509
+ if (disposed) {
510
+ return;
511
+ }
512
+ disposed = true;
513
+ resumeOnForeground = false;
514
+ detach?.();
515
+ detach = null;
516
+ await releaseCamera();
517
+ listeners.clear();
518
+ },
519
+ };
520
+
521
+ return controller;
522
+ }