index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. "use strict";
  2. function makeException(ErrorType, message, opts = {}) {
  3. if (opts.globals) {
  4. ErrorType = opts.globals[ErrorType.name];
  5. }
  6. return new ErrorType(`${opts.context ? opts.context : "Value"} ${message}.`);
  7. }
  8. function toNumber(value, opts = {}) {
  9. if (!opts.globals) {
  10. return +value;
  11. }
  12. if (typeof value === "bigint") {
  13. throw opts.globals.TypeError("Cannot convert a BigInt value to a number");
  14. }
  15. return opts.globals.Number(value);
  16. }
  17. function type(V) {
  18. if (V === null) {
  19. return "Null";
  20. }
  21. switch (typeof V) {
  22. case "undefined":
  23. return "Undefined";
  24. case "boolean":
  25. return "Boolean";
  26. case "number":
  27. return "Number";
  28. case "string":
  29. return "String";
  30. case "symbol":
  31. return "Symbol";
  32. case "bigint":
  33. return "BigInt";
  34. case "object":
  35. // Falls through
  36. case "function":
  37. // Falls through
  38. default:
  39. // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for
  40. // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for
  41. // such cases. So treat the default case as an object.
  42. return "Object";
  43. }
  44. }
  45. // Round x to the nearest integer, choosing the even integer if it lies halfway between two.
  46. function evenRound(x) {
  47. // There are four cases for numbers with fractional part being .5:
  48. //
  49. // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example
  50. // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0
  51. // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2
  52. // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0
  53. // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2
  54. // (where n is a non-negative integer)
  55. //
  56. // Branch here for cases 1 and 4
  57. if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) ||
  58. (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) {
  59. return censorNegativeZero(Math.floor(x));
  60. }
  61. return censorNegativeZero(Math.round(x));
  62. }
  63. function integerPart(n) {
  64. return censorNegativeZero(Math.trunc(n));
  65. }
  66. function sign(x) {
  67. return x < 0 ? -1 : 1;
  68. }
  69. function modulo(x, y) {
  70. // https://tc39.github.io/ecma262/#eqn-modulo
  71. // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos
  72. const signMightNotMatch = x % y;
  73. if (sign(y) !== sign(signMightNotMatch)) {
  74. return signMightNotMatch + y;
  75. }
  76. return signMightNotMatch;
  77. }
  78. function censorNegativeZero(x) {
  79. return x === 0 ? 0 : x;
  80. }
  81. function createIntegerConversion(bitLength, typeOpts) {
  82. const isSigned = !typeOpts.unsigned;
  83. let lowerBound;
  84. let upperBound;
  85. if (bitLength === 64) {
  86. upperBound = Number.MAX_SAFE_INTEGER;
  87. lowerBound = !isSigned ? 0 : Number.MIN_SAFE_INTEGER;
  88. } else if (!isSigned) {
  89. lowerBound = 0;
  90. upperBound = Math.pow(2, bitLength) - 1;
  91. } else {
  92. lowerBound = -Math.pow(2, bitLength - 1);
  93. upperBound = Math.pow(2, bitLength - 1) - 1;
  94. }
  95. const twoToTheBitLength = Math.pow(2, bitLength);
  96. const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1);
  97. return (V, opts = {}) => {
  98. let x = toNumber(V, opts);
  99. x = censorNegativeZero(x);
  100. if (opts.enforceRange) {
  101. if (!Number.isFinite(x)) {
  102. throw makeException(TypeError, "is not a finite number", opts);
  103. }
  104. x = integerPart(x);
  105. if (x < lowerBound || x > upperBound) {
  106. throw makeException(TypeError,
  107. `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts);
  108. }
  109. return x;
  110. }
  111. if (!Number.isNaN(x) && opts.clamp) {
  112. x = Math.min(Math.max(x, lowerBound), upperBound);
  113. x = evenRound(x);
  114. return x;
  115. }
  116. if (!Number.isFinite(x) || x === 0) {
  117. return 0;
  118. }
  119. x = integerPart(x);
  120. // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if
  121. // possible. Hopefully it's an optimization for the non-64-bitLength cases too.
  122. if (x >= lowerBound && x <= upperBound) {
  123. return x;
  124. }
  125. // These will not work great for bitLength of 64, but oh well. See the README for more details.
  126. x = modulo(x, twoToTheBitLength);
  127. if (isSigned && x >= twoToOneLessThanTheBitLength) {
  128. return x - twoToTheBitLength;
  129. }
  130. return x;
  131. };
  132. }
  133. function createLongLongConversion(bitLength, { unsigned }) {
  134. const upperBound = Number.MAX_SAFE_INTEGER;
  135. const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
  136. const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN;
  137. return (V, opts = {}) => {
  138. if (opts === undefined) {
  139. opts = {};
  140. }
  141. let x = toNumber(V, opts);
  142. x = censorNegativeZero(x);
  143. if (opts.enforceRange) {
  144. if (!Number.isFinite(x)) {
  145. throw makeException(TypeError, "is not a finite number", opts);
  146. }
  147. x = integerPart(x);
  148. if (x < lowerBound || x > upperBound) {
  149. throw makeException(TypeError,
  150. `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts);
  151. }
  152. return x;
  153. }
  154. if (!Number.isNaN(x) && opts.clamp) {
  155. x = Math.min(Math.max(x, lowerBound), upperBound);
  156. x = evenRound(x);
  157. return x;
  158. }
  159. if (!Number.isFinite(x) || x === 0) {
  160. return 0;
  161. }
  162. let xBigInt = BigInt(integerPart(x));
  163. xBigInt = asBigIntN(bitLength, xBigInt);
  164. return Number(xBigInt);
  165. };
  166. }
  167. exports.any = V => {
  168. return V;
  169. };
  170. exports.void = function () {
  171. return undefined;
  172. };
  173. exports.boolean = function (val) {
  174. return !!val;
  175. };
  176. exports.byte = createIntegerConversion(8, { unsigned: false });
  177. exports.octet = createIntegerConversion(8, { unsigned: true });
  178. exports.short = createIntegerConversion(16, { unsigned: false });
  179. exports["unsigned short"] = createIntegerConversion(16, { unsigned: true });
  180. exports.long = createIntegerConversion(32, { unsigned: false });
  181. exports["unsigned long"] = createIntegerConversion(32, { unsigned: true });
  182. exports["long long"] = createLongLongConversion(64, { unsigned: false });
  183. exports["unsigned long long"] = createLongLongConversion(64, { unsigned: true });
  184. exports.double = (V, opts) => {
  185. const x = toNumber(V, opts);
  186. if (!Number.isFinite(x)) {
  187. throw makeException(TypeError, "is not a finite floating-point value", opts);
  188. }
  189. return x;
  190. };
  191. exports["unrestricted double"] = (V, opts) => {
  192. const x = toNumber(V, opts);
  193. return x;
  194. };
  195. exports.float = (V, opts) => {
  196. const x = toNumber(V, opts);
  197. if (!Number.isFinite(x)) {
  198. throw makeException(TypeError, "is not a finite floating-point value", opts);
  199. }
  200. if (Object.is(x, -0)) {
  201. return x;
  202. }
  203. const y = Math.fround(x);
  204. if (!Number.isFinite(y)) {
  205. throw makeException(TypeError, "is outside the range of a single-precision floating-point value", opts);
  206. }
  207. return y;
  208. };
  209. exports["unrestricted float"] = (V, opts) => {
  210. const x = toNumber(V, opts);
  211. if (isNaN(x)) {
  212. return x;
  213. }
  214. if (Object.is(x, -0)) {
  215. return x;
  216. }
  217. return Math.fround(x);
  218. };
  219. exports.DOMString = function (V, opts = {}) {
  220. if (opts.treatNullAsEmptyString && V === null) {
  221. return "";
  222. }
  223. if (typeof V === "symbol") {
  224. throw makeException(TypeError, "is a symbol, which cannot be converted to a string", opts);
  225. }
  226. const StringCtor = opts.globals ? opts.globals.String : String;
  227. return StringCtor(V);
  228. };
  229. exports.ByteString = (V, opts) => {
  230. const x = exports.DOMString(V, opts);
  231. let c;
  232. for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) {
  233. if (c > 255) {
  234. throw makeException(TypeError, "is not a valid ByteString", opts);
  235. }
  236. }
  237. return x;
  238. };
  239. exports.USVString = (V, opts) => {
  240. const S = exports.DOMString(V, opts);
  241. const n = S.length;
  242. const U = [];
  243. for (let i = 0; i < n; ++i) {
  244. const c = S.charCodeAt(i);
  245. if (c < 0xD800 || c > 0xDFFF) {
  246. U.push(String.fromCodePoint(c));
  247. } else if (0xDC00 <= c && c <= 0xDFFF) {
  248. U.push(String.fromCodePoint(0xFFFD));
  249. } else if (i === n - 1) {
  250. U.push(String.fromCodePoint(0xFFFD));
  251. } else {
  252. const d = S.charCodeAt(i + 1);
  253. if (0xDC00 <= d && d <= 0xDFFF) {
  254. const a = c & 0x3FF;
  255. const b = d & 0x3FF;
  256. U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b));
  257. ++i;
  258. } else {
  259. U.push(String.fromCodePoint(0xFFFD));
  260. }
  261. }
  262. }
  263. return U.join("");
  264. };
  265. exports.object = (V, opts) => {
  266. if (type(V) !== "Object") {
  267. throw makeException(TypeError, "is not an object", opts);
  268. }
  269. return V;
  270. };
  271. // Not exported, but used in Function and VoidFunction.
  272. // Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so
  273. // handling for that is omitted.
  274. function convertCallbackFunction(V, opts) {
  275. if (typeof V !== "function") {
  276. throw makeException(TypeError, "is not a function", opts);
  277. }
  278. return V;
  279. }
  280. const abByteLengthGetter =
  281. Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
  282. const sabByteLengthGetter =
  283. Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get;
  284. function isNonSharedArrayBuffer(V) {
  285. try {
  286. // This will throw on SharedArrayBuffers, but not detached ArrayBuffers.
  287. // (The spec says it should throw, but the spec conflicts with implementations: https://github.com/tc39/ecma262/issues/678)
  288. abByteLengthGetter.call(V);
  289. return true;
  290. } catch {
  291. return false;
  292. }
  293. }
  294. function isSharedArrayBuffer(V) {
  295. try {
  296. sabByteLengthGetter.call(V);
  297. return true;
  298. } catch {
  299. return false;
  300. }
  301. }
  302. function isArrayBufferDetached(V) {
  303. try {
  304. // eslint-disable-next-line no-new
  305. new Uint8Array(V);
  306. return false;
  307. } catch {
  308. return true;
  309. }
  310. }
  311. exports.ArrayBuffer = (V, opts = {}) => {
  312. if (!isNonSharedArrayBuffer(V)) {
  313. if (opts.allowShared && !isSharedArrayBuffer(V)) {
  314. throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", opts);
  315. }
  316. throw makeException(TypeError, "is not an ArrayBuffer", opts);
  317. }
  318. if (isArrayBufferDetached(V)) {
  319. throw makeException(TypeError, "is a detached ArrayBuffer", opts);
  320. }
  321. return V;
  322. };
  323. const dvByteLengthGetter =
  324. Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
  325. exports.DataView = (V, opts = {}) => {
  326. try {
  327. dvByteLengthGetter.call(V);
  328. } catch (e) {
  329. throw makeException(TypeError, "is not a DataView", opts);
  330. }
  331. if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {
  332. throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", opts);
  333. }
  334. if (isArrayBufferDetached(V.buffer)) {
  335. throw makeException(TypeError, "is backed by a detached ArrayBuffer", opts);
  336. }
  337. return V;
  338. };
  339. // Returns the unforgeable `TypedArray` constructor name or `undefined`,
  340. // if the `this` value isn't a valid `TypedArray` object.
  341. //
  342. // https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag
  343. const typedArrayNameGetter = Object.getOwnPropertyDescriptor(
  344. Object.getPrototypeOf(Uint8Array).prototype,
  345. Symbol.toStringTag
  346. ).get;
  347. [
  348. Int8Array, Int16Array, Int32Array, Uint8Array,
  349. Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array
  350. ].forEach(func => {
  351. const name = func.name;
  352. const article = /^[AEIOU]/.test(name) ? "an" : "a";
  353. exports[name] = (V, opts = {}) => {
  354. if (!ArrayBuffer.isView(V) || typedArrayNameGetter.call(V) !== name) {
  355. throw makeException(TypeError, `is not ${article} ${name} object`, opts);
  356. }
  357. if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {
  358. throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts);
  359. }
  360. if (isArrayBufferDetached(V.buffer)) {
  361. throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts);
  362. }
  363. return V;
  364. };
  365. });
  366. // Common definitions
  367. exports.ArrayBufferView = (V, opts = {}) => {
  368. if (!ArrayBuffer.isView(V)) {
  369. throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", opts);
  370. }
  371. if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {
  372. throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts);
  373. }
  374. if (isArrayBufferDetached(V.buffer)) {
  375. throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts);
  376. }
  377. return V;
  378. };
  379. exports.BufferSource = (V, opts = {}) => {
  380. if (ArrayBuffer.isView(V)) {
  381. if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {
  382. throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts);
  383. }
  384. if (isArrayBufferDetached(V.buffer)) {
  385. throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts);
  386. }
  387. return V;
  388. }
  389. if (!opts.allowShared && !isNonSharedArrayBuffer(V)) {
  390. throw makeException(TypeError, "is not an ArrayBuffer or a view on one", opts);
  391. }
  392. if (opts.allowShared && !isSharedArrayBuffer(V) && !isNonSharedArrayBuffer(V)) {
  393. throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBufer, or a view on one", opts);
  394. }
  395. if (isArrayBufferDetached(V)) {
  396. throw makeException(TypeError, "is a detached ArrayBuffer", opts);
  397. }
  398. return V;
  399. };
  400. exports.DOMTimeStamp = exports["unsigned long long"];
  401. exports.Function = convertCallbackFunction;
  402. exports.VoidFunction = convertCallbackFunction;