@stacksjs/stx 0.2.889 → 0.2.890

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 (177) hide show
  1. package/dist/{chunk-1n33yrar.js → chunk-062qfv99.js} +2 -2
  2. package/dist/{chunk-2a5g80mq.js → chunk-0jdz31q1.js} +3 -3
  3. package/dist/{chunk-mhxg6j6s.js → chunk-0jkj8thz.js} +1 -1
  4. package/dist/chunk-0q0nbq50.js +2 -0
  5. package/dist/{chunk-kj43fbzm.js → chunk-0wp23n1d.js} +1 -1
  6. package/dist/{chunk-cz1sdes5.js → chunk-115bb91s.js} +2 -2
  7. package/dist/{chunk-w82nk19t.js → chunk-12cjs6vs.js} +1 -1
  8. package/dist/chunk-1a7a8cjs.js +2 -0
  9. package/dist/{chunk-700m927w.js → chunk-1bft48gk.js} +2 -2
  10. package/dist/{chunk-6pz5gq6v.js → chunk-1jtsr42q.js} +20 -20
  11. package/dist/chunk-1ph2yhfn.js +3 -0
  12. package/dist/{chunk-f3cyghnb.js → chunk-1t15z230.js} +4 -4
  13. package/dist/{chunk-7212fwzz.js → chunk-1w0bqqh5.js} +2 -2
  14. package/dist/{chunk-s0mf56y1.js → chunk-2xnbdqy4.js} +4 -4
  15. package/dist/{chunk-2gn2nc2j.js → chunk-35j7gaj5.js} +1 -1
  16. package/dist/chunk-3b3mkgpj.js +3 -0
  17. package/dist/{chunk-snv80b1b.js → chunk-3bsz7zj3.js} +2 -2
  18. package/dist/chunk-3yvmaphj.js +2 -0
  19. package/dist/{chunk-njpva3zq.js → chunk-40k0r6z9.js} +1 -1
  20. package/dist/{chunk-eyx92t9n.js → chunk-41z7f41b.js} +2 -2
  21. package/dist/chunk-44teqn0b.js +2 -0
  22. package/dist/{chunk-b15c4g3e.js → chunk-49xwf7dk.js} +6 -6
  23. package/dist/chunk-4d85str1.js +2 -0
  24. package/dist/{chunk-7hpca9c7.js → chunk-4eescf3s.js} +4 -4
  25. package/dist/chunk-4xbtxeak.js +2 -0
  26. package/dist/{chunk-0ncafcs2.js → chunk-67j2m620.js} +3 -3
  27. package/dist/{chunk-5ssv10ep.js → chunk-690518hw.js} +1 -1
  28. package/dist/chunk-6s3jwysv.js +2 -0
  29. package/dist/{chunk-mt8edb75.js → chunk-6svc4kb8.js} +57 -57
  30. package/dist/{chunk-5kqezrjt.js → chunk-80ky40mm.js} +1 -1
  31. package/dist/chunk-850tye3c.js +2 -0
  32. package/dist/{chunk-eceeqy74.js → chunk-8ccgty8s.js} +2 -2
  33. package/dist/{chunk-1gyxxfdf.js → chunk-8f8qgjjr.js} +1 -1
  34. package/dist/{chunk-87g5xmmr.js → chunk-9344rq4r.js} +14 -14
  35. package/dist/chunk-94j4p584.js +2 -0
  36. package/dist/{chunk-446tb2th.js → chunk-97snfzsy.js} +49 -49
  37. package/dist/chunk-9a9cec4x.js +2 -0
  38. package/dist/{chunk-pctf14yw.js → chunk-9rjgq8k4.js} +1 -1
  39. package/dist/{chunk-q9tc9rdv.js → chunk-a0aqs5a8.js} +2 -2
  40. package/dist/{chunk-cgfjrgfw.js → chunk-a3zrwky3.js} +11 -11
  41. package/dist/{chunk-6gtecbe7.js → chunk-a7bqrjm5.js} +2 -2
  42. package/dist/{chunk-vc432a0w.js → chunk-adsqckg4.js} +9 -9
  43. package/dist/{chunk-51720m79.js → chunk-aj5tsksz.js} +9 -9
  44. package/dist/chunk-amb7e0fp.js +2 -0
  45. package/dist/chunk-arr79m90.js +2 -0
  46. package/dist/{chunk-9d91h636.js → chunk-b0hj8eg2.js} +2 -2
  47. package/dist/chunk-bm0mzk3b.js +2 -0
  48. package/dist/{chunk-ymqm898x.js → chunk-bvqgq18r.js} +2 -2
  49. package/dist/{chunk-m95sygv4.js → chunk-c25q87ys.js} +1 -1
  50. package/dist/{chunk-mgh5rst1.js → chunk-cphc60zw.js} +2 -2
  51. package/dist/{chunk-ranjkpc8.js → chunk-e16ef18k.js} +1 -1
  52. package/dist/chunk-e28czxw3.js +2 -0
  53. package/dist/{chunk-g6ap4085.js → chunk-e8szp5wa.js} +1 -1
  54. package/dist/chunk-eq86wzhr.js +1314 -0
  55. package/dist/chunk-essd43ad.js +2 -0
  56. package/dist/chunk-fsk3rk2x.js +2 -0
  57. package/dist/{chunk-s93yh7ed.js → chunk-g3vce7ka.js} +2 -2
  58. package/dist/{chunk-zwwhpxp7.js → chunk-g5nfqzfh.js} +2 -2
  59. package/dist/chunk-gfea8a9y.js +2 -0
  60. package/dist/chunk-hda7t8g6.js +2 -0
  61. package/dist/{chunk-dymck524.js → chunk-hyyh7qxw.js} +5 -5
  62. package/dist/chunk-j6fs31va.js +2 -0
  63. package/dist/chunk-j9kejcrx.js +2 -0
  64. package/dist/chunk-j9vfv53x.js +20 -0
  65. package/dist/chunk-jhbz5w30.js +2 -0
  66. package/dist/chunk-jvnsz2x9.js +2 -0
  67. package/dist/{chunk-bwx6w87c.js → chunk-k8bk685s.js} +1 -1
  68. package/dist/chunk-kexqmwx8.js +2 -0
  69. package/dist/{chunk-bqtj62ys.js → chunk-kg7vby72.js} +7 -7
  70. package/dist/{chunk-mjp1z9kz.js → chunk-khm56bfm.js} +1 -1
  71. package/dist/chunk-kpjq135z.js +2 -0
  72. package/dist/chunk-kqsm7gf1.js +2 -0
  73. package/dist/{chunk-mctzpw0w.js → chunk-kr2400c3.js} +4 -4
  74. package/dist/{chunk-b6bf0t02.js → chunk-mhrnjaka.js} +4 -4
  75. package/dist/chunk-mtfymhy1.js +2 -0
  76. package/dist/{chunk-eqffvse2.js → chunk-n6q1d66k.js} +1 -1
  77. package/dist/{chunk-3hsv6ejp.js → chunk-neg6ckjg.js} +7 -7
  78. package/dist/{chunk-hm9d40yf.js → chunk-nhv81gp2.js} +2 -2
  79. package/dist/{chunk-kbbbpae2.js → chunk-nq60tjkz.js} +2 -2
  80. package/dist/{chunk-kx09v9ya.js → chunk-nzpb263k.js} +9 -9
  81. package/dist/{chunk-6kyqejnq.js → chunk-p0bjbtdx.js} +20 -20
  82. package/dist/{chunk-967ydrq4.js → chunk-p3hbsrk9.js} +2 -2
  83. package/dist/chunk-p82fzxdg.js +2 -0
  84. package/dist/{chunk-pz554g43.js → chunk-pvm48tse.js} +3 -3
  85. package/dist/{chunk-zek9t5za.js → chunk-pwpge9bj.js} +2 -2
  86. package/dist/{chunk-58qzyyyv.js → chunk-qnf7w4xw.js} +1 -1
  87. package/dist/chunk-qsv84cwm.js +2 -0
  88. package/dist/chunk-r7m60q1m.js +2 -0
  89. package/dist/chunk-r98pye4h.js +2 -0
  90. package/dist/{chunk-6pdy7ajr.js → chunk-rd663v1m.js} +1 -1
  91. package/dist/{chunk-55tc5w32.js → chunk-sh7a0g09.js} +2 -2
  92. package/dist/chunk-sztr4d5g.js +2 -0
  93. package/dist/{chunk-95sd8h5g.js → chunk-t3zmfh8w.js} +3 -3
  94. package/dist/chunk-t4gcsbna.js +2 -0
  95. package/dist/chunk-tspqdt8e.js +2 -0
  96. package/dist/{chunk-sjjw6y49.js → chunk-v1mwwben.js} +4 -4
  97. package/dist/chunk-v6gkjg5f.js +3 -0
  98. package/dist/{chunk-48rwqchc.js → chunk-v90nz5xm.js} +9 -9
  99. package/dist/chunk-vfcbz0an.js +3 -0
  100. package/dist/{chunk-hgf7bc50.js → chunk-vkfw9k1n.js} +6 -6
  101. package/dist/{chunk-4kmg6g5n.js → chunk-vxbvrbqs.js} +9 -9
  102. package/dist/chunk-wedwczed.js +2 -0
  103. package/dist/chunk-wg6fmren.js +4 -0
  104. package/dist/{chunk-mw7hacm3.js → chunk-whcrca58.js} +21 -21
  105. package/dist/chunk-wmvvrsn0.js +2 -0
  106. package/dist/chunk-wnrh62by.js +2 -0
  107. package/dist/{chunk-nkyff7v6.js → chunk-wy6vjz1e.js} +17 -17
  108. package/dist/{chunk-brzjass3.js → chunk-xc5esqcb.js} +2 -2
  109. package/dist/{chunk-nbdscgvj.js → chunk-xeyq6d0t.js} +6 -6
  110. package/dist/{chunk-3dqfjpz4.js → chunk-xmg6bmh6.js} +29 -29
  111. package/dist/chunk-xwrjre34.js +2 -0
  112. package/dist/{chunk-p8shtje2.js → chunk-yesh4dfe.js} +45 -45
  113. package/dist/chunk-ymc1wgb3.js +2 -0
  114. package/dist/{chunk-6c1vm6bs.js → chunk-zkwkhesc.js} +2 -2
  115. package/dist/{chunk-me4yq8c2.js → chunk-zpqjsnz9.js} +2 -2
  116. package/dist/{chunk-hpzje67q.js → chunk-zwqkbk2m.js} +2 -2
  117. package/dist/chunk-zxjdfgdx.js +3 -0
  118. package/dist/cli.js +28 -28
  119. package/dist/component-contract.d.ts +1 -0
  120. package/dist/component-contract.js +6 -4
  121. package/dist/component-library.js +207 -58
  122. package/dist/composition-api.d.ts +7 -1
  123. package/dist/craft-entry.js +1 -1
  124. package/dist/craft.js +1 -1
  125. package/dist/emits-declaration.d.ts +9 -0
  126. package/dist/emits-declaration.js +64 -0
  127. package/dist/props-declaration.d.ts +2 -0
  128. package/dist/props-declaration.js +25 -0
  129. package/dist/pwa.js +3 -3
  130. package/dist/ssg.js +28 -28
  131. package/package.json +5 -5
  132. package/dist/chunk-0g9cceht.js +0 -2
  133. package/dist/chunk-0rpj5t80.js +0 -2
  134. package/dist/chunk-2ba4zfa0.js +0 -2
  135. package/dist/chunk-2wkpksg1.js +0 -2
  136. package/dist/chunk-3yjyjq0m.js +0 -2
  137. package/dist/chunk-444haxxa.js +0 -2
  138. package/dist/chunk-4rvfeee5.js +0 -2
  139. package/dist/chunk-5aa83bpm.js +0 -2
  140. package/dist/chunk-67rppc5v.js +0 -2
  141. package/dist/chunk-77c89d23.js +0 -2
  142. package/dist/chunk-79vbkez0.js +0 -2
  143. package/dist/chunk-8354mzpd.js +0 -2
  144. package/dist/chunk-8ygf6jnt.js +0 -2
  145. package/dist/chunk-94mpe1ny.js +0 -3
  146. package/dist/chunk-9n5h4sqc.js +0 -3
  147. package/dist/chunk-9ztn7w4y.js +0 -2
  148. package/dist/chunk-ankap9pc.js +0 -2
  149. package/dist/chunk-asnd03sr.js +0 -2
  150. package/dist/chunk-b0b5yr97.js +0 -2
  151. package/dist/chunk-b0e7dgv8.js +0 -3
  152. package/dist/chunk-b7jj45bz.js +0 -2
  153. package/dist/chunk-dzqfv801.js +0 -3
  154. package/dist/chunk-ery4tty7.js +0 -20
  155. package/dist/chunk-evwrxsxd.js +0 -3
  156. package/dist/chunk-fdqdz018.js +0 -2
  157. package/dist/chunk-gz9pknbw.js +0 -1204
  158. package/dist/chunk-hjb4c8g2.js +0 -2
  159. package/dist/chunk-jhbj9ja2.js +0 -2
  160. package/dist/chunk-k9abxnpa.js +0 -2
  161. package/dist/chunk-mvavjydq.js +0 -2
  162. package/dist/chunk-qqng9545.js +0 -2
  163. package/dist/chunk-rjm515e2.js +0 -2
  164. package/dist/chunk-rye4b2x3.js +0 -2
  165. package/dist/chunk-ryj8139z.js +0 -2
  166. package/dist/chunk-s9b809n2.js +0 -2
  167. package/dist/chunk-sb67wg5x.js +0 -2
  168. package/dist/chunk-sqwx2g02.js +0 -2
  169. package/dist/chunk-tpyekw0q.js +0 -2
  170. package/dist/chunk-v2627s75.js +0 -2
  171. package/dist/chunk-v98n53nk.js +0 -2
  172. package/dist/chunk-w34vvhm7.js +0 -2
  173. package/dist/chunk-wbmx0rge.js +0 -2
  174. package/dist/chunk-yjwa7ktk.js +0 -2
  175. package/dist/chunk-z47p2gx8.js +0 -2
  176. package/dist/chunk-z6kw6sct.js +0 -4
  177. package/dist/chunk-zhywjwdr.js +0 -2
@@ -1,4 +1,5 @@
1
1
  import { scanHtmlScriptElements } from "./html-masking.js";
2
+ import { parseEmitsDeclaration } from "./emits-declaration.js";
2
3
  import { mkdir, readFile, readdir, realpath, stat, writeFile } from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import { builtinModules } from "node:module";
@@ -6,7 +7,7 @@ import { scriptAttributes, scriptContainsCode } from "./script-attributes.js";
6
7
  import { topLevelDeclarationSites } from "./client-parameter-bindings.js";
7
8
  import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
8
9
  import { Tokenizer } from "./parser/tokenizer.js";
9
- import { literalValue, parseDefaults, parsePropsDeclaration, skipBalanced, splitTopLevel } from "./props-declaration.js";
10
+ import { literalValue, localType, parseDefaults, parsePropsDeclaration, skipBalanced, splitTopLevel } from "./props-declaration.js";
10
11
  export { parseDefaults } from "./props-declaration.js";
11
12
  function reservedMethodMessage(name) {
12
13
  if (name === "connectedCallback")
@@ -170,20 +171,21 @@ function extractClientMethods(source, file) {
170
171
  const methods = {}, declarations = {}, types = [], imports = [], scripts = scanHtmlScriptElements(componentScriptSource(source)).map((script) => ({
171
172
  code: source.slice(script.bodyStart, script.bodyEnd),
172
173
  attributes: scriptAttributes(script.attrs)
173
- })).filter(({ attributes }) => !["src", "server", "component", "stx:component"].some((name) => attributes.has(name)) && scriptContainsCode(attributes));
174
+ })).filter(({ attributes }) => !["src", "server", "component", "stx:component"].some((name) => attributes.has(name)) && scriptContainsCode(attributes)), combined = scripts.map((script) => script.code).join(`
175
+ `), publicProps = parsePropsDeclaration(combined), publicEmits = parseEmitsDeclaration(combined);
174
176
  for (const script of scripts) {
175
- const { code, attributes } = script;
177
+ const { code } = script;
176
178
  try {
177
179
  new Bun.Transpiler({ loader: "ts" }).transformSync(code);
178
180
  } catch (error) {
179
181
  throw Error(`${file}: failed to transpile <script client> (${error.message})`);
180
182
  }
181
- const props = attributes.has("client") ? null : parsePropsDeclaration(code), extracted = attributes.has("client") ? clientMethods(code) : [], overloads = new Set(extracted.filter((method) => !method.source).map((method) => method.name));
183
+ const extracted = clientMethods(code), overloads = new Set(extracted.filter((method) => !method.source).map((method) => method.name));
182
184
  for (const method of extracted) {
183
185
  if (RESERVED_METHODS.has(method.name))
184
186
  throw Error(`${file}: client ${reservedMethodMessage(method.name)}`);
185
187
  if (method.source)
186
- methods[method.name] = new Bun.Transpiler({ loader: "ts" }).transformSync(method.source).trim().replace(/^(?:export\s+)?(async\s+)?function\s+/, "$1");
188
+ methods[method.name] = `${method.name}(...args) { return this._callScopeMethod(${JSON.stringify(method.name)}, args); }`;
187
189
  if (!method.source || !overloads.has(method.name))
188
190
  (declarations[method.name] ??= []).push(methodDeclaration(method));
189
191
  }
@@ -225,10 +227,10 @@ function extractClientMethods(source, file) {
225
227
  }
226
228
  const declaration = code.slice(match.index, cursor), declarationStart = match.index, name = /(?:interface|type)\s+([A-Za-z_$][\w$]*)/.exec(match[0])?.[1], remaining = scripts.map((other) => {
227
229
  const body = other === script ? code.slice(0, declarationStart) + code.slice(cursor) : other.code;
228
- return stripCommentsAndLiterals(body.replace(parsePropsDeclaration(other.code)?.text ?? "\x00", ""));
230
+ return stripCommentsAndLiterals(body.replace(parsePropsDeclaration(other.code)?.text ?? "\x00", "").replace(parseEmitsDeclaration(other.code)?.text ?? "\x00", ""));
229
231
  }).join(`
230
232
  `);
231
- if (!(props?.typeName === name && !/^export\s/.test(declaration) && name && !new RegExp(`\\b${name}\\b`).test(remaining)))
233
+ if (!((publicProps?.typeName === name || publicEmits?.typeName === name) && !/^export\s/.test(declaration) && name && !new RegExp(`\\b${name}\\b`).test(remaining)))
232
234
  types.push(declaration.replace(/^export\s+/, "").trim());
233
235
  typePattern.lastIndex = cursor + 1;
234
236
  }
@@ -236,13 +238,21 @@ function extractClientMethods(source, file) {
236
238
  const referenced = Object.values(declarations).flat().join(`
237
239
  `) + `
238
240
  ` + types.join(`
239
- `), usedImports = imports.filter((imported) => (imported.binding.match(/[A-Za-z_$][\w$]*/g) || []).filter((name) => !["type", "as"].includes(name)).some((name) => new RegExp(`\\b${name}\\b`).test(referenced)));
241
+ `) + `
242
+ ` + Object.values(publicEmits?.events || {}).map((event) => event.detailType).join(`
243
+ `), referenceTokens = new Tokenizer(referenced, "javascript").tokenize().filter((token) => !["WHITESPACE", "COMMENT"].includes(token.type)), typeReferences = new Set(referenceTokens.filter((token, index) => {
244
+ if (referenceTokens[index - 1]?.value === ".")
245
+ return !1;
246
+ const next = referenceTokens[index + 1]?.value;
247
+ return next !== ":" && !(next === "?" && referenceTokens[index + 2]?.value === ":");
248
+ }).map((token) => token.value)), usedImports = imports.filter((imported) => (imported.binding.match(/[A-Za-z_$][\w$]*/g) || []).filter((name) => !["type", "as"].includes(name)).some((name) => typeReferences.has(name)));
240
249
  for (const imported of usedImports)
241
250
  if (imported.module.startsWith(".") || path.isAbsolute(imported.module))
242
251
  throw Error(`${file}: public method types import ${JSON.stringify(imported.module)} outside the generated package; declare these types in the component or import them from a published dependency`);
243
252
  const typeImports = [...new Set(usedImports.map((imported) => `import type ${imported.binding.replace(/\btype\s+/g, "")} from ${JSON.stringify(imported.module)}`))];
244
- return { methods, declarations, types: [...typeImports, ...types].join(`
253
+ return { methods, declarations, types: types.join(`
245
254
 
255
+ `), typeImports: typeImports.join(`
246
256
  `) };
247
257
  }
248
258
  function extractTemplate(source) {
@@ -311,7 +321,7 @@ export function parseNativeComponentLoop(expression) {
311
321
  const pair = /^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec(expression.trim());
312
322
  return pair ? { iterable: pair[1], key: pair[2], value: pair[3] } : void 0;
313
323
  }
314
- function compileTemplateToRender(template) {
324
+ function compileTemplateToRender(template, handlers) {
315
325
  const parts = [];
316
326
  let cursor = 0;
317
327
  const source = template.replace(/\{\{--[\s\S]*?--\}\}/g, ""), directive = /@(if|elseif|else|endif|foreach|endforeach)\s*/g;
@@ -320,12 +330,12 @@ function compileTemplateToRender(template) {
320
330
  if (raw === "")
321
331
  return;
322
332
  let index = 0;
323
- const interpolation = /\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g;
333
+ const interpolation = /\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}|(data-stx-on-[\w:-]+=")(\d+)(")/g;
324
334
  let hit;
325
335
  while (hit = interpolation.exec(raw)) {
326
336
  if (hit.index > index)
327
337
  parts.push(`out += ${JSON.stringify(raw.slice(index, hit.index))};`);
328
- parts.push(hit[1] !== void 0 ? `out += __raw(${hit[1]});` : `out += __escape(${hit[2]});`);
338
+ parts.push(hit[3] !== void 0 ? `out += ${JSON.stringify(hit[3])} + (this._handlers.push(${handlers[Number(hit[4])]}) - 1) + ${JSON.stringify(hit[5])};` : hit[1] !== void 0 ? `out += __raw(${hit[1]});` : `out += __escape(${hit[2]});`);
329
339
  index = hit.index + hit[0].length;
330
340
  }
331
341
  if (index < raw.length)
@@ -410,7 +420,7 @@ function hoistScriptImports(code) {
410
420
  last++;
411
421
  const end = start + tokens[last].end;
412
422
  spans.push({ start, end });
413
- if (specifier.value.slice(1, -1) !== "stx")
423
+ if (!["stx", "@stacksjs/stx"].includes(specifier.value.slice(1, -1)))
414
424
  imports.push(code.slice(start, end));
415
425
  }
416
426
  let body = code;
@@ -419,13 +429,14 @@ function hoistScriptImports(code) {
419
429
  return { imports, body };
420
430
  }
421
431
  function compileScriptScope(source) {
422
- const block = scanHtmlScriptElements(componentScriptSource(source)).find((script) => {
432
+ const blocks = scanHtmlScriptElements(componentScriptSource(source)).filter((script) => {
423
433
  const attrs = scriptAttributes(script.attrs);
424
- return scriptContainsCode(attrs) && !["component", "stx:component", "client", "server", "src"].some((name) => attrs.has(name));
434
+ return scriptContainsCode(attrs) && !["component", "stx:component", "server", "src"].some((name) => attrs.has(name));
425
435
  });
426
- if (!block)
427
- return { imports: [], body: "", propNames: [], propBindings: {}, defaults: {}, declared: {} };
428
- let code = source.slice(block.bodyStart, block.bodyEnd);
436
+ if (!blocks.length)
437
+ return { imports: [], body: "", propNames: [], propBindings: {}, defaults: {}, declared: {}, apis: [] };
438
+ let code = blocks.map((block) => source.slice(block.bodyStart, block.bodyEnd)).join(`
439
+ `);
429
440
  const imports = [], propNames = [], propBindings = Object.create(null), defaults = Object.create(null), declared = Object.create(null), hoisted = hoistScriptImports(code);
430
441
  imports.push(...hoisted.imports);
431
442
  code = hoisted.body;
@@ -437,31 +448,38 @@ function compileScriptScope(source) {
437
448
  Object.assign(declared, props.declared);
438
449
  code = code.replace(props.text, props.identifier ? `const ${props.identifier} = this._props();` : "");
439
450
  }
440
- const interfaceMembers = {};
441
- for (const block of code.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)) {
442
- const members = [];
443
- for (const member of block[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm)) {
444
- declared[member[1]] = member[2].trim();
445
- members.push(member[1]);
446
- }
447
- interfaceMembers[block[1]] = members;
448
- }
449
- if (props && props.propNames.length === 0 && props.typeName) {
450
- for (const name of interfaceMembers[props.typeName] ?? [])
451
- if (!propNames.includes(name))
452
- propNames.push(name);
451
+ if (props?.typeName) {
452
+ const type = localType(code, props.typeName);
453
+ if (type)
454
+ for (const member of splitTopLevel(type.slice(1, -1), `;,
455
+ `, !0)) {
456
+ const parsed = /^(?:readonly\s+)?([A-Za-z_$][\w$]*)\??\s*:\s*([\s\S]+)$/.exec(member);
457
+ if (!parsed)
458
+ continue;
459
+ declared[parsed[1]] = parsed[2].trim();
460
+ if (!propNames.includes(parsed[1]))
461
+ propNames.push(parsed[1]);
462
+ }
453
463
  }
454
- code = code.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g, "");
455
- return { imports, body: code.trim(), propNames, propBindings, defaults, declared };
464
+ const emits = parseEmitsDeclaration(code);
465
+ if (emits)
466
+ code = code.replace(emits.text, "this._emitScope.bind(this)");
467
+ const publicMask = stripCommentsAndLiterals(code), publicDepths = bracketDepths(publicMask).depths;
468
+ for (const match of [...publicMask.matchAll(/\bexport\s+(?=(?:interface|type|const|let|var|async|function)\b)/g)].reverse())
469
+ if (publicDepths[match.index] === 0)
470
+ code = code.slice(0, match.index) + " ".repeat(match[0].length) + code.slice(match.index + match[0].length);
471
+ const locals = new Set(topLevelDeclarationSites(code).map((site) => site.name)), masked = stripCommentsAndLiterals(code), apis = ["state", "derived", "effect", "batch", "onMount", "onDestroy"].filter((name) => !locals.has(name) && new RegExp(`\\b${name}\\s*(?:<|\\()`).test(masked));
472
+ return { imports, body: code.trim(), propNames, propBindings, defaults, declared, apis };
456
473
  }
457
474
  function compileEventDirectives(template) {
458
- const eventTypes = new Set;
459
- return { template: template.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi, (_match, eventName, modifiers, _quote, method) => {
475
+ const eventTypes = new Set, handlers = [];
476
+ return { template: template.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([\s\S]*?)\3/gi, (_match, eventName, modifiers, _quote, expression) => {
460
477
  const event = eventName.toLowerCase();
461
478
  eventTypes.add(event);
462
- const normalizedModifiers = (modifiers || "").split(".").filter(Boolean).join(" ");
463
- return ` data-stx-on-${event}="${method}"${normalizedModifiers ? ` data-stx-mod-${event}="${normalizedModifiers}"` : ""}`;
464
- }), eventTypes: [...eventTypes].sort() };
479
+ const normalizedModifiers = (modifiers || "").split(".").filter(Boolean).join(" "), id = handlers.length;
480
+ handlers.push(/^[A-Za-z_$][\w$]*$/.test(expression.trim()) ? `($event) => (typeof ${expression} === 'function' ? ${expression} : this[${JSON.stringify(expression.trim())}]).call(this, $event)` : `($event) => { ${expression} }`);
481
+ return ` data-stx-on-${event}="${id}"${normalizedModifiers ? ` data-stx-mod-${event}="${normalizedModifiers}"` : ""}`;
482
+ }), eventTypes: [...eventTypes].sort(), handlers };
465
483
  }
466
484
  function compileDynamicBindings(template) {
467
485
  const bindings = [];
@@ -502,7 +520,7 @@ async function compileComponent(inputDir, entry, defaults) {
502
520
  scope.imports.push(...hoistScriptImports(source.slice(script.bodyStart, script.bodyEnd)).imports);
503
521
  }
504
522
  scope.imports = [...new Set(scope.imports)];
505
- const render = compileTemplateToRender(bindingCompilation.template);
523
+ const render = compileTemplateToRender(bindingCompilation.template, eventCompilation.handlers);
506
524
  for (const propertyName of scope.propNames) {
507
525
  if (properties[propertyName])
508
526
  continue;
@@ -524,11 +542,18 @@ async function compileComponent(inputDir, entry, defaults) {
524
542
  shadowMode: normalizeShadowMode(entry.shadowDOM ?? metadata.shadowDOM ?? defaults.shadowDOM),
525
543
  progressive: entry.progressive ?? metadata.progressive ?? defaults.progressive ?? !0,
526
544
  properties,
527
- events: entry.events || metadata.events || {},
545
+ events: { ...parseEmitsDeclaration(scanHtmlScriptElements(componentScriptSource(source)).filter((script) => {
546
+ const attrs = scriptAttributes(script.attrs);
547
+ return scriptContainsCode(attrs) && !["server", "component", "stx:component", "src"].some((name) => attrs.has(name));
548
+ }).map((script) => source.slice(script.bodyStart, script.bodyEnd)).join(`
549
+ `))?.events || {}, ...entry.events || metadata.events || {} },
528
550
  methods: { ...metadataMethods, ...configuredMethods, ...extractedMethods.methods },
529
551
  methodDeclarations: extractedMethods.declarations,
530
552
  declarationTypes: extractedMethods.types,
553
+ declarationImports: extractedMethods.typeImports,
531
554
  eventTypes: eventCompilation.eventTypes,
555
+ handlers: eventCompilation.handlers,
556
+ scopeMethods: Object.keys(extractedMethods.methods),
532
557
  bindings: bindingCompilation.bindings,
533
558
  slots: extractSlots(bindingCompilation.template),
534
559
  cssProperties: extractCssProperties(extractStyles(source)),
@@ -536,9 +561,10 @@ async function compileComponent(inputDir, entry, defaults) {
536
561
  render
537
562
  };
538
563
  }
539
- function runtimeModule() {
564
+ function runtimeModule(signals = !1) {
540
565
  const rawInterpolation = JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"), escapedInterpolation = JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");
541
- return `const HTMLElementBase = globalThis.HTMLElement || class {};
566
+ return `${signals ? `import { state as nativeState, derived as nativeDerived, effect as nativeEffect, batch as nativeBatch } from './signals.js';
567
+ ` : ""}const HTMLElementBase = globalThis.HTMLElement || class {};
542
568
 
543
569
  const escapeHTML = (value) => String(value ?? '')
544
570
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -600,6 +626,14 @@ export class StxElement extends HTMLElementBase {
600
626
  this._initializing = false;
601
627
  this._updatePending = false;
602
628
  this._listeners = new Map();
629
+ this._scopeStates = [];
630
+ this._scopeDerived = [];
631
+ this._scopeEffects = [];
632
+ this._scopeSubscriptions = [];
633
+ this._scopeMounts = [];
634
+ this._scopeDestroys = [];
635
+ this._scopeConnectionDestroys = [];
636
+ this._scopeMountCleanups = [];
603
637
  const definition = this.constructor.definition;
604
638
  for (const [name, property] of Object.entries(definition.properties || {})) {
605
639
  this._values[name] = defaultFor(property);
@@ -630,7 +664,10 @@ export class StxElement extends HTMLElementBase {
630
664
  const hasMarkup = [...(root.childNodes || [])].some(node => node.nodeType !== 3 || node.textContent.trim());
631
665
  const firstConnection = !this._hasConnected;
632
666
  if (!(firstConnection && definition.progressive && hasMarkup)) this._render();
633
- else this._upgradeDeclarativeEvents();
667
+ else {
668
+ if (typeof this.render === 'function') this.render(RENDER_HELPERS);
669
+ this._upgradeDeclarativeEvents();
670
+ }
634
671
  this._bindEvents();
635
672
  if (firstConnection) {
636
673
  this._hasConnected = true;
@@ -640,6 +677,7 @@ export class StxElement extends HTMLElementBase {
640
677
  // Called last, so a component that acquires something sees its own rendered
641
678
  // markup and its events already bound. Reported rather than rethrown: a
642
679
  // component that fails to set up must not take the element down with it.
680
+ this._runScopeMounts();
643
681
  try { this.onConnect?.(); }
644
682
  catch (error) { console.error('[stx] onConnect failed', error); }
645
683
  }
@@ -652,6 +690,13 @@ export class StxElement extends HTMLElementBase {
652
690
  try { this.onDisconnect?.(); }
653
691
  catch (error) { console.error('[stx] onDisconnect failed', error); }
654
692
  finally {
693
+ this._disposeScopeEffects();
694
+ for (const dispose of this._scopeSubscriptions.splice(0)) {
695
+ try { dispose?.(); } catch (error) { console.error('[stx] scope subscription cleanup failed', error); }
696
+ }
697
+ for (const cleanup of [...this._scopeDestroys.splice(0), ...this._scopeConnectionDestroys.splice(0), ...this._scopeMountCleanups.splice(0)]) {
698
+ try { cleanup(); } catch (error) { console.error('[stx] scope cleanup failed', error); }
699
+ }
655
700
  for (const [event, listener] of this._listeners) this.renderRoot.removeEventListener(event, listener);
656
701
  this._listeners.clear();
657
702
  }
@@ -700,6 +745,66 @@ export class StxElement extends HTMLElementBase {
700
745
  }));
701
746
  }
702
747
 
748
+ _disposeScopeEffects() {
749
+ for (const dispose of this._scopeEffects.splice(0)) {
750
+ try { dispose(); } catch (error) { console.error('[stx] effect cleanup failed', error); }
751
+ }
752
+ }
753
+
754
+ _runScopeMounts() {
755
+ for (const mount of this._scopeMounts) {
756
+ try { const cleanup = mount(); if (typeof cleanup === 'function') this._scopeMountCleanups.push(cleanup); }
757
+ catch (error) { console.error('[stx] onMount failed', error); }
758
+ }
759
+ }
760
+
761
+ ${signals ? ` _beginScope() {
762
+ this._disposeScopeEffects();
763
+ this._scopeMounts = [];
764
+ this._scopeDestroys = [];
765
+ let stateIndex = 0, derivedIndex = 0;
766
+ let rendering = true;
767
+ return {
768
+ finish: () => { rendering = false; },
769
+ state: (initial) => {
770
+ const index = stateIndex++;
771
+ const value = this._scopeStates[index] ||= nativeState(initial);
772
+ if (this._connected && !this._scopeSubscriptions[index]) this._scopeSubscriptions[index] = value.subscribe(() => this.requestUpdate());
773
+ return value;
774
+ },
775
+ derived: (compute, options) => {
776
+ const index = derivedIndex++;
777
+ let entry = this._scopeDerived[index];
778
+ if (!entry) {
779
+ entry = { compute, revision: nativeState(0) };
780
+ entry.value = nativeDerived(() => { entry.revision(); return entry.compute(); }, options);
781
+ this._scopeDerived[index] = entry;
782
+ } else {
783
+ entry.compute = compute;
784
+ entry.revision.update(value => value + 1);
785
+ }
786
+ return entry.value;
787
+ },
788
+ effect: (callback, options) => {
789
+ const dispose = nativeEffect(callback, options);
790
+ this._scopeEffects.push(dispose);
791
+ return dispose;
792
+ },
793
+ batch: nativeBatch,
794
+ onMount: callback => this._scopeMounts.push(callback),
795
+ onDestroy: callback => (rendering ? this._scopeDestroys : this._scopeConnectionDestroys).push(callback),
796
+ };
797
+ }
798
+
799
+ ` : ""} _emitScope(name, ...args) {
800
+ return this.emit(name, args.length === 1 ? args[0] : args, { cancelable: true });
801
+ }
802
+
803
+ _callScopeMethod(name, args) {
804
+ if (!this._scopeMethods || this._updatePending) this.render(RENDER_HELPERS);
805
+ return this._scopeMethods[name].apply(this, args);
806
+ }
807
+
703
808
  _upgradeProperty(name) {
704
809
  if (!Object.prototype.hasOwnProperty.call(this, name)) return;
705
810
  const value = this[name];
@@ -728,10 +833,12 @@ export class StxElement extends HTMLElementBase {
728
833
  const target = $event.target?.closest?.(selector);
729
834
  if (!target || !this.renderRoot.contains(target)) return;
730
835
  const modifiers = (target.getAttribute('data-stx-mod-' + event) || '').split(' ');
836
+ if (modifiers.includes('self') && target !== $event.target) return;
731
837
  if (modifiers.includes('prevent')) $event.preventDefault();
732
838
  if (modifiers.includes('stop')) $event.stopPropagation();
733
839
  const method = target.getAttribute('data-stx-on-' + event);
734
- if (typeof this[method] === 'function') this[method]($event);
840
+ if (this._handlers?.[method]) this._handlers[method]($event);
841
+ else if (typeof this[method] === 'function') this[method]($event);
735
842
  };
736
843
  this.renderRoot.addEventListener(event, listener);
737
844
  this._listeners.set(event, listener);
@@ -881,7 +988,12 @@ ${body}
881
988
  }`;
882
989
  }).join(`
883
990
 
884
- `), scope = component.scope, destructured = [...new Set([...Object.keys(component.properties), ...scope.propNames])].map((name) => {
991
+ `), scope = component.scope, localNames = new Set(new Tokenizer([scope.body, ...scope.imports, ...Object.keys(component.properties), ...Object.values(scope.propBindings)].join(`
992
+ `)).tokenize().map((token) => token.value));
993
+ let scopeOwner = "__stxScope";
994
+ while (localNames.has(scopeOwner))
995
+ scopeOwner += "$";
996
+ const destructured = [...new Set([...Object.keys(component.properties), ...scope.propNames])].map((name) => {
885
997
  const binding = scope.propBindings[name] || name;
886
998
  return scope.defaults[name] === void 0 ? binding : `${binding} = ${scope.defaults[name]}`;
887
999
  }).join(", "), indent = (code) => code.split(`
@@ -890,10 +1002,15 @@ ${body}
890
1002
  let renderMethod = "";
891
1003
  if (component.render.trim() !== "" || scope.body !== "" || destructured !== "") {
892
1004
  const inner = [
1005
+ scope.apis.length ? `const ${scopeOwner} = this._beginScope();
1006
+ const { ${scope.apis.join(", ")} } = ${scopeOwner};` : "",
893
1007
  destructured ? `const { ${destructured} } = this._props();` : "",
894
1008
  scope.body,
1009
+ component.scopeMethods.length ? `this._scopeMethods = { ${component.scopeMethods.join(", ")} };` : "",
1010
+ component.handlers.length ? "this._handlers = [];" : "",
895
1011
  "let out = '';",
896
1012
  component.render,
1013
+ scope.apis.length ? `${scopeOwner}.finish();` : "",
897
1014
  "return out;"
898
1015
  ].filter(Boolean).join(`
899
1016
  `);
@@ -943,13 +1060,31 @@ export function typeForProperty(property) {
943
1060
  }
944
1061
  }
945
1062
  function componentDeclaration(component) {
946
- const props = Object.entries(component.properties).map(([name, property]) => ` ${name}${property.required ? "" : "?"}: ${typeForProperty(property)}`).join(`
947
- `), events = Object.entries(component.events).map(([name, event]) => ` ${JSON.stringify(name)}: CustomEvent<${event.detailType || "unknown"}>`).join(`
1063
+ const authoredTypes = [component.declarationTypes, component.declarationImports, component.name, ...Object.values(component.methodDeclarations).flat(), ...Object.values(component.events).map((event) => event.detailType)].join(`
1064
+ `), identifiers = new Set(new Tokenizer(authoredTypes).tokenize().map((token) => token.value)), unique = (base) => {
1065
+ let name = base;
1066
+ while (identifiers.has(name))
1067
+ name += "$";
1068
+ identifiers.add(name);
1069
+ return name;
1070
+ }, support = unique("__StxSupport"), publicMethods = unique("__Methods"), eventDetails = unique("__Details"), scoped = !!component.declarationTypes, props = Object.entries(component.properties).map(([name, property]) => ` ${name}${property.required ? "" : "?"}: ${typeForProperty(property)}`).join(`
1071
+ `), events = Object.entries(component.events).map(([name, event]) => ` ${JSON.stringify(name)}: CustomEvent<${scoped ? `${support}.${eventDetails}[${JSON.stringify(name)}]` : event.detailType || "unknown"}>`).join(`
948
1072
  `), methods = Object.keys(component.methods).flatMap((name) => component.methodDeclarations[name] || [`${name}($event?: Event): unknown`]).map((signature) => ` ${signature}`).join(`
949
- `);
950
- return `${component.declarationTypes ? `${component.declarationTypes}
1073
+ `), supportDeclaration = scoped ? `declare namespace ${support} {
1074
+ ${component.declarationTypes}
1075
+ export interface ${publicMethods} {
1076
+ ${methods}
1077
+ }
1078
+ export interface ${eventDetails} {
1079
+ ${Object.entries(component.events).map(([name, event]) => ` ${JSON.stringify(name)}: ${event.detailType || "unknown"}`).join(`
1080
+ `)}
1081
+ }
1082
+ }
1083
+
1084
+ ` : "";
1085
+ return `${component.declarationImports ? component.declarationImports + `
951
1086
 
952
- ` : ""}export interface ${component.name}Props {
1087
+ ` : ""}${supportDeclaration}export interface ${component.name}Props {
953
1088
  ${props}
954
1089
  }
955
1090
 
@@ -957,10 +1092,16 @@ export interface ${component.name}EventMap {
957
1092
  ${events}
958
1093
  }
959
1094
 
960
- export interface ${component.name} extends Required<Pick<${component.name}Props, Exclude<keyof ${component.name}Props, keyof HTMLElement>>> {}
1095
+ export interface ${component.name} extends Required<Pick<${component.name}Props, Exclude<keyof ${component.name}Props, keyof HTMLElement>>>${scoped ? `, ${support}.${publicMethods}` : ""} {}
961
1096
 
962
1097
  export declare class ${component.name} extends HTMLElement {
963
- ${methods}
1098
+ ${scoped ? "" : methods}
1099
+ addEventListener<K extends keyof ${component.name}EventMap>(type: K, listener: (this: ${component.name}, event: ${component.name}EventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void
1100
+ addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void
1101
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void
1102
+ removeEventListener<K extends keyof ${component.name}EventMap>(type: K, listener: (this: ${component.name}, event: ${component.name}EventMap[K]) => unknown, options?: boolean | EventListenerOptions): void
1103
+ removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void
1104
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void
964
1105
  readonly updateComplete: Promise<void>
965
1106
  requestUpdate(): Promise<void>
966
1107
  emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
@@ -982,7 +1123,7 @@ function customElementsDeclaration(components) {
982
1123
  ${components.map((component) => {
983
1124
  const props = Object.entries(component.properties).map(([name, property]) => ` ${JSON.stringify(name)}?: ${typeForProperty(property)}`).join(`
984
1125
  `), events = Object.keys(component.events).map((event) => {
985
- return ` ${`on${event.split(/[-:]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("")}`}?: (event: CustomEvent<${component.events[event].detailType || "unknown"}>) => void`;
1126
+ return ` ${`on${event.split(/[-:]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("")}`}?: (event: import('./${component.tag}.js').${component.name}EventMap[${JSON.stringify(event)}]) => void`;
986
1127
  }).join(`
987
1128
  `);
988
1129
  return ` ${JSON.stringify(component.tag)}: {
@@ -1116,8 +1257,10 @@ export async function buildComponentLibrary(config) {
1116
1257
  if (!files.includes(target))
1117
1258
  files.push(target);
1118
1259
  return target;
1119
- };
1120
- await emit("runtime.js", runtimeModule());
1260
+ }, signals = components.some((component) => component.scope.apis.length), extension = import.meta.url.endsWith(".ts") ? ".ts" : ".js", nativeSignals = new URL(`./signals-api${extension}`, import.meta.url).pathname;
1261
+ if (signals)
1262
+ await emit("signals.js", `export * from ${JSON.stringify(nativeSignals)};`);
1263
+ await emit("runtime.js", runtimeModule(signals));
1121
1264
  for (const component of components) {
1122
1265
  await emit(`${component.tag}.js`, componentModule(component));
1123
1266
  if (config.declarations !== !1)
@@ -1128,11 +1271,15 @@ export async function buildComponentLibrary(config) {
1128
1271
  }
1129
1272
  }
1130
1273
  const importScanner = new Bun.Transpiler({ loader: "ts" });
1131
- if (components.some((component) => component.scope.imports.length || importScanner.scanImports(componentModule(component)).some((imported) => imported.kind === "dynamic-import"))) {
1274
+ if (signals || components.some((component) => component.scope.imports.length || importScanner.scanImports(componentModule(component)).some((imported) => imported.kind === "dynamic-import"))) {
1132
1275
  const entrypoints = components.map((component) => path.join(outputDir, `${component.tag}.js`)), canonicalEntries = new Map(await Promise.all(entrypoints.map(async (file, index) => [await realpath(file), components[index]])));
1133
1276
  for (const [index, file] of entrypoints.entries())
1134
1277
  canonicalEntries.set(file, components[index]);
1135
- const sourceEntries = new Map(components.map((component) => [path.join(path.dirname(component.sourcePath), `.stx-library-${component.tag}.ts`), component])), runtimePath = path.join(outputDir, "runtime.js"), built = await Bun.build({
1278
+ const sourceEntries = new Map(components.map((component) => [path.join(path.dirname(component.sourcePath), `.stx-library-${component.tag}.ts`), component])), runtimePath = path.join(outputDir, "runtime.js");
1279
+ entrypoints.push(runtimePath);
1280
+ if (signals)
1281
+ entrypoints.push(path.join(outputDir, "signals.js"));
1282
+ const built = await Bun.build({
1136
1283
  entrypoints,
1137
1284
  outdir: outputDir,
1138
1285
  root: outputDir,
@@ -1150,7 +1297,9 @@ export async function buildComponentLibrary(config) {
1150
1297
  if (!args.importer && entry)
1151
1298
  return { path: path.join(path.dirname(entry.sourcePath), `.stx-library-${entry.tag}.ts`) };
1152
1299
  if (args.path === runtimePath && sourceEntries.has(args.importer))
1153
- return { path: "./runtime.js", external: !0 };
1300
+ return { path: runtimePath };
1301
+ if (/^(?:@stacksjs\/stx|stx)\/signals-api(?:\.[jt]s)?$/.test(args.path))
1302
+ return { path: nativeSignals };
1154
1303
  });
1155
1304
  builder.onLoad({ filter: /\.ts$/ }, (args) => {
1156
1305
  const component = sourceEntries.get(args.path);
@@ -74,7 +74,8 @@ export declare function setGlobalProvide<T>(key: string | symbol, value: T): voi
74
74
  * emit('change', 'newValue')
75
75
  * ```
76
76
  */
77
- export declare function defineEmits<T extends Record<string, any[]> = Record<string, any[]>>(events?: string[] | T): EmitFn<Extract<keyof T, string>>;
77
+ export declare function defineEmits<const T extends readonly string[]>(events: T): EmitFn<T[number]>;
78
+ export declare function defineEmits<T extends object = Record<string, any[]>>(events?: T): ComponentEmit<T>;
78
79
  /**
79
80
  * Expose public properties from a component instance.
80
81
  * These properties become accessible via template refs from the parent.
@@ -195,3 +196,8 @@ export declare interface StxComponentInstance {
195
196
  /** Type-safe emit function */
196
197
  // eslint-disable-next-line pickier/no-unused-vars
197
198
  export type EmitFn<T extends string = string> = (event: T, ...args: any[]) => void;
199
+ /** Tuple maps, payload maps and callable overload contracts share one emitter. */
200
+ export type ComponentEmit<T> = T extends (...args: never[]) => unknown ? T : <K extends Extract<keyof T, string>>(
201
+ event: K,
202
+ ...args: T[K] extends readonly unknown[] ? T[K] : [payload: T[K]]
203
+ ) => void;
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunk-gz9pknbw.js";import{Vo,Ua,Wa}from"./chunk-cmg9x1ka.js";import"./chunk-mw7hacm3.js";import"./chunk-2a5g80mq.js";import"./chunk-3dqfjpz4.js";import"./chunk-mgh5rst1.js";import"./chunk-vk2jy6mn.js";import"./chunk-9n5h4sqc.js";import"./chunk-eyx92t9n.js";import"./chunk-s93yh7ed.js";import"./chunk-q0y8gv18.js";import"./chunk-eceeqy74.js";import"./chunk-p8shtje2.js";import"./chunk-95sd8h5g.js";import"./chunk-rb2zbdqd.js";import"./chunk-9d91h636.js";import"./chunk-vc432a0w.js";import"./chunk-mt8edb75.js";import"./chunk-hgf7bc50.js";import"./chunk-48rwqchc.js";import"./chunk-4kmg6g5n.js";import"./chunk-dymck524.js";import"./chunk-05x1rd86.js";import"./chunk-pz554g43.js";import{Hu,qa,Xh,Jh,Ka,Uo,hs,Ga,Xa,Yh,Zh,Ja,Ya,Za,Qa}from"./chunk-6kyqejnq.js";import"./chunk-f3cyghnb.js";import"./chunk-b0e7dgv8.js";import"./chunk-5kqezrjt.js";import"./chunk-bqtj62ys.js";import"./chunk-pctf14yw.js";import"./chunk-eqffvse2.js";import"./chunk-58qzyyyv.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
2
+ import"./chunk-eq86wzhr.js";import{Vo,Ua,Wa}from"./chunk-cmg9x1ka.js";import"./chunk-whcrca58.js";import"./chunk-0jdz31q1.js";import"./chunk-xmg6bmh6.js";import"./chunk-cphc60zw.js";import"./chunk-vk2jy6mn.js";import"./chunk-3b3mkgpj.js";import"./chunk-41z7f41b.js";import"./chunk-g3vce7ka.js";import"./chunk-q0y8gv18.js";import"./chunk-8ccgty8s.js";import"./chunk-yesh4dfe.js";import"./chunk-t3zmfh8w.js";import"./chunk-rb2zbdqd.js";import"./chunk-b0hj8eg2.js";import"./chunk-adsqckg4.js";import"./chunk-6svc4kb8.js";import"./chunk-vkfw9k1n.js";import"./chunk-v90nz5xm.js";import"./chunk-vxbvrbqs.js";import"./chunk-hyyh7qxw.js";import"./chunk-05x1rd86.js";import"./chunk-pvm48tse.js";import{Hu,qa,Xh,Jh,Ka,Uo,hs,Ga,Xa,Yh,Zh,Ja,Ya,Za,Qa}from"./chunk-p0bjbtdx.js";import"./chunk-1t15z230.js";import"./chunk-vfcbz0an.js";import"./chunk-80ky40mm.js";import"./chunk-kg7vby72.js";import"./chunk-9rjgq8k4.js";import"./chunk-n6q1d66k.js";import"./chunk-qnf7w4xw.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
3
3
  `),scripts:t.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
5
5
  `),scripts:t.scripts.join(`
package/dist/craft.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunk-gz9pknbw.js";import{Vo,Ua,Wa}from"./chunk-cmg9x1ka.js";import"./chunk-mw7hacm3.js";import"./chunk-2a5g80mq.js";import"./chunk-3dqfjpz4.js";import"./chunk-mgh5rst1.js";import"./chunk-vk2jy6mn.js";import"./chunk-9n5h4sqc.js";import"./chunk-eyx92t9n.js";import"./chunk-s93yh7ed.js";import"./chunk-q0y8gv18.js";import"./chunk-eceeqy74.js";import"./chunk-p8shtje2.js";import"./chunk-95sd8h5g.js";import"./chunk-rb2zbdqd.js";import"./chunk-9d91h636.js";import"./chunk-vc432a0w.js";import"./chunk-mt8edb75.js";import"./chunk-hgf7bc50.js";import"./chunk-48rwqchc.js";import"./chunk-4kmg6g5n.js";import"./chunk-dymck524.js";import"./chunk-05x1rd86.js";import"./chunk-pz554g43.js";import{Hu,qa,Xh,Jh,Ka,Uo,hs,Ga,Xa,Yh,Zh,Ja,Ya,Za,Qa}from"./chunk-6kyqejnq.js";import"./chunk-f3cyghnb.js";import"./chunk-b0e7dgv8.js";import"./chunk-5kqezrjt.js";import"./chunk-bqtj62ys.js";import"./chunk-pctf14yw.js";import"./chunk-eqffvse2.js";import"./chunk-58qzyyyv.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
2
+ import"./chunk-eq86wzhr.js";import{Vo,Ua,Wa}from"./chunk-cmg9x1ka.js";import"./chunk-whcrca58.js";import"./chunk-0jdz31q1.js";import"./chunk-xmg6bmh6.js";import"./chunk-cphc60zw.js";import"./chunk-vk2jy6mn.js";import"./chunk-3b3mkgpj.js";import"./chunk-41z7f41b.js";import"./chunk-g3vce7ka.js";import"./chunk-q0y8gv18.js";import"./chunk-8ccgty8s.js";import"./chunk-yesh4dfe.js";import"./chunk-t3zmfh8w.js";import"./chunk-rb2zbdqd.js";import"./chunk-b0hj8eg2.js";import"./chunk-adsqckg4.js";import"./chunk-6svc4kb8.js";import"./chunk-vkfw9k1n.js";import"./chunk-v90nz5xm.js";import"./chunk-vxbvrbqs.js";import"./chunk-hyyh7qxw.js";import"./chunk-05x1rd86.js";import"./chunk-pvm48tse.js";import{Hu,qa,Xh,Jh,Ka,Uo,hs,Ga,Xa,Yh,Zh,Ja,Ya,Za,Qa}from"./chunk-p0bjbtdx.js";import"./chunk-1t15z230.js";import"./chunk-vfcbz0an.js";import"./chunk-80ky40mm.js";import"./chunk-kg7vby72.js";import"./chunk-9rjgq8k4.js";import"./chunk-n6q1d66k.js";import"./chunk-qnf7w4xw.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
3
3
  `),scripts:t.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
5
5
  `),scripts:t.scripts.join(`
@@ -0,0 +1,9 @@
1
+ import type { ComponentLibraryEvent } from './types.js';
2
+ export declare function parseEmitsDeclaration(code: string): EmitsDeclaration | null;
3
+ export declare interface EmitsDeclaration {
4
+ text: string
5
+ start: number
6
+ end: number
7
+ typeName?: string
8
+ events: Record<string, ComponentLibraryEvent>
9
+ }
@@ -0,0 +1,64 @@
1
+ import { macroCall } from "./component-contract.js";
2
+ import { parseStringLiteral } from "./directive-arguments.js";
3
+ import { Tokenizer } from "./parser/tokenizer.js";
4
+ import { localType, skipBalanced, splitTopLevel } from "./props-declaration.js";
5
+ function eventName(raw) {
6
+ const name = raw.trim();
7
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : parseStringLiteral(name) ?? void 0;
8
+ }
9
+ function detailFromTuple(tuple) {
10
+ const members = splitTopLevel(tuple.trim().slice(1, -1), ",", !0);
11
+ if (members.length !== 1)
12
+ return tuple.trim();
13
+ const member = members[0];
14
+ if (member.startsWith("..."))
15
+ return tuple.trim();
16
+ const labelled = /^(?:[A-Za-z_$][\w$]*)(\?)?\s*:\s*([\s\S]+)$/.exec(member), optional = labelled ? !!labelled[1] : member.endsWith("?"), type = labelled ? labelled[2] : optional ? member.slice(0, -1).trim() : member;
17
+ return optional ? `(${type}) | undefined | []` : type;
18
+ }
19
+ export function parseEmitsDeclaration(code) {
20
+ const call = macroCall(code, ["defineEmits"], !0);
21
+ if (!call)
22
+ return null;
23
+ const events = Object.create(null), typeName = /^[A-Za-z_$][\w$]*$/.test(call.type.trim()) ? call.type.trim() : void 0, type = typeName ? localType(code, typeName) : call.type.trim();
24
+ if (type?.startsWith("{"))
25
+ for (const member of splitTopLevel(type.slice(1, -1), `;,
26
+ `, !0)) {
27
+ if (member.startsWith("(")) {
28
+ const end = skipBalanced(member, 0, "(", ")");
29
+ if (end < 0)
30
+ continue;
31
+ const parameters = splitTopLevel(member.slice(1, end - 1), ",", !0), first = parameters.shift() || "", colon = first.indexOf(":");
32
+ if (colon < 0)
33
+ continue;
34
+ for (const literal of splitTopLevel(first.slice(colon + 1), "|", !0)) {
35
+ const name = eventName(literal);
36
+ if (name !== void 0)
37
+ events[name] = { detailType: detailFromTuple(`[${parameters.join(", ")}]`) };
38
+ }
39
+ continue;
40
+ }
41
+ const tokens = new Tokenizer(member, "javascript").tokenize().filter((token) => !["WHITESPACE", "COMMENT", "EOF"].includes(token.type)), key = tokens[0], colon = tokens.findIndex((token) => token.value === ":");
42
+ if (!key || colon < 0)
43
+ continue;
44
+ const name = eventName(key.value), value = member.slice(tokens[colon].end).trim();
45
+ if (name !== void 0)
46
+ events[name] = { detailType: value.startsWith("[") ? detailFromTuple(value) : value };
47
+ }
48
+ else {
49
+ const argument = call.args[0]?.trim() || "";
50
+ if (argument.startsWith("["))
51
+ for (const item of splitTopLevel(argument.slice(1, -1), ",", !1)) {
52
+ const name = eventName(item);
53
+ if (name !== void 0)
54
+ events[name] = { detailType: "unknown" };
55
+ }
56
+ else if (argument.startsWith("{"))
57
+ for (const member of splitTopLevel(argument.slice(1, -1), ",", !1)) {
58
+ const key = new Tokenizer(member, "javascript").tokenize().find((token) => !["WHITESPACE", "COMMENT"].includes(token.type)), name = key && eventName(key.value);
59
+ if (name !== void 0)
60
+ events[name] = { detailType: "unknown" };
61
+ }
62
+ }
63
+ return { ...call, text: code.slice(call.start, call.end), typeName, events };
64
+ }
@@ -51,6 +51,8 @@ export declare function parsePropsDeclaration(source: string): PropsDeclaration
51
51
  export declare function parseDefaults(object: string): Array<[string, string]>;
52
52
  /** Literal defaults only: no client functions, imports, identifiers or getters run in SSR. */
53
53
  export declare function literalValue(source: string): unknown;
54
+ /** Resolve local macro-support types with the same balanced scanner as props. */
55
+ export declare function localType(code: string, name: string): string | undefined;
54
56
  declare interface PropsDeclaration {
55
57
  text: string
56
58
  propNames: string[]