@kirejs/h3 0.2.4 → 0.2.5

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/AGENT.md ADDED
@@ -0,0 +1,27 @@
1
+ # h3 + Kire — agent guide
2
+
3
+ > For AI assistants working in this package. Part of the [Kire](https://github.com/drysius/kire) monorepo — see the repository root `CLAUDE.md` for architecture and conventions.
4
+
5
+ **Package:** `@kirejs/h3`
6
+
7
+ h3 (unjs) integration returning { view, middleware }.
8
+
9
+ ## Primary API
10
+
11
+ ```ts
12
+ import { kireH3 } from "@kirejs/h3";
13
+
14
+ const { view, middleware } = kireH3({ views: "views", wire: { instance: wire } });
15
+ app.use(middleware);
16
+ app.get("/", () => view("home"));
17
+ ```
18
+
19
+ ## Notes
20
+
21
+ - Targets h3 v2 (new H3(), app.get, serve).
22
+
23
+ ## Conventions
24
+
25
+ - Bun + Biome (tabs, strict TS). Run `bun test` and `bunx biome check` before finishing.
26
+ - `noExplicitAny` is off — use `any` without `biome-ignore` suppressions.
27
+ - Keep this file and `README.md` in sync with the code.
package/README.md CHANGED
@@ -14,4 +14,17 @@ app.use(middleware);
14
14
  app.get("/", () => view("home"));
15
15
  ```
16
16
 
17
+ ### WebSocket transport (optional)
18
+
19
+ Enable with `wire.ws`. h3 doesn't own its server, so pass the Node `http.Server`
20
+ and install [`ws`](https://www.npmjs.com/package/ws); the client then connects
21
+ over WebSocket. Without a `server` it warns and stays on HTTP.
22
+
23
+ ```ts
24
+ import { createServer } from "node:http";
25
+ const server = createServer(/* your h3 handler */);
26
+ kireH3({ views: "views", wire: { instance: wire, ws: { server } } });
27
+ server.listen(3000);
28
+ ```
29
+
17
30
  > **AI agents:** see [AGENT.md](./AGENT.md) for a focused guide, and the repository root `CLAUDE.md`.
package/dist/cjs/index.js CHANGED
@@ -848,9 +848,12 @@ class Kirewire {
848
848
  features;
849
849
  broadcaster;
850
850
  constructor(opts) {
851
- if (!opts.secret)
852
- throw new Error("Kirewire requires a `secret`.");
853
- this.secret = opts.secret;
851
+ if (opts.secret) {
852
+ this.secret = opts.secret;
853
+ } else {
854
+ this.secret = import_node_crypto3.randomBytes(32).toString("hex");
855
+ console.warn("[kirewire] No `secret` provided; using a random per-process secret. " + "Set a stable `secret` in production (and across instances) so component " + "snapshots verify after restarts.");
856
+ }
854
857
  this.synth = opts.synth ?? createDefaultSynthRegistry();
855
858
  this.registry = opts.registry ?? new ComponentRegistry;
856
859
  this.features = opts.features ?? createDefaultFeatures();
@@ -1391,18 +1394,37 @@ function kirewirePlugin(kirewire, options = {}) {
1391
1394
  }
1392
1395
  const scriptUrl = options.scriptUrl ?? "/kirewire.js";
1393
1396
  const updatePath = options.path ?? "/_wire";
1397
+ const wsAttr = options.wsPath ? ` data-kirewire-ws="${options.wsPath}"` : "";
1398
+ const channelAttr = options.channel ? ` data-kirewire-channel="${options.channel}"` : "";
1394
1399
  kire.directive({
1395
1400
  name: "kirewireScripts",
1396
1401
  description: "Inject the Kirewire client runtime script tag.",
1397
1402
  example: "@kirewireScripts",
1398
1403
  onCall: (api) => {
1399
- api.append(`<script src="${scriptUrl}" data-kirewire-url="${updatePath}" defer></script>`);
1404
+ api.append(`<script src="${scriptUrl}" data-kirewire-url="${updatePath}"${wsAttr}${channelAttr} defer></script>`);
1400
1405
  }
1401
1406
  });
1402
1407
  }
1403
1408
  };
1404
1409
  }
1405
1410
 
1411
+ // packages/wire/src/server/fivem.ts
1412
+ function createFiveMHandler(kirewire, engineFactory) {
1413
+ return (data, cb) => {
1414
+ Promise.resolve(kirewire.handle(data, engineFactory?.())).then((response) => cb(response)).catch(() => cb({ v: 1, components: [] }));
1415
+ };
1416
+ }
1417
+
1418
+ class FiveMBroadcaster {
1419
+ sendNuiMessage;
1420
+ constructor(sendNuiMessage) {
1421
+ this.sendNuiMessage = sendNuiMessage;
1422
+ }
1423
+ publish(push) {
1424
+ this.sendNuiMessage(JSON.stringify({ type: "kirewire:push", push }));
1425
+ }
1426
+ }
1427
+
1406
1428
  // packages/wire/src/server/hub.ts
1407
1429
  class Hub {
1408
1430
  byChannel = new Map;
@@ -1448,23 +1470,6 @@ function serveWs(kirewire, hub, conn, options = {}) {
1448
1470
  }
1449
1471
  }
1450
1472
 
1451
- // packages/wire/src/server/fivem.ts
1452
- function createFiveMHandler(kirewire, engineFactory) {
1453
- return (data, cb) => {
1454
- Promise.resolve(kirewire.handle(data, engineFactory?.())).then((response) => cb(response)).catch(() => cb({ v: 1, components: [] }));
1455
- };
1456
- }
1457
-
1458
- class FiveMBroadcaster {
1459
- sendNuiMessage;
1460
- constructor(sendNuiMessage) {
1461
- this.sendNuiMessage = sendNuiMessage;
1462
- }
1463
- publish(push) {
1464
- this.sendNuiMessage(JSON.stringify({ type: "kirewire:push", push }));
1465
- }
1466
- }
1467
-
1468
1473
  // packages/wire/src/server/index.ts
1469
1474
  var init_server = __esm(() => {
1470
1475
  init_http();
@@ -1600,6 +1605,170 @@ __export(exports_src2, {
1600
1605
  });
1601
1606
  module.exports = __toCommonJS(exports_src2);
1602
1607
 
1608
+ // core/src/utils/regex.ts
1609
+ var NullProtoObj = function() {
1610
+ return Object.create(null);
1611
+ };
1612
+ var TAG_OPEN_REGEX = /^<([a-zA-Z0-9_\-:.]+)/;
1613
+ var TAG_CLOSE_REGEX = /^<\/([a-zA-Z0-9_\-:.]+)>/;
1614
+ var ATTR_NAME_BREAK_REGEX = /\s|=|>|\/|\(/;
1615
+ var WHITESPACE_REGEX = /\s/;
1616
+ var HTML_VOID_TAGS = new Set([
1617
+ "area",
1618
+ "base",
1619
+ "br",
1620
+ "col",
1621
+ "embed",
1622
+ "hr",
1623
+ "img",
1624
+ "input",
1625
+ "link",
1626
+ "meta",
1627
+ "param",
1628
+ "source",
1629
+ "track",
1630
+ "wbr"
1631
+ ]);
1632
+ var DIRECTIVE_NAME_REGEX = /^@([a-zA-Z0-9_\-.:]+)/;
1633
+ var JS_IDENTIFIER_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
1634
+ var INTERPOLATION_PURE_REGEX = /^\s*\{\{\s*(.*?)\s*\}\}\s*$/;
1635
+ var INTERPOLATION_GLOBAL_REGEX = /\{\{\s*(.*?)\s*\}\}/g;
1636
+ var RESERVED_KEYWORDS_REGEX = /^(?:break|case|catch|class|const|continue|debugger|default|delete|do|else|export|extends|finally|for|function|if|import|in|instanceof|new|return|super|switch|this|throw|try|typeof|var|void|while|with|yield|enum|await|true|false|null|of)$/;
1637
+ var HTML_ESCAPE_CHECK_REGEX = /[&<>"']/;
1638
+ var HTML_ESCAPE_GLOBAL_REGEX = /[&<>"']/g;
1639
+ var INTERPOLATION_START_REGEX = /{{/;
1640
+ var WILDCARD_CHAR_REGEX = /\*/;
1641
+ var AWAIT_KEYWORD_REGEX = /\bawait\b/g;
1642
+ var QUOTED_STR_CHECK_REGEX = /^['"]/;
1643
+ var STRIP_QUOTES_REGEX = /^['"]|['"]$/g;
1644
+ function createFastMatcher(list) {
1645
+ const sources = list.map((item) => {
1646
+ if (item instanceof RegExp)
1647
+ return item.source;
1648
+ if (item.includes("*")) {
1649
+ const parts = item.split("*");
1650
+ const escapedParts = parts.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`));
1651
+ return escapedParts.join(".*");
1652
+ }
1653
+ return item.replace(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`);
1654
+ });
1655
+ sources.sort((a, b) => b.length - a.length);
1656
+ return new RegExp(`(?:${sources.join("|")})`);
1657
+ }
1658
+
1659
+ // core/src/utils/html.ts
1660
+ var ESCAPE_MAP = {
1661
+ "&": "&amp;",
1662
+ "<": "&lt;",
1663
+ ">": "&gt;",
1664
+ '"': "&quot;",
1665
+ "'": "&#039;"
1666
+ };
1667
+ function escapeHtml(unsafe) {
1668
+ if (unsafe === null || unsafe === undefined)
1669
+ return "";
1670
+ const type = typeof unsafe;
1671
+ if (type === "number" || type === "boolean")
1672
+ return String(unsafe);
1673
+ if (type === "object" && typeof unsafe.toHtml === "function") {
1674
+ return unsafe.toHtml();
1675
+ }
1676
+ const s = type === "string" ? unsafe : String(unsafe);
1677
+ const n = s.length;
1678
+ if (n <= 16) {
1679
+ for (let i = 0;i < n; i++) {
1680
+ const c = s.charCodeAt(i);
1681
+ if (c === 38 || c === 60 || c === 62 || c === 34 || c === 39) {
1682
+ return s.replace(HTML_ESCAPE_GLOBAL_REGEX, (m) => ESCAPE_MAP[m]);
1683
+ }
1684
+ }
1685
+ return s;
1686
+ }
1687
+ if (!HTML_ESCAPE_CHECK_REGEX.test(s))
1688
+ return s;
1689
+ return s.replace(HTML_ESCAPE_GLOBAL_REGEX, (m) => ESCAPE_MAP[m]);
1690
+ }
1691
+
1692
+ // core/src/compiler/attr-codegen.ts
1693
+ class AttrCodegen {
1694
+ scanner;
1695
+ onAsync;
1696
+ usesEscape = false;
1697
+ mixedAttrIdents = new Set;
1698
+ interpRx = new RegExp(INTERPOLATION_GLOBAL_REGEX.source, "g");
1699
+ constructor(scanner, onAsync) {
1700
+ this.scanner = scanner;
1701
+ this.onAsync = onAsync;
1702
+ }
1703
+ reset() {
1704
+ this.usesEscape = false;
1705
+ this.mixedAttrIdents.clear();
1706
+ }
1707
+ esc(str) {
1708
+ return "`" + str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$") + "`";
1709
+ }
1710
+ escapeChunk(str) {
1711
+ return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
1712
+ }
1713
+ parseAttrCode(val) {
1714
+ if (!INTERPOLATION_START_REGEX.test(val))
1715
+ return val;
1716
+ const pureMatch = val.match(INTERPOLATION_PURE_REGEX);
1717
+ if (pureMatch)
1718
+ return pureMatch[1];
1719
+ this.usesEscape = true;
1720
+ const res = val.replace(INTERPOLATION_GLOBAL_REGEX, (_, expr) => {
1721
+ this.collectExpressionIdents(expr);
1722
+ return `\${$escape(${expr})}`;
1723
+ });
1724
+ return `\`${res}\``;
1725
+ }
1726
+ parseHtmlAttrCode(val) {
1727
+ if (!INTERPOLATION_START_REGEX.test(val))
1728
+ return this.esc(escapeHtml(val));
1729
+ const pureMatch = val.match(INTERPOLATION_PURE_REGEX);
1730
+ if (pureMatch) {
1731
+ const expr = pureMatch[1];
1732
+ if (this.scanner.containsAwait(expr))
1733
+ this.onAsync();
1734
+ this.usesEscape = true;
1735
+ return `$escape(${expr})`;
1736
+ }
1737
+ this.usesEscape = true;
1738
+ let out = "";
1739
+ let lastIndex = 0;
1740
+ const rx = this.interpRx;
1741
+ rx.lastIndex = 0;
1742
+ let match;
1743
+ while ((match = rx.exec(val)) !== null) {
1744
+ const literalChunk = val.slice(lastIndex, match.index);
1745
+ if (literalChunk)
1746
+ out += this.escapeChunk(escapeHtml(literalChunk));
1747
+ const expr = match[1] || "";
1748
+ this.collectExpressionIdents(expr);
1749
+ if (this.scanner.containsAwait(expr))
1750
+ this.onAsync();
1751
+ out += `\${$escape(${expr})}`;
1752
+ lastIndex = match.index + match[0].length;
1753
+ }
1754
+ const tail = val.slice(lastIndex);
1755
+ if (tail)
1756
+ out += this.escapeChunk(escapeHtml(tail));
1757
+ return `\`${out}\``;
1758
+ }
1759
+ collectExpressionIdents(expr) {
1760
+ const rx = /[a-zA-Z_$][a-zA-Z0-9_$]*/g;
1761
+ let m;
1762
+ while ((m = rx.exec(expr)) !== null) {
1763
+ const id = m[0];
1764
+ if (RESERVED_KEYWORDS_REGEX.test(id))
1765
+ continue;
1766
+ if (expr[m.index - 1] === ".")
1767
+ continue;
1768
+ this.mixedAttrIdents.add(id);
1769
+ }
1770
+ }
1771
+ }
1603
1772
  // core/src/lexer/balance.ts
1604
1773
  function findInterpolationEnd(template, from, close) {
1605
1774
  let inQuote = null;
@@ -1722,90 +1891,6 @@ function parseArgs(argsStr) {
1722
1891
  return args;
1723
1892
  }
1724
1893
 
1725
- // core/src/utils/regex.ts
1726
- var NullProtoObj = function() {
1727
- return Object.create(null);
1728
- };
1729
- var TAG_OPEN_REGEX = /^<([a-zA-Z0-9_\-:.]+)/;
1730
- var TAG_CLOSE_REGEX = /^<\/([a-zA-Z0-9_\-:.]+)>/;
1731
- var ATTR_NAME_BREAK_REGEX = /\s|=|>|\/|\(/;
1732
- var WHITESPACE_REGEX = /\s/;
1733
- var HTML_VOID_TAGS = new Set([
1734
- "area",
1735
- "base",
1736
- "br",
1737
- "col",
1738
- "embed",
1739
- "hr",
1740
- "img",
1741
- "input",
1742
- "link",
1743
- "meta",
1744
- "param",
1745
- "source",
1746
- "track",
1747
- "wbr"
1748
- ]);
1749
- var DIRECTIVE_NAME_REGEX = /^@([a-zA-Z0-9_\-.:]+)/;
1750
- var JS_IDENTIFIER_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
1751
- var INTERPOLATION_PURE_REGEX = /^\s*\{\{\s*(.*?)\s*\}\}\s*$/;
1752
- var INTERPOLATION_GLOBAL_REGEX = /\{\{\s*(.*?)\s*\}\}/g;
1753
- var RESERVED_KEYWORDS_REGEX = /^(?:break|case|catch|class|const|continue|debugger|default|delete|do|else|export|extends|finally|for|function|if|import|in|instanceof|new|return|super|switch|this|throw|try|typeof|var|void|while|with|yield|enum|await|true|false|null|of)$/;
1754
- var HTML_ESCAPE_CHECK_REGEX = /[&<>"']/;
1755
- var HTML_ESCAPE_GLOBAL_REGEX = /[&<>"']/g;
1756
- var INTERPOLATION_START_REGEX = /{{/;
1757
- var WILDCARD_CHAR_REGEX = /\*/;
1758
- var AWAIT_KEYWORD_REGEX = /\bawait\b/g;
1759
- var QUOTED_STR_CHECK_REGEX = /^['"]/;
1760
- var STRIP_QUOTES_REGEX = /^['"]|['"]$/g;
1761
- function createFastMatcher(list) {
1762
- const sources = list.map((item) => {
1763
- if (item instanceof RegExp)
1764
- return item.source;
1765
- if (item.includes("*")) {
1766
- const parts = item.split("*");
1767
- const escapedParts = parts.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`));
1768
- return escapedParts.join(".*");
1769
- }
1770
- return item.replace(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`);
1771
- });
1772
- sources.sort((a, b) => b.length - a.length);
1773
- return new RegExp(`(?:${sources.join("|")})`);
1774
- }
1775
-
1776
- // core/src/utils/html.ts
1777
- var ESCAPE_MAP = {
1778
- "&": "&amp;",
1779
- "<": "&lt;",
1780
- ">": "&gt;",
1781
- '"': "&quot;",
1782
- "'": "&#039;"
1783
- };
1784
- function escapeHtml(unsafe) {
1785
- if (unsafe === null || unsafe === undefined)
1786
- return "";
1787
- const type = typeof unsafe;
1788
- if (type === "number" || type === "boolean")
1789
- return String(unsafe);
1790
- if (type === "object" && typeof unsafe.toHtml === "function") {
1791
- return unsafe.toHtml();
1792
- }
1793
- const s = type === "string" ? unsafe : String(unsafe);
1794
- const n = s.length;
1795
- if (n <= 16) {
1796
- for (let i = 0;i < n; i++) {
1797
- const c = s.charCodeAt(i);
1798
- if (c === 38 || c === 60 || c === 62 || c === 34 || c === 39) {
1799
- return s.replace(HTML_ESCAPE_GLOBAL_REGEX, (m) => ESCAPE_MAP[m]);
1800
- }
1801
- }
1802
- return s;
1803
- }
1804
- if (!HTML_ESCAPE_CHECK_REGEX.test(s))
1805
- return s;
1806
- return s.replace(HTML_ESCAPE_GLOBAL_REGEX, (m) => ESCAPE_MAP[m]);
1807
- }
1808
-
1809
1894
  // core/src/utils/base64.ts
1810
1895
  function hasNodeBuffer() {
1811
1896
  return typeof Buffer !== "undefined" && typeof Buffer.from === "function";
@@ -1996,87 +2081,6 @@ function resolveSourceLocation(map, genLine, genCol) {
1996
2081
  return bestMatch;
1997
2082
  }
1998
2083
 
1999
- // core/src/compiler/attr-codegen.ts
2000
- class AttrCodegen {
2001
- scanner;
2002
- onAsync;
2003
- usesEscape = false;
2004
- mixedAttrIdents = new Set;
2005
- interpRx = new RegExp(INTERPOLATION_GLOBAL_REGEX.source, "g");
2006
- constructor(scanner, onAsync) {
2007
- this.scanner = scanner;
2008
- this.onAsync = onAsync;
2009
- }
2010
- reset() {
2011
- this.usesEscape = false;
2012
- this.mixedAttrIdents.clear();
2013
- }
2014
- esc(str) {
2015
- return "`" + str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$") + "`";
2016
- }
2017
- escapeChunk(str) {
2018
- return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
2019
- }
2020
- parseAttrCode(val) {
2021
- if (!INTERPOLATION_START_REGEX.test(val))
2022
- return val;
2023
- const pureMatch = val.match(INTERPOLATION_PURE_REGEX);
2024
- if (pureMatch)
2025
- return pureMatch[1];
2026
- this.usesEscape = true;
2027
- const res = val.replace(INTERPOLATION_GLOBAL_REGEX, (_, expr) => {
2028
- this.collectExpressionIdents(expr);
2029
- return `\${$escape(${expr})}`;
2030
- });
2031
- return "`" + res + "`";
2032
- }
2033
- parseHtmlAttrCode(val) {
2034
- if (!INTERPOLATION_START_REGEX.test(val))
2035
- return this.esc(escapeHtml(val));
2036
- const pureMatch = val.match(INTERPOLATION_PURE_REGEX);
2037
- if (pureMatch) {
2038
- const expr = pureMatch[1];
2039
- if (this.scanner.containsAwait(expr))
2040
- this.onAsync();
2041
- this.usesEscape = true;
2042
- return `$escape(${expr})`;
2043
- }
2044
- this.usesEscape = true;
2045
- let out = "";
2046
- let lastIndex = 0;
2047
- const rx = this.interpRx;
2048
- rx.lastIndex = 0;
2049
- let match;
2050
- while ((match = rx.exec(val)) !== null) {
2051
- const literalChunk = val.slice(lastIndex, match.index);
2052
- if (literalChunk)
2053
- out += this.escapeChunk(escapeHtml(literalChunk));
2054
- const expr = match[1] || "";
2055
- this.collectExpressionIdents(expr);
2056
- if (this.scanner.containsAwait(expr))
2057
- this.onAsync();
2058
- out += `\${$escape(${expr})}`;
2059
- lastIndex = match.index + match[0].length;
2060
- }
2061
- const tail = val.slice(lastIndex);
2062
- if (tail)
2063
- out += this.escapeChunk(escapeHtml(tail));
2064
- return "`" + out + "`";
2065
- }
2066
- collectExpressionIdents(expr) {
2067
- const rx = /[a-zA-Z_$][a-zA-Z0-9_$]*/g;
2068
- let m;
2069
- while ((m = rx.exec(expr)) !== null) {
2070
- const id = m[0];
2071
- if (RESERVED_KEYWORDS_REGEX.test(id))
2072
- continue;
2073
- if (expr[m.index - 1] === ".")
2074
- continue;
2075
- this.mixedAttrIdents.add(id);
2076
- }
2077
- }
2078
- }
2079
-
2080
2084
  // core/src/compiler/js-scanner.ts
2081
2085
  class JsScanner {
2082
2086
  containsAwait(code) {
@@ -4417,7 +4421,14 @@ var checks_default = (kire) => {
4417
4421
  signature: [`expr:any`],
4418
4422
  children: true,
4419
4423
  relatedTo: [`for`, `each`, `foreach`, `forelse`],
4420
- closeBy: [`endempty`, `endfor`, `endeach`, `endforeach`, `endforelse`, `end`],
4424
+ closeBy: [
4425
+ `endempty`,
4426
+ `endfor`,
4427
+ `endeach`,
4428
+ `endforeach`,
4429
+ `endforelse`,
4430
+ `end`
4431
+ ],
4421
4432
  description: "Fallback branch for empty collections or falsy values, often used alongside @for or @each.",
4422
4433
  example: `@empty(items)
4423
4434
  <p>No items</p>
@@ -4633,7 +4644,6 @@ var loop_default = (kire) => {
4633
4644
  const id = api.uid("fe");
4634
4645
  const relatedNodes = api.node.related || [];
4635
4646
  const hasEmptyBranch = relatedNodes.some((n) => n?.name === "empty");
4636
- const exposeKey = key ? true : api.fullBody.includes("$loop") || api.allIdentifiers.has("$loop");
4637
4647
  const exposeLoop = api.fullBody.includes("$loop") || api.allIdentifiers.has("$loop");
4638
4648
  api.write(`{
4639
4649
  const _src${id} = ${source};
@@ -5057,7 +5067,6 @@ var KireDirectives = {
5057
5067
  natives_default(kire);
5058
5068
  }
5059
5069
  };
5060
-
5061
5070
  // core/src/lexer/cursor.ts
5062
5071
  class Cursor {
5063
5072
  template;
@@ -5121,7 +5130,6 @@ class Cursor {
5121
5130
  this.column = this.baseColumn;
5122
5131
  }
5123
5132
  }
5124
-
5125
5133
  // core/src/lexer/lexer.ts
5126
5134
  class Lexer extends Cursor {
5127
5135
  kire;
@@ -5391,7 +5399,13 @@ class Lexer extends Cursor {
5391
5399
  this.reportError(hasOpenDirective ? `@${rawName} does not close the current block` : `@${rawName} has no matching opening directive`, this.cursor, this.cursor + rawName.length + 1, loc);
5392
5400
  }
5393
5401
  this.advance(rawName.length + 1);
5394
- this.addNode({ type: "directive", name: rawName, args: [], children: [], loc });
5402
+ this.addNode({
5403
+ type: "directive",
5404
+ name: rawName,
5405
+ args: [],
5406
+ children: [],
5407
+ loc
5408
+ });
5395
5409
  return true;
5396
5410
  }
5397
5411
  const name = matchedName;
@@ -5680,7 +5694,11 @@ class Lexer extends Cursor {
5680
5694
  end++;
5681
5695
  }
5682
5696
  if (end > this.cursor) {
5683
- this.addNode({ type: "text", content: this.slice(this.cursor, end), loc });
5697
+ this.addNode({
5698
+ type: "text",
5699
+ content: this.slice(this.cursor, end),
5700
+ loc
5701
+ });
5684
5702
  this.advance(end - this.cursor);
5685
5703
  } else {
5686
5704
  this.addNode({ type: "text", content: this.char(), loc });
@@ -5731,29 +5749,6 @@ function createKireFunction(_kire, execute, meta) {
5731
5749
  return fn;
5732
5750
  }
5733
5751
 
5734
- // core/src/utils/browser.ts
5735
- var throwNoAPI = (name) => {
5736
- return () => {
5737
- throw new Error(`Platform API '${name}' is not available in browser. Provide it via store or use virtual files.`);
5738
- };
5739
- };
5740
- var platform = {
5741
- readFile: throwNoAPI("readFile"),
5742
- exists: () => false,
5743
- readDir: throwNoAPI("readDir"),
5744
- stat: throwNoAPI("stat"),
5745
- writeFile: throwNoAPI("writeFile"),
5746
- resolve: (...args) => args.join("/").replace(/\/+/g, "/"),
5747
- join: (...args) => args.join("/").replace(/\/+/g, "/"),
5748
- isAbsolute: (path) => path.startsWith("/") || path.startsWith("http"),
5749
- relative: (_from, to) => to,
5750
- cwd: () => "/",
5751
- env: (_key) => {
5752
- return;
5753
- },
5754
- isProd: () => false
5755
- };
5756
-
5757
5752
  // core/src/utils/attributes-bag.ts
5758
5753
  function classString(input) {
5759
5754
  if (input == null || input === false)
@@ -5891,6 +5886,29 @@ function createAttributes(attrs = {}) {
5891
5886
  return new KireAttributes(attrs);
5892
5887
  }
5893
5888
 
5889
+ // core/src/utils/browser.ts
5890
+ var throwNoAPI = (name) => {
5891
+ return () => {
5892
+ throw new Error(`Platform API '${name}' is not available in browser. Provide it via store or use virtual files.`);
5893
+ };
5894
+ };
5895
+ var platform = {
5896
+ readFile: throwNoAPI("readFile"),
5897
+ exists: () => false,
5898
+ readDir: throwNoAPI("readDir"),
5899
+ stat: throwNoAPI("stat"),
5900
+ writeFile: throwNoAPI("writeFile"),
5901
+ resolve: (...args) => args.join("/").replace(/\/+/g, "/"),
5902
+ join: (...args) => args.join("/").replace(/\/+/g, "/"),
5903
+ isAbsolute: (path) => path.startsWith("/") || path.startsWith("http"),
5904
+ relative: (_from, to) => to,
5905
+ cwd: () => "/",
5906
+ env: (_key) => {
5907
+ return;
5908
+ },
5909
+ isProd: () => false
5910
+ };
5911
+
5894
5912
  // core/src/utils/error.ts
5895
5913
  var SOURCE_MAP_PREFIX = "//# sourceMappingURL=data:application/json;charset=utf-8;base64,";
5896
5914
  var STACK_FRAME_REGEX = /^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?$/;
@@ -7130,7 +7148,14 @@ function prepareInlineWire(engine, wire) {
7130
7148
  const wirePkg = requireWire();
7131
7149
  const wirePath = wire.path ?? "/_wire";
7132
7150
  const scriptUrl = wire.scriptUrl ?? "/kirewire.js";
7133
- engine.plugin(wirePkg.kirewirePlugin(wire.instance, { scriptUrl, path: wirePath }));
7151
+ const ws = resolveWs(wire);
7152
+ const wsActive = ws ? attachNodeWs(wirePkg, wire.instance, ws) : false;
7153
+ engine.plugin(wirePkg.kirewirePlugin(wire.instance, {
7154
+ scriptUrl,
7155
+ path: wirePath,
7156
+ wsPath: wsActive ? ws.path : undefined,
7157
+ channel: wsActive ? ws.channel : undefined
7158
+ }));
7134
7159
  const clientScript = resolveClientScript(wire);
7135
7160
  return (event) => {
7136
7161
  const method = event.req.method;
@@ -7149,6 +7174,39 @@ function prepareInlineWire(engine, wire) {
7149
7174
  return null;
7150
7175
  };
7151
7176
  }
7177
+ function resolveWs(wire) {
7178
+ if (!wire.ws)
7179
+ return null;
7180
+ const ws = wire.ws === true ? {} : wire.ws;
7181
+ return {
7182
+ path: ws.path ?? "/_wire/ws",
7183
+ channel: ws.channel,
7184
+ server: ws.server,
7185
+ hub: ws.hub
7186
+ };
7187
+ }
7188
+ function attachNodeWs(wirePkg, instance, ws) {
7189
+ if (!ws.server) {
7190
+ console.warn("[@kirejs/h3] wire.ws is enabled but no `server` was provided; " + "pass the http.Server (e.g. from app.listen or http.createServer(app)). " + "Falling back to the HTTP transport.");
7191
+ return false;
7192
+ }
7193
+ let WebSocketServer;
7194
+ try {
7195
+ ({ WebSocketServer } = require("ws"));
7196
+ } catch {
7197
+ throw new Error("@kirejs/h3: wire.ws requires the `ws` package to be installed.");
7198
+ }
7199
+ const hub = ws.hub ?? new wirePkg.Hub;
7200
+ const wss = new WebSocketServer({ server: ws.server, path: ws.path });
7201
+ wss.on("connection", (socket) => {
7202
+ wirePkg.serveWs(instance, hub, {
7203
+ send: (data) => socket.send(data),
7204
+ onMessage: (cb) => socket.on("message", (d) => cb(d.toString())),
7205
+ onClose: (cb) => socket.on("close", cb)
7206
+ }, { channel: ws.channel });
7207
+ });
7208
+ return true;
7209
+ }
7152
7210
  function requireWire() {
7153
7211
  try {
7154
7212
  return init_src(), __toCommonJS(exports_src);
package/dist/esm/index.js CHANGED
@@ -831,7 +831,7 @@ var init_builtins = __esm(() => {
831
831
  });
832
832
 
833
833
  // packages/wire/src/kirewire.ts
834
- import { randomUUID as randomUUID2 } from "node:crypto";
834
+ import { randomBytes, randomUUID as randomUUID2 } from "node:crypto";
835
835
  function serializeSnapshotAttr(snapshot) {
836
836
  return JSON.stringify(snapshot).replace(/&/g, "&amp;").replace(/'/g, "&#39;");
837
837
  }
@@ -850,9 +850,12 @@ class Kirewire {
850
850
  features;
851
851
  broadcaster;
852
852
  constructor(opts) {
853
- if (!opts.secret)
854
- throw new Error("Kirewire requires a `secret`.");
855
- this.secret = opts.secret;
853
+ if (opts.secret) {
854
+ this.secret = opts.secret;
855
+ } else {
856
+ this.secret = randomBytes(32).toString("hex");
857
+ console.warn("[kirewire] No `secret` provided; using a random per-process secret. " + "Set a stable `secret` in production (and across instances) so component " + "snapshots verify after restarts.");
858
+ }
856
859
  this.synth = opts.synth ?? createDefaultSynthRegistry();
857
860
  this.registry = opts.registry ?? new ComponentRegistry;
858
861
  this.features = opts.features ?? createDefaultFeatures();
@@ -1392,18 +1395,37 @@ function kirewirePlugin(kirewire, options = {}) {
1392
1395
  }
1393
1396
  const scriptUrl = options.scriptUrl ?? "/kirewire.js";
1394
1397
  const updatePath = options.path ?? "/_wire";
1398
+ const wsAttr = options.wsPath ? ` data-kirewire-ws="${options.wsPath}"` : "";
1399
+ const channelAttr = options.channel ? ` data-kirewire-channel="${options.channel}"` : "";
1395
1400
  kire.directive({
1396
1401
  name: "kirewireScripts",
1397
1402
  description: "Inject the Kirewire client runtime script tag.",
1398
1403
  example: "@kirewireScripts",
1399
1404
  onCall: (api) => {
1400
- api.append(`<script src="${scriptUrl}" data-kirewire-url="${updatePath}" defer></script>`);
1405
+ api.append(`<script src="${scriptUrl}" data-kirewire-url="${updatePath}"${wsAttr}${channelAttr} defer></script>`);
1401
1406
  }
1402
1407
  });
1403
1408
  }
1404
1409
  };
1405
1410
  }
1406
1411
 
1412
+ // packages/wire/src/server/fivem.ts
1413
+ function createFiveMHandler(kirewire, engineFactory) {
1414
+ return (data, cb) => {
1415
+ Promise.resolve(kirewire.handle(data, engineFactory?.())).then((response) => cb(response)).catch(() => cb({ v: 1, components: [] }));
1416
+ };
1417
+ }
1418
+
1419
+ class FiveMBroadcaster {
1420
+ sendNuiMessage;
1421
+ constructor(sendNuiMessage) {
1422
+ this.sendNuiMessage = sendNuiMessage;
1423
+ }
1424
+ publish(push) {
1425
+ this.sendNuiMessage(JSON.stringify({ type: "kirewire:push", push }));
1426
+ }
1427
+ }
1428
+
1407
1429
  // packages/wire/src/server/hub.ts
1408
1430
  class Hub {
1409
1431
  byChannel = new Map;
@@ -1449,23 +1471,6 @@ function serveWs(kirewire, hub, conn, options = {}) {
1449
1471
  }
1450
1472
  }
1451
1473
 
1452
- // packages/wire/src/server/fivem.ts
1453
- function createFiveMHandler(kirewire, engineFactory) {
1454
- return (data, cb) => {
1455
- Promise.resolve(kirewire.handle(data, engineFactory?.())).then((response) => cb(response)).catch(() => cb({ v: 1, components: [] }));
1456
- };
1457
- }
1458
-
1459
- class FiveMBroadcaster {
1460
- sendNuiMessage;
1461
- constructor(sendNuiMessage) {
1462
- this.sendNuiMessage = sendNuiMessage;
1463
- }
1464
- publish(push) {
1465
- this.sendNuiMessage(JSON.stringify({ type: "kirewire:push", push }));
1466
- }
1467
- }
1468
-
1469
1474
  // packages/wire/src/server/index.ts
1470
1475
  var init_server = __esm(() => {
1471
1476
  init_http();
@@ -1594,6 +1599,170 @@ var init_src = __esm(() => {
1594
1599
  init_class();
1595
1600
  });
1596
1601
 
1602
+ // core/src/utils/regex.ts
1603
+ var NullProtoObj = function() {
1604
+ return Object.create(null);
1605
+ };
1606
+ var TAG_OPEN_REGEX = /^<([a-zA-Z0-9_\-:.]+)/;
1607
+ var TAG_CLOSE_REGEX = /^<\/([a-zA-Z0-9_\-:.]+)>/;
1608
+ var ATTR_NAME_BREAK_REGEX = /\s|=|>|\/|\(/;
1609
+ var WHITESPACE_REGEX = /\s/;
1610
+ var HTML_VOID_TAGS = new Set([
1611
+ "area",
1612
+ "base",
1613
+ "br",
1614
+ "col",
1615
+ "embed",
1616
+ "hr",
1617
+ "img",
1618
+ "input",
1619
+ "link",
1620
+ "meta",
1621
+ "param",
1622
+ "source",
1623
+ "track",
1624
+ "wbr"
1625
+ ]);
1626
+ var DIRECTIVE_NAME_REGEX = /^@([a-zA-Z0-9_\-.:]+)/;
1627
+ var JS_IDENTIFIER_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
1628
+ var INTERPOLATION_PURE_REGEX = /^\s*\{\{\s*(.*?)\s*\}\}\s*$/;
1629
+ var INTERPOLATION_GLOBAL_REGEX = /\{\{\s*(.*?)\s*\}\}/g;
1630
+ var RESERVED_KEYWORDS_REGEX = /^(?:break|case|catch|class|const|continue|debugger|default|delete|do|else|export|extends|finally|for|function|if|import|in|instanceof|new|return|super|switch|this|throw|try|typeof|var|void|while|with|yield|enum|await|true|false|null|of)$/;
1631
+ var HTML_ESCAPE_CHECK_REGEX = /[&<>"']/;
1632
+ var HTML_ESCAPE_GLOBAL_REGEX = /[&<>"']/g;
1633
+ var INTERPOLATION_START_REGEX = /{{/;
1634
+ var WILDCARD_CHAR_REGEX = /\*/;
1635
+ var AWAIT_KEYWORD_REGEX = /\bawait\b/g;
1636
+ var QUOTED_STR_CHECK_REGEX = /^['"]/;
1637
+ var STRIP_QUOTES_REGEX = /^['"]|['"]$/g;
1638
+ function createFastMatcher(list) {
1639
+ const sources = list.map((item) => {
1640
+ if (item instanceof RegExp)
1641
+ return item.source;
1642
+ if (item.includes("*")) {
1643
+ const parts = item.split("*");
1644
+ const escapedParts = parts.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`));
1645
+ return escapedParts.join(".*");
1646
+ }
1647
+ return item.replace(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`);
1648
+ });
1649
+ sources.sort((a, b) => b.length - a.length);
1650
+ return new RegExp(`(?:${sources.join("|")})`);
1651
+ }
1652
+
1653
+ // core/src/utils/html.ts
1654
+ var ESCAPE_MAP = {
1655
+ "&": "&amp;",
1656
+ "<": "&lt;",
1657
+ ">": "&gt;",
1658
+ '"': "&quot;",
1659
+ "'": "&#039;"
1660
+ };
1661
+ function escapeHtml(unsafe) {
1662
+ if (unsafe === null || unsafe === undefined)
1663
+ return "";
1664
+ const type = typeof unsafe;
1665
+ if (type === "number" || type === "boolean")
1666
+ return String(unsafe);
1667
+ if (type === "object" && typeof unsafe.toHtml === "function") {
1668
+ return unsafe.toHtml();
1669
+ }
1670
+ const s = type === "string" ? unsafe : String(unsafe);
1671
+ const n = s.length;
1672
+ if (n <= 16) {
1673
+ for (let i = 0;i < n; i++) {
1674
+ const c = s.charCodeAt(i);
1675
+ if (c === 38 || c === 60 || c === 62 || c === 34 || c === 39) {
1676
+ return s.replace(HTML_ESCAPE_GLOBAL_REGEX, (m) => ESCAPE_MAP[m]);
1677
+ }
1678
+ }
1679
+ return s;
1680
+ }
1681
+ if (!HTML_ESCAPE_CHECK_REGEX.test(s))
1682
+ return s;
1683
+ return s.replace(HTML_ESCAPE_GLOBAL_REGEX, (m) => ESCAPE_MAP[m]);
1684
+ }
1685
+
1686
+ // core/src/compiler/attr-codegen.ts
1687
+ class AttrCodegen {
1688
+ scanner;
1689
+ onAsync;
1690
+ usesEscape = false;
1691
+ mixedAttrIdents = new Set;
1692
+ interpRx = new RegExp(INTERPOLATION_GLOBAL_REGEX.source, "g");
1693
+ constructor(scanner, onAsync) {
1694
+ this.scanner = scanner;
1695
+ this.onAsync = onAsync;
1696
+ }
1697
+ reset() {
1698
+ this.usesEscape = false;
1699
+ this.mixedAttrIdents.clear();
1700
+ }
1701
+ esc(str) {
1702
+ return "`" + str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$") + "`";
1703
+ }
1704
+ escapeChunk(str) {
1705
+ return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
1706
+ }
1707
+ parseAttrCode(val) {
1708
+ if (!INTERPOLATION_START_REGEX.test(val))
1709
+ return val;
1710
+ const pureMatch = val.match(INTERPOLATION_PURE_REGEX);
1711
+ if (pureMatch)
1712
+ return pureMatch[1];
1713
+ this.usesEscape = true;
1714
+ const res = val.replace(INTERPOLATION_GLOBAL_REGEX, (_, expr) => {
1715
+ this.collectExpressionIdents(expr);
1716
+ return `\${$escape(${expr})}`;
1717
+ });
1718
+ return `\`${res}\``;
1719
+ }
1720
+ parseHtmlAttrCode(val) {
1721
+ if (!INTERPOLATION_START_REGEX.test(val))
1722
+ return this.esc(escapeHtml(val));
1723
+ const pureMatch = val.match(INTERPOLATION_PURE_REGEX);
1724
+ if (pureMatch) {
1725
+ const expr = pureMatch[1];
1726
+ if (this.scanner.containsAwait(expr))
1727
+ this.onAsync();
1728
+ this.usesEscape = true;
1729
+ return `$escape(${expr})`;
1730
+ }
1731
+ this.usesEscape = true;
1732
+ let out = "";
1733
+ let lastIndex = 0;
1734
+ const rx = this.interpRx;
1735
+ rx.lastIndex = 0;
1736
+ let match;
1737
+ while ((match = rx.exec(val)) !== null) {
1738
+ const literalChunk = val.slice(lastIndex, match.index);
1739
+ if (literalChunk)
1740
+ out += this.escapeChunk(escapeHtml(literalChunk));
1741
+ const expr = match[1] || "";
1742
+ this.collectExpressionIdents(expr);
1743
+ if (this.scanner.containsAwait(expr))
1744
+ this.onAsync();
1745
+ out += `\${$escape(${expr})}`;
1746
+ lastIndex = match.index + match[0].length;
1747
+ }
1748
+ const tail = val.slice(lastIndex);
1749
+ if (tail)
1750
+ out += this.escapeChunk(escapeHtml(tail));
1751
+ return `\`${out}\``;
1752
+ }
1753
+ collectExpressionIdents(expr) {
1754
+ const rx = /[a-zA-Z_$][a-zA-Z0-9_$]*/g;
1755
+ let m;
1756
+ while ((m = rx.exec(expr)) !== null) {
1757
+ const id = m[0];
1758
+ if (RESERVED_KEYWORDS_REGEX.test(id))
1759
+ continue;
1760
+ if (expr[m.index - 1] === ".")
1761
+ continue;
1762
+ this.mixedAttrIdents.add(id);
1763
+ }
1764
+ }
1765
+ }
1597
1766
  // core/src/lexer/balance.ts
1598
1767
  function findInterpolationEnd(template, from, close) {
1599
1768
  let inQuote = null;
@@ -1716,90 +1885,6 @@ function parseArgs(argsStr) {
1716
1885
  return args;
1717
1886
  }
1718
1887
 
1719
- // core/src/utils/regex.ts
1720
- var NullProtoObj = function() {
1721
- return Object.create(null);
1722
- };
1723
- var TAG_OPEN_REGEX = /^<([a-zA-Z0-9_\-:.]+)/;
1724
- var TAG_CLOSE_REGEX = /^<\/([a-zA-Z0-9_\-:.]+)>/;
1725
- var ATTR_NAME_BREAK_REGEX = /\s|=|>|\/|\(/;
1726
- var WHITESPACE_REGEX = /\s/;
1727
- var HTML_VOID_TAGS = new Set([
1728
- "area",
1729
- "base",
1730
- "br",
1731
- "col",
1732
- "embed",
1733
- "hr",
1734
- "img",
1735
- "input",
1736
- "link",
1737
- "meta",
1738
- "param",
1739
- "source",
1740
- "track",
1741
- "wbr"
1742
- ]);
1743
- var DIRECTIVE_NAME_REGEX = /^@([a-zA-Z0-9_\-.:]+)/;
1744
- var JS_IDENTIFIER_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
1745
- var INTERPOLATION_PURE_REGEX = /^\s*\{\{\s*(.*?)\s*\}\}\s*$/;
1746
- var INTERPOLATION_GLOBAL_REGEX = /\{\{\s*(.*?)\s*\}\}/g;
1747
- var RESERVED_KEYWORDS_REGEX = /^(?:break|case|catch|class|const|continue|debugger|default|delete|do|else|export|extends|finally|for|function|if|import|in|instanceof|new|return|super|switch|this|throw|try|typeof|var|void|while|with|yield|enum|await|true|false|null|of)$/;
1748
- var HTML_ESCAPE_CHECK_REGEX = /[&<>"']/;
1749
- var HTML_ESCAPE_GLOBAL_REGEX = /[&<>"']/g;
1750
- var INTERPOLATION_START_REGEX = /{{/;
1751
- var WILDCARD_CHAR_REGEX = /\*/;
1752
- var AWAIT_KEYWORD_REGEX = /\bawait\b/g;
1753
- var QUOTED_STR_CHECK_REGEX = /^['"]/;
1754
- var STRIP_QUOTES_REGEX = /^['"]|['"]$/g;
1755
- function createFastMatcher(list) {
1756
- const sources = list.map((item) => {
1757
- if (item instanceof RegExp)
1758
- return item.source;
1759
- if (item.includes("*")) {
1760
- const parts = item.split("*");
1761
- const escapedParts = parts.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`));
1762
- return escapedParts.join(".*");
1763
- }
1764
- return item.replace(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`);
1765
- });
1766
- sources.sort((a, b) => b.length - a.length);
1767
- return new RegExp(`(?:${sources.join("|")})`);
1768
- }
1769
-
1770
- // core/src/utils/html.ts
1771
- var ESCAPE_MAP = {
1772
- "&": "&amp;",
1773
- "<": "&lt;",
1774
- ">": "&gt;",
1775
- '"': "&quot;",
1776
- "'": "&#039;"
1777
- };
1778
- function escapeHtml(unsafe) {
1779
- if (unsafe === null || unsafe === undefined)
1780
- return "";
1781
- const type = typeof unsafe;
1782
- if (type === "number" || type === "boolean")
1783
- return String(unsafe);
1784
- if (type === "object" && typeof unsafe.toHtml === "function") {
1785
- return unsafe.toHtml();
1786
- }
1787
- const s = type === "string" ? unsafe : String(unsafe);
1788
- const n = s.length;
1789
- if (n <= 16) {
1790
- for (let i = 0;i < n; i++) {
1791
- const c = s.charCodeAt(i);
1792
- if (c === 38 || c === 60 || c === 62 || c === 34 || c === 39) {
1793
- return s.replace(HTML_ESCAPE_GLOBAL_REGEX, (m) => ESCAPE_MAP[m]);
1794
- }
1795
- }
1796
- return s;
1797
- }
1798
- if (!HTML_ESCAPE_CHECK_REGEX.test(s))
1799
- return s;
1800
- return s.replace(HTML_ESCAPE_GLOBAL_REGEX, (m) => ESCAPE_MAP[m]);
1801
- }
1802
-
1803
1888
  // core/src/utils/base64.ts
1804
1889
  function hasNodeBuffer() {
1805
1890
  return typeof Buffer !== "undefined" && typeof Buffer.from === "function";
@@ -1990,87 +2075,6 @@ function resolveSourceLocation(map, genLine, genCol) {
1990
2075
  return bestMatch;
1991
2076
  }
1992
2077
 
1993
- // core/src/compiler/attr-codegen.ts
1994
- class AttrCodegen {
1995
- scanner;
1996
- onAsync;
1997
- usesEscape = false;
1998
- mixedAttrIdents = new Set;
1999
- interpRx = new RegExp(INTERPOLATION_GLOBAL_REGEX.source, "g");
2000
- constructor(scanner, onAsync) {
2001
- this.scanner = scanner;
2002
- this.onAsync = onAsync;
2003
- }
2004
- reset() {
2005
- this.usesEscape = false;
2006
- this.mixedAttrIdents.clear();
2007
- }
2008
- esc(str) {
2009
- return "`" + str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$") + "`";
2010
- }
2011
- escapeChunk(str) {
2012
- return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
2013
- }
2014
- parseAttrCode(val) {
2015
- if (!INTERPOLATION_START_REGEX.test(val))
2016
- return val;
2017
- const pureMatch = val.match(INTERPOLATION_PURE_REGEX);
2018
- if (pureMatch)
2019
- return pureMatch[1];
2020
- this.usesEscape = true;
2021
- const res = val.replace(INTERPOLATION_GLOBAL_REGEX, (_, expr) => {
2022
- this.collectExpressionIdents(expr);
2023
- return `\${$escape(${expr})}`;
2024
- });
2025
- return "`" + res + "`";
2026
- }
2027
- parseHtmlAttrCode(val) {
2028
- if (!INTERPOLATION_START_REGEX.test(val))
2029
- return this.esc(escapeHtml(val));
2030
- const pureMatch = val.match(INTERPOLATION_PURE_REGEX);
2031
- if (pureMatch) {
2032
- const expr = pureMatch[1];
2033
- if (this.scanner.containsAwait(expr))
2034
- this.onAsync();
2035
- this.usesEscape = true;
2036
- return `$escape(${expr})`;
2037
- }
2038
- this.usesEscape = true;
2039
- let out = "";
2040
- let lastIndex = 0;
2041
- const rx = this.interpRx;
2042
- rx.lastIndex = 0;
2043
- let match;
2044
- while ((match = rx.exec(val)) !== null) {
2045
- const literalChunk = val.slice(lastIndex, match.index);
2046
- if (literalChunk)
2047
- out += this.escapeChunk(escapeHtml(literalChunk));
2048
- const expr = match[1] || "";
2049
- this.collectExpressionIdents(expr);
2050
- if (this.scanner.containsAwait(expr))
2051
- this.onAsync();
2052
- out += `\${$escape(${expr})}`;
2053
- lastIndex = match.index + match[0].length;
2054
- }
2055
- const tail = val.slice(lastIndex);
2056
- if (tail)
2057
- out += this.escapeChunk(escapeHtml(tail));
2058
- return "`" + out + "`";
2059
- }
2060
- collectExpressionIdents(expr) {
2061
- const rx = /[a-zA-Z_$][a-zA-Z0-9_$]*/g;
2062
- let m;
2063
- while ((m = rx.exec(expr)) !== null) {
2064
- const id = m[0];
2065
- if (RESERVED_KEYWORDS_REGEX.test(id))
2066
- continue;
2067
- if (expr[m.index - 1] === ".")
2068
- continue;
2069
- this.mixedAttrIdents.add(id);
2070
- }
2071
- }
2072
- }
2073
-
2074
2078
  // core/src/compiler/js-scanner.ts
2075
2079
  class JsScanner {
2076
2080
  containsAwait(code) {
@@ -4411,7 +4415,14 @@ var checks_default = (kire) => {
4411
4415
  signature: [`expr:any`],
4412
4416
  children: true,
4413
4417
  relatedTo: [`for`, `each`, `foreach`, `forelse`],
4414
- closeBy: [`endempty`, `endfor`, `endeach`, `endforeach`, `endforelse`, `end`],
4418
+ closeBy: [
4419
+ `endempty`,
4420
+ `endfor`,
4421
+ `endeach`,
4422
+ `endforeach`,
4423
+ `endforelse`,
4424
+ `end`
4425
+ ],
4415
4426
  description: "Fallback branch for empty collections or falsy values, often used alongside @for or @each.",
4416
4427
  example: `@empty(items)
4417
4428
  <p>No items</p>
@@ -4627,7 +4638,6 @@ var loop_default = (kire) => {
4627
4638
  const id = api.uid("fe");
4628
4639
  const relatedNodes = api.node.related || [];
4629
4640
  const hasEmptyBranch = relatedNodes.some((n) => n?.name === "empty");
4630
- const exposeKey = key ? true : api.fullBody.includes("$loop") || api.allIdentifiers.has("$loop");
4631
4641
  const exposeLoop = api.fullBody.includes("$loop") || api.allIdentifiers.has("$loop");
4632
4642
  api.write(`{
4633
4643
  const _src${id} = ${source};
@@ -5051,7 +5061,6 @@ var KireDirectives = {
5051
5061
  natives_default(kire);
5052
5062
  }
5053
5063
  };
5054
-
5055
5064
  // core/src/lexer/cursor.ts
5056
5065
  class Cursor {
5057
5066
  template;
@@ -5115,7 +5124,6 @@ class Cursor {
5115
5124
  this.column = this.baseColumn;
5116
5125
  }
5117
5126
  }
5118
-
5119
5127
  // core/src/lexer/lexer.ts
5120
5128
  class Lexer extends Cursor {
5121
5129
  kire;
@@ -5385,7 +5393,13 @@ class Lexer extends Cursor {
5385
5393
  this.reportError(hasOpenDirective ? `@${rawName} does not close the current block` : `@${rawName} has no matching opening directive`, this.cursor, this.cursor + rawName.length + 1, loc);
5386
5394
  }
5387
5395
  this.advance(rawName.length + 1);
5388
- this.addNode({ type: "directive", name: rawName, args: [], children: [], loc });
5396
+ this.addNode({
5397
+ type: "directive",
5398
+ name: rawName,
5399
+ args: [],
5400
+ children: [],
5401
+ loc
5402
+ });
5389
5403
  return true;
5390
5404
  }
5391
5405
  const name = matchedName;
@@ -5674,7 +5688,11 @@ class Lexer extends Cursor {
5674
5688
  end++;
5675
5689
  }
5676
5690
  if (end > this.cursor) {
5677
- this.addNode({ type: "text", content: this.slice(this.cursor, end), loc });
5691
+ this.addNode({
5692
+ type: "text",
5693
+ content: this.slice(this.cursor, end),
5694
+ loc
5695
+ });
5678
5696
  this.advance(end - this.cursor);
5679
5697
  } else {
5680
5698
  this.addNode({ type: "text", content: this.char(), loc });
@@ -5725,29 +5743,6 @@ function createKireFunction(_kire, execute, meta) {
5725
5743
  return fn;
5726
5744
  }
5727
5745
 
5728
- // core/src/utils/browser.ts
5729
- var throwNoAPI = (name) => {
5730
- return () => {
5731
- throw new Error(`Platform API '${name}' is not available in browser. Provide it via store or use virtual files.`);
5732
- };
5733
- };
5734
- var platform = {
5735
- readFile: throwNoAPI("readFile"),
5736
- exists: () => false,
5737
- readDir: throwNoAPI("readDir"),
5738
- stat: throwNoAPI("stat"),
5739
- writeFile: throwNoAPI("writeFile"),
5740
- resolve: (...args) => args.join("/").replace(/\/+/g, "/"),
5741
- join: (...args) => args.join("/").replace(/\/+/g, "/"),
5742
- isAbsolute: (path) => path.startsWith("/") || path.startsWith("http"),
5743
- relative: (_from, to) => to,
5744
- cwd: () => "/",
5745
- env: (_key) => {
5746
- return;
5747
- },
5748
- isProd: () => false
5749
- };
5750
-
5751
5746
  // core/src/utils/attributes-bag.ts
5752
5747
  function classString(input) {
5753
5748
  if (input == null || input === false)
@@ -5885,6 +5880,29 @@ function createAttributes(attrs = {}) {
5885
5880
  return new KireAttributes(attrs);
5886
5881
  }
5887
5882
 
5883
+ // core/src/utils/browser.ts
5884
+ var throwNoAPI = (name) => {
5885
+ return () => {
5886
+ throw new Error(`Platform API '${name}' is not available in browser. Provide it via store or use virtual files.`);
5887
+ };
5888
+ };
5889
+ var platform = {
5890
+ readFile: throwNoAPI("readFile"),
5891
+ exists: () => false,
5892
+ readDir: throwNoAPI("readDir"),
5893
+ stat: throwNoAPI("stat"),
5894
+ writeFile: throwNoAPI("writeFile"),
5895
+ resolve: (...args) => args.join("/").replace(/\/+/g, "/"),
5896
+ join: (...args) => args.join("/").replace(/\/+/g, "/"),
5897
+ isAbsolute: (path) => path.startsWith("/") || path.startsWith("http"),
5898
+ relative: (_from, to) => to,
5899
+ cwd: () => "/",
5900
+ env: (_key) => {
5901
+ return;
5902
+ },
5903
+ isProd: () => false
5904
+ };
5905
+
5888
5906
  // core/src/utils/error.ts
5889
5907
  var SOURCE_MAP_PREFIX = "//# sourceMappingURL=data:application/json;charset=utf-8;base64,";
5890
5908
  var STACK_FRAME_REGEX = /^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?$/;
@@ -7129,7 +7147,14 @@ function prepareInlineWire(engine, wire) {
7129
7147
  const wirePkg = requireWire();
7130
7148
  const wirePath = wire.path ?? "/_wire";
7131
7149
  const scriptUrl = wire.scriptUrl ?? "/kirewire.js";
7132
- engine.plugin(wirePkg.kirewirePlugin(wire.instance, { scriptUrl, path: wirePath }));
7150
+ const ws = resolveWs(wire);
7151
+ const wsActive = ws ? attachNodeWs(wirePkg, wire.instance, ws) : false;
7152
+ engine.plugin(wirePkg.kirewirePlugin(wire.instance, {
7153
+ scriptUrl,
7154
+ path: wirePath,
7155
+ wsPath: wsActive ? ws.path : undefined,
7156
+ channel: wsActive ? ws.channel : undefined
7157
+ }));
7133
7158
  const clientScript = resolveClientScript(wire);
7134
7159
  return (event) => {
7135
7160
  const method = event.req.method;
@@ -7148,6 +7173,39 @@ function prepareInlineWire(engine, wire) {
7148
7173
  return null;
7149
7174
  };
7150
7175
  }
7176
+ function resolveWs(wire) {
7177
+ if (!wire.ws)
7178
+ return null;
7179
+ const ws = wire.ws === true ? {} : wire.ws;
7180
+ return {
7181
+ path: ws.path ?? "/_wire/ws",
7182
+ channel: ws.channel,
7183
+ server: ws.server,
7184
+ hub: ws.hub
7185
+ };
7186
+ }
7187
+ function attachNodeWs(wirePkg, instance, ws) {
7188
+ if (!ws.server) {
7189
+ console.warn("[@kirejs/h3] wire.ws is enabled but no `server` was provided; " + "pass the http.Server (e.g. from app.listen or http.createServer(app)). " + "Falling back to the HTTP transport.");
7190
+ return false;
7191
+ }
7192
+ let WebSocketServer;
7193
+ try {
7194
+ ({ WebSocketServer } = __require("ws"));
7195
+ } catch {
7196
+ throw new Error("@kirejs/h3: wire.ws requires the `ws` package to be installed.");
7197
+ }
7198
+ const hub = ws.hub ?? new wirePkg.Hub;
7199
+ const wss = new WebSocketServer({ server: ws.server, path: ws.path });
7200
+ wss.on("connection", (socket) => {
7201
+ wirePkg.serveWs(instance, hub, {
7202
+ send: (data) => socket.send(data),
7203
+ onMessage: (cb) => socket.on("message", (d) => cb(d.toString())),
7204
+ onClose: (cb) => socket.on("close", cb)
7205
+ }, { channel: ws.channel });
7206
+ });
7207
+ return true;
7208
+ }
7151
7209
  function requireWire() {
7152
7210
  try {
7153
7211
  return init_src(), __toCommonJS(exports_src);
@@ -1,6 +1,23 @@
1
1
  import type { Kire, KirePlugin } from "kire";
2
2
  /** A Kire plugin, optionally with its options. */
3
3
  export type PluginEntry = KirePlugin<any> | [KirePlugin<any>, any];
4
+ /** WebSocket transport options for the Kirewire integration. */
5
+ export interface WireWsOptions {
6
+ /** WebSocket endpoint path (default `/_wire/ws`). */
7
+ path?: string;
8
+ /** Server-push channel the client subscribes to on connect. */
9
+ channel?: string;
10
+ /** Shared Kirewire `Hub` for server pushes (optional; one is created if omitted). */
11
+ hub?: any;
12
+ /**
13
+ * Node `http.Server` to attach the WebSocket upgrade to. Required for h3
14
+ * (the middleware does not own the server): pass the server returned by
15
+ * `app.listen(...)` or `http.createServer(app)`. Without it WebSocket is
16
+ * skipped, the client stays on HTTP, and a warning is logged. Needs the `ws`
17
+ * package installed.
18
+ */
19
+ server?: any;
20
+ }
4
21
  /** Optional Kirewire (reactive components) integration. */
5
22
  export interface WireIntegration {
6
23
  /** A Kirewire instance (from `@kirejs/wire`). */
@@ -13,6 +30,12 @@ export interface WireIntegration {
13
30
  clientScript?: string;
14
31
  /** Optional file-upload store. */
15
32
  store?: any;
33
+ /**
34
+ * Enable the duplex WebSocket transport. `true` uses the default path
35
+ * `/_wire/ws`; an object customizes it. When active, the injected client
36
+ * script connects over WebSocket instead of HTTP POST.
37
+ */
38
+ ws?: boolean | WireWsOptions;
16
39
  }
17
40
  export interface KireH3Options {
18
41
  /** Directory that holds the `.kire` views. */
package/llms.txt ADDED
@@ -0,0 +1,48 @@
1
+ # @kirejs/h3 — h3 (unjs) integration
2
+
3
+ > Wire Kire (and optionally Kirewire) into h3 through a returned `{ view, middleware, engine }` handle.
4
+
5
+ `kireH3(options)` builds a Kire engine (or reuses `options.engine`), loads `plugins` and `globals`, and returns a `KireH3` handle. Unlike the other integrations it does not decorate the request: you call `kire.view(dotted.name, data)` yourself inside handlers (it returns an HTML `Response` that h3 sends as-is), and you optionally mount `kire.middleware` to serve the Kirewire endpoints.
6
+
7
+ ## API
8
+
9
+ ```ts
10
+ import { H3, serve } from "h3";
11
+ import { kireH3 } from "@kirejs/h3";
12
+
13
+ const kire = kireH3({ views: "resources/views" });
14
+ const app = new H3();
15
+
16
+ app.use(kire.middleware); // only does work when `wire` is set; otherwise passes through
17
+
18
+ app.get("/", () => kire.view("home", { title: "Hi" }));
19
+ app.get("/about", () => kire.view("pages.about", { who: "Kire" }));
20
+ serve(app, { port: 3000 });
21
+ ```
22
+
23
+ There is a single call style: `kireH3(options): KireH3`. The handle has:
24
+ - `engine`: the `Kire` instance.
25
+ - `view(name, data?)`: `Promise<Response>` with `content-type: text/html; charset=utf-8`.
26
+ - `middleware(event, next)`: h3 middleware; serves wire endpoints when `wire` is set, else calls `next()`.
27
+
28
+ Options (`KireH3Options`):
29
+ `{ views: string; extension?: string = "kire"; production?: boolean; engine?: Kire; plugins?: (KirePlugin | [KirePlugin, opts])[]; globals?: Record<string, unknown>; wire?: WireIntegration }`
30
+
31
+ ## Kirewire setup
32
+
33
+ `wire: { instance, path?, scriptUrl?, clientScript?, store? }` requires `@kirejs/wire` (optional peer; throws at creation if missing). It loads `kirewirePlugin(instance, { scriptUrl, path })`; `kire.middleware` then answers `POST <path>` (default `/_wire`; reads `event.req.text()`, calls `handleUpdate`, replies `Response.json(body, { status })`) and `GET <scriptUrl>` (default `/kirewire.js`) serving the client runtime resolved from `@kirejs/wire` or `clientScript`.
34
+
35
+ ```ts
36
+ const kire = kireH3({ views: "resources/views", wire: { instance: wire } });
37
+ app.use(kire.middleware);
38
+ ```
39
+
40
+ ## Notes
41
+
42
+ - Written for the h3 v2 API (`new H3()`, `event.req`, `event.url.pathname`); the middleware relies on those properties.
43
+ - You MUST register `app.use(kire.middleware)` for wire to work; `wire` alone does not mount routes.
44
+ - Because `view` is not on the event, import/share the `kire` handle between modules (or export it) to render from route files.
45
+ - Use dotted view paths (`pages.about` -> `pages/about.kire`).
46
+ - Wire reads the raw text body, so no body-parser is needed.
47
+ - `store` exists on the shared `WireIntegration` type but is not used by the h3 wiring.
48
+ - `production: true` disables source maps and enables caching.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kirejs/h3",
3
3
  "description": "h3 (unjs) integration for Kire — view rendering, a view() helper and one-line Kirewire setup.",
4
- "version": "0.2.4",
4
+ "version": "0.2.5",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "module": "./dist/esm/index.js",
7
7
  "types": "./dist/types/index.d.ts",
@@ -29,15 +29,19 @@
29
29
  "author": "drysius",
30
30
  "license": "MIT",
31
31
  "dependencies": {
32
- "kire": "0.2.4"
32
+ "kire": "0.2.5"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "@kirejs/wire": "workspace:*",
36
- "h3": "^2"
36
+ "h3": "^2",
37
+ "ws": "^8"
37
38
  },
38
39
  "peerDependenciesMeta": {
39
40
  "@kirejs/wire": {
40
41
  "optional": true
42
+ },
43
+ "ws": {
44
+ "optional": true
41
45
  }
42
46
  }
43
47
  }