bitwrench 2.0.15 → 2.0.16

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.
Files changed (51) hide show
  1. package/README.md +57 -21
  2. package/dist/bitwrench-bccl.cjs.js +3746 -0
  3. package/dist/bitwrench-bccl.cjs.min.js +40 -0
  4. package/dist/bitwrench-bccl.esm.js +3741 -0
  5. package/dist/bitwrench-bccl.esm.min.js +40 -0
  6. package/dist/bitwrench-bccl.umd.js +3752 -0
  7. package/dist/bitwrench-bccl.umd.min.js +40 -0
  8. package/dist/bitwrench-code-edit.cjs.js +57 -7
  9. package/dist/bitwrench-code-edit.cjs.min.js +9 -2
  10. package/dist/bitwrench-code-edit.es5.js +74 -11
  11. package/dist/bitwrench-code-edit.es5.min.js +9 -2
  12. package/dist/bitwrench-code-edit.esm.js +57 -7
  13. package/dist/bitwrench-code-edit.esm.min.js +9 -2
  14. package/dist/bitwrench-code-edit.umd.js +57 -7
  15. package/dist/bitwrench-code-edit.umd.min.js +9 -2
  16. package/dist/bitwrench-lean.cjs.js +413 -17
  17. package/dist/bitwrench-lean.cjs.min.js +7 -7
  18. package/dist/bitwrench-lean.es5.js +428 -16
  19. package/dist/bitwrench-lean.es5.min.js +5 -5
  20. package/dist/bitwrench-lean.esm.js +413 -17
  21. package/dist/bitwrench-lean.esm.min.js +7 -7
  22. package/dist/bitwrench-lean.umd.js +413 -17
  23. package/dist/bitwrench-lean.umd.min.js +7 -7
  24. package/dist/bitwrench.cjs.js +413 -17
  25. package/dist/bitwrench.cjs.min.js +7 -7
  26. package/dist/bitwrench.css +60 -17
  27. package/dist/bitwrench.es5.js +428 -16
  28. package/dist/bitwrench.es5.min.js +6 -6
  29. package/dist/bitwrench.esm.js +413 -17
  30. package/dist/bitwrench.esm.min.js +7 -7
  31. package/dist/bitwrench.min.css +1 -1
  32. package/dist/bitwrench.umd.js +413 -17
  33. package/dist/bitwrench.umd.min.js +7 -7
  34. package/dist/builds.json +168 -80
  35. package/dist/bwserve.cjs.js +646 -0
  36. package/dist/bwserve.esm.js +638 -0
  37. package/dist/sri.json +36 -28
  38. package/package.json +18 -3
  39. package/readme.html +62 -23
  40. package/src/bitwrench-bccl-entry.js +72 -0
  41. package/src/bitwrench-code-edit.js +56 -6
  42. package/src/bitwrench-color-utils.js +5 -6
  43. package/src/bitwrench-styles.js +20 -8
  44. package/src/bitwrench.js +385 -0
  45. package/src/bwserve/client.js +182 -0
  46. package/src/bwserve/index.js +352 -0
  47. package/src/bwserve/shell.js +103 -0
  48. package/src/cli/index.js +36 -15
  49. package/src/cli/serve.js +325 -0
  50. package/src/version.js +3 -3
  51. /package/bin/{bitwrench.js → bwcli.js} +0 -0
@@ -1,4 +1,4 @@
1
- /*! bitwrench-lean v2.0.15 | BSD-2-Clause | https://deftio.github.com/bitwrench/pages */
1
+ /*! bitwrench-lean v2.0.16 | BSD-2-Clause | https://deftio.github.com/bitwrench/pages */
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
4
4
  typeof define === 'function' && define.amd ? define(factory) :
@@ -11,14 +11,14 @@
11
11
  */
12
12
 
13
13
  const VERSION_INFO = {
14
- version: '2.0.15',
14
+ version: '2.0.16',
15
15
  name: 'bitwrench',
16
16
  description: 'A library for javascript UI functions.',
17
17
  license: 'BSD-2-Clause',
18
18
  homepage: 'https://deftio.github.com/bitwrench/pages',
19
19
  repository: 'git+https://github.com/deftio/bitwrench.git',
20
20
  author: 'manu a. chatterjee <deftio@deftio.com> (https://deftio.com/)',
21
- buildDate: '2026-03-10T09:08:17.015Z'
21
+ buildDate: '2026-03-12T08:05:52.043Z'
22
22
  };
23
23
 
24
24
  /**
@@ -436,12 +436,11 @@
436
436
  var lightBase = config.light || hslToHex([h, 8, 97]);
437
437
  var darkBase = config.dark || hslToHex([h, 10, 13]);
438
438
 
439
- // Background & surface tokens — default to light (white/near-white).
440
- // Dark backgrounds require explicit config.background / config.surface.
441
- // Primary/secondary colors are accents, not page backgrounds, so
442
- // isLightPalette should NOT drive bg/surface defaults.
443
- var bgBase = config.background || '#ffffff';
444
- var surfBase = config.surface || '#f8f9fa';
439
+ // Background & surface tokens — tinted with primary hue for theme personality.
440
+ // Very subtle: bg at L=98/S=6, surface at L=96/S=8.
441
+ // User can override with config.background / config.surface.
442
+ var bgBase = config.background || hslToHex([h, 6, 98]);
443
+ var surfBase = config.surface || hslToHex([h, 8, 96]);
445
444
 
446
445
  var palette = {
447
446
  primary: deriveShades(config.primary),
@@ -1574,7 +1573,7 @@
1574
1573
  '@media (min-width: 992px)': { '.bw_container': { 'max-width': '960px' } },
1575
1574
  '@media (min-width: 1200px)': { '.bw_container': { 'max-width': '1140px' } },
1576
1575
  '.bw_container_fluid': {
1577
- 'width': '100%', 'padding-right': '15px', 'padding-left': '15px',
1576
+ 'width': '100%', 'padding-right': '0.75rem', 'padding-left': '0.75rem',
1578
1577
  'margin-right': 'auto', 'margin-left': 'auto'
1579
1578
  },
1580
1579
  '.bw_row': {
@@ -1735,7 +1734,8 @@
1735
1734
  '.bw_badge': {
1736
1735
  'display': 'inline-block', 'font-size': '0.875rem',
1737
1736
  'font-weight': '600', 'line-height': '1.3', 'text-align': 'center',
1738
- 'white-space': 'nowrap', 'vertical-align': 'baseline'
1737
+ 'white-space': 'nowrap', 'vertical-align': 'baseline',
1738
+ 'padding': '0.35rem 0.65rem', 'border-radius': '0.25rem'
1739
1739
  },
1740
1740
  '.bw_badge:empty': { 'display': 'none' },
1741
1741
  '.bw_badge_sm': { 'font-size': '0.75rem', 'padding': '0.25rem 0.5rem' },
@@ -1920,7 +1920,7 @@
1920
1920
  // ---- Code demo ----
1921
1921
  codeDemo: {
1922
1922
  '.bw_code_demo': { 'margin-bottom': '2rem' },
1923
- '.bw_code_pre': { 'margin': '0', 'border': 'none', 'overflow-x': 'auto' },
1923
+ '.bw_code_pre': { 'margin': '0', 'border': 'none', 'overflow-x': 'auto', 'max-width': '100%' },
1924
1924
  '.bw_code_block': {
1925
1925
  'display': 'block', 'padding': '1.25rem',
1926
1926
  'font-family': '"SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas, "Courier New", monospace',
@@ -2017,7 +2017,7 @@
2017
2017
  },
2018
2018
  '.bw_modal.bw_modal_show': { 'opacity': '1', 'visibility': 'visible', 'pointer-events': 'auto' },
2019
2019
  '.bw_modal_dialog': {
2020
- 'position': 'relative', 'width': '100%', 'max-width': '500px', 'margin': '1.75rem auto',
2020
+ 'position': 'relative', 'width': 'calc(100% - 1rem)', 'max-width': '500px', 'margin': '1.75rem auto',
2021
2021
  'pointer-events': 'none'
2022
2022
  },
2023
2023
  '.bw_modal.bw_modal_show .bw_modal_dialog': { 'transform': 'translateY(0)' },
@@ -2047,7 +2047,7 @@
2047
2047
  '.bw_toast_container.bw_toast_top_center': { 'top': '0', 'left': '50%', 'transform': 'translateX(-50%)' },
2048
2048
  '.bw_toast_container.bw_toast_bottom_center': { 'bottom': '0', 'left': '50%', 'transform': 'translateX(-50%)' },
2049
2049
  '.bw_toast': {
2050
- 'pointer-events': 'auto', 'width': '350px', 'max-width': '100%', 'background-clip': 'padding-box',
2050
+ 'pointer-events': 'auto', 'width': '350px', 'max-width': 'calc(100vw - 2rem)', 'background-clip': 'padding-box',
2051
2051
  'opacity': '0'
2052
2052
  },
2053
2053
  '.bw_toast.bw_toast_show': { 'opacity': '1', 'transform': 'translateY(0)' },
@@ -2133,7 +2133,7 @@
2133
2133
  '.bw_tooltip_wrapper': { 'position': 'relative', 'display': 'inline-block' },
2134
2134
  '.bw_tooltip': {
2135
2135
  'position': 'absolute', 'z-index': '999',
2136
- 'font-size': '0.875rem', 'white-space': 'nowrap', 'pointer-events': 'none',
2136
+ 'font-size': '0.875rem', 'white-space': 'nowrap', 'max-width': 'min(300px, calc(100vw - 1rem))', 'pointer-events': 'none',
2137
2137
  'opacity': '0', 'visibility': 'hidden'
2138
2138
  },
2139
2139
  '.bw_tooltip.bw_tooltip_show': { 'opacity': '1', 'visibility': 'visible' },
@@ -2153,7 +2153,7 @@
2153
2153
  '.bw_popover_trigger': { 'cursor': 'pointer' },
2154
2154
  '.bw_popover': {
2155
2155
  'position': 'absolute', 'z-index': '1000',
2156
- 'min-width': '200px', 'max-width': '320px',
2156
+ 'min-width': '200px', 'max-width': 'min(320px, calc(100vw - 2rem))',
2157
2157
  'pointer-events': 'none', 'opacity': '0', 'visibility': 'hidden'
2158
2158
  },
2159
2159
  '.bw_popover.bw_popover_show': { 'opacity': '1', 'visibility': 'visible', 'pointer-events': 'auto' },
@@ -2336,7 +2336,18 @@
2336
2336
  '.bw_hero, .bw_hero': { 'padding': '2rem 1rem' },
2337
2337
  '.bw_cta_actions, .bw_cta-actions': { 'flex-direction': 'column' },
2338
2338
  '.bw_hstack, .bw_hstack': { 'flex-direction': 'column' },
2339
- '.bw_feature_grid, .bw_feature-grid': { 'grid-template-columns': '1fr' }
2339
+ '.bw_feature_grid, .bw_feature-grid': { 'grid-template-columns': '1fr' },
2340
+ '.bw_modal_dialog': { 'margin': '0.5rem auto' },
2341
+ '.bw_modal_lg': { 'max-width': 'calc(100% - 1rem)' },
2342
+ '.bw_modal_xl': { 'max-width': 'calc(100% - 1rem)' },
2343
+ '.bw_navbar': { 'padding': '0.5rem 0.75rem' },
2344
+ '.bw_navbar_brand': { 'margin-right': '0.5rem', 'font-size': '1rem' },
2345
+ '.bw_navbar_nav': { 'flex-wrap': 'wrap' },
2346
+ '.bw_tooltip': { 'white-space': 'normal' },
2347
+ '.bw_table': { 'display': 'block', 'overflow-x': 'auto', '-webkit-overflow-scrolling': 'touch' },
2348
+ '.bw_col, .bw_col_1, .bw_col_2, .bw_col_3, .bw_col_4, .bw_col_5, .bw_col_6, .bw_col_7, .bw_col_8, .bw_col_9, .bw_col_10, .bw_col_11, .bw_col_12': { 'flex': '0 0 100%', 'max-width': '100%' },
2349
+ '.bw_container': { 'padding-right': '0.5rem', 'padding-left': '0.5rem' },
2350
+ '.bw_container_fluid': { 'padding-right': '0.5rem', 'padding-left': '0.5rem' }
2340
2351
  }
2341
2352
  }
2342
2353
  };
@@ -5837,6 +5848,391 @@
5837
5848
  return true;
5838
5849
  };
5839
5850
 
5851
+ // ===================================================================================
5852
+ // bw.clientApply() / bw.clientConnect() — Server-driven UI protocol
5853
+ // ===================================================================================
5854
+
5855
+ /**
5856
+ * Registry of named functions sent via register messages.
5857
+ * Populated by clientApply({ type: 'register', name, body }).
5858
+ * Invoked by clientApply({ type: 'call', name, args }).
5859
+ * @private
5860
+ */
5861
+ bw._clientFunctions = {};
5862
+
5863
+ /**
5864
+ * Whether exec messages are allowed. Set by clientConnect opts.allowExec.
5865
+ * Default false — exec messages are rejected unless explicitly opted in.
5866
+ * @private
5867
+ */
5868
+ bw._allowExec = false;
5869
+
5870
+ /**
5871
+ * Built-in client functions available via call() without registration.
5872
+ * @private
5873
+ */
5874
+ bw._builtinClientFunctions = {
5875
+ scrollTo: function(selector) {
5876
+ var el = bw._el(selector);
5877
+ if (el) el.scrollTop = el.scrollHeight;
5878
+ },
5879
+ focus: function(selector) {
5880
+ var el = bw._el(selector);
5881
+ if (el && typeof el.focus === 'function') el.focus();
5882
+ },
5883
+ download: function(filename, content, mimeType) {
5884
+ if (typeof document === 'undefined') return;
5885
+ var blob = new Blob([content], { type: mimeType || 'text/plain' });
5886
+ var a = document.createElement('a');
5887
+ a.href = URL.createObjectURL(blob);
5888
+ a.download = filename;
5889
+ a.click();
5890
+ URL.revokeObjectURL(a.href);
5891
+ },
5892
+ clipboard: function(text) {
5893
+ if (typeof navigator !== 'undefined' && navigator.clipboard) {
5894
+ navigator.clipboard.writeText(text);
5895
+ }
5896
+ },
5897
+ redirect: function(url) {
5898
+ if (typeof window !== 'undefined') window.location.href = url;
5899
+ },
5900
+ log: function() {
5901
+ console.log.apply(console, arguments);
5902
+ }
5903
+ };
5904
+
5905
+ /**
5906
+ * Parse a bwserve protocol message string, supporting both strict JSON
5907
+ * and r-prefixed relaxed JSON (single-quoted strings, trailing commas).
5908
+ *
5909
+ * The r-prefix format is designed for C/C++ string literals where
5910
+ * double-quote escaping is painful. The parser is a state machine
5911
+ * that walks character by character — not a regex replace.
5912
+ *
5913
+ * Escaping: apostrophes inside single-quoted values must be escaped
5914
+ * with backslash: r{'name':'Barry\'s room'}
5915
+ *
5916
+ * @param {string} str - JSON or r-prefixed relaxed JSON string
5917
+ * @returns {Object} Parsed message object
5918
+ * @throws {SyntaxError} If the string is not valid JSON or relaxed JSON
5919
+ * @category Server
5920
+ */
5921
+ bw.clientParse = function(str) {
5922
+ str = (str || '').trim();
5923
+ if (str.charAt(0) !== 'r') return JSON.parse(str);
5924
+ str = str.slice(1);
5925
+
5926
+ var out = [];
5927
+ var i = 0;
5928
+ var len = str.length;
5929
+
5930
+ while (i < len) {
5931
+ var ch = str[i];
5932
+
5933
+ if (ch === "'") {
5934
+ // Single-quoted string → emit as double-quoted
5935
+ out.push('"');
5936
+ i++;
5937
+ while (i < len) {
5938
+ var c = str[i];
5939
+ if (c === '\\' && i + 1 < len) {
5940
+ var next = str[i + 1];
5941
+ if (next === "'") {
5942
+ out.push("'"); // \' in input → ' in output
5943
+ } else {
5944
+ out.push('\\');
5945
+ out.push(next);
5946
+ }
5947
+ i += 2;
5948
+ } else if (c === '"') {
5949
+ out.push('\\"');
5950
+ i++;
5951
+ } else if (c === "'") {
5952
+ break;
5953
+ } else {
5954
+ out.push(c);
5955
+ i++;
5956
+ }
5957
+ }
5958
+ out.push('"');
5959
+ i++; // skip closing '
5960
+
5961
+ } else if (ch === '"') {
5962
+ // Double-quoted string — pass through verbatim
5963
+ out.push(ch);
5964
+ i++;
5965
+ while (i < len) {
5966
+ var c2 = str[i];
5967
+ if (c2 === '\\' && i + 1 < len) {
5968
+ out.push(c2);
5969
+ out.push(str[i + 1]);
5970
+ i += 2;
5971
+ } else {
5972
+ out.push(c2);
5973
+ i++;
5974
+ if (c2 === '"') break;
5975
+ }
5976
+ }
5977
+
5978
+ } else if (ch === ',') {
5979
+ // Trailing comma check: skip comma if next non-whitespace is } or ]
5980
+ var j = i + 1;
5981
+ while (j < len && (str[j] === ' ' || str[j] === '\t' || str[j] === '\n' || str[j] === '\r')) j++;
5982
+ if (j < len && (str[j] === '}' || str[j] === ']')) {
5983
+ i++; // skip trailing comma
5984
+ } else {
5985
+ out.push(ch);
5986
+ i++;
5987
+ }
5988
+
5989
+ } else {
5990
+ out.push(ch);
5991
+ i++;
5992
+ }
5993
+ }
5994
+
5995
+ return JSON.parse(out.join(''));
5996
+ };
5997
+
5998
+ /**
5999
+ * Apply a bwserve protocol message to the DOM.
6000
+ *
6001
+ * Dispatches one of 9 message types:
6002
+ * replace — bw.DOM(target, node)
6003
+ * append — target.appendChild(bw.createDOM(node))
6004
+ * remove — bw.cleanup(target); target.remove()
6005
+ * patch — bw.patch(target, content, attr)
6006
+ * batch — iterate ops, call clientApply for each
6007
+ * message — bw.message(target, action, data)
6008
+ * register — store a named function for later call()
6009
+ * call — invoke a registered or built-in function
6010
+ * exec — execute arbitrary JS (requires allowExec)
6011
+ *
6012
+ * Target resolution:
6013
+ * Starts with '#' or '.' → CSS selector (querySelector)
6014
+ * Otherwise → getElementById, then bw._el fallback
6015
+ *
6016
+ * @param {Object} msg - Protocol message
6017
+ * @returns {boolean} true if the message was applied successfully
6018
+ * @category Server
6019
+ */
6020
+ bw.clientApply = function(msg) {
6021
+ if (!msg || !msg.type) return false;
6022
+
6023
+ var type = msg.type;
6024
+ var target = msg.target;
6025
+
6026
+ if (type === 'replace') {
6027
+ var el = bw._el(target);
6028
+ if (!el) return false;
6029
+ bw.DOM(el, msg.node);
6030
+ return true;
6031
+
6032
+ } else if (type === 'patch') {
6033
+ var patched = bw.patch(target, msg.content, msg.attr);
6034
+ return patched !== null;
6035
+
6036
+ } else if (type === 'append') {
6037
+ var parent = bw._el(target);
6038
+ if (!parent) return false;
6039
+ var child = bw.createDOM(msg.node);
6040
+ parent.appendChild(child);
6041
+ return true;
6042
+
6043
+ } else if (type === 'remove') {
6044
+ var toRemove = bw._el(target);
6045
+ if (!toRemove) return false;
6046
+ if (typeof bw.cleanup === 'function') bw.cleanup(toRemove);
6047
+ toRemove.remove();
6048
+ return true;
6049
+
6050
+ } else if (type === 'batch') {
6051
+ if (!Array.isArray(msg.ops)) return false;
6052
+ var allOk = true;
6053
+ msg.ops.forEach(function(op) {
6054
+ if (!bw.clientApply(op)) allOk = false;
6055
+ });
6056
+ return allOk;
6057
+
6058
+ } else if (type === 'message') {
6059
+ return bw.message(msg.target, msg.action, msg.data);
6060
+
6061
+ } else if (type === 'register') {
6062
+ if (!msg.name || !msg.body) return false;
6063
+ try {
6064
+ bw._clientFunctions[msg.name] = new Function('return ' + msg.body)();
6065
+ return true;
6066
+ } catch (e) {
6067
+ console.error('[bw] register error:', msg.name, e);
6068
+ return false;
6069
+ }
6070
+
6071
+ } else if (type === 'call') {
6072
+ if (!msg.name) return false;
6073
+ var fn = bw._clientFunctions[msg.name] || bw._builtinClientFunctions[msg.name];
6074
+ if (typeof fn !== 'function') return false;
6075
+ try {
6076
+ var args = Array.isArray(msg.args) ? msg.args : [];
6077
+ fn.apply(null, args);
6078
+ return true;
6079
+ } catch (e) {
6080
+ console.error('[bw] call error:', msg.name, e);
6081
+ return false;
6082
+ }
6083
+
6084
+ } else if (type === 'exec') {
6085
+ if (!bw._allowExec) {
6086
+ console.warn('[bw] exec rejected: allowExec is not enabled');
6087
+ return false;
6088
+ }
6089
+ if (!msg.code) return false;
6090
+ try {
6091
+ new Function(msg.code)();
6092
+ return true;
6093
+ } catch (e) {
6094
+ console.error('[bw] exec error:', e);
6095
+ return false;
6096
+ }
6097
+ }
6098
+
6099
+ return false;
6100
+ };
6101
+
6102
+ /**
6103
+ * Connect to a bwserve SSE endpoint and apply protocol messages automatically.
6104
+ *
6105
+ * Returns a connection object with sendAction(), on(), and close() methods.
6106
+ *
6107
+ * @param {string} url - SSE endpoint URL (e.g., '/__bw/events/client-1')
6108
+ * @param {Object} [opts] - Connection options
6109
+ * @param {string} [opts.transport='sse'] - Transport type: 'sse' (default) or 'poll'
6110
+ * @param {number} [opts.interval=2000] - Poll interval in ms (only for 'poll' transport)
6111
+ * @param {string} [opts.actionUrl] - POST endpoint for actions (default: derived from url)
6112
+ * @param {boolean} [opts.reconnect=true] - Auto-reconnect on disconnect
6113
+ * @param {boolean} [opts.allowExec=false] - Enable exec message type (arbitrary JS execution)
6114
+ * @param {Function} [opts.onStatus] - Status callback: 'connecting'|'connected'|'disconnected'
6115
+ * @param {Function} [opts.onMessage] - Raw message callback (before clientApply)
6116
+ * @returns {Object} Connection object { sendAction, on, close, status }
6117
+ * @category Server
6118
+ */
6119
+ bw.clientConnect = function(url, opts) {
6120
+ opts = opts || {};
6121
+ var transport = opts.transport || 'sse';
6122
+ var actionUrl = opts.actionUrl || url.replace(/\/events\//, '/action/');
6123
+ var reconnect = opts.reconnect !== false;
6124
+ var onStatus = opts.onStatus || function() {};
6125
+ var onMessage = opts.onMessage || null;
6126
+ var handlers = {};
6127
+ // Set the global allowExec flag from connection options
6128
+ bw._allowExec = !!opts.allowExec;
6129
+ var conn = {
6130
+ status: 'connecting',
6131
+ _es: null,
6132
+ _pollTimer: null
6133
+ };
6134
+
6135
+ function setStatus(s) {
6136
+ conn.status = s;
6137
+ onStatus(s);
6138
+ }
6139
+
6140
+ function handleMessage(data) {
6141
+ try {
6142
+ var msg = typeof data === 'string' ? bw.clientParse(data) : data;
6143
+ if (onMessage) onMessage(msg);
6144
+ if (handlers.message) handlers.message(msg);
6145
+ bw.clientApply(msg);
6146
+ } catch (e) {
6147
+ if (handlers.error) handlers.error(e);
6148
+ }
6149
+ }
6150
+
6151
+ if (transport === 'sse' && typeof EventSource !== 'undefined') {
6152
+ setStatus('connecting');
6153
+ var es = new EventSource(url);
6154
+ conn._es = es;
6155
+
6156
+ es.onopen = function() {
6157
+ setStatus('connected');
6158
+ if (handlers.open) handlers.open();
6159
+ };
6160
+
6161
+ es.onmessage = function(e) {
6162
+ handleMessage(e.data);
6163
+ };
6164
+
6165
+ es.onerror = function() {
6166
+ if (conn.status === 'connected') {
6167
+ setStatus('disconnected');
6168
+ }
6169
+ if (handlers.error) handlers.error(new Error('SSE connection error'));
6170
+ if (!reconnect) {
6171
+ es.close();
6172
+ }
6173
+ // EventSource auto-reconnects by default when reconnect=true
6174
+ };
6175
+ } else if (transport === 'poll') {
6176
+ var interval = opts.interval || 2000;
6177
+ setStatus('connected');
6178
+ conn._pollTimer = setInterval(function() {
6179
+ fetch(url).then(function(r) { return r.json(); }).then(function(msgs) {
6180
+ if (Array.isArray(msgs)) {
6181
+ msgs.forEach(handleMessage);
6182
+ } else if (msgs && msgs.type) {
6183
+ handleMessage(msgs);
6184
+ }
6185
+ }).catch(function(e) {
6186
+ if (handlers.error) handlers.error(e);
6187
+ });
6188
+ }, interval);
6189
+ }
6190
+
6191
+ /**
6192
+ * Send an action to the server via POST.
6193
+ * @param {string} action - Action name
6194
+ * @param {Object} [data] - Action payload
6195
+ */
6196
+ conn.sendAction = function(action, data) {
6197
+ var body = JSON.stringify({ type: 'action', action: action, data: data || {} });
6198
+ fetch(actionUrl, {
6199
+ method: 'POST',
6200
+ headers: { 'Content-Type': 'application/json' },
6201
+ body: body
6202
+ }).catch(function(e) {
6203
+ if (handlers.error) handlers.error(e);
6204
+ });
6205
+ };
6206
+
6207
+ /**
6208
+ * Register an event handler.
6209
+ * @param {string} event - 'open'|'message'|'error'|'close'
6210
+ * @param {Function} handler
6211
+ */
6212
+ conn.on = function(event, handler) {
6213
+ handlers[event] = handler;
6214
+ return conn;
6215
+ };
6216
+
6217
+ /**
6218
+ * Close the connection.
6219
+ */
6220
+ conn.close = function() {
6221
+ if (conn._es) {
6222
+ conn._es.close();
6223
+ conn._es = null;
6224
+ }
6225
+ if (conn._pollTimer) {
6226
+ clearInterval(conn._pollTimer);
6227
+ conn._pollTimer = null;
6228
+ }
6229
+ setStatus('disconnected');
6230
+ if (handlers.close) handlers.close();
6231
+ };
6232
+
6233
+ return conn;
6234
+ };
6235
+
5840
6236
  // ===================================================================================
5841
6237
  // bw.inspect() — Debug utility
5842
6238
  // ===================================================================================