版博士V2.0程序
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

1447 wiersze
45 KiB

  1. // src/attributes.ts
  2. import { pipe as pipe4 } from "fp-ts/lib/function.js";
  3. // src/create.ts
  4. import { identity } from "fp-ts/lib/function.js";
  5. import { Comment, Text, Window } from "happy-dom";
  6. import { dasherize } from "native-dash";
  7. // src/errors.ts
  8. import { relative } from "path";
  9. // node_modules/.pnpm/callsites@4.0.0/node_modules/callsites/index.js
  10. function callsites() {
  11. const _prepareStackTrace = Error.prepareStackTrace;
  12. Error.prepareStackTrace = (_, stack2) => stack2;
  13. const stack = new Error().stack.slice(1);
  14. Error.prepareStackTrace = _prepareStackTrace;
  15. return stack;
  16. }
  17. // src/diagnostics.ts
  18. import { flow as flow2, pipe as pipe3 } from "fp-ts/lib/function.js";
  19. // src/nodes.ts
  20. import { pipe as pipe2 } from "fp-ts/lib/function.js";
  21. // src/type-guards.ts
  22. function isHappyWrapperError(err) {
  23. return typeof err === "object" && err.kind === "HappyWrapper";
  24. }
  25. var isInspectionTuple = (thing) => {
  26. return Array.isArray(thing) && thing.length === 2 && typeof thing[0] === "string" && !Array.isArray(thing[1]);
  27. };
  28. function isDocument(dom) {
  29. return typeof dom === "object" && dom !== null && !isElement(dom) && "body" in dom;
  30. }
  31. function isFragment(dom) {
  32. return typeof dom === "object" && dom !== null && !isElement(dom) && !isTextNode(dom) && !("body" in dom);
  33. }
  34. var nodeStartsWithElement = (node) => {
  35. return !!(node.firstChild === node.firstElementChild);
  36. };
  37. var nodeEndsWithElement = (node) => {
  38. return "lastElementChild" in node && node.lastChild === node.lastElementChild;
  39. };
  40. var nodeBoundedByElements = (node) => {
  41. return nodeStartsWithElement(node) && nodeEndsWithElement(node);
  42. };
  43. var hasSingularElement = (node) => {
  44. return nodeBoundedByElements(node) && node.childNodes.length === 1;
  45. };
  46. function isElement(el) {
  47. return typeof el === "object" && el !== null && "outerHTML" in el && el.nodeType === 1;
  48. }
  49. var isElementLike = (container) => {
  50. if (isDocument(container)) {
  51. return container.body.childNodes.length === 1 && container.body.firstChild === container.body.firstElementChild;
  52. }
  53. return isFragment(container) && container.childNodes.length === 1 && container.firstChild === container.firstElementChild;
  54. };
  55. function isTextNodeLike(node) {
  56. var _a;
  57. return (isDocument(node) || isFragment(node)) && ((_a = node == null ? void 0 : node.childNodes) == null ? void 0 : _a.length) === 1 && isTextNode(node.firstChild);
  58. }
  59. var isUpdateSignature = (args) => {
  60. return Array.isArray(args) && args.length === 3 && typeof args[1] === "number" && typeof args[2] === "number";
  61. };
  62. function isTextNode(node) {
  63. if (typeof node === "string") {
  64. const test = createFragment(node);
  65. return isTextNodeLike(test);
  66. } else {
  67. return typeof node === "object" && node !== null && !("firstElementChild" in node);
  68. }
  69. }
  70. var isContainer = (thing) => {
  71. return isDocument(thing) || isFragment(thing) || isElement(thing) || isTextNode(thing);
  72. };
  73. var nodeChildrenAllElements = (node) => {
  74. return node.childNodes.every((n) => isElement(n));
  75. };
  76. // src/utils.ts
  77. import { flow, pipe } from "fp-ts/lib/function.js";
  78. var nodeTypeLookup = (type) => {
  79. switch (type) {
  80. case 1: {
  81. return "element";
  82. }
  83. case 3: {
  84. return "text";
  85. }
  86. case 8: {
  87. return "comment";
  88. }
  89. case 11: {
  90. return "fragment";
  91. }
  92. }
  93. };
  94. var getNodeType = (node) => {
  95. if (typeof node === "string") {
  96. return "html";
  97. }
  98. const byType = nodeTypeLookup(node.nodeType);
  99. if (byType) {
  100. return byType;
  101. }
  102. return isTextNode(node) ? "text" : isElement(node) ? "element" : isDocument(node) ? "document" : isFragment(node) ? "fragment" : "node";
  103. };
  104. var solveForNodeType = (_ = void 0) => {
  105. const solver = () => ({
  106. solver: (s) => (node, parent) => {
  107. if (node === null) {
  108. throw new Error("Value passed into solver was NULL!");
  109. }
  110. if (node === void 0) {
  111. throw new Error("Value passed into solver was UNDEFINED!");
  112. }
  113. const type = getNodeType(node);
  114. if (type in s) {
  115. const fn = s[type];
  116. return fn(node, parent);
  117. } else {
  118. if (type === "node" && "element" in s && isElement(node)) {
  119. const fn = s.element;
  120. return fn(node, parent);
  121. } else if (type === "node" && "text" in s && isTextNode(node)) {
  122. const fn = s.text;
  123. return fn(node);
  124. }
  125. throw new HappyMishap(`Problem finding "${type}" in solver.`, {
  126. name: `solveForNodeType(${type})`
  127. });
  128. }
  129. }
  130. });
  131. return {
  132. outputType: () => solver(),
  133. mirror: () => solver()
  134. };
  135. };
  136. function toHtml(node) {
  137. if (node === null) {
  138. return "";
  139. }
  140. const n = Array.isArray(node) ? node : [node];
  141. try {
  142. const results = n.map((i) => {
  143. const convert = solveForNodeType().outputType().solver({
  144. html: (h) => h,
  145. text: (t) => t.textContent,
  146. comment: (h) => `<!-- ${h.textContent} -->`,
  147. element: (e) => e.outerHTML,
  148. node: (ne) => {
  149. if (isElement(ne)) {
  150. convert(ne);
  151. }
  152. if (isTextNode(ne)) {
  153. convert(ne);
  154. }
  155. throw new Error(
  156. `Unknown node type detected while converting to HTML: [ name: ${ne.nodeName}, type: ${ne.nodeType}, value: ${ne.nodeValue} ]`
  157. );
  158. },
  159. document: (d) => `<html>${d.head.hasChildNodes() ? d.head.outerHTML : ""}${d.body.outerHTML}</html>`,
  160. fragment: (f) => {
  161. return isElementLike(f) ? f.firstElementChild.outerHTML : f.childNodes.map((c) => convert(c, f)).join("");
  162. }
  163. });
  164. return convert(i);
  165. });
  166. return results.join("");
  167. } catch (error_) {
  168. const error = Array.isArray(node) ? new HappyMishap(
  169. `Problem converting an array of ${n.length} nodes [${n.map((i) => getNodeType(i)).join(", ")}] to HTML`,
  170. {
  171. name: "toHTML([...])",
  172. inspect: ["first node", node[0]],
  173. error: error_
  174. }
  175. ) : new HappyMishap(`Problem converting "${getNodeType(node)}" to HTML!`, {
  176. name: "toHTML(getNodeType(node))",
  177. inspect: node,
  178. error: error_
  179. });
  180. throw error;
  181. }
  182. }
  183. function clone(container) {
  184. const clone2 = solveForNodeType().mirror().solver({
  185. html: (h) => `${h}`,
  186. fragment: flow(toHtml, createFragment),
  187. document: (d) => {
  188. return createDocument(d.body.innerHTML, d.head.innerHTML);
  189. },
  190. element: (e) => pipe(e, toHtml, createElement),
  191. node: (n) => {
  192. throw new HappyMishap("Can't clone an unknown node!", { inspect: n });
  193. },
  194. text: flow(toHtml, createTextNode),
  195. comment: flow(toHtml, createCommentNode)
  196. });
  197. return clone2(container);
  198. }
  199. function safeString(str) {
  200. const node = createFragment(str);
  201. return node.textContent;
  202. }
  203. // src/nodes.ts
  204. var getChildren = (el) => {
  205. if (!el.hasChildNodes()) {
  206. return [];
  207. }
  208. const output = [];
  209. let child = el.firstChild;
  210. for (let idx = 0; idx < el.childNodes.length; idx++) {
  211. if (isElement(child) || isTextNode(child)) {
  212. output.push(child);
  213. } else if (isFragment(child) || isDocument(child)) {
  214. for (const fragChild of getChildren(child)) {
  215. output.push(fragChild);
  216. }
  217. } else {
  218. throw new HappyMishap(
  219. `unknown node type [${getNodeType(
  220. child
  221. )}] found while trying to convert children to an array`,
  222. { name: "getChildrenAsArray", inspect: child }
  223. );
  224. }
  225. child = child.nextSibling;
  226. }
  227. return output;
  228. };
  229. var getChildElements = (el) => {
  230. return getChildren(el).filter((c) => isElement(c));
  231. };
  232. var extract = (memory) => (node) => {
  233. if (memory) {
  234. memory.push(clone(node));
  235. }
  236. return false;
  237. };
  238. var placeholder = (memory, placeholder2) => (node) => {
  239. if (memory) {
  240. memory.push(clone(node));
  241. }
  242. const el = placeholder2 ? placeholder2 : createElement("<placeholder></placeholder>");
  243. addClass(...getClassList(node))(el);
  244. node.replaceWith(el);
  245. return node;
  246. };
  247. var replaceElement = (newElement) => (oldElement) => {
  248. const parent = oldElement.parentElement;
  249. if (isElement(parent) || isTextNode(parent)) {
  250. parent.replaceChild(createElement(newElement), oldElement);
  251. }
  252. const newEl = typeof newElement === "string" ? createElement(newElement) : newElement;
  253. if (parent) {
  254. const children = getChildElements(parent);
  255. const childIdx = children.findIndex(
  256. (c) => toHtml(c) === toHtml(oldElement)
  257. );
  258. const updated = (children || []).map(
  259. (c, i) => i === childIdx ? newEl : c
  260. );
  261. parent.replaceChildren(...updated);
  262. }
  263. return newEl;
  264. };
  265. var append = (...nodes) => {
  266. const n = nodes.flat();
  267. return (parent) => {
  268. const result = solveForNodeType("text", "node", "comment").mirror().solver({
  269. html: (h) => pipe2(h, createElement, append(...nodes), toHtml),
  270. element: (e) => {
  271. for (const i of n) {
  272. e.append(i);
  273. }
  274. return e;
  275. },
  276. fragment: (f) => {
  277. for (const i of n) {
  278. f.append(i);
  279. }
  280. return f;
  281. },
  282. document: (d) => {
  283. for (const i of n) {
  284. d.body.append(i);
  285. }
  286. return d;
  287. }
  288. })(isUpdateSignature(parent) ? parent[0] : parent);
  289. return result;
  290. };
  291. };
  292. var into = (parent) => (...content) => {
  293. const wrapped = !!(typeof parent === "string");
  294. let normalizedParent = wrapped ? createFragment(parent) : isElement(parent) ? parent : parent ? parent : createFragment();
  295. const flat = isUpdateSignature(content) ? [content[0]] : content.flatMap((c) => c);
  296. if (isTextNodeLike(normalizedParent)) {
  297. throw new HappyMishap(
  298. `The wrapper node -- when calling into() -- is wrapping a text node; this is not allowed. Parent HTML: "${toHtml(
  299. normalizedParent
  300. )}"`,
  301. {
  302. name: "into()",
  303. inspect: [["parent node", parent]]
  304. }
  305. );
  306. }
  307. const contentHtml = flat.map((c) => toHtml(c)).join("");
  308. const transient = createFragment(contentHtml);
  309. const parentHasChildElements = normalizedParent.childElementCount > 0;
  310. if (parentHasChildElements) {
  311. for (const c of getChildren(transient)) {
  312. normalizedParent.firstChild.appendChild(clone(c));
  313. }
  314. } else {
  315. for (const c of getChildren(transient)) {
  316. normalizedParent.append(c);
  317. }
  318. }
  319. if (isUpdateSignature(content) && isElement(content[0])) {
  320. normalizedParent = isElementLike(normalizedParent) ? normalizedParent.firstElementChild : createElement(normalizedParent);
  321. content[0].replaceWith(normalizedParent);
  322. }
  323. return wrapped && !isUpdateSignature(content) ? toHtml(normalizedParent) : normalizedParent;
  324. };
  325. var changeTagName = (tagName) => (...args) => {
  326. const node = args[0];
  327. const replacer = (el, tagName2) => {
  328. const open = new RegExp(`^<${el.tagName.toLowerCase()}`);
  329. const close = new RegExp(`</${el.tagName.toLowerCase()}>$`);
  330. const newTag = toHtml(el).replace(open, `<${tagName2}`).replace(close, `</${tagName2}>`);
  331. if (el.parentNode && el.parentNode !== null) {
  332. el.parentNode.replaceChild(createNode(newTag), el);
  333. }
  334. return newTag;
  335. };
  336. const areTheSame = (before2, after2) => before2.toLocaleLowerCase() === after2.toLocaleLowerCase();
  337. return solveForNodeType().mirror().solver({
  338. html: (h) => {
  339. const before2 = createFragment(h).firstElementChild.tagName;
  340. return areTheSame(before2, tagName) ? h : toHtml(replacer(createFragment(h).firstElementChild, tagName));
  341. },
  342. text: (t) => {
  343. throw new HappyMishap(
  344. "Attempt to change a tag name for a IText node. This is not allowed.",
  345. { inspect: t, name: "changeTagName(IText)" }
  346. );
  347. },
  348. comment: (t) => {
  349. throw new HappyMishap(
  350. "Attempt to change a tag name for a IComment node. This is not allowed.",
  351. { inspect: t, name: "changeTagName(IComment)" }
  352. );
  353. },
  354. node: (n) => {
  355. throw new HappyMishap(
  356. "Attempt to change a generic INode node's tag name. This is not allowed.",
  357. { inspect: n, name: "changeTagName(INode)" }
  358. );
  359. },
  360. element: (el) => areTheSame(el.tagName, tagName) ? el : replaceElement(replacer(el, tagName))(el),
  361. fragment: (f) => {
  362. if (f.firstElementChild) {
  363. if (f.firstElementChild.parentElement) {
  364. f.firstElementChild.replaceWith(
  365. changeTagName(tagName)(f.firstElementChild)
  366. );
  367. } else {
  368. throw new HappyMishap(
  369. "Fragment's first child node must have a parent node to change the tag name!",
  370. { name: "changeTagName(Fragment)", inspect: f }
  371. );
  372. }
  373. } else {
  374. throw new HappyMishap(
  375. "Fragment passed into changeTagName() has no elements as children!",
  376. { name: "changeTagName(Fragment)", inspect: f }
  377. );
  378. }
  379. return f;
  380. },
  381. document: (d) => {
  382. d.body.firstElementChild.replaceWith(
  383. changeTagName(tagName)(d.body.firstElementChild)
  384. );
  385. const body = toHtml(d.body);
  386. const head = d.head.innerHTML;
  387. return createDocument(body, head);
  388. }
  389. })(node);
  390. };
  391. var prepend = (prepend2) => (el) => {
  392. const p = typeof prepend2 === "string" ? createFragment(prepend2).firstChild : prepend2;
  393. el.prepend(p);
  394. return el;
  395. };
  396. var before = (beforeNode) => (...afterNode) => {
  397. const outputIsHtml = typeof afterNode[0] === "string";
  398. const beforeNormalized = typeof beforeNode === "string" ? createFragment(beforeNode).firstElementChild || createFragment(beforeNode).firstChild : createNode(beforeNode);
  399. const afterNormalized = typeof afterNode[0] === "string" ? createFragment(afterNode[0]) : isUpdateSignature(afterNode[0]) ? afterNode[0][0] : afterNode[0];
  400. const invalidType = (n) => {
  401. throw new HappyMishap(
  402. `The before() utility was passed an invalid container type for the "after" node: ${getNodeType(
  403. n
  404. )}`,
  405. {
  406. name: `before(${getNodeType(beforeNormalized)})(${getNodeType(n)})`,
  407. inspect: n
  408. }
  409. );
  410. };
  411. const noParent = (n) => new HappyMishap(
  412. `the before() utility for depends on having a parent element in the "afterNode" as the parent's value must be mutated. If you do genuinely want this behavior then use a Fragment (or just HTML strings)`,
  413. {
  414. name: `before(${getNodeType(beforeNode)})(${getNodeType(n)})`
  415. }
  416. );
  417. const node = solveForNodeType().mirror().solver({
  418. html: (h) => pipe2(h, createFragment, before(beforeNode), toHtml),
  419. text: (t) => {
  420. if (!t.parentElement) {
  421. throw noParent(t);
  422. }
  423. t.before(beforeNormalized);
  424. return t;
  425. },
  426. comment: (t) => {
  427. if (!t.parentElement) {
  428. throw noParent(t);
  429. }
  430. t.before(beforeNormalized);
  431. return t;
  432. },
  433. node: (n) => invalidType(n),
  434. document: (d) => {
  435. d.body.prepend(beforeNormalized);
  436. return d;
  437. },
  438. fragment: (f) => {
  439. f.prepend(beforeNormalized);
  440. return f;
  441. },
  442. element: (el) => {
  443. if (el.parentElement) {
  444. el.before(beforeNormalized);
  445. return el;
  446. } else {
  447. throw noParent(el);
  448. }
  449. }
  450. })(afterNormalized);
  451. return outputIsHtml && !isUpdateSignature(afterNode) ? toHtml(node) : node;
  452. };
  453. var after = (afterNode) => (beforeNode) => {
  454. const afterNormalized = typeof afterNode === "string" ? createFragment(afterNode).firstElementChild : afterNode;
  455. const invalidType = (n) => {
  456. throw new HappyMishap(
  457. `The after function was passed an invalid container type: ${getNodeType(
  458. n
  459. )}`,
  460. { name: `after(${getNodeType(beforeNode)})(invalid)` }
  461. );
  462. };
  463. return solveForNodeType().mirror().solver({
  464. html: (h) => pipe2(h, createFragment, after(afterNode), toHtml),
  465. text: (t) => invalidType(t),
  466. comment: (t) => invalidType(t),
  467. node: (n) => invalidType(n),
  468. document: (d) => {
  469. d.body.append(afterNormalized);
  470. return d;
  471. },
  472. fragment: (f) => {
  473. f.append(afterNormalized);
  474. return f;
  475. },
  476. element: (el) => {
  477. if (el.parentElement) {
  478. el.after(afterNormalized);
  479. return el;
  480. } else {
  481. throw new HappyMishap(
  482. `the after() utility for depends on having a parent element in the "afterNode" as the parent's value must be mutated. If you do genuinely want this behavior then use a Fragment (or just HTML strings)`,
  483. { name: `after(${getNodeType(afterNode)})(IElement)` }
  484. );
  485. }
  486. }
  487. })(beforeNode);
  488. };
  489. var wrap = (...children) => (parent) => {
  490. return into(parent)(...children);
  491. };
  492. // src/diagnostics.ts
  493. function descClass(n) {
  494. const list = getClassList(n);
  495. return list.length > 0 ? `{ ${list.join(" ")} }` : "";
  496. }
  497. function descFrag(n) {
  498. const children = getChildren(n).map((i) => describeNode(i));
  499. return isElementLike(n) ? `[el: ${n.firstElementChild.tagName.toLowerCase()}]${descClass}` : isTextNodeLike(n) ? `[text: ${n.textContent.slice(0, 4).replace(/\n+/g, "")}...]` : `[children: ${children.length > 0 ? `${children.join(", ")}` : "none"}]`;
  500. }
  501. var describeNode = (node) => {
  502. if (!node) {
  503. return node === null ? "[null]" : "undefined";
  504. } else if (isUpdateSignature(node)) {
  505. return `UpdateSignature(${describeNode(node[0])})`;
  506. } else if (Array.isArray(node)) {
  507. return node.map((i) => describeNode(i)).join("\n");
  508. }
  509. return solveForNodeType().outputType().solver({
  510. html: (h) => pipe3(h, createFragment, describeNode),
  511. node: (n) => `node${descClass(n)}`,
  512. text: (t) => `text[${t.textContent.slice(0, 5).replace("\n", "")}...]`,
  513. comment: (t) => `comment[${t.textContent.slice(0, 5).replace("\n", "")}...]`,
  514. element: (e) => `element[${e.tagName.toLowerCase()}]${descClass(e)}`,
  515. fragment: (f) => `fragment${descFrag(f)}`,
  516. document: (d) => `doc[head: ${!!d.head}, body: ${!!d.body}]: ${describeNode(
  517. createFragment(d.body)
  518. )}`
  519. })(node);
  520. };
  521. var inspect = (item, toJSON = false) => {
  522. const solver = Array.isArray(item) ? () => item.map((i) => describeNode(i)) : solveForNodeType().outputType().solver({
  523. html: (h) => pipe3(h, createFragment, (f) => inspect(f)),
  524. fragment: (x) => ({
  525. kind: "Fragment",
  526. children: `${x.children.length} / ${x.childNodes.length}`,
  527. ...x.childNodes.length > 1 ? {
  528. leadsWith: isElement(x.firstChild) ? "element" : isTextNode(x.firstChild) ? "text" : "other",
  529. endsWith: isElement(x.lastChild) ? "element" : isTextNode(x.lastChild) ? "text" : "other"
  530. } : {
  531. childNode: inspect(x.firstChild)
  532. },
  533. content: x.textContent.length > 128 ? `${x.textContent.slice(0, 128)} ...` : x.textContent,
  534. childDetails: x.childNodes.map((i) => {
  535. try {
  536. return {
  537. html: toHtml(i),
  538. nodeType: getNodeType(i),
  539. hasParentElement: !!i.parentElement,
  540. hasParentNode: i.parentNode ? `${getNodeType(i.parentNode)} [type:${i.parentNode.nodeType}]` : false,
  541. childNodes: i.childNodes.length
  542. };
  543. } catch {
  544. return "N/A";
  545. }
  546. }),
  547. html: toHtml(x)
  548. }),
  549. document: (x) => {
  550. var _a, _b, _c, _d;
  551. return {
  552. kind: "Document",
  553. headerChildren: (_a = x.head.childNodes) == null ? void 0 : _a.length,
  554. bodyChildren: (_b = x.body.childNodes) == null ? void 0 : _b.length,
  555. body: toHtml(x.body),
  556. children: `${(_c = x.body.children) == null ? void 0 : _c.length} / ${(_d = x.body.childNodes) == null ? void 0 : _d.length}`,
  557. childTextContent: x.body.childNodes.map((i) => i.textContent),
  558. childDetails: x.childNodes.map((i) => {
  559. try {
  560. return {
  561. html: toHtml(i),
  562. nodeType: getNodeType(i),
  563. hasParentElement: !!i.parentElement,
  564. hasParentNode: i.parentNode ? `${getNodeType(i.parentNode)} [type:${i.parentNode.nodeType}]` : false,
  565. childNodes: i.childNodes.length
  566. };
  567. } catch {
  568. return "N/A";
  569. }
  570. })
  571. };
  572. },
  573. text: (x) => {
  574. var _a, _b;
  575. return {
  576. kind: "IText node",
  577. textContent: x.textContent.length > 128 ? `${x.textContent.slice(0, 128)} ...` : x.textContent,
  578. children: (_a = x.childNodes) == null ? void 0 : _a.length,
  579. childContent: (_b = x.childNodes) == null ? void 0 : _b.map((i) => i.textContent)
  580. };
  581. },
  582. comment: (c) => {
  583. var _a, _b;
  584. return {
  585. kind: "IComment node",
  586. textContent: c.textContent.length > 128 ? `${c.textContent.slice(0, 128)} ...` : c.textContent,
  587. children: (_a = c.childNodes) == null ? void 0 : _a.length,
  588. childContent: (_b = c.childNodes) == null ? void 0 : _b.map((i) => i.textContent)
  589. };
  590. },
  591. element: (x) => {
  592. var _a;
  593. return {
  594. kind: "IElement node",
  595. tagName: x.tagName,
  596. classes: getClassList(x),
  597. hasNaturalParent: !!x.parentElement,
  598. ...x.parentElement ? { parent: describeNode(x.parentElement) } : {},
  599. textContent: x.textContent,
  600. children: `${x.children.length} / ${x.childNodes.length}`,
  601. childContent: (_a = x.childNodes) == null ? void 0 : _a.map((i) => i.textContent),
  602. childDetails: x.childNodes.map((i) => {
  603. try {
  604. return {
  605. html: toHtml(i),
  606. nodeType: getNodeType(i),
  607. hasParentElement: !!i.parentElement,
  608. hasParentNode: i.parentNode ? `${getNodeType(i.parentNode)} [type:${i.parentNode.nodeType}]` : false,
  609. childNodes: i.childNodes.length
  610. };
  611. } catch {
  612. return "N/A";
  613. }
  614. }),
  615. html: truncate(512)(toHtml(x))
  616. };
  617. },
  618. node: (n) => {
  619. var _a, _b;
  620. return {
  621. kind: "INode (generic)",
  622. looksLike: isElement(n) ? "element" : isTextNode(n) ? "text" : "unknown",
  623. children: `${(_a = n.childNodes) == null ? void 0 : _a.length}`,
  624. childContent: (_b = n.childNodes) == null ? void 0 : _b.map((i) => truncate(128)(i.textContent)),
  625. html: truncate(512)(n.toString())
  626. };
  627. }
  628. });
  629. const result = isContainer(item) || typeof item === "string" ? solver(item) : {
  630. result: "not found",
  631. type: typeof item,
  632. ...typeof item === "object" && item !== null ? { keys: Object.keys(item) } : { value: JSON.stringify(item) }
  633. };
  634. return toJSON ? JSON.stringify(result, null, 2) : result;
  635. };
  636. var removeSpecialChars = (input) => input.replace(/\\t/g, "").replace(/\\n/g, "").trim();
  637. var truncate = (maxLength) => (input) => input.slice(0, maxLength);
  638. var tree = (node) => {
  639. const summarize = (tree2) => {
  640. const summary = (n) => {
  641. let ts;
  642. switch (n.type) {
  643. case "text": {
  644. ts = {
  645. node: `t(${pipe3(
  646. n.node.textContent,
  647. removeSpecialChars,
  648. truncate(10)
  649. )})`,
  650. children: n.children.map((c) => summary(c))
  651. };
  652. break;
  653. }
  654. case "comment": {
  655. ts = {
  656. node: `c(${pipe3(
  657. n.node.textContent,
  658. removeSpecialChars,
  659. truncate(10)
  660. )})`,
  661. children: n.children.map((c) => summary(c))
  662. };
  663. break;
  664. }
  665. case "element": {
  666. const el = n.node;
  667. ts = {
  668. node: `el(${el.tagName.toLowerCase()})`,
  669. children: n.children.map((c) => summary(c))
  670. };
  671. break;
  672. }
  673. case "node": {
  674. const node2 = n.node;
  675. ts = {
  676. node: `n(${pipe3(node2.nodeName, removeSpecialChars, truncate(10)) || pipe3(node2.textContent, removeSpecialChars, truncate(10))}`,
  677. children: n.children.map((c) => summary(c))
  678. };
  679. break;
  680. }
  681. case "fragment": {
  682. const f = n.node;
  683. ts = {
  684. node: `frag(${f.firstElementChild ? f.firstElementChild.tagName.toLowerCase() : removeSpecialChars(f.textContent).trim().slice(0, 10)})`,
  685. children: n.children.map((c) => summary(c))
  686. };
  687. break;
  688. }
  689. case "document": {
  690. const d = n.node;
  691. ts = {
  692. node: `doc(${isElementLike(d) ? d.body.firstElementChild.tagName.toLowerCase() : d.textContent.slice(0, 10)})`,
  693. children: n.children.map((c) => summary(c))
  694. };
  695. break;
  696. }
  697. default: {
  698. ts = {
  699. node: `u(${n.toString()})`,
  700. children: n.children.map((c) => summary(c))
  701. };
  702. break;
  703. }
  704. }
  705. return ts;
  706. };
  707. const recurse = (level = 0) => (node2) => {
  708. const indent = `${"".padStart(level * 6, " ")}${level > 0 ? `${level}) ` : "ROOT: "}`;
  709. return `${indent}${node2.node} ${node2.children.length > 0 ? "\u2935" : "\u21A4"}
  710. ${node2.children.map((i) => recurse(level + 1)(i))}`;
  711. };
  712. return {
  713. ...tree2,
  714. summary: () => summary(tree2),
  715. toString: () => {
  716. const describe = summary(tree2);
  717. return `
  718. Tree Summary: ${describe.node}
  719. ${"".padStart(
  720. 40,
  721. "-"
  722. )}
  723. ${recurse(0)(describe)}`;
  724. }
  725. };
  726. };
  727. const convert = (level) => solveForNodeType().outputType().solver({
  728. html: flow2(createFragment, tree),
  729. text: (t) => summarize({
  730. type: "text",
  731. node: t,
  732. level,
  733. children: t.childNodes.map((c) => convert(level + 1)(c))
  734. }),
  735. comment: (c) => summarize({
  736. type: "comment",
  737. node: c,
  738. level,
  739. children: c.childNodes.map((i) => convert(level + 1)(i))
  740. }),
  741. element: (e) => summarize({
  742. type: "element",
  743. node: e,
  744. level,
  745. children: e.childNodes.map((c) => convert(level + 1)(c))
  746. }),
  747. node: (n) => summarize({
  748. type: "node",
  749. node: n,
  750. level,
  751. children: n.childNodes.map((c) => convert(level + 1)(c))
  752. }),
  753. fragment: (f) => summarize({
  754. type: "fragment",
  755. node: f,
  756. level,
  757. children: f.childNodes.map((c) => convert(level + 1)(c))
  758. }),
  759. document: (d) => summarize({
  760. type: "document",
  761. node: d,
  762. level,
  763. children: d.childNodes.map((c) => convert(level + 1)(c))
  764. })
  765. });
  766. return convert(0)(node);
  767. };
  768. var siblings = (...content) => {
  769. return into()(...content);
  770. };
  771. // src/errors.ts
  772. var HappyMishap = class extends Error {
  773. constructor(message, options = {}) {
  774. var _a;
  775. super();
  776. this.name = "HappyWrapper";
  777. this.kind = "HappyWrapper";
  778. this.trace = [];
  779. this.message = `
  780. ${message}`;
  781. if (options.name) {
  782. this.name = `HappyWrapper::${options.name || "unknown"}`;
  783. }
  784. try {
  785. const sites = callsites();
  786. this.structuredStack = (sites || []).slice(1).map((i) => {
  787. var _a2;
  788. return {
  789. fn: i.getFunctionName() || i.getMethodName() || ((_a2 = i.getFunction()) == null ? void 0 : _a2.name) || "",
  790. line: i.getLineNumber() || void 0,
  791. file: i.getFileName() ? relative(process.cwd(), i.getFileName()) : ""
  792. };
  793. }) || [];
  794. } catch {
  795. this.structuredStack = [];
  796. }
  797. this.fn = this.structuredStack[0].fn || "";
  798. this.file = this.structuredStack[0].file || "";
  799. this.line = this.structuredStack[0].line || null;
  800. if (isHappyWrapperError(options.error)) {
  801. this.name = `[file: ${this.file}, line: ${this.line}] HappyWrapper::${options.name || options.error.name}`;
  802. }
  803. if (options.error) {
  804. const name = options.error instanceof Error ? options.error.name.replace("HappyWrapper::", "") : "unknown";
  805. const underlying = `
  806. The underlying error message [${name}] was:
  807. ${options.error instanceof Error ? options.error.message : String(options.error)}`;
  808. this.message = `${this.message}${underlying}`;
  809. this.trace = [...this.trace, name];
  810. } else {
  811. if (options.inspect) {
  812. const inspections = isInspectionTuple(options.inspect) ? [options.inspect] : Array.isArray(options.inspect) ? options.inspect : [options.inspect];
  813. for (const [idx, i] of inspections.entries()) {
  814. const intro = isInspectionTuple(i) ? `${i[0]}
  815. ` : `${[idx]}:
  816. `;
  817. const container = isInspectionTuple(i) ? i[1] : i;
  818. this.message = `${this.message}
  819. ${intro}${JSON.stringify(
  820. inspect(container),
  821. null,
  822. 2
  823. )}`;
  824. }
  825. }
  826. if (this.trace.length > 1) {
  827. this.message = `${this.message}
  828. Trace:${this.trace.map(
  829. (i, idx) => `${idx}. ${i}`
  830. )}`;
  831. }
  832. }
  833. this.message = `${this.message}
  834. `;
  835. for (const l of this.structuredStack) {
  836. this.message = ((_a = l.file) == null ? void 0 : _a.includes(".pnpm")) ? this.message : `${this.message}
  837. - ${l.fn ? `${l.fn}() ` : ""}${l.file}:${l.line}`;
  838. }
  839. this.structuredStack = [];
  840. }
  841. toJSON() {
  842. return {
  843. name: this.name,
  844. message: this.message
  845. };
  846. }
  847. toString() {
  848. return {
  849. name: this.name,
  850. message: this.message
  851. };
  852. }
  853. };
  854. // src/create.ts
  855. function createDocument(body, head) {
  856. const window = new Window();
  857. const document = window.document;
  858. document.body.innerHTML = body;
  859. if (head) {
  860. document.head.innerHTML = head;
  861. }
  862. return document;
  863. }
  864. function createFragment(content) {
  865. const window = new Window();
  866. const document = window.document;
  867. const fragment = document.createDocumentFragment();
  868. if (content) {
  869. fragment.append(clone(content));
  870. }
  871. return fragment;
  872. }
  873. var createNode = (node) => {
  874. const frag = createFragment(node);
  875. if (isElementLike(frag)) {
  876. return frag.firstElementChild;
  877. } else if (isTextNodeLike(frag)) {
  878. return frag.firstChild;
  879. } else {
  880. throw new HappyMishap(
  881. "call to createNode() couldn't be converted to IElement or IText node",
  882. { name: "createNode()", inspect: node }
  883. );
  884. }
  885. };
  886. function createTextNode(text) {
  887. if (!text) {
  888. return new Text("");
  889. }
  890. const frag = createFragment(text);
  891. if (isTextNodeLike(frag)) {
  892. return frag.firstChild;
  893. } else {
  894. throw new HappyMishap(
  895. `The HTML passed in cannot be converted to a single text node: "${text}".`,
  896. { name: "createFragment(text)", inspect: frag }
  897. );
  898. }
  899. }
  900. function createCommentNode(comment) {
  901. return new Comment(comment);
  902. }
  903. var createElement = (el, parent) => solveForNodeType().outputType().solver({
  904. node: (n) => {
  905. if (isElement(n)) {
  906. return createElement(n);
  907. } else {
  908. throw new HappyMishap(
  909. "can't create an IElement from an INode node because it doesn't have a tagName property",
  910. { inspect: n }
  911. );
  912. }
  913. },
  914. html: (h) => {
  915. const frag = createFragment(h);
  916. if (isElementLike(frag)) {
  917. if (parent) {
  918. parent.append(frag.firstElementChild);
  919. return parent == null ? void 0 : parent.lastElementChild;
  920. }
  921. return frag.firstElementChild;
  922. } else {
  923. throw new HappyMishap(
  924. "The HTML passed into createElement() is not convertible to a IElement node!",
  925. { name: "createElement(html)", inspect: frag }
  926. );
  927. }
  928. },
  929. element: identity,
  930. text: (t) => {
  931. throw new HappyMishap(
  932. "An IElement can not be created from a IText node because element's require a wrapping tag name!",
  933. { name: "createElement(text)", inspect: t }
  934. );
  935. },
  936. comment: (t) => {
  937. throw new HappyMishap(
  938. "An IElement can not be created from a IComment node because element's require a wrapping tag name!",
  939. { name: "createElement(comment)", inspect: t }
  940. );
  941. },
  942. fragment: (f) => {
  943. if (isElement(f.firstElementChild)) {
  944. return f.firstElementChild;
  945. } else {
  946. throw new HappyMishap(
  947. `Unable to create a IElement node from:
  948. ${toHtml(f)}`,
  949. { name: "createElement()" }
  950. );
  951. }
  952. },
  953. document: (d) => {
  954. if (isElementLike(d)) {
  955. if (parent) {
  956. throw new HappyMishap(
  957. "A Document and a parent IElement were passed into createElement. This is not a valid combination!"
  958. );
  959. }
  960. return d.firstElementChild;
  961. } else {
  962. throw new HappyMishap(
  963. "Can not create an Element from passed in Document",
  964. { name: "createElement(document)", inspect: d }
  965. );
  966. }
  967. }
  968. })(el);
  969. var renderClasses = (klasses) => {
  970. return klasses.map(
  971. ([selector, defn]) => `
  972. ${selector} {
  973. ${Object.keys(defn).map((p) => ` ${dasherize(p)}: ${defn[p]};`).join("\n")}
  974. }`
  975. ).join("\n");
  976. };
  977. var createInlineStyle = (type = "text/css") => {
  978. const cssVariables = {};
  979. const cssClasses = [];
  980. let isVueBlock = false;
  981. let isScoped = true;
  982. let vueLang = "css";
  983. const api = {
  984. addCssVariable(prop, value, scope = ":root") {
  985. if (!(scope in cssVariables)) {
  986. cssVariables[scope] = [];
  987. }
  988. cssVariables[scope].push({ prop: prop.replace(/^--/, ""), value });
  989. return api;
  990. },
  991. addClassDefinition(selector, cb) {
  992. const classApi = {
  993. addChild: (child, defn) => {
  994. const childSelector = `${selector} ${child}`;
  995. cssClasses.push([childSelector, defn]);
  996. return classApi;
  997. },
  998. addProps: (defn) => {
  999. cssClasses.push([selector, defn]);
  1000. return classApi;
  1001. }
  1002. };
  1003. cb(classApi);
  1004. return api;
  1005. },
  1006. addCssVariables(dictionary, scope = ":root") {
  1007. for (const p of Object.keys(dictionary)) {
  1008. api.addCssVariable(p, dictionary[p], scope);
  1009. }
  1010. return api;
  1011. },
  1012. convertToVueStyleBlock(lang, scoped = true) {
  1013. vueLang = lang;
  1014. isVueBlock = true;
  1015. isScoped = scoped;
  1016. return api;
  1017. },
  1018. finish() {
  1019. const setVariable = (scope, defn) => `${scope} {
  1020. ${Object.keys(defn).map(
  1021. (prop) => ` --${defn[prop].prop}: ${defn[prop].value}${String(defn.prop).endsWith(";") ? "" : ";"}`
  1022. ).join("\n")}
  1023. }`;
  1024. let text = "";
  1025. for (const v of Object.keys(cssVariables)) {
  1026. text = `${text}${setVariable(v, cssVariables[v])}
  1027. `;
  1028. }
  1029. text = `${text}${renderClasses(cssClasses)}`;
  1030. return isVueBlock ? createElement(
  1031. `<style lang="${vueLang}"${isScoped ? " scoped" : ""}>
  1032. ${text}
  1033. </style>`
  1034. ) : createElement(`<style type="${type}">
  1035. ${text}
  1036. </style>`);
  1037. }
  1038. };
  1039. return api;
  1040. };
  1041. // src/attributes.ts
  1042. var setAttribute = (attr) => (value) => (node) => {
  1043. const invalidNode = (n) => {
  1044. throw new HappyMishap(
  1045. `You can not use the setAttribute() utility on a node of type: "${getNodeType(
  1046. n
  1047. )}"`,
  1048. { name: `setAttribute(${attr})(${value})(INVALID)` }
  1049. );
  1050. };
  1051. const result = solveForNodeType().mirror().solver({
  1052. html: (h) => pipe4(h, createFragment, (f) => setAttribute(attr)(value)(f), toHtml),
  1053. text: (t) => invalidNode(t),
  1054. comment: (t) => invalidNode(t),
  1055. node: (n) => invalidNode(n),
  1056. fragment: (f) => {
  1057. f.firstElementChild.setAttribute(attr, value);
  1058. return f;
  1059. },
  1060. document: (d) => {
  1061. d.body.firstElementChild.setAttribute(attr, value);
  1062. return d;
  1063. },
  1064. element: (e) => {
  1065. e.setAttribute(attr, value);
  1066. return e;
  1067. }
  1068. })(node);
  1069. return result;
  1070. };
  1071. var getAttribute = (attr) => {
  1072. return solveForNodeType("text", "node", "comment").outputType().solver({
  1073. html: (h) => pipe4(h, createFragment, getAttribute(attr)),
  1074. fragment: (f) => f.firstElementChild.getAttribute(attr),
  1075. document: (doc) => doc.body.firstElementChild.getAttribute(attr),
  1076. element: (el) => el.getAttribute(attr)
  1077. });
  1078. };
  1079. var getClass = getAttribute("class");
  1080. var setClass = setAttribute("class");
  1081. var getClassList = (container) => {
  1082. if (!container) {
  1083. return [];
  1084. }
  1085. return solveForNodeType().outputType().solver({
  1086. html: (h) => pipe4(h, createFragment, getClassList),
  1087. document: (d) => {
  1088. var _a;
  1089. return ((_a = getClass(d.body.firstElementChild)) == null ? void 0 : _a.split(/\s+/)) || [];
  1090. },
  1091. fragment: (f) => {
  1092. var _a;
  1093. return ((_a = getClass(f.firstElementChild)) == null ? void 0 : _a.split(/\s+/)) || [];
  1094. },
  1095. element: (e) => {
  1096. var _a;
  1097. return ((_a = getClass(e)) == null ? void 0 : _a.split(/\s+/)) || [];
  1098. },
  1099. text: (n) => {
  1100. throw new HappyMishap("Passed in a text node to getClassList!", {
  1101. name: "getClassList",
  1102. inspect: n
  1103. });
  1104. },
  1105. comment: (n) => {
  1106. throw new HappyMishap("Passed in a comment node to getClassList!", {
  1107. name: "getClassList",
  1108. inspect: n
  1109. });
  1110. },
  1111. node: (n) => {
  1112. throw new HappyMishap(
  1113. "Passed in an unknown node type to getClassList!",
  1114. { name: "getClassList", inspect: n }
  1115. );
  1116. }
  1117. })(container).filter(Boolean);
  1118. };
  1119. var removeClass = (remove) => (doc) => {
  1120. var _a;
  1121. const current = ((_a = getClass(doc)) == null ? void 0 : _a.split(/\s+/g)) || [];
  1122. const toRemove = Array.isArray(remove) ? remove : [remove];
  1123. const resultantClassString = [
  1124. ...new Set(current.filter((c) => !toRemove.includes(c)))
  1125. ].filter(Boolean).join(" ");
  1126. return setClass(resultantClassString)(doc);
  1127. };
  1128. var addClass = (...add) => (doc) => {
  1129. var _a;
  1130. const toAdd = Array.isArray(add) ? add.flat() : [add];
  1131. const currentClasses = ((_a = getClass(doc)) == null ? void 0 : _a.split(/\s+/g)) || [];
  1132. const resultantClasses = [
  1133. .../* @__PURE__ */ new Set([...currentClasses, ...toAdd])
  1134. ];
  1135. return setClass(resultantClasses.join(" ").trim())(doc);
  1136. };
  1137. var addVueEvent = (event, value) => {
  1138. return (el) => {
  1139. const isHtml = typeof el === "string";
  1140. const bound = getAttribute("v-bind")(isHtml ? createElement(el) : el);
  1141. const bind = bound ? bound.replace("}", `, ${event}: '${value}' }`) : `{ ${event}: "${value}" }`;
  1142. const e2 = setAttribute("v-bind")(bind)(el);
  1143. return isHtml ? toHtml(e2) : el;
  1144. };
  1145. };
  1146. function hasFilterCallback(filters) {
  1147. return typeof filters[0] === "function";
  1148. }
  1149. var filterClasses = (...args) => (doc) => {
  1150. const el = isDocument(doc) || isFragment(doc) ? doc.firstElementChild : isElement(doc) ? doc : null;
  1151. if (!el) {
  1152. throw new HappyMishap(
  1153. "An invalid container was passed into filterClasses()!",
  1154. { name: "filterClasses", inspect: doc }
  1155. );
  1156. }
  1157. const filters = hasFilterCallback(args) ? args.slice(1) : args;
  1158. const cb = hasFilterCallback(args) ? args[0] : void 0;
  1159. const classes = getClassList(el);
  1160. const removed = [];
  1161. for (const klass of classes) {
  1162. const matched = !filters.every(
  1163. (f) => typeof f === "string" ? f.trim() !== klass.trim() : !f.test(klass)
  1164. );
  1165. if (matched) {
  1166. removed.push(klass);
  1167. }
  1168. }
  1169. setClass(classes.filter((k) => !removed.includes(k)).join(" "))(doc);
  1170. if (cb) {
  1171. cb(removed);
  1172. }
  1173. return doc;
  1174. };
  1175. var hasParentElement = (node) => {
  1176. const n = typeof node === "string" ? createNode(node) : node;
  1177. return solveForNodeType().outputType().solver({
  1178. html: () => false,
  1179. text: (t) => !!t.parentElement,
  1180. comment: (t) => !!t.parentElement,
  1181. element: (e) => !!e.parentElement,
  1182. fragment: (f) => !!f.parentElement,
  1183. document: () => true,
  1184. node: (n2) => !!n2.parentElement
  1185. })(n);
  1186. };
  1187. var getParent = (node) => {
  1188. return hasParentElement(node) ? node.parentElement : null;
  1189. };
  1190. // src/select.ts
  1191. var select = (node) => {
  1192. const originIsHtml = typeof node === "string";
  1193. let rootNode = originIsHtml ? createFragment(node) : isElement(node) ? node : isDocument(node) || isFragment(node) ? node : void 0;
  1194. if (!rootNode) {
  1195. throw new HappyMishap(
  1196. `Attempt to select() an invalid node type: ${getNodeType(node)}`,
  1197. { name: "select(INode)", inspect: node }
  1198. );
  1199. }
  1200. const api = {
  1201. type: () => {
  1202. return originIsHtml ? "html" : getNodeType(rootNode);
  1203. },
  1204. findAll: (sel) => {
  1205. return sel ? rootNode.querySelectorAll(sel) : getChildElements(rootNode);
  1206. },
  1207. findFirst: (sel, errorMsg) => {
  1208. const result = rootNode.querySelector(sel);
  1209. if (!result && errorMsg) {
  1210. throw new HappyMishap(
  1211. `${errorMsg}.
  1212. The HTML from the selected DOM node is:
  1213. ${toHtml(
  1214. rootNode
  1215. )}`,
  1216. { name: "select.findFirst()", inspect: rootNode }
  1217. );
  1218. }
  1219. return result;
  1220. },
  1221. append: (content) => {
  1222. if (!content) {
  1223. return api;
  1224. }
  1225. const nodes = Array.isArray(content) ? content.filter(Boolean) : [content];
  1226. rootNode.append(...nodes);
  1227. return api;
  1228. },
  1229. update: (selection, errorIfNotFound = false) => (mutate) => {
  1230. const el = selection ? rootNode == null ? void 0 : rootNode.querySelector(selection) : isElement(rootNode) ? rootNode : rootNode.firstElementChild ? rootNode.firstElementChild : null;
  1231. if (el) {
  1232. let elReplacement;
  1233. try {
  1234. elReplacement = mutate(
  1235. el,
  1236. 0,
  1237. 1
  1238. );
  1239. } catch (error) {
  1240. throw new HappyMishap(
  1241. `update(): the passed in callback to select(container).update('${selection}')():
  1242. mutate(${describeNode(
  1243. el
  1244. )}, 0, 1)
  1245. ${error instanceof Error ? error.message : String(error)}.`,
  1246. {
  1247. name: `select(${typeof rootNode}).updateAll(${selection})(mutation fn)`,
  1248. inspect: el
  1249. }
  1250. );
  1251. }
  1252. if (elReplacement === false) {
  1253. el.remove();
  1254. } else if (!isElement(elReplacement)) {
  1255. throw new HappyMishap(
  1256. `The return value for a call to select(${getNodeType(
  1257. rootNode
  1258. )}).update(${selection}) return an invalid value! Value return values are an IElement or false.`,
  1259. { name: "select.update", inspect: el }
  1260. );
  1261. }
  1262. } else {
  1263. if (errorIfNotFound) {
  1264. throw new HappyMishap(
  1265. errorIfNotFound === true ? `The selection "${selection}" was not found so the update() operation wasn't able to be run` : errorIfNotFound,
  1266. {
  1267. name: `select(${selection}).update(sel)`,
  1268. inspect: ["parent node", rootNode]
  1269. }
  1270. );
  1271. }
  1272. if (!selection) {
  1273. throw new HappyMishap(
  1274. `Call to select(container).update() was intended to target the root node of the selection but nothing was selected! This shouldn't really happen ... the rootNode's type is ${typeof rootNode}${typeof rootNode === "object" ? `,
  1275. ${getNodeType(rootNode)} [element-like: ${isElementLike(
  1276. rootNode
  1277. )}, element: ${isElement(rootNode)}, children: ${rootNode.childNodes.length}]` : ""}`
  1278. );
  1279. }
  1280. }
  1281. return api;
  1282. },
  1283. updateAll: (selection) => (mutate) => {
  1284. const elements = selection ? rootNode.querySelectorAll(selection) : getChildElements(rootNode);
  1285. for (const [idx, el] of elements.entries()) {
  1286. if (isElement(el)) {
  1287. let elReplacement;
  1288. try {
  1289. elReplacement = mutate(
  1290. el,
  1291. idx,
  1292. elements.length
  1293. );
  1294. } catch (error) {
  1295. throw new HappyMishap(
  1296. `updateAll(): the passed in callback to select(container).updateAll('${selection}')():
  1297. mutate(${describeNode(
  1298. el
  1299. )}, ${idx} idx, ${elements.length} elements)
  1300. ${error instanceof Error ? error.message : String(error)}.`,
  1301. {
  1302. name: `select(${typeof rootNode}).updateAll(${selection})(mutation fn)`,
  1303. inspect: el
  1304. }
  1305. );
  1306. }
  1307. if (elReplacement === false) {
  1308. el.remove();
  1309. } else if (!isElement(elReplacement)) {
  1310. throw new HappyMishap(
  1311. `The return value from the "select(container).updateAll('${selection}')(${describeNode(
  1312. el
  1313. )}, ${idx} idx, ${elements.length} elements)" call was invalid! Valid return values are FALSE or an IElement but instead got: ${typeof elReplacement}.`,
  1314. { name: "select().updateAll -> invalid return value" }
  1315. );
  1316. }
  1317. } else {
  1318. throw new Error(
  1319. `Ran into an unknown node type while running updateAll(): ${JSON.stringify(
  1320. inspect(el),
  1321. null,
  1322. 2
  1323. )}`
  1324. );
  1325. }
  1326. }
  1327. return api;
  1328. },
  1329. mapAll: (selection) => (mutate) => {
  1330. const collection = [];
  1331. const elements = selection ? rootNode.querySelectorAll(selection) : getChildElements(rootNode);
  1332. for (const el of elements) {
  1333. collection.push(mutate(clone(el)));
  1334. }
  1335. return collection;
  1336. },
  1337. filterAll: (selection, cb) => {
  1338. for (const el of rootNode == null ? void 0 : rootNode.querySelectorAll(selection)) {
  1339. if (cb) {
  1340. cb(el);
  1341. }
  1342. el.remove();
  1343. }
  1344. return api;
  1345. },
  1346. wrap: (wrapper, errMsg) => {
  1347. try {
  1348. const safeWrap = typeof wrapper === "string" ? createElement(wrapper) : wrapper;
  1349. rootNode = wrap(rootNode)(safeWrap);
  1350. return api;
  1351. } catch (error) {
  1352. if (isHappyWrapperError(error) || error instanceof Error) {
  1353. error.message = errMsg ? `Error calling select.wrap(): ${errMsg}
  1354. ${error.message}` : `Error calling select.wrap():
  1355. ${error.message}`;
  1356. throw error;
  1357. }
  1358. throw error;
  1359. }
  1360. },
  1361. toContainer: () => {
  1362. return originIsHtml ? toHtml(rootNode) : rootNode;
  1363. }
  1364. };
  1365. return api;
  1366. };
  1367. export {
  1368. HappyMishap,
  1369. addClass,
  1370. addVueEvent,
  1371. after,
  1372. append,
  1373. before,
  1374. changeTagName,
  1375. clone,
  1376. createCommentNode,
  1377. createDocument,
  1378. createElement,
  1379. createFragment,
  1380. createInlineStyle,
  1381. createNode,
  1382. createTextNode,
  1383. describeNode,
  1384. extract,
  1385. filterClasses,
  1386. getAttribute,
  1387. getChildElements,
  1388. getChildren,
  1389. getClassList,
  1390. getNodeType,
  1391. getParent,
  1392. hasParentElement,
  1393. hasSingularElement,
  1394. inspect,
  1395. into,
  1396. isContainer,
  1397. isDocument,
  1398. isElement,
  1399. isElementLike,
  1400. isFragment,
  1401. isHappyWrapperError,
  1402. isInspectionTuple,
  1403. isTextNode,
  1404. isTextNodeLike,
  1405. isUpdateSignature,
  1406. nodeBoundedByElements,
  1407. nodeChildrenAllElements,
  1408. nodeEndsWithElement,
  1409. nodeStartsWithElement,
  1410. nodeTypeLookup,
  1411. placeholder,
  1412. prepend,
  1413. removeClass,
  1414. replaceElement,
  1415. safeString,
  1416. select,
  1417. setAttribute,
  1418. siblings,
  1419. solveForNodeType,
  1420. toHtml,
  1421. tree,
  1422. wrap
  1423. };
  1424. //# sourceMappingURL=index.js.map