phonesinc 1.0.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,90 @@
1
+ import type { ApiResponse, App, AppiumRequest, AppRequest, ClientOptions, Endpoint, FileExport, Identity, KeyRequest, Media, MediaSource, MediaUploadRequest, OptionalEndpoint, Phone, PhoneFile, PhoneResult, PhoneSelection, PhoneTargets, RequestOptions, ScreenRequest, Screenshot, Session, Stream, TouchRequest, TypeRequest } from "./types.js";
2
+ export type * from "./types.js";
3
+ /** Public phone operations. A request is sent once; actions are never replayed. */
4
+ export declare class PhonesInc {
5
+ private readonly baseUrl;
6
+ private readonly token;
7
+ private readonly fetchImpl;
8
+ private readonly organizationId?;
9
+ constructor(options: ClientOptions);
10
+ private headers;
11
+ private request;
12
+ private required;
13
+ private optional;
14
+ private custom;
15
+ readonly me: OptionalEndpoint<Record<never, never>, Identity>;
16
+ readonly phones: {
17
+ get: OptionalEndpoint<PhoneSelection, Phone[]>;
18
+ reboot: Endpoint<PhoneTargets, PhoneResult[]>;
19
+ };
20
+ readonly session: {
21
+ get: OptionalEndpoint<PhoneSelection, Session[]>;
22
+ start: OptionalEndpoint<PhoneSelection, PhoneResult<{
23
+ session: Session;
24
+ }>[]>;
25
+ renew: OptionalEndpoint<PhoneSelection, PhoneResult<{
26
+ session: Session;
27
+ }>[]>;
28
+ end: OptionalEndpoint<PhoneSelection, PhoneResult[]>;
29
+ };
30
+ readonly touch: Endpoint<TouchRequest, PhoneResult[]>;
31
+ readonly type: Endpoint<TypeRequest, PhoneResult[]>;
32
+ readonly key: Endpoint<KeyRequest, PhoneResult[]>;
33
+ readonly screen: OptionalEndpoint<ScreenRequest, PhoneResult<Screenshot>[]>;
34
+ readonly apps: {
35
+ get: OptionalEndpoint<PhoneSelection, PhoneResult<{
36
+ apps: App[];
37
+ }>[]>;
38
+ launch: Endpoint<AppRequest, PhoneResult[]>;
39
+ stop: Endpoint<AppRequest, PhoneResult[]>;
40
+ uninstall: Endpoint<AppRequest, PhoneResult[]>;
41
+ install: Endpoint<PhoneTargets & MediaSource, PhoneResult<{
42
+ app: App;
43
+ }>[]>;
44
+ };
45
+ readonly files: {
46
+ get: OptionalEndpoint<PhoneSelection & {
47
+ path?: string;
48
+ }, PhoneResult<{
49
+ files: PhoneFile[];
50
+ }>[]>;
51
+ export: Endpoint<PhoneSelection & {
52
+ path: string;
53
+ }, PhoneResult<FileExport>[]>;
54
+ push: Endpoint<PhoneTargets & (MediaSource & {
55
+ path: string;
56
+ }), PhoneResult<{
57
+ file: PhoneFile;
58
+ }>[]>;
59
+ delete: Endpoint<PhoneTargets & {
60
+ path: string;
61
+ }, PhoneResult[]>;
62
+ };
63
+ readonly media: {
64
+ get: OptionalEndpoint<{
65
+ ids?: string[];
66
+ }, Media[]>;
67
+ upload: ((body: MediaUploadRequest, options?: RequestOptions) => Promise<ApiResponse<Media>>) & {
68
+ readonly endpoint: string;
69
+ };
70
+ delete: Endpoint<{
71
+ ids: string[];
72
+ }, {
73
+ deleted: string[];
74
+ }>;
75
+ import: Endpoint<PhoneTargets & MediaSource, PhoneResult[]>;
76
+ };
77
+ readonly clipboard: {
78
+ get: OptionalEndpoint<PhoneSelection, PhoneResult<{
79
+ text: string;
80
+ }>[]>;
81
+ set: Endpoint<PhoneTargets & {
82
+ text: string;
83
+ }, PhoneResult[]>;
84
+ };
85
+ readonly stream: OptionalEndpoint<PhoneSelection, Stream>;
86
+ /** Raw WebDriver responses, including WebDriver errors, are returned unchanged. */
87
+ readonly appium: ((body: AppiumRequest, options?: RequestOptions) => Promise<Response>) & {
88
+ readonly endpoint: string;
89
+ };
90
+ }
package/dist/index.js ADDED
@@ -0,0 +1,162 @@
1
+ function named(endpoint, method) {
2
+ return Object.defineProperty(method, "endpoint", { value: endpoint, enumerable: true });
3
+ }
4
+ /** Public phone operations. A request is sent once; actions are never replayed. */
5
+ export class PhonesInc {
6
+ baseUrl;
7
+ token;
8
+ fetchImpl;
9
+ organizationId;
10
+ constructor(options) {
11
+ this.baseUrl = (options.baseUrl ?? "https://api.phones.inc")
12
+ .replace(/\/+$/, "")
13
+ .replace(/\/v1$/, "");
14
+ this.token = options.apiKey ?? options.token;
15
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
16
+ this.organizationId = options.organizationId;
17
+ }
18
+ async headers(options) {
19
+ const token = typeof this.token === "function" ? await this.token() : this.token;
20
+ const headers = new Headers();
21
+ if (token)
22
+ headers.set("Authorization", `Bearer ${token}`);
23
+ const organization = options.organizationId === undefined ? this.organizationId : options.organizationId;
24
+ if (organization !== undefined && organization !== null)
25
+ headers.set("X-Phonesinc-Organization", organization);
26
+ return headers;
27
+ }
28
+ async request(path, body, options = {}) {
29
+ try {
30
+ const headers = await this.headers(options);
31
+ const form = body instanceof FormData;
32
+ if (!form)
33
+ headers.set("Content-Type", "application/json");
34
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
35
+ method: "POST",
36
+ headers,
37
+ signal: options.signal,
38
+ body: form ? body : JSON.stringify(body ?? {}),
39
+ });
40
+ const value = await response.json();
41
+ if (value && typeof value === "object" && "ok" in value) {
42
+ if (value.ok === true && "data" in value && response.ok)
43
+ return value;
44
+ if (value.ok === false &&
45
+ "error" in value &&
46
+ value.error &&
47
+ typeof value.error === "object" &&
48
+ "code" in value.error &&
49
+ typeof value.error.code === "string" &&
50
+ "message" in value.error &&
51
+ typeof value.error.message === "string")
52
+ return value;
53
+ }
54
+ return {
55
+ ok: false,
56
+ error: {
57
+ code: "bad_response",
58
+ message: `Unexpected API response (HTTP ${response.status})`,
59
+ },
60
+ };
61
+ }
62
+ catch (error) {
63
+ if (error instanceof SyntaxError)
64
+ return {
65
+ ok: false,
66
+ error: { code: "bad_response", message: "The API response was not JSON" },
67
+ };
68
+ return {
69
+ ok: false,
70
+ error: {
71
+ code: options.signal?.aborted ? "aborted" : "network_error",
72
+ message: error instanceof Error ? error.message : "The API could not be reached",
73
+ },
74
+ };
75
+ }
76
+ }
77
+ required(path) {
78
+ return named(path, (body, options) => this.request(path, body, options));
79
+ }
80
+ optional(path) {
81
+ return named(path, (body, options) => this.request(path, body, options));
82
+ }
83
+ custom(path, run) {
84
+ return named(path, (body, options = {}) => run(path, body, options));
85
+ }
86
+ me = this.optional("/v1/me");
87
+ phones = {
88
+ get: this.optional("/v1/phones"),
89
+ reboot: this.required("/v1/phones/reboot"),
90
+ };
91
+ session = {
92
+ get: this.optional("/v1/session"),
93
+ start: this.optional("/v1/session/start"),
94
+ renew: this.optional("/v1/session/renew"),
95
+ end: this.optional("/v1/session/end"),
96
+ };
97
+ touch = this.required("/v1/touch");
98
+ type = this.required("/v1/type");
99
+ key = this.required("/v1/key");
100
+ screen = this.optional("/v1/screen");
101
+ apps = {
102
+ get: this.optional("/v1/apps"),
103
+ launch: this.required("/v1/apps/launch"),
104
+ stop: this.required("/v1/apps/stop"),
105
+ uninstall: this.required("/v1/apps/uninstall"),
106
+ install: this.required("/v1/apps/install"),
107
+ };
108
+ files = {
109
+ get: this.optional("/v1/files"),
110
+ export: this.required("/v1/files/export"),
111
+ push: this.required("/v1/files/push"),
112
+ delete: this.required("/v1/files/delete"),
113
+ };
114
+ media = {
115
+ get: this.optional("/v1/media"),
116
+ upload: this.custom("/v1/media/upload", (path, body, options) => {
117
+ if (body.file !== undefined) {
118
+ if (body.url !== undefined)
119
+ return Promise.resolve({
120
+ ok: false,
121
+ error: { code: "invalid_request", message: "Provide one file or URL" },
122
+ });
123
+ const form = new FormData();
124
+ const originalName = "name" in body.file && typeof body.file.name === "string"
125
+ ? body.file.name
126
+ : "upload.bin";
127
+ form.append("file", body.file, originalName);
128
+ if (body.name !== undefined)
129
+ form.append("name", body.name);
130
+ return this.request(path, form, options);
131
+ }
132
+ return this.request(path, body, options);
133
+ }),
134
+ delete: this.required("/v1/media/delete"),
135
+ import: this.required("/v1/media/import"),
136
+ };
137
+ clipboard = {
138
+ get: this.optional("/v1/clipboard"),
139
+ set: this.required("/v1/clipboard/set"),
140
+ };
141
+ stream = this.optional("/v1/stream");
142
+ /** Raw WebDriver responses, including WebDriver errors, are returned unchanged. */
143
+ appium = this.custom("/v1/appium", async (path, request, options) => {
144
+ const base = `${this.baseUrl}${path}`;
145
+ const url = new URL(base + request.path);
146
+ if (!request.path.startsWith("/") ||
147
+ request.path.startsWith("//") ||
148
+ url.origin !== new URL(base).origin ||
149
+ !url.pathname.startsWith(`${path}/`) ||
150
+ url.hash)
151
+ throw new TypeError("Appium requires a relative WebDriver path");
152
+ const headers = await this.headers(options);
153
+ if (request.body !== undefined)
154
+ headers.set("Content-Type", "application/json");
155
+ return this.fetchImpl(url, {
156
+ method: request.method,
157
+ headers,
158
+ signal: options.signal,
159
+ ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
160
+ });
161
+ });
162
+ }
@@ -0,0 +1,19 @@
1
+ import { Room, type RemoteTrack, type RemoteTrackPublication } from "livekit-client";
2
+ import type { LiveInput, Stream, StreamError } from "./types.js";
3
+ export type StreamOptions = {
4
+ /** Supply a configured, disconnected room, or let the helper create one. */
5
+ room?: Room;
6
+ onTrack?: (phoneId: string, track: RemoteTrack, publication: RemoteTrackPublication) => void;
7
+ onError?: (phoneId: string, error: StreamError) => void;
8
+ };
9
+ export type StreamConnection = {
10
+ room: Room;
11
+ sendInput(phoneId: string, input: LiveInput): Promise<void>;
12
+ disconnect(): Promise<void>;
13
+ };
14
+ /**
15
+ * Browser stream helper. Import from `phonesinc/stream` with livekit-client
16
+ * installed. Only the grant's successful phones are subscribed. No watch,
17
+ * presence, or private control messages are needed.
18
+ */
19
+ export declare function connectStream(grant: Stream, options?: StreamOptions): Promise<StreamConnection>;
package/dist/stream.js ADDED
@@ -0,0 +1,87 @@
1
+ import { ConnectionState, Room, RoomEvent, } from "livekit-client";
2
+ /**
3
+ * Browser stream helper. Import from `phonesinc/stream` with livekit-client
4
+ * installed. Only the grant's successful phones are subscribed. No watch,
5
+ * presence, or private control messages are needed.
6
+ */
7
+ export async function connectStream(grant, options = {}) {
8
+ const room = options.room ?? new Room({ adaptiveStream: true });
9
+ const phones = new Set(grant.phones.filter((p) => p.ok).map((p) => p.phoneId));
10
+ const phoneOf = (participant) => {
11
+ if (!participant?.identity.startsWith("phone:"))
12
+ return undefined;
13
+ const id = participant.identity.slice("phone:".length);
14
+ return phones.has(id) ? id : undefined;
15
+ };
16
+ const subscribe = (publication, participant) => {
17
+ if (phoneOf(participant))
18
+ publication.setSubscribed(true);
19
+ };
20
+ const subscribed = (track, publication, participant) => {
21
+ const id = phoneOf(participant);
22
+ if (id)
23
+ options.onTrack?.(id, track, publication);
24
+ };
25
+ const received = (bytes, participant) => {
26
+ const id = phoneOf(participant);
27
+ if (!id)
28
+ return;
29
+ let message;
30
+ try {
31
+ message = JSON.parse(new TextDecoder().decode(bytes));
32
+ }
33
+ catch {
34
+ return;
35
+ }
36
+ if (message &&
37
+ typeof message === "object" &&
38
+ "type" in message &&
39
+ message.type === "error" &&
40
+ "code" in message &&
41
+ typeof message.code === "string" &&
42
+ "message" in message &&
43
+ typeof message.message === "string")
44
+ options.onError?.(id, message);
45
+ };
46
+ const clean = () => {
47
+ room.off(RoomEvent.TrackPublished, subscribe);
48
+ room.off(RoomEvent.TrackSubscribed, subscribed);
49
+ room.off(RoomEvent.DataReceived, received);
50
+ };
51
+ room.on(RoomEvent.TrackPublished, subscribe);
52
+ room.on(RoomEvent.TrackSubscribed, subscribed);
53
+ room.on(RoomEvent.DataReceived, received);
54
+ try {
55
+ await room.connect(grant.url, grant.token, { autoSubscribe: false });
56
+ for (const participant of room.remoteParticipants.values()) {
57
+ for (const publication of participant.trackPublications.values())
58
+ subscribe(publication, participant);
59
+ }
60
+ }
61
+ catch (error) {
62
+ clean();
63
+ await room.disconnect();
64
+ throw error;
65
+ }
66
+ let closed = false;
67
+ return {
68
+ room,
69
+ async sendInput(phoneId, input) {
70
+ if (!phones.has(phoneId))
71
+ throw new Error("The phone is not available in this stream grant");
72
+ if (closed || room.state !== ConnectionState.Connected)
73
+ throw new Error("The stream is not connected");
74
+ await room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(input)), {
75
+ reliable: true,
76
+ destinationIdentities: [`phone:${phoneId}`],
77
+ });
78
+ },
79
+ async disconnect() {
80
+ if (closed)
81
+ return;
82
+ closed = true;
83
+ clean();
84
+ await room.disconnect();
85
+ },
86
+ };
87
+ }
@@ -0,0 +1,212 @@
1
+ /** The public JSON contract. No provider or administrative fields are exposed. */
2
+ export type ApiError = {
3
+ code: string;
4
+ message: string;
5
+ };
6
+ export type ApiResponse<T> = {
7
+ ok: true;
8
+ data: T;
9
+ } | {
10
+ ok: false;
11
+ error: ApiError;
12
+ };
13
+ export type PhoneResult<T extends object = Record<never, never>> = ({
14
+ phoneId: string;
15
+ ok: true;
16
+ } & T) | {
17
+ phoneId: string;
18
+ ok: false;
19
+ error: ApiError;
20
+ };
21
+ export type Session = {
22
+ id: string;
23
+ phoneId: string;
24
+ network: "connecting" | "ready" | "failed";
25
+ startedAt: string;
26
+ expiresAt: string;
27
+ };
28
+ export type Phone = {
29
+ id: string;
30
+ name: string;
31
+ platform: "android" | "ios";
32
+ model: string | null;
33
+ osVersion: string;
34
+ status: "online" | "preparing" | "offline";
35
+ screen: {
36
+ width: number;
37
+ height: number;
38
+ } | null;
39
+ phoneNumber: string | null;
40
+ appium: boolean;
41
+ session: Session | null;
42
+ };
43
+ export type App = {
44
+ id: string;
45
+ name: string | null;
46
+ protected: boolean;
47
+ };
48
+ export type PhoneFile = {
49
+ path: string;
50
+ name: string;
51
+ type: "file" | "directory";
52
+ size: number | null;
53
+ modifiedAt: string | null;
54
+ };
55
+ export type Media = {
56
+ id: string;
57
+ name: string;
58
+ type: "image" | "video" | "other";
59
+ size: number;
60
+ url: string;
61
+ createdAt: string;
62
+ };
63
+ export type Identity = {
64
+ organization: {
65
+ id: string;
66
+ name: string;
67
+ } | null;
68
+ key: {
69
+ id: string;
70
+ name: string;
71
+ createdAt: string;
72
+ } | null;
73
+ };
74
+ export type Box = {
75
+ id: number;
76
+ x: number;
77
+ y: number;
78
+ width: number;
79
+ height: number;
80
+ };
81
+ export type TextLine = Box & {
82
+ text: string;
83
+ confidence: number;
84
+ };
85
+ export type Element = Box & {
86
+ label: string;
87
+ confidence: number;
88
+ };
89
+ export type Screenshot = {
90
+ imageUrl: string;
91
+ format: "png" | "jpeg";
92
+ width: number;
93
+ height: number;
94
+ text?: TextLine[];
95
+ elements?: Element[];
96
+ annotatedImageUrl?: string;
97
+ };
98
+ export type FileExport = {
99
+ url: string;
100
+ filename: string;
101
+ size: number;
102
+ expiresAt: string;
103
+ };
104
+ export type Stream = {
105
+ url: string;
106
+ token: string;
107
+ expiresAt: string;
108
+ phones: PhoneResult[];
109
+ };
110
+ export type PhoneSelection = {
111
+ phoneIds?: string[];
112
+ };
113
+ export type PhoneTargets = {
114
+ phoneIds: string[];
115
+ };
116
+ export type TouchPoint = {
117
+ x: number;
118
+ y: number;
119
+ time?: number;
120
+ };
121
+ export type TouchRequest = PhoneTargets & {
122
+ inputs: TouchPoint[];
123
+ };
124
+ export type TypeRequest = PhoneTargets & {
125
+ text: string;
126
+ duration?: number;
127
+ };
128
+ export type Modifier = "shift" | "ctrl" | "alt" | "meta";
129
+ export type Key = "home" | "enter" | "backspace" | "lock" | "unlock" | "back" | "app_switcher" | "volume_up" | "volume_down" | "tab" | "escape" | "delete" | "up" | "down" | "left" | "right" | "a" | "c" | "x" | "z" | "cursor_home" | "cursor_end" | "page_up" | "page_down" | "caps_lock";
130
+ export type KeyRequest = PhoneTargets & {
131
+ key: Key;
132
+ modifiers?: Modifier[];
133
+ };
134
+ export type ScreenRequest = PhoneSelection & {
135
+ format?: "png" | "jpeg";
136
+ quality?: number;
137
+ ocr?: boolean;
138
+ detect?: boolean;
139
+ annotate?: boolean;
140
+ };
141
+ /** Exactly one existing library item or customer URL supplies the bytes. */
142
+ export type MediaSource = {
143
+ mediaId: string;
144
+ url?: never;
145
+ } | {
146
+ url: string;
147
+ mediaId?: never;
148
+ };
149
+ export type AppRequest = PhoneTargets & {
150
+ appId: string;
151
+ };
152
+ export type MediaUploadRequest = {
153
+ file: Blob;
154
+ name?: string;
155
+ url?: never;
156
+ } | {
157
+ url: string;
158
+ name?: string;
159
+ file?: never;
160
+ };
161
+ export type LiveInput = {
162
+ type: "touch";
163
+ phase: "start" | "move";
164
+ x: number;
165
+ y: number;
166
+ } | {
167
+ type: "touch";
168
+ phase: "end" | "cancel";
169
+ x?: number;
170
+ y?: number;
171
+ } | {
172
+ type: "type";
173
+ text: string;
174
+ } | {
175
+ type: "key";
176
+ key: Key;
177
+ modifiers?: Modifier[];
178
+ };
179
+ export type StreamError = ApiError & {
180
+ type: "error";
181
+ };
182
+ export type RequestOptions = {
183
+ signal?: AbortSignal;
184
+ /** Override the client's selection; null uses the login's unselected scope. */
185
+ organizationId?: string | null;
186
+ };
187
+ export type TokenProvider = () => string | null | Promise<string | null>;
188
+ export type ClientOptions = {
189
+ /** Origin, optionally ending in /v1. Defaults to https://api.phones.inc. */
190
+ baseUrl?: string;
191
+ organizationId?: string;
192
+ fetch?: typeof globalThis.fetch;
193
+ } & ({
194
+ apiKey: string;
195
+ token?: never;
196
+ } | {
197
+ token: string | TokenProvider;
198
+ apiKey?: never;
199
+ });
200
+ /** Metadata and transport use the same endpoint; useful for contract checks. */
201
+ export type Endpoint<Q, T> = ((request: Q, options?: RequestOptions) => Promise<ApiResponse<T>>) & {
202
+ readonly endpoint: string;
203
+ };
204
+ export type OptionalEndpoint<Q, T> = ((request?: Q, options?: RequestOptions) => Promise<ApiResponse<T>>) & {
205
+ readonly endpoint: string;
206
+ };
207
+ export type AppiumRequest = {
208
+ method: "GET" | "POST" | "DELETE";
209
+ /** A WebDriver path, such as /session or /session/<id>/url. */
210
+ path: string;
211
+ body?: unknown;
212
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "phonesinc",
3
+ "version": "1.0.0",
4
+ "description": "The public Phones Inc API client",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./stream": {
15
+ "types": "./dist/stream.d.ts",
16
+ "import": "./dist/stream.js",
17
+ "default": "./dist/stream.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.json",
25
+ "test": "bun test src",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "license": "MIT",
32
+ "peerDependencies": {
33
+ "livekit-client": "^2.22.0"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "livekit-client": {
37
+ "optional": true
38
+ }
39
+ },
40
+ "devDependencies": {
41
+ "typescript": "^5.8.2",
42
+ "livekit-client": "2.22.0"
43
+ }
44
+ }