@swipt/cli 0.1.0-nightly.94 → 0.1.0-nightly.97
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.
- package/dist/cli/cli.js +1 -1
- package/dist/cli/cli.js.map +1 -1
- package/dist/cli/commands/data/read.js +4 -6
- package/dist/cli/commands/data/read.js.map +1 -1
- package/dist/cli/commands/device/stop.js +3 -3
- package/dist/cli/commands/device/stop.js.map +1 -1
- package/dist/cli/commands/driver/driver.js +28 -0
- package/dist/cli/commands/driver/driver.js.map +1 -0
- package/dist/cli/commands/driver/index.js +1 -0
- package/dist/cli/commands/flags.js +8 -7
- package/dist/cli/commands/flags.js.map +1 -1
- package/dist/cli/commands/index.js +3 -0
- package/dist/cli/commands/index.js.map +1 -1
- package/dist/cli/commands/project/create.js +2 -2
- package/dist/cli/commands/project/create.js.map +1 -1
- package/dist/cli/commands/project/source.js +10 -9
- package/dist/cli/commands/project/source.js.map +1 -1
- package/dist/cli/commands/swiplet/remove.js +1 -1
- package/dist/cli/commands/swiplet/remove.js.map +1 -1
- package/dist/client.js +27 -6
- package/dist/client.js.map +1 -1
- package/dist/connection.d.ts +3 -1
- package/dist/connection.js +41 -52
- package/dist/connection.js.map +1 -1
- package/dist/directories.d.ts +2 -0
- package/dist/directories.js +9 -0
- package/dist/directories.js.map +1 -0
- package/dist/driver.d.ts +39 -0
- package/dist/driver.js +199 -0
- package/dist/driver.js.map +1 -0
- package/dist/i18n.d.ts +1 -1
- package/dist/i18n.js +43 -7
- package/dist/i18n.js.map +1 -1
- package/dist/mdns.d.ts +7 -0
- package/dist/mdns.js +44 -0
- package/dist/mdns.js.map +1 -0
- package/dist/output.js +6 -6
- package/dist/output.js.map +1 -1
- package/dist/passcode.d.ts +9 -0
- package/dist/passcode.js +81 -0
- package/dist/passcode.js.map +1 -0
- package/dist/project.js +38 -32
- package/dist/project.js.map +1 -1
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +124 -0
- package/dist/serve.js.map +1 -0
- package/dist/sideload.d.ts +0 -1
- package/dist/sideload.js +82 -340
- package/dist/sideload.js.map +1 -1
- package/dist/swipt-app.d.ts +14 -0
- package/dist/swipt-app.js +51 -0
- package/dist/swipt-app.js.map +1 -0
- package/locales/ar.json +52 -28
- package/locales/bg.json +58 -34
- package/locales/bn.json +49 -25
- package/locales/ca.json +55 -31
- package/locales/cs.json +55 -31
- package/locales/da.json +50 -26
- package/locales/de.json +50 -26
- package/locales/el.json +60 -36
- package/locales/es-419.json +51 -27
- package/locales/es.json +51 -27
- package/locales/fi.json +51 -27
- package/locales/fr-CA.json +53 -29
- package/locales/fr.json +56 -32
- package/locales/gu.json +69 -45
- package/locales/he.json +51 -27
- package/locales/hi.json +50 -26
- package/locales/hr.json +51 -27
- package/locales/hu.json +62 -38
- package/locales/id.json +50 -26
- package/locales/it.json +69 -45
- package/locales/ja.json +50 -26
- package/locales/kk.json +49 -25
- package/locales/kn.json +49 -25
- package/locales/ko.json +79 -55
- package/locales/lt.json +50 -26
- package/locales/ml.json +49 -25
- package/locales/mr.json +56 -32
- package/locales/ms.json +50 -26
- package/locales/nb.json +50 -26
- package/locales/nl.json +56 -32
- package/locales/or.json +50 -26
- package/locales/pa.json +49 -25
- package/locales/pl.json +68 -44
- package/locales/pt-BR.json +51 -27
- package/locales/pt-PT.json +52 -28
- package/locales/ro.json +52 -28
- package/locales/ru.json +54 -30
- package/locales/sk.json +80 -56
- package/locales/sl.json +50 -26
- package/locales/sv.json +52 -28
- package/locales/ta.json +49 -25
- package/locales/te.json +49 -25
- package/locales/th.json +54 -30
- package/locales/tr.json +50 -26
- package/locales/uk.json +53 -29
- package/locales/ur.json +49 -25
- package/locales/vi.json +49 -25
- package/locales/zh-HK.json +54 -30
- package/locales/zh-Hans.json +54 -30
- package/locales/zh-Hant.json +60 -36
- package/package.json +13 -4
- package/dist/coredevice.d.ts +0 -22
- package/dist/coredevice.js +0 -329
- package/dist/coredevice.js.map +0 -1
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["import dns from \"node:dns\";\nimport { createRequire } from \"node:module\";\n\nimport { create, fromBinary, toBinary } from \"@bufbuild/protobuf\";\n\nimport { LogService } from \"./proto/logs_pb\";\nimport { REPLService } from \"./proto/repl_pb\";\nimport { SwipletService } from \"./proto/swiplets_pb\";\nimport { SystemService } from \"./proto/system_pb\";\n\nconst largestMessage = 128 << 20;\nconst contentType = \"application/grpc-web+proto\";\nconst webSocketSubprotocol = \"grpc-websockets\";\nconst { apiLevel } = createRequire(import.meta.url)(\"@swipt/api/package.json\");\n\ndns.setDefaultResultOrder(\"ipv4first\");\n\nexport const Code = {\n Canceled: 1,\n Unknown: 2,\n DeadlineExceeded: 4,\n NotFound: 5,\n Unimplemented: 12,\n Internal: 13,\n Unavailable: 14,\n Unauthenticated: 16,\n};\n\nexport class UsageError extends Error {}\n\nexport class RpcError extends Error {\n declare code: number;\n\n constructor(code: number, message?: string) {\n super(message);\n this.code = code;\n }\n}\n\nconst httpStatusCodes = {\n 400: Code.Internal,\n 401: Code.Unauthenticated,\n 403: Code.Unauthenticated,\n 404: Code.Unimplemented,\n 429: Code.Unavailable,\n 502: Code.Unavailable,\n 503: Code.Unavailable,\n 504: Code.Unavailable,\n};\n\nfunction statusMessage(text) {\n if (text === undefined || text === null) {\n return \"\";\n }\n try {\n return decodeURIComponent(text);\n } catch {\n return text;\n }\n}\n\nconst causeText = (cause) =>\n cause?.errors?.length > 0\n ? cause.errors.map(causeText).join(\"; \")\n : cause?.message || cause?.code;\n\nconst transportError = (error) => {\n if (error instanceof RpcError) {\n return error;\n }\n if (error?.name === \"AbortError\") {\n return new RpcError(Code.Canceled, \"the call was canceled\");\n }\n return new RpcError(\n Code.Unavailable,\n causeText(error?.cause) || error?.message || String(error),\n );\n};\n\nfunction frame(schema, init) {\n const body = toBinary(schema, create(schema, init));\n const out = Buffer.allocUnsafe(5 + body.length);\n out[0] = 0;\n out.writeUInt32BE(body.length, 1);\n out.set(body, 5);\n return out;\n}\n\nfunction parseMetadata(body) {\n const headers = {};\n for (const line of Buffer.from(body).toString().split(\"\\r\\n\")) {\n const separator = line.indexOf(\":\");\n if (separator > 0) {\n headers[line.slice(0, separator).trim().toLowerCase()] = line\n .slice(separator + 1)\n .trim();\n }\n }\n return headers;\n}\n\nclass FrameReader {\n declare schema: any;\n pending = Buffer.alloc(0);\n\n constructor(schema) {\n this.schema = schema;\n }\n\n push(chunk) {\n this.pending =\n this.pending.length === 0\n ? Buffer.from(chunk)\n : Buffer.concat([this.pending, Buffer.from(chunk)]);\n const frames = [];\n while (this.pending.length >= 5) {\n const length = this.pending.readUInt32BE(1);\n if (length > largestMessage) {\n throw new RpcError(\n Code.Internal,\n `the server sent a message of ${length} bytes`,\n );\n }\n if (this.pending.length < 5 + length) {\n break;\n }\n const body = this.pending.subarray(5, 5 + length);\n frames.push(\n (this.pending[0] & 0x80) !== 0\n ? { trailers: parseMetadata(body) }\n : { message: fromBinary(this.schema, body) },\n );\n this.pending = this.pending.subarray(5 + length);\n }\n return frames;\n }\n}\n\nfunction checkStatus(headers) {\n const status = headers[\"grpc-status\"];\n if (status === undefined || status === null) {\n return false;\n }\n const code = Number(status);\n if (code !== 0) {\n throw new RpcError(code, statusMessage(headers[\"grpc-message\"]));\n }\n return true;\n}\n\nfunction requestHeaders(connection) {\n const headers: Record<string, string> = {\n \"content-type\": contentType,\n \"x-grpc-web\": \"1\",\n \"swipt-api-level\": String(apiLevel),\n };\n if (connection.token !== \"\") {\n headers.authorization = `Bearer ${connection.token}`;\n }\n return headers;\n}\n\nasync function* invokeHTTP(connection, method, input, { signal }) {\n let response;\n try {\n response = await fetch(\n `${connection.base}/${method.parent.typeName}/${method.name}`,\n {\n method: \"POST\",\n headers: requestHeaders(connection),\n body: frame(method.input, input),\n signal,\n },\n );\n } catch (error) {\n throw transportError(error);\n }\n const headers = Object.fromEntries(response.headers);\n if (response.status !== 200) {\n await response.body?.cancel();\n throw new RpcError(\n httpStatusCodes[response.status] ?? Code.Unknown,\n `HTTP ${response.status}`,\n );\n }\n if (checkStatus(headers)) {\n await response.body?.cancel();\n return;\n }\n const reader = new FrameReader(method.output);\n let ended = false;\n try {\n for await (const chunk of response.body) {\n for (const found of reader.push(chunk)) {\n if (found.trailers) {\n checkStatus(found.trailers);\n ended = true;\n } else if (!ended) {\n yield found.message;\n }\n }\n }\n } catch (error) {\n throw transportError(error);\n }\n if (!ended) {\n throw new RpcError(Code.Unavailable, \"the response ended without a status\");\n }\n}\n\nasync function* invokeWebSocket(connection, method, input, { signal }) {\n if (signal?.aborted) {\n throw new RpcError(Code.Canceled, \"the call was canceled\");\n }\n const socket = new WebSocket(\n `${connection.webSocketBase}/${method.parent.typeName}/${method.name}`,\n [webSocketSubprotocol],\n );\n socket.binaryType = \"arraybuffer\";\n const reader = new FrameReader(method.output);\n const messages = [];\n let failure;\n let closed = false;\n let headersSeen = false;\n let wake: (value?: unknown) => void = () => {};\n const notify = () => {\n const current = wake;\n wake = () => {};\n current();\n };\n const fail = (error) => {\n failure ??= error;\n socket.close();\n notify();\n };\n const abort = () =>\n fail(new RpcError(Code.Canceled, \"the call was canceled\"));\n const opened = new Promise((resolve, reject) => {\n socket.addEventListener(\"open\", resolve, { once: true });\n socket.addEventListener(\n \"close\",\n () =>\n reject(\n failure ??\n new RpcError(\n Code.Unavailable,\n `cannot connect to ${connection.webSocketBase}`,\n ),\n ),\n { once: true },\n );\n });\n socket.addEventListener(\"message\", (event) => {\n try {\n for (const found of reader.push(new Uint8Array(event.data))) {\n if (found.message) {\n messages.push(found.message);\n } else if (headersSeen || \"grpc-status\" in found.trailers) {\n checkStatus(found.trailers);\n closed = true;\n socket.close();\n } else {\n headersSeen = true;\n }\n }\n } catch (error) {\n fail(error);\n }\n notify();\n });\n socket.addEventListener(\"close\", (event) => {\n if (!closed) {\n failure ??= new RpcError(\n Code.Unavailable,\n event.reason || \"the connection closed before the response\",\n );\n }\n closed = true;\n notify();\n });\n socket.addEventListener(\"error\", () => {\n failure ??= new RpcError(\n Code.Unavailable,\n `cannot connect to ${connection.webSocketBase}`,\n );\n });\n signal?.addEventListener(\"abort\", abort, { once: true });\n try {\n await opened;\n const headers = requestHeaders(connection);\n socket.send(\n Buffer.from(\n `${Object.entries(headers)\n .map(([key, value]) => `${key}: ${value}\\r\\n`)\n .join(\"\")}`,\n ),\n );\n void (async () => {\n try {\n const body = method.methodKind === \"client_streaming\" ? input : [input];\n for await (const message of body) {\n if (closed || failure) {\n return;\n }\n socket.send(\n Buffer.concat([Buffer.from([0]), frame(method.input, message)]),\n );\n }\n if (!closed && !failure) {\n socket.send(Buffer.from([1]));\n }\n } catch (error) {\n fail(transportError(error));\n }\n })();\n while (true) {\n if (messages.length > 0) {\n yield messages.shift();\n continue;\n }\n if (closed || failure) {\n break;\n }\n await new Promise((resolve) => {\n wake = resolve;\n });\n }\n if (failure) {\n throw failure;\n }\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n if (socket.readyState !== WebSocket.CLOSED) {\n socket.close();\n }\n }\n}\n\nasync function single(iterable) {\n let found;\n for await (const message of iterable) {\n found ??= message;\n }\n if (found === undefined) {\n throw new RpcError(Code.Internal, \"the server sent no response\");\n }\n return found;\n}\n\nfunction bind(service, connection): Record<string, any> {\n const client: Record<string, any> = {};\n for (const method of service.methods) {\n const streamsInput =\n method.methodKind === \"client_streaming\" ||\n method.methodKind === \"bidi_streaming\";\n client[method.localName] = (\n input,\n options: { signal?: AbortSignal } = {},\n ) => {\n const call = (streamsInput ? invokeWebSocket : invokeHTTP)(\n connection,\n method,\n input,\n { signal: options.signal },\n );\n return method.methodKind === \"unary\" ||\n method.methodKind === \"client_streaming\"\n ? single(call)\n : call;\n };\n }\n return client;\n}\n\nexport function open({ url, token }) {\n const connection = {\n token,\n base: url,\n webSocketBase: url.replace(/^http/, \"ws\"),\n };\n return {\n system: bind(SystemService, connection),\n logs: bind(LogService, connection),\n swiplets: bind(SwipletService, connection),\n repl: bind(REPLService, connection),\n };\n}\n\nexport const unauthenticated = (error) =>\n error instanceof RpcError && error.code === Code.Unauthenticated;\n"],"mappings":";;;;;;;;AAUA,MAAM,iBAAiB,OAAO;AAC9B,MAAM,cAAc;AACpB,MAAM,uBAAuB;AAC7B,MAAM,EAAE,aAAa,cAAc,YAAY,GAAG,CAAC,CAAC,yBAAyB;AAE7E,IAAI,sBAAsB,WAAW;AAErC,MAAa,OAAO;CAClB,UAAU;CACV,SAAS;CACT,kBAAkB;CAClB,UAAU;CACV,eAAe;CACf,UAAU;CACV,aAAa;CACb,iBAAiB;AACnB;AAEA,IAAa,aAAb,cAAgC,MAAM,CAAC;AAEvC,IAAa,WAAb,cAA8B,MAAM;CAGlC,YAAY,MAAc,SAAkB;EAC1C,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,MAAM,kBAAkB;CACtB,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;AACZ;AAEA,SAAS,cAAc,MAAM;CAC3B,IAAI,SAAS,KAAA,KAAa,SAAS,MACjC,OAAO;CAET,IAAI;EACF,OAAO,mBAAmB,IAAI;CAChC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,aAAa,UACjB,OAAO,QAAQ,SAAS,IACpB,MAAM,OAAO,IAAI,SAAS,CAAC,CAAC,KAAK,IAAI,IACrC,OAAO,WAAW,OAAO;AAE/B,MAAM,kBAAkB,UAAU;CAChC,IAAI,iBAAiB,UACnB,OAAO;CAET,IAAI,OAAO,SAAS,cAClB,OAAO,IAAI,SAAS,KAAK,UAAU,uBAAuB;CAE5D,OAAO,IAAI,SACT,KAAK,aACL,UAAU,OAAO,KAAK,KAAK,OAAO,WAAW,OAAO,KAAK,CAC3D;AACF;AAEA,SAAS,MAAM,QAAQ,MAAM;CAC3B,MAAM,OAAO,SA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IAAI;CACJ,WAAW,MAAM,WAAW,UAC1B,UAAU;CAEZ,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,SAAS,KAAK,UAAU,6BAA6B;CAEjE,OAAO;AACT;AAEA,SAAS,KAAK,SAAS,YAAiC;CACtD,MAAM,SAA8B,CAAC;CACrC,KAAK,MAAM,UAAU,QAAQ,SAAS;EACpC,MAAM,eACJ,OAAO,eAAe,sBACtB,OAAO,eAAe;EACxB,OAAO,OAAO,cACZ,OACA,UAAoC,CAAC,MAClC;GACH,MAAM,QAAQ,eAAe,kBAAkB,WAAA,CAC7C,YACA,QACA,OACA,EAAE,QAAQ,QAAQ,OAAO,CAC3B;GACA,OAAO,OAAO,eAAe,WAC3B,OAAO,eAAe,qBACpB,OAAO,IAAI,IACX;EACN;CACF;CACA,OAAO;AACT;AAEA,SAAgB,KAAK,EAAE,KAAK,SAAS;CACnC,MAAM,aAAa;EACjB;EACA,MAAM;EACN,eAAe,IAAI,QAAQ,SAAS,IAAI;CAC1C;CACA,OAAO;EACL,QAAQ,KAAK,eAAe,UAAU;EACtC,MAAM,KAAK,YAAY,UAAU;EACjC,UAAU,KAAK,gBAAgB,UAAU;EACzC,MAAM,KAAK,aAAa,UAAU;CACpC;AACF;AAEA,MAAa,mBAAmB,UAC9B,iBAAiB,YAAY,MAAM,SAAS,KAAK"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["import dns from \"node:dns\";\nimport { createRequire } from \"node:module\";\n\nimport { create, fromBinary, toBinary } from \"@bufbuild/protobuf\";\n\nimport { resolveHost } from \"./mdns\";\nimport { LogService } from \"./proto/logs_pb\";\nimport { REPLService } from \"./proto/repl_pb\";\nimport { SwipletService } from \"./proto/swiplets_pb\";\nimport { SystemService } from \"./proto/system_pb\";\n\nconst largestMessage = 128 << 20;\nconst resolveLimit = 5000;\nconst contentType = \"application/grpc-web+proto\";\nconst webSocketSubprotocol = \"grpc-websockets\";\nconst { apiLevel } = createRequire(import.meta.url)(\"@swipt/api/package.json\");\n\ndns.setDefaultResultOrder(\"ipv4first\");\n\nexport const Code = {\n Canceled: 1,\n Unknown: 2,\n DeadlineExceeded: 4,\n NotFound: 5,\n Unimplemented: 12,\n Internal: 13,\n Unavailable: 14,\n Unauthenticated: 16,\n};\n\nexport class UsageError extends Error {}\n\nexport class RpcError extends Error {\n declare code: number;\n\n constructor(code: number, message?: string) {\n super(message);\n this.code = code;\n }\n}\n\nconst httpStatusCodes = {\n 400: Code.Internal,\n 401: Code.Unauthenticated,\n 403: Code.Unauthenticated,\n 404: Code.Unimplemented,\n 429: Code.Unavailable,\n 502: Code.Unavailable,\n 503: Code.Unavailable,\n 504: Code.Unavailable,\n};\n\nfunction statusMessage(text) {\n if (text === undefined || text === null) {\n return \"\";\n }\n try {\n return decodeURIComponent(text);\n } catch {\n return text;\n }\n}\n\nconst causeText = (cause) =>\n cause?.errors?.length > 0\n ? cause.errors.map(causeText).join(\"; \")\n : cause?.message || cause?.code;\n\nconst transportError = (error) => {\n if (error instanceof RpcError) {\n return error;\n }\n if (error?.name === \"AbortError\") {\n return new RpcError(Code.Canceled, \"the call was canceled\");\n }\n return new RpcError(\n Code.Unavailable,\n causeText(error?.cause) || error?.message || String(error),\n );\n};\n\nasync function locate(connection, signal) {\n const url = new URL(connection.url);\n if (!url.hostname.endsWith(\".local\")) {\n return connection.url;\n }\n let address;\n try {\n address = await resolveHost(\n url.hostname,\n AbortSignal.any([\n ...(signal ? [signal] : []),\n AbortSignal.timeout(resolveLimit),\n ]),\n );\n } catch (error) {\n throw transportError(error);\n }\n if (signal?.aborted) {\n throw new RpcError(Code.Canceled, \"the call was canceled\");\n }\n if (address === undefined) {\n throw new RpcError(\n Code.Unavailable,\n `${url.hostname} isn't found on the local network`,\n );\n }\n url.hostname = address.includes(\":\") ? `[${address}]` : address;\n return url.href.replace(/\\/+$/, \"\");\n}\n\nasync function base(connection, signal) {\n connection.resolved ??= await locate(connection, signal);\n return connection.resolved;\n}\n\nfunction frame(schema, init) {\n const body = toBinary(schema, create(schema, init));\n const out = Buffer.allocUnsafe(5 + body.length);\n out[0] = 0;\n out.writeUInt32BE(body.length, 1);\n out.set(body, 5);\n return out;\n}\n\nfunction parseMetadata(body) {\n const headers = {};\n for (const line of Buffer.from(body).toString().split(\"\\r\\n\")) {\n const separator = line.indexOf(\":\");\n if (separator > 0) {\n headers[line.slice(0, separator).trim().toLowerCase()] = line\n .slice(separator + 1)\n .trim();\n }\n }\n return headers;\n}\n\nclass FrameReader {\n declare schema: any;\n pending = Buffer.alloc(0);\n\n constructor(schema) {\n this.schema = schema;\n }\n\n push(chunk) {\n this.pending =\n this.pending.length === 0\n ? Buffer.from(chunk)\n : Buffer.concat([this.pending, Buffer.from(chunk)]);\n const frames = [];\n while (this.pending.length >= 5) {\n const length = this.pending.readUInt32BE(1);\n if (length > largestMessage) {\n throw new RpcError(\n Code.Internal,\n `the server sent a message of ${length} bytes`,\n );\n }\n if (this.pending.length < 5 + length) {\n break;\n }\n const body = this.pending.subarray(5, 5 + length);\n frames.push(\n (this.pending[0] & 0x80) !== 0\n ? { trailers: parseMetadata(body) }\n : { message: fromBinary(this.schema, body) },\n );\n this.pending = this.pending.subarray(5 + length);\n }\n return frames;\n }\n}\n\nfunction checkStatus(headers) {\n const status = headers[\"grpc-status\"];\n if (status === undefined || status === null) {\n return false;\n }\n const code = Number(status);\n if (code !== 0) {\n throw new RpcError(code, statusMessage(headers[\"grpc-message\"]));\n }\n return true;\n}\n\nfunction requestHeaders(connection) {\n const headers: Record<string, string> = {\n \"content-type\": contentType,\n \"x-grpc-web\": \"1\",\n \"swipt-api-level\": String(apiLevel),\n };\n if (connection.token !== \"\") {\n headers.authorization = `Bearer ${connection.token}`;\n }\n return headers;\n}\n\nasync function* invokeHTTP(connection, method, input, { signal }) {\n let response;\n try {\n response = await fetch(\n `${await base(connection, signal)}/${method.parent.typeName}/${method.name}`,\n {\n method: \"POST\",\n headers: requestHeaders(connection),\n body: frame(method.input, input),\n signal,\n },\n );\n } catch (error) {\n throw transportError(error);\n }\n const headers = Object.fromEntries(response.headers);\n if (response.status !== 200) {\n await response.body?.cancel();\n throw new RpcError(\n httpStatusCodes[response.status] ?? Code.Unknown,\n `HTTP ${response.status}`,\n );\n }\n if (checkStatus(headers)) {\n await response.body?.cancel();\n return;\n }\n const reader = new FrameReader(method.output);\n let ended = false;\n try {\n for await (const chunk of response.body) {\n for (const found of reader.push(chunk)) {\n if (found.trailers) {\n checkStatus(found.trailers);\n ended = true;\n } else if (!ended) {\n yield found.message;\n }\n }\n }\n } catch (error) {\n throw transportError(error);\n }\n if (!ended) {\n throw new RpcError(Code.Unavailable, \"the response ended without a status\");\n }\n}\n\nasync function* invokeWebSocket(connection, method, input, { signal }) {\n if (signal?.aborted) {\n throw new RpcError(Code.Canceled, \"the call was canceled\");\n }\n const webSocketBase = (await base(connection, signal)).replace(/^http/, \"ws\");\n const socket = new WebSocket(\n `${webSocketBase}/${method.parent.typeName}/${method.name}`,\n [webSocketSubprotocol],\n );\n socket.binaryType = \"arraybuffer\";\n const reader = new FrameReader(method.output);\n const messages = [];\n let failure;\n let closed = false;\n let headersSeen = false;\n let wake: (value?: unknown) => void = () => {};\n const notify = () => {\n const current = wake;\n wake = () => {};\n current();\n };\n const fail = (error) => {\n failure ??= error;\n socket.close();\n notify();\n };\n const abort = () =>\n fail(new RpcError(Code.Canceled, \"the call was canceled\"));\n const opened = new Promise((resolve, reject) => {\n socket.addEventListener(\"open\", resolve, { once: true });\n socket.addEventListener(\n \"close\",\n () =>\n reject(\n failure ??\n new RpcError(\n Code.Unavailable,\n `cannot connect to ${webSocketBase}`,\n ),\n ),\n { once: true },\n );\n });\n socket.addEventListener(\"message\", (event) => {\n try {\n for (const found of reader.push(new Uint8Array(event.data))) {\n if (found.message) {\n messages.push(found.message);\n } else if (headersSeen || \"grpc-status\" in found.trailers) {\n checkStatus(found.trailers);\n closed = true;\n socket.close();\n } else {\n headersSeen = true;\n }\n }\n } catch (error) {\n fail(error);\n }\n notify();\n });\n socket.addEventListener(\"close\", (event) => {\n if (!closed) {\n failure ??= new RpcError(\n Code.Unavailable,\n event.reason || \"the connection closed before the response\",\n );\n }\n closed = true;\n notify();\n });\n socket.addEventListener(\"error\", () => {\n failure ??= new RpcError(\n Code.Unavailable,\n `cannot connect to ${webSocketBase}`,\n );\n });\n signal?.addEventListener(\"abort\", abort, { once: true });\n try {\n await opened;\n const headers = requestHeaders(connection);\n socket.send(\n Buffer.from(\n `${Object.entries(headers)\n .map(([key, value]) => `${key}: ${value}\\r\\n`)\n .join(\"\")}`,\n ),\n );\n void (async () => {\n try {\n const body = method.methodKind === \"client_streaming\" ? input : [input];\n for await (const message of body) {\n if (closed || failure) {\n return;\n }\n socket.send(\n Buffer.concat([Buffer.from([0]), frame(method.input, message)]),\n );\n }\n if (!closed && !failure) {\n socket.send(Buffer.from([1]));\n }\n } catch (error) {\n fail(transportError(error));\n }\n })();\n while (true) {\n if (messages.length > 0) {\n yield messages.shift();\n continue;\n }\n if (closed || failure) {\n break;\n }\n await new Promise((resolve) => {\n wake = resolve;\n });\n }\n if (failure) {\n throw failure;\n }\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n if (socket.readyState !== WebSocket.CLOSED) {\n socket.close();\n }\n }\n}\n\nasync function single(iterable) {\n let found;\n for await (const message of iterable) {\n found ??= message;\n }\n if (found === undefined) {\n throw new RpcError(Code.Internal, \"the server sent no response\");\n }\n return found;\n}\n\nfunction bind(service, connection): Record<string, any> {\n const client: Record<string, any> = {};\n for (const method of service.methods) {\n const streamsInput =\n method.methodKind === \"client_streaming\" ||\n method.methodKind === \"bidi_streaming\";\n client[method.localName] = (\n input,\n options: { signal?: AbortSignal } = {},\n ) => {\n const call = (streamsInput ? invokeWebSocket : invokeHTTP)(\n connection,\n method,\n input,\n { signal: options.signal },\n );\n return method.methodKind === \"unary\" ||\n method.methodKind === \"client_streaming\"\n ? single(call)\n : call;\n };\n }\n return client;\n}\n\nexport function open({ url, token }) {\n const connection = { url, token, resolved: undefined };\n return {\n system: bind(SystemService, connection),\n logs: bind(LogService, connection),\n swiplets: bind(SwipletService, connection),\n repl: bind(REPLService, connection),\n };\n}\n\nexport const unauthenticated = (error) =>\n error instanceof RpcError && error.code === Code.Unauthenticated;\n"],"mappings":";;;;;;;;;AAWA,MAAM,iBAAiB,OAAO;AAC9B,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,uBAAuB;AAC7B,MAAM,EAAE,aAAa,cAAc,YAAY,GAAG,CAAC,CAAC,yBAAyB;AAE7E,IAAI,sBAAsB,WAAW;AAErC,MAAa,OAAO;CAClB,UAAU;CACV,SAAS;CACT,kBAAkB;CAClB,UAAU;CACV,eAAe;CACf,UAAU;CACV,aAAa;CACb,iBAAiB;AACnB;AAEA,IAAa,aAAb,cAAgC,MAAM,CAAC;AAEvC,IAAa,WAAb,cAA8B,MAAM;CAGlC,YAAY,MAAc,SAAkB;EAC1C,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,MAAM,kBAAkB;CACtB,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;AACZ;AAEA,SAAS,cAAc,MAAM;CAC3B,IAAI,SAAS,KAAA,KAAa,SAAS,MACjC,OAAO;CAET,IAAI;EACF,OAAO,mBAAmB,IAAI;CAChC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,aAAa,UACjB,OAAO,QAAQ,SAAS,IACpB,MAAM,OAAO,IAAI,SAAS,CAAC,CAAC,KAAK,IAAI,IACrC,OAAO,WAAW,OAAO;AAE/B,MAAM,kBAAkB,UAAU;CAChC,IAAI,iBAAiB,UACnB,OAAO;CAET,IAAI,OAAO,SAAS,cAClB,OAAO,IAAI,SAAS,KAAK,UAAU,uBAAuB;CAE5D,OAAO,IAAI,SACT,KAAK,aACL,UAAU,OAAO,KAAK,KA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,QACA,OACA,EAAE,QAAQ,QAAQ,OAAO,CAC3B;GACA,OAAO,OAAO,eAAe,WAC3B,OAAO,eAAe,qBACpB,OAAO,IAAI,IACX;EACN;CACF;CACA,OAAO;AACT;AAEA,SAAgB,KAAK,EAAE,KAAK,SAAS;CACnC,MAAM,aAAa;EAAE;EAAK;EAAO,UAAU,KAAA;CAAU;CACrD,OAAO;EACL,QAAQ,KAAK,eAAe,UAAU;EACtC,MAAM,KAAK,YAAY,UAAU;EACjC,UAAU,KAAK,gBAAgB,UAAU;EACzC,MAAM,KAAK,aAAa,UAAU;CACpC;AACF;AAEA,MAAa,mBAAmB,UAC9B,iBAAiB,YAAY,MAAM,SAAS,KAAK"}
|
package/dist/connection.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export declare function label(name: any): any;
|
|
2
2
|
export declare const sameName: (a: any, b: any) => boolean;
|
|
3
|
-
export declare const withToken: (url: any) => any;
|
|
3
|
+
export declare const withToken: (url: any, token?: string) => any;
|
|
4
4
|
export declare function findPublished(name: any, signal: any): Promise<any>;
|
|
5
|
+
export declare function findDriver(udid: any, signal: any): Promise<any>;
|
|
6
|
+
export declare function stopDriver(service: any, signal: any): Promise<void>;
|
|
5
7
|
export declare function runningSwipt(name: any, signal: any): Promise<{
|
|
6
8
|
system: Record<string, any>;
|
|
7
9
|
logs: Record<string, any>;
|
package/dist/connection.js
CHANGED
|
@@ -1,21 +1,20 @@
|
|
|
1
1
|
import { Code, RpcError, UsageError, open } from "./client.js";
|
|
2
|
+
import { configDirectory } from "./directories.js";
|
|
2
3
|
import { tr } from "./i18n.js";
|
|
4
|
+
import { multicastOptions } from "./mdns.js";
|
|
3
5
|
import { columns } from "./output.js";
|
|
4
6
|
import "./proto/common_pb.js";
|
|
5
7
|
import fs from "node:fs";
|
|
6
8
|
import path from "node:path";
|
|
7
|
-
import dgram from "node:dgram";
|
|
8
|
-
import { on } from "node:events";
|
|
9
|
-
import os from "node:os";
|
|
10
9
|
import { setTimeout } from "node:timers/promises";
|
|
11
10
|
import Bonjour from "bonjour-service";
|
|
12
|
-
import multicastDNS from "multicast-dns";
|
|
13
11
|
// src/connection.ts
|
|
14
12
|
const browseLimit = 1500;
|
|
15
13
|
const browseRequery = 300;
|
|
16
14
|
const publishLimit = 1e4;
|
|
17
15
|
const answerLimit = 5e3;
|
|
18
|
-
const
|
|
16
|
+
const stopLimit = 1e4;
|
|
17
|
+
const storeFile = path.join(configDirectory, "devices.json");
|
|
19
18
|
function load() {
|
|
20
19
|
let text;
|
|
21
20
|
try {
|
|
@@ -58,26 +57,26 @@ function parseURL(text) {
|
|
|
58
57
|
token
|
|
59
58
|
};
|
|
60
59
|
}
|
|
61
|
-
const withToken = (url) => url.replace("://",
|
|
60
|
+
const withToken = (url, token = "TOKEN") => url.replace("://", `://${encodeURIComponent(token)}@`);
|
|
62
61
|
async function browse(signal, until, limit = browseLimit) {
|
|
63
|
-
const
|
|
64
|
-
socket: dgram.createSocket("udp4"),
|
|
65
|
-
bind: false
|
|
66
|
-
});
|
|
62
|
+
const responders = multicastOptions().map((options) => new Bonjour(options));
|
|
67
63
|
const found = /* @__PURE__ */ new Map();
|
|
68
64
|
const enough = new AbortController();
|
|
69
65
|
try {
|
|
70
|
-
const
|
|
66
|
+
const browsers = responders.map((bonjour) => bonjour.find({ type: "swipt" }, (service) => {
|
|
71
67
|
if (!service.host || found.has(service.name)) return;
|
|
72
68
|
const host = service.host.replace(/\.$/, "").toLowerCase();
|
|
73
69
|
found.set(service.name, {
|
|
74
70
|
name: label(service.name),
|
|
75
71
|
url: `http://${host.includes(":") ? `[${host}]` : host}:${service.port}`,
|
|
76
|
-
authenticates: service.txt?.auth === "1"
|
|
72
|
+
authenticates: service.txt?.auth === "1",
|
|
73
|
+
udid: service.txt?.udid
|
|
77
74
|
});
|
|
78
75
|
if (until?.([...found.values()])) enough.abort();
|
|
79
|
-
});
|
|
80
|
-
const requery = setInterval(() =>
|
|
76
|
+
}));
|
|
77
|
+
const requery = setInterval(() => {
|
|
78
|
+
for (const browser of browsers) browser.update();
|
|
79
|
+
}, browseRequery);
|
|
81
80
|
try {
|
|
82
81
|
await setTimeout(limit, void 0, { signal: AbortSignal.any([signal, enough.signal]) });
|
|
83
82
|
} catch (error) {
|
|
@@ -85,9 +84,9 @@ async function browse(signal, until, limit = browseLimit) {
|
|
|
85
84
|
} finally {
|
|
86
85
|
clearInterval(requery);
|
|
87
86
|
}
|
|
88
|
-
browser.stop();
|
|
87
|
+
for (const browser of browsers) browser.stop();
|
|
89
88
|
} finally {
|
|
90
|
-
bonjour.destroy();
|
|
89
|
+
for (const bonjour of responders) bonjour.destroy();
|
|
91
90
|
}
|
|
92
91
|
return [...found.values()];
|
|
93
92
|
}
|
|
@@ -96,6 +95,23 @@ async function findPublished(name, signal) {
|
|
|
96
95
|
const matches = (service) => sameName(service.name, wanted);
|
|
97
96
|
return (await browse(signal, (services) => services.some(matches), publishLimit)).find(matches);
|
|
98
97
|
}
|
|
98
|
+
async function findDriver(udid, signal) {
|
|
99
|
+
const serves = (service) => service.udid !== void 0 && sameName(service.udid, udid);
|
|
100
|
+
return (await browse(signal, (services) => services.some(serves))).find(serves);
|
|
101
|
+
}
|
|
102
|
+
async function stopDriver(service, signal) {
|
|
103
|
+
await open({
|
|
104
|
+
url: service.url,
|
|
105
|
+
token: ""
|
|
106
|
+
}).system.shutdown({}, { signal });
|
|
107
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(stopLimit)]);
|
|
108
|
+
try {
|
|
109
|
+
while (await findDriver(service.udid, deadline) !== void 0) await setTimeout(browseRequery, void 0, { signal: deadline });
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (signal.aborted) throw error;
|
|
112
|
+
throw new Error(tr("The driver on {computer} didn't stop.", { computer: new URL(service.url).hostname }));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
99
115
|
async function runningSwipt(name, signal) {
|
|
100
116
|
const wanted = label(name);
|
|
101
117
|
const stored = load();
|
|
@@ -179,11 +195,11 @@ async function attach(context) {
|
|
|
179
195
|
return open(device);
|
|
180
196
|
}
|
|
181
197
|
const connectionStates = {
|
|
182
|
-
[1]: tr("stopped"),
|
|
183
|
-
[2]: tr("connecting"),
|
|
184
|
-
[3]: tr("preparing"),
|
|
185
|
-
[4]: tr("running"),
|
|
186
|
-
[5]: tr("failed")
|
|
198
|
+
[1]: tr("stopped", {}, "device connection"),
|
|
199
|
+
[2]: tr("connecting", {}, "device connection"),
|
|
200
|
+
[3]: tr("preparing", {}, "device connection"),
|
|
201
|
+
[4]: tr("running", {}, "device connection"),
|
|
202
|
+
[5]: tr("failed", {}, "device connection")
|
|
187
203
|
};
|
|
188
204
|
const connectionProblems = {
|
|
189
205
|
[1]: tr("unreachable"),
|
|
@@ -198,36 +214,9 @@ const connectionProblems = {
|
|
|
198
214
|
function connectionText(connection) {
|
|
199
215
|
return [[connectionStates[connection?.state], connectionProblems[connection?.problem]].filter(Boolean).join(", "), connection?.message].filter(Boolean).join(": ");
|
|
200
216
|
}
|
|
201
|
-
async function onLocalNetwork(host, signal) {
|
|
202
|
-
const mdns = multicastDNS({
|
|
203
|
-
socket: dgram.createSocket("udp4"),
|
|
204
|
-
bind: false
|
|
205
|
-
});
|
|
206
|
-
const query = () => mdns.query([{
|
|
207
|
-
name: host,
|
|
208
|
-
type: "A"
|
|
209
|
-
}, {
|
|
210
|
-
name: host,
|
|
211
|
-
type: "AAAA"
|
|
212
|
-
}]);
|
|
213
|
-
const requery = setInterval(query, browseRequery);
|
|
214
|
-
query();
|
|
215
|
-
try {
|
|
216
|
-
for await (const [response] of on(mdns, "response", { signal })) if (response.answers.some((it) => sameName(it.name, host))) return true;
|
|
217
|
-
} catch (error) {
|
|
218
|
-
if (!signal.aborted) throw error;
|
|
219
|
-
} finally {
|
|
220
|
-
clearInterval(requery);
|
|
221
|
-
mdns.destroy();
|
|
222
|
-
}
|
|
223
|
-
return false;
|
|
224
|
-
}
|
|
225
217
|
async function probe(url, signal) {
|
|
226
218
|
try {
|
|
227
|
-
const
|
|
228
|
-
const { hostname } = new URL(device.url);
|
|
229
|
-
if (hostname.endsWith(".local") && !await onLocalNetwork(hostname, signal)) return { cells: [tr("offline")] };
|
|
230
|
-
const info = await open(device).system.getInfo({}, { signal });
|
|
219
|
+
const info = await open(parseURL(url)).system.getInfo({}, { signal });
|
|
231
220
|
return { cells: [info.appBuild === "" ? info.appVersion : `${info.appVersion} (${info.appBuild})`, connectionText(info.deviceConnection)] };
|
|
232
221
|
} catch (error) {
|
|
233
222
|
if (error instanceof RpcError && error.code === Code.Unauthenticated) return { cells: [tr("requires a token")] };
|
|
@@ -241,7 +230,7 @@ async function list({ signal }) {
|
|
|
241
230
|
const stored = load();
|
|
242
231
|
const deadline = AbortSignal.any([signal, AbortSignal.timeout(browseLimit)]);
|
|
243
232
|
const probes = new Map(Object.values(stored).map((url) => [url, probe(url, deadline)]));
|
|
244
|
-
const locked = (await discover(signal, stored)).filter((it) => it.authenticates &&
|
|
233
|
+
const locked = (await discover(signal, stored)).filter((it) => it.authenticates && !Object.values(stored).some((url) => parseURL(url).url === it.url));
|
|
245
234
|
const names = Object.keys(stored).sort((a, b) => a.localeCompare(b));
|
|
246
235
|
if (names.length === 0 && locked.length === 0) {
|
|
247
236
|
console.error(tr("No device publishes Swipt on the local network; turn on Swipt › Developer › Local Network, or connect one with \"swipt device add URL\"."));
|
|
@@ -281,8 +270,8 @@ function remove({ args }) {
|
|
|
281
270
|
if (name === void 0) throw new Error(tr("There is no device {device}.", { device: args[0] }));
|
|
282
271
|
delete stored[name];
|
|
283
272
|
save(stored);
|
|
284
|
-
console.log(tr("removed {name}", { name }));
|
|
273
|
+
console.log(tr("removed {name}", { name }, "device"));
|
|
285
274
|
}
|
|
286
|
-
export { add, attach, findPublished, label, list, remove, runningSwipt, sameName, tryUnlock, withToken };
|
|
275
|
+
export { add, attach, findDriver, findPublished, label, list, remove, runningSwipt, sameName, stopDriver, tryUnlock, withToken };
|
|
287
276
|
|
|
288
277
|
//# sourceMappingURL=connection.js.map
|
package/dist/connection.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connection.js","names":["sleep"],"sources":["../src/connection.ts"],"sourcesContent":["import dgram from \"node:dgram\";\nimport { on } from \"node:events\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\nimport Bonjour from \"bonjour-service\";\nimport multicastDNS from \"multicast-dns\";\n\nimport { Code, RpcError, UsageError, open } from \"./client\";\nimport { tr } from \"./i18n\";\nimport { columns } from \"./output\";\nimport {\n DeviceConnectionProblem,\n DeviceConnectionState,\n} from \"./proto/common_pb\";\n\nconst browseLimit = 1500;\nconst browseRequery = 300;\nconst publishLimit = 10_000;\nconst answerLimit = 5000;\n\nconst storeFile = path.join(\n process.env.XDG_CONFIG_HOME || path.join(os.homedir(), \".config\"),\n \"swipt\",\n \"devices.json\",\n);\n\nfunction load() {\n let text;\n try {\n text = fs.readFileSync(storeFile, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return {};\n }\n throw error;\n }\n return JSON.parse(text);\n}\n\nfunction save(devices) {\n fs.mkdirSync(path.dirname(storeFile), { recursive: true, mode: 0o700 });\n fs.writeFileSync(storeFile, `${JSON.stringify(devices, null, 2)}\\n`, {\n mode: 0o600,\n });\n}\n\nexport function label(name) {\n const slug = [...name.replaceAll(/['’]/g, \"\")]\n .map((character) => (/[A-Za-z0-9]/.test(character) ? character : \"-\"))\n .join(\"\")\n .split(\"-\")\n .filter((part) => part !== \"\")\n .join(\"-\");\n return slug === \"\" ? name : slug;\n}\n\nexport const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();\n\nconst storedName = (stored, name) =>\n Object.keys(stored).find((it) => sameName(it, name));\n\nfunction parseURL(text) {\n let parsed;\n try {\n parsed = new URL(text.includes(\"://\") ? text : `http://${text}`);\n } catch {\n throw new UsageError(tr(\"{text} isn't a URL.\", { text }));\n }\n if (\n parsed.hostname === \"\" ||\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")\n ) {\n throw new UsageError(tr(\"{text} isn't an http or https URL.\", { text }));\n }\n let token;\n try {\n token = decodeURIComponent(parsed.username);\n } catch {\n token = parsed.username;\n }\n return {\n url: `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\\/+$/, \"\")}`,\n token,\n };\n}\n\nexport const withToken = (url) => url.replace(\"://\", \"://TOKEN@\");\n\nasync function browse(signal, until, limit = browseLimit) {\n const bonjour = new Bonjour({\n socket: dgram.createSocket(\"udp4\"),\n bind: false,\n } as any);\n const found = new Map();\n const enough = new AbortController();\n try {\n const browser = bonjour.find({ type: \"swipt\" }, (service) => {\n if (!service.host || found.has(service.name)) {\n return;\n }\n const host = service.host.replace(/\\.$/, \"\").toLowerCase();\n found.set(service.name, {\n name: label(service.name),\n url: `http://${host.includes(\":\") ? `[${host}]` : host}:${service.port}`,\n authenticates: service.txt?.auth === \"1\",\n });\n if (until?.([...found.values()])) {\n enough.abort();\n }\n });\n const requery = setInterval(() => browser.update(), browseRequery);\n try {\n await sleep(limit, undefined, {\n signal: AbortSignal.any([signal, enough.signal]),\n });\n } catch (error) {\n if (signal.aborted) {\n throw error;\n }\n } finally {\n clearInterval(requery);\n }\n browser.stop();\n } finally {\n bonjour.destroy();\n }\n return [...found.values()];\n}\n\nexport async function findPublished(name, signal) {\n const wanted = label(name);\n const matches = (service) => sameName(service.name, wanted);\n const found = await browse(\n signal,\n (services) => services.some(matches),\n publishLimit,\n );\n return found.find(matches);\n}\n\nexport async function runningSwipt(name, signal) {\n const wanted = label(name);\n const stored = load();\n await discover(signal, stored, (services) =>\n services.some((it) => sameName(it.name, wanted)),\n );\n const known = storedName(stored, wanted);\n if (known === undefined) {\n return undefined;\n }\n const client = open(parseURL(stored[known]));\n try {\n await client.system.getInfo(\n {},\n { signal: AbortSignal.any([signal, AbortSignal.timeout(answerLimit)]) },\n );\n } catch (error) {\n if (signal.aborted || !(error instanceof RpcError)) {\n throw error;\n }\n if (error.code === Code.Unauthenticated) {\n console.error(tr(\"error: {message}\", { message: error.message }));\n }\n return undefined;\n }\n return client;\n}\n\nexport async function tryUnlock(client, signal) {\n try {\n for await (const response of client.repl.execute(\n { code: \"await device.unlock()\", args: [], program: false },\n { signal },\n )) {\n if (response.part.case === \"error\") {\n return response.part.value.message;\n }\n }\n } catch (error) {\n if (signal.aborted || !(error instanceof RpcError)) {\n throw error;\n }\n return error.message;\n }\n return undefined;\n}\n\nasync function discover(signal, stored, until?) {\n const found = await browse(signal, until);\n let changed = false;\n for (const it of found) {\n if (it.authenticates) {\n continue;\n }\n const name = storedName(stored, it.name);\n if (name === undefined) {\n stored[it.name] = it.url;\n changed = true;\n } else {\n const current = parseURL(stored[name]);\n if (\n current.token === \"\" &&\n current.url !== it.url &&\n new URL(current.url).hostname.endsWith(\".local\")\n ) {\n stored[name] = it.url;\n changed = true;\n }\n }\n }\n if (changed) {\n save(stored);\n }\n return found;\n}\n\nconst requiresToken = (found) =>\n tr(\"{device} requires a token: swipt device add {url}\", {\n device: found.name,\n url: withToken(found.url),\n });\n\nexport async function attach(context) {\n const given = context.options.device;\n const stored = load();\n let device;\n if (given && /[:/]/.test(given)) {\n device = parseURL(given);\n } else if (given) {\n const name = label(given);\n let known = storedName(stored, name);\n if (known === undefined) {\n const found = (\n await discover(context.signal, stored, (services) =>\n services.some((it) => sameName(it.name, name)),\n )\n ).find((it) => sameName(it.name, name));\n if (!found) {\n throw new Error(\n tr('There is no device {device}; \"swipt device list\" lists them.', {\n device: name,\n }),\n );\n }\n if (found.authenticates) {\n throw new Error(requiresToken(found));\n }\n known = found.name;\n }\n device = parseURL(stored[known]);\n } else {\n let found = [];\n if (Object.keys(stored).length === 0) {\n found = await discover(context.signal, stored);\n }\n const names = Object.keys(stored);\n if (names.length === 0) {\n const locked = found.filter((it) => it.authenticates);\n if (locked.length > 0) {\n throw new Error(locked.map(requiresToken).join(\"\\n\"));\n }\n throw new Error(\n tr(\n 'There is no device; turn on Swipt › Developer › Local Network, or connect one with \"swipt device add URL\".',\n ),\n );\n }\n if (names.length > 1) {\n throw new Error(\n tr(\"There is more than one device: {devices}; choose one with -d\", {\n devices: names.join(\", \"),\n }),\n );\n }\n device = parseURL(stored[names[0]]);\n }\n context.target.url = device.url;\n return open(device);\n}\n\nconst connectionStates = {\n [DeviceConnectionState.STOPPED]: tr(\"stopped\"),\n [DeviceConnectionState.CONNECTING]: tr(\"connecting\"),\n [DeviceConnectionState.PREPARING]: tr(\"preparing\"),\n [DeviceConnectionState.RUNNING]: tr(\"running\"),\n [DeviceConnectionState.FAILED]: tr(\"failed\"),\n};\n\nconst connectionProblems = {\n [DeviceConnectionProblem.UNREACHABLE]: tr(\"unreachable\"),\n [DeviceConnectionProblem.PAIRING_REJECTED]: tr(\"pairing rejected\"),\n [DeviceConnectionProblem.DEVELOPER_MODE_OFF]: tr(\"developer mode off\"),\n [DeviceConnectionProblem.DISK_IMAGE_MISSING]: tr(\"disk image missing\"),\n [DeviceConnectionProblem.DISK_IMAGE_MOUNT_FAILED]: tr(\n \"disk image mount failed\",\n ),\n [DeviceConnectionProblem.DEVICE_UNSUPPORTED]: tr(\"device unsupported\"),\n [DeviceConnectionProblem.SCREEN_IN_USE]: tr(\"screen in use\"),\n [DeviceConnectionProblem.VPN_PEER_ADDRESS_MISSING]: tr(\n \"VPN peer address missing\",\n ),\n};\n\nfunction connectionText(connection) {\n return [\n [\n connectionStates[connection?.state],\n connectionProblems[connection?.problem],\n ]\n .filter(Boolean)\n .join(\", \"),\n connection?.message,\n ]\n .filter(Boolean)\n .join(\": \");\n}\n\nasync function onLocalNetwork(host, signal) {\n const mdns = multicastDNS({\n socket: dgram.createSocket(\"udp4\"),\n bind: false,\n });\n const query = () =>\n mdns.query([\n { name: host, type: \"A\" },\n { name: host, type: \"AAAA\" },\n ]);\n const requery = setInterval(query, browseRequery);\n query();\n try {\n for await (const [response] of on(mdns, \"response\", { signal })) {\n if (response.answers.some((it) => sameName(it.name, host))) {\n return true;\n }\n }\n } catch (error) {\n if (!signal.aborted) {\n throw error;\n }\n } finally {\n clearInterval(requery);\n mdns.destroy();\n }\n return false;\n}\n\nasync function probe(url, signal) {\n try {\n const device = parseURL(url);\n const { hostname } = new URL(device.url);\n if (\n hostname.endsWith(\".local\") &&\n !(await onLocalNetwork(hostname, signal))\n ) {\n return { cells: [tr(\"offline\")] };\n }\n const info = await open(device).system.getInfo({}, { signal });\n return {\n cells: [\n info.appBuild === \"\"\n ? info.appVersion\n : `${info.appVersion} (${info.appBuild})`,\n connectionText(info.deviceConnection),\n ],\n };\n } catch (error) {\n if (error instanceof RpcError && error.code === Code.Unauthenticated) {\n return { cells: [tr(\"requires a token\")] };\n }\n return {\n cells: [tr(\"offline\")],\n failure: signal.aborted ? undefined : error.message,\n };\n }\n}\n\nexport async function list({ signal }) {\n const stored = load();\n const deadline = AbortSignal.any([signal, AbortSignal.timeout(browseLimit)]);\n const probes = new Map(\n Object.values(stored).map((url) => [url, probe(url, deadline)]),\n );\n const locked = (await discover(signal, stored)).filter(\n (it) => it.authenticates && storedName(stored, it.name) === undefined,\n );\n const names = Object.keys(stored).sort((a, b) => a.localeCompare(b));\n if (names.length === 0 && locked.length === 0) {\n console.error(\n tr(\n 'No device publishes Swipt on the local network; turn on Swipt › Developer › Local Network, or connect one with \"swipt device add URL\".',\n ),\n );\n return;\n }\n const late = AbortSignal.any([signal, AbortSignal.timeout(browseLimit)]);\n const probed = await Promise.all(\n names.map(async (name) => ({\n name,\n ...(await (probes.get(stored[name]) ?? probe(stored[name], late))),\n })),\n );\n console.log(\n columns(\n [\n ...probed.map(({ name, cells }) => [\n name,\n parseURL(stored[name]).url,\n ...cells,\n ]),\n ...locked.map((it) => [it.name, it.url, tr(\"requires a token\")]),\n ].sort((a, b) => a[0].localeCompare(b[0])),\n ),\n );\n for (const { name, failure } of probed) {\n if (failure !== undefined) {\n console.error(`${name}: ${failure}`);\n }\n }\n for (const it of locked) {\n console.error(requiresToken(it));\n }\n}\n\nexport async function add(context) {\n const device = parseURL(context.args[0]);\n context.target.url = device.url;\n const info = await open(device).system.getInfo(\n {},\n { signal: context.signal },\n );\n const name = label(info.deviceName) || new URL(device.url).hostname;\n const stored = load();\n const previous = storedName(stored, name);\n if (previous !== undefined) {\n delete stored[previous];\n }\n stored[name] = context.args[0];\n save(stored);\n console.log(tr(\"added {device}\", { device: name }));\n}\n\nexport function remove({ args }) {\n const stored = load();\n const name = storedName(stored, label(args[0]));\n if (name === undefined) {\n throw new Error(tr(\"There is no device {device}.\", { device: args[0] }));\n }\n delete stored[name];\n save(stored);\n console.log(tr(\"removed {name}\", { name }));\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,MAAM,cAAc;AACpB,MAAM,gBAAgB;AACtB,MAAM,eAAe;AACrB,MAAM,cAAc;AAEpB,MAAM,YAAY,KAAK,KACrB,QAAQ,IAAI,mBAAmB,KAAK,KAAK,GAAG,QAAQ,GAAG,SAAS,GAChE,SACA,cACF;AAEA,SAAS,OAAO;CACd,IAAI;CACJ,IAAI;EACF,OAAO,GAAG,aAAa,WAAW,MAAM;CAC1C,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAC5C,OAAO,CAAC;EAEV,MAAM;CACR;CACA,OAAO,KAAK,MAAM,IAAI;AACxB;AAEA,SAAS,KAAK,SAAS;CACrB,GAAG,UAAU,KAAK,QAAQ,SAAS,GAAG;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;CACtE,GAAG,cAAc,WAAW,GAAG,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE,KAAK,EACnE,MAAM,IACR,CAAC;AACH;AAEA,SAAgB,MAAM,MAAM;CAC1B,MAAM,OAAO,CAAC,GAAG,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC,CAC3C,KAAK,cAAe,cAAc,KAAK,SAAS,IAAI,YAAY,GAAI,CAAC,CACrE,KAAK,EAAE,CAAC,CACR,MAAM,GAAG,CAAC,CACV,Q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Q,KAAK,GAAG,CAAC,CAAC;CAEzE,OAAO,OAAO;CACd,KAAK,MAAM;CACX,QAAQ,IAAI,GAAG,kBAAkB,EAAE,KAAK,CAAC,CAAC;AAC5C"}
|
|
1
|
+
{"version":3,"file":"connection.js","names":["sleep"],"sources":["../src/connection.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\nimport Bonjour from \"bonjour-service\";\n\nimport { Code, RpcError, UsageError, open } from \"./client\";\nimport { configDirectory } from \"./directories\";\nimport { tr } from \"./i18n\";\nimport { multicastOptions } from \"./mdns\";\nimport { columns } from \"./output\";\nimport {\n DeviceConnectionProblem,\n DeviceConnectionState,\n} from \"./proto/common_pb\";\n\nconst browseLimit = 1500;\nconst browseRequery = 300;\nconst publishLimit = 10_000;\nconst answerLimit = 5000;\nconst stopLimit = 10_000;\n\nconst storeFile = path.join(configDirectory, \"devices.json\");\n\nfunction load() {\n let text;\n try {\n text = fs.readFileSync(storeFile, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return {};\n }\n throw error;\n }\n return JSON.parse(text);\n}\n\nfunction save(devices) {\n fs.mkdirSync(path.dirname(storeFile), { recursive: true, mode: 0o700 });\n fs.writeFileSync(storeFile, `${JSON.stringify(devices, null, 2)}\\n`, {\n mode: 0o600,\n });\n}\n\nexport function label(name) {\n const slug = [...name.replaceAll(/['’]/g, \"\")]\n .map((character) => (/[A-Za-z0-9]/.test(character) ? character : \"-\"))\n .join(\"\")\n .split(\"-\")\n .filter((part) => part !== \"\")\n .join(\"-\");\n return slug === \"\" ? name : slug;\n}\n\nexport const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();\n\nconst storedName = (stored, name) =>\n Object.keys(stored).find((it) => sameName(it, name));\n\nfunction parseURL(text) {\n let parsed;\n try {\n parsed = new URL(text.includes(\"://\") ? text : `http://${text}`);\n } catch {\n throw new UsageError(tr(\"{text} isn't a URL.\", { text }));\n }\n if (\n parsed.hostname === \"\" ||\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")\n ) {\n throw new UsageError(tr(\"{text} isn't an http or https URL.\", { text }));\n }\n let token;\n try {\n token = decodeURIComponent(parsed.username);\n } catch {\n token = parsed.username;\n }\n return {\n url: `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\\/+$/, \"\")}`,\n token,\n };\n}\n\nexport const withToken = (url, token = \"TOKEN\") =>\n url.replace(\"://\", `://${encodeURIComponent(token)}@`);\n\nasync function browse(signal, until, limit = browseLimit) {\n const responders = multicastOptions().map(\n (options) => new Bonjour(options as any),\n );\n const found = new Map();\n const enough = new AbortController();\n try {\n const browsers = responders.map((bonjour) =>\n bonjour.find({ type: \"swipt\" }, (service) => {\n if (!service.host || found.has(service.name)) {\n return;\n }\n const host = service.host.replace(/\\.$/, \"\").toLowerCase();\n found.set(service.name, {\n name: label(service.name),\n url: `http://${host.includes(\":\") ? `[${host}]` : host}:${service.port}`,\n authenticates: service.txt?.auth === \"1\",\n udid: service.txt?.udid,\n });\n if (until?.([...found.values()])) {\n enough.abort();\n }\n }),\n );\n const requery = setInterval(() => {\n for (const browser of browsers) {\n browser.update();\n }\n }, browseRequery);\n try {\n await sleep(limit, undefined, {\n signal: AbortSignal.any([signal, enough.signal]),\n });\n } catch (error) {\n if (signal.aborted) {\n throw error;\n }\n } finally {\n clearInterval(requery);\n }\n for (const browser of browsers) {\n browser.stop();\n }\n } finally {\n for (const bonjour of responders) {\n bonjour.destroy();\n }\n }\n return [...found.values()];\n}\n\nexport async function findPublished(name, signal) {\n const wanted = label(name);\n const matches = (service) => sameName(service.name, wanted);\n const found = await browse(\n signal,\n (services) => services.some(matches),\n publishLimit,\n );\n return found.find(matches);\n}\n\nexport async function findDriver(udid, signal) {\n const serves = (service) =>\n service.udid !== undefined && sameName(service.udid, udid);\n return (await browse(signal, (services) => services.some(serves))).find(\n serves,\n );\n}\n\nexport async function stopDriver(service, signal) {\n await open({ url: service.url, token: \"\" }).system.shutdown({}, { signal });\n const deadline = AbortSignal.any([signal, AbortSignal.timeout(stopLimit)]);\n try {\n while ((await findDriver(service.udid, deadline)) !== undefined) {\n await sleep(browseRequery, undefined, { signal: deadline });\n }\n } catch (error) {\n if (signal.aborted) {\n throw error;\n }\n throw new Error(\n tr(\"The driver on {computer} didn't stop.\", {\n computer: new URL(service.url).hostname,\n }),\n );\n }\n}\n\nexport async function runningSwipt(name, signal) {\n const wanted = label(name);\n const stored = load();\n await discover(signal, stored, (services) =>\n services.some((it) => sameName(it.name, wanted)),\n );\n const known = storedName(stored, wanted);\n if (known === undefined) {\n return undefined;\n }\n const client = open(parseURL(stored[known]));\n try {\n await client.system.getInfo(\n {},\n { signal: AbortSignal.any([signal, AbortSignal.timeout(answerLimit)]) },\n );\n } catch (error) {\n if (signal.aborted || !(error instanceof RpcError)) {\n throw error;\n }\n if (error.code === Code.Unauthenticated) {\n console.error(tr(\"error: {message}\", { message: error.message }));\n }\n return undefined;\n }\n return client;\n}\n\nexport async function tryUnlock(client, signal) {\n try {\n for await (const response of client.repl.execute(\n { code: \"await device.unlock()\", args: [], program: false },\n { signal },\n )) {\n if (response.part.case === \"error\") {\n return response.part.value.message;\n }\n }\n } catch (error) {\n if (signal.aborted || !(error instanceof RpcError)) {\n throw error;\n }\n return error.message;\n }\n return undefined;\n}\n\nasync function discover(signal, stored, until?) {\n const found = await browse(signal, until);\n let changed = false;\n for (const it of found) {\n if (it.authenticates) {\n continue;\n }\n const name = storedName(stored, it.name);\n if (name === undefined) {\n stored[it.name] = it.url;\n changed = true;\n } else {\n const current = parseURL(stored[name]);\n if (\n current.token === \"\" &&\n current.url !== it.url &&\n new URL(current.url).hostname.endsWith(\".local\")\n ) {\n stored[name] = it.url;\n changed = true;\n }\n }\n }\n if (changed) {\n save(stored);\n }\n return found;\n}\n\nconst requiresToken = (found) =>\n tr(\"{device} requires a token: swipt device add {url}\", {\n device: found.name,\n url: withToken(found.url),\n });\n\nexport async function attach(context) {\n const given = context.options.device;\n const stored = load();\n let device;\n if (given && /[:/]/.test(given)) {\n device = parseURL(given);\n } else if (given) {\n const name = label(given);\n let known = storedName(stored, name);\n if (known === undefined) {\n const found = (\n await discover(context.signal, stored, (services) =>\n services.some((it) => sameName(it.name, name)),\n )\n ).find((it) => sameName(it.name, name));\n if (!found) {\n throw new Error(\n tr('There is no device {device}; \"swipt device list\" lists them.', {\n device: name,\n }),\n );\n }\n if (found.authenticates) {\n throw new Error(requiresToken(found));\n }\n known = found.name;\n }\n device = parseURL(stored[known]);\n } else {\n let found = [];\n if (Object.keys(stored).length === 0) {\n found = await discover(context.signal, stored);\n }\n const names = Object.keys(stored);\n if (names.length === 0) {\n const locked = found.filter((it) => it.authenticates);\n if (locked.length > 0) {\n throw new Error(locked.map(requiresToken).join(\"\\n\"));\n }\n throw new Error(\n tr(\n 'There is no device; turn on Swipt › Developer › Local Network, or connect one with \"swipt device add URL\".',\n ),\n );\n }\n if (names.length > 1) {\n throw new Error(\n tr(\"There is more than one device: {devices}; choose one with -d\", {\n devices: names.join(\", \"),\n }),\n );\n }\n device = parseURL(stored[names[0]]);\n }\n context.target.url = device.url;\n return open(device);\n}\n\nconst connectionStates = {\n [DeviceConnectionState.STOPPED]: tr(\"stopped\", {}, \"device connection\"),\n [DeviceConnectionState.CONNECTING]: tr(\"connecting\", {}, \"device connection\"),\n [DeviceConnectionState.PREPARING]: tr(\"preparing\", {}, \"device connection\"),\n [DeviceConnectionState.RUNNING]: tr(\"running\", {}, \"device connection\"),\n [DeviceConnectionState.FAILED]: tr(\"failed\", {}, \"device connection\"),\n};\n\nconst connectionProblems = {\n [DeviceConnectionProblem.UNREACHABLE]: tr(\"unreachable\"),\n [DeviceConnectionProblem.PAIRING_REJECTED]: tr(\"pairing rejected\"),\n [DeviceConnectionProblem.DEVELOPER_MODE_OFF]: tr(\"developer mode off\"),\n [DeviceConnectionProblem.DISK_IMAGE_MISSING]: tr(\"disk image missing\"),\n [DeviceConnectionProblem.DISK_IMAGE_MOUNT_FAILED]: tr(\n \"disk image mount failed\",\n ),\n [DeviceConnectionProblem.DEVICE_UNSUPPORTED]: tr(\"device unsupported\"),\n [DeviceConnectionProblem.SCREEN_IN_USE]: tr(\"screen in use\"),\n [DeviceConnectionProblem.VPN_PEER_ADDRESS_MISSING]: tr(\n \"VPN peer address missing\",\n ),\n};\n\nfunction connectionText(connection) {\n return [\n [\n connectionStates[connection?.state],\n connectionProblems[connection?.problem],\n ]\n .filter(Boolean)\n .join(\", \"),\n connection?.message,\n ]\n .filter(Boolean)\n .join(\": \");\n}\n\nasync function probe(url, signal) {\n try {\n const info = await open(parseURL(url)).system.getInfo({}, { signal });\n return {\n cells: [\n info.appBuild === \"\"\n ? info.appVersion\n : `${info.appVersion} (${info.appBuild})`,\n connectionText(info.deviceConnection),\n ],\n };\n } catch (error) {\n if (error instanceof RpcError && error.code === Code.Unauthenticated) {\n return { cells: [tr(\"requires a token\")] };\n }\n return {\n cells: [tr(\"offline\")],\n failure: signal.aborted ? undefined : error.message,\n };\n }\n}\n\nexport async function list({ signal }) {\n const stored = load();\n const deadline = AbortSignal.any([signal, AbortSignal.timeout(browseLimit)]);\n const probes = new Map(\n Object.values(stored).map((url) => [url, probe(url, deadline)]),\n );\n const locked = (await discover(signal, stored)).filter(\n (it) =>\n it.authenticates &&\n !Object.values(stored).some((url) => parseURL(url).url === it.url),\n );\n const names = Object.keys(stored).sort((a, b) => a.localeCompare(b));\n if (names.length === 0 && locked.length === 0) {\n console.error(\n tr(\n 'No device publishes Swipt on the local network; turn on Swipt › Developer › Local Network, or connect one with \"swipt device add URL\".',\n ),\n );\n return;\n }\n const late = AbortSignal.any([signal, AbortSignal.timeout(browseLimit)]);\n const probed = await Promise.all(\n names.map(async (name) => ({\n name,\n ...(await (probes.get(stored[name]) ?? probe(stored[name], late))),\n })),\n );\n console.log(\n columns(\n [\n ...probed.map(({ name, cells }) => [\n name,\n parseURL(stored[name]).url,\n ...cells,\n ]),\n ...locked.map((it) => [it.name, it.url, tr(\"requires a token\")]),\n ].sort((a, b) => a[0].localeCompare(b[0])),\n ),\n );\n for (const { name, failure } of probed) {\n if (failure !== undefined) {\n console.error(`${name}: ${failure}`);\n }\n }\n for (const it of locked) {\n console.error(requiresToken(it));\n }\n}\n\nexport async function add(context) {\n const device = parseURL(context.args[0]);\n context.target.url = device.url;\n const info = await open(device).system.getInfo(\n {},\n { signal: context.signal },\n );\n const name = label(info.deviceName) || new URL(device.url).hostname;\n const stored = load();\n const previous = storedName(stored, name);\n if (previous !== undefined) {\n delete stored[previous];\n }\n stored[name] = context.args[0];\n save(stored);\n console.log(tr(\"added {device}\", { device: name }));\n}\n\nexport function remove({ args }) {\n const stored = load();\n const name = storedName(stored, label(args[0]));\n if (name === undefined) {\n throw new Error(tr(\"There is no device {device}.\", { device: args[0] }));\n }\n delete stored[name];\n save(stored);\n console.log(tr(\"removed {name}\", { name }, \"device\"));\n}\n"],"mappings":";;;;;;;;;;;AAgBA,MAAM,cAAc;AACpB,MAAM,gBAAgB;AACtB,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,YAAY;AAElB,MAAM,YAAY,KAAK,KAAK,iBAAiB,cAAc;AAE3D,SAAS,OAAO;CACd,IAAI;CACJ,IAAI;EACF,OAAO,GAAG,aAAa,WAAW,MAAM;CAC1C,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAC5C,OAAO,CAAC;EAEV,MAAM;CACR;CACA,OAAO,KAAK,MAAM,IAAI;AACxB;AAEA,SAAS,KAAK,SAAS;CACrB,GAAG,UAAU,KAAK,QAAQ,SAAS,GAAG;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;CACtE,GAAG,cAAc,WAAW,GAAG,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE,KAAK,EACnE,MAAM,IACR,CAAC;AACH;AAEA,SAAgB,MAAM,MAAM;CAC1B,MAAM,OAAO,CAAC,GAAG,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC,CAC3C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,SAAS,KAAK;CACpB,MAAM,WAAW,WAAW,QAAQ,IAAI;CACxC,IAAI,aAAa,KAAA,GACf,OAAO,OAAO;CAEhB,OAAO,QAAQ,QAAQ,KAAK;CAC5B,KAAK,MAAM;CACX,QAAQ,IAAI,GAAG,kBAAkB,EAAE,QAAQ,KAAK,CAAC,CAAC;AACpD;AAEA,SAAgB,OAAO,EAAE,QAAQ;CAC/B,MAAM,SAAS,KAAK;CACpB,MAAM,OAAO,WAAW,QAAQ,MAAM,KAAK,EAAE,CAAC;CAC9C,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MAAM,GAAG,gCAAgC,EAAE,QAAQ,KAAK,GAAG,CAAC,CAAC;CAEzE,OAAO,OAAO;CACd,KAAK,MAAM;CACX,QAAQ,IAAI,GAAG,kBAAkB,EAAE,KAAK,GAAG,QAAQ,CAAC;AACtD"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
// src/directories.ts
|
|
4
|
+
const home = os.homedir();
|
|
5
|
+
const configDirectory = path.join(process.platform === "win32" ? process.env.APPDATA || path.join(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "swipt");
|
|
6
|
+
const cacheDirectory = path.join(process.platform === "win32" ? process.env.LOCALAPPDATA || path.join(home, "AppData", "Local") : process.env.XDG_CACHE_HOME || path.join(home, ".cache"), "swipt");
|
|
7
|
+
export { cacheDirectory, configDirectory };
|
|
8
|
+
|
|
9
|
+
//# sourceMappingURL=directories.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"directories.js","names":[],"sources":["../src/directories.ts"],"sourcesContent":["import os from \"node:os\";\nimport path from \"node:path\";\n\nconst home = os.homedir();\n\nexport const configDirectory = path.join(\n process.platform === \"win32\"\n ? process.env.APPDATA || path.join(home, \"AppData\", \"Roaming\")\n : process.env.XDG_CONFIG_HOME || path.join(home, \".config\"),\n \"swipt\",\n);\n\nexport const cacheDirectory = path.join(\n process.platform === \"win32\"\n ? process.env.LOCALAPPDATA || path.join(home, \"AppData\", \"Local\")\n : process.env.XDG_CACHE_HOME || path.join(home, \".cache\"),\n \"swipt\",\n);\n"],"mappings":";;;AAGA,MAAM,OAAO,GAAG,QAAQ;AAExB,MAAa,kBAAkB,KAAK,KAClC,QAAQ,aAAa,UACjB,QAAQ,IAAI,WAAW,KAAK,KAAK,MAAM,WAAW,SAAS,IAC3D,QAAQ,IAAI,mBAAmB,KAAK,KAAK,MAAM,SAAS,GAC5D,OACF;AAEA,MAAa,iBAAiB,KAAK,KACjC,QAAQ,aAAa,UACjB,QAAQ,IAAI,gBAAgB,KAAK,KAAK,MAAM,WAAW,OAAO,IAC9D,QAAQ,IAAI,kBAAkB,KAAK,KAAK,MAAM,QAAQ,GAC1D,OACF"}
|
package/dist/driver.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export declare const failures: {
|
|
2
|
+
deviceNotListed: string;
|
|
3
|
+
locked: string;
|
|
4
|
+
untrusted: string;
|
|
5
|
+
};
|
|
6
|
+
export declare const randomToken: () => string;
|
|
7
|
+
export declare function serve(udid: any, { passcode, token, localNetwork, signal }: {
|
|
8
|
+
localNetwork?: boolean;
|
|
9
|
+
passcode?: any;
|
|
10
|
+
signal: any;
|
|
11
|
+
token?: string;
|
|
12
|
+
}): {
|
|
13
|
+
serving: Promise<any>;
|
|
14
|
+
stderr: import("stream").Readable;
|
|
15
|
+
finished: () => Promise<any>;
|
|
16
|
+
stop(): Promise<void>;
|
|
17
|
+
};
|
|
18
|
+
interface DeviceQuery {
|
|
19
|
+
required?: boolean;
|
|
20
|
+
virtual?: boolean;
|
|
21
|
+
filter?: (devices: any[]) => Promise<any[]> | any[];
|
|
22
|
+
}
|
|
23
|
+
export declare function trustedDevice(context: any, query?: DeviceQuery): Promise<any>;
|
|
24
|
+
export declare const apps: (device: any) => Promise<any>;
|
|
25
|
+
export declare const appRunning: (device: any, id: any) => Promise<any>;
|
|
26
|
+
export declare const installApp: (device: any, app: any, id: any) => Promise<any>;
|
|
27
|
+
export declare const uninstallApp: (device: any, id: any) => Promise<any>;
|
|
28
|
+
export declare const launchApp: (device: any, id: any, args?: any[]) => Promise<any>;
|
|
29
|
+
export declare const openSettings: (device: any, url: any) => Promise<any>;
|
|
30
|
+
export declare const terminateApp: (device: any, id: any) => Promise<any>;
|
|
31
|
+
export declare const configureVirtual: (device: any, id: any, name: any) => Promise<any>;
|
|
32
|
+
export declare const pairApp: (device: any, id: any, file: any) => Promise<any>;
|
|
33
|
+
export declare const containerHasFile: (device: any, id: any, file: any) => Promise<any>;
|
|
34
|
+
export declare const containerSQL: (device: any, id: any, file: any, statements: any, { query }?: {
|
|
35
|
+
query?: boolean;
|
|
36
|
+
}) => Promise<any>;
|
|
37
|
+
export declare const provisioningProfiles: (device: any) => Promise<any>;
|
|
38
|
+
export declare const mountDiskImage: (device: any) => Promise<any>;
|
|
39
|
+
export {};
|
package/dist/driver.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { label, sameName } from "./connection.js";
|
|
2
|
+
import { tr } from "./i18n.js";
|
|
3
|
+
import { choose, interactive, step } from "./output.js";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import crypto from "node:crypto";
|
|
9
|
+
import readline from "node:readline";
|
|
10
|
+
// src/driver.ts
|
|
11
|
+
const require = createRequire(import.meta.url);
|
|
12
|
+
const target = `${process.platform}-${process.arch}`;
|
|
13
|
+
const executable = process.platform === "win32" ? "swipt-driver.exe" : "swipt-driver";
|
|
14
|
+
const checkout = path.resolve(import.meta.dirname, "../..");
|
|
15
|
+
const fromSource = fs.existsSync(path.join(checkout, "go.mod"));
|
|
16
|
+
const failures = {
|
|
17
|
+
deviceNotListed: "device_not_listed",
|
|
18
|
+
locked: "locked",
|
|
19
|
+
untrusted: "untrusted"
|
|
20
|
+
};
|
|
21
|
+
function driverPath() {
|
|
22
|
+
if (fromSource) return path.join(checkout, "build/driver", target, executable);
|
|
23
|
+
try {
|
|
24
|
+
return path.join(path.dirname(require.resolve(`@swipt/driver-${target}/package.json`)), executable);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (error.code !== "MODULE_NOT_FOUND") throw error;
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const diskImage = () => path.dirname(require.resolve("@swipt/developer-disk-image/package.json"));
|
|
31
|
+
const usbmuxdHint = process.platform === "linux" ? tr("usbmuxd isn't running; install usbmuxd and start it") : process.platform === "win32" ? tr("Apple Mobile Device Service isn't running; install Apple Devices from the Microsoft Store") : void 0;
|
|
32
|
+
function driverError({ code, message }) {
|
|
33
|
+
let text = message;
|
|
34
|
+
if (code === "usbmuxd_unavailable" && usbmuxdHint !== void 0) text = `${usbmuxdHint} (${message})`;
|
|
35
|
+
else if (code === "driver_running") text = tr("The driver is already running on this computer; stop it first.");
|
|
36
|
+
return Object.assign(new Error(text), { code });
|
|
37
|
+
}
|
|
38
|
+
function start(args, { input = void 0, signal = void 0 } = {}) {
|
|
39
|
+
const file = driverPath();
|
|
40
|
+
if (file === void 0 || !fs.existsSync(file)) throw new Error(fromSource ? `${file} is missing; build it with "make driver".` : tr("The driver is missing; install it with \"npm install -g @swipt/cli --include=optional\"."));
|
|
41
|
+
const child = spawn(file, args, {
|
|
42
|
+
stdio: [
|
|
43
|
+
"pipe",
|
|
44
|
+
"pipe",
|
|
45
|
+
"pipe"
|
|
46
|
+
],
|
|
47
|
+
windowsHide: true
|
|
48
|
+
});
|
|
49
|
+
let stopped = false;
|
|
50
|
+
const stop = () => {
|
|
51
|
+
stopped = true;
|
|
52
|
+
child.stdin.end();
|
|
53
|
+
};
|
|
54
|
+
child.stdin.on("error", () => {});
|
|
55
|
+
if (input !== void 0) child.stdin.write(`${JSON.stringify(input)}\n`);
|
|
56
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
57
|
+
let logs = "";
|
|
58
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
59
|
+
logs = (logs + chunk).slice(-65536);
|
|
60
|
+
});
|
|
61
|
+
const lines = [];
|
|
62
|
+
let firstLine;
|
|
63
|
+
const first = new Promise((resolve) => {
|
|
64
|
+
firstLine = resolve;
|
|
65
|
+
});
|
|
66
|
+
readline.createInterface({ input: child.stdout }).on("line", (line) => {
|
|
67
|
+
let parsed;
|
|
68
|
+
try {
|
|
69
|
+
parsed = JSON.parse(line);
|
|
70
|
+
} catch {
|
|
71
|
+
parsed = { error: { message: line } };
|
|
72
|
+
}
|
|
73
|
+
lines.push(parsed);
|
|
74
|
+
firstLine(parsed);
|
|
75
|
+
});
|
|
76
|
+
const exited = new Promise((resolve, reject) => {
|
|
77
|
+
child.once("error", reject);
|
|
78
|
+
child.once("close", (code, signalName) => {
|
|
79
|
+
signal?.removeEventListener("abort", stop);
|
|
80
|
+
child.stdin.end();
|
|
81
|
+
firstLine(void 0);
|
|
82
|
+
const last = lines.at(-1);
|
|
83
|
+
if (last?.error !== void 0) reject(driverError(last.error));
|
|
84
|
+
else if (code === 0 || stopped) resolve(last?.result);
|
|
85
|
+
else reject(/* @__PURE__ */ new Error(`swipt-driver exited with ${code ?? signalName}${logs.trim() === "" ? "" : `:\n${logs.trim()}`}`));
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
exited.catch(() => {});
|
|
89
|
+
return {
|
|
90
|
+
first,
|
|
91
|
+
exited,
|
|
92
|
+
stop,
|
|
93
|
+
stderr: child.stderr
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const driver = async (args, options = {}) => start(args, options).exited;
|
|
97
|
+
const onDevice = (device, command, args = [], options = {}) => driver([
|
|
98
|
+
"device",
|
|
99
|
+
command,
|
|
100
|
+
"-d",
|
|
101
|
+
device.udid,
|
|
102
|
+
...args
|
|
103
|
+
], options);
|
|
104
|
+
const randomToken = () => crypto.randomBytes(16).toString("hex");
|
|
105
|
+
function serve(udid, { passcode = void 0, token = "", localNetwork = false, signal }) {
|
|
106
|
+
const running = start([
|
|
107
|
+
"-d",
|
|
108
|
+
udid,
|
|
109
|
+
"--disk-image",
|
|
110
|
+
diskImage(),
|
|
111
|
+
"--secrets-stdin",
|
|
112
|
+
...passcode ? ["--passcode-type", passcode.type] : [],
|
|
113
|
+
...localNetwork ? ["--local-network"] : []
|
|
114
|
+
], {
|
|
115
|
+
input: {
|
|
116
|
+
passcode: passcode?.passcode,
|
|
117
|
+
token
|
|
118
|
+
},
|
|
119
|
+
signal
|
|
120
|
+
});
|
|
121
|
+
return {
|
|
122
|
+
serving: running.first.then(async (line) => {
|
|
123
|
+
if (line?.result === void 0) {
|
|
124
|
+
await running.exited;
|
|
125
|
+
signal.throwIfAborted();
|
|
126
|
+
throw new Error("swipt-driver stopped before serving");
|
|
127
|
+
}
|
|
128
|
+
const local = new URL(line.result.api);
|
|
129
|
+
local.hostname = "127.0.0.1";
|
|
130
|
+
return {
|
|
131
|
+
...line.result,
|
|
132
|
+
local: {
|
|
133
|
+
url: local.origin,
|
|
134
|
+
token
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}),
|
|
138
|
+
stderr: running.stderr,
|
|
139
|
+
finished: () => running.exited,
|
|
140
|
+
async stop() {
|
|
141
|
+
running.stop();
|
|
142
|
+
await running.exited.catch(() => {});
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
const deviceLine = (device) => ` ${device.name} ${device.udid}`;
|
|
147
|
+
async function findDevice(context, { required = true, virtual = true, filter }) {
|
|
148
|
+
const given = context.options.device;
|
|
149
|
+
const devices = (await step(tr("looking for devices"), () => driver(["device", "list"]), { transient: true })).filter((device) => virtual || !device.virtual).map((device) => ({
|
|
150
|
+
...device,
|
|
151
|
+
name: device.name || device.udid
|
|
152
|
+
}));
|
|
153
|
+
const named = (device) => sameName(device.udid, given) || sameName(label(device.name), label(given));
|
|
154
|
+
const matches = given ? devices.filter(named) : devices;
|
|
155
|
+
if ((given || !required) && matches.length === 1) return matches[0];
|
|
156
|
+
if (devices.length === 0) throw new Error(tr("No iPhone or iPad is connected to this computer or found on the local network; connect one with a USB cable and unlock it."));
|
|
157
|
+
const reason = !given ? tr("Choose a device with -d NAME|UDID") : matches.length === 0 ? tr("No iPhone or iPad is named {name}", { name: given }) : tr("More than one iPhone or iPad is named {name}; choose one by UDID", { name: given });
|
|
158
|
+
const failed = /* @__PURE__ */ new Error(`${tr("{reason}; connected iPhone and iPad devices:", { reason })}\n${devices.map(deviceLine).join("\n")}`);
|
|
159
|
+
if (matches.length === 0) throw failed;
|
|
160
|
+
const choices = filter !== void 0 && interactive(context) ? await filter(matches) : matches;
|
|
161
|
+
return choose(context, tr("Choose a device"), choices.map((device) => ({
|
|
162
|
+
name: `${device.name} ${device.udid}`,
|
|
163
|
+
short: device.name,
|
|
164
|
+
value: device
|
|
165
|
+
})), failed);
|
|
166
|
+
}
|
|
167
|
+
async function trustedDevice(context, query = {}) {
|
|
168
|
+
const device = await findDevice(context, query);
|
|
169
|
+
if (!device.paired) await step(device.virtual ? tr("pairing with {device}", { device: device.name }) : tr("tap Trust on {device} and enter its passcode to trust this computer", { device: device.name }), () => onDevice(device, "trust"), { transient: device.virtual });
|
|
170
|
+
return device;
|
|
171
|
+
}
|
|
172
|
+
const apps = (device) => onDevice(device, "apps");
|
|
173
|
+
const appRunning = (device, id) => onDevice(device, "running", [id]);
|
|
174
|
+
const installApp = (device, app, id) => onDevice(device, "install", [app, id]);
|
|
175
|
+
const uninstallApp = (device, id) => onDevice(device, "uninstall", [id]);
|
|
176
|
+
const launchApp = (device, id, args = []) => onDevice(device, "launch", [
|
|
177
|
+
id,
|
|
178
|
+
"--",
|
|
179
|
+
...args
|
|
180
|
+
]);
|
|
181
|
+
const openSettings = (device, url) => onDevice(device, "launch", [
|
|
182
|
+
"--payload-url",
|
|
183
|
+
url,
|
|
184
|
+
"com.apple.Preferences"
|
|
185
|
+
]);
|
|
186
|
+
const terminateApp = (device, id) => onDevice(device, "terminate", [id]);
|
|
187
|
+
const configureVirtual = (device, id, name) => onDevice(device, "configure", [id, name]);
|
|
188
|
+
const pairApp = (device, id, file) => onDevice(device, "pair", [id, file]);
|
|
189
|
+
const containerHasFile = (device, id, file) => onDevice(device, "has", [id, file]);
|
|
190
|
+
const containerSQL = (device, id, file, statements, { query = false } = {}) => onDevice(device, "sqlite", [
|
|
191
|
+
id,
|
|
192
|
+
file,
|
|
193
|
+
...query ? ["--query"] : []
|
|
194
|
+
], { input: statements });
|
|
195
|
+
const provisioningProfiles = (device) => onDevice(device, "profiles");
|
|
196
|
+
const mountDiskImage = (device) => onDevice(device, "mount", ["--disk-image", diskImage()]);
|
|
197
|
+
export { appRunning, apps, configureVirtual, containerHasFile, containerSQL, failures, installApp, launchApp, mountDiskImage, openSettings, pairApp, provisioningProfiles, randomToken, serve, terminateApp, trustedDevice, uninstallApp };
|
|
198
|
+
|
|
199
|
+
//# sourceMappingURL=driver.js.map
|