Last commit july 5th

This commit is contained in:
2024-07-05 13:46:23 +02:00
parent dad0d86e8c
commit b0e4dfbb76
24982 changed files with 2621219 additions and 413 deletions

69
spa/node_modules/resolve-url-loader/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,69 @@
# resolve-url-loader
## Version 5
**Features**
* Update `postcss` and completely remove `rework` parser.
**Breaking Changes**
* Require `node@>=12`.
* Support `webpack@>=4` (no longer tested for earlier versions).
* The `engine` option has been removed.
**Migrating**
Remove the `engine` option if you are using it.
## Version 4
**Features**
* Better resolution of the original source location - You can more successfully use `url()` in variables and mixins.
* Dependencies now accept a wider range and explicit dependency on `rework` and `rework-visit` has been removed.
**Breaking Changes**
* The `engine` option is deprecated which means the old `rework` engine is deprecated.
* The `keepQuery` behaviour is now the default, the `keepQuery` option has been removed.
* The `removeCR` option defaults to `true` when executing on Windows OS.
* The `absolute` option has been removed.
* The `join` option has changed.
**Migrating**
Remove the `engine` option if you are using it - the default "postcss" engine is much more reliable. The "rework" engine will still work for now but will be removed in the next major version.
Remove the `keepQuery` option if you are using it.
Remove the `absolute` option, webpack should work fine without it. If you have a specific need to rebase `url()` then you should use a separate loader.
If you use a custom `join` function then you will need to refactor it to the new API. Refer to the advanced usage documentation.
If you wish to still use `engine: "rework"` then note that `rework` and `rework-visit` packages are now `peerDependencies` that must be explicitly installed by you.
## Version 3
**Features**
* Use `postcss` parser by default. This is long overdue as the old `rework` parser doesn't cope with modern css.
* Lots of automated tests running actual webpack builds. If you have an interesting use-case let me know.
**Breaking Changes**
* Multiple options changed or deprecated.
* Removed file search "magic" in favour of `join` option.
* Errors always fail and are no longer swallowed.
* Processing absolute asset paths requires `root` option to be set.
**Migrating**
Initially set option `engine: 'rework'` for parity with your existing build. Once working you can remove this option **or** set `engine: 'postcss'` explicitly.
Retain `keepQuery` option if you are already using it.
The `root` option now has a different meaning. Previously it limited file search. Now it is the base path for absolute or root-relative URIs, consistent with `css-loader`. If you are already using it you can probably remove it.
If you build on Windows platform **and** your content contains absolute asset paths, then `css-loader` could fail. The `root` option here may fix the URIs before they get to `css-loader`. Try to leave it unspecified, otherwise (windows only) set to empty string `root: ''`.

21
spa/node_modules/resolve-url-loader/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

136
spa/node_modules/resolve-url-loader/README.md generated vendored Normal file
View File

@@ -0,0 +1,136 @@
# Resolve URL Loader
[![NPM](https://nodei.co/npm/resolve-url-loader.png)](https://www.npmjs.com/package/resolve-url-loader)
This **webpack loader** allows you to have a distributed set SCSS files and assets co-located with those SCSS files.
## Do you organise your SCSS and assets by feature?
Where are your assets?
* ✅ I want my assets all over the place, next to my SCSS files.
* ❌ My assets are in a single directory.
How complicated is your SASS?
* ✅ I have a deep SASS composition with partials importing other partials.
* ✅ My asset paths are constructed by functions or `@mixin`s.
* ❌ I have a single SCSS file. The asset paths are just explicit in that.
What asset paths are you using?
* ✅ Fully relative `url(./foo.png)` or `url(foo.png)`
* ❌ Root relative `url(/foo.png)`
* ❌ Relative to some package or webpack root `url(~stuff/foo.png`)
* ❌ Relative to some variable which is your single asset directory `url($variable/foo.png)`
What webpack errors are you getting?
* ✅ Webpack can't find the relative asset `foo.png` 😞
* ❌ Webpack says it doesn't have a loader for `fully/resolved/path/foo.png` 😕
If you can tick at least 1 item in **all of these questions** then use this loader. It will allow webpack to find assets with **fully relative paths**.
If for any question you can't tick _any_ items then webpack should be able to already find your assets. You don't need this loader. 🤷
Once webpack resolves your assets (even if it complains about loading them) then this loading is working correctly. 👍
## What's the problem with SASS?
When you use **fully relative paths** in `url()` statements then Webpack expects to find those assets next to the root SCSS file, regardless of where you specify the `url()`.
To illustrate here are 3 simple examples of SASS and Webpack _without_ `resolve-url-loader`.
[![the basic problem](https://raw.githubusercontent.com/bholloway/resolve-url-loader/v5/packages/resolve-url-loader/docs/basic-problem.svg)](docs/basic-problem.svg)
The first 2 cases are trivial and work fine. The asset is specified in the root SCSS file and Webpack finds it.
But any practical SASS composition will have nested SCSS files, as in the 3rd case. Here Webpack cannot find the asset.
```
Module not found: Can't resolve './cool.png' in '/absolute/path/.../my-project/src/styles.scss'
```
The path we present to Webpack really needs to be `./subdir/cool.png` but we don't want to write that in our SCSS. 😒
Luckily we can use `resolve-url-loader` to do the **url re-writing** and make it work. 😊🎉
With functions and mixins and multiple nesting it gets more complicated. Read more detail in [how the loader works](docs/how-it-works.md). 🤓
## Getting started
> **Upgrading?** the [changelog](CHANGELOG.md) shows how to migrate your webpack config.
### Install
via npm
```bash
npm install resolve-url-loader --save-dev
```
via yarn
```bash
yarn add resolve-url-loader --dev
```
### Configure Webpack
The typical use case is `resolve-url-loader` between `sass-loader` and `css-loader`.
**⚠️ IMPORTANT**
* **source-maps required** for loaders preceding `resolve-url-loader` (regardless of `devtool`).
* Always use **full loader package name** (don't omit `-loader`) otherwise you can get errors that are hard to debug.
``` javascript
rules: [
{
test: /\.scss$/,
use: [
...
{
loader: 'css-loader',
options: {...}
}, {
loader: 'resolve-url-loader',
options: {...}
}, {
loader: 'sass-loader',
options: {
sourceMap: true, // <-- !!IMPORTANT!!
}
}
]
},
...
]
```
## Options
The loader should work without options but use these as required.
| option | type | default | | description |
|-------------|----------|-----------------------------------------|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `sourceMap` | boolean | `false` | | Generate an outgoing source-map. |
| `removeCR` | boolean | `true` Windows OS<br/>`false` otherwise | | Convert orphan CR to whitespace.<br/>See known issues below. |
| `debug` | boolean | `false` | | Display debug information. |
| `silent` | boolean | `false` | | Do **not** display warnings or deprecation messages. |
| `root` | string | _unset_ | | Similar to the (now defunct) option in `css-loader`.<br/>This string, possibly empty, is prepended to absolute URIs.<br/>Absolute URIs are only processed if this option is set. |
| `join` | function | _inbuilt_ | advanced | Custom join function.<br/>Use custom javascript to fix asset paths on a per-case basis.<br/>Refer to the [advanced features](docs/advanced-features.md) docs. |
## Limitations
### Compatibility
Tested `macOS` and `Windows`.
All `webpack@4`-`webpack@5` with contemporaneous loaders/plugins using `node@12`.
Refer to `test` directory for full webpack configurations as used in automated tests.
### Known issues
Read the [troubleshooting](docs/troubleshooting.md) docs before raising an issue.

View File

@@ -0,0 +1,397 @@
# Advanced Features
All the advanced features of this loader involve customising the `join` option.
Jump to the **"how to"** section -
* [How to: change precedence of source locations](#how-to-change-precedence-of-source-locations)
* [How to: fallback to a theme or other global directory](#how-to-fallback-to-a-theme-or-other-global-directory)
* [How to: fallback to some other asset file](#how-to-fallback-to-some-other-asset-file)
* [How to: perform a file-system search for an asset](#how-to-perform-a-file-system-search-for-an-asset)
## What is the "join" function?
The "join" function determines how CSS URIs are combined with one of the possible base paths the algorithm has identified.
⚠️ **IMPORTANT** - First read how the [algorithm](./how-it-works.md#algorithm) works.
The "join" function is a higher-order function created using the `options` and `loader` reference. That gives a function that accepts a single `item` and synchronously returns an absolute asset path to substitute back into the original CSS.
```javascript
(options:{}, loader:{}) =>
(item:{ uri:string, query: string, isAbsolute: boolean, bases:{} }) =>
string | null
```
Where the `bases` are absolute directory paths `{ subString, value, property, selector }` per the [algorithm](./how-it-works.md#algorithm). Note that returning `null` implies no substitution, the original relative `uri` is retained.
The job of the "join" function is to consider possible locations for the asset based on the `bases` and determine which is most appropriate. This implies some order of precedence in these locations and some file-system operation to determine if the asset there.
The default implementation is suitable for most users but can be customised per the `join` option.
A custom `join` function from scratch is possible but we've provided some [building blocks](#building-blocks) to make the task easier.
## Building blocks
There are a number of utilities (defined in [`lib/join-function/index.js`](../lib/join-function/index.js)) to help construct a custom "join" function . These are conveniently re-exported as properties of the loader.
These utilities are used to create the `defaultJoin` as follows.
```javascript
const {
createJoinFunction,
createJoinImplementation,
defaultJoinGenerator,
} = require('resolve-url-loader');
// create a join function equivalent to "defaultJoin"
const myJoinFn = createJoinFunction(
'myJoinFn',
createJoinImplementation(defaultJoinGenerator),
});
```
🤓 If you have some very specific behaviour in mind you can specify your own implementation. This gives full control but still gives you `debug` logging for free.
```javascript
createJoinFunction = (name:string, implementation: function): function
```
For each item, the implementation needs to make multiple attempts at locating the asset. It has mixed concerns of itentifying locations to search and then evaluating those locates one by one.
👉 However its recommended to instead use `createJoinImplementation` to create the `implementation` using the `generator` concept.
```javascript
createJoinImplementation = (generator: function*): function
```
The `generator` has the single concern of identifying locations to search. The work of searching these locations is done by `createJoinImplementation`. Overall this means less boilerplate code for you to write.
Don't worry, you don't need to use `function*` semantics for the `generator` unless you want to.
## Simple customisation
It is relatively simple to change the precedence of values (from the [algorithm](./how-it-works.md#algorithm)) or add further locations to search for an asset. To do this we use `createJoinImplementation` and write a custom `generator`.
See the reference or jump directly to the [examples](#how-to-change-precedence-of-source-locations).
### Reference
The `generator` identifies `[base:string,uri:string]` tuples describing locations to search for an asset. It does **not** return the final asset path.
You may lazily generate tuples as `Iterator`. Refer to this [guide on Iterators and Generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators).
```javascript
generator = function* (item: {}, options: {}, loader: {}): Iterator<[string,string]>
```
Or it can be simpler to write a function that returns `Array` and convert it to a generator using `asGenerator`.
```javascript
generator = asGenerator( function (item: {}, options: {}, loader: {}): Array<string> )
```
```javascript
generator = asGenerator( function (item: {}, options: {}, loader: {}): Array<[string,string]> )
```
When using `asGenerator` you may return elements as either `base:string` **or** `[base:string,uri:string]` tuples.
<details>
<summary>Arguments</summary>
* `item` consist of -
* `uri: string` is the argument to the `url()` as it appears in the source file.
* `query: string` is any query or hash string starting with `?` or `#` that suffixes the `uri`
* `isAbsolute: boolean` flag indicates whether the URI is considered an absolute file or root relative path by webpack's definition. Absolute URIs are only processed if the `root` option is specified.
* `bases: {}` are a hash where the keys are the sourcemap evaluation locations in the [algorithm](./how-it-works.md#algorithm) and the values are absolute paths that the sourcemap reports. These directories might not actually exist.
* `options` consist of -
* All documented options for the loader.
* Any other values you include in the loader configuration for your own purposes.
* `loader` consists of the webpack loader API, useful items include -
* `fs: {}` the virtual file-system from Webpack.
* `resourcePath: string` the source file currently being processed.
* returns an `Iterator` with elements of `[base:string,uri:string]` either intrinsically or by using `asGenerator`.
</details>
<details>
<summary>FAQ</summary>
* **Why a tuple?**
The primary pupose of this loader is to find the correct `base` path for your `uri`. By returning a list of paths to search we can better generate `debug` logging.
That said there are cases where you might want to amend the `uri`. The solution is to make each element a tuple of `base` and `uri` representing a potential location to find the asset.
If you're interested only in the `base` path and don't intend to vary the `uri` then the `asGenerator` utility saves you having to create repetative tuples (and from using `function*` semantics).
* **Can I vary the `query` using the tuple?**
No. We don't support amending the `query` in the final value. If you would like this enhancement please open an issue.
* **What about duplicate or falsey elements?**
The `createJoinImplementation` will eliminate any invalid elements regardless of whether you use `Array` or `Iterator`. This makes it possible to `&&` elements inline with a predicate value.
If you use `Array` then `asGenerator` will also remove duplicates.
* **When should I use `function*`?**
If you need lazy generation of values then you may return `Iterator` or use `function*` semantics. Refer to [this guide on Iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators).
But in most cases, when the values are known apriori, simply returning `Array` has simpler semantics making `asGenerator` preferable.
* **Why is this generator so complicated?**
The join function must make multiple attempts to join a `base` and `uri` and check that the file exists using webpack `fs`.
The `generator` is focussed on identifying locations to search. It is a more scalable concept where you wish to search many places. The traditional use case for the custom "join" function is a file-system search so the `generator` was designed to make this possible.
If you prefer a less abstract approach consider a full `implementation` per the [full customisation](#full-customisation) approach.
</details>
### How to: change precedence of source locations
Source-map sampling is limited to the locations defined in the [algorithm](./how-it-works.md#algorithm). You can't change these locations but you can preference them in a different order.
This example shows the default order which you can easily amend. Absolute URIs are rare in most projects but can be handled for completeness.
**Using `asGenerator`**
```javascript
const {
createJoinFunction,
createJoinImplementation,
asGenerator,
defaultJoinGenerator,
} = require('resolve-url-loader');
// order source-map sampling location by your preferred precedence (matches defaultJoinGenerator)
const myGenerator = asGenerator(
({ isAbsolute, bases: { substring, value, property, selector} }, { root }) =>
isAbsolute ? [root] : [subString, value, property, selector]
);
const myJoinFn = createJoinFunction(
'myJoinFn',
createJoinImplementation(myGenerator),
);
```
**Notes**
* The implementation is the default behaviour, so if you want this precedence do **not** customise the `join` option.
* Absolute URIs generally use the base path given in the `root` option as shown.
* The `asGenerator` utility allows us to return simple `Array<string>` of potential base paths.
### How to: fallback to a theme or other global directory
Additional locations can be added by decorating the default generator. This is popular for adding some sort of "theme" directory containing assets.
This example appends a static theme directory as a fallback location where the asset might reside. Absolute URIs are rare in most projects but can be handled for completeness.
**Using `asGenerator`**
```javascript
const path = require('path');
const {
createJoinFunction,
createJoinImplementation,
asGenerator,
defaultJoinGenerator,
} = require('resolve-url-loader');
const myThemeDirectory = path.resolve(...);
// call default generator then append any additional paths
const myGenerator = asGenerator(
(item, ...rest) => [
...defaultJoinGenerator(item, ...rest),
item.isAbsolute ? null : myThemeDirectory,
]
);
const myJoinFn = createJoinFunction(
'myJoinFn',
createJoinImplementation(myGenerator),
);
```
**Notes**
* By spreading the result of `defaultJoinGenerator` we are first trying the default behaviour. If that is unsuccessful we then try the theme location.
* It's assumed that theming doesn't apply to absolute URIs. Since falsey elements are ignored we can easily `null` the additional theme element inline as shown.
* The `asGenerator` utility allows us to return simple `Array<string>` of potential base paths.
### How to: fallback to some other asset file
Lets imagine we don't have high quality files for all our assets and must sometimes use a lower quality format. For each item we need to try the `uri` with different file extensions. We can do this by returning tuples of `[base:string,uri:string]`.
In this example we prefer the `.svg` asset we are happy to use any available `.png` or `.jpg` instead.
**Using `asGenerator`**
```javascript
const {
createJoinFunction,
createJoinImplementation,
asGenerator,
defaultJoinGenerator,
} = require('resolve-url-loader');
// call default generator then pair different variations of uri with each base
const myGenerator = asGenerator(
(item, ...rest) => {
const defaultTuples = [...defaultJoinGenerator(item, ...rest)];
return /\.svg$/.test(item.uri)
? ['.svg', '.png', 'jpg'].flatMap((ext) =>
defaultTuples.flatMap(([base, uri]) =>
[base, uri.replace(/\.svg$/, ext)]
})
)
: defaultTuples;
}
);
const myJoinFn = createJoinFunction(
'myJoinFn',
createJoinImplementation(myGenerator),
);
```
**Using `function*`**
```javascript
const {
createJoinFunction,
createJoinImplementation,
defaultJoinGenerator,
} = require('resolve-url-loader');
// call default generator then pair different variations of uri with each base
const myGenerator = function* (item, ...rest) {
if (/\.svg$/.test(item.uri)) {
for (let ext of ['.svg', '.png', 'jpg']) {
for (let [base, uri] of defaultJoinGenerator(item, ...rest)) {
yield [base, uri.replace(/\.svg$/, ext)];
}
}
} else {
for (let value of defaultJoinGenerator(item, ...rest)) {
yield value;
}
}
}
const myJoinFn = createJoinFunction(
'myJoinFn',
createJoinImplementation(myGenerator),
);
```
**Notes**
* Existing generators such as `defaultJoinGenerator` will always return `[string,string]` tuples so we can destruture `base` and `uri` values with confidence.
* This implementation attempts all extensions for a given `base` before moving to the next `base`. Obviously we may change the nesting and instead do the oposite, attempt all bases for a single extension before moving on to the next extension
* The `asGenerator` utility allows us to return `Array<[string, string]>` but is **not** needed when we use `function*` semantics.
### How to: perform a file-system search for an asset
⚠️ **IMPORTANT** - This example is indicative only and is **not** advised.
When this loader was originally released it was very common for packages be broken to the point that a full file search was needed to locate assets referred to in CSS. While this was not performant some users really liked it. By customising the `generator` we can once again lazily search the file-system.
In this example we search the parent directories of the base paths, continuing upwards until we hit a package boundary. Absolute URIs are rare in most projects but can be handled for completeness.
**Using `function*`**
```javascript
const path = require('path');
const {
createJoinFunction,
createJoinImplementation,
webpackExistsSync
} = require('resolve-url-loader');
// search up from the initial base path until you hit a package boundary
const myGenerator = function* (
{ uri, isAbsolute, bases: { substring, value, property, selector } },
{ root, attempts = 1e3 },
{ fs },
) {
if (isAbsolute) {
yield [root, uri];
} else {
for (let base of [subString, value, property, selector]) {
for (let isDone = false, i = 0; !isDone && i < attempts; i++) {
yield [base, uri];
// unfortunately fs.existsSync() is not present so we must shim it
const maybePkg = path.normalize(path.join(base, 'package.json'));
try {
isDone = fs.statSync(maybePkg).isFile();
} catch (error) {
isDone = false;
}
base = base.split(/(\\\/)/).slice(0, -2).join('');
}
}
}
};
const myJoinFn = createJoinFunction(
'myJoinFn',
createJoinImplementation(myGenerator),
);
```
**Notes**
* This implementation is nether tested nor robust, it would need further safeguards to avoid searching the entire file system.
* By using `function*` the generator is lazy. We only walk the file-system directory tree as necessary.
* The webpack file-system is provided by the `enhanced-resolver-plugin` and does **not** contain `fs.existsSync()`. We must use `fs.statsSync()` instead and catch any error where the file isn't present.
* You may set additional `options` when you configure the loader in webpack and then access them in your `generator`. In this case we add an `attempts` option to limit the file search.
## Full customisation
The `createJoinFunction` can give you full control over how the `base` and `uri` are joined to create an absolute file path **and** the definitiion of success for that combination.
It provides additional logging when using `debug` option so is a better choice then writing a "join" function from scratch.
Limited documentation is given here since it is rare to require a full customisation. Refer to the source code for further information.
### Reference
The `implementation` synchronously returns the final asset path or some fallback value. It makes a number of attempts to search for the given item and returns an element describing each attempt.
```javascript
implementation = function (item: {}, options: {}, loader: {}):
Array<{
base : string,
uri : string,
joined : string,
isSuccess : boolean,
isFallback: boolean,
}>
```
<details>
<summary>Arguments</summary>
* `item` consist of -
* `uri: string` is the argument to the `url()` as it appears in the source file.
* `query: string` is any string starting with `?` or `#` that suffixes the `uri`
* `isAbsolute: boolean` flag indicates whether the URI is considered an absolute file or root relative path by webpack's definition. Absolute URIs are only processed if the `root` option is specified.
* `bases: {}` are a hash where the keys are the sourcemap evaluation locations in the [algorithm](./how-it-works.md#algorithm) and the values are absolute paths that the sourcemap reports. These directories might not actually exist.
* `options` consist of -
* All documented options for the loader.
* Any other values you include in the loader configuration for your own purposes.
* `loader` consists of the webpack loader API, useful items include -
* `fs: {}` the virtual file-system from Webpack.
* `resourcePath: string` the source file currently being processed.
* returns an array of attempts that were made in resolving the URI -
* `base` the base path
* `uri` the uri path
* `joined` the absolute path created from the joining the `base` and `uri` paths.
* `isSuccess` indicates the asset was found and that `joined` should be the final result
* `isFallback` indicates the asset was not found but that `joined` kis suitable as a fallback value
</details>

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 19 KiB

View File

@@ -0,0 +1 @@
# Contributing

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -0,0 +1,159 @@
# How it works
## The problem
The `resolve-url-loader` is typically used where SASS source files are transpiled to CSS. CSS being a format that webpack can readily ingest. So let's look at a basic example where the structure is basically CSS but is composed using SASS features.
Working backwards, this is the final CSS we are after. Just a single rule with a single declaration.
```css
.cool {
background-image: url(cool.png);
}
```
When using SASS it's common for rules to come from different [partials](https://sass-lang.com/documentation/at-rules/import#partials), and for declarations to be composed using mixins and functions. Consider this more complicated project with imported files.
<img src="detailed-problem.svg" alt="the detailed problem" width="363px" height="651px">
All the subdirectories here contributed something to the rule, so we could reasonably place the asset in any of them. And any of these locations might be the "correct" to our way of thinking.
There could actually be a separate `cool.png` in each of the subdirectories! 🤯 In that case, which one gets used?
The answer: none. 😞 Webpack expects asset paths to be relative to the root SASS file `src/styles.scss`. So for the CSS `url(cool.png)` it will look for `src/cool.png` which is not present. 💥
All our assets are in subdirecties `src/foo/cool.png` or `src/foo/bar/cool.png` or `src/foo/bar/baz/cool.png`. We need to re-write the `url()` to point to the one we intend. But right now that's pretty ambiguous.
Worse still, Webpack doesn't know any of these nested SCSS files were part of the SASS composition. Meaing it doesn't know there _are_ nested directories in the first place. How do we rewite to something we don't know about?
**The problem:** How to identify contributing directectories and look for the asset in those directories in some well-defined priority order?
**The crux:** How to identify what contributed to the SASS compilation, internally and post factum, but from within Webpack? 😫
## The solution
Sourcemaps! 😃
Wait, don't run away! Sourcemaps might sound scary, but they solve our problem reasonably well. 👍
The SASS compiler source-map can tell us which original SCSS file contributed each character in the resulting CSS.
The SASS source-map is also something we can access from within Webpack.
### concept
Continuing with the example let's compile SASS on the command line. You can do this several different ways but I prefer [npx](https://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner).
```sh
> npx node-sass src/styles.scss --output . --output-style expanded --source-map true
```
Using the experimental `sourcemap-to-string` package (also in this repository) we can visualise the SASS source on the left vs the output CSS on the right.
```
src/styles.scss
-------------------------------------------------------------------------------
src/foo/_partial.scss
-------------------------------------------------------------------------------
3:01 .cool░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 1:01 .cool░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
3:06 ░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 1:06 ░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░
3:07 ░░░░░░{⏎ 1:07 ░░░░░░{⏎
@include cool-background-image;⏎ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
-:-- ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 3:02 ░⏎
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ⏎
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ /*# sourceMappingURL=styles.css.ma
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ p */░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
src/foo/bar/_mixins.scss
-------------------------------------------------------------------------------
4:03 ░░background-image░░░░░░░░░░░░░░░░ 2:03 ░░background-image░░░░░░░░░░░░░░░░
4:19 ░░░░░░░░░░░░░░░░░░: get-url("cool" 2:19 ░░░░░░░░░░░░░░░░░░: ░░░░░░░░░░░░░░
);⏎ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}⏎ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
src/foo/bar/baz/_functions.scss
-------------------------------------------------------------------------------
2:11 ░░░░░░░░░░url(#░░░░░░░░░░░░░░░░░░░ 2:21 ░░░░░░░░░░░░░░░░░░░░url(cool.png)░
2:16 ░░░░░░░░░░░░░░░{$temp}.png);⏎ 2:34 ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░;
}░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ⏎
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ }░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
```
As expected, the pure CSS portions are essentially the same in the source and the output.
Meanwhile the indirect `@mixin` and `funtion` substitutes values into the output. But we can still clearly see where in the source that final value originated from.
### algorithm
Now we know the original SCSS sources we can use a CSS parser such as `postcss` to process all the declaration values that contain `url()` and rewrite any file paths we find there.
1. Enumerate all declaration values
2. Split the value into path substrings
3. Evaluate the source-map at that location, find the original source file
4. Rebase the path to that original source file.
For our example, this algorithm will always give us the asset located in the `baz` subdirectory. Clearly evaluating the source-map at just one location is not enough. Any of the directories that contributed source files to the rule-set might be considered the "correct" place to store the asset and all these files contributed different parts of the rule-set, not just the declaration value.
We stop short of evaluating the source-map for _every characer_ in the rule-set and instead we chose a small number of meaningful points.
| | label | sampling location | in the example | implies asset |
|---|-----------|------------------------------------------|---------------------------|--------------------------------------------------|
| 1 | subString | start of **argument** to the `url()` | `c` in `cool.png` | `src/foo/bar/baz/cool.png` |
| 2 | value | start of **value** in the declaration | `u` in `url(...)` | `src/foo/bar/baz/cool.png` |
| 3 | property | start of **property** in the declaration | `b` in `background-image` | `src/foo/bar/cool.png` |
| 4 | selector | start of **selector** in the rule-set | `.` in `.selector` | `src/foo/cool.png` |
These locations are tested in order. If an asset of the correct filename is found then we break and use that result.
Note it is a quirk of the example that the `value` and `subString` locations imply the same file. In a more complex example this may not be true.
If necessary the order can be customised or a custom file search (starting at each location) be implemented. Refer to the [advanced features](advanced-features.md).
### webpack
To operate on the `sass-loader` output, both **CSS** and **source-map**, we introduce `resolve-url-loader` containing the algorithm above.
The `resolve-url-loader` rewrites asset paths found in `url()` notation using the `postcss` parser.
This webpack configuration outlines some important points.
```javascript
rules: [
{
test: /\.scss$/,
use: [
{
loader: 'css-loader' // <-- assets are identified here
}, {
loader: 'resolve-url-loader' // <-- receives CSS and source-map from SASS compile
}, {
loader: 'sass-loader',
options: {
sourceMap: true, // <-- IMPORTANT!
sourceMapContents: false
}
}
],
},
...
{
test: /\.png$/, // <-- assets needs their own loader configuration
use: [ ... ]
}
]
```
Its essential to explicitly configure the `sass-loader` for `sourceMap: true`. That way we definitely get a sourcemap from upstream SASS loader all the time, not just in developement mode or where `devtool` is used.
Once the CSS reaches the `css-loader` webpack becomes aware of each of the asset files and will try to separately load and process them. You will need more Webpack configuration to make that work. Refer to the [troubleshooting docs](troubleshooting.md) before raising an issue.
### beyond...?
The implementation here is limited to the webpack loader but it's plausible the algorithm could be realised as a `postcss` plugin in isolation using the [root.input.map](https://postcss.org/api/#postcss-input) property to access the incomming source-map.
As a separate plugin it could be combined with other plugins in a single `postcss-loader` step. Processing multiple plugins together in this way without reparsing would arguably be more efficient.
However as a Webpack loader we have full access to the loader API and the virtual file-system. This means maximum compatibility with `webpack-dev-server` and the rest of the Webpack ecosystem.

View File

@@ -0,0 +1,71 @@
# Troubleshooting
Webpack is difficult to configure simply because it is so powerful. If you face a problem it is important to raise it in the right place.
Possibly whatever problem you are facing is _not_ an issue with this loader, so please work this list before raising an issue.
**Working with a framework**
1. Check to see if that framework is still using an older version with the `rework` engine. This will not support modern CSS and is the source of most problems. Usually there is an existing issue raised in that framework and there may be workarounds there.
2. Hack the framework code in your `node_modules` to diagose the root cause.
**Creating your own webpack config**
1. Do the checklist at the top of the page - do you _need_ to use this loader?
2. Read and understand the detail on [how the loader works](how-it-works.md).
3. Check the known-issues below.
4. Use the `debug` option to see where the loader is looking for your assets.
5. Temporarily remove this loader and use non-relative asset paths to check if the problem is something else.
6. Check [stack overflow](http://stackoverflow.com/search?q=resolve-url-loader) for an answer.
7. Review [previous issues](/issues?utf8=%E2%9C%93&q=is%3Aissue) that may be similar.
8. Try to recreate the problem with a minimum breaking example project.
I'm happy this loader helps so many people. Open-source is provided as-is and I'm currently **not** [dogfooding](https://en.wikipedia.org/wiki/Eating_your_own_dog_food) this loader in my own work, so please try not project your frustrations. There are some really great people who follow this project who can help.
## Known issues
### Support for `image-set()`
Right now this loader only rewrites `url()` statements.
If you need other statements processed, such as `image-set()`, then please upvote [issue #119](issues/119).
### Absolute URIs
By "absolute URIs" we more correctly mean assets with root-relative URLs or absolute file paths. These paths are **not** processed unless a `root` is specified.
However any paths that _are_ processed will have windows back-slash converted to posix forward-slash. This can be useful since some webpack loaders can choke on windows paths. By using `root: ''` then `resolve-url-loader` effectively does nothing to absolute paths except change the windows backslash.
**💡 Protip** In **windows** if your downstream loaders are choking on windows paths using `root: ''` can help.
Also it be useful to process absolute URIs if you have a custom `join` function and want to process all the paths. Although this is perhaps better done with some separate `postcss` plugin.
### Windows line breaks
Normal windows linebreaks are `CRLF`. But sometimes libsass will output single `CR` characters.
This problem is specific to multiline declarations. Refer to the [libsass bug #2693](https://github.com/sass/libsass/issues/2693).
If you have _any_ such multiline declarations preceding `url()` statements it will fail your build.
Libsass doesn't consider these orphan `CR` to be newlines but `postcss` engine does. The result being an offset in source-map line-numbers which crashes `resolve-url-loader`.
```
Module build failed: Error: resolve-url-loader: error processing CSS
source-map information is not available at url() declaration
```
Some users find the node-sass `linefeed` option solves the problem.
**Solutions**
* Try the node-sass [linefeed](https://github.com/sass/node-sass#linefeed--v300) option by way of `sass-loader`.
**Work arounds**
* Enable `removeCR` option [here](../README.md#options) (enabled by default on Window OS).
* Remove linebreaks in declarations in your `.scss` sources.
**Diagnosis**
1. Run a stand-alone sass build `npx node-sass index.scss output.css`.
2. Use a hex editor to check line endings `Format-Hex output.css`.
3. Expect `0DOA` (or desired) line endings. Single `0D` confirms this problem.

292
spa/node_modules/resolve-url-loader/index.js generated vendored Normal file
View File

@@ -0,0 +1,292 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
const os = require('os');
const path = require('path');
const fs = require('fs');
const util = require('util');
const loaderUtils = require('loader-utils');
const SourceMapConsumer = require('source-map').SourceMapConsumer;
const adjustSourceMap = require('adjust-sourcemap-loader/lib/process');
const valueProcessor = require('./lib/value-processor');
const joinFn = require('./lib/join-function');
const logToTestHarness = require('./lib/log-to-test-harness');
const DEPRECATED_OPTIONS = {
engine: [
'DEP_RESOLVE_URL_LOADER_OPTION_ENGINE',
'"engine" option has been removed, postcss is the only parser used'
],
keepQuery: [
'DEP_RESOLVE_URL_LOADER_OPTION_KEEP_QUERY',
'"keepQuery" option has been removed, the query and/or hash are now always retained'
],
absolute: [
'DEP_RESOLVE_URL_LOADER_OPTION_ABSOLUTE',
'"absolute" option has been removed, consider the "join" option if absolute paths must be processed'
],
attempts: [
'DEP_RESOLVE_URL_LOADER_OPTION_ATTEMPTS',
'"attempts" option has been removed, consider the "join" option if search is needed'
],
includeRoot: [
'DEP_RESOLVE_URL_LOADER_OPTION_INCLUDE_ROOT',
'"includeRoot" option has been removed, consider the "join" option if search is needed'
],
fail: [
'DEP_RESOLVE_URL_LOADER_OPTION_FAIL',
'"fail" option has been removed'
]
};
/**
* A webpack loader that resolves absolute url() paths relative to their original source file.
* Requires source-maps to do any meaningful work.
* @param {string} content Css content
* @param {object} sourceMap The source-map
* @returns {string|String}
*/
function resolveUrlLoader(content, sourceMap) {
/* jshint validthis:true */
// details of the file being processed
const loader = this;
// a relative loader.context is a problem
if (/^\./.test(loader.context)) {
return handleAsError(
'webpack misconfiguration',
'loader.context is relative, expected absolute'
);
}
// infer webpack version from new loader features
const isWebpackGte5 = 'getOptions' in loader && typeof loader.getOptions === 'function';
// use loader.getOptions where available otherwise use loaderUtils
const rawOptions = isWebpackGte5 ? loader.getOptions() : loaderUtils.getOptions(loader);
const options = Object.assign(
{
sourceMap: loader.sourceMap,
silent : false,
removeCR : os.EOL.includes('\r'),
root : false,
debug : false,
join : joinFn.defaultJoin
},
rawOptions,
);
// maybe log options for the test harness
if (process.env.RESOLVE_URL_LOADER_TEST_HARNESS) {
logToTestHarness(
process[process.env.RESOLVE_URL_LOADER_TEST_HARNESS],
options
);
}
// deprecated options
const deprecatedItems = Object.entries(DEPRECATED_OPTIONS).filter(([key]) => key in rawOptions);
if (deprecatedItems.length) {
deprecatedItems.forEach(([, value]) => handleAsDeprecated(...value));
}
// validate join option
if (typeof options.join !== 'function') {
return handleAsError(
'loader misconfiguration',
'"join" option must be a Function'
);
} else if (options.join.length !== 2) {
return handleAsError(
'loader misconfiguration',
'"join" Function must take exactly 2 arguments (options, loader)'
);
}
// validate the result of calling the join option
const joinProper = options.join(options, loader);
if (typeof joinProper !== 'function') {
return handleAsError(
'loader misconfiguration',
'"join" option must itself return a Function when it is called'
);
} else if (joinProper.length !== 1) {
return handleAsError(
'loader misconfiguration',
'"join" Function must create a function that takes exactly 1 arguments (item)'
);
}
// validate root option
if (typeof options.root === 'string') {
const isValid = (options.root === '') ||
(path.isAbsolute(options.root) && fs.existsSync(options.root) && fs.statSync(options.root).isDirectory());
if (!isValid) {
return handleAsError(
'loader misconfiguration',
'"root" option must be an empty string or an absolute path to an existing directory'
);
}
} else if (options.root !== false) {
handleAsWarning(
'loader misconfiguration',
'"root" option must be string where used or false where unused'
);
}
// loader result is cacheable
loader.cacheable();
// incoming source-map
let absSourceMap = null;
let sourceMapConsumer = null;
if (sourceMap) {
// support non-standard string encoded source-map (per less-loader)
if (typeof sourceMap === 'string') {
try {
sourceMap = JSON.parse(sourceMap);
}
catch (exception) {
return handleAsError(
'source-map error',
'cannot parse source-map string (from less-loader?)'
);
}
}
// leverage adjust-sourcemap-loader's codecs to avoid having to make any assumptions about the sourcemap
// historically this is a regular source of breakage
try {
absSourceMap = adjustSourceMap(loader, {format: 'absolute'}, sourceMap);
}
catch (exception) {
return handleAsError(
'source-map error',
exception.message
);
}
// prepare the adjusted sass source-map for later look-ups
sourceMapConsumer = new SourceMapConsumer(absSourceMap);
} else {
handleAsWarning(
'webpack misconfiguration',
'webpack or the upstream loader did not supply a source-map'
);
}
// allow engine to throw at initialisation
let engine = null;
try {
engine = require('./lib/engine/postcss');
} catch (error) {
return handleAsError(
'error initialising',
error
);
}
// process async
const callback = loader.async();
Promise
.resolve(engine(loader.resourcePath, content, {
outputSourceMap : !!options.sourceMap,
absSourceMap : absSourceMap,
sourceMapConsumer : sourceMapConsumer,
removeCR : options.removeCR,
transformDeclaration: valueProcessor({
join : joinProper,
root : options.root,
directory: path.dirname(loader.resourcePath)
})
}))
.catch(onFailure)
.then(onSuccess);
function onFailure(error) {
callback(encodeError('error processing CSS', error));
}
function onSuccess(result) {
if (result) {
// complete with source-map
// webpack4 and earlier: source-map sources are relative to the file being processed
// webpack5: source-map sources are relative to the project root but without a leading slash
if (options.sourceMap) {
const finalMap = adjustSourceMap(loader, {
format: isWebpackGte5 ? 'projectRelative' : 'sourceRelative'
}, result.map);
callback(null, result.content, finalMap);
}
// complete without source-map
else {
callback(null, result.content);
}
}
}
/**
* Trigger a node deprecation message for the given exception and return the original content.
* @param {string} code Deprecation code
* @param {string} message Deprecation message
* @returns {string} The original CSS content
*/
function handleAsDeprecated(code, message) {
if (!options.silent) {
util.deprecate(() => undefined, message, code)();
}
return content;
}
/**
* Push a warning for the given exception and return the original content.
* @param {string} label Summary of the error
* @param {string|Error} [exception] Optional extended error details
* @returns {string} The original CSS content
*/
function handleAsWarning(label, exception) {
if (!options.silent) {
loader.emitWarning(encodeError(label, exception));
}
return content;
}
/**
* Push a warning for the given exception and return the original content.
* @param {string} label Summary of the error
* @param {string|Error} [exception] Optional extended error details
* @returns {string} The original CSS content
*/
function handleAsError(label, exception) {
loader.emitError(encodeError(label, exception));
return content;
}
function encodeError(label, exception) {
return new Error(
[
'resolve-url-loader',
': ',
[label]
.concat(
(typeof exception === 'string') && exception ||
Array.isArray(exception) && exception ||
(exception instanceof Error) && [exception.message, exception.stack.split('\n')[1].trim()] ||
[]
)
.filter(Boolean)
.join('\n ')
].join('')
);
}
}
module.exports = Object.assign(resolveUrlLoader, joinFn);

View File

@@ -0,0 +1,132 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
const os = require('os');
const path = require('path');
const postcss = require('postcss');
const fileProtocol = require('../file-protocol');
const algerbra = require('../position-algerbra');
const ORPHAN_CR_REGEX = /\r(?!\n)(.|\n)?/g;
/**
* Process the given CSS content into reworked CSS content.
*
* @param {string} sourceFile The absolute path of the file being processed
* @param {string} sourceContent CSS content without source-map
* @param {{outputSourceMap: boolean, transformDeclaration:function, absSourceMap:object,
* sourceMapConsumer:object, removeCR:boolean}} params Named parameters
* @return {{content: string, map: object}} Reworked CSS and optional source-map
*/
function process(sourceFile, sourceContent, params) {
// #107 libsass emits orphan CR not considered newline, postcss does consider newline (content vs source-map mismatch)
const correctedContent = params.removeCR && (os.EOL !== '\r') ?
sourceContent.replace(ORPHAN_CR_REGEX, ' $1') :
sourceContent;
// IMPORTANT - prepend file protocol to all sources to avoid problems with source map
const plugin = Object.assign(
() => ({
postcssPlugin: 'postcss-resolve-url',
prepare: () => {
const visited = new Set();
/**
* Given an apparent position find the directory of the original file.
*
* @param startPosApparent {{line: number, column: number}}
* @returns {false|string} Directory of original file or false on invalid
*/
const positionToOriginalDirectory = (startPosApparent) => {
// reverse the original source-map to find the original source file before transpilation
const startPosOriginal =
!!params.sourceMapConsumer &&
params.sourceMapConsumer.originalPositionFor(startPosApparent);
// we require a valid directory for the specified file
const directory =
!!startPosOriginal &&
!!startPosOriginal.source &&
fileProtocol.remove(path.dirname(startPosOriginal.source));
return directory;
};
return {
Declaration: (declaration) => {
var prefix,
isValid = declaration.value && (declaration.value.indexOf('url') >= 0) && !visited.has(declaration);
if (isValid) {
prefix = declaration.prop + declaration.raws.between;
declaration.value = params.transformDeclaration(declaration.value, getPathsAtChar);
visited.add(declaration);
}
/**
* Create a hash of base path strings.
*
* Position in the declaration is supported by postcss at the position of the url() statement.
*
* @param {number} index Index in the declaration value at which to evaluate
* @throws Error on invalid source map
* @returns {{subString:string, value:string, property:string, selector:string}} Hash of base path strings
*/
function getPathsAtChar(index) {
var subString = declaration.value.slice(0, index),
posSelector = algerbra.sanitise(declaration.parent.source.start),
posProperty = algerbra.sanitise(declaration.source.start),
posValue = algerbra.add([posProperty, algerbra.strToOffset(prefix)]),
posSubString = algerbra.add([posValue, algerbra.strToOffset(subString)]);
var result = {
subString: positionToOriginalDirectory(posSubString),
value : positionToOriginalDirectory(posValue),
property : positionToOriginalDirectory(posProperty),
selector : positionToOriginalDirectory(posSelector)
};
var isValid = [result.subString, result.value, result.property, result.selector].every(Boolean);
if (isValid) {
return result;
}
else if (params.sourceMapConsumer) {
throw new Error(
'source-map information is not available at url() declaration ' + (
ORPHAN_CR_REGEX.test(sourceContent) ?
'(found orphan CR, try removeCR option)' :
'(no orphan CR found)'
)
);
} else {
throw new Error('a valid source-map is not present (ensure preceding loaders output a source-map)');
}
}
}
};
}
}),
{ postcss: true }
);
// IMPORTANT - prepend file protocol to all sources to avoid problems with source map
return postcss([plugin])
.process(correctedContent, {
from: fileProtocol.prepend(sourceFile),
map : params.outputSourceMap && {
prev : !!params.absSourceMap && fileProtocol.prepend(params.absSourceMap),
inline : false,
annotation : false,
sourcesContent: true // #98 sourcesContent missing from output map
}
})
.then(({css, map}) => ({
content: css,
map : params.outputSourceMap ? fileProtocol.remove(map.toJSON()) : null
}));
}
module.exports = process;

View File

@@ -0,0 +1,39 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
/**
* Prepend file:// protocol to source path string or source-map sources.
*/
function prepend(candidate) {
if (typeof candidate === 'string') {
return 'file://' + candidate;
} else if (candidate && (typeof candidate === 'object') && Array.isArray(candidate.sources)) {
return Object.assign({}, candidate, {
sources: candidate.sources.map(prepend)
});
} else {
throw new Error('expected string|object');
}
}
exports.prepend = prepend;
/**
* Remove file:// protocol from source path string or source-map sources.
*/
function remove(candidate) {
if (typeof candidate === 'string') {
return candidate.replace(/^file:\/{2}/, '');
} else if (candidate && (typeof candidate === 'object') && Array.isArray(candidate.sources)) {
return Object.assign({}, candidate, {
sources: candidate.sources.map(remove)
});
} else {
throw new Error('expected string|object');
}
}
exports.remove = remove;

View File

@@ -0,0 +1,86 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
const path = require('path');
const PACKAGE_NAME = require('../../package.json').name;
/**
* Paths are formatted to have posix style path separators and those within the CWD are made relative to CWD.
*
* @param {string} absolutePath An absolute path to format
* @returns {string} the formatted path
*/
const pathToString = (absolutePath) => {
if (absolutePath === '') {
return '-empty-';
} else {
const relative = path.relative(process.cwd(), absolutePath).split(path.sep);
const segments =
(relative[0] !== '..') ? ['.'].concat(relative).filter(Boolean) :
(relative.lastIndexOf('..') < 2) ? relative :
absolutePath.replace(/^[A-Z]\:/, '').split(path.sep);
return segments.join('/');
}
};
exports.pathToString = pathToString;
/**
* Format a debug message.
*
* @param {string} filename The file being processed by webpack
* @param {string} uri A uri path, relative or absolute
* @param {Array<{base:string,joined:string,isSuccess:boolean}>} attempts An array of attempts, possibly empty
* @return {string} Formatted message
*/
const formatJoinMessage = (filename, uri, attempts) => {
const attemptToCells = (_, i, array) => {
const { base: prev } = (i === 0) ? {} : array[i-1];
const { base: curr, joined } = array[i];
return [(curr === prev) ? '' : pathToString(curr), pathToString(joined)];
};
const formatCells = (lines) => {
const maxWidth = lines.reduce((max, [cellA]) => Math.max(max, cellA.length), 0);
return lines.map(([cellA, cellB]) => [cellA.padEnd(maxWidth), cellB]).map((cells) => cells.join(' --> '));
};
return [PACKAGE_NAME + ': ' + pathToString(filename) + ': ' + uri]
.concat(attempts.length === 0 ? '-empty-' : formatCells(attempts.map(attemptToCells)))
.concat(attempts.some(({ isSuccess }) => isSuccess) ? 'FOUND' : 'NOT FOUND')
.join('\n ');
};
exports.formatJoinMessage = formatJoinMessage;
/**
* A factory for a log function predicated on the given debug parameter.
*
* The logging function created accepts a function that formats a message and parameters that the function utilises.
* Presuming the message function may be expensive we only call it if logging is enabled.
*
* The log messages are de-duplicated based on the parameters, so it is assumed they are simple types that stringify
* well.
*
* @param {function|boolean} debug A boolean or debug function
* @return {function(function, array):void} A logging function possibly degenerate
*/
const createDebugLogger = (debug) => {
const log = !!debug && ((typeof debug === 'function') ? debug : console.log);
const cache = {};
return log ?
((msgFn, params) => {
const key = Function.prototype.toString.call(msgFn) + JSON.stringify(params);
if (!cache[key]) {
cache[key] = true;
log(msgFn.apply(null, params));
}
}) :
(() => undefined);
};
exports.createDebugLogger = createDebugLogger;

View File

@@ -0,0 +1,24 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
const fsUtils = (fs) => {
// fs from enhanced-resolver doesn't include fs.existsSync so we need to use fs.statsSync instead
const withStats = (fn) => (absolutePath) => {
try {
return fn(fs.statSync(absolutePath));
} catch (e) {
return false;
}
};
return {
isFileSync: withStats((stats) => stats.isFile()),
isDirectorySync: withStats((stats) => stats.isDirectory()),
existsSync: withStats((stats) => stats.isFile() || stats.isDirectory())
};
};
module.exports = fsUtils;

View File

@@ -0,0 +1,235 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
const path = require('path');
const { createDebugLogger, formatJoinMessage } = require('./debug');
const fsUtils = require('./fs-utils');
const ITERATION_SAFETY_LIMIT = 100e3;
/**
* Wrap a function such that it always returns a generator of tuple elements.
*
* @param {function({uri:string},...):(Array|Iterator)<[string,string]|string>} fn The function to wrap
* @returns {function({uri:string},...):(Array|Iterator)<[string,string]>} A function that always returns tuple elements
*/
const asGenerator = (fn) => {
const toTuple = (defaults) => (value) => {
const partial = [].concat(value);
return [...partial, ...defaults.slice(partial.length)];
};
const isTupleUnique = (v, i, a) => {
const required = v.join(',');
return a.findIndex((vv) => vv.join(',') === required) === i;
};
return (item, ...rest) => {
const {uri} = item;
const mapTuple = toTuple([null, uri]);
const pending = fn(item, ...rest);
if (Array.isArray(pending)) {
return pending.map(mapTuple).filter(isTupleUnique)[Symbol.iterator]();
} else if (
pending &&
(typeof pending === 'object') &&
(typeof pending.next === 'function') &&
(pending.next.length === 0)
) {
return pending;
} else {
throw new TypeError(`in "join" function expected "generator" to return Array|Iterator`);
}
};
};
exports.asGenerator = asGenerator;
/**
* A high-level utility to create a join function.
*
* The `generator` is responsible for ordering possible base paths. The `operation` is responsible for joining a single
* `base` path with the given `uri`. The `predicate` is responsible for reporting whether the single joined value is
* successful as the overall result.
*
* Both the `generator` and `operation` may be `function*()` or simply `function(...):Array<string>`.
*
* @param {function({uri:string, isAbsolute:boolean, bases:{subString:string, value:string, property:string,
* selector:string}}, {filename:string, fs:Object, debug:function|boolean, root:string}):
* (Array<string>|Iterator<string>)} generator A function that takes the hash of base paths from the `engine` and
* returns ordered iterable of paths to consider
* @returns {function({filename:string, fs:Object, debug:function|boolean, root:string}):
* (function({uri:string, isAbsolute:boolean, bases:{subString:string, value:string, property:string,
* selector:string}}):string)} join implementation
*/
const createJoinImplementation = (generator) => (item, options, loader) => {
const { isAbsolute } = item;
const { root } = options;
const { fs } = loader;
// generate the iterator
const iterator = generator(item, options, loader);
const isValidIterator = iterator && typeof iterator === 'object' && typeof iterator.next === 'function';
if (!isValidIterator) {
throw new Error('expected generator to return Iterator');
}
// run the iterator lazily and record attempts
const { isFileSync, isDirectorySync } = fsUtils(fs);
const attempts = [];
for (let i = 0; i < ITERATION_SAFETY_LIMIT; i++) {
const { value, done } = iterator.next();
if (done) {
break;
} else if (value) {
const tuple = Array.isArray(value) && value.length === 2 ? value : null;
if (!tuple) {
throw new Error('expected Iterator values to be tuple of [string,string], do you need asGenerator utility?');
}
// skip elements where base or uri is non-string
// noting that we need to support base="" when root=""
const [base, uri] = value;
if ((typeof base === 'string') && (typeof uri === 'string')) {
// validate
const isValidBase = (isAbsolute && base === root) || (path.isAbsolute(base) && isDirectorySync(base));
if (!isValidBase) {
throw new Error(`expected "base" to be absolute path to a valid directory, got "${base}"`);
}
// make the attempt
const joined = path.normalize(path.join(base, uri));
const isFallback = true;
const isSuccess = isFileSync(joined);
attempts.push({base, uri, joined, isFallback, isSuccess});
if (isSuccess) {
break;
}
// validate any non-strings are falsey
} else {
const isValidTuple = value.every((v) => (typeof v === 'string') || !v);
if (!isValidTuple) {
throw new Error('expected Iterator values to be tuple of [string,string]');
}
}
}
}
return attempts;
};
exports.createJoinImplementation = createJoinImplementation;
/**
* A low-level utility to create a join function.
*
* The `implementation` function processes an individual `item` and returns an Array of attempts. Each attempt consists
* of a `base` and a `joined` value with `isSuccessful` and `isFallback` flags.
*
* In the case that any attempt `isSuccessful` then its `joined` value is the outcome. Otherwise the first `isFallback`
* attempt is used. If there is no successful or fallback attempts then `null` is returned indicating no change to the
* original URI in the CSS.
*
* The `attempts` Array is logged to console when in `debug` mode.
*
* @param {string} name Name for the resulting join function
* @param {function({uri:string, query:string, isAbsolute:boolean, bases:{subString:string, value:string,
* property:string, selector:string}}, {filename:string, fs:Object, debug:function|boolean, root:string}):
* Array<{base:string,joined:string,fallback?:string,result?:string}>} implementation A function accepts an item and
* returns a list of attempts
* @returns {function({filename:string, fs:Object, debug:function|boolean, root:string}):
* (function({uri:string, isAbsolute:boolean, bases:{subString:string, value:string, property:string,
* selector:string}}):string)} join function
*/
const createJoinFunction = (name, implementation) => {
const assertAttempts = (value) => {
const isValid =
Array.isArray(value) && value.every((v) =>
v &&
(typeof v === 'object') &&
(typeof v.base === 'string') &&
(typeof v.uri === 'string') &&
(typeof v.joined === 'string') &&
(typeof v.isSuccess === 'boolean') &&
(typeof v.isFallback === 'boolean')
);
if (!isValid) {
throw new Error(`expected implementation to return Array of {base, uri, joined, isSuccess, isFallback}`);
} else {
return value;
}
};
const assertJoined = (value) => {
const isValid = value && (typeof value === 'string') && path.isAbsolute(value) || (value === null);
if (!isValid) {
throw new Error(`expected "joined" to be absolute path, got "${value}"`);
} else {
return value;
}
};
const join = (options, loader) => {
const { debug } = options;
const { resourcePath } = loader;
const log = createDebugLogger(debug);
return (item) => {
const { uri } = item;
const attempts = implementation(item, options, loader);
assertAttempts(attempts, !!debug);
const { joined: fallback } = attempts.find(({ isFallback }) => isFallback) || {};
const { joined: result } = attempts.find(({ isSuccess }) => isSuccess) || {};
log(formatJoinMessage, [resourcePath, uri, attempts]);
return assertJoined(result || fallback || null);
};
};
const toString = () => '[Function ' + name + ']';
return Object.assign(join, !!name && {
toString,
toJSON: toString
});
};
exports.createJoinFunction = createJoinFunction;
/**
* The default iterable factory will order `subString` then `value` then `property` then `selector`.
*
* @param {string} uri The uri given in the file webpack is processing
* @param {boolean} isAbsolute True for absolute URIs, false for relative URIs
* @param {string} subString A possible base path
* @param {string} value A possible base path
* @param {string} property A possible base path
* @param {string} selector A possible base path
* @param {string} root The loader options.root value where given
* @returns {Array<string>} An iterable of possible base paths in preference order
*/
const defaultJoinGenerator = asGenerator(
({ uri, isAbsolute, bases: { subString, value, property, selector } }, { root }) =>
isAbsolute ? [root] : [subString, value, property, selector]
);
exports.defaultJoinGenerator = defaultJoinGenerator;
/**
* @type {function({filename:string, fs:Object, debug:function|boolean, root:string}):
* (function({uri:string, isAbsolute:boolean, bases:{subString:string, value:string, property:string,
* selector:string}}):string)} join function
*/
exports.defaultJoin = createJoinFunction(
'defaultJoin',
createJoinImplementation(defaultJoinGenerator)
);

View File

@@ -0,0 +1,36 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
var stream = require('stream');
var hasLogged = false;
function logToTestHarness(maybeStream, options) {
var doLogging =
!hasLogged &&
!!maybeStream &&
(typeof maybeStream === 'object') &&
(maybeStream instanceof stream.Writable);
if (doLogging) {
hasLogged = true; // ensure we log only once
Object.keys(options).forEach(eachOptionKey);
}
function eachOptionKey(key) {
maybeStream.write(key + ': ' + stringify(options[key]) + '\n');
}
function stringify(value) {
try {
return JSON.stringify(value) || String(value);
} catch (e) {
return '-unstringifyable-';
}
}
}
module.exports = logToTestHarness;

View File

@@ -0,0 +1,62 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
/**
* Given a sourcemap position create a new maybeObject with only line and column properties.
*
* @param {*|{line: number, column: number}} maybeObj Possible location hash
* @returns {{line: number, column: number}} Location hash with possible NaN values
*/
function sanitise(maybeObj) {
var obj = !!maybeObj && typeof maybeObj === 'object' && maybeObj || {};
return {
line: isNaN(obj.line) ? NaN : obj.line,
column: isNaN(obj.column) ? NaN : obj.column
};
}
exports.sanitise = sanitise;
/**
* Infer a line and position delta based on the linebreaks in the given string.
*
* @param candidate {string} A string with possible linebreaks
* @returns {{line: number, column: number}} A position object where line and column are deltas
*/
function strToOffset(candidate) {
var split = candidate.split(/\r\n|\n/g);
var last = split[split.length - 1];
return {
line: split.length - 1,
column: last.length
};
}
exports.strToOffset = strToOffset;
/**
* Add together a list of position elements.
*
* Lines are added. If the new line is zero the column is added otherwise it is overwritten.
*
* @param {{line: number, column: number}[]} list One or more sourcemap position elements to add
* @returns {{line: number, column: number}} Resultant position element
*/
function add(list) {
return list
.slice(1)
.reduce(
function (accumulator, element) {
return {
line: accumulator.line + element.line,
column: element.line > 0 ? element.column : accumulator.column + element.column,
};
},
list[0]
);
}
exports.add = add;

View File

@@ -0,0 +1,136 @@
/*
* MIT License http://opensource.org/licenses/MIT
* Author: Ben Holloway @bholloway
*/
'use strict';
var path = require('path'),
loaderUtils = require('loader-utils');
/**
* Create a value processing function for a given file path.
*
* @param {function(Object):string} join The inner join function
* @param {string} root The loader options.root value where given
* @param {string} directory The directory of the file webpack is currently processing
* @return {function} value processing function
*/
function valueProcessor({ join, root, directory }) {
var URL_STATEMENT_REGEX = /(url\s*\(\s*)(?:(['"])((?:(?!\2).)*)(\2)|([^'"](?:(?!\)).)*[^'"]))(\s*\))/g,
QUERY_REGEX = /([?#])/g;
/**
* Process the given CSS declaration value.
*
* @param {string} value A declaration value that may or may not contain a url() statement
* @param {function(number):Object} getPathsAtChar Given an offset in the declaration value get a
* list of possible absolute path strings
*/
return function transformValue(value, getPathsAtChar) {
// allow multiple url() values in the declaration
// split by url statements and process the content
// additional capture groups are needed to match quotations correctly
// escaped quotations are not considered
return value
.split(URL_STATEMENT_REGEX)
.map(initialise)
.map(eachSplitOrGroup)
.join('');
/**
* Ensure all capture group tokens are a valid string.
*
* @param {string|void} token A capture group or uncaptured token
* @returns {string}
*/
function initialise(token) {
return typeof token === 'string' ? token : '';
}
/**
* An Array reduce function that accumulates string length.
*/
function accumulateLength(accumulator, element) {
return accumulator + element.length;
}
/**
* Encode the content portion of <code>url()</code> statements.
* There are 6 capture groups in the split making every 7th unmatched.
*
* @param {string} element A single split item
* @param {number} i The index of the item in the split
* @param {Array} arr The array of split values
* @returns {string} Every 3 or 5 items is an encoded url everything else is as is
*/
function eachSplitOrGroup(element, i, arr) {
// the content of the url() statement is either in group 3 or group 5
var mod = i % 7;
// only one of the capture groups 3 or 5 will match the other will be falsey
if (element && ((mod === 3) || (mod === 5))) {
// calculate the offset of the match from the front of the string
var position = arr.slice(0, i - mod + 1).reduce(accumulateLength, 0);
// detect quoted url and unescape backslashes
var before = arr[i - 1],
after = arr[i + 1],
isQuoted = (before === after) && ((before === '\'') || (before === '"')),
unescaped = isQuoted ? element.replace(/\\{2}/g, '\\') : element;
// split into uri and query/hash and then determine if the uri is some type of file
var split = unescaped.split(QUERY_REGEX),
uri = split[0],
query = split.slice(1).join(''),
isRelative = testIsRelative(uri),
isAbsolute = testIsAbsolute(uri);
// file like URIs are processed but not all URIs are files
if (isRelative || isAbsolute) {
var bases = getPathsAtChar(position), // construct iterator as late as possible in case sourcemap invalid
absolute = join({ uri, query, isAbsolute, bases });
if (typeof absolute === 'string') {
var relative = path.relative(directory, absolute)
.replace(/\\/g, '/'); // #6 - backslashes are not legal in URI
return loaderUtils.urlToRequest(relative + query);
}
}
}
// everything else, including parentheses and quotation (where present) and media statements
return element;
}
};
/**
* The loaderUtils.isUrlRequest() doesn't support windows absolute paths on principle. We do not subscribe to that
* dogma so we add path.isAbsolute() check to allow them.
*
* We also eliminate module relative (~) paths.
*
* @param {string|undefined} uri A uri string possibly empty or undefined
* @return {boolean} True for relative uri
*/
function testIsRelative(uri) {
return !!uri && loaderUtils.isUrlRequest(uri, false) && !path.isAbsolute(uri) && (uri.indexOf('~') !== 0);
}
/**
* The loaderUtils.isUrlRequest() doesn't support windows absolute paths on principle. We do not subscribe to that
* dogma so we add path.isAbsolute() check to allow them.
*
* @param {string|undefined} uri A uri string possibly empty or undefined
* @return {boolean} True for absolute uri
*/
function testIsAbsolute(uri) {
return !!uri && (typeof root === 'string') && loaderUtils.isUrlRequest(uri, root) &&
(/^\//.test(uri) || path.isAbsolute(uri));
}
}
module.exports = valueProcessor;

View File

@@ -0,0 +1,23 @@
Copyright 2013 Thorsten Lorenz.
All rights reserved.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,123 @@
# convert-source-map [![Build Status][ci-image]][ci-url]
Converts a source-map from/to different formats and allows adding/changing properties.
```js
var convert = require('convert-source-map');
var json = convert
.fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.toJSON();
var modified = convert
.fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.setProperty('sources', [ 'SRC/FOO.JS' ])
.toJSON();
console.log(json);
console.log(modified);
```
```json
{"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"}
{"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"}
```
## API
### fromObject(obj)
Returns source map converter from given object.
### fromJSON(json)
Returns source map converter from given json string.
### fromBase64(base64)
Returns source map converter from given base64 encoded json string.
### fromComment(comment)
Returns source map converter from given base64 encoded json string prefixed with `//# sourceMappingURL=...`.
### fromMapFileComment(comment, mapFileDir)
Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`.
`filename` must point to a file that is found inside the `mapFileDir`. Most tools store this file right next to the
generated file, i.e. the one containing the source map.
### fromSource(source)
Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found.
### fromMapFileSource(source, mapFileDir)
Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was
found.
The sourcemap will be read from the map file found by parsing `# sourceMappingURL=file` comment. For more info see
fromMapFileComment.
### toObject()
Returns a copy of the underlying source map.
### toJSON([space])
Converts source map to json string. If `space` is given (optional), this will be passed to
[JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the
JSON string is generated.
### toBase64()
Converts source map to base64 encoded json string.
### toComment([options])
Converts source map to an inline comment that can be appended to the source-file.
By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would
normally see in a JS source file.
When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file.
### addProperty(key, value)
Adds given property to the source map. Throws an error if property already exists.
### setProperty(key, value)
Sets given property to the source map. If property doesn't exist it is added, otherwise its value is updated.
### getProperty(key)
Gets given property of the source map.
### removeComments(src)
Returns `src` with all source map comments removed
### removeMapFileComments(src)
Returns `src` with all source map comments pointing to map files removed.
### commentRegex
Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments.
### mapFileCommentRegex
Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files.
### generateMapFileComment(file, [options])
Returns a comment that links to an external source map via `file`.
By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file.
When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file.
[ci-url]: https://github.com/thlorenz/convert-source-map/actions?query=workflow:ci
[ci-image]: https://img.shields.io/github/workflow/status/thlorenz/convert-source-map/CI?style=flat-square

View File

@@ -0,0 +1,179 @@
'use strict';
var fs = require('fs');
var path = require('path');
Object.defineProperty(exports, 'commentRegex', {
get: function getCommentRegex () {
return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg;
}
});
Object.defineProperty(exports, 'mapFileCommentRegex', {
get: function getMapFileCommentRegex () {
// Matches sourceMappingURL in either // or /* comment styles.
return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg;
}
});
var decodeBase64;
if (typeof Buffer !== 'undefined') {
if (typeof Buffer.from === 'function') {
decodeBase64 = decodeBase64WithBufferFrom;
} else {
decodeBase64 = decodeBase64WithNewBuffer;
}
} else {
decodeBase64 = decodeBase64WithAtob;
}
function decodeBase64WithBufferFrom(base64) {
return Buffer.from(base64, 'base64').toString();
}
function decodeBase64WithNewBuffer(base64) {
if (typeof value === 'number') {
throw new TypeError('The value to decode must not be of type number.');
}
return new Buffer(base64, 'base64').toString();
}
function decodeBase64WithAtob(base64) {
return decodeURIComponent(escape(atob(base64)));
}
function stripComment(sm) {
return sm.split(',').pop();
}
function readFromFileMap(sm, dir) {
// NOTE: this will only work on the server since it attempts to read the map file
var r = exports.mapFileCommentRegex.exec(sm);
// for some odd reason //# .. captures in 1 and /* .. */ in 2
var filename = r[1] || r[2];
var filepath = path.resolve(dir, filename);
try {
return fs.readFileSync(filepath, 'utf8');
} catch (e) {
throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e);
}
}
function Converter (sm, opts) {
opts = opts || {};
if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir);
if (opts.hasComment) sm = stripComment(sm);
if (opts.isEncoded) sm = decodeBase64(sm);
if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm);
this.sourcemap = sm;
}
Converter.prototype.toJSON = function (space) {
return JSON.stringify(this.sourcemap, null, space);
};
if (typeof Buffer !== 'undefined') {
if (typeof Buffer.from === 'function') {
Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
} else {
Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
}
} else {
Converter.prototype.toBase64 = encodeBase64WithBtoa;
}
function encodeBase64WithBufferFrom() {
var json = this.toJSON();
return Buffer.from(json, 'utf8').toString('base64');
}
function encodeBase64WithNewBuffer() {
var json = this.toJSON();
if (typeof json === 'number') {
throw new TypeError('The json to encode must not be of type number.');
}
return new Buffer(json, 'utf8').toString('base64');
}
function encodeBase64WithBtoa() {
var json = this.toJSON();
return btoa(unescape(encodeURIComponent(json)));
}
Converter.prototype.toComment = function (options) {
var base64 = this.toBase64();
var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
};
// returns copy instead of original
Converter.prototype.toObject = function () {
return JSON.parse(this.toJSON());
};
Converter.prototype.addProperty = function (key, value) {
if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
return this.setProperty(key, value);
};
Converter.prototype.setProperty = function (key, value) {
this.sourcemap[key] = value;
return this;
};
Converter.prototype.getProperty = function (key) {
return this.sourcemap[key];
};
exports.fromObject = function (obj) {
return new Converter(obj);
};
exports.fromJSON = function (json) {
return new Converter(json, { isJSON: true });
};
exports.fromBase64 = function (base64) {
return new Converter(base64, { isEncoded: true });
};
exports.fromComment = function (comment) {
comment = comment
.replace(/^\/\*/g, '//')
.replace(/\*\/$/g, '');
return new Converter(comment, { isEncoded: true, hasComment: true });
};
exports.fromMapFileComment = function (comment, dir) {
return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true });
};
// Finds last sourcemap comment in file or returns null if none was found
exports.fromSource = function (content) {
var m = content.match(exports.commentRegex);
return m ? exports.fromComment(m.pop()) : null;
};
// Finds last sourcemap comment in file or returns null if none was found
exports.fromMapFileSource = function (content, dir) {
var m = content.match(exports.mapFileCommentRegex);
return m ? exports.fromMapFileComment(m.pop(), dir) : null;
};
exports.removeComments = function (src) {
return src.replace(exports.commentRegex, '');
};
exports.removeMapFileComments = function (src) {
return src.replace(exports.mapFileCommentRegex, '');
};
exports.generateMapFileComment = function (file, options) {
var data = 'sourceMappingURL=' + file;
return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
};

View File

@@ -0,0 +1,41 @@
{
"name": "convert-source-map",
"version": "1.9.0",
"description": "Converts a source-map from/to different formats and allows adding/changing properties.",
"main": "index.js",
"scripts": {
"test": "tap test/*.js --color"
},
"repository": {
"type": "git",
"url": "git://github.com/thlorenz/convert-source-map.git"
},
"homepage": "https://github.com/thlorenz/convert-source-map",
"devDependencies": {
"inline-source-map": "~0.6.2",
"tap": "~9.0.0"
},
"keywords": [
"convert",
"sourcemap",
"source",
"map",
"browser",
"debug"
],
"author": {
"name": "Thorsten Lorenz",
"email": "thlorenz@gmx.de",
"url": "http://thlorenz.com"
},
"license": "MIT",
"engine": {
"node": ">=0.6"
},
"files": [
"index.js"
],
"browser": {
"fs": false
}
}

44
spa/node_modules/resolve-url-loader/package.json generated vendored Normal file
View File

@@ -0,0 +1,44 @@
{
"name": "resolve-url-loader",
"version": "5.0.0",
"description": "Webpack loader that resolves relative paths in url() statements based on the original source file",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/bholloway/resolve-url-loader.git",
"directory": "packages/resolve-url-loader"
},
"keywords": [
"webpack",
"loader",
"css",
"normalize",
"rewrite",
"resolve",
"url",
"sass",
"relative",
"file"
],
"author": "bholloway",
"license": "MIT",
"bugs": {
"url": "https://github.com/bholloway/resolve-url-loader/issues"
},
"homepage": "https://github.com/bholloway/resolve-url-loader/tree/v5/packages/resolve-url-loader",
"engines": {
"node": ">=12"
},
"files": [
"index.js",
"lib/**/+([a-z-]).js",
"docs/**/*.*"
],
"dependencies": {
"adjust-sourcemap-loader": "^4.0.0",
"convert-source-map": "^1.7.0",
"loader-utils": "^2.0.0",
"postcss": "^8.2.14",
"source-map": "0.6.1"
}
}