code:
# JavaScript ObjectSchema Package

by [Nicholas C. Zakas](https://humanwhocodes.com)

If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).

## Overview

A JavaScript object merge/validation utility where you can define a different merge and validation strategy for each key. This is helpful when you need to validate complex data structures and then merge them in a way that is more complex than `Object.assign()`.

## Installation

You can install using either npm:

```
npm install @humanwhocodes/object-schema
```

Or Yarn:

```
yarn add @humanwhocodes/object-schema
```

## Usage

Use CommonJS to get access to the `ObjectSchema` constructor:

```js
const { ObjectSchema } = require("@humanwhocodes/object-schema");

const schema = new ObjectSchema({

    // define a definition for the "downloads" key
    downloads: {
        required: true,
        merge(value1, value2) {
            return value1 + value2;
        },
        validate(value) {
            if (typeof value !== "number") {
                throw new Error("Expected downloads to be a number.");
            }
        }
    },

    // define a strategy for the "versions" key
    version: {
        required: true,
        merge(value1, value2) {
            return value1.concat(value2);
        },
        validate(value) {
            if (!Array.isArray(value)) {
                throw new Error("Expected versions to be an array.");
            }
        }
    }
});

const record1 = {
    downloads: 25,
    versions: [
        "v1.0.0",
        "v1.1.0",
        "v1.2.0"
    ]
};

const record2 = {
    downloads: 125,
    versions: [
        "v2.0.0",
        "v2.1.0",
        "v3.0.0"
    ]
};

// make sure the records are valid
schema.validate(record1);
schema.validate(record2);

// merge together (schema.merge() accepts any number of objects)
const result = schema.merge(record1, record2);

// result looks like this:

const result = {
    downloads: 75,
    versions: [
        "v1.0.0",
        "v1.1.0",
        "v1.2.0",
        "v2.0.0",
        "v2.1.0",
        "v3.0.0"
    ]
};
```

## Tips and Tricks

### Named merge strategies

Instead of specifying a `merge()` method, you can specify one of the following strings to use a default merge strategy:

* `"assign"` - use `Object.assign()` to merge the two values into one object.
* `"overwrite"` - the second value always replaces the first.
* `"replace"` - the second value replaces the first if the second is not `undefined`.

For example:

```js
const schema = new ObjectSchema({
    name: {
        merge: "replace",
        validate() {}
    }
});
```

### Named validation strategies

Instead of specifying a `validate()` method, you can specify one of the following strings to use a default validation strategy:

* `"array"` - value must be an array.
* `"boolean"` - value must be a boolean.
* `"number"` - value must be a number.
* `"object"` - value must be an object.
* `"object?"` - value must be an object or null.
* `"string"` - value must be a string.
* `"string!"` - value must be a non-empty string.

For example:

```js
const schema = new ObjectSchema({
    name: {
        merge: "replace",
        validate: "string"
    }
});
```

### Subschemas

If you are defining a key that is, itself, an object, you can simplify the process by using a subschema. Instead of defining `merge()` and `validate()`, assign a `schema` key that contains a schema definition, like this:

```js
const schema = new ObjectSchema({
    name: {
        schema: {
            first: {
                merge: "replace",
                validate: "string"
            },
            last: {
                merge: "replace",
                validate: "string"
            }
        }
    }
});

schema.validate({
    name: {
        first: "n",
        last: "z"
    }
});
```

### Remove Keys During Merge

If the merge strategy for a key returns `undefined`, then the key will not appear in the final object. For example:

```js
const schema = new ObjectSchema({
    date: {
        merge() {
            return undefined;
        },
        validate(value) {
            Date.parse(value);  // throws an error when invalid
        }
    }
});

const object1 = { date: "5/5/2005" };
const object2 = { date: "6/6/2006" };

const result = schema.merge(object1, object2);

console.log("date" in result);  // false
```

### Requiring Another Key Be Present

If you'd like the presence of one key to require the presence of another key, you can use the `requires` property to specify an array of other properties that any key requires. For example:

```js
const schema = new ObjectSchema();

const schema = new ObjectSchema({
    date: {
        merge() {
            return undefined;
        },
        validate(value) {
            Date.parse(value);  // throws an error when invalid
        }
    },
    time: {
        requires: ["date"],
        merge(first, second) {
            return second;
        },
        validate(value) {
            // ...
        }
    }
});

// throws error: Key "time" requires keys "date"
schema.validate({
    time: "13:45"
});
```

In this example, even though `date` is an optional key, it is required to be present whenever `time` is present.

## License

BSD 3-Clause


@humanwhocodes/object-schema

description: An object schema merger/validator

files: src LICENSE README.md

test: tests

test: mocha tests/

type: git

keywords: object validation schema merge

author: Nicholas C. Zakas

license: mit


code:
/**
 * @filedescription Object Schema Package
 */

exports.ObjectSchema = require("./object-schema").ObjectSchema;
exports.MergeStrategy = require("./merge-strategy").MergeStrategy;
exports.ValidationStrategy = require("./validation-strategy").ValidationStrategy;


code:
/**
 * @filedescription Merge Strategy
 */

"use strict";

//-----------------------------------------------------------------------------
// Class
//-----------------------------------------------------------------------------

/**
 * Container class for several different merge strategies.
 */
class MergeStrategy {

    /**
     * Merges two keys by overwriting the first with the second.
     * @param {*} value1 The value from the first object key.
     * @param {*} value2 The value from the second object key.
     * @returns {*} The second value.
     */
    static overwrite(value1, value2) {
        return value2;
    }

    /**
     * Merges two keys by replacing the first with the second only if the
     * second is defined.
     * @param {*} value1 The value from the first object key.
     * @param {*} value2 The value from the second object key.
     * @returns {*} The second value if it is defined.
     */
    static replace(value1, value2) {
        if (typeof value2 !== "undefined") {
            return value2;
        }

        return value1;
    }

    /**
     * Merges two properties by assigning properties from the second to the first.
     * @param {*} value1 The value from the first object key.
     * @param {*} value2 The value from the second object key.
     * @returns {*} A new object containing properties from both value1 and
     *      value2.
     */
    static assign(value1, value2) {
        return Object.assign({}, value1, value2);
    }
}

exports.MergeStrategy = MergeStrategy;


code:
/**
 * @filedescription Object Schema
 */

"use strict";

//-----------------------------------------------------------------------------
// Requirements
//-----------------------------------------------------------------------------

const { MergeStrategy } = require("./merge-strategy");
const { ValidationStrategy } = require("./validation-strategy");

//-----------------------------------------------------------------------------
// Private
//-----------------------------------------------------------------------------

const strategies = Symbol("strategies");
const requiredKeys = Symbol("requiredKeys");

/**
 * Validates a schema strategy.
 * @param {string} name The name of the key this strategy is for.
 * @param {Object} strategy The strategy for the object key.
 * @param {boolean} [strategy.required=true] Whether the key is required.
 * @param {string[]} [strategy.requires] Other keys that are required when
 *      this key is present.
 * @param {Function} strategy.merge A method to call when merging two objects
 *      with the same key.
 * @param {Function} strategy.validate A method to call when validating an
 *      object with the key.
 * @returns {void}
 * @throws {Error} When the strategy is missing a name.
 * @throws {Error} When the strategy is missing a merge() method.
 * @throws {Error} When the strategy is missing a validate() method.
 */
function validateDefinition(name, strategy) {

    let hasSchema = false;
    if (strategy.schema) {
        if (typeof strategy.schema === "object") {
            hasSchema = true;
        } else {
            throw new TypeError("Schema must be an object.");
        }
    }

    if (typeof strategy.merge === "string") {
        if (!(strategy.merge in MergeStrategy)) {
            throw new TypeError(`Definition for key "${name}" missing valid merge strategy.`);
        }
    } else if (!hasSchema && typeof strategy.merge !== "function") {
        throw new TypeError(`Definition for key "${name}" must have a merge property.`);
    }

    if (typeof strategy.validate === "string") {
        if (!(strategy.validate in ValidationStrategy)) {
            throw new TypeError(`Definition for key "${name}" missing valid validation strategy.`);
        }
    } else if (!hasSchema && typeof strategy.validate !== "function") {
        throw new TypeError(`Definition for key "${name}" must have a validate() method.`);
    }
}

//-----------------------------------------------------------------------------
// Errors
//-----------------------------------------------------------------------------

/**
 * Error when an unexpected key is found.
 */
class UnexpectedKeyError extends Error {

    /**
     * Creates a new instance.
     * @param {string} key The key that was unexpected.
     */
    constructor(key) {
        super(`Unexpected key "${key}" found.`);
    }
}

/**
 * Error when a required key is missing.
 */
class MissingKeyError extends Error {

    /**
     * Creates a new instance.
     * @param {string} key The key that was missing.
     */
    constructor(key) {
        super(`Missing required key "${key}".`);
    }
}

/**
 * Error when a key requires other keys that are missing.
 */
class MissingDependentKeysError extends Error {

    /**
     * Creates a new instance.
     * @param {string} key The key that was unexpected.
     * @param {Array<string>} requiredKeys The keys that are required.
     */
    constructor(key, requiredKeys) {
        super(`Key "${key}" requires keys "${requiredKeys.join("\", \"")}".`);
    }
}

/**
 * Wrapper error for errors occuring during a merge or validate operation.
 */
class WrapperError extends Error {

    /**
     * Creates a new instance.
     * @param {string} key The object key causing the error.
     * @param {Error} source The source error.
     */
    constructor(key, source) {
        super(`Key "${key}": ${source.message}`, { cause: source });

        // copy over custom properties that aren't represented
        for (const key of Object.keys(source)) {
            if (!(key in this)) {
                this[key] = source[key];
            }
        }
    }
}

//-----------------------------------------------------------------------------
// Main
//-----------------------------------------------------------------------------

/**
 * Represents an object validation/merging schema.
 */
class ObjectSchema {

    /**
     * Creates a new instance.
     */
    constructor(definitions) {

        if (!definitions) {
            throw new Error("Schema definitions missing.");
        }

        /**
         * Track all strategies in the schema by key.
         * @type {Map}
         * @property strategies
         */
        this[strategies] = new Map();

        /**
         * Separately track any keys that are required for faster validation.
         * @type {Map}
         * @property requiredKeys
         */
        this[requiredKeys] = new Map();

        // add in all strategies
        for (const key of Object.keys(definitions)) {
            validateDefinition(key, definitions[key]);

            // normalize merge and validate methods if subschema is present
            if (typeof definitions[key].schema === "object") {
                const schema = new ObjectSchema(definitions[key].schema);
                definitions[key] = {
                    ...definitions[key],
                    merge(first = {}, second = {}) {
                        return schema.merge(first, second);
                    },
                    validate(value) {
                        ValidationStrategy.object(value);
                        schema.validate(value);
                    }
                };
            }

            // normalize the merge method in case there's a string
            if (typeof definitions[key].merge === "string") {
                definitions[key] = {
                    ...definitions[key],
                    merge: MergeStrategy[definitions[key].merge]
                };
            };

            // normalize the validate method in case there's a string
            if (typeof definitions[key].validate === "string") {
                definitions[key] = {
                    ...definitions[key],
                    validate: ValidationStrategy[definitions[key].validate]
                };
            };

            this[strategies].set(key, definitions[key]);

            if (definitions[key].required) {
                this[requiredKeys].set(key, definitions[key]);
            }
        }
    }

    /**
     * Determines if a strategy has been registered for the given object key.
     * @param {string} key The object key to find a strategy for.
     * @returns {boolean} True if the key has a strategy registered, false if not.
     */
    hasKey(key) {
        return this[strategies].has(key);
    }

    /**
     * Merges objects together to create a new object comprised of the keys
     * of the all objects. Keys are merged based on the each key's merge
     * strategy.
     * @param {...Object} objects The objects to merge.
     * @returns {Object} A new object with a mix of all objects' keys.
     * @throws {Error} If any object is invalid.
     */
    merge(...objects) {

        // double check arguments
        if (objects.length < 2) {
            throw new TypeError("merge() requires at least two arguments.");
        }

        if (objects.some(object => (object == null || typeof object !== "object"))) {
            throw new TypeError("All arguments must be objects.");
        }

        return objects.reduce((result, object) => {

            this.validate(object);

            for (const [key, strategy] of this[strategies]) {
                try {
                    if (key in result || key in object) {
                        const value = strategy.merge.call(this, result[key], object[key]);
                        if (value !== undefined) {
                            result[key] = value;
                        }
                    }
                } catch (ex) {
                    throw new WrapperError(key, ex);
                }
            }
            return result;
        }, {});
    }

    /**
     * Validates an object's keys based on the validate strategy for each key.
     * @param {Object} object The object to validate.
     * @returns {void}
     * @throws {Error} When the object is invalid.
     */
    validate(object) {

        // check existing keys first
        for (const key of Object.keys(object)) {

            // check to see if the key is defined
            if (!this.hasKey(key)) {
                throw new UnexpectedKeyError(key);
            }

            // validate existing keys
            const strategy = this[strategies].get(key);

            // first check to see if any other keys are required
            if (Array.isArray(strategy.requires)) {
                if (!strategy.requires.every(otherKey => otherKey in object)) {
                    throw new MissingDependentKeysError(key, strategy.requires);
                }
            }

            // now apply remaining validation strategy
            try {
                strategy.validate.call(strategy, object[key]);
            } catch (ex) {
                throw new WrapperError(key, ex);
            }
        }

        // ensure required keys aren't missing
        for (const [key] of this[requiredKeys]) {
            if (!(key in object)) {
                throw new MissingKeyError(key);
            }
        }

    }
}

exports.ObjectSchema = ObjectSchema;


code:
/**
 * @filedescription Validation Strategy
 */

"use strict";

//-----------------------------------------------------------------------------
// Class
//-----------------------------------------------------------------------------

/**
 * Container class for several different validation strategies.
 */
class ValidationStrategy {

    /**
     * Validates that a value is an array.
     * @param {*} value The value to validate.
     * @returns {void}
     * @throws {TypeError} If the value is invalid.
     */
    static array(value) {
        if (!Array.isArray(value)) {
            throw new TypeError("Expected an array.");
        }
    }

    /**
     * Validates that a value is a boolean.
     * @param {*} value The value to validate.
     * @returns {void}
     * @throws {TypeError} If the value is invalid.
     */
    static boolean(value) {
        if (typeof value !== "boolean") {
            throw new TypeError("Expected a Boolean.");
        }
    }

    /**
     * Validates that a value is a number.
     * @param {*} value The value to validate.
     * @returns {void}
     * @throws {TypeError} If the value is invalid.
     */
    static number(value) {
        if (typeof value !== "number") {
            throw new TypeError("Expected a number.");
        }
    }

    /**
     * Validates that a value is a object.
     * @param {*} value The value to validate.
     * @returns {void}
     * @throws {TypeError} If the value is invalid.
     */
    static object(value) {
        if (!value || typeof value !== "object") {
            throw new TypeError("Expected an object.");
        }
    }

    /**
     * Validates that a value is a object or null.
     * @param {*} value The value to validate.
     * @returns {void}
     * @throws {TypeError} If the value is invalid.
     */
    static "object?"(value) {
        if (typeof value !== "object") {
            throw new TypeError("Expected an object or null.");
        }
    }

    /**
     * Validates that a value is a string.
     * @param {*} value The value to validate.
     * @returns {void}
     * @throws {TypeError} If the value is invalid.
     */
    static string(value) {
        if (typeof value !== "string") {
            throw new TypeError("Expected a string.");
        }
    }

    /**
     * Validates that a value is a non-empty string.
     * @param {*} value The value to validate.
     * @returns {void}
     * @throws {TypeError} If the value is invalid.
     */
    static "string!"(value) {
        if (typeof value !== "string" || value.length === 0) {
            throw new TypeError("Expected a non-empty string.");
        }
    }

}

exports.ValidationStrategy = ValidationStrategy;


code:
# @jridgewell/gen-mapping

> Generate source maps

`gen-mapping` allows you to generate a source map during transpilation or minification.
With a source map, you're able to trace the original location in the source file, either in Chrome's
DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping].

You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This
provides the same `addMapping` and `setSourceContent` API.

## Installation

```sh
npm install @jridgewell/gen-mapping
```

## Usage

```typescript
import { GenMapping, addMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping';

const map = new GenMapping({
  file: 'output.js',
  sourceRoot: 'https://example.com/',
});

setSourceContent(map, 'input.js', `function foo() {}`);

addMapping(map, {
  // Lines start at line 1, columns at column 0.
  generated: { line: 1, column: 0 },
  source: 'input.js',
  original: { line: 1, column: 0 },
});

addMapping(map, {
  generated: { line: 1, column: 9 },
  source: 'input.js',
  original: { line: 1, column: 9 },
  name: 'foo',
});

assert.deepEqual(toDecodedMap(map), {
  version: 3,
  file: 'output.js',
  names: ['foo'],
  sourceRoot: 'https://example.com/',
  sources: ['input.js'],
  sourcesContent: ['function foo() {}'],
  mappings: [
    [ [0, 0, 0, 0], [9, 0, 0, 9, 0] ]
  ],
});

assert.deepEqual(toEncodedMap(map), {
  version: 3,
  file: 'output.js',
  names: ['foo'],
  sourceRoot: 'https://example.com/',
  sources: ['input.js'],
  sourcesContent: ['function foo() {}'],
  mappings: 'AAAA,SAASA',
});
```

### Smaller Sourcemaps

Not everything needs to be added to a sourcemap, and needless markings can cause signficantly
larger file sizes. `gen-mapping` exposes `maybeAddSegment`/`maybeAddMapping` APIs that will
intelligently determine if this marking adds useful information. If not, the marking will be
skipped.

```typescript
import { maybeAddMapping } from '@jridgewell/gen-mapping';

const map = new GenMapping();

// Adding a sourceless marking at the beginning of a line isn't useful.
maybeAddMapping(map, {
  generated: { line: 1, column: 0 },
});

// Adding a new source marking is useful.
maybeAddMapping(map, {
  generated: { line: 1, column: 0 },
  source: 'input.js',
  original: { line: 1, column: 0 },
});

// But adding another marking pointing to the exact same original location isn't, even if the
// generated column changed.
maybeAddMapping(map, {
  generated: { line: 1, column: 9 },
  source: 'input.js',
  original: { line: 1, column: 0 },
});

assert.deepEqual(toEncodedMap(map), {
  version: 3,
  names: [],
  sources: ['input.js'],
  sourcesContent: [null],
  mappings: 'AAAA',
});
```

## Benchmarks

```
node v18.0.0

amp.js.map
Memory Usage:
gen-mapping: addSegment      5852872 bytes
gen-mapping: addMapping      7716042 bytes
source-map-js                6143250 bytes
source-map-0.6.1             6124102 bytes
source-map-0.8.0             6121173 bytes
Smallest memory usage is gen-mapping: addSegment

Adding speed:
gen-mapping:      addSegment x 441 ops/sec ±2.07% (90 runs sampled)
gen-mapping:      addMapping x 350 ops/sec ±2.40% (86 runs sampled)
source-map-js:    addMapping x 169 ops/sec ±2.42% (80 runs sampled)
source-map-0.6.1: addMapping x 167 ops/sec ±2.56% (80 runs sampled)
source-map-0.8.0: addMapping x 168 ops/sec ±2.52% (80 runs sampled)
Fastest is gen-mapping:      addSegment

Generate speed:
gen-mapping:      decoded output x 150,824,370 ops/sec ±0.07% (102 runs sampled)
gen-mapping:      encoded output x 663 ops/sec ±0.22% (98 runs sampled)
source-map-js:    encoded output x 197 ops/sec ±0.45% (84 runs sampled)
source-map-0.6.1: encoded output x 198 ops/sec ±0.33% (85 runs sampled)
source-map-0.8.0: encoded output x 197 ops/sec ±0.06% (93 runs sampled)
Fastest is gen-mapping:      decoded output

***

babel.min.js.map
Memory Usage:
gen-mapping: addSegment     37578063 bytes
gen-mapping: addMapping     37212897 bytes
source-map-js               47638527 bytes
source-map-0.6.1            47690503 bytes
source-map-0.8.0            47470188 bytes
Smallest memory usage is gen-mapping: addMapping

Adding speed:
gen-mapping:      addSegment x 31.05 ops/sec ±8.31% (43 runs sampled)
gen-mapping:      addMapping x 29.83 ops/sec ±7.36% (51 runs sampled)
source-map-js:    addMapping x 20.73 ops/sec ±6.22% (38 runs sampled)
source-map-0.6.1: addMapping x 20.03 ops/sec ±10.51% (38 runs sampled)
source-map-0.8.0: addMapping x 19.30 ops/sec ±8.27% (37 runs sampled)
Fastest is gen-mapping:      addSegment

Generate speed:
gen-mapping:      decoded output x 381,379,234 ops/sec ±0.29% (96 runs sampled)
gen-mapping:      encoded output x 95.15 ops/sec ±2.98% (72 runs sampled)
source-map-js:    encoded output x 15.20 ops/sec ±7.41% (33 runs sampled)
source-map-0.6.1: encoded output x 16.36 ops/sec ±10.46% (31 runs sampled)
source-map-0.8.0: encoded output x 16.06 ops/sec ±6.45% (31 runs sampled)
Fastest is gen-mapping:      decoded output

***

preact.js.map
Memory Usage:
gen-mapping: addSegment       416247 bytes
gen-mapping: addMapping       419824 bytes
source-map-js                1024619 bytes
source-map-0.6.1             1146004 bytes
source-map-0.8.0             1113250 bytes
Smallest memory usage is gen-mapping: addSegment

Adding speed:
gen-mapping:      addSegment x 13,755 ops/sec ±0.15% (98 runs sampled)
gen-mapping:      addMapping x 13,013 ops/sec ±0.11% (101 runs sampled)
source-map-js:    addMapping x 4,564 ops/sec ±0.21% (98 runs sampled)
source-map-0.6.1: addMapping x 4,562 ops/sec ±0.11% (99 runs sampled)
source-map-0.8.0: addMapping x 4,593 ops/sec ±0.11% (100 runs sampled)
Fastest is gen-mapping:      addSegment

Generate speed:
gen-mapping:      decoded output x 379,864,020 ops/sec ±0.23% (93 runs sampled)
gen-mapping:      encoded output x 14,368 ops/sec ±4.07% (82 runs sampled)
source-map-js:    encoded output x 5,261 ops/sec ±0.21% (99 runs sampled)
source-map-0.6.1: encoded output x 5,124 ops/sec ±0.58% (99 runs sampled)
source-map-0.8.0: encoded output x 5,434 ops/sec ±0.33% (96 runs sampled)
Fastest is gen-mapping:      decoded output

***

react.js.map
Memory Usage:
gen-mapping: addSegment       975096 bytes
gen-mapping: addMapping      1102981 bytes
source-map-js                2918836 bytes
source-map-0.6.1             2885435 bytes
source-map-0.8.0             2874336 bytes
Smallest memory usage is gen-mapping: addSegment

Adding speed:
gen-mapping:      addSegment x 4,772 ops/sec ±0.15% (100 runs sampled)
gen-mapping:      addMapping x 4,456 ops/sec ±0.13% (97 runs sampled)
source-map-js:    addMapping x 1,618 ops/sec ±0.24% (97 runs sampled)
source-map-0.6.1: addMapping x 1,622 ops/sec ±0.12% (99 runs sampled)
source-map-0.8.0: addMapping x 1,631 ops/sec ±0.12% (100 runs sampled)
Fastest is gen-mapping:      addSegment

Generate speed:
gen-mapping:      decoded output x 379,107,695 ops/sec ±0.07% (99 runs sampled)
gen-mapping:      encoded output x 5,421 ops/sec ±1.60% (89 runs sampled)
source-map-js:    encoded output x 2,113 ops/sec ±1.81% (98 runs sampled)
source-map-0.6.1: encoded output x 2,126 ops/sec ±0.10% (100 runs sampled)
source-map-0.8.0: encoded output x 2,176 ops/sec ±0.39% (98 runs sampled)
Fastest is gen-mapping:      decoded output
```

[source-map]: https://www.npmjs.com/package/source-map
[trace-mapping]: https://github.com/jridgewell/trace-mapping


code:
import { SetArray, put, remove } from '@jridgewell/set-array';
import { encode } from '@jridgewell/sourcemap-codec';
import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';

const COLUMN = 0;
const SOURCES_INDEX = 1;
const SOURCE_LINE = 2;
const SOURCE_COLUMN = 3;
const NAMES_INDEX = 4;

const NO_NAME = -1;
/**
 * Provides the state to generate a sourcemap.
 */
class GenMapping {
    constructor({ file, sourceRoot } = {}) {
        this._names = new SetArray();
        this._sources = new SetArray();
        this._sourcesContent = [];
        this._mappings = [];
        this.file = file;
        this.sourceRoot = sourceRoot;
        this._ignoreList = new SetArray();
    }
}
/**
 * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
 * with public access modifiers.
 */
function cast(map) {
    return map;
}
function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
    return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
}
function addMapping(map, mapping) {
    return addMappingInternal(false, map, mapping);
}
/**
 * Same as `addSegment`, but will only add the segment if it generates useful information in the
 * resulting map. This only works correctly if segments are added **in order**, meaning you should
 * not add a segment with a lower generated line/column than one that came before.
 */
const maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
    return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
};
/**
 * Same as `addMapping`, but will only add the mapping if it generates useful information in the
 * resulting map. This only works correctly if mappings are added **in order**, meaning you should
 * not add a mapping with a lower generated line/column than one that came before.
 */
const maybeAddMapping = (map, mapping) => {
    return addMappingInternal(true, map, mapping);
};
/**
 * Adds/removes the content of the source file to the source map.
 */
function setSourceContent(map, source, content) {
    const { _sources: sources, _sourcesContent: sourcesContent } = cast(map);
    const index = put(sources, source);
    sourcesContent[index] = content;
}
function setIgnore(map, source, ignore = true) {
    const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map);
    const index = put(sources, source);
    if (index === sourcesContent.length)
        sourcesContent[index] = null;
    if (ignore)
        put(ignoreList, index);
    else
        remove(ignoreList, index);
}
/**
 * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
 * a sourcemap, or to JSON.stringify.
 */
function toDecodedMap(map) {
    const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList, } = cast(map);
    removeEmptyFinalLines(mappings);
    return {
        version: 3,
        file: map.file || undefined,
        names: names.array,
        sourceRoot: map.sourceRoot || undefined,
        sources: sources.array,
        sourcesContent,
        mappings,
        ignoreList: ignoreList.array,
    };
}
/**
 * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
 * a sourcemap, or to JSON.stringify.
 */
function toEncodedMap(map) {
    const decoded = toDecodedMap(map);
    return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
}
/**
 * Constructs a new GenMapping, using the already present mappings of the input.
 */
function fromMap(input) {
    const map = new TraceMap(input);
    const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });
    putAll(cast(gen)._names, map.names);
    putAll(cast(gen)._sources, map.sources);
    cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null);
    cast(gen)._mappings = decodedMappings(map);
    if (map.ignoreList)
        putAll(cast(gen)._ignoreList, map.ignoreList);
    return gen;
}
/**
 * Returns an array of high-level mapping objects for every recorded segment, which could then be
 * passed to the `source-map` library.
 */
function allMappings(map) {
    const out = [];
    const { _mappings: mappings, _sources: sources, _names: names } = cast(map);
    for (let i = 0; i < mappings.length; i++) {
        const line = mappings[i];
        for (let j = 0; j < line.length; j++) {
            const seg = line[j];
            const generated = { line: i + 1, column: seg[COLUMN] };
            let source = undefined;
            let original = undefined;
            let name = undefined;
            if (seg.length !== 1) {
                source = sources.array[seg[SOURCES_INDEX]];
                original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };
                if (seg.length === 5)
                    name = names.array[seg[NAMES_INDEX]];
            }
            out.push({ generated, source, original, name });
        }
    }
    return out;
}
// This split declaration is only so that terser can elminiate the static initialization block.
function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
    const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = cast(map);
    const line = getLine(mappings, genLine);
    const index = getColumnIndex(line, genColumn);
    if (!source) {
        if (skipable && skipSourceless(line, index))
            return;
        return insert(line, index, [genColumn]);
    }
    const sourcesIndex = put(sources, source);
    const namesIndex = name ? put(names, name) : NO_NAME;
    if (sourcesIndex === sourcesContent.length)
        sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
    if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
        return;
    }
    return insert(line, index, name
        ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
        : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
}
function getLine(mappings, index) {
    for (let i = mappings.length; i <= index; i++) {
        mappings[i] = [];
    }
    return mappings[index];
}
function getColumnIndex(line, genColumn) {
    let index = line.length;
    for (let i = index - 1; i >= 0; index = i--) {
        const current = line[i];
        if (genColumn >= current[COLUMN])
            break;
    }
    return index;
}
function insert(array, index, value) {
    for (let i = array.length; i > index; i--) {
        array[i] = array[i - 1];
    }
    array[index] = value;
}
function removeEmptyFinalLines(mappings) {
    const { length } = mappings;
    let len = length;
    for (let i = len - 1; i >= 0; len = i, i--) {
        if (mappings[i].length > 0)
            break;
    }
    if (len < length)
        mappings.length = len;
}
function putAll(setarr, array) {
    for (let i = 0; i < array.length; i++)
        put(setarr, array[i]);
}
function skipSourceless(line, index) {
    // The start of a line is already sourceless, so adding a sourceless segment to the beginning
    // doesn't generate any useful information.
    if (index === 0)
        return true;
    const prev = line[index - 1];
    // If the previous segment is also sourceless, then adding another sourceless segment doesn't
    // genrate any new information. Else, this segment will end the source/named segment and point to
    // a sourceless position, which is useful.
    return prev.length === 1;
}
function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
    // A source/named segment at the start of a line gives position at that genColumn
    if (index === 0)
        return false;
    const prev = line[index - 1];
    // If the previous segment is sourceless, then we're transitioning to a source.
    if (prev.length === 1)
        return false;
    // If the previous segment maps to the exact same source position, then this segment doesn't
    // provide any new position information.
    return (sourcesIndex === prev[SOURCES_INDEX] &&
        sourceLine === prev[SOURCE_LINE] &&
        sourceColumn === prev[SOURCE_COLUMN] &&
        namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
}
function addMappingInternal(skipable, map, mapping) {
    const { generated, source, original, name, content } = mapping;
    if (!source) {
        return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null);
    }
    return addSegmentInternal(skipable, map, generated.line - 1, generated.column, source, original.line - 1, original.column, name, content);
}

export { GenMapping, addMapping, addSegment, allMappings, fromMap, maybeAddMapping, maybeAddSegment, setIgnore, setSourceContent, toDecodedMap, toEncodedMap };
//# sourceMappingURL=gen-mapping.mjs.map


code:
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/set-array'), require('@jridgewell/sourcemap-codec'), require('@jridgewell/trace-mapping')) :
    typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/set-array', '@jridgewell/sourcemap-codec', '@jridgewell/trace-mapping'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.genMapping = {}, global.setArray, global.sourcemapCodec, global.traceMapping));
})(this, (function (exports, setArray, sourcemapCodec, traceMapping) { 'use strict';

    const COLUMN = 0;
    const SOURCES_INDEX = 1;
    const SOURCE_LINE = 2;
    const SOURCE_COLUMN = 3;
    const NAMES_INDEX = 4;

    const NO_NAME = -1;
    /**
     * Provides the state to generate a sourcemap.
     */
    class GenMapping {
        constructor({ file, sourceRoot } = {}) {
            this._names = new setArray.SetArray();
            this._sources = new setArray.SetArray();
            this._sourcesContent = [];
            this._mappings = [];
            this.file = file;
            this.sourceRoot = sourceRoot;
            this._ignoreList = new setArray.SetArray();
        }
    }
    /**
     * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
     * with public access modifiers.
     */
    function cast(map) {
        return map;
    }
    function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
        return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
    }
    function addMapping(map, mapping) {
        return addMappingInternal(false, map, mapping);
    }
    /**
     * Same as `addSegment`, but will only add the segment if it generates useful information in the
     * resulting map. This only works correctly if segments are added **in order**, meaning you should
     * not add a segment with a lower generated line/column than one that came before.
     */
    const maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
        return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
    };
    /**
     * Same as `addMapping`, but will only add the mapping if it generates useful information in the
     * resulting map. This only works correctly if mappings are added **in order**, meaning you should
     * not add a mapping with a lower generated line/column than one that came before.
     */
    const maybeAddMapping = (map, mapping) => {
        return addMappingInternal(true, map, mapping);
    };
    /**
     * Adds/removes the content of the source file to the source map.
     */
    function setSourceContent(map, source, content) {
        const { _sources: sources, _sourcesContent: sourcesContent } = cast(map);
        const index = setArray.put(sources, source);
        sourcesContent[index] = content;
    }
    function setIgnore(map, source, ignore = true) {
        const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map);
        const index = setArray.put(sources, source);
        if (index === sourcesContent.length)
            sourcesContent[index] = null;
        if (ignore)
            setArray.put(ignoreList, index);
        else
            setArray.remove(ignoreList, index);
    }
    /**
     * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
     * a sourcemap, or to JSON.stringify.
     */
    function toDecodedMap(map) {
        const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList, } = cast(map);
        removeEmptyFinalLines(mappings);
        return {
            version: 3,
            file: map.file || undefined,
            names: names.array,
            sourceRoot: map.sourceRoot || undefined,
            sources: sources.array,
            sourcesContent,
            mappings,
            ignoreList: ignoreList.array,
        };
    }
    /**
     * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
     * a sourcemap, or to JSON.stringify.
     */
    function toEncodedMap(map) {
        const decoded = toDecodedMap(map);
        return Object.assign(Object.assign({}, decoded), { mappings: sourcemapCodec.encode(decoded.mappings) });
    }
    /**
     * Constructs a new GenMapping, using the already present mappings of the input.
     */
    function fromMap(input) {
        const map = new traceMapping.TraceMap(input);
        const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });
        putAll(cast(gen)._names, map.names);
        putAll(cast(gen)._sources, map.sources);
        cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null);
        cast(gen)._mappings = traceMapping.decodedMappings(map);
        if (map.ignoreList)
            putAll(cast(gen)._ignoreList, map.ignoreList);
        return gen;
    }
    /**
     * Returns an array of high-level mapping objects for every recorded segment, which could then be
     * passed to the `source-map` library.
     */
    function allMappings(map) {
        const out = [];
        const { _mappings: mappings, _sources: sources, _names: names } = cast(map);
        for (let i = 0; i < mappings.length; i++) {
            const line = mappings[i];
            for (let j = 0; j < line.length; j++) {
                const seg = line[j];
                const generated = { line: i + 1, column: seg[COLUMN] };
                let source = undefined;
                let original = undefined;
                let name = undefined;
                if (seg.length !== 1) {
                    source = sources.array[seg[SOURCES_INDEX]];
                    original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };
                    if (seg.length === 5)
                        name = names.array[seg[NAMES_INDEX]];
                }
                out.push({ generated, source, original, name });
            }
        }
        return out;
    }
    // This split declaration is only so that terser can elminiate the static initialization block.
    function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
        const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = cast(map);
        const line = getLine(mappings, genLine);
        const index = getColumnIndex(line, genColumn);
        if (!source) {
            if (skipable && skipSourceless(line, index))
                return;
            return insert(line, index, [genColumn]);
        }
        const sourcesIndex = setArray.put(sources, source);
        const namesIndex = name ? setArray.put(names, name) : NO_NAME;
        if (sourcesIndex === sourcesContent.length)
            sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
        if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
            return;
        }
        return insert(line, index, name
            ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
            : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
    }
    function getLine(mappings, index) {
        for (let i = mappings.length; i <= index; i++) {
            mappings[i] = [];
        }
        return mappings[index];
    }
    function getColumnIndex(line, genColumn) {
        let index = line.length;
        for (let i = index - 1; i >= 0; index = i--) {
            const current = line[i];
            if (genColumn >= current[COLUMN])
                break;
        }
        return index;
    }
    function insert(array, index, value) {
        for (let i = array.length; i > index; i--) {
            array[i] = array[i - 1];
        }
        array[index] = value;
    }
    function removeEmptyFinalLines(mappings) {
        const { length } = mappings;
        let len = length;
        for (let i = len - 1; i >= 0; len = i, i--) {
            if (mappings[i].length > 0)
                break;
        }
        if (len < length)
            mappings.length = len;
    }
    function putAll(setarr, array) {
        for (let i = 0; i < array.length; i++)
            setArray.put(setarr, array[i]);
    }
    function skipSourceless(line, index) {
        // The start of a line is already sourceless, so adding a sourceless segment to the beginning
        // doesn't generate any useful information.
        if (index === 0)
            return true;
        const prev = line[index - 1];
        // If the previous segment is also sourceless, then adding another sourceless segment doesn't
        // genrate any new information. Else, this segment will end the source/named segment and point to
        // a sourceless position, which is useful.
        return prev.length === 1;
    }
    function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
        // A source/named segment at the start of a line gives position at that genColumn
        if (index === 0)
            return false;
        const prev = line[index - 1];
        // If the previous segment is sourceless, then we're transitioning to a source.
        if (prev.length === 1)
            return false;
        // If the previous segment maps to the exact same source position, then this segment doesn't
        // provide any new position information.
        return (sourcesIndex === prev[SOURCES_INDEX] &&
            sourceLine === prev[SOURCE_LINE] &&
            sourceColumn === prev[SOURCE_COLUMN] &&
            namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
    }
    function addMappingInternal(skipable, map, mapping) {
        const { generated, source, original, name, content } = mapping;
        if (!source) {
            return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null);
        }
        return addSegmentInternal(skipable, map, generated.line - 1, generated.column, source, original.line - 1, original.column, name, content);
    }

    exports.GenMapping = GenMapping;
    exports.addMapping = addMapping;
    exports.addSegment = addSegment;
    exports.allMappings = allMappings;
    exports.fromMap = fromMap;
    exports.maybeAddMapping = maybeAddMapping;
    exports.maybeAddSegment = maybeAddSegment;
    exports.setIgnore = setIgnore;
    exports.setSourceContent = setSourceContent;
    exports.toDecodedMap = toDecodedMap;
    exports.toEncodedMap = toEncodedMap;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=gen-mapping.umd.js.map


code:
import type { SourceMapInput } from '@jridgewell/trace-mapping';
import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';
export type { DecodedSourceMap, EncodedSourceMap, Mapping };
export declare type Options = {
    file?: string | null;
    sourceRoot?: string | null;
};
/**
 * Provides the state to generate a sourcemap.
 */
export declare class GenMapping {
    private _names;
    private _sources;
    private _sourcesContent;
    private _mappings;
    private _ignoreList;
    file: string | null | undefined;
    sourceRoot: string | null | undefined;
    constructor({ file, sourceRoot }?: Options);
}
/**
 * A low-level API to associate a generated position with an original source position. Line and
 * column here are 0-based, unlike `addMapping`.
 */
export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void;
export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void;
export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void;
/**
 * A high-level API to associate a generated position with an original source position. Line is
 * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.
 */
export declare function addMapping(map: GenMapping, mapping: {
    generated: Pos;
    source?: null;
    original?: null;
    name?: null;
    content?: null;
}): void;
export declare function addMapping(map: GenMapping, mapping: {
    generated: Pos;
    source: string;
    original: Pos;
    name?: null;
    content?: string | null;
}): void;
export declare function addMapping(map: GenMapping, mapping: {
    generated: Pos;
    source: string;
    original: Pos;
    name: string;
    content?: string | null;
}): void;
/**
 * Same as `addSegment`, but will only add the segment if it generates useful information in the
 * resulting map. This only works correctly if segments are added **in order**, meaning you should
 * not add a segment with a lower generated line/column than one that came before.
 */
export declare const maybeAddSegment: typeof addSegment;
/**
 * Same as `addMapping`, but will only add the mapping if it generates useful information in the
 * resulting map. This only works correctly if mappings are added **in order**, meaning you should
 * not add a mapping with a lower generated line/column than one that came before.
 */
export declare const maybeAddMapping: typeof addMapping;
/**
 * Adds/removes the content of the source file to the source map.
 */
export declare function setSourceContent(map: GenMapping, source: string, content: string | null): void;
export declare function setIgnore(map: GenMapping, source: string, ignore?: boolean): void;
/**
 * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
 * a sourcemap, or to JSON.stringify.
 */
export declare function toDecodedMap(map: GenMapping): DecodedSourceMap;
/**
 * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
 * a sourcemap, or to JSON.stringify.
 */
export declare function toEncodedMap(map: GenMapping): EncodedSourceMap;
/**
 * Constructs a new GenMapping, using the already present mappings of the input.
 */
export declare function fromMap(input: SourceMapInput): GenMapping;
/**
 * Returns an array of high-level mapping objects for every recorded segment, which could then be
 * passed to the `source-map` library.
 */
export declare function allMappings(map: GenMapping): Mapping[];


code:
declare type GeneratedColumn = number;
declare type SourcesIndex = number;
declare type SourceLine = number;
declare type SourceColumn = number;
declare type NamesIndex = number;
export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];
export declare const COLUMN = 0;
export declare const SOURCES_INDEX = 1;
export declare const SOURCE_LINE = 2;
export declare const SOURCE_COLUMN = 3;
export declare const NAMES_INDEX = 4;
export {};


code:
import type { SourceMapSegment } from './sourcemap-segment';
export interface SourceMapV3 {
    file?: string | null;
    names: readonly string[];
    sourceRoot?: string;
    sources: readonly (string | null)[];
    sourcesContent?: readonly (string | null)[];
    version: 3;
    ignoreList?: readonly number[];
}
export interface EncodedSourceMap extends SourceMapV3 {
    mappings: string;
}
export interface DecodedSourceMap extends SourceMapV3 {
    mappings: readonly SourceMapSegment[][];
}
export interface Pos {
    line: number;
    column: number;
}
export declare type Mapping = {
    generated: Pos;
    source: undefined;
    original: undefined;
    name: undefined;
} | {
    generated: Pos;
    source: string;
    original: Pos;
    name: string;
} | {
    generated: Pos;
    source: string;
    original: Pos;
    name: undefined;
};


@jridgewell/gen-mapping

description: Generate source maps

keywords: source map

license: MIT

benchmark: run-s build:rollup benchmark:*

benchmark:install: cd benchmark && npm install

benchmark:only: node benchmark/index.mjs

prebuild: rm -rf dist

build: run-s -n build:*

build:rollup: rollup -c rollup.config.js

build:ts: tsc --project tsconfig.build.json

lint: run-s -n lint:*

lint:prettier: npm run test:lint:prettier -- --write

lint:ts: npm run test:lint:ts -- --fix

test: run-s -n test:lint test:only

test:debug: mocha --inspect-brk

test:lint: run-s -n test:lint:*

test:lint:prettier: prettier --check '{src,test}/**/*.ts'

test:lint:ts: eslint '{src,test}/**/*.ts'

test:only: c8 mocha

test:watch: mocha --watch

prepublishOnly: npm run preversion

preversion: run-s test build


code:
# @jridgewell/resolve-uri

> Resolve a URI relative to an optional base URI

Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths.

## Installation

```sh
npm install @jridgewell/resolve-uri
```

## Usage

```typescript
function resolve(input: string, base?: string): string;
```

```js
import resolve from '@jridgewell/resolve-uri';

resolve('foo', 'https://example.com'); // => 'https://example.com/foo'
```

| Input                 | Base                    | Resolution                     | Explanation                                                  |
|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------|
| `https://example.com` | _any_                   | `https://example.com/`         | Input is normalized only                                     |
| `//example.com`       | `https://base.com/`     | `https://example.com/`         | Input inherits the base's protocol                           |
| `//example.com`       | _rest_                  | `//example.com/`               | Input is normalized only                                     |
| `/example`            | `https://base.com/`     | `https://base.com/example`     | Input inherits the base's origin                             |
| `/example`            | `//base.com/`           | `//base.com/example`           | Input inherits the base's host and remains protocol relative |
| `/example`            | _rest_                  | `/example`                     | Input is normalized only                                     |
| `example`             | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base                                |
| `example`             | `https://base.com/file` | `https://base.com/example`     | Input is joined with the base without its file               |
| `example`             | `//base.com/dir/`       | `//base.com/dir/example`       | Input is joined with the base's last directory               |
| `example`             | `//base.com/file`       | `//base.com/example`           | Input is joined with the base without its file               |
| `example`             | `/base/dir/`            | `/base/dir/example`            | Input is joined with the base's last directory               |
| `example`             | `/base/file`            | `/base/example`                | Input is joined with the base without its file               |
| `example`             | `base/dir/`             | `base/dir/example`             | Input is joined with the base's last directory               |
| `example`             | `base/file`             | `base/example`                 | Input is joined with the base without its file               |


code:
// Matches the scheme of a URL, eg "http://"
const schemeRegex = /^[\w+.-]+:\/\//;
/**
 * Matches the parts of a URL:
 * 1. Scheme, including ":", guaranteed.
 * 2. User/password, including "@", optional.
 * 3. Host, guaranteed.
 * 4. Port, including ":", optional.
 * 5. Path, including "/", optional.
 * 6. Query, including "?", optional.
 * 7. Hash, including "#", optional.
 */
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
/**
 * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
 * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
 *
 * 1. Host, optional.
 * 2. Path, which may include "/", guaranteed.
 * 3. Query, including "?", optional.
 * 4. Hash, including "#", optional.
 */
const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
function isAbsoluteUrl(input) {
    return schemeRegex.test(input);
}
function isSchemeRelativeUrl(input) {
    return input.startsWith('//');
}
function isAbsolutePath(input) {
    return input.startsWith('/');
}
function isFileUrl(input) {
    return input.startsWith('file:');
}
function isRelative(input) {
    return /^[.?#]/.test(input);
}
function parseAbsoluteUrl(input) {
    const match = urlRegex.exec(input);
    return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
}
function parseFileUrl(input) {
    const match = fileRegex.exec(input);
    const path = match[2];
    return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
}
function makeUrl(scheme, user, host, port, path, query, hash) {
    return {
        scheme,
        user,
        host,
        port,
        path,
        query,
        hash,
        type: 7 /* Absolute */,
    };
}
function parseUrl(input) {
    if (isSchemeRelativeUrl(input)) {
        const url = parseAbsoluteUrl('http:' + input);
        url.scheme = '';
        url.type = 6 /* SchemeRelative */;
        return url;
    }
    if (isAbsolutePath(input)) {
        const url = parseAbsoluteUrl('http://foo.com' + input);
        url.scheme = '';
        url.host = '';
        url.type = 5 /* AbsolutePath */;
        return url;
    }
    if (isFileUrl(input))
        return parseFileUrl(input);
    if (isAbsoluteUrl(input))
        return parseAbsoluteUrl(input);
    const url = parseAbsoluteUrl('http://foo.com/' + input);
    url.scheme = '';
    url.host = '';
    url.type = input
        ? input.startsWith('?')
            ? 3 /* Query */
            : input.startsWith('#')
                ? 2 /* Hash */
                : 4 /* RelativePath */
        : 1 /* Empty */;
    return url;
}
function stripPathFilename(path) {
    // If a path ends with a parent directory "..", then it's a relative path with excess parent
    // paths. It's not a file, so we can't strip it.
    if (path.endsWith('/..'))
        return path;
    const index = path.lastIndexOf('/');
    return path.slice(0, index + 1);
}
function mergePaths(url, base) {
    normalizePath(base, base.type);
    // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
    // path).
    if (url.path === '/') {
        url.path = base.path;
    }
    else {
        // Resolution happens relative to the base path's directory, not the file.
        url.path = stripPathFilename(base.path) + url.path;
    }
}
/**
 * The path can have empty directories "//", unneeded parents "foo/..", or current directory
 * "foo/.". We need to normalize to a standard representation.
 */
function normalizePath(url, type) {
    const rel = type <= 4 /* RelativePath */;
    const pieces = url.path.split('/');
    // We need to preserve the first piece always, so that we output a leading slash. The item at
    // pieces[0] is an empty string.
    let pointer = 1;
    // Positive is the number of real directories we've output, used for popping a parent directory.
    // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
    let positive = 0;
    // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
    // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
    // real directory, we won't need to append, unless the other conditions happen again.
    let addTrailingSlash = false;
    for (let i = 1; i < pieces.length; i++) {
        const piece = pieces[i];
        // An empty directory, could be a trailing slash, or just a double "//" in the path.
        if (!piece) {
            addTrailingSlash = true;
            continue;
        }
        // If we encounter a real directory, then we don't need to append anymore.
        addTrailingSlash = false;
        // A current directory, which we can always drop.
        if (piece === '.')
            continue;
        // A parent directory, we need to see if there are any real directories we can pop. Else, we
        // have an excess of parents, and we'll need to keep the "..".
        if (piece === '..') {
            if (positive) {
                addTrailingSlash = true;
                positive--;
                pointer--;
            }
            else if (rel) {
                // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
                // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
                pieces[pointer++] = piece;
            }
            continue;
        }
        // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
        // any popped or dropped directories.
        pieces[pointer++] = piece;
        positive++;
    }
    let path = '';
    for (let i = 1; i < pointer; i++) {
        path += '/' + pieces[i];
    }
    if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
        path += '/';
    }
    url.path = path;
}
/**
 * Attempts to resolve `input` URL/path relative to `base`.
 */
function resolve(input, base) {
    if (!input && !base)
        return '';
    const url = parseUrl(input);
    let inputType = url.type;
    if (base && inputType !== 7 /* Absolute */) {
        const baseUrl = parseUrl(base);
        const baseType = baseUrl.type;
        switch (inputType) {
            case 1 /* Empty */:
                url.hash = baseUrl.hash;
            // fall through
            case 2 /* Hash */:
                url.query = baseUrl.query;
            // fall through
            case 3 /* Query */:
            case 4 /* RelativePath */:
                mergePaths(url, baseUrl);
            // fall through
            case 5 /* AbsolutePath */:
                // The host, user, and port are joined, you can't copy one without the others.
                url.user = baseUrl.user;
                url.host = baseUrl.host;
                url.port = baseUrl.port;
            // fall through
            case 6 /* SchemeRelative */:
                // The input doesn't have a schema at least, so we need to copy at least that over.
                url.scheme = baseUrl.scheme;
        }
        if (baseType > inputType)
            inputType = baseType;
    }
    normalizePath(url, inputType);
    const queryHash = url.query + url.hash;
    switch (inputType) {
        // This is impossible, because of the empty checks at the start of the function.
        // case UrlType.Empty:
        case 2 /* Hash */:
        case 3 /* Query */:
            return queryHash;
        case 4 /* RelativePath */: {
            // The first char is always a "/", and we need it to be relative.
            const path = url.path.slice(1);
            if (!path)
                return queryHash || '.';
            if (isRelative(base || input) && !isRelative(path)) {
                // If base started with a leading ".", or there is no base and input started with a ".",
                // then we need to ensure that the relative path starts with a ".". We don't know if
                // relative starts with a "..", though, so check before prepending.
                return './' + path + queryHash;
            }
            return path + queryHash;
        }
        case 5 /* AbsolutePath */:
            return url.path + queryHash;
        default:
            return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
    }
}

export { resolve as default };
//# sourceMappingURL=resolve-uri.mjs.map


code:
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory());
})(this, (function () { 'use strict';

    // Matches the scheme of a URL, eg "http://"
    const schemeRegex = /^[\w+.-]+:\/\//;
    /**
     * Matches the parts of a URL:
     * 1. Scheme, including ":", guaranteed.
     * 2. User/password, including "@", optional.
     * 3. Host, guaranteed.
     * 4. Port, including ":", optional.
     * 5. Path, including "/", optional.
     * 6. Query, including "?", optional.
     * 7. Hash, including "#", optional.
     */
    const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
    /**
     * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
     * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
     *
     * 1. Host, optional.
     * 2. Path, which may include "/", guaranteed.
     * 3. Query, including "?", optional.
     * 4. Hash, including "#", optional.
     */
    const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
    function isAbsoluteUrl(input) {
        return schemeRegex.test(input);
    }
    function isSchemeRelativeUrl(input) {
        return input.startsWith('//');
    }
    function isAbsolutePath(input) {
        return input.startsWith('/');
    }
    function isFileUrl(input) {
        return input.startsWith('file:');
    }
    function isRelative(input) {
        return /^[.?#]/.test(input);
    }
    function parseAbsoluteUrl(input) {
        const match = urlRegex.exec(input);
        return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
    }
    function parseFileUrl(input) {
        const match = fileRegex.exec(input);
        const path = match[2];
        return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
    }
    function makeUrl(scheme, user, host, port, path, query, hash) {
        return {
            scheme,
            user,
            host,
            port,
            path,
            query,
            hash,
            type: 7 /* Absolute */,
        };
    }
    function parseUrl(input) {
        if (isSchemeRelativeUrl(input)) {
            const url = parseAbsoluteUrl('http:' + input);
            url.scheme = '';
            url.type = 6 /* SchemeRelative */;
            return url;
        }
        if (isAbsolutePath(input)) {
            const url = parseAbsoluteUrl('http://foo.com' + input);
            url.scheme = '';
            url.host = '';
            url.type = 5 /* AbsolutePath */;
            return url;
        }
        if (isFileUrl(input))
            return parseFileUrl(input);
        if (isAbsoluteUrl(input))
            return parseAbsoluteUrl(input);
        const url = parseAbsoluteUrl('http://foo.com/' + input);
        url.scheme = '';
        url.host = '';
        url.type = input
            ? input.startsWith('?')
                ? 3 /* Query */
                : input.startsWith('#')
                    ? 2 /* Hash */
                    : 4 /* RelativePath */
            : 1 /* Empty */;
        return url;
    }
    function stripPathFilename(path) {
        // If a path ends with a parent directory "..", then it's a relative path with excess parent
        // paths. It's not a file, so we can't strip it.
        if (path.endsWith('/..'))
            return path;
        const index = path.lastIndexOf('/');
        return path.slice(0, index + 1);
    }
    function mergePaths(url, base) {
        normalizePath(base, base.type);
        // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
        // path).
        if (url.path === '/') {
            url.path = base.path;
        }
        else {
            // Resolution happens relative to the base path's directory, not the file.
            url.path = stripPathFilename(base.path) + url.path;
        }
    }
    /**
     * The path can have empty directories "//", unneeded parents "foo/..", or current directory
     * "foo/.". We need to normalize to a standard representation.
     */
    function normalizePath(url, type) {
        const rel = type <= 4 /* RelativePath */;
        const pieces = url.path.split('/');
        // We need to preserve the first piece always, so that we output a leading slash. The item at
        // pieces[0] is an empty string.
        let pointer = 1;
        // Positive is the number of real directories we've output, used for popping a parent directory.
        // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
        let positive = 0;
        // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
        // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
        // real directory, we won't need to append, unless the other conditions happen again.
        let addTrailingSlash = false;
        for (let i = 1; i < pieces.length; i++) {
            const piece = pieces[i];
            // An empty directory, could be a trailing slash, or just a double "//" in the path.
            if (!piece) {
                addTrailingSlash = true;
                continue;
            }
            // If we encounter a real directory, then we don't need to append anymore.
            addTrailingSlash = false;
            // A current directory, which we can always drop.
            if (piece === '.')
                continue;
            // A parent directory, we need to see if there are any real directories we can pop. Else, we
            // have an excess of parents, and we'll need to keep the "..".
            if (piece === '..') {
                if (positive) {
                    addTrailingSlash = true;
                    positive--;
                    pointer--;
                }
                else if (rel) {
                    // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
                    // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
                    pieces[pointer++] = piece;
                }
                continue;
            }
            // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
            // any popped or dropped directories.
            pieces[pointer++] = piece;
            positive++;
        }
        let path = '';
        for (let i = 1; i < pointer; i++) {
            path += '/' + pieces[i];
        }
        if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
            path += '/';
        }
        url.path = path;
    }
    /**
     * Attempts to resolve `input` URL/path relative to `base`.
     */
    function resolve(input, base) {
        if (!input && !base)
            return '';
        const url = parseUrl(input);
        let inputType = url.type;
        if (base && inputType !== 7 /* Absolute */) {
            const baseUrl = parseUrl(base);
            const baseType = baseUrl.type;
            switch (inputType) {
                case 1 /* Empty */:
                    url.hash = baseUrl.hash;
                // fall through
                case 2 /* Hash */:
                    url.query = baseUrl.query;
                // fall through
                case 3 /* Query */:
                case 4 /* RelativePath */:
                    mergePaths(url, baseUrl);
                // fall through
                case 5 /* AbsolutePath */:
                    // The host, user, and port are joined, you can't copy one without the others.
                    url.user = baseUrl.user;
                    url.host = baseUrl.host;
                    url.port = baseUrl.port;
                // fall through
                case 6 /* SchemeRelative */:
                    // The input doesn't have a schema at least, so we need to copy at least that over.
                    url.scheme = baseUrl.scheme;
            }
            if (baseType > inputType)
                inputType = baseType;
        }
        normalizePath(url, inputType);
        const queryHash = url.query + url.hash;
        switch (inputType) {
            // This is impossible, because of the empty checks at the start of the function.
            // case UrlType.Empty:
            case 2 /* Hash */:
            case 3 /* Query */:
                return queryHash;
            case 4 /* RelativePath */: {
                // The first char is always a "/", and we need it to be relative.
                const path = url.path.slice(1);
                if (!path)
                    return queryHash || '.';
                if (isRelative(base || input) && !isRelative(path)) {
                    // If base started with a leading ".", or there is no base and input started with a ".",
                    // then we need to ensure that the relative path starts with a ".". We don't know if
                    // relative starts with a "..", though, so check before prepending.
                    return './' + path + queryHash;
                }
                return path + queryHash;
            }
            case 5 /* AbsolutePath */:
                return url.path + queryHash;
            default:
                return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
        }
    }

    return resolve;

}));
//# sourceMappingURL=resolve-uri.umd.js.map


code:
/**
 * Attempts to resolve `input` URL/path relative to `base`.
 */
export default function resolve(input: string, base: string | undefined): string;


@jridgewell/resolve-uri

description: Resolve a URI relative to an optional base URI

keywords: resolve uri url path

pretest: run-s build:rollup

test:only: mocha

test:coverage: c8 mocha


code:
# @jridgewell/set-array

> Like a Set, but provides the index of the `key` in the backing array

This is designed to allow synchronizing a second array with the contents of the backing array, like
how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, and there
are never duplicates.

## Installation

```sh
npm install @jridgewell/set-array
```

## Usage

```js
import { SetArray, get, put, pop } from '@jridgewell/set-array';

const sa = new SetArray();

let index = put(sa, 'first');
assert.strictEqual(index, 0);

index = put(sa, 'second');
assert.strictEqual(index, 1);

assert.deepEqual(sa.array, [ 'first', 'second' ]);

index = get(sa, 'first');
assert.strictEqual(index, 0);

pop(sa);
index = get(sa, 'second');
assert.strictEqual(index, undefined);
assert.deepEqual(sa.array, [ 'first' ]);
```


code:
/**
 * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
 * index of the `key` in the backing array.
 *
 * This is designed to allow synchronizing a second array with the contents of the backing array,
 * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
 * and there are never duplicates.
 */
class SetArray {
    constructor() {
        this._indexes = { __proto__: null };
        this.array = [];
    }
}
/**
 * Typescript doesn't allow friend access to private fields, so this just casts the set into a type
 * with public access modifiers.
 */
function cast(set) {
    return set;
}
/**
 * Gets the index associated with `key` in the backing array, if it is already present.
 */
function get(setarr, key) {
    return cast(setarr)._indexes[key];
}
/**
 * Puts `key` into the backing array, if it is not already present. Returns
 * the index of the `key` in the backing array.
 */
function put(setarr, key) {
    // The key may or may not be present. If it is present, it's a number.
    const index = get(setarr, key);
    if (index !== undefined)
        return index;
    const { array, _indexes: indexes } = cast(setarr);
    const length = array.push(key);
    return (indexes[key] = length - 1);
}
/**
 * Pops the last added item out of the SetArray.
 */
function pop(setarr) {
    const { array, _indexes: indexes } = cast(setarr);
    if (array.length === 0)
        return;
    const last = array.pop();
    indexes[last] = undefined;
}
/**
 * Removes the key, if it exists in the set.
 */
function remove(setarr, key) {
    const index = get(setarr, key);
    if (index === undefined)
        return;
    const { array, _indexes: indexes } = cast(setarr);
    for (let i = index + 1; i < array.length; i++) {
        const k = array[i];
        array[i - 1] = k;
        indexes[k]--;
    }
    indexes[key] = undefined;
    array.pop();
}

export { SetArray, get, pop, put, remove };
//# sourceMappingURL=set-array.mjs.map


code:
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.setArray = {}));
})(this, (function (exports) { 'use strict';

    /**
     * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
     * index of the `key` in the backing array.
     *
     * This is designed to allow synchronizing a second array with the contents of the backing array,
     * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
     * and there are never duplicates.
     */
    class SetArray {
        constructor() {
            this._indexes = { __proto__: null };
            this.array = [];
        }
    }
    /**
     * Typescript doesn't allow friend access to private fields, so this just casts the set into a type
     * with public access modifiers.
     */
    function cast(set) {
        return set;
    }
    /**
     * Gets the index associated with `key` in the backing array, if it is already present.
     */
    function get(setarr, key) {
        return cast(setarr)._indexes[key];
    }
    /**
     * Puts `key` into the backing array, if it is not already present. Returns
     * the index of the `key` in the backing array.
     */
    function put(setarr, key) {
        // The key may or may not be present. If it is present, it's a number.
        const index = get(setarr, key);
        if (index !== undefined)
            return index;
        const { array, _indexes: indexes } = cast(setarr);
        const length = array.push(key);
        return (indexes[key] = length - 1);
    }
    /**
     * Pops the last added item out of the SetArray.
     */
    function pop(setarr) {
        const { array, _indexes: indexes } = cast(setarr);
        if (array.length === 0)
            return;
        const last = array.pop();
        indexes[last] = undefined;
    }
    /**
     * Removes the key, if it exists in the set.
     */
    function remove(setarr, key) {
        const index = get(setarr, key);
        if (index === undefined)
            return;
        const { array, _indexes: indexes } = cast(setarr);
        for (let i = index + 1; i < array.length; i++) {
            const k = array[i];
            array[i - 1] = k;
            indexes[k]--;
        }
        indexes[key] = undefined;
        array.pop();
    }

    exports.SetArray = SetArray;
    exports.get = get;
    exports.pop = pop;
    exports.put = put;
    exports.remove = remove;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=set-array.umd.js.map


code:
declare type Key = string | number | symbol;
/**
 * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
 * index of the `key` in the backing array.
 *
 * This is designed to allow synchronizing a second array with the contents of the backing array,
 * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
 * and there are never duplicates.
 */
export declare class SetArray<T extends Key = Key> {
    private _indexes;
    array: readonly T[];
    constructor();
}
/**
 * Gets the index associated with `key` in the backing array, if it is already present.
 */
export declare function get<T extends Key>(setarr: SetArray<T>, key: T): number | undefined;
/**
 * Puts `key` into the backing array, if it is not already present. Returns
 * the index of the `key` in the backing array.
 */
export declare function put<T extends Key>(setarr: SetArray<T>, key: T): number;
/**
 * Pops the last added item out of the SetArray.
 */
export declare function pop<T extends Key>(setarr: SetArray<T>): void;
/**
 * Removes the key, if it exists in the set.
 */
export declare function remove<T extends Key>(setarr: SetArray<T>, key: T): void;
export {};


@jridgewell/set-array

description: Like a Set, but provides the index of the `key` in the backing array


code:
# @jridgewell/source-map

> Packages `@jridgewell/trace-mapping` and `@jridgewell/gen-mapping` into the familiar source-map API

This isn't the full API, but it's the core functionality. This wraps
[@jridgewell/trace-mapping][trace-mapping] and [@jridgewell/gen-mapping][gen-mapping]
implementations.

## Installation

```sh
npm install @jridgewell/source-map
```

## Usage

TODO

### SourceMapConsumer

```typescript
import { SourceMapConsumer } from '@jridgewell/source-map';
const smc = new SourceMapConsumer({
  version: 3,
  names: ['foo'],
  sources: ['input.js'],
  mappings: 'AAAAA',
});
```

#### SourceMapConsumer.fromSourceMap(mapGenerator[, mapUrl])

Transforms a `SourceMapGenerator` into a `SourceMapConsumer`.

```typescript
const smg = new SourceMapGenerator();

const smc = SourceMapConsumer.fromSourceMap(map);
smc.originalPositionFor({ line: 1, column: 0 });
```

#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)

```typescript
const smc = new SourceMapConsumer(map);
smc.originalPositionFor({ line: 1, column: 0 });
```

#### SourceMapConsumer.prototype.mappings

```typescript
const smc = new SourceMapConsumer(map);
smc.mappings; // AAAA
```

#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)

```typescript
const smc = new SourceMapConsumer(map);
smc.allGeneratedpositionsfor({ line: 1, column: 5, source: "baz.ts" });
// [
//   { line: 2, column: 8 }
// ]
```

#### SourceMapConsumer.prototype.eachMapping(callback[, context[, order]])

> This implementation currently does not support the "order" parameter.
> This function can only iterate in Generated order.

```typescript
const smc = new SourceMapConsumer(map);
smc.eachMapping((mapping) => {
// { source: 'baz.ts',
//   generatedLine: 4,
//   generatedColumn: 5,
//   originalLine: 4,
//   originalColumn: 5,
//   name: null }
});
```

#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)

```typescript
const smc = new SourceMapConsumer(map);
smc.generatedPositionFor({ line: 1, column: 5, source: "baz.ts" });
// { line: 2, column: 8 }
```

#### SourceMapConsumer.prototype.hasContentsOfAllSources()

```typescript
const smc = new SourceMapConsumer(map);
smc.hasContentsOfAllSources();
// true
```

#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])

```typescript
const smc = new SourceMapConsumer(map);
smc.generatedPositionFor("baz.ts");
// "export default ..."
```

#### SourceMapConsumer.prototype.version

Returns the source map's version

### SourceMapGenerator

```typescript
import { SourceMapGenerator } from '@jridgewell/source-map';
const smg = new SourceMapGenerator({
  file: 'output.js',
  sourceRoot: 'https://example.com/',
});
```

#### SourceMapGenerator.fromSourceMap(map)

Transform a `SourceMapConsumer` into a `SourceMapGenerator`.

```typescript
const smc = new SourceMapConsumer();
const smg = SourceMapGenerator.fromSourceMap(smc);
```

#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])

> This method is not implemented yet

#### SourceMapGenerator.prototype.addMapping(mapping)

```typescript
const smg = new SourceMapGenerator();
smg.addMapping({
  generated: { line: 1, column: 0 },
  source: 'input.js',
  original: { line: 1, column: 0 },
  name: 'foo',
});
```

#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)

```typescript
const smg = new SourceMapGenerator();
smg.setSourceContent('input.js', 'foobar');
```

#### SourceMapGenerator.prototype.toJSON()

```typescript
const smg = new SourceMapGenerator();
smg.toJSON(); // { version: 3, names: [], sources: [], mappings: '' }
```

#### SourceMapGenerator.prototype.toString()

```typescript
const smg = new SourceMapGenerator();
smg.toJSON(); // "{version:3,names:[],sources:[],mappings:''}"
```

#### SourceMapGenerator.prototype.toDecodedMap()

```typescript
const smg = new SourceMapGenerator();
smg.toDecodedMap(); // { version: 3, names: [], sources: [], mappings: [] }
```

## Known differences with other implementations

This implementation has some differences with `source-map` and `source-map-js`.

- `SourceMapConsumer.prototype.eachMapping()`
  - Does not support the `order` argument
- `SourceMapGenerator.prototype.applySourceMap()`
  - Not implemented

[trace-mapping]: https://github.com/jridgewell/trace-mapping/
[gen-mapping]: https://github.com/jridgewell/gen-mapping/


code:
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var traceMapping = require('@jridgewell/trace-mapping');
var genMapping = require('@jridgewell/gen-mapping');

class SourceMapConsumer {
    constructor(map, mapUrl) {
        const trace = (this._map = new traceMapping.AnyMap(map, mapUrl));
        this.file = trace.file;
        this.names = trace.names;
        this.sourceRoot = trace.sourceRoot;
        this.sources = trace.resolvedSources;
        this.sourcesContent = trace.sourcesContent;
        this.version = trace.version;
    }
    static fromSourceMap(map, mapUrl) {
        // This is more performant if we receive
        // a @jridgewell/source-map SourceMapGenerator
        if (map.toDecodedMap) {
            return new SourceMapConsumer(map.toDecodedMap(), mapUrl);
        }
        // This is a fallback for `source-map` and `source-map-js`
        return new SourceMapConsumer(map.toJSON(), mapUrl);
    }
    get mappings() {
        return traceMapping.encodedMappings(this._map);
    }
    originalPositionFor(needle) {
        return traceMapping.originalPositionFor(this._map, needle);
    }
    generatedPositionFor(originalPosition) {
        return traceMapping.generatedPositionFor(this._map, originalPosition);
    }
    allGeneratedPositionsFor(originalPosition) {
        return traceMapping.allGeneratedPositionsFor(this._map, originalPosition);
    }
    hasContentsOfAllSources() {
        if (!this.sourcesContent || this.sourcesContent.length !== this.sources.length) {
            return false;
        }
        for (const content of this.sourcesContent) {
            if (content == null) {
                return false;
            }
        }
        return true;
    }
    sourceContentFor(source, nullOnMissing) {
        const sourceContent = traceMapping.sourceContentFor(this._map, source);
        if (sourceContent != null) {
            return sourceContent;
        }
        if (nullOnMissing) {
            return null;
        }
        throw new Error(`"${source}" is not in the SourceMap.`);
    }
    eachMapping(callback, context /*, order?: number*/) {
        // order is ignored as @jridgewell/trace-map doesn't implement it
        traceMapping.eachMapping(this._map, context ? callback.bind(context) : callback);
    }
    destroy() {
        // noop.
    }
}
class SourceMapGenerator {
    constructor(opts) {
        // TODO :: should this be duck-typed ?
        this._map = opts instanceof genMapping.GenMapping ? opts : new genMapping.GenMapping(opts);
    }
    static fromSourceMap(consumer) {
        return new SourceMapGenerator(genMapping.fromMap(consumer));
    }
    addMapping(mapping) {
        genMapping.maybeAddMapping(this._map, mapping);
    }
    setSourceContent(source, content) {
        genMapping.setSourceContent(this._map, source, content);
    }
    toJSON() {
        return genMapping.toEncodedMap(this._map);
    }
    toString() {
        return JSON.stringify(this.toJSON());
    }
    toDecodedMap() {
        return genMapping.toDecodedMap(this._map);
    }
}

exports.SourceMapConsumer = SourceMapConsumer;
exports.SourceMapGenerator = SourceMapGenerator;
//# sourceMappingURL=source-map.cjs.map


code:
import { AnyMap, encodedMappings, originalPositionFor, generatedPositionFor, allGeneratedPositionsFor, sourceContentFor, eachMapping } from '@jridgewell/trace-mapping';
import { GenMapping, fromMap, maybeAddMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping';

class SourceMapConsumer {
    constructor(map, mapUrl) {
        const trace = (this._map = new AnyMap(map, mapUrl));
        this.file = trace.file;
        this.names = trace.names;
        this.sourceRoot = trace.sourceRoot;
        this.sources = trace.resolvedSources;
        this.sourcesContent = trace.sourcesContent;
        this.version = trace.version;
    }
    static fromSourceMap(map, mapUrl) {
        // This is more performant if we receive
        // a @jridgewell/source-map SourceMapGenerator
        if (map.toDecodedMap) {
            return new SourceMapConsumer(map.toDecodedMap(), mapUrl);
        }
        // This is a fallback for `source-map` and `source-map-js`
        return new SourceMapConsumer(map.toJSON(), mapUrl);
    }
    get mappings() {
        return encodedMappings(this._map);
    }
    originalPositionFor(needle) {
        return originalPositionFor(this._map, needle);
    }
    generatedPositionFor(originalPosition) {
        return generatedPositionFor(this._map, originalPosition);
    }
    allGeneratedPositionsFor(originalPosition) {
        return allGeneratedPositionsFor(this._map, originalPosition);
    }
    hasContentsOfAllSources() {
        if (!this.sourcesContent || this.sourcesContent.length !== this.sources.length) {
            return false;
        }
        for (const content of this.sourcesContent) {
            if (content == null) {
                return false;
            }
        }
        return true;
    }
    sourceContentFor(source, nullOnMissing) {
        const sourceContent = sourceContentFor(this._map, source);
        if (sourceContent != null) {
            return sourceContent;
        }
        if (nullOnMissing) {
            return null;
        }
        throw new Error(`"${source}" is not in the SourceMap.`);
    }
    eachMapping(callback, context /*, order?: number*/) {
        // order is ignored as @jridgewell/trace-map doesn't implement it
        eachMapping(this._map, context ? callback.bind(context) : callback);
    }
    destroy() {
        // noop.
    }
}
class SourceMapGenerator {
    constructor(opts) {
        // TODO :: should this be duck-typed ?
        this._map = opts instanceof GenMapping ? opts : new GenMapping(opts);
    }
    static fromSourceMap(consumer) {
        return new SourceMapGenerator(fromMap(consumer));
    }
    addMapping(mapping) {
        maybeAddMapping(this._map, mapping);
    }
    setSourceContent(source, content) {
        setSourceContent(this._map, source, content);
    }
    toJSON() {
        return toEncodedMap(this._map);
    }
    toString() {
        return JSON.stringify(this.toJSON());
    }
    toDecodedMap() {
        return toDecodedMap(this._map);
    }
}

export { SourceMapConsumer, SourceMapGenerator };
//# sourceMappingURL=source-map.mjs.map