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