@blotch/angular-lynx-testing-library 22.3.1 → 22.3.3

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 (69) hide show
  1. package/dist/app-state.d.ts +34 -0
  2. package/dist/app-state.d.ts.map +1 -0
  3. package/dist/app-state.js +33 -0
  4. package/dist/apple-sign-in.d.ts +116 -0
  5. package/dist/apple-sign-in.d.ts.map +1 -0
  6. package/dist/apple-sign-in.js +179 -0
  7. package/dist/audio-recorder.d.ts +95 -0
  8. package/dist/audio-recorder.d.ts.map +1 -0
  9. package/dist/audio-recorder.js +250 -0
  10. package/dist/back-button.d.ts +43 -0
  11. package/dist/back-button.d.ts.map +1 -0
  12. package/dist/back-button.js +77 -0
  13. package/dist/barcode-scanner.d.ts +59 -0
  14. package/dist/barcode-scanner.d.ts.map +1 -0
  15. package/dist/barcode-scanner.js +100 -0
  16. package/dist/biometrics.d.ts +79 -0
  17. package/dist/biometrics.d.ts.map +1 -0
  18. package/dist/biometrics.js +151 -0
  19. package/dist/bluetooth.d.ts +121 -0
  20. package/dist/bluetooth.d.ts.map +1 -0
  21. package/dist/bluetooth.js +369 -0
  22. package/dist/calendar.d.ts +68 -0
  23. package/dist/calendar.d.ts.map +1 -0
  24. package/dist/calendar.js +120 -0
  25. package/dist/file-picker.d.ts +76 -0
  26. package/dist/file-picker.d.ts.map +1 -0
  27. package/dist/file-picker.js +125 -0
  28. package/dist/fire-event.d.ts.map +1 -1
  29. package/dist/fire-event.js +58 -8
  30. package/dist/geolocation.d.ts +94 -0
  31. package/dist/geolocation.d.ts.map +1 -0
  32. package/dist/geolocation.js +255 -0
  33. package/dist/global-props.d.ts +17 -0
  34. package/dist/global-props.d.ts.map +1 -0
  35. package/dist/global-props.js +35 -0
  36. package/dist/image-picker.d.ts +84 -0
  37. package/dist/image-picker.d.ts.map +1 -0
  38. package/dist/image-picker.js +140 -0
  39. package/dist/index.d.ts +35 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +19 -0
  42. package/dist/motion.d.ts +90 -0
  43. package/dist/motion.d.ts.map +1 -0
  44. package/dist/motion.js +169 -0
  45. package/dist/network.d.ts +26 -0
  46. package/dist/network.d.ts.map +1 -0
  47. package/dist/network.js +31 -0
  48. package/dist/nfc.d.ts +85 -0
  49. package/dist/nfc.d.ts.map +1 -0
  50. package/dist/nfc.js +253 -0
  51. package/dist/photo-library.d.ts +58 -0
  52. package/dist/photo-library.d.ts.map +1 -0
  53. package/dist/photo-library.js +91 -0
  54. package/dist/render.d.ts.map +1 -1
  55. package/dist/render.js +19 -1
  56. package/dist/setup.js +86 -7
  57. package/dist/share-target.d.ts +56 -0
  58. package/dist/share-target.d.ts.map +1 -0
  59. package/dist/share-target.js +92 -0
  60. package/dist/store-review.d.ts +30 -0
  61. package/dist/store-review.d.ts.map +1 -0
  62. package/dist/store-review.js +49 -0
  63. package/dist/tracking.d.ts +60 -0
  64. package/dist/tracking.d.ts.map +1 -0
  65. package/dist/tracking.js +94 -0
  66. package/dist/wifi.d.ts +77 -0
  67. package/dist/wifi.d.ts.map +1 -0
  68. package/dist/wifi.js +148 -0
  69. package/package.json +3 -3
@@ -0,0 +1,151 @@
1
+ /** What `LynxBiometrics` and `LynxSecureStorage` call, as the shells name it. */
2
+ const MODULE = 'AngularLynxBiometrics';
3
+ /** The phone a test starts with: Face ID, set up, behind a passcode. */
4
+ const DEFAULT_PHONE = {
5
+ type: 'faceID',
6
+ enrolled: true,
7
+ deviceCredential: true,
8
+ };
9
+ /**
10
+ * Gives the environment's background thread an `AngularLynxBiometrics`
11
+ * module, as the apps `ng build --platform` makes with
12
+ * `permissions.biometrics` have. It stands for a phone with Face ID set up
13
+ * (see {@link setBiometrics}), where each prompt succeeds unless a spec
14
+ * queues another outcome ({@link queueBiometricResult}), and it keeps the
15
+ * values `LynxSecureStorage` stores with `requireBiometrics`. The runtime
16
+ * reaches it through the background thread, as it reaches the shells'
17
+ * module, so specs see the runtime's own behavior.
18
+ *
19
+ * It runs each time the environment injects the background thread's
20
+ * globals: when it's created, and on the reset after each test, so each test
21
+ * starts with that phone, nothing queued and nothing stored.
22
+ */
23
+ export const installBiometricsModule = (threadGlobals) => {
24
+ const module = {
25
+ phone: { ...DEFAULT_PHONE },
26
+ queued: [],
27
+ prompts: [],
28
+ guarded: new Map(),
29
+ availability(done) {
30
+ done({ ...this.phone });
31
+ },
32
+ authenticate(options, done) {
33
+ const allowDeviceCredential = options.allowDeviceCredential === true;
34
+ const refusal = refuse(this.phone, allowDeviceCredential);
35
+ if (refusal)
36
+ return done(refusal);
37
+ this.prompts.push({ reason: options.reason, allowDeviceCredential });
38
+ done(outcome(this.queued.shift()));
39
+ },
40
+ getItem(key, reason, done) {
41
+ const value = this.guarded.get(key);
42
+ if (value === undefined)
43
+ return done({});
44
+ // A phone that can't show the prompt can't open the value either.
45
+ const refusal = refuse(this.phone, false);
46
+ if (refusal)
47
+ return done(refusal);
48
+ this.prompts.push({ reason, allowDeviceCredential: false });
49
+ const result = outcome(this.queued.shift());
50
+ done(result['error'] === undefined ? { value } : result);
51
+ },
52
+ setItem(key, value, done) {
53
+ // Biometric values need a sensor, a face or finger set up and a
54
+ // passcode, as on a phone.
55
+ if (this.phone.type === 'none' || !this.phone.deviceCredential) {
56
+ return done({
57
+ error: 'unavailable',
58
+ message: 'This phone has no biometrics to keep the value behind.',
59
+ });
60
+ }
61
+ if (!this.phone.enrolled)
62
+ return done({ error: 'notEnrolled' });
63
+ this.guarded.set(key, value);
64
+ done({});
65
+ },
66
+ removeItem(key, done) {
67
+ this.guarded.delete(key);
68
+ done({});
69
+ },
70
+ clear(done) {
71
+ this.guarded.clear();
72
+ done({});
73
+ },
74
+ };
75
+ threadGlobals.NativeModules = {
76
+ ...threadGlobals.NativeModules,
77
+ [MODULE]: module,
78
+ };
79
+ };
80
+ /**
81
+ * Why `phone` can't show the prompt, if it can't.
82
+ */
83
+ const refuse = (phone, allowDeviceCredential) => {
84
+ if (allowDeviceCredential && phone.deviceCredential)
85
+ return undefined;
86
+ if (phone.type === 'none')
87
+ return { error: 'unavailable' };
88
+ if (!phone.enrolled)
89
+ return { error: 'notEnrolled' };
90
+ return undefined;
91
+ };
92
+ const outcome = (result = 'success') => result === 'success' ? {} : { error: result };
93
+ /**
94
+ * The fake module, read through the environment rather than kept here:
95
+ * under `ng test`, the setup file and the specs can load different copies of
96
+ * this module.
97
+ */
98
+ const fakeModule = (helper) => {
99
+ const module = globalThis.lynxTestingEnv?.backgroundThread.globalThis
100
+ .NativeModules?.[MODULE];
101
+ if (!module) {
102
+ throw new Error(`${helper}() needs the testing library's environment, which its setup file installs.`);
103
+ }
104
+ return module;
105
+ };
106
+ /**
107
+ * Describes the phone `LynxBiometrics` sees in this test: its sensor,
108
+ * whether a face or a finger is set up, and whether it has a passcode. Each
109
+ * test starts with Face ID set up behind a passcode; what isn't given keeps
110
+ * that value. `{ type: 'none' }` is a phone without a sensor, or an app
111
+ * without `permissions.biometrics`: prompts then reject with `unavailable`,
112
+ * as does `LynxSecureStorage`'s `requireBiometrics`.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * setBiometrics({ type: 'fingerprint', enrolled: false });
117
+ * await render(Unlock);
118
+ * expect(screen.getByText('Set up a fingerprint to unlock')).toBeInTheDocument();
119
+ * ```
120
+ */
121
+ export const setBiometrics = (phone) => {
122
+ const module = fakeModule('setBiometrics');
123
+ module.phone = { ...module.phone, ...phone };
124
+ };
125
+ /**
126
+ * Has the next biometric prompt end with `result`: the person confirms
127
+ * (`success`), or `LynxBiometrics.authenticate()`, or a `LynxSecureStorage`
128
+ * read of a value kept behind biometrics, rejects with a `BiometricsError`
129
+ * of that code. Results queue in order, one per prompt; once they run out,
130
+ * prompts succeed. A prompt the phone can't show (see {@link setBiometrics})
131
+ * takes none.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * queueBiometricResult('canceled');
136
+ * fireEvent.tap(screen.getByText('Unlock'));
137
+ * await waitForUpdate();
138
+ * expect(screen.getByText('Still locked')).toBeInTheDocument();
139
+ * ```
140
+ */
141
+ export const queueBiometricResult = (result) => {
142
+ fakeModule('queueBiometricResult').queued.push(result);
143
+ };
144
+ /**
145
+ * The biometric prompts the app has shown in this test, oldest first: each
146
+ * `authenticate()`, and each read of a value kept behind biometrics. Each
147
+ * test starts with none.
148
+ */
149
+ export const biometricPrompts = () => [
150
+ ...fakeModule('biometricPrompts').prompts,
151
+ ];
@@ -0,0 +1,121 @@
1
+ import type { BluetoothCharacteristicProperty, BluetoothState } from '@blotch/angular-lynx';
2
+ /** A characteristic of a {@link FakeBluetoothDevice}. */
3
+ export type FakeBluetoothCharacteristic = {
4
+ /** What it lets a connection do. By default it can be read, written and notified. */
5
+ readonly properties?: readonly BluetoothCharacteristicProperty[];
6
+ /** What a read gets. Change it to change what the next read gets. */
7
+ value?: Uint8Array;
8
+ /**
9
+ * Called with each value the app writes, and the device, so a spec can
10
+ * answer the way the real device does, such as notifying a status.
11
+ */
12
+ readonly onWrite?: (value: Uint8Array, device: FakeBluetoothDeviceRef) => void;
13
+ };
14
+ /** A device {@link addBluetoothDevice} puts in range of the app. */
15
+ export type FakeBluetoothDevice = {
16
+ /** What `LynxBluetooth.connect()` takes. */
17
+ readonly id: string;
18
+ readonly name?: string | null;
19
+ /** Its signal strength, in dBm. */
20
+ readonly rssi?: number;
21
+ /**
22
+ * The services it advertises, which a scan matches against. By default,
23
+ * every service in {@link services}.
24
+ */
25
+ readonly advertisedServices?: readonly string[];
26
+ /** The data it advertises for a service, by the service's UUID. */
27
+ readonly serviceData?: Readonly<Record<string, Uint8Array>>;
28
+ /** The data it advertises for a manufacturer, by company identifier. */
29
+ readonly manufacturerData?: Readonly<Record<number, Uint8Array>>;
30
+ /** Its services: each service's characteristics, by UUID. */
31
+ readonly services?: Readonly<Record<string, Readonly<Record<string, FakeBluetoothCharacteristic>>>>;
32
+ /**
33
+ * The most bytes one write without response carries. A longer one is
34
+ * refused, as the shells refuse it, so a spec catches an app that doesn't
35
+ * split what it writes.
36
+ */
37
+ readonly maxWriteLength?: number;
38
+ };
39
+ /** A value the app wrote to a {@link FakeBluetoothDevice}. */
40
+ export type FakeBluetoothWrite = {
41
+ readonly service: string;
42
+ readonly characteristic: string;
43
+ readonly value: Uint8Array;
44
+ readonly withResponse: boolean;
45
+ };
46
+ /** What {@link addBluetoothDevice} gives a spec to drive the device with. */
47
+ export type FakeBluetoothDeviceRef = {
48
+ /** Whether the app is connected to it. */
49
+ readonly connected: boolean;
50
+ /** What the app wrote to it, oldest first. */
51
+ readonly writes: readonly FakeBluetoothWrite[];
52
+ /**
53
+ * Sends a value from a characteristic, as a notification. It reaches the
54
+ * app only while it's connected and subscribed to the characteristic.
55
+ */
56
+ notify(service: string, characteristic: string, value: Uint8Array): void;
57
+ /** Ends the app's connection from the device's side, as going out of range does. */
58
+ disconnect(): void;
59
+ };
60
+ /**
61
+ * Gives the environment's background thread an `AngularLynxBluetooth`
62
+ * module, as the apps `ng build --platform` makes have when angular.json's
63
+ * `permissions` list `bluetooth`. The devices in range are the ones
64
+ * {@link addBluetoothDevice} adds, and the radio is on and allowed until
65
+ * {@link setBluetoothState} says otherwise. `LynxBluetooth` reaches it
66
+ * through the background thread, as it reaches the shells' module, so specs
67
+ * see the runtime's own behavior.
68
+ *
69
+ * It runs each time the environment injects the background thread's
70
+ * globals: when it's created, and on the reset after each test, so each test
71
+ * starts with no devices and the radio on.
72
+ */
73
+ export declare const installBluetoothModule: (threadGlobals: {
74
+ NativeModules?: Record<string, unknown>;
75
+ }) => void;
76
+ /**
77
+ * Puts a Bluetooth LE device in range of the app, for `LynxBluetooth` to
78
+ * find, connect to and talk to as it would a real one. A scan that's running
79
+ * sees it at once, and one that starts later sees it as it starts. Each test
80
+ * starts with none, and adding an id a second time throws.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * const frame = addBluetoothDevice({
85
+ * id: 'frame',
86
+ * name: 'Blotch - XyZ1',
87
+ * services: {
88
+ * [SETUP_SERVICE]: {
89
+ * [CREDENTIALS]: {
90
+ * properties: ['write'],
91
+ * onWrite: (_value, device) =>
92
+ * device.notify(SETUP_SERVICE, STATUS, encode('connected')),
93
+ * },
94
+ * [STATUS]: { properties: ['notify'] },
95
+ * },
96
+ * },
97
+ * });
98
+ * await render(SetUpFrame);
99
+ * fireEvent.tap(await screen.findByText('Blotch - XyZ1'));
100
+ * // …
101
+ * expect(frame.writes).toHaveLength(1);
102
+ * ```
103
+ */
104
+ export declare const addBluetoothDevice: (device: FakeBluetoothDevice) => FakeBluetoothDeviceRef;
105
+ /**
106
+ * Sets the state of the phone's Bluetooth, as the person turning it off or
107
+ * refusing permission does, so a spec can check what the app shows then.
108
+ * Anything but `poweredOn` ends a running scan and every connection, as it
109
+ * does on a phone. `unknown` stands for not asked yet: the person allows it
110
+ * when `LynxBluetooth` asks, as `requestPermission()`, `scan()` and
111
+ * `connect()` do.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * setBluetoothState('poweredOff');
116
+ * await render(SetUpFrame);
117
+ * expect(await screen.findByText('Turn on Bluetooth')).toBeInTheDocument();
118
+ * ```
119
+ */
120
+ export declare const setBluetoothState: (state: BluetoothState) => void;
121
+ //# sourceMappingURL=bluetooth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bluetooth.d.ts","sourceRoot":"","sources":["../src/bluetooth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+BAA+B,EAC/B,cAAc,EACf,MAAM,sBAAsB,CAAC;AAM9B,yDAAyD;AACzD,MAAM,MAAM,2BAA2B,GAAG;IACxC,qFAAqF;IACrF,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,+BAA+B,EAAE,CAAC;IACjE,qEAAqE;IACrE,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,CACjB,KAAK,EAAE,UAAU,EACjB,MAAM,EAAE,sBAAsB,KAC3B,IAAI,CAAC;CACX,CAAC;AAEF,oEAAoE;AACpE,MAAM,MAAM,mBAAmB,GAAG;IAChC,4CAA4C;IAC5C,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,mCAAmC;IACnC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,kBAAkB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChD,mEAAmE;IACnE,QAAQ,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;IAC5D,wEAAwE;IACxE,QAAQ,CAAC,gBAAgB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;IACjE,6DAA6D;IAC7D,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAC1B,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,CAAC,CAAC,CACtE,CAAC;IACF;;;;OAIG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;CAClC,CAAC;AAEF,8DAA8D;AAC9D,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC;CAChC,CAAC;AAEF,6EAA6E;AAC7E,MAAM,MAAM,sBAAsB,GAAG;IACnC,0CAA0C;IAC1C,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,8CAA8C;IAC9C,QAAQ,CAAC,MAAM,EAAE,SAAS,kBAAkB,EAAE,CAAC;IAC/C;;;OAGG;IACH,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,GAAG,IAAI,CAAC;IACzE,oFAAoF;IACpF,UAAU,IAAI,IAAI,CAAC;CACpB,CAAC;AA8LF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,sBAAsB,GAAI,eAAe;IACpD,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACzC,KAAG,IAgKH,CAAC;AAmBF;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,eAAO,MAAM,kBAAkB,GAC7B,QAAQ,mBAAmB,KAC1B,sBA6CF,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,iBAAiB,GAAI,OAAO,cAAc,KAAG,IAWzD,CAAC"}
@@ -0,0 +1,369 @@
1
+ /** What `LynxBluetooth` calls and hears, named as the shells name them. */
2
+ const MODULE = 'AngularLynxBluetooth';
3
+ const EVENT = 'angularLynxBluetooth';
4
+ const DEFAULT_PROPERTIES = [
5
+ 'read',
6
+ 'write',
7
+ 'notify',
8
+ ];
9
+ /** A device's write-without-response limit when the spec gives none. */
10
+ const DEFAULT_MAX_WRITE_LENGTH = 182;
11
+ /** The longest attribute value, and so write with a response, ATT allows. */
12
+ const MAX_ATTRIBUTE_LENGTH = 512;
13
+ const BASE_UUID_TAIL = '-0000-1000-8000-00805f9b34fb';
14
+ /**
15
+ * A UUID as the runtime sends and expects them, so a spec can name a
16
+ * service either way.
17
+ */
18
+ const canonical = (uuid) => {
19
+ const text = uuid.toLowerCase();
20
+ if (text.length === 4)
21
+ return `0000${text}${BASE_UUID_TAIL}`;
22
+ if (text.length === 8)
23
+ return `${text}${BASE_UUID_TAIL}`;
24
+ return text;
25
+ };
26
+ const toBase64 = (bytes) => {
27
+ let binary = '';
28
+ for (const byte of bytes)
29
+ binary += String.fromCharCode(byte);
30
+ return btoa(binary);
31
+ };
32
+ const fromBase64 = (base64) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
33
+ const failure = (error, message) => ({ error, message });
34
+ /**
35
+ * Why the radio can't be used in `state`, as the error the shells give, or
36
+ * undefined when it's on.
37
+ */
38
+ const unusable = (state) => {
39
+ if (state === 'poweredOn')
40
+ return undefined;
41
+ const code = state === 'unsupported' ||
42
+ state === 'unauthorized' ||
43
+ state === 'poweredOff'
44
+ ? state
45
+ : 'failed';
46
+ return failure(code, `Bluetooth is ${state}.`);
47
+ };
48
+ const environment = () => globalThis.lynxTestingEnv;
49
+ /**
50
+ * Sends one of the shells' global events. They arrive on the background
51
+ * thread, whose listener calls the app's on the main thread, so the event is
52
+ * sent from it. A fake method the runtime called is on that thread already;
53
+ * a spec is on the main thread, which comes back afterwards.
54
+ */
55
+ const emit = (payload) => {
56
+ const env = environment();
57
+ const background = env.backgroundThread.globalThis;
58
+ const onMainThread = globalThis.lynx !== background.lynx;
59
+ if (onMainThread)
60
+ env.switchToBackgroundThread();
61
+ try {
62
+ background.lynx.getJSModule('GlobalEventEmitter').emit(EVENT, [payload]);
63
+ }
64
+ finally {
65
+ if (onMainThread)
66
+ env.switchToMainThread();
67
+ }
68
+ };
69
+ /**
70
+ * The most bytes a write without response to `device` carries: never more
71
+ * than an attribute holds, as the shells cap it however large the MTU.
72
+ */
73
+ const maxWriteLength = (device) => Math.min(device.maxWriteLength ?? DEFAULT_MAX_WRITE_LENGTH, MAX_ATTRIBUTE_LENGTH);
74
+ const sighting = (device, scan) => ({
75
+ type: 'device',
76
+ scan,
77
+ device: {
78
+ id: device.id,
79
+ name: device.name ?? null,
80
+ rssi: device.rssi ?? -50,
81
+ services: advertised(device),
82
+ serviceData: Object.fromEntries(Object.entries(device.serviceData ?? {}).map(([uuid, data]) => [
83
+ canonical(uuid),
84
+ toBase64(data),
85
+ ])),
86
+ manufacturerData: Object.fromEntries(Object.entries(device.manufacturerData ?? {}).map(([company, data]) => [
87
+ company,
88
+ toBase64(data),
89
+ ])),
90
+ },
91
+ });
92
+ const advertised = (device) => (device.advertisedServices ?? Object.keys(device.services ?? {})).map(canonical);
93
+ const matches = (device, services) => services.length === 0 ||
94
+ advertised(device).some((uuid) => services.includes(uuid));
95
+ /**
96
+ * The characteristic a call names, by the runtime's canonical UUIDs.
97
+ */
98
+ const characteristicOf = (device, service, characteristic) => {
99
+ const services = Object.entries(device.services ?? {});
100
+ const characteristics = services.find(([uuid]) => canonical(uuid) === service)?.[1];
101
+ return Object.entries(characteristics ?? {}).find(([uuid]) => canonical(uuid) === characteristic)?.[1];
102
+ };
103
+ /**
104
+ * Gives the environment's background thread an `AngularLynxBluetooth`
105
+ * module, as the apps `ng build --platform` makes have when angular.json's
106
+ * `permissions` list `bluetooth`. The devices in range are the ones
107
+ * {@link addBluetoothDevice} adds, and the radio is on and allowed until
108
+ * {@link setBluetoothState} says otherwise. `LynxBluetooth` reaches it
109
+ * through the background thread, as it reaches the shells' module, so specs
110
+ * see the runtime's own behavior.
111
+ *
112
+ * It runs each time the environment injects the background thread's
113
+ * globals: when it's created, and on the reset after each test, so each test
114
+ * starts with no devices and the radio on.
115
+ */
116
+ export const installBluetoothModule = (threadGlobals) => {
117
+ const devices = new Map();
118
+ const connectedDevice = (id, done) => {
119
+ const device = devices.get(id);
120
+ if (device?.connected)
121
+ return device;
122
+ done(failure('notConnected', `${id} isn't connected.`));
123
+ return undefined;
124
+ };
125
+ /**
126
+ * The characteristic of a connected device a call names, if it can do
127
+ * `property`; otherwise calls back with why not.
128
+ */
129
+ const usable = (id, service, characteristic, properties, done) => {
130
+ const device = connectedDevice(id, done);
131
+ if (!device)
132
+ return undefined;
133
+ const found = characteristicOf(device.spec, service, characteristic);
134
+ if (!found) {
135
+ done(failure('notFound', `${id} has no characteristic ${characteristic}.`));
136
+ return undefined;
137
+ }
138
+ const allowed = found.properties ?? DEFAULT_PROPERTIES;
139
+ if (!properties.some((property) => allowed.includes(property))) {
140
+ done(failure('failed', `${characteristic} can't ${properties.join(' or ')}.`));
141
+ return undefined;
142
+ }
143
+ return { device, characteristic: found };
144
+ };
145
+ /**
146
+ * Asks the person for permission when they haven't been asked, as the
147
+ * shells do before the first scan or connection: they allow it, unless a
148
+ * spec said otherwise.
149
+ */
150
+ const ask = () => {
151
+ if (module.state !== 'unknown')
152
+ return;
153
+ module.state = 'poweredOn';
154
+ emit({ type: 'state', state: module.state });
155
+ };
156
+ const module = {
157
+ state: 'poweredOn',
158
+ devices,
159
+ scanning: null,
160
+ getState: (done) => done({ state: module.state }),
161
+ requestPermission: (done) => {
162
+ ask();
163
+ done({ state: module.state });
164
+ },
165
+ startScan: ({ services, scan }, done) => {
166
+ ask();
167
+ const error = unusable(module.state);
168
+ if (error)
169
+ return done(error);
170
+ module.scanning = { id: scan, services };
171
+ done({});
172
+ for (const { spec } of devices.values()) {
173
+ if (matches(spec, services))
174
+ emit(sighting(spec, scan));
175
+ }
176
+ },
177
+ stopScan: (done) => {
178
+ module.scanning = null;
179
+ done({});
180
+ },
181
+ connect: (id, _options, done) => {
182
+ ask();
183
+ const error = unusable(module.state);
184
+ if (error)
185
+ return done(error);
186
+ const device = devices.get(id);
187
+ if (!device)
188
+ return done(failure('notFound', `No device is ${id}.`));
189
+ device.connected = true;
190
+ const { spec } = device;
191
+ done({
192
+ id,
193
+ name: spec.name ?? null,
194
+ maxWriteLength: maxWriteLength(spec),
195
+ services: Object.entries(spec.services ?? {}).map(([uuid, characteristics]) => ({
196
+ uuid: canonical(uuid),
197
+ characteristics: Object.entries(characteristics).map(([characteristic, { properties }]) => ({
198
+ uuid: canonical(characteristic),
199
+ properties: properties ?? DEFAULT_PROPERTIES,
200
+ })),
201
+ })),
202
+ });
203
+ },
204
+ disconnect: (id, done) => {
205
+ const device = devices.get(id);
206
+ if (device) {
207
+ device.connected = false;
208
+ device.subscribed.clear();
209
+ }
210
+ done({});
211
+ },
212
+ read: (id, service, characteristic, done) => {
213
+ const found = usable(id, service, characteristic, ['read'], done);
214
+ if (!found)
215
+ return;
216
+ done({ value: toBase64(found.characteristic.value ?? new Uint8Array()) });
217
+ },
218
+ write: (id, service, characteristic, value, withResponse, done) => {
219
+ const found = usable(id, service, characteristic, [withResponse ? 'write' : 'writeWithoutResponse'], done);
220
+ if (!found)
221
+ return;
222
+ const bytes = fromBase64(value);
223
+ const limit = withResponse
224
+ ? MAX_ATTRIBUTE_LENGTH
225
+ : maxWriteLength(found.device.spec);
226
+ if (bytes.length > limit) {
227
+ return done(failure('failed', `The value is ${bytes.length} bytes, and this write takes at most ${limit}.`));
228
+ }
229
+ found.device.writes.push({
230
+ service,
231
+ characteristic,
232
+ value: bytes,
233
+ withResponse,
234
+ });
235
+ done({});
236
+ found.characteristic.onWrite?.(bytes, found.device.ref);
237
+ },
238
+ setNotifications: (id, service, characteristic, enabled, done) => {
239
+ const found = usable(id, service, characteristic, ['notify', 'indicate'], done);
240
+ if (!found)
241
+ return;
242
+ const key = `${service} ${characteristic}`;
243
+ if (enabled)
244
+ found.device.subscribed.add(key);
245
+ else
246
+ found.device.subscribed.delete(key);
247
+ done({});
248
+ },
249
+ };
250
+ threadGlobals.NativeModules = {
251
+ ...threadGlobals.NativeModules,
252
+ [MODULE]: module,
253
+ };
254
+ };
255
+ /**
256
+ * The fake module of this test's environment. Read through the environment
257
+ * rather than kept here: under `ng test`, the setup file and the specs can
258
+ * load different copies of this module.
259
+ */
260
+ const fakeModule = (caller) => {
261
+ const module = environment()?.backgroundThread.globalThis.NativeModules?.[MODULE];
262
+ if (!module) {
263
+ throw new Error(`${caller}() needs the testing library's environment, which its setup file installs.`);
264
+ }
265
+ return module;
266
+ };
267
+ /**
268
+ * Puts a Bluetooth LE device in range of the app, for `LynxBluetooth` to
269
+ * find, connect to and talk to as it would a real one. A scan that's running
270
+ * sees it at once, and one that starts later sees it as it starts. Each test
271
+ * starts with none, and adding an id a second time throws.
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * const frame = addBluetoothDevice({
276
+ * id: 'frame',
277
+ * name: 'Blotch - XyZ1',
278
+ * services: {
279
+ * [SETUP_SERVICE]: {
280
+ * [CREDENTIALS]: {
281
+ * properties: ['write'],
282
+ * onWrite: (_value, device) =>
283
+ * device.notify(SETUP_SERVICE, STATUS, encode('connected')),
284
+ * },
285
+ * [STATUS]: { properties: ['notify'] },
286
+ * },
287
+ * },
288
+ * });
289
+ * await render(SetUpFrame);
290
+ * fireEvent.tap(await screen.findByText('Blotch - XyZ1'));
291
+ * // …
292
+ * expect(frame.writes).toHaveLength(1);
293
+ * ```
294
+ */
295
+ export const addBluetoothDevice = (device) => {
296
+ const module = fakeModule('addBluetoothDevice');
297
+ // Replacing it would leave the app's connection to it looking open while
298
+ // its calls fail.
299
+ if (module.devices.has(device.id)) {
300
+ throw new Error(`addBluetoothDevice() already added a device with the id ${device.id}.`);
301
+ }
302
+ const writes = [];
303
+ const subscribed = new Set();
304
+ const entry = {
305
+ spec: device,
306
+ writes,
307
+ subscribed,
308
+ connected: false,
309
+ ref: {
310
+ get connected() {
311
+ return entry.connected;
312
+ },
313
+ writes,
314
+ notify: (service, characteristic, value) => {
315
+ const key = `${canonical(service)} ${canonical(characteristic)}`;
316
+ if (!entry.connected || !subscribed.has(key))
317
+ return;
318
+ emit({
319
+ type: 'value',
320
+ id: device.id,
321
+ service: canonical(service),
322
+ characteristic: canonical(characteristic),
323
+ value: toBase64(value),
324
+ });
325
+ },
326
+ disconnect: () => {
327
+ if (!entry.connected)
328
+ return;
329
+ entry.connected = false;
330
+ subscribed.clear();
331
+ emit({ type: 'disconnected', id: device.id });
332
+ },
333
+ },
334
+ };
335
+ module.devices.set(device.id, entry);
336
+ if (module.scanning && matches(device, module.scanning.services)) {
337
+ emit(sighting(device, module.scanning.id));
338
+ }
339
+ return entry.ref;
340
+ };
341
+ /**
342
+ * Sets the state of the phone's Bluetooth, as the person turning it off or
343
+ * refusing permission does, so a spec can check what the app shows then.
344
+ * Anything but `poweredOn` ends a running scan and every connection, as it
345
+ * does on a phone. `unknown` stands for not asked yet: the person allows it
346
+ * when `LynxBluetooth` asks, as `requestPermission()`, `scan()` and
347
+ * `connect()` do.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * setBluetoothState('poweredOff');
352
+ * await render(SetUpFrame);
353
+ * expect(await screen.findByText('Turn on Bluetooth')).toBeInTheDocument();
354
+ * ```
355
+ */
356
+ export const setBluetoothState = (state) => {
357
+ const module = fakeModule('setBluetoothState');
358
+ module.state = state;
359
+ emit({ type: 'state', state });
360
+ const error = unusable(state);
361
+ if (!error)
362
+ return;
363
+ if (module.scanning) {
364
+ emit({ type: 'scanStopped', scan: module.scanning.id, ...error });
365
+ module.scanning = null;
366
+ }
367
+ for (const { ref } of module.devices.values())
368
+ ref.disconnect();
369
+ };