@inox-tools/utils 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lazy.js CHANGED
@@ -1,5 +1,5 @@
1
1
  class a{constructor(i){this.factory=i;}initialized=!1;value;static of(i){return new this(i)}get(){return this.initialized||(this.value=this.factory(),this.initialized=!0),this.value}}
2
2
 
3
3
  export { a as Lazy };
4
- //# sourceMappingURL=out.js.map
4
+ //# sourceMappingURL=lazy.js.map
5
5
  //# sourceMappingURL=lazy.js.map
package/dist/lazy.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lazy.ts"],"names":["Lazy","factory"],"mappings":"AAMO,MAAMA,CAAQ,CAGZ,YAAoBC,EAAkB,CAAlB,aAAAA,CAAmB,CAFvC,YAAc,GACd,MAGR,OAAc,GAAMA,EAA2B,CAC9C,OAAO,IAAI,KAAKA,CAAO,CACxB,CAEO,KAAS,CACf,OAAK,KAAK,cACT,KAAK,MAAQ,KAAK,QAAQ,EAC1B,KAAK,YAAc,IAGb,KAAK,KACb,CACD","sourcesContent":["/**\n * A lazily computed memoized value.\n *\n * The given factory is only constructed on first use of the value.\n * Any subsequent use retrieves the same instance of the value.\n */\nexport class Lazy<T> {\n\tprivate initialized = false;\n\tprivate value?: T;\n\tprivate constructor(private factory: () => T) {}\n\n\tpublic static of<T>(factory: () => T): Lazy<T> {\n\t\treturn new this(factory);\n\t}\n\n\tpublic get(): T {\n\t\tif (!this.initialized) {\n\t\t\tthis.value = this.factory();\n\t\t\tthis.initialized = true;\n\t\t}\n\n\t\treturn this.value!;\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/lazy.ts"],"names":["Lazy","factory"],"mappings":"AAMO,MAAMA,CAAQ,CAGZ,WAAA,CAAoBC,CAAkB,CAAA,CAAlB,aAAAA,EAAmB,CAFvC,WAAc,CAAA,CAAA,CAAA,CACd,MAGR,OAAc,EAAA,CAAMA,CAA2B,CAAA,CAC9C,OAAO,IAAI,IAAA,CAAKA,CAAO,CACxB,CAEO,GAAS,EAAA,CACf,OAAK,IAAA,CAAK,cACT,IAAK,CAAA,KAAA,CAAQ,IAAK,CAAA,OAAA,GAClB,IAAK,CAAA,WAAA,CAAc,CAGb,CAAA,CAAA,CAAA,IAAA,CAAK,KACb,CACD","file":"lazy.js","sourcesContent":["/**\n * A lazily computed memoized value.\n *\n * The given factory is only constructed on first use of the value.\n * Any subsequent use retrieves the same instance of the value.\n */\nexport class Lazy<T> {\n\tprivate initialized = false;\n\tprivate value?: T;\n\tprivate constructor(private factory: () => T) {}\n\n\tpublic static of<T>(factory: () => T): Lazy<T> {\n\t\treturn new this(factory);\n\t}\n\n\tpublic get(): T {\n\t\tif (!this.initialized) {\n\t\t\tthis.value = this.factory();\n\t\t\tthis.initialized = true;\n\t\t}\n\n\t\treturn this.value!;\n\t}\n}\n"]}
package/dist/once.js CHANGED
@@ -1,5 +1,5 @@
1
1
  class o{#i=!1;do(i){this.#i||(i(),this.#i=!0);}async doAsync(i){this.#i||(await i(),this.#i=!0);}}
2
2
 
3
3
  export { o as Once };
4
- //# sourceMappingURL=out.js.map
4
+ //# sourceMappingURL=once.js.map
5
5
  //# sourceMappingURL=once.js.map
package/dist/once.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/once.ts"],"names":["Once","#done","callback"],"mappings":"AAAO,MAAMA,CAAK,CACjBC,GAAQ,GAED,GAAGC,EAA4B,CAChC,KAAKD,KACTC,EAAS,EACT,KAAKD,GAAQ,GAEf,CAEA,MAAa,QAAQC,EAA8C,CAC7D,KAAKD,KACT,MAAMC,EAAS,EACf,KAAKD,GAAQ,GAEf,CACD","sourcesContent":["export class Once {\n\t#done = false;\n\n\tpublic do(callback: () => void): void {\n\t\tif (!this.#done) {\n\t\t\tcallback();\n\t\t\tthis.#done = true;\n\t\t}\n\t}\n\n\tpublic async doAsync(callback: () => Promise<void>): Promise<void> {\n\t\tif (!this.#done) {\n\t\t\tawait callback();\n\t\t\tthis.#done = true;\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/once.ts"],"names":["Once","#done","callback"],"mappings":"AAAO,MAAMA,CAAK,CACjBC,EAAAA,CAAQ,CAED,CAAA,CAAA,EAAA,CAAGC,CAA4B,CAAA,CAChC,IAAKD,CAAAA,EAAAA,GACTC,CAAS,EAAA,CACT,IAAKD,CAAAA,EAAAA,CAAQ,CAEf,CAAA,EAAA,CAEA,MAAa,OAAA,CAAQC,CAA8C,CAAA,CAC7D,IAAKD,CAAAA,EAAAA,GACT,MAAMC,CAAAA,EACN,CAAA,IAAA,CAAKD,EAAQ,CAAA,CAAA,CAAA,EAEf,CACD","file":"once.js","sourcesContent":["export class Once {\n\t#done = false;\n\n\tpublic do(callback: () => void): void {\n\t\tif (!this.#done) {\n\t\t\tcallback();\n\t\t\tthis.#done = true;\n\t\t}\n\t}\n\n\tpublic async doAsync(callback: () => Promise<void>): Promise<void> {\n\t\tif (!this.#done) {\n\t\t\tawait callback();\n\t\t\tthis.#done = true;\n\t\t}\n\t}\n}\n"]}
package/dist/types.js CHANGED
@@ -1,3 +1,3 @@
1
1
 
2
- //# sourceMappingURL=out.js.map
2
+ //# sourceMappingURL=types.js.map
3
3
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"types.js"}
@@ -0,0 +1,135 @@
1
+ import * as unist_util_is from 'unist-util-is';
2
+ import * as unist from 'unist';
3
+
4
+ /**
5
+ * Continue traversing as normal.
6
+ */
7
+ declare const CONTINUE = true;
8
+ /**
9
+ * Stop traversing immediately.
10
+ */
11
+ declare const EXIT = false;
12
+ /**
13
+ * Do not traverse this node’s children.
14
+ */
15
+ declare const SKIP = "skip";
16
+ type Options<Tree extends unist.Node, Check extends Test> = {
17
+ tree: Tree;
18
+ test?: Check;
19
+ enter?: BuildVisitor<Tree, Check>;
20
+ leave?: BuildVisitor<Tree, Check>;
21
+ reverse?: boolean;
22
+ };
23
+ declare function visitParents<Tree extends unist.Node, Check extends Test>({ tree, test, enter: enterVisitor, leave: leaveVisitor, reverse, }: Options<Tree, Check>): void;
24
+ type UnistNode = unist.Node;
25
+ type UnistParent = unist.Parent;
26
+ /**
27
+ * Test from `unist-util-is`.
28
+ *
29
+ * Note: we have remove and add `undefined`, because otherwise when generating
30
+ * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
31
+ * which doesn’t work when publishing on npm.
32
+ */
33
+ type Test = Exclude<unist_util_is.Test, undefined> | undefined;
34
+ /**
35
+ * Get the value of a type guard `Fn`.
36
+ */
37
+ type Predicate<Fn, Fallback> = Fn extends (value: any) => value is infer Thing ? Thing : Fallback;
38
+ /**
39
+ * Check whether a node matches a primitive check in the type system.
40
+ */
41
+ type MatchesOne<Value, Check> = Check extends null | undefined ? Value : Value extends {
42
+ type: Check;
43
+ } ? Value : Value extends Check ? Value : Check extends Function ? Predicate<Check, Value> extends Value ? Predicate<Check, Value> : never : never;
44
+ /**
45
+ * Check whether a node matches a check in the type system.
46
+ */
47
+ type Matches<Value, Check> = Check extends Array<any> ? MatchesOne<Value, Check[keyof Check]> : MatchesOne<Value, Check>;
48
+ /**
49
+ * Number; capped reasonably.
50
+ */
51
+ type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
52
+ /**
53
+ * Increment a number in the type system.
54
+ */
55
+ type Increment<I extends Uint = 0> = I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10;
56
+ /**
57
+ * Collect nodes that can be parents of `Child`.
58
+ */
59
+ type InternalParent<Node extends unist.Node, Child extends unist.Node> = Node extends unist.Parent ? Node extends {
60
+ children: (infer Children)[];
61
+ } ? Child extends Children ? Node : never : never : never;
62
+ /**
63
+ * Collect nodes in `Tree` that can be parents of `Child`.
64
+ */
65
+ type Parent<Tree extends unist.Node, Child extends unist.Node> = InternalParent<InclusiveDescendant<Tree>, Child>;
66
+ /**
67
+ * Collect nodes in `Tree` that can be ancestors of `Child`.
68
+ */
69
+ type InternalAncestor<Node extends unist.Node, Child extends unist.Node, Max extends Uint = 10, Depth extends Uint = 0> = Depth extends Max ? never : InternalParent<Node, Child> | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>;
70
+ /**
71
+ * Collect nodes in `Tree` that can be ancestors of `Child`.
72
+ */
73
+ type Ancestor<Tree extends unist.Node, Child extends unist.Node> = InternalAncestor<InclusiveDescendant<Tree>, Child>;
74
+ /**
75
+ * Collect all (inclusive) descendants of `Tree`.
76
+ *
77
+ * > 👉 **Note**: for performance reasons, this seems to be the fastest way to
78
+ * > recurse without actually running into an infinite loop, which the
79
+ * > previous version did.
80
+ * >
81
+ * > Practically, a max of `2` is typically enough assuming a `Root` is
82
+ * > passed, but it doesn’t improve performance.
83
+ * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
84
+ * > Using up to `10` doesn’t hurt or help either.
85
+ */
86
+ type InclusiveDescendant<Tree extends unist.Node, Max extends Uint = 10, Depth extends Uint = 0> = Tree extends UnistParent ? Depth extends Max ? Tree : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>> : Tree;
87
+ /**
88
+ * Union of the action types.
89
+ */
90
+ type Action = 'skip' | boolean;
91
+ /**
92
+ * Move to the sibling at `index` next (after node itself is completely
93
+ * traversed).
94
+ *
95
+ * Useful if mutating the tree, such as removing the node the visitor is
96
+ * currently on, or any of its previous siblings.
97
+ * Results less than 0 or greater than or equal to `children.length` stop
98
+ * traversing the parent.
99
+ */
100
+ type Index = number;
101
+ /**
102
+ * List with one or two values, the first an action, the second an index.
103
+ */
104
+ type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];
105
+ /**
106
+ * Any value that can be returned from a visitor.
107
+ */
108
+ type VisitorResult = Action | [(void | Action | null | undefined)?, (number | null | undefined)?] | Index | null | undefined | void;
109
+ /**
110
+ * Handle a node (matching `test`, if given).
111
+ *
112
+ * Visitors are free to transform `node`.
113
+ * They can also transform the parent of node (the last of `ancestors`).
114
+ *
115
+ * Replacing `node` itself, if `SKIP` is not returned, still causes its
116
+ * descendants to be walked (which is a bug).
117
+ *
118
+ * When adding or removing previous siblings of `node` (or next siblings, in
119
+ * case of reverse), the `Visitor` should return a new `Index` to specify the
120
+ * sibling to traverse after `node` is traversed.
121
+ * Adding or removing next siblings of `node` (or previous siblings, in case
122
+ * of reverse) is handled as expected without needing to return a new `Index`.
123
+ *
124
+ * Removing the children property of an ancestor still results in them being
125
+ * traversed.
126
+ */
127
+ type Visitor<Visited extends unist.Node = unist.Node, VisitedParents extends unist.Parent = unist.Parent> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;
128
+ /**
129
+ * Build a typed `Visitor` function from a tree and a test.
130
+ *
131
+ * It will infer which values are passed as `node` and which as `parents`.
132
+ */
133
+ type BuildVisitor<Tree extends unist.Node = unist.Node, Check extends Test = Test> = Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>;
134
+
135
+ export { type Action, type ActionTuple, type Ancestor, type BuildVisitor, CONTINUE, EXIT, type InclusiveDescendant, type Increment, type Index, type InternalAncestor, type InternalParent, type Matches, type MatchesOne, type Options, type Parent, type Predicate, SKIP, type Test, type Uint, type UnistNode, type UnistParent, type Visitor, type VisitorResult, visitParents };
@@ -0,0 +1,7 @@
1
+ import { convert } from 'unist-util-is';
2
+
3
+ const a=[],A=!0,f=!1,P="skip";function M({tree:e,test:u,enter:l,leave:c,reverse:p}){if(!e)throw new TypeError("A tree is required");if(!l&&!c)throw new Error("At least one visitor (`enter` or `leave`) must be provided");const I=convert(u),x=p?-1:1;h(e,void 0,[])();function h(n,k,s){const d=n;if(typeof d.type=="string"){const t=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(y,"name",{value:"node ("+n.type+(t?"<"+t+">":"")+")"});}return y;function y(){let t=a,o,i,T;const m=!u||I(n,k,s[s.length-1]);if(m&&(t=C(l?.(n,s)),t[0]===f))return t;if("children"in n&&n.children){const r=n;if(r.children&&t[0]!==P)for(i=(p?r.children.length:-1)+x,T=s.concat(r);i>-1&&i<r.children.length;){const N=r.children[i];if(o=h(N,i,T)(),o[0]===f)return o;i=typeof o[1]=="number"?o[1]:i+x;}}if(m&&c){const r=C(c(n,s));return r===a?t:r}return t}}}function C(e){return Array.isArray(e)?e:typeof e=="number"?[A,e]:e==null?a:[e]}
4
+
5
+ export { A as CONTINUE, f as EXIT, P as SKIP, M as visitParents };
6
+ //# sourceMappingURL=visit.js.map
7
+ //# sourceMappingURL=visit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/unist/visit.ts"],"names":["empty","CONTINUE","EXIT","SKIP","visitParents","tree","test","enterVisitor","leaveVisitor","reverse","is","convert","step","factory","node","index","parents","value","name","visit","result","subresult","offset","grandparents","isMatch","toResult","nodeAsParent","child","leaveResult"],"mappings":"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","file":"visit.js","sourcesContent":["import { convert } from 'unist-util-is';\n\nconst empty: ActionTuple = [];\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true;\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false;\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip';\n\nexport type Options<Tree extends import('unist').Node, Check extends Test> = {\n\ttree: Tree;\n\ttest?: Check;\n\tenter?: BuildVisitor<Tree, Check>;\n\tleave?: BuildVisitor<Tree, Check>;\n\treverse?: boolean;\n};\n\nexport function visitParents<Tree extends import('unist').Node, Check extends Test>({\n\ttree,\n\ttest,\n\tenter: enterVisitor,\n\tleave: leaveVisitor,\n\treverse,\n}: Options<Tree, Check>) {\n\tif (!tree) {\n\t\tthrow new TypeError('A tree is required');\n\t}\n\n\tif (!enterVisitor && !leaveVisitor) {\n\t\tthrow new Error('At least one visitor (`enter` or `leave`) must be provided');\n\t}\n\n\tconst is = convert(test) as (\n\t\tnode: UnistNode,\n\t\tindex?: number,\n\t\tparent?: UnistParent\n\t) => node is Matches<InclusiveDescendant<Tree>, Check>;\n\tconst step = reverse ? -1 : 1;\n\n\tfactory(tree, undefined, [])();\n\n\tfunction factory(node: UnistNode, index: number | undefined, parents: UnistParent[]) {\n\t\tconst value = node as UnistNode & Record<string, unknown>;\n\n\t\tif (typeof value.type === 'string') {\n\t\t\tconst name =\n\t\t\t\t// `hast`\n\t\t\t\ttypeof value.tagName === 'string'\n\t\t\t\t\t? value.tagName\n\t\t\t\t\t: // `xast`\n\t\t\t\t\t\ttypeof value.name === 'string'\n\t\t\t\t\t\t? value.name\n\t\t\t\t\t\t: undefined;\n\n\t\t\tObject.defineProperty(visit, 'name', {\n\t\t\t\tvalue: 'node (' + node.type + (name ? '<' + name + '>' : '') + ')',\n\t\t\t});\n\t\t}\n\n\t\treturn visit;\n\n\t\tfunction visit() {\n\t\t\tlet result: Readonly<ActionTuple> = empty;\n\t\t\tlet subresult: Readonly<ActionTuple>;\n\t\t\tlet offset: number;\n\t\t\tlet grandparents: UnistParent[];\n\t\t\tconst isMatch = !test || is(node, index, parents[parents.length - 1]);\n\n\t\t\tif (isMatch) {\n\t\t\t\tresult = toResult(\n\t\t\t\t\tenterVisitor?.(\n\t\t\t\t\t\tnode as Matches<InclusiveDescendant<Tree>, Check>,\n\t\t\t\t\t\tparents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t\tif (result[0] === EXIT) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('children' in node && node.children) {\n\t\t\t\tconst nodeAsParent = node as UnistParent;\n\n\t\t\t\tif (nodeAsParent.children && result[0] !== SKIP) {\n\t\t\t\t\toffset = (reverse ? nodeAsParent.children.length : -1) + step;\n\t\t\t\t\tgrandparents = parents.concat(nodeAsParent);\n\n\t\t\t\t\twhile (offset > -1 && offset < nodeAsParent.children.length) {\n\t\t\t\t\t\tconst child = nodeAsParent.children[offset];\n\n\t\t\t\t\t\tsubresult = factory(child, offset, grandparents)();\n\n\t\t\t\t\t\tif (subresult[0] === EXIT) {\n\t\t\t\t\t\t\treturn subresult;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\toffset = typeof subresult[1] === 'number' ? subresult[1] : offset + step;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isMatch && leaveVisitor) {\n\t\t\t\tconst leaveResult = toResult(\n\t\t\t\t\tleaveVisitor(\n\t\t\t\t\t\tnode as Matches<InclusiveDescendant<Tree>, Check>,\n\t\t\t\t\t\tparents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t\treturn leaveResult === empty ? result : leaveResult;\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n}\n\n/**\n * Turn a return value into a clean result.\n */\nfunction toResult(value: VisitorResult): Readonly<ActionTuple> {\n\tif (Array.isArray(value)) {\n\t\treturn value;\n\t}\n\n\tif (typeof value === 'number') {\n\t\treturn [CONTINUE, value];\n\t}\n\n\treturn value === null || value === undefined ? empty : [value];\n}\n\nexport type UnistNode = import('unist').Node;\nexport type UnistParent = import('unist').Parent;\n/**\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\nexport type Test = Exclude<import('unist-util-is').Test, undefined> | undefined;\n/**\n * Get the value of a type guard `Fn`.\n */\nexport type Predicate<Fn, Fallback> = Fn extends (value: any) => value is infer Thing\n\t? Thing\n\t: Fallback;\n/**\n * Check whether a node matches a primitive check in the type system.\n */\nexport type MatchesOne<Value, Check> = Check extends null | undefined\n\t? Value\n\t: Value extends {\n\t\t\t\ttype: Check;\n\t\t }\n\t\t? Value\n\t\t: Value extends Check\n\t\t\t? Value\n\t\t\t: Check extends Function\n\t\t\t\t? Predicate<Check, Value> extends Value\n\t\t\t\t\t? Predicate<Check, Value>\n\t\t\t\t\t: never\n\t\t\t\t: never;\n/**\n * Check whether a node matches a check in the type system.\n */\nexport type Matches<Value, Check> =\n\tCheck extends Array<any> ? MatchesOne<Value, Check[keyof Check]> : MatchesOne<Value, Check>;\n/**\n * Number; capped reasonably.\n */\nexport type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;\n/**\n * Increment a number in the type system.\n */\nexport type Increment<I extends Uint = 0> = I extends 0\n\t? 1\n\t: I extends 1\n\t\t? 2\n\t\t: I extends 2\n\t\t\t? 3\n\t\t\t: I extends 3\n\t\t\t\t? 4\n\t\t\t\t: I extends 4\n\t\t\t\t\t? 5\n\t\t\t\t\t: I extends 5\n\t\t\t\t\t\t? 6\n\t\t\t\t\t\t: I extends 6\n\t\t\t\t\t\t\t? 7\n\t\t\t\t\t\t\t: I extends 7\n\t\t\t\t\t\t\t\t? 8\n\t\t\t\t\t\t\t\t: I extends 8\n\t\t\t\t\t\t\t\t\t? 9\n\t\t\t\t\t\t\t\t\t: 10;\n/**\n * Collect nodes that can be parents of `Child`.\n */\nexport type InternalParent<\n\tNode extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = Node extends import('unist').Parent\n\t? Node extends {\n\t\t\tchildren: (infer Children)[];\n\t\t}\n\t\t? Child extends Children\n\t\t\t? Node\n\t\t\t: never\n\t\t: never\n\t: never;\n/**\n * Collect nodes in `Tree` that can be parents of `Child`.\n */\nexport type Parent<\n\tTree extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = InternalParent<InclusiveDescendant<Tree>, Child>;\n/**\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n */\nexport type InternalAncestor<\n\tNode extends import('unist').Node,\n\tChild extends import('unist').Node,\n\tMax extends Uint = 10,\n\tDepth extends Uint = 0,\n> = Depth extends Max\n\t? never\n\t:\n\t\t\t| InternalParent<Node, Child>\n\t\t\t| InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>;\n/**\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n */\nexport type Ancestor<\n\tTree extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = InternalAncestor<InclusiveDescendant<Tree>, Child>;\n/**\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n */\nexport type InclusiveDescendant<\n\tTree extends import('unist').Node,\n\tMax extends Uint = 10,\n\tDepth extends Uint = 0,\n> = Tree extends UnistParent\n\t? Depth extends Max\n\t\t? Tree\n\t\t: Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n\t: Tree;\n/**\n * Union of the action types.\n */\nexport type Action = 'skip' | boolean;\n/**\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n */\nexport type Index = number;\n/**\n * List with one or two values, the first an action, the second an index.\n */\nexport type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];\n/**\n * Any value that can be returned from a visitor.\n */\nexport type VisitorResult =\n\t| Action\n\t| [(void | Action | null | undefined)?, (number | null | undefined)?]\n\t| Index\n\t| null\n\t| undefined\n\t| void;\n/**\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n */\nexport type Visitor<\n\tVisited extends import('unist').Node = import('unist').Node,\n\tVisitedParents extends import('unist').Parent = import('unist').Parent,\n> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;\n\n/**\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\nexport type BuildVisitor<\n\tTree extends import('unist').Node = import('unist').Node,\n\tCheck extends Test = Test,\n> = Visitor<\n\tMatches<InclusiveDescendant<Tree>, Check>,\n\tAncestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>\n>;\n"]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A value that can be might be pending to be resolved.
3
+ */
4
+ type MaybePromise<T> = T | Promise<T>;
5
+ /**
6
+ * A value or a thunk for a value.
7
+ *
8
+ * A "thunk" is a function that takes no arguments and return
9
+ * a value that is potentially expensive to compute.
10
+ * This can be used when the value might not be needed and as
11
+ * such can be computed on demand potentially saving the
12
+ * expensive computation.
13
+ *
14
+ * If the value is not expensive to compute it can be used directly
15
+ * for simplicity.
16
+ *
17
+ * A value type that is itself a function cannot be a "maybe" thunk.
18
+ *
19
+ * @see https://en.wikipedia.org/wiki/Thunk
20
+ */
21
+ type MaybeThunk<T> = T extends Function ? never : T | (() => T);
22
+ /**
23
+ * A value or a thunk for a synchronous or asynchronous value.
24
+ *
25
+ * @see MaybePromise
26
+ * @see MaybeThunk
27
+ */
28
+ type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;
29
+ /**
30
+ * Load a value from a possibly thunk argument.
31
+ *
32
+ * If the value is a thunk it is called and the result is returned.
33
+ * Otherwise the value itself is returned.
34
+ *
35
+ * @see MaybeThunk
36
+ */
37
+ declare function loadThunkValue<T>(value: MaybeThunk<T>): T;
38
+
39
+ export { type MaybeAsyncThunk, type MaybePromise, type MaybeThunk, loadThunkValue };
package/dist/values.js ADDED
@@ -0,0 +1,5 @@
1
+ function T(e){return typeof e=="function"?e():e}
2
+
3
+ export { T as loadThunkValue };
4
+ //# sourceMappingURL=values.js.map
5
+ //# sourceMappingURL=values.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/values.ts"],"names":["loadThunkValue","value"],"mappings":"AAuCO,SAASA,CAAAA,CAAkBC,EAAyB,CAC1D,OAAO,OAAOA,CAAU,EAAA,UAAA,CAAaA,CAAM,EAAA,CAAIA,CAChD","file":"values.js","sourcesContent":["/**\n * A value that can be might be pending to be resolved.\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value or a thunk for a value.\n *\n * A \"thunk\" is a function that takes no arguments and return\n * a value that is potentially expensive to compute.\n * This can be used when the value might not be needed and as\n * such can be computed on demand potentially saving the\n * expensive computation.\n *\n * If the value is not expensive to compute it can be used directly\n * for simplicity.\n *\n * A value type that is itself a function cannot be a \"maybe\" thunk.\n *\n * @see https://en.wikipedia.org/wiki/Thunk\n */\nexport type MaybeThunk<T> = T extends Function ? never : T | (() => T);\n\n/**\n * A value or a thunk for a synchronous or asynchronous value.\n *\n * @see MaybePromise\n * @see MaybeThunk\n */\nexport type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;\n\n/**\n * Load a value from a possibly thunk argument.\n *\n * If the value is a thunk it is called and the result is returned.\n * Otherwise the value itself is returned.\n *\n * @see MaybeThunk\n */\nexport function loadThunkValue<T>(value: MaybeThunk<T>): T {\n\treturn typeof value === 'function' ? value() : value;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inox-tools/utils",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "A collection of utilities used throughout Inox Tools",
5
5
  "keywords": [
6
6
  "utilities"
@@ -20,15 +20,21 @@
20
20
  "src"
21
21
  ],
22
22
  "devDependencies": {
23
- "@types/node": "^20.14.10",
24
- "@vitest/coverage-v8": "^2.0.2",
25
- "@vitest/ui": "^2.0.2",
26
- "astro": "^4.11.5",
23
+ "@types/hast": "^3.0.4",
24
+ "@types/mdast": "^4.0.4",
25
+ "@types/node": "^22.7.4",
26
+ "@types/unist": "^3.0.3",
27
+ "@types/xast": "^2.0.4",
28
+ "@vitest/coverage-v8": "^2.1.1",
29
+ "@vitest/ui": "^2.1.1",
30
+ "astro": "^4.15.9",
27
31
  "jest-extended": "^4.0.2",
28
- "tsup": "^8.1.0",
29
- "typescript": "^5.5.3",
30
- "vite": "^5.3.3",
31
- "vitest": "^2.0.2"
32
+ "mdast-util-from-markdown": "^2.0.1",
33
+ "tsup": "8.2.4",
34
+ "typescript": "^5.5.4",
35
+ "unist-util-is": "^6.0.0",
36
+ "vite": "^5.4.8",
37
+ "vitest": "^2.1.1"
32
38
  },
33
39
  "scripts": {
34
40
  "build": "tsup",
@@ -0,0 +1,332 @@
1
+ import { convert } from 'unist-util-is';
2
+
3
+ const empty: ActionTuple = [];
4
+
5
+ /**
6
+ * Continue traversing as normal.
7
+ */
8
+ export const CONTINUE = true;
9
+
10
+ /**
11
+ * Stop traversing immediately.
12
+ */
13
+ export const EXIT = false;
14
+
15
+ /**
16
+ * Do not traverse this node’s children.
17
+ */
18
+ export const SKIP = 'skip';
19
+
20
+ export type Options<Tree extends import('unist').Node, Check extends Test> = {
21
+ tree: Tree;
22
+ test?: Check;
23
+ enter?: BuildVisitor<Tree, Check>;
24
+ leave?: BuildVisitor<Tree, Check>;
25
+ reverse?: boolean;
26
+ };
27
+
28
+ export function visitParents<Tree extends import('unist').Node, Check extends Test>({
29
+ tree,
30
+ test,
31
+ enter: enterVisitor,
32
+ leave: leaveVisitor,
33
+ reverse,
34
+ }: Options<Tree, Check>) {
35
+ if (!tree) {
36
+ throw new TypeError('A tree is required');
37
+ }
38
+
39
+ if (!enterVisitor && !leaveVisitor) {
40
+ throw new Error('At least one visitor (`enter` or `leave`) must be provided');
41
+ }
42
+
43
+ const is = convert(test) as (
44
+ node: UnistNode,
45
+ index?: number,
46
+ parent?: UnistParent
47
+ ) => node is Matches<InclusiveDescendant<Tree>, Check>;
48
+ const step = reverse ? -1 : 1;
49
+
50
+ factory(tree, undefined, [])();
51
+
52
+ function factory(node: UnistNode, index: number | undefined, parents: UnistParent[]) {
53
+ const value = node as UnistNode & Record<string, unknown>;
54
+
55
+ if (typeof value.type === 'string') {
56
+ const name =
57
+ // `hast`
58
+ typeof value.tagName === 'string'
59
+ ? value.tagName
60
+ : // `xast`
61
+ typeof value.name === 'string'
62
+ ? value.name
63
+ : undefined;
64
+
65
+ Object.defineProperty(visit, 'name', {
66
+ value: 'node (' + node.type + (name ? '<' + name + '>' : '') + ')',
67
+ });
68
+ }
69
+
70
+ return visit;
71
+
72
+ function visit() {
73
+ let result: Readonly<ActionTuple> = empty;
74
+ let subresult: Readonly<ActionTuple>;
75
+ let offset: number;
76
+ let grandparents: UnistParent[];
77
+ const isMatch = !test || is(node, index, parents[parents.length - 1]);
78
+
79
+ if (isMatch) {
80
+ result = toResult(
81
+ enterVisitor?.(
82
+ node as Matches<InclusiveDescendant<Tree>, Check>,
83
+ parents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>
84
+ )
85
+ );
86
+
87
+ if (result[0] === EXIT) {
88
+ return result;
89
+ }
90
+ }
91
+
92
+ if ('children' in node && node.children) {
93
+ const nodeAsParent = node as UnistParent;
94
+
95
+ if (nodeAsParent.children && result[0] !== SKIP) {
96
+ offset = (reverse ? nodeAsParent.children.length : -1) + step;
97
+ grandparents = parents.concat(nodeAsParent);
98
+
99
+ while (offset > -1 && offset < nodeAsParent.children.length) {
100
+ const child = nodeAsParent.children[offset];
101
+
102
+ subresult = factory(child, offset, grandparents)();
103
+
104
+ if (subresult[0] === EXIT) {
105
+ return subresult;
106
+ }
107
+
108
+ offset = typeof subresult[1] === 'number' ? subresult[1] : offset + step;
109
+ }
110
+ }
111
+ }
112
+
113
+ if (isMatch && leaveVisitor) {
114
+ const leaveResult = toResult(
115
+ leaveVisitor(
116
+ node as Matches<InclusiveDescendant<Tree>, Check>,
117
+ parents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>
118
+ )
119
+ );
120
+
121
+ return leaveResult === empty ? result : leaveResult;
122
+ }
123
+
124
+ return result;
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Turn a return value into a clean result.
131
+ */
132
+ function toResult(value: VisitorResult): Readonly<ActionTuple> {
133
+ if (Array.isArray(value)) {
134
+ return value;
135
+ }
136
+
137
+ if (typeof value === 'number') {
138
+ return [CONTINUE, value];
139
+ }
140
+
141
+ return value === null || value === undefined ? empty : [value];
142
+ }
143
+
144
+ export type UnistNode = import('unist').Node;
145
+ export type UnistParent = import('unist').Parent;
146
+ /**
147
+ * Test from `unist-util-is`.
148
+ *
149
+ * Note: we have remove and add `undefined`, because otherwise when generating
150
+ * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
151
+ * which doesn’t work when publishing on npm.
152
+ */
153
+ export type Test = Exclude<import('unist-util-is').Test, undefined> | undefined;
154
+ /**
155
+ * Get the value of a type guard `Fn`.
156
+ */
157
+ export type Predicate<Fn, Fallback> = Fn extends (value: any) => value is infer Thing
158
+ ? Thing
159
+ : Fallback;
160
+ /**
161
+ * Check whether a node matches a primitive check in the type system.
162
+ */
163
+ export type MatchesOne<Value, Check> = Check extends null | undefined
164
+ ? Value
165
+ : Value extends {
166
+ type: Check;
167
+ }
168
+ ? Value
169
+ : Value extends Check
170
+ ? Value
171
+ : Check extends Function
172
+ ? Predicate<Check, Value> extends Value
173
+ ? Predicate<Check, Value>
174
+ : never
175
+ : never;
176
+ /**
177
+ * Check whether a node matches a check in the type system.
178
+ */
179
+ export type Matches<Value, Check> =
180
+ Check extends Array<any> ? MatchesOne<Value, Check[keyof Check]> : MatchesOne<Value, Check>;
181
+ /**
182
+ * Number; capped reasonably.
183
+ */
184
+ export type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
185
+ /**
186
+ * Increment a number in the type system.
187
+ */
188
+ export type Increment<I extends Uint = 0> = I extends 0
189
+ ? 1
190
+ : I extends 1
191
+ ? 2
192
+ : I extends 2
193
+ ? 3
194
+ : I extends 3
195
+ ? 4
196
+ : I extends 4
197
+ ? 5
198
+ : I extends 5
199
+ ? 6
200
+ : I extends 6
201
+ ? 7
202
+ : I extends 7
203
+ ? 8
204
+ : I extends 8
205
+ ? 9
206
+ : 10;
207
+ /**
208
+ * Collect nodes that can be parents of `Child`.
209
+ */
210
+ export type InternalParent<
211
+ Node extends import('unist').Node,
212
+ Child extends import('unist').Node,
213
+ > = Node extends import('unist').Parent
214
+ ? Node extends {
215
+ children: (infer Children)[];
216
+ }
217
+ ? Child extends Children
218
+ ? Node
219
+ : never
220
+ : never
221
+ : never;
222
+ /**
223
+ * Collect nodes in `Tree` that can be parents of `Child`.
224
+ */
225
+ export type Parent<
226
+ Tree extends import('unist').Node,
227
+ Child extends import('unist').Node,
228
+ > = InternalParent<InclusiveDescendant<Tree>, Child>;
229
+ /**
230
+ * Collect nodes in `Tree` that can be ancestors of `Child`.
231
+ */
232
+ export type InternalAncestor<
233
+ Node extends import('unist').Node,
234
+ Child extends import('unist').Node,
235
+ Max extends Uint = 10,
236
+ Depth extends Uint = 0,
237
+ > = Depth extends Max
238
+ ? never
239
+ :
240
+ | InternalParent<Node, Child>
241
+ | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>;
242
+ /**
243
+ * Collect nodes in `Tree` that can be ancestors of `Child`.
244
+ */
245
+ export type Ancestor<
246
+ Tree extends import('unist').Node,
247
+ Child extends import('unist').Node,
248
+ > = InternalAncestor<InclusiveDescendant<Tree>, Child>;
249
+ /**
250
+ * Collect all (inclusive) descendants of `Tree`.
251
+ *
252
+ * > 👉 **Note**: for performance reasons, this seems to be the fastest way to
253
+ * > recurse without actually running into an infinite loop, which the
254
+ * > previous version did.
255
+ * >
256
+ * > Practically, a max of `2` is typically enough assuming a `Root` is
257
+ * > passed, but it doesn’t improve performance.
258
+ * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
259
+ * > Using up to `10` doesn’t hurt or help either.
260
+ */
261
+ export type InclusiveDescendant<
262
+ Tree extends import('unist').Node,
263
+ Max extends Uint = 10,
264
+ Depth extends Uint = 0,
265
+ > = Tree extends UnistParent
266
+ ? Depth extends Max
267
+ ? Tree
268
+ : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>
269
+ : Tree;
270
+ /**
271
+ * Union of the action types.
272
+ */
273
+ export type Action = 'skip' | boolean;
274
+ /**
275
+ * Move to the sibling at `index` next (after node itself is completely
276
+ * traversed).
277
+ *
278
+ * Useful if mutating the tree, such as removing the node the visitor is
279
+ * currently on, or any of its previous siblings.
280
+ * Results less than 0 or greater than or equal to `children.length` stop
281
+ * traversing the parent.
282
+ */
283
+ export type Index = number;
284
+ /**
285
+ * List with one or two values, the first an action, the second an index.
286
+ */
287
+ export type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];
288
+ /**
289
+ * Any value that can be returned from a visitor.
290
+ */
291
+ export type VisitorResult =
292
+ | Action
293
+ | [(void | Action | null | undefined)?, (number | null | undefined)?]
294
+ | Index
295
+ | null
296
+ | undefined
297
+ | void;
298
+ /**
299
+ * Handle a node (matching `test`, if given).
300
+ *
301
+ * Visitors are free to transform `node`.
302
+ * They can also transform the parent of node (the last of `ancestors`).
303
+ *
304
+ * Replacing `node` itself, if `SKIP` is not returned, still causes its
305
+ * descendants to be walked (which is a bug).
306
+ *
307
+ * When adding or removing previous siblings of `node` (or next siblings, in
308
+ * case of reverse), the `Visitor` should return a new `Index` to specify the
309
+ * sibling to traverse after `node` is traversed.
310
+ * Adding or removing next siblings of `node` (or previous siblings, in case
311
+ * of reverse) is handled as expected without needing to return a new `Index`.
312
+ *
313
+ * Removing the children property of an ancestor still results in them being
314
+ * traversed.
315
+ */
316
+ export type Visitor<
317
+ Visited extends import('unist').Node = import('unist').Node,
318
+ VisitedParents extends import('unist').Parent = import('unist').Parent,
319
+ > = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;
320
+
321
+ /**
322
+ * Build a typed `Visitor` function from a tree and a test.
323
+ *
324
+ * It will infer which values are passed as `node` and which as `parents`.
325
+ */
326
+ export type BuildVisitor<
327
+ Tree extends import('unist').Node = import('unist').Node,
328
+ Check extends Test = Test,
329
+ > = Visitor<
330
+ Matches<InclusiveDescendant<Tree>, Check>,
331
+ Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>
332
+ >;
package/src/values.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A value that can be might be pending to be resolved.
3
+ */
4
+ export type MaybePromise<T> = T | Promise<T>;
5
+
6
+ /**
7
+ * A value or a thunk for a value.
8
+ *
9
+ * A "thunk" is a function that takes no arguments and return
10
+ * a value that is potentially expensive to compute.
11
+ * This can be used when the value might not be needed and as
12
+ * such can be computed on demand potentially saving the
13
+ * expensive computation.
14
+ *
15
+ * If the value is not expensive to compute it can be used directly
16
+ * for simplicity.
17
+ *
18
+ * A value type that is itself a function cannot be a "maybe" thunk.
19
+ *
20
+ * @see https://en.wikipedia.org/wiki/Thunk
21
+ */
22
+ export type MaybeThunk<T> = T extends Function ? never : T | (() => T);
23
+
24
+ /**
25
+ * A value or a thunk for a synchronous or asynchronous value.
26
+ *
27
+ * @see MaybePromise
28
+ * @see MaybeThunk
29
+ */
30
+ export type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;
31
+
32
+ /**
33
+ * Load a value from a possibly thunk argument.
34
+ *
35
+ * If the value is a thunk it is called and the result is returned.
36
+ * Otherwise the value itself is returned.
37
+ *
38
+ * @see MaybeThunk
39
+ */
40
+ export function loadThunkValue<T>(value: MaybeThunk<T>): T {
41
+ return typeof value === 'function' ? value() : value;
42
+ }