|
| 1 | +/* |
| 2 | + * Copyright 2026 Adobe. All rights reserved. |
| 3 | + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. You may obtain a copy |
| 5 | + * of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + * |
| 7 | + * Unless required by applicable law or agreed to in writing, software distributed under |
| 8 | + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 9 | + * OF ANY KIND, either express or implied. See the License for the specific language |
| 10 | + * governing permissions and limitations under the License. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * Type guard that checks if a value is a Node. Verifies the presence and type of the nodeType |
| 15 | + * property. |
| 16 | + */ |
| 17 | +export function isNode(value: unknown): value is Node { |
| 18 | + return ( |
| 19 | + value !== null && |
| 20 | + typeof value === 'object' && |
| 21 | + 'nodeType' in value && |
| 22 | + typeof value.nodeType === 'number' |
| 23 | + ); |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Type guard that checks if a value is a Window. Uses window self reference checks to |
| 28 | + * distinguish Window from other values. |
| 29 | + */ |
| 30 | +export function isWindow(value: unknown): value is Window & typeof globalThis { |
| 31 | + return typeof value === 'object' && value != null && 'window' in value && value.window === value; |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Type guard that checks if a value is a Document. Uses nodeType and host property checks to |
| 36 | + * distinguish Document from other values. |
| 37 | + */ |
| 38 | +export function isDocument(value: unknown): value is Document { |
| 39 | + return isNode(value) && value.nodeType === 9; |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Type guard that checks if a value is a ShadowRoot. Uses nodeType and host property checks to |
| 44 | + * distinguish ShadowRoot from other values. |
| 45 | + */ |
| 46 | +export function isShadowRoot(value: unknown): value is ShadowRoot { |
| 47 | + // 11 = DOCUMENT_FRAGMENT_NODE |
| 48 | + return isNode(value) && value.nodeType === 11 && 'host' in value; |
| 49 | +} |
0 commit comments