@cldmv/wisp 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.mjs"],"names":[],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-from-caller.d.mts","sourceRoot":"","sources":["../../src/lib/resolve-from-caller.mjs"],"names":[],"mappings":"AAqFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,6CAhCa,KAAK,CAAC,QAAQ,CAAC,CA0C3B;AA4MD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,2CAzCW,MAAM,GACJ,MAAM,CAsDlB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,0CA1CW,MAAM,GACJ,MAAM,CAuDlB;AAtXM,4BAvBI,GAAG,GACD,MAAM,GAAC,IAAI,CAsB+F;;iBA0XzG,MAAY,MAAM,GAAC,SAAS;mBAC5B,MAAY,MAAM,GAAC,SAAS;qBAC5B,MAAY,MAAM,GAAC,SAAS;iBAC5B,MAAY,MAAM,GAAC,SAAS;mBAC5B,MAAY,MAAM,GAAC,SAAS;8BAC5B,MAAY,MAAM,GAAC,SAAS;qBAC5B,MAAY,MAAM,GAAC,SAAS;cAC5B,MAAY,OAAO,GAAC,SAAS;YAC7B,MAAY,OAAO,GAAC,SAAS;mBAC7B,MAAY,OAAO,GAAC,SAAS;gBAC7B,MAAY,OAAO,GAAC,SAAS;aAC7B,MAAY,OAAO,GAAC,SAAS;kBAC7B,MAAY,OAAO,GAAC,SAAS;qBAC7B,MAAY,MAAM,GAAC,SAAS"}
1
+ {"version":3,"file":"resolve-from-caller.d.mts","sourceRoot":"","sources":["../../src/lib/resolve-from-caller.mjs"],"names":[],"mappings":"AAuFA;;;;;;;;;;;;;;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**
2
- * @fileoverview CJS entry point for @cldmv/wisp, providing version-agnostic JSON importing.
3
- * @module @cldmv/wisp
4
- * @public
5
- *
6
- * @description
7
- * This module provides CommonJS exports for the wisp and wispSync functions.
8
- * It uses createRequire to load the ESM implementation and re-exports it.
9
- *
10
- * @example
11
- * const { wisp, wispSync } = require('@cldmv/wisp');
12
- * const data = wispSync('./data.json');
13
- */
14
-
15
- "use strict";
16
-
17
- const { createRequire } = require("module");
18
- const requireESM = createRequire(__filename);
19
- const esm = requireESM("./index.mjs");
20
-
21
- module.exports = esm.default;
22
- module.exports.default = esm.default;
23
- module.exports.wisp = esm.wisp;
24
- module.exports.wispSync = esm.wispSync;
package/index.mjs DELETED
@@ -1,22 +0,0 @@
1
- /**
2
- * @fileoverview Main entry point for @cldmv/wisp, providing version-agnostic JSON importing.
3
- * @module @cldmv/wisp
4
- * @public
5
- *
6
- * @description
7
- * This module exports the wisp and wispSync functions for loading JSON files
8
- * with support for different Node.js versions and import syntaxes.
9
- *
10
- * @example
11
- * // ESM
12
- * import { wisp, wispSync } from '@cldmv/wisp';
13
- * const data = await wisp('./data.json');
14
- *
15
- * @example
16
- * // CJS
17
- * const { wisp, wispSync } = require('@cldmv/wisp');
18
- * const data = wispSync('./data.json');
19
- */
20
-
21
- export * from "./src/wisp.mjs";
22
- export { default } from "./src/wisp.mjs";
@@ -1,479 +0,0 @@
1
- /**
2
- * @Project: @cldmv/wisp
3
- * @Filename: /src/lib/resolve-from-caller.mjs
4
- * @Date: 2025-09-09 13:22:38 -07:00 (1757449358)
5
- * @Author: Nate Hyson <CLDMV>
6
- * @Email: <Shinrai@users.noreply.github.com>
7
- * -----
8
- * @Last modified by: Nate Hyson <CLDMV> (Shinrai@users.noreply.github.com)
9
- * @Last modified time: 2025-10-31 07:31:40 -07:00 (1761921100)
10
- * -----
11
- * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
- */
13
-
14
- /**
15
- * @fileoverview Path resolution utilities for resolving paths from the caller context. Internal file (not exported in package.json).
16
- * @module @cldmv/wisp.helpers.resolve-from-caller
17
- * @memberof module:@cldmv/wisp.helpers
18
- * @internal
19
- * @package
20
- *
21
- * @description
22
- * Advanced path resolution system that uses V8 stack trace analysis to determine caller context.
23
- * Provides utilities for resolving relative paths from the caller's directory, implementing
24
- * sophisticated caller detection algorithms to handle complex module loading scenarios.
25
- *
26
- * Key features:
27
- * - V8 CallSite-based stack trace analysis
28
- * - Primary base file detection with fallback strategies
29
- * - Support for both filesystem paths and file:// URLs
30
- * - Smart handling of slothlet.mjs and index file patterns
31
- * - Existence-based resolution with automatic fallback
32
- *
33
- * Technical implementation:
34
- * - Uses Error.prepareStackTrace to access V8 CallSite objects
35
- * - Implements dual-phase resolution (primary + fallback)
36
- * - Handles edge cases like node:internal modules and helper directories
37
- * - Provides both path and URL resolution variants
38
- *
39
- *
40
- * @example
41
- * // ESM (internal)
42
- * import { resolvePathFromCaller } from "@cldmv/slothlet/helpers/resolve-from-caller";
43
- * // Internal example using package.json exports
44
- *
45
- * @example
46
- * // Relative import (internal)
47
- * import { resolvePathFromCaller, resolveUrlFromCaller } from "./resolve-from-caller.mjs";
48
- * const configPath = resolvePathFromCaller("../config.json");
49
- */
50
-
51
- import fs from "node:fs";
52
- import path from "node:path";
53
- import { fileURLToPath, pathToFileURL } from "node:url";
54
-
55
- /* ---------- tiny utils ---------- */
56
-
57
- /**
58
- * @function toFsPath
59
- * @package
60
- * @internal
61
- * @param {any} v - Value to convert (file:// URL, path string, or any other value)
62
- * @returns {string|null} Filesystem path if URL conversion successful, original string if already a path, null if input is falsy
63
- *
64
- * @description
65
- * Convert file:// URL to filesystem path, or return string as-is.
66
- * Handles URL-to-path conversion for cross-platform compatibility while preserving
67
- * non-URL strings unchanged. Provides null-safe operation for invalid inputs.
68
- *
69
- * @example
70
- * // URL conversion
71
- * toFsPath("file:///project/config.json"); // "/project/config.json" (Unix) or "C:\\project\\config.json" (Windows)
72
- *
73
- * @example
74
- * // String passthrough
75
- * toFsPath("/project/config.json"); // "/project/config.json"
76
- * toFsPath("C:\\project\\config.json"); // "C:\\project\\config.json"
77
- *
78
- * @example
79
- * // Null-safe handling
80
- * toFsPath(null); // null
81
- * toFsPath(undefined); // null
82
- * toFsPath(""); // null
83
- */
84
- export const toFsPath = (v) => (v && String(v).startsWith("file://") ? fileURLToPath(String(v)) : v ? String(v) : null);
85
-
86
- /**
87
- * @function getStack
88
- * @package
89
- * @internal
90
- * @param {Function} [skipFn] - Function to skip in stack trace via Error.captureStackTrace
91
- * @returns {Array<CallSite>} Array of V8 CallSite objects with methods like getFileName(), getLineNumber(), etc.
92
- *
93
- * @description
94
- * Get V8 stack trace as CallSite array for debugging and caller detection.
95
- * Temporarily overrides Error.prepareStackTrace to access raw V8 CallSite objects
96
- * instead of formatted string stack traces. Provides safe restoration of original handler.
97
- *
98
- * @example
99
- * // Get current call stack for debugging
100
- * const stack = getStack();
101
- * console.log(stack[0]?.getFileName?.()); // Current file path
102
- * console.log(stack[0]?.getLineNumber?.()); // Current line number
103
- *
104
- * @example
105
- * // Skip current function from stack trace
106
- * function myFunction() {
107
- * return getStack(myFunction); // Stack starts from caller of myFunction
108
- * }
109
- * const callerStack = myFunction();
110
- *
111
- * @example
112
- * // Stack analysis for caller detection
113
- * function findCaller() {
114
- * const stack = getStack(findCaller);
115
- * for (const frame of stack) {
116
- * const filename = frame?.getFileName?.();
117
- * if (filename && !filename.includes("node_modules")) {
118
- * return filename; // First non-dependency file
119
- * }
120
- * }
121
- * }
122
- */
123
- export function getStack(skipFn) {
124
- const orig = Error.prepareStackTrace;
125
- try {
126
- Error.prepareStackTrace = (_, s) => s; // V8 CallSite[]
127
- const e = new Error("Stack trace");
128
- if (skipFn) Error.captureStackTrace(e, skipFn);
129
- return /** @type {NodeJS.CallSite[]} */ (/** @type {unknown} */ (e.stack)) || [];
130
- } finally {
131
- Error.prepareStackTrace = orig;
132
- }
133
- }
134
-
135
- const THIS_FILE = fileURLToPath(import.meta.url);
136
-
137
- // Find the package root by looking for package.json
138
- function findPackageRoot(startPath) {
139
- let currentPath = startPath;
140
- while (currentPath !== path.dirname(currentPath)) {
141
- const packageJsonPath = path.join(currentPath, "package.json");
142
- if (fs.existsSync(packageJsonPath)) {
143
- return currentPath;
144
- }
145
- currentPath = path.dirname(currentPath);
146
- }
147
- return null;
148
- }
149
-
150
- const PACKAGE_ROOT = findPackageRoot(THIS_FILE);
151
-
152
- /* ---------- base selection (shared) ---------- */
153
- // Two-flag state machine for detecting when we've exited package infrastructure:
154
- // 1) Flag 1: Set when we exit src/ or dist/ directories
155
- // 2) Flag 2: Set when we exit index.* entry point files
156
- // 3) Once both flags are set, we've found the actual caller outside the package
157
-
158
- /**
159
- * @function pickPrimaryBaseFile
160
- * @internal
161
- * @private
162
- * @returns {string|null} Primary base file path for resolution, null if detection fails
163
- *
164
- * @description
165
- * Find the primary base file using stack trace analysis with a two-flag state machine.
166
- * Tracks when we **exit** from package infrastructure directories/files.
167
- *
168
- * Algorithm:
169
- * 1. Walk stack trace backwards (from deepest to shallowest calls)
170
- * 2. Flag 1: Set when we exit src/ or dist/ folder (transition from src/dist to non-src/dist)
171
- * 3. Flag 2: Set when we exit index.* files (transition from index.* to non-index.*)
172
- * 4. Once both flags are set, we've fully exited the package infrastructure
173
- * 5. Return the current file as the actual caller
174
- *
175
- * @example
176
- * // Stack trace flow (wisp example):
177
- * // 0: src/lib/resolve-from-caller.mjs [in src/]
178
- * // 1: src/wisp.mjs [still in src/]
179
- * // 2: index.mjs [exited src/ - Flag 1 set]
180
- * // 3: user-code.mjs [exited index.* - Flag 2 set, return this!]
181
- */
182
- function pickPrimaryBaseFile() {
183
- let exitedSrcOrDist = false; // Flag 1: Have we exited src/ or dist/?
184
- // This function's own docstring documents a "Flag 2 set, return this!"
185
- // scenario, but nothing reads exitedIndex to return early once it's set --
186
- // looks like a pre-existing gap between the documented intent and the
187
- // implementation. Left as-is; fixing the behavior is a separate decision
188
- // from unblocking lint.
189
- let exitedIndex = false; // Flag 2: Have we exited index.*?
190
- let previousWasInSrcOrDist = false;
191
- let previousWasIndex = false;
192
-
193
- for (const cs of getStack(pickPrimaryBaseFile)) {
194
- const f = toFsPath(cs?.getFileName?.());
195
- if (!f) continue;
196
- if (f.startsWith?.("node:internal")) continue;
197
- if (f === THIS_FILE) continue;
198
-
199
- let currentIsInSrcOrDist = false;
200
- let currentIsIndex = false;
201
-
202
- // Check if this file is in our package
203
- if (PACKAGE_ROOT && f.startsWith(PACKAGE_ROOT + path.sep)) {
204
- const relativePath = path.relative(PACKAGE_ROOT, f);
205
- const segments = relativePath.split(path.sep);
206
-
207
- // Check if current file is in src/ or dist/
208
- currentIsInSrcOrDist = segments[0] === "src" || segments[0] === "dist";
209
-
210
- // Check if current file is index.*
211
- currentIsIndex = segments.length === 1 && /^index\.(mjs|cjs|js|ts)$/.test(segments[0]);
212
- }
213
-
214
- // Flag 1: Check if we've exited src/dist (was in, now not in)
215
- if (previousWasInSrcOrDist && !currentIsInSrcOrDist) {
216
- exitedSrcOrDist = true;
217
- }
218
-
219
- // Flag 2: Check if we've exited index.* (was index, now not index)
220
- if (previousWasIndex && !currentIsIndex) {
221
- // eslint-disable-next-line no-unused-vars -- see the declaration above
222
- exitedIndex = true;
223
- }
224
-
225
- // If we've exited src/dist, we've found the caller (index.mjs might be optimized away)
226
- if (exitedSrcOrDist) {
227
- return f;
228
- }
229
-
230
- // Update previous state for next iteration
231
- previousWasInSrcOrDist = currentIsInSrcOrDist;
232
- previousWasIndex = currentIsIndex;
233
- }
234
- return null;
235
- }
236
- /**
237
- * @function pickFallbackBaseFile
238
- * @internal
239
- * @private
240
- * @returns {string} Fallback base file path, guaranteed to return a valid path
241
- *
242
- * @description
243
- * Find fallback base file when primary detection fails.
244
- * Provides robust fallback strategy by finding the first legitimate user code frame.
245
- * Filters out internal Node.js modules, helper utilities, and slothlet infrastructure.
246
- *
247
- * Fallback algorithm:
248
- * 1. Iterate through stack frames from top to bottom
249
- * 2. Skip node:internal modules (Node.js internals)
250
- * 3. Skip this file itself (resolve-from-caller.mjs)
251
- * 4. Skip other files in the helpers directory
252
- * 5. Skip slothlet.mjs infrastructure files
253
- * 6. Return first remaining frame, or THIS_FILE as ultimate fallback
254
- *
255
- * This ensures we always have a base path for resolution, even in edge cases.
256
- *
257
- * @example
258
- * // Fallback scenarios:
259
- * // - Primary detection failed (no slothlet.mjs in stack)
260
- * // - Complex loading chain with multiple loaders
261
- * // - Edge cases like REPL or test environments
262
- * // - Direct API usage without slothlet loader
263
- */
264
- function pickFallbackBaseFile() {
265
- // Use simpler fallback logic - just find first non-Node.js-internal file
266
- for (const cs of getStack(pickFallbackBaseFile)) {
267
- const f = toFsPath(cs?.getFileName?.());
268
- if (!f) continue;
269
- if (f.startsWith?.("node:internal")) continue;
270
- if (f === THIS_FILE) continue;
271
- return f;
272
- }
273
- return THIS_FILE;
274
- }
275
-
276
- /* ---------- generic resolver (shared) ---------- */
277
-
278
- /**
279
- * @function resolveWith
280
- * @internal
281
- * @private
282
- * @param {string} rel - Relative path to resolve (must be a string)
283
- * @param {Function} makePrimary - Function to build primary candidate: (baseFile, rel) => candidate
284
- * @param {Function} exists - Existence check function: (candidate) => boolean
285
- * @param {Function} makeFallback - Function to build fallback result: (baseFile, rel) => result
286
- * @returns {string} Resolved path or URL (type depends on make functions)
287
- * @throws {TypeError} When rel parameter is not a string
288
- *
289
- * @description
290
- * Generic resolver that tries primary base file detection with fallback.
291
- * Core resolution engine that orchestrates the two-phase detection strategy.
292
- * Attempts primary resolution first, then falls back if target doesn't exist.
293
- *
294
- * Resolution strategy:
295
- * 1. Get primary base file using sophisticated stack analysis
296
- * 2. Build primary candidate using makePrimary function
297
- * 3. Check if primary candidate exists using exists function
298
- * 4. If exists, return primary candidate
299
- * 5. Otherwise, get fallback base file and build fallback result
300
- * 6. Return fallback result (no second existence check)
301
- *
302
- * This pattern ensures we try the most accurate resolution first, but always
303
- * provide a reasonable fallback even if the target doesn't exist yet.
304
- *
305
- * @example
306
- * // Usage pattern for filesystem paths:
307
- * resolveWith(
308
- * "../config.json",
309
- * (base, rel) => path.resolve(path.dirname(base), rel), // makePrimary
310
- * (candidate) => fs.existsSync(candidate), // exists
311
- * (base, rel) => path.resolve(path.dirname(base), rel) // makeFallback
312
- * );
313
- *
314
- * @example
315
- * // Usage pattern for URLs:
316
- * resolveWith(
317
- * "../config.json",
318
- * (base, rel) => new URL(rel, pathToFileURL(base)).href, // makePrimary
319
- * (href) => fs.existsSync(fileURLToPath(href)), // exists
320
- * (base, rel) => new URL(rel, pathToFileURL(base)).href // makeFallback
321
- * );
322
- */
323
- function resolveWith(rel, makePrimary, exists, makeFallback) {
324
- if (typeof rel !== "string") throw new TypeError("rel must be a string");
325
-
326
- // absolute / already-URL cases are handled in the public wrappers
327
- const primaryBase = pickPrimaryBaseFile() ?? pickFallbackBaseFile();
328
- const primary = makePrimary(primaryBase, rel);
329
- if (exists(primary)) return primary;
330
-
331
- const fbBase = pickFallbackBaseFile();
332
- return makeFallback(fbBase, rel);
333
- }
334
-
335
- /* ---------- public API (thin wrappers) ---------- */
336
-
337
- /**
338
- * @function resolvePathFromCaller
339
- * @package
340
- * @internal
341
- * @param {string} rel - Relative path to resolve (e.g., "../config.json", "./data/file.txt")
342
- * @returns {string} Absolute filesystem path with platform-specific separators
343
- * @throws {TypeError} When rel parameter is not a string
344
- *
345
- * @description
346
- * Resolve a relative path from the caller's context to an absolute filesystem path.
347
- * Primary public API for filesystem path resolution with intelligent caller detection.
348
- * Uses sophisticated stack trace analysis to determine the appropriate base directory.
349
- *
350
- * Resolution behavior:
351
- * - file:// URLs: Converted to filesystem paths via fileURLToPath()
352
- * - Absolute paths: Returned unchanged (already absolute)
353
- * - Relative paths: Resolved using caller detection algorithm
354
- *
355
- * Caller detection process:
356
- * 1. Primary: Use sophisticated slothlet.mjs-aware stack analysis
357
- * 2. Fallback: Use first non-helper frame if primary fails
358
- * 3. Existence check: Prefer primary if target exists, otherwise use fallback
359
- *
360
- * @example
361
- * // From a file at /project/src/modules/math.mjs
362
- * const configPath = resolvePathFromCaller("../config.json");
363
- * // Returns: /project/config.json (absolute filesystem path)
364
- *
365
- * @example
366
- * // Short-circuit cases
367
- * resolvePathFromCaller("file:///absolute/path.txt");
368
- * // Returns: /absolute/path.txt (converted from URL)
369
- *
370
- * resolvePathFromCaller("/already/absolute/path.txt");
371
- * // Returns: /already/absolute/path.txt (unchanged)
372
- *
373
- * @example
374
- * // Relative resolution from different contexts
375
- * // If called from /project/src/lib/utils.mjs:
376
- * resolvePathFromCaller("./helpers/format.js");
377
- * // Returns: /project/src/lib/helpers/format.js
378
- *
379
- * resolvePathFromCaller("../../config/settings.json");
380
- * // Returns: /project/config/settings.json
381
- */
382
- export function resolvePathFromCaller(rel) {
383
- // short-circuits
384
- if (rel.startsWith?.("file://")) return fileURLToPath(rel);
385
- if (path.isAbsolute(rel)) return rel;
386
-
387
- return resolveWith(
388
- rel,
389
- // makePrimary (PATH)
390
- (baseFile, r) => path.resolve(path.dirname(baseFile), r),
391
- // exists (PATH)
392
- (candidate) => fs.existsSync(candidate),
393
- // makeFallback (PATH)
394
- (baseFile, r) => path.resolve(path.dirname(baseFile), r)
395
- );
396
- }
397
-
398
- /**
399
- * @function resolveUrlFromCaller
400
- * @package
401
- * @internal
402
- * @param {string} rel - Relative path to resolve (e.g., "../config.json", "./data/file.txt")
403
- * @returns {string} Absolute file:// URL suitable for dynamic imports and URL operations
404
- * @throws {TypeError} When rel parameter is not a string
405
- *
406
- * @description
407
- * Resolve a relative path from the caller's context to a file:// URL.
408
- * Companion API to resolvePathFromCaller that returns file:// URLs instead of filesystem paths.
409
- * Uses identical caller detection algorithm but outputs URL format for ESM imports.
410
- *
411
- * Resolution behavior:
412
- * - file:// URLs: Returned unchanged (already in URL format)
413
- * - Absolute paths: Converted to file:// URLs via pathToFileURL()
414
- * - Relative paths: Resolved using caller detection, then converted to URL
415
- *
416
- * Caller detection uses the same sophisticated algorithm as resolvePathFromCaller,
417
- * but the final result is converted to a file:// URL for compatibility with
418
- * ESM dynamic imports and other URL-based operations.
419
- *
420
- * @example
421
- * // From a file at /project/src/modules/math.mjs
422
- * const configUrl = resolveUrlFromCaller("../config.json");
423
- * // Returns: file:///project/config.json (absolute file:// URL)
424
- *
425
- * @example
426
- * // Short-circuit cases
427
- * resolveUrlFromCaller("file:///absolute/path.txt");
428
- * // Returns: file:///absolute/path.txt (unchanged)
429
- *
430
- * resolveUrlFromCaller("/already/absolute/path.txt");
431
- * // Returns: file:///already/absolute/path.txt (converted to URL)
432
- *
433
- * @example
434
- * // Dynamic ESM import usage
435
- * const modulePath = resolveUrlFromCaller("./dynamic-module.mjs");
436
- * const dynamicModule = await import(modulePath);
437
- * // Works seamlessly with ESM import() which expects URLs
438
- *
439
- * @example
440
- * // Cross-platform URL handling
441
- * // Unix: resolveUrlFromCaller("../config.json") → file:///project/config.json
442
- * // Windows: resolveUrlFromCaller("../config.json") → file:///C:/project/config.json
443
- */
444
- export function resolveUrlFromCaller(rel) {
445
- // short-circuits
446
- if (rel.startsWith?.("file://")) return rel;
447
- if (path.isAbsolute(rel)) return pathToFileURL(rel).href;
448
-
449
- return resolveWith(
450
- rel,
451
- // makePrimary (URL)
452
- (baseFile, r) => new URL(r, pathToFileURL(baseFile)).href,
453
- // exists (URL→check target path)
454
- (href) => fs.existsSync(fileURLToPath(href)),
455
- // makeFallback (URL)
456
- (baseFile, r) => new URL(r, pathToFileURL(baseFile)).href
457
- );
458
- }
459
-
460
- /**
461
- * @typedef {object} CallSite
462
- * @property {function(): string|undefined} getFileName
463
- * @property {function(): number|undefined} getLineNumber
464
- * @property {function(): string|undefined} getFunctionName
465
- * @property {function(): string|undefined} getTypeName
466
- * @property {function(): string|undefined} getMethodName
467
- * @property {function(): string|undefined} getScriptNameOrSourceURL
468
- * @property {function(): number|undefined} getColumnNumber
469
- * @property {function(): boolean|undefined} isNative
470
- * @property {function(): boolean|undefined} isEval
471
- * @property {function(): boolean|undefined} isConstructor
472
- * @property {function(): boolean|undefined} isToplevel
473
- * @property {function(): boolean|undefined} isAsync
474
- * @property {function(): boolean|undefined} isPromiseAll
475
- * @property {function(): number|undefined} getPromiseIndex
476
- *
477
- * @description
478
- * Minimal V8 CallSite object type for stack trace analysis. Only includes methods used in this module.
479
- */