@d2m/april-serial 0.0.0-stage → 0.1.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.
@@ -0,0 +1,6 @@
1
+ import type { AprilSerialApi } from "./serialFacade.js";
2
+ declare module "@d2m/april" {
3
+ interface AprilExtensions {
4
+ readonly serial?: AprilSerialApi;
5
+ }
6
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import "./augmentApril.js";
2
+ export { createSerialFacade, decodeSerialBinaryPayload, encodeSerialBinaryPayload, } from "./serialFacade.js";
3
+ declare const moduleDefinition: import("@d2m/april-plugin").AprilPluginModuleDefinition;
4
+ export default moduleDefinition;
5
+ export type { AprilSerialApi, AprilSerialBinaryPayload, AprilSerialConnection, AprilSerialData, SerialAdapterState, SerialAdapterStateEvent, SerialConnectionCapabilities, SerialConnectionStateEvent, SerialDataEvent, SerialDeviceDescriptor, SerialDeviceSnapshot, SerialFlushOptions, SerialListOptions, SerialOpenOptions, SerialOperationSupport, SerialReadOptions, SerialSettings, SerialSignalSupport, SerialSignalUpdate, SerialSignals, SerialSubscribeOptions, SerialTransport, SerialTransportState, SerialWriteOptions, SerialWriteResult, } from "./serialFacade.js";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ import "./augmentApril.js";
2
+ import { defineAprilPluginModule } from "@d2m/april-plugin";
3
+ import { createSerialFacade } from "./serialFacade.js";
4
+ export { createSerialFacade, decodeSerialBinaryPayload, encodeSerialBinaryPayload, } from "./serialFacade.js";
5
+ const moduleDefinition = defineAprilPluginModule({
6
+ moduleId: "d2m.serial.client",
7
+ install(context) {
8
+ context.mount("serial", createSerialFacade(context.april, context.signal));
9
+ },
10
+ });
11
+ export default moduleDefinition;
@@ -0,0 +1,135 @@
1
+ import type { April, AprilSubscription, AprilSubscriptionObserver } from "@d2m/april";
2
+ export type SerialTransport = "native" | "usb";
3
+ export interface SerialListOptions {
4
+ readonly transports?: readonly SerialTransport[];
5
+ }
6
+ export interface SerialTransportState {
7
+ readonly transport: SerialTransport;
8
+ readonly supported: boolean;
9
+ readonly reason?: string;
10
+ }
11
+ export interface SerialAdapterState {
12
+ readonly available: boolean;
13
+ readonly transports: readonly SerialTransportState[];
14
+ }
15
+ export interface SerialAdapterStateEvent {
16
+ readonly state: SerialAdapterState;
17
+ readonly occurredAt: string;
18
+ }
19
+ export interface SerialDeviceDescriptor {
20
+ readonly deviceRef: string;
21
+ readonly displayName?: string;
22
+ readonly transport: SerialTransport;
23
+ readonly vendorName?: string;
24
+ readonly productName?: string;
25
+ readonly driverName?: string;
26
+ readonly requiresPermission?: boolean;
27
+ readonly connectable?: boolean;
28
+ }
29
+ export interface SerialDeviceSnapshot {
30
+ readonly devices: readonly SerialDeviceDescriptor[];
31
+ readonly changedDeviceRef?: string;
32
+ readonly occurredAt: string;
33
+ }
34
+ export interface SerialOpenOptions {
35
+ readonly baudRate?: number;
36
+ readonly dataBits?: 5 | 6 | 7 | 8;
37
+ readonly stopBits?: 1 | 1.5 | 2;
38
+ readonly parity?: "none" | "odd" | "even" | "mark" | "space";
39
+ readonly flowControl?: "none" | "xonXoff" | "rtsCts" | "dsrDtr";
40
+ readonly readTimeoutMs?: number;
41
+ readonly writeTimeoutMs?: number;
42
+ readonly dtr?: boolean;
43
+ readonly rts?: boolean;
44
+ }
45
+ export interface SerialSettings {
46
+ readonly baudRate: number;
47
+ readonly dataBits: 5 | 6 | 7 | 8;
48
+ readonly stopBits: 1 | 1.5 | 2;
49
+ readonly parity: "none" | "odd" | "even" | "mark" | "space";
50
+ readonly flowControl: "none" | "xonXoff" | "rtsCts" | "dsrDtr";
51
+ readonly readTimeoutMs: number;
52
+ readonly writeTimeoutMs: number;
53
+ }
54
+ export interface SerialReadOptions {
55
+ readonly maxBytes?: number;
56
+ readonly timeoutMs?: number;
57
+ }
58
+ export interface SerialWriteOptions {
59
+ readonly timeoutMs?: number;
60
+ }
61
+ export interface SerialWriteResult {
62
+ readonly bytesWritten: number;
63
+ }
64
+ export interface SerialSubscribeOptions {
65
+ readonly maxChunkBytes?: number;
66
+ }
67
+ export interface SerialDataEvent {
68
+ readonly data: ArrayBuffer;
69
+ readonly receivedAt: string;
70
+ readonly sequence: number;
71
+ }
72
+ export interface SerialSignalUpdate {
73
+ readonly dtr?: boolean;
74
+ readonly rts?: boolean;
75
+ }
76
+ export interface SerialSignals {
77
+ readonly dtr?: boolean;
78
+ readonly rts?: boolean;
79
+ readonly cts?: boolean;
80
+ readonly dsr?: boolean;
81
+ readonly dcd?: boolean;
82
+ readonly ri?: boolean;
83
+ }
84
+ export interface SerialFlushOptions {
85
+ readonly direction?: "input" | "output" | "both";
86
+ }
87
+ export interface SerialConnectionStateEvent {
88
+ readonly state: "opening" | "open" | "reconnecting" | "closed";
89
+ readonly reason?: string;
90
+ readonly occurredAt: string;
91
+ }
92
+ export interface SerialOperationSupport {
93
+ readonly supported: boolean;
94
+ readonly reason?: string;
95
+ }
96
+ export interface SerialSignalSupport extends SerialOperationSupport {
97
+ readonly supportedSignals: readonly string[];
98
+ }
99
+ export interface SerialConnectionCapabilities {
100
+ readonly transport: SerialTransport;
101
+ readonly updateSettings: SerialOperationSupport;
102
+ readonly signals: SerialSignalSupport;
103
+ readonly flush: SerialOperationSupport;
104
+ }
105
+ export interface AprilSerialBinaryPayload {
106
+ readonly kind: "base64";
107
+ readonly byteLength: number;
108
+ readonly data: string;
109
+ }
110
+ export type AprilSerialData = ArrayBuffer | Uint8Array | readonly number[];
111
+ export interface AprilSerialConnection {
112
+ readonly device: SerialDeviceDescriptor;
113
+ readonly settings: SerialSettings;
114
+ readonly closed: boolean;
115
+ read(options?: SerialReadOptions): Promise<ArrayBuffer>;
116
+ write(data: AprilSerialData, options?: SerialWriteOptions): Promise<SerialWriteResult>;
117
+ subscribe(options: SerialSubscribeOptions | undefined, observer: AprilSubscriptionObserver<SerialDataEvent>): Promise<AprilSubscription>;
118
+ updateSettings(settings: Partial<SerialSettings>): Promise<void>;
119
+ setSignals(signals: SerialSignalUpdate): Promise<void>;
120
+ getSignals(): Promise<SerialSignals>;
121
+ flush(options?: SerialFlushOptions): Promise<void>;
122
+ watchState(observer: AprilSubscriptionObserver<SerialConnectionStateEvent>): Promise<AprilSubscription>;
123
+ getCapabilities(): Promise<SerialConnectionCapabilities>;
124
+ close(): Promise<void>;
125
+ }
126
+ export interface AprilSerialApi {
127
+ getState(): Promise<SerialAdapterState>;
128
+ watchState(observer: AprilSubscriptionObserver<SerialAdapterStateEvent>): Promise<AprilSubscription>;
129
+ list(options?: SerialListOptions): Promise<readonly SerialDeviceDescriptor[]>;
130
+ watchDevices(options: SerialListOptions | undefined, observer: AprilSubscriptionObserver<SerialDeviceSnapshot>): Promise<AprilSubscription>;
131
+ open(deviceRef: string, options?: SerialOpenOptions): Promise<AprilSerialConnection>;
132
+ }
133
+ export declare function createSerialFacade(april: April, defaultSignal?: AbortSignal): AprilSerialApi;
134
+ export declare function encodeSerialBinaryPayload(data: AprilSerialData): AprilSerialBinaryPayload;
135
+ export declare function decodeSerialBinaryPayload(payload: AprilSerialBinaryPayload): ArrayBuffer;
@@ -0,0 +1,130 @@
1
+ const ADAPTER_CAPABILITY = "serial.adapter";
2
+ const DISCOVERY_CAPABILITY = "serial.discovery";
3
+ const CONNECTION_CAPABILITY = "serial.connection";
4
+ const CONTRACT_VERSION = "1.0";
5
+ export function createSerialFacade(april, defaultSignal) {
6
+ const call = (capability, action, payload, connection) => april.capabilities.call({
7
+ capability,
8
+ action,
9
+ contractVersion: CONTRACT_VERSION,
10
+ payload,
11
+ ...(connection === undefined ? {} : { connection }),
12
+ ...(defaultSignal === undefined ? {} : { signal: defaultSignal }),
13
+ });
14
+ const subscribe = (capability, action, payload, observer, connection) => april.capabilities.subscribe({
15
+ capability,
16
+ action,
17
+ contractVersion: CONTRACT_VERSION,
18
+ payload,
19
+ ...(connection === undefined ? {} : { connection }),
20
+ ...(defaultSignal === undefined ? {} : { signal: defaultSignal }),
21
+ }, observer);
22
+ const facade = {
23
+ getState: () => call(ADAPTER_CAPABILITY, "getState", {}),
24
+ watchState: (observer) => subscribe(ADAPTER_CAPABILITY, "watchState", {}, observer),
25
+ list: (options) => call(DISCOVERY_CAPABILITY, "list", options === undefined ? {} : { options }),
26
+ watchDevices: (options, observer) => subscribe(DISCOVERY_CAPABILITY, "watchDevices", options === undefined ? {} : { options }, observer),
27
+ open: async (deviceRef, options) => {
28
+ const opened = await april.capabilities.connect({
29
+ capability: CONNECTION_CAPABILITY,
30
+ action: "open",
31
+ contractVersion: CONTRACT_VERSION,
32
+ payload: {
33
+ deviceRef,
34
+ ...(options === undefined ? {} : { options }),
35
+ },
36
+ ...(defaultSignal === undefined ? {} : { signal: defaultSignal }),
37
+ });
38
+ return createConnection((action, payload, connection) => call(CONNECTION_CAPABILITY, action, payload, connection), (action, payload, observer, connection) => subscribe(CONNECTION_CAPABILITY, action, payload, observer, connection), opened.connection, opened.value);
39
+ },
40
+ };
41
+ return Object.freeze(facade);
42
+ }
43
+ export function encodeSerialBinaryPayload(data) {
44
+ const values = toBytes(data);
45
+ return {
46
+ kind: "base64",
47
+ byteLength: values.byteLength,
48
+ data: bytesToBase64(values),
49
+ };
50
+ }
51
+ export function decodeSerialBinaryPayload(payload) {
52
+ if (payload?.kind !== "base64" ||
53
+ !Number.isSafeInteger(payload.byteLength) ||
54
+ payload.byteLength < 0 ||
55
+ typeof payload.data !== "string") {
56
+ throw new TypeError("April serial binary payload is invalid");
57
+ }
58
+ const values = base64ToBytes(payload.data);
59
+ if (values.byteLength !== payload.byteLength) {
60
+ throw new TypeError("April serial binary payload byteLength does not match data");
61
+ }
62
+ return values.buffer.slice(values.byteOffset, values.byteOffset + values.byteLength);
63
+ }
64
+ function createConnection(call, subscribe, handle, opened) {
65
+ let closed = false;
66
+ let closePromise;
67
+ const connection = {
68
+ device: opened.device,
69
+ settings: opened.settings,
70
+ get closed() {
71
+ return closed;
72
+ },
73
+ read: async (options) => decodeSerialBinaryPayload(await call("read", options ?? {}, handle)),
74
+ write: (data, options) => call("write", {
75
+ data: encodeSerialBinaryPayload(data),
76
+ ...(options?.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
77
+ }, handle),
78
+ subscribe: (options, observer) => subscribe("subscribe", options ?? {}, observer, handle),
79
+ updateSettings: async (settings) => {
80
+ await call("updateSettings", settings, handle);
81
+ },
82
+ setSignals: async (signals) => {
83
+ await call("setSignals", signals, handle);
84
+ },
85
+ getSignals: () => call("getSignals", {}, handle),
86
+ flush: async (options) => {
87
+ await call("flush", options ?? {}, handle);
88
+ },
89
+ watchState: (observer) => subscribe("watchConnectionState", {}, observer, handle),
90
+ getCapabilities: () => call("getConnectionCapabilities", {}, handle),
91
+ close: async () => {
92
+ if (closed) {
93
+ return;
94
+ }
95
+ closePromise ??= call("close", {}, handle)
96
+ .finally(() => {
97
+ closed = true;
98
+ });
99
+ await closePromise;
100
+ },
101
+ };
102
+ return Object.freeze(connection);
103
+ }
104
+ function toBytes(data) {
105
+ if (data instanceof ArrayBuffer) {
106
+ return new Uint8Array(data);
107
+ }
108
+ if (data instanceof Uint8Array) {
109
+ return new Uint8Array(data);
110
+ }
111
+ if (!Array.isArray(data) || data.some(value => !Number.isSafeInteger(value) || value < 0 || value > 255)) {
112
+ throw new TypeError("April serial binary data is invalid");
113
+ }
114
+ return Uint8Array.from(data);
115
+ }
116
+ function bytesToBase64(values) {
117
+ let binary = "";
118
+ const chunkSize = 0x8000;
119
+ for (let offset = 0; offset < values.length; offset += chunkSize) {
120
+ binary += String.fromCharCode(...values.subarray(offset, offset + chunkSize));
121
+ }
122
+ return btoa(binary);
123
+ }
124
+ function base64ToBytes(value) {
125
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
126
+ throw new TypeError("April serial binary payload data is not Base64");
127
+ }
128
+ const binary = atob(value);
129
+ return Uint8Array.from(binary, character => character.charCodeAt(0));
130
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@d2m/april-serial",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "import": "./dist/index.js"
9
+ }
10
+ },
11
+ "types": "./dist/index.d.ts",
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "peerDependencies": {
19
+ "@d2m/april": "^0.1.0"
20
+ },
21
+ "dependencies": {
22
+ "@d2m/april-plugin": "^0.1.0"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^25.5.0",
26
+ "esbuild": "0.27.3",
27
+ "vitest": "^4.1.1",
28
+ "@d2m/april-plugin": "^0.1.0",
29
+ "@d2m/april": "^0.1.0"
30
+ },
31
+ "scripts": {
32
+ "prebuild": "pnpm --filter @d2m/april build && pnpm --filter @d2m/april-plugin build",
33
+ "build": "tsc -p tsconfig.build.json && node esbuild.mjs",
34
+ "lint": "eslint src --max-warnings 0",
35
+ "test:run": "vitest run",
36
+ "type-check": "tsc -p tsconfig.json --noEmit"
37
+ }
6
38
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.