quickwin 2.0.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.en.md +21 -26
  2. package/README.md +3 -6
  3. package/examples/exec_server.js +139 -31
  4. package/examples/exec_server.tsx +7 -8
  5. package/examples/exec_server_worker.js +1 -1
  6. package/examples/exec_server_worker.ts +2 -2
  7. package/examples/pdf_preview2.js +1 -1
  8. package/examples/pdf_preview2.ts +1 -1
  9. package/examples/pdf_viewer.js +132 -28
  10. package/examples/pdf_viewer.tsx +1 -1
  11. package/examples/test_gallery.js +131 -27
  12. package/examples/test_react_lazy.js +131 -27
  13. package/examples/test_react_listbox.js +131 -27
  14. package/examples/test_root_window.js +131 -27
  15. package/examples/test_tab.js +131 -27
  16. package/lib/certs.js +13 -8
  17. package/lib/certs.ts +13 -8
  18. package/lib/fetch.js +51 -3
  19. package/lib/fetch.ts +38 -3
  20. package/lib/ffi/bind.js +94 -5
  21. package/lib/ffi/bind.ts +107 -10
  22. package/lib/ffi/ctype.js +33 -7
  23. package/lib/ffi/ctype.ts +48 -10
  24. package/lib/ffi/struct.js +92 -14
  25. package/lib/ffi/struct.ts +108 -19
  26. package/lib/react-qw/components/ListView.js +1 -0
  27. package/lib/react-qw/components/PathPicker.js +2 -2
  28. package/lib/react-qw/index.js +1 -1
  29. package/lib/react-qw/index.ts +4 -1
  30. package/lib/text-measure.js +3 -1
  31. package/lib/text-measure.ts +4 -3
  32. package/lib/websocket.js +32 -2
  33. package/lib/websocket.ts +25 -2
  34. package/lib/windows/advapi32.js +53 -0
  35. package/lib/windows/advapi32.ts +64 -0
  36. package/lib/windows/comctl32.js +15 -15
  37. package/lib/windows/comctl32.ts +15 -16
  38. package/lib/windows/comdlg32.js +3 -2
  39. package/lib/windows/comdlg32.ts +3 -2
  40. package/lib/windows/gdi32.js +328 -26
  41. package/lib/windows/gdi32.ts +349 -26
  42. package/lib/windows/kernel32.js +206 -10
  43. package/lib/windows/kernel32.ts +225 -10
  44. package/lib/windows/msimg32.js +38 -0
  45. package/lib/windows/msimg32.ts +45 -0
  46. package/lib/windows/ntdll.js +3 -2
  47. package/lib/windows/ntdll.ts +3 -2
  48. package/lib/windows/ole32.js +1 -1
  49. package/lib/windows/ole32.ts +1 -1
  50. package/lib/windows/psapi.js +32 -0
  51. package/lib/windows/psapi.ts +37 -0
  52. package/lib/windows/shell32.js +5 -3
  53. package/lib/windows/shell32.ts +5 -3
  54. package/lib/windows/structs.js +135 -0
  55. package/lib/windows/structs.ts +144 -0
  56. package/lib/windows/user32.js +202 -99
  57. package/lib/windows/user32.ts +204 -99
  58. package/lib/windows/version.js +29 -0
  59. package/lib/windows/version.ts +35 -0
  60. package/lib/windows/winspool.js +71 -0
  61. package/lib/windows/winspool.ts +80 -0
  62. package/package.json +1 -1
  63. package/quickwin.d.ts +11 -5
  64. package/quickwin_const.d.ts +136 -0
  65. package/qwin-nowasm-x86.exe +0 -0
  66. package/qwin-nowasm.exe +0 -0
  67. package/qwin-x86.exe +0 -0
  68. package/qwin.exe +0 -0
  69. package/test/run.js +7 -0
  70. package/test/run.ts +7 -0
  71. package/test/test_basic_fetch.js +21 -0
  72. package/test/test_basic_fetch.ts +17 -0
  73. package/test/test_ffi.js +6 -6
  74. package/test/test_ffi.ts +6 -6
  75. package/test/test_ffi_abi.js +55 -0
  76. package/test/test_ffi_abi.ts +56 -0
  77. package/test/test_ffi_array.js +116 -0
  78. package/test/test_ffi_array.ts +141 -0
  79. package/test/test_ffi_bind.js +82 -0
  80. package/test/test_ffi_bind.ts +71 -0
  81. package/test/test_files.js +102 -0
  82. package/test/test_files.ts +121 -0
  83. package/test/test_gdi_draw.js +681 -0
  84. package/test/test_gdi_draw.ts +725 -0
  85. package/test/test_net_fetch.js +4 -3
  86. package/test/test_net_fetch.ts +4 -3
  87. package/test/test_printer.js +137 -0
  88. package/test/test_printer.ts +148 -0
  89. package/test/test_proc.js +141 -0
  90. package/test/test_proc.ts +163 -0
  91. package/test/test_react_complex.js +131 -27
  92. package/test/test_react_counter.js +131 -27
  93. package/test/test_react_flex.js +131 -27
  94. package/test/test_react_hidden.js +131 -27
  95. package/test/test_react_listview_link.js +131 -27
  96. package/test/test_react_notify.js +131 -27
  97. package/test/test_react_render.js +131 -27
  98. package/test/test_registry.js +74 -0
  99. package/test/test_registry.ts +95 -0
  100. package/test/test_sysinfo.js +122 -0
  101. package/test/test_sysinfo.ts +141 -0
  102. package/test/test_wolfssl_read.js +45 -44
  103. package/test/test_wolfssl_read.ts +42 -42
@@ -15601,10 +15601,18 @@ var C_BASIC_TYPE = [
15601
15601
  "f64",
15602
15602
  "ptr"
15603
15603
  ];
15604
- var PTR_TOKEN_RE = /^<([^<>\s]*)>ptr(!|@[A-Za-z_]\w*)?$/;
15604
+ var PTR_TOKEN_RE = /^<([A-Za-z_]\w*|)>ptr(!|@[A-Za-z_]\w*)?$/;
15605
15605
  function isCPtrToken(t) {
15606
15606
  return PTR_TOKEN_RE.test(t);
15607
15607
  }
15608
+ var VAL_TOKEN_RE = /^<([A-Za-z_]\w*)>$/;
15609
+ function isCValToken(t) {
15610
+ return VAL_TOKEN_RE.test(t);
15611
+ }
15612
+ function valName(t) {
15613
+ const m = VAL_TOKEN_RE.exec(t);
15614
+ return m?.[1] || "";
15615
+ }
15608
15616
  function ptrName(t) {
15609
15617
  const m = PTR_TOKEN_RE.exec(t);
15610
15618
  return m?.[1] || "";
@@ -15612,8 +15620,9 @@ function ptrName(t) {
15612
15620
  var cTokenToType = (t) => {
15613
15621
  if (isCPtrToken(t))
15614
15622
  return "ptr";
15615
- else
15616
- return t;
15623
+ if (isCValToken(t))
15624
+ throw new Error(`ffi: cTokenToType: by-value token "${t}" has no scalar slot type`);
15625
+ return t;
15617
15626
  };
15618
15627
  var PTR_SIZE = os.arch === "x64" ? 8 : 4;
15619
15628
  var SizeAlign = {
@@ -15632,8 +15641,12 @@ var NULL = 0;
15632
15641
  function normToken(t) {
15633
15642
  if (isCPtrToken(t)) {
15634
15643
  const m = PTR_TOKEN_RE.exec(t);
15635
- return m?.[2]?.startsWith("@") ? `<${m[1]}>ptr` : t;
15644
+ const name = m?.[1] || "";
15645
+ const mod = m?.[2];
15646
+ return mod?.startsWith("@") ? `<${name}>ptr` : t;
15636
15647
  }
15648
+ if (isCValToken(t))
15649
+ return t;
15637
15650
  const at = t.indexOf("@");
15638
15651
  const base = at >= 0 ? t.slice(0, at) : t;
15639
15652
  const suffixOk = at < 0 || /^[A-Za-z_]\w*$/.test(t.slice(at + 1));
@@ -15729,6 +15742,9 @@ var PtrArrayBuffer = class extends ArrayBuffer {
15729
15742
  };
15730
15743
 
15731
15744
  // _build/lib/ffi/bind.js
15745
+ function valCodec(name, encoders) {
15746
+ return encoders[name];
15747
+ }
15732
15748
  var _dllCache = /* @__PURE__ */ new Map();
15733
15749
  function loadDll(dll) {
15734
15750
  const cached = _dllCache.get(dll);
@@ -15754,14 +15770,27 @@ function parseSig(sig) {
15754
15770
  }
15755
15771
  argTokens.push(tok);
15756
15772
  }
15773
+ const retToken = normToken(parts[1]);
15774
+ if (isCValToken(retToken))
15775
+ throw new Error(`ffi-bind: "${sig}": by-value struct at the return position (<${valName(retToken)}>) is not supported \u2014 argument positions only; pass a struct out through an out-param slot instead (<N>ptr + caller buffer)`);
15757
15776
  return {
15758
15777
  argTokens,
15759
- retToken: normToken(parts[1]),
15778
+ retToken,
15760
15779
  sig
15761
15780
  };
15762
15781
  }
15763
15782
  function makeFn(proc, sig, encoders, decoders) {
15764
15783
  const ps = parseSig(sig);
15784
+ for (const t of ps.argTokens) {
15785
+ if (!isCValToken(t))
15786
+ continue;
15787
+ const name = valName(t);
15788
+ const codec = valCodec(name, encoders);
15789
+ if (!codec || typeof codec.encode !== "function")
15790
+ throw new Error(`ffi-bind: ${sig}: by-value position <${name}> has no registered layout (available: ${Object.keys(encoders).join(", ") || "none"})`);
15791
+ if (typeof codec.size !== "number" || codec.size < 1)
15792
+ throw new Error(`ffi-bind: ${sig}: by-value position <${name}> requires a struct layout with size >= 1 (got ${codec.size}; non-struct codecs expose no size)`);
15793
+ }
15765
15794
  return (...a) => callPacked(proc, ps, a, encoders, decoders);
15766
15795
  }
15767
15796
  var IA32_ARG_SIZE = {
@@ -15781,15 +15810,29 @@ var X64_MIN_SLOTS = 4;
15781
15810
  function callPacked(proc, { argTokens, retToken, sig }, args, encoders, decoders) {
15782
15811
  const is64 = os2.arch === "x64";
15783
15812
  const getWidth = (t, is642) => {
15813
+ if (isCValToken(t))
15814
+ throw new Error(`ffi-bind: getWidth: by-value token "${t}" (dispatched by widthOf)`);
15784
15815
  if (is642)
15785
15816
  return 8;
15786
15817
  if (isCPtrToken(t))
15787
15818
  return PTR_SIZE;
15788
15819
  return IA32_ARG_SIZE[t];
15789
15820
  };
15821
+ const widthOf = (t) => {
15822
+ if (isCValToken(t)) {
15823
+ if (is64)
15824
+ return 8;
15825
+ const layout = valCodec(valName(t), encoders);
15826
+ if (!layout)
15827
+ throw new Error(`ffi-bind: <${valName(t)}> by-value position has no registered layout`);
15828
+ const size = layout.size;
15829
+ return size % 4 === 0 ? size : size + 4 - size % 4;
15830
+ }
15831
+ return getWidth(t, is64);
15832
+ };
15790
15833
  let total = 0;
15791
15834
  for (const t of argTokens)
15792
- total += getWidth(t, is64);
15835
+ total += widthOf(t);
15793
15836
  if (is64 && argTokens.length < X64_MIN_SLOTS)
15794
15837
  total = X64_MIN_SLOTS * 8;
15795
15838
  const argFrame = new ArrayBuffer(total);
@@ -15826,10 +15869,28 @@ function callPacked(proc, { argTokens, retToken, sig }, args, encoders, decoders
15826
15869
  throw new Error(`ffi-bind: ${sig}: arg#${i + 1} <${name}>ptr! encode produced 0 (null pointer forbidden here)`);
15827
15870
  writeSlot(dv, off, { k: "ptr", v: p });
15828
15871
  }
15872
+ } else if (isCValToken(argToken)) {
15873
+ const name = valName(argToken);
15874
+ const codec = valCodec(name, encoders);
15875
+ if (!codec)
15876
+ throw new Error(`ffi-bind: ${sig}: arg#${i + 1} <${name}> by-value position has no registered layout`);
15877
+ if (arg === null || arg === void 0)
15878
+ throw new Error(`ffi-bind: <${name}> value position got ${String(arg)}; pass a struct object (use <${name}>ptr to pass a pointer)`);
15879
+ const size = codec.size;
15880
+ if (!is64 || size <= 8 && (size & size - 1) === 0) {
15881
+ codec.encode(arg, argFrame, off);
15882
+ } else {
15883
+ const buf = new ArrayBuffer(size + 15);
15884
+ const base = ffi.bufferPtr(buf);
15885
+ const pad = (16 - base % 16) % 16;
15886
+ codec.encode(arg, buf, pad);
15887
+ held.push(buf);
15888
+ writeSlot(dv, off, { k: "ptr", v: base + pad });
15889
+ }
15829
15890
  } else {
15830
15891
  writeSlot(dv, off, { k: argToken, v: arg });
15831
15892
  }
15832
- off += getWidth(argToken, is64);
15893
+ off += widthOf(argToken);
15833
15894
  }
15834
15895
  const retBuf = new ArrayBuffer(8);
15835
15896
  const retIsFp = retToken === "f32" || retToken === "f64";
@@ -16220,21 +16281,20 @@ function createStruct(t) {
16220
16281
  size,
16221
16282
  structAlign: maxEffectiveAlign,
16222
16283
  decode: (p) => {
16223
- if (typeof p === "number") {
16224
- const buf = new ArrayBuffer(size);
16225
- const u8 = new Uint8Array(buf);
16226
- for (let i = 0; i < size; i++)
16227
- u8[i] = ffi2.readByte(p + i);
16228
- return doDecode(new DataView(buf), 0, fields);
16229
- }
16284
+ if (typeof p === "number")
16285
+ return doDecode(new DataView(ffi2.readBytes(p, size)), 0, fields);
16230
16286
  return doDecode(new DataView(p), 0, fields);
16231
16287
  },
16232
- alloc: (() => new PtrArrayBuffer(size)),
16233
- encode: ((v, buf) => {
16288
+ alloc: ((n) => {
16289
+ if (n !== void 0 && (!Number.isInteger(n) || n < 1))
16290
+ throw new Error(`ffi-struct: alloc(n) requires an integer n >= 1 (PAB(0) never escapes \u2014 pass NULL for an empty pointer position)`);
16291
+ return new PtrArrayBuffer(size * (n ?? 1));
16292
+ }),
16293
+ encode: ((v, buf, offset) => {
16234
16294
  if (v === void 0 || v === null)
16235
16295
  throw new Error(`ffi-struct: encode(v) requires an argument; use alloc() for a zeroed out-param slot`);
16236
16296
  const out = buf ?? new PtrArrayBuffer(size);
16237
- doEncode(new DataView(out), 0, fields, v);
16297
+ doEncode(new DataView(out), offset ?? 0, fields, v);
16238
16298
  return out;
16239
16299
  }),
16240
16300
  offsetOf: (name) => {
@@ -16254,6 +16314,49 @@ function buildDecl(kind, member, pack) {
16254
16314
  decl[k] = v;
16255
16315
  return decl;
16256
16316
  }
16317
+ function structArray(def) {
16318
+ const { fields, size } = computeStructLayout(def.__struct);
16319
+ const readN = (dv, n) => {
16320
+ const out = [];
16321
+ for (let i = 0; i < n; i++)
16322
+ out.push(doDecode(dv, i * size, fields));
16323
+ return out;
16324
+ };
16325
+ return {
16326
+ encode: (els) => {
16327
+ if (!Array.isArray(els) || els.length === 0)
16328
+ throw new Error(`ffi-struct: structArray(def).encode(els) requires a non-empty element array (pass NULL for an empty pointer position)`);
16329
+ const out = def.alloc(els.length);
16330
+ for (let i = 0; i < els.length; i++)
16331
+ def.encode(els[i], out, i * def.size);
16332
+ return out;
16333
+ },
16334
+ decode: ((p, count) => {
16335
+ if (count !== void 0 && (!Number.isInteger(count) || count < 0))
16336
+ throw new Error(`ffi-struct: structArray.decode(p, count) requires a non-negative integer count, got ${count}`);
16337
+ if (typeof p === "number") {
16338
+ if (count === void 0)
16339
+ throw new Error(`ffi-struct: structArray.decode(address, count) requires an explicit count (a bare address carries no length)`);
16340
+ if (count === 0)
16341
+ return [];
16342
+ return readN(new DataView(ffi2.readBytes(p, count * size)), count);
16343
+ }
16344
+ let n;
16345
+ if (count !== void 0) {
16346
+ n = count;
16347
+ if (n * size > p.byteLength)
16348
+ throw new Error(`ffi-struct: structArray.decode: count ${n} \xD7 size ${size} = ${n * size} exceeds buffer byteLength ${p.byteLength}`);
16349
+ } else {
16350
+ if (p.byteLength % size !== 0)
16351
+ throw new Error(`ffi-struct: structArray.decode: byteLength ${p.byteLength} is not a multiple of size ${size} (mixed buffer? pass count explicitly)`);
16352
+ n = p.byteLength / size;
16353
+ }
16354
+ if (n === 0)
16355
+ return [];
16356
+ return readN(new DataView(p), n);
16357
+ })
16358
+ };
16359
+ }
16257
16360
  function struct(a, b6, c) {
16258
16361
  const isNamed = typeof a === "string";
16259
16362
  const raw = isNamed ? b6 : a;
@@ -16503,11 +16606,12 @@ import * as os4 from "os";
16503
16606
 
16504
16607
  // _build/lib/windows/gdi32.js
16505
16608
  var b2 = (name, sig, encoders) => bind("gdi32.dll", name, sig, encoders);
16506
- var DeleteObject = /* @__PURE__ */ b2("DeleteObject", "<>ptr -> i32");
16609
+ var POINTArr = structArray(POINT);
16610
+ var DeleteObject = /* @__PURE__ */ b2("DeleteObject", "<HGDIOBJ>ptr -> i32");
16507
16611
  var GetDeviceCaps = /* @__PURE__ */ b2("GetDeviceCaps", "<HDC>ptr! i32@DeviceCap -> i32");
16508
- var CreateFontIndirect = /* @__PURE__ */ b2("CreateFontIndirectW", "<LOGFONTW>ptr -> <>ptr", { LOGFONTW });
16509
- var SelectObject = /* @__PURE__ */ b2("SelectObject", "<HDC>ptr! <>ptr -> <>ptr");
16510
- var GetObject = /* @__PURE__ */ b2("GetObjectW", "<>ptr i32 <BYTE>ptr -> i32");
16612
+ var CreateFontIndirect = /* @__PURE__ */ b2("CreateFontIndirectW", "<LOGFONTW>ptr -> <HGDIOBJ>ptr", { LOGFONTW });
16613
+ var SelectObject = /* @__PURE__ */ b2("SelectObject", "<HDC>ptr! <HGDIOBJ>ptr -> <HGDIOBJ>ptr");
16614
+ var GetObject = /* @__PURE__ */ b2("GetObjectW", "<HGDIOBJ>ptr i32 <BYTE>ptr -> i32");
16511
16615
 
16512
16616
  // _build/lib/react-qw/props.js
16513
16617
  import * as gui from "gui";
@@ -16654,7 +16758,7 @@ function measureTextForHwnd(hwnd2, text) {
16654
16758
  if (!hdc)
16655
16759
  return { width: 0, height: 0 };
16656
16760
  const hFont = gui2.SendMessage(hwnd2, 49, 0, 0);
16657
- const oldFont = hFont ? SelectObject(hdc, hFont) : 0;
16761
+ const oldFont = hFont ? SelectObject(hdc, hFont) : NULL;
16658
16762
  const result = measureText(hdc, text, 0);
16659
16763
  if (hFont)
16660
16764
  SelectObject(hdc, oldFont);
@@ -18039,11 +18143,11 @@ var import_react17 = __toESM(require_react(), 1);
18039
18143
 
18040
18144
  // _build/lib/windows/comdlg32.js
18041
18145
  var b3 = (name, sig) => bind("comdlg32.dll", name, sig);
18042
- var GetOpenFileName = /* @__PURE__ */ b3("GetOpenFileNameW", "<BYTE>ptr -> u32");
18146
+ var GetOpenFileName = /* @__PURE__ */ b3("GetOpenFileNameW", "<OPENFILENAMEW>ptr -> u32");
18043
18147
 
18044
18148
  // _build/lib/windows/shell32.js
18045
18149
  var b4 = (name, sig) => bind("shell32.dll", name, sig);
18046
- var SHBrowseForFolder = /* @__PURE__ */ b4("SHBrowseForFolderW", "<BYTE>ptr -> <>ptr");
18150
+ var SHBrowseForFolder = /* @__PURE__ */ b4("SHBrowseForFolderW", "<BROWSEINFOW>ptr -> <>ptr");
18047
18151
  var SHGetPathFromIDList = /* @__PURE__ */ b4("SHGetPathFromIDListW", "<>ptr <BYTE>ptr -> u32");
18048
18152
 
18049
18153
  // _build/lib/windows/ole32.js
@@ -18068,7 +18172,7 @@ function openFileDialog(owner, filter, title, multiple) {
18068
18172
  lpstrTitle: titleWide?.ptr ?? 0,
18069
18173
  Flags: flags
18070
18174
  });
18071
- const ret = GetOpenFileName(ofn);
18175
+ const ret = GetOpenFileName(ofn.ptr);
18072
18176
  if (!ret)
18073
18177
  return null;
18074
18178
  if (!multiple) {
@@ -18086,7 +18190,7 @@ function openFolderDialog(owner, title) {
18086
18190
  lpszTitle: titleWide?.ptr ?? 0,
18087
18191
  ulFlags: 65
18088
18192
  });
18089
- const pidl = SHBrowseForFolder(bi);
18193
+ const pidl = SHBrowseForFolder(bi.ptr);
18090
18194
  if (!pidl)
18091
18195
  return null;
18092
18196
  const pathBuf = WCHAR.alloc(260);
@@ -18181,7 +18285,7 @@ function createRoot(container) {
18181
18285
  } else {
18182
18286
  hwnd2 = container;
18183
18287
  }
18184
- const root = reconciler_default.createContainer(hwnd2, 0, null, false, null, "", noop, noop, noop, noop);
18288
+ const root = reconciler_default.createContainer(hwnd2, 0, null, false, null, "", (error, info) => console.log("[React uncaught]", error, error.stack, info.componentStack), (error, info) => console.log("[React caught]", error, error.stack, info.componentStack), (error, info) => console.log("[React recoverable]", error, error.stack, info.componentStack), noop);
18185
18289
  const rootInst = { hwnd: hwnd2, type: "_root", props: { type: "_root", style: { flexDirection: "column", alignItems: "stretch" } }, children: [] };
18186
18290
  instancesByHwnd.set(hwnd2, rootInst);
18187
18291
  if (typeof container === "object")
package/lib/certs.js CHANGED
@@ -203,12 +203,17 @@ tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1
203
203
  /q4AaOeMSQ+2b1tbFfLn
204
204
  -----END CERTIFICATE-----`;
205
205
  // Register at import time. Importers of this module get the anchors
206
- // without writing any code themselves.
207
- wolfssl.addTrustedCA(GLOBALSIGN_R3);
208
- wolfssl.addTrustedCA(GLOBALSIGN_R1);
209
- wolfssl.addTrustedCA(USERTRUST_ECC_CA);
210
- wolfssl.addTrustedCA(DIGICERT_GLOBAL_G2);
211
- wolfssl.addTrustedCA(GLOBALSIGN_R46);
212
- wolfssl.addTrustedCA(ISRG_X1);
213
- wolfssl.addTrustedCA(ISRG_X2);
206
+ // without writing any code themselves. addTrustedCA only returns the
207
+ // slot count (-1 when full/empty); the fatal-vs-not decision is ours.
208
+ function trust(pem) {
209
+ if (wolfssl.addTrustedCA(pem) < 0)
210
+ throw new Error('certs: trust store full or empty PEM');
211
+ }
212
+ trust(GLOBALSIGN_R3);
213
+ trust(GLOBALSIGN_R1);
214
+ trust(USERTRUST_ECC_CA);
215
+ trust(DIGICERT_GLOBAL_G2);
216
+ trust(GLOBALSIGN_R46);
217
+ trust(ISRG_X1);
218
+ trust(ISRG_X2);
214
219
  export const TRUSTED_CA_COUNT = 7;
package/lib/certs.ts CHANGED
@@ -212,13 +212,18 @@ tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1
212
212
  -----END CERTIFICATE-----`
213
213
 
214
214
  // Register at import time. Importers of this module get the anchors
215
- // without writing any code themselves.
216
- wolfssl.addTrustedCA(GLOBALSIGN_R3)
217
- wolfssl.addTrustedCA(GLOBALSIGN_R1)
218
- wolfssl.addTrustedCA(USERTRUST_ECC_CA)
219
- wolfssl.addTrustedCA(DIGICERT_GLOBAL_G2)
220
- wolfssl.addTrustedCA(GLOBALSIGN_R46)
221
- wolfssl.addTrustedCA(ISRG_X1)
222
- wolfssl.addTrustedCA(ISRG_X2)
215
+ // without writing any code themselves. addTrustedCA only returns the
216
+ // slot count (-1 when full/empty); the fatal-vs-not decision is ours.
217
+ function trust(pem: string): void {
218
+ if (wolfssl.addTrustedCA(pem) < 0)
219
+ throw new Error('certs: trust store full or empty PEM')
220
+ }
221
+ trust(GLOBALSIGN_R3)
222
+ trust(GLOBALSIGN_R1)
223
+ trust(USERTRUST_ECC_CA)
224
+ trust(DIGICERT_GLOBAL_G2)
225
+ trust(GLOBALSIGN_R46)
226
+ trust(ISRG_X1)
227
+ trust(ISRG_X2)
223
228
 
224
229
  export const TRUSTED_CA_COUNT = 7
package/lib/fetch.js CHANGED
@@ -56,6 +56,9 @@ const ST_DONE = 5;
56
56
  // ── Main fetch request ──
57
57
  async function fetchRequest(req) {
58
58
  const parsedUrl = new URL(req.url);
59
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
60
+ throw new TypeError('fetch: unsupported protocol "' + parsedUrl.protocol + '"');
61
+ }
59
62
  const method = req.method;
60
63
  const headers = new HeadersImpl(req.headers);
61
64
  const timeout = req.timeout || 30000;
@@ -241,7 +244,21 @@ async function fetchRequest(req) {
241
244
  break;
242
245
  let data;
243
246
  if (isHTTPS && ssl) {
244
- data = wolfssl.wolfSSL_read(ssl, 8192);
247
+ const buf = new ArrayBuffer(8192);
248
+ const n = wolfssl.wolfSSL_read(ssl, buf);
249
+ if (n > 0) {
250
+ data = buf.slice(0, n);
251
+ }
252
+ else {
253
+ const err = wolfssl.wolfSSL_get_error(ssl, n);
254
+ if (err === 2 /* wolfssl.ErrorCode.WOLFSSL_ERROR_WANT_READ */ ||
255
+ err === 3 /* wolfssl.ErrorCode.WOLFSSL_ERROR_WANT_WRITE */)
256
+ break;
257
+ if (n === 0 || err === 6 /* wolfssl.ErrorCode.WOLFSSL_ERROR_ZERO_RETURN */)
258
+ break;
259
+ doReject(new Error('TLS read failed: ' + err));
260
+ return;
261
+ }
245
262
  }
246
263
  else if (s !== null && s >= 0) {
247
264
  data = sock.recv(s, 8192);
@@ -314,7 +331,31 @@ async function fetchRequest(req) {
314
331
  break;
315
332
  let data;
316
333
  if (isHTTPS && ssl) {
317
- data = wolfssl.wolfSSL_read(ssl, 8192);
334
+ const buf = new ArrayBuffer(8192);
335
+ const n = wolfssl.wolfSSL_read(ssl, buf);
336
+ if (n > 0) {
337
+ data = buf.slice(0, n);
338
+ }
339
+ else {
340
+ const err = wolfssl.wolfSSL_get_error(ssl, n);
341
+ if (err === 2 /* wolfssl.ErrorCode.WOLFSSL_ERROR_WANT_READ */ ||
342
+ err === 3 /* wolfssl.ErrorCode.WOLFSSL_ERROR_WANT_WRITE */)
343
+ break;
344
+ if (n === 0 || err === 6 /* wolfssl.ErrorCode.WOLFSSL_ERROR_ZERO_RETURN */)
345
+ break;
346
+ // Fatal TLS error mid-body: the response already
347
+ // resolved, so fail the body stream instead of
348
+ // silently waiting for an FD event that never comes.
349
+ if (_controller) {
350
+ try {
351
+ _controller.error(new Error('TLS read failed: ' + err));
352
+ }
353
+ catch { /* already closed */ }
354
+ }
355
+ stream = null;
356
+ cleanupSocket();
357
+ return;
358
+ }
318
359
  }
319
360
  else if (s !== null && s >= 0) {
320
361
  data = sock.recv(s, 8192);
@@ -362,7 +403,14 @@ async function fetchRequest(req) {
362
403
  break;
363
404
  let data;
364
405
  if (isHTTPS && ssl) {
365
- data = wolfssl.wolfSSL_read(ssl, 8192);
406
+ const buf = new ArrayBuffer(8192);
407
+ const n = wolfssl.wolfSSL_read(ssl, buf);
408
+ // Best-effort drain: any non-data result (EOF, WANT_*,
409
+ // late error) ends the drain — the stream closes below.
410
+ if (n > 0)
411
+ data = buf.slice(0, n);
412
+ else
413
+ break;
366
414
  }
367
415
  else if (s !== null && s >= 0) {
368
416
  data = sock.recv(s, 8192);
package/lib/fetch.ts CHANGED
@@ -78,6 +78,9 @@ const ST_DONE = 5
78
78
 
79
79
  async function fetchRequest(req: RequestImpl): Promise<ResponseImpl> {
80
80
  const parsedUrl = new URL(req.url)
81
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
82
+ throw new TypeError('fetch: unsupported protocol "' + parsedUrl.protocol + '"')
83
+ }
81
84
  const method = req.method
82
85
  const headers = new HeadersImpl(req.headers)
83
86
  const timeout = req.timeout || 30000
@@ -225,7 +228,18 @@ async function fetchRequest(req: RequestImpl): Promise<ResponseImpl> {
225
228
  if (s !== null && s < 0 && !ssl) break
226
229
  let data: ArrayBuffer | null
227
230
  if (isHTTPS && ssl) {
228
- data = wolfssl.wolfSSL_read(ssl, 8192)
231
+ const buf = new ArrayBuffer(8192)
232
+ const n = wolfssl.wolfSSL_read(ssl, buf)
233
+ if (n > 0) {
234
+ data = buf.slice(0, n)
235
+ } else {
236
+ const err = wolfssl.wolfSSL_get_error(ssl, n)
237
+ if (err === wolfssl.ErrorCode.WOLFSSL_ERROR_WANT_READ ||
238
+ err === wolfssl.ErrorCode.WOLFSSL_ERROR_WANT_WRITE) break
239
+ if (n === 0 || err === wolfssl.ErrorCode.WOLFSSL_ERROR_ZERO_RETURN) break
240
+ doReject(new Error('TLS read failed: ' + err))
241
+ return
242
+ }
229
243
  } else if (s !== null && s >= 0) {
230
244
  data = sock.recv(s, 8192)
231
245
  } else { break }
@@ -295,7 +309,23 @@ async function fetchRequest(req: RequestImpl): Promise<ResponseImpl> {
295
309
  if (s !== null && s < 0 && !ssl) break
296
310
  let data: ArrayBuffer | null
297
311
  if (isHTTPS && ssl) {
298
- data = wolfssl.wolfSSL_read(ssl, 8192)
312
+ const buf = new ArrayBuffer(8192)
313
+ const n = wolfssl.wolfSSL_read(ssl, buf)
314
+ if (n > 0) {
315
+ data = buf.slice(0, n)
316
+ } else {
317
+ const err = wolfssl.wolfSSL_get_error(ssl, n)
318
+ if (err === wolfssl.ErrorCode.WOLFSSL_ERROR_WANT_READ ||
319
+ err === wolfssl.ErrorCode.WOLFSSL_ERROR_WANT_WRITE) break
320
+ if (n === 0 || err === wolfssl.ErrorCode.WOLFSSL_ERROR_ZERO_RETURN) break
321
+ // Fatal TLS error mid-body: the response already
322
+ // resolved, so fail the body stream instead of
323
+ // silently waiting for an FD event that never comes.
324
+ if (_controller) { try { _controller.error(new Error('TLS read failed: ' + err)) } catch { /* already closed */ } }
325
+ stream = null
326
+ cleanupSocket()
327
+ return
328
+ }
299
329
  } else if (s !== null && s >= 0) {
300
330
  data = sock.recv(s, 8192)
301
331
  } else { break }
@@ -335,7 +365,12 @@ async function fetchRequest(req: RequestImpl): Promise<ResponseImpl> {
335
365
  if (s !== null && s < 0 && !ssl) break
336
366
  let data: ArrayBuffer | null
337
367
  if (isHTTPS && ssl) {
338
- data = wolfssl.wolfSSL_read(ssl, 8192)
368
+ const buf = new ArrayBuffer(8192)
369
+ const n = wolfssl.wolfSSL_read(ssl, buf)
370
+ // Best-effort drain: any non-data result (EOF, WANT_*,
371
+ // late error) ends the drain — the stream closes below.
372
+ if (n > 0) data = buf.slice(0, n)
373
+ else break
339
374
  } else if (s !== null && s >= 0) {
340
375
  data = sock.recv(s, 8192)
341
376
  } else { break }
package/lib/ffi/bind.js CHANGED
@@ -3,7 +3,12 @@ import * as os from 'os';
3
3
  import * as std from 'std';
4
4
  import * as win from 'win';
5
5
  import '../text-codec.js';
6
- import { cTokenToType, isCPtrToken, normToken, PTR_SIZE, ptrName, readScalar, writeSlot, PtrArrayBuffer } from './ctype.js';
6
+ import { cTokenToType, isCPtrToken, isCValToken, valName, normToken, PTR_SIZE, ptrName, readScalar, writeSlot, PtrArrayBuffer } from './ctype.js';
7
+ // CodecMap 的值是结构形(size 只在 StructDef 上、不属 Codec 契约),统一走 unknown
8
+ // 二跳提取;存在性与 size 由 makeFn 绑定期校验。
9
+ function valCodec(name, encoders) {
10
+ return encoders[name];
11
+ }
7
12
  const _dllCache = new Map();
8
13
  function loadDll(dll) {
9
14
  const cached = _dllCache.get(dll);
@@ -36,14 +41,36 @@ function parseSig(sig) {
36
41
  }
37
42
  // 裸 'ptr'/非法 token 由类型层拦截(C_BasicType_Token 已 Exclude 'ptr'、拼错 token 塌成 never);
38
43
  // 运行时再比较只会得到 TS2367「两类型无重叠」——类型已表达的约束不重复校验。
44
+ const retToken = normToken(parts[1]);
45
+ // 按值形 '<N>' 仅支持入参位:大结构返回需要隐藏指针/sret 级 ABI(本运行时的
46
+ // retBuf 恒 8 字节,只支持标量/浮点/指针返回),绑定期 throw 而非静默降级。
47
+ // 类型层对返回位的 '<N>' 不设专门分支(fallthrough),本 throw 是唯一防线。
48
+ if (isCValToken(retToken))
49
+ throw new Error(`ffi-bind: "${sig}": by-value struct at the return position ` +
50
+ `(<${valName(retToken)}>) is not supported — argument positions only; ` +
51
+ `pass a struct out through an out-param slot instead (<N>ptr + caller buffer)`);
39
52
  return {
40
53
  argTokens,
41
- retToken: normToken(parts[1]),
54
+ retToken,
42
55
  sig,
43
56
  };
44
57
  }
45
58
  function makeFn(proc, sig, encoders, decoders) {
46
59
  const ps = parseSig(sig);
60
+ // 按值位的能力校验前移到绑定期(模块加载即炸,不留到首个调用):布局缺位 / 非结构
61
+ // 布局(无 size)/ 退化 size 都是签名层面的错误,报错指向具体位与可用布局清单。
62
+ for (const t of ps.argTokens) {
63
+ if (!isCValToken(t))
64
+ continue;
65
+ const name = valName(t);
66
+ const codec = valCodec(name, encoders);
67
+ if (!codec || typeof codec.encode !== 'function')
68
+ throw new Error(`ffi-bind: ${sig}: by-value position <${name}> has no registered layout ` +
69
+ `(available: ${Object.keys(encoders).join(', ') || 'none'})`);
70
+ if (typeof codec.size !== 'number' || codec.size < 1)
71
+ throw new Error(`ffi-bind: ${sig}: by-value position <${name}> requires a struct ` +
72
+ `layout with size >= 1 (got ${codec.size}; non-struct codecs expose no size)`);
73
+ }
47
74
  return (...a) => callPacked(proc, ps, a, encoders, decoders);
48
75
  }
49
76
  // 每个参数在 argFrame 里占的字节数。与 quickjs-ffi-type.h 的 qwin_ffi_arg_size[]
@@ -59,15 +86,36 @@ const X64_MIN_SLOTS = 4;
59
86
  function callPacked(proc, { argTokens, retToken, sig }, args, encoders, decoders) {
60
87
  const is64 = os.arch === 'x64';
61
88
  const getWidth = (t, is64) => {
89
+ // 按值形由 widthOf 分派(槽宽依赖布局 size),此处只认标量/指针档;守卫同时
90
+ // 收窄类型(IA32_ARG_SIZE 索引不认 val 形)。
91
+ if (isCValToken(t))
92
+ throw new Error(`ffi-bind: getWidth: by-value token "${t}" (dispatched by widthOf)`);
62
93
  if (is64)
63
94
  return 8;
64
95
  if (isCPtrToken(t))
65
96
  return PTR_SIZE;
66
97
  return IA32_ARG_SIZE[t];
67
98
  };
99
+ // 按值位的槽宽:x64 恒 8 字节(尺寸 ∈{1,2,4,8} 按「同尺寸整数」进槽,其余尺寸进
100
+ // 槽的是指向临时副本的指针);ia32 = ALIGN(size, 4) —— 结构字节原样压栈,无按
101
+ // 引用一说(libffi ffi.c 的 ia32 分支同规则,桩只做一次 rep movsb 搬运)。
102
+ const widthOf = (t) => {
103
+ if (isCValToken(t)) {
104
+ if (is64)
105
+ return 8;
106
+ const layout = valCodec(valName(t), encoders);
107
+ // 绑定期 makeFn 已校验(存在 + size >= 1);此处兜动态/无类型路径。
108
+ if (!layout)
109
+ throw new Error(`ffi-bind: <${valName(t)}> by-value position has no registered layout`);
110
+ const size = layout.size;
111
+ return size % 4 === 0 ? size : size + 4 - (size % 4);
112
+ }
113
+ // val 形已在上分支 return,此处恒为标量/指针形(类型层收窄,见 C_BasicType_Token)。
114
+ return getWidth(t, is64);
115
+ };
68
116
  let total = 0;
69
117
  for (const t of argTokens)
70
- total += getWidth(t, is64);
118
+ total += widthOf(t);
71
119
  if (is64 && argTokens.length < X64_MIN_SLOTS)
72
120
  total = X64_MIN_SLOTS * 8;
73
121
  const argFrame = new ArrayBuffer(total);
@@ -118,10 +166,40 @@ function callPacked(proc, { argTokens, retToken, sig }, args, encoders, decoders
118
166
  writeSlot(dv, off, { k: 'ptr', v: p });
119
167
  }
120
168
  }
169
+ else if (isCValToken(argToken)) {
170
+ // 按值位:对象直传(值域由注册布局推导),无地址词汇 —— NULL / number
171
+ // 进这里是必然错位(引擎按值语义,指针位请写 <N>ptr),fail-loud。
172
+ const name = valName(argToken);
173
+ const codec = valCodec(name, encoders);
174
+ if (!codec)
175
+ throw new Error(`ffi-bind: ${sig}: arg#${i + 1} <${name}> by-value position ` +
176
+ `has no registered layout`);
177
+ if (arg === null || arg === undefined)
178
+ throw new Error(`ffi-bind: <${name}> value position got ${String(arg)}; ` +
179
+ `pass a struct object (use <${name}>ptr to pass a pointer)`);
180
+ const size = codec.size;
181
+ if (!is64 || (size <= 8 && (size & (size - 1)) === 0)) {
182
+ // 字节直接落槽:ia32 结构按值压栈(任意尺寸);x64 尺寸 ∈{1,2,4,8}
183
+ // 按「同尺寸整数」传值——字节在 8 字节槽低位,callee 右对齐读。
184
+ // argFrame 构造时即零填充,槽高位为 0(callee 忽略高位,无歧义)。
185
+ codec.encode(arg, argFrame, off);
186
+ }
187
+ else {
188
+ // x64 其余尺寸(>8 或非 2 的幂)按引用:槽放指针,指向 caller 分配的
189
+ // 16 字节对齐临时副本(MS x64 官方规则:单参数永不跨多个寄存器;对齐
190
+ // 偏移自算,不依赖分配器的对齐保证)。held 保持引用直到调用返回。
191
+ const buf = new ArrayBuffer(size + 15);
192
+ const base = ffi.bufferPtr(buf);
193
+ const pad = (16 - (base % 16)) % 16;
194
+ codec.encode(arg, buf, pad);
195
+ held.push(buf);
196
+ writeSlot(dv, off, { k: 'ptr', v: base + pad });
197
+ }
198
+ }
121
199
  else {
122
200
  writeSlot(dv, off, { k: argToken, v: arg });
123
201
  }
124
- off += getWidth(argToken, is64);
202
+ off += widthOf(argToken);
125
203
  }
126
204
  const retBuf = new ArrayBuffer(8);
127
205
  const retIsFp = retToken === 'f32' || retToken === 'f64';
@@ -155,7 +233,8 @@ function readRet(ret, retBuf) {
155
233
  * 品牌指针逐字节读到 NUL(野指针无终止 4MiB 上限 fail-fast)、ArrayBuffer 直读到
156
234
  * NUL 或末尾(out 参数未写 NUL 时按读满处理);alloc 预分配返回带 .ptr 的
157
235
  * PtrArrayBuffer(a = 字符数,缺省 256)。类型取必需形态——
158
- * 内建三件齐备,调用无需空断言。 */
236
+ * 内建三件齐备,调用无需空断言。刻意 Pick 而非 Required<Codec>:只声明消费的
237
+ * 三件(encode/decode/alloc),新增可选能力位不被拉成必填。 */
159
238
  export const WCHAR = {
160
239
  encode: (v) => {
161
240
  // TextEncoder 没有 encodeInto:先编码再拷入带 .ptr 的 buffer(单次 memcpy,
@@ -316,6 +395,16 @@ function dispatchClosure(args, ret, fn, frameBuf, retBuf, sig) {
316
395
  * → 打印泄漏警告(只警告、不自动释放,见 leakRegistry)。 */
317
396
  export function closure(sig, fn, opts) {
318
397
  const { argTokens, retToken } = parseSig(sig);
398
+ // 按值位仅支持 bind 的入参方向:closure 的 C→JS 方向由 quickjs-ffi-closure-*.S
399
+ // 按固定槽宽读参数(x64 固定 8 字节槽、ia32 IA32_ARG_SIZE 表),不区分「槽内是
400
+ // 结构字节还是指向临时副本的指针」——该分派未实现,创建期 fail-fast。
401
+ for (const t of argTokens)
402
+ if (isCValToken(t))
403
+ throw new Error(`ffi-bind: closure signature cannot take a by-value struct ` +
404
+ `(<${valName(t)}>); by-value is bind-only — the C→JS direction has no ` +
405
+ `struct slot decoding (pass a pointer and decode on the JS side)`);
406
+ // 上方已拒 '<N>' 按值形:此处 tok 恒为标量/指针档(cTokenToType 对 val 形原样返回,
407
+ // 但那条路径不可达——IA32_ARG_SIZE 索引与 dispatchClosure 只认标量档)。
319
408
  const argSpecs = argTokens.map(t => ({ tok: cTokenToType(t), nonnull: t.endsWith('!') }));
320
409
  const retSpec = { tok: cTokenToType(retToken), nonnull: retToken.endsWith('!') };
321
410
  const is64 = os.arch === 'x64';