@cldmv/droidsock 1.1.1 → 1.2.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.
- package/README.md +7 -7
- package/dist/api/discover.mjs +17 -0
- package/dist/api/files.mjs +1 -1
- package/dist/api/utils.mjs +1 -1
- package/package.json +1 -1
- package/types/dist/api/discover.d.mts +3 -0
- package/types/dist/api/discover.d.mts.map +1 -0
- package/types/dist/api/files.d.mts.map +1 -1
- package/types/dist/api/utils.d.mts +1 -0
- package/types/dist/api/utils.d.mts.map +1 -1
package/README.md
CHANGED
|
@@ -21,7 +21,13 @@ A complete, from-scratch implementation of the Android Debug Bridge (ADB) protoc
|
|
|
21
21
|
|
|
22
22
|
## ✨ What's New
|
|
23
23
|
|
|
24
|
-
### Latest: v1.
|
|
24
|
+
### Latest: v1.2.0 (September 2026)
|
|
25
|
+
|
|
26
|
+
- **Device discovery** - `discover.subnet()` sweeps a CIDR range for a reachable ADB TCP port; `discover.mdns()` is a hand-written mDNS client (no dependency) for wireless-debugging-advertised devices. Both **experimental** - see [#1](https://github.com/CLDMV/droidsock/issues/1).
|
|
27
|
+
- **Shell-injection fix** - every `files.*` shell-based method now single-quote-escapes remote paths before interpolation; `mkdir`/`chmod`'s mode and `find`'s `maxDepth`/`type` are validated too.
|
|
28
|
+
- [View full v1.2.0 Changelog](./docs/changelog/v1/v1.2.0.md)
|
|
29
|
+
|
|
30
|
+
### Previous: v1.1.0 (September 2026)
|
|
25
31
|
|
|
26
32
|
- **`list` / `stat` fixed** - v1.0.0 shipped both throwing due to a dangling reference to a module that never existed in the repo.
|
|
27
33
|
- **Binary-safe `list()`** - prefers the ADB SYNC `LIST` command, falls back to shell `ls -la` parsing only when SYNC isn't usable.
|
|
@@ -31,12 +37,6 @@ A complete, from-scratch implementation of the Android Debug Bridge (ADB) protoc
|
|
|
31
37
|
- **`device.install()`** (experimental) - local APK install via the classic push-then-install flow.
|
|
32
38
|
- [View full v1.1.0 Changelog](./docs/changelog/v1/v1.1.0.md)
|
|
33
39
|
|
|
34
|
-
### Previous: v1.0.0 (September 2026)
|
|
35
|
-
|
|
36
|
-
- **First stable release** - a real Vitest test suite with measured coverage, the full CLDMV v4 CI/release pipeline, a real `dist/` build, and an API surface that's been reviewed rather than just grown.
|
|
37
|
-
- **Breaking**: the default export is now itself the callable quick path (`await droidsock()`); the old top-level `connect()` / `listDevices()` exports are gone.
|
|
38
|
-
- [View full v1.0.0 Changelog](./docs/changelog/v1/v1.0.0.md)
|
|
39
|
-
|
|
40
40
|
📚 **For complete version history and detailed release notes, see [docs/changelog/](./docs/changelog/) folder.**
|
|
41
41
|
|
|
42
42
|
---
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2026 CLDMV/Shinrai
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import{self}from"@cldmv/slothlet/runtime";import net from"node:net";import dgram from"node:dgram";import{isValidIP,isValidPort}from"./utils.mjs";const DNS_TYPE_A=1;const DNS_TYPE_PTR=12;const DNS_TYPE_TXT=16;const DNS_TYPE_SRV=33;const DNS_CLASS_IN=1;function ipToInt(ip){const parts=ip.split(".").map(Number);return(parts[0]<<24|parts[1]<<16|parts[2]<<8|parts[3])>>>0}function intToIp(int){return[24,16,8,0].map(shift=>int>>>shift&255).join(".")}function parseCidr(cidr){const parts=String(cidr).split("/");if(parts.length!==2||!isValidIP(parts[0])||!/^\d+$/.test(parts[1])){throw new Error(`Invalid CIDR: ${cidr}`)}const[ip,prefixStr]=parts;const prefix=Number(prefixStr);if(prefix>32){throw new Error(`Invalid CIDR prefix (must be 0-32): ${cidr}`)}const base=ipToInt(ip);const hostBits=32-prefix;if(hostBits===0){return{firstHostInt:base,lastHostInt:base,sweepCount:1}}if(hostBits===32){return{firstHostInt:1,lastHostInt:4294967294,sweepCount:4294967294}}const mask=~0<<hostBits>>>0;const network=(base&mask)>>>0;const broadcast=(network|~mask>>>0)>>>0;if(hostBits===1){return{firstHostInt:network,lastHostInt:broadcast,sweepCount:2}}return{firstHostInt:network+1,lastHostInt:broadcast-1,sweepCount:broadcast-network-1}}function attemptConnect(host,port,timeoutMs){return new Promise(resolve=>{const socket=new net.Socket;let settled=false;const finish=reachable=>{if(settled)return;settled=true;socket.removeAllListeners();socket.destroy();resolve(reachable)};socket.setTimeout(timeoutMs);socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false));socket.once("timeout",()=>finish(false));socket.connect(port,host)})}async function sweepPool(hosts,port,{timeoutMs,concurrency}){const reachable=[];let nextIndex=0;async function worker(){for(;;){const i=nextIndex++;if(i>=hosts.length)return;const host=hosts[i];if(await attemptConnect(host,port,timeoutMs)){reachable.push({host,port})}}}const workers=Array.from({length:Math.min(concurrency,hosts.length)},()=>worker());await Promise.all(workers);return reachable.sort((a,b)=>ipToInt(a.host)-ipToInt(b.host))}async function subnet(cidr,port=5555,options={}){const{timeoutMs=500,concurrency=32,maxHosts=1024}=options;if(!isValidPort(port)){throw new Error(`Invalid port: ${port}`)}if(!Number.isInteger(timeoutMs)||timeoutMs<=0){throw new Error(`Invalid timeoutMs: ${timeoutMs} (must be a positive integer)`)}if(!Number.isInteger(concurrency)||concurrency<=0){throw new Error(`Invalid concurrency: ${concurrency} (must be a positive integer)`)}if(!Number.isInteger(maxHosts)||maxHosts<=0){throw new Error(`Invalid maxHosts: ${maxHosts} (must be a positive integer)`)}const range=parseCidr(cidr);if(range.sweepCount>maxHosts){throw new Error(`CIDR ${cidr} has ${range.sweepCount} sweepable host(s), exceeding maxHosts (${maxHosts}). Use a narrower CIDR or raise maxHosts.`)}const hosts=[];for(let ip=range.firstHostInt;ip<=range.lastHostInt;ip++){hosts.push(intToIp(ip))}self.log.debug(`discover.subnet: sweeping ${hosts.length} host(s) in ${cidr} on port ${port}`);return await sweepPool(hosts,port,{timeoutMs,concurrency})}function encodeDnsName(name){const labels=name.replace(/\.$/,"").split(".").filter(Boolean);const parts=labels.map(label=>{const labelBuf=Buffer.from(label,"utf8");if(labelBuf.length>63){throw new Error(`DNS label too long (max 63 bytes): "${label}"`)}return Buffer.concat([Buffer.from([labelBuf.length]),labelBuf])});const encoded=Buffer.concat([...parts,Buffer.from([0])]);if(encoded.length>255){throw new Error(`DNS name too long (max 255 bytes): "${name}"`)}return encoded}function decodeDnsName(buffer,offset){const labels=[];let pos=offset;let next=-1;let guard=0;for(;;){if(guard++>128)throw new Error("DNS name decoding exceeded compression-pointer guard");const len=buffer.readUInt8(pos);if(len===0){pos+=1;if(next===-1)next=pos;break}if((len&192)===192){const pointer=(len&63)<<8|buffer.readUInt8(pos+1);if(next===-1)next=pos+2;pos=pointer;continue}labels.push(buffer.toString("utf8",pos+1,pos+1+len));pos+=1+len}return{name:labels.join("."),next}}function readDnsRecord(buffer,offset){const{name,next:afterName}=decodeDnsName(buffer,offset);let pos=afterName;const type=buffer.readUInt16BE(pos);pos+=2;pos+=2;const ttl=buffer.readUInt32BE(pos);pos+=4;const rdlength=buffer.readUInt16BE(pos);pos+=2;const rdataStart=pos;const rdataEnd=pos+rdlength;let data;switch(type){case DNS_TYPE_PTR:{const ptr=decodeDnsName(buffer,rdataStart);data=ptr.next<=rdataEnd?{target:ptr.name}:null;break}case DNS_TYPE_SRV:{if(rdlength<6){data=null;break}const srv=decodeDnsName(buffer,rdataStart+6);data=srv.next<=rdataEnd?{priority:buffer.readUInt16BE(rdataStart),weight:buffer.readUInt16BE(rdataStart+2),port:buffer.readUInt16BE(rdataStart+4),target:srv.name}:null;break}case DNS_TYPE_TXT:{const txt=Object.create(null);let p=rdataStart;while(p<rdataEnd){const len=buffer.readUInt8(p);p+=1;if(len===0)continue;if(p+len>rdataEnd)break;const entry=buffer.toString("utf8",p,p+len);p+=len;const eq=entry.indexOf("=");if(eq===-1)txt[entry]=true;else txt[entry.slice(0,eq)]=entry.slice(eq+1)}data=txt;break}case DNS_TYPE_A:data=Array.from(buffer.subarray(rdataStart,rdataEnd)).join(".");break;default:data=buffer.subarray(rdataStart,rdataEnd)}return{name,type,ttl,data,next:rdataEnd}}function parseDnsMessage(buffer){const qdcount=buffer.readUInt16BE(4);const ancount=buffer.readUInt16BE(6);const nscount=buffer.readUInt16BE(8);const arcount=buffer.readUInt16BE(10);let offset=12;for(let i=0;i<qdcount;i++){const{next}=decodeDnsName(buffer,offset);offset=next+4}const records=[];for(let i=0;i<ancount+nscount+arcount;i++){const record=readDnsRecord(buffer,offset);records.push(record);offset=record.next}return records}function buildPtrQuery(serviceType){const header=Buffer.alloc(12);header.writeUInt16BE(1,4);const question=Buffer.alloc(4);question.writeUInt16BE(DNS_TYPE_PTR,0);question.writeUInt16BE(DNS_CLASS_IN,2);return Buffer.concat([header,encodeDnsName(serviceType),question])}function isMulticastAddress(address){const firstOctet=Number(address.split(".",1)[0]);return Number.isInteger(firstOctet)&&firstOctet>=224&&firstOctet<=239}function ingestDnsRecords(records,results,addresses){for(const record of records){if(record.type===DNS_TYPE_A&&isValidIP(record.data))addresses.set(record.name,record.data)}for(const record of records){if(record.type!==DNS_TYPE_PTR||!record.data)continue;const instanceName=record.data.target;if(!results.has(instanceName)){results.set(instanceName,{name:instanceName,txt:Object.create(null)})}}for(const record of records){if(record.type===DNS_TYPE_SRV){if(!record.data)continue;const entry=results.get(record.name);if(!entry)continue;entry.port=record.data.port;entry._target=record.data.target;entry.host=addresses.get(record.data.target)||entry.host}else if(record.type===DNS_TYPE_TXT){const entry=results.get(record.name);if(!entry)continue;Object.assign(entry.txt,record.data)}}for(const entry of results.values()){if(!entry.host&&entry._target&&addresses.has(entry._target)){entry.host=addresses.get(entry._target)}}}async function mdns(options={}){const{serviceType="_adb-tls-connect._tcp.local",address="224.0.0.251",port=5353,timeoutMs=3e3}=options;if(!isValidPort(port)){throw new Error(`Invalid port: ${port}`)}if(!Number.isInteger(timeoutMs)||timeoutMs<=0){throw new Error(`Invalid timeoutMs: ${timeoutMs} (must be a positive integer)`)}const query=buildPtrQuery(serviceType);const isMulticast=isMulticastAddress(address);const socket=dgram.createSocket({type:"udp4",reuseAddr:true});const results=new Map;const addresses=new Map;let settled=false;return new Promise((resolve,reject)=>{const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);socket.removeAllListeners();socket.close();fn(value)};socket.on("error",error=>finish(reject,error));socket.on("message",message=>{try{ingestDnsRecords(parseDnsMessage(message),results,addresses)}catch(error){self.log.debug(`discover.mdns: ignoring unparseable response - ${error.message}`)}});const timer=setTimeout(()=>{finish(resolve,Array.from(results.values()).filter(entry=>entry.host&&entry.port).map(entry=>({name:entry.name,host:entry.host,port:entry.port,txt:entry.txt})))},timeoutMs);socket.bind(isMulticast?port:0,()=>{if(isMulticast){try{socket.addMembership(address)}catch(error){self.log.debug(`discover.mdns: couldn't join multicast group ${address} - ${error.message}`)}}try{socket.setMulticastTTL(255)}catch(error){self.log.debug(`discover.mdns: couldn't set multicast TTL - ${error.message}`)}self.log.debug(`discover.mdns: querying ${serviceType} via ${address}:${port}`);socket.send(query,port,address,error=>{if(error)finish(reject,error)})})})}export{mdns,subnet};
|
package/dist/api/files.mjs
CHANGED
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{self}from"@cldmv/slothlet/runtime";import{parseListing}from"./utils.mjs";import{readFile,writeFile}from"node:fs/promises";const SYNC_ID_SEND="SEND";const SYNC_ID_RECV="RECV";const SYNC_ID_LIST="LIST";const SYNC_ID_DENT="DENT";const SYNC_ID_DATA="DATA";const SYNC_ID_DONE="DONE";const SYNC_ID_OKAY="OKAY";const SYNC_ID_FAIL="FAIL";const SYNC_ID_QUIT="QUIT";const SYNC_DATA_MAX=64*1024;const SYNC_DENT_HEADER_SIZE=20;const S_IFMT=61440;const S_IFDIR=16384;const S_IFREG=32768;const S_IFLNK=40960;function buildSyncFrame(id,valueOrPayload){const payload=Buffer.isBuffer(valueOrPayload)?valueOrPayload:Buffer.alloc(0);const value=Buffer.isBuffer(valueOrPayload)?valueOrPayload.length:valueOrPayload;const header=Buffer.alloc(8);header.write(id,0,4,"ascii");header.writeUInt32LE(value>>>0,4);return Buffer.concat([header,payload])}function createSyncFrameReader(stream){let buffer=Buffer.alloc(0);const pending=[];let waiter=null;function drain(){while(buffer.length>=8){const id=buffer.toString("ascii",0,4);const value=buffer.readUInt32LE(4);if(buffer.length<8+value)return;const payload=Buffer.from(buffer.subarray(8,8+value));buffer=buffer.subarray(8+value);pending.push({id,value,payload})}if(pending.length>0&&waiter){const resolve=waiter;waiter=null;resolve()}}stream.on("data",chunk=>{buffer=Buffer.concat([buffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);drain()});return{async next(){while(pending.length===0){await new Promise(resolve=>{waiter=resolve})}return pending.shift()}}}function createListFrameReader(stream){let buffer=Buffer.alloc(0);const pending=[];let waiter=null;let endError=null;function drain(){for(;;){if(buffer.length<4)break;const id=buffer.toString("ascii",0,4);if(id===SYNC_ID_DENT){if(buffer.length<SYNC_DENT_HEADER_SIZE)break;const mode=buffer.readUInt32LE(4);const size=buffer.readUInt32LE(8);const mtime=buffer.readUInt32LE(12);const namelen=buffer.readUInt32LE(16);if(buffer.length<SYNC_DENT_HEADER_SIZE+namelen)break;const name=buffer.toString("utf8",SYNC_DENT_HEADER_SIZE,SYNC_DENT_HEADER_SIZE+namelen);buffer=buffer.subarray(SYNC_DENT_HEADER_SIZE+namelen);pending.push({id,mode,size,mtime,name});continue}if(buffer.length<8)break;const value=buffer.readUInt32LE(4);if(buffer.length<8+value)break;const payload=Buffer.from(buffer.subarray(8,8+value));buffer=buffer.subarray(8+value);pending.push({id,value,payload})}if(pending.length>0&&waiter){const resolve=waiter.resolve;waiter=null;resolve()}}function endWith(error){if(endError)return;endError=error||new Error("Sync stream ended before a DONE/FAIL frame arrived");if(waiter){const reject=waiter.reject;waiter=null;reject(endError)}}stream.on("data",chunk=>{buffer=Buffer.concat([buffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);drain()});stream.on("close",()=>endWith());stream.on("error",error=>endWith(error));return{async next(){while(pending.length===0){if(endError)throw endError;await new Promise((resolve,reject)=>{waiter={resolve,reject}})}return pending.shift()}}}async function quitSyncStream(stream){try{await stream.write(buildSyncFrame(SYNC_ID_QUIT,Buffer.alloc(0)))}catch{}stream.close()}async function push(___socket,streamManager,localPath,remotePath,options={}){const{onProgress,mode=420}=options;const data=await readFile(localPath);const stream=await streamManager.openStream("sync:");const reader=createSyncFrameReader(stream);try{const pathAndMode=Buffer.from(`${remotePath},${mode.toString(10)}`,"utf8");await stream.write(buildSyncFrame(SYNC_ID_SEND,pathAndMode));let offset=0;while(offset<data.length){const chunk=data.subarray(offset,Math.min(offset+SYNC_DATA_MAX,data.length));await stream.write(buildSyncFrame(SYNC_ID_DATA,chunk));offset+=chunk.length;if(onProgress)onProgress({bytesTransferred:offset,totalBytes:data.length})}await stream.write(buildSyncFrame(SYNC_ID_DONE,Math.floor(Date.now()/1e3)));const frame=await reader.next();if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC push failed: ${frame.payload.toString("utf8")}`)}if(frame.id!==SYNC_ID_OKAY){throw new Error(`Unexpected SYNC frame during push: ${frame.id}`)}}finally{await quitSyncStream(stream)}}async function pull(___socket,streamManager,remotePath,localPath,options={}){const{onProgress}=options;const stream=await streamManager.openStream("sync:");const reader=createSyncFrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_RECV,Buffer.from(remotePath,"utf8")));const chunks=[];let totalBytes=0;for(;;){const frame=await reader.next();if(frame.id===SYNC_ID_DATA){chunks.push(frame.payload);totalBytes+=frame.payload.length;if(onProgress)onProgress({bytesTransferred:totalBytes})}else if(frame.id===SYNC_ID_DONE){break}else if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC pull failed: ${frame.payload.toString("utf8")}`)}else{throw new Error(`Unexpected SYNC frame during pull: ${frame.id}`)}}await writeFile(localPath,Buffer.concat(chunks))}finally{await quitSyncStream(stream)}}async function listOverStream(stream,remotePath){const reader=createListFrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_LIST,Buffer.from(remotePath,"utf8")));const entries=[];for(;;){const frame=await reader.next();if(frame.id===SYNC_ID_DENT){entries.push({name:frame.name,size:frame.size,mtime:frame.mtime,mode:frame.mode,isDirectory:(frame.mode&S_IFMT)===S_IFDIR,isFile:(frame.mode&S_IFMT)===S_IFREG,isSymlink:(frame.mode&S_IFMT)===S_IFLNK})}else if(frame.id===SYNC_ID_DONE){break}else if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC list failed: ${frame.payload.toString("utf8")}`)}else{throw new Error(`Unexpected SYNC frame during list: ${frame.id}`)}}return entries}finally{await quitSyncStream(stream)}}async function listSync(___socket,streamManager,remotePath){const stream=await streamManager.openStream("sync:");return await listOverStream(stream,remotePath)}async function listShell(socket,streamManager,remotePath){const output=await self.shell.execute(socket,streamManager,`ls -la
|
|
17
|
+
import{self}from"@cldmv/slothlet/runtime";import{parseListing,quoteShellArg}from"./utils.mjs";import{readFile,writeFile}from"node:fs/promises";function assertValidMode(mode){if(!Number.isInteger(mode)||mode<0||mode>4095){throw new Error(`Invalid mode: ${mode} (must be an integer between 0 and 0o7777)`)}return mode}const SYNC_ID_SEND="SEND";const SYNC_ID_RECV="RECV";const SYNC_ID_LIST="LIST";const SYNC_ID_DENT="DENT";const SYNC_ID_DATA="DATA";const SYNC_ID_DONE="DONE";const SYNC_ID_OKAY="OKAY";const SYNC_ID_FAIL="FAIL";const SYNC_ID_QUIT="QUIT";const SYNC_DATA_MAX=64*1024;const SYNC_DENT_HEADER_SIZE=20;const S_IFMT=61440;const S_IFDIR=16384;const S_IFREG=32768;const S_IFLNK=40960;function buildSyncFrame(id,valueOrPayload){const payload=Buffer.isBuffer(valueOrPayload)?valueOrPayload:Buffer.alloc(0);const value=Buffer.isBuffer(valueOrPayload)?valueOrPayload.length:valueOrPayload;const header=Buffer.alloc(8);header.write(id,0,4,"ascii");header.writeUInt32LE(value>>>0,4);return Buffer.concat([header,payload])}function createSyncFrameReader(stream){let buffer=Buffer.alloc(0);const pending=[];let waiter=null;function drain(){while(buffer.length>=8){const id=buffer.toString("ascii",0,4);const value=buffer.readUInt32LE(4);if(buffer.length<8+value)return;const payload=Buffer.from(buffer.subarray(8,8+value));buffer=buffer.subarray(8+value);pending.push({id,value,payload})}if(pending.length>0&&waiter){const resolve=waiter;waiter=null;resolve()}}stream.on("data",chunk=>{buffer=Buffer.concat([buffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);drain()});return{async next(){while(pending.length===0){await new Promise(resolve=>{waiter=resolve})}return pending.shift()}}}function createListFrameReader(stream){let buffer=Buffer.alloc(0);const pending=[];let waiter=null;let endError=null;function drain(){for(;;){if(buffer.length<4)break;const id=buffer.toString("ascii",0,4);if(id===SYNC_ID_DENT){if(buffer.length<SYNC_DENT_HEADER_SIZE)break;const mode=buffer.readUInt32LE(4);const size=buffer.readUInt32LE(8);const mtime=buffer.readUInt32LE(12);const namelen=buffer.readUInt32LE(16);if(buffer.length<SYNC_DENT_HEADER_SIZE+namelen)break;const name=buffer.toString("utf8",SYNC_DENT_HEADER_SIZE,SYNC_DENT_HEADER_SIZE+namelen);buffer=buffer.subarray(SYNC_DENT_HEADER_SIZE+namelen);pending.push({id,mode,size,mtime,name});continue}if(buffer.length<8)break;const value=buffer.readUInt32LE(4);if(buffer.length<8+value)break;const payload=Buffer.from(buffer.subarray(8,8+value));buffer=buffer.subarray(8+value);pending.push({id,value,payload})}if(pending.length>0&&waiter){const resolve=waiter.resolve;waiter=null;resolve()}}function endWith(error){if(endError)return;endError=error||new Error("Sync stream ended before a DONE/FAIL frame arrived");if(waiter){const reject=waiter.reject;waiter=null;reject(endError)}}stream.on("data",chunk=>{buffer=Buffer.concat([buffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);drain()});stream.on("close",()=>endWith());stream.on("error",error=>endWith(error));return{async next(){while(pending.length===0){if(endError)throw endError;await new Promise((resolve,reject)=>{waiter={resolve,reject}})}return pending.shift()}}}async function quitSyncStream(stream){try{await stream.write(buildSyncFrame(SYNC_ID_QUIT,Buffer.alloc(0)))}catch{}stream.close()}async function push(___socket,streamManager,localPath,remotePath,options={}){const{onProgress,mode=420}=options;const data=await readFile(localPath);const stream=await streamManager.openStream("sync:");const reader=createSyncFrameReader(stream);try{const pathAndMode=Buffer.from(`${remotePath},${mode.toString(10)}`,"utf8");await stream.write(buildSyncFrame(SYNC_ID_SEND,pathAndMode));let offset=0;while(offset<data.length){const chunk=data.subarray(offset,Math.min(offset+SYNC_DATA_MAX,data.length));await stream.write(buildSyncFrame(SYNC_ID_DATA,chunk));offset+=chunk.length;if(onProgress)onProgress({bytesTransferred:offset,totalBytes:data.length})}await stream.write(buildSyncFrame(SYNC_ID_DONE,Math.floor(Date.now()/1e3)));const frame=await reader.next();if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC push failed: ${frame.payload.toString("utf8")}`)}if(frame.id!==SYNC_ID_OKAY){throw new Error(`Unexpected SYNC frame during push: ${frame.id}`)}}finally{await quitSyncStream(stream)}}async function pull(___socket,streamManager,remotePath,localPath,options={}){const{onProgress}=options;const stream=await streamManager.openStream("sync:");const reader=createSyncFrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_RECV,Buffer.from(remotePath,"utf8")));const chunks=[];let totalBytes=0;for(;;){const frame=await reader.next();if(frame.id===SYNC_ID_DATA){chunks.push(frame.payload);totalBytes+=frame.payload.length;if(onProgress)onProgress({bytesTransferred:totalBytes})}else if(frame.id===SYNC_ID_DONE){break}else if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC pull failed: ${frame.payload.toString("utf8")}`)}else{throw new Error(`Unexpected SYNC frame during pull: ${frame.id}`)}}await writeFile(localPath,Buffer.concat(chunks))}finally{await quitSyncStream(stream)}}async function listOverStream(stream,remotePath){const reader=createListFrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_LIST,Buffer.from(remotePath,"utf8")));const entries=[];for(;;){const frame=await reader.next();if(frame.id===SYNC_ID_DENT){entries.push({name:frame.name,size:frame.size,mtime:frame.mtime,mode:frame.mode,isDirectory:(frame.mode&S_IFMT)===S_IFDIR,isFile:(frame.mode&S_IFMT)===S_IFREG,isSymlink:(frame.mode&S_IFMT)===S_IFLNK})}else if(frame.id===SYNC_ID_DONE){break}else if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC list failed: ${frame.payload.toString("utf8")}`)}else{throw new Error(`Unexpected SYNC frame during list: ${frame.id}`)}}return entries}finally{await quitSyncStream(stream)}}async function listSync(___socket,streamManager,remotePath){const stream=await streamManager.openStream("sync:");return await listOverStream(stream,remotePath)}async function listShell(socket,streamManager,remotePath){const output=await self.shell.execute(socket,streamManager,`ls -la ${quoteShellArg(remotePath)}`);return parseListing(output)}async function list(socket,streamManager,remotePath){let stream;try{stream=await streamManager.openStream("sync:")}catch{return await listShell(socket,streamManager,remotePath)}return await listOverStream(stream,remotePath)}async function stat(socket,streamManager,remotePath){return await self.shell.execute(socket,streamManager,`stat ${quoteShellArg(remotePath)}`)}async function mkdir(socket,streamManager,remotePath,mode=493){assertValidMode(mode);const command=`mkdir -p ${quoteShellArg(remotePath)} && chmod ${mode.toString(8)} ${quoteShellArg(remotePath)}`;return await self.shell.execute(socket,streamManager,command)}async function remove(socket,streamManager,remotePath,recursive=false){const flag=recursive?"-rf":"-f";const command=`rm ${flag} ${quoteShellArg(remotePath)}`;return await self.shell.execute(socket,streamManager,command)}async function move(socket,streamManager,sourcePath,destPath){const command=`mv ${quoteShellArg(sourcePath)} ${quoteShellArg(destPath)}`;return await self.shell.execute(socket,streamManager,command)}async function copy(socket,streamManager,sourcePath,destPath,recursive=false){const flag=recursive?"-r":"";const command=`cp ${flag} ${quoteShellArg(sourcePath)} ${quoteShellArg(destPath)}`;return await self.shell.execute(socket,streamManager,command)}async function chmod(socket,streamManager,remotePath,mode,recursive=false){assertValidMode(mode);const flag=recursive?"-R":"";const command=`chmod ${flag} ${mode.toString(8)} ${quoteShellArg(remotePath)}`;return await self.shell.execute(socket,streamManager,command)}async function diskUsage(socket,streamManager,path="/"){const command=`df -h ${quoteShellArg(path)}`;return await self.shell.execute(socket,streamManager,command)}async function find(socket,streamManager,path,pattern,options={}){let command=`find ${quoteShellArg(path)}`;if(options.maxDepth!==void 0){if(!Number.isInteger(options.maxDepth)||options.maxDepth<0){throw new Error(`Invalid maxDepth: ${options.maxDepth} (must be a non-negative integer)`)}command+=` -maxdepth ${options.maxDepth}`}if(options.type!==void 0){if(!/^[bcdpfls]$/.test(options.type)){throw new Error(`Invalid type: ${options.type} (must be one of b, c, d, p, f, l, s)`)}command+=` -type ${options.type}`}command+=` -name ${quoteShellArg(pattern)}`;return await self.shell.execute(socket,streamManager,command)}export{chmod,copy,diskUsage,find,list,listShell,listSync,mkdir,move,pull,push,remove,stat};
|
package/dist/api/utils.mjs
CHANGED
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
function parseProperties(propOutput){const props={};const lines=propOutput.split("\n");for(const line of lines){const match=line.match(/^\[([^\]]+)\]:\s*\[([^\]]*)\]$/);if(match){const[,key,value]=match;props[key]=value}}return props}function parseListing(lsOutput){const entries=[];const lines=lsOutput.split("\n").filter(line=>line.trim());const startIdx=lines[0]?.startsWith("total")?1:0;for(let i=startIdx;i<lines.length;i++){const line=lines[i];const match=line.match(/^([drwx-]+)\s+(\d+)\s+(\w+)\s+(\w+)\s+(\d+)\s+(.+?)\s+(.+)$/);if(match){const[,permissions,links,owner,group,size,dateTime,name]=match;entries.push({name,permissions,links:parseInt(links),owner,group,size:parseInt(size),dateTime,isDirectory:permissions.startsWith("d"),isFile:permissions.startsWith("-"),isSymlink:permissions.startsWith("l")})}}return entries}function parseBattery(batteryOutput){const battery={};const lines=batteryOutput.split("\n");for(const line of lines){const match=line.match(/^\s*([^:]+):\s*(.+)$/);if(match){let[,key,value]=match;key=key.trim();value=value.trim();if(/^\d+$/.test(value)){value=parseInt(value)}battery[key]=value}}return battery}function formatBytes(bytes,decimals=2){if(bytes===0)return"0 Bytes";const k=1024;const dm=decimals<0?0:decimals;const sizes=["Bytes","KB","MB","GB","TB"];const i=Math.floor(Math.log(bytes)/Math.log(k));return parseFloat((bytes/Math.pow(k,i)).toFixed(dm))+" "+sizes[i]}function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms))}async function retry(fn,options={}){const{baseDelay=1e3,maxDelay=1e4,shouldRetry=()=>true}=options;let{maxRetries=3}=options;if(maxRetries<0){console.warn(`retry: maxRetries must be >= 0, got ${maxRetries} - clamping to 0`);maxRetries=0}let lastError;for(let attempt=0;attempt<=maxRetries;attempt++){try{return await fn()}catch(error){lastError=error;if(attempt===maxRetries||!shouldRetry(error)){throw error}const delayMs=Math.min(baseDelay*Math.pow(2,attempt),maxDelay);await delay(delayMs)}}throw lastError}function isValidIP(ip){const parts=ip.split(".");if(parts.length!==4)return false;return parts.every(part=>{const num=parseInt(part,10);return num>=0&&num<=255&&part===num.toString()})}function isValidPort(port){return Number.isInteger(port)&&port>=1&&port<=65535}function parseHostPort(hostPort,defaultPort=5555){const colonIndex=hostPort.lastIndexOf(":");if(colonIndex===-1){return{host:hostPort,port:defaultPort}}const host=hostPort.substring(0,colonIndex);const portStr=hostPort.substring(colonIndex+1);const port=parseInt(portStr,10);if(!isValidPort(port)){throw new Error(`Invalid port: ${portStr}`)}return{host,port}}function escapeShell(str){return str.replace(/[\\$`"]/g,"\\$&")}function timeout(ms,message="Operation timed out"){return new Promise((_,reject)=>{setTimeout(()=>reject(new Error(message)),ms)})}function withTimeout(promise,ms,message){return Promise.race([promise,timeout(ms,message)])}export{delay,escapeShell,formatBytes,isValidIP,isValidPort,parseBattery,parseHostPort,parseListing,parseProperties,retry,timeout,withTimeout};
|
|
17
|
+
function parseProperties(propOutput){const props={};const lines=propOutput.split("\n");for(const line of lines){const match=line.match(/^\[([^\]]+)\]:\s*\[([^\]]*)\]$/);if(match){const[,key,value]=match;props[key]=value}}return props}function parseListing(lsOutput){const entries=[];const lines=lsOutput.split("\n").filter(line=>line.trim());const startIdx=lines[0]?.startsWith("total")?1:0;for(let i=startIdx;i<lines.length;i++){const line=lines[i];const match=line.match(/^([drwx-]+)\s+(\d+)\s+(\w+)\s+(\w+)\s+(\d+)\s+(.+?)\s+(.+)$/);if(match){const[,permissions,links,owner,group,size,dateTime,name]=match;entries.push({name,permissions,links:parseInt(links),owner,group,size:parseInt(size),dateTime,isDirectory:permissions.startsWith("d"),isFile:permissions.startsWith("-"),isSymlink:permissions.startsWith("l")})}}return entries}function parseBattery(batteryOutput){const battery={};const lines=batteryOutput.split("\n");for(const line of lines){const match=line.match(/^\s*([^:]+):\s*(.+)$/);if(match){let[,key,value]=match;key=key.trim();value=value.trim();if(/^\d+$/.test(value)){value=parseInt(value)}battery[key]=value}}return battery}function formatBytes(bytes,decimals=2){if(bytes===0)return"0 Bytes";const k=1024;const dm=decimals<0?0:decimals;const sizes=["Bytes","KB","MB","GB","TB"];const i=Math.floor(Math.log(bytes)/Math.log(k));return parseFloat((bytes/Math.pow(k,i)).toFixed(dm))+" "+sizes[i]}function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms))}async function retry(fn,options={}){const{baseDelay=1e3,maxDelay=1e4,shouldRetry=()=>true}=options;let{maxRetries=3}=options;if(maxRetries<0){console.warn(`retry: maxRetries must be >= 0, got ${maxRetries} - clamping to 0`);maxRetries=0}let lastError;for(let attempt=0;attempt<=maxRetries;attempt++){try{return await fn()}catch(error){lastError=error;if(attempt===maxRetries||!shouldRetry(error)){throw error}const delayMs=Math.min(baseDelay*Math.pow(2,attempt),maxDelay);await delay(delayMs)}}throw lastError}function isValidIP(ip){const parts=ip.split(".");if(parts.length!==4)return false;return parts.every(part=>{const num=parseInt(part,10);return num>=0&&num<=255&&part===num.toString()})}function isValidPort(port){return Number.isInteger(port)&&port>=1&&port<=65535}function parseHostPort(hostPort,defaultPort=5555){const colonIndex=hostPort.lastIndexOf(":");if(colonIndex===-1){return{host:hostPort,port:defaultPort}}const host=hostPort.substring(0,colonIndex);const portStr=hostPort.substring(colonIndex+1);const port=parseInt(portStr,10);if(!isValidPort(port)){throw new Error(`Invalid port: ${portStr}`)}return{host,port}}function escapeShell(str){return str.replace(/[\\$`"]/g,"\\$&")}function quoteShellArg(str){return`'${String(str).replace(/'/g,`'\\''`)}'`}function timeout(ms,message="Operation timed out"){return new Promise((_,reject)=>{setTimeout(()=>reject(new Error(message)),ms)})}function withTimeout(promise,ms,message){return Promise.race([promise,timeout(ms,message)])}export{delay,escapeShell,formatBytes,isValidIP,isValidPort,parseBattery,parseHostPort,parseListing,parseProperties,quoteShellArg,retry,timeout,withTimeout};
|
package/package.json
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discover.d.mts","sourceRoot":"","sources":["../../../dist/api/discover.mjs"],"names":[],"mappings":"AAgB04N,iDAAmlD;AAA17M,+EAAq/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"files.d.mts","sourceRoot":"","sources":["../../../dist/api/files.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"files.d.mts","sourceRoot":"","sources":["../../../dist/api/files.mjs"],"names":[],"mappings":"AAgB8yO,sHAA2Q;AAAvgB,yHAA4P;AAA2Q,wFAAmK;AAAA,2GAA4mB;AAA5yE;;;;;;;;;;;;;;;;;;;KAAgO;AAAxZ;;;;;;;;;;;KAAwL;AAAxV;;;;;;;;KAAgK;AAAuiB,qGAAmQ;AAA6N,oGAAuM;AAA12F,uHAAkyB;AAAlwD,uHAAg+B;AAAs8E,4GAA6N;AAA/mB,qFAA+I"}
|
|
@@ -21,6 +21,7 @@ export function parseListing(lsOutput: any): {
|
|
|
21
21
|
isSymlink: any;
|
|
22
22
|
}[];
|
|
23
23
|
export function parseProperties(propOutput: any): {};
|
|
24
|
+
export function quoteShellArg(str: any): string;
|
|
24
25
|
export function retry(fn: any, options?: {}): Promise<any>;
|
|
25
26
|
export function timeout(ms: any, message?: string): Promise<any>;
|
|
26
27
|
export function withTimeout(promise: any, ms: any, message: any): Promise<any>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../../dist/api/utils.mjs"],"names":[],"mappings":"AAgBq4C,6CAAuE;AAA8mC,2CAAgE;AAAjgD,mEAA4Q;AAAqkB,wCAAyL;AAAA,gDAA+E;AAAh5C,qDAAuT;AAAylC;;;EAAwW;AAAh1E;;;;;;;;;;;IAAwlB;AAAl0B,qDAA0O;
|
|
1
|
+
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../../dist/api/utils.mjs"],"names":[],"mappings":"AAgBq4C,6CAAuE;AAA8mC,2CAAgE;AAAjgD,mEAA4Q;AAAqkB,wCAAyL;AAAA,gDAA+E;AAAh5C,qDAAuT;AAAylC;;;EAAwW;AAAh1E;;;;;;;;;;;IAAwlB;AAAl0B,qDAA0O;AAAg5E,gDAA2E;AAAzvC,2DAA8f;AAA2vB,iEAAmI;AAAA,+EAA4F"}
|