webserial-core 2.0.0-dev.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import{_ as e,a as t,b as n,d as r,f as i,g as a,h as o,i as s,l as ee,m as te,n as ne,o as re,p as c,r as l,t as u,v as ie,x as ae,y as oe}from"./demo-shared-DnvFynUr.js";var se=32,ce=34,d=0,le=30,ue=3,de=7,fe=1,pe=0,me=771,he=768,f=255,ge=8,p=`none`,m=1,_e=[16,8,7,6,5],ve=[1,2],ye=[`none`,`even`,`odd`],be=[`none`,`odd`,`even`],xe=[1,1.5,2],h={usbControlInterfaceClass:2,usbTransferInterfaceClass:10,protocol:void 0};function g(e,t){let n=e.configurations[0];if(!n)return null;for(let e of n.interfaces)if(e.alternates[0]?.interfaceClass===t)return e;return null}function _(e,t){let n=e.configurations[0];if(!n)return null;for(let e of n.interfaces){let n=e.alternates[0];if(!n||n.interfaceClass!==t)continue;let r=n.endpoints.some(e=>e.direction===`in`),i=n.endpoints.some(e=>e.direction===`out`);if(r&&i)return e}return null}function v(e,t){let n=e.alternates[0];if(n){for(let e of n.endpoints)if(e.direction===t)return e}throw TypeError(`Interface ${e.interfaceNumber} does not have an ${t} endpoint.`)}function Se(e,t){return t===2?`cdc_acm`:e.vendorId===4292?`cp210x`:`none`}var Ce=class{device_;endpoint_;onError_;constructor(e,t,n){this.device_=e,this.endpoint_=t,this.onError_=n}pull(e){(async()=>{let t=this.endpoint_.packetSize;try{let n=await this.device_.transferIn(this.endpoint_.endpointNumber,t);if(n.status!==`ok`){e.error(`USB error: ${n.status}`),this.onError_();return}if(n.data?.buffer&&n.data.byteLength>0){let t=new Uint8Array(n.data.buffer,n.data.byteOffset,n.data.byteLength);t.length>0&&e.enqueue(t)}}catch(t){e.error(String(t)),this.onError_()}})()}},we=class{device_;endpoint_;onError_;constructor(e,t,n){this.device_=e,this.endpoint_=t,this.onError_=n}async write(e,t){try{let n=await this.device_.transferOut(this.endpoint_.endpointNumber,e.buffer);n.status!==`ok`&&(t.error(n.status),this.onError_())}catch(e){t.error(String(e)),this.onError_()}}},y=class{device_;protocol_;controlInterface_;transferInterface_;inEndpoint_;outEndpoint_;serialOptions_;readable_=null;writable_=null;cdcOutputSignals_={dataTerminalReady:!1,requestToSend:!1,break:!1};constructor(e,t){this.device_=e;let n={...h,...t};this.protocol_=n.protocol??Se(e,n.usbControlInterfaceClass);let r=n.usbControlInterfaceClass,i=n.usbTransferInterfaceClass;if(r===i){let t=_(e,i);if(!t)throw TypeError(`Unable to find interface with class ${i} that has both IN and OUT endpoints.`);this.controlInterface_=t,this.transferInterface_=t}else{let t=g(e,r);if(!t)throw TypeError(`Unable to find control interface with class ${r}.`);let n=_(e,i)??g(e,i);if(!n)throw TypeError(`Unable to find transfer interface with class ${i}.`);this.controlInterface_=t,this.transferInterface_=n}this.inEndpoint_=v(this.transferInterface_,`in`),this.outEndpoint_=v(this.transferInterface_,`out`)}get readable(){return!this.readable_&&this.device_.opened&&(this.readable_=new ReadableStream(new Ce(this.device_,this.inEndpoint_,()=>{this.readable_=null}),{highWaterMark:this.serialOptions_?.bufferSize??f})),this.readable_}get writable(){return!this.writable_&&this.device_.opened&&(this.writable_=new WritableStream(new we(this.device_,this.outEndpoint_,()=>{this.writable_=null}),new ByteLengthQueuingStrategy({highWaterMark:this.serialOptions_?.bufferSize??f}))),this.writable_}async open(e){this.serialOptions_=e,this.validateOptions();try{switch(await this.device_.open(),this.device_.configuration===null&&await this.device_.selectConfiguration(1),await this.device_.claimInterface(this.controlInterface_.interfaceNumber),this.controlInterface_!==this.transferInterface_&&await this.device_.claimInterface(this.transferInterface_.interfaceNumber),this.protocol_){case`cdc_acm`:await this.cdcInit();break;case`cp210x`:await this.cp210xInit();break;case`none`:break}}catch(e){throw this.device_.opened&&await this.device_.close(),Error(`Error setting up device: `+(e instanceof Error?e.message:String(e)),{cause:e})}}async close(){let e=[];if(this.readable_&&e.push(this.readable_.cancel()),this.writable_&&e.push(this.writable_.abort()),await Promise.all(e),this.readable_=null,this.writable_=null,this.device_.opened){switch(this.protocol_){case`cdc_acm`:await this.cdcSetSignals({dataTerminalReady:!1,requestToSend:!1});break;case`cp210x`:await this.cp210xDeinit();break}await this.device_.close()}}async forget(){return this.device_.forget()}getInfo(){return{usbVendorId:this.device_.vendorId,usbProductId:this.device_.productId}}async cdcInit(){await this.cdcSetLineCoding(),await this.cdcSetSignals({dataTerminalReady:!0})}async cdcSetSignals(e){if(this.cdcOutputSignals_={...this.cdcOutputSignals_,...e},e.dataTerminalReady!==void 0||e.requestToSend!==void 0){let e=(this.cdcOutputSignals_.dataTerminalReady?1:0)|(this.cdcOutputSignals_.requestToSend?2:0);await this.device_.controlTransferOut({requestType:`class`,recipient:`interface`,request:ce,value:e,index:this.controlInterface_.interfaceNumber})}}async cdcSetLineCoding(){let e=new ArrayBuffer(7),t=new DataView(e);if(t.setUint32(0,this.serialOptions_.baudRate,!0),t.setUint8(4,xe.indexOf(this.serialOptions_.stopBits??m)),t.setUint8(5,be.indexOf(this.serialOptions_.parity??p)),t.setUint8(6,this.serialOptions_.dataBits??ge),(await this.device_.controlTransferOut({requestType:`class`,recipient:`interface`,request:se,value:0,index:this.controlInterface_.interfaceNumber},e)).status!==`ok`)throw new DOMException(`Failed to set line coding.`,`NetworkError`)}async cp210xInit(){let e=this.controlInterface_.interfaceNumber;await this.device_.controlTransferOut({requestType:`vendor`,recipient:`interface`,request:d,value:fe,index:e});let t=new ArrayBuffer(4);new DataView(t).setUint32(0,this.serialOptions_.baudRate,!0),await this.device_.controlTransferOut({requestType:`vendor`,recipient:`interface`,request:le,value:0,index:e},t);let n=this.serialOptions_.dataBits??ge,r={none:0,odd:16,even:32}[this.serialOptions_.parity??p]??0,i=({1:0,2:2}[this.serialOptions_.stopBits??m]??0)<<8|r|n;await this.device_.controlTransferOut({requestType:`vendor`,recipient:`interface`,request:ue,value:i,index:e}),await this.device_.controlTransferOut({requestType:`vendor`,recipient:`interface`,request:de,value:me,index:e})}async cp210xDeinit(){let e=this.controlInterface_.interfaceNumber;await this.device_.controlTransferOut({requestType:`vendor`,recipient:`interface`,request:de,value:he,index:e}),await this.device_.controlTransferOut({requestType:`vendor`,recipient:`interface`,request:d,value:pe,index:e})}validateOptions(){if(this.serialOptions_.baudRate%1!=0)throw RangeError(`Invalid baud rate: ${this.serialOptions_.baudRate}`);if(this.serialOptions_.dataBits!==void 0&&!_e.includes(this.serialOptions_.dataBits))throw RangeError(`Invalid dataBits: ${this.serialOptions_.dataBits}`);if(this.serialOptions_.stopBits!==void 0&&!ve.includes(this.serialOptions_.stopBits))throw RangeError(`Invalid stopBits: ${this.serialOptions_.stopBits}`);if(this.serialOptions_.parity!==void 0&&!ye.includes(this.serialOptions_.parity))throw RangeError(`Invalid parity: ${this.serialOptions_.parity}`)}},Te=class{options_;constructor(e){this.options_={...h,...e}}async requestPort(e,t){let n={...this.options_,...t},r=[];if(e?.filters&&e.filters.length>0)for(let t of e.filters){let e={};t.usbVendorId!==void 0&&(e.vendorId=t.usbVendorId),t.usbProductId!==void 0&&(e.productId=t.usbProductId),n.usbControlInterfaceClass!==void 0&&n.usbControlInterfaceClass!==255?e.classCode=n.usbControlInterfaceClass:e.vendorId===void 0&&e.productId===void 0&&(e.classCode=n.usbControlInterfaceClass??2),r.push(e)}else r.push({classCode:n.usbControlInterfaceClass??2});return new y(await navigator.usb.requestDevice({filters:r}),n)}async getPorts(e){let t={...this.options_,...e},n=await navigator.usb.getDevices(),r=[];for(let e of n)try{let n=new y(e,t);r.push(n)}catch{}return r}},b=[],x=[],Ee=class extends ae{_hsCmd;_hsCmdMode;_hsExpect;_hsExpectMode;constructor(e,t,n,r,i){super(e),this._hsCmd=t,this._hsCmdMode=n,this._hsExpect=r,this._hsExpectMode=i}async handshake(){if(!this._hsCmd||(this._hsCmdMode===`hex`?await this.send(L(this._hsCmd)):await this.send(l(this._hsCmd)),!this._hsExpect))return!0;let e=this._hsExpect.trim();return new Promise(t=>{let n=r=>{if(this.off(`serial:data`,n),this._hsExpectMode===`hex`){let e=new TextEncoder().encode(String(r)),n=L(this._hsExpect);t(e.length===n.length&&e.every((e,t)=>e===n[t]))}else t(String(r).trim()===e)};this.on(`serial:data`,n)})}},S=e=>document.getElementById(e),C=S(`messages`),w=S(`btn-connect`),De=S(`btn-disconnect`),Oe=S(`btn-send`),T=S(`input-send`),ke=S(`mode-toggle`),Ae=S(`status-dot`),je=S(`status-text`),Me=S(`console-dot`),E=S(`console-text`),D=S(`sidebar`),O=S(`code-panel`),k=S(`code-view`),A=S(`code-tab`),Ne=S(`menu-btn`),Pe=S(`code-toggle-btn`),j=S(`theme-btn`),Fe=S(`clear-btn`),M=S(`copy-btn`),Ie=S(`dl-btn`),Le=S(`cfg-export-btn`),N=S(`cfg-import-input`);function P(){let e=e=>(S(e)?.value??``).trim(),t=(t,n)=>parseInt(e(t))||n,n=e=>S(e)?.value??``,r=e=>S(e)?.checked??!1,i=e(`cfg-vendor`),a=e(`cfg-product`),o=[];if(i||a){let e={};i&&(e.usbVendorId=parseInt(i,16)),a&&(e.usbProductId=parseInt(a,16)),o.push(e)}return{usbControlInterfaceClass:t(`cfg-ctrl-class`,255),usbTransferInterfaceClass:t(`cfg-xfer-class`,255),baudRate:t(`cfg-baud`,9600),dataBits:t(`cfg-databits`,8),stopBits:t(`cfg-stopbits`,1),parity:n(`cfg-parity`)||`none`,flowControl:n(`cfg-flow`)||`none`,bufferSize:t(`cfg-bufsize`,255),commandTimeout:t(`cfg-timeout`,3e3),autoReconnect:r(`cfg-autoreconnect`),autoReconnectInterval:t(`cfg-reconnect-ms`,1500),handshakeTimeout:t(`cfg-handshake`,2e3),delimiter:e(`cfg-delim`)||`\\n`,prepend:e(`cfg-prepend`),append:e(`cfg-append`),hsCmd:e(`cfg-hs-cmd`),hsCmdMode:n(`cfg-hs-cmd-mode`)||`text`,hsExpect:e(`cfg-hs-expect`),hsExpectMode:n(`cfg-hs-expect-mode`)||`text`,filters:o}}function Re(e){let t=(e,t)=>{let n=document.getElementById(e);n&&(n instanceof HTMLInputElement&&n.type===`checkbox`?n.checked=!!t:(n instanceof HTMLInputElement||n instanceof HTMLSelectElement)&&(n.value=String(t??``)))};t(`cfg-ctrl-class`,e.usbControlInterfaceClass??255),t(`cfg-xfer-class`,e.usbTransferInterfaceClass??255),t(`cfg-baud`,e.baudRate??9600),t(`cfg-databits`,e.dataBits??8),t(`cfg-stopbits`,e.stopBits??1),t(`cfg-parity`,e.parity??`none`),t(`cfg-flow`,e.flowControl??`none`),t(`cfg-bufsize`,e.bufferSize??255),t(`cfg-timeout`,e.commandTimeout??3e3),t(`cfg-handshake`,e.handshakeTimeout??2e3),t(`cfg-reconnect-ms`,e.autoReconnectInterval??1500),t(`cfg-autoreconnect`,e.autoReconnect??!1),t(`cfg-vendor`,e.filters?.[0]?.usbVendorId==null?``:e.filters[0].usbVendorId.toString(16)),t(`cfg-product`,e.filters?.[0]?.usbProductId==null?``:e.filters[0].usbProductId.toString(16)),t(`cfg-delim`,e.delimiter??`\\n`),t(`cfg-prepend`,e.prepend??``),t(`cfg-append`,e.append??``),t(`cfg-hs-cmd`,e.hsCmd??``),t(`cfg-hs-cmd-mode`,e.hsCmdMode??`text`),t(`cfg-hs-expect`,e.hsExpect??``),t(`cfg-hs-expect-mode`,e.hsExpectMode??`text`)}function F(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,``).replace(/^[^a-zA-Z_$]/,`C`);return t.charAt(0).toUpperCase()+t.slice(1)||`MyDevice`}function I(e){return Array.from(e).map(e=>e.toString(16).toUpperCase().padStart(2,`0`)).join(` `)}function L(e){let t=e.replace(/\s+/g,``);if(t.length%2!=0)throw Error(`Odd number of hex characters.`);let n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=parseInt(t.substring(e,e+2),16);return n}function R(e,t){[Ae,Me].forEach(t=>{t&&(t.className=`status-dot`,e!==`disconnected`&&t.classList.add(e))}),je&&(je.textContent=t),E&&(E.textContent=t)}var z=null;function B(){z&&clearTimeout(z),z=setTimeout(()=>{let e=P(),t=F((S(`dl-name`)?.value??`MyUsbDevice`).trim()),n=(document.querySelector(`input[name='dl-lang']:checked`)?.value??`ts`)===`ts`,r=n?`ts`:`js`;ie(k,ee(e,t,n,b,x)),A&&(A.textContent=`${t.substring(0,10).toLowerCase()}.${r}`)},180)}var ze=c();j&&(j.textContent=ze===`dark`?`☀️`:`🌙`),Ne?.addEventListener(`click`,()=>D.classList.toggle(`collapsed`)),Pe?.addEventListener(`click`,()=>O.classList.toggle(`collapsed`));var V=S(`resize-handle`);if(V){let e=0,t=0,n=n=>{let r=Math.max(180,Math.min(700,t+(e-n.clientX)));document.documentElement.style.setProperty(`--code-w`,`${r}px`)},r=()=>{V.classList.remove(`dragging`),document.removeEventListener(`pointermove`,n)};V.addEventListener(`pointerdown`,i=>{e=i.clientX,t=O.getBoundingClientRect().width,V.classList.add(`dragging`),document.addEventListener(`pointermove`,n),document.addEventListener(`pointerup`,r,{once:!0}),i.preventDefault()})}var H=S(`sidebar-resize-handle`);if(H){let e=0,t=0,n=n=>{let r=Math.max(200,Math.min(600,t+(n.clientX-e)));document.documentElement.style.setProperty(`--sidebar-w`,`${r}px`)},r=()=>{H.classList.remove(`dragging`),document.removeEventListener(`pointermove`,n)};H.addEventListener(`pointerdown`,i=>{e=i.clientX,t=D.getBoundingClientRect().width,H.classList.add(`dragging`),document.addEventListener(`pointermove`,n),document.addEventListener(`pointerup`,r,{once:!0}),i.preventDefault()})}window.innerWidth<=960&&O.classList.add(`collapsed`),window.innerWidth<=640&&D.classList.add(`collapsed`),j?.addEventListener(`click`,()=>{let e=oe();j&&(j.textContent=e===`dark`?`☀️`:`🌙`)}),Fe?.addEventListener(`click`,()=>ne(C)),M?.addEventListener(`click`,async()=>{let e=k?.textContent??``;try{await navigator.clipboard.writeText(e),M&&(M.textContent=`Copied!`,M.classList.add(`copied`),setTimeout(()=>{M.textContent=`Copy`,M.classList.remove(`copied`)},1500))}catch{}}),Ie?.addEventListener(`click`,()=>{let n=P(),r=(S(`dl-name`)?.value??`my-usb-device`).trim(),i=F(r),s=(document.querySelector(`input[name='dl-lang']:checked`)?.value??`ts`)===`ts`,ne=document.querySelector(`input[name='dl-type']:checked`)?.value??`file`,c=s?`ts`:`js`,l=ee(n,i,s,b,x);ne===`project`?re([{name:`device.${c}`,content:l},{name:`package.json`,content:o(r,s,`usb`)},{name:`index.html`,content:te(i,c,`WebUSB`)},{name:`README.md`,content:a(i,c,`WebUSB`,`Requires a Chromium browser. Common USB-to-serial chips: CP2102 (0x10c4/0xea60), CH340 (0x1a86/0x7523).`)},...s?[{name:`tsconfig.json`,content:e()}]:[]],`${r}-project`):t(`${r}.${c}`,l)}),Le?.addEventListener(`click`,()=>{let e=(S(`dl-name`)?.value??`my-usb-device`).trim(),t=F(e);s({$version:1,provider:`usb`,className:e,language:document.querySelector(`input[name='dl-lang']:checked`)?.value??`ts`,dlType:document.querySelector(`input[name='dl-type']:checked`)?.value??`file`,cfg:P(),commands:b,listeners:x},t+`-config`)}),N?.addEventListener(`change`,()=>{let e=N.files?.[0];if(!e)return;let t=new FileReader;t.onload=e=>{try{let t=JSON.parse(e.target?.result);if(t.$version!==1||t.provider!==`usb`)return;let n=S(`dl-name`);n&&(n.value=t.className),document.querySelectorAll(`input[name='dl-lang']`).forEach(e=>{e.checked=e.value===t.language}),document.querySelectorAll(`input[name='dl-type']`).forEach(e=>{e.checked=e.value===t.dlType}),Re(t.cfg),b=t.commands.map(e=>({...e,id:crypto.randomUUID()})),x=t.listeners.map(e=>({...e,id:crypto.randomUUID()})),Q(),$(),B()}catch{}N.value=``},t.readAsText(e)}),[`cfg-ctrl-class`,`cfg-xfer-class`,`cfg-baud`,`cfg-databits`,`cfg-stopbits`,`cfg-parity`,`cfg-flow`,`cfg-bufsize`,`cfg-timeout`,`cfg-handshake`,`cfg-reconnect-ms`,`cfg-autoreconnect`,`cfg-vendor`,`cfg-product`,`cfg-delim`,`cfg-prepend`,`cfg-append`,`cfg-hs-cmd`,`cfg-hs-cmd-mode`,`cfg-hs-expect`,`cfg-hs-expect-mode`,`dl-name`].forEach(e=>{let t=document.getElementById(e);t?.addEventListener(`change`,B),t?.addEventListener(`input`,B)}),document.querySelectorAll(`input[name='dl-lang']`).forEach(e=>e.addEventListener(`change`,B)),B();var U=`text`;ke?.addEventListener(`click`,()=>{U=U===`text`?`hex`:`text`,ke.textContent=U===`text`?`TXT`:`HEX`,T.placeholder=U===`text`?`Type a command, e.g. LED_ON`:`Hex bytes, e.g. FF 01 A3`});var W=null;function Be(e){Oe.disabled=!e,T.disabled=!e,De.disabled=!e,w.disabled=e}w?.addEventListener(`click`,async()=>{if(W){try{await W.disconnect()}catch{}W=null}let e=P();ae.setProvider(new Te({usbControlInterfaceClass:e.usbControlInterfaceClass,usbTransferInterfaceClass:e.usbTransferInterfaceClass}));let t=l(e.delimiter);W=new Ee({baudRate:e.baudRate,dataBits:e.dataBits,stopBits:e.stopBits,parity:e.parity,flowControl:e.flowControl,bufferSize:e.bufferSize,commandTimeout:e.commandTimeout,parser:n(t),autoReconnect:e.autoReconnect,autoReconnectInterval:e.autoReconnectInterval,handshakeTimeout:e.handshakeTimeout,filters:e.filters??[]},e.hsCmd,e.hsCmdMode,e.hsExpect,e.hsExpectMode),W.on(`serial:connecting`,()=>{R(`connecting`,`Connecting…`),w.disabled=!0,u(C,`Connecting via WebUSB…`,{kind:`system`})}),W.on(`serial:connected`,()=>{R(`connected`,`Connected`),Be(!0),u(C,`Connected via WebUSB!`,{kind:`system`})}),W.on(`serial:disconnected`,()=>{R(`disconnected`,`Disconnected`),Be(!1),u(C,`Disconnected.`,{kind:`system`}),W=null}),W.on(`serial:data`,e=>{u(C,String(e),{kind:`received`,label:`Device`})}),W.on(`serial:error`,e=>{R(`error`,`Error`),u(C,`Error: ${e.message}`,{kind:`error`}),w.disabled=!1}),W.on(`serial:need-permission`,()=>{R(`error`,`Permission denied`),u(C,`Permission denied — allow access to the USB device.`,{kind:`error`}),w.disabled=!1}),W.on(`serial:timeout`,e=>{u(C,`Timeout: ${I(e)}`,{kind:`error`})}),W.on(`serial:reconnecting`,()=>{R(`connecting`,`Reconnecting…`),u(C,`Auto-reconnecting via WebUSB…`,{kind:`system`})});try{await W.connect()}catch{}}),De?.addEventListener(`click`,async()=>{await W?.disconnect()});async function G(){let e=T.value.trim();if(!e||!W)return;let t=P(),n=t.append?l(t.append):l(t.delimiter);try{if(U===`hex`){let t=L(e);u(C,`HEX: ${I(t)}`,{kind:`sent`,label:`You`}),await W.send(t)}else{let r=t.prepend+e+n;u(C,e,{kind:`sent`,label:`You`}),await W.send(r)}T.value=``,T.focus()}catch(e){u(C,`Send error: ${e instanceof Error?e.message:String(e)}`,{kind:`error`})}}Oe?.addEventListener(`click`,G),T?.addEventListener(`keydown`,e=>{e.key===`Enter`&&G()});var K=S(`cmd-name`),q=S(`cmd-value`),Ve=S(`cmd-mode`),He=S(`cmd-add`),J=S(`cmd-list`),Y=S(`lst-name`),X=S(`lst-pattern`),Ue=S(`lst-match`),We=S(`lst-add`),Z=S(`lst-list`);function Q(){if(J){J.innerHTML=``;for(let e of b){let t=document.createElement(`div`);t.className=`chip`;let n=document.createElement(`span`);n.className=`chip-badge`,n.textContent=e.mode.toUpperCase();let r=document.createElement(`span`);r.className=`chip-name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`chip-val`,i.textContent=e.value;let a=document.createElement(`button`);a.className=`chip-send`,a.title=`Send now`,a.textContent=`▶`,a.addEventListener(`click`,()=>{if(W)if(e.mode===`hex`){let t=L(e.value);W.send(t).catch(()=>{}),u(C,`HEX: ${I(t)}`,{kind:`sent`,label:`You`})}else{let t=P(),n=t.append?l(t.append):l(t.delimiter);W.send(t.prepend+e.value+n).catch(()=>{}),u(C,e.name,{kind:`sent`,label:`You`})}});let o=document.createElement(`button`);o.className=`chip-del`,o.title=`Remove`,o.textContent=`×`,o.addEventListener(`click`,()=>{b=b.filter(t=>t.id!==e.id),Q(),B()}),t.append(n,r,i,a,o),J.appendChild(t)}}}function $(){if(Z){Z.innerHTML=``;for(let e of x){let t=document.createElement(`div`);t.className=`chip`;let n=document.createElement(`span`);n.className=`chip-badge`,n.textContent=e.match;let r=document.createElement(`span`);r.className=`chip-name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`chip-val`,i.textContent=e.pattern;let a=document.createElement(`button`);a.className=`chip-del`,a.title=`Remove`,a.textContent=`×`,a.addEventListener(`click`,()=>{x=x.filter(t=>t.id!==e.id),$(),B()}),t.append(n,r,i,a),Z.appendChild(t)}}}He?.addEventListener(`click`,()=>{let e=K?.value.trim(),t=q?.value.trim();!e||!t||(b.push({id:crypto.randomUUID(),name:e,value:t,mode:Ve?.value??`text`}),K&&(K.value=``),q&&(q.value=``),Q(),B())}),We?.addEventListener(`click`,()=>{let e=Y?.value.trim(),t=X?.value.trim();!e||!t||(x.push({id:crypto.randomUUID(),name:e,pattern:t,match:Ue?.value??`exact`}),Y&&(Y.value=``),X&&(X.value=``),$(),B())}),u(C,`WebUSB demo ready — CP2102/ESP32 (0x10c4/0xea60), CH340/Arduino (0x1a86/0x7523). Configure and click Connect.`,{kind:`system`}),r(C),i();
@@ -0,0 +1 @@
1
+ import{_ as e,a as t,b as n,d as r,f as i,g as a,h as o,i as s,m as c,n as l,o as ee,p as u,r as d,t as f,u as p,v as te,x as m,y as ne}from"./demo-shared-DnvFynUr.js";function re(e){return new Promise((t,n)=>{e.addEventListener(`open`,()=>t(),{once:!0}),e.addEventListener(`error`,e=>n(e),{once:!0})})}function h(e,t){return new Promise(n=>{let r=i=>{let a=JSON.parse(i.data);a.type===t&&(e.removeEventListener(`message`,r),n(a.payload))};e.addEventListener(`message`,r)})}function g(e,t){let n=null,r=null;return{get readable(){return n},get writable(){return r},getInfo(){return{usbVendorId:t.vendorId,usbProductId:t.productId}},async open(i){e.send(JSON.stringify({type:`open`,path:t.path,baudRate:i.baudRate,dataBits:i.dataBits,stopBits:i.stopBits,parity:i.parity,parser:{type:`delimiter`,value:`\\n`}})),await h(e,`opened`);let a=[],o=null,s=!1;function c(e){let t=JSON.parse(e.data);if(t.type===`data`&&t.bytes){let e=new Uint8Array(t.bytes);o?o.enqueue(e):a.push(e)}t.type===`closed`&&(s=!0,o&&o.close())}e.addEventListener(`message`,c),n=new ReadableStream({start(e){o=e;for(let t of a)e.enqueue(t);a.length=0,s&&e.close()},cancel(){e.removeEventListener(`message`,c),o=null}}),r=new WritableStream({write(t){e.send(JSON.stringify({type:`write`,bytes:Array.from(t)}))}})},async close(){e.send(JSON.stringify({type:`close`})),n=null,r=null,e.close()}}}function ie(e){return{async requestPort(t){let n=new WebSocket(e);await re(n),n.send(JSON.stringify({type:`list-ports`,filters:t?.filters??[]}));let r=(await h(n,`port-list`))[0];if(!r)throw Error(`No ports available on the bridge server. Make sure the Node.js server is running and a device is connected.`);return g(n,r)},async getPorts(){let t=new WebSocket(e);return await re(t),t.send(JSON.stringify({type:`list-ports`,filters:[]})),(await h(t,`port-list`)).map(e=>g(t,e))}}}var _=[],v=[],ae=class extends m{_hsCmd;_hsCmdMode;_hsExpect;_hsExpectMode;constructor(e,t,n,r,i){super(e),this._hsCmd=t,this._hsCmdMode=n,this._hsExpect=r,this._hsExpectMode=i}async handshake(){if(!this._hsCmd||(this._hsCmdMode===`hex`?await this.send(I(this._hsCmd)):await this.send(d(this._hsCmd)),!this._hsExpect))return!0;let e=this._hsExpect.trim();return new Promise(t=>{let n=r=>{if(this.off(`serial:data`,n),this._hsExpectMode===`hex`){let e=new TextEncoder().encode(String(r)),n=I(this._hsExpect);t(e.length===n.length&&e.every((e,t)=>e===n[t]))}else t(String(r).trim()===e)};this.on(`serial:data`,n)})}},y=e=>document.getElementById(e),b=y(`messages`),x=y(`btn-connect`),S=y(`btn-disconnect`),C=y(`btn-send`),w=y(`input-send`),T=y(`mode-toggle`),oe=y(`status-dot`),E=y(`status-text`),se=y(`console-dot`),D=y(`console-text`),O=y(`sidebar`),k=y(`code-panel`),ce=y(`code-view`),le=y(`code-tab`),ue=y(`menu-btn`),de=y(`code-toggle-btn`),A=y(`theme-btn`),fe=y(`clear-btn`),j=y(`copy-btn`),pe=y(`dl-btn`),me=y(`cfg-export-btn`),M=y(`cfg-import-input`);function N(){let e=e=>(y(e)?.value??``).trim(),t=(t,n)=>parseInt(e(t))||n,n=e=>y(e)?.value??``;return{wsUrl:e(`cfg-wsurl`)||`ws://localhost:8080`,baudRate:t(`cfg-baud`,9600),dataBits:t(`cfg-databits`,8),stopBits:t(`cfg-stopbits`,1),parity:n(`cfg-parity`)||`none`,flowControl:n(`cfg-flow`)||`none`,bufferSize:t(`cfg-bufsize`,255),commandTimeout:t(`cfg-timeout`,3e3),autoReconnect:(e=>y(e)?.checked??!1)(`cfg-autoreconnect`),autoReconnectInterval:t(`cfg-reconnect-ms`,1500),handshakeTimeout:t(`cfg-handshake`,2e3),delimiter:e(`cfg-delim`)||`\\n`,prepend:e(`cfg-prepend`),append:e(`cfg-append`),hsCmd:e(`cfg-hs-cmd`),hsCmdMode:n(`cfg-hs-cmd-mode`)||`text`,hsExpect:e(`cfg-hs-expect`),hsExpectMode:n(`cfg-hs-expect-mode`)||`text`}}function he(e){let t=(e,t)=>{let n=document.getElementById(e);n&&(n instanceof HTMLInputElement&&n.type===`checkbox`?n.checked=!!t:(n instanceof HTMLInputElement||n instanceof HTMLSelectElement)&&(n.value=String(t??``)))};t(`cfg-wsurl`,e.wsUrl??`ws://localhost:8080`),t(`cfg-baud`,e.baudRate??9600),t(`cfg-databits`,e.dataBits??8),t(`cfg-stopbits`,e.stopBits??1),t(`cfg-parity`,e.parity??`none`),t(`cfg-flow`,e.flowControl??`none`),t(`cfg-bufsize`,e.bufferSize??255),t(`cfg-timeout`,e.commandTimeout??3e3),t(`cfg-handshake`,e.handshakeTimeout??2e3),t(`cfg-reconnect-ms`,e.autoReconnectInterval??1500),t(`cfg-autoreconnect`,e.autoReconnect??!1),t(`cfg-delim`,e.delimiter??`\\n`),t(`cfg-prepend`,e.prepend??``),t(`cfg-append`,e.append??``),t(`cfg-hs-cmd`,e.hsCmd??``),t(`cfg-hs-cmd-mode`,e.hsCmdMode??`text`),t(`cfg-hs-expect`,e.hsExpect??``),t(`cfg-hs-expect-mode`,e.hsExpectMode??`text`)}function P(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,``).replace(/^[^a-zA-Z_$]/,`C`);return t.charAt(0).toUpperCase()+t.slice(1)||`MyDevice`}function F(e){return Array.from(e).map(e=>e.toString(16).toUpperCase().padStart(2,`0`)).join(` `)}function I(e){let t=e.replace(/\s+/g,``);if(t.length%2!=0)throw Error(`Odd number of hex characters.`);let n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=parseInt(t.substring(e,e+2),16);return n}function L(e,t){[oe,se].forEach(t=>{t&&(t.className=`status-dot`,e!==`disconnected`&&t.classList.add(e))}),E&&(E.textContent=t),D&&(D.textContent=t)}var R=null;function z(){R&&clearTimeout(R),R=setTimeout(()=>{let e=N(),t=P((y(`dl-name`)?.value??`MyWsDevice`).trim()),n=(document.querySelector(`input[name='dl-lang']:checked`)?.value??`ts`)===`ts`,r=n?`ts`:`js`;te(ce,p(e,t,n,_,v)),le&&(le.textContent=`${t.substring(0,10).toLowerCase()}.${r}`)},180)}var ge=u();A&&(A.textContent=ge===`dark`?`☀️`:`🌙`),ue?.addEventListener(`click`,()=>O.classList.toggle(`collapsed`)),de?.addEventListener(`click`,()=>k.classList.toggle(`collapsed`));var B=y(`resize-handle`);if(B){let e=0,t=0,n=n=>{let r=Math.max(180,Math.min(700,t+(e-n.clientX)));document.documentElement.style.setProperty(`--code-w`,`${r}px`)},r=()=>{B.classList.remove(`dragging`),document.removeEventListener(`pointermove`,n)};B.addEventListener(`pointerdown`,i=>{e=i.clientX,t=k.getBoundingClientRect().width,B.classList.add(`dragging`),document.addEventListener(`pointermove`,n),document.addEventListener(`pointerup`,r,{once:!0}),i.preventDefault()})}var V=y(`sidebar-resize-handle`);if(V){let e=0,t=0,n=n=>{let r=Math.max(200,Math.min(600,t+(n.clientX-e)));document.documentElement.style.setProperty(`--sidebar-w`,`${r}px`)},r=()=>{V.classList.remove(`dragging`),document.removeEventListener(`pointermove`,n)};V.addEventListener(`pointerdown`,i=>{e=i.clientX,t=O.getBoundingClientRect().width,V.classList.add(`dragging`),document.addEventListener(`pointermove`,n),document.addEventListener(`pointerup`,r,{once:!0}),i.preventDefault()})}window.innerWidth<=960&&k.classList.add(`collapsed`),window.innerWidth<=640&&O.classList.add(`collapsed`),A?.addEventListener(`click`,()=>{let e=ne();A&&(A.textContent=e===`dark`?`☀️`:`🌙`)}),fe?.addEventListener(`click`,()=>l(b)),j?.addEventListener(`click`,async()=>{let e=ce?.textContent??``;try{await navigator.clipboard.writeText(e),j&&(j.textContent=`Copied!`,j.classList.add(`copied`),setTimeout(()=>{j.textContent=`Copy`,j.classList.remove(`copied`)},1500))}catch{}}),pe?.addEventListener(`click`,()=>{let n=N(),r=(y(`dl-name`)?.value??`my-ws-device`).trim(),i=P(r),s=(document.querySelector(`input[name='dl-lang']:checked`)?.value??`ts`)===`ts`,l=document.querySelector(`input[name='dl-type']:checked`)?.value??`file`,u=s?`ts`:`js`,d=p(n,i,s,_,v);l===`project`?ee([{name:`device.${u}`,content:d},{name:`package.json`,content:o(r,s,`ws`)},{name:`index.html`,content:c(i,u,`WebSocket`)},{name:`README.md`,content:a(i,u,`WebSocket`,"Requires a WebSocket-to-serial bridge. Start the bridge: `cd demos/websocket && node server.js`")},...s?[{name:`tsconfig.json`,content:e()}]:[]],`${r}-project`):t(`${r}.${u}`,d)}),me?.addEventListener(`click`,()=>{let e=(y(`dl-name`)?.value??`my-ws-device`).trim(),t=P(e);s({$version:1,provider:`ws`,className:e,language:document.querySelector(`input[name='dl-lang']:checked`)?.value??`ts`,dlType:document.querySelector(`input[name='dl-type']:checked`)?.value??`file`,cfg:N(),commands:_,listeners:v},t+`-config`)}),M?.addEventListener(`change`,()=>{let e=M.files?.[0];if(!e)return;let t=new FileReader;t.onload=e=>{try{let t=JSON.parse(e.target?.result);if(t.$version!==1||t.provider!==`ws`)return;let n=y(`dl-name`);n&&(n.value=t.className),document.querySelectorAll(`input[name='dl-lang']`).forEach(e=>{e.checked=e.value===t.language}),document.querySelectorAll(`input[name='dl-type']`).forEach(e=>{e.checked=e.value===t.dlType}),he(t.cfg),_=t.commands.map(e=>({...e,id:crypto.randomUUID()})),v=t.listeners.map(e=>({...e,id:crypto.randomUUID()})),Q(),$(),z()}catch{}M.value=``},t.readAsText(e)}),[`cfg-wsurl`,`cfg-baud`,`cfg-databits`,`cfg-stopbits`,`cfg-parity`,`cfg-flow`,`cfg-bufsize`,`cfg-timeout`,`cfg-handshake`,`cfg-reconnect-ms`,`cfg-autoreconnect`,`cfg-delim`,`cfg-prepend`,`cfg-append`,`cfg-hs-cmd`,`cfg-hs-cmd-mode`,`cfg-hs-expect`,`cfg-hs-expect-mode`,`dl-name`].forEach(e=>{let t=document.getElementById(e);t?.addEventListener(`change`,z),t?.addEventListener(`input`,z)}),document.querySelectorAll(`input[name='dl-lang']`).forEach(e=>e.addEventListener(`change`,z)),z();var H=`text`;T?.addEventListener(`click`,()=>{H=H===`text`?`hex`:`text`,T.textContent=H===`text`?`TXT`:`HEX`,w.placeholder=H===`text`?`Type a command, e.g. LED_ON`:`Hex bytes, e.g. FF 01 A3`});var U=null;function W(e){C.disabled=!e,w.disabled=!e,S.disabled=!e,x.disabled=e}x?.addEventListener(`click`,async()=>{if(U){try{await U.disconnect()}catch{}U=null}let e=N();m.setProvider(ie(e.wsUrl));let t=d(e.delimiter);U=new ae({baudRate:e.baudRate,dataBits:e.dataBits,stopBits:e.stopBits,parity:e.parity,flowControl:e.flowControl,bufferSize:e.bufferSize,commandTimeout:e.commandTimeout,parser:n(t),autoReconnect:e.autoReconnect,autoReconnectInterval:e.autoReconnectInterval,handshakeTimeout:e.handshakeTimeout},e.hsCmd,e.hsCmdMode,e.hsExpect,e.hsExpectMode),U.on(`serial:connecting`,()=>{L(`connecting`,`Connecting…`),x.disabled=!0,f(b,`Connecting to ${e.wsUrl}…`,{kind:`system`})}),U.on(`serial:connected`,()=>{L(`connected`,`Connected`),W(!0),f(b,`Connected via WebSocket (${e.wsUrl})!`,{kind:`system`})}),U.on(`serial:disconnected`,()=>{L(`disconnected`,`Disconnected`),W(!1),f(b,`Disconnected.`,{kind:`system`}),U=null}),U.on(`serial:data`,e=>{f(b,String(e),{kind:`received`,label:`Device`})}),U.on(`serial:error`,e=>{L(`error`,`Error`),f(b,`Error: ${e.message}`,{kind:`error`}),x.disabled=!1}),U.on(`serial:need-permission`,()=>{L(`error`,`Connection refused`),f(b,`Could not connect — is the WebSocket bridge running?`,{kind:`error`}),x.disabled=!1}),U.on(`serial:timeout`,e=>{f(b,`Timeout: ${F(e)}`,{kind:`error`})}),U.on(`serial:reconnecting`,()=>{L(`connecting`,`Reconnecting…`),f(b,`Auto-reconnecting via WebSocket…`,{kind:`system`})});try{await U.connect()}catch{}}),S?.addEventListener(`click`,async()=>{await U?.disconnect()});async function G(){let e=w.value.trim();if(!e||!U)return;let t=N(),n=t.append?d(t.append):d(t.delimiter);try{if(H===`hex`){let t=I(e);f(b,`HEX: ${F(t)}`,{kind:`sent`,label:`You`}),await U.send(t)}else{let r=t.prepend+e+n;f(b,e,{kind:`sent`,label:`You`}),await U.send(r)}w.value=``,w.focus()}catch(e){f(b,`Send error: ${e instanceof Error?e.message:String(e)}`,{kind:`error`})}}C?.addEventListener(`click`,G),w?.addEventListener(`keydown`,e=>{e.key===`Enter`&&G()});var K=y(`cmd-name`),q=y(`cmd-value`),_e=y(`cmd-mode`),ve=y(`cmd-add`),J=y(`cmd-list`),Y=y(`lst-name`),X=y(`lst-pattern`),ye=y(`lst-match`),be=y(`lst-add`),Z=y(`lst-list`);function Q(){if(J){J.innerHTML=``;for(let e of _){let t=document.createElement(`div`);t.className=`chip`;let n=document.createElement(`span`);n.className=`chip-badge`,n.textContent=e.mode.toUpperCase();let r=document.createElement(`span`);r.className=`chip-name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`chip-val`,i.textContent=e.value;let a=document.createElement(`button`);a.className=`chip-send`,a.title=`Send now`,a.textContent=`▶`,a.addEventListener(`click`,()=>{if(U)if(e.mode===`hex`){let t=I(e.value);U.send(t).catch(()=>{}),f(b,`HEX: ${F(t)}`,{kind:`sent`,label:`You`})}else{let t=N(),n=t.append?d(t.append):d(t.delimiter);U.send(t.prepend+e.value+n).catch(()=>{}),f(b,e.name,{kind:`sent`,label:`You`})}});let o=document.createElement(`button`);o.className=`chip-del`,o.title=`Remove`,o.textContent=`×`,o.addEventListener(`click`,()=>{_=_.filter(t=>t.id!==e.id),Q(),z()}),t.append(n,r,i,a,o),J.appendChild(t)}}}function $(){if(Z){Z.innerHTML=``;for(let e of v){let t=document.createElement(`div`);t.className=`chip`;let n=document.createElement(`span`);n.className=`chip-badge`,n.textContent=e.match;let r=document.createElement(`span`);r.className=`chip-name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`chip-val`,i.textContent=e.pattern;let a=document.createElement(`button`);a.className=`chip-del`,a.title=`Remove`,a.textContent=`×`,a.addEventListener(`click`,()=>{v=v.filter(t=>t.id!==e.id),$(),z()}),t.append(n,r,i,a),Z.appendChild(t)}}}ve?.addEventListener(`click`,()=>{let e=K?.value.trim(),t=q?.value.trim();if(!e||!t)return;let n=_e?.value??`text`;_.push({id:crypto.randomUUID(),name:e,value:t,mode:n}),K&&(K.value=``),q&&(q.value=``),Q(),z()}),be?.addEventListener(`click`,()=>{let e=Y?.value.trim(),t=X?.value.trim();if(!e||!t)return;let n=ye?.value??`exact`;v.push({id:crypto.randomUUID(),name:e,pattern:t,match:n}),Y&&(Y.value=``),X&&(X.value=``),$(),z()}),f(b,`WebSocket bridge demo — start the Node.js bridge first: cd demos/websocket && node server.js`,{kind:`system`}),r(b),i();
@@ -0,0 +1,408 @@
1
+ <!doctype html>
2
+ <html lang="en" data-theme="dark">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
7
+ <title>Web Bluetooth — webserial-core demo</title>
8
+ <style>
9
+ :root {
10
+ --accent: #a855f7;
11
+ --accent-dark: #9333ea;
12
+ --accent-glow: rgba(168, 85, 247, 0.12);
13
+ --accent-badge: #faf5ff;
14
+ }
15
+ </style>
16
+ <script
17
+ type="module"
18
+ crossorigin
19
+ src="/demos/assets/web-bluetooth-VVwTClLx.js"
20
+ ></script>
21
+ <link
22
+ rel="modulepreload"
23
+ crossorigin
24
+ href="/demos/assets/demo-shared-DnvFynUr.js"
25
+ />
26
+ <link
27
+ rel="stylesheet"
28
+ crossorigin
29
+ href="/demos/assets/demo-shared-DLFsukQx.css"
30
+ />
31
+ </head>
32
+ <body>
33
+ <!-- ── Topbar ──────────────────────────────────────────── -->
34
+ <header class="topbar">
35
+ <button class="icon-btn" id="menu-btn" title="Toggle sidebar">
36
+ <i data-lucide="menu"></i>
37
+ </button>
38
+ <a class="topbar-brand" href="/demos/web-serial.html">
39
+ <span class="brand-icon"><i data-lucide="bluetooth"></i></span>
40
+ <span class="brand-name">webserial-core</span>
41
+ <span class="brand-ver">v2</span>
42
+ </a>
43
+ <span class="provider-pill">Bluetooth</span>
44
+ <span class="flex-1"></span>
45
+
46
+ <nav class="topbar-nav">
47
+ <a class="nav-item" href="/demos/web-serial.html"
48
+ ><i data-lucide="zap"></i><span class="nav-lbl"> Web Serial</span></a
49
+ >
50
+ <a class="nav-item active" href="/demos/web-bluetooth.html"
51
+ ><i data-lucide="bluetooth"></i
52
+ ><span class="nav-lbl"> Bluetooth</span></a
53
+ >
54
+ <a class="nav-item" href="/demos/web-usb.html"
55
+ ><i data-lucide="usb"></i><span class="nav-lbl"> WebUSB</span></a
56
+ >
57
+ <a class="nav-item" href="/demos/websocket.html"
58
+ ><i data-lucide="globe"></i><span class="nav-lbl"> WebSocket</span></a
59
+ >
60
+ </nav>
61
+
62
+ <div class="topbar-actions">
63
+ <div class="status-pill">
64
+ <div class="status-dot" id="status-dot"></div>
65
+ <span id="status-text">Disconnected</span>
66
+ </div>
67
+ <button class="icon-btn" id="theme-btn" title="Toggle theme">🌙</button>
68
+ <button
69
+ class="icon-btn code-toggle"
70
+ id="code-toggle-btn"
71
+ title="Toggle code panel"
72
+ >
73
+ <i data-lucide="code-2"></i>
74
+ </button>
75
+ <button class="btn btn-connect" id="btn-connect">Pair Device</button>
76
+ <button class="btn btn-disconnect" id="btn-disconnect" disabled>
77
+ Disconnect
78
+ </button>
79
+ </div>
80
+ </header>
81
+
82
+ <!-- ── App layout ───────────────────────────────────────── -->
83
+ <div class="app-layout">
84
+ <!-- ── Sidebar ─────────────────────────────────────────── -->
85
+ <aside class="sidebar" id="sidebar">
86
+ <div class="sidebar-scroll">
87
+ <!-- BLE info notice -->
88
+ <div class="sb-section">
89
+ <div class="notice">
90
+ Uses <strong>Nordic UART Service (NUS)</strong> over GATT.
91
+ Compatible: nRF52, ESP32 BLE UART, or any NUS device
92
+ (<code>6e400001-…</code>).<br />
93
+ Requires <strong>HTTPS</strong> or <code>localhost</code> +
94
+ Chromium with Web Bluetooth enabled.
95
+ </div>
96
+ </div>
97
+
98
+ <!-- Connection settings (limited for BLE) -->
99
+ <div class="sb-section">
100
+ <div class="sb-title">Connection</div>
101
+
102
+ <div class="field-row">
103
+ <div class="field">
104
+ <label for="cfg-bufsize">Buffer Size</label>
105
+ <input
106
+ type="number"
107
+ id="cfg-bufsize"
108
+ value="255"
109
+ min="64"
110
+ max="65536"
111
+ />
112
+ </div>
113
+ <div class="field">
114
+ <label for="cfg-timeout">Cmd Timeout (ms)</label>
115
+ <input type="number" id="cfg-timeout" value="3000" min="0" />
116
+ </div>
117
+ </div>
118
+ <div class="field">
119
+ <label for="cfg-handshake">Handshake Timeout (ms)</label>
120
+ <input type="number" id="cfg-handshake" value="2000" min="0" />
121
+ </div>
122
+
123
+ <div class="notice" style="margin-top: 6px">
124
+ <strong>Baud rate</strong> is not used over BLE — link speed is
125
+ negotiated at the GATT level.
126
+ </div>
127
+ </div>
128
+
129
+ <!-- Message format -->
130
+ <div class="sb-section">
131
+ <div class="sb-title">Message Format</div>
132
+ <div class="field">
133
+ <label for="cfg-delim">Delimiter</label>
134
+ <input
135
+ type="text"
136
+ id="cfg-delim"
137
+ value="\n"
138
+ placeholder="\n \r\n | etc."
139
+ />
140
+ </div>
141
+ <div class="field-row">
142
+ <div class="field">
143
+ <label for="cfg-prepend">Prepend</label>
144
+ <input
145
+ type="text"
146
+ id="cfg-prepend"
147
+ value=""
148
+ placeholder="e.g. STX"
149
+ />
150
+ </div>
151
+ <div class="field">
152
+ <label for="cfg-append">Append</label>
153
+ <input
154
+ type="text"
155
+ id="cfg-append"
156
+ value="\n"
157
+ placeholder="e.g. \n"
158
+ />
159
+ </div>
160
+ </div>
161
+ </div>
162
+
163
+ <!-- Handshake -->
164
+ <div class="sb-section">
165
+ <div class="sb-title">Handshake on Connect</div>
166
+ <div class="notice" style="margin-bottom: 6px">
167
+ Sent automatically right after the GATT link opens. Leave
168
+ <em>Command</em> empty to skip entirely.
169
+ </div>
170
+ <div class="field-row">
171
+ <div class="field">
172
+ <label for="cfg-hs-cmd">Command to send</label>
173
+ <input
174
+ type="text"
175
+ id="cfg-hs-cmd"
176
+ value=""
177
+ placeholder="e.g. PING\n or FF 01 A3"
178
+ />
179
+ </div>
180
+ <div class="field" style="flex: 0 0 62px">
181
+ <label for="cfg-hs-cmd-mode">Mode</label>
182
+ <select id="cfg-hs-cmd-mode">
183
+ <option value="text" selected>TXT</option>
184
+ <option value="hex">HEX</option>
185
+ </select>
186
+ </div>
187
+ </div>
188
+ <div class="field-row">
189
+ <div class="field">
190
+ <label for="cfg-hs-expect"
191
+ >Expected <small>(empty = no check)</small></label
192
+ >
193
+ <input
194
+ type="text"
195
+ id="cfg-hs-expect"
196
+ value=""
197
+ placeholder="e.g. PONG or OK"
198
+ />
199
+ </div>
200
+ <div class="field" style="flex: 0 0 62px">
201
+ <label for="cfg-hs-expect-mode">Mode</label>
202
+ <select id="cfg-hs-expect-mode">
203
+ <option value="text" selected>TXT</option>
204
+ <option value="hex">HEX</option>
205
+ </select>
206
+ </div>
207
+ </div>
208
+ </div>
209
+
210
+ <!-- Saved Commands -->
211
+ <div class="sb-section">
212
+ <div class="sb-title">Saved Commands</div>
213
+ <div class="notice" style="margin-bottom: 6px">
214
+ Pre-defined commands to send. Use <em>HEX</em> for raw bytes.
215
+ </div>
216
+ <div class="field-row">
217
+ <div class="field" style="flex: 0 0 72px">
218
+ <label for="cmd-name">Name</label>
219
+ <input type="text" id="cmd-name" placeholder="LED ON" />
220
+ </div>
221
+ <div class="field">
222
+ <label for="cmd-value">Command</label>
223
+ <input type="text" id="cmd-value" placeholder="LED_ON\n" />
224
+ </div>
225
+ <div class="field" style="flex: 0 0 62px">
226
+ <label for="cmd-mode">Mode</label>
227
+ <select id="cmd-mode">
228
+ <option value="text" selected>TXT</option>
229
+ <option value="hex">HEX</option>
230
+ </select>
231
+ </div>
232
+ </div>
233
+ <button
234
+ class="btn btn-ghost"
235
+ id="cmd-add"
236
+ style="width: 100%; margin-top: 3px"
237
+ >
238
+ <i data-lucide="plus"></i> Add Command
239
+ </button>
240
+ <div class="chip-list" id="cmd-list"></div>
241
+ </div>
242
+
243
+ <!-- Data Listeners -->
244
+ <div class="sb-section">
245
+ <div class="sb-title">Data Listeners</div>
246
+ <div class="notice" style="margin-bottom: 6px">
247
+ Patterns for <code>on('serial:data')</code> — skeleton code in
248
+ download.
249
+ </div>
250
+ <div class="field-row">
251
+ <div class="field" style="flex: 0 0 64px">
252
+ <label for="lst-name">Name</label>
253
+ <input type="text" id="lst-name" placeholder="Temp" />
254
+ </div>
255
+ <div class="field">
256
+ <label for="lst-pattern">Pattern</label>
257
+ <input type="text" id="lst-pattern" placeholder="TEMP:" />
258
+ </div>
259
+ <div class="field" style="flex: 0 0 62px">
260
+ <label for="lst-match">Match</label>
261
+ <select id="lst-match">
262
+ <option value="exact">exact</option>
263
+ <option value="contains" selected>has</option>
264
+ <option value="startsWith">starts</option>
265
+ <option value="hex">hex</option>
266
+ </select>
267
+ </div>
268
+ </div>
269
+ <button
270
+ class="btn btn-ghost"
271
+ id="lst-add"
272
+ style="width: 100%; margin-top: 3px"
273
+ >
274
+ <i data-lucide="plus"></i> Add Listener
275
+ </button>
276
+ <div class="chip-list" id="lst-list"></div>
277
+ </div>
278
+
279
+ <!-- Download -->
280
+ <div class="sb-section">
281
+ <div class="sb-title">Download Code</div>
282
+ <div class="field">
283
+ <label for="dl-name">Class / File name</label>
284
+ <input
285
+ type="text"
286
+ id="dl-name"
287
+ value="MyBleDevice"
288
+ placeholder="MyBleDevice"
289
+ />
290
+ </div>
291
+ <div class="dl-lang-row">
292
+ <label class="dl-opt"
293
+ ><input type="radio" name="dl-lang" value="ts" checked />
294
+ TypeScript</label
295
+ >
296
+ <label class="dl-opt"
297
+ ><input type="radio" name="dl-lang" value="js" />
298
+ JavaScript</label
299
+ >
300
+ </div>
301
+ <div class="dl-type-row">
302
+ <label class="dl-opt"
303
+ ><input type="radio" name="dl-type" value="file" checked />
304
+ Standalone file</label
305
+ >
306
+ <label class="dl-opt"
307
+ ><input type="radio" name="dl-type" value="project" /> Full
308
+ project (ZIP)</label
309
+ >
310
+ </div>
311
+ <div class="dl-btns">
312
+ <button class="btn btn-dl" id="dl-btn">
313
+ <i data-lucide="download"></i> Download
314
+ </button>
315
+ <button
316
+ class="btn btn-ghost"
317
+ id="cfg-export-btn"
318
+ title="Export configuration as JSON"
319
+ >
320
+ <i data-lucide="share"></i> Export config
321
+ </button>
322
+ <label
323
+ class="btn btn-ghost"
324
+ title="Import configuration from JSON"
325
+ >
326
+ <i data-lucide="upload"></i> Import config
327
+ <input
328
+ type="file"
329
+ id="cfg-import-input"
330
+ accept=".json"
331
+ style="display: none"
332
+ />
333
+ </label>
334
+ </div>
335
+ </div>
336
+ </div>
337
+ <!-- /sidebar-scroll -->
338
+ </aside>
339
+ <div class="sidebar-resize-handle" id="sidebar-resize-handle"></div>
340
+
341
+ <!-- ── Chat console ─────────────────────────────────── -->
342
+ <main class="console-area">
343
+ <div class="console-hdr">
344
+ <div class="status-pill">
345
+ <div class="status-dot" id="console-dot"></div>
346
+ <span id="console-text">Pair a Bluetooth device to begin</span>
347
+ </div>
348
+ <button
349
+ class="btn btn-ghost"
350
+ id="clear-btn"
351
+ style="margin-left: auto; font-size: 0.7rem; padding: 4px 10px"
352
+ >
353
+ Clear
354
+ </button>
355
+ </div>
356
+
357
+ <div class="messages" id="messages">
358
+ <div class="empty-state">
359
+ <div class="empty-icon">📡</div>
360
+ <span>Pair a BLE device to begin</span>
361
+ </div>
362
+ </div>
363
+
364
+ <div class="input-bar">
365
+ <button class="btn btn-mode" id="mode-toggle">TXT</button>
366
+ <input
367
+ class="msg-input"
368
+ id="input-send"
369
+ type="text"
370
+ placeholder="Type a command, e.g. LED_ON"
371
+ disabled
372
+ />
373
+ <button class="btn btn-send" id="btn-send" disabled>Send</button>
374
+ </div>
375
+ </main>
376
+
377
+ <!-- ── Code panel ────────────────────────────────────── -->
378
+ <div class="resize-handle" id="resize-handle"></div>
379
+ <aside class="code-panel" id="code-panel">
380
+ <div class="cp-hdr">
381
+ <div class="cp-title">
382
+ <span>Code Preview</span>
383
+ <span class="cp-tab" id="code-tab">device.ts</span>
384
+ </div>
385
+ <div class="cp-actions">
386
+ <button class="cp-btn" id="copy-btn">Copy</button>
387
+ </div>
388
+ </div>
389
+ <pre class="code-view" id="code-view"></pre>
390
+ </aside>
391
+ </div>
392
+ <!-- /app-layout -->
393
+
394
+ <footer class="app-footer">
395
+ © 2025
396
+ <a
397
+ href="https://github.com/danidoble"
398
+ style="color: inherit; text-decoration: none"
399
+ >@danidoble</a
400
+ >
401
+ · webserial-core v2
402
+ </footer>
403
+ <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
404
+ <script>
405
+ lucide.createIcons();
406
+ </script>
407
+ </body>
408
+ </html>