From 6fd67549db85547af30b3e7cae40531d96c656e9 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Tue, 17 Dec 2024 10:31:25 +0000 Subject: [PATCH 01/15] Added bundle config option (true by default) to enable/disable bundling --- fixtures/dummy/lib/engines/gem3.js | 1 + .../dummy/lib/import_npm_module_with_ext.css | 1 + .../svg/{absolute.jsx => absolute_jsx.jsx} | 0 .../svg/{absolute.tsx => absolute_tsx.tsx} | 0 fixtures/dummy/node_modules/.modules.yaml | 6 +- .../node_modules/gem2/app/views/user.rb | 2 +- .../node_modules/js-tokens/CHANGELOG.md | 151 + .../node_modules/js-tokens/LICENSE | 21 + .../node_modules/js-tokens/README.md | 240 ++ .../node_modules/js-tokens/index.js | 23 + .../node_modules/js-tokens/package.json | 30 + fixtures/dummy/node_modules/.pnpm/lock.yaml | 21 + .../loose-envify@1.4.0/node_modules/js-tokens | 1 + .../node_modules/loose-envify/LICENSE | 21 + .../node_modules/loose-envify/README.md | 45 + .../node_modules/loose-envify/cli.js | 16 + .../node_modules/loose-envify/custom.js | 4 + .../node_modules/loose-envify/index.js | 3 + .../node_modules/loose-envify/loose-envify.js | 36 + .../node_modules/.bin/loose-envify | 17 + .../node_modules/loose-envify/package.json | 36 + .../node_modules/loose-envify/replace.js | 65 + .../.pnpm/node_modules/.bin/loose-envify | 17 + .../node_modules/.pnpm/node_modules/js-tokens | 1 + .../.pnpm/node_modules/loose-envify | 1 + .../react@18.3.1/node_modules/loose-envify | 1 + .../react@18.3.1/node_modules/react/LICENSE | 21 + .../react@18.3.1/node_modules/react/README.md | 37 + .../cjs/react-jsx-dev-runtime.development.js | 1315 +++++++ .../react-jsx-dev-runtime.production.min.js | 10 + .../react-jsx-dev-runtime.profiling.min.js | 10 + .../cjs/react-jsx-runtime.development.js | 1333 +++++++ .../cjs/react-jsx-runtime.production.min.js | 11 + .../cjs/react-jsx-runtime.profiling.min.js | 11 + .../react/cjs/react.development.js | 2740 ++++++++++++++ .../react/cjs/react.production.min.js | 26 + .../cjs/react.shared-subset.development.js | 20 + .../cjs/react.shared-subset.production.min.js | 10 + .../react@18.3.1/node_modules/react/index.js | 7 + .../node_modules/react/jsx-dev-runtime.js | 7 + .../node_modules/react/jsx-runtime.js | 7 + .../react/node_modules/.bin/loose-envify | 17 + .../node_modules/react/package.json | 47 + .../node_modules/react/react.shared-subset.js | 7 + .../react/umd/react.development.js | 3343 +++++++++++++++++ .../react/umd/react.production.min.js | 31 + .../react/umd/react.profiling.min.js | 31 + fixtures/dummy/node_modules/react | 1 + fixtures/dummy/package.json | 6 +- fixtures/dummy/pnpm-lock.yaml | 21 + .../dummy/vendor/gem3/lib/gem3/console.js | 1 + fixtures/dummy/vendor/gem3/lib/gem3/foo.js | 1 + fixtures/dummy/vendor/gem3/lib/gem3/gem3.js | 2 + fixtures/external/gem4/lib/gem4/console.js | 1 + fixtures/external/gem4/lib/gem4/foo.js | 1 + fixtures/external/gem4/lib/gem4/gem4.js | 3 + go.mod | 1 + go.sum | 2 + internal/builder/build.go | 53 +- internal/css/mixins.go | 4 +- internal/importmap/importmap.go | 174 + internal/importmap/parse.go | 186 +- internal/importmap/resolve.go | 17 +- internal/plugin/bundler.go | 47 +- internal/plugin/bundless.go | 178 + internal/plugin/libs.go | 51 + internal/resolver/resolve.go | 40 +- internal/types/types.go | 18 +- lib/proscenium/builder.rb | 22 +- lib/proscenium/railtie.rb | 3 +- main.go | 2 +- test/build_bundless_test.go | 258 ++ test/build_test.go | 114 +- test/build_to_path_test.go | 32 +- test/build_to_string_test.go | 19 +- test/css_test.go | 73 +- test/env_test.go | 7 +- test/i18n_test.go | 13 +- test/import_map_test.go | 141 +- test/libs_test.go | 71 +- test/proscenium_suite_test.go | 9 +- test/resolver_test.go | 55 +- test/support/be_parsed_to_matcher.go | 9 +- test/support/build.go | 81 - test/support/resolve.go | 39 - test/svg_test.go | 25 +- test/url_test.go | 23 +- 87 files changed, 11005 insertions(+), 600 deletions(-) create mode 100644 fixtures/dummy/lib/engines/gem3.js create mode 100644 fixtures/dummy/lib/import_npm_module_with_ext.css rename fixtures/dummy/lib/svg/{absolute.jsx => absolute_jsx.jsx} (100%) rename fixtures/dummy/lib/svg/{absolute.tsx => absolute_tsx.tsx} (100%) create mode 100644 fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/CHANGELOG.md create mode 100644 fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/LICENSE create mode 100644 fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/README.md create mode 100644 fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/index.js create mode 100644 fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/package.json create mode 120000 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/js-tokens create mode 100644 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/LICENSE create mode 100644 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/README.md create mode 100755 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/cli.js create mode 100644 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/custom.js create mode 100644 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/index.js create mode 100644 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/loose-envify.js create mode 100755 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/node_modules/.bin/loose-envify create mode 100644 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/package.json create mode 100644 fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/replace.js create mode 100755 fixtures/dummy/node_modules/.pnpm/node_modules/.bin/loose-envify create mode 120000 fixtures/dummy/node_modules/.pnpm/node_modules/js-tokens create mode 120000 fixtures/dummy/node_modules/.pnpm/node_modules/loose-envify create mode 120000 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/loose-envify create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/LICENSE create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/README.md create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.development.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.production.min.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.profiling.min.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.production.min.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.profiling.min.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.production.min.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.shared-subset.development.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.shared-subset.production.min.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/index.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/jsx-dev-runtime.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/jsx-runtime.js create mode 100755 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/node_modules/.bin/loose-envify create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/package.json create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/react.shared-subset.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.development.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.production.min.js create mode 100644 fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.profiling.min.js create mode 120000 fixtures/dummy/node_modules/react create mode 100644 fixtures/dummy/vendor/gem3/lib/gem3/console.js create mode 100644 fixtures/dummy/vendor/gem3/lib/gem3/foo.js create mode 100644 fixtures/external/gem4/lib/gem4/console.js create mode 100644 fixtures/external/gem4/lib/gem4/foo.js create mode 100644 internal/importmap/importmap.go create mode 100644 internal/plugin/bundless.go create mode 100644 internal/plugin/libs.go create mode 100644 test/build_bundless_test.go delete mode 100644 test/support/build.go delete mode 100644 test/support/resolve.go diff --git a/fixtures/dummy/lib/engines/gem3.js b/fixtures/dummy/lib/engines/gem3.js new file mode 100644 index 00000000..8283652c --- /dev/null +++ b/fixtures/dummy/lib/engines/gem3.js @@ -0,0 +1 @@ +import "/gem3/lib/gem3/console.js"; diff --git a/fixtures/dummy/lib/import_npm_module_with_ext.css b/fixtures/dummy/lib/import_npm_module_with_ext.css new file mode 100644 index 00000000..8499414e --- /dev/null +++ b/fixtures/dummy/lib/import_npm_module_with_ext.css @@ -0,0 +1 @@ +@import "mypackage/styles.css"; diff --git a/fixtures/dummy/lib/svg/absolute.jsx b/fixtures/dummy/lib/svg/absolute_jsx.jsx similarity index 100% rename from fixtures/dummy/lib/svg/absolute.jsx rename to fixtures/dummy/lib/svg/absolute_jsx.jsx diff --git a/fixtures/dummy/lib/svg/absolute.tsx b/fixtures/dummy/lib/svg/absolute_tsx.tsx similarity index 100% rename from fixtures/dummy/lib/svg/absolute.tsx rename to fixtures/dummy/lib/svg/absolute_tsx.tsx diff --git a/fixtures/dummy/node_modules/.modules.yaml b/fixtures/dummy/node_modules/.modules.yaml index b760d90b..9c2f64f6 100644 --- a/fixtures/dummy/node_modules/.modules.yaml +++ b/fixtures/dummy/node_modules/.modules.yaml @@ -3,6 +3,10 @@ hoistPattern: hoistedDependencies: /is-plain-obj/4.1.0: is-plain-obj: private + /js-tokens/4.0.0: + js-tokens: private + /loose-envify/1.4.0: + loose-envify: private included: dependencies: true devDependencies: true @@ -12,7 +16,7 @@ layoutVersion: 5 nodeLinker: isolated packageManager: pnpm@8.10.2 pendingBuilds: [] -prunedAt: Fri, 22 Mar 2024 15:46:12 GMT +prunedAt: Tue, 26 Nov 2024 21:50:52 GMT publicHoistPattern: - '*eslint*' - '*prettier*' diff --git a/fixtures/dummy/node_modules/.pnpm/file+..+external+gem2/node_modules/gem2/app/views/user.rb b/fixtures/dummy/node_modules/.pnpm/file+..+external+gem2/node_modules/gem2/app/views/user.rb index 368b7d69..1a9280b9 100644 --- a/fixtures/dummy/node_modules/.pnpm/file+..+external+gem2/node_modules/gem2/app/views/user.rb +++ b/fixtures/dummy/node_modules/.pnpm/file+..+external+gem2/node_modules/gem2/app/views/user.rb @@ -1,6 +1,6 @@ module Gem2::Views class User < Proscenium::Phlex - def template + def view_template h1 { 'Hello' } end end diff --git a/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/CHANGELOG.md b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/CHANGELOG.md new file mode 100644 index 00000000..755e6f6e --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/CHANGELOG.md @@ -0,0 +1,151 @@ +### Version 4.0.0 (2018-01-28) ### + +- Added: Support for ES2018. The only change needed was recognizing the `s` + regex flag. +- Changed: _All_ tokens returned by the `matchToToken` function now have a + `closed` property. It is set to `undefined` for the tokens where “closed” + doesn’t make sense. This means that all tokens objects have the same shape, + which might improve performance. + +These are the breaking changes: + +- `'/a/s'.match(jsTokens)` no longer returns `['/', 'a', '/', 's']`, but + `['/a/s']`. (There are of course other variations of this.) +- Code that rely on some token objects not having the `closed` property could + now behave differently. + + +### Version 3.0.2 (2017-06-28) ### + +- No code changes. Just updates to the readme. + + +### Version 3.0.1 (2017-01-30) ### + +- Fixed: ES2015 unicode escapes with more than 6 hex digits are now matched + correctly. + + +### Version 3.0.0 (2017-01-11) ### + +This release contains one breaking change, that should [improve performance in +V8][v8-perf]: + +> So how can you, as a JavaScript developer, ensure that your RegExps are fast? +> If you are not interested in hooking into RegExp internals, make sure that +> neither the RegExp instance, nor its prototype is modified in order to get the +> best performance: +> +> ```js +> var re = /./g; +> re.exec(''); // Fast path. +> re.new_property = 'slow'; +> ``` + +This module used to export a single regex, with `.matchToToken` bolted +on, just like in the above example. This release changes the exports of +the module to avoid this issue. + +Before: + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens") +var matchToToken = jsTokens.matchToToken +``` + +After: + +```js +import jsTokens, {matchToToken} from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +var matchToToken = require("js-tokens").matchToToken +``` + +[v8-perf]: http://v8project.blogspot.se/2017/01/speeding-up-v8-regular-expressions.html + + +### Version 2.0.0 (2016-06-19) ### + +- Added: Support for ES2016. In other words, support for the `**` exponentiation + operator. + +These are the breaking changes: + +- `'**'.match(jsTokens)` no longer returns `['*', '*']`, but `['**']`. +- `'**='.match(jsTokens)` no longer returns `['*', '*=']`, but `['**=']`. + + +### Version 1.0.3 (2016-03-27) ### + +- Improved: Made the regex ever so slightly smaller. +- Updated: The readme. + + +### Version 1.0.2 (2015-10-18) ### + +- Improved: Limited npm package contents for a smaller download. Thanks to + @zertosh! + + +### Version 1.0.1 (2015-06-20) ### + +- Fixed: Declared an undeclared variable. + + +### Version 1.0.0 (2015-02-26) ### + +- Changed: Merged the 'operator' and 'punctuation' types into 'punctuator'. That + type is now equivalent to the Punctuator token in the ECMAScript + specification. (Backwards-incompatible change.) +- Fixed: A `-` followed by a number is now correctly matched as a punctuator + followed by a number. It used to be matched as just a number, but there is no + such thing as negative number literals. (Possibly backwards-incompatible + change.) + + +### Version 0.4.1 (2015-02-21) ### + +- Added: Support for the regex `u` flag. + + +### Version 0.4.0 (2015-02-21) ### + +- Improved: `jsTokens.matchToToken` performance. +- Added: Support for octal and binary number literals. +- Added: Support for template strings. + + +### Version 0.3.1 (2015-01-06) ### + +- Fixed: Support for unicode spaces. They used to be allowed in names (which is + very confusing), and some unicode newlines were wrongly allowed in strings and + regexes. + + +### Version 0.3.0 (2014-12-19) ### + +- Changed: The `jsTokens.names` array has been replaced with the + `jsTokens.matchToToken` function. The capturing groups of `jsTokens` are no + longer part of the public API; instead use said function. See this [gist] for + an example. (Backwards-incompatible change.) +- Changed: The empty string is now considered an “invalid” token, instead an + “empty” token (its own group). (Backwards-incompatible change.) +- Removed: component support. (Backwards-incompatible change.) + +[gist]: https://gist.github.com/lydell/be49dbf80c382c473004 + + +### Version 0.2.0 (2014-06-19) ### + +- Changed: Match ES6 function arrows (`=>`) as an operator, instead of its own + category (“functionArrow”), for simplicity. (Backwards-incompatible change.) +- Added: ES6 splats (`...`) are now matched as an operator (instead of three + punctuations). (Backwards-incompatible change.) + + +### Version 0.1.0 (2014-03-08) ### + +- Initial release. diff --git a/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/LICENSE b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/LICENSE new file mode 100644 index 00000000..54aef52f --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell + +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. diff --git a/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/README.md b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/README.md new file mode 100644 index 00000000..00cdf163 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/README.md @@ -0,0 +1,240 @@ +Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) +======== + +A regex that tokenizes JavaScript. + +```js +var jsTokens = require("js-tokens").default + +var jsString = "var foo=opts.foo;\n..." + +jsString.match(jsTokens) +// ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] +``` + + +Installation +============ + +`npm install js-tokens` + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +``` + + +Usage +===== + +### `jsTokens` ### + +A regex with the `g` flag that matches JavaScript tokens. + +The regex _always_ matches, even invalid JavaScript and the empty string. + +The next match is always directly after the previous. + +### `var token = matchToToken(match)` ### + +```js +import {matchToToken} from "js-tokens" +// or: +var matchToToken = require("js-tokens").matchToToken +``` + +Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: +String, value: String}` object. The following types are available: + +- string +- comment +- regex +- number +- name +- punctuator +- whitespace +- invalid + +Multi-line comments and strings also have a `closed` property indicating if the +token was closed or not (see below). + +Comments and strings both come in several flavors. To distinguish them, check if +the token starts with `//`, `/*`, `'`, `"` or `` ` ``. + +Names are ECMAScript IdentifierNames, that is, including both identifiers and +keywords. You may use [is-keyword-js] to tell them apart. + +Whitespace includes both line terminators and other whitespace. + +[is-keyword-js]: https://github.com/crissdev/is-keyword-js + + +ECMAScript support +================== + +The intention is to always support the latest ECMAScript version whose feature +set has been finalized. + +If adding support for a newer version requires changes, a new version with a +major verion bump will be released. + +Currently, ECMAScript 2018 is supported. + + +Invalid code handling +===================== + +Unterminated strings are still matched as strings. JavaScript strings cannot +contain (unescaped) newlines, so unterminated strings simply end at the end of +the line. Unterminated template strings can contain unescaped newlines, though, +so they go on to the end of input. + +Unterminated multi-line comments are also still matched as comments. They +simply go on to the end of the input. + +Unterminated regex literals are likely matched as division and whatever is +inside the regex. + +Invalid ASCII characters have their own capturing group. + +Invalid non-ASCII characters are treated as names, to simplify the matching of +names (except unicode spaces which are treated as whitespace). Note: See also +the [ES2018](#es2018) section. + +Regex literals may contain invalid regex syntax. They are still matched as +regex literals. They may also contain repeated regex flags, to keep the regex +simple. + +Strings may contain invalid escape sequences. + + +Limitations +=========== + +Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be +perfect. But that’s not the point either. + +You may compare jsTokens with [esprima] by using `esprima-compare.js`. +See `npm run esprima-compare`! + +[esprima]: http://esprima.org/ + +### Template string interpolation ### + +Template strings are matched as single tokens, from the starting `` ` `` to the +ending `` ` ``, including interpolations (whose tokens are not matched +individually). + +Matching template string interpolations requires recursive balancing of `{` and +`}`—something that JavaScript regexes cannot do. Only one level of nesting is +supported. + +### Division and regex literals collision ### + +Consider this example: + +```js +var g = 9.82 +var number = bar / 2/g + +var regex = / 2/g +``` + +A human can easily understand that in the `number` line we’re dealing with +division, and in the `regex` line we’re dealing with a regex literal. How come? +Because humans can look at the whole code to put the `/` characters in context. +A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also +look backwards. See the [ES2018](#es2018) section). + +When the `jsTokens` regex scans throught the above, it will see the following +at the end of both the `number` and `regex` rows: + +```js +/ 2/g +``` + +It is then impossible to know if that is a regex literal, or part of an +expression dealing with division. + +Here is a similar case: + +```js +foo /= 2/g +foo(/= 2/g) +``` + +The first line divides the `foo` variable with `2/g`. The second line calls the +`foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only +sees forwards, it cannot tell the two cases apart. + +There are some cases where we _can_ tell division and regex literals apart, +though. + +First off, we have the simple cases where there’s only one slash in the line: + +```js +var foo = 2/g +foo /= 2 +``` + +Regex literals cannot contain newlines, so the above cases are correctly +identified as division. Things are only problematic when there are more than +one non-comment slash in a single line. + +Secondly, not every character is a valid regex flag. + +```js +var number = bar / 2/e +``` + +The above example is also correctly identified as division, because `e` is not a +valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` +(any letter) as flags, but it is not worth it since it increases the amount of +ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are +allowed. This means that the above example will be identified as division as +long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 +characters long. + +Lastly, we can look _forward_ for information. + +- If the token following what looks like a regex literal is not valid after a + regex literal, but is valid in a division expression, then the regex literal + is treated as division instead. For example, a flagless regex cannot be + followed by a string, number or name, but all of those three can be the + denominator of a division. +- Generally, if what looks like a regex literal is followed by an operator, the + regex literal is treated as division instead. This is because regexes are + seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division + could likely be part of such an expression. + +Please consult the regex source and the test cases for precise information on +when regex or division is matched (should you need to know). In short, you +could sum it up as: + +If the end of a statement looks like a regex literal (even if it isn’t), it +will be treated as one. Otherwise it should work as expected (if you write sane +code). + +### ES2018 ### + +ES2018 added some nice regex improvements to the language. + +- [Unicode property escapes] should allow telling names and invalid non-ASCII + characters apart without blowing up the regex size. +- [Lookbehind assertions] should allow matching telling division and regex + literals apart in more cases. +- [Named capture groups] might simplify some things. + +These things would be nice to do, but are not critical. They probably have to +wait until the oldest maintained Node.js LTS release supports those features. + +[Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html +[Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html +[Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html + + +License +======= + +[MIT](LICENSE). diff --git a/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/index.js b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/index.js new file mode 100644 index 00000000..b23a4a0e --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/index.js @@ -0,0 +1,23 @@ +// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell +// License: MIT. (See LICENSE.) + +Object.defineProperty(exports, "__esModule", { + value: true +}) + +// This regex comes from regex.coffee, and is inserted here by generate-index.js +// (run `npm run build`). +exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g + +exports.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined} + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) + else if (match[ 5]) token.type = "comment" + else if (match[ 6]) token.type = "comment", token.closed = !!match[7] + else if (match[ 8]) token.type = "regex" + else if (match[ 9]) token.type = "number" + else if (match[10]) token.type = "name" + else if (match[11]) token.type = "punctuator" + else if (match[12]) token.type = "whitespace" + return token +} diff --git a/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/package.json b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/package.json new file mode 100644 index 00000000..66752fab --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/package.json @@ -0,0 +1,30 @@ +{ + "name": "js-tokens", + "version": "4.0.0", + "author": "Simon Lydell", + "license": "MIT", + "description": "A regex that tokenizes JavaScript.", + "keywords": [ + "JavaScript", + "js", + "token", + "tokenize", + "regex" + ], + "files": [ + "index.js" + ], + "repository": "lydell/js-tokens", + "scripts": { + "test": "mocha --ui tdd", + "esprima-compare": "node esprima-compare ./index.js everything.js/es5.js", + "build": "node generate-index.js", + "dev": "npm run build && npm test" + }, + "devDependencies": { + "coffeescript": "2.1.1", + "esprima": "4.0.0", + "everything.js": "1.0.3", + "mocha": "5.0.0" + } +} diff --git a/fixtures/dummy/node_modules/.pnpm/lock.yaml b/fixtures/dummy/node_modules/.pnpm/lock.yaml index f19840ee..444fa222 100644 --- a/fixtures/dummy/node_modules/.pnpm/lock.yaml +++ b/fixtures/dummy/node_modules/.pnpm/lock.yaml @@ -26,6 +26,9 @@ dependencies: mypackage: specifier: link:packages/mypackage version: link:packages/mypackage + react: + specifier: ^18.3.1 + version: 18.3.1 packages: @@ -34,6 +37,24 @@ packages: engines: {node: '>=12'} dev: false + /js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + dev: false + + /loose-envify@1.4.0: + resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} + hasBin: true + dependencies: + js-tokens: 4.0.0 + dev: false + + /react@18.3.1: + resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==} + engines: {node: '>=0.10.0'} + dependencies: + loose-envify: 1.4.0 + dev: false + file:../external/gem2: resolution: {directory: ../external/gem2, type: directory} name: gem2 diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/js-tokens b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/js-tokens new file mode 120000 index 00000000..3c2d36dd --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/js-tokens @@ -0,0 +1 @@ +../../js-tokens@4.0.0/node_modules/js-tokens \ No newline at end of file diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/LICENSE b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/LICENSE new file mode 100644 index 00000000..fbafb487 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andres Suarez + +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. diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/README.md b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/README.md new file mode 100644 index 00000000..7f4e07b0 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/README.md @@ -0,0 +1,45 @@ +# loose-envify + +[![Build Status](https://travis-ci.org/zertosh/loose-envify.svg?branch=master)](https://travis-ci.org/zertosh/loose-envify) + +Fast (and loose) selective `process.env` replacer using [js-tokens](https://github.com/lydell/js-tokens) instead of an AST. Works just like [envify](https://github.com/hughsk/envify) but much faster. + +## Gotchas + +* Doesn't handle broken syntax. +* Doesn't look inside embedded expressions in template strings. + - **this won't work:** + ```js + console.log(`the current env is ${process.env.NODE_ENV}`); + ``` +* Doesn't replace oddly-spaced or oddly-commented expressions. + - **this won't work:** + ```js + console.log(process./*won't*/env./*work*/NODE_ENV); + ``` + +## Usage/Options + +loose-envify has the exact same interface as [envify](https://github.com/hughsk/envify), including the CLI. + +## Benchmark + +``` +envify: + + $ for i in {1..5}; do node bench/bench.js 'envify'; done + 708ms + 727ms + 791ms + 719ms + 720ms + +loose-envify: + + $ for i in {1..5}; do node bench/bench.js '../'; done + 51ms + 52ms + 52ms + 52ms + 52ms +``` diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/cli.js b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/cli.js new file mode 100755 index 00000000..c0b63cb1 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/cli.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node +'use strict'; + +var looseEnvify = require('./'); +var fs = require('fs'); + +if (process.argv[2]) { + fs.createReadStream(process.argv[2], {encoding: 'utf8'}) + .pipe(looseEnvify(process.argv[2])) + .pipe(process.stdout); +} else { + process.stdin.resume() + process.stdin + .pipe(looseEnvify(__filename)) + .pipe(process.stdout); +} diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/custom.js b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/custom.js new file mode 100644 index 00000000..6389bfac --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/custom.js @@ -0,0 +1,4 @@ +// envify compatibility +'use strict'; + +module.exports = require('./loose-envify'); diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/index.js b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/index.js new file mode 100644 index 00000000..8cd8305d --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./loose-envify')(process.env); diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/loose-envify.js b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/loose-envify.js new file mode 100644 index 00000000..b5a5be22 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/loose-envify.js @@ -0,0 +1,36 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); +var replace = require('./replace'); + +var jsonExtRe = /\.json$/; + +module.exports = function(rootEnv) { + rootEnv = rootEnv || process.env; + return function (file, trOpts) { + if (jsonExtRe.test(file)) { + return stream.PassThrough(); + } + var envs = trOpts ? [rootEnv, trOpts] : [rootEnv]; + return new LooseEnvify(envs); + }; +}; + +function LooseEnvify(envs) { + stream.Transform.call(this); + this._data = ''; + this._envs = envs; +} +util.inherits(LooseEnvify, stream.Transform); + +LooseEnvify.prototype._transform = function(buf, enc, cb) { + this._data += buf; + cb(); +}; + +LooseEnvify.prototype._flush = function(cb) { + var replaced = replace(this._data, this._envs); + this.push(replaced); + cb(); +}; diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/node_modules/.bin/loose-envify b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/node_modules/.bin/loose-envify new file mode 100755 index 00000000..f430b91c --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/node_modules/.bin/loose-envify @@ -0,0 +1,17 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -z "$NODE_PATH" ]; then + export NODE_PATH="/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/node_modules:/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules:/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/node_modules" +else + export NODE_PATH="/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/node_modules:/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules:/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/node_modules:$NODE_PATH" +fi +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../../cli.js" "$@" +else + exec node "$basedir/../../cli.js" "$@" +fi diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/package.json b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/package.json new file mode 100644 index 00000000..5e3d0e27 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/package.json @@ -0,0 +1,36 @@ +{ + "name": "loose-envify", + "version": "1.4.0", + "description": "Fast (and loose) selective `process.env` replacer using js-tokens instead of an AST", + "keywords": [ + "environment", + "variables", + "browserify", + "browserify-transform", + "transform", + "source", + "configuration" + ], + "homepage": "https://github.com/zertosh/loose-envify", + "license": "MIT", + "author": "Andres Suarez ", + "main": "index.js", + "bin": { + "loose-envify": "cli.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/zertosh/loose-envify.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "devDependencies": { + "browserify": "^13.1.1", + "envify": "^3.4.0", + "tap": "^8.0.0" + } +} diff --git a/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/replace.js b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/replace.js new file mode 100644 index 00000000..ec15e81c --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/replace.js @@ -0,0 +1,65 @@ +'use strict'; + +var jsTokens = require('js-tokens').default; + +var processEnvRe = /\bprocess\.env\.[_$a-zA-Z][$\w]+\b/; +var spaceOrCommentRe = /^(?:\s|\/[/*])/; + +function replace(src, envs) { + if (!processEnvRe.test(src)) { + return src; + } + + var out = []; + var purge = envs.some(function(env) { + return env._ && env._.indexOf('purge') !== -1; + }); + + jsTokens.lastIndex = 0 + var parts = src.match(jsTokens); + + for (var i = 0; i < parts.length; i++) { + if (parts[i ] === 'process' && + parts[i + 1] === '.' && + parts[i + 2] === 'env' && + parts[i + 3] === '.') { + var prevCodeToken = getAdjacentCodeToken(-1, parts, i); + var nextCodeToken = getAdjacentCodeToken(1, parts, i + 4); + var replacement = getReplacementString(envs, parts[i + 4], purge); + if (prevCodeToken !== '.' && + nextCodeToken !== '.' && + nextCodeToken !== '=' && + typeof replacement === 'string') { + out.push(replacement); + i += 4; + continue; + } + } + out.push(parts[i]); + } + + return out.join(''); +} + +function getAdjacentCodeToken(dir, parts, i) { + while (true) { + var part = parts[i += dir]; + if (!spaceOrCommentRe.test(part)) { + return part; + } + } +} + +function getReplacementString(envs, name, purge) { + for (var j = 0; j < envs.length; j++) { + var env = envs[j]; + if (typeof env[name] !== 'undefined') { + return JSON.stringify(env[name]); + } + } + if (purge) { + return 'undefined'; + } +} + +module.exports = replace; diff --git a/fixtures/dummy/node_modules/.pnpm/node_modules/.bin/loose-envify b/fixtures/dummy/node_modules/.pnpm/node_modules/.bin/loose-envify new file mode 100755 index 00000000..98e732c9 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/node_modules/.bin/loose-envify @@ -0,0 +1,17 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -z "$NODE_PATH" ]; then + export NODE_PATH="/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/node_modules:/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules:/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/node_modules" +else + export NODE_PATH="/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules/loose-envify/node_modules:/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/loose-envify@1.4.0/node_modules:/Users/joelmoss/dev/proscenium/fixtures/dummy/node_modules/.pnpm/node_modules:$NODE_PATH" +fi +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../loose-envify/cli.js" "$@" +else + exec node "$basedir/../loose-envify/cli.js" "$@" +fi diff --git a/fixtures/dummy/node_modules/.pnpm/node_modules/js-tokens b/fixtures/dummy/node_modules/.pnpm/node_modules/js-tokens new file mode 120000 index 00000000..69ced252 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/node_modules/js-tokens @@ -0,0 +1 @@ +../js-tokens@4.0.0/node_modules/js-tokens \ No newline at end of file diff --git a/fixtures/dummy/node_modules/.pnpm/node_modules/loose-envify b/fixtures/dummy/node_modules/.pnpm/node_modules/loose-envify new file mode 120000 index 00000000..81ade23b --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/node_modules/loose-envify @@ -0,0 +1 @@ +../loose-envify@1.4.0/node_modules/loose-envify \ No newline at end of file diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/loose-envify b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/loose-envify new file mode 120000 index 00000000..3dd74c09 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/loose-envify @@ -0,0 +1 @@ +../../loose-envify@1.4.0/node_modules/loose-envify \ No newline at end of file diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/LICENSE b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/LICENSE new file mode 100644 index 00000000..b96dcb04 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +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. diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/README.md b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/README.md new file mode 100644 index 00000000..826563e1 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/README.md @@ -0,0 +1,37 @@ +# `react` + +React is a JavaScript library for creating user interfaces. + +The `react` package contains only the functionality necessary to define React components. It is typically used together with a React renderer like `react-dom` for the web, or `react-native` for the native environments. + +**Note:** by default, React will be in development mode. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages. Don't forget to use the [production build](https://reactjs.org/docs/optimizing-performance.html#use-the-production-build) when deploying your application. + +## Usage + +```js +import { useState } from 'react'; +import { createRoot } from 'react-dom/client'; + +function Counter() { + const [count, setCount] = useState(0); + return ( + <> +

{count}

+ + + ); +} + +const root = createRoot(document.getElementById('root')); +root.render(); +``` + +## Documentation + +See https://reactjs.org/ + +## API + +See https://reactjs.org/docs/react-api.html diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.development.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.development.js new file mode 100644 index 00000000..f47788bc --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.development.js @@ -0,0 +1,1315 @@ +/** + * @license React + * react-jsx-dev-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var React = require('react'); + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PORTAL_TYPE = Symbol.for('react.portal'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); +var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_CONTEXT_TYPE = Symbol.for('react.context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +// ----------------------------------------------------------------------------- + +var enableScopeAPI = false; // Experimental Create Event Handle API. +var enableCacheElement = false; +var enableTransitionTracing = false; // No known bugs, but needs performance testing + +var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber +// stuff. Intended to enable React core members to more easily debug scheduling +// issues in DEV builds. + +var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + +var REACT_MODULE_REFERENCE; + +{ + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); +} + +function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + + return false; +} + +function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + + if (displayName) { + return displayName; + } + + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; +} // Keep in sync with react-reconciler/getComponentNameFromFiber + + +function getContextName(type) { + return type.displayName || 'Context'; +} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + +function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + + if (outerName !== null) { + return outerName; + } + + return getComponentNameFromType(type.type) || 'Memo'; + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + + return null; +} + +var assign = Object.assign; + +// Helpers to patch console.logs to avoid logging during side-effect free +// replaying on render function. This currently only patches the object +// lazily which won't cover if the log function was extracted eagerly. +// We could also eagerly patch the method. +var disabledDepth = 0; +var prevLog; +var prevInfo; +var prevWarn; +var prevError; +var prevGroup; +var prevGroupCollapsed; +var prevGroupEnd; + +function disabledLog() {} + +disabledLog.__reactDisabledLog = true; +function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } +} +function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } +} + +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var prefix; +function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } +} +var reentry = false; +var componentFrameCache; + +{ + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); +} + +function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; +} +function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } +} + +function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); +} + +function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var loggedTypeFailures = {}; +var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + +function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } +} + +function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + + setCurrentlyValidatingElement(null); + } + + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + + error('Failed %s type: %s', location, error$1.message); + + setCurrentlyValidatingElement(null); + } + } + } + } +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +/* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ +// $FlowFixMe only called in DEV, so void return is not possible. +function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } +} // $FlowFixMe only called in DEV, so void return is not possible. + + +function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } +} + +function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; +} +function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} + +var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; +var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true +}; +var specialPropKeyWarningShown; +var specialPropRefWarningShown; +var didWarnAboutStringRefs; + +{ + didWarnAboutStringRefs = {}; +} + +function hasValidRef(config) { + { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.ref !== undefined; +} + +function hasValidKey(config) { + { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.key !== undefined; +} + +function warnIfStringRefCannotBeAutoConverted(config, self) { + { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); + + didWarnAboutStringRefs[componentName] = true; + } + } + } +} + +function defineKeyPropWarningGetter(props, displayName) { + { + var warnAboutAccessingKey = function () { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + + error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + }; + + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); + } +} + +function defineRefPropWarningGetter(props, displayName) { + { + var warnAboutAccessingRef = function () { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + + error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + }; + + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); + } +} +/** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ + + +var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + + { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + + return element; +}; +/** + * https://github.com/reactjs/rfcs/pull/107 + * @param {*} type + * @param {object} props + * @param {string} key + */ + +function jsxDEV(type, config, maybeKey, source, self) { + { + var propName; // Reserved names are extracted + + var props = {}; + var key = null; + var ref = null; // Currently, key can be spread in as a prop. This causes a potential + // issue if key is also explicitly declared (ie.
+ // or
). We want to deprecate key spread, + // but as an intermediary step, we will use jsxDEV for everything except + //
, because we aren't currently able to tell if + // key is explicitly declared to be undefined or not. + + if (maybeKey !== undefined) { + { + checkKeyStringCoercion(maybeKey); + } + + key = '' + maybeKey; + } + + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + + key = '' + config.key; + } + + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config, self); + } // Remaining properties are added to a new props object + + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } // Resolve default props + + + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + } + + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); + } +} + +var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; +var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + +function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } +} + +var propTypesMisspellWarningShown; + +{ + propTypesMisspellWarningShown = false; +} +/** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ + + +function isValidElement(object) { + { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } +} + +function getDeclarationErrorAddendum() { + { + if (ReactCurrentOwner$1.current) { + var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); + + if (name) { + return '\n\nCheck the render method of `' + name + '`.'; + } + } + + return ''; + } +} + +function getSourceInfoErrorAddendum(source) { + { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + + return ''; + } +} +/** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ + + +var ownerHasKeyUseWarning = {}; + +function getCurrentComponentErrorInfo(parentType) { + { + var info = getDeclarationErrorAddendum(); + + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + + return info; + } +} +/** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ + + +function validateExplicitKey(element, parentType) { + { + if (!element._store || element._store.validated || element.key != null) { + return; + } + + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + + var childOwner = ''; + + if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { + // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + + setCurrentlyValidatingElement$1(element); + + error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + + setCurrentlyValidatingElement$1(null); + } +} +/** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ + + +function validateChildKeys(node, parentType) { + { + if (typeof node !== 'object') { + return; + } + + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + + if (typeof iteratorFn === 'function') { + // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } +} +/** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ + + +function validatePropTypes(element) { + { + var type = element.type; + + if (type === null || type === undefined || typeof type === 'string') { + return; + } + + var propTypes; + + if (typeof type === 'function') { + propTypes = type.propTypes; + } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + + var _name = getComponentNameFromType(type); + + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { + error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); + } + } +} +/** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ + + +function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); + + setCurrentlyValidatingElement$1(null); + break; + } + } + + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + + setCurrentlyValidatingElement$1(null); + } + } +} + +var didWarnAboutKeySpread = {}; +function jsxWithValidation(type, props, key, isStaticChildren, source, self) { + { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + + if (!validType) { + var info = ''; + + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; + } + + var sourceInfo = getSourceInfoErrorAddendum(source); + + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + + var typeString; + + if (type === null) { + typeString = 'null'; + } else if (isArray(type)) { + typeString = 'array'; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else { + typeString = typeof type; + } + + error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); + } + + var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + + if (element == null) { + return element; + } // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + + + if (validType) { + var children = props.children; + + if (children !== undefined) { + if (isStaticChildren) { + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + validateChildKeys(children[i], type); + } + + if (Object.freeze) { + Object.freeze(children); + } + } else { + error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); + } + } else { + validateChildKeys(children, type); + } + } + } + + { + if (hasOwnProperty.call(props, 'key')) { + var componentName = getComponentNameFromType(type); + var keys = Object.keys(props).filter(function (k) { + return k !== 'key'; + }); + var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}'; + + if (!didWarnAboutKeySpread[componentName + beforeExample]) { + var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}'; + + error('A props object containing a "key" prop is being spread into JSX:\n' + ' let props = %s;\n' + ' <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + ' let props = %s;\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName); + + didWarnAboutKeySpread[componentName + beforeExample] = true; + } + } + } + + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + + return element; + } +} // These two functions exist to still get child warnings in dev + +var jsxDEV$1 = jsxWithValidation ; + +exports.Fragment = REACT_FRAGMENT_TYPE; +exports.jsxDEV = jsxDEV$1; + })(); +} diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.production.min.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.production.min.js new file mode 100644 index 00000000..d117ce37 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.production.min.js @@ -0,0 +1,10 @@ +/** + * @license React + * react-jsx-dev-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var a=Symbol.for("react.fragment");exports.Fragment=a;exports.jsxDEV=void 0; diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.profiling.min.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.profiling.min.js new file mode 100644 index 00000000..1d8cf154 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-dev-runtime.profiling.min.js @@ -0,0 +1,10 @@ +/** + * @license React + * react-jsx-dev-runtime.profiling.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var a=Symbol.for("react.fragment");exports.Fragment=a;exports.jsxDEV=void 0; diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js new file mode 100644 index 00000000..8827d8bc --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js @@ -0,0 +1,1333 @@ +/** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var React = require('react'); + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PORTAL_TYPE = Symbol.for('react.portal'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); +var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_CONTEXT_TYPE = Symbol.for('react.context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +// ----------------------------------------------------------------------------- + +var enableScopeAPI = false; // Experimental Create Event Handle API. +var enableCacheElement = false; +var enableTransitionTracing = false; // No known bugs, but needs performance testing + +var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber +// stuff. Intended to enable React core members to more easily debug scheduling +// issues in DEV builds. + +var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + +var REACT_MODULE_REFERENCE; + +{ + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); +} + +function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + + return false; +} + +function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + + if (displayName) { + return displayName; + } + + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; +} // Keep in sync with react-reconciler/getComponentNameFromFiber + + +function getContextName(type) { + return type.displayName || 'Context'; +} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + +function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + + if (outerName !== null) { + return outerName; + } + + return getComponentNameFromType(type.type) || 'Memo'; + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + + return null; +} + +var assign = Object.assign; + +// Helpers to patch console.logs to avoid logging during side-effect free +// replaying on render function. This currently only patches the object +// lazily which won't cover if the log function was extracted eagerly. +// We could also eagerly patch the method. +var disabledDepth = 0; +var prevLog; +var prevInfo; +var prevWarn; +var prevError; +var prevGroup; +var prevGroupCollapsed; +var prevGroupEnd; + +function disabledLog() {} + +disabledLog.__reactDisabledLog = true; +function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } +} +function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } +} + +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var prefix; +function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } +} +var reentry = false; +var componentFrameCache; + +{ + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); +} + +function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; +} +function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } +} + +function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); +} + +function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var loggedTypeFailures = {}; +var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + +function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } +} + +function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + + setCurrentlyValidatingElement(null); + } + + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + + error('Failed %s type: %s', location, error$1.message); + + setCurrentlyValidatingElement(null); + } + } + } + } +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +/* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ +// $FlowFixMe only called in DEV, so void return is not possible. +function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } +} // $FlowFixMe only called in DEV, so void return is not possible. + + +function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } +} + +function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; +} +function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} + +var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; +var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true +}; +var specialPropKeyWarningShown; +var specialPropRefWarningShown; +var didWarnAboutStringRefs; + +{ + didWarnAboutStringRefs = {}; +} + +function hasValidRef(config) { + { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.ref !== undefined; +} + +function hasValidKey(config) { + { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.key !== undefined; +} + +function warnIfStringRefCannotBeAutoConverted(config, self) { + { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); + + didWarnAboutStringRefs[componentName] = true; + } + } + } +} + +function defineKeyPropWarningGetter(props, displayName) { + { + var warnAboutAccessingKey = function () { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + + error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + }; + + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); + } +} + +function defineRefPropWarningGetter(props, displayName) { + { + var warnAboutAccessingRef = function () { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + + error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + }; + + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); + } +} +/** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ + + +var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + + { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + + return element; +}; +/** + * https://github.com/reactjs/rfcs/pull/107 + * @param {*} type + * @param {object} props + * @param {string} key + */ + +function jsxDEV(type, config, maybeKey, source, self) { + { + var propName; // Reserved names are extracted + + var props = {}; + var key = null; + var ref = null; // Currently, key can be spread in as a prop. This causes a potential + // issue if key is also explicitly declared (ie.
+ // or
). We want to deprecate key spread, + // but as an intermediary step, we will use jsxDEV for everything except + //
, because we aren't currently able to tell if + // key is explicitly declared to be undefined or not. + + if (maybeKey !== undefined) { + { + checkKeyStringCoercion(maybeKey); + } + + key = '' + maybeKey; + } + + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + + key = '' + config.key; + } + + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config, self); + } // Remaining properties are added to a new props object + + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } // Resolve default props + + + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + } + + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); + } +} + +var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; +var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + +function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } +} + +var propTypesMisspellWarningShown; + +{ + propTypesMisspellWarningShown = false; +} +/** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ + + +function isValidElement(object) { + { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } +} + +function getDeclarationErrorAddendum() { + { + if (ReactCurrentOwner$1.current) { + var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); + + if (name) { + return '\n\nCheck the render method of `' + name + '`.'; + } + } + + return ''; + } +} + +function getSourceInfoErrorAddendum(source) { + { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + + return ''; + } +} +/** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ + + +var ownerHasKeyUseWarning = {}; + +function getCurrentComponentErrorInfo(parentType) { + { + var info = getDeclarationErrorAddendum(); + + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + + return info; + } +} +/** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ + + +function validateExplicitKey(element, parentType) { + { + if (!element._store || element._store.validated || element.key != null) { + return; + } + + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + + var childOwner = ''; + + if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { + // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + + setCurrentlyValidatingElement$1(element); + + error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + + setCurrentlyValidatingElement$1(null); + } +} +/** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ + + +function validateChildKeys(node, parentType) { + { + if (typeof node !== 'object') { + return; + } + + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + + if (typeof iteratorFn === 'function') { + // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } +} +/** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ + + +function validatePropTypes(element) { + { + var type = element.type; + + if (type === null || type === undefined || typeof type === 'string') { + return; + } + + var propTypes; + + if (typeof type === 'function') { + propTypes = type.propTypes; + } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + + var _name = getComponentNameFromType(type); + + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { + error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); + } + } +} +/** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ + + +function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); + + setCurrentlyValidatingElement$1(null); + break; + } + } + + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + + setCurrentlyValidatingElement$1(null); + } + } +} + +var didWarnAboutKeySpread = {}; +function jsxWithValidation(type, props, key, isStaticChildren, source, self) { + { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + + if (!validType) { + var info = ''; + + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; + } + + var sourceInfo = getSourceInfoErrorAddendum(source); + + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + + var typeString; + + if (type === null) { + typeString = 'null'; + } else if (isArray(type)) { + typeString = 'array'; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else { + typeString = typeof type; + } + + error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); + } + + var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + + if (element == null) { + return element; + } // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + + + if (validType) { + var children = props.children; + + if (children !== undefined) { + if (isStaticChildren) { + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + validateChildKeys(children[i], type); + } + + if (Object.freeze) { + Object.freeze(children); + } + } else { + error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); + } + } else { + validateChildKeys(children, type); + } + } + } + + { + if (hasOwnProperty.call(props, 'key')) { + var componentName = getComponentNameFromType(type); + var keys = Object.keys(props).filter(function (k) { + return k !== 'key'; + }); + var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}'; + + if (!didWarnAboutKeySpread[componentName + beforeExample]) { + var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}'; + + error('A props object containing a "key" prop is being spread into JSX:\n' + ' let props = %s;\n' + ' <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + ' let props = %s;\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName); + + didWarnAboutKeySpread[componentName + beforeExample] = true; + } + } + } + + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + + return element; + } +} // These two functions exist to still get child warnings in dev +// even with the prod transform. This means that jsxDEV is purely +// opt-in behavior for better messages but that we won't stop +// giving you warnings if you use production apis. + +function jsxWithValidationStatic(type, props, key) { + { + return jsxWithValidation(type, props, key, true); + } +} +function jsxWithValidationDynamic(type, props, key) { + { + return jsxWithValidation(type, props, key, false); + } +} + +var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children. +// for now we can ship identical prod functions + +var jsxs = jsxWithValidationStatic ; + +exports.Fragment = REACT_FRAGMENT_TYPE; +exports.jsx = jsx; +exports.jsxs = jsxs; + })(); +} diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.production.min.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.production.min.js new file mode 100644 index 00000000..6d1e3a38 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.production.min.js @@ -0,0 +1,11 @@ +/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var f=require("react"),k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0}; +function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q; diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.profiling.min.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.profiling.min.js new file mode 100644 index 00000000..a392b065 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.profiling.min.js @@ -0,0 +1,11 @@ +/** + * @license React + * react-jsx-runtime.profiling.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var f=require("react"),k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0}; +function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q; diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js new file mode 100644 index 00000000..87359908 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js @@ -0,0 +1,2740 @@ +/** + * @license React + * react.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { + + 'use strict'; + +/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ +if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === + 'function' +) { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); +} + var ReactVersion = '18.3.1'; + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PORTAL_TYPE = Symbol.for('react.portal'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); +var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_CONTEXT_TYPE = Symbol.for('react.context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +/** + * Keeps track of the current dispatcher. + */ +var ReactCurrentDispatcher = { + /** + * @internal + * @type {ReactComponent} + */ + current: null +}; + +/** + * Keeps track of the current batch's configuration such as how long an update + * should suspend for if it needs to. + */ +var ReactCurrentBatchConfig = { + transition: null +}; + +var ReactCurrentActQueue = { + current: null, + // Used to reproduce behavior of `batchedUpdates` in legacy mode. + isBatchingLegacy: false, + didScheduleLegacyUpdate: false +}; + +/** + * Keeps track of the current owner. + * + * The current owner is the component who should own any components that are + * currently being constructed. + */ +var ReactCurrentOwner = { + /** + * @internal + * @type {ReactComponent} + */ + current: null +}; + +var ReactDebugCurrentFrame = {}; +var currentExtraStackFrame = null; +function setExtraStackFrame(stack) { + { + currentExtraStackFrame = stack; + } +} + +{ + ReactDebugCurrentFrame.setExtraStackFrame = function (stack) { + { + currentExtraStackFrame = stack; + } + }; // Stack implementation injected by the current renderer. + + + ReactDebugCurrentFrame.getCurrentStack = null; + + ReactDebugCurrentFrame.getStackAddendum = function () { + var stack = ''; // Add an extra top frame while an element is being validated + + if (currentExtraStackFrame) { + stack += currentExtraStackFrame; + } // Delegate to the injected renderer-specific implementation + + + var impl = ReactDebugCurrentFrame.getCurrentStack; + + if (impl) { + stack += impl() || ''; + } + + return stack; + }; +} + +// ----------------------------------------------------------------------------- + +var enableScopeAPI = false; // Experimental Create Event Handle API. +var enableCacheElement = false; +var enableTransitionTracing = false; // No known bugs, but needs performance testing + +var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber +// stuff. Intended to enable React core members to more easily debug scheduling +// issues in DEV builds. + +var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + +var ReactSharedInternals = { + ReactCurrentDispatcher: ReactCurrentDispatcher, + ReactCurrentBatchConfig: ReactCurrentBatchConfig, + ReactCurrentOwner: ReactCurrentOwner +}; + +{ + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; +} + +// by calls to these methods by a Babel plugin. +// +// In PROD (or in packages without access to React internals), +// they are left as they are instead. + +function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } + } +} +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +var didWarnStateUpdateForUnmountedComponent = {}; + +function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; + var warningKey = componentName + "." + callerName; + + if (didWarnStateUpdateForUnmountedComponent[warningKey]) { + return; + } + + error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); + + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } +} +/** + * This is the abstract API for an update queue. + */ + + +var ReactNoopUpdateQueue = { + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function (publicInstance) { + return false; + }, + + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueForceUpdate: function (publicInstance, callback, callerName) { + warnNoop(publicInstance, 'forceUpdate'); + }, + + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { + warnNoop(publicInstance, 'replaceState'); + }, + + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @param {?function} callback Called after component is updated. + * @param {?string} Name of the calling function in the public API. + * @internal + */ + enqueueSetState: function (publicInstance, partialState, callback, callerName) { + warnNoop(publicInstance, 'setState'); + } +}; + +var assign = Object.assign; + +var emptyObject = {}; + +{ + Object.freeze(emptyObject); +} +/** + * Base class helpers for the updating state of a component. + */ + + +function Component(props, context, updater) { + this.props = props; + this.context = context; // If a component has string refs, we will assign a different object later. + + this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the + // renderer. + + this.updater = updater || ReactNoopUpdateQueue; +} + +Component.prototype.isReactComponent = {}; +/** + * Sets a subset of the state. Always use this to mutate + * state. You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * There is no guarantee that calls to `setState` will run synchronously, + * as they may eventually be batched together. You can provide an optional + * callback that will be executed when the call to setState is actually + * completed. + * + * When a function is provided to setState, it will be called at some point in + * the future (not synchronously). It will be called with the up to date + * component arguments (state, props, context). These values can be different + * from this.* because your function may be called after receiveProps but before + * shouldComponentUpdate, and this new state, props, and context will not yet be + * assigned to this. + * + * @param {object|function} partialState Next partial state or function to + * produce next partial state to be merged with current state. + * @param {?function} callback Called after state is updated. + * @final + * @protected + */ + +Component.prototype.setState = function (partialState, callback) { + if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) { + throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.'); + } + + this.updater.enqueueSetState(this, partialState, callback, 'setState'); +}; +/** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {?function} callback Called after update is complete. + * @final + * @protected + */ + + +Component.prototype.forceUpdate = function (callback) { + this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); +}; +/** + * Deprecated APIs. These APIs used to exist on classic React classes but since + * we would like to deprecate them, we're not going to move them over to this + * modern base class. Instead, we define a getter that warns if it's accessed. + */ + + +{ + var deprecatedAPIs = { + isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], + replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] + }; + + var defineDeprecationWarning = function (methodName, info) { + Object.defineProperty(Component.prototype, methodName, { + get: function () { + warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); + + return undefined; + } + }); + }; + + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } +} + +function ComponentDummy() {} + +ComponentDummy.prototype = Component.prototype; +/** + * Convenience component with default shallow equality check for sCU. + */ + +function PureComponent(props, context, updater) { + this.props = props; + this.context = context; // If a component has string refs, we will assign a different object later. + + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; +} + +var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); +pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. + +assign(pureComponentPrototype, Component.prototype); +pureComponentPrototype.isPureReactComponent = true; + +// an immutable object with a single mutable value +function createRef() { + var refObject = { + current: null + }; + + { + Object.seal(refObject); + } + + return refObject; +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +/* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ +// $FlowFixMe only called in DEV, so void return is not possible. +function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } +} // $FlowFixMe only called in DEV, so void return is not possible. + + +function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } +} + +function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; +} +function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} + +function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + + if (displayName) { + return displayName; + } + + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; +} // Keep in sync with react-reconciler/getComponentNameFromFiber + + +function getContextName(type) { + return type.displayName || 'Context'; +} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + +function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + + if (outerName !== null) { + return outerName; + } + + return getComponentNameFromType(type.type) || 'Memo'; + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + + return null; +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true +}; +var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; + +{ + didWarnAboutStringRefs = {}; +} + +function hasValidRef(config) { + { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.ref !== undefined; +} + +function hasValidKey(config) { + { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.key !== undefined; +} + +function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function () { + { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + + error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + } + }; + + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); +} + +function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function () { + { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + + error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + } + }; + + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); +} + +function warnIfStringRefCannotBeAutoConverted(config) { + { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); + + didWarnAboutStringRefs[componentName] = true; + } + } + } +} +/** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ + + +var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + + { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + + return element; +}; +/** + * Create and return a new ReactElement of the given type. + * See https://reactjs.org/docs/react-api.html#createelement + */ + +function createElement(type, config, children) { + var propName; // Reserved names are extracted + + var props = {}; + var key = null; + var ref = null; + var self = null; + var source = null; + + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + + { + warnIfStringRefCannotBeAutoConverted(config); + } + } + + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + + key = '' + config.key; + } + + self = config.__self === undefined ? null : config.__self; + source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + + + var childrenLength = arguments.length - 2; + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + + { + if (Object.freeze) { + Object.freeze(childArray); + } + } + + props.children = childArray; + } // Resolve default props + + + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + } + + { + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + } + + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); +} +function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + return newElement; +} +/** + * Clone and return a new ReactElement using element as the starting point. + * See https://reactjs.org/docs/react-api.html#cloneelement + */ + +function cloneElement(element, config, children) { + if (element === null || element === undefined) { + throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); + } + + var propName; // Original props are copied + + var props = assign({}, element.props); // Reserved names are extracted + + var key = element.key; + var ref = element.ref; // Self is preserved since the owner is preserved. + + var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a + // transpiler, and the original source is probably a better indicator of the + // true owner. + + var source = element._source; // Owner will be preserved, unless ref is overridden + + var owner = element._owner; + + if (config != null) { + if (hasValidRef(config)) { + // Silently steal the ref from the parent. + ref = config.ref; + owner = ReactCurrentOwner.current; + } + + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + + key = '' + config.key; + } // Remaining properties override existing props + + + var defaultProps; + + if (element.type && element.type.defaultProps) { + defaultProps = element.type.defaultProps; + } + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + if (config[propName] === undefined && defaultProps !== undefined) { + // Resolve default props + props[propName] = defaultProps[propName]; + } else { + props[propName] = config[propName]; + } + } + } + } // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + + + var childrenLength = arguments.length - 2; + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + + props.children = childArray; + } + + return ReactElement(element.type, key, ref, self, source, owner, props); +} +/** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ + +function isValidElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; +} + +var SEPARATOR = '.'; +var SUBSEPARATOR = ':'; +/** + * Escape and wrap key so it is safe to use as a reactid + * + * @param {string} key to be escaped. + * @return {string} the escaped key. + */ + +function escape(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + '=': '=0', + ':': '=2' + }; + var escapedString = key.replace(escapeRegex, function (match) { + return escaperLookup[match]; + }); + return '$' + escapedString; +} +/** + * TODO: Test that a single child and an array with one item have the same key + * pattern. + */ + + +var didWarnAboutMaps = false; +var userProvidedKeyEscapeRegex = /\/+/g; + +function escapeUserProvidedKey(text) { + return text.replace(userProvidedKeyEscapeRegex, '$&/'); +} +/** + * Generate a key string that identifies a element within a set. + * + * @param {*} element A element that could contain a manual key. + * @param {number} index Index that is used if a manual key is not provided. + * @return {string} + */ + + +function getElementKey(element, index) { + // Do some typechecking here since we call this blindly. We want to ensure + // that we don't block potential future ES APIs. + if (typeof element === 'object' && element !== null && element.key != null) { + // Explicit key + { + checkKeyStringCoercion(element.key); + } + + return escape('' + element.key); + } // Implicit key determined by the index in the set + + + return index.toString(36); +} + +function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + + if (type === 'undefined' || type === 'boolean') { + // All of the above are perceived as null. + children = null; + } + + var invokeCallback = false; + + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case 'string': + case 'number': + invokeCallback = true; + break; + + case 'object': + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + + } + } + + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array + // so that it's consistent if the number of children grows: + + var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; + + if (isArray(mappedChild)) { + var escapedChildKey = ''; + + if (childKey != null) { + escapedChildKey = escapeUserProvidedKey(childKey) + '/'; + } + + mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) { + return c; + }); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) { + { + // The `if` statement here prevents auto-disabling of the safe + // coercion ESLint rule, so we must manually disable it below. + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { + checkKeyStringCoercion(mappedChild.key); + } + } + + mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as + // traverseAllChildren used to do for objects as children + escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number + // eslint-disable-next-line react-internal/safe-string-coercion + escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey); + } + + array.push(mappedChild); + } + + return 1; + } + + var child; + var nextName; + var subtreeCount = 0; // Count of children found in the current subtree. + + var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; + + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getElementKey(child, i); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else { + var iteratorFn = getIteratorFn(children); + + if (typeof iteratorFn === 'function') { + var iterableChildren = children; + + { + // Warn about using Maps as children + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) { + warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); + } + + didWarnAboutMaps = true; + } + } + + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii = 0; + + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii++); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else if (type === 'object') { + // eslint-disable-next-line react-internal/safe-string-coercion + var childrenString = String(children); + throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); + } + } + + return subtreeCount; +} + +/** + * Maps children that are typically specified as `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenmap + * + * The provided mapFunction(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} func The map function. + * @param {*} context Context for mapFunction. + * @return {object} Object containing the ordered map of results. + */ +function mapChildren(children, func, context) { + if (children == null) { + return children; + } + + var result = []; + var count = 0; + mapIntoArray(children, result, '', '', function (child) { + return func.call(context, child, count++); + }); + return result; +} +/** + * Count the number of children that are typically specified as + * `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrencount + * + * @param {?*} children Children tree container. + * @return {number} The number of children. + */ + + +function countChildren(children) { + var n = 0; + mapChildren(children, function () { + n++; // Don't return anything + }); + return n; +} + +/** + * Iterates through children that are typically specified as `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenforeach + * + * The provided forEachFunc(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} forEachFunc + * @param {*} forEachContext Context for forEachContext. + */ +function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren(children, function () { + forEachFunc.apply(this, arguments); // Don't return anything. + }, forEachContext); +} +/** + * Flatten a children object (typically specified as `props.children`) and + * return an array with appropriately re-keyed children. + * + * See https://reactjs.org/docs/react-api.html#reactchildrentoarray + */ + + +function toArray(children) { + return mapChildren(children, function (child) { + return child; + }) || []; +} +/** + * Returns the first child in a collection of children and verifies that there + * is only one child in the collection. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenonly + * + * The current implementation of this function assumes that a single child gets + * passed without a wrapper, but the purpose of this helper function is to + * abstract away the particular structure of children. + * + * @param {?object} children Child collection structure. + * @return {ReactElement} The first and only `ReactElement` contained in the + * structure. + */ + + +function onlyChild(children) { + if (!isValidElement(children)) { + throw new Error('React.Children.only expected to receive a single React element child.'); + } + + return children; +} + +function createContext(defaultValue) { + // TODO: Second argument used to be an optional `calculateChangedBits` + // function. Warn to reserve for future use? + var context = { + $$typeof: REACT_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: defaultValue, + _currentValue2: defaultValue, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + // Add these to use same hidden class in VM as ServerContext + _defaultValue: null, + _globalName: null + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + + { + // A separate object, but proxies back to the original context object for + // backwards compatibility. It has a different $$typeof, so we can properly + // warn for the incorrect usage of Context as a Consumer. + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context + }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here + + Object.defineProperties(Consumer, { + Provider: { + get: function () { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + + error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + + return context.Provider; + }, + set: function (_Provider) { + context.Provider = _Provider; + } + }, + _currentValue: { + get: function () { + return context._currentValue; + }, + set: function (_currentValue) { + context._currentValue = _currentValue; + } + }, + _currentValue2: { + get: function () { + return context._currentValue2; + }, + set: function (_currentValue2) { + context._currentValue2 = _currentValue2; + } + }, + _threadCount: { + get: function () { + return context._threadCount; + }, + set: function (_threadCount) { + context._threadCount = _threadCount; + } + }, + Consumer: { + get: function () { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + + error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + + return context.Consumer; + } + }, + displayName: { + get: function () { + return context.displayName; + }, + set: function (displayName) { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName); + + hasWarnedAboutDisplayNameOnConsumer = true; + } + } + } + }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty + + context.Consumer = Consumer; + } + + { + context._currentRenderer = null; + context._currentRenderer2 = null; + } + + return context; +} + +var Uninitialized = -1; +var Pending = 0; +var Resolved = 1; +var Rejected = 2; + +function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); // Transition to the next state. + // This might throw either because it's missing or throws. If so, we treat it + // as still uninitialized and try again next time. Which is the same as what + // happens if the ctor or any wrappers processing the ctor throws. This might + // end up fixing it if the resolution was a concurrency bug. + + thenable.then(function (moduleObject) { + if (payload._status === Pending || payload._status === Uninitialized) { + // Transition to the next state. + var resolved = payload; + resolved._status = Resolved; + resolved._result = moduleObject; + } + }, function (error) { + if (payload._status === Pending || payload._status === Uninitialized) { + // Transition to the next state. + var rejected = payload; + rejected._status = Rejected; + rejected._result = error; + } + }); + + if (payload._status === Uninitialized) { + // In case, we're still uninitialized, then we're waiting for the thenable + // to resolve. Set it as pending in the meantime. + var pending = payload; + pending._status = Pending; + pending._result = thenable; + } + } + + if (payload._status === Resolved) { + var moduleObject = payload._result; + + { + if (moduleObject === undefined) { + error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. + 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject); + } + } + + { + if (!('default' in moduleObject)) { + error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. + 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject); + } + } + + return moduleObject.default; + } else { + throw payload._result; + } +} + +function lazy(ctor) { + var payload = { + // We use these fields to store the result. + _status: Uninitialized, + _result: ctor + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer + }; + + { + // In production, this would just set it on the object. + var defaultProps; + var propTypes; // $FlowFixMe + + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: function () { + return defaultProps; + }, + set: function (newDefaultProps) { + error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); + + defaultProps = newDefaultProps; // Match production behavior more closely: + // $FlowFixMe + + Object.defineProperty(lazyType, 'defaultProps', { + enumerable: true + }); + } + }, + propTypes: { + configurable: true, + get: function () { + return propTypes; + }, + set: function (newPropTypes) { + error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); + + propTypes = newPropTypes; // Match production behavior more closely: + // $FlowFixMe + + Object.defineProperty(lazyType, 'propTypes', { + enumerable: true + }); + } + } + }); + } + + return lazyType; +} + +function forwardRef(render) { + { + if (render != null && render.$$typeof === REACT_MEMO_TYPE) { + error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); + } else if (typeof render !== 'function') { + error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); + } else { + if (render.length !== 0 && render.length !== 2) { + error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); + } + } + + if (render != null) { + if (render.defaultProps != null || render.propTypes != null) { + error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?'); + } + } + } + + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: render + }; + + { + var ownName; + Object.defineProperty(elementType, 'displayName', { + enumerable: false, + configurable: true, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; // The inner component shouldn't inherit this display name in most cases, + // because the component may be used elsewhere. + // But it's nice for anonymous functions to inherit the name, + // so that our component-stack generation logic will display their frames. + // An anonymous function generally suggests a pattern like: + // React.forwardRef((props, ref) => {...}); + // This kind of inner function is not used elsewhere so the side effect is okay. + + if (!render.name && !render.displayName) { + render.displayName = name; + } + } + }); + } + + return elementType; +} + +var REACT_MODULE_REFERENCE; + +{ + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); +} + +function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + + return false; +} + +function memo(type, compare) { + { + if (!isValidElementType(type)) { + error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); + } + } + + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type: type, + compare: compare === undefined ? null : compare + }; + + { + var ownName; + Object.defineProperty(elementType, 'displayName', { + enumerable: false, + configurable: true, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; // The inner component shouldn't inherit this display name in most cases, + // because the component may be used elsewhere. + // But it's nice for anonymous functions to inherit the name, + // so that our component-stack generation logic will display their frames. + // An anonymous function generally suggests a pattern like: + // React.memo((props) => {...}); + // This kind of inner function is not used elsewhere so the side effect is okay. + + if (!type.name && !type.displayName) { + type.displayName = name; + } + } + }); + } + + return elementType; +} + +function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + + { + if (dispatcher === null) { + error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); + } + } // Will result in a null access error if accessed outside render phase. We + // intentionally don't throw our own error because this is in a hot path. + // Also helps ensure this is inlined. + + + return dispatcher; +} +function useContext(Context) { + var dispatcher = resolveDispatcher(); + + { + // TODO: add a more generic warning for invalid values. + if (Context._context !== undefined) { + var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs + // and nobody should be using this in existing code. + + if (realContext.Consumer === Context) { + error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); + } else if (realContext.Provider === Context) { + error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); + } + } + } + + return dispatcher.useContext(Context); +} +function useState(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); +} +function useReducer(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); +} +function useRef(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); +} +function useEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); +} +function useInsertionEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useInsertionEffect(create, deps); +} +function useLayoutEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); +} +function useCallback(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); +} +function useMemo(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); +} +function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); +} +function useDebugValue(value, formatterFn) { + { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } +} +function useTransition() { + var dispatcher = resolveDispatcher(); + return dispatcher.useTransition(); +} +function useDeferredValue(value) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDeferredValue(value); +} +function useId() { + var dispatcher = resolveDispatcher(); + return dispatcher.useId(); +} +function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var dispatcher = resolveDispatcher(); + return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); +} + +// Helpers to patch console.logs to avoid logging during side-effect free +// replaying on render function. This currently only patches the object +// lazily which won't cover if the log function was extracted eagerly. +// We could also eagerly patch the method. +var disabledDepth = 0; +var prevLog; +var prevInfo; +var prevWarn; +var prevError; +var prevGroup; +var prevGroupCollapsed; +var prevGroupEnd; + +function disabledLog() {} + +disabledLog.__reactDisabledLog = true; +function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } +} +function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } +} + +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; +var prefix; +function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } +} +var reentry = false; +var componentFrameCache; + +{ + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); +} + +function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; +} +function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } +} + +function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); +} + +function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; +} + +var loggedTypeFailures = {}; +var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + +function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } +} + +function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + + setCurrentlyValidatingElement(null); + } + + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + + error('Failed %s type: %s', location, error$1.message); + + setCurrentlyValidatingElement(null); + } + } + } + } +} + +function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + setExtraStackFrame(stack); + } else { + setExtraStackFrame(null); + } + } +} + +var propTypesMisspellWarningShown; + +{ + propTypesMisspellWarningShown = false; +} + +function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentNameFromType(ReactCurrentOwner.current.type); + + if (name) { + return '\n\nCheck the render method of `' + name + '`.'; + } + } + + return ''; +} + +function getSourceInfoErrorAddendum(source) { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + + return ''; +} + +function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== undefined) { + return getSourceInfoErrorAddendum(elementProps.__source); + } + + return ''; +} +/** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ + + +var ownerHasKeyUseWarning = {}; + +function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + + return info; +} +/** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ + + +function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + + var childOwner = ''; + + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + + { + setCurrentlyValidatingElement$1(element); + + error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + + setCurrentlyValidatingElement$1(null); + } +} +/** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ + + +function validateChildKeys(node, parentType) { + if (typeof node !== 'object') { + return; + } + + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + + if (typeof iteratorFn === 'function') { + // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } +} +/** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ + + +function validatePropTypes(element) { + { + var type = element.type; + + if (type === null || type === undefined || typeof type === 'string') { + return; + } + + var propTypes; + + if (typeof type === 'function') { + propTypes = type.propTypes; + } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + + var _name = getComponentNameFromType(type); + + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { + error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); + } + } +} +/** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ + + +function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); + + setCurrentlyValidatingElement$1(null); + break; + } + } + + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + + setCurrentlyValidatingElement$1(null); + } + } +} +function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + + if (!validType) { + var info = ''; + + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; + } + + var sourceInfo = getSourceInfoErrorAddendumForProps(props); + + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + + var typeString; + + if (type === null) { + typeString = 'null'; + } else if (isArray(type)) { + typeString = 'array'; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else { + typeString = typeof type; + } + + { + error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); + } + } + + var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + + if (element == null) { + return element; + } // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + + + if (validType) { + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + + return element; +} +var didWarnAboutDeprecatedCreateFactory = false; +function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + + { + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + + warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.'); + } // Legacy hook: remove it + + + Object.defineProperty(validatedFactory, 'type', { + enumerable: false, + get: function () { + warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); + + Object.defineProperty(this, 'type', { + value: type + }); + return type; + } + }); + } + + return validatedFactory; +} +function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement.apply(this, arguments); + + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + + validatePropTypes(newElement); + return newElement; +} + +function startTransition(scope, options) { + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = {}; + var currentTransition = ReactCurrentBatchConfig.transition; + + { + ReactCurrentBatchConfig.transition._updatedFibers = new Set(); + } + + try { + scope(); + } finally { + ReactCurrentBatchConfig.transition = prevTransition; + + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; + + if (updatedFibersCount > 10) { + warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); + } + + currentTransition._updatedFibers.clear(); + } + } + } +} + +var didWarnAboutMessageChannel = false; +var enqueueTaskImpl = null; +function enqueueTask(task) { + if (enqueueTaskImpl === null) { + try { + // read require off the module object to get around the bundlers. + // we don't want them to detect a require and bundle a Node polyfill. + var requireString = ('require' + Math.random()).slice(0, 7); + var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's + // version of setImmediate, bypassing fake timers if any. + + enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate; + } catch (_err) { + // we're in a browser + // we can't use regular timers because they may still be faked + // so we try MessageChannel+postMessage instead + enqueueTaskImpl = function (callback) { + { + if (didWarnAboutMessageChannel === false) { + didWarnAboutMessageChannel = true; + + if (typeof MessageChannel === 'undefined') { + error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.'); + } + } + } + + var channel = new MessageChannel(); + channel.port1.onmessage = callback; + channel.port2.postMessage(undefined); + }; + } + } + + return enqueueTaskImpl(task); +} + +var actScopeDepth = 0; +var didWarnNoAwaitAct = false; +function act(callback) { + { + // `act` calls can be nested, so we track the depth. This represents the + // number of `act` scopes on the stack. + var prevActScopeDepth = actScopeDepth; + actScopeDepth++; + + if (ReactCurrentActQueue.current === null) { + // This is the outermost `act` scope. Initialize the queue. The reconciler + // will detect the queue and use it instead of Scheduler. + ReactCurrentActQueue.current = []; + } + + var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; + var result; + + try { + // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only + // set to `true` while the given callback is executed, not for updates + // triggered during an async event, because this is how the legacy + // implementation of `act` behaved. + ReactCurrentActQueue.isBatchingLegacy = true; + result = callback(); // Replicate behavior of original `act` implementation in legacy mode, + // which flushed updates immediately after the scope function exits, even + // if it's an async function. + + if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { + var queue = ReactCurrentActQueue.current; + + if (queue !== null) { + ReactCurrentActQueue.didScheduleLegacyUpdate = false; + flushActQueue(queue); + } + } + } catch (error) { + popActScope(prevActScopeDepth); + throw error; + } finally { + ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; + } + + if (result !== null && typeof result === 'object' && typeof result.then === 'function') { + var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait + // for it to resolve before exiting the current scope. + + var wasAwaited = false; + var thenable = { + then: function (resolve, reject) { + wasAwaited = true; + thenableResult.then(function (returnValue) { + popActScope(prevActScopeDepth); + + if (actScopeDepth === 0) { + // We've exited the outermost act scope. Recursively flush the + // queue until there's no remaining work. + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + }, function (error) { + // The callback threw an error. + popActScope(prevActScopeDepth); + reject(error); + }); + } + }; + + { + if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') { + // eslint-disable-next-line no-undef + Promise.resolve().then(function () {}).then(function () { + if (!wasAwaited) { + didWarnNoAwaitAct = true; + + error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);'); + } + }); + } + } + + return thenable; + } else { + var returnValue = result; // The callback is not an async function. Exit the current scope + // immediately, without awaiting. + + popActScope(prevActScopeDepth); + + if (actScopeDepth === 0) { + // Exiting the outermost act scope. Flush the queue. + var _queue = ReactCurrentActQueue.current; + + if (_queue !== null) { + flushActQueue(_queue); + ReactCurrentActQueue.current = null; + } // Return a thenable. If the user awaits it, we'll flush again in + // case additional work was scheduled by a microtask. + + + var _thenable = { + then: function (resolve, reject) { + // Confirm we haven't re-entered another `act` scope, in case + // the user does something weird like await the thenable + // multiple times. + if (ReactCurrentActQueue.current === null) { + // Recursively flush the queue until there's no remaining work. + ReactCurrentActQueue.current = []; + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + } + }; + return _thenable; + } else { + // Since we're inside a nested `act` scope, the returned thenable + // immediately resolves. The outer scope will flush the queue. + var _thenable2 = { + then: function (resolve, reject) { + resolve(returnValue); + } + }; + return _thenable2; + } + } + } +} + +function popActScope(prevActScopeDepth) { + { + if (prevActScopeDepth !== actScopeDepth - 1) { + error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. '); + } + + actScopeDepth = prevActScopeDepth; + } +} + +function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + { + var queue = ReactCurrentActQueue.current; + + if (queue !== null) { + try { + flushActQueue(queue); + enqueueTask(function () { + if (queue.length === 0) { + // No additional work was scheduled. Finish. + ReactCurrentActQueue.current = null; + resolve(returnValue); + } else { + // Keep flushing work until there's none left. + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } + }); + } catch (error) { + reject(error); + } + } else { + resolve(returnValue); + } + } +} + +var isFlushing = false; + +function flushActQueue(queue) { + { + if (!isFlushing) { + // Prevent re-entrance. + isFlushing = true; + var i = 0; + + try { + for (; i < queue.length; i++) { + var callback = queue[i]; + + do { + callback = callback(true); + } while (callback !== null); + } + + queue.length = 0; + } catch (error) { + // If something throws, leave the remaining callbacks on the queue. + queue = queue.slice(i + 1); + throw error; + } finally { + isFlushing = false; + } + } + } +} + +var createElement$1 = createElementWithValidation ; +var cloneElement$1 = cloneElementWithValidation ; +var createFactory = createFactoryWithValidation ; +var Children = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray: toArray, + only: onlyChild +}; + +exports.Children = Children; +exports.Component = Component; +exports.Fragment = REACT_FRAGMENT_TYPE; +exports.Profiler = REACT_PROFILER_TYPE; +exports.PureComponent = PureComponent; +exports.StrictMode = REACT_STRICT_MODE_TYPE; +exports.Suspense = REACT_SUSPENSE_TYPE; +exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; +exports.act = act; +exports.cloneElement = cloneElement$1; +exports.createContext = createContext; +exports.createElement = createElement$1; +exports.createFactory = createFactory; +exports.createRef = createRef; +exports.forwardRef = forwardRef; +exports.isValidElement = isValidElement; +exports.lazy = lazy; +exports.memo = memo; +exports.startTransition = startTransition; +exports.unstable_act = act; +exports.useCallback = useCallback; +exports.useContext = useContext; +exports.useDebugValue = useDebugValue; +exports.useDeferredValue = useDeferredValue; +exports.useEffect = useEffect; +exports.useId = useId; +exports.useImperativeHandle = useImperativeHandle; +exports.useInsertionEffect = useInsertionEffect; +exports.useLayoutEffect = useLayoutEffect; +exports.useMemo = useMemo; +exports.useReducer = useReducer; +exports.useRef = useRef; +exports.useState = useState; +exports.useSyncExternalStore = useSyncExternalStore; +exports.useTransition = useTransition; +exports.version = ReactVersion; + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ +if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === + 'function' +) { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); +} + + })(); +} diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.production.min.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.production.min.js new file mode 100644 index 00000000..c2b2f776 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.production.min.js @@ -0,0 +1,26 @@ +/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z=Symbol.iterator;function A(a){if(null===a||"object"!==typeof a)return null;a=z&&a[z]||a["@@iterator"];return"function"===typeof a?a:null} +var B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={}; +E.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F; +H.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0}; +function M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1=0.10.0" + }, + "dependencies": { + "loose-envify": "^1.1.0" + }, + "browserify": { + "transform": [ + "loose-envify" + ] + } +} \ No newline at end of file diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/react.shared-subset.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/react.shared-subset.js new file mode 100644 index 00000000..694e9667 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/react.shared-subset.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./cjs/react.shared-subset.production.min.js'); +} else { + module.exports = require('./cjs/react.shared-subset.development.js'); +} diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.development.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.development.js new file mode 100644 index 00000000..37b38b35 --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.development.js @@ -0,0 +1,3343 @@ +/** + * @license React + * react.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.React = {})); +}(this, (function (exports) { 'use strict'; + + var ReactVersion = '18.3.1'; + + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. + var REACT_ELEMENT_TYPE = Symbol.for('react.element'); + var REACT_PORTAL_TYPE = Symbol.for('react.portal'); + var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); + var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); + var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); + var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); + var REACT_CONTEXT_TYPE = Symbol.for('react.context'); + var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); + var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); + var REACT_MEMO_TYPE = Symbol.for('react.memo'); + var REACT_LAZY_TYPE = Symbol.for('react.lazy'); + var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; + } + + /** + * Keeps track of the current dispatcher. + */ + var ReactCurrentDispatcher = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + + /** + * Keeps track of the current batch's configuration such as how long an update + * should suspend for if it needs to. + */ + var ReactCurrentBatchConfig = { + transition: null + }; + + var ReactCurrentActQueue = { + current: null, + // Used to reproduce behavior of `batchedUpdates` in legacy mode. + isBatchingLegacy: false, + didScheduleLegacyUpdate: false + }; + + /** + * Keeps track of the current owner. + * + * The current owner is the component who should own any components that are + * currently being constructed. + */ + var ReactCurrentOwner = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + + var ReactDebugCurrentFrame = {}; + var currentExtraStackFrame = null; + function setExtraStackFrame(stack) { + { + currentExtraStackFrame = stack; + } + } + + { + ReactDebugCurrentFrame.setExtraStackFrame = function (stack) { + { + currentExtraStackFrame = stack; + } + }; // Stack implementation injected by the current renderer. + + + ReactDebugCurrentFrame.getCurrentStack = null; + + ReactDebugCurrentFrame.getStackAddendum = function () { + var stack = ''; // Add an extra top frame while an element is being validated + + if (currentExtraStackFrame) { + stack += currentExtraStackFrame; + } // Delegate to the injected renderer-specific implementation + + + var impl = ReactDebugCurrentFrame.getCurrentStack; + + if (impl) { + stack += impl() || ''; + } + + return stack; + }; + } + + // ----------------------------------------------------------------------------- + + var enableScopeAPI = false; // Experimental Create Event Handle API. + var enableCacheElement = false; + var enableTransitionTracing = false; // No known bugs, but needs performance testing + + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber + // stuff. Intended to enable React core members to more easily debug scheduling + // issues in DEV builds. + + var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + + var ReactSharedInternals = { + ReactCurrentDispatcher: ReactCurrentDispatcher, + ReactCurrentBatchConfig: ReactCurrentBatchConfig, + ReactCurrentOwner: ReactCurrentOwner + }; + + { + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; + } + + // by calls to these methods by a Babel plugin. + // + // In PROD (or in packages without access to React internals), + // they are left as they are instead. + + function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } + } + } + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } + } + + function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + + var didWarnStateUpdateForUnmountedComponent = {}; + + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; + var warningKey = componentName + "." + callerName; + + if (didWarnStateUpdateForUnmountedComponent[warningKey]) { + return; + } + + error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); + + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } + } + /** + * This is the abstract API for an update queue. + */ + + + var ReactNoopUpdateQueue = { + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function (publicInstance) { + return false; + }, + + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueForceUpdate: function (publicInstance, callback, callerName) { + warnNoop(publicInstance, 'forceUpdate'); + }, + + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { + warnNoop(publicInstance, 'replaceState'); + }, + + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @param {?function} callback Called after component is updated. + * @param {?string} Name of the calling function in the public API. + * @internal + */ + enqueueSetState: function (publicInstance, partialState, callback, callerName) { + warnNoop(publicInstance, 'setState'); + } + }; + + var assign = Object.assign; + + var emptyObject = {}; + + { + Object.freeze(emptyObject); + } + /** + * Base class helpers for the updating state of a component. + */ + + + function Component(props, context, updater) { + this.props = props; + this.context = context; // If a component has string refs, we will assign a different object later. + + this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the + // renderer. + + this.updater = updater || ReactNoopUpdateQueue; + } + + Component.prototype.isReactComponent = {}; + /** + * Sets a subset of the state. Always use this to mutate + * state. You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * There is no guarantee that calls to `setState` will run synchronously, + * as they may eventually be batched together. You can provide an optional + * callback that will be executed when the call to setState is actually + * completed. + * + * When a function is provided to setState, it will be called at some point in + * the future (not synchronously). It will be called with the up to date + * component arguments (state, props, context). These values can be different + * from this.* because your function may be called after receiveProps but before + * shouldComponentUpdate, and this new state, props, and context will not yet be + * assigned to this. + * + * @param {object|function} partialState Next partial state or function to + * produce next partial state to be merged with current state. + * @param {?function} callback Called after state is updated. + * @final + * @protected + */ + + Component.prototype.setState = function (partialState, callback) { + if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) { + throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.'); + } + + this.updater.enqueueSetState(this, partialState, callback, 'setState'); + }; + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {?function} callback Called after update is complete. + * @final + * @protected + */ + + + Component.prototype.forceUpdate = function (callback) { + this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); + }; + /** + * Deprecated APIs. These APIs used to exist on classic React classes but since + * we would like to deprecate them, we're not going to move them over to this + * modern base class. Instead, we define a getter that warns if it's accessed. + */ + + + { + var deprecatedAPIs = { + isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], + replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] + }; + + var defineDeprecationWarning = function (methodName, info) { + Object.defineProperty(Component.prototype, methodName, { + get: function () { + warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); + + return undefined; + } + }); + }; + + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } + } + + function ComponentDummy() {} + + ComponentDummy.prototype = Component.prototype; + /** + * Convenience component with default shallow equality check for sCU. + */ + + function PureComponent(props, context, updater) { + this.props = props; + this.context = context; // If a component has string refs, we will assign a different object later. + + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + + var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); + pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. + + assign(pureComponentPrototype, Component.prototype); + pureComponentPrototype.isPureReactComponent = true; + + // an immutable object with a single mutable value + function createRef() { + var refObject = { + current: null + }; + + { + Object.seal(refObject); + } + + return refObject; + } + + var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + + function isArray(a) { + return isArrayImpl(a); + } + + /* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ + // $FlowFixMe only called in DEV, so void return is not possible. + function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } + } // $FlowFixMe only called in DEV, so void return is not possible. + + + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + + function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } + } + + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + + if (displayName) { + return displayName; + } + + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; + } // Keep in sync with react-reconciler/getComponentNameFromFiber + + + function getContextName(type) { + return type.displayName || 'Context'; + } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + + function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + + if (outerName !== null) { + return outerName; + } + + return getComponentNameFromType(type.type) || 'Memo'; + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + + return null; + } + + var hasOwnProperty = Object.prototype.hasOwnProperty; + + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; + + { + didWarnAboutStringRefs = {}; + } + + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.ref !== undefined; + } + + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + + if (getter && getter.isReactWarning) { + return false; + } + } + } + + return config.key !== undefined; + } + + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function () { + { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + + error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + } + }; + + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); + } + + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function () { + { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + + error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + } + }; + + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); + } + + function warnIfStringRefCannotBeAutoConverted(config) { + { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); + + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + /** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ + + + var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + + { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + + return element; + }; + /** + * Create and return a new ReactElement of the given type. + * See https://reactjs.org/docs/react-api.html#createelement + */ + + function createElement(type, config, children) { + var propName; // Reserved names are extracted + + var props = {}; + var key = null; + var ref = null; + var self = null; + var source = null; + + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + + { + warnIfStringRefCannotBeAutoConverted(config); + } + } + + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + + key = '' + config.key; + } + + self = config.__self === undefined ? null : config.__self; + source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + + + var childrenLength = arguments.length - 2; + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + + { + if (Object.freeze) { + Object.freeze(childArray); + } + } + + props.children = childArray; + } // Resolve default props + + + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + } + + { + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + } + + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); + } + function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + return newElement; + } + /** + * Clone and return a new ReactElement using element as the starting point. + * See https://reactjs.org/docs/react-api.html#cloneelement + */ + + function cloneElement(element, config, children) { + if (element === null || element === undefined) { + throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); + } + + var propName; // Original props are copied + + var props = assign({}, element.props); // Reserved names are extracted + + var key = element.key; + var ref = element.ref; // Self is preserved since the owner is preserved. + + var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a + // transpiler, and the original source is probably a better indicator of the + // true owner. + + var source = element._source; // Owner will be preserved, unless ref is overridden + + var owner = element._owner; + + if (config != null) { + if (hasValidRef(config)) { + // Silently steal the ref from the parent. + ref = config.ref; + owner = ReactCurrentOwner.current; + } + + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + + key = '' + config.key; + } // Remaining properties override existing props + + + var defaultProps; + + if (element.type && element.type.defaultProps) { + defaultProps = element.type.defaultProps; + } + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + if (config[propName] === undefined && defaultProps !== undefined) { + // Resolve default props + props[propName] = defaultProps[propName]; + } else { + props[propName] = config[propName]; + } + } + } + } // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + + + var childrenLength = arguments.length - 2; + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + + props.children = childArray; + } + + return ReactElement(element.type, key, ref, self, source, owner, props); + } + /** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ + + function isValidElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + + var SEPARATOR = '.'; + var SUBSEPARATOR = ':'; + /** + * Escape and wrap key so it is safe to use as a reactid + * + * @param {string} key to be escaped. + * @return {string} the escaped key. + */ + + function escape(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + '=': '=0', + ':': '=2' + }; + var escapedString = key.replace(escapeRegex, function (match) { + return escaperLookup[match]; + }); + return '$' + escapedString; + } + /** + * TODO: Test that a single child and an array with one item have the same key + * pattern. + */ + + + var didWarnAboutMaps = false; + var userProvidedKeyEscapeRegex = /\/+/g; + + function escapeUserProvidedKey(text) { + return text.replace(userProvidedKeyEscapeRegex, '$&/'); + } + /** + * Generate a key string that identifies a element within a set. + * + * @param {*} element A element that could contain a manual key. + * @param {number} index Index that is used if a manual key is not provided. + * @return {string} + */ + + + function getElementKey(element, index) { + // Do some typechecking here since we call this blindly. We want to ensure + // that we don't block potential future ES APIs. + if (typeof element === 'object' && element !== null && element.key != null) { + // Explicit key + { + checkKeyStringCoercion(element.key); + } + + return escape('' + element.key); + } // Implicit key determined by the index in the set + + + return index.toString(36); + } + + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + + if (type === 'undefined' || type === 'boolean') { + // All of the above are perceived as null. + children = null; + } + + var invokeCallback = false; + + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case 'string': + case 'number': + invokeCallback = true; + break; + + case 'object': + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + + } + } + + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array + // so that it's consistent if the number of children grows: + + var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; + + if (isArray(mappedChild)) { + var escapedChildKey = ''; + + if (childKey != null) { + escapedChildKey = escapeUserProvidedKey(childKey) + '/'; + } + + mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) { + return c; + }); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) { + { + // The `if` statement here prevents auto-disabling of the safe + // coercion ESLint rule, so we must manually disable it below. + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { + checkKeyStringCoercion(mappedChild.key); + } + } + + mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as + // traverseAllChildren used to do for objects as children + escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number + // eslint-disable-next-line react-internal/safe-string-coercion + escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey); + } + + array.push(mappedChild); + } + + return 1; + } + + var child; + var nextName; + var subtreeCount = 0; // Count of children found in the current subtree. + + var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; + + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getElementKey(child, i); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else { + var iteratorFn = getIteratorFn(children); + + if (typeof iteratorFn === 'function') { + var iterableChildren = children; + + { + // Warn about using Maps as children + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) { + warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); + } + + didWarnAboutMaps = true; + } + } + + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii = 0; + + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii++); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else if (type === 'object') { + // eslint-disable-next-line react-internal/safe-string-coercion + var childrenString = String(children); + throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); + } + } + + return subtreeCount; + } + + /** + * Maps children that are typically specified as `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenmap + * + * The provided mapFunction(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} func The map function. + * @param {*} context Context for mapFunction. + * @return {object} Object containing the ordered map of results. + */ + function mapChildren(children, func, context) { + if (children == null) { + return children; + } + + var result = []; + var count = 0; + mapIntoArray(children, result, '', '', function (child) { + return func.call(context, child, count++); + }); + return result; + } + /** + * Count the number of children that are typically specified as + * `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrencount + * + * @param {?*} children Children tree container. + * @return {number} The number of children. + */ + + + function countChildren(children) { + var n = 0; + mapChildren(children, function () { + n++; // Don't return anything + }); + return n; + } + + /** + * Iterates through children that are typically specified as `props.children`. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenforeach + * + * The provided forEachFunc(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} forEachFunc + * @param {*} forEachContext Context for forEachContext. + */ + function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren(children, function () { + forEachFunc.apply(this, arguments); // Don't return anything. + }, forEachContext); + } + /** + * Flatten a children object (typically specified as `props.children`) and + * return an array with appropriately re-keyed children. + * + * See https://reactjs.org/docs/react-api.html#reactchildrentoarray + */ + + + function toArray(children) { + return mapChildren(children, function (child) { + return child; + }) || []; + } + /** + * Returns the first child in a collection of children and verifies that there + * is only one child in the collection. + * + * See https://reactjs.org/docs/react-api.html#reactchildrenonly + * + * The current implementation of this function assumes that a single child gets + * passed without a wrapper, but the purpose of this helper function is to + * abstract away the particular structure of children. + * + * @param {?object} children Child collection structure. + * @return {ReactElement} The first and only `ReactElement` contained in the + * structure. + */ + + + function onlyChild(children) { + if (!isValidElement(children)) { + throw new Error('React.Children.only expected to receive a single React element child.'); + } + + return children; + } + + function createContext(defaultValue) { + // TODO: Second argument used to be an optional `calculateChangedBits` + // function. Warn to reserve for future use? + var context = { + $$typeof: REACT_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: defaultValue, + _currentValue2: defaultValue, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + // Add these to use same hidden class in VM as ServerContext + _defaultValue: null, + _globalName: null + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + + { + // A separate object, but proxies back to the original context object for + // backwards compatibility. It has a different $$typeof, so we can properly + // warn for the incorrect usage of Context as a Consumer. + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context + }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here + + Object.defineProperties(Consumer, { + Provider: { + get: function () { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + + error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + + return context.Provider; + }, + set: function (_Provider) { + context.Provider = _Provider; + } + }, + _currentValue: { + get: function () { + return context._currentValue; + }, + set: function (_currentValue) { + context._currentValue = _currentValue; + } + }, + _currentValue2: { + get: function () { + return context._currentValue2; + }, + set: function (_currentValue2) { + context._currentValue2 = _currentValue2; + } + }, + _threadCount: { + get: function () { + return context._threadCount; + }, + set: function (_threadCount) { + context._threadCount = _threadCount; + } + }, + Consumer: { + get: function () { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + + error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + + return context.Consumer; + } + }, + displayName: { + get: function () { + return context.displayName; + }, + set: function (displayName) { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName); + + hasWarnedAboutDisplayNameOnConsumer = true; + } + } + } + }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty + + context.Consumer = Consumer; + } + + { + context._currentRenderer = null; + context._currentRenderer2 = null; + } + + return context; + } + + var Uninitialized = -1; + var Pending = 0; + var Resolved = 1; + var Rejected = 2; + + function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); // Transition to the next state. + // This might throw either because it's missing or throws. If so, we treat it + // as still uninitialized and try again next time. Which is the same as what + // happens if the ctor or any wrappers processing the ctor throws. This might + // end up fixing it if the resolution was a concurrency bug. + + thenable.then(function (moduleObject) { + if (payload._status === Pending || payload._status === Uninitialized) { + // Transition to the next state. + var resolved = payload; + resolved._status = Resolved; + resolved._result = moduleObject; + } + }, function (error) { + if (payload._status === Pending || payload._status === Uninitialized) { + // Transition to the next state. + var rejected = payload; + rejected._status = Rejected; + rejected._result = error; + } + }); + + if (payload._status === Uninitialized) { + // In case, we're still uninitialized, then we're waiting for the thenable + // to resolve. Set it as pending in the meantime. + var pending = payload; + pending._status = Pending; + pending._result = thenable; + } + } + + if (payload._status === Resolved) { + var moduleObject = payload._result; + + { + if (moduleObject === undefined) { + error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. + 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject); + } + } + + { + if (!('default' in moduleObject)) { + error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. + 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject); + } + } + + return moduleObject.default; + } else { + throw payload._result; + } + } + + function lazy(ctor) { + var payload = { + // We use these fields to store the result. + _status: Uninitialized, + _result: ctor + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer + }; + + { + // In production, this would just set it on the object. + var defaultProps; + var propTypes; // $FlowFixMe + + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: function () { + return defaultProps; + }, + set: function (newDefaultProps) { + error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); + + defaultProps = newDefaultProps; // Match production behavior more closely: + // $FlowFixMe + + Object.defineProperty(lazyType, 'defaultProps', { + enumerable: true + }); + } + }, + propTypes: { + configurable: true, + get: function () { + return propTypes; + }, + set: function (newPropTypes) { + error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); + + propTypes = newPropTypes; // Match production behavior more closely: + // $FlowFixMe + + Object.defineProperty(lazyType, 'propTypes', { + enumerable: true + }); + } + } + }); + } + + return lazyType; + } + + function forwardRef(render) { + { + if (render != null && render.$$typeof === REACT_MEMO_TYPE) { + error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); + } else if (typeof render !== 'function') { + error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); + } else { + if (render.length !== 0 && render.length !== 2) { + error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); + } + } + + if (render != null) { + if (render.defaultProps != null || render.propTypes != null) { + error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?'); + } + } + } + + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: render + }; + + { + var ownName; + Object.defineProperty(elementType, 'displayName', { + enumerable: false, + configurable: true, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; // The inner component shouldn't inherit this display name in most cases, + // because the component may be used elsewhere. + // But it's nice for anonymous functions to inherit the name, + // so that our component-stack generation logic will display their frames. + // An anonymous function generally suggests a pattern like: + // React.forwardRef((props, ref) => {...}); + // This kind of inner function is not used elsewhere so the side effect is okay. + + if (!render.name && !render.displayName) { + render.displayName = name; + } + } + }); + } + + return elementType; + } + + var REACT_MODULE_REFERENCE; + + { + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); + } + + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + + return false; + } + + function memo(type, compare) { + { + if (!isValidElementType(type)) { + error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); + } + } + + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type: type, + compare: compare === undefined ? null : compare + }; + + { + var ownName; + Object.defineProperty(elementType, 'displayName', { + enumerable: false, + configurable: true, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; // The inner component shouldn't inherit this display name in most cases, + // because the component may be used elsewhere. + // But it's nice for anonymous functions to inherit the name, + // so that our component-stack generation logic will display their frames. + // An anonymous function generally suggests a pattern like: + // React.memo((props) => {...}); + // This kind of inner function is not used elsewhere so the side effect is okay. + + if (!type.name && !type.displayName) { + type.displayName = name; + } + } + }); + } + + return elementType; + } + + function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + + { + if (dispatcher === null) { + error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); + } + } // Will result in a null access error if accessed outside render phase. We + // intentionally don't throw our own error because this is in a hot path. + // Also helps ensure this is inlined. + + + return dispatcher; + } + function useContext(Context) { + var dispatcher = resolveDispatcher(); + + { + // TODO: add a more generic warning for invalid values. + if (Context._context !== undefined) { + var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs + // and nobody should be using this in existing code. + + if (realContext.Consumer === Context) { + error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); + } else if (realContext.Provider === Context) { + error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); + } + } + } + + return dispatcher.useContext(Context); + } + function useState(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); + } + function useReducer(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); + } + function useRef(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); + } + function useEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); + } + function useInsertionEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useInsertionEffect(create, deps); + } + function useLayoutEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); + } + function useCallback(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); + } + function useMemo(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); + } + function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); + } + function useDebugValue(value, formatterFn) { + { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } + } + function useTransition() { + var dispatcher = resolveDispatcher(); + return dispatcher.useTransition(); + } + function useDeferredValue(value) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDeferredValue(value); + } + function useId() { + var dispatcher = resolveDispatcher(); + return dispatcher.useId(); + } + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var dispatcher = resolveDispatcher(); + return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + } + + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + + function disabledLog() {} + + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } + } + + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + + { + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; + } + + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + + setCurrentlyValidatingElement(null); + } + + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + + error('Failed %s type: %s', location, error$1.message); + + setCurrentlyValidatingElement(null); + } + } + } + } + } + + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + setExtraStackFrame(stack); + } else { + setExtraStackFrame(null); + } + } + } + + var propTypesMisspellWarningShown; + + { + propTypesMisspellWarningShown = false; + } + + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentNameFromType(ReactCurrentOwner.current.type); + + if (name) { + return '\n\nCheck the render method of `' + name + '`.'; + } + } + + return ''; + } + + function getSourceInfoErrorAddendum(source) { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + + return ''; + } + + function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== undefined) { + return getSourceInfoErrorAddendum(elementProps.__source); + } + + return ''; + } + /** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ + + + var ownerHasKeyUseWarning = {}; + + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + + return info; + } + /** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ + + + function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + + var childOwner = ''; + + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + + { + setCurrentlyValidatingElement$1(element); + + error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + + setCurrentlyValidatingElement$1(null); + } + } + /** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ + + + function validateChildKeys(node, parentType) { + if (typeof node !== 'object') { + return; + } + + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + + if (typeof iteratorFn === 'function') { + // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + /** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ + + + function validatePropTypes(element) { + { + var type = element.type; + + if (type === null || type === undefined || typeof type === 'string') { + return; + } + + var propTypes; + + if (typeof type === 'function') { + propTypes = type.propTypes; + } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + + var _name = getComponentNameFromType(type); + + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { + error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); + } + } + } + /** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ + + + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); + + setCurrentlyValidatingElement$1(null); + break; + } + } + + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + + setCurrentlyValidatingElement$1(null); + } + } + } + function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + + if (!validType) { + var info = ''; + + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; + } + + var sourceInfo = getSourceInfoErrorAddendumForProps(props); + + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + + var typeString; + + if (type === null) { + typeString = 'null'; + } else if (isArray(type)) { + typeString = 'array'; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else { + typeString = typeof type; + } + + { + error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); + } + } + + var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + + if (element == null) { + return element; + } // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + + + if (validType) { + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + + return element; + } + var didWarnAboutDeprecatedCreateFactory = false; + function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + + { + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + + warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.'); + } // Legacy hook: remove it + + + Object.defineProperty(validatedFactory, 'type', { + enumerable: false, + get: function () { + warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); + + Object.defineProperty(this, 'type', { + value: type + }); + return type; + } + }); + } + + return validatedFactory; + } + function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement.apply(this, arguments); + + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + + validatePropTypes(newElement); + return newElement; + } + + var enableSchedulerDebugging = false; + var enableProfiling = false; + var frameYieldMs = 5; + + function push(heap, node) { + var index = heap.length; + heap.push(node); + siftUp(heap, node, index); + } + function peek(heap) { + return heap.length === 0 ? null : heap[0]; + } + function pop(heap) { + if (heap.length === 0) { + return null; + } + + var first = heap[0]; + var last = heap.pop(); + + if (last !== first) { + heap[0] = last; + siftDown(heap, last, 0); + } + + return first; + } + + function siftUp(heap, node, i) { + var index = i; + + while (index > 0) { + var parentIndex = index - 1 >>> 1; + var parent = heap[parentIndex]; + + if (compare(parent, node) > 0) { + // The parent is larger. Swap positions. + heap[parentIndex] = node; + heap[index] = parent; + index = parentIndex; + } else { + // The parent is smaller. Exit. + return; + } + } + } + + function siftDown(heap, node, i) { + var index = i; + var length = heap.length; + var halfLength = length >>> 1; + + while (index < halfLength) { + var leftIndex = (index + 1) * 2 - 1; + var left = heap[leftIndex]; + var rightIndex = leftIndex + 1; + var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. + + if (compare(left, node) < 0) { + if (rightIndex < length && compare(right, left) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + heap[index] = left; + heap[leftIndex] = node; + index = leftIndex; + } + } else if (rightIndex < length && compare(right, node) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + // Neither child is smaller. Exit. + return; + } + } + } + + function compare(a, b) { + // Compare sort index first, then task id. + var diff = a.sortIndex - b.sortIndex; + return diff !== 0 ? diff : a.id - b.id; + } + + // TODO: Use symbols? + var ImmediatePriority = 1; + var UserBlockingPriority = 2; + var NormalPriority = 3; + var LowPriority = 4; + var IdlePriority = 5; + + function markTaskErrored(task, ms) { + } + + /* eslint-disable no-var */ + var getCurrentTime; + var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; + + if (hasPerformanceNow) { + var localPerformance = performance; + + getCurrentTime = function () { + return localPerformance.now(); + }; + } else { + var localDate = Date; + var initialTime = localDate.now(); + + getCurrentTime = function () { + return localDate.now() - initialTime; + }; + } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. + // Math.pow(2, 30) - 1 + // 0b111111111111111111111111111111 + + + var maxSigned31BitInt = 1073741823; // Times out immediately + + var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out + + var USER_BLOCKING_PRIORITY_TIMEOUT = 250; + var NORMAL_PRIORITY_TIMEOUT = 5000; + var LOW_PRIORITY_TIMEOUT = 10000; // Never times out + + var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap + + var taskQueue = []; + var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. + + var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. + var currentTask = null; + var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. + + var isPerformingWork = false; + var isHostCallbackScheduled = false; + var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. + + var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; + var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; + var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom + + var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; + + function advanceTimers(currentTime) { + // Check for tasks that are no longer delayed and add them to the queue. + var timer = peek(timerQueue); + + while (timer !== null) { + if (timer.callback === null) { + // Timer was cancelled. + pop(timerQueue); + } else if (timer.startTime <= currentTime) { + // Timer fired. Transfer to the task queue. + pop(timerQueue); + timer.sortIndex = timer.expirationTime; + push(taskQueue, timer); + } else { + // Remaining timers are pending. + return; + } + + timer = peek(timerQueue); + } + } + + function handleTimeout(currentTime) { + isHostTimeoutScheduled = false; + advanceTimers(currentTime); + + if (!isHostCallbackScheduled) { + if (peek(taskQueue) !== null) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } else { + var firstTimer = peek(timerQueue); + + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + } + } + } + + function flushWork(hasTimeRemaining, initialTime) { + + + isHostCallbackScheduled = false; + + if (isHostTimeoutScheduled) { + // We scheduled a timeout but it's no longer needed. Cancel it. + isHostTimeoutScheduled = false; + cancelHostTimeout(); + } + + isPerformingWork = true; + var previousPriorityLevel = currentPriorityLevel; + + try { + if (enableProfiling) { + try { + return workLoop(hasTimeRemaining, initialTime); + } catch (error) { + if (currentTask !== null) { + var currentTime = getCurrentTime(); + markTaskErrored(currentTask, currentTime); + currentTask.isQueued = false; + } + + throw error; + } + } else { + // No catch in prod code path. + return workLoop(hasTimeRemaining, initialTime); + } + } finally { + currentTask = null; + currentPriorityLevel = previousPriorityLevel; + isPerformingWork = false; + } + } + + function workLoop(hasTimeRemaining, initialTime) { + var currentTime = initialTime; + advanceTimers(currentTime); + currentTask = peek(taskQueue); + + while (currentTask !== null && !(enableSchedulerDebugging )) { + if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { + // This currentTask hasn't expired, and we've reached the deadline. + break; + } + + var callback = currentTask.callback; + + if (typeof callback === 'function') { + currentTask.callback = null; + currentPriorityLevel = currentTask.priorityLevel; + var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; + + var continuationCallback = callback(didUserCallbackTimeout); + currentTime = getCurrentTime(); + + if (typeof continuationCallback === 'function') { + currentTask.callback = continuationCallback; + } else { + + if (currentTask === peek(taskQueue)) { + pop(taskQueue); + } + } + + advanceTimers(currentTime); + } else { + pop(taskQueue); + } + + currentTask = peek(taskQueue); + } // Return whether there's additional work + + + if (currentTask !== null) { + return true; + } else { + var firstTimer = peek(timerQueue); + + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + + return false; + } + } + + function unstable_runWithPriority(priorityLevel, eventHandler) { + switch (priorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + case LowPriority: + case IdlePriority: + break; + + default: + priorityLevel = NormalPriority; + } + + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + + function unstable_next(eventHandler) { + var priorityLevel; + + switch (currentPriorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + // Shift down to normal priority + priorityLevel = NormalPriority; + break; + + default: + // Anything lower than normal priority should remain at the current level. + priorityLevel = currentPriorityLevel; + break; + } + + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + + function unstable_wrapCallback(callback) { + var parentPriorityLevel = currentPriorityLevel; + return function () { + // This is a fork of runWithPriority, inlined for performance. + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = parentPriorityLevel; + + try { + return callback.apply(this, arguments); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + }; + } + + function unstable_scheduleCallback(priorityLevel, callback, options) { + var currentTime = getCurrentTime(); + var startTime; + + if (typeof options === 'object' && options !== null) { + var delay = options.delay; + + if (typeof delay === 'number' && delay > 0) { + startTime = currentTime + delay; + } else { + startTime = currentTime; + } + } else { + startTime = currentTime; + } + + var timeout; + + switch (priorityLevel) { + case ImmediatePriority: + timeout = IMMEDIATE_PRIORITY_TIMEOUT; + break; + + case UserBlockingPriority: + timeout = USER_BLOCKING_PRIORITY_TIMEOUT; + break; + + case IdlePriority: + timeout = IDLE_PRIORITY_TIMEOUT; + break; + + case LowPriority: + timeout = LOW_PRIORITY_TIMEOUT; + break; + + case NormalPriority: + default: + timeout = NORMAL_PRIORITY_TIMEOUT; + break; + } + + var expirationTime = startTime + timeout; + var newTask = { + id: taskIdCounter++, + callback: callback, + priorityLevel: priorityLevel, + startTime: startTime, + expirationTime: expirationTime, + sortIndex: -1 + }; + + if (startTime > currentTime) { + // This is a delayed task. + newTask.sortIndex = startTime; + push(timerQueue, newTask); + + if (peek(taskQueue) === null && newTask === peek(timerQueue)) { + // All tasks are delayed, and this is the task with the earliest delay. + if (isHostTimeoutScheduled) { + // Cancel an existing timeout. + cancelHostTimeout(); + } else { + isHostTimeoutScheduled = true; + } // Schedule a timeout. + + + requestHostTimeout(handleTimeout, startTime - currentTime); + } + } else { + newTask.sortIndex = expirationTime; + push(taskQueue, newTask); + // wait until the next time we yield. + + + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + + return newTask; + } + + function unstable_pauseExecution() { + } + + function unstable_continueExecution() { + + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + + function unstable_getFirstCallbackNode() { + return peek(taskQueue); + } + + function unstable_cancelCallback(task) { + // remove from the queue because you can't remove arbitrary nodes from an + // array based heap, only the first one.) + + + task.callback = null; + } + + function unstable_getCurrentPriorityLevel() { + return currentPriorityLevel; + } + + var isMessageLoopRunning = false; + var scheduledHostCallback = null; + var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main + // thread, like user events. By default, it yields multiple times per frame. + // It does not attempt to align with frame boundaries, since most tasks don't + // need to be frame aligned; for those that do, use requestAnimationFrame. + + var frameInterval = frameYieldMs; + var startTime = -1; + + function shouldYieldToHost() { + var timeElapsed = getCurrentTime() - startTime; + + if (timeElapsed < frameInterval) { + // The main thread has only been blocked for a really short amount of time; + // smaller than a single frame. Don't yield yet. + return false; + } // The main thread has been blocked for a non-negligible amount of time. We + + + return true; + } + + function requestPaint() { + + } + + function forceFrameRate(fps) { + if (fps < 0 || fps > 125) { + // Using console['error'] to evade Babel and ESLint + console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); + return; + } + + if (fps > 0) { + frameInterval = Math.floor(1000 / fps); + } else { + // reset the framerate + frameInterval = frameYieldMs; + } + } + + var performWorkUntilDeadline = function () { + if (scheduledHostCallback !== null) { + var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread + // has been blocked. + + startTime = currentTime; + var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the + // error can be observed. + // + // Intentionally not using a try-catch, since that makes some debugging + // techniques harder. Instead, if `scheduledHostCallback` errors, then + // `hasMoreWork` will remain true, and we'll continue the work loop. + + var hasMoreWork = true; + + try { + hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); + } finally { + if (hasMoreWork) { + // If there's more work, schedule the next message event at the end + // of the preceding one. + schedulePerformWorkUntilDeadline(); + } else { + isMessageLoopRunning = false; + scheduledHostCallback = null; + } + } + } else { + isMessageLoopRunning = false; + } // Yielding to the browser will give it a chance to paint, so we can + }; + + var schedulePerformWorkUntilDeadline; + + if (typeof localSetImmediate === 'function') { + // Node.js and old IE. + // There's a few reasons for why we prefer setImmediate. + // + // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. + // (Even though this is a DOM fork of the Scheduler, you could get here + // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) + // https://github.com/facebook/react/issues/20756 + // + // But also, it runs earlier which is the semantic we want. + // If other browsers ever implement it, it's better to use it. + // Although both of these would be inferior to native scheduling. + schedulePerformWorkUntilDeadline = function () { + localSetImmediate(performWorkUntilDeadline); + }; + } else if (typeof MessageChannel !== 'undefined') { + // DOM and Worker environments. + // We prefer MessageChannel because of the 4ms setTimeout clamping. + var channel = new MessageChannel(); + var port = channel.port2; + channel.port1.onmessage = performWorkUntilDeadline; + + schedulePerformWorkUntilDeadline = function () { + port.postMessage(null); + }; + } else { + // We should only fallback here in non-browser environments. + schedulePerformWorkUntilDeadline = function () { + localSetTimeout(performWorkUntilDeadline, 0); + }; + } + + function requestHostCallback(callback) { + scheduledHostCallback = callback; + + if (!isMessageLoopRunning) { + isMessageLoopRunning = true; + schedulePerformWorkUntilDeadline(); + } + } + + function requestHostTimeout(callback, ms) { + taskTimeoutID = localSetTimeout(function () { + callback(getCurrentTime()); + }, ms); + } + + function cancelHostTimeout() { + localClearTimeout(taskTimeoutID); + taskTimeoutID = -1; + } + + var unstable_requestPaint = requestPaint; + var unstable_Profiling = null; + + + + var Scheduler = /*#__PURE__*/Object.freeze({ + __proto__: null, + unstable_ImmediatePriority: ImmediatePriority, + unstable_UserBlockingPriority: UserBlockingPriority, + unstable_NormalPriority: NormalPriority, + unstable_IdlePriority: IdlePriority, + unstable_LowPriority: LowPriority, + unstable_runWithPriority: unstable_runWithPriority, + unstable_next: unstable_next, + unstable_scheduleCallback: unstable_scheduleCallback, + unstable_cancelCallback: unstable_cancelCallback, + unstable_wrapCallback: unstable_wrapCallback, + unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel, + unstable_shouldYield: shouldYieldToHost, + unstable_requestPaint: unstable_requestPaint, + unstable_continueExecution: unstable_continueExecution, + unstable_pauseExecution: unstable_pauseExecution, + unstable_getFirstCallbackNode: unstable_getFirstCallbackNode, + get unstable_now () { return getCurrentTime; }, + unstable_forceFrameRate: forceFrameRate, + unstable_Profiling: unstable_Profiling + }); + + var ReactSharedInternals$1 = { + ReactCurrentDispatcher: ReactCurrentDispatcher, + ReactCurrentOwner: ReactCurrentOwner, + ReactCurrentBatchConfig: ReactCurrentBatchConfig, + // Re-export the schedule API(s) for UMD bundles. + // This avoids introducing a dependency on a new UMD global in a minor update, + // Since that would be a breaking change (e.g. for all existing CodeSandboxes). + // This re-export is only required for UMD bundles; + // CJS bundles use the shared NPM package. + Scheduler: Scheduler + }; + + { + ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue; + ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + } + + function startTransition(scope, options) { + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = {}; + var currentTransition = ReactCurrentBatchConfig.transition; + + { + ReactCurrentBatchConfig.transition._updatedFibers = new Set(); + } + + try { + scope(); + } finally { + ReactCurrentBatchConfig.transition = prevTransition; + + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; + + if (updatedFibersCount > 10) { + warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); + } + + currentTransition._updatedFibers.clear(); + } + } + } + } + + var didWarnAboutMessageChannel = false; + var enqueueTaskImpl = null; + function enqueueTask(task) { + if (enqueueTaskImpl === null) { + try { + // read require off the module object to get around the bundlers. + // we don't want them to detect a require and bundle a Node polyfill. + var requireString = ('require' + Math.random()).slice(0, 7); + var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's + // version of setImmediate, bypassing fake timers if any. + + enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate; + } catch (_err) { + // we're in a browser + // we can't use regular timers because they may still be faked + // so we try MessageChannel+postMessage instead + enqueueTaskImpl = function (callback) { + { + if (didWarnAboutMessageChannel === false) { + didWarnAboutMessageChannel = true; + + if (typeof MessageChannel === 'undefined') { + error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.'); + } + } + } + + var channel = new MessageChannel(); + channel.port1.onmessage = callback; + channel.port2.postMessage(undefined); + }; + } + } + + return enqueueTaskImpl(task); + } + + var actScopeDepth = 0; + var didWarnNoAwaitAct = false; + function act(callback) { + { + // `act` calls can be nested, so we track the depth. This represents the + // number of `act` scopes on the stack. + var prevActScopeDepth = actScopeDepth; + actScopeDepth++; + + if (ReactCurrentActQueue.current === null) { + // This is the outermost `act` scope. Initialize the queue. The reconciler + // will detect the queue and use it instead of Scheduler. + ReactCurrentActQueue.current = []; + } + + var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; + var result; + + try { + // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only + // set to `true` while the given callback is executed, not for updates + // triggered during an async event, because this is how the legacy + // implementation of `act` behaved. + ReactCurrentActQueue.isBatchingLegacy = true; + result = callback(); // Replicate behavior of original `act` implementation in legacy mode, + // which flushed updates immediately after the scope function exits, even + // if it's an async function. + + if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { + var queue = ReactCurrentActQueue.current; + + if (queue !== null) { + ReactCurrentActQueue.didScheduleLegacyUpdate = false; + flushActQueue(queue); + } + } + } catch (error) { + popActScope(prevActScopeDepth); + throw error; + } finally { + ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; + } + + if (result !== null && typeof result === 'object' && typeof result.then === 'function') { + var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait + // for it to resolve before exiting the current scope. + + var wasAwaited = false; + var thenable = { + then: function (resolve, reject) { + wasAwaited = true; + thenableResult.then(function (returnValue) { + popActScope(prevActScopeDepth); + + if (actScopeDepth === 0) { + // We've exited the outermost act scope. Recursively flush the + // queue until there's no remaining work. + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + }, function (error) { + // The callback threw an error. + popActScope(prevActScopeDepth); + reject(error); + }); + } + }; + + { + if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') { + // eslint-disable-next-line no-undef + Promise.resolve().then(function () {}).then(function () { + if (!wasAwaited) { + didWarnNoAwaitAct = true; + + error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);'); + } + }); + } + } + + return thenable; + } else { + var returnValue = result; // The callback is not an async function. Exit the current scope + // immediately, without awaiting. + + popActScope(prevActScopeDepth); + + if (actScopeDepth === 0) { + // Exiting the outermost act scope. Flush the queue. + var _queue = ReactCurrentActQueue.current; + + if (_queue !== null) { + flushActQueue(_queue); + ReactCurrentActQueue.current = null; + } // Return a thenable. If the user awaits it, we'll flush again in + // case additional work was scheduled by a microtask. + + + var _thenable = { + then: function (resolve, reject) { + // Confirm we haven't re-entered another `act` scope, in case + // the user does something weird like await the thenable + // multiple times. + if (ReactCurrentActQueue.current === null) { + // Recursively flush the queue until there's no remaining work. + ReactCurrentActQueue.current = []; + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + } + }; + return _thenable; + } else { + // Since we're inside a nested `act` scope, the returned thenable + // immediately resolves. The outer scope will flush the queue. + var _thenable2 = { + then: function (resolve, reject) { + resolve(returnValue); + } + }; + return _thenable2; + } + } + } + } + + function popActScope(prevActScopeDepth) { + { + if (prevActScopeDepth !== actScopeDepth - 1) { + error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. '); + } + + actScopeDepth = prevActScopeDepth; + } + } + + function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + { + var queue = ReactCurrentActQueue.current; + + if (queue !== null) { + try { + flushActQueue(queue); + enqueueTask(function () { + if (queue.length === 0) { + // No additional work was scheduled. Finish. + ReactCurrentActQueue.current = null; + resolve(returnValue); + } else { + // Keep flushing work until there's none left. + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } + }); + } catch (error) { + reject(error); + } + } else { + resolve(returnValue); + } + } + } + + var isFlushing = false; + + function flushActQueue(queue) { + { + if (!isFlushing) { + // Prevent re-entrance. + isFlushing = true; + var i = 0; + + try { + for (; i < queue.length; i++) { + var callback = queue[i]; + + do { + callback = callback(true); + } while (callback !== null); + } + + queue.length = 0; + } catch (error) { + // If something throws, leave the remaining callbacks on the queue. + queue = queue.slice(i + 1); + throw error; + } finally { + isFlushing = false; + } + } + } + } + + var createElement$1 = createElementWithValidation ; + var cloneElement$1 = cloneElementWithValidation ; + var createFactory = createFactoryWithValidation ; + var Children = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray: toArray, + only: onlyChild + }; + + exports.Children = Children; + exports.Component = Component; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.Profiler = REACT_PROFILER_TYPE; + exports.PureComponent = PureComponent; + exports.StrictMode = REACT_STRICT_MODE_TYPE; + exports.Suspense = REACT_SUSPENSE_TYPE; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1; + exports.act = act; + exports.cloneElement = cloneElement$1; + exports.createContext = createContext; + exports.createElement = createElement$1; + exports.createFactory = createFactory; + exports.createRef = createRef; + exports.forwardRef = forwardRef; + exports.isValidElement = isValidElement; + exports.lazy = lazy; + exports.memo = memo; + exports.startTransition = startTransition; + exports.unstable_act = act; + exports.useCallback = useCallback; + exports.useContext = useContext; + exports.useDebugValue = useDebugValue; + exports.useDeferredValue = useDeferredValue; + exports.useEffect = useEffect; + exports.useId = useId; + exports.useImperativeHandle = useImperativeHandle; + exports.useInsertionEffect = useInsertionEffect; + exports.useLayoutEffect = useLayoutEffect; + exports.useMemo = useMemo; + exports.useReducer = useReducer; + exports.useRef = useRef; + exports.useState = useState; + exports.useSyncExternalStore = useSyncExternalStore; + exports.useTransition = useTransition; + exports.version = ReactVersion; + +}))); diff --git a/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.production.min.js b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.production.min.js new file mode 100644 index 00000000..9f467cac --- /dev/null +++ b/fixtures/dummy/node_modules/.pnpm/react@18.3.1/node_modules/react/umd/react.production.min.js @@ -0,0 +1,31 @@ +/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +(function(){'use strict';(function(c,x){"object"===typeof exports&&"undefined"!==typeof module?x(exports):"function"===typeof define&&define.amd?define(["exports"],x):(c=c||self,x(c.React={}))})(this,function(c){function x(a){if(null===a||"object"!==typeof a)return null;a=V&&a[V]||a["@@iterator"];return"function"===typeof a?a:null}function w(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Y(){}function K(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Z(a,b, +e){var m,d={},c=null,h=null;if(null!=b)for(m in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(c=""+b.key),b)aa.call(b,m)&&!ba.hasOwnProperty(m)&&(d[m]=b[m]);var l=arguments.length-2;if(1===l)d.children=e;else if(1>>1,d=a[c];if(0>>1;cD(l,e))fD(g,l)?(a[c]=g,a[f]=e,c=f):(a[c]=l,a[h]=e,c=h);else if(fD(g,e))a[c]=g,a[f]=e,c=f;else break a}}return b} +function D(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}function P(a){for(var b=p(r);null!==b;){if(null===b.callback)E(r);else if(b.startTime<=a)E(r),b.sortIndex=b.expirationTime,O(q,b);else break;b=p(r)}}function Q(a){z=!1;P(a);if(!u)if(null!==p(q))u=!0,R(S);else{var b=p(r);null!==b&&T(Q,b.startTime-a)}}function S(a,b){u=!1;z&&(z=!1,ea(A),A=-1);F=!0;var c=k;try{P(b);for(n=p(q);null!==n&&(!(n.expirationTime>b)||a&&!fa());){var m=n.callback;if("function"===typeof m){n.callback=null; +k=n.priorityLevel;var d=m(n.expirationTime<=b);b=v();"function"===typeof d?n.callback=d:n===p(q)&&E(q);P(b)}else E(q);n=p(q)}if(null!==n)var g=!0;else{var h=p(r);null!==h&&T(Q,h.startTime-b);g=!1}return g}finally{n=null,k=c,F=!1}}function fa(){return v()-hae?(a.sortIndex=c,O(r,a),null===p(q)&&a===p(r)&&(z?(ea(A),A=-1):z=!0,T(Q,c-e))):(a.sortIndex=d,O(q,a),u||F||(u=!0,R(S)));return a},unstable_cancelCallback:function(a){a.callback=null},unstable_wrapCallback:function(a){var b= +k;return function(){var c=k;k=b;try{return a.apply(this,arguments)}finally{k=c}}},unstable_getCurrentPriorityLevel:function(){return k},unstable_shouldYield:fa,unstable_requestPaint:function(){},unstable_continueExecution:function(){u||F||(u=!0,R(S))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return p(q)},get unstable_now(){return v},unstable_forceFrameRate:function(a){0>a||125>>1,d=a[c];if(0>>1;cD(l,e))fD(g,l)?(a[c]=g,a[f]=e,c=f):(a[c]=l,a[h]=e,c=h);else if(fD(g,e))a[c]=g,a[f]=e,c=f;else break a}}return b} +function D(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}function P(a){for(var b=p(r);null!==b;){if(null===b.callback)E(r);else if(b.startTime<=a)E(r),b.sortIndex=b.expirationTime,O(q,b);else break;b=p(r)}}function Q(a){z=!1;P(a);if(!u)if(null!==p(q))u=!0,R(S);else{var b=p(r);null!==b&&T(Q,b.startTime-a)}}function S(a,b){u=!1;z&&(z=!1,ea(A),A=-1);F=!0;var c=k;try{P(b);for(n=p(q);null!==n&&(!(n.expirationTime>b)||a&&!fa());){var m=n.callback;if("function"===typeof m){n.callback=null; +k=n.priorityLevel;var d=m(n.expirationTime<=b);b=v();"function"===typeof d?n.callback=d:n===p(q)&&E(q);P(b)}else E(q);n=p(q)}if(null!==n)var g=!0;else{var h=p(r);null!==h&&T(Q,h.startTime-b);g=!1}return g}finally{n=null,k=c,F=!1}}function fa(){return v()-hae?(a.sortIndex=c,O(r,a),null===p(q)&&a===p(r)&&(z?(ea(A),A=-1):z=!0,T(Q,c-e))):(a.sortIndex=d,O(q,a),u||F||(u=!0,R(S)));return a},unstable_cancelCallback:function(a){a.callback=null},unstable_wrapCallback:function(a){var b= +k;return function(){var c=k;k=b;try{return a.apply(this,arguments)}finally{k=c}}},unstable_getCurrentPriorityLevel:function(){return k},unstable_shouldYield:fa,unstable_requestPaint:function(){},unstable_continueExecution:function(){u||F||(u=!0,R(S))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return p(q)},get unstable_now(){return v},unstable_forceFrameRate:function(a){0>a||125=12'} dev: false + /js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + dev: false + + /loose-envify@1.4.0: + resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} + hasBin: true + dependencies: + js-tokens: 4.0.0 + dev: false + + /react@18.3.1: + resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==} + engines: {node: '>=0.10.0'} + dependencies: + loose-envify: 1.4.0 + dev: false + file:../external/gem2: resolution: {directory: ../external/gem2, type: directory} name: gem2 diff --git a/fixtures/dummy/vendor/gem3/lib/gem3/console.js b/fixtures/dummy/vendor/gem3/lib/gem3/console.js new file mode 100644 index 00000000..11ba268e --- /dev/null +++ b/fixtures/dummy/vendor/gem3/lib/gem3/console.js @@ -0,0 +1 @@ +console.log("gem3"); diff --git a/fixtures/dummy/vendor/gem3/lib/gem3/foo.js b/fixtures/dummy/vendor/gem3/lib/gem3/foo.js new file mode 100644 index 00000000..85ce559e --- /dev/null +++ b/fixtures/dummy/vendor/gem3/lib/gem3/foo.js @@ -0,0 +1 @@ +console.log("foo"); diff --git a/fixtures/dummy/vendor/gem3/lib/gem3/gem3.js b/fixtures/dummy/vendor/gem3/lib/gem3/gem3.js index a7a166fe..eb5e707f 100644 --- a/fixtures/dummy/vendor/gem3/lib/gem3/gem3.js +++ b/fixtures/dummy/vendor/gem3/lib/gem3/gem3.js @@ -1,6 +1,8 @@ import { one } from "mypackage/treeshake"; import imported from "./imported"; import "/lib/foo.js"; // app +import "./foo"; +import "/gem3/lib/gem3/console.js"; import styles from "./styles.module.css"; console.log(styles); diff --git a/fixtures/external/gem4/lib/gem4/console.js b/fixtures/external/gem4/lib/gem4/console.js new file mode 100644 index 00000000..5cab10ed --- /dev/null +++ b/fixtures/external/gem4/lib/gem4/console.js @@ -0,0 +1 @@ +console.log("gem4"); diff --git a/fixtures/external/gem4/lib/gem4/foo.js b/fixtures/external/gem4/lib/gem4/foo.js new file mode 100644 index 00000000..85ce559e --- /dev/null +++ b/fixtures/external/gem4/lib/gem4/foo.js @@ -0,0 +1 @@ +console.log("foo"); diff --git a/fixtures/external/gem4/lib/gem4/gem4.js b/fixtures/external/gem4/lib/gem4/gem4.js index d2522f19..2f72df4c 100644 --- a/fixtures/external/gem4/lib/gem4/gem4.js +++ b/fixtures/external/gem4/lib/gem4/gem4.js @@ -1,6 +1,9 @@ import { one } from "mypackage/treeshake"; import imported from "./imported"; import "/lib/foo.js"; // app +import "./foo"; +import "/gem3/lib/gem3/console.js"; +import "/gem4/lib/gem4/console.js"; import styles from "./styles.module.css"; console.log(styles); diff --git a/go.mod b/go.mod index 273c9151..1864111d 100644 --- a/go.mod +++ b/go.mod @@ -42,6 +42,7 @@ require ( github.com/peterbourgon/mergemap v0.0.1 github.com/riking/cssparse v0.0.0-20180325025645-c37ded0aac89 github.com/rogpeppe/go-internal v1.13.1 // indirect + github.com/spf13/afero v1.11.0 golang.org/x/sys v0.26.0 // indirect golang.org/x/text v0.19.0 // indirect gopkg.in/yaml.v3 v3.0.1 diff --git a/go.sum b/go.sum index dba8d6f2..4b69bdd8 100644 --- a/go.sum +++ b/go.sum @@ -97,6 +97,8 @@ github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= diff --git a/internal/builder/build.go b/internal/builder/build.go index 5a996b79..09b67948 100644 --- a/internal/builder/build.go +++ b/internal/builder/build.go @@ -19,26 +19,6 @@ const ( OutputToPath ) -type BuildOptions struct { - // The path to build relative to `root`. Multiple paths can be given by separating them with a - // semi-colon. - Path string - - // Base URL of the Rails app. eg. https://example.com - BaseUrl string - - // Path to an import map (js or json), relative to the given root. - ImportMapPath string - - // Environment variables as a JSON string. - EnvVars string - - // Import map contents. - ImportMap []byte - - Output Output -} - // Build the given `path` in the `config.RootPath`. // // - path - The path to build relative to `root`. @@ -46,32 +26,31 @@ type BuildOptions struct { // - RootPath - The working directory, usually Rails root. // - GemPath - Proscenium gem root. // - Environment - The environment (1 = development, 2 = test, 3 = production) -// - ImportMapPath - Path to the import map relative to `root`. // - EnvVars - Map of environment variables. // - Engines- Map of Rails engine names and paths. // - CodeSpitting? +// - Bundle? // - Debug? // //export build -func Build(path string, output Output) esbuild.BuildResult { +func Build(path string, args ...Output) esbuild.BuildResult { entrypoints := strings.Split(path, ";") - // default to outputting to a string - if output < 1 { - output = OutputToString - } - - importMap := []byte{} - err := importmap.Parse(importMap) + _, err := importmap.Imports() if err != nil { return esbuild.BuildResult{ Errors: []esbuild.Message{{ - Text: "Failed to parse import map", + Text: "Failed to parse importmap", Detail: err.Error(), }}, } } + output := OutputToString + if len(args) > 0 { + output = args[0] + } + minify := !types.Config.Debug && types.Config.Environment == types.ProdEnv logLevel := esbuild.LogLevelSilent @@ -104,7 +83,7 @@ func Build(path string, output Output) esbuild.BuildResult { MinifyIdentifiers: minify, MinifySyntax: minify, Bundle: true, - External: []string{"*.rjs", "*.gif", "*.jpg", "*.png", "*.woff2", "*.woff"}, + ResolveExtensions: []string{".tsx", ".ts", ".jsx", ".js", ".mjs", ".css", ".json"}, Conditions: []string{types.Config.Environment.String(), "proscenium"}, Write: true, Sourcemap: sourcemap, @@ -134,10 +113,18 @@ func Build(path string, output Output) esbuild.BuildResult { buildOptions.Plugins = []esbuild.Plugin{ plugin.I18n, plugin.Rjs(), - plugin.Bundler, - plugin.Svg, plugin.Css, + plugin.Libs, } + if types.Config.Bundle { + buildOptions.External = []string{"*.rjs", "*.gif", "*.jpg", "*.png", "*.woff2", "*.woff"} + buildOptions.Plugins = append(buildOptions.Plugins, plugin.Bundler) + } else { + buildOptions.Plugins = append(buildOptions.Plugins, plugin.Bundless) + } + + buildOptions.Plugins = append(buildOptions.Plugins, plugin.Svg, plugin.Css) + if !utils.IsUrl(path) { definitions, err := buildEnvVars() if err != nil { diff --git a/internal/css/mixins.go b/internal/css/mixins.go index ab75bb6a..4a9da86e 100644 --- a/internal/css/mixins.go +++ b/internal/css/mixins.go @@ -34,9 +34,7 @@ func (p *cssParser) resolveMixin(mixinIdent string, uri string) bool { if uri != "" { // Resolve the uri. - absPath, err := resolver.Resolve(uri, resolver.Options{ - Importer: p.filePath, - }) + absPath, err := resolver.Resolve(uri, p.filePath) if err != nil { return false } diff --git a/internal/importmap/importmap.go b/internal/importmap/importmap.go new file mode 100644 index 00000000..ba01220f --- /dev/null +++ b/internal/importmap/importmap.go @@ -0,0 +1,174 @@ +package importmap + +import ( + "encoding/json" + "errors" + "fmt" + "joelmoss/proscenium/internal/types" + "os" + "path" + + "github.com/dop251/goja" + "github.com/mitchellh/mapstructure" +) + +type ImportMapScopes map[string]string +type ImportMapImports map[string]string +type contentType uint8 + +func wrapError(err error) error { + return fmt.Errorf("Cannot read import map: %w", err) +} + +const ( + JsonType contentType = iota + JavascriptType + NoType +) + +type ImportMap struct { + Imports ImportMapImports + Scopes map[string]ImportMapScopes + FilePath string + IsParsed bool +} + +func (ctype contentType) String() string { + return [...]string{"json", "javascript", "nil"}[ctype] +} + +func (im *ImportMap) reset() { + TEST_IMPORT_MAP_FILE = "" + TEST_IMPORT_MAP_TYPE = NoType + im.Imports = map[string]string{} + im.Scopes = map[string]ImportMapScopes{} + im.FilePath = "UKNOWN" + im.IsParsed = false +} + +func (im *ImportMap) parse() error { + if im.IsParsed { + return nil + } + + filePath, ctype := im.guessFile() + if ctype == NoType { + return nil + } + + fileContents, err := os.ReadFile(filePath) + if err != nil { + return wrapError(err) + } + + err = im.parseContents(fileContents, ctype) + if err != nil { + return err + } + + return nil +} + +// Parses the given import map `contents` as JSON or JS (`contentType`). +func (im *ImportMap) parseContents(contents []byte, contentType contentType) error { + if contentType == JsonType { + if err := json.Unmarshal(contents, &im); err != nil { + return wrapError(err) + } + } else if contentType == JavascriptType { + vm := goja.New() + jsFn, jsErr := vm.RunString(string(contents)) + if jsErr != nil { + return wrapError(jsErr) + } + + mapFn, ok := goja.AssertFunction(jsFn) + if !ok { + return wrapError(errors.New("invalid format")) + } + + fnRes, err := mapFn(goja.Undefined(), vm.ToValue(types.Config.Environment.String())) + if err != nil { + return wrapError(err) + } + + if err = mapstructure.Decode(fnRes.Export(), &im); err != nil { + return wrapError(err) + } + } + + im.IsParsed = true + + return nil +} + +var TEST_IMPORT_MAP_FILE string +var TEST_IMPORT_MAP_TYPE contentType + +func (im *ImportMap) guessFile() (string, contentType) { + if TEST_IMPORT_MAP_FILE != "" && + (TEST_IMPORT_MAP_TYPE == JsonType || TEST_IMPORT_MAP_TYPE == JavascriptType) { + if filePath, ok := im.fileExists(TEST_IMPORT_MAP_FILE); ok { + return filePath, TEST_IMPORT_MAP_TYPE + } else { + panic("Cannot find TEST_IMPORT_MAP_FILE: " + TEST_IMPORT_MAP_FILE) + } + } else if filePath, ok := im.fileExists("config/import_map.json"); ok { + return filePath, JsonType + } else if filePath, ok := im.fileExists("config/import_map.js"); ok { + return filePath, JavascriptType + } else { + return "", NoType + } +} + +func (im *ImportMap) fileExists(file string) (string, bool) { + filePath := path.Join(types.Config.RootPath, file) + + if _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) { + return "", false + } else { + im.FilePath = filePath + return filePath, true + } +} + +var importmap ImportMap + +func Imports() (ImportMapImports, error) { + if !importmap.IsParsed { + if err := importmap.parse(); err != nil { + return nil, err + } + } + + return importmap.Imports, nil +} + +func FilePath() string { + return importmap.FilePath +} + +// TESTING HELPERS +func NewJavaScriptImportMap(contents []byte) error { + return NewImportMap(contents, JavascriptType) +} + +func NewJsonImportMap(contents []byte) error { + return NewImportMap(contents, JsonType) +} + +func NewImportMap(contents []byte, ctype contentType) error { + importmap.reset() + + err := importmap.parseContents(contents, ctype) + if err != nil { + return err + } + + return nil +} + +func Reset() { + importmap.reset() +} diff --git a/internal/importmap/parse.go b/internal/importmap/parse.go index 8b4addd1..041bfed6 100644 --- a/internal/importmap/parse.go +++ b/internal/importmap/parse.go @@ -1,95 +1,95 @@ package importmap -import ( - "encoding/json" - "errors" - "joelmoss/proscenium/internal/types" - "os" - "path" - "reflect" - - "github.com/dop251/goja" - "github.com/mitchellh/mapstructure" -) - -type ContentType uint8 - -// Holds the parsed content of the import map. -// FIXME: This is cached, which means we have to restart rails to pick up changes to the import map. -var Contents *types.ImportMap = &types.ImportMap{} - -const ( - JsonType ContentType = iota + 1 - JavascriptType -) - -type SyntaxError struct { - Message string -} - -func (err SyntaxError) Error() string { - return err.Message -} - -func Parse(importMap []byte) error { - if Contents.IsParsed { - return nil - } - - if len(importMap) > 0 { - err := parseContents(importMap, JsonType) - if err != nil { - return errors.New(reflect.TypeOf(err).String() + ": " + err.Error()) - } - } else if len(types.Config.ImportMapPath) > 0 { - err := parseFile(path.Join(types.Config.RootPath, types.Config.ImportMapPath)) - if err != nil { - return err - } - } - - return nil -} - -// Parses the import map file at the given path, and for the given environment. The file can be a JSON or JS file. -func parseFile(file string) error { - bytes, err := os.ReadFile(file) - if err != nil { - return err - } - - var contentType ContentType - switch path.Ext(file) { - case ".json": - contentType = JsonType - case ".js": - contentType = JavascriptType - } - - return parseContents(bytes, contentType) -} - -// Parses the given import map contents as JSON or JS, and for the given environment. -func parseContents(contents []byte, contentType ContentType) error { - if contentType == JsonType { - err := json.Unmarshal(contents, &Contents) - if err != nil { - return err - } - } else if contentType == JavascriptType { - vm := goja.New() - v, runErr := vm.RunString("(" + string(contents) + ")('" + types.Config.Environment.String() + "')") - if runErr != nil { - return runErr - } - - err := mapstructure.Decode(v.Export(), &Contents) - if err != nil { - return err - } - } - - Contents.IsParsed = true - - return nil -} +// import ( +// "encoding/json" +// "errors" +// "joelmoss/proscenium/internal/types" +// "os" +// "path" +// "reflect" + +// "github.com/dop251/goja" +// "github.com/mitchellh/mapstructure" +// ) + +// type ContentType uint8 + +// // Holds the parsed content of the import map. +// // FIXME: This is cached, which means we have to restart rails to pick up changes to the import map. +// var Contents *types.ImportMap = &types.ImportMap{} + +// const ( +// JsonType ContentType = iota + 1 +// JavascriptType +// ) + +// type SyntaxError struct { +// Message string +// } + +// func (err SyntaxError) Error() string { +// return err.Message +// } + +// func Parse(importMap []byte) error { +// if Contents.IsParsed { +// return nil +// } + +// if len(importMap) > 0 { +// err := parseContents(importMap, JsonType) +// if err != nil { +// return errors.New(reflect.TypeOf(err).String() + ": " + err.Error()) +// } +// } else if len(types.Config.ImportMapPath) > 0 { +// err := parseFile(path.Join(types.Config.RootPath, types.Config.ImportMapPath)) +// if err != nil { +// return err +// } +// } + +// return nil +// } + +// // Parses the import map file at the given path, and for the given environment. The file can be a JSON or JS file. +// func parseFile(file string) error { +// bytes, err := os.ReadFile(file) +// if err != nil { +// return err +// } + +// var contentType ContentType +// switch path.Ext(file) { +// case ".json": +// contentType = JsonType +// case ".js": +// contentType = JavascriptType +// } + +// return parseContents(bytes, contentType) +// } + +// // Parses the given import map contents as JSON or JS, and for the given environment. +// func parseContents(contents []byte, contentType ContentType) error { +// if contentType == JsonType { +// err := json.Unmarshal(contents, &Contents) +// if err != nil { +// return err +// } +// } else if contentType == JavascriptType { +// vm := goja.New() +// v, runErr := vm.RunString("(" + string(contents) + ")('" + types.Config.Environment.String() + "')") +// if runErr != nil { +// return runErr +// } + +// err := mapstructure.Decode(v.Export(), &Contents) +// if err != nil { +// return err +// } +// } + +// Contents.IsParsed = true + +// return nil +// } diff --git a/internal/importmap/resolve.go b/internal/importmap/resolve.go index ea9f34c1..dd1209dd 100644 --- a/internal/importmap/resolve.go +++ b/internal/importmap/resolve.go @@ -28,21 +28,24 @@ type importEntry struct { // Returns the resolved specifier, and a boolean indicating whether the resolution was successful. // It is important to note that the resolved specifier could be an absolute URL path, an HTTP(S) // URL, or a bare module specifier. -func Resolve(specifier string, resolveDir string) (string, bool) { - if Contents == nil || len(Contents.Imports) == 0 { - return "", false +func Resolve(specifier string, resolveDir string) (string, error) { + imports, err := Imports() + if err != nil { + return specifier, err + } else if len(imports) == 0 { + return specifier, nil } resolveDir = strings.TrimPrefix(resolveDir, types.Config.RootPath) normalizedImports := make(map[string]importEntry) // Sort and normalize imports. - for key, value := range Contents.Imports { + for key, value := range imports { if key == "" || value == "" { continue } - key = normalizeKey(key, resolveDir) + // key = normalizeKey(key, resolveDir) value = normalizeValue(value, resolveDir) keyHasTrailingSlash := strings.HasSuffix(key, "/") valueHasTrailingSlash := strings.HasSuffix(value, "/") @@ -101,10 +104,10 @@ func Resolve(specifier string, resolveDir string) (string, bool) { log.Printf("[proscenium] importmap match! `%v` => `%v`", specifier, matchedPath) } - return matchedPath, true + return matchedPath, nil } - return "", false + return specifier, nil } func normalizeKey(key string, resolveDir string) string { diff --git a/internal/plugin/bundler.go b/internal/plugin/bundler.go index f524a8af..b8021004 100644 --- a/internal/plugin/bundler.go +++ b/internal/plugin/bundler.go @@ -24,7 +24,6 @@ var Bundler = esbuild.Plugin{ Name: "bundler", Setup: func(build esbuild.PluginBuild) { root := build.InitialOptions.AbsWorkingDir - libDir := path.Join(types.Config.GemPath, "lib", "proscenium", "libs") // Resolve with esbuild. Try and avoid this call as much as possible! resolveWithEsbuild := func(pathToResolve string, args esbuild.OnResolveArgs) (esbuildResolveResult, bool) { @@ -60,34 +59,6 @@ var Bundler = esbuild.Plugin{ return result, true } - build.OnResolve(esbuild.OnResolveOptions{Filter: `^@proscenium/`}, - func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { - - pathToResolve := path.Join(libDir, strings.TrimPrefix(args.Path, "@proscenium/")) - - r := build.Resolve(pathToResolve, esbuild.ResolveOptions{ - ResolveDir: args.ResolveDir, - Importer: args.Importer, - Kind: args.Kind, - PluginData: types.PluginData{ - IsResolvingPath: true, - }, - }) - - sideEffects := esbuild.SideEffectsFalse - if r.SideEffects { - sideEffects = esbuild.SideEffectsTrue - } - - return esbuild.OnResolveResult{ - Path: r.Path, - External: r.External, - Errors: r.Errors, - Warnings: r.Warnings, - SideEffects: sideEffects, - }, nil - }) - // File types which should be external. build.OnResolve(esbuild.OnResolveOptions{Filter: `\.(gif|jpe?g|png|woff2?)$`}, func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { @@ -98,8 +69,6 @@ var Bundler = esbuild.Plugin{ build.OnResolve(esbuild.OnResolveOptions{Filter: `^https?://(.+)\.svg$`}, func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { - // pp.Println("[1a] filter(^https://)", args) - // SVG files imported from JSX should be downloaded and bundled as JSX with the svgFromJsx // namespace. if utils.IsImportedFromJsx(args.Path, args) { @@ -163,8 +132,6 @@ var Bundler = esbuild.Plugin{ } } - // pp.Println("[3] filter(.*)", args) - if result.Path == "" { result.Path = args.Path } @@ -182,11 +149,19 @@ var Bundler = esbuild.Plugin{ unbundled = true } - resolvedImport, importMapMatched := importmap.Resolve(result.Path, args.ResolveDir) - if importMapMatched { + resolvedImport, imErr := importmap.Resolve(result.Path, args.ResolveDir) + if imErr != nil { + result.PluginName = "importmap" + result.Errors = []esbuild.Message{{ + Text: imErr.Error(), + Location: &esbuild.Location{File: importmap.FilePath()}, + Detail: imErr, + }} + return result, nil + } else { result.Path = resolvedImport - if utils.IsUrl(resolvedImport) { + if utils.IsUrl(result.Path) { result.External = true return result, nil } diff --git a/internal/plugin/bundless.go b/internal/plugin/bundless.go new file mode 100644 index 00000000..faca111b --- /dev/null +++ b/internal/plugin/bundless.go @@ -0,0 +1,178 @@ +package plugin + +import ( + "joelmoss/proscenium/internal/importmap" + "joelmoss/proscenium/internal/types" + "joelmoss/proscenium/internal/utils" + "path" + "path/filepath" + "strings" + + esbuild "github.com/evanw/esbuild/pkg/api" +) + +// Bundler plugin that does not bundles everything together. +var Bundless = esbuild.Plugin{ + Name: "bundless", + Setup: func(build esbuild.PluginBuild) { + root := build.InitialOptions.AbsWorkingDir + + build.OnResolve(esbuild.OnResolveOptions{Filter: ".*"}, + func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { + // Pass through paths that are currently resolving. + if args.PluginData != nil && args.PluginData.(types.PluginData).IsResolvingPath { + return esbuild.OnResolveResult{}, nil + } + + // Should we use esbuild to resolve this path? + useResolve := false + + // Path that is resolved from a Rails engine. + pathFromEngine := "" + + // The root path of the resolved Rails engine. + resolvedEnginePath := "" + + // The key of the resolved Rails engine. + resolvedEngineKey := "" + + result := esbuild.OnResolveResult{ + External: true, + Path: strings.TrimPrefix(args.Path, "unbundle:"), + } + + // Entry points should usually be passed through as-is, so esbuild can handle them. However, + // we do need to resolve paths that are from any registered Rails engines. + if args.Kind == esbuild.ResolveEntryPoint { + // Handle Ruby gems. + for key, value := range types.Config.Engines { + prefix := key + pathSep + if strings.HasPrefix(result.Path, prefix) { + resolvedEngineKey = key + resolvedEnginePath = value + pathFromEngine = filepath.Join(value, strings.TrimPrefix(result.Path, prefix)) + break + } + } + + if pathFromEngine == "" { + // Not in an engine, so pass through entry point as-is. + return esbuild.OnResolveResult{}, nil + } + + result.External = false + } else { + // Handle non-entrypoint Ruby gems. + for key, value := range types.Config.Engines { + prefix := pathSep + key + pathSep + if strings.HasPrefix(result.Path, prefix) { + resolvedEngineKey = key + resolvedEnginePath = value + pathFromEngine = filepath.Join(value, strings.TrimPrefix(result.Path, prefix)) + break + } + } + } + + if pathFromEngine != "" { + result.Path = pathFromEngine + } else { + if resolvedPath, imErr := importmap.Resolve(result.Path, args.ResolveDir); imErr != nil { + result.PluginName = "importmap" + result.Errors = []esbuild.Message{{ + Text: imErr.Error(), + Location: &esbuild.Location{File: importmap.FilePath()}, + Detail: imErr, + }} + return result, nil + } else { + result.Path = resolvedPath + + if strings.HasPrefix(result.Path, "unbundle:") { + result.Path = strings.TrimPrefix(result.Path, "unbundle:") + } + } + + if utils.IsUrl(result.Path) { + goto FINISH + } + + if path.IsAbs(result.Path) { + result.Path = path.Join(root, result.Path) + } else if utils.PathIsRelative(result.Path) { + result.Path = path.Join(args.ResolveDir, result.Path) + } + } + + // isCssImportedFromJs := false + if utils.IsCssImportedFromJs(result.Path, args) { + // We're importing a CSS file from JS(X). Assigning `pluginData.importedFromJs` tells + // the css plugin to return the CSS as a JS object of class names (css module). + // isCssImportedFromJs = true + result.External = false + result.PluginData = types.PluginData{ImportedFromJs: true} + } + + if utils.IsBareModule(result.Path) || filepath.Ext(result.Path) == "" { + useResolve = true + } + + if useResolve { + resolveOpts := esbuild.ResolveOptions{ + ResolveDir: args.ResolveDir, + Importer: args.Importer, + Kind: args.Kind, + PluginData: types.PluginData{ + IsResolvingPath: true, + }, + } + + if utils.IsBareModule(result.Path) { + // If importer is a Rails engine, then change ResolveDir to the app root. This ensures + // that bare imports are resolved relative to the app root, and not the engine root. + // Which allows us to use the app's package.json and node_modules dir. + for _, value := range types.Config.Engines { + if strings.HasPrefix(args.Importer, value+pathSep) { + resolveOpts.ResolveDir = root + break + } + } + } + + r := build.Resolve(result.Path, resolveOpts) + + result.Path = r.Path + result.Errors = r.Errors + result.Warnings = r.Warnings + + if r.SideEffects { + result.SideEffects = esbuild.SideEffectsTrue + } else { + result.SideEffects = esbuild.SideEffectsFalse + } + } + + FINISH: + // Only entrypoints must be an absolute path. + if args.Kind != esbuild.ResolveEntryPoint && result.Path != "" { + if !strings.HasPrefix(result.Path, root) { + if resolvedEnginePath != "" && resolvedEngineKey != "" { + result.Path = filepath.Join(pathSep, resolvedEngineKey, strings.TrimPrefix(result.Path, resolvedEnginePath)) + } else { + for key, value := range types.Config.Engines { + if strings.HasPrefix(result.Path, value+pathSep) { + result.Path = filepath.Join(pathSep, key, strings.TrimPrefix(result.Path, value)) + break + } + } + } + } else { + result.Path = strings.TrimPrefix(result.Path, root) + } + } + + // pp.Println("[bundless] resolve", result) + + return result, nil + }) + }} diff --git a/internal/plugin/libs.go b/internal/plugin/libs.go new file mode 100644 index 00000000..28fa0983 --- /dev/null +++ b/internal/plugin/libs.go @@ -0,0 +1,51 @@ +package plugin + +import ( + "joelmoss/proscenium/internal/types" + "path" + "path/filepath" + "strings" + + esbuild "github.com/evanw/esbuild/pkg/api" +) + +var Libs = esbuild.Plugin{ + Name: "libs", + Setup: func(build esbuild.PluginBuild) { + libDir := path.Join(types.Config.GemPath, "lib", "proscenium", "libs") + + build.OnResolve(esbuild.OnResolveOptions{Filter: `^@proscenium/`}, + func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { + pathToResolve := path.Join(libDir, strings.TrimPrefix(args.Path, "@proscenium/")) + + if filepath.Ext(pathToResolve) != "" { + // We have a full file path with extension, so no need to resolve with esbuild. Instead + // just pass through as-is. + return esbuild.OnResolveResult{ + Path: pathToResolve, + }, nil + } + + r := build.Resolve(pathToResolve, esbuild.ResolveOptions{ + ResolveDir: args.ResolveDir, + Importer: args.Importer, + Kind: args.Kind, + PluginData: types.PluginData{ + IsResolvingPath: true, + }, + }) + + sideEffects := esbuild.SideEffectsFalse + if r.SideEffects { + sideEffects = esbuild.SideEffectsTrue + } + + return esbuild.OnResolveResult{ + Path: r.Path, + External: r.External, + Errors: r.Errors, + Warnings: r.Warnings, + SideEffects: sideEffects, + }, nil + }) + }} diff --git a/internal/resolver/resolve.go b/internal/resolver/resolve.go index 0ab3ae18..0ebde966 100644 --- a/internal/resolver/resolve.go +++ b/internal/resolver/resolve.go @@ -16,9 +16,6 @@ import ( type Options struct { // The absolute file system path of the file doing the importing. Importer string - - // Import map as a string. - ImportMap []byte } // Resolve the given `path` relative to the `root`, where the path is a URL path or bare specifier. @@ -29,17 +26,11 @@ type Options struct { // // Returns an absolute URL path. That is, one that has a leading slash and can be appended to the // app domain. -func Resolve(filePath string, options Options) (string, error) { - // Parse the import map - if any. - err := importmap.Parse(options.ImportMap) - if err != nil { - return "", errors.New("Failed to parse import map: " + err.Error()) - } - +func Resolve(filePath string, importer string) (string, error) { // Look for a match in the import map - resolvedImport, matched := importmap.Resolve(filePath, types.Config.RootPath) - if matched { - filePath = resolvedImport + filePath, imErr := importmap.Resolve(filePath, types.Config.RootPath) + if imErr != nil { + return filePath, imErr } else if path.IsAbs(filePath) && utils.HasExtension(filePath) { return filePath, nil } @@ -49,11 +40,11 @@ func Resolve(filePath string, options Options) (string, error) { } if utils.PathIsRelative(filePath) { - if options.Importer == "" { + if importer == "" { return "", errors.New("relative paths are not supported when an importer is not given") } - return strings.TrimPrefix(path.Join(path.Dir(options.Importer), filePath), types.Config.RootPath), nil + return strings.TrimPrefix(path.Join(path.Dir(importer), filePath), types.Config.RootPath), nil } // Replace leading slash with `./` for absolute paths. @@ -67,14 +58,15 @@ func Resolve(filePath string, options Options) (string, error) { } result := esbuild.Build(esbuild.BuildOptions{ - EntryPoints: []string{filePath}, - AbsWorkingDir: types.Config.RootPath, - Format: esbuild.FormatESModule, - Conditions: []string{types.Config.Environment.String(), "proscenium"}, - Write: false, - Metafile: true, - LogLevel: logLevel, - LogLimit: 1, + EntryPoints: []string{filePath}, + AbsWorkingDir: types.Config.RootPath, + Format: esbuild.FormatESModule, + Conditions: []string{types.Config.Environment.String(), "proscenium"}, + ResolveExtensions: []string{".tsx", ".ts", ".jsx", ".js", ".mjs", ".css", ".json"}, + Write: false, + Metafile: true, + LogLevel: logLevel, + LogLimit: 1, // The Esbuild default places browser before module, but we're building for modern browsers // which support esm. So we prioritise that. Some libraries export a "browser" build that still @@ -87,7 +79,7 @@ func Resolve(filePath string, options Options) (string, error) { } var metadata struct{ Inputs map[string]interface{} } - err = json.Unmarshal([]byte(result.Metafile), &metadata) + err := json.Unmarshal([]byte(result.Metafile), &metadata) if err != nil { return "", err } diff --git a/internal/types/types.go b/internal/types/types.go index f9cdbf90..9dc67e33 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -16,37 +16,29 @@ func (e Environment) String() string { // - RootPath - The working directory, usually Rails root. // - GemPath - Proscenium gem root. // - Environment - The environment (1 = development, 2 = test, 3 = production) -// - ImportMapPath - Path to the import map relative to `root`. // - EnvVars - Map of environment variables. // - Engines- Map of Rails engine names and paths. -// - CodeSpitting? +// - CodeSplitting? +// - Bundle? // - Debug? type ConfigT struct { RootPath string GemPath string - ImportMapPath string Engines map[string]string EnvVars map[string]string Debug bool CodeSplitting bool + Bundle bool Environment Environment } -var Config = ConfigT{} -var zeroConfig = &ConfigT{} +var Config = ConfigT{CodeSplitting: true, Bundle: true} +var zeroConfig = &ConfigT{CodeSplitting: true, Bundle: true} func (config *ConfigT) Reset() { *config = *zeroConfig } -type ImportMapScopes map[string]string - -type ImportMap struct { - Imports map[string]string - Scopes map[string]ImportMapScopes - IsParsed bool -} - type PluginData = struct { IsResolvingPath bool ImportedFromJs bool diff --git a/lib/proscenium/builder.rb b/lib/proscenium/builder.rb index 9d9297bc..3ef9642c 100644 --- a/lib/proscenium/builder.rb +++ b/lib/proscenium/builder.rb @@ -83,10 +83,10 @@ def initialize(root: nil) RootPath: (root || Rails.root).to_s, GemPath: gem_root, Environment: ENVIRONMENTS.fetch(Rails.env.to_sym, 2), - ImportMapPath: import_map_path, Engines: engines, EnvVars: env_vars, CodeSplitting: Proscenium.config.code_splitting, + Bundle: Proscenium.config.bundle, Debug: Proscenium.config.debug }.to_json) end @@ -145,19 +145,19 @@ def engines end end - def import_map_path - return unless (path = Rails.root&.join('config')) + # def import_map_path + # return unless (path = Rails.root&.join('config')) - if (json = path.join('import_map.json')).exist? - return json.relative_path_from(@root).to_s - end + # if (json = path.join('import_map.json')).exist? + # return json.relative_path_from(@root).to_s + # end - if (js = path.join('import_map.js')).exist? - return js.relative_path_from(@root).to_s - end + # if (js = path.join('import_map.js')).exist? + # return js.relative_path_from(@root).to_s + # end - nil - end + # nil + # end def gem_root Pathname.new(__dir__).join('..', '..').to_s diff --git a/lib/proscenium/railtie.rb b/lib/proscenium/railtie.rb index fc062dcb..e5e27949 100644 --- a/lib/proscenium/railtie.rb +++ b/lib/proscenium/railtie.rb @@ -11,7 +11,7 @@ class Railtie < ::Rails::Engine config.proscenium = ActiveSupport::OrderedOptions.new config.proscenium.debug = false - config.proscenium.bundle = false + config.proscenium.bundle = true config.proscenium.side_load = true config.proscenium.code_splitting = true @@ -39,6 +39,7 @@ class Railtie < ::Rails::Engine # config.proscenium.engines << self # end config.proscenium.engines = Set.new + config.proscenium.engines << self config.action_dispatch.rescue_templates = { 'Proscenium::Builder::BuildError' => 'build_error' diff --git a/main.go b/main.go index a06c43fe..edd97211 100644 --- a/main.go +++ b/main.go @@ -74,7 +74,7 @@ func resolve(filePath *C.char, configJson *C.char) C.struct_Result { return C.struct_Result{C.int(0), C.CString(err.Error())} } - resolvedPath, err := resolver.Resolve(C.GoString(filePath), resolver.Options{}) + resolvedPath, err := resolver.Resolve(C.GoString(filePath), "") if err != nil { return C.struct_Result{C.int(0), C.CString(string(err.Error()))} } diff --git a/test/build_bundless_test.go b/test/build_bundless_test.go new file mode 100644 index 00000000..729e9639 --- /dev/null +++ b/test/build_bundless_test.go @@ -0,0 +1,258 @@ +package proscenium_test + +import ( + b "joelmoss/proscenium/internal/builder" + "joelmoss/proscenium/internal/importmap" + "joelmoss/proscenium/internal/types" + . "joelmoss/proscenium/test/support" + "path/filepath" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("Build bundless", func() { + BeforeEach(func() { + types.Config.Bundle = false + }) + + It("should fail on unknown entrypoint", func() { + result := b.Build("unknown.js") + + Expect(result.Errors[0].Text).To(Equal("Could not resolve \"unknown.js\"")) + }) + + It("should build entrypoint", func() { + Expect(b.Build("lib/foo.js")).To(ContainCode(`console.log("/lib/foo.js")`)) + }) + + It("should not build entrypoint with import map", func() { + importmap.NewJsonImportMap([]byte(`{ + "imports": { + "/lib/foo.js": "/lib/foo2.js" + } + }`)) + Expect(b.Build("lib/foo.js")).To(ContainCode(`console.log("/lib/foo.js")`)) + }) + + It("should leave rjs imports untouched", func() { + Expect(b.Build("lib/rjs.js")).To(ContainCode(`import foo from "/constants.rjs"`)) + }) + + It("should resolve bare module", func() { + Expect(b.Build("lib/import_npm_module.js")).To(ContainCode(` + import { one } from "/packages/mypackage/treeshake.js"; + one(); + `)) + }) + + It("should resolve extension-less imports", func() { + Expect(b.Build("lib/import_absolute_module_without_extension.js")).To(ContainCode(` + import foo from "/lib/foo2.js"; + `)) + }) + + It("should resolve relative path", func() { + Expect(b.Build("lib/import_relative_module.js")).To(ContainCode(` + import foo4 from "/lib/foo4.js"; + foo4(); + `)) + }) + + It("should resolve absolute path", func() { + Expect(b.Build("lib/import_absolute_module.js")).To(ContainCode(` + import foo4 from "/lib/foo4.js"; + foo4(); + `)) + }) + + It("should resolve from import map", func() { + importmap.NewJsonImportMap([]byte(`{ + "imports": { + "/lib/foo4.js": "/lib/foo.js" + } + }`)) + + Expect(b.Build("lib/import_absolute_module.js")).To(ContainCode(` + import foo4 from "/lib/foo.js"; + foo4(); + `)) + }) + + It("unbundle: prefix is stripped and ignored", func() { + importmap.NewJsonImportMap([]byte(`{ + "imports": { + "/lib/foo3.js": "unbundle:/lib/foo32.js", + "react-dom": "unbundle:react-dom" + } + }`)) + + Expect(b.Build("lib/unbundle/local_modules.js")).To(ContainCode(` + import "/lib/unbundle/foo1.js"; + import "/lib/unbundle/foo2.js"; + import "/lib/foo32.js"; + import { one } from "/packages/mypackage/treeshake.js"; + import "/packages/mypackage/index.js"; + `)) + }) + + Describe("vendored ruby gem", func() { + var _ = BeforeEach(func() { + types.Config.Engines = map[string]string{ + "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), + } + }) + + It("should fail on unknown entrypoint", func() { + result := b.Build("unknown.js") + + Expect(result.Errors[0].Text).To(Equal("Could not resolve \"unknown.js\"")) + }) + + It("engine is resolved before import map", func() { + importmap.NewJsonImportMap([]byte(`{ + "imports": { + "/gem3/lib/gem3/console.js": "/lib/foo.js", + } + }`)) + + result := b.Build("lib/engines/gem3.js") + + Expect(result).To(ContainCode(`import "/vendor/gem3/lib/gem3/console.js";`)) + }) + + It("should resolve extension-less imports", func() { + result := b.Build("gem3/lib/gem3/gem3.js") + + Expect(result).To(ContainCode(`import "/vendor/gem3/lib/gem3/foo.js";`)) + }) + + It("should fail on engined but unknown entrypoint", func() { + result := b.Build("gem3/unknown.js") + + Expect(result.Errors[0].Text).To(Equal("Could not read from file: /Users/joelmoss/dev/proscenium/fixtures/dummy/vendor/gem3/unknown.js")) + }) + + It("resolves entry point", func() { + result := b.Build("gem3/lib/gem3/console.js") + + Expect(result).To(ContainCode(`console.log("gem3");`)) + }) + + It("resolves absolute and same engine imports", func() { + result := b.Build("gem3/lib/gem3/gem3.js") + + Expect(result).To(ContainCode(` + import "/vendor/gem3/lib/gem3/console.js"; + `)) + }) + + It("resolves bare import to Rails app (not engine)", func() { + result := b.Build("gem3/lib/gem3/gem3.js") + + Expect(result).To(ContainCode(` + import { one } from "/packages/mypackage/treeshake.js"; + `)) + }) + + It("resolves relative import to engine", func() { + result := b.Build("gem3/lib/gem3/gem3.js") + + Expect(result).To(ContainCode(` + import imported from "/vendor/gem3/lib/gem3/imported.js"; + `)) + }) + + It("resolves absolute import to Rails app (not engine)", func() { + result := b.Build("gem3/lib/gem3/gem3.js") + + Expect(result).To(ContainCode(` + import "/lib/foo.js"; + `)) + }) + + It("resolves import from engine when in app", func() { + result := b.Build("lib/gems/gem3.js") + + Expect(result).To(ContainCode(`import "/vendor/gem3/lib/gem3/gem3.js"`)) + }) + }) + + Describe("non-vendored ruby gem", func() { + var _ = BeforeEach(func() { + types.Config.Engines = map[string]string{ + "gem4": filepath.Join(fixturesRoot, "external", "gem4"), + } + }) + + It("should fail on unknown entrypoint", func() { + result := b.Build("unknown.js") + + Expect(result.Errors[0].Text).To(Equal("Could not resolve \"unknown.js\"")) + }) + + It("should fail on engined but unknown entrypoint", func() { + result := b.Build("gem4/unknown.js") + + Expect(result.Errors[0].Text).To(Equal("Could not read from file: /Users/joelmoss/dev/proscenium/fixtures/external/gem4/unknown.js")) + }) + + It("resolves entry point", func() { + result := b.Build("gem4/lib/gem4/console.js") + + Expect(result).To(ContainCode(`console.log("gem4");`)) + }) + + It("resolves absolute and same engine imports", func() { + result := b.Build("gem4/lib/gem4/gem4.js") + + Expect(result).To(ContainCode(` + import "/gem4/lib/gem4/console.js"; + `)) + }) + + It("resolves other engine imports", func() { + result := b.Build("gem4/lib/gem4/gem4.js") + + Expect(result).To(ContainCode(` + import "/gem3/lib/gem3/console.js"; + `)) + }) + + It("resolves bare import to Rails app (not engine)", func() { + result := b.Build("gem4/lib/gem4/gem4.js") + + Expect(result).To(ContainCode(` + import { one } from "/packages/mypackage/treeshake.js"; + `)) + }) + + It("resolves relative import to engine", func() { + result := b.Build("gem4/lib/gem4/gem4.js") + + Expect(result).To(ContainCode(` + import imported from "/gem4/lib/gem4/imported.js"; + `)) + }) + + It("resolves absolute import to Rails app (not engine)", func() { + result := b.Build("gem4/lib/gem4/gem4.js") + + Expect(result).To(ContainCode(` + import "/lib/foo.js"; + `)) + }) + + It("resolves import from engine when in app", func() { + result := b.Build("lib/gems/gem4.js") + + Expect(result).To(ContainCode(`import "/gem4/lib/gem4/gem4.js"`)) + }) + }) + + It("should define NODE_ENV", func() { + result := b.Build("lib/define_node_env.js") + + Expect(result).To(ContainCode(`console.log("test")`)) + }) +}) diff --git a/test/build_test.go b/test/build_test.go index e5f224e9..9fb5fae7 100644 --- a/test/build_test.go +++ b/test/build_test.go @@ -1,6 +1,9 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" + "joelmoss/proscenium/internal/importmap" + "joelmoss/proscenium/internal/types" . "joelmoss/proscenium/test/support" "os" "path/filepath" @@ -15,93 +18,78 @@ var fixturesRoot string = filepath.Join(cwd, "..", "fixtures") var _ = Describe("Build", func() { It("should fail on unknown entrypoint", func() { - result := Build("unknown.js") + result := b.Build("unknown.js") Expect(result.Errors[0].Text).To(Equal("Could not resolve \"unknown.js\"")) }) It("should build js", func() { - Expect(Build("lib/foo.js")).To(ContainCode(`console.log("/lib/foo.js")`)) + Expect(b.Build("lib/foo.js")).To(ContainCode(`console.log("/lib/foo.js")`)) }) It("should bundle rjs", Pending, func() { MockURL("/constants.rjs", "export default 'constants';") - Expect(Build("lib/rjs.js")).To(ContainCode(`"constants"`)) - }) - - It("should build jsx", func() { - result := Build("lib/component.jsx") - - Expect(result).To(ContainCode(` - import { jsx } from "react/jsx-runtime"; - var Component = () => { - return /* @__PURE__ */ jsx("div", { children: "Hello" }); - }; - var component_default = Component; - export { - component_default as default - }; - `)) + Expect(b.Build("lib/rjs.js")).To(ContainCode(`"constants"`)) }) It("should bundle bare module", func() { - Expect(Build("lib/import_npm_module.js")).To(ContainCode(` + Expect(b.Build("lib/import_npm_module.js")).To(ContainCode(` function one() { console.log("one"); } `)) }) It("should resolve extension-less imports", func() { - Expect(Build("lib/import_absolute_module_without_extension.js")).To(ContainCode(` + Expect(b.Build("lib/import_absolute_module_without_extension.js")).To(ContainCode(` console.log("/lib/foo2.js") `)) }) It("should bundle relative path", func() { - Expect(Build("lib/import_relative_module.js")).To(ContainCode(` + Expect(b.Build("lib/import_relative_module.js")).To(ContainCode(` console.log("/lib/foo4.js") `)) }) It("should bundle absolute path", func() { - Expect(Build("lib/import_absolute_module.js")).To(ContainCode(` + Expect(b.Build("lib/import_absolute_module.js")).To(ContainCode(` console.log("/lib/foo4.js") `)) }) PIt("should build dynamic path", func() { - Expect(Build("lib/import_dynamic.js")).To(ContainCode(` + Expect(b.Build("lib/import_dynamic.js")).To(ContainCode(` console.log("/lib/foo4.js") `)) }) Describe("unbundle:* imports", func() { It("should unbundle imports", func() { - Expect(Build("lib/unbundle/local_modules.js", BuildOpts{ - ImportMap: `{ - "imports": { - "/lib/foo3.js": "unbundle:/lib/foo3.js", - "react-dom": "unbundle:react-dom" - } - }`, - })).To(ContainCode(` + importmap.NewJsonImportMap([]byte(`{ + "imports": { + "/lib/foo3.js": "unbundle:/lib/foo3.js", + "react-dom": "unbundle:react-dom" + } + }`)) + + Expect(b.Build("lib/unbundle/local_modules.js")).To(ContainCode(` import "/lib/unbundle/foo1.js"; import "/lib/unbundle/foo2.js"; import "/lib/foo3.js"; import { one } from "/packages/mypackage/treeshake.js"; // packages/mypackage/index.js - console.log("node_modules/mypackage"); + console.log("node_modules/mypackage"); `)) }) }) Describe("vendored ruby gem", func() { It("resolves entry point", func() { - result := Build("gem3/lib/gem3/gem3.js", BuildOpts{ - Engines: map[string]string{ - "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), - }, - }) + types.Config.Engines = map[string]string{ + "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), + } + + result := b.Build("gem3/lib/gem3/gem3.js") Expect(result).To(ContainCode(`h1 { color: red; }`)) Expect(result).To(ContainCode(`h2 { color: blue; }`)) @@ -112,11 +100,11 @@ var _ = Describe("Build", func() { }) It("bundles", func() { - result := Build("lib/gems/gem3.js", BuildOpts{ - Engines: map[string]string{ - "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), - }, - }) + types.Config.Engines = map[string]string{ + "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), + } + + result := b.Build("lib/gems/gem3.js") Expect(result).To(ContainCode(`h1 { color: red; }`)) Expect(result).To(ContainCode(`h2 { color: blue; }`)) @@ -129,11 +117,12 @@ var _ = Describe("Build", func() { Describe("non-vendored ruby gem", func() { It("resolves entry point", func() { - result := Build("gem4/lib/gem4/gem4", BuildOpts{ - Engines: map[string]string{ - "gem4": filepath.Join(fixturesRoot, "external", "gem4"), - }, - }) + types.Config.Engines = map[string]string{ + "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), + "gem4": filepath.Join(fixturesRoot, "external", "gem4"), + } + + result := b.Build("gem4/lib/gem4/gem4") Expect(result).To(ContainCode(`e.id = "_401b6cac";`)) Expect(result).To(ContainCode(`.name-401b6cac`)) @@ -146,11 +135,12 @@ var _ = Describe("Build", func() { }) It("bundles", func() { - result := Build("lib/gems/gem4.js", BuildOpts{ - Engines: map[string]string{ - "gem4": filepath.Join(fixturesRoot, "external", "gem4"), - }, - }) + types.Config.Engines = map[string]string{ + "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), + "gem4": filepath.Join(fixturesRoot, "external", "gem4"), + } + + result := b.Build("lib/gems/gem4.js") Expect(result).To(ContainCode(`e.id = "_401b6cac";`)) Expect(result).To(ContainCode(`.name-401b6cac`)) @@ -164,7 +154,7 @@ var _ = Describe("Build", func() { }) It("tree shakes bare import", func() { - Expect(Build("lib/import_tree_shake.js")).To(EqualCode(` + Expect(b.Build("lib/import_tree_shake.js")).To(EqualCode(` // packages/mypackage/treeshake.js function one() { console.log("one"); @@ -178,20 +168,20 @@ var _ = Describe("Build", func() { It("does not bundle URLs", func() { MockURL("/import-url-module.js", "export default 'Hello World'") - Expect(Build("lib/import_url.js")).To(ContainCode(` + Expect(b.Build("lib/import_url.js")).To(ContainCode(` import myFunction from "https://proscenium.test/import-url-module.js"; `)) }) It("should define NODE_ENV", func() { - result := Build("lib/define_node_env.js") + result := b.Build("lib/define_node_env.js") Expect(result).To(ContainCode(`console.log("test")`)) }) When("css", func() { It("should bundle absolute path", func() { - Expect(Build("lib/import_absolute.css")).To(ContainCode(` + Expect(b.Build("lib/import_absolute.css")).To(ContainCode(` .stuff { color: red; } @@ -199,7 +189,7 @@ var _ = Describe("Build", func() { }) It("should bundle relative path", func() { - result := Build("lib/import_relative.css") + result := b.Build("lib/import_relative.css") Expect(result).To(ContainCode(` .body { @@ -214,7 +204,7 @@ var _ = Describe("Build", func() { }) It("should not bundle fonts", func() { - result := Build("lib/fonts.css") + result := b.Build("lib/fonts.css") Expect(result).To(ContainCode(`url(/somefont.woff2)`)) Expect(result).To(ContainCode(`url(/somefont.woff)`)) @@ -222,11 +212,11 @@ var _ = Describe("Build", func() { }) }) -func BenchmarkBuild(b *testing.B) { - b.ResetTimer() +func BenchmarkBuild(bm *testing.B) { + bm.ResetTimer() - for i := 0; i < b.N; i++ { - result := Build("lib/foo.js") + for i := 0; i < bm.N; i++ { + result := b.Build("lib/foo.js") if len(result.Errors) > 0 { panic("Build failed: " + result.Errors[0].Text) diff --git a/test/build_to_path_test.go b/test/build_to_path_test.go index 4ff6d5c5..1842bc97 100644 --- a/test/build_to_path_test.go +++ b/test/build_to_path_test.go @@ -1,7 +1,8 @@ package proscenium_test import ( - . "joelmoss/proscenium/test/support" + b "joelmoss/proscenium/internal/builder" + "joelmoss/proscenium/internal/types" "path/filepath" "testing" @@ -11,43 +12,44 @@ import ( var _ = Describe("BuildToPath", func() { It("should fail on unknown entrypoint", func() { - success, result := BuildToPath("unknown.js") + success, result := b.BuildToPath("unknown.js") Expect(success).To(BeFalse()) Expect(result).To(Equal("{\"ID\":\"\",\"PluginName\":\"\",\"Text\":\"Could not resolve \\\"unknown.js\\\"\",\"Location\":null,\"Notes\":null,\"Detail\":null}")) }) It("should build js", func() { - _, result := BuildToPath("lib/foo.js") + _, result := b.BuildToPath("lib/foo.js") Expect(result).To(Equal(`lib/foo.js::public/assets/lib/foo$2IXPSM5U$.js`)) }) When("multiple inputs", func() { It("should return input > output mapping", func() { - _, code := BuildToPath("lib/code_splitting/son.js;lib/code_splitting/daughter.js") + _, code := b.BuildToPath("lib/code_splitting/son.js;lib/code_splitting/daughter.js") - Expect(code).To(Equal("lib/code_splitting/son.js::public/assets/lib/code_splitting/son$7CNKRT3J$.js;lib/code_splitting/daughter.js::public/assets/lib/code_splitting/daughter$P5YYU4WE$.js")) + Expect(code).To(Equal("lib/code_splitting/son.js::public/assets/lib/code_splitting/son$LAGMAD6O$.js;lib/code_splitting/daughter.js::public/assets/lib/code_splitting/daughter$7JJ2HGHC$.js")) }) }) When("from engine", func() { It("should return input > output mapping", func() { - _, code := BuildToPath("gem4/lib/gem4/gem4.js;lib/gems/gem3.js;lib/foo.css", BuildOpts{ - Engines: map[string]string{ - "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), - "gem4": filepath.Join(fixturesRoot, "external", "gem4"), - }}) + types.Config.Engines = map[string]string{ + "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), + "gem4": filepath.Join(fixturesRoot, "external", "gem4"), + } - Expect(code).To(Equal("gem4/lib/gem4/gem4.js::public/assets/gem4/lib/gem4/gem4$24V4BFL3$.js;lib/gems/gem3.js::public/assets/lib/gems/gem3$NH2KC6S6$.js;lib/foo.css::public/assets/lib/foo$EAILS7QS$.css")) + _, code := b.BuildToPath("gem4/lib/gem4/gem4.js;lib/gems/gem3.js;lib/foo.css") + + Expect(code).To(Equal("gem4/lib/gem4/gem4.js::public/assets/gem4/lib/gem4/gem4$YQBH44X7$.js;lib/gems/gem3.js::public/assets/lib/gems/gem3$BPCGTVQJ$.js;lib/foo.css::public/assets/lib/foo$EAILS7QS$.css")) }) }) }) -func BenchmarkBuildToPath(b *testing.B) { - b.ResetTimer() +func BenchmarkBuildToPath(bm *testing.B) { + bm.ResetTimer() - for i := 0; i < b.N; i++ { - success, result := BuildToString("lib/foo.js") + for i := 0; i < bm.N; i++ { + success, result := b.BuildToPath("lib/foo.js") if !success { panic("Build failed: " + result) diff --git a/test/build_to_string_test.go b/test/build_to_string_test.go index 7ba26875..43edd2eb 100644 --- a/test/build_to_string_test.go +++ b/test/build_to_string_test.go @@ -1,6 +1,7 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" . "joelmoss/proscenium/test/support" "testing" @@ -10,19 +11,19 @@ import ( var _ = Describe("BuildToString", func() { It("should fail on unknown entrypoint", func() { - success, result := BuildToString("unknown.js") + success, result := b.BuildToString("unknown.js") Expect(success).To(BeFalse()) Expect(result).To(Equal("{\"ID\":\"\",\"PluginName\":\"\",\"Text\":\"Could not resolve \\\"unknown.js\\\"\",\"Location\":null,\"Notes\":null,\"Detail\":null}")) }) It("should build js", func() { - _, result := BuildToString("lib/foo.js") + _, result := b.BuildToString("lib/foo.js") Expect(result).To(ContainCode(`console.log("/lib/foo.js")`)) }) It("should return source map", func() { - _, result := BuildToString("lib/foo.js.map") + _, result := b.BuildToString("lib/foo.js.map") Expect(result).To(ContainCode(` "sources": ["../../../lib/foo.js"], "sourcesContent": ["console.log('/lib/foo.js')\n"], @@ -30,21 +31,21 @@ var _ = Describe("BuildToString", func() { }) It("should append source map location for js", func() { - _, result := BuildToString("lib/foo.js") + _, result := b.BuildToString("lib/foo.js") Expect(result).To(ContainCode("//# sourceMappingURL=foo.js.map")) }) It("should append source map location for css", func() { - _, result := BuildToString("lib/foo.css") + _, result := b.BuildToString("lib/foo.css") Expect(result).To(ContainCode("/*# sourceMappingURL=foo.css.map */")) }) }) -func BenchmarkBuildToString(b *testing.B) { - b.ResetTimer() +func BenchmarkBuildToString(bm *testing.B) { + bm.ResetTimer() - for i := 0; i < b.N; i++ { - success, result := BuildToString("lib/foo.js") + for i := 0; i < bm.N; i++ { + success, result := b.BuildToString("lib/foo.js") if !success { panic("Build failed: " + result) diff --git a/test/css_test.go b/test/css_test.go index 984d720e..e7167ca1 100644 --- a/test/css_test.go +++ b/test/css_test.go @@ -1,16 +1,18 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" + "joelmoss/proscenium/internal/types" . "joelmoss/proscenium/test/support" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("Build(css)", func() { +var _ = Describe("b.Build(css)", func() { Describe("plain css", func() { It("should build", func() { - Expect(Build("lib/foo.css")).To(ContainCode(`.body { color: red; }`)) + Expect(b.Build("lib/foo.css")).To(ContainCode(`.body { color: red; }`)) }) }) @@ -18,30 +20,30 @@ var _ = Describe("Build(css)", func() { path := "lib/css_modules/basic.module.css" It("should build", func() { - Expect(Build(path)).To(ContainCode(`.foo-c3f452b4 { color: red; }`)) + Expect(b.Build(path)).To(ContainCode(`.foo-c3f452b4 { color: red; }`)) }) }) When("importing absolute path", func() { It("should bundle", func() { - Expect(Build("lib/import_absolute.css")).To(ContainCode(`.stuff { color: red; }`)) + Expect(b.Build("lib/import_absolute.css")).To(ContainCode(`.stuff { color: red; }`)) }) }) When("importing css module from css", func() { It("should bundle", func() { - Expect(Build("lib/css_modules/import_css_module.css")).To(ContainCode(` - /* lib/css_modules/basic.module.css */ - .foo-c3f452b4 { color: red; } - /* lib/css_modules/import_css_module.css */ - .bar { color: blue; } - `)) + Expect(b.Build("lib/css_modules/import_css_module.css")).To(ContainCode(` + /* lib/css_modules/basic.module.css */ + .foo-c3f452b4 { color: red; } + /* lib/css_modules/import_css_module.css */ + .bar { color: blue; } + `)) }) }) When("importing css module from css module", func() { It("should bundle with different digest", func() { - result := Build("lib/css_modules/import_css_module.module.css") + result := b.Build("lib/css_modules/import_css_module.module.css") Expect(result).To(ContainCode(`.foo-c3f452b4 { color: red; }`)) Expect(result).To(ContainCode(`.bar-60bd820c { color: blue; }`)) @@ -50,28 +52,37 @@ var _ = Describe("Build(css)", func() { When("importing relative path", func() { It("should bundle", func() { - Expect(Build("lib/import_relative.css")).To(ContainCode(` - /* lib/foo.css */ - .body { color: red; } - /* lib/foo2.css */ - .body { color: blue; } - `)) + Expect(b.Build("lib/import_relative.css")).To(ContainCode(` + /* lib/foo.css */ + .body { color: red; } + /* lib/foo2.css */ + .body { color: blue; } + `)) }) }) When("importing bare specifier", func() { It("is replaced with absolute path", func() { - result := Build("lib/import_npm_module.css") + result := b.Build("lib/import_npm_module.css") Expect(result).To(ContainCode(`.mypackage { color: red; }`)) Expect(result).NotTo(ContainCode(`@import "mypackage/styles";`)) }) }) + When("importing bare specifier with extension", func() { + It("is replaced with absolute path", func() { + types.Config.Bundle = false + result := b.Build("lib/import_npm_module_with_ext.css") + + Expect(result).To(ContainCode(`@import "/packages/mypackage/styles.css"`)) + }) + }) + Describe("mixins", func() { When("from URL", func() { It("is replaced with defined mixin", func() { - Expect(Build("lib/with_mixin_from_url.css")).To(ContainCode(` + Expect(b.Build("lib/with_mixin_from_url.css")).To(ContainCode(` a { color: red; font-size: 20px; } `)) }) @@ -79,7 +90,7 @@ var _ = Describe("Build(css)", func() { When("from relative URL", func() { It("is replaced with defined mixin", func() { - Expect(Build("lib/with_mixin_from_relative_url.css")).To(ContainCode(` + Expect(b.Build("lib/with_mixin_from_relative_url.css")).To(ContainCode(` a { color: red; font-size: 20px; } `)) }) @@ -121,18 +132,30 @@ var _ = Describe("Build(css)", func() { ` It("includes stylesheet and proxies class names", func() { - Expect(Build("lib/import_css_module.js")).To(ContainCode(expectedCode)) + Expect(b.Build("lib/import_css_module.js")).To(ContainCode(expectedCode)) }) It("import relative css module from js", func() { - Expect(Build("lib/import_relative_css_module.js")).To(ContainCode(expectedCode)) + Expect(b.Build("lib/import_relative_css_module.js")).To(ContainCode(expectedCode)) }) - When("importing css module from css module", func() { - path := "lib/css_modules/import_css_module.js" + When("Bundle = false", func() { + BeforeEach(func() { + types.Config.Bundle = false + }) + + It("import relative css module from js", func() { + Expect(b.Build("lib/import_relative_css_module.js")).To(ContainCode(expectedCode)) + }) + It("includes stylesheet and proxies class names", func() { + Expect(b.Build("lib/import_css_module.js")).To(ContainCode(expectedCode)) + }) + }) + + When("importing css module from css module", func() { It("should bundle with different digest", func() { - result := Build(path) + result := b.Build("lib/css_modules/import_css_module.js") Expect(result).To(ContainCode(`.foo-c3f452b4 { color: red; }`)) Expect(result).To(ContainCode(`.bar-60bd820c { color: blue; }`)) diff --git a/test/env_test.go b/test/env_test.go index 01983284..431c96b1 100644 --- a/test/env_test.go +++ b/test/env_test.go @@ -1,22 +1,23 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" . "joelmoss/proscenium/test/support" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("Build(env)", func() { +var _ = Describe("b.Build(env)", func() { It("replaces with value", func() { - Expect(Build("lib/env/env.js")).To(ContainCode(` + Expect(b.Build("lib/env/env.js")).To(ContainCode(` console.log("testtest"); `)) }) When("env var is undefined", func() { It("is void", func() { - Expect(Build("lib/env/unknown.js")).To(ContainCode(` + Expect(b.Build("lib/env/unknown.js")).To(ContainCode(` console.log((void 0).NUFFIN); console.log("test"); `)) diff --git a/test/i18n_test.go b/test/i18n_test.go index 0b45baf2..99659423 100644 --- a/test/i18n_test.go +++ b/test/i18n_test.go @@ -1,6 +1,7 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" . "joelmoss/proscenium/test/support" "testing" @@ -8,20 +9,20 @@ import ( . "github.com/onsi/gomega" ) -var _ = Describe("Build(i18n)", func() { +var _ = Describe("b.Build(i18n)", func() { It("exports json", func() { - Expect(Build("lib/i18n/benchmark/index.js")).To(ContainCode(` + Expect(b.Build("lib/i18n/benchmark/index.js")).To(ContainCode(` { first_name: "Joel", foo: { bar: { baz: 1 } }, last_name: "Moss" } `)) }) }) // Avg 875,000 ns/op -func BenchmarkI18n(b *testing.B) { - b.ResetTimer() +func BenchmarkI18n(bm *testing.B) { + bm.ResetTimer() - for i := 0; i < b.N; i++ { - result := Build("lib/i18n/benchmark/index.js") + for i := 0; i < bm.N; i++ { + result := b.Build("lib/i18n/benchmark/index.js") if len(result.Errors) > 0 { panic("Build failed: " + result.Errors[0].Text) diff --git a/test/import_map_test.go b/test/import_map_test.go index 6cf84313..ba5c0ea7 100644 --- a/test/import_map_test.go +++ b/test/import_map_test.go @@ -1,7 +1,10 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" + "joelmoss/proscenium/internal/importmap" . "joelmoss/proscenium/test/support" + "strings" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -10,31 +13,54 @@ import ( var _ = Describe("Build(import_map)", func() { When("import map is JS", func() { It("should parse", func() { - result := Build("lib/import_map/as_js.js", BuildOpts{ - ImportMapPath: "config/import_maps/as.js", - }) + importmap.NewJavaScriptImportMap([]byte(` + env => ({ + imports: { + pkg: env === 'test' ? '/lib/foo2.js' : '/lib/foo3.js' + } + }) + `)) - Expect(result).To(ContainCode(`console.log("/lib/foo2.js");`)) + Expect(b.Build("lib/import_map/as_js.js")).To(ContainCode(`console.log("/lib/foo2.js");`)) }) - It("produces error when invalid", func() { - result := Build("lib/foo.js", BuildOpts{ - ImportMapPath: "config/import_maps/invalid.js", - }) + It("errors when invalid contents", func() { + result := importmap.NewJavaScriptImportMap([]byte(`()(())`)) - Expect(result.Errors[0].Text).To(Equal("Failed to parse import map")) + Expect(strings.HasPrefix(result.Error(), "Cannot read import map:")).To(BeTrue()) + }) + + It("populates build errors when invalid", func() { + importmap.TEST_IMPORT_MAP_FILE = "config/import_maps/invalid.js" + importmap.TEST_IMPORT_MAP_TYPE = importmap.JavascriptType + + result := importmap.NewJavaScriptImportMap([]byte(`()(())`)) + + Expect(strings.HasPrefix(result.Error(), "Cannot read import map:")).To(BeTrue()) }) }) + It("errors with invalid json", func() { + result := importmap.NewJsonImportMap([]byte(`{`)) + + Expect(strings.HasPrefix(result.Error(), "Cannot read import map:")).To(BeTrue()) + }) + + It("populates build errors with invalid json", func() { + result := importmap.NewJsonImportMap([]byte(`{`)) + + Expect(strings.HasPrefix(result.Error(), "Cannot read import map:")).To(BeTrue()) + }) + // import foo from 'foo' When("specifier is bare", func() { When("value starts with /", func() { It("resolves", func() { - result := Build("lib/import_map/bare_specifier.js", BuildOpts{ - ImportMap: `{ - "imports": { "foo": "/lib/foo.js" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "/lib/foo.js" } + }`)) + + result := b.Build("lib/import_map/bare_specifier.js") Expect(result).To(ContainCode(`console.log("/lib/foo.js");`)) }) @@ -42,11 +68,11 @@ var _ = Describe("Build(import_map)", func() { When("value starts with ./ or ../", func() { It("resolves", func() { - result := Build("lib/import_map/bare_specifier.js", BuildOpts{ - ImportMap: `{ - "imports": { "foo": "../foo.js" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "../foo.js" } + }`)) + + result := b.Build("lib/import_map/bare_specifier.js") Expect(result).To(ContainCode(`console.log("/lib/foo.js");`)) }) @@ -56,11 +82,11 @@ var _ = Describe("Build(import_map)", func() { It("is not bundled", func() { MockURL("/foo.js", "console.log('foo');") - result := Build("lib/import_map/bare_specifier.js", BuildOpts{ - ImportMap: `{ - "imports": { "foo": "https://proscenium.test/foo.js" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "https://proscenium.test/foo.js" } + }`)) + + result := b.Build("lib/import_map/bare_specifier.js") Expect(result).To(ContainCode(` import foo from "https://proscenium.test/foo.js"; @@ -70,11 +96,11 @@ var _ = Describe("Build(import_map)", func() { When("value is bare specifier", func() { It("resolves the value", func() { - result := Build("lib/import_map/bare_specifier.js", BuildOpts{ - ImportMap: `{ - "imports": { "foo": "mypackage" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "mypackage" } + }`)) + + result := b.Build("lib/import_map/bare_specifier.js") Expect(result).To(ContainCode(` console.log("node_modules/mypackage"); @@ -84,11 +110,11 @@ var _ = Describe("Build(import_map)", func() { When("value is directory containing an index file", func() { It("resolves the value to index file", func() { - result := Build("lib/import_map/bare_specifier.js", BuildOpts{ - ImportMap: `{ - "imports": { "foo": "/lib/indexes" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "/lib/indexes" } + }`)) + + result := b.Build("lib/import_map/bare_specifier.js") Expect(result).To(ContainCode(` console.log("lib/indexes/index.js"); @@ -97,11 +123,11 @@ var _ = Describe("Build(import_map)", func() { }) It("resolves file without extension", func() { - result := Build("lib/import_map/bare_specifier.js", BuildOpts{ - ImportMap: `{ - "imports": { "foo": "/lib/foo2" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "/lib/foo2" } + }`)) + + result := b.Build("lib/import_map/bare_specifier.js") Expect(result).To(ContainCode(`console.log("/lib/foo2.js");`)) }) @@ -110,22 +136,22 @@ var _ = Describe("Build(import_map)", func() { // import foo from "foo/one.js" When("key and value have trailing slash", func() { It("resolves", func() { - result := Build("lib/import_map/path_prefix.js", BuildOpts{ - ImportMap: `{ - "imports": { "foo/": "./nested/foo/" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo/": "./nested/foo/" } + }`)) + + result := b.Build("lib/import_map/path_prefix.js") Expect(result).To(ContainCode(`console.log("/lib/import_map/nested/foo/one.js");`)) }) }) It("resolves to URL", func() { - result := Build("lib/import_map/to_url.js", BuildOpts{ - ImportMap: `{ - "imports": { "axios": "https://proscenium.test/axios.js" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "axios": "https://proscenium.test/axios.js" } + }`)) + + result := b.Build("lib/import_map/to_url.js") Expect(result).To(ContainCode(` import axios from "https://proscenium.test/axios.js"; @@ -133,17 +159,17 @@ var _ = Describe("Build(import_map)", func() { }) It("resolves to bare module", func() { - result := Build("lib/import_map/bare_modules.js", BuildOpts{ - ImportMap: `{ - "imports": { "my-package": "mypackage" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "my-package": "mypackage" } + }`)) + + result := b.Build("lib/import_map/bare_modules.js") Expect(result).To(ContainCode(`console.log("node_modules/mypackage");`)) }) // It("scopes", Pending, func() { - // result := Build("lib/import_map/scopes.js", `{ + // importmap.NewJsonImportMap([]byte(`{ // "imports": { // "foo": "/lib/foo.js" // }, @@ -152,9 +178,10 @@ var _ = Describe("Build(import_map)", func() { // "foo": "/lib/foo4.js" // } // } - // }`) + // }`)) + + // result := b.Build("lib/import_map/scopes.js") // Expect(result.OutputFiles[0].Contents).To(ContainCode(`import foo from "/lib/foo4.js";`)) // }) - }) diff --git a/test/libs_test.go b/test/libs_test.go index 583e7192..b957e68d 100644 --- a/test/libs_test.go +++ b/test/libs_test.go @@ -1,25 +1,74 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" + "joelmoss/proscenium/internal/types" . "joelmoss/proscenium/test/support" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("Build(Libs)", func() { - It("builds from lib/libs", func() { - Expect(Build("@proscenium/test.js")).To(ContainCode(` - console.log("/@proscenium/test.js"); - `)) +var _ = Describe("b.Build(Libs)", func() { + BeforeEach(func() { + types.Config.Engines = map[string]string{ + "proscenium": types.Config.GemPath, + } + }) + + When("Bundle = false", func() { + BeforeEach(func() { + types.Config.Bundle = false + }) + + It("builds from lib/libs", func() { + Expect(b.Build("@proscenium/test.js")).To(ContainCode(` + console.log("/@proscenium/test.js"); + `)) + + Expect(b.Build("@proscenium/ujs")).To(ContainCode(` + const classPath = "/@proscenium/ujs/class.js"; + `)) + }) + + It("builds without file extension", func() { + Expect(b.Build("@proscenium/ujs/class")).To(ContainCode(` + import DataConfirm from "/proscenium/lib/proscenium/libs/ujs/data_confirm.js"; + import DataDisableWith from "/proscenium/lib/proscenium/libs/ujs/data_disable_with.js"; + `)) + }) - Expect(Build("@proscenium/ujs")).To(ContainCode(` - const classPath = "/@proscenium/ujs/class.js"; - `)) + It("builds with file extension", func() { + Expect(b.Build("@proscenium/ujs/class.js")).To(ContainCode(` + import DataConfirm from "/proscenium/lib/proscenium/libs/ujs/data_confirm.js"; + import DataDisableWith from "/proscenium/lib/proscenium/libs/ujs/data_disable_with.js"; + `)) + }) + + It("builds to path", func() { + _, code := b.BuildToPath("@proscenium/test.js") + Expect(code).To(Equal("@proscenium/test.js::public/assets/@proscenium/test$SLCFI4GA$.js")) + }) }) - It("builds to path", func() { - _, code := BuildToPath("@proscenium/test.js") - Expect(code).To(Equal("@proscenium/test.js::public/assets/@proscenium/test$SLCFI4GA$.js")) + When("Bundle = true", func() { + BeforeEach(func() { + types.Config.Bundle = true + }) + + It("builds from lib/libs", func() { + Expect(b.Build("@proscenium/test.js")).To(ContainCode(` + console.log("/@proscenium/test.js"); + `)) + + Expect(b.Build("@proscenium/ujs")).To(ContainCode(` + const classPath = "/@proscenium/ujs/class.js"; + `)) + }) + + It("builds to path", func() { + _, code := b.BuildToPath("@proscenium/test.js") + Expect(code).To(Equal("@proscenium/test.js::public/assets/@proscenium/test$SLCFI4GA$.js")) + }) }) }) diff --git a/test/proscenium_suite_test.go b/test/proscenium_suite_test.go index 7c1d9e47..cf640bb3 100644 --- a/test/proscenium_suite_test.go +++ b/test/proscenium_suite_test.go @@ -29,9 +29,16 @@ var _ = BeforeSuite(func() { }) var _ = BeforeEach(func() { + importmap.Reset() types.Config.Reset() types.Config.Environment = types.TestEnv - importmap.Contents = &types.ImportMap{} + + _, filename, _, _ := runtime.Caller(0) + root := path.Dir(filename) + types.Config.RootPath = path.Join(root, "..", "fixtures", "dummy") + types.Config.GemPath = path.Join(root, "..") + + // Currently only used by the SVG plugin plugin.DiskvCache.EraseAll() }) diff --git a/test/resolver_test.go b/test/resolver_test.go index 17b48378..0f13992a 100644 --- a/test/resolver_test.go +++ b/test/resolver_test.go @@ -1,7 +1,8 @@ package proscenium_test import ( - . "joelmoss/proscenium/test/support" + "joelmoss/proscenium/internal/importmap" + r "joelmoss/proscenium/internal/resolver" "testing" . "github.com/onsi/ginkgo/v2" @@ -10,83 +11,71 @@ import ( var _ = Describe("Resolve", func() { It("resolves unknown path", func() { - path, err := Resolve("unknown") + path, err := r.Resolve("unknown", "") Expect(err).NotTo(Succeed()) Expect(path).To(Equal("")) }) It("resolves absolute path", func() { - Expect(Resolve("/lib/foo.js")).To(Equal("/lib/foo.js")) + Expect(r.Resolve("/lib/foo.js", "")).To(Equal("/lib/foo.js")) }) When("relative path without importer", func() { It("returns errors", func() { - _, err := Resolve("./lib/foo.js") + _, err := r.Resolve("./lib/foo.js", "") Expect(err).NotTo(Succeed()) }) }) When("importer is given", func() { It("resolves relative path", func() { - Expect(Resolve("./foo2.js", ResolveOpts{Importer: "/lib/foo.js"})).To(Equal("/lib/foo2.js")) + Expect(r.Resolve("./foo2.js", "/lib/foo.js")).To(Equal("/lib/foo2.js")) }) }) It("resolves bare specifier", func() { - Expect(Resolve("mypackage")).To(Equal("/packages/mypackage/index.js")) + Expect(r.Resolve("mypackage", "")).To(Equal("/packages/mypackage/index.js")) }) It("resolves directory to its index file", func() { - result, _ := Resolve("/lib/indexes") + result, _ := r.Resolve("/lib/indexes", "") Expect(result).To(Equal("/lib/indexes/index.js")) }) It("resolves file without extension", func() { - result, _ := Resolve("/lib/foo2") + result, _ := r.Resolve("/lib/foo2", "") Expect(result).To(Equal("/lib/foo2.js")) }) Describe("with import map", func() { It("resolves from import map", func() { - im := `{ + importmap.NewJsonImportMap([]byte(`{ "imports": { "foo": "/lib/foo.js", "bar": "https://some.com/bar.js" } - }` + }`)) - Expect(Resolve("foo", ResolveOpts{ImportMap: im})).To(Equal("/lib/foo.js")) - Expect(Resolve("bar", ResolveOpts{ImportMap: im})).To(Equal("https://some.com/bar.js")) - }) - - It("produces error on invalid json", func() { - _, err := Resolve("lib/foo.js", ResolveOpts{ImportMap: `{[}]}`}) - - Expect(err.Error()).To(Equal( - "Failed to parse import map: *json.SyntaxError: invalid character '[' looking for beginning of object key string", - )) + Expect(r.Resolve("foo", "")).To(Equal("/lib/foo.js")) + Expect(r.Resolve("bar", "")).To(Equal("https://some.com/bar.js")) }) It("resolves directory to its index file", func() { - result, _ := Resolve("foo", ResolveOpts{ - ImportMap: `{ - "imports": { "foo": "/lib/indexes" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "/lib/indexes" } + }`)) - Expect(result).To(Equal("/lib/indexes/index.js")) + Expect(r.Resolve("foo", "")).To(Equal("/lib/indexes/index.js")) }) It("resolves file without extension", func() { - result, _ := Resolve("foo", ResolveOpts{ - ImportMap: `{ - "imports": { "foo": "/lib/foo2" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "/lib/foo2" } + }`)) - Expect(result).To(Equal("/lib/foo2.js")) + Expect(r.Resolve("foo", "")).To(Equal("/lib/foo2.js")) }) }) }) @@ -95,7 +84,7 @@ func BenchmarkResolve(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - _, err := Resolve("/lib/foo2") + _, err := r.Resolve("/lib/foo2", "") if err != nil { panic("Build failed: " + err.Error()) } diff --git a/test/support/be_parsed_to_matcher.go b/test/support/be_parsed_to_matcher.go index 63623bd2..cee859ba 100644 --- a/test/support/be_parsed_to_matcher.go +++ b/test/support/be_parsed_to_matcher.go @@ -4,8 +4,6 @@ import ( "fmt" "joelmoss/proscenium/internal/css" "joelmoss/proscenium/internal/types" - "os" - "path" "runtime" "strings" @@ -24,16 +22,11 @@ type BeParsedToMatcher struct { Expected interface{} } -var cwd, _ = os.Getwd() -var root string = path.Join(cwd, "..", "fixtures", "dummy") - func (matcher *BeParsedToMatcher) Match(actual interface{}) (success bool, matchErr error) { - types.Config.RootPath = root - matcher.Input = strings.TrimSpace(heredoc.Doc(actual.(string))) matcher.Expected = strings.TrimSpace(heredoc.Doc(matcher.Expected.(string))) - matcher.Output, _ = css.ParseCss(matcher.Input, matcher.Path, root, "") + matcher.Output, _ = css.ParseCss(matcher.Input, matcher.Path, types.Config.RootPath, "") matcher.Output = strings.TrimSpace(matcher.Output) defer func() { diff --git a/test/support/build.go b/test/support/build.go deleted file mode 100644 index d8c7ec68..00000000 --- a/test/support/build.go +++ /dev/null @@ -1,81 +0,0 @@ -package support - -import ( - "joelmoss/proscenium/internal/builder" - "joelmoss/proscenium/internal/importmap" - "joelmoss/proscenium/internal/types" - "path" - "runtime" - - esbuild "github.com/evanw/esbuild/pkg/api" -) - -type BuildOpts struct { - ImportMap string - ImportMapPath string - EnvVars string - Engines map[string]string - Debug bool -} - -func BuildToString(pathToBuild string, rest ...BuildOpts) (bool, string) { - _, filename, _, _ := runtime.Caller(1) - types.Config.RootPath = path.Join(path.Dir(filename), "..", "fixtures", "dummy") - - restOpts := BuildOpts{} - if len(rest) > 0 { - restOpts = rest[0] - } - buildConfig(restOpts) - - return builder.BuildToString(pathToBuild) -} - -func BuildToPath(pathToBuild string, rest ...BuildOpts) (bool, string) { - _, filename, _, _ := runtime.Caller(1) - types.Config.RootPath = path.Join(path.Dir(filename), "..", "fixtures", "dummy") - - restOpts := BuildOpts{} - if len(rest) > 0 { - restOpts = rest[0] - } - buildConfig(restOpts) - - return builder.BuildToPath(pathToBuild) -} - -func Build(pathToBuild string, rest ...BuildOpts) esbuild.BuildResult { - _, filename, _, _ := runtime.Caller(1) - types.Config.RootPath = path.Join(path.Dir(filename), "..", "fixtures", "dummy") - - restOpts := BuildOpts{} - if len(rest) > 0 { - restOpts = rest[0] - } - buildConfig(restOpts) - - return builder.Build(pathToBuild, builder.OutputToString) -} - -func buildConfig(restOpts BuildOpts) { - // Ensure test environment. - types.Config.Environment = types.Environment(2) - - types.Config.Debug = restOpts.Debug - types.Config.Engines = restOpts.Engines - - _, filename, _, _ := runtime.Caller(1) - types.Config.GemPath = path.Join(path.Dir(filename), "..", "..") - - // if restOpts.EnvVars == "" { - // types.Config.EnvVars = make(map[string]string) - // types.Config.EnvVars["NODE_ENV"] = "test" - // } - - if restOpts.ImportMap != "" { - importmap.Contents.IsParsed = false - importmap.Parse([]byte(restOpts.ImportMap)) - } else if restOpts.ImportMapPath != "" { - types.Config.ImportMapPath = restOpts.ImportMapPath - } -} diff --git a/test/support/resolve.go b/test/support/resolve.go deleted file mode 100644 index 672239ca..00000000 --- a/test/support/resolve.go +++ /dev/null @@ -1,39 +0,0 @@ -package support - -import ( - "joelmoss/proscenium/internal/resolver" - "joelmoss/proscenium/internal/types" - "path" - "runtime" -) - -type ResolveOpts struct { - Importer string - ImportMap string - Debug bool -} - -func Resolve(pathToResolve string, rest ...ResolveOpts) (string, error) { - _, filename, _, _ := runtime.Caller(1) - - // Ensure test environment. - types.Config.Environment = types.Environment(2) - types.Config.RootPath = path.Join(path.Dir(filename), "..", "fixtures", "dummy") - - restOpts := ResolveOpts{} - if len(rest) > 0 { - restOpts = rest[0] - } - - types.Config.Debug = restOpts.Debug - - options := resolver.Options{} - if restOpts.ImportMap != "" { - options.ImportMap = []byte(restOpts.ImportMap) - } - if restOpts.Importer != "" { - options.Importer = restOpts.Importer - } - - return resolver.Resolve(pathToResolve, options) -} diff --git a/test/svg_test.go b/test/svg_test.go index d2ac40ac..7e2944b0 100644 --- a/test/svg_test.go +++ b/test/svg_test.go @@ -1,6 +1,7 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" . "joelmoss/proscenium/test/support" "regexp" @@ -8,50 +9,50 @@ import ( . "github.com/onsi/gomega" ) -var _ = Describe("Build(svg)", func() { +var _ = Describe("b.Build(svg)", func() { svgContent := ` ` When("importing absolute svg from jsx", func() { It("bundles", func() { - result := Build("lib/svg/absolute.jsx") + result := b.Build("lib/svg/absolute_jsx.jsx") - Expect(result).To(ContainCode(`svg = /* @__PURE__ */ jsx("svg"`)) + Expect(result).To(ContainCode(`svg = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg"`)) Expect(result).NotTo(ContainCode(`import AtIcon from "/public/at.svg";`)) }) }) When("importing svg from tsx", func() { It("bundles", func() { - result := Build("lib/svg/absolute.tsx") + result := b.Build("lib/svg/absolute_tsx.tsx") - Expect(result).To(ContainCode(`svg = /* @__PURE__ */ jsx("svg"`)) + Expect(result).To(ContainCode(`svg = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg"`)) Expect(result).NotTo(ContainCode(`import AtIcon from "/public/at.svg";`)) }) }) When("importing relative svg from jsx", func() { It("bundles", func() { - result := Build("lib/svg/relative.jsx") + result := b.Build("lib/svg/relative.jsx") - Expect(result).To(ContainCode(`svg = /* @__PURE__ */ jsx("svg"`)) + Expect(result).To(ContainCode(`svg = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg"`)) Expect(result).NotTo(ContainCode(`import AtIcon from "/lib/svg/at.svg";`)) }) }) When("importing bare svg specifier from jsx", func() { It("bundles", func() { - result := Build("lib/svg/bare.jsx") + result := b.Build("lib/svg/bare.jsx") Expect(result).NotTo(ContainCode(`import AtIcon from "/public/at.svg";`)) - Expect(result).To(ContainCode(`var svg = /* @__PURE__ */ jsx("svg"`)) + Expect(result).To(ContainCode(`svg = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg"`)) }) }) When("importing svg from css", func() { It("should not bundle", func() { - Expect(Build("lib/svg.css")).To(ContainCode(` + Expect(b.Build("lib/svg.css")).To(ContainCode(` url(/hue/icons/angle-right-regular.svg)`, )) }) @@ -61,7 +62,7 @@ var _ = Describe("Build(svg)", func() { It("should bundle", func() { MockURL("/at.svg", svgContent) - result := Build("lib/svg/remote.jsx") + result := b.Build("lib/svg/remote.jsx") Expect(result).To(ContainCode(` var svg = /* @__PURE__ */ jsx("svg", { "aria-hidden": "true", focusable: "false", role: "img", xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 512 512", children: /* @__PURE__ */ jsx("path", { fill: "currentColor", d: "M504" }) }); @@ -78,7 +79,7 @@ var _ = Describe("Build(svg)", func() { PIt("should not bundle or encode; leave as is", func() { MockURL("/at.svg", svgContent) - result := Build("lib/svg/remote.css") + result := b.Build("lib/svg/remote.css") Expect(result).To(ContainCode(`background-image: url(https://proscenium.test/at.svg);`)) }) diff --git a/test/url_test.go b/test/url_test.go index 15543de8..e968f0e1 100644 --- a/test/url_test.go +++ b/test/url_test.go @@ -1,33 +1,32 @@ package proscenium_test import ( + b "joelmoss/proscenium/internal/builder" + "joelmoss/proscenium/internal/importmap" . "joelmoss/proscenium/test/support" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("Build(url)", func() { +var _ = Describe("b.Build(url)", func() { When("importing a URL", func() { It("should leave as is", func() { - Expect(Build("lib/import_url.js")).To(ContainCode(` - import myFunction from "https://proscenium.test/import-url-module.js"; + Expect(b.Build("lib/import_url.js")).To(ContainCode(` + import myFunction from "https://proscenium.test/import-url-module.js"; `)) }) }) When("import map resolves to url", func() { It("should encode URL", func() { - result := Build("lib/import_map/bare_specifier.js", BuildOpts{ - ImportMap: `{ - "imports": { "foo": "https://proscenium.test/import-url-module.js" } - }`, - }) + importmap.NewJsonImportMap([]byte(`{ + "imports": { "foo": "https://proscenium.test/import-url-module.js" } + }`)) - Expect(result).To(ContainCode(` - import foo from "https://proscenium.test/import-url-module.js"; - `)) + Expect(b.Build("lib/import_map/bare_specifier.js")).To(ContainCode(` + import foo from "https://proscenium.test/import-url-module.js"; + `)) }) }) - }) From 2124c4caa79aac8228ec599d04deb55b7017971f Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Sat, 21 Dec 2024 12:13:44 +0000 Subject: [PATCH 02/15] chore(deps): Update go deps --- go.mod | 26 ++++++---------- go.sum | 94 ++++++++++++++-------------------------------------------- 2 files changed, 31 insertions(+), 89 deletions(-) diff --git a/go.mod b/go.mod index 1864111d..aaccf7f9 100644 --- a/go.mod +++ b/go.mod @@ -3,30 +3,24 @@ module joelmoss/proscenium go 1.23 require ( - github.com/evanw/esbuild v0.24.0 - github.com/k0kubun/pp v3.0.1+incompatible - github.com/onsi/ginkgo/v2 v2.20.2 + github.com/evanw/esbuild v0.24.2 + github.com/onsi/ginkgo/v2 v2.22.1 github.com/peterbourgon/diskv v2.0.1+incompatible github.com/sergi/go-diff v1.3.1 ) require ( - github.com/chzyer/readline v1.5.1 // indirect github.com/dlclark/regexp2 v1.11.4 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect github.com/google/btree v1.1.3 // indirect github.com/google/go-cmp v0.6.0 // indirect - github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db // indirect + github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect - github.com/ianlancetaylor/demangle v0.0.0-20240912202439-0a2b6291aafd // indirect - github.com/kr/text v0.2.0 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect - github.com/stretchr/testify v1.9.0 // indirect - golang.org/x/net v0.30.0 // indirect - golang.org/x/tools v0.26.0 // indirect + github.com/stretchr/testify v1.10.0 // indirect + golang.org/x/net v0.33.0 // indirect + golang.org/x/tools v0.28.0 // indirect ) require ( @@ -35,15 +29,13 @@ require ( github.com/dop251/goja v0.0.0-20241024094426-79f3a7efcdbd github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/h2non/gock v1.2.0 - github.com/k0kubun/pp/v3 v3.3.0 github.com/kr/pretty v0.3.1 // indirect github.com/mitchellh/mapstructure v1.5.0 - github.com/onsi/gomega v1.34.2 + github.com/onsi/gomega v1.36.1 github.com/peterbourgon/mergemap v0.0.1 github.com/riking/cssparse v0.0.0-20180325025645-c37ded0aac89 github.com/rogpeppe/go-internal v1.13.1 // indirect - github.com/spf13/afero v1.11.0 - golang.org/x/sys v0.26.0 // indirect - golang.org/x/text v0.19.0 // indirect + golang.org/x/sys v0.28.0 // indirect + golang.org/x/text v0.21.0 // indirect gopkg.in/yaml.v3 v3.0.1 ) diff --git a/go.sum b/go.sum index 4b69bdd8..159d39bd 100644 --- a/go.sum +++ b/go.sum @@ -2,60 +2,36 @@ 4d63.com/collapsewhitespace v0.0.0-20190109064012-23971e8e1f30/go.mod h1:lnsj6LXLeotLpzklyHG6AwLEyRHmTYqj9HrKxmOFgo8= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= -github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= -github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= -github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= -github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= +github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= +github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= -github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo= github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/dop251/goja v0.0.0-20240610225006-393f6d42497b h1:fMKDnOAKCGXSZBphY/ilLtu7cmwMnjqE+xJxUkfkpCY= -github.com/dop251/goja v0.0.0-20240610225006-393f6d42497b/go.mod h1:o31y53rb/qiIAONF7w3FHJZRqqP3fzHUr1HqanthByw= -github.com/dop251/goja v0.0.0-20241009100908-5f46f2705ca3 h1:MXsAuToxwsTn5BEEYm2DheqIiC4jWGmkEJ1uy+KFhvQ= -github.com/dop251/goja v0.0.0-20241009100908-5f46f2705ca3/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4= github.com/dop251/goja v0.0.0-20241024094426-79f3a7efcdbd h1:QMSNEh9uQkDjyPwu/J541GgSH+4hw+0skJDIj9HJ3mE= github.com/dop251/goja v0.0.0-20241024094426-79f3a7efcdbd/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4= -github.com/evanw/esbuild v0.21.5 h1:oShm8TT5QUhf6vM7teg0nmd14eHu64dPmVluC2f4DMg= -github.com/evanw/esbuild v0.21.5/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48= -github.com/evanw/esbuild v0.24.0 h1:GZ78naTLp7FKr+K7eNuM/SLs5maeiHYRPsTg6kmdsSE= -github.com/evanw/esbuild v0.24.0/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48= +github.com/evanw/esbuild v0.24.2 h1:PQExybVBrjHjN6/JJiShRGIXh1hWVm6NepVnhZhrt0A= +github.com/evanw/esbuild v0.24.2/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-sourcemap/sourcemap v2.1.4+incompatible h1:a+iTbH5auLKxaNwQFg0B+TCYl6lbukKPc7b5x0n1s6Q= github.com/go-sourcemap/sourcemap v2.1.4+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= -github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/pprof v0.0.0-20240528025155-186aa0362fba h1:ql1qNgCyOB7iAEk8JTNM+zJrgIbnyCKX/wdlyPufP5g= -github.com/google/pprof v0.0.0-20240528025155-186aa0362fba/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo= -github.com/google/pprof v0.0.0-20241009165004-a3522334989c h1:NDovD0SMpBYXlE1zJmS1q55vWB/fUQBcPAqAboZSccA= -github.com/google/pprof v0.0.0-20241009165004-a3522334989c/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= -github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= -github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= +github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad h1:a6HEuzUHeKH6hwfN/ZoQgRgVIWFJljSWa/zetS2WTvg= +github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJrOjhax5N+uePQ0Fh1Z7PheYoUI/0nzkPA= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/h2non/gock v1.2.0 h1:K6ol8rfrRkUOefooBC8elXoaNGYkpp7y2qcxGG6BzUE= github.com/h2non/gock v1.2.0/go.mod h1:tNhoxHYW2W42cYkYb1WqzdbYIieALC99kpYr7rH/BQk= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= -github.com/ianlancetaylor/demangle v0.0.0-20240312041847-bd984b5ce465 h1:KwWnWVWCNtNq/ewIX7HIKnELmEx2nDP42yskD/pi7QE= -github.com/ianlancetaylor/demangle v0.0.0-20240312041847-bd984b5ce465/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= -github.com/ianlancetaylor/demangle v0.0.0-20240912202439-0a2b6291aafd h1:EVX1s+XNss9jkRW9K6XGJn2jL2lB1h5H804oKPsxOec= -github.com/ianlancetaylor/demangle v0.0.0-20240912202439-0a2b6291aafd/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= -github.com/k0kubun/pp v3.0.1+incompatible h1:3tqvf7QgUnZ5tXO6pNAZlrvHgl6DvifjDrd9g2S9Z40= -github.com/k0kubun/pp v3.0.1+incompatible/go.mod h1:GWse8YhT0p8pT4ir3ZgBbfZild3tgzSScAn6HmfYukg= -github.com/k0kubun/pp/v3 v3.3.0 h1:/Unrck5tDGUSjsUJsmx9GUL64pNKOY5UEdoP1F7FBq8= -github.com/k0kubun/pp/v3 v3.3.0/go.mod h1:wJadGBvcY6JKaiUkB89VzUACKDmTX1r4aQTPERpZc6w= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -63,24 +39,14 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= -github.com/onsi/ginkgo/v2 v2.19.0 h1:9Cnnf7UHo57Hy3k6/m5k3dRfGTMXGvxhHFvkDTCTpvA= -github.com/onsi/ginkgo/v2 v2.19.0/go.mod h1:rlwLi9PilAFJ8jCg9UE1QP6VBpd6/xj3SRC0d6TU0To= -github.com/onsi/ginkgo/v2 v2.20.2 h1:7NVCeyIWROIAheY21RLS+3j2bb52W0W82tkberYytp4= -github.com/onsi/ginkgo/v2 v2.20.2/go.mod h1:K9gyxPIlb+aIvnZ8bd9Ak+YP18w3APlR+5coaZoE2ag= -github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= -github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0= -github.com/onsi/gomega v1.34.2 h1:pNCwDkzrsv7MS9kpaQvVb1aVLahQXyJ/Tv5oAZMI3i8= -github.com/onsi/gomega v1.34.2/go.mod h1:v1xfxRgk0KIsG+QOdm7p8UosrOzPYRo60fd3B/1Dukc= +github.com/onsi/ginkgo/v2 v2.22.1 h1:QW7tbJAUDyVDVOM5dFa7qaybo+CRfR7bemlQUN6Z8aM= +github.com/onsi/ginkgo/v2 v2.22.1/go.mod h1:S6aTpoRsSq2cZOd+pssHAlKW/Q/jZt6cPrPlnj4a1xM= +github.com/onsi/gomega v1.36.1 h1:bJDPBO7ibjxcbHMgSCoo4Yj18UWbKDlLwX1x9sybDcw= +github.com/onsi/gomega v1.36.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= github.com/peterbourgon/mergemap v0.0.1 h1:5/brtSACv34REV0xoYjPQ8JXZnx3nurGt6WInLRwqX4= @@ -91,41 +57,25 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/riking/cssparse v0.0.0-20180325025645-c37ded0aac89 h1:hMsoSMebpfpaDW7+B7gsxNnMBNChjekeqmK8wkzAlc0= github.com/riking/cssparse v0.0.0-20180325025645-c37ded0aac89/go.mod h1:yc5MYwuNUGggTQ8++IDAbOYq/9PXxsg73+EHYgoG/4w= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= -github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= -github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= -golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= -golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4= -golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= -golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= -golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= -golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= -golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= -golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= -golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= -golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= -golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= -golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= -golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= -google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= -google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= -google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/tools v0.28.0 h1:WuB6qZ4RPCQo5aP3WdKZS7i595EdWqWR8vqJTlwTVK8= +golang.org/x/tools v0.28.0/go.mod h1:dcIOrVd3mfQKTgrDVQHqCPMWy6lnhfhtX3hLXYVLfRw= +google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= +google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From 56d7e2ce362e04cd139711a4a0df87285348c542 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Sat, 21 Dec 2024 12:32:12 +0000 Subject: [PATCH 03/15] chore(deps): Update ruby deps --- Gemfile.lock | 181 +++++++++++++++++++++++---------------------- proscenium.gemspec | 4 +- 2 files changed, 94 insertions(+), 91 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index 3c0d7bce..69271f78 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -2,11 +2,11 @@ PATH remote: . specs: proscenium (0.18.0) - activesupport (>= 7.1.0, < 9.0) + activesupport (>= 7.1.0, < 8.0) ffi (~> 1.17.0) literal (~> 1.0) oj (~> 3.13) - railties (>= 7.1.0, < 9.0) + railties (>= 7.1.0, < 8.0) ruby-next (~> 1.0.1) PATH @@ -36,29 +36,29 @@ PATH GEM remote: https://rubygems.org/ specs: - actioncable (7.2.2) - actionpack (= 7.2.2) - activesupport (= 7.2.2) + actioncable (7.2.2.1) + actionpack (= 7.2.2.1) + activesupport (= 7.2.2.1) nio4r (~> 2.0) websocket-driver (>= 0.6.1) zeitwerk (~> 2.6) - actionmailbox (7.2.2) - actionpack (= 7.2.2) - activejob (= 7.2.2) - activerecord (= 7.2.2) - activestorage (= 7.2.2) - activesupport (= 7.2.2) + actionmailbox (7.2.2.1) + actionpack (= 7.2.2.1) + activejob (= 7.2.2.1) + activerecord (= 7.2.2.1) + activestorage (= 7.2.2.1) + activesupport (= 7.2.2.1) mail (>= 2.8.0) - actionmailer (7.2.2) - actionpack (= 7.2.2) - actionview (= 7.2.2) - activejob (= 7.2.2) - activesupport (= 7.2.2) + actionmailer (7.2.2.1) + actionpack (= 7.2.2.1) + actionview (= 7.2.2.1) + activejob (= 7.2.2.1) + activesupport (= 7.2.2.1) mail (>= 2.8.0) rails-dom-testing (~> 2.2) - actionpack (7.2.2) - actionview (= 7.2.2) - activesupport (= 7.2.2) + actionpack (7.2.2.1) + actionview (= 7.2.2.1) + activesupport (= 7.2.2.1) nokogiri (>= 1.8.5) racc rack (>= 2.2.4, < 3.2) @@ -67,35 +67,35 @@ GEM rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) useragent (~> 0.16) - actiontext (7.2.2) - actionpack (= 7.2.2) - activerecord (= 7.2.2) - activestorage (= 7.2.2) - activesupport (= 7.2.2) + actiontext (7.2.2.1) + actionpack (= 7.2.2.1) + activerecord (= 7.2.2.1) + activestorage (= 7.2.2.1) + activesupport (= 7.2.2.1) globalid (>= 0.6.0) nokogiri (>= 1.8.5) - actionview (7.2.2) - activesupport (= 7.2.2) + actionview (7.2.2.1) + activesupport (= 7.2.2.1) builder (~> 3.1) erubi (~> 1.11) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) - activejob (7.2.2) - activesupport (= 7.2.2) + activejob (7.2.2.1) + activesupport (= 7.2.2.1) globalid (>= 0.3.6) - activemodel (7.2.2) - activesupport (= 7.2.2) - activerecord (7.2.2) - activemodel (= 7.2.2) - activesupport (= 7.2.2) + activemodel (7.2.2.1) + activesupport (= 7.2.2.1) + activerecord (7.2.2.1) + activemodel (= 7.2.2.1) + activesupport (= 7.2.2.1) timeout (>= 0.4.0) - activestorage (7.2.2) - actionpack (= 7.2.2) - activejob (= 7.2.2) - activerecord (= 7.2.2) - activesupport (= 7.2.2) + activestorage (7.2.2.1) + actionpack (= 7.2.2.1) + activejob (= 7.2.2.1) + activerecord (= 7.2.2.1) + activesupport (= 7.2.2.1) marcel (~> 1.0) - activesupport (7.2.2) + activesupport (7.2.2.1) base64 benchmark (>= 0.3) bigdecimal @@ -135,14 +135,14 @@ GEM cuprite (0.15.1) capybara (~> 3.0) ferrum (~> 0.15.0) - date (3.4.0) - debug (1.9.2) + date (3.4.1) + debug (1.10.0) irb (~> 1.10) reline (>= 0.3.8) diff-lcs (1.5.1) drb (2.2.1) - erubi (1.13.0) - fakefs (2.5.0) + erubi (1.13.1) + fakefs (2.8.0) ferrum (0.15) addressable (~> 2.5) concurrent-ruby (~> 1.1) @@ -155,14 +155,14 @@ GEM htmlbeautifier (1.4.3) i18n (1.14.6) concurrent-ruby (~> 1.0) - io-console (0.7.2) - irb (1.14.1) + io-console (0.8.0) + irb (1.14.3) rdoc (>= 4.0.0) reline (>= 0.4.2) - json (2.8.2) + json (2.9.1) language_server-protocol (3.17.0.3) - literal (1.1.0) - logger (1.6.1) + literal (1.4.0) + logger (1.6.4) loofah (2.23.1) crass (~> 1.0.2) nokogiri (>= 1.12.0) @@ -177,13 +177,13 @@ GEM minitest (>= 5.14.0, < 5.26.0) method_source (1.1.0) mini_mime (1.1.5) - minitest (5.25.1) + minitest (5.25.4) minitest-focus (1.4.0) minitest (>= 4, < 6) minitest-spec-rails (7.4.1) minitest (>= 5.0) railties (>= 4.1) - net-imap (0.5.1) + net-imap (0.5.3) date net-protocol net-pop (0.1.2) @@ -193,11 +193,11 @@ GEM net-smtp (0.5.0) net-protocol nio4r (2.7.4) - nokogiri (1.16.7-arm64-darwin) + nokogiri (1.17.2-arm64-darwin) racc (~> 1.4) - nokogiri (1.16.7-x86_64-linux) + nokogiri (1.17.2-x86_64-linux) racc (~> 1.4) - oj (3.16.7) + oj (3.16.8) bigdecimal (>= 3.0) ostruct (>= 0.2) ostruct (0.6.1) @@ -216,10 +216,11 @@ GEM phlexible (2.0.0) phlex (>= 1.10.0, < 2.0.0) phlex-rails (>= 1.2.1, < 2.0.0) - psych (5.2.0) + psych (5.2.2) + date stringio public_suffix (6.0.1) - puma (6.4.3) + puma (6.5.0) nio4r (~> 2.0) racc (1.8.1) rack (3.1.8) @@ -229,30 +230,30 @@ GEM rack (>= 1.3) rackup (2.2.1) rack (>= 3) - rails (7.2.2) - actioncable (= 7.2.2) - actionmailbox (= 7.2.2) - actionmailer (= 7.2.2) - actionpack (= 7.2.2) - actiontext (= 7.2.2) - actionview (= 7.2.2) - activejob (= 7.2.2) - activemodel (= 7.2.2) - activerecord (= 7.2.2) - activestorage (= 7.2.2) - activesupport (= 7.2.2) + rails (7.2.2.1) + actioncable (= 7.2.2.1) + actionmailbox (= 7.2.2.1) + actionmailer (= 7.2.2.1) + actionpack (= 7.2.2.1) + actiontext (= 7.2.2.1) + actionview (= 7.2.2.1) + activejob (= 7.2.2.1) + activemodel (= 7.2.2.1) + activerecord (= 7.2.2.1) + activestorage (= 7.2.2.1) + activesupport (= 7.2.2.1) bundler (>= 1.15.0) - railties (= 7.2.2) + railties (= 7.2.2.1) rails-dom-testing (2.2.0) activesupport (>= 5.0.0) minitest nokogiri (>= 1.6) - rails-html-sanitizer (1.6.0) + rails-html-sanitizer (1.6.2) loofah (~> 2.21) - nokogiri (~> 1.14) - railties (7.2.2) - actionpack (= 7.2.2) - activesupport (= 7.2.2) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (7.2.2.1) + actionpack (= 7.2.2.1) + activesupport (= 7.2.2.1) irb (~> 1.13) rackup (>= 1.0.0) rake (>= 12.2) @@ -260,24 +261,24 @@ GEM zeitwerk (~> 2.6) rainbow (3.1.1) rake (13.2.1) - rdoc (6.8.1) + rdoc (6.10.0) psych (>= 4.0.0) - regexp_parser (2.9.2) - reline (0.5.11) + regexp_parser (2.9.3) + reline (0.6.0) io-console (~> 0.5) require-hooks (0.2.2) rouge (4.5.1) - rubocop (1.68.0) + rubocop (1.69.2) json (~> 2.3) language_server-protocol (>= 3.17.0) parallel (~> 1.10) parser (>= 3.3.0.2) rainbow (>= 2.2.2, < 4.0) - regexp_parser (>= 2.4, < 3.0) - rubocop-ast (>= 1.32.2, < 2.0) + regexp_parser (>= 2.9.3, < 3.0) + rubocop-ast (>= 1.36.2, < 2.0) ruby-progressbar (~> 1.7) - unicode-display_width (>= 2.4.0, < 3.0) - rubocop-ast (1.36.1) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.37.0) parser (>= 3.3.1.0) rubocop-minitest (0.36.0) rubocop (>= 1.61, < 2.0) @@ -299,20 +300,22 @@ GEM ruby-next-parser (3.2.2.0) parser (>= 3.0.3.1) ruby-progressbar (1.13.0) - securerandom (0.3.2) - sqlite3 (2.2.0-arm64-darwin) - sqlite3 (2.2.0-x86_64-linux-gnu) + securerandom (0.4.1) + sqlite3 (2.4.1-arm64-darwin) + sqlite3 (2.4.1-x86_64-linux-gnu) stringio (3.1.2) thor (1.3.2) - timeout (0.4.2) + timeout (0.4.3) tzinfo (2.0.6) concurrent-ruby (~> 1.0) - unicode-display_width (2.6.0) + unicode-display_width (3.1.2) + unicode-emoji (~> 4.0, >= 4.0.4) + unicode-emoji (4.0.4) unparser (0.6.15) diff-lcs (~> 1.3) parser (>= 3.3.0) - useragent (0.16.10) - view_component (3.20.0) + useragent (0.16.11) + view_component (3.21.0) activesupport (>= 5.2.0, < 8.1) concurrent-ruby (~> 1.0) method_source (~> 1.0) @@ -321,7 +324,7 @@ GEM activemodel (>= 6.0.0) bindex (>= 0.4.0) railties (>= 6.0.0) - webrick (1.9.0) + webrick (1.9.1) websocket-driver (0.7.6) websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) diff --git a/proscenium.gemspec b/proscenium.gemspec index 995aa674..0efd2254 100644 --- a/proscenium.gemspec +++ b/proscenium.gemspec @@ -27,10 +27,10 @@ Gem::Specification.new do |spec| 'LICENSE.txt'] spec.require_paths = ['lib'] - spec.add_dependency 'activesupport', ['>= 7.1.0', '< 9.0'] + spec.add_dependency 'activesupport', ['>= 7.1.0', '< 8.0'] spec.add_dependency 'ffi', '~> 1.17.0' spec.add_dependency 'literal', '~> 1.0' spec.add_dependency 'oj', '~> 3.13' - spec.add_dependency 'railties', ['>= 7.1.0', '< 9.0'] + spec.add_dependency 'railties', ['>= 7.1.0', '< 8.0'] spec.add_dependency 'ruby-next', '~> 1.0.1' end From bffee5ca537b9f0921437006cc32c8a42f69ad35 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Sun, 29 Dec 2024 11:35:50 +0000 Subject: [PATCH 04/15] chore: Unify libs and UI libs and support bundless --- fixtures/dummy/lib/ui/test.js | 3 + internal/builder/build.go | 2 +- internal/builder/build_to_path.go | 8 +- internal/plugin/bundler.go | 2 +- internal/plugin/css.go | 2 +- internal/plugin/libs.go | 51 ------------ internal/plugin/ui.go | 74 +++++++++++++++++ lib/proscenium/builder.rb | 14 ---- lib/proscenium/helper.rb | 2 +- lib/proscenium/libs/test.js | 1 - lib/proscenium/railtie.rb | 1 - lib/proscenium/resolver.rb | 4 +- lib/proscenium/{libs => ui}/custom_element.js | 0 .../{libs => ui}/react-manager/index.jsx | 0 .../{libs => ui}/react-manager/react.js | 0 .../{libs => ui}/stimulus-loading.js | 0 lib/proscenium/ui/test.js | 2 +- lib/proscenium/{libs => ui}/ujs/class.js | 0 .../{libs => ui}/ujs/data_confirm.js | 0 .../{libs => ui}/ujs/data_disable_with.js | 0 lib/proscenium/{libs => ui}/ujs/index.js | 2 +- test/build_test.go | 12 --- test/libs_test.go | 74 ----------------- test/middleware_test.rb | 6 +- test/side_load_test.rb | 3 +- test/ui_test.go | 81 +++++++++++++++++++ 26 files changed, 174 insertions(+), 170 deletions(-) create mode 100644 fixtures/dummy/lib/ui/test.js delete mode 100644 internal/plugin/libs.go create mode 100644 internal/plugin/ui.go delete mode 100644 lib/proscenium/libs/test.js rename lib/proscenium/{libs => ui}/custom_element.js (100%) rename lib/proscenium/{libs => ui}/react-manager/index.jsx (100%) rename lib/proscenium/{libs => ui}/react-manager/react.js (100%) rename lib/proscenium/{libs => ui}/stimulus-loading.js (100%) rename lib/proscenium/{libs => ui}/ujs/class.js (100%) rename lib/proscenium/{libs => ui}/ujs/data_confirm.js (100%) rename lib/proscenium/{libs => ui}/ujs/data_disable_with.js (100%) rename lib/proscenium/{libs => ui}/ujs/index.js (79%) delete mode 100644 test/libs_test.go create mode 100644 test/ui_test.go diff --git a/fixtures/dummy/lib/ui/test.js b/fixtures/dummy/lib/ui/test.js new file mode 100644 index 00000000..1a366179 --- /dev/null +++ b/fixtures/dummy/lib/ui/test.js @@ -0,0 +1,3 @@ +import "@proscenium/ui/test"; + +console.log("lib/ui/test.js"); diff --git a/internal/builder/build.go b/internal/builder/build.go index 09b67948..43e2a323 100644 --- a/internal/builder/build.go +++ b/internal/builder/build.go @@ -113,7 +113,7 @@ func Build(path string, args ...Output) esbuild.BuildResult { buildOptions.Plugins = []esbuild.Plugin{ plugin.I18n, plugin.Rjs(), - plugin.Libs, + plugin.Ui, } if types.Config.Bundle { diff --git a/internal/builder/build_to_path.go b/internal/builder/build_to_path.go index 524e2d7d..871b8cbe 100644 --- a/internal/builder/build_to_path.go +++ b/internal/builder/build_to_path.go @@ -7,7 +7,7 @@ import ( "strings" ) -var libsSplitPath = "/proscenium/libs/" +var libsSplitPath = "/proscenium/ui/" // Return a mapping of path inputs to outputs. // @@ -16,9 +16,8 @@ var libsSplitPath = "/proscenium/libs/" // lib/code_splitting/son.js::public/assets/lib/code_splitting/son$LAGMAD6O$.js; // lib/code_splitting/daughter.js::public/assets/lib/code_splitting/daughter$7JJ2HGHC$.js func BuildToPath(filePath string) (bool, string) { - entrypoints := strings.Split(filePath, ";") - result := Build(filePath, OutputToPath) + entrypoints := strings.Split(filePath, ";") if len(result.Errors) != 0 { j, err := json.Marshal(result.Errors[0]) @@ -56,7 +55,7 @@ func BuildToPath(filePath string) (bool, string) { key := input.(string) if strings.Contains(key, libsSplitPath) { sliced := strings.Split(key, libsSplitPath) - key = "@proscenium/" + sliced[len(sliced)-1] + key = "@proscenium/ui/" + sliced[len(sliced)-1] } if mapping[key] == "" { @@ -75,7 +74,6 @@ func BuildToPath(filePath string) (bool, string) { } return true, strings.Join(contents, ";") - } func entryPointToRelativePath(entryPoint string) string { diff --git a/internal/plugin/bundler.go b/internal/plugin/bundler.go index b8021004..b4e08dab 100644 --- a/internal/plugin/bundler.go +++ b/internal/plugin/bundler.go @@ -209,7 +209,7 @@ var Bundler = esbuild.Plugin{ if path.IsAbs(result.Path) && filepath.Ext(result.Path) != "" { // If the path is absolute, then we can just return it as is. However, it must be a - // fully qualified path with a file extension. We can then return it as is. Othwerwise, + // fully qualified path with a file extension. We can then return it as is. Otherwise, // we need to resolve it. if unbundled { result.Path = strings.TrimPrefix(result.Path, root) diff --git a/internal/plugin/css.go b/internal/plugin/css.go index 54ba6718..8d664ad5 100644 --- a/internal/plugin/css.go +++ b/internal/plugin/css.go @@ -47,7 +47,7 @@ var Css = esbuild.Plugin{ return esbuild.OnLoadResult{ Errors: cssResult.Errors, Warnings: cssResult.Warnings, - }, fmt.Errorf(cssResult.Errors[0].Text) + }, fmt.Errorf("%s", cssResult.Errors[0].Text) } contents := strings.TrimSpace(string(cssResult.OutputFiles[0].Contents)) diff --git a/internal/plugin/libs.go b/internal/plugin/libs.go deleted file mode 100644 index 28fa0983..00000000 --- a/internal/plugin/libs.go +++ /dev/null @@ -1,51 +0,0 @@ -package plugin - -import ( - "joelmoss/proscenium/internal/types" - "path" - "path/filepath" - "strings" - - esbuild "github.com/evanw/esbuild/pkg/api" -) - -var Libs = esbuild.Plugin{ - Name: "libs", - Setup: func(build esbuild.PluginBuild) { - libDir := path.Join(types.Config.GemPath, "lib", "proscenium", "libs") - - build.OnResolve(esbuild.OnResolveOptions{Filter: `^@proscenium/`}, - func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { - pathToResolve := path.Join(libDir, strings.TrimPrefix(args.Path, "@proscenium/")) - - if filepath.Ext(pathToResolve) != "" { - // We have a full file path with extension, so no need to resolve with esbuild. Instead - // just pass through as-is. - return esbuild.OnResolveResult{ - Path: pathToResolve, - }, nil - } - - r := build.Resolve(pathToResolve, esbuild.ResolveOptions{ - ResolveDir: args.ResolveDir, - Importer: args.Importer, - Kind: args.Kind, - PluginData: types.PluginData{ - IsResolvingPath: true, - }, - }) - - sideEffects := esbuild.SideEffectsFalse - if r.SideEffects { - sideEffects = esbuild.SideEffectsTrue - } - - return esbuild.OnResolveResult{ - Path: r.Path, - External: r.External, - Errors: r.Errors, - Warnings: r.Warnings, - SideEffects: sideEffects, - }, nil - }) - }} diff --git a/internal/plugin/ui.go b/internal/plugin/ui.go new file mode 100644 index 00000000..871fe20a --- /dev/null +++ b/internal/plugin/ui.go @@ -0,0 +1,74 @@ +package plugin + +import ( + "joelmoss/proscenium/internal/types" + "path" + "path/filepath" + "strings" + + esbuild "github.com/evanw/esbuild/pkg/api" +) + +// var aliases = map[string]string{ +// "@proscenium/ujs": "@proscenium/ui/ujs", +// "@proscenium/react-manager": "@proscenium/ui/react-manager", +// "@proscenium/stimulus-loading": path.Join(uiDir, "stimulus-loading.js"), +// } + +var Ui = esbuild.Plugin{ + Name: "ui", + Setup: func(build esbuild.PluginBuild) { + var uiDir = path.Join(types.Config.GemPath, "lib", "proscenium", "ui") + + resolvePath := func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { + args.Path = path.Join(uiDir, args.Path) + + if filepath.Ext(args.Path) != "" { + // We have a full file path with extension, so no need to resolve with esbuild. Instead + // just pass through as-is. + return esbuild.OnResolveResult{ + Path: args.Path, + }, nil + } + + r := build.Resolve(args.Path, esbuild.ResolveOptions{ + ResolveDir: args.ResolveDir, + Importer: args.Importer, + Kind: args.Kind, + PluginData: types.PluginData{ + IsResolvingPath: true, + }, + }) + + sideEffects := esbuild.SideEffectsFalse + if r.SideEffects { + sideEffects = esbuild.SideEffectsTrue + } + + if !types.Config.Bundle && args.Kind != esbuild.ResolveEntryPoint { + r.External = true + r.Path = strings.TrimPrefix(r.Path, uiDir) + r.Path = path.Join("/proscenium", "ui", r.Path) + } + + return esbuild.OnResolveResult{ + Path: r.Path, + External: r.External, + Errors: r.Errors, + Warnings: r.Warnings, + SideEffects: sideEffects, + }, nil + } + + build.OnResolve(esbuild.OnResolveOptions{Filter: `^@proscenium/ujs`}, + func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { + args.Path = strings.TrimPrefix(args.Path, "@proscenium/") + return resolvePath(args) + }) + + build.OnResolve(esbuild.OnResolveOptions{Filter: `^@proscenium/`}, + func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { + args.Path = strings.TrimPrefix(args.Path, "@proscenium/ui") + return resolvePath(args) + }) + }} diff --git a/lib/proscenium/builder.rb b/lib/proscenium/builder.rb index 3ef9642c..36f8b688 100644 --- a/lib/proscenium/builder.rb +++ b/lib/proscenium/builder.rb @@ -145,20 +145,6 @@ def engines end end - # def import_map_path - # return unless (path = Rails.root&.join('config')) - - # if (json = path.join('import_map.json')).exist? - # return json.relative_path_from(@root).to_s - # end - - # if (js = path.join('import_map.js')).exist? - # return js.relative_path_from(@root).to_s - # end - - # nil - # end - def gem_root Pathname.new(__dir__).join('..', '..').to_s end diff --git a/lib/proscenium/helper.rb b/lib/proscenium/helper.rb index 6ebd9c5b..de63d818 100644 --- a/lib/proscenium/helper.rb +++ b/lib/proscenium/helper.rb @@ -16,7 +16,7 @@ def sideload_assets(value) # those asset paths all begin with a slash, which the Rails asset helpers do not pass through to # here. # - # If the given `path` is a bare path (does not start with `/` or `./` or `../`), then we use + # If the given `path` is a bare path (does not start with `./` or `../`), then we use # Rails default conventions, and serve CSS from /app/assets/stylesheets and JS from # /app/javascript. def compute_asset_path(path, options = {}) diff --git a/lib/proscenium/libs/test.js b/lib/proscenium/libs/test.js deleted file mode 100644 index 5e06d5cb..00000000 --- a/lib/proscenium/libs/test.js +++ /dev/null @@ -1 +0,0 @@ -console.log("/@proscenium/test.js"); diff --git a/lib/proscenium/railtie.rb b/lib/proscenium/railtie.rb index e5e27949..989e11f8 100644 --- a/lib/proscenium/railtie.rb +++ b/lib/proscenium/railtie.rb @@ -39,7 +39,6 @@ class Railtie < ::Rails::Engine # config.proscenium.engines << self # end config.proscenium.engines = Set.new - config.proscenium.engines << self config.action_dispatch.rescue_templates = { 'Proscenium::Builder::BuildError' => 'build_error' diff --git a/lib/proscenium/resolver.rb b/lib/proscenium/resolver.rb index 649f21e4..93bd0f69 100644 --- a/lib/proscenium/resolver.rb +++ b/lib/proscenium/resolver.rb @@ -25,10 +25,10 @@ def self.resolve(path) "/#{path}" elsif path.start_with?(Proscenium.ui_path.to_s) path.delete_prefix Proscenium.root.join('lib').to_s - elsif (engine = Proscenium.config.engines.find { |e| path.start_with? "#{e.root}/" }) - path.sub(/^#{engine.root}/, "/#{engine.engine_name}") elsif path.start_with?("#{Rails.root}/") path.delete_prefix Rails.root.to_s + elsif (engine = Proscenium.config.engines.find { |e| path.start_with? "#{e.root}/" }) + path.sub(/^#{engine.root}/, "/#{engine.engine_name}") else Builder.resolve path end diff --git a/lib/proscenium/libs/custom_element.js b/lib/proscenium/ui/custom_element.js similarity index 100% rename from lib/proscenium/libs/custom_element.js rename to lib/proscenium/ui/custom_element.js diff --git a/lib/proscenium/libs/react-manager/index.jsx b/lib/proscenium/ui/react-manager/index.jsx similarity index 100% rename from lib/proscenium/libs/react-manager/index.jsx rename to lib/proscenium/ui/react-manager/index.jsx diff --git a/lib/proscenium/libs/react-manager/react.js b/lib/proscenium/ui/react-manager/react.js similarity index 100% rename from lib/proscenium/libs/react-manager/react.js rename to lib/proscenium/ui/react-manager/react.js diff --git a/lib/proscenium/libs/stimulus-loading.js b/lib/proscenium/ui/stimulus-loading.js similarity index 100% rename from lib/proscenium/libs/stimulus-loading.js rename to lib/proscenium/ui/stimulus-loading.js diff --git a/lib/proscenium/ui/test.js b/lib/proscenium/ui/test.js index fffdaadf..893f00a5 100644 --- a/lib/proscenium/ui/test.js +++ b/lib/proscenium/ui/test.js @@ -1 +1 @@ -console.log("/proscenium/ui/test.js"); +console.log("@proscenium/ui/test.js"); diff --git a/lib/proscenium/libs/ujs/class.js b/lib/proscenium/ui/ujs/class.js similarity index 100% rename from lib/proscenium/libs/ujs/class.js rename to lib/proscenium/ui/ujs/class.js diff --git a/lib/proscenium/libs/ujs/data_confirm.js b/lib/proscenium/ui/ujs/data_confirm.js similarity index 100% rename from lib/proscenium/libs/ujs/data_confirm.js rename to lib/proscenium/ui/ujs/data_confirm.js diff --git a/lib/proscenium/libs/ujs/data_disable_with.js b/lib/proscenium/ui/ujs/data_disable_with.js similarity index 100% rename from lib/proscenium/libs/ujs/data_disable_with.js rename to lib/proscenium/ui/ujs/data_disable_with.js diff --git a/lib/proscenium/libs/ujs/index.js b/lib/proscenium/ui/ujs/index.js similarity index 79% rename from lib/proscenium/libs/ujs/index.js rename to lib/proscenium/ui/ujs/index.js index cd092e4d..be33c6cc 100644 --- a/lib/proscenium/libs/ujs/index.js +++ b/lib/proscenium/ui/ujs/index.js @@ -2,7 +2,7 @@ export default async () => { window.Proscenium = window.Proscenium || {}; if (!window.Proscenium.UJS) { - const classPath = "/@proscenium/ujs/class.js"; + const classPath = "/proscenium/ui/ujs/class.js"; const module = await import(classPath); window.Proscenium.UJS = new module.default(); } diff --git a/test/build_test.go b/test/build_test.go index 9fb5fae7..f9cc1abf 100644 --- a/test/build_test.go +++ b/test/build_test.go @@ -27,12 +27,6 @@ var _ = Describe("Build", func() { Expect(b.Build("lib/foo.js")).To(ContainCode(`console.log("/lib/foo.js")`)) }) - It("should bundle rjs", Pending, func() { - MockURL("/constants.rjs", "export default 'constants';") - - Expect(b.Build("lib/rjs.js")).To(ContainCode(`"constants"`)) - }) - It("should bundle bare module", func() { Expect(b.Build("lib/import_npm_module.js")).To(ContainCode(` function one() { console.log("one"); } @@ -57,12 +51,6 @@ var _ = Describe("Build", func() { `)) }) - PIt("should build dynamic path", func() { - Expect(b.Build("lib/import_dynamic.js")).To(ContainCode(` - console.log("/lib/foo4.js") - `)) - }) - Describe("unbundle:* imports", func() { It("should unbundle imports", func() { importmap.NewJsonImportMap([]byte(`{ diff --git a/test/libs_test.go b/test/libs_test.go deleted file mode 100644 index b957e68d..00000000 --- a/test/libs_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package proscenium_test - -import ( - b "joelmoss/proscenium/internal/builder" - "joelmoss/proscenium/internal/types" - . "joelmoss/proscenium/test/support" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -var _ = Describe("b.Build(Libs)", func() { - BeforeEach(func() { - types.Config.Engines = map[string]string{ - "proscenium": types.Config.GemPath, - } - }) - - When("Bundle = false", func() { - BeforeEach(func() { - types.Config.Bundle = false - }) - - It("builds from lib/libs", func() { - Expect(b.Build("@proscenium/test.js")).To(ContainCode(` - console.log("/@proscenium/test.js"); - `)) - - Expect(b.Build("@proscenium/ujs")).To(ContainCode(` - const classPath = "/@proscenium/ujs/class.js"; - `)) - }) - - It("builds without file extension", func() { - Expect(b.Build("@proscenium/ujs/class")).To(ContainCode(` - import DataConfirm from "/proscenium/lib/proscenium/libs/ujs/data_confirm.js"; - import DataDisableWith from "/proscenium/lib/proscenium/libs/ujs/data_disable_with.js"; - `)) - }) - - It("builds with file extension", func() { - Expect(b.Build("@proscenium/ujs/class.js")).To(ContainCode(` - import DataConfirm from "/proscenium/lib/proscenium/libs/ujs/data_confirm.js"; - import DataDisableWith from "/proscenium/lib/proscenium/libs/ujs/data_disable_with.js"; - `)) - }) - - It("builds to path", func() { - _, code := b.BuildToPath("@proscenium/test.js") - Expect(code).To(Equal("@proscenium/test.js::public/assets/@proscenium/test$SLCFI4GA$.js")) - }) - }) - - When("Bundle = true", func() { - BeforeEach(func() { - types.Config.Bundle = true - }) - - It("builds from lib/libs", func() { - Expect(b.Build("@proscenium/test.js")).To(ContainCode(` - console.log("/@proscenium/test.js"); - `)) - - Expect(b.Build("@proscenium/ujs")).To(ContainCode(` - const classPath = "/@proscenium/ujs/class.js"; - `)) - }) - - It("builds to path", func() { - _, code := b.BuildToPath("@proscenium/test.js") - Expect(code).To(Equal("@proscenium/test.js::public/assets/@proscenium/test$SLCFI4GA$.js")) - }) - }) -}) diff --git a/test/middleware_test.rb b/test/middleware_test.rb index 41394a5d..4c6f38bd 100644 --- a/test/middleware_test.rb +++ b/test/middleware_test.rb @@ -127,15 +127,15 @@ class Proscenium::MiddlewareTest < ActiveSupport::TestCase end it 'serves @proscenium/* runtime libs' do - get '/@proscenium/test.js' + get '/proscenium/ui/test.js' - assert_includes response.body, 'console.log("/@proscenium/test.js")' + assert_includes response.body, 'console.log("@proscenium/ui/test.js")' end it 'serves proscenium/ui/* ui' do get '/proscenium/ui/test.js' - assert_includes response.body, 'console.log("/proscenium/ui/test.js")' + assert_includes response.body, 'console.log("@proscenium/ui/test.js")' end context 'cache_query_string' do diff --git a/test/side_load_test.rb b/test/side_load_test.rb index be585314..6937bb5f 100644 --- a/test/side_load_test.rb +++ b/test/side_load_test.rb @@ -67,7 +67,8 @@ class Proscenium::SideLoadTest < ActiveSupport::TestCase assert_equal({ '/@proscenium/react-manager/index.jsx' => { js: { type: 'module' } }, - '/gem1/app/components/flash/component.jsx' => { sideloaded: true, lazy: true }, + '/vendor/gem1/app/components/flash/component.jsx' => { sideloaded: true, + lazy: true }, '/app/views/layouts/bare.js' => { sideloaded: true }, '/app/views/layouts/bare.css' => { sideloaded: true } }, Proscenium::Importer.imported) diff --git a/test/ui_test.go b/test/ui_test.go new file mode 100644 index 00000000..0ef5f780 --- /dev/null +++ b/test/ui_test.go @@ -0,0 +1,81 @@ +package proscenium_test + +import ( + b "joelmoss/proscenium/internal/builder" + "joelmoss/proscenium/internal/types" + . "joelmoss/proscenium/test/support" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("b.Build(ui)", func() { + BeforeEach(func() { + types.Config.Engines = map[string]string{ + "proscenium/ui": types.Config.GemPath + "/lib/proscenium/ui", + } + }) + + When("Bundle = false", func() { + BeforeEach(func() { + types.Config.Bundle = false + }) + + It("builds from lib/ui", func() { + Expect(b.Build("@proscenium/ui/test.js")).To(ContainCode(` + console.log("@proscenium/ui/test.js"); + `)) + + Expect(b.Build("@proscenium/ujs")).To(ContainCode(` + const classPath = "/proscenium/ui/ujs/class.js"; + `)) + }) + + It("builds without file extension", func() { + Expect(b.Build("@proscenium/ui/test")).To(ContainCode(` + console.log("@proscenium/ui/test.js"); + `)) + }) + + It("does not bundle imports", func() { + Expect(b.Build("lib/ui/test.js")).To(ContainCode(` + import "/proscenium/ui/test.js"; + `)) + }) + + It("resolves imports", func() { + Expect(b.Build("@proscenium/ujs/class.js")).To(ContainCode(` + import DataConfirm from "/proscenium/ui/ujs/data_confirm.js"; + import DataDisableWith from "/proscenium/ui/ujs/data_disable_with.js"; + `)) + }) + }) + + When("Bundle = true", func() { + BeforeEach(func() { + types.Config.Bundle = true + }) + + It("builds from lib/ui", func() { + Expect(b.Build("@proscenium/ui/test.js")).To(ContainCode(` + console.log("@proscenium/ui/test.js"); + `)) + + Expect(b.Build("@proscenium/ujs")).To(ContainCode(` + const classPath = "/proscenium/ui/ujs/class.js"; + `)) + }) + + It("bundles imports", func() { + Expect(b.Build("lib/ui/test.js")).To(ContainCode(` + console.log("@proscenium/ui/test.js"); + `)) + }) + + It("builds without file extension", func() { + Expect(b.Build("@proscenium/ui/test")).To(ContainCode(` + console.log("@proscenium/ui/test.js"); + `)) + }) + }) +}) From 45163431245f8c175008134f0993989704086360 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Mon, 30 Dec 2024 09:08:12 +0000 Subject: [PATCH 05/15] chore: Bump version to 0.19.0.beta1 --- Gemfile.lock | 2 +- lib/proscenium/version.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index 69271f78..d2718477 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - proscenium (0.18.0) + proscenium (0.19.0.beta1) activesupport (>= 7.1.0, < 8.0) ffi (~> 1.17.0) literal (~> 1.0) diff --git a/lib/proscenium/version.rb b/lib/proscenium/version.rb index 3bd68841..ce16abdd 100644 --- a/lib/proscenium/version.rb +++ b/lib/proscenium/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Proscenium - VERSION = '0.18.0' + VERSION = '0.19.0.beta1' end From 0d3c75bec4e442a4e1e6ebce8902e4d4c8463105 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Mon, 30 Dec 2024 10:12:57 +0000 Subject: [PATCH 06/15] fix: correctly resolve vendored engine paths in resolver --- lib/proscenium/resolver.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/proscenium/resolver.rb b/lib/proscenium/resolver.rb index 93bd0f69..063463f2 100644 --- a/lib/proscenium/resolver.rb +++ b/lib/proscenium/resolver.rb @@ -25,10 +25,14 @@ def self.resolve(path) "/#{path}" elsif path.start_with?(Proscenium.ui_path.to_s) path.delete_prefix Proscenium.root.join('lib').to_s + elsif (engine = Proscenium.config.engines.find { |e| path.start_with? "#{e.root}/" }) + if engine.root.to_s.start_with?("#{Rails.root}/") + path.delete_prefix Rails.root.to_s + else + path.sub(/^#{engine.root}/, "/#{engine.engine_name}") + end elsif path.start_with?("#{Rails.root}/") path.delete_prefix Rails.root.to_s - elsif (engine = Proscenium.config.engines.find { |e| path.start_with? "#{e.root}/" }) - path.sub(/^#{engine.root}/, "/#{engine.engine_name}") else Builder.resolve path end From 4de47d1a42e6063fb8d1cbaeb9861eb922b05d53 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Mon, 30 Dec 2024 10:16:50 +0000 Subject: [PATCH 07/15] chore: Bump version to 0.19.0.beta2 --- Gemfile.lock | 2 +- lib/proscenium/version.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index d2718477..e96c750e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - proscenium (0.19.0.beta1) + proscenium (0.19.0.beta2) activesupport (>= 7.1.0, < 8.0) ffi (~> 1.17.0) literal (~> 1.0) diff --git a/lib/proscenium/version.rb b/lib/proscenium/version.rb index ce16abdd..e688304e 100644 --- a/lib/proscenium/version.rb +++ b/lib/proscenium/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Proscenium - VERSION = '0.19.0.beta1' + VERSION = '0.19.0.beta2' end From 2cd2580d9c2a888a1382037969836aaf81a57fc7 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Mon, 30 Dec 2024 10:37:55 +0000 Subject: [PATCH 08/15] fix: test/build_bundless_test.go: fix test to not depend on absolute paths --- test/build_bundless_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/build_bundless_test.go b/test/build_bundless_test.go index 729e9639..32a9d188 100644 --- a/test/build_bundless_test.go +++ b/test/build_bundless_test.go @@ -130,7 +130,7 @@ var _ = Describe("Build bundless", func() { It("should fail on engined but unknown entrypoint", func() { result := b.Build("gem3/unknown.js") - Expect(result.Errors[0].Text).To(Equal("Could not read from file: /Users/joelmoss/dev/proscenium/fixtures/dummy/vendor/gem3/unknown.js")) + Expect(result.Errors[0].Text).To(HavePrefix("Could not read from file: /")) }) It("resolves entry point", func() { @@ -194,7 +194,7 @@ var _ = Describe("Build bundless", func() { It("should fail on engined but unknown entrypoint", func() { result := b.Build("gem4/unknown.js") - Expect(result.Errors[0].Text).To(Equal("Could not read from file: /Users/joelmoss/dev/proscenium/fixtures/external/gem4/unknown.js")) + Expect(result.Errors[0].Text).To(HavePrefix("Could not read from file: /")) }) It("resolves entry point", func() { From e9e22abc32166d8c8365f77adc66f5ce5ada57d1 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Tue, 31 Dec 2024 18:40:55 +0000 Subject: [PATCH 09/15] chore: bump ruby version to 3.3.6 --- .ruby-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ruby-version b/.ruby-version index 0163af7e..eedb52ba 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -3.3.5 \ No newline at end of file +3.3.6 \ No newline at end of file From 4a6b8e867aa4d7e7141deb39cea757746d6eaa15 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Fri, 3 Jan 2025 18:09:48 +0000 Subject: [PATCH 10/15] fix: vendored engines --- Gemfile | 1 + Gemfile.lock | 7 + fixtures/dummy/lib/engines/fonts.css | 7 + .../ruby/3.3.0/bundler/gems/gem5/.gitignore | 8 + .../ruby/3.3.0/bundler/gems/gem5/Gemfile | 6 + .../ruby/3.3.0/bundler/gems/gem5/Gemfile.lock | 153 ++++++++++++++++++ .../ruby/3.3.0/bundler/gems/gem5/Rakefile | 16 ++ .../gem5/app/components/flash/component.jsx | 1 + .../gem5/app/components/flash/component.rb | 4 + .../bundler/gems/gem5/app/views/user.css | 1 + .../3.3.0/bundler/gems/gem5/app/views/user.js | 1 + .../3.3.0/bundler/gems/gem5/app/views/user.rb | 9 ++ .../ruby/3.3.0/bundler/gems/gem5/gem5.gemspec | 17 ++ .../ruby/3.3.0/bundler/gems/gem5/lib/gem5.rb | 9 ++ .../3.3.0/bundler/gems/gem5/lib/gem5/blue.css | 3 + .../bundler/gems/gem5/lib/gem5/console.js | 1 + .../bundler/gems/gem5/lib/gem5/engine.rb | 21 +++ .../3.3.0/bundler/gems/gem5/lib/gem5/foo.js | 1 + .../3.3.0/bundler/gems/gem5/lib/gem5/gem5.js | 11 ++ .../bundler/gems/gem5/lib/gem5/imported.js | 3 + .../3.3.0/bundler/gems/gem5/lib/gem5/red.css | 3 + .../gems/gem5/lib/gem5/styles.module.css | 6 + .../bundler/gems/gem5/lib/gem5/version.rb | 5 + .../3.3.0/bundler/gems/gem5/public/gem5.js | 1 + .../bundler/gems/gem5/public/somefont.woff2 | 0 .../dummy/vendor/gem3/public/somefont.woff2 | 0 go.mod | 3 + go.sum | 7 + internal/plugin/bundless.go | 32 ++-- lib/proscenium/resolver.rb | 6 +- test/build_bundless_test.go | 25 +-- test/parse_css_test.go | 2 +- test/side_load_test.rb | 4 +- test/svg_test.go | 23 ++- 34 files changed, 353 insertions(+), 44 deletions(-) create mode 100644 fixtures/dummy/lib/engines/fonts.css create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/.gitignore create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Gemfile create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Gemfile.lock create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Rakefile create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/components/flash/component.jsx create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/components/flash/component.rb create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.css create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.js create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.rb create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/gem5.gemspec create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5.rb create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/blue.css create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/console.js create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/engine.rb create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/foo.js create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/gem5.js create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/imported.js create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/red.css create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/styles.module.css create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/version.rb create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/public/gem5.js create mode 100644 fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/public/somefont.woff2 create mode 100644 fixtures/dummy/vendor/gem3/public/somefont.woff2 diff --git a/Gemfile b/Gemfile index 8d420759..c31b35c5 100644 --- a/Gemfile +++ b/Gemfile @@ -34,6 +34,7 @@ group :test do gem 'gem2', path: './fixtures/external/gem2' gem 'gem3', path: './fixtures/dummy/vendor/gem3' gem 'gem4', path: './fixtures/external/gem4' + gem 'gem5', path: './fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5' gem 'maxitest' gem 'minitest-focus' gem 'minitest-spec-rails' diff --git a/Gemfile.lock b/Gemfile.lock index e96c750e..d17c74af 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -9,6 +9,12 @@ PATH railties (>= 7.1.0, < 8.0) ruby-next (~> 1.0.1) +PATH + remote: fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5 + specs: + gem5 (0.1.0) + rails (>= 7.0.4) + PATH remote: fixtures/dummy/vendor/gem1 specs: @@ -350,6 +356,7 @@ DEPENDENCIES gem2! gem3! gem4! + gem5! htmlbeautifier maxitest minitest-focus diff --git a/fixtures/dummy/lib/engines/fonts.css b/fixtures/dummy/lib/engines/fonts.css new file mode 100644 index 00000000..0460ceec --- /dev/null +++ b/fixtures/dummy/lib/engines/fonts.css @@ -0,0 +1,7 @@ +@font-face { + font-family: SomeFont; + font-weight: 300; + font-style: normal; + font-display: swap; + src: local("SomeFont"), url("/gem5/somefont.woff2") format("woff2"); +} diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/.gitignore b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/.gitignore new file mode 100644 index 00000000..9106b2a3 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/.gitignore @@ -0,0 +1,8 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Gemfile b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Gemfile new file mode 100644 index 00000000..e5e6420e --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Gemfile @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' + +# Specify your gem's dependencies in gem5.gemspec +gemspec diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Gemfile.lock b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Gemfile.lock new file mode 100644 index 00000000..48bebf66 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Gemfile.lock @@ -0,0 +1,153 @@ +PATH + remote: . + specs: + gem5 (0.1.0) + rails (>= 7.0.4) + +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.0.4) + actionpack (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activesupport (= 7.0.4) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.0) + actionpack (7.0.4) + actionview (= 7.0.4) + activesupport (= 7.0.4) + rack (~> 2.0, >= 2.2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (7.0.4) + actionpack (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.0.4) + activesupport (= 7.0.4) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.3.6) + activemodel (7.0.4) + activesupport (= 7.0.4) + activerecord (7.0.4) + activemodel (= 7.0.4) + activesupport (= 7.0.4) + activestorage (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activesupport (= 7.0.4) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (7.0.4) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + builder (3.2.4) + concurrent-ruby (1.1.10) + crass (1.0.6) + erubi (1.11.0) + globalid (1.0.0) + activesupport (>= 5.0) + i18n (1.12.0) + concurrent-ruby (~> 1.0) + loofah (2.19.0) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.8.0) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + method_source (1.0.0) + mini_mime (1.1.2) + minitest (5.16.3) + net-imap (0.3.1) + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.0) + timeout + net-smtp (0.3.3) + net-protocol + nio4r (2.5.8) + nokogiri (1.13.9-arm64-darwin) + racc (~> 1.4) + racc (1.6.1) + rack (2.2.4) + rack-test (2.0.2) + rack (>= 1.3) + rails (7.0.4) + actioncable (= 7.0.4) + actionmailbox (= 7.0.4) + actionmailer (= 7.0.4) + actionpack (= 7.0.4) + actiontext (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activemodel (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + bundler (>= 1.15.0) + railties (= 7.0.4) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.4.3) + loofah (~> 2.3) + railties (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + method_source + rake (>= 12.2) + thor (~> 1.0) + zeitwerk (~> 2.5) + rake (13.0.6) + thor (1.2.1) + timeout (0.3.1) + tzinfo (2.0.5) + concurrent-ruby (~> 1.0) + websocket-driver (0.7.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.6.6) + +PLATFORMS + arm64-darwin-21 + +DEPENDENCIES + gem5! + +BUNDLED WITH + 2.3.17 diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Rakefile b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Rakefile new file mode 100644 index 00000000..68c3f3a4 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/Rakefile @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require 'bundler/gem_tasks' +require 'rake/testtask' + +Rake::TestTask.new(:test) do |t| + t.libs << 'test' + t.libs << 'lib' + t.test_files = FileList['test/**/test_*.rb'] +end + +require 'rubocop/rake_task' + +RuboCop::RakeTask.new + +task default: %i[test rubocop] diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/components/flash/component.jsx b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/components/flash/component.jsx new file mode 100644 index 00000000..296d5492 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/components/flash/component.jsx @@ -0,0 +1 @@ +console.log(1); diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/components/flash/component.rb b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/components/flash/component.rb new file mode 100644 index 00000000..07d7677f --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/components/flash/component.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +class Gem5::Components::Flash::Component < Proscenium::Phlex::ReactComponent +end diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.css b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.css new file mode 100644 index 00000000..41613843 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.css @@ -0,0 +1 @@ +@import 'open-props/shadows'; diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.js b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.js new file mode 100644 index 00000000..59e1c06d --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.js @@ -0,0 +1 @@ +console.log("gem5/views/user"); diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.rb b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.rb new file mode 100644 index 00000000..8245f339 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/app/views/user.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +module Gem5::Views + class User < Proscenium::Phlex + def view_template + h1 { 'Hello' } + end + end +end diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/gem5.gemspec b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/gem5.gemspec new file mode 100644 index 00000000..7714a1cc --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/gem5.gemspec @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require_relative 'lib/gem5/version' + +Gem::Specification.new do |spec| + spec.name = 'gem5' + spec.version = Gem5::VERSION + spec.authors = ['Joel Moss'] + spec.email = ['joel@developwithstyle.com'] + spec.required_ruby_version = '>= 2.7.0' + spec.summary = 'Test gem 5' + + spec.require_paths = ['lib'] + spec.metadata['rubygems_mfa_required'] = 'true' + + spec.add_dependency 'rails', '>= 7.0.4' +end diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5.rb b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5.rb new file mode 100644 index 00000000..d7d84543 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +require_relative 'gem5/version' +require_relative 'gem5/engine' + +module Gem5 + class Error < StandardError; end + module Components; end +end diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/blue.css b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/blue.css new file mode 100644 index 00000000..18c79458 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/blue.css @@ -0,0 +1,3 @@ +@define-mixin blue { + color: blue; +} diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/console.js b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/console.js new file mode 100644 index 00000000..221676b1 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/console.js @@ -0,0 +1 @@ +console.log("gem5"); diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/engine.rb b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/engine.rb new file mode 100644 index 00000000..31dd1d65 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/engine.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +require 'proscenium' + +module Gem5 + class Engine < ::Rails::Engine + # isolate_namespace Gem5 + engine_name 'gem5' + + config.proscenium.engines << self + + initializer 'gem5.autoload' do + # ActiveSupport::Dependencies.autoload_paths << "#{root}/app" + + # Rails.autoloaders.main.push_dir(root.join('app'), namespace: Gem5) + + ActiveSupport::Dependencies.autoload_paths.delete("#{root}/app/components") + Rails.autoloaders.main.push_dir("#{root}/app/components", namespace: Gem5::Components) + end + end +end diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/foo.js b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/foo.js new file mode 100644 index 00000000..85ce559e --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/foo.js @@ -0,0 +1 @@ +console.log("foo"); diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/gem5.js b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/gem5.js new file mode 100644 index 00000000..50f43764 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/gem5.js @@ -0,0 +1,11 @@ +import { one } from "mypackage/treeshake"; +import imported from "./imported"; +import "/lib/foo.js"; // app +import "./foo"; +import "/gem5/lib/gem5/console.js"; +import styles from "./styles.module.css"; + +console.log(styles); +console.log("gem5"); +imported(); +one(); diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/imported.js b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/imported.js new file mode 100644 index 00000000..47be4810 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/imported.js @@ -0,0 +1,3 @@ +export default () => { + console.log("gem5/imported"); +}; diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/red.css b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/red.css new file mode 100644 index 00000000..1edfa146 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/red.css @@ -0,0 +1,3 @@ +@define-mixin red { + color: red; +} diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/styles.module.css b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/styles.module.css new file mode 100644 index 00000000..73d09ae4 --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/styles.module.css @@ -0,0 +1,6 @@ +h1 { + @mixin red from url("./red.css"); +} +h2 { + @mixin blue from url("/gem5/lib/gem5/blue.css"); +} diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/version.rb b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/version.rb new file mode 100644 index 00000000..7330086c --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/lib/gem5/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Gem5 + VERSION = '0.1.0' +end diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/public/gem5.js b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/public/gem5.js new file mode 100644 index 00000000..5b2f8cab --- /dev/null +++ b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/public/gem5.js @@ -0,0 +1 @@ +console.log("/public/gem5.js"); diff --git a/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/public/somefont.woff2 b/fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5/public/somefont.woff2 new file mode 100644 index 00000000..e69de29b diff --git a/fixtures/dummy/vendor/gem3/public/somefont.woff2 b/fixtures/dummy/vendor/gem3/public/somefont.woff2 new file mode 100644 index 00000000..e69de29b diff --git a/go.mod b/go.mod index aaccf7f9..b6984dc8 100644 --- a/go.mod +++ b/go.mod @@ -18,6 +18,8 @@ require ( github.com/google/go-cmp v0.6.0 // indirect github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.16 // indirect github.com/stretchr/testify v1.10.0 // indirect golang.org/x/net v0.33.0 // indirect golang.org/x/tools v0.28.0 // indirect @@ -29,6 +31,7 @@ require ( github.com/dop251/goja v0.0.0-20241024094426-79f3a7efcdbd github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/h2non/gock v1.2.0 + github.com/k0kubun/pp/v3 v3.4.1 github.com/kr/pretty v0.3.1 // indirect github.com/mitchellh/mapstructure v1.5.0 github.com/onsi/gomega v1.36.1 diff --git a/go.sum b/go.sum index 159d39bd..9420e12a 100644 --- a/go.sum +++ b/go.sum @@ -32,6 +32,8 @@ github.com/h2non/gock v1.2.0 h1:K6ol8rfrRkUOefooBC8elXoaNGYkpp7y2qcxGG6BzUE= github.com/h2non/gock v1.2.0/go.mod h1:tNhoxHYW2W42cYkYb1WqzdbYIieALC99kpYr7rH/BQk= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= +github.com/k0kubun/pp/v3 v3.4.1 h1:1WdFZDRRqe8UsR61N/2RoOZ3ziTEqgTPVqKrHeb779Y= +github.com/k0kubun/pp/v3 v3.4.1/go.mod h1:+SiNiqKnBfw1Nkj82Lh5bIeKQOAkPy6Xw9CAZUZ8npI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -39,6 +41,10 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= @@ -68,6 +74,7 @@ github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= diff --git a/internal/plugin/bundless.go b/internal/plugin/bundless.go index faca111b..4a19eb4a 100644 --- a/internal/plugin/bundless.go +++ b/internal/plugin/bundless.go @@ -24,6 +24,8 @@ var Bundless = esbuild.Plugin{ return esbuild.OnResolveResult{}, nil } + // pp.Println("[bundless] args:", args) + // Should we use esbuild to resolve this path? useResolve := false @@ -141,6 +143,8 @@ var Bundless = esbuild.Plugin{ r := build.Resolve(result.Path, resolveOpts) + // pp.Println("[bundless] resolve result:", r) + result.Path = r.Path result.Errors = r.Errors result.Warnings = r.Warnings @@ -155,23 +159,27 @@ var Bundless = esbuild.Plugin{ FINISH: // Only entrypoints must be an absolute path. if args.Kind != esbuild.ResolveEntryPoint && result.Path != "" { - if !strings.HasPrefix(result.Path, root) { - if resolvedEnginePath != "" && resolvedEngineKey != "" { - result.Path = filepath.Join(pathSep, resolvedEngineKey, strings.TrimPrefix(result.Path, resolvedEnginePath)) - } else { - for key, value := range types.Config.Engines { - if strings.HasPrefix(result.Path, value+pathSep) { - result.Path = filepath.Join(pathSep, key, strings.TrimPrefix(result.Path, value)) - break - } + if resolvedEnginePath != "" && resolvedEngineKey != "" { + result.Path = filepath.Join(pathSep, resolvedEngineKey, strings.TrimPrefix(result.Path, resolvedEnginePath)) + } else { + newPath := "" + + for key, value := range types.Config.Engines { + if strings.HasPrefix(result.Path, value+pathSep) { + newPath = filepath.Join(pathSep, key, strings.TrimPrefix(result.Path, value)) + break } } - } else { - result.Path = strings.TrimPrefix(result.Path, root) + + if newPath != "" { + result.Path = newPath + } else if strings.HasPrefix(result.Path, root) { + result.Path = strings.TrimPrefix(result.Path, root) + } } } - // pp.Println("[bundless] resolve", result) + // pp.Println("[bundless] result:", result) return result, nil }) diff --git a/lib/proscenium/resolver.rb b/lib/proscenium/resolver.rb index 063463f2..649f21e4 100644 --- a/lib/proscenium/resolver.rb +++ b/lib/proscenium/resolver.rb @@ -26,11 +26,7 @@ def self.resolve(path) elsif path.start_with?(Proscenium.ui_path.to_s) path.delete_prefix Proscenium.root.join('lib').to_s elsif (engine = Proscenium.config.engines.find { |e| path.start_with? "#{e.root}/" }) - if engine.root.to_s.start_with?("#{Rails.root}/") - path.delete_prefix Rails.root.to_s - else - path.sub(/^#{engine.root}/, "/#{engine.engine_name}") - end + path.sub(/^#{engine.root}/, "/#{engine.engine_name}") elsif path.start_with?("#{Rails.root}/") path.delete_prefix Rails.root.to_s else diff --git a/test/build_bundless_test.go b/test/build_bundless_test.go index 32a9d188..a4519678 100644 --- a/test/build_bundless_test.go +++ b/test/build_bundless_test.go @@ -100,6 +100,7 @@ var _ = Describe("Build bundless", func() { var _ = BeforeEach(func() { types.Config.Engines = map[string]string{ "gem3": filepath.Join(fixturesRoot, "dummy", "vendor", "gem3"), + "gem5": filepath.Join(fixturesRoot, "dummy", "vendor", "bundle", "ruby", "3.3.0", "bundler", "gems", "gem5"), } }) @@ -118,13 +119,13 @@ var _ = Describe("Build bundless", func() { result := b.Build("lib/engines/gem3.js") - Expect(result).To(ContainCode(`import "/vendor/gem3/lib/gem3/console.js";`)) + Expect(result).To(ContainCode(`import "/gem3/lib/gem3/console.js";`)) }) It("should resolve extension-less imports", func() { result := b.Build("gem3/lib/gem3/gem3.js") - Expect(result).To(ContainCode(`import "/vendor/gem3/lib/gem3/foo.js";`)) + Expect(result).To(ContainCode(`import "/gem3/lib/gem3/foo.js";`)) }) It("should fail on engined but unknown entrypoint", func() { @@ -142,9 +143,7 @@ var _ = Describe("Build bundless", func() { It("resolves absolute and same engine imports", func() { result := b.Build("gem3/lib/gem3/gem3.js") - Expect(result).To(ContainCode(` - import "/vendor/gem3/lib/gem3/console.js"; - `)) + Expect(result).To(ContainCode(`import "/gem3/lib/gem3/console.js";`)) }) It("resolves bare import to Rails app (not engine)", func() { @@ -158,23 +157,25 @@ var _ = Describe("Build bundless", func() { It("resolves relative import to engine", func() { result := b.Build("gem3/lib/gem3/gem3.js") - Expect(result).To(ContainCode(` - import imported from "/vendor/gem3/lib/gem3/imported.js"; - `)) + Expect(result).To(ContainCode(`import imported from "/gem3/lib/gem3/imported.js";`)) }) It("resolves absolute import to Rails app (not engine)", func() { result := b.Build("gem3/lib/gem3/gem3.js") - Expect(result).To(ContainCode(` - import "/lib/foo.js"; - `)) + Expect(result).To(ContainCode(`import "/lib/foo.js";`)) }) It("resolves import from engine when in app", func() { result := b.Build("lib/gems/gem3.js") - Expect(result).To(ContainCode(`import "/vendor/gem3/lib/gem3/gem3.js"`)) + Expect(result).To(ContainCode(`import "/gem3/lib/gem3/gem3.js"`)) + }) + + It("should not bundle fonts", func() { + result := b.Build("lib/engines/fonts.css") + + Expect(result).To(ContainCode(`url(/gem5/somefont.woff2)`)) }) }) diff --git a/test/parse_css_test.go b/test/parse_css_test.go index 5279e2e9..81960ec9 100644 --- a/test/parse_css_test.go +++ b/test/parse_css_test.go @@ -148,7 +148,7 @@ var _ = Describe("Build(parseCss)", func() { }) When("mixin file is not found", func() { - It("should log warning", Pending) + // It("should log warning", Pending) It("should pass through the @mixin declaration", func() { Expect(` diff --git a/test/side_load_test.rb b/test/side_load_test.rb index 6937bb5f..f13d87fa 100644 --- a/test/side_load_test.rb +++ b/test/side_load_test.rb @@ -67,8 +67,8 @@ class Proscenium::SideLoadTest < ActiveSupport::TestCase assert_equal({ '/@proscenium/react-manager/index.jsx' => { js: { type: 'module' } }, - '/vendor/gem1/app/components/flash/component.jsx' => { sideloaded: true, - lazy: true }, + '/gem1/app/components/flash/component.jsx' => { sideloaded: true, + lazy: true }, '/app/views/layouts/bare.js' => { sideloaded: true }, '/app/views/layouts/bare.css' => { sideloaded: true } }, Proscenium::Importer.imported) diff --git a/test/svg_test.go b/test/svg_test.go index 7e2944b0..f59eb2c4 100644 --- a/test/svg_test.go +++ b/test/svg_test.go @@ -3,7 +3,6 @@ package proscenium_test import ( b "joelmoss/proscenium/internal/builder" . "joelmoss/proscenium/test/support" - "regexp" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -70,18 +69,18 @@ var _ = Describe("b.Build(svg)", func() { }) }) - When("importing remote svg from css", func() { - PIt("should not bundle or encode; leave as is", func() { - var re = regexp.MustCompile(`^https?://.+(^\.svg)`) - Expect(re.MatchString("https://sdfsdf.jsvg")).To(BeTrue()) - }) + // When("importing remote svg from css", func() { + // PIt("should not bundle or encode; leave as is", func() { + // var re = regexp.MustCompile(`^https?://.+(^\.svg)`) + // Expect(re.MatchString("https://sdfsdf.jsvg")).To(BeTrue()) + // }) - PIt("should not bundle or encode; leave as is", func() { - MockURL("/at.svg", svgContent) + // PIt("should not bundle or encode; leave as is", func() { + // MockURL("/at.svg", svgContent) - result := b.Build("lib/svg/remote.css") + // result := b.Build("lib/svg/remote.css") - Expect(result).To(ContainCode(`background-image: url(https://proscenium.test/at.svg);`)) - }) - }) + // Expect(result).To(ContainCode(`background-image: url(https://proscenium.test/at.svg);`)) + // }) + // }) }) From 7e472a1b15e60d9d041b6284b57b268e98757768 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Fri, 3 Jan 2025 19:35:27 +0000 Subject: [PATCH 11/15] chore: bump to 0.19.0.beta3 --- Gemfile.lock | 2 +- go.mod | 3 --- go.sum | 7 ------- lib/proscenium/version.rb | 2 +- 4 files changed, 2 insertions(+), 12 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index d17c74af..f9689377 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - proscenium (0.19.0.beta2) + proscenium (0.19.0.beta3) activesupport (>= 7.1.0, < 8.0) ffi (~> 1.17.0) literal (~> 1.0) diff --git a/go.mod b/go.mod index b6984dc8..aaccf7f9 100644 --- a/go.mod +++ b/go.mod @@ -18,8 +18,6 @@ require ( github.com/google/go-cmp v0.6.0 // indirect github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.16 // indirect github.com/stretchr/testify v1.10.0 // indirect golang.org/x/net v0.33.0 // indirect golang.org/x/tools v0.28.0 // indirect @@ -31,7 +29,6 @@ require ( github.com/dop251/goja v0.0.0-20241024094426-79f3a7efcdbd github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/h2non/gock v1.2.0 - github.com/k0kubun/pp/v3 v3.4.1 github.com/kr/pretty v0.3.1 // indirect github.com/mitchellh/mapstructure v1.5.0 github.com/onsi/gomega v1.36.1 diff --git a/go.sum b/go.sum index 9420e12a..159d39bd 100644 --- a/go.sum +++ b/go.sum @@ -32,8 +32,6 @@ github.com/h2non/gock v1.2.0 h1:K6ol8rfrRkUOefooBC8elXoaNGYkpp7y2qcxGG6BzUE= github.com/h2non/gock v1.2.0/go.mod h1:tNhoxHYW2W42cYkYb1WqzdbYIieALC99kpYr7rH/BQk= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= -github.com/k0kubun/pp/v3 v3.4.1 h1:1WdFZDRRqe8UsR61N/2RoOZ3ziTEqgTPVqKrHeb779Y= -github.com/k0kubun/pp/v3 v3.4.1/go.mod h1:+SiNiqKnBfw1Nkj82Lh5bIeKQOAkPy6Xw9CAZUZ8npI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -41,10 +39,6 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= @@ -74,7 +68,6 @@ github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= diff --git a/lib/proscenium/version.rb b/lib/proscenium/version.rb index e688304e..75ffafd4 100644 --- a/lib/proscenium/version.rb +++ b/lib/proscenium/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Proscenium - VERSION = '0.19.0.beta2' + VERSION = '0.19.0.beta3' end From 42d495113d9afe75ee571ea5505b2189a55f2a1d Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Fri, 3 Jan 2025 21:58:15 +0000 Subject: [PATCH 12/15] fix(bundless): ensure absolute path is returned for external imports --- internal/plugin/bundless.go | 2 +- internal/plugin/css.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/plugin/bundless.go b/internal/plugin/bundless.go index 4a19eb4a..6804e258 100644 --- a/internal/plugin/bundless.go +++ b/internal/plugin/bundless.go @@ -173,7 +173,7 @@ var Bundless = esbuild.Plugin{ if newPath != "" { result.Path = newPath - } else if strings.HasPrefix(result.Path, root) { + } else if result.External && strings.HasPrefix(result.Path, root) { result.Path = strings.TrimPrefix(result.Path, root) } } diff --git a/internal/plugin/css.go b/internal/plugin/css.go index 8d664ad5..09704b93 100644 --- a/internal/plugin/css.go +++ b/internal/plugin/css.go @@ -17,7 +17,7 @@ var Css = esbuild.Plugin{ build.OnLoad(esbuild.OnLoadOptions{Filter: `\.css$`}, func(args esbuild.OnLoadArgs) (esbuild.OnLoadResult, error) { - // pp.Println("[6] filter(.css$)", args) + // pp.Println("[cssPlugin.onLoad] args:", args) var pluginData types.PluginData if args.PluginData != nil { From 81efdc4ee1e7824a79c4c82c949902dc3b6cc9eb Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Fri, 3 Jan 2025 21:58:56 +0000 Subject: [PATCH 13/15] chore: bump version to 0.19.0.beta4 --- Gemfile.lock | 2 +- lib/proscenium/version.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index f9689377..f17bce63 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - proscenium (0.19.0.beta3) + proscenium (0.19.0.beta4) activesupport (>= 7.1.0, < 8.0) ffi (~> 1.17.0) literal (~> 1.0) diff --git a/lib/proscenium/version.rb b/lib/proscenium/version.rb index 75ffafd4..af86ab19 100644 --- a/lib/proscenium/version.rb +++ b/lib/proscenium/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Proscenium - VERSION = '0.19.0.beta3' + VERSION = '0.19.0.beta4' end From 45fe13d9179d1765fcec91068bfb0ce44c9169ca Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Sat, 4 Jan 2025 11:55:57 +0000 Subject: [PATCH 14/15] chore: Support for Rails 8 --- Appraisals | 2 +- Gemfile.lock | 4 +- gemfiles/rails_7.1.gemfile | 1 + gemfiles/rails_7.1.gemfile.lock | 9 ++- gemfiles/rails_7.2.gemfile | 1 + gemfiles/rails_7.2.gemfile.lock | 9 ++- gemfiles/rails_8.gemfile | 3 +- gemfiles/rails_8.gemfile.lock | 123 +++++++++++++++++--------------- proscenium.gemspec | 4 +- 9 files changed, 90 insertions(+), 66 deletions(-) diff --git a/Appraisals b/Appraisals index 5937ffcd..5c658dae 100644 --- a/Appraisals +++ b/Appraisals @@ -9,5 +9,5 @@ appraise 'rails-7.2' do end appraise 'rails-8' do - gem 'rails', '~> 8.0.0' + gem 'rails', '~> 8.0.1' end diff --git a/Gemfile.lock b/Gemfile.lock index f17bce63..1fb4c4b3 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -2,11 +2,11 @@ PATH remote: . specs: proscenium (0.19.0.beta4) - activesupport (>= 7.1.0, < 8.0) + activesupport (>= 7.1.0, < 9.0) ffi (~> 1.17.0) literal (~> 1.0) oj (~> 3.13) - railties (>= 7.1.0, < 8.0) + railties (>= 7.1.0, < 9.0) ruby-next (~> 1.0.1) PATH diff --git a/gemfiles/rails_7.1.gemfile b/gemfiles/rails_7.1.gemfile index cf444332..2224b947 100644 --- a/gemfiles/rails_7.1.gemfile +++ b/gemfiles/rails_7.1.gemfile @@ -29,6 +29,7 @@ group :test do gem "gem2", path: "../fixtures/external/gem2" gem "gem3", path: "../fixtures/dummy/vendor/gem3" gem "gem4", path: "../fixtures/external/gem4" + gem "gem5", path: "../fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5" gem "maxitest" gem "minitest-focus" gem "minitest-spec-rails" diff --git a/gemfiles/rails_7.1.gemfile.lock b/gemfiles/rails_7.1.gemfile.lock index 1e45ebb7..60d1b2d3 100644 --- a/gemfiles/rails_7.1.gemfile.lock +++ b/gemfiles/rails_7.1.gemfile.lock @@ -1,3 +1,9 @@ +PATH + remote: ../fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5 + specs: + gem5 (0.1.0) + rails (>= 7.0.4) + PATH remote: ../fixtures/dummy/vendor/gem1 specs: @@ -25,7 +31,7 @@ PATH PATH remote: .. specs: - proscenium (0.18.0) + proscenium (0.19.0.beta4) activesupport (>= 7.1.0, < 9.0) ffi (~> 1.17.0) literal (~> 1.0) @@ -345,6 +351,7 @@ DEPENDENCIES gem2! gem3! gem4! + gem5! htmlbeautifier maxitest minitest-focus diff --git a/gemfiles/rails_7.2.gemfile b/gemfiles/rails_7.2.gemfile index de624647..af017748 100644 --- a/gemfiles/rails_7.2.gemfile +++ b/gemfiles/rails_7.2.gemfile @@ -29,6 +29,7 @@ group :test do gem "gem2", path: "../fixtures/external/gem2" gem "gem3", path: "../fixtures/dummy/vendor/gem3" gem "gem4", path: "../fixtures/external/gem4" + gem "gem5", path: "../fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5" gem "maxitest" gem "minitest-focus" gem "minitest-spec-rails" diff --git a/gemfiles/rails_7.2.gemfile.lock b/gemfiles/rails_7.2.gemfile.lock index a29e3740..f441e444 100644 --- a/gemfiles/rails_7.2.gemfile.lock +++ b/gemfiles/rails_7.2.gemfile.lock @@ -1,3 +1,9 @@ +PATH + remote: ../fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5 + specs: + gem5 (0.1.0) + rails (>= 7.0.4) + PATH remote: ../fixtures/dummy/vendor/gem1 specs: @@ -25,7 +31,7 @@ PATH PATH remote: .. specs: - proscenium (0.18.0) + proscenium (0.19.0.beta4) activesupport (>= 7.1.0, < 9.0) ffi (~> 1.17.0) literal (~> 1.0) @@ -339,6 +345,7 @@ DEPENDENCIES gem2! gem3! gem4! + gem5! htmlbeautifier maxitest minitest-focus diff --git a/gemfiles/rails_8.gemfile b/gemfiles/rails_8.gemfile index f3948363..857d6188 100644 --- a/gemfiles/rails_8.gemfile +++ b/gemfiles/rails_8.gemfile @@ -3,7 +3,7 @@ source "https://rubygems.org" gem "debug" -gem "rails", "~> 8.0.0" +gem "rails", "~> 8.0.1" gem "appraisal" gem "htmlbeautifier" gem "phlexible" @@ -29,6 +29,7 @@ group :test do gem "gem2", path: "../fixtures/external/gem2" gem "gem3", path: "../fixtures/dummy/vendor/gem3" gem "gem4", path: "../fixtures/external/gem4" + gem "gem5", path: "../fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5" gem "maxitest" gem "minitest-focus" gem "minitest-spec-rails" diff --git a/gemfiles/rails_8.gemfile.lock b/gemfiles/rails_8.gemfile.lock index 54d620ff..042fb09b 100644 --- a/gemfiles/rails_8.gemfile.lock +++ b/gemfiles/rails_8.gemfile.lock @@ -1,3 +1,9 @@ +PATH + remote: ../fixtures/dummy/vendor/bundle/ruby/3.3.0/bundler/gems/gem5 + specs: + gem5 (0.1.0) + rails (>= 7.0.4) + PATH remote: ../fixtures/dummy/vendor/gem1 specs: @@ -25,7 +31,7 @@ PATH PATH remote: .. specs: - proscenium (0.18.0) + proscenium (0.19.0.beta4) activesupport (>= 7.1.0, < 9.0) ffi (~> 1.17.0) literal (~> 1.0) @@ -36,29 +42,29 @@ PATH GEM remote: https://rubygems.org/ specs: - actioncable (8.0.0) - actionpack (= 8.0.0) - activesupport (= 8.0.0) + actioncable (8.0.1) + actionpack (= 8.0.1) + activesupport (= 8.0.1) nio4r (~> 2.0) websocket-driver (>= 0.6.1) zeitwerk (~> 2.6) - actionmailbox (8.0.0) - actionpack (= 8.0.0) - activejob (= 8.0.0) - activerecord (= 8.0.0) - activestorage (= 8.0.0) - activesupport (= 8.0.0) + actionmailbox (8.0.1) + actionpack (= 8.0.1) + activejob (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) mail (>= 2.8.0) - actionmailer (8.0.0) - actionpack (= 8.0.0) - actionview (= 8.0.0) - activejob (= 8.0.0) - activesupport (= 8.0.0) + actionmailer (8.0.1) + actionpack (= 8.0.1) + actionview (= 8.0.1) + activejob (= 8.0.1) + activesupport (= 8.0.1) mail (>= 2.8.0) rails-dom-testing (~> 2.2) - actionpack (8.0.0) - actionview (= 8.0.0) - activesupport (= 8.0.0) + actionpack (8.0.1) + actionview (= 8.0.1) + activesupport (= 8.0.1) nokogiri (>= 1.8.5) rack (>= 2.2.4) rack-session (>= 1.0.1) @@ -66,35 +72,35 @@ GEM rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) useragent (~> 0.16) - actiontext (8.0.0) - actionpack (= 8.0.0) - activerecord (= 8.0.0) - activestorage (= 8.0.0) - activesupport (= 8.0.0) + actiontext (8.0.1) + actionpack (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) globalid (>= 0.6.0) nokogiri (>= 1.8.5) - actionview (8.0.0) - activesupport (= 8.0.0) + actionview (8.0.1) + activesupport (= 8.0.1) builder (~> 3.1) erubi (~> 1.11) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) - activejob (8.0.0) - activesupport (= 8.0.0) + activejob (8.0.1) + activesupport (= 8.0.1) globalid (>= 0.3.6) - activemodel (8.0.0) - activesupport (= 8.0.0) - activerecord (8.0.0) - activemodel (= 8.0.0) - activesupport (= 8.0.0) + activemodel (8.0.1) + activesupport (= 8.0.1) + activerecord (8.0.1) + activemodel (= 8.0.1) + activesupport (= 8.0.1) timeout (>= 0.4.0) - activestorage (8.0.0) - actionpack (= 8.0.0) - activejob (= 8.0.0) - activerecord (= 8.0.0) - activesupport (= 8.0.0) + activestorage (8.0.1) + actionpack (= 8.0.1) + activejob (= 8.0.1) + activerecord (= 8.0.1) + activesupport (= 8.0.1) marcel (~> 1.0) - activesupport (8.0.0) + activesupport (8.0.1) base64 benchmark (>= 0.3) bigdecimal @@ -135,7 +141,7 @@ GEM cuprite (0.15.1) capybara (~> 3.0) ferrum (~> 0.15.0) - date (3.4.0) + date (3.4.1) debug (1.9.2) irb (~> 1.10) reline (>= 0.3.8) @@ -182,7 +188,7 @@ GEM minitest-spec-rails (7.4.1) minitest (>= 5.0) railties (>= 4.1) - net-imap (0.5.1) + net-imap (0.5.5) date net-protocol net-pop (0.1.2) @@ -226,20 +232,20 @@ GEM rack (>= 1.3) rackup (2.2.1) rack (>= 3) - rails (8.0.0) - actioncable (= 8.0.0) - actionmailbox (= 8.0.0) - actionmailer (= 8.0.0) - actionpack (= 8.0.0) - actiontext (= 8.0.0) - actionview (= 8.0.0) - activejob (= 8.0.0) - activemodel (= 8.0.0) - activerecord (= 8.0.0) - activestorage (= 8.0.0) - activesupport (= 8.0.0) + rails (8.0.1) + actioncable (= 8.0.1) + actionmailbox (= 8.0.1) + actionmailer (= 8.0.1) + actionpack (= 8.0.1) + actiontext (= 8.0.1) + actionview (= 8.0.1) + activejob (= 8.0.1) + activemodel (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) bundler (>= 1.15.0) - railties (= 8.0.0) + railties (= 8.0.1) rails-dom-testing (2.2.0) activesupport (>= 5.0.0) minitest @@ -247,9 +253,9 @@ GEM rails-html-sanitizer (1.6.0) loofah (~> 2.21) nokogiri (~> 1.14) - railties (8.0.0) - actionpack (= 8.0.0) - activesupport (= 8.0.0) + railties (8.0.1) + actionpack (= 8.0.1) + activesupport (= 8.0.1) irb (~> 1.13) rackup (>= 1.0.0) rake (>= 12.2) @@ -300,7 +306,7 @@ GEM sqlite3 (2.2.0-arm64-darwin) stringio (3.1.2) thor (1.3.2) - timeout (0.4.2) + timeout (0.4.3) tzinfo (2.0.6) concurrent-ruby (~> 1.0) unicode-display_width (2.6.0) @@ -340,6 +346,7 @@ DEPENDENCIES gem2! gem3! gem4! + gem5! htmlbeautifier maxitest minitest-focus @@ -348,7 +355,7 @@ DEPENDENCIES phlexible proscenium! puma - rails (~> 8.0.0) + rails (~> 8.0.1) rouge rubocop rubocop-minitest diff --git a/proscenium.gemspec b/proscenium.gemspec index 0efd2254..995aa674 100644 --- a/proscenium.gemspec +++ b/proscenium.gemspec @@ -27,10 +27,10 @@ Gem::Specification.new do |spec| 'LICENSE.txt'] spec.require_paths = ['lib'] - spec.add_dependency 'activesupport', ['>= 7.1.0', '< 8.0'] + spec.add_dependency 'activesupport', ['>= 7.1.0', '< 9.0'] spec.add_dependency 'ffi', '~> 1.17.0' spec.add_dependency 'literal', '~> 1.0' spec.add_dependency 'oj', '~> 3.13' - spec.add_dependency 'railties', ['>= 7.1.0', '< 8.0'] + spec.add_dependency 'railties', ['>= 7.1.0', '< 9.0'] spec.add_dependency 'ruby-next', '~> 1.0.1' end From c29d020445f5170a729399fbc7bb099e62227bb1 Mon Sep 17 00:00:00 2001 From: Joel Moss Date: Sat, 4 Jan 2025 13:36:08 +0000 Subject: [PATCH 15/15] fix: alias @proscenium/stimulus-loading --- Gemfile.lock | 2 +- internal/plugin/ui.go | 6 ++++++ test/ui_test.go | 12 ++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Gemfile.lock b/Gemfile.lock index 1fb4c4b3..c1162a67 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -203,7 +203,7 @@ GEM racc (~> 1.4) nokogiri (1.17.2-x86_64-linux) racc (~> 1.4) - oj (3.16.8) + oj (3.16.9) bigdecimal (>= 3.0) ostruct (>= 0.2) ostruct (0.6.1) diff --git a/internal/plugin/ui.go b/internal/plugin/ui.go index 871fe20a..ffb1c1f9 100644 --- a/internal/plugin/ui.go +++ b/internal/plugin/ui.go @@ -66,6 +66,12 @@ var Ui = esbuild.Plugin{ return resolvePath(args) }) + build.OnResolve(esbuild.OnResolveOptions{Filter: `^@proscenium/stimulus-loading`}, + func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { + args.Path = strings.TrimPrefix(args.Path, "@proscenium/") + return resolvePath(args) + }) + build.OnResolve(esbuild.OnResolveOptions{Filter: `^@proscenium/`}, func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) { args.Path = strings.TrimPrefix(args.Path, "@proscenium/ui") diff --git a/test/ui_test.go b/test/ui_test.go index 0ef5f780..b8e322af 100644 --- a/test/ui_test.go +++ b/test/ui_test.go @@ -43,6 +43,12 @@ var _ = Describe("b.Build(ui)", func() { `)) }) + It("resolves @proscenium/stimulus-loading", func() { + Expect(b.Build("@proscenium/stimulus-loading")).To(ContainCode(` + function lazyLoadControllersFrom + `)) + }) + It("resolves imports", func() { Expect(b.Build("@proscenium/ujs/class.js")).To(ContainCode(` import DataConfirm from "/proscenium/ui/ujs/data_confirm.js"; @@ -77,5 +83,11 @@ var _ = Describe("b.Build(ui)", func() { console.log("@proscenium/ui/test.js"); `)) }) + + It("resolves @proscenium/stimulus-loading", func() { + Expect(b.Build("@proscenium/stimulus-loading")).To(ContainCode(` + function lazyLoadControllersFrom + `)) + }) }) })