├── LICENCE.txt
├── README.md
├── index.d.ts
├── package.json
├── test.ts
├── tsconfig.json
├── types
├── accept-more-things.d.ts
├── callback-functions.d.ts
├── clone-node.d.ts
├── custom-element.d.ts
├── devtools-formatters.d.ts
├── dom-parser.d.ts
├── ecmascript.d.ts
├── element.d.ts
├── event-target.d.ts
├── execcommand.d.ts
├── get-target-ranges.d.ts
├── input-event.d.ts
├── matches.d.ts
├── non-standard-stuff.d.ts
├── offscreen-canvas.d.ts
├── performance-entry-types.d.ts
├── query-selector.d.ts
├── selector-parser.d.ts
├── service-worker.d.ts
├── shadow-root-events.d.ts
├── shared-worker.d.ts
├── tree-walker.d.ts
├── tuple.d.ts
├── typed-array.d.ts
└── webassembly.d.ts
└── worklet
├── animation.d.ts
├── audio.d.ts
├── layout.d.ts
├── paint.d.ts
└── worklet-global.d.ts
/LICENCE.txt:
--------------------------------------------------------------------------------
1 | DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
2 | Version 2, December 2004
3 |
4 | Everyone is permitted to copy and distribute verbatim or modified
5 | copies of this license document, and changing it is allowed as long
6 | as the name is changed.
7 |
8 | DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
9 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
10 |
11 | 0. You just DO WHAT THE FUCK YOU WANT TO.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Better-TypeScript
3 |
4 | This repository contains various TypeScript type definitions to make working with TypeScript more convenient.
5 |
6 | This project goes along with [TypeScript types for new JavaScript](https://github.com/BenjaminAster/TypeScript-types-for-new-JavaScript), which contains TypeScript type definitions for new JavaScript stuff that isn't in TypeScript's standard type definitions. Better-TypeScript depends on [TypeScript types for new JavaScript](https://github.com/BenjaminAster/TypeScript-types-for-new-JavaScript), so it is automatically included if you use Better-TypeScript.
7 |
8 | ---
9 |
10 | NPM: [better-typescript](https://www.npmjs.com/package/better-typescript)
11 |
12 | GitHub: [BenjaminAster/Better-TypeScript](https://github.com/BenjaminAster/Better-TypeScript)
13 |
14 | ---
15 |
16 | Install using npm:
17 |
18 | ```shell
19 | npm i --save better-typescript@latest
20 | ```
21 |
22 | Reference the type definitions directly in your TypeScript/JavaScript files...
23 |
24 | ```javascript
25 | ///
26 | ```
27 |
28 | ...or include them in your `tsconfig.json` or `jsconfig.json`:
29 |
30 | ```jsonc
31 | {
32 | "compilerOptions": {
33 | "types": ["better-typescript"],
34 | },
35 | }
36 | ```
37 |
38 | For [worklets](https://developer.mozilla.org/en-US/docs/Web/API/Worklet), use `better-typescript/worklet/` as the path:
39 | - `better-typescript/worklet/audio` for [audio worklets](https://developer.mozilla.org/en-US/docs/Web/API/AudioWorklet)
40 | - `better-typescript/worklet/paint` for [paint worklets](https://developer.mozilla.org/en-US/docs/Web/API/PaintWorklet)
41 | - `better-typescript/worklet/layout` for [layout worklets](https://github.com/w3c/css-houdini-drafts/blob/main/css-layout-api/EXPLAINER.md)
42 | - `better-typescript/worklet/animation` for [animation worklets](https://github.com/w3c/css-houdini-drafts/blob/main/css-animation-worklet-1/README.md)
43 | ```javascript
44 | ///
45 | ```
46 | ```javascript
47 | ///
48 | ```
49 | ```javascript
50 | ///
51 | ```
52 | ```javascript
53 | ///
54 | ```
55 |
56 | ## Stuff in this repository
57 |
58 | ### `.querySelector()` element parser ([view source](./types/query-selector.d.ts))
59 |
60 | A querySelector parser that parses the CSS selector and automatically returns the interface for the respective element:
61 |
62 | ```typescript
63 | document.querySelector("a#foo.bar") // HTMLAnchorElement
64 | document.querySelector("form.info input[type=radio][name=test]:nth-of-type(even)") // HTMLInputElement
65 | document.querySelector(".math-output mrow ~ munderover[displaystyle=false]") // MathMLElement
66 | document.querySelector("svg#logo > filter:first-of-type feTurbulence:not([type=fractalNoise])") // SVGFETurbulenceElement
67 | element.querySelectorAll(":scope > li:nth-of-type(odd)") // NodeListOf
68 | ```
69 |
70 | If the element type itself cannot be determined, but the element is a descendant of any SVG or MathML element, the element automacially becomes an `SVGElement` or `MathMLElement`, respectively:
71 |
72 | ```typescript
73 | document.querySelector("math.formula .fraction") // MathMLElement
74 | document.querySelector("filter#displacement-filter > .noise") // SVGElement
75 | document.querySelector("body > #logo-svg foreignObject[height] msubsup .power") // MathMLElement
76 | ```
77 |
78 | Just to be clear: This parser is _not_ written in TypeScript, it's written solely in _TypeScript type definitions_ (files ending in `.d.ts`). This works similarly to [HypeScript](https://github.com/ronami/HypeScript).
79 |
80 | ### `.matches()` ([view source](./types/matches.d.ts))
81 |
82 | You can now use `element.matches(selector)` and Better-TypeScript will automatically detect the element and provide you with its type definitions when using it in an if-statement.
83 |
84 | ```typescript
85 | const element = document.querySelector(".foo");
86 |
87 | if (element.matches("img")) {
88 | // `element` has type `HTMLImageElement` in this scope
89 | element.src = "https://bigrat.monster/media/bigrat.png";
90 | } else if (element.matches("dialog[open]")) {
91 | // `element` has type `HTMLDialogElement` in this scope
92 | element.showModal();
93 | } else if (element.matches("body > a#main-link[href]")) {
94 | // `element` has type `HTMLAnchorElement` in this scope
95 | element.href = "https://youtube.be/dQw4w9WgXcQ";
96 | } else if (element.matches(".inputfield")) {
97 | // `element` has type `HTMLTextAreaElement` in this scope
98 | element.value = "Hello world!";
99 | }
100 | ```
101 |
102 | ### Service workers ([view source](./types/service-worker.d.ts))
103 |
104 | Working with service workers with type checking enabled is an awful experience by default as in TypeScript, there is no `ServiceWorker` lib, only a `WebWorker` one. Stuff like `self.registration`, `self.clients` or the `fetch` event aren't available by default because from TypeScript's perspecitve, `self` alywas has the type `WorkerGlobalScope` in workers, not `ServiceWorkerGlobalScope`. The way you could previously get around this is by declaring a variable `const _self = self as unknown as ServiceWorkerGlobalScope;` and then working with this `_self` instead of `self` as the global object. This is very ugly and hacky, so Better-TypeScript simply provides all service worker related stuff out of the box to all files.
105 |
106 | ```typescript
107 | self.addEventListener("fetch", (event) => {
108 | // `event` has type `FetchEvent`
109 | })
110 | ```
111 |
112 | ### Shared workers ([view source](./types/shared-worker.d.ts))
113 |
114 | The same as for service workers also applies to [shared workers](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker). You can now use all shared worker related things out of the box.
115 |
116 | ```typescript
117 | self.addEventListener("connect", (event) => {
118 | // `event` has type `MessageEvent`
119 | })
120 | ```
121 |
122 | ### Tuple ([view source](./types/tuple.d.ts))
123 |
124 | This adds the `Tuple` type to create fixed length arrays:
125 |
126 | ```typescript
127 | // 💩 previos method:
128 | const color: [number, number, number, number] = [255, 0, 0, 255];
129 |
130 | // 😎 with Better-TypeScript:
131 | const color: Tuple = [255, 0, 0, 255];
132 | ```
133 |
134 | ### Accept more things ([view source](./types/accept-more-things.d.ts))
135 |
136 | Many JavaScript functions also accept numbers which then get automatically converted into a string. TypeScript often _just_ accepts strings, so Better-TypeScript adds the ability to call a function with numbers instead of strings.
137 |
138 | ```typescript
139 | window.addEventListener("pointermove", (event) => {
140 | document.documentElement.style.setProperty("--mouse-x", event.clientX); // would be an error without Better-TypeScript
141 | document.documentElement.style.setProperty("--mouse-y", event.clientY);
142 | });
143 | ```
144 |
145 | ```typescript
146 | const searchParams = new URLSearchParams(location.search);
147 | searchParams.set("count", ++count); // would be an error without Better-TypeScript
148 | history.replaceState(null, "", "?" + searchParams.toString());
149 | ```
150 |
151 | Also, for some reason, TypeScript doesn't allow calling [`history.pushState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`history.replaceState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) without the unused second parameter. Better-TypeScript adds support for that:
152 |
153 | ```typescript
154 | history.replaceState({ someState: 4 });
155 | history.pushState({ someOtherState: 42 });
156 | ```
157 |
158 | ### `.cloneNode()` ([view source](./types/clone-node.d.ts))
159 |
160 | When calling `.cloneNode()` on any element or fragment, TypeScript just returns the `Node` type by default which is not very useful. With Better-TypeScript, `.cloneNode()` returns the type of the element that it is called on.
161 |
162 | ```typescript
163 | const anchorTemplate = document.createElement("a");
164 | anchorTemplate.href = "https://example.com";
165 | anchorTemplate.textContent = "example";
166 | const anchorClone = anchorTemplate.cloneNode(true); // has the type `HTMLAnchorElement` instead of just `Node`
167 | ```
168 |
169 | ```typescript
170 | const fragment = document.querySelector("template#foo-template").content;
171 |
172 | for (let i = 0; i < 10; i++) {
173 | const clone = fragment.cloneNode(true); // has the type `DocumentFragment` instead of just `Node`
174 | clone.querySelector("a.destination").href = "https://example.com";
175 | document.body.append(clone);
176 | }
177 | ```
178 |
179 | ### Typed OffscreenCanvas options ([view source](./types/offscreen-canvas.d.ts))
180 |
181 | When getting a specific canvas context (e.g. `"2d"`, `"webgl2"`, ...) from a normal canvas element, TypeScript automatically detects the context type and gives the the second options parameter the right options type.
182 |
183 | ```typescript
184 | const canvas = document.querySelector("canvas");
185 | canvas.getContext("2d", { alpha: false }); // options parameter has type `CanvasRenderingContext2DSettings`
186 | ```
187 |
188 | However, when using an `OffscreenCanvas`, TypeScript does not provide you with these type definitions and gives the options parameter a type of `any` which is not very useful. Better-TypeScript adds the right options interfaces.
189 |
190 | ```typescript
191 | const canvas = new OffscreenCanvas(width, height);
192 | canvas.getContext("2d", { alpha: false }); // the options parameter now has type `OffscreenCanvasRenderingContext2DSettings`
193 | ```
194 |
195 | ### Non-standard stuff ([view source](./types/non-standard-stuff.d.ts))
196 |
197 | This includes various non-standard features that are not part of any specification, e.g. Brave's [`navigator.brave.isBrave()`](https://github.com/brave/brave-browser/issues/8216#issuecomment-590184398), Firefox' `CSSMozDocumentRule` or Chromium & WebKit's [`scrollIntoViewIfNeeded()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded) function. This can also be used for spoofing-resistant browser detection.
198 |
199 | ```typescript
200 | const isBrave = await navigator.brave?.isBrave?.();
201 | ```
202 |
203 | ```typescript
204 | if (Element.prototype.scrollIntoViewIfNeeded) element.scrollIntoViewIfNeeded(true);
205 | else element.scrollIntoView({ block: "center" });
206 | ```
207 |
208 | ```typescript
209 | const isChromium = Boolean(window.chrome || Intl.v8BreakIterator);
210 | ```
211 |
212 | ### `TypedArray`
213 |
214 | This simply provides the `TypedArray` type as a union type alias of all typed arrays (`Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array`, `Float32Array` and `Float64Array`).
215 |
216 | ```typescript
217 | const sendArrayToWASM = (array: TypedArray) => {
218 | const buffer = array.buffer;
219 | // do some magic...
220 | return pointer;
221 | }
222 | ```
223 |
224 | ### `Element` extensions ([view source](./types/element.d.ts))
225 |
226 | When an element just has a type of `Element` and not `HTMLElement`/`SVGElement`/`MathMLElement`, properties such as `.dataset` or `.style` are not available. Better-TypeScript adds them.
227 |
228 | ```typescript
229 | for (const child of document.body.children) {
230 | child.dataset.foo = "bar"; // error without Better-TypeScript because `child` has type `Element`
231 | }
232 | ```
233 |
234 | ### TreeWalker filters ([view source](./types/tree-walker.d.ts))
235 |
236 | When using a `SHOW_ELEMENT`, `SHOW_TEXT` or `SHOW_COMMENT` filter when creating a tree walker, the tree walker just walks over elements, text nodes and comments, respectively. Better-TypeScript provides intelligent typings for these.
237 |
238 | ```typescript
239 | const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
240 | while (walker.nextNode()) {
241 | const currentNode = walker.currentNode; // has type `Text`
242 | }
243 | ```
244 |
245 | ### Callable WebAssembly export functions ([view source](./types/webassembly.d.ts))
246 |
247 | A WebAssembly export can either be a function, a `WebAssembly.Global`, a `WebAssembly.Memory` or a `WebAssembly.Table`. Because TypeScript doesn't know which export has which type, you ironically cannot do anything on an export, not even call it as a function. With Better-TypeScript, an export is function, a `WebAssembly.Global`, a `WebAssembly.Memory` *and* a `WebAssembly.Table` all at the same time, which allows you to finally call function exports.
248 |
249 | ```typescript
250 | const { module, instance } = await WebAssembly.instantiateStreaming(await window.fetch("./test.wasm"));
251 | const result = instance.exports.add(34, 35); // error without Better-TypeScript
252 | ```
253 |
254 | ### `DOMParser` returns right document type ([view source](./types/dom-parser.d.ts))
255 |
256 | Calling `DOMParser.prototype.parseFromString()` returns the generic `Document` interface in pure TypeScript. With Better-TypeScript, it returns `Document` for `"text/html"` and `XMLDocument` for `"application/xhtml+xml"`, `"application/xml"`, `"image/svg+xml"` and `"text/xml"`.
257 |
258 | ```typescript
259 | const doc = new DOMParser().parseFromString(svg, "image/svg+xml"); // has type `XMLDocument`
260 | ```
261 |
262 | ### Bubbling `ShadowRoot` events ([view source](./types/shadow-root-events.d.ts))
263 |
264 | Events of DOM elements inside a `ShadowRoot` bubble and can be listened for by a `ShadowRoot`. Better-TypeScript adds support for these events.
265 |
266 | ```typescript
267 | customElements.define("my-element", class extends HTMLElement {
268 | constructor() {
269 | super();
270 | this.attachShadow({ mode: "open" });
271 | this.shadowRoot.append(template.content.cloneNode(true));
272 |
273 | this.shadowRoot.addEventListener("pointerdown", (event) => {
274 | console.log(event.pointerType); // `event` has type `PointerEvent`
275 | });
276 | }
277 | });
278 | ```
279 |
280 | ### Performance entry types ([view source](./types/performance-entry-types.d.ts))
281 |
282 | When calling [`navigator.performance.getEntriesByType`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/getEntriesByType), Better-TypeScript automatically returns an array of the corresponding performance entry type instead of just the generic `PerformanceEntry`.
283 |
284 | ```typescript
285 | const siteLoadingType = performance.getEntriesByType("navigation")[0]?.type; // error without Bettery-TypeScript
286 | ```
287 |
288 | ### DevTools Custom Object Formatters ([view source](./types/devtools-formatters.d.ts))
289 |
290 | Chromium & Firefox DevTools support a feature called [Custom Object Formatters](https://docs.google.com/document/d/1FTascZXT9cxfetuPRT2eXPQKXui4nWFivUnS_335T3U/preview) that let you customize the appearance and interactivity of objects printed in the JavaScript console (To enable this feature, click `Enable custom formatters` in the DevTools settings of Chromium or Firefox). Better-TypeScript adds type definitions for this feature.
291 |
292 | ```typescript
293 | const recursion = {};
294 | const style = "border: 1px solid red; inline-size: fit-content";
295 | window.devtoolsFormatters = [{
296 | header: (object) => object === recursion ? ["span", { style }, "Hello"] : null,
297 | hasBody: (object) => object === recursion,
298 | body: (object) => ["ol", {}, ["li", {}, "world!"], ["li", {}, ["object", { object }]]],
299 | }];
300 | console.log(recursion);
301 | ```
302 |
303 | ### Event target for `HTMLFieldSetElement` ([view source](./types/event-target.d.ts))
304 |
305 | [`Event.prototype.target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target) is always just [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) by default, which is not very helpful. Better-TypeScript adds support for [`Event.prototype.target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target) and [`Event.prototype.currentTarget`](https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget) for [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement), [`HTMLSelectElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement), [`HTMLSelectMenuElement`](https://open-ui.org/components/selectmenu/) and [`HTMLTextAreaElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement) (always the element itself) as well as [`HTMLFieldSetElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement) (a union type of `HTMLInputElement`, `HTMLSelectElement`, `HTMLSelectMenuElement` and `HTMLTextAreaElement`). This allows you to group multiple form elements (such as [` `](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio)) in one [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) and listen to a change with only a single event listener.
306 |
307 | ```html
308 |
309 | Choose your favorite animal
310 |
311 |
312 | Cat
313 |
314 |
315 |
316 | Dog
317 |
318 |
319 |
320 | Psychrolutes marcidus
321 |
322 |
323 | ```
324 |
325 | ```typescript
326 | let favoriteAnimal: string;
327 | document.querySelector("fieldset#favorite-animal").addEventListener("change", ({ target }) => {
328 | favoriteAnimal = target.value;
329 | });
330 | ```
331 |
332 | ### `InputEvent` interface for `"input"` event types ([view source](./types/input-event.d.ts))
333 |
334 | When the browser fires an [`"input"`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) event, the event _usually_ is an [`InputEvent`](https://developer.mozilla.org/en-US/docs/Web/API/InputEvent). But because there are situations where it just has the generic [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) type (e.g. with an ` `), TypeScript _always_ gives `"input"` events the `Event` interface as its type, which makes working with it very impractical. Better-TypeScript reverts this and makes `"input"` events always have the `InputEvent` type so that you can use its properties (specifically [`data`](https://developer.mozilla.org/docs/Web/API/InputEvent/data), [`dataTransfer`](https://developer.mozilla.org/docs/Web/API/InputEvent/dataTransfer), [`inputType`](https://developer.mozilla.org/docs/Web/API/InputEvent/inputType), [`isComposing`](https://developer.mozilla.org/docs/Web/API/InputEvent/isComposing) and [`getTargetRanges()`](https://developer.mozilla.org/docs/Web/API/InputEvent/getTargetRanges)).
335 |
336 | ```typescript
337 | element.addEventListener("input", (event) => {
338 | // `event` now has type `InputEvent`
339 | console.log(event.inputType);
340 | });
341 | ```
342 |
343 | ### `execCommand` command id enum ([view source](./types/execcommand.d.ts))
344 |
345 | Better-TypeScript adds enum values for the `commandId` parameter of [`document.execCommand()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) so that your editor can autocomplete the string. Keep in mind that the behavior of `execCommand()` is very inconsistent between browsers and there is only an [unofficial draft specification](https://w3c.github.io/editing/docs/execCommand/). MDN even goes as far as marking the function as "deprecated".
346 |
347 | ### Custom element classes ([view source](./types/custom-element.d.ts))
348 |
349 | Better-TypeScript adds type checking for the static attributes and lifecycle callback functions of custom element classes.
350 |
351 | ```typescript
352 | customElements.define("my-element", class extends HTMLElement {
353 | constructor() {
354 | super();
355 | };
356 | connectedCallback() { };
357 | disconnectedCallback() { };
358 | adoptedCallback(oldDocument: Document, newDocument: Document) { };
359 | attributeChangedCallback(name: string, oldValue: string, newValue: string, namespace: string) { };
360 | formAssociatedCallback(form: HTMLFormElement) { };
361 | formDisabledCallback(disabled: boolean) { };
362 | formResetCallback() { };
363 | formStateRestoreCallback(newState: any, mode: string) { };
364 | static observedAttributes: string[] = [];
365 | static disabledFeatures: string[] = [];
366 | static formAssociated: boolean = true;
367 | });
368 | ```
369 |
370 | ### Callback functions ([view source](./types/callback-functions.d.ts))
371 |
372 | [TODO]: add description
373 |
374 | ### ECMAScript stuff ([view source](./types/ecmascript.d.ts))
375 |
376 | #### Symbol keys in `Object.getOwnPropertyDescriptors()`
377 |
378 | For some reason, TypeScript's standard library thinks that [`Object.getOwnPropertyDescriptors()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors) returns just strings as its object keys. Better-TypeScript adds support for symbol keys.
379 |
380 | ```typescript
381 | const logOwnKeys = (object: any) => {
382 | const descriptors = Object.getOwnPropertyDescriptors(object);
383 | for (const key of Reflect.ownKeys(descriptors)) {
384 | console.log(key, descriptors[key]); // error without Better-TypeScript
385 | }
386 | };
387 | ```
388 |
389 | [TODO]: add description for Array::includes & Function::{call, apply, bind}
390 |
391 | ### `.getTargetRanges()`
392 |
393 | [TODO]: add description
394 |
--------------------------------------------------------------------------------
/index.d.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 | ///
4 | ///
5 |
6 | ///
7 |
8 | ///
9 | ///
10 | ///
11 | ///
12 | ///
13 | ///
14 | ///
15 | ///
16 | ///
17 | ///
18 | ///
19 | ///
20 | ///
21 | ///
22 | ///
23 | ///
24 | ///
25 | ///
26 | ///
27 | ///
28 | ///
29 | ///
30 | ///
31 | ///
32 | ///
33 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "better-typescript",
3 | "version": "0.2.4",
4 | "description": "Various TypeScript type definitions to make working with TypeScript more convenient",
5 | "main": "./index.d.ts",
6 | "repository": {
7 | "type": "git",
8 | "url": "git+https://github.com/BenjaminAster/Better-TypeScript.git"
9 | },
10 | "dependencies": {
11 | "new-javascript": ">=0.4.3"
12 | },
13 | "author": "Benjamin Aster",
14 | "license": "WTFPL",
15 | "bugs": {
16 | "url": "https://github.com/BenjaminAster/Better-TypeScript/issues"
17 | },
18 | "homepage": "https://github.com/BenjaminAster/Better-TypeScript#readme"
19 | }
--------------------------------------------------------------------------------
/test.ts:
--------------------------------------------------------------------------------
1 |
2 | // /
3 |
4 | // document.body.style.setProperty("--test", 2);
5 |
6 | // // document.body.textContent = 3;
7 |
8 | // const a = document.querySelector("sdfks > input[type=range].test#hi[no]:hover")
9 | // const b = document.querySelector("svg#logo > filter:first-of-child feTurbulence:not([type=fractalNoise])")
10 |
11 | // /
12 | // /
13 | // /
14 | // /
15 |
16 | ///
17 | // /
18 |
19 | // onfetch
20 |
21 | history.pushState({})
22 |
23 | const ownKeys = (object: any) => {
24 | const descriptors = Object.getOwnPropertyDescriptors(object);
25 | for (const key of Reflect.ownKeys(descriptors)) {
26 | console.log(key, descriptors[key])
27 | }
28 | }
29 |
30 | self.addEventListener("fetch", (event) => {
31 |
32 | });
33 |
34 | customElements.define("a-b", class extends HTMLElement {
35 | constructor() {
36 | super()
37 | };
38 | static formAssociated = true
39 | asdkfasdf = "a"
40 | static disabledFeatures = ["internals"]
41 | connectedCallback() {
42 | return 5
43 | };
44 | adoptedCallback() {
45 |
46 | }
47 | });
48 |
49 | self.onconnect
50 |
51 | self.addEventListener("connect", e => {
52 |
53 | })
54 |
55 | const asdfa = () => 5;
56 | asdfa.apply
57 |
58 | const c = document.querySelector.apply(document, "canvas")
59 |
60 | self.name
61 |
62 | document.execCommand("bold");
63 |
64 | let s = document.getSelection();
65 | s.extend
66 |
67 | document.body.addEventListener("input", function (event) {
68 | event.inputType
69 | this
70 | })
71 |
72 | document.addEventListener("input", event => { })
73 |
74 | const input = document.createElement("input");
75 | input.type = "text";
76 | input.addEventListener("input", ({ target }) => {
77 | target.value;
78 | })
79 |
80 |
81 | // self.addEventListener("fetch", (event) => {
82 |
83 | // });
84 |
85 | const $ = document.querySelector.bind(document);
86 |
87 | const dialog = $("dialog[open]");
88 |
89 | const asdfkjdf = Document.prototype.querySelector.call(document, "body.a");
90 | const asdfkjdf2 = document.querySelector("body.a");
91 |
92 | const a: Tuple = [3, 4, 5];
93 |
94 | const element1 = document.querySelector("alskdfj a");
95 | element1.querySelectorAll(":scope > li:nth-of-type(odd)")
96 |
97 | window.SpeechRecognitionResult
98 |
99 | const element = document.querySelector(".foo");
100 |
101 | if (element.matches("img")) {
102 | element.src = "https://bigrat.monster/media/bigrat.png";
103 | } else if (element.matches("dialog[open]")) {
104 | element.showModal();
105 | } else if (element.matches("body > a#main-link[href]")) {
106 | element.href = "https://youtube.be/dQw4w9WgXcQ";
107 | } else if (element.matches(".inputfield")) {
108 | element.value = "Hello world!";
109 | }
110 |
111 | //////////////
112 |
113 | declare const noice: Element;
114 |
115 | if (noice.matches("a")) {
116 | noice;
117 |
118 | if (noice.matches("[href]")) {
119 | noice;
120 | } else {
121 | noice.href = "";
122 | }
123 | } else {
124 | noice;
125 | }
126 |
127 | if (noice.matches("a[disabled]")) {
128 | noice;
129 | } else {
130 | noice;
131 | }
132 |
133 |
134 | const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ATTRIBUTE);
135 |
136 | walker.nextNode();
137 | walker.root;
138 |
139 |
140 | const walker2 = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
141 | while (walker2.nextNode()) {
142 | const currentNode = walker2.currentNode // `currentNode` now has type `Text`
143 | }
144 |
145 | document.body.textContent
146 |
147 | const asdg = JSON.parse("sldkfjsldaf")
148 |
149 | const parseFromString = DOMParser.prototype.parseFromString.bind(new DOMParser());
150 | const parseHTML = Range.prototype.createContextualFragment.bind(new Range());
151 |
152 | declare const test: HTMLAnchorElement;
153 |
154 | if (test.matches("div")) {
155 | test
156 | } else {
157 | test
158 | }
159 |
160 | const template = document.querySelector("template#my-element-template");
161 |
162 | customElements.define("my-element", class extends HTMLElement {
163 | constructor() {
164 | super();
165 | this.attachShadow({ mode: "open" });
166 | this.shadowRoot.append(template.content.cloneNode(true));
167 |
168 | this.shadowRoot.addEventListener("pointerdown", (event) => {
169 | console.log(event.pointerType); // `event` has type `PointerEvent`
170 | });
171 | }
172 | });
173 |
174 |
175 | type HypertextNode = string | [string, { [key: string]: any }, ...HypertextNode[]];
176 |
177 | const hypertextNode: HypertextNode =
178 | ["div", { id: "parent" },
179 | ["div", { id: "first-child" }, "I'm the first child"],
180 | ["div", { id: "second-child" }, "I'm the second child"]
181 | ];
182 |
183 |
184 | const { module, instance } = await WebAssembly.instantiateStreaming(await fetch("./test.wasm"));
185 |
186 | document.documentElement.addEventListener("drop", (event) => {
187 | const items = event.dataTransfer.items;
188 | const [item] = items;
189 | })
190 |
191 | var custom = {};
192 |
193 | var formatter = {
194 | header: function (x) {
195 | if (x === custom) {
196 | return ["span", { "style": "background-color: #fcc" }, "Hello!"] as const;
197 | } else {
198 | return null;
199 | }
200 | },
201 | hasBody: function (x) {
202 | return x === custom;
203 | },
204 | body: function (x) {
205 | var selfRef = ["object", { "object": custom }] as const;
206 | return ["ol", {}, ["li", {}, "world!"], ["li", {}, selfRef]] as const;
207 | }
208 | };
209 |
210 | window.devtoolsFormatters = [formatter];
211 |
212 |
213 | let recursion = {};
214 | window.devtoolsFormatters = [{
215 | header: (object) => object === recursion ? ["span", { style: "border: 1px solid #888" }, "Hello!"] : null,
216 | hasBody: Boolean,
217 | body: (object) => ["ol", {}, ["li", {}, "world!"], ["li", {}, ["object", { object }]]],
218 | }];
219 | console.log(recursion);
220 |
221 |
222 |
223 |
224 | const sgdjh = instance.exports.abc(3, 6, 7);
225 | const sgdjht = instance.exports.myGlobal.value;
226 | const sgdjsdfht = instance.exports.myMemory.buffer;
227 | const sgasdfdjht = instance.exports.myTable.set;
228 |
229 | document.caretRangeFromPoint
230 | document.caretPositionFromPoint
231 |
232 | document.elementFromPoint
233 | document.elementsFromPoint
234 | document.scrollingElement
235 |
236 | CaretPosition
237 |
238 | new DOMParser().parseFromString("asdf", "application/xhtml+xml");
239 | new DOMParser().parseFromString("asdf", "application/xml");
240 | new DOMParser().parseFromString("asdf", "image/svg+xml");
241 | new DOMParser().parseFromString("asdf", "text/html");
242 | new DOMParser().parseFromString("asdf", "text/xml");
243 |
244 | const test20 = document.querySelector("q.c[a]:p.c[a]");
245 | const test21 = document.querySelector("q[a]#i#i:p.c");
246 | const test22 = document.querySelector("q#i.c[a][a]");
247 | const test23 = document.querySelector("q:p#i:p#i");
248 | const test24 = document.querySelector("q");
249 | const test25 = document.querySelector("q.c");
250 | const test26 = document.querySelector("q.c#i");
251 | const test27 = document.querySelector("q#i.c");
252 | const test28 = document.querySelector("math#i.c");
253 | const test29 = document.querySelector("munderover.c#i");
254 |
255 | const test1 = document.querySelector("html body > div ~ a * + portal.basdf.asdfasdf:has(b)");
256 | const test2 = document.querySelector("b:hover");
257 | const test3 = document.querySelector("ul[class^=a].b");
258 | const test4 = document.querySelector("div#no");
259 | const test5 = document.querySelector("input.basdf.asdfasdf");
260 | const test6 = document.querySelector("canvas.basdf.asdfasdf");
261 | const test7 = document.querySelector("body.basdf.asdfasdf");
262 | const test8 = document.querySelector("x.b:hover");
263 | const test9 = document.querySelector(":scope > input[type=radio][name=test].aa:nth-of-type(even)");
264 |
265 | const test10 = document.querySelector(":scope > .foo [viewBox] foreignObject[xmlns] munderover.sum .fraction [href] .foo[displaystyle]");
266 | const test11 = document.querySelector(":scope > .foo [viewBox] foreignObject[xmlns] .fraction");
267 | const test12 = document.querySelector(":scope > .foo [vviewBox] .ffvoreignObject[xmlns] .fraction");
268 | const test13 = document.querySelector(":scope > .foo");
269 | const test14 = document.querySelector(".bar");
270 | const test15 = document.querySelector(".bar .baz");
271 | const test16 = document.querySelector("filter .noise");
272 | document.querySelector(":scope > #logo-svg msubsup")
273 | document.querySelector("math .fraction") // MathMLElement
274 | document.querySelector("filter > .noise") // SVGElement
275 | document.querySelector(":scope > #logo-svg foreignObject msubsup .power") // MathMLElement
276 |
277 | const test30 = document.querySelector("a.askdjf.lsdjf")
278 | const test31 = document.querySelector("portal:hover")
279 | const test32 = document.querySelector("a.b:hover")
280 | const test33 = document.querySelector("html body > div ~ a * + portal.basdf.asdfasdf:has(b)")
281 | const test34 = document.querySelector("body a")
282 | const test35 = document.querySelector("a .test")
283 | const test36 = document.querySelector("input[type=range] ~ .text")
284 | const test37 = document.querySelector("input[type=range] .text")
285 | const test38 = document.querySelector("input .text")
286 | const test39 = document.querySelector("b .test")
287 |
288 | document.querySelector(".parameter-chooser > label > input[type=radio][name=parameter] ~ .text");
289 |
290 | let kasdf: BetterTypeScript.SelectorContainsSVGOrMathMLElement<"a math svg munderover.a img[src]">;
291 | let kasdfsdf: BetterTypeScript.GetElementTypeFromSimpleSelector<".bar">;
292 | let kasdfsdsdf: BetterTypeScript.SelectorContainsSVGOrMathMLElement<".bar .baz">;
293 |
294 | let alskdfl: BetterTypeScript.SelectorStringContainingElementName = "alsdjfl.a a.b laksdfj";
295 |
296 | type asdf = BetterTypeScript.SelectorContainsSVGOrMathMLElement<"span .test", BetterTypeScript.ElementNamespace.SVG>
297 | type asd3f = BetterTypeScript.SelectorContainsSVGOrMathMLElement<"span .test">
298 | type asdfdfds = BetterTypeScript.GetElementTypeFromSimpleSelector<"span">
299 | type asdfdfdssdf = HTMLSpanElement extends MathMLElement ? 1 : 0;
300 | type asdfdfdssdfsd = HTMLInputElement extends MathMLElement ? 1 : 0;
301 | type asdfdfdssdf4 = MathMLElement extends HTMLSpanElement ? 1 : 0;
302 | type asdfdfdssdf4sdf = MathMLElement["constructor"]["name"];
303 |
304 |
305 | const string = Object.prototype.toString.apply({})
306 |
307 | // OffscreenCanvas
308 |
309 | // const element = document.querySelector("b");
310 | // // const element = document.querySelector("a");
311 |
312 | // if (element instanceof HTMLAnchorElement) {
313 | // element.href
314 | // } else if (element instanceof HTMLInputElement) {
315 | // element.value
316 | // }
317 |
318 | // if (element.matches("a")) {
319 | // element.href;
320 | // }
321 |
322 | // // const _self = self as unknown as ServiceWorkerGlobalScope;
323 |
324 | // window.addEventListener("pointermove", (event) => {
325 | // document.documentElement.style.setProperty("--mouse-x", event.clientX);
326 | // document.documentElement.style.setProperty("--mouse-y", event.clientY);
327 | // });
328 |
329 |
330 | // const anchorTemplate = document.createElement("a");
331 | // anchorTemplate.href = "https://example.com";
332 | // anchorTemplate.textContent = "example";
333 | // const anchorClone = anchorTemplate.cloneNode(true);
334 |
335 | // importScripts("s")
336 | // document
337 |
338 | // const fragment = document.querySelector("template#foo-template").content;
339 |
340 | // for (let i = 0; i < 10; i++) {
341 | // const clone = fragment.cloneNode(true); // `clone` now has the type `DocumentFragment` instead of just `Node`
342 | // clone.querySelector("a.destination").href = "https://example.com";
343 | // document.body.append(clone);
344 | // }
345 |
346 | // const c = new OffscreenCanvas(1, 1);
347 |
348 | // const ctx = c.getContext("2d", { alpha: true });
349 |
350 |
351 | export { };
352 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "ESNext",
4 | "target": "ESNext",
5 | "noEmit": true,
6 | "strict": false,
7 | "lib": ["ESNext", "DOM", "DOM.Iterable"],
8 | "types": ["new-javascript"],
9 | },
10 | }
--------------------------------------------------------------------------------
/types/accept-more-things.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface CSSStyleDeclaration {
3 | setProperty(property: string, value: string | number | null, priority?: string): void;
4 | }
5 |
6 | interface URLSearchParams {
7 | append(name: string, value: string | number): void;
8 | set(name: string, value: string | number): void;
9 | }
10 |
11 | interface Element {
12 | setAttribute(qualifiedName: string, value: string | number | boolean): void;
13 | }
14 |
15 | interface History {
16 | pushState(data: any): void;
17 | replaceState(data: any): void;
18 | }
19 |
--------------------------------------------------------------------------------
/types/callback-functions.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface WindowOrWorkerGlobalScope {
3 | queueMicrotask(callback: Function): any;
4 | }
5 |
6 | declare function queueMicrotask(callback: Function): any;
7 |
--------------------------------------------------------------------------------
/types/clone-node.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface Node extends EventTarget {
3 | cloneNode(deep?: boolean): this;
4 | }
5 |
--------------------------------------------------------------------------------
/types/custom-element.d.ts:
--------------------------------------------------------------------------------
1 |
2 | declare namespace BetterTypeScript {
3 | interface CustomElement extends HTMLElement {
4 | connectedCallback?: () => any;
5 | disconnectedCallback?: () => any;
6 | adoptedCallback?: (oldDocument: Document, newDocument: Document) => any;
7 | attributeChangedCallback?: (name: string, oldValue: string, newValue: string, namespace: string) => any;
8 | formAssociatedCallback?: (form: HTMLFormElement) => any;
9 | formDisabledCallback?: (disabled: boolean) => any;
10 | formResetCallback?: () => any;
11 | formStateRestoreCallback?: (newState: any, mode: string) => any;
12 | }
13 | }
14 |
15 | interface CustomElementConstructor {
16 | observedAttributes?: string[];
17 | disabledFeatures?: string[];
18 | formAssociated?: boolean;
19 | new(...params: any[]): BetterTypeScript.CustomElement;
20 | }
21 |
--------------------------------------------------------------------------------
/types/devtools-formatters.d.ts:
--------------------------------------------------------------------------------
1 |
2 | // See https://docs.google.com/document/d/1FTascZXT9cxfetuPRT2eXPQKXui4nWFivUnS_335T3U/preview
3 |
4 | declare namespace BetterTypeScript {
5 | type DevtoolsFormatterObjectConfig = Record;
6 |
7 | type DevtoolsFormatterElementTagName = (
8 | | "div"
9 | | "span"
10 | | "ol"
11 | | "li"
12 | | "table"
13 | | "tr"
14 | | "td"
15 | );
16 |
17 | type DevtoolsFormatterElementTemplate = (
18 | | DevtoolsFormatterStyledElementTemplate
19 | | DevtoolsFormatterUnstyledElementTemplate
20 | );
21 |
22 | type DevtoolsFormatterStyledElementTemplate = readonly [
23 | BetterTypeScript.DevtoolsFormatterElementTagName,
24 | {
25 | style?: string,
26 | },
27 | ...BetterTypeScript.DevtoolsFormatterItem[],
28 | ];
29 |
30 | type DevtoolsFormatterUnstyledElementTemplate = readonly [
31 | BetterTypeScript.DevtoolsFormatterElementTagName,
32 | ...BetterTypeScript.DevtoolsFormatterItem[],
33 | ];
34 |
35 | type DevtoolsFormatterObjectReference = readonly [
36 | "object",
37 | {
38 | object: any,
39 | config?: BetterTypeScript.DevtoolsFormatterObjectConfig,
40 | },
41 | ];
42 |
43 | type DevtoolsFormatterItem = (
44 | | string
45 | | BetterTypeScript.DevtoolsFormatterElementTemplate
46 | | BetterTypeScript.DevtoolsFormatterObjectReference
47 | );
48 |
49 | interface DevtoolsFormatter {
50 | header(object?: any, config?: BetterTypeScript.DevtoolsFormatterObjectConfig): BetterTypeScript.DevtoolsFormatterItem | null;
51 | hasBody(object?: any, config?: BetterTypeScript.DevtoolsFormatterObjectConfig): boolean;
52 | body(object?: any, config?: BetterTypeScript.DevtoolsFormatterObjectConfig): BetterTypeScript.DevtoolsFormatterItem;
53 | }
54 | }
55 |
56 | declare var devtoolsFormatters: BetterTypeScript.DevtoolsFormatter[];
57 |
--------------------------------------------------------------------------------
/types/dom-parser.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface DOMParser {
3 | parseFromString(string: string, type: "text/html"): Document;
4 | parseFromString(string: string, type: "application/xml"): XMLDocument;
5 | parseFromString(string: string, type: "image/svg+xml"): XMLDocument;
6 |
7 | /** @deprecated Use type `"application/xml"` instead */
8 | parseFromString(string: string, type: "text/xml"): XMLDocument;
9 | /** @deprecated Use type `"application/xml"` instead */
10 | parseFromString(string: string, type: "application/xhtml+xml"): XMLDocument;
11 | }
12 |
--------------------------------------------------------------------------------
/types/ecmascript.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface ObjectConstructor {
3 | getOwnPropertyDescriptors(o: T): { [P in keyof T]: TypedPropertyDescriptor; } & { [x: string | symbol]: PropertyDescriptor; };
4 | }
5 |
6 | interface Array {
7 | includes(searchElement: any, fromIndex?: number): boolean;
8 | }
9 |
10 | interface Function {
11 | apply(this: (this: T) => R, thisArg: T): R;
12 | apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R;
13 | call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R;
14 | bind(this: (this: T, ...args: [...A, ...B]) => R, thisArg: T, ...args: A): (...args: B) => R;
15 | bind(this: T, thisArg: ThisParameterType): OmitThisParameter;
16 | }
17 |
--------------------------------------------------------------------------------
/types/element.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface Element extends HTMLOrSVGElement, GlobalEventHandlers {
3 | readonly style: CSSStyleDeclaration;
4 | hidden: boolean;
5 | }
6 |
--------------------------------------------------------------------------------
/types/event-target.d.ts:
--------------------------------------------------------------------------------
1 |
2 | declare namespace BetterTypeScript {
3 | interface EventWithTargets extends Event {
4 | target: Target;
5 | currentTarget: CurrentTarget;
6 | }
7 |
8 | interface InputEventWithTargets extends InputEvent {
9 | target: Target;
10 | currentTarget: CurrentTarget;
11 | }
12 | }
13 |
14 | interface Element {
15 | addEventListener(type: "change", listener: (this: Element, ev: BetterTypeScript.EventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
16 | addEventListener(type: "input", listener: (this: Element, ev: BetterTypeScript.InputEventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
17 | }
18 |
19 | interface HTMLElement {
20 | addEventListener(type: "change", listener: (this: HTMLElement, ev: BetterTypeScript.EventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
21 | addEventListener(type: "input", listener: (this: HTMLElement, ev: BetterTypeScript.InputEventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
22 | }
23 |
24 | interface HTMLFieldSetElement {
25 | addEventListener(type: "change", listener: (this: HTMLFieldSetElement, ev: BetterTypeScript.EventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
26 | addEventListener(type: "input", listener: (this: HTMLFieldSetElement, ev: BetterTypeScript.InputEventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
27 | }
28 |
29 | interface HTMLInputElement {
30 | addEventListener(type: "change", listener: (this: HTMLInputElement, ev: BetterTypeScript.EventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
31 | addEventListener(type: "input", listener: (this: HTMLInputElement, ev: BetterTypeScript.InputEventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
32 | }
33 |
34 | interface HTMLSelectElement {
35 | addEventListener(type: "change", listener: (this: HTMLSelectElement, ev: BetterTypeScript.EventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
36 | addEventListener(type: "input", listener: (this: HTMLSelectElement, ev: BetterTypeScript.InputEventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
37 | }
38 |
39 | interface HTMLSelectListElement {
40 | addEventListener(type: "change", listener: (this: HTMLSelectListElement, ev: BetterTypeScript.EventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
41 | addEventListener(type: "input", listener: (this: HTMLSelectListElement, ev: BetterTypeScript.InputEventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
42 | }
43 |
44 | interface HTMLTextAreaElement {
45 | addEventListener(type: "change", listener: (this: HTMLTextAreaElement, ev: BetterTypeScript.EventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
46 | addEventListener(type: "input", listener: (this: HTMLTextAreaElement, ev: BetterTypeScript.InputEventWithTargets) => any, options?: boolean | AddEventListenerOptions): void;
47 | }
48 |
--------------------------------------------------------------------------------
/types/execcommand.d.ts:
--------------------------------------------------------------------------------
1 |
2 | type ExecCommandCommandId = (
3 | // https://w3c.github.io/editing/docs/execCommand/
4 | | "backColor"
5 | | "bold"
6 | | "createLink"
7 | | "fontName"
8 | | "fontSize"
9 | | "foreColor"
10 | | "hiliteColor"
11 | | "italic"
12 | | "removeFormat"
13 | | "strikethrough"
14 | | "subscript"
15 | | "superscript"
16 | | "underline"
17 | | "unlink"
18 | | "delete"
19 | | "formatBlock"
20 | | "forwardDelete"
21 | | "indent"
22 | | "insertHorizontalRule"
23 | | "insertHTML"
24 | | "insertImage"
25 | | "insertLineBreak"
26 | | "insertOrderedList"
27 | | "insertParagraph"
28 | | "insertText"
29 | | "insertUnorderedList"
30 | | "justifyCenter"
31 | | "justifyFull"
32 | | "justifyLeft"
33 | | "justifyRight"
34 | | "outdent"
35 | | "copy"
36 | | "cut"
37 | | "paste"
38 | | "defaultParagraphSeparator"
39 | | "redo"
40 | | "selectAll"
41 | | "styleWithCSS"
42 | | "undo"
43 | | "useCSS"
44 |
45 | // https://w3c.github.io/editing/docs/execCommand/#h-note
46 | | "decreaseFontSize"
47 | | "increaseFontSize"
48 | | "contentReadOnly"
49 | | "enableInlineTableEditing"
50 | | "enableObjectResizing"
51 | | "heading"
52 | | "insertBrOnReturn"
53 | | "readOnly"
54 | | "2D-Position"
55 | | "absolutePosition"
56 | | "clearAuthenticationCache"
57 | | "createBookmark"
58 | | "insertButton"
59 | | "insertFieldset"
60 | | "insertIframe"
61 | | "insertInput"
62 | | "insertMarquee"
63 | | "insertSelectDropdown"
64 | | "insertSelectListbox"
65 | | "insertTextarea"
66 | | "liveResize"
67 | | "multipleSelection"
68 | | "overwrite"
69 | | "print"
70 | | "refresh"
71 | | "saveAs"
72 | | "unbookmark"
73 | | "findString"
74 | | "fontSizeDelta"
75 | | "insertNewlineInQuotedContent"
76 | | "justifyNone"
77 | | "transpose"
78 | | "unselect"
79 | );
80 |
81 | interface Document {
82 | execCommand(commandId: ExecCommandCommandId, showUI?: boolean, value?: string): boolean;
83 | }
84 |
--------------------------------------------------------------------------------
/types/get-target-ranges.d.ts:
--------------------------------------------------------------------------------
1 |
2 | declare namespace BetterTypeScript {
3 | interface AbstractRange {
4 | readonly collapsed: boolean;
5 | readonly endContainer: Text;
6 | readonly endOffset: number;
7 | readonly startContainer: Text;
8 | readonly startOffset: number;
9 | }
10 |
11 | interface StaticRange extends BetterTypeScript.AbstractRange {
12 | }
13 | }
14 |
15 | interface InputEvent extends UIEvent {
16 | getTargetRanges(): BetterTypeScript.StaticRange[];
17 | }
18 |
--------------------------------------------------------------------------------
/types/input-event.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface HTMLElement {
3 | addEventListener(type: "input", listener: (this: HTMLElement, ev: InputEvent) => any, options?: boolean | AddEventListenerOptions): void;
4 | removeEventListener(type: "input", listener: (this: HTMLElement, ev: InputEvent) => any, options?: boolean | EventListenerOptions): void;
5 | }
6 |
7 | interface HTMLTextAreaElement {
8 | addEventListener(type: "input", listener: (this: HTMLTextAreaElement, ev: InputEvent) => any, options?: boolean | AddEventListenerOptions): void;
9 | removeEventListener(type: "input", listener: (this: HTMLTextAreaElement, ev: InputEvent) => any, options?: boolean | EventListenerOptions): void;
10 | }
11 |
12 | interface HTMLInputElement {
13 | addEventListener(type: "input", listener: (this: HTMLInputElement, ev: InputEvent) => any, options?: boolean | AddEventListenerOptions): void;
14 | removeEventListener(type: "input", listener: (this: HTMLInputElement, ev: InputEvent) => any, options?: boolean | EventListenerOptions): void;
15 | }
16 |
17 | interface Document {
18 | addEventListener(type: "input", listener: (this: Document, ev: InputEvent) => any, options?: boolean | AddEventListenerOptions): void;
19 | removeEventListener(type: "input", listener: (this: Document, ev: InputEvent) => any, options?: boolean | EventListenerOptions): void;
20 | }
21 |
22 | interface Window {
23 | addEventListener(type: "input", listener: (this: Window, ev: InputEvent) => any, options?: boolean | AddEventListenerOptions): void;
24 | removeEventListener(type: "input", listener: (this: Window, ev: InputEvent) => any, options?: boolean | EventListenerOptions): void;
25 | }
26 |
--------------------------------------------------------------------------------
/types/matches.d.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 |
4 | interface Element {
5 | matches(selectors: K): this is BetterTypeScript.GetElementTypeFromSelector;
6 | matches(selectors: string): boolean;
7 | matches(selectors: string): this is E;
8 | }
9 |
--------------------------------------------------------------------------------
/types/non-standard-stuff.d.ts:
--------------------------------------------------------------------------------
1 |
2 | // Various non-standard features that are not part of any specification
3 |
4 | // Chromium, Firefox & WebKit:
5 |
6 | interface Screen {
7 | availLeft: number;
8 | availTop: number;
9 | }
10 |
11 | // Chromium:
12 |
13 | declare namespace chrome {
14 | var app: any;
15 | function csi(): {
16 | onloadT: DOMHighResTimeStamp,
17 | pageT: DOMHighResTimeStamp,
18 | startE: DOMHighResTimeStamp,
19 | tran: number,
20 | };
21 | function loadTimes(): {
22 | commitLoadTime: DOMHighResTimeStamp,
23 | connectionInfo: string,
24 | finishDocumentLoadTime: DOMHighResTimeStamp,
25 | finishLoadTime: DOMHighResTimeStamp,
26 | firstPaintAfterLoadTime: DOMHighResTimeStamp,
27 | firstPaintTime: DOMHighResTimeStamp,
28 | navigationType: string,
29 | npnNegotiatedProtocol: string,
30 | requestTime: DOMHighResTimeStamp,
31 | startLoadTime: DOMHighResTimeStamp,
32 | wasAlternateProtocolAvailable: boolean,
33 | wasFetchedViaSpdy: boolean,
34 | wasNpnNegotiated: boolean,
35 | };
36 | }
37 |
38 | declare namespace Intl {
39 | type v8BreakIteratorType = (
40 | | "character"
41 | | "word"
42 | | "sentence"
43 | | "line"
44 | );
45 |
46 | type v8BreakIteratorBreakType = (
47 | | "none"
48 | | "number"
49 | | "letter"
50 | | "kana"
51 | | "ideo"
52 | | "unknown"
53 | );
54 |
55 | interface v8BreakIteratorOptions {
56 | type: Intl.v8BreakIteratorType;
57 | }
58 |
59 | interface Resolvedv8BreakIteratorOptions {
60 | locale: string;
61 | type: Intl.v8BreakIteratorType;
62 | }
63 |
64 | interface v8BreakIterator {
65 | first(): number;
66 | next(): number;
67 | current(): number;
68 | adoptText(text: string): void;
69 | breakType(): Intl.v8BreakIteratorBreakType;
70 | resolvedOptions(): Intl.Resolvedv8BreakIteratorOptions;
71 | }
72 |
73 | const v8BreakIterator: {
74 | new(locales?: string | string[], options?: Intl.v8BreakIteratorOptions): Intl.v8BreakIterator;
75 | supportedLocalesOf(locales: string | string[]): string[];
76 | };
77 | }
78 |
79 | interface Performance {
80 | readonly memory: MemoryInfo;
81 | }
82 |
83 | interface MemoryInfo {
84 | readonly jsHeapSizeLimit: number;
85 | readonly totalJSHeapSize: number;
86 | readonly usedJSHeapSize: number;
87 | }
88 |
89 | interface GPUAdapterInfo {
90 | readonly driver: string;
91 | }
92 |
93 | // Storage Pressure Event (https://github.com/jarryd999/storage-pressure-event):
94 |
95 | interface StorageManagerEventMap {
96 | "quotachange": Event;
97 | }
98 |
99 | interface StorageManager extends EventTarget {
100 | onquotachange: ((this: StorageManager, ev: Event) => any) | null;
101 | addEventListener(type: K, listener: (this: StorageManager, ev: StorageManagerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
102 | addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
103 | removeEventListener(type: K, listener: (this: StorageManager, ev: StorageManagerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
104 | removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
105 | }
106 |
107 | // Chromium & WebKit:
108 |
109 | interface Element {
110 | scrollIntoViewIfNeeded(centerIfNeeded: boolean): void;
111 | }
112 |
113 | declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number;
114 | declare function webkitCancelAnimationFrame(handle: number): void;
115 |
116 | // WebKit:
117 |
118 | // https://github.com/WebKit/WebKit/tree/main/Source/WebCore/Modules/applepay
119 | declare var ApplePayAutomaticReloadPaymentRequest: any;
120 | declare var ApplePayCancelEvent: any;
121 | declare var ApplePayContactField: any;
122 | declare var ApplePayCouponCodeChangedEvent: any;
123 | declare var ApplePayCouponCodeDetails: any;
124 | declare var ApplePayCouponCodeUpdate: any;
125 | declare var ApplePayDateComponents: any;
126 | declare var ApplePayDateComponentsRange: any;
127 | declare var ApplePayDeferredPaymentRequest: any;
128 | declare var ApplePayDetailsUpdateBase: any;
129 | declare var ApplePayError: any;
130 | declare var ApplePayErrorCode: any;
131 | declare var ApplePayErrorContactField: any;
132 | declare var ApplePayFeature: any;
133 | declare var ApplePayInstallmentConfiguration: any;
134 | declare var ApplePayInstallmentItem: any;
135 | declare var ApplePayInstallmentItemType: any;
136 | declare var ApplePayInstallmentRetailChannel: any;
137 | declare var ApplePayLaterAvailability: any;
138 | declare var ApplePayLineItem: any;
139 | declare var ApplePayMerchantCapability: any;
140 | declare var ApplePayPayment: any;
141 | declare var ApplePayPaymentAuthorizationResult: any;
142 | declare var ApplePayPaymentAuthorizedEvent: any;
143 | declare var ApplePayPaymentContact: any;
144 | declare var ApplePayPaymentMethod: any;
145 | declare var ApplePayPaymentMethodSelectedEvent: any;
146 | declare var ApplePayPaymentMethodType: any;
147 | declare var ApplePayPaymentMethodUpdate: any;
148 | declare var ApplePayPaymentOrderDetails: any;
149 | declare var ApplePayPaymentPass: any;
150 | declare var ApplePayPaymentRequest: any;
151 | declare var ApplePayPaymentTiming: any;
152 | declare var ApplePayPaymentTokenContext: any;
153 | declare var ApplePayRecurringPaymentDateUnit: any;
154 | declare var ApplePayRecurringPaymentRequest: any;
155 | declare var ApplePayRequestBase: any;
156 | declare var ApplePaySession: any;
157 | declare var ApplePaySessionError: any;
158 | declare var ApplePaySetup: any;
159 | declare var ApplePaySetupConfiguration: any;
160 | declare var ApplePaySetupFeature: any;
161 | declare var ApplePaySetupFeatureState: any;
162 | declare var ApplePaySetupFeatureType: any;
163 | declare var ApplePayShippingContactEditingMode: any;
164 | declare var ApplePayShippingContactSelectedEvent: any;
165 | declare var ApplePayShippingContactUpdate: any;
166 | declare var ApplePayShippingMethod: any;
167 | declare var ApplePayShippingMethodSelectedEvent: any;
168 | declare var ApplePayShippingMethodUpdate: any;
169 | declare var ApplePayValidateMerchantEvent: any;
170 |
171 | interface Navigator {
172 | readonly standalone: boolean;
173 | }
174 |
175 | // Brave:
176 |
177 | interface Brave {
178 | isBrave(): Promise;
179 | }
180 |
181 | declare var Brave: {
182 | prototype: Brave;
183 | };
184 |
185 | interface Navigator {
186 | brave: Brave;
187 | }
188 |
189 | // Opera:
190 |
191 | declare var g_opr: {
192 | scrap(): void;
193 | };
194 |
195 | declare var isOpera: boolean;
196 |
197 | // Ulaa:
198 |
199 | declare var ulaa: {
200 | getVersion(): string;
201 | };
202 |
203 | // Samsung Internet:
204 |
205 | declare var News: {
206 | isHomepageNewsFeed(...args: any[]): any;
207 | setHomepageAsNewsFeed(...args: any[]): any;
208 | };
209 |
210 | declare var QuickAccess: {
211 | deleteItems(...args: any[]): any;
212 | enterEditMode(...args: any[]): any;
213 | enterPrivacyBoard(...args: any[]): any;
214 | getItems(...args: any[]): any;
215 | getPrivacyDashboardData(...args: any[]): any;
216 | isNightModeEnabled(...args: any[]): any;
217 | isPrivacyBoardEnabled(...args: any[]): any;
218 | isRefererCleanerEnabled(...args: any[]): any;
219 | isSecretMode(...args: any[]): any;
220 | isSetAsHomePage(...args: any[]): any;
221 | requestPrivacyDashbordData(...args: any[]): any;
222 | sendSILog(...args: any[]): any;
223 | showAddDialog(...args: any[]): any;
224 | showQuickAccessSettings(...args: any[]): any;
225 | showRenameDialog(...args: any[]): any;
226 | turnOnPrivacyFeature(...args: any[]): any;
227 | };
228 |
229 | // DuckDuckGo Android:
230 |
231 | declare var AutoconsentAndroid: any;
232 | declare var BlobConverter: any;
233 | declare var BrowserAutofill: any;
234 | declare var EmailInterface: any;
235 | declare var LoginDetection: any;
236 | declare var Print: any;
237 |
238 | // DuckDuckGo Desktop:
239 |
240 | declare function gc(): void;
241 |
242 | interface Navigator {
243 | readonly duckduckgo: {
244 | isDuckDuckGo(): Promise;
245 | readonly platform: string;
246 | readonly taintedOrigins: Set;
247 | readonly taints: Set;
248 | };
249 | }
250 |
251 | // Microsoft Edge:
252 |
253 | interface SpeechSynthesis {
254 | preload(arg1: any, arg2: any[]): void;
255 | }
256 |
257 | interface HTMLVideoElement {
258 | readonly msVideoProcessing: string;
259 | msGetVideoProcessingTypes(): string[];
260 | }
261 |
262 | type MicrosoftHostEnvironmentValueName = (
263 | | "os-architecture"
264 | | "os-build"
265 | | "os-mode"
266 | | "os-sku"
267 | );
268 |
269 | interface External {
270 | // https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/mt795399(v=vs.85)
271 | getHostEnvironmentValue(name: MicrosoftHostEnvironmentValueName): string | null;
272 | }
273 |
274 | declare var videoAdsBlockerNativeHandler: {
275 | logBlockSuccess: any
276 | };
277 |
278 | // Vivaldi:
279 |
280 | interface DataTransfer {
281 | SetURLAndTitle(url: string, title: string): void;
282 | }
283 |
284 | // Google Go:
285 |
286 | declare var __gg__: {
287 | karaokeNavigateToParagraph(...args: any[]): any;
288 | loadElementCss(...args: any[]): any;
289 | loadElementJs(...args: any[]): any;
290 | translateNotifyApiReady(...args: any[]): any;
291 | translateNotifyDetectionError(...args: any[]): any;
292 | translateNotifyError(...args: any[]): any;
293 | translateNotifyFinished(...args: any[]): any;
294 | translateRemoteApiProxyCancel(...args: any[]): any;
295 | translateRemoteApiProxyIsSupported(...args: any[]): any;
296 | translateRemoteApiProxySend(...args: any[]): any;
297 | translateSetSourceLanguage(...args: any[]): any;
298 | }
299 |
300 | declare var gmaSdk: {
301 | getClickSignals(...args: any[]): any;
302 | getClickSignalsWithTimeout(...args: any[]): any;
303 | getQueryInfo(...args: any[]): any;
304 | getViewSignals(...args: any[]): any;
305 | getViewSignalsWithTimeout(...args: any[]): any;
306 | recordClick(...args: any[]): any;
307 | reportTouchEvent(...args: any[]): any;
308 | }
309 |
310 | // Firefox:
311 |
312 | interface Navigator {
313 | taintEnabled(): boolean;
314 | readonly oscpu: string;
315 | }
316 |
317 | interface CSSMozDocumentRule { }
318 |
319 | declare var CSSMozDocumentRule: {
320 | prototype: CSSMozDocumentRule;
321 | };
322 |
323 | declare function dump(message: string): void;
324 |
325 | interface DeviceLightEventInit extends EventInit {
326 | value: number;
327 | }
328 |
329 | declare var DeviceLightEvent: {
330 | prototype: DeviceLightEvent;
331 | new(name: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent;
332 | }
333 |
334 | interface DeviceLightEvent extends Event {
335 | readonly value: number;
336 | }
337 |
338 | /** @deprecated */
339 | declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;
340 |
341 | interface GlobalEventHandlersEventMap {
342 | "devicelight": DeviceLightEvent;
343 | }
344 |
345 | interface DataTransfer {
346 | addElement(element: Element): void;
347 | }
348 |
349 | declare var CSS2Properties: any;
350 |
351 | interface DataTransfer {
352 | addElement(): any;
353 | mozCursor(): any;
354 | mozSourceNode(): any;
355 | mozUserCancelled(): any;
356 | }
357 |
358 | interface Directory {
359 | getfiles(): any;
360 | getfilesAndDirectories(): any;
361 | path: any;
362 | }
363 |
364 | declare var Directory: {
365 | prototype: Directory;
366 | };
367 |
368 | // Servo:
369 |
370 | declare var webdriverTimeout: any;
371 | declare var webdriverCallback: any;
372 |
--------------------------------------------------------------------------------
/types/offscreen-canvas.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface OffscreenCanvasRenderingContext2DSettings {
3 | alpha?: boolean;
4 | colorSpace?: PredefinedColorSpace;
5 | desynchronized?: boolean;
6 | willReadFrequently?: boolean;
7 | }
8 |
9 | interface OffscreenImageBitmapRenderingContextSettings {
10 | alpha?: boolean;
11 | }
12 |
13 | interface OffscreenWebGLContextAttributes {
14 | alpha?: boolean;
15 | antialias?: boolean;
16 | depth?: boolean;
17 | desynchronized?: boolean;
18 | failIfMajorPerformanceCaveat?: boolean;
19 | powerPreference?: WebGLPowerPreference;
20 | premultipliedAlpha?: boolean;
21 | preserveDrawingBuffer?: boolean;
22 | stencil?: boolean;
23 | }
24 |
25 | interface OffscreenCanvas extends EventTarget {
26 | /** Set the third parameter (`_set_to_undefined`) to `undefined` so that TypeScript recognizes that you are using the Better-TypeScript version of it */
27 | getContext(contextId: "2d", options?: OffscreenCanvasRenderingContext2DSettings, _set_to_undefined?: undefined): OffscreenCanvasRenderingContext2D | null;
28 | /** Set the third parameter (`_set_to_undefined`) to `undefined` so that TypeScript recognizes that you are using the Better-TypeScript version of it */
29 | getContext(contextId: "bitmaprenderer", options?: OffscreenImageBitmapRenderingContextSettings, _set_to_undefined?: undefined): ImageBitmapRenderingContext | null;
30 | /** Set the third parameter (`_set_to_undefined`) to `undefined` so that TypeScript recognizes that you are using the Better-TypeScript version of it */
31 | getContext(contextId: "webgl", options?: OffscreenWebGLContextAttributes, _set_to_undefined?: undefined): WebGLRenderingContext | null;
32 | /** Set the third parameter (`_set_to_undefined`) to `undefined` so that TypeScript recognizes that you are using the Better-TypeScript version of it */
33 | getContext(contextId: "webgl2", options?: OffscreenWebGLContextAttributes, _set_to_undefined?: undefined): WebGL2RenderingContext | null;
34 | }
35 |
--------------------------------------------------------------------------------
/types/performance-entry-types.d.ts:
--------------------------------------------------------------------------------
1 |
2 | declare namespace BetterTypeScript {
3 | interface PerformanceEntryTypeMap {
4 | "element": PerformanceElementTiming;
5 | "event": PerformanceEventTiming;
6 | "first-input": PerformanceEventTiming;
7 | "largest-contentful-paint": LargestContentfulPaint;
8 | "layout-shift": LayoutShift;
9 | "longtask": PerformanceLongTaskTiming;
10 | "mark": PerformanceMark;
11 | "measure": PerformanceMeasure;
12 | "navigation": PerformanceNavigationTiming;
13 | "paint": PerformancePaintTiming;
14 | "resource": PerformanceResourceTiming;
15 | "taskattribution": TaskAttributionTiming;
16 | }
17 | }
18 |
19 | interface Performance {
20 | getEntriesByType(type: K): BetterTypeScript.PerformanceEntryTypeMap[K][];
21 | }
22 |
--------------------------------------------------------------------------------
/types/query-selector.d.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 |
4 | interface ParentNode extends Node {
5 | querySelector(selectors: K): BetterTypeScript.GetElementTypeFromSelector | null;
6 | querySelectorAll(selectors: K): NodeListOf> | null;
7 | }
8 |
--------------------------------------------------------------------------------
/types/selector-parser.d.ts:
--------------------------------------------------------------------------------
1 |
2 | // Used by query-selector.d.ts and matches.d.ts
3 |
4 | declare namespace BetterTypeScript {
5 | type GetStringAfterLastSpace = (
6 | Input extends `${string} ${infer AfterFirstSpace}` ? BetterTypeScript.GetStringAfterLastSpace : Input
7 | );
8 |
9 | enum ElementNamespace {
10 | HTML = "html",
11 | SVG = "svg",
12 | MATHML = "mathml",
13 | }
14 |
15 | type NamespaceElements = {
16 | [BetterTypeScript.ElementNamespace.HTML]: HTMLElement;
17 | [BetterTypeScript.ElementNamespace.SVG]: SVGElement;
18 | [BetterTypeScript.ElementNamespace.MATHML]: MathMLElement;
19 | }
20 |
21 | type SelectorContainsSVGOrMathMLElement = (
22 | Input extends `${infer CurrentSelectorFragment} ${infer AfterFirstSpace}` ? (
23 | BetterTypeScript.GetElementNamespaceFromSimpleSelector extends infer ElementNamespace ? (
24 | ElementNamespace extends (BetterTypeScript.ElementNamespace.SVG | BetterTypeScript.ElementNamespace.MATHML)
25 | ? SelectorContainsSVGOrMathMLElement
26 | : SelectorContainsSVGOrMathMLElement
27 | ) : never
28 | ) : BetterTypeScript.NamespaceElements[CurrentElementNamespace]
29 | );
30 |
31 | type GetElementNamespaceFromSimpleSelector = (
32 | BetterTypeScript.GetElementTagNameFromSimpleSelector extends infer ElementTagName ? (
33 | ElementTagName extends keyof HTMLElementTagNameMap
34 | ? BetterTypeScript.ElementNamespace.HTML
35 | : ElementTagName extends keyof SVGElementTagNameMap
36 | ? BetterTypeScript.ElementNamespace.SVG
37 | : ElementTagName extends keyof MathMLElementTagNameMap
38 | ? BetterTypeScript.ElementNamespace.MATHML
39 | : BetterTypeScript.ElementNamespace.HTML
40 | ) : never
41 | );
42 |
43 | type GetElementTagNameFromSimpleSelector = (
44 | (
45 | Input extends `${infer BeforeFirstHash}#${string}`
46 | ? BeforeFirstHash
47 | : Input
48 | ) extends infer Selector ? (
49 | Selector extends `${infer BeforeFirstPeriod}.${string}`
50 | ? BeforeFirstPeriod
51 | : Selector
52 | ) extends infer Selector ? (
53 | Selector extends `${infer BeforeFirstBracket}[${string}`
54 | ? BeforeFirstBracket
55 | : Selector
56 | ) extends infer Selector ? (
57 | Selector extends `${infer BeforeFirstColon}:${string}`
58 | ? BeforeFirstColon
59 | : Selector
60 | ) : never : never : never
61 | );
62 |
63 | type GetElementTypeFromSimpleSelector = (
64 | BetterTypeScript.GetElementTagNameFromSimpleSelector extends infer ElementTagName ? (
65 | ElementTagName extends keyof HTMLElementTagNameMap
66 | ? HTMLElementTagNameMap[ElementTagName]
67 | : ElementTagName extends keyof SVGElementTagNameMap
68 | ? SVGElementTagNameMap[ElementTagName]
69 | : ElementTagName extends keyof MathMLElementTagNameMap
70 | ? MathMLElementTagNameMap[ElementTagName]
71 | : null
72 | ) : never
73 | );
74 |
75 | type GetElementTypeFromSelector = (
76 | BetterTypeScript.GetStringAfterLastSpace extends infer SimpleSelector extends string ? (
77 | BetterTypeScript.GetElementTypeFromSimpleSelector extends infer ElementType ? (
78 | ElementType extends null ? SelectorContainsSVGOrMathMLElement : ElementType
79 | ) : never
80 | ) : never
81 | );
82 |
83 | type SelectorStringContainingElementName = `${(
84 | `${string} ` | ""
85 | )}${(
86 | keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap | keyof MathMLElementTagNameMap
87 | )}${(
88 | "" | `${"#" | "." | "[" | ":"}${string}`
89 | )}`;
90 | }
91 |
--------------------------------------------------------------------------------
/types/service-worker.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface MessageEvent {
3 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */
4 | waitUntil(f: Promise): void;
5 | }
6 |
7 | interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
8 | "activate": ExtendableEvent;
9 | "fetch": FetchEvent;
10 | "install": ExtendableEvent;
11 | "message": MessageEvent;
12 | "messageerror": MessageEvent;
13 | "notificationclick": NotificationEvent;
14 | "notificationclose": NotificationEvent;
15 | "push": PushEvent;
16 | "pushsubscriptionchange": Event;
17 | }
18 |
19 | interface WindowEventMap extends ServiceWorkerGlobalScopeEventMap { }
20 |
21 | type PushMessageDataInit = BufferSource | string;
22 |
23 | /**
24 | * This Push API interface provides methods which let you retrieve the push data sent by a server in various formats.
25 | * Available only in secure contexts.
26 | *
27 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData)
28 | */
29 | interface PushMessageData {
30 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData/arrayBuffer) */
31 | arrayBuffer(): ArrayBuffer;
32 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData/blob) */
33 | blob(): Blob;
34 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData/json) */
35 | json(): any;
36 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData/text) */
37 | text(): string;
38 | }
39 |
40 | declare var PushMessageData: {
41 | prototype: PushMessageData;
42 | new(): PushMessageData;
43 | };
44 |
45 | interface PushEventInit extends ExtendableEventInit {
46 | data?: PushMessageDataInit;
47 | }
48 |
49 | /**
50 | * This Push API interface represents a push message that has been received. This event is sent to the global scope of a ServiceWorker. It contains the information sent from an application server to a PushSubscription.
51 | * Available only in secure contexts.
52 | *
53 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushEvent)
54 | */
55 | interface PushEvent extends ExtendableEvent {
56 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushEvent/data) */
57 | readonly data: PushMessageData | null;
58 | }
59 |
60 | declare var PushEvent: {
61 | prototype: PushEvent;
62 | new(type: string, eventInitDict?: PushEventInit): PushEvent;
63 | };
64 |
65 | interface NotificationEventInit extends ExtendableEventInit {
66 | action?: string;
67 | notification: Notification;
68 | }
69 |
70 | /**
71 | * The parameter passed into the onnotificationclick handler, the NotificationEvent interface represents a notification click event that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker.
72 | *
73 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/NotificationEvent)
74 | */
75 | interface NotificationEvent extends ExtendableEvent {
76 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/NotificationEvent/action) */
77 | readonly action: string;
78 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/NotificationEvent/notification) */
79 | readonly notification: Notification;
80 | }
81 |
82 | declare var NotificationEvent: {
83 | prototype: NotificationEvent;
84 | new(type: string, eventInitDict: NotificationEventInit): NotificationEvent;
85 | };
86 |
87 | interface ExtendableMessageEventInit extends ExtendableEventInit {
88 | data?: any;
89 | lastEventId?: string;
90 | origin?: string;
91 | ports?: MessagePort[];
92 | source?: Client | ServiceWorker | MessagePort | null;
93 | }
94 |
95 | /**
96 | * This ServiceWorker API interface represents the event object of a message event fired on a service worker (when a channel message is received on the ServiceWorkerGlobalScope from another context) — extends the lifetime of such events.
97 | *
98 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableMessageEvent)
99 | */
100 | interface ExtendableMessageEvent extends ExtendableEvent {
101 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableMessageEvent/data) */
102 | readonly data: any;
103 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableMessageEvent/lastEventId) */
104 | readonly lastEventId: string;
105 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableMessageEvent/origin) */
106 | readonly origin: string;
107 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableMessageEvent/ports) */
108 | readonly ports: ReadonlyArray;
109 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableMessageEvent/source) */
110 | readonly source: Client | ServiceWorker | MessagePort | null;
111 | }
112 |
113 | declare var ExtendableMessageEvent: {
114 | prototype: ExtendableMessageEvent;
115 | new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent;
116 | };
117 |
118 | interface FetchEventInit extends ExtendableEventInit {
119 | clientId?: string;
120 | handled?: Promise;
121 | preloadResponse?: Promise;
122 | replacesClientId?: string;
123 | request: Request;
124 | resultingClientId?: string;
125 | }
126 |
127 | /**
128 | * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch.
129 | *
130 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)
131 | */
132 | interface FetchEvent extends ExtendableEvent {
133 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/clientId) */
134 | readonly clientId: string;
135 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/handled) */
136 | readonly handled: Promise;
137 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/preloadResponse) */
138 | readonly preloadResponse: Promise;
139 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */
140 | readonly request: Request;
141 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/resultingClientId) */
142 | readonly resultingClientId: string;
143 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */
144 | respondWith(r: Response | PromiseLike): void;
145 | }
146 |
147 | declare var FetchEvent: {
148 | prototype: FetchEvent;
149 | new(type: string, eventInitDict: FetchEventInit): FetchEvent;
150 | };
151 |
152 | /**
153 | * This ServiceWorker API interface represents the global execution context of a service worker.
154 | *
155 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)
156 | */
157 | interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
158 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/clients) */
159 | readonly clients: Clients;
160 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/activate_event) */
161 | onactivate: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null;
162 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/fetch_event) */
163 | onfetch: ((this: ServiceWorkerGlobalScope, ev: FetchEvent) => any) | null;
164 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/install_event) */
165 | oninstall: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null;
166 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/message_event) */
167 | onmessage: ((this: ServiceWorkerGlobalScope, ev: ExtendableMessageEvent) => any) | null;
168 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/messageerror_event) */
169 | onmessageerror: ((this: ServiceWorkerGlobalScope, ev: MessageEvent) => any) | null;
170 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/notificationclick_event) */
171 | onnotificationclick: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null;
172 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/notificationclose_event) */
173 | onnotificationclose: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null;
174 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/push_event) */
175 | onpush: ((this: ServiceWorkerGlobalScope, ev: PushEvent) => any) | null;
176 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/pushsubscriptionchange_event) */
177 | onpushsubscriptionchange: ((this: ServiceWorkerGlobalScope, ev: Event) => any) | null;
178 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/registration) */
179 | readonly registration: ServiceWorkerRegistration;
180 | readonly serviceWorker: ServiceWorker;
181 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting) */
182 | skipWaiting(): Promise;
183 | addEventListener(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
184 | addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
185 | removeEventListener(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
186 | removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
187 | }
188 |
189 | declare var ServiceWorkerGlobalScope: {
190 | prototype: ServiceWorkerGlobalScope;
191 | new(): ServiceWorkerGlobalScope;
192 | };
193 |
194 | /**
195 | * This ServiceWorker API interface represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. The service worker client independently selects and uses a service worker for its own loading and sub-resources.
196 | *
197 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WindowClient)
198 | */
199 | interface WindowClient extends Client {
200 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WindowClient/focused) */
201 | readonly focused: boolean;
202 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WindowClient/visibilityState) */
203 | readonly visibilityState: DocumentVisibilityState;
204 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WindowClient/focus) */
205 | focus(): Promise;
206 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WindowClient/navigate) */
207 | navigate(url: string | URL): Promise;
208 | }
209 |
210 | declare var WindowClient: {
211 | prototype: WindowClient;
212 | new(): WindowClient;
213 | };
214 |
215 | type FrameType = "auxiliary" | "nested" | "none" | "top-level";
216 |
217 | /**
218 | * The Client interface represents an executable context such as a Worker, or a SharedWorker. Window clients are represented by the more-specific WindowClient. You can get Client/WindowClient objects from methods such as Clients.matchAll() and Clients.get().
219 | *
220 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Client)
221 | */
222 | interface Client {
223 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Client/frameType) */
224 | readonly frameType: FrameType;
225 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Client/id) */
226 | readonly id: string;
227 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Client/type) */
228 | readonly type: ClientTypes;
229 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Client/url) */
230 | readonly url: string;
231 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Client/postMessage) */
232 | postMessage(message: any, transfer: Transferable[]): void;
233 | postMessage(message: any, options?: StructuredSerializeOptions): void;
234 | }
235 |
236 | declare var Client: {
237 | prototype: Client;
238 | new(): Client;
239 | };
240 |
241 | /**
242 | * Provides access to Client objects. Access it via self.clients within a service worker.
243 | *
244 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clients)
245 | */
246 | interface Clients {
247 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clients/claim) */
248 | claim(): Promise;
249 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clients/get) */
250 | get(id: string): Promise;
251 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clients/matchAll) */
252 | matchAll(options?: T): Promise>;
253 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clients/openWindow) */
254 | openWindow(url: string | URL): Promise;
255 | }
256 |
257 | declare var Clients: {
258 | prototype: Clients;
259 | new(): Clients;
260 | };
261 |
262 | declare var clients: Clients;
263 | declare var onactivate: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null;
264 | declare var onfetch: ((this: ServiceWorkerGlobalScope, ev: FetchEvent) => any) | null;
265 | declare var oninstall: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null;
266 | declare var onnotificationclick: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null;
267 | declare var onnotificationclose: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null;
268 | declare var onpush: ((this: ServiceWorkerGlobalScope, ev: PushEvent) => any) | null;
269 | declare var onpushsubscriptionchange: ((this: ServiceWorkerGlobalScope, ev: Event) => any) | null;
270 | declare var registration: ServiceWorkerRegistration;
271 | declare var serviceWorker: ServiceWorker;
272 | declare function skipWaiting(): Promise;
273 |
--------------------------------------------------------------------------------
/types/shadow-root-events.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface ShadowRootEventMap extends GlobalEventHandlersEventMap { }
3 |
--------------------------------------------------------------------------------
/types/shared-worker.d.ts:
--------------------------------------------------------------------------------
1 |
2 | interface SharedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
3 | "connect": MessageEvent;
4 | }
5 |
6 | interface WindowEventMap extends SharedWorkerGlobalScopeEventMap { }
7 |
8 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SharedWorkerGlobalScope) */
9 | interface SharedWorkerGlobalScope extends WorkerGlobalScope {
10 | /**
11 | * Returns sharedWorkerGlobal's name, i.e. the value given to the SharedWorker constructor. Multiple SharedWorker objects can correspond to the same shared worker (and SharedWorkerGlobalScope), by reusing the same name.
12 | *
13 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SharedWorkerGlobalScope/name)
14 | */
15 | readonly name: string;
16 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SharedWorkerGlobalScope/connect_event) */
17 | onconnect: ((this: SharedWorkerGlobalScope, ev: MessageEvent) => any) | null;
18 | /**
19 | * Aborts sharedWorkerGlobal.
20 | *
21 | * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SharedWorkerGlobalScope/close)
22 | */
23 | close(): void;
24 | addEventListener(type: K, listener: (this: SharedWorkerGlobalScope, ev: SharedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
25 | addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
26 | removeEventListener(type: K, listener: (this: SharedWorkerGlobalScope, ev: SharedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
27 | removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
28 | }
29 |
30 | declare var SharedWorkerGlobalScope: {
31 | prototype: SharedWorkerGlobalScope;
32 | new(): SharedWorkerGlobalScope;
33 | };
34 |
35 | declare var onconnect: ((this: SharedWorkerGlobalScope, ev: MessageEvent) => any) | null;
36 | declare function close(): void;
37 |
38 | interface WorkerGlobalScope {
39 | readonly name: string;
40 | onconnect: ((this: SharedWorkerGlobalScope, ev: MessageEvent) => any) | null;
41 | close(): void;
42 | addEventListener(type: K, listener: (this: SharedWorkerGlobalScope, ev: SharedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
43 | addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
44 | removeEventListener(type: K, listener: (this: SharedWorkerGlobalScope, ev: SharedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
45 | removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
46 | }
47 |
--------------------------------------------------------------------------------
/types/tree-walker.d.ts:
--------------------------------------------------------------------------------
1 |
2 | declare namespace BetterTypeScript {
3 | type NodeFilter = ((node: T) => number) | { acceptNode(node: T): number; }
4 |
5 | interface TreeWalker {
6 | currentNode: T;
7 | readonly filter: globalThis.NodeFilter | null;
8 | readonly root: R;
9 | readonly whatToShow: number;
10 | firstChild(): T | null;
11 | lastChild(): T | null;
12 | nextNode(): T | null;
13 | nextSibling(): T | null;
14 | parentNode(): T | null;
15 | previousNode(): T | null;
16 | previousSibling(): T | null;
17 | }
18 |
19 | interface NodeFilterMap {
20 | [NodeFilter.SHOW_ELEMENT]: Element;
21 | [NodeFilter.SHOW_TEXT]: Text;
22 | [NodeFilter.SHOW_COMMENT]: Comment;
23 | }
24 | }
25 |
26 | interface Document {
27 | createTreeWalker(root: R, whatToShow: F, filter?: BetterTypeScript.NodeFilter): BetterTypeScript.TreeWalker;
28 | }
29 |
--------------------------------------------------------------------------------
/types/tuple.d.ts:
--------------------------------------------------------------------------------
1 |
2 | // Shamelessly copied from https://stackoverflow.com/a/60762482
3 |
4 | declare namespace BetterTypeScript {
5 | type GrowToSize = (
6 | A["length"] extends N
7 | ? A
8 | : GrowToSize
9 | );
10 | }
11 |
12 | type Tuple = BetterTypeScript.GrowToSize;
13 |
--------------------------------------------------------------------------------
/types/typed-array.d.ts:
--------------------------------------------------------------------------------
1 |
2 | type TypedArray = (
3 | | Int8Array
4 | | Uint8Array
5 | | Uint8ClampedArray
6 | | Int16Array
7 | | Uint16Array
8 | | Int32Array
9 | | Uint32Array
10 | | BigInt64Array
11 | | BigUint64Array
12 | | Float32Array
13 | | Float64Array
14 | );
15 |
--------------------------------------------------------------------------------
/types/webassembly.d.ts:
--------------------------------------------------------------------------------
1 |
2 | declare namespace BetterTypeScript {
3 | namespace WebAssembly {
4 | interface Instance {
5 | readonly exports: BetterTypeScript.WebAssembly.Exports;
6 | }
7 |
8 | interface WebAssemblyInstantiatedSource {
9 | instance: BetterTypeScript.WebAssembly.Instance;
10 | module: globalThis.WebAssembly.Module;
11 | }
12 |
13 | type ExportValue = (
14 | & ((...args: any[]) => any)
15 | & globalThis.WebAssembly.Global
16 | & globalThis.WebAssembly.Memory
17 | & globalThis.WebAssembly.Table
18 | );
19 |
20 | type Exports = Record;
21 | }
22 | }
23 |
24 | declare namespace WebAssembly {
25 | function instantiate(bytes: BufferSource, importObject?: Imports): Promise;
26 | function instantiate(moduleObject: Module, importObject?: Imports): Promise;
27 | function instantiateStreaming(source: Response | PromiseLike, importObject?: Imports): Promise;
28 | }
29 |
--------------------------------------------------------------------------------
/worklet/animation.d.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 | ///
4 | ///
5 |
6 | ///
7 |
8 | ///
9 |
--------------------------------------------------------------------------------
/worklet/audio.d.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 | ///
4 | ///
5 |
6 | ///
7 |
8 | ///
9 |
--------------------------------------------------------------------------------
/worklet/layout.d.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 | ///
4 | ///
5 |
6 | ///
7 |
8 | ///
9 |
--------------------------------------------------------------------------------
/worklet/paint.d.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 | ///
4 | ///
5 |
6 | ///
7 |
8 | ///
9 |
--------------------------------------------------------------------------------
/worklet/worklet-global.d.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 |
--------------------------------------------------------------------------------