text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
node_modules/** /docs/_assets /docs/_includes /docs/_data
modernweb-dev/web/.eleventyignore/0
{ "file_path": "modernweb-dev/web/.eleventyignore", "repo_id": "modernweb-dev", "token_count": 20 }
161
--- title: 'Introducing: Web Test Runner' published: false canonical_url: https://modern-web.dev/blog/introducing-web-test-runner/ description: Reexperience the joy of working with the standards based web. Starting off with a test runner which uses multiple browsers in parallel. date: 2020-08-25 tags: [javascript, web-test-runner] cover_image: /blog/introducing-web-test-runner/introducing-web-test-runner-blog-header.jpg socialMediaImage: /blog/introducing-web-test-runner/introducing-web-test-runner-blog-social-media-image.jpg --- We are very excited to announce today the official 1.x release of [web test runner](../../docs/test-runner/overview.md), a project we have been working on for the past months. There are already a lot of testing solutions out there today. Unfortunately, all of them either run tests in Node.js and mock browser APIs using something like JSDom or don't support native es modules out of the box. We think that making browser code compatible for testing in node is unnecessarily complex. Running tests in real browsers gives greater confidence in (cross-browser) compatibility and makes writing and debugging tests more approachable. By building on top of our web dev server, and modern browser launchers like Puppeteer and Playwright, we created a new test runner which fills this gap in the ecosystem. We think it is already feature-complete enough to be picked up by any web project. Some highlights: ๐Ÿ‘‰&nbsp;&nbsp; Headless browsers with [Puppeteer](../../docs/test-runner/browsers/puppeteer.md), [Playwright](../../docs/test-runner/browsers/playwright.md), or [Selenium](../../docs/test-runner/browsers/selenium.md). <br> ๐Ÿšง&nbsp;&nbsp; Reports logs, 404s, and errors from the browser. <br> ๐Ÿ”&nbsp;&nbsp; Debug opens a real browser window with devtools.<br> ๐Ÿ”ง&nbsp;&nbsp; Exposes browser properties like viewport size and dark mode.<br> โฑ&nbsp;&nbsp;Runs tests in parallel and isolation.<br> ๐Ÿ‘€&nbsp;&nbsp; Interactive watch mode.<br> ๐Ÿƒ&nbsp;&nbsp; Fast development by rerunning only changed tests.<br> ๐Ÿš€&nbsp;&nbsp; Powered by [esbuild](../../docs/dev-server/plugins/esbuild.md) and [rollup plugins](../../docs/dev-server/plugins/rollup.md) ## Getting started with Web Test Runner This is the minimal instruction on how to start using the web test runner. 1. Install the necessary packages ``` npm i --save-dev @web/test-runner @esm-bundle/chai ``` 2. Add a script to your `package.json` ```json { "scripts": { "test": "web-test-runner \"test/**/*.test.js\" --node-resolve", "test:watch": "web-test-runner \"test/**/*.test.js\" --node-resolve --watch" } } ``` 3. Create a test file `test/sum.test.js`. ```js import { expect } from '@esm-bundle/chai'; import { sum } from '../src/sum.js'; it('sums up 2 numbers', () => { expect(sum(1, 1)).to.equal(2); expect(sum(3, 12)).to.equal(15); }); ``` 4. Create the src file `src/sum.js` ```js export function sum(a, b) { return a + b; } ``` 5. Run it ``` $ npm run test $ web-test-runner test/**/*.test.js --coverage --node-resolve Chrome: |โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 1/1 test files | 1 passed, 0 failed Code coverage: 100 % View full coverage report at coverage/lcov-report/index.html Finished running tests in 0.9s, all tests passed! ๐ŸŽ‰ ``` You can find more detailed instructions in the [Getting Started Guide](../../guides/test-runner/getting-started.md). ## Watch and debug Once you have the basic test running you can enjoy some of the more advanced features, such as `watch` mode. With `watch` mode, the same tests will be run but you get some additional features that help with development and debugging: - Tests are rerun on file change (source or test) - You can focus on a specific test file - You can open a test file in the browser Most of you will probably be familiar with automatic rerunning of tests, but what do we mean with focusing on a specific test file? Focus mode is actually one of the key features when working with many test files. While developing your code, you'll often want to _focus_ on one test file only. With web test runner, you can do this straight from your terminal, to improve your workflow. Start the test runner in watch mode and you will see a menu at the bottom: ``` Finished running tests, watching for file changes... Press F to focus on a test file. Press D to debug in the browser. Press Q to quit watch mode. Press Enter to re-run all tests. ``` Now if you use `F` a menu will present itself with all the files you can focus on ``` [1] test/calc.test.js [2] test/sum.test.js [3] test/multiply.test.js Number of the file to focus: 2 ``` Once a test file is focused you can also open it directly in the browser. You can find more detailed instructions in the [Watch and Debug Guide](../../guides/test-runner/watch-and-debug/index.md). ## Test in multiple browsers using playwright [Playwright](https://github.com/microsoft/playwright) is a great tool by Microsoft that allows us to run tests in all evergreen browsers. If you want to make use of this, you can do so by following these instructions: ``` npm i --save-dev @web/test-runner-playwright ``` This will locally install the required versions of Chromium, Firefox, and WebKit. Once installation is done, we can specify which browsers we want to actually make use of in our `package.json` script: ```json "test": "web-test-runner \"test/**/*.test.js\" --node-resolve --playwright --browsers chromium firefox webkit", ``` Now all we need to do is run our tests: ``` $ npm run test $ web-test-runner "test/**/*.test.js" --node-resolve --playwright --browsers chromium firefox webkit Chromium: |โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 2/2 test files | 3 passed, 0 failed Firefox: |โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 2/2 test files | 3 passed, 0 failed Webkit: |โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 2/2 test files | 3 passed, 0 failed Finished running tests in 3.4s, all tests passed! ๐ŸŽ‰ ``` As you can see, we've executed 2 test files in 3 different real browsers. If all your tests are green you can't get any more confident about your code. So let's ship it! See more instructions in the [Browsers Guide](../../guides/test-runner/browsers.md). ## Testing responsive views With the world going mobile-first there needs to be a way of testing your mobile views. Working with a real browser means you can directly change the viewport. Let's assume we have some code that should only execute on mobile. It would be nice to have some sort of functionality to check for it. You might implement a function called `isMobile()` that returns true/false. ```js describe('isMobile', () => { it('returns true if width < 1024px', async () => { expect(isMobile()).to.be.true; }); it('returns false if width > 1024px', async () => { expect(isMobile()).to.be.false; }); }); ``` Doesn't it feel like something is missing in this test, though? We need to have a way to run these two tests on different viewport sizes to verify if they work correctly. For that we can to install a library: ``` npm i --save-dev @web/test-runner-commands ``` With that, we get a `setViewport` method which we can use. ```js import { expect } from '@esm-bundle/chai'; import { setViewport } from '@web/test-runner-commands'; import { isMobile } from '../src/isMobile'; describe('isMobile', () => { it('returns true if width < 1024px', async () => { await setViewport({ width: 360, height: 640 }); expect(isMobile()).to.be.true; }); it('returns false if width > 1024px', async () => { await setViewport({ width: 1200, height: 640 }); expect(isMobile()).to.be.false; }); }); ``` If you want to know more, like for example how to test CSS media queries see the [Responsive Guide](../../guides/test-runner/responsive.md). See the [commands documentation](../../docs/test-runner/commands.md) to learn more about additional features like emulating media, setting the user agent or writing your own commands. ## Taking code coverage into account Once you have a decent set of tests you may want to look into what could still be improved. Code coverage can help to find which code segments have not yet been tested. Any web-test-runner launcher that works with chromium can provide code coverage. To enable it you add the `--coverage` flag. `package.json`: ```json { "scripts": { "test": "web-test-runner \"test/**/*.test.js\" --node-resolve --coverage" } } ``` See more instructions in the [Code Coverage Guide](../../guides/test-runner/code-coverage/index.md). ## Using TypeScript > Browsers don't support Typescript syntax. Your code will need to be transformed before it is served to the browser, adding extra complexity and compilation time. While typescript can be a powerful addition to your project, we generally don't recommend it for beginners. First, we need to install the required dependencies: ``` npm i --save-dev @web/test-runner @esm-bundle/chai @types/mocha typescript ``` Add the `src/sum.ts` file: ```ts export function sum(...numbers: number[]) { let sum = 0; for (const number of numbers) { sum += number; } return sum; } ``` Add the `test/sum.test.ts` file: ```ts import { expect } from '@esm-bundle/chai'; import { sum } from '../src/sum.js'; it('sums up 2 numbers', () => { expect(sum(1, 1)).to.equal(2); expect(sum(3, 12)).to.equal(15); }); it('sums up 3 numbers', () => { expect(sum(1, 1, 1)).to.equal(3); expect(sum(3, 12, 5)).to.equal(20); }); ``` > Notice that we're using the `.js` extension in our import. With native es modules, file extensions are required so we recommend using them even in Typescript files. The easiest way to use Typescript with the test runner is to use `tsc`, the official typescript compiler. To do this, we first need to add some scripts to our `package.json`: ```json { "scripts": { "test": "web-test-runner \"test/**/*.test.js\" --node-resolve", "build": "tsc" } } ``` To execute you run ``` npm run build npm run test ``` See more instructions in the [Using TypeScript Guide](../../guides/test-runner/using-typescript.md). ## Enable your needs with custom plugins Unfortunately, not every use case will be covered by existing plugins. Therefore if you encounter a situation that requires some custom adjustments you can create a plugin yourself. If you are often using ES modules directly in the browser then `ReferenceError: process is not defined` might sound familiar. Some packages use the global `process.env` variable to check for environment variable. This variable is available in node, but not in the browser. We can, however fake it by writing a custom plugin. Plugins can be added via the configuration file `web-test-runner.config.mjs` and offer various hooks into how code gets found, handled, and served. For our use case the `transform` hook is useful. `web-test-runner.config.mjs` ```js export default { files: 'test/**/*.test.js', nodeResolve: true, plugins: [ { name: 'provide-process', transform(context) { if (context.path === '/') { const transformedBody = context.body.replace( '</head>', '<script>window.process = { env: { NODE_ENV: "development" } }</script></head>', ); return transformedBody; } }, }, ], }; ``` This is only one example and plugins can do way more and if you want to go even more low level you can also write your own koa middleware. See more instructions in the [Writing Plugin Guide](../../guides/test-runner/writing-plugins.md). ## Thanks for reading We are incredibly proud of our first Modern Web Tool, and we hope you find it useful as well. If you find an issue or if you are stuck [please let us know](https://github.com/modernweb-dev/web/issues/new). There is much, much more to come so follow us on [Twitter](https://twitter.com/modern_web_dev) and if you like what you see please consider sponsoring the project on [Open Collective](https://opencollective.com/modern-web). --- <span>Photo by <a href="https://unsplash.com/@lemonvlad">Vladislav Klapin</a> on <a href="https://unsplash.com/s/photos/hello">Unsplash</a></span>
modernweb-dev/web/docs/blog/introducing-web-test-runner/index.md.review/0
{ "file_path": "modernweb-dev/web/docs/blog/introducing-web-test-runner/index.md.review", "repo_id": "modernweb-dev", "token_count": 3792 }
162
# Dev Server >> Plugins >> Esbuild ||3 Plugin for using [esbuild](https://github.com/evanw/esbuild) in Web Dev Server and Web Test Runner. [esbuild](https://github.com/evanw/esbuild) is a blazing fast build tool. It can be used for fast single-file transforms, for example to transform TS, JSX, TSX and JSON to JS, or to transform modern JS to an older version of JS for older browsers. ## Usage Install the package: ``` npm i --save-dev @web/dev-server-esbuild ``` Add the plugin in your configuration file: ```js import { esbuildPlugin } from '@web/dev-server-esbuild'; export default { plugins: [esbuildPlugin({ ts: true, target: 'auto' })], }; ``` ## Single file transforms Note that the esbuild plugin uses the [esbuild single file transform API](https://esbuild.github.io/api/#transform-api), transforming files as they are requested by the browser. We don't use esbuild's bundling API, so some features like module transformation are not available. ## Configuration We expose the following options for esbuild. Most of them are a mirror of the esbuild API, check the esbuild docs to learn more about them. ```ts type Loader = | 'js' | 'jsx' | 'ts' | 'tsx' | 'json' | 'text' | 'base64' | 'file' | 'dataurl' | 'binary'; interface EsbuildPluginArgs { target?: string | string[]; js?: boolean; ts?: boolean; json?: boolean; jsx?: boolean; tsx?: boolean; jsxFactory?: string; jsxFragment?: string; loaders?: Record<string, Loader>; define?: { [key: string]: string }; tsconfig?: string; } ``` ## Target The target option defines what version of javascript to compile down to. This is primarily to support older browsers. ### Auto target We recommended setting target to `auto`, this is the default when you turn on a loader but needs to be enabled explicitly for JS transforms. When target is `auto`, we look at the browser's user agent. If you're on the latest version of a browser that adopts modern javascript syntax at a reasonable pace, we skip any compilation work. The current set of browsers are Chrome, Firefox and Edge. Otherwise we transform the code to a compatible version of javascript specific to that browser. This transformation is very fast. ### Always auto The `auto-always` option looks at the user agent, but doesn't skip the latest versions of modern browsers. It will always compile to a compatible target for that browser. Use this when you're using features not yet supported in the latest version of one of the modern browsers. ### Browser and language target The target option can be set to one or more browser or language targetversions, for example `chrome80` or `es2020`. The property can be an array, so you can set multiple browser targets. While the auto target options are specific to this plugin, the browser and language target come directly from esbuild. [Check the docs](https://github.com/evanw/esbuild) for more information. ### No target If `target` is set to `esnext`, transformation is skipped entirely. ## Loaders Loaders transform different kinds of file formats to JS. The `loaders` option takes a mapping from file extension to loader name: ```js import { esbuildPlugin } from '@web/dev-server-esbuild'; export default { plugins: [esbuildPlugin({ loaders: { '.ts': 'ts', '.data': 'json' } })], }; ``` For a few common loaders, there are boolean options which act like shorthand for setting the file extension and loader. ```js import { esbuildPlugin } from '@web/dev-server-esbuild'; export default { plugins: [ esbuildPlugin({ // shorthand for loaders: { '.ts': 'ts' } ts: true, // shorthand for loaders: { '.json': 'json' } json: true, // shorthand for loaders: { '.jsx': 'jsx' } jsx: true, // shorthand for loaders: { '.tsx': 'tsx' } tsx: true, }), ], }; ``` ## Examples **Typescript:** Transform all .ts files to javascript: ```js esbuildPlugin({ ts: true }); ``` Transform all .ts files to javascript using settings from tsconfig.json. (The `tsconfig.json` file is not read by default.) ```js import { fileURLToPath } from 'url'; esbuildPlugin({ ts: true, tsconfig: fileURLToPath(new URL('./tsconfig.json', import.meta.url)), }); ``` **JSX:** Transform all .jsx files to javascript: ```js esbuildPlugin({ jsx: true }); ``` By default, `jsx` gets transformed to React.createElement calls. You can change this to the JSX style you are using. For example when importing from preact like this: ```js import { h, Fragment } from 'preact'; ``` ```js esbuildPlugin({ jsx: true, jsxFactory: 'h', jsxFragment: 'Fragment' }); ``` If you want to use jsx inside .js files you need to set up a custom loader: ```ts esbuildPlugin({ loaders: { ['.js']: 'jsx' }, jsxFactory: 'h', jsxFragment: 'Fragment' }); ``` **TSX** Transform all .tsx files to javascript: ```js esbuildPlugin({ tsx: true }); esbuildPlugin({ tsx: true, jsxFactory: 'h', jsxFragment: 'Fragment' }); ``` **JS** Transform all JS to older versions of JS: ```js esbuildPlugin({ target: 'auto' }); ``` Transform TS, but don't transform any syntax: ```js esbuildPlugin({ ts: true, target: 'esnext' }); ```
modernweb-dev/web/docs/docs/dev-server/plugins/esbuild.md/0
{ "file_path": "modernweb-dev/web/docs/docs/dev-server/plugins/esbuild.md", "repo_id": "modernweb-dev", "token_count": 1586 }
163
# Storybook Builder ||4
modernweb-dev/web/docs/docs/storybook-builder/index.md/0
{ "file_path": "modernweb-dev/web/docs/docs/storybook-builder/index.md", "repo_id": "modernweb-dev", "token_count": 7 }
164
# Test Runner >> Writing Tests >> JS Tests ||10 Javascript files are loaded by the test framework that is configured. The default test framework is mocha, which loads your test as a standard browser es module. You can use module imports to import your code and any modules you want to use for testing. For example: ```js import { expect } from '@esm-bundle/chai'; import { myFunction } from '../src/myFunction.js'; describe('myFunction', () => { it('adds two numbers together', () => { expect(myFunction(1, 2)).to.equal(3); }); }); ``` See the [Test frameworks](../test-frameworks/index.md) and [es modules](../../../guides/going-buildless/es-modules.md) sections for more information.
modernweb-dev/web/docs/docs/test-runner/writing-tests/js-tests.md/0
{ "file_path": "modernweb-dev/web/docs/docs/test-runner/writing-tests/js-tests.md", "repo_id": "modernweb-dev", "token_count": 204 }
165
# Going Buildless >> Serving ||10 The fundamental relationship at the heart of the web is the relationship between the server and the client or browser (we'll use "browser" and "client" interchangeably for the rest of this article). Every web page is produced by a server and viewed by a browser. There are many different kinds of web servers and many different kinds of web browsers. The client doesn't know everything about the server, and the server cannot control everything about the browser; but the thing they both agree on is to communicate (at least initially) using the [HyperText Transfer Protocol](https://developer.mozilla.org/en-US/docs/Web/HTTP), <dfn><abbr>HTTP</abbr></dfn>. ## Serving Web Content Now that your `GET` request has reached the web server, the server has to parse the URL to determine what to include in the response. So when the request for `GET https://my-domain.dev/` comes in, the web server parses it into three major parts, 1. the protocol `https://`, 2. the domain name `my-domain.dev` 3. the path `/` So this particular request is asking for the entire web root directory since the path part of the URL didn't include any specific file in the request. How does the web server know how to respond? Most web servers when given a request for a directory will look for a special file in that directory named `index.html` and serve that. It's as if the user actually typed `https://my-domain.dev/index.html` into their browser. The simplest kinds of web servers retrieve the file located at the path specified in the URL, relative to the web root. The web root is the directory which that web server is configured to look in for files. For example, the [Apache](https://httpd.apache.org/) web server running on Ubuntu Linux 14.04 looks in `/var/www/html/` by default, whereas the nginx server by some default configurations looks in `/usr/share/nginx/html/`. Just like on your computer, you can have as many pages and folders as you want in the web root ``` / โ””โ”€โ”€ var โ””โ”€โ”€ www โ””โ”€โ”€ html โ”œโ”€โ”€ about โ”‚ โ”œโ”€โ”€ contact.html โ”‚ โ””โ”€โ”€ index.html โ”œโ”€โ”€ index.html โ””โ”€โ”€ help.html ``` This represents the default server root for Apache web server on linux. | Page | Url | File | | -------- | ------------------------------------------ | ---------------------------------- | | Homepage | `https://my-domain.com/` | `/var/www/html/index.html` | | Help | `https://my-domain.com/help.html` | `/var/www/html/help.html` | | About | `https://my-domain.com/about/` | `/var/www/html/about/index.html` | | Contact | `https://my-domain.com/about/contact.html` | `/var/www/html/about/contact.html` | Now if you were to request `https://my-domain.com/main.html`, the server would send back the infamous "404 - File not found" error, since there's no `/main.html` file in the web root. Likewise, if you were to rename `index.html` to `main.html`, then `https://my-domain.com/main.html` would work but `https://my-domain.com/` would give a "404". ### Files Outside the Web Root In the above examples, the server used the default web root `/var/www/html`, but we could also have configured it to use `/var/www/html/about`, e.g. by changing into that directory and starting a server from the command line: ``` cd /var/www/html/about http-server ``` If we did that, though, the server would not be able to read `help.html`. The only files it can serve are: ``` . โ”œโ”€โ”€ contact.html โ””โ”€โ”€ index.html ``` It will be important to keep this in mind when structuring your projects. In a buildless workflow, the web server will need to have all of your dependencies, including `node_modules` in its web root. So if you decide to keep your JavaScript code in a subdirectory of the project root, like `/src`, you will need to keep `index.html` in the root directory and run your local development server from there. Just like how running `http-server` from `/about` made `help.html` inaccessible, running your local development server from `/src` would make `node_modules` inaccessible. ## Link Urls The "HT" in <abbr>HTML</abbr>, "HyperText", refers to the way in which documents can link to other documents. This is the fundamental feature of <abbr>HTML</abbr> and the most important feature of the web. Hyperlinks ("links" for short) in <abbr>HTML</abbr> are represented by the [anchor element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a). The `href` attribute contains the URL which the hyperlink points to. There are three basic types of URLs which you can link to: 1. [Fully-Qualified URLs](#fully-qualified-urls) 2. [Absolute Urls](#absolute-urls) 3. [Relative Urls](#relative-urls) ### Fully Qualified URLs The most specific type of URL is the fully-qualified URL. They contain a protocol; zero, one, or more subdomains; a domain name; and an optional path. They refer specifically to a single, unique resource. Some examples: - `https://www.google.com` - `https://modern-web.dev/guides/going-buildless/serving/` - `ws://demos.kaazing.com/echo` Links with fully qualified URLs can link a page on your server, to pages on another server. This is what puts the "world-wide" in "world-wide-web". All the links to [MDN](https://developer.mozilla.org) in this article are like that. ```html <a href="https://google.com/">if you click me I will open google</a> ``` Because the URL is fully-qualified, adding that `<a>` tag to any page anywhere on the web will have the same behavior[^1], namely opening google's home page. [^1]: Assuming that the page doesn't use JavaScript or other techniques to surreptitiously change the destination of the link ### Absolute URLs Absolute URLs contain only a path, omitting the protocol and origin. They always begin with `/`. Like fully-qualified URLs, they always refer to the same path relative to the origin, for example: ```html <a href="/index.html">Home Page</a> ``` This link will have the same behaviour on all pages on `modern-web.dev`, namely returning to the Modern Web homepage. but if placed on `developer.mozilla.org`, will link to the MDN homepage, not Modern Web's. Absolute links containing _only_ a `/` are special, they refer to the web root. In most cases, they are synonymous with `/index.html`. ### Relative URLs The least specific type of URL is a relative URL. Like absolute URLs, they omit the protocol and origin, but unlike absolute URLs, which contain a full path, relative URLs contain a partial, or relative path. They start with `./`, `../`, or a path to a resource. for example: ```html <a href="../">Go Up</a> <a href="./help.html">Go to Help Page</a> <a href="help.html">Also Go to Help Page</a> ``` Relative URLs are relative to the current document, so they may have different behaviour depending on which page on a website they are used. Given the following folder structure: ``` . โ”œโ”€โ”€ about โ”‚ โ”œโ”€โ”€ index.html โ”‚ โ””โ”€โ”€ contact.html โ”œโ”€โ”€ help.html โ””โ”€โ”€ index.html ``` And the following link tag ```html <a href="index.html">...</a> ``` A link within `help.html` would link to `index.html`. <br> A link within `about/contact.html` would link to `about/index.html`. ## Learn more If you wanna know more check out MDN's [HTML basics](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics).
modernweb-dev/web/docs/guides/going-buildless/serving.md/0
{ "file_path": "modernweb-dev/web/docs/guides/going-buildless/serving.md", "repo_id": "modernweb-dev", "token_count": 2260 }
166
<html> <body> <script type="module"> import { expect } from '../../../../../node_modules/@esm-bundle/chai/esm/chai.js'; import { runTests } from '../../../../../packages/test-runner-mocha/dist/standalone.js'; runTests(() => { describe('basic test', () => { it('works', () => { expect(true).to.equal(true); }); }); }); </script> </body> </html>
modernweb-dev/web/integration/test-runner/tests/basic/browser-tests/basic.test.html/0
{ "file_path": "modernweb-dev/web/integration/test-runner/tests/basic/browser-tests/basic.test.html", "repo_id": "modernweb-dev", "token_count": 203 }
167
import { BrowserLauncher, TestRunnerCoreConfig, TestSession } from '@web/test-runner-core'; import { runTests } from '@web/test-runner-core/test-helpers'; import { legacyPlugin } from '@web/dev-server-legacy'; import { resolve } from 'path'; import { expect } from 'chai'; export function runFocusTest( config: Partial<TestRunnerCoreConfig> & { browsers: BrowserLauncher[] }, ) { describe.skip('focus', async function () { let allSessions: TestSession[]; before(async () => { const result = await runTests({ ...config, // 2 means some are executed concurrently, and some sequentially concurrency: 2, files: [...(config.files ?? []), resolve(__dirname, 'browser-tests', '*.test.js')], plugins: [...(config.plugins ?? []), legacyPlugin()], }); allSessions = result.sessions; }); it.skip('can run tests with focus, concurrently and sequentially', () => { expect(allSessions.every(s => s.passed)).to.equal(true, 'All sessions should have passed'); }); }); }
modernweb-dev/web/integration/test-runner/tests/focus/runFocusTest.ts/0
{ "file_path": "modernweb-dev/web/integration/test-runner/tests/focus/runFocusTest.ts", "repo_id": "modernweb-dev", "token_count": 364 }
168
import { throwErrorA } from './fail-stack-trace-a.js'; it('test 1', () => { throwErrorA(); });
modernweb-dev/web/integration/test-runner/tests/test-failure/browser-tests/fail-stack-trace.test.js/0
{ "file_path": "modernweb-dev/web/integration/test-runner/tests/test-failure/browser-tests/fail-stack-trace.test.js", "repo_id": "modernweb-dev", "token_count": 38 }
169
import * as errorStacks from 'errorstacks'; import path from 'path'; type RawLocation = Pick<errorStacks.StackFrame, 'fileName' | 'line' | 'column'>; interface Location { filePath: string; line: number; column: number; } export interface StackLocation extends Location { browserUrl: string; } export type MapStackLocation = (location: StackLocation) => StackLocation | Promise<StackLocation>; export type MapBrowserUrl = (url: URL) => string; export interface ParseStackTraceOptions { browserRootDir?: string; cwd?: string; mapBrowserUrl?: MapBrowserUrl; mapStackLocation?: MapStackLocation; } // regexp to match a stack track that is only a full address const REGEXP_ADDRESS = /^(http(s)?:\/\/.*)(:\d+)(:\d+)$/; const FILTERED_STACKS = [ '@web/test-runner', '@web/dev-runner', '__web-test-runner__', '__web-dev-server__', ]; const validString = (str: unknown) => typeof str === 'string' && str !== ''; const validNumber = (nr: unknown) => typeof nr === 'number' && nr !== -1; function filterStackFrames(frames: errorStacks.StackFrame[]) { const withoutNative = frames.filter(f => f.type !== 'native'); const withoutInternal = withoutNative.filter( f => !FILTERED_STACKS.some(p => f.fileName.includes(p)), ); return withoutInternal.length > 0 ? withoutInternal : withoutNative; } async function mapLocation( url: URL, loc: RawLocation, mapBrowserUrl: MapBrowserUrl, mapStackLocation: MapStackLocation, ) { const browserUrl = `${url.pathname}${url.search}${url.hash}`; const filePath = mapBrowserUrl(url); return mapStackLocation({ filePath, browserUrl, line: loc.line, column: loc.column, }); } function parseUrl(url: string) { try { return new URL(url, 'http://www.example.org/'); } catch { return undefined; } } async function formatLocation( loc: RawLocation, cwd: string, mapBrowserUrl: MapBrowserUrl, mapStackLocation: MapStackLocation, ): Promise<StackLocation> { const url = parseUrl(loc.fileName); let mappedLocation: StackLocation; if (url) { mappedLocation = await mapLocation(url, loc, mapBrowserUrl, mapStackLocation); } else { // we could not create a browser URL from the stack location, so we don't try to map it mappedLocation = { browserUrl: '', filePath: loc.fileName, line: loc.line, column: loc.column }; } const relativeFileName = path.relative(cwd, mappedLocation.filePath); return { ...mappedLocation, filePath: relativeFileName }; } async function formatFrame( f: errorStacks.StackFrame, cwd: string, mapBrowserUrl: MapBrowserUrl, mapStackLocation: MapStackLocation, ) { if (validString(f.fileName) && validNumber(f.line) && validNumber(f.column)) { const location = `${f.fileName}:${f.line}:${f.column}`; if (validString(f.name)) { return ` at ${f.name} (${location})`; } return ` at ${location}`; } const trimmedRaw = f.raw.trim(); const matchFullAddress = trimmedRaw.match(REGEXP_ADDRESS); if (matchFullAddress) { // frame is only a full browser path (ex. http://localhost:8000/foo/bar.js:1:2) const [, fileName, , line, column] = matchFullAddress; const mappedLocation = await formatLocation( { fileName, line: Number(line), column: Number(column) }, cwd, mapBrowserUrl, mapStackLocation, ); return ` at ${mappedLocation.filePath}:${mappedLocation.line}:${mappedLocation.column}`; } // fallback to raw return ` ${trimmedRaw}`; } export async function parseStackTrace( errorMsg: string, rawStack: string, options: ParseStackTraceOptions = {}, ) { if (rawStack === '' || (rawStack.split('\n').length === 1 && rawStack.includes(errorMsg))) { // there is no track trace, or it's only an error message return undefined; } const defaultCwd = process.cwd(); const { browserRootDir = defaultCwd, cwd = defaultCwd, mapStackLocation = l => l, mapBrowserUrl = p => path.join(browserRootDir, p.pathname.split('/').join(path.sep)), } = options; const allFrames = errorStacks.parseStackTrace(rawStack); const frames = filterStackFrames(allFrames); if (frames.length === 0) { return undefined; } for (const frame of frames) { if (validString(frame.fileName) && validNumber(frame.line) && validNumber(frame.column)) { const l = await formatLocation(frame, cwd, mapBrowserUrl, mapStackLocation); frame.fileName = l.filePath; frame.line = l.line; frame.column = l.column; } } const formattedFrames = await Promise.all( frames.map(f => formatFrame(f, browserRootDir, mapBrowserUrl, mapStackLocation)), ); return formattedFrames.join('\n'); }
modernweb-dev/web/packages/browser-logs/src/parseStackTrace.ts/0
{ "file_path": "modernweb-dev/web/packages/browser-logs/src/parseStackTrace.ts", "repo_id": "modernweb-dev", "token_count": 1608 }
170
const fs = require('fs').promises; /** * @param {string} path */ async function fileExists(path) { try { await fs.access(path); return true; } catch (e) { return false; } } module.exports = { fileExists };
modernweb-dev/web/packages/config-loader/src/utils.js/0
{ "file_path": "modernweb-dev/web/packages/config-loader/src/utils.js", "repo_id": "modernweb-dev", "token_count": 89 }
171
-----BEGIN CERTIFICATE----- MIIFbzCCA1egAwIBAgIUYjUb0QWavs6p/gaKaxCxhHD6nQswDQYJKoZIhvcNAQEL BQAwRzELMAkGA1UEBhMCQVUxDDAKBgNVBAgMA3dlYjEMMAoGA1UEBwwDZGV2MQ0w CwYDVQQKDARUZXN0MQ0wCwYDVQQLDARUZXN0MB4XDTIzMDIxNDIzNDkwMloXDTI0 MDIxNDIzNDkwMlowRzELMAkGA1UEBhMCQVUxDDAKBgNVBAgMA3dlYjEMMAoGA1UE BwwDZGV2MQ0wCwYDVQQKDARUZXN0MQ0wCwYDVQQLDARUZXN0MIICIjANBgkqhkiG 9w0BAQEFAAOCAg8AMIICCgKCAgEAo2o+5wB4QdfmafKY0vXsCSOkXpbiU0TTdedF vCrUajQnKsksE3yKL9ct0oZFm9IEILdL6rE1hd45mdkNZC5nS/Oro0a6KDyPDnNh EN8L2NLdmm2k9JVgtSHhsjAnn7yhZPE84nX+zvoszoErGA0LKmRqsdDqt9FT/dBT tQPwP5bgj+GS5OxxEcVfUp2+FiPkFA8kZcN7NSSaF+CctDB3ZmjSF3Nqp+rUVHuY 5d4WqPLB7S+Tl0vSXjrwwbQSdW7xr4cYa+kEr2KYa4E9MysUCJzggSqrXa4OvqnG Mu/plqWpmnU23wdbz2gaQbL5hEv4cvTZqqAesHBprOTTKLJsI6r/Pun2fcpHeYMy RP+ZvQnllRz2crs2QUlDGArNvt+cgX6FiV7VWIhZg7yK/DrJTTP4oP5M63+zjDYa FcXHld+5zWweukgt6fBN4QbDGGI+o+i6LyDGrrmxUa2S9zjzt4BacehySrtmeSVS qGai5Mm3ef0mc0y1Ld6XCY01UMPhslxLFD55lV4OBgzP+BM00ErDIkOvNlryaVqu uBNC9H7SsQ507DKetOdLTij3xJ7pCoS+tel5BRSMluyN6v7bS9TOwb6EIEF3Ff3F KxJAPHqEux+ipn8rytUvz8AMZOVKKdLdqTdpKdSPQW8FTtbAamxbLjxBSKYMm2rb nIAv+nUCAwEAAaNTMFEwHQYDVR0OBBYEFP8IvDK1+18YqNPSPov01kc92vUlMB8G A1UdIwQYMBaAFP8IvDK1+18YqNPSPov01kc92vUlMA8GA1UdEwEB/wQFMAMBAf8w DQYJKoZIhvcNAQELBQADggIBAFLfeElEM3AyAYOuILykyWcSy1VcvTcc0QkiRbN2 gSit/IcF3unjYe0jZnI8G7iFAtYhlNsfCFV1K9l8pVrp5m4nUMGKx5xEfrapedA3 hplVvOkVJknUgkj+KRytiO32y05/Qp2glteBVqvDz3hPmaBEDFwRAxLbT3hTMK+/ K984GC3Ebwy2j6IoHvkReuH/8dRDep4ObjlQGkRkXtEnO2uqPishZL+CRBdvf6wP LlNVDPdhjkyoloDq7P5H+Mx8fmuwXavhSHcDv3S07eFEAtrceGzjFC5zS/cIMdG7 qXjvqfBkfoWCMI7TDhkisrsEgwooJ5YqjD0Z4ZhwpynSKVDXufDhOw7zzO9er5Cw i8XKHvuFY/xFKJ234Jb4zHkf9YplgJkStAQZtbqDaNnHNi+fUNPPLNAxUJEZYrjw ISovb87CnOsbnyKfxVhNIcyPtR/LRQMNkiUh8Hhm4kHsDWMntCTe4hphER9tH9ZD bmvg7SXA/SwTldZ6/1KWfjsCc/aa3A8tViWT0BKKTWX1i3hNfcPNYfM+T/UOPNDd IowvTPmdW3YrCErZcvVKXGc6625QewoAhg4vzWL8GQAFXqLO3ofQrgLD7sfWa6XT HxzMgYWx9JIa0OXJeTkoMvJo94QxMtqezAsQ0L6X3TU/wBThCigkaZK6edZVTq2S VNHS -----END CERTIFICATE-----
modernweb-dev/web/packages/dev-server-core/.self-signed-dev-server-ssl.cert/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/.self-signed-dev-server-ssl.cert", "repo_id": "modernweb-dev", "token_count": 1452 }
172
import LRUCache from 'lru-cache'; import { FSWatcher } from 'chokidar'; import fs from 'fs'; import { promisify } from 'util'; import { RequestCancelledError } from '../utils.js'; const fsStat = promisify(fs.stat); async function fileExists(filePath: string) { try { const stat = await fsStat(filePath); return stat.isFile(); } catch { return false; } } interface CacheEntry { body: string; headers: Record<string, string>; filePath: string; } /** * Cache for file transformations. */ export class PluginTransformCache { private cacheKeysPerFilePath = new Map<string, Set<string>>(); private lruCache: LRUCache<string, CacheEntry>; constructor(private fileWatcher: FSWatcher, private rootDir: string) { this.lruCache = new LRUCache<string, CacheEntry>({ sizeCalculation: (e, key) => e.body.length + (key ? key.length : 0), maxSize: 52428800, noDisposeOnSet: true, dispose: (_value, cacheKey) => { // remove file path -> url mapping when we are no longer caching it for (const [filePath, cacheKeysForFilePath] of this.cacheKeysPerFilePath.entries()) { if (cacheKeysForFilePath.has(cacheKey)) { this.cacheKeysPerFilePath.delete(filePath); return; } } }, }); // remove file from cache on change const removeCacheListener = (filePath: string) => { const cacheKeys = this.cacheKeysPerFilePath.get(filePath); if (cacheKeys) { for (const cacheKey of cacheKeys) { this.lruCache.delete(cacheKey); } } }; fileWatcher.addListener('change', removeCacheListener); fileWatcher.addListener('unlink', removeCacheListener); } async get(cacheKey: string) { return this.lruCache.get(cacheKey); } async set(filePath: string, body: string, headers: Record<string, string>, cacheKey: string) { try { if (!(await fileExists(filePath))) { // only cache files on the file system return; } if (typeof body === 'string') { let cacheKeysForFilePath = this.cacheKeysPerFilePath.get(filePath); if (!cacheKeysForFilePath) { cacheKeysForFilePath = new Set(); this.cacheKeysPerFilePath.set(filePath, cacheKeysForFilePath); } cacheKeysForFilePath.add(cacheKey); this.lruCache.set(cacheKey, { body, headers, filePath }); } } catch (error) { if (error instanceof RequestCancelledError) { // no need to do anything if the request was cancelled return; } throw error; } } }
modernweb-dev/web/packages/dev-server-core/src/middleware/PluginTransformCache.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/src/middleware/PluginTransformCache.ts", "repo_id": "modernweb-dev", "token_count": 1019 }
173
import { DevServerCoreConfig } from './DevServerCoreConfig.js'; import { transformModuleImportsPlugin } from '../plugins/transformModuleImportsPlugin.js'; import { webSocketsPlugin } from '../web-sockets/webSocketsPlugin.js'; import { mimeTypesPlugin } from '../plugins/mimeTypesPlugin.js'; import { Logger } from '../logger/Logger.js'; export function addPlugins(logger: Logger, config: DevServerCoreConfig) { if (!config.plugins) { config.plugins = []; } if (config.mimeTypes && Object.keys(config.mimeTypes).length > 0) { config.plugins.unshift(mimeTypesPlugin(config.mimeTypes)); } if (config.injectWebSocket && config.plugins?.some(pl => pl.injectWebSocket)) { config.plugins.unshift(webSocketsPlugin()); } if (config.plugins?.some(pl => 'resolveImport' in pl || 'transformImport' in pl)) { // transform module imports must happen after all other plugins did their regular transforms config.plugins.push(transformModuleImportsPlugin(logger, config.plugins, config.rootDir)); } }
modernweb-dev/web/packages/dev-server-core/src/server/addPlugins.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/src/server/addPlugins.ts", "repo_id": "modernweb-dev", "token_count": 320 }
174
import express from 'express'; import http from 'http'; import Koa from 'koa'; import { Server } from 'net'; import { FSWatcher } from 'chokidar'; import { expect } from 'chai'; import portfinder from 'portfinder'; import { Stub, stubMethod } from 'hanbi'; import { ServerStartParams } from '../../src/plugins/Plugin.js'; import { DevServer } from '../../src/server/DevServer.js'; import { createTestServer } from '../helpers.js'; describe('basic', () => { let host: string; let server: DevServer; beforeEach(async () => { ({ host, server } = await createTestServer()); }); afterEach(() => { server.stop(); }); it('returns static files', async () => { const response = await fetch(`${host}/index.html`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.include('<title>My app</title>'); }); it('returns hidden files', async () => { const response = await fetch(`${host}/.hidden`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.include('this file is hidden'); }); it('returns files in a folder', async () => { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.equal('Hello world!'); }); it('returns a 404 for unknown files', async () => { const response = await fetch(`${host}/non-existing.js`); expect(response.status).to.equal(404); }); it('sets no-cache header', async () => { const response = await fetch(`${host}/index.html`); expect(response.status).to.equal(200); expect(response.headers.get('cache-control')).to.equal('no-cache'); }); }); it('can configure the hostname', async () => { const { server, host } = await createTestServer({ hostname: 'localhost' }); const response = await fetch(`${host}/index.html`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.include('<title>My app</title>'); server.stop(); }); describe('http2', () => { before(() => { // Turn off the TLS authorized check in node.js so that we don't reject the network response // based off the fact it has a self-signed certificate. // // A better way to achive this might be to _somehow_ load up the certificate used into the // testing process so that we aren't just turning off the TLS/SSL certificate validation. process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; }); after(() => { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1'; }); it('serves a website', async () => { const { server, host } = await createTestServer({ hostname: 'localhost', http2: true }); const response = await fetch(`${host}/index.html`); const responseText = await response.text(); // It's a bit of a shame that we can't verify that the response was delivered with a http/2 // protocol. It would be good to have a extra assertion here. Something like: // // expect(response.protocol).to.equal('http2'); expect(response.status).to.equal(200); expect(responseText).to.include('<title>My app</title>'); server.stop(); }); }); it('can run in middleware mode', async () => { const { server: wdsServer } = await createTestServer({ middlewareMode: true }); expect(wdsServer.server).to.equal(undefined); const app = express(); let httpServer: http.Server; const port = await portfinder.getPortPromise({ port: 9000 }); await new Promise( resolve => (httpServer = app.listen(port, 'localhost', () => { resolve(undefined); })), ); app.use(wdsServer.koaApp.callback()); const response = await fetch(`http://localhost:${port}/index.html`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.include('<title>My app</title>'); httpServer!.close(); }); it('can run multiple servers in parallel', async () => { const results = [ await createTestServer(), await createTestServer(), await createTestServer(), await createTestServer(), await createTestServer(), ]; for (const result of results) { const response = await fetch(`${result.host}/index.html`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.include('<title>My app</title>'); result.server.stop(); } }); it('can add extra middleware', async () => { const { server, host } = await createTestServer({ middleware: [ async ctx => { if (ctx.path === '/foo') { ctx.body = 'response from middleware'; return; } }, ], }); const response = await fetch(`${host}/foo`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.include('response from middleware'); server.stop(); }); it('calls serverStart on plugin hook on start', async () => { let startArgs: ServerStartParams; const { server } = await createTestServer({ plugins: [ { name: 'test', serverStart(args) { startArgs = args; }, }, ], }); expect(startArgs!).to.exist; expect(startArgs!.app).to.be.an.instanceOf(Koa); expect(startArgs!.server).to.be.an.instanceOf(Server); expect(startArgs!.fileWatcher).to.be.an.instanceOf(FSWatcher); expect(startArgs!.config).to.be.an('object'); server.stop(); }); it('calls serverStop on plugin hook on stop', async () => { let stopCalled = false; const { server } = await createTestServer({ plugins: [ { name: 'test', serverStop() { stopCalled = true; }, }, ], }); await server.stop(); expect(stopCalled).to.be.true; }); it('waits on server start hooks before starting', async () => { let aFinished = false; let bFinished = false; const { server } = await createTestServer({ plugins: [ { name: 'test-a', serverStart() { return new Promise(resolve => setTimeout(() => { aFinished = true; resolve(); }, 5), ); }, }, { name: 'test-b', serverStart() { return new Promise(resolve => setTimeout(() => { bFinished = true; resolve(); }, 10), ); }, }, ], }); expect(aFinished).to.be.true; expect(bFinished).to.be.true; server.stop(); }); describe('disableFileWatcher', () => { /** * Extracted setup to ensure `fileWatcher.add` is called when * `disableFileWatch = false`. Only then there is confidence that the * `disableFileWatch = true` actually works. * */ const setupDisableFileWatch = async (config: { disableFileWatcher: boolean }) => { let fileWatchStub: Stub<FSWatcher['add']>; const { host, server } = await createTestServer({ disableFileWatcher: config.disableFileWatcher, plugins: [ { name: 'watcher-stub', serverStart({ fileWatcher }) { fileWatchStub = stubMethod(fileWatcher, 'add'); }, }, ], }); // @ts-ignore if (!fileWatchStub) { throw new Error('Something went wrong with stubbing the file watcher'); } // Ensure something is fetched to trigger all the middlewares await fetch(`${host}/index.html`); return { fileWatchStub, host, server }; }; it('disables file watch when true', async () => { const { fileWatchStub, server } = await setupDisableFileWatch({ disableFileWatcher: true }); expect(fileWatchStub.callCount).to.equal(0); server.stop(); }); it('leaves file watch in tact when false', async () => { const { fileWatchStub, server } = await setupDisableFileWatch({ disableFileWatcher: false }); expect(fileWatchStub.callCount).to.gt(0); server.stop(); }); });
modernweb-dev/web/packages/dev-server-core/test/server/DevServer.test.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/test/server/DevServer.test.ts", "repo_id": "modernweb-dev", "token_count": 2939 }
175
// this file is autogenerated with the generate-mjs-dts-entrypoints script import cjsEntrypoint from './dist/index.js'; const { esbuildPlugin } = cjsEntrypoint; export { esbuildPlugin };
modernweb-dev/web/packages/dev-server-esbuild/index.mjs/0
{ "file_path": "modernweb-dev/web/packages/dev-server-esbuild/index.mjs", "repo_id": "modernweb-dev", "token_count": 59 }
176
import { html } from 'lit-html'; import { BaseElement } from './BaseElement.js'; class TodoItem extends BaseElement { get styles() { return html` <style> .message { color: blue; } </style> `; } get template() { return html` <div> <input type="checkbox" .checked=${!!this.checked} @change=${this._onCheckedChanged} /> <span class="message">${this.message}</span> </div> `; } set checked(value) { this._checked = !!value; this.update(); } get checked() { return this._checked; } set message(value) { this._message = value; this.update(); } get message() { return this._message; } _onCheckedChanged(e) { this.dispatchEvent(new CustomEvent('checked-changed', { detail: e.target.checked })); } } customElements.define('todo-item', TodoItem); if (import.meta.hot) { import.meta.hot.accept(() => {}); }
modernweb-dev/web/packages/dev-server-hmr/demo/lit-html/src/todo-item.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server-hmr/demo/lit-html/src/todo-item.js", "repo_id": "modernweb-dev", "token_count": 390 }
177
import { join } from 'path'; import { fileURLToPath } from 'url'; import { importMapsPlugin } from '../index.mjs'; export default { rootDir: fileURLToPath(join(import.meta.url, '..', '..', '..', '..')), plugins: [ importMapsPlugin({ inject: { include: '**/*.html', importMap: { imports: { 'chai/': '/node_modules/chai/', hanbi: '/node_modules/hanbi/lib/main.js', '@web/test-runner-mocha': '/packages/test-runner-mocha/dist/standalone.js', '@esm-bundle/chai': '/node_modules/@esm-bundle/chai/esm/chai.js', }, }, }, }), ], };
modernweb-dev/web/packages/dev-server-import-maps/test-browser/web-test-runner.config.mjs/0
{ "file_path": "modernweb-dev/web/packages/dev-server-import-maps/test-browser/web-test-runner.config.mjs", "repo_id": "modernweb-dev", "token_count": 314 }
178
import { Context } from '@web/dev-server-core'; import { getAttribute, getTextContent, remove } from '@web/dev-server-core/dist/dom5'; import { parse, serialize, Document as DocumentAst, Node as NodeAst } from 'parse5'; import { injectPolyfillsLoader as originalInjectPolyfillsLoader, PolyfillsConfig, fileTypes, getScriptFileType, GeneratedFile, File, } from '@web/polyfills-loader'; import { PARAM_TRANSFORM_SYSTEMJS } from './constants.js'; import { findJsScripts } from './findJsScripts.js'; function findScripts(indexUrl: string, documentAst: DocumentAst) { const scriptNodes = findJsScripts(documentAst); const files: File[] = []; const inlineScripts: GeneratedFile[] = []; const inlineScriptNodes: NodeAst[] = []; scriptNodes.forEach((scriptNode, i) => { const type = getScriptFileType(scriptNode); let src = getAttribute(scriptNode, 'src'); if (!src) { const suffix = type === 'module' ? `&${PARAM_TRANSFORM_SYSTEMJS}=true` : ''; src = `inline-script-${i}.js?source=${encodeURIComponent(indexUrl)}${suffix}`; inlineScripts.push({ path: src, type, content: getTextContent(scriptNode), }); inlineScriptNodes.push(scriptNode); } else if (type === 'module') { const separator = src.includes('?') ? '&' : '?'; src = `${src}${separator}${PARAM_TRANSFORM_SYSTEMJS}=true`; } files.push({ type, path: src, }); }); return { files, inlineScripts, scriptNodes, inlineScriptNodes }; } export interface ReturnValue { htmlPath: string; indexHTML: string; inlineScripts: GeneratedFile[]; polyfills: GeneratedFile[]; } /** * transforms index.html, extracting any modules and import maps and adds them back * with the appropriate polyfills, shims and a script loader so that they can be loaded * at the right time */ export async function injectPolyfillsLoader( context: Context, polyfills?: boolean | PolyfillsConfig, ): Promise<ReturnValue> { const documentAst = parse(context.body as string); const { files, inlineScripts, scriptNodes } = findScripts(context.url, documentAst); const polyfillsLoaderConfig = { modern: { files: files.map(f => ({ ...f, type: f.type === fileTypes.MODULE ? fileTypes.SYSTEMJS : f.type, })), }, polyfills: polyfills === false ? { regeneratorRuntime: 'always' as const } : { coreJs: true, regeneratorRuntime: 'always' as const, fetch: true, abortController: true, webcomponents: true, ...(polyfills === true ? {} : polyfills), }, preload: false, }; // we will inject a loader, so we need to remove the inline script nodes as the loader // will include them as virtual modules for (const scriptNode of scriptNodes) { // remove script from document remove(scriptNode); } const result = await originalInjectPolyfillsLoader(serialize(documentAst), polyfillsLoaderConfig); return { htmlPath: context.url, indexHTML: result.htmlString, inlineScripts, polyfills: result.polyfillFiles, }; }
modernweb-dev/web/packages/dev-server-legacy/src/injectPolyfillsLoader.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-legacy/src/injectPolyfillsLoader.ts", "repo_id": "modernweb-dev", "token_count": 1159 }
179
// this file is autogenerated with the generate-mjs-dts-entrypoints script import cjsEntrypoint from './dist/index.js'; const { nodeResolve, fromRollup, rollupAdapter, rollupBundlePlugin } = cjsEntrypoint; export { nodeResolve, fromRollup, rollupAdapter, rollupBundlePlugin };
modernweb-dev/web/packages/dev-server-rollup/index.mjs/0
{ "file_path": "modernweb-dev/web/packages/dev-server-rollup/index.mjs", "repo_id": "modernweb-dev", "token_count": 87 }
180
import bc from './src/b.js'; import d from './src/foo/d.js'; export default `a ${bc} ${d}`;
modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/bundle-basic/a.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/bundle-basic/a.js", "repo_id": "modernweb-dev", "token_count": 40 }
181
const foo = require('./default-export'); module.exports = foo;
modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/commonjs/modules/require-default.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/commonjs/modules/require-default.js", "repo_id": "modernweb-dev", "token_count": 21 }
182
/// <reference types="../../../types/rollup__plugin-babel" /> import rollupBabel from '@rollup/plugin-babel'; import { createTestServer, fetchText, expectIncludes } from '../test-helpers.js'; import { fromRollup } from '../../../src/index.js'; const babel = fromRollup(rollupBabel); describe('@rollup/plugin-alias', () => { it('can resolve imports', async () => { const { server, host } = await createTestServer({ plugins: [ { name: 'test', serve(context) { if (context.path === '/app.js') { return 'const foo = html`bar ${foo} foo`'; } }, }, babel({ babelHelpers: 'inline', plugins: [require.resolve('@babel/plugin-transform-template-literals')], }), ], }); try { const text = await fetchText(`${host}/app.js`); expectIncludes(text, 'function _taggedTemplateLiteral('); expectIncludes(text, '_taggedTemplateLiteral(["bar ", " foo"])'); expectIncludes(text, 'html(_templateObject'); } finally { server.stop(); } }); });
modernweb-dev/web/packages/dev-server-rollup/test/node/plugins/babel.test.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/plugins/babel.test.ts", "repo_id": "modernweb-dev", "token_count": 477 }
183
import { readStorybookConfig } from '../shared/config/readStorybookConfig.js'; import { validatePluginConfig } from '../shared/config/validatePluginConfig.js'; import { createRollupConfig } from './rollup/createRollupConfig.js'; import { buildAndWrite } from './rollup/buildAndWrite.js'; import { createManagerHtml } from '../shared/html/createManagerHtml.js'; import { createPreviewHtml } from '../shared/html/createPreviewHtml.js'; import { findStories } from '../shared/stories/findStories.js'; import { StorybookPluginConfig } from '../shared/config/StorybookPluginConfig.js'; import { StorybookConfig } from '../shared/config/StorybookConfig.js'; interface BuildPreviewParams { type: string; storybookConfig: StorybookConfig; pluginConfig: StorybookPluginConfig; outputDir: string; rootDir: string; } async function buildPreview(params: BuildPreviewParams) { const { type, storybookConfig, pluginConfig, outputDir, rootDir } = params; const { storyImports, storyFilePaths } = await findStories( rootDir, storybookConfig.mainJsPath, storybookConfig.mainJs.stories, ); const previewHtml = createPreviewHtml(pluginConfig, storybookConfig, rootDir, storyImports); let config = createRollupConfig({ type, outputDir, indexFilename: 'iframe.html', indexHtmlString: previewHtml, storyFilePaths, }); if (storybookConfig.mainJs.rollupConfig) { config = (await storybookConfig.mainJs.rollupConfig(config)) ?? config; } await buildAndWrite(config); } interface BuildmanagerParams { type: string; storybookConfig: StorybookConfig; outputDir: string; rootDir: string; } async function buildManager(params: BuildmanagerParams) { const managerHtml = createManagerHtml(params.storybookConfig, params.rootDir); const config = createRollupConfig({ type: params.type, outputDir: params.outputDir, indexFilename: 'index.html', indexHtmlString: managerHtml, }); await buildAndWrite(config); } export interface BuildParams { type: 'web-components' | 'preact'; outputDir: string; configDir: string; } export async function build(params: BuildParams) { const { type, outputDir } = params; const rootDir = process.cwd(); validatePluginConfig(params); const storybookConfig = await readStorybookConfig(params); await buildManager({ type, outputDir, storybookConfig, rootDir }); await buildPreview({ type, storybookConfig, pluginConfig: params, outputDir, rootDir }); }
modernweb-dev/web/packages/dev-server-storybook/src/build/build.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-storybook/src/build/build.ts", "repo_id": "modernweb-dev", "token_count": 765 }
184
import { createRequire } from 'node:module'; import mdx from '@mdx-js/mdx'; import { transformAsync } from '@babel/core'; // @ts-ignore import { createCompiler } from '@storybook/csf-tools/mdx.js'; import { createError } from '../utils.js'; const require = createRequire(import.meta.url); const compilers = [createCompiler({})]; export async function transformMdxToCsf(body: string, filePath: string): Promise<string> { // turn MDX to JSX const jsx = ` import { React, mdx } from '@web/storybook-prebuilt/web-components.js'; ${await mdx(body, { compilers, filepath: filePath })} `; // turn JSX to JS const babelResult = await transformAsync(jsx, { filename: filePath, sourceMaps: true, plugins: [require.resolve('@babel/plugin-transform-react-jsx')], }); if (!babelResult?.code) { throw createError(`Something went wrong while transforming ${filePath}`); } // rewrite imports let result = babelResult.code.replace( /@storybook\/addon-docs\/blocks/g, '@web/storybook-prebuilt/addon-docs/blocks.js', ); result = result.replace( /@storybook\/addon-docs/g, '@web/storybook-prebuilt/addon-docs/blocks.js', ); return result; }
modernweb-dev/web/packages/dev-server-storybook/src/shared/mdx/transformMdxToCsf.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-storybook/src/shared/mdx/transformMdxToCsf.ts", "repo_id": "modernweb-dev", "token_count": 435 }
185
import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const indexPath = path.resolve(__dirname, 'virtual-files', 'index.html'); function createServeHtmlPlugin() { return { serverStart({ fileWatcher }) { fileWatcher.add(indexPath); }, serve(context) { if (['/', '/index.html'].includes(context.path)) { return { body: fs.readFileSync(indexPath, 'utf-8'), type: 'html' }; } }, }; } export default { rootDir: resolve(fileURLToPath(import.meta.url), '..', '..', '..'), plugins: [createServeHtmlPlugin()], };
modernweb-dev/web/packages/dev-server/demo/plugin-serve/config.mjs/0
{ "file_path": "modernweb-dev/web/packages/dev-server/demo/plugin-serve/config.mjs", "repo_id": "modernweb-dev", "token_count": 250 }
186
// this file is autogenerated with the generate-mjs-dts-entrypoints script import cjsEntrypoint from './dist/index.js'; const { startDevServer, mergeConfigs, DevServerStartError, esbuildPlugin, nodeResolvePlugin } = cjsEntrypoint; export { startDevServer, mergeConfigs, DevServerStartError, esbuildPlugin, nodeResolvePlugin };
modernweb-dev/web/packages/dev-server/index.mjs/0
{ "file_path": "modernweb-dev/web/packages/dev-server/index.mjs", "repo_id": "modernweb-dev", "token_count": 97 }
187
import { Plugin } from '@web/dev-server-core'; import debounce from 'debounce'; export function watchPlugin(): Plugin { return { name: 'watch', injectWebSocket: true, serverStart({ fileWatcher, webSockets }) { if (!webSockets) { throw new Error('Cannot use watch mode when web sockets are disabled.'); } function onFileChanged() { webSockets!.sendImport('data:text/javascript,window.location.reload()'); } const onChange = debounce(onFileChanged, 100); fileWatcher.addListener('change', onChange); fileWatcher.addListener('unlink', onChange); }, }; }
modernweb-dev/web/packages/dev-server/src/plugins/watchPlugin.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server/src/plugins/watchPlugin.ts", "repo_id": "modernweb-dev", "token_count": 231 }
188
// @ts-nocheck if (!('json' in Response)) { Response.json = function (data, options = {}) { const headers = new Headers(); headers.set('Content-Type', 'application/json'); if (options.headers) { Object.entries(options.headers).forEach(([key, value]) => { headers.set(key, value); }); } return new Response(JSON.stringify(data), { ...options, headers, }); }; }
modernweb-dev/web/packages/mocks/polyfills.js/0
{ "file_path": "modernweb-dev/web/packages/mocks/polyfills.js", "repo_id": "modernweb-dev", "token_count": 169 }
189
export * from './dist/index.js';
modernweb-dev/web/packages/parse5-utils/index.d.ts/0
{ "file_path": "modernweb-dev/web/packages/parse5-utils/index.d.ts", "repo_id": "modernweb-dev", "token_count": 12 }
190
import { Element } from 'parse5'; import { getAttribute } from '@web/parse5-utils'; import crypto from 'crypto'; import { FileType, PolyfillsLoaderConfig } from './types.js'; export const noModuleSupportTest = "!('noModule' in HTMLScriptElement.prototype)"; export const fileTypes: Record<'SCRIPT' | 'MODULE' | 'MODULESHIM' | 'SYSTEMJS', FileType> = { SCRIPT: 'script', MODULE: 'module', MODULESHIM: 'module-shim', SYSTEMJS: 'systemjs', }; export function createContentHash(content: string) { return crypto.createHash('md5').update(content).digest('hex'); } export function cleanImportPath(importPath: string) { if (importPath.startsWith('/')) { return importPath; } if (importPath.startsWith('../') || importPath.startsWith('./')) { return importPath; } return `./${importPath}`; } export function getScriptFileType(script: Element): FileType { return getAttribute(script, 'type') === 'module' ? fileTypes.MODULE : fileTypes.SCRIPT; } export function hasFileOfType(cfg: PolyfillsLoaderConfig, type: FileType) { return ( cfg.modern?.files.some(f => f.type === type) || (cfg.legacy && cfg.legacy.some(e => e.files.some(f => f.type === type))) ); }
modernweb-dev/web/packages/polyfills-loader/src/utils.ts/0
{ "file_path": "modernweb-dev/web/packages/polyfills-loader/src/utils.ts", "repo_id": "modernweb-dev", "token_count": 411 }
191
const path = require('path'); const { expect } = require('chai'); const rollup = require('rollup'); const { copy } = require('../src/copy.js'); describe('rollup-plugin-copy', () => { it('adds files to rollup', async () => { const bundle = await rollup.rollup({ input: path.resolve(__dirname, './fixture/index.js'), plugins: [copy({ patterns: '**/*.svg', rootDir: path.resolve(__dirname, './fixture/') })], }); const { output } = await bundle.generate({ format: 'es' }); expect(output.length).to.equal(5); expect(output.map(x => x.fileName).filter(x => x.endsWith('.svg'))).to.have.members([ 'a.svg', 'b.svg', `sub${path.sep}sub-a.svg`, `sub${path.sep}sub-b.mark.svg`, ]); }); });
modernweb-dev/web/packages/rollup-plugin-copy/test/integration.test.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-copy/test/integration.test.js", "repo_id": "modernweb-dev", "token_count": 314 }
192
const html = require('../../dist/index').default; module.exports = { input: 'demo/spa/index.html', output: { dir: './demo/dist', }, plugins: [html({ absoluteBaseUrl: 'http://localhost:8000' })], };
modernweb-dev/web/packages/rollup-plugin-html/demo/spa/rollup.config.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/demo/spa/rollup.config.js", "repo_id": "modernweb-dev", "token_count": 86 }
193
import path from 'path'; import { parse, serialize } from 'parse5'; import { extractModules } from './extractModules.js'; import { extractAssets } from './extractAssets.js'; export interface ExtractParams { html: string; htmlFilePath: string; rootDir: string; extractAssets: boolean; externalAssets?: string | string[]; absolutePathPrefix?: string; } export function extractModulesAndAssets(params: ExtractParams) { const { html, htmlFilePath, rootDir, externalAssets, absolutePathPrefix } = params; const htmlDir = path.dirname(htmlFilePath); const document = parse(html); // extract functions mutate the AST const { moduleImports, inlineModules } = extractModules({ document, htmlDir, rootDir, absolutePathPrefix, }); const assets = params.extractAssets ? extractAssets({ document, htmlDir, htmlFilePath, rootDir, externalAssets, absolutePathPrefix, }) : []; // turn mutated AST back to a string const updatedHtmlString = serialize(document); return { moduleImports, inlineModules, assets, htmlWithoutModules: updatedHtmlString }; }
modernweb-dev/web/packages/rollup-plugin-html/src/input/extract/extractModulesAndAssets.ts/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/src/input/extract/extractModulesAndAssets.ts", "repo_id": "modernweb-dev", "token_count": 389 }
194
<svg xmlns="http://www.w3.org/2000/svg">x</svg>
modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/assets/foo.svg/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/assets/foo.svg", "repo_id": "modernweb-dev", "token_count": 26 }
195
/* no module script file */
modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/assets/no-module.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/assets/no-module.js", "repo_id": "modernweb-dev", "token_count": 7 }
196
console.log('hello world');
modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/basic/src/foo.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/basic/src/foo.js", "repo_id": "modernweb-dev", "token_count": 8 }
197
#a { background-image: url("images/star.svg"); } #b { background-image: url("images/star.svg#foo"); } #c { background-image: url("images/star.png"); } #d { background-image: url("images/star.jpg"); } #e { background-image: url("images/star.jpeg"); } #f { background-image: url("images/star.webp"); } #g { background-image: url("images/star.gif"); } #h { background-image: url("images/star.avif"); }
modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/resolves-assets-in-styles-images/styles.css/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/resolves-assets-in-styles-images/styles.css", "repo_id": "modernweb-dev", "token_count": 166 }
198
console.log('foo');
modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/foo/foo.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/foo/foo.js", "repo_id": "modernweb-dev", "token_count": 7 }
199
<h1>hey there</h1>
modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/pure-index2.html/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/pure-index2.html", "repo_id": "modernweb-dev", "token_count": 11 }
200
/* eslint-disable @typescript-eslint/ban-ts-comment */ // @ts-nocheck module.exports = require('./rollup-plugin-import-meta-assets');
modernweb-dev/web/packages/rollup-plugin-import-meta-assets/src/index.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/src/index.js", "repo_id": "modernweb-dev", "token_count": 51 }
201
const nameFour = 'four-name'; const imageFour = new URL(new URL('assets/four-lJVunLww.svg', import.meta.url).href, import.meta.url).href; export { imageFour, nameFour };
modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/snapshots/four-bundle.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/snapshots/four-bundle.js", "repo_id": "modernweb-dev", "token_count": 60 }
202
import { expect, test } from '@playwright/test'; import { Manager } from './manager.js'; import { Preview } from './preview.js'; /** @type import('./manager.js').Manager */ let manager; /** @type import('./preview.js').Preview */ let preview; test.describe('all in one', () => { test.beforeEach(async ({ page }) => { await page.goto('/'); manager = new Manager(page); preview = new Preview(page); }); test('renders test story', async ({ page }) => { await expect(page).toHaveTitle(/^Test \/ Stories - Test Story/); expect(await preview.storyParent().innerHTML()).toContain('<div>Test Story works</div>'); }); test('renders core manager toolbar', async () => { await expect(manager.toolbarItemByTitle('Remount component')).toBeVisible(); await expect(manager.toolbarItemByTitle('Zoom in')).toBeVisible(); await expect(manager.toolbarItemByTitle('Zoom out')).toBeVisible(); await expect(manager.toolbarItemByTitle('Reset zoom')).toBeVisible(); }); test('renders @storybook/addon-backgrounds toolbar', async () => { await expect(manager.toolbarItemByTitle('Change the background of the preview')).toBeVisible(); await expect(manager.toolbarItemByTitle('Apply a grid to the preview')).toBeVisible(); }); test('renders @storybook/addon-viewport toolbar', async () => { await expect(manager.toolbarItemByTitle('Change the size of the preview')).toBeVisible(); }); test('renders @storybook/addon-measure toolbar', async () => { await expect(manager.toolbarItemByTitle('Enable measure')).toBeVisible(); }); test('renders @storybook/addon-outline toolbar', async () => { await expect(manager.toolbarItemByTitle('Apply outlines to the preview')).toBeVisible(); }); test('renders @storybook/addon-a11y toolbar', async () => { await expect(manager.toolbarItemByTitle('Vision simulator')).toBeVisible(); }); test('renders @storybook/addon-controls panel', async () => { const panelButton = manager.panelButtonByText('Controls'); await panelButton.click(); await expect(panelButton).toHaveClass(/tabbutton-active/); }); test('renders @storybook/addon-actions panel', async () => { const panelButton = manager.panelButtonByText('Actions'); await panelButton.click(); await expect(panelButton).toHaveClass(/tabbutton-active/); }); test('renders @storybook/addon-interactions panel', async () => { const panelButton = manager.panelButtonByText('Interactions'); await panelButton.click(); await expect(panelButton).toHaveClass(/tabbutton-active/); }); test('renders @storybook/addon-a11y panel', async () => { const panelButton = manager.panelButtonByText('Accessibility'); await panelButton.click(); await expect(panelButton).toHaveClass(/tabbutton-active/); }); });
modernweb-dev/web/packages/storybook-framework-web-components/tests/all-in-one.spec.js/0
{ "file_path": "modernweb-dev/web/packages/storybook-framework-web-components/tests/all-in-one.spec.js", "repo_id": "modernweb-dev", "token_count": 898 }
203
// this file is autogenerated with the generate-mjs-dts-entrypoints script import cjsEntrypoint from './dist/index.js'; const { browserstackLauncher } = cjsEntrypoint; export { browserstackLauncher };
modernweb-dev/web/packages/test-runner-browserstack/index.mjs/0
{ "file_path": "modernweb-dev/web/packages/test-runner-browserstack/index.mjs", "repo_id": "modernweb-dev", "token_count": 61 }
204
export default 'moduleFeaturesA';
modernweb-dev/web/packages/test-runner-browserstack/test-remote/fixtures/module-features-a.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner-browserstack/test-remote/fixtures/module-features-a.js", "repo_id": "modernweb-dev", "token_count": 8 }
205
{ "name": "@web/test-runner-commands", "version": "0.9.0", "publishConfig": { "access": "public" }, "description": "Web test runner commands", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/modernweb-dev/web.git", "directory": "packages/test-runner-commands" }, "author": "modern-web", "homepage": "https://github.com/modernweb-dev/web/tree/master/packages/test-runner-commands", "main": "browser/commands.mjs", "exports": { ".": { "types": "./browser/commands.d.ts", "default": "./browser/commands.mjs" }, "./plugins": { "types": "./plugins.d.ts", "import": "./plugins.mjs", "require": "./dist/index.js" } }, "engines": { "node": ">=18.0.0" }, "scripts": { "build": "tsc", "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test --watch-ignore **/*.snap.js" }, "files": [ "*.d.ts", "*.js", "*.mjs", "browser", "dist", "src" ], "keywords": [ "web", "test", "runner", "testrunner", "commands" ], "dependencies": { "@web/test-runner-core": "^0.13.0", "mkdirp": "^1.0.4" }, "devDependencies": { "@web/test-runner-chrome": "^0.16.0", "@web/test-runner-playwright": "^0.11.0", "@web/test-runner-webdriver": "^0.8.0", "mocha": "^10.2.0" } }
modernweb-dev/web/packages/test-runner-commands/package.json/0
{ "file_path": "modernweb-dev/web/packages/test-runner-commands/package.json", "repo_id": "modernweb-dev", "token_count": 686 }
206
/* eslint-env browser */ import '../../../node_modules/chai/chai.js'; export const expect = window.chai.expect; export const assert = window.chai.assert;
modernweb-dev/web/packages/test-runner-commands/test/chai.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner-commands/test/chai.js", "repo_id": "modernweb-dev", "token_count": 53 }
207
import { sendMouse, resetMouse } from '../../browser/commands.mjs'; import { expect } from '../chai.js'; function spyEvent() { let events = []; const callback = event => events.push(event); callback.getEvents = () => events; callback.getLastEvent = () => events[events.length - 1]; callback.resetHistory = () => { events = []; }; return callback; } before(() => { // The native context menu needs to be prevented from opening at least in WebKit // where it doesn't get automatically closed that, in turn, blocks the next `mouseup` event. document.addEventListener('contextmenu', event => { event.preventDefault(); }); }); describe('sendMouse', () => { let element, x, y; beforeEach(() => { element = document.createElement('div'); element.style.width = '100px'; element.style.height = '100px'; element.style.margin = '100px'; x = 150; // Horizontal middle of the element. y = 150; // Vertical middle of the element. document.body.appendChild(element); }); afterEach(() => { element.remove(); }); describe('move', () => { let spy; beforeEach(() => { spy = spyEvent(); document.addEventListener('mousemove', spy); }); afterEach(() => { document.removeEventListener('mousemove', spy); }); it('can move mouse to a position', async () => { await sendMouse({ type: 'move', position: [x, y] }); expect(spy.getLastEvent()).to.include({ x, y }); }); }); describe('click', () => { let spy; beforeEach(async () => { spy = spyEvent(); element.addEventListener('mousedown', spy); element.addEventListener('mouseup', spy); await sendMouse({ type: 'move', position: [0, 0] }); }); it('can click the left mouse button', async () => { await sendMouse({ type: 'click', position: [x, y], button: 'left' }); expect(spy.getEvents()).to.have.lengthOf(2); expect(spy.getEvents()[0]).to.include({ type: 'mousedown', button: 0, x, y }); expect(spy.getEvents()[1]).to.include({ type: 'mouseup', button: 0, x, y }); }); it('should click the left mouse button by default', async () => { await sendMouse({ type: 'click', position: [x, y] }); expect(spy.getEvents()).to.have.lengthOf(2); expect(spy.getEvents()[0]).to.include({ type: 'mousedown', button: 0, x, y }); expect(spy.getEvents()[1]).to.include({ type: 'mouseup', button: 0, x, y }); }); it('can click the middle mouse button', async () => { await sendMouse({ type: 'click', position: [x, y], button: 'middle' }); expect(spy.getEvents()).to.have.lengthOf(2); expect(spy.getEvents()[0]).to.include({ type: 'mousedown', button: 1, x, y }); expect(spy.getEvents()[1]).to.include({ type: 'mouseup', button: 1, x, y }); }); it('can click the right mouse button', async () => { await sendMouse({ type: 'click', position: [x, y], button: 'right' }); expect(spy.getEvents()).to.have.lengthOf(2); expect(spy.getEvents()[0]).to.include({ type: 'mousedown', button: 2, x, y }); expect(spy.getEvents()[1]).to.include({ type: 'mouseup', button: 2, x, y }); }); }); describe('down and up', () => { let spy; beforeEach(async () => { spy = spyEvent(); element.addEventListener('mousedown', spy); element.addEventListener('mouseup', spy); await sendMouse({ type: 'move', position: [x, y] }); }); it('can down and up the left mouse button', async () => { await sendMouse({ type: 'down', button: 'left' }); expect(spy.getEvents()).to.have.lengthOf(1); expect(spy.getEvents()[0]).to.include({ type: 'mousedown', button: 0, x, y }); spy.resetHistory(); await sendMouse({ type: 'up', button: 'left' }); expect(spy.getEvents()).to.have.lengthOf(1); expect(spy.getEvents()[0]).to.include({ type: 'mouseup', button: 0, x, y }); }); it('should down and up the left mouse button by default', async () => { await sendMouse({ type: 'down' }); expect(spy.getEvents()).to.have.lengthOf(1); expect(spy.getEvents()[0]).to.include({ type: 'mousedown', button: 0, x, y }); spy.resetHistory(); await sendMouse({ type: 'up' }); expect(spy.getEvents()).to.have.lengthOf(1); expect(spy.getEvents()[0]).to.include({ type: 'mouseup', button: 0, x, y }); }); it('can down and up the middle mouse button', async () => { await sendMouse({ type: 'down', button: 'middle' }); expect(spy.getEvents()).to.have.lengthOf(1); expect(spy.getEvents()[0]).to.include({ type: 'mousedown', button: 1, x, y }); spy.resetHistory(); await sendMouse({ type: 'up', button: 'middle' }); expect(spy.getEvents()).to.have.lengthOf(1); expect(spy.getEvents()[0]).to.include({ type: 'mouseup', button: 1, x, y }); }); it('can down and up the right mouse button', async () => { await sendMouse({ type: 'down', button: 'right' }); expect(spy.getEvents()).to.have.lengthOf(1); expect(spy.getEvents()[0]).to.include({ type: 'mousedown', button: 2, x, y }); spy.resetHistory(); await sendMouse({ type: 'up', button: 'right' }); expect(spy.getEvents()).to.have.lengthOf(1); expect(spy.getEvents()[0]).to.include({ type: 'mouseup', button: 2, x, y }); }); }); }); describe('resetMouse', () => { let spy; beforeEach(() => { spy = spyEvent(); document.addEventListener('mouseup', spy); document.addEventListener('mousemove', spy); }); afterEach(() => { document.addEventListener('mouseup', spy); document.removeEventListener('mousemove', spy); }); it('can reset mouse', async () => { await sendMouse({ type: 'move', position: [100, 100] }); await sendMouse({ type: 'down', button: 'left' }); await sendMouse({ type: 'down', button: 'right' }); await sendMouse({ type: 'down', button: 'middle' }); spy.resetHistory(); await resetMouse(); expect(spy.getEvents()).to.have.lengthOf(4); expect(spy.getEvents()[0]).to.include({ type: 'mouseup', button: 0 }); expect(spy.getEvents()[1]).to.include({ type: 'mouseup', button: 1 }); expect(spy.getEvents()[2]).to.include({ type: 'mouseup', button: 2 }); expect(spy.getEvents()[3]).to.include({ type: 'mousemove', x: 0, y: 0 }); }); });
modernweb-dev/web/packages/test-runner-commands/test/send-mouse/browser-test.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner-commands/test/send-mouse/browser-test.js", "repo_id": "modernweb-dev", "token_count": 2434 }
208
/* eslint-env browser, es2020 */ /** @typedef {import('../dist/index').TestResultError} TestResultError */ /** @typedef {import('../dist/index').TestResult} TestResult */ /** @typedef {import('../dist/index').TestSuiteResult} TestSuiteResult */ import { sendMessage } from '/__web-dev-server__web-socket.js'; const PARAM_SESSION_ID = 'wtr-session-id'; const PARAM_TEST_FILE = 'wtr-test-file'; const PARAM_IMPORT_MAP = 'wds-import-map'; let finished = false; const testFile = new URL(window.location.href).searchParams.get(PARAM_TEST_FILE); const sessionId = new URL(window.location.href).searchParams.get(PARAM_SESSION_ID); if (typeof sessionId !== 'string' && typeof testFile !== 'string') { throw new Error(`Could not find any session id or test filequery parameter.`); } if (!window.__WTR_CONFIG__) { const message = 'Could not find any config defined by the test runner. Are your dependencies up to date?'; sessionFailed({ message }); throw new Error(message); } // TODO: make this sync export async function getConfig() { try { const config = window.__WTR_CONFIG__; const url = new URL(import.meta.url); // pass on import map parameter to test files, this special cases a specific plugin // which is not ideal const importMapId = url.searchParams.get(PARAM_IMPORT_MAP); if (importMapId == null) { return config; } const separator = config.testFile.includes('?') ? '&' : '?'; return { ...config, testFile: `${config.testFile}${separator}${PARAM_IMPORT_MAP}=${importMapId}`, }; } catch (err) { await sessionFailed({ name: err ? err.name : undefined, message: `Failed to fetch test config: ${err ? err.message : 'Unknown error'}`, stack: err ? err.stack : undefined, }); throw err; } } export function sessionFailed(error) { return sessionFinished({ userAgent: window.navigator.userAgent, passed: false, errors: [ // copy references because an Error instance cannot be turned into JSON { name: error.name, message: error.message, stack: error.stack, expected: error.expected, actual: error.actual, }, ], }); } export async function sessionStarted() { if (!sessionId) { // don't send anything if we're debugging manually return; } await sendMessage({ type: 'wtr-session-started', sessionId, testFile }); } export async function sessionFinished(result) { if (!sessionId) { // don't send anything if we're debugging manually return; } if (finished) { return; } finished = true; const fullResult = { // some browser launchers set browser logs here logs: window.__wtr_browser_logs__ ? window.__wtr_browser_logs__.logs : [], errors: [], ...result, }; await sendMessage({ type: 'wtr-session-finished', userAgent: window.navigator.userAgent, sessionId, testFile, result: fullResult, }); }
modernweb-dev/web/packages/test-runner-core/browser/session.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner-core/browser/session.js", "repo_id": "modernweb-dev", "token_count": 1062 }
209
export { CoverageMapData } from 'istanbul-lib-coverage'; import * as constants from './utils/constants.js'; export { constants }; export { BrowserLauncher, SessionResult } from './browser-launcher/BrowserLauncher.js'; export { Reporter, ReportTestResultsArgs, GetTestProgressArgs, ReporterArgs, TestRunArgs, TestRunStartedArgs, TestRunFinishedArgs, } from './reporter/Reporter.js'; export { TestRunner } from './runner/TestRunner.js'; export { TestRunnerCli } from './cli/TestRunnerCli.js'; export { BufferedLogger } from './cli/BufferedLogger.js'; export { TestRunnerPlugin } from './server/TestRunnerPlugin.js'; export { TestFramework } from './test-framework/TestFramework.js'; export { TestRunnerCoreConfig, CoverageConfig, CoverageThresholdConfig, } from './config/TestRunnerCoreConfig.js'; export { TestRunnerGroupConfig } from './config/TestRunnerGroupConfig.js'; export { TestCoverage } from './coverage/getTestCoverage.js'; export { Logger, ErrorWithLocation } from './logger/Logger.js'; export { TestSession, TestResultError, TestResult, TestSuiteResult, } from './test-session/TestSession.js'; export { DebugTestSession } from './test-session/DebugTestSession.js'; export { BasicTestSession } from './test-session/BasicTestSession.js'; export { TestSessionManager } from './test-session/TestSessionManager.js'; export { TestSessionStatus, SESSION_STATUS } from './test-session/TestSessionStatus.js'; export { EventEmitter } from './utils/EventEmitter.js'; export { isTestFilePath } from './utils/isTestFilePath.js'; export { fetchSourceMap } from './utils/fetchSourceMap.js';
modernweb-dev/web/packages/test-runner-core/src/index.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-core/src/index.ts", "repo_id": "modernweb-dev", "token_count": 497 }
210
import { deserialize, MapStackLocation } from '@web/browser-logs'; import { MapBrowserUrl } from '@web/browser-logs'; import { TestRunnerCoreConfig } from '../../../config/TestRunnerCoreConfig.js'; import { TestSession } from '../../../test-session/TestSession.js'; import { mapAsync } from '../../../utils/async.js'; interface BrowserLog { type: string; args: string[]; } async function parseBrowserLog( browserLog: BrowserLog, mapBrowserUrl: MapBrowserUrl, mapStackLocation: MapStackLocation, config: TestRunnerCoreConfig, ) { const browserRootDir = config.rootDir; const args = await mapAsync(browserLog.args, arg => deserialize(arg, { browserRootDir, mapBrowserUrl, mapStackLocation }), ); return { type: browserLog.type, args }; } export async function parseBrowserLogs( config: TestRunnerCoreConfig, mapBrowserUrl: MapBrowserUrl, mapStackLocation: MapStackLocation, result: Partial<TestSession>, ) { if (!result.logs) { return; } const browserLogs = result.logs as any as BrowserLog[]; const logsWithType = await mapAsync(browserLogs, b => parseBrowserLog(b, mapBrowserUrl, mapStackLocation, config), ); const logs: any[][] = []; for (const log of logsWithType) { if (!config.filterBrowserLogs || config.filterBrowserLogs(log, result)) { logs.push(log.args); } } result.logs = logs; }
modernweb-dev/web/packages/test-runner-core/src/server/plugins/api/parseBrowserLogs.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-core/src/server/plugins/api/parseBrowserLogs.ts", "repo_id": "modernweb-dev", "token_count": 448 }
211
/** * Wraps a Promise with a timeout, rejecing the promise with the timeout. */ export function withTimeout<T>( promise: Promise<T> | void, message: string, timeout: number, ): Promise<T> { return new Promise<T>((resolve, reject) => { if (!(promise instanceof Promise)) { (resolve as any)(); return; } const timeoutId = setTimeout(() => { reject(new Error(message)); }, timeout); promise .then(val => { resolve(val); }) .catch(err => { reject(err); }) .finally(() => { clearTimeout(timeoutId); }); }); } /** * Iterates iterable, executes each function in parallel and awaits * all function return values */ export async function forEachAsync<T>( it: Iterable<T>, fn: (t: T) => void | Promise<void>, ): Promise<void> { const result: (void | Promise<void>)[] = []; for (const e of it) { result.push(fn(e)); } await Promise.all(result); } /** * Iterates iterable, executes each function in parallel and awaits * all function return values returning the awaited result */ export function mapAsync<T, R>(it: Iterable<T>, fn: (t: T) => R | Promise<R>): Promise<R[]> { const result: (R | Promise<R>)[] = []; for (const e of it) { result.push(fn(e)); } return Promise.all(result); }
modernweb-dev/web/packages/test-runner-core/src/utils/async.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-core/src/utils/async.ts", "repo_id": "modernweb-dev", "token_count": 494 }
212
import { expect } from 'chai'; import * as hanbi from 'hanbi'; import { BrowserLauncher } from '../../../src/browser-launcher/BrowserLauncher.js'; import { TestRunnerCoreConfig } from '../../../src/config/TestRunnerCoreConfig.js'; import { TestScheduler } from '../../../src/runner/TestScheduler.js'; import { TestSession } from '../../../src/test-session/TestSession.js'; import { TestSessionManager } from '../../../src/test-session/TestSessionManager.js'; import { SESSION_STATUS } from '../../../src/test-session/TestSessionStatus.js'; function timeout(ms = 0): Promise<void> { return new Promise(r => setTimeout(r, ms)); } interface BrowserStubs { stop: hanbi.Stub<Exclude<BrowserLauncher['stop'], undefined>>; startDebugSession: hanbi.Stub<BrowserLauncher['startDebugSession']>; startSession: hanbi.Stub<BrowserLauncher['startSession']>; stopSession: hanbi.Stub<BrowserLauncher['stopSession']>; isActive: hanbi.Stub<BrowserLauncher['isActive']>; getBrowserUrl: hanbi.Stub<BrowserLauncher['getBrowserUrl']>; } describe('TestScheduler', () => { let mockConfig: TestRunnerCoreConfig; function createSession(session: Partial<TestSession>): TestSession { return { ...session, testFile: `test-${session.id}.js`, status: SESSION_STATUS.SCHEDULED, } as Partial<TestSession> as TestSession; } function createBrowserStub(name: string): [BrowserStubs, BrowserLauncher] { const spies = { stop: hanbi.spy(), startDebugSession: hanbi.spy(), startSession: hanbi.spy(), stopSession: hanbi.spy(), isActive: hanbi.spy(), getBrowserUrl: hanbi.spy(), }; spies.stop.returns(timeout(1)); spies.startDebugSession.returns(timeout(1)); spies.startSession.returns(timeout(1)); spies.stopSession.returns(timeout(1).then(() => ({ testCoverage: {} }))); spies.isActive.returns(true); spies.getBrowserUrl.returns(''); return [ spies, { name, type: name, stop: spies.stop.handler, startDebugSession: spies.startDebugSession.handler, startSession: spies.startSession.handler, stopSession: spies.stopSession.handler, isActive: spies.isActive.handler, getBrowserUrl: spies.getBrowserUrl.handler, }, ]; } beforeEach(() => { mockConfig = { rootDir: process.cwd(), logger: { ...console, error(...args) { console.error(...args); }, logSyntaxError(error) { console.error(error); }, }, protocol: 'http:', hostname: 'localhost', port: 8000, concurrentBrowsers: 2, concurrency: 2, browserStartTimeout: 1000, testsStartTimeout: 1000, testsFinishTimeout: 1000, } as Partial<TestRunnerCoreConfig> as TestRunnerCoreConfig; }); function createTestFixture( ...ids: string[] ): [TestScheduler, TestSessionManager, TestSession[], BrowserStubs] { const [browserStubs, browser] = createBrowserStub('a'); const sessions: TestSession[] = []; for (const id of ids) { const session = createSession({ id, browser }); sessions.push(session); } const sessionManager = new TestSessionManager([], sessions); const scheduler = new TestScheduler(mockConfig, sessionManager, [browser]); return [scheduler, sessionManager, sessions, browserStubs]; } describe('single browser', () => { it('scheduling a session starts the browser and marks initializing', async () => { const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); scheduler.schedule(1, [session1]); const finalSession1 = sessions.get(session1.id)!; expect(finalSession1.status).to.equal(SESSION_STATUS.INITIALIZING); expect(stubs.startSession.callCount).to.equal(1); }); it('when a session goes to status test finished, the browser is stopped and results is stored', async () => { const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); const testCoverage = {}; stubs.stopSession.returns(timeout(1).then(() => ({ testCoverage }))); scheduler.schedule(1, [session1]); await timeout(2); sessions.updateStatus({ ...session1, passed: true }, SESSION_STATUS.TEST_FINISHED); await timeout(4); const finalSession1 = sessions.get(session1.id)!; expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); expect(finalSession1.passed).to.equal(true); expect(finalSession1.testCoverage).to.equal(testCoverage); }); it('batches test execution', async () => { const [scheduler, sessions, sessionsToSchedule] = createTestFixture('1', '2', '3'); scheduler.schedule(1, sessionsToSchedule); expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.INITIALIZING); expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.INITIALIZING); expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.SCHEDULED); // wait for browser to start, session 3 should still not be started await timeout(2); expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.SCHEDULED); // mark tests as finished sessions.updateStatus({ ...sessions.get('1')!, passed: true }, SESSION_STATUS.TEST_FINISHED); sessions.updateStatus({ ...sessions.get('2')!, passed: true }, SESSION_STATUS.TEST_FINISHED); // wait for browser to end await timeout(4); // sessions 1 and 2 should be finished expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.FINISHED); expect(sessions.get('1')!.passed).to.be.true; expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.FINISHED); expect(sessions.get('2')!.passed).to.be.true; // session 3 should be started expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.INITIALIZING); }); it('scheduling new tests while executing keeps batching', async () => { const sessionIds = ['1', '2', '3', '4', '5', '6']; const [scheduler, sessions, sessionsToSchedule] = createTestFixture(...sessionIds); // schedule 2 sessions scheduler.schedule(1, sessionsToSchedule.slice(0, 2)); expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.INITIALIZING); expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.INITIALIZING); // schedule 3 more sessions after browser starts await timeout(4); scheduler.schedule(1, sessionsToSchedule.slice(2, 5)); expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.INITIALIZING); expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.INITIALIZING); expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.SCHEDULED); expect(sessions.get('4')!.status).to.equal(SESSION_STATUS.SCHEDULED); expect(sessions.get('5')!.status).to.equal(SESSION_STATUS.SCHEDULED); // mark first test as finished sessions.updateStatus({ ...sessions.get('1')!, passed: true }, SESSION_STATUS.TEST_FINISHED); // wait for browser to end await timeout(4); // session 1 is finished, session 2 is still waiting, session 3 is now starting and the rest is still scheduled expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.FINISHED); expect(sessions.get('1')!.passed).to.be.true; expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.INITIALIZING); expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.INITIALIZING); expect(sessions.get('4')!.status).to.equal(SESSION_STATUS.SCHEDULED); expect(sessions.get('5')!.status).to.equal(SESSION_STATUS.SCHEDULED); // mark 2 and 3 as finished await timeout(2); sessions.updateStatus({ ...sessions.get('2')!, passed: true }, SESSION_STATUS.TEST_FINISHED); sessions.updateStatus({ ...sessions.get('3')!, passed: true }, SESSION_STATUS.TEST_FINISHED); // 2 and 3 finish when browser closes await timeout(2); expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.FINISHED); expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.FINISHED); }); it('error while starting browser marks session as failed', async () => { const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); stubs.startSession.callsFake(() => Promise.reject(new Error('mock error'))); scheduler.schedule(1, [session1]); await timeout(4); const finalSession1 = sessions.get(session1.id)!; expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); expect(finalSession1.passed).to.equal(false); expect(finalSession1.errors.length).to.equal(1); expect(finalSession1.errors[0].message).to.equal('mock error'); }); it('error while starting browser after a session changed state gets logged', async () => { const errorStub = hanbi.stubMethod(mockConfig.logger, 'error'); const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); stubs.startSession.returns( timeout(5).then(() => { throw new Error('mock error'); }), ); scheduler.schedule(1, [session1]); await timeout(1); sessions.updateStatus({ ...session1, passed: true }, SESSION_STATUS.TEST_FINISHED); await timeout(2); const finalSession1 = sessions.get(session1.id)!; expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); expect(finalSession1.passed).to.equal(true); await timeout(20); expect(errorStub.callCount).to.equal(1); expect(errorStub.getCall(0).args[0]).to.an.instanceof(Error); expect((errorStub.getCall(0).args[0] as Error).message).to.equal('mock error'); }); it('error while stopping browser marks session as failed', async () => { const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); stubs.stopSession.callsFake(() => Promise.reject(new Error('mock error'))); scheduler.schedule(1, [session1]); await timeout(2); sessions.updateStatus({ ...session1, passed: true }, SESSION_STATUS.TEST_FINISHED); await timeout(4); const finalSession1 = sessions.get(session1.id)!; expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); expect(finalSession1.passed).to.equal(false); expect(finalSession1.errors.length).to.equal(1); expect(finalSession1.errors[0].message).to.equal('mock error'); }); it('timeout starting the browser marks the session as failed', async () => { mockConfig.browserStartTimeout = 2; const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); stubs.startSession.returns(timeout(4)); scheduler.schedule(1, [session1]); await timeout(3); const finalSession1 = sessions.get(session1.id)!; expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); expect(finalSession1.passed).to.equal(false); expect(finalSession1.errors.length).to.equal(1); expect(finalSession1.errors[0].message).to.equal( 'The browser was unable to create and start a test page after 2ms. You can increase this timeout with the browserStartTimeout option.', ); }); it('timeout starting the tests marks the session as failed', async () => { mockConfig.testsStartTimeout = 2; const [scheduler, sessions, [session1]] = createTestFixture('1'); scheduler.schedule(1, [session1]); await timeout(20); const finalSession1 = sessions.get(session1.id)!; expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); expect(finalSession1.passed).to.equal(false); expect(finalSession1.errors.length).to.equal(1); expect(finalSession1.errors[0].message).to.equal( 'Browser tests did not start after 2ms You can increase this timeout with the testsStartTimeout option. Check the browser logs or open the browser in debug mode for more information.', ); }); it('timeout finishing the tests marks the session as failed', async () => { mockConfig.testsFinishTimeout = 2; const [scheduler, sessions, [session1]] = createTestFixture('1'); scheduler.schedule(1, [session1]); await timeout(1); sessions.updateStatus({ ...session1, passed: true }, SESSION_STATUS.TEST_STARTED); await timeout(4); const finalSession1 = sessions.get(session1.id)!; expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); expect(finalSession1.passed).to.equal(false); expect(finalSession1.errors.length).to.equal(1); expect(finalSession1.errors[0].message).to.equal( 'Browser tests did not finish within 2ms. You can increase this timeout with the testsFinishTimeout option. Check the browser logs or open the browser in debug mode for more information.', ); }); }); describe('multi browsers', () => { function createTestFixture( fixtures: { name: string; ids: string[] }[], ): [TestScheduler, TestSessionManager, Array<[BrowserStubs, BrowserLauncher]>, TestSession[]] { const browsers: Array<[BrowserStubs, BrowserLauncher]> = []; const sessions: TestSession[] = []; for (const fixture of fixtures) { const [stubs, browser] = createBrowserStub(fixture.name); browsers.push([stubs, browser]); for (const id of fixture.ids) { const session = createSession({ id, browser }); sessions.push(session); } } const sessionManager = new TestSessionManager([], sessions); const scheduler = new TestScheduler( mockConfig, sessionManager, browsers.map(b => b[1]), ); return [scheduler, sessionManager, browsers, sessions]; } it('can schedule sessions on multiple browsers', async () => { const [scheduler, sessionManager, browsers, sessions] = createTestFixture([ { name: 'a', ids: ['1', '2', '3'] }, { name: 'b', ids: ['4', '5', '6'] }, { name: 'c', ids: ['7', '8', '9'] }, ]); scheduler.schedule(1, sessions); const session1 = sessionManager.get('1')!; const session2 = sessionManager.get('2')!; const session3 = sessionManager.get('3')!; expect(session1.browser).to.equal(browsers[0][1]); expect(session2.browser).to.equal(browsers[0][1]); expect(session3.browser).to.equal(browsers[0][1]); expect(session1.status).to.equal(SESSION_STATUS.INITIALIZING); expect(session2.status).to.equal(SESSION_STATUS.INITIALIZING); expect(session3.status).to.equal(SESSION_STATUS.SCHEDULED); expect(browsers[0][0].startSession.callCount).to.equal(2); const session4 = sessionManager.get('4')!; const session5 = sessionManager.get('5')!; const session6 = sessionManager.get('6')!; expect(session4.browser).to.equal(browsers[1][1]); expect(session5.browser).to.equal(browsers[1][1]); expect(session6.browser).to.equal(browsers[1][1]); expect(session4.status).to.equal(SESSION_STATUS.INITIALIZING); expect(session5.status).to.equal(SESSION_STATUS.INITIALIZING); expect(session6.status).to.equal(SESSION_STATUS.SCHEDULED); expect(browsers[1][0].startSession.callCount).to.equal(2); const session7 = sessionManager.get('7')!; const session8 = sessionManager.get('8')!; const session9 = sessionManager.get('9')!; expect(session7.browser).to.equal(browsers[2][1]); expect(session8.browser).to.equal(browsers[2][1]); expect(session9.browser).to.equal(browsers[2][1]); expect(session7.status).to.equal(SESSION_STATUS.SCHEDULED); expect(session8.status).to.equal(SESSION_STATUS.SCHEDULED); expect(session9.status).to.equal(SESSION_STATUS.SCHEDULED); expect(browsers[2][0].startSession.called).to.equal(false); }); it('finishing a test schedules a new one', async () => { const [scheduler, sessionManager, browsers, sessions] = createTestFixture([ { name: 'a', ids: ['1', '2', '3'] }, { name: 'b', ids: ['4', '5', '6'] }, { name: 'c', ids: ['7', '8', '9'] }, ]); scheduler.schedule(1, sessions); await timeout(1); sessionManager.updateStatus({ ...sessions[0], passed: true }, SESSION_STATUS.TEST_FINISHED); await timeout(4); const session3 = sessionManager.get('3')!; expect(session3.browser).to.equal(browsers[0][1]); expect(session3.status).to.equal(SESSION_STATUS.INITIALIZING); expect(browsers[0][0].startSession.callCount).to.equal(3); }); it('overflow of concurrency budget does not trigger a new browser to start', async () => { const [scheduler, sessionManager, browsers, sessions] = createTestFixture([ { name: 'a', ids: ['1', '2', '3'] }, { name: 'b', ids: ['4', '5', '6'] }, { name: 'c', ids: ['7', '8', '9'] }, ]); scheduler.schedule(1, sessions); await timeout(2); sessionManager.updateStatus({ ...sessions[0], passed: true }, SESSION_STATUS.TEST_FINISHED); sessionManager.updateStatus({ ...sessions[1], passed: true }, SESSION_STATUS.TEST_FINISHED); await timeout(4); const session7 = sessionManager.get('7')!; expect(session7.browser).to.equal(browsers[2][1]); expect(session7.status).to.equal(SESSION_STATUS.SCHEDULED); expect(browsers[2][0].startSession.called).to.equal(false); }); it('finishing one browsers schedules a new browser', async () => { const [scheduler, sessionManager, browsers, sessions] = createTestFixture([ { name: 'a', ids: ['1', '2', '3'] }, { name: 'b', ids: ['4', '5', '6'] }, { name: 'c', ids: ['7', '8', '9'] }, ]); scheduler.schedule(1, sessions); await timeout(2); sessionManager.updateStatus({ ...sessions[0], passed: true }, SESSION_STATUS.TEST_FINISHED); sessionManager.updateStatus({ ...sessions[1], passed: true }, SESSION_STATUS.TEST_FINISHED); await timeout(2); sessionManager.updateStatus({ ...sessions[2], passed: true }, SESSION_STATUS.TEST_FINISHED); await timeout(4); const session7 = sessionManager.get('7')!; expect(session7.browser).to.equal(browsers[2][1]); expect(session7.status).to.equal(SESSION_STATUS.INITIALIZING); expect(browsers[2][0].startSession.callCount).to.equal(2); }); }); });
modernweb-dev/web/packages/test-runner-core/test/src/runner/TestScheduler.test.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-core/test/src/runner/TestScheduler.test.ts", "repo_id": "modernweb-dev", "token_count": 7172 }
213
import 'array-flat-polyfill'; import path from 'path'; import fs from 'fs'; import { Reporter, TestResult, TestSession, TestSuiteResult } from '@web/test-runner-core'; import XML from 'xml'; export interface JUnitReporterArgs { outputPath?: string; reportLogs?: boolean; /* package root dir. defaults to cwd */ rootDir?: string; } type TestSessionMetadata = Omit<TestSession, 'tests'>; type TestResultWithMetadata = TestResult & TestSessionMetadata & { suiteName: string }; // Browser name is highly dynamic, hence `string` type TestResultsWithMetadataByBrowserTestFileName = Record<string, TestResultWithMetadata[]>; interface TestFailureXMLElement { _cdata?: string | string[]; _attr: { message: string; type: string; }; } interface TestCaseXMLAttributes { _attr: { name: string; time: number; file: string; line?: string; classname: string; }; } type PassedTestCase = TestCaseXMLAttributes; type SkippedTestCase = [TestCaseXMLAttributes, { skipped: null }]; type FailedTestCase = [TestCaseXMLAttributes, { failure: TestFailureXMLElement }]; interface TestCaseXMLElement { testcase: PassedTestCase | SkippedTestCase | FailedTestCase; } type TestSuitePropertiesXMLElement = { property: { _attr: { name: string; value: string; }; }; }; interface TestSuiteXMLAttributes { _attr: { name: string; id: number; tests: number; skipped: number; errors: number; failures: number; time: number; }; } const assignSessionAndSuitePropertiesToTests = ({ testResults, ...rest }: TestSession): TestResultWithMetadata[] => { const assignToTest = (parentSuiteName: string) => (test: TestResult): TestResultWithMetadata => { const suiteName = parentSuiteName.replace(/^\s+/, ''); return { ...test, ...rest, suiteName }; }; const assignToSuite = (parentSuiteName: string) => (suite: TestSuiteResult): TestResultWithMetadata[] => [ ...suite.tests.map(assignToTest(`${parentSuiteName} ${suite.name}`)), ...(suite.suites?.flatMap?.(assignToSuite(`${parentSuiteName} ${suite.name}`)) ?? []), ]; const suites = testResults?.suites ?? []; return suites.flatMap(assignToSuite('')); }; const toResultsWithMetadataByBrowserTestFileName = ( acc: TestResultsWithMetadataByBrowserTestFileName, test: TestResultWithMetadata, ): TestResultsWithMetadataByBrowserTestFileName => { const testSuiteName = `${test.browser.name}_${test.browser.type}_${test.testFile.replace( process.cwd(), '', )}`; return { ...acc, [testSuiteName]: [...(acc[testSuiteName] ?? []), test] }; }; const escapeLogs = (test: TestResultWithMetadata) => test.logs.flatMap(x => x.map(_cdata => ({ _cdata: stripXMLInvalidChars(_cdata) }))); const isFailedTest = (test: TestResult): boolean => // NB: shouldn't have to check for `error`, // but ATM all tests are coming back `passed: false` !test.passed && !!test.error; const isSkippedTest = (test: TestResult): boolean => !!test.skipped; const addSuiteTime = (time: number, test: TestResultWithMetadata) => time + (test.duration || 0) / 1000; type TestMetaGetter<T = string> = (test: TestResultWithMetadata) => T; const getTestName: TestMetaGetter = test => test.name; const getSuiteName: TestMetaGetter = test => test.suiteName; const getTestFile: TestMetaGetter = test => test.testFile; const getTestDurationInSeconds = ({ duration }: TestResult): number => (typeof duration === 'undefined' ? 0 : duration) / 1000; // A subset of invalid characters as defined in http://www.w3.org/TR/xml/#charsets that can occur in e.g. stacktraces // lifted from https://github.com/michaelleeallen/mocha-junit-reporter/blob/master/index.js (licensed MIT) // other portions of code adapted from same // regex lifted from https://github.com/MylesBorins/xml-sanitizer/ (licensed MIT) const INVALID_CHARACTERS_REGEX = // eslint-disable-next-line no-control-regex /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007f-\u0084\u0086-\u009f\uD800-\uDFFF\uFDD0-\uFDFF\uFFFF\uC008]/g; const STACK_TRACE_UNIQUE_IDS_REGEX = /localhost:\d+|wtr-session-id=[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+|/g; const stripXMLInvalidChars = (x: string): string => x && x.replace ? x.replace(INVALID_CHARACTERS_REGEX, '') : x; /** * Makes a `<failure>` element */ function testFailureXMLElement(test: TestResultWithMetadata): TestFailureXMLElement { const { error } = test; const message = stripXMLInvalidChars(error?.message ?? ''); const stack = stripXMLInvalidChars(error?.stack ?? ''); const type = error?.name ?? (stack.match(/^\w+Error:/) ? stack.split(':')[0] : ''); return { _attr: { message, type }, _cdata: `${type}: ${message}\n${stack}`.replace(STACK_TRACE_UNIQUE_IDS_REGEX, ''), }; } /** * Makes attributes for a `<testcase>` element * @param test Test Result */ function testCaseXMLAttributes( test: TestResultWithMetadata, rootDir: string, ): TestCaseXMLAttributes { const name = getTestName(test); const time = getTestDurationInSeconds(test); const classname = getSuiteName(test); const file = getTestFile(test).replace(`${rootDir}${path.sep}`, ''); const [, line] = stripXMLInvalidChars(test.error?.stack ?? '').match(/(\d+):\d+/m) ?? []; return { _attr: { name, time, classname, file, ...(!!line && { line }), }, }; } /** * Makes a `<testcase>` element */ function testCaseXMLElement(test: TestResultWithMetadata, rootDir: string): TestCaseXMLElement { const attributes = testCaseXMLAttributes(test, rootDir); // prettier-ignore if (isSkippedTest(test)) return { testcase: [attributes, { skipped: null }] }; else if (isFailedTest(test)) return { testcase: [attributes, { failure: testFailureXMLElement(test) }] }; else // prettier-ignore return { testcase: attributes }; } /** * Makes attributes for a `<testsuite>` element * @param name Test Suite Name * @param id Test Run ID * @param results Test Results */ function testSuiteXMLAttributes( name: string, id: number, results: TestResultWithMetadata[], ): TestSuiteXMLAttributes { const tests = results.length; const skipped = results.filter(x => x.skipped).length; const errors = results.map(x => x.error).filter(Boolean).length; const failures = results.filter(isFailedTest).length; const time = results.reduce(addSuiteTime, 0); return { _attr: { name, id, tests, skipped, errors, failures, time, }, }; } /** * Makes a `<properties>` element * @param testFile Absolute path to test file * @param browserName Short browser name * @param launcherType browser launcher type */ function testSuitePropertiesXMLElement( testFile: string, browserName: string, launcherType: string, rootDir: string, ): TestSuitePropertiesXMLElement[] { return [ { property: { _attr: { name: 'test.fileName', value: testFile.replace(`${rootDir}${path.sep}`, ''), }, }, }, { property: { _attr: { name: 'browser.name', value: browserName, }, }, }, { property: { _attr: { name: 'browser.launcher', value: launcherType, }, }, }, ]; } /** * Collates test sessions by browser, converts them to an XML object representation, * then stringifies the XML. * @param sessions Test Sessions */ function getTestRunXML({ reportLogs, rootDir, sessions, }: { sessions: TestSession[]; reportLogs: boolean; rootDir: string; }): string { const testsuites = Object.entries( sessions .flatMap(assignSessionAndSuitePropertiesToTests) .reduce( toResultsWithMetadataByBrowserTestFileName, {} as TestResultsWithMetadataByBrowserTestFileName, ), ).map(([name, tests]) => { const [{ testRun = 0, browser, testFile }] = tests; const browserName = browser.name ?? ''; const launcherType = browser.type ?? ''; const attributes = testSuiteXMLAttributes(name, testRun, tests); const properties = testSuitePropertiesXMLElement(testFile, browserName, launcherType, rootDir); const testcases = tests.map(t => testCaseXMLElement(t, rootDir)); const systemOut = !reportLogs ? [] : tests.flatMap(escapeLogs).map(x => ({ 'system-out': x })); const testsuite = [attributes, { properties }, ...testcases, ...systemOut]; return { testsuite }; }); return XML({ testsuites }, { declaration: true, indent: ' ' }); } /** * A JUnit-format XML file reporter for Web Test Runner * * @param args Options for JUnit Reporter */ export function junitReporter({ outputPath = './test-results.xml', reportLogs = false, rootDir = process.cwd(), }: JUnitReporterArgs = {}): Reporter { const filepath = path.resolve(rootDir, outputPath); const dir = path.dirname(filepath); return { onTestRunFinished({ sessions }) { const xml = getTestRunXML({ reportLogs, rootDir, sessions }); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(filepath, xml); }, }; }
modernweb-dev/web/packages/test-runner-junit-reporter/src/junitReporter.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-junit-reporter/src/junitReporter.ts", "repo_id": "modernweb-dev", "token_count": 3350 }
214
import { TestResult, TestSuiteResult, TestResultError, } from '../../test-runner-core/browser/session.js'; // type only import, has to be a bare import import { Hook } from 'mocha'; export function collectTestResults(mocha: BrowserMocha) { const hookErrors: TestResultError[] = []; let passed = true; function collectHooks(hooks: Hook[]) { for (const hook of hooks) { const hookError = (hook as any).err as Error | undefined; if (hook.state === 'failed' || hookError) { if (hookError) { const stackArray = hookError.stack?.split('\n') ?? []; hookErrors.push({ name: hookError.name, message: hookError.message, stack: stackArray.join('\n'), }); } else { hookErrors.push({ message: 'Unknown error in mocha hook' }); } } } } function getTestResults(tests: Mocha.Test[]) { const testResults: TestResult[] = []; for (const test of tests) { if (!test.isPassed() && !test.isPending()) { passed = false; } const err = test.err as Error & { actual?: string; expected?: string }; testResults.push({ name: test.title, passed: test.isPassed(), skipped: test.isPending(), ...(test.duration !== undefined && { duration: test.duration }), error: err ? { name: err.name, message: err.message, stack: err.stack, expected: err.expected, actual: err.actual, } : undefined, }); } return testResults; } function getSuiteResults(suite: Mocha.Suite): TestSuiteResult { collectHooks((suite as any)._beforeAll as Hook[]); collectHooks((suite as any)._afterAll as Hook[]); collectHooks((suite as any)._beforeEach as Hook[]); collectHooks((suite as any)._afterEach as Hook[]); const suites = suite.suites.map(s => getSuiteResults(s)); const tests = getTestResults(suite.tests); return { name: suite.title, suites, tests }; } const testResults = getSuiteResults(mocha.suite); return { testResults, hookErrors, passed }; }
modernweb-dev/web/packages/test-runner-mocha/src/collectTestResults.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-mocha/src/collectTestResults.ts", "repo_id": "modernweb-dev", "token_count": 912 }
215
export { moduleMockingPlugin } from './moduleMockingPlugin.js';
modernweb-dev/web/packages/test-runner-module-mocking/src/index.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-module-mocking/src/index.ts", "repo_id": "modernweb-dev", "token_count": 18 }
216
# @web/test-runner-playwright ## 0.11.0 ### Minor Changes - c185cbaa: Set minimum node version to 18 ### Patch Changes - Updated dependencies [c185cbaa] - @web/test-runner-coverage-v8@0.8.0 - @web/test-runner-core@0.13.0 ## 0.10.3 ### Patch Changes - Updated dependencies [43be7391] - @web/test-runner-core@0.12.0 - @web/test-runner-coverage-v8@0.7.3 ## 0.10.2 ### Patch Changes - 640ba85f: added types for main entry point - Updated dependencies [640ba85f] - @web/test-runner-coverage-v8@0.7.2 - @web/test-runner-core@0.11.6 ## 0.10.1 ### Patch Changes - Updated dependencies [3c33d74a] - @web/test-runner-coverage-v8@0.7.0 ## 0.10.0 ### Minor Changes - febd9d9d: Set node 16 as the minimum version. ### Patch Changes - Updated dependencies [ca715faf] - Updated dependencies [febd9d9d] - @web/test-runner-coverage-v8@0.6.0 - @web/test-runner-core@0.11.0 ## 0.9.0 ### Minor Changes - acca5d51: Update dependency v8-to-istanbul to v9 ### Patch Changes - Updated dependencies [acca5d51] - @web/test-runner-coverage-v8@0.5.0 ## 0.8.10 ### Patch Changes - 07e87287: Fixes playwright memory leak ## 0.8.9 ### Patch Changes - 8e3bb3cf: Add "forcedColors" support to "emulateMedia" command ## 0.8.8 ### Patch Changes - 62369e4d: Upgrade playwright to 1.14.0 which enables prefers-reduced-motion ## 0.8.7 ### Patch Changes - 33ada3d8: Align @web/test-runner-core version - Updated dependencies [33ada3d8] - @web/test-runner-coverage-v8@0.4.8 ## 0.8.6 ### Patch Changes - fdca82b2: fix error retreiving coverage in latest playwright ## 0.8.5 ### Patch Changes - a6a018da: fix type references ## 0.8.4 ### Patch Changes - 4a609a18: skip non-http coverage files - Updated dependencies [4a609a18] - @web/test-runner-coverage-v8@0.4.5 ## 0.8.3 ### Patch Changes - 9ecb49f4: release test coverage package - Updated dependencies [9ecb49f4] - @web/test-runner-coverage-v8@0.4.3 ## 0.8.2 ### Patch Changes - 83e0757e: handle cases when userAgent is not defined - Updated dependencies [83e0757e] - @web/test-runner-core@0.10.8 ## 0.8.1 ### Patch Changes - ad815710: fetch source map from server when generating code coverage reports. this fixes errors when using build tools that generate source maps on the fly, which don't exist on the file system - Updated dependencies [ad815710] - Updated dependencies [c4738a40] - @web/test-runner-core@0.10.5 - @web/test-runner-coverage-v8@0.4.2 ## 0.8.0 ### Minor Changes - a7d74fdc: drop support for node v10 and v11 - 1dd7cd0e: version bump after breaking change in @web/test-runner-core ### Patch Changes - Updated dependencies [1dd7cd0e] - Updated dependencies [a7d74fdc] - Updated dependencies [1dd7cd0e] - @web/test-runner-core@0.10.0 - @web/test-runner-coverage-v8@0.4.0 ## 0.7.2 ### Patch Changes - cbbeae3f: allow configuring puppeteer and playwright browser context ## 0.7.1 ### Patch Changes - 69b2d13d: use about:blank to kill stale browser pages, this makes tests that rely on browser focus work with puppeteer ## 0.7.0 ### Minor Changes - 6e313c18: merged @web/test-runner-cli package into @web/test-runner ### Patch Changes - Updated dependencies [6e313c18] - Updated dependencies [0f613e0e] - @web/test-runner-core@0.9.0 - @web/test-runner-coverage-v8@0.3.0 ## 0.6.6 ### Patch Changes - 2278a95: bump dependencies - Updated dependencies [0614acf] - Updated dependencies [2278a95] - @web/test-runner-coverage-v8@0.2.3 - @web/test-runner-core@0.8.11 ## 0.6.5 ### Patch Changes - 72b6bd0: update to playwright 1.6.x ## 0.6.4 ### Patch Changes - 416c0d2: Update dependencies - Updated dependencies [416c0d2] - Updated dependencies [aadf0fe] - @web/test-runner-coverage-v8@0.2.1 - @web/test-runner-core@0.8.4 ## 0.6.3 ### Patch Changes - 735658a: share the same browser context across pages ## 0.6.2 ### Patch Changes - c256a08: allow configuring concurrency per browser launcher - Updated dependencies [c256a08] - @web/test-runner-core@0.8.3 ## 0.6.1 ### Patch Changes - 859008b: added experimental mode to test workflows where tests on firefox require the browser window to be focused - Updated dependencies [859008b] - @web/test-runner-core@0.8.2 ## 0.6.0 ### Minor Changes - 2291ca1: replaced HTTP with websocket for server-browser communication this improves test speed, especially when a test file makes a lot of concurrent requests it lets us us catch more errors during test execution, and makes us catch them faster ### Patch Changes - Updated dependencies [2291ca1] - @web/test-runner-core@0.8.0 - @web/test-runner-coverage-v8@0.2.0 ## 0.5.8 ### Patch Changes - 88cc7ac: Reworked concurrent scheduling logic When running tests in multiple browsers, the browsers are no longer all started in parallel. Instead a new `concurrentBrowsers` property controls how many browsers are run concurrently. This helps improve speed and stability. - Updated dependencies [88cc7ac] - @web/test-runner-core@0.7.19 ## 0.5.7 ### Patch Changes - cde5d29: add browser logging for all browser launchers - Updated dependencies [cde5d29] - Updated dependencies [cde5d29] - @web/test-runner-core@0.7.15 ## 0.5.6 ### Patch Changes - be3c9ed: track and log page reloads - 2802df6: handle cases where reloading the page creates an infinite loop - Updated dependencies [be3c9ed] - @web/test-runner-core@0.7.10 ## 0.5.5 ### Patch Changes - 41d895f: capture native browser errors ## 0.5.4 ### Patch Changes - ce2a2e6: align dependencies - Updated dependencies [ce2a2e6] - @web/test-runner-coverage-v8@0.1.2 ## 0.5.3 ### Patch Changes - 22c85b5: fix handle race condition when starting browser ## 0.5.2 ### Patch Changes - e71eae9: restart browser on timeout - Updated dependencies [60de9b5] - @web/browser-logs@0.1.2 ## 0.5.1 ### Patch Changes - aa65fd1: run build before publishing - Updated dependencies [aa65fd1] - @web/browser-logs@0.1.1 - @web/test-runner-core@0.7.1 - @web/test-runner-coverage-v8@0.1.1 ## 0.5.0 ### Minor Changes - cdddf68: Removed support for `@web/test-runner-helpers`. This is a breaking change, the functionality is now available in `@web/test-runner-commands`. - fdcf2e5: Merged test runner server into core, and made it no longer possible configure a different server. The test runner relies on the server for many things, merging it into core makes the code more maintainable. The server is composable, you can proxy requests to other servers and we can look into adding more composition APIs later. - 9be1f95: Added native node es module entrypoints. This is a breaking change. Before, native node es module imports would import a CJS module as a default import and require destructuring afterwards: ```js import playwrightModule from '@web/test-runner-playwright'; const { playwrightLauncher } = playwrightModule; ``` Now, the exports are only available directly as a named export: ```js import { playwrightLauncher } from '@web/test-runner-playwright'; ``` ### Patch Changes - Updated dependencies [cdddf68] - Updated dependencies [fdcf2e5] - Updated dependencies [62ff8b2] - Updated dependencies [9be1f95] - @web/test-runner-core@0.7.0 - @web/browser-logs@0.1.0 - @web/test-runner-coverage-v8@0.1.0 ## 0.4.22 ### Patch Changes - c1e9884: fix checking for native instrumentation ## 0.4.21 ### Patch Changes - d77093b: allow code coverage instrumentation through JS - Updated dependencies [d77093b] - @web/test-runner-core@0.6.23 ## 0.4.20 ### Patch Changes - f0fe1f0: update to playwright 1.3.x ## 0.4.19 ### Patch Changes - 02a3926: expose browser name from BrowserLauncher - 74cc129: implement commands API - Updated dependencies [02a3926] - Updated dependencies [74cc129] - @web/test-runner-core@0.6.22 ## 0.4.18 ### Patch Changes - cbdf3c7: chore: merge browser lib into test-runner-core - Updated dependencies [cbdf3c7] - @web/test-runner-core@0.6.21 ## 0.4.17 ### Patch Changes - 432f090: expose browser name from BrowserLauncher - 5b36825: prevent debug sessions from interferring with regular test sessions - Updated dependencies [432f090] - Updated dependencies [5b36825] - @web/test-runner-core@0.6.19 ## 0.4.16 ### Patch Changes - 736d101: improve scheduling logic and error handling - Updated dependencies [736d101] - @web/test-runner-core@0.6.18 ## 0.4.15 ### Patch Changes - 4e3de03: fix a potential race condition when starting a new test ## 0.4.14 ### Patch Changes - 7c25ba4: guard against the logs script being unavailable ## 0.4.13 ### Patch Changes - Updated dependencies [ad11e36] - @web/test-runner-coverage-v8@0.0.4 ## 0.4.12 ### Patch Changes - 911aa74: remove log serialization workaround ## 0.4.11 ### Patch Changes - 5fada4a: improve logging and error reporting - Updated dependencies [5fada4a] - @web/browser-logs@0.0.1 - @web/test-runner-core@0.6.16 ## 0.4.10 ### Patch Changes - 7a22269: allow customize browser page creation ## 0.4.9 ### Patch Changes - Updated dependencies [db5baff] - @web/test-runner-core@0.6.9 - @web/test-runner-coverage-v8@0.0.3 ## 0.4.8 ### Patch Changes - c72ea22: allow configuring browser launch options - Updated dependencies [c72ea22] - @web/test-runner-core@0.6.7 ## 0.4.7 ### Patch Changes - 6bcf981: correctly map pages to browsers ## 0.4.6 ### Patch Changes - 4a6b9c2: make coverage work in watch mode - Updated dependencies [4a6b9c2] - @web/test-runner-core@0.6.6 ## 0.4.5 ### Patch Changes - 1d6d498: allow changing viewport in tests - Updated dependencies [1d6d498] - @web/test-runner-core@0.6.5 ## 0.4.4 ### Patch Changes - afc3cc7: update dependencies ## 0.4.3 ### Patch Changes - Updated dependencies [835b30c] - @web/test-runner-coverage-v8@0.0.2 ## 0.4.2 ### Patch Changes - 5ab18d8: feat(test-runner-core): batch v8 test coverage - Updated dependencies [5ab18d8] - @web/test-runner-core@0.6.4 ## 0.4.1 ### Patch Changes - 3dab600: profile test coverage through v8/chromium - Updated dependencies [3dab600] - @web/test-runner-core@0.6.2 - @web/test-runner-coverage-v8@0.0.1 ## 0.4.0 ### Minor Changes - c4cb321: Use web dev server in test runner. This contains multiple breaking changes: - Browsers that don't support es modules are not supported for now. We will add this back later. - Most es-dev-server config options are no longer available. The only options that are kept are `plugins`, `middleware`, `nodeResolve` and `preserveSymlinks`. - Test runner config changes: - Dev server options are not available on the root level of the configuration file. - `nodeResolve` is no longer enabled by default. You can enable it with the `--node-resolve` flag or `nodeResolve` option. - `middlewares` option is now called `middleware`. - `testFrameworkImport` is now called `testFramework`. - `address` is now split into `protocol` and `hostname`. ### Patch Changes - Updated dependencies [c4cb321] - @web/test-runner-core@0.6.0 ## 0.3.4 ### Patch Changes - 14b7fae: handle errors in mocha hooks - Updated dependencies [14b7fae] - @web/test-runner-core@0.5.6 ## 0.3.3 ### Patch Changes - 56ed519: open browser windows sequentially in selenium - Updated dependencies [56ed519] - @web/test-runner-core@0.5.5 ## 0.3.2 ### Patch Changes - 0f8935d: make going to a URL non-blocking - Updated dependencies [64d867c] - @web/test-runner-core@0.5.3 ## 0.3.1 ### Patch Changes - 45a2f21: add ability to run HTML tests - Updated dependencies [45a2f21] - @web/test-runner-core@0.5.1 ## 0.3.0 ### Minor Changes - 1d277e9: rename framework to browser-lib ### Patch Changes - Updated dependencies [1d277e9] - @web/test-runner-core@0.5.0 ## 0.2.0 ### Minor Changes - ccb63df: @web/test-runner-dev-server to @web/test-runner-server ### Patch Changes - Updated dependencies [ccb63df] - @web/test-runner-core@0.4.0 ## 0.1.2 ### Patch Changes - Updated dependencies [0c83d7e] - @web/test-runner-core@0.3.0 ## 0.1.1 ### Patch Changes - 115442b: add readme, package tags and description - Updated dependencies [115442b] - @web/test-runner-core@0.2.5 ## 0.1.0 ### Minor Changes - 9578c89: first setup
modernweb-dev/web/packages/test-runner-playwright/CHANGELOG.md/0
{ "file_path": "modernweb-dev/web/packages/test-runner-playwright/CHANGELOG.md", "repo_id": "modernweb-dev", "token_count": 4446 }
217
import { runIntegrationTests } from '../../../integration/test-runner/index.js'; import { puppeteerLauncher } from '../src/index.js'; describe('test-runner-puppeteer', function testRunnerPuppeteer() { this.timeout(20000); function createConfig() { return { browsers: [puppeteerLauncher()], }; } runIntegrationTests(createConfig, { basic: true, many: true, focus: true, groups: true, parallel: true, testFailure: true, locationChanged: true, }); });
modernweb-dev/web/packages/test-runner-puppeteer/test/puppeteerLauncher.test.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-puppeteer/test/puppeteerLauncher.test.ts", "repo_id": "modernweb-dev", "token_count": 188 }
218
import { CoverageMapData, TestRunnerCoreConfig } from '@web/test-runner-core'; import { WebDriver } from 'selenium-webdriver'; interface BrowserResult { testCoverage?: CoverageMapData; url: string; } function validateBrowserResult(result: any): result is BrowserResult { if (typeof result !== 'object') throw new Error('Browser did not return an object'); if (result.testCoverage != null && typeof result.testCoverage !== 'object') throw new Error('Browser returned non-object testCoverage'); return true; } /** * Manages tests to be excuted in iframes on a page. */ export class IFrameManager { private config: TestRunnerCoreConfig; private driver: WebDriver; private framePerSession = new Map<string, string>(); private inactiveFrames: string[] = []; private frameCount = 0; private initialized = false; private initializePromise?: Promise<void>; private locked?: Promise<unknown>; private isIE: boolean; constructor(config: TestRunnerCoreConfig, driver: WebDriver, isIE: boolean) { this.config = config; this.driver = driver; this.isIE = isIE; } private async _initialize(url: string) { const pageUrl = `${new URL(url).origin}/?mode=iframe`; await this.driver.navigate().to(pageUrl); } isActive(id: string) { return this.framePerSession.has(id); } async getBrowserUrl(sessionId: string): Promise<string | undefined> { const frameId = this.framePerSession.get(sessionId); if (!frameId) { throw new Error( `Something went wrong while running tests, there is no frame id for session ${frameId}`, ); } const returnValue = (await this.driver.executeScript(` try { var iframe = document.getElementById("${frameId}"); return iframe.contentWindow.location.href; } catch (_) { return undefined; } `)) as string | undefined; return returnValue; } private async scheduleCommand<T>(fn: () => Promise<T>) { if (!this.isIE) { return fn(); } while (this.locked) { await this.locked; } const fnPromise = fn(); this.locked = fnPromise; const result = await fnPromise; this.locked = undefined; return result; } async queueStartSession(id: string, url: string) { if (!this.initializePromise && !this.initialized) { this.initializePromise = this._initialize(url); } if (this.initializePromise) { await this.initializePromise; this.initializePromise = undefined; this.initialized = true; } this.scheduleCommand(() => this.startSession(id, url)); } private async startSession(id: string, url: string) { let frameId: string; if (this.inactiveFrames.length > 0) { frameId = this.inactiveFrames.pop()!; await this.driver.executeScript(` var iframe = document.getElementById("${frameId}"); iframe.src = "${url}"; `); } else { this.frameCount += 1; frameId = `wtr-test-frame-${this.frameCount}`; await this.driver.executeScript(` var iframe = document.createElement("iframe"); iframe.id = "${frameId}"; iframe.src = "${url}"; document.body.appendChild(iframe); `); } this.framePerSession.set(id, frameId); } async queueStopSession(id: string) { return this.scheduleCommand(() => this.stopSession(id)); } async stopSession(id: string) { const frameId = this.framePerSession.get(id); this.framePerSession.delete(id); if (!frameId) { throw new Error( `Something went wrong while running tests, there is no frame id for session ${id}`, ); } // retreive test results from iframe const returnValue = await this.driver.executeScript(` var iframe = document.getElementById("${frameId}"); var testCoverage; try { testCoverage = iframe.contentWindow.__coverage__; } catch (error) { // iframe can throw a cross-origin error if the test navigated } // set src after retreiving values to avoid the iframe from navigating away iframe.src = "about:blank"; return { testCoverage: testCoverage }; `); if (!validateBrowserResult(returnValue)) { throw new Error(); } const { testCoverage } = returnValue; this.inactiveFrames.push(frameId); return { testCoverage: this.config.coverage ? testCoverage : undefined }; } }
modernweb-dev/web/packages/test-runner-selenium/src/IFrameManager.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-selenium/src/IFrameManager.ts", "repo_id": "modernweb-dev", "token_count": 1605 }
219
import { expect } from '../../../../node_modules/@esm-bundle/chai/esm/chai.js'; import module from './module-features-a.js'; it('supports static imports', () => { expect(module).to.equal('moduleFeaturesA'); }); it('supports dynamic imports', async () => { const featuresB = (await import('./module-features-b.js')).default; expect(featuresB).to.equal('moduleFeaturesB'); }); it('supports import meta', () => { expect(import.meta.url.indexOf('fixtures/module-features.js')).to.not.equal(-1); });
modernweb-dev/web/packages/test-runner-selenium/test/fixtures/module-features.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner-selenium/test/fixtures/module-features.js", "repo_id": "modernweb-dev", "token_count": 172 }
220
export default /** @type {import('@web/test-runner').TestRunnerConfig} */ ({ files: ['demo/test/logging.test.js'], filterBrowserLogs(log) { return log.type === 'error'; }, });
modernweb-dev/web/packages/test-runner/demo/filter-logs.config.mjs/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/filter-logs.config.mjs", "repo_id": "modernweb-dev", "token_count": 67 }
221
/* @web/test-runner snapshot v1 */ export const snapshots = {}; snapshots["snapshot-a"] = `some snapshot A3`; /* end snapshot snapshot-a */ snapshots["snapshot-b"] = `some snapshot B3`; /* end snapshot snapshot-b */ snapshots["snapshot-c"] = `some snapshot C3`; /* end snapshot snapshot-c */
modernweb-dev/web/packages/test-runner/demo/test/__snapshots__/pass-snapshot-3.test.snap.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/test/__snapshots__/pass-snapshot-3.test.snap.js", "repo_id": "modernweb-dev", "token_count": 103 }
222
import { expect } from './chai.js'; it('fails on non-chrome browsers', () => { if ( /^((?!chrome|android).)*safari/i.test(navigator.userAgent) || navigator.userAgent.toLowerCase().includes('firefox') ) { throw new Error('This should fail on non-chrome'); } });
modernweb-dev/web/packages/test-runner/demo/test/fail-non-chrome.test.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/test/fail-non-chrome.test.js", "repo_id": "modernweb-dev", "token_count": 103 }
223
console.log('console.log'); console.warn('console.warn'); console.debug('console.debug'); console.error('console.error'); console.log('Log', 'multiple', 'strings'); console.log('simple object', { a: '1', b: '2' }); console.log('nested', { a1: '1', b1: { a2: '1', b2: { a3: { a4: { a5: { a6: { a7: 'a7', }, }, }, }, }, c2: '3', }, c1: '3', }); console.log('array', [{ a: 1, b: 2 }, 'some string', [1, 2, 3]]); const div = document.createElement('div'); div.textContent = 'my div'; console.log('dom element', div); const nestedDiv = document.createElement('div'); nestedDiv.innerHTML = ` <style> :host { color: blue; } </style> <div> <div> <div> <span>hi</span> </div> </div> </div> `; console.log('nested dom elements', nestedDiv); const mySymbol = Symbol('foo'); console.log('symbol', mySymbol); const myComment = document.createComment('this is a HTML comment'); console.log(myComment); const textNode = document.createTextNode('this is a text node'); console.log(textNode); class Foo {} const foo = new Foo(); foo.bar = 'buz'; foo.lorem = 'ipsum'; console.log(foo); const url = new URL(window.location); console.log(url); console.log(url.searchParams); console.log(undefined); console.log(null); console.log({ x: undefined }); console.log([undefined, null]); describe('x', () => { it('y', async () => { await new Promise(r => setTimeout(r, 500)); console.log('lazy logs'); }); });
modernweb-dev/web/packages/test-runner/demo/test/logging.test.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/test/logging.test.js", "repo_id": "modernweb-dev", "token_count": 673 }
224
import { compareSnapshot } from '@web/test-runner-commands'; it('can test snapshot A', async () => { await compareSnapshot({ name: 'snapshot-a', content: 'some snapshot A4' }); }); it('can test snapshot B', async () => { await compareSnapshot({ name: 'snapshot-b', content: 'some snapshot B4' }); }); it('can test snapshot C', async () => { await compareSnapshot({ name: 'snapshot-c', content: 'some snapshot C4' }); });
modernweb-dev/web/packages/test-runner/demo/test/pass-snapshot-4.test.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/test/pass-snapshot-4.test.js", "repo_id": "modernweb-dev", "token_count": 136 }
225
import './shared-a.js'; import './shared-b.js';
modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-14.test.d.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-14.test.d.ts", "repo_id": "modernweb-dev", "token_count": 20 }
226
export declare function sharedB1(): string;
modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/shared-b.d.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/shared-b.d.ts", "repo_id": "modernweb-dev", "token_count": 10 }
227
export class TestRunnerStartError extends Error {}
modernweb-dev/web/packages/test-runner/src/TestRunnerStartError.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/src/TestRunnerStartError.ts", "repo_id": "modernweb-dev", "token_count": 10 }
228
import { TestSession, Logger } from '@web/test-runner-core'; export function reportBrowserLogs(logger: Logger, sessions: TestSession[]) { const commonLogs: any[] = []; const commonStringified: string[] = []; const logsByBrowser = new Map<string, any[]>(); const allStringified = sessions.map(s => JSON.stringify(s.logs)); for (const session of sessions) { for (const args of session.logs) { // for the first session, we always include all logs // for others we deduplicate logs, this way we can allow the same log // msg appearing multiple times while also deduplicating common logs // between browsers const stringifiedArgs = JSON.stringify(args); if ( args.length > 0 && (session === sessions[0] || !commonStringified.includes(stringifiedArgs)) ) { if (allStringified.every(logs => logs.includes(stringifiedArgs))) { commonLogs.push(args); commonStringified.push(stringifiedArgs); } else { let logsForBrowser = logsByBrowser.get(session.browser.name); if (!logsForBrowser) { logsForBrowser = []; logsByBrowser.set(session.browser.name, logsForBrowser); } logsForBrowser.push(args); } } } } if (commonLogs.length > 0) { logger.log(` ๐Ÿšง Browser logs:`); logger.group(); logger.group(); logger.group(); for (const args of commonLogs) { logger.log(...args); } logger.groupEnd(); logger.groupEnd(); logger.groupEnd(); } for (const [browser, logs] of logsByBrowser) { logger.log(` ๐Ÿšง Browser logs on ${browser}:`); logger.group(); logger.group(); logger.group(); for (const args of logs) { logger.log(...args); } logger.groupEnd(); logger.groupEnd(); logger.groupEnd(); } if (commonLogs.length > 0 || logsByBrowser.size > 0) { logger.log(''); } }
modernweb-dev/web/packages/test-runner/src/reporter/reportBrowserLogs.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/src/reporter/reportBrowserLogs.ts", "repo_id": "modernweb-dev", "token_count": 764 }
229
import { rocketLaunch } from '@rocket/launch'; import { rocketBlog } from '@rocket/blog'; import { rocketSearch } from '@rocket/search'; import { absoluteBaseUrlNetlify } from '@rocket/core/helpers'; export default { presets: [rocketLaunch(), rocketBlog(), rocketSearch()], absoluteBaseUrl: absoluteBaseUrlNetlify('http://localhost:8080'), serviceWorkerName: 'sw.js', };
modernweb-dev/web/rocket.config.mjs/0
{ "file_path": "modernweb-dev/web/rocket.config.mjs", "repo_id": "modernweb-dev", "token_count": 113 }
230
root = true [*] end_of_line = lf insert_final_newline = true [*.{js,jsx}] charset = utf-8 indent_style = space indent_size = 2
odota/web/.editorconfig/0
{ "file_path": "odota/web/.editorconfig", "repo_id": "odota", "token_count": 61 }
231
/* eslint-disable import/no-extraneous-dependencies, no-console, import/no-unresolved */ const request = require('request'); const fs = require('fs'); const vdf = require('simple-vdf'); // For updating the opendota-ui lang files with data from the vpk const dontReplace = [ 'npc_dota_brewmaster_earth_#', 'npc_dota_brewmaster_fire_#', 'npc_dota_brewmaster_storm_#', 'game_mode_22', ]; // links langTag to the language file in the vpk // null indicates that dota does not support this language const langTagNames = { 'bg-BG': 'bulgarian', 'cs-CZ': 'czech', 'da-DK': 'danish', 'de-DE': 'german', 'el-GR': 'greek', // 'en-US': 'english', // commented out because we don't want to mess up the spacing 'es-ES': 'spanish', 'es-PE': 'spanish', 'es-US': 'spanish', 'fi-FI': 'finnish', 'fr-FR': 'french', 'he-IL': null, 'hu-HU': 'hungarian', 'it-IT': 'italian', 'ja-JP': 'japanese', 'ko-KR': 'korean', 'ms-MY': null, 'nl-NL': 'dutch', 'no-NO': 'norwegian', 'pl-PL': 'polish', 'pt-BR': 'portuguese', 'pt-PT': 'portuguese', 'ro-RO': 'romanian', 'ru-RU': 'russian', 'sk-SK': null, 'sr-SP': null, 'sv-SE': 'swedish', 'th-TH': 'thai', 'tr-TR': 'turkish', 'uk-UA': 'ukrainian', 'vi-VN': null, 'zh-CN': 'schinese', 'zh-TW': 'tchinese', }; // The rest of these are build later on const replacements = { rune_0: 'DOTA_Tooltip_rune_doubledamage', rune_1: 'DOTA_Tooltip_rune_haste', rune_2: 'DOTA_Tooltip_rune_illusion', rune_3: 'DOTA_Tooltip_rune_invisibility', rune_4: 'DOTA_Tooltip_rune_regeneration', rune_5: 'DOTA_Tooltip_rune_bounty', rune_6: 'DOTA_Tooltip_rune_arcane', }; const langDir = 'src/lang/'; let englishLang = null; try { englishLang = JSON.parse(fs.readFileSync(`${langDir}en-US.json`, 'utf8')); } catch (ex) { console.log("Couldn't find en-US.json in the specified directory"); process.exit(1); } const updateLang = (langTag, langName) => { if (!langName) { return; // Means dota doesn't have this lang file } const stringsUrl = `https://raw.githubusercontent.com/dotabuff/d2vpkr/master/dota/resource/dota_${langName}.json`; const langFilename = `${langDir}${langTag}.json`; request(stringsUrl, (err, resp, body) => { console.log(`${langTag} <= ${langName}`); if (err || resp.statusCode !== 200) { console.log(`Error ${resp.statusCode} when getting ${langName}: ${err}`); process.exit(1); } const strings = JSON.parse(body).lang.Tokens; let lang = null; try { lang = JSON.parse(fs.readFileSync(langFilename, 'utf8')); } catch (ex) { console.log(`${ex.name} when reading ${langTag}: ${ex.message}`); process.exit(1); } Object.keys(replacements).forEach((key) => { if ((!lang[key] || lang[key] === englishLang[key]) && (replacements[key] in strings)) { let result = strings[replacements[key]]; if (['chatwheel_71', 'chatwheel_72'].indexOf(key) >= 0) { result = result.replace(/%s1/, strings.DOTA_Shared_Unit_Control_Hero); } lang[key] = result; } }); let outString = JSON.stringify(lang, null, 2); // Fix "key": "value" to "key":"value", because thats how it is currently outString = outString.replace(/": "/g, '":"'); fs.writeFile(langFilename, outString, 'utf8'); }); }; // Build the rest of replacements here // game modes for (let i = 0; `game_mode_${i}` in englishLang; i += 1) { replacements[`game_mode_${i}`] = `game_mode_lobby_name_${i}`; } // npc_dota_(unitstrings) Object.keys(englishLang).filter(k => k.match(/^npc_dota_/)).forEach((key) => { replacements[key] = key.replace('#', '1'); }); replacements.npc_dota_phoenix_sun = 'DOTA_Tooltip_ability_phoenix_supernova'; replacements.npc_dota_weaver_swarm = 'DOTA_Tooltip_ability_weaver_the_swarm'; // regions, chat wheel, & call update request('https://raw.githubusercontent.com/dotabuff/d2vpkr/master/dota/scripts/regions.json', (err, resp, body) => { if (err || resp.statusCode !== 200) { console.log('Error getting regions info from d2vpkr'); process.exit(1); } const { regions } = JSON.parse(body); Object.keys(regions).forEach((key) => { replacements[`region_${regions[key].region}`] = regions[key].display_name.replace(/^#/, ''); }); request('https://raw.githubusercontent.com/dotabuff/d2vpkr/master/dota/scripts/chat_wheel.txt', (_err, _resp, _body) => { if (_err || _resp.statusCode !== 200) { console.log('Error getting chat wheel info from d2vpkr'); process.exit(1); } const chatWheel = vdf.parse(_body).chat_wheel.messages; Object.keys(chatWheel).forEach((key) => { if (chatWheel[key].message[0] === '#') { replacements[`chatwheel_${chatWheel[key].message_id}`] = chatWheel[key].message.replace(/^#/, ''); } }); // Remove ones we don't want to replace dontReplace.forEach((key) => { delete replacements[key]; }); console.log('Updating lang files...'); Object.keys(langTagNames).forEach(tag => updateLang(tag, langTagNames[tag])); }); });
odota/web/dev/updatelangvpk.js/0
{ "file_path": "odota/web/dev/updatelangvpk.js", "repo_id": "odota", "token_count": 2059 }
232
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <path d="M0 0h640v160H0z" fill="red"/> <path d="M0 160h640v160H0z" fill="#00f"/> <path d="M0 320h640v160H0z" fill="orange"/> </svg>
odota/web/public/assets/images/flags/am.svg/0
{ "file_path": "odota/web/public/assets/images/flags/am.svg", "repo_id": "odota", "token_count": 106 }
233
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <defs> <clipPath id="a"> <path fill-opacity=".67" d="M0 0h640v480H0z"/> </clipPath> </defs> <g fill-rule="evenodd" stroke-width="1pt" clip-path="url(#a)"> <path fill="#e10011" d="M-32.5 0h720v480h-720z"/> <path d="M114.25 479.77L-32.5 480V0l146.06.075 94.242 30.306-93.554 29.542 93.554 30.458-93.554 29.542 93.554 30.458-93.554 29.54 93.554 30.46-93.554 29.54 93.554 30.46-93.554 29.54 93.554 30.46-93.554 29.54 93.554 30.46-93.554 29.54 93.554 30.46-93.554 29.54" fill="#fff"/> </g> </svg>
odota/web/public/assets/images/flags/bh.svg/0
{ "file_path": "odota/web/public/assets/images/flags/bh.svg", "repo_id": "odota", "token_count": 305 }
234
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <path fill="#fff" d="M0 0h640v480H0z"/> <path fill="#003580" d="M0 174.545h640v130.909H0z"/> <path fill="#003580" d="M175.455 0h130.909v480H175.455z"/> </svg>
odota/web/public/assets/images/flags/fi.svg/0
{ "file_path": "odota/web/public/assets/images/flags/fi.svg", "repo_id": "odota", "token_count": 119 }
235
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="480" width="640" viewBox="0 0 640 480"> <path d="M0 0h640v480H0z" fill="#fff"/> <path d="M256 0h128v480H256z" fill="#e8112d"/> <path d="M0 176h640v128H0z" fill="#e8112d"/> <path id="a" d="M109.991 286.667l23.342-23.343h210.01v-46.666h-210.01l-23.342-23.325z" fill="#f9dd16"/> <use xlink:href="#a" transform="rotate(90 320 240)" height="24" width="36"/> <use xlink:href="#a" transform="rotate(-90 320 240)" height="24" width="36"/> <use xlink:href="#a" transform="rotate(180 320 240)" height="24" width="36"/> </svg>
odota/web/public/assets/images/flags/gg.svg/0
{ "file_path": "odota/web/public/assets/images/flags/gg.svg", "repo_id": "odota", "token_count": 273 }
236
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="480" width="640" viewBox="0 0 640 480"> <path d="M0 0h640v480H0z" fill="#0073cf"/> <path d="M0 160h640v160H0z" fill="#fff"/> <g id="c" transform="matrix(26.66665 0 0 26.66665 320 240)" fill="#0073cf"> <g id="b"> <path id="a" d="M-.31-.05l.477.156L0-1z"/> <use height="100%" width="100%" xlink:href="#a" transform="scale(-1 1)"/> </g> <use height="100%" width="100%" xlink:href="#b" transform="rotate(72)"/> <use height="100%" width="100%" xlink:href="#b" transform="rotate(-72)"/> <use height="100%" width="100%" xlink:href="#b" transform="rotate(144)"/> <use height="100%" width="100%" xlink:href="#b" transform="rotate(-144)"/> </g> <use height="100%" width="100%" xlink:href="#c" transform="translate(133.333 -42.666)"/> <use height="100%" width="100%" xlink:href="#c" transform="translate(133.333 37.333)"/> <use height="100%" width="100%" xlink:href="#c" transform="translate(-133.333 -42.666)"/> <use height="100%" width="100%" xlink:href="#c" transform="translate(-133.333 37.333)"/> </svg>
odota/web/public/assets/images/flags/hn.svg/0
{ "file_path": "odota/web/public/assets/images/flags/hn.svg", "repo_id": "odota", "token_count": 467 }
237
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <defs> <clipPath id="a"> <path fill-opacity=".67" d="M-117.82 0h682.67v512h-682.67z"/> </clipPath> </defs> <g clip-path="url(#a)" transform="translate(110.46) scale(.9375)"> <g fill-rule="evenodd" stroke-width="1pt"> <path d="M-117.82 0H906.182v170.667H-117.82z"/> <path fill="#fff" d="M-117.82 170.667H906.182v170.667H-117.82z"/> <path fill="#090" d="M-117.82 341.334H906.182v170.667H-117.82z"/> <path d="M-117.82 512.001l512.001-256L-117.82 0v512.001z" fill="red"/> <path fill="#fff" d="M24.528 288.964l5.664-24.82H4.743l22.928-11.045-15.867-19.9 22.93 11.05 5.664-24.82 5.661 24.82 22.93-11.05-15.866 19.9 22.93 11.045H50.602l5.663 24.82-15.867-19.92z"/> </g> </g> </svg>
odota/web/public/assets/images/flags/jo.svg/0
{ "file_path": "odota/web/public/assets/images/flags/jo.svg", "repo_id": "odota", "token_count": 435 }
238
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <g fill-rule="evenodd"> <path fill="red" d="M425.75 0H640v480H425.75z"/> <path fill="#009a00" d="M0 0h212.88v480H0z"/> <path fill="#ff0" d="M212.88 0h213.95v480H212.88z"/> </g> </svg>
odota/web/public/assets/images/flags/ml.svg/0
{ "file_path": "odota/web/public/assets/images/flags/ml.svg", "repo_id": "odota", "token_count": 142 }
239
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="480" width="640" viewBox="0 0 640 480"> <path fill="#0038a8" d="M0 0h640v240H0z"/> <path fill="#ce1126" d="M0 240h640v240H0z"/> <path d="M415.692 240L0 480V0" fill="#fff"/> <g transform="translate(149.333 240) scale(5.33333)" fill="#fcd116"> <circle r="9"/> <g id="d"> <g id="c"> <g id="b"> <path d="M-1 0l.062.062L0 0l-.938-.062z" transform="scale(19)"/> <path id="a" d="M-.884.116l.05.05L0 0z" transform="scale(19.2381)"/> <use height="100%" width="100%" xlink:href="#a" transform="scale(1 -1)"/> </g> <use height="100%" width="100%" xlink:href="#b" transform="rotate(45)"/> </g> <use height="100%" width="100%" xlink:href="#c" transform="rotate(90)"/> </g> <use height="100%" width="100%" xlink:href="#d" transform="scale(-1)"/> <g transform="translate(-2.02)"> <g id="f" transform="translate(37.962)"> <path id="e" d="M5 0L1.618 1.176l-.073 3.58-2.163-2.854-3.427 1.037L-2 0z"/> <use height="100%" width="100%" xlink:href="#e" transform="scale(1 -1)"/> </g> <use height="100%" width="100%" xlink:href="#f" transform="rotate(120)"/> <use height="100%" width="100%" xlink:href="#f" transform="rotate(-120)"/> </g> </g> </svg>
odota/web/public/assets/images/flags/ph.svg/0
{ "file_path": "odota/web/public/assets/images/flags/ph.svg", "repo_id": "odota", "token_count": 657 }
240
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <defs> <clipPath id="a"> <path fill-opacity=".67" d="M0 0h682.67v512H0z"/> </clipPath> </defs> <g clip-path="url(#a)" fill-rule="evenodd" transform="scale(.9375)"> <path fill="#ff0" d="M0 0h1024v504.3H0z"/> <path fill="#009d00" d="M0 0h1024v146.29H0zM0 365.71h1024V512H0z"/> <path d="M.708 0c1.417 0 255.29 253.03 255.29 253.03L-.002 512 .707 0z" fill="#f10600"/> <g stroke-width="1pt"> <path d="M411.966 268.686l-31.97-23.896 39.499.04 12.174-38.705 12.173 38.705 39.5-.029-31.977 23.885 12.236 38.687-31.938-23.942-31.938 23.937zM215.048 268.686l-31.971-23.896 39.5.04 12.173-38.705 12.174 38.705 39.5-.029-31.977 23.885 12.235 38.687-31.938-23.942-31.937 23.937z"/> </g> </g> </svg>
odota/web/public/assets/images/flags/st.svg/0
{ "file_path": "odota/web/public/assets/images/flags/st.svg", "repo_id": "odota", "token_count": 426 }
241
<?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="900" height="450" viewBox="-3 -6 24 12"> <path d="M21,6V-6H-3V6z" fill="#dc241f"/> <path d="M-3,-6V6L9,0z" fill="#ffc726"/> <path d="M-3,-6V6L5,0z"/> <!-- -arctan(0.5) v --> <g transform="rotate(-26.565051)"> <g id="f"> <g id="t"> <path d="M0,-2.1V0H1z" fill="#fff" transform="rotate(18,0,-2.1)" id="o"/> <use xlink:href="#o" transform="scale(-1,1)"/> </g> <use xlink:href="#t" transform="rotate(72)"/> </g> <use xlink:href="#t" transform="rotate(-72)"/> <use xlink:href="#f" transform="rotate(144)"/> </g> </svg>
odota/web/public/assets/images/flags/tp.svg/0
{ "file_path": "odota/web/public/assets/images/flags/tp.svg", "repo_id": "odota", "token_count": 323 }
242
import patch from 'dotaconstants/build/patch.json'; import region from 'dotaconstants/build/region.json'; import { getPercentWin } from '../utility'; import store from '../store'; const patchLookup = {}; patch.forEach((patchElement, index) => { patchLookup[index] = patchElement.name; }); export default function transformCounts(data) { const { strings } = store.getState().app; const countTypes = { patch: patchLookup, region, is_radiant: { 0: strings.general_dire, 1: strings.general_radiant, }, }; const result = {}; Object.keys(data).forEach((key) => { // Translate each ID to a string result[key] = { name: key, list: Object.keys(data[key]) .map(innerKey => ({ category: strings[`${key}_${innerKey}`] || (countTypes[key] && countTypes[key][innerKey]) || innerKey, matches: data[key][innerKey].games, winPercent: getPercentWin(data[key][innerKey].win, data[key][innerKey].games), })).sort((a, b) => b.category - a.category), }; }); return result; }
odota/web/src/actions/transformCounts.js/0
{ "file_path": "odota/web/src/actions/transformCounts.js", "repo_id": "odota", "token_count": 414 }
243
import React from 'react'; import PropTypes from 'prop-types'; import AlertWarning from 'material-ui/svg-icons/alert/warning'; import styled from 'styled-components'; import constants from '../constants'; const StyledDiv = styled.div` font-weight: ${constants.fontWeightLight}; font-size: ${constants.fontSizeMedium}; letter-spacing: 0.1ex; & svg { vertical-align: sub; margin-right: 5px; width: 20px !important; height: 20px !important; fill: ${constants.colorYelor} !important; } color: ${constants.colorYelor}; `; const Warning = ({ children, className, msg }) => ( <StyledDiv className={`${className}`}> <AlertWarning /> <span> {!children && msg} {!msg && children} </span> </StyledDiv> ); Warning.propTypes = { children: PropTypes.node, className: PropTypes.string, msg: PropTypes.string, }; export default Warning;
odota/web/src/components/Alerts/Warning.jsx/0
{ "file_path": "odota/web/src/components/Alerts/Warning.jsx", "repo_id": "odota", "token_count": 324 }
244
import styled from 'styled-components'; import constants from '../constants'; export const StyledCombos = styled.div` margin-bottom: 150px; .submit-section { display: inline-block; margin-bottom: 23px; margin-top: 15px; } .main-section { border-bottom: 1px solid rgba(255, 255, 255, 0.28); margin-bottom: 10px; } .hero-overview { display: grid; gap: 6px; grid-template-columns: repeat(auto-fill,50px); margin-bottom: 50px; @media screen and (max-width: ${constants.wrapMobile}) { grid-template-columns: repeat(auto-fill,60px); } } `; export const StyledInputFilter = styled.div` display: flex; align-items: center; justify-content: center; margin-bottom: 40px; .container { background: #1313135c; padding: 0px 7px 3px 7px; border-radius: 5px; border: 1px solid #e3e3e421; } .reset-button { display: inline-block; font-size: 22px; opacity: 0.5; cursor: pointer; margin-left: 10px; &:hover { opacity: 1; } } `; export const StyledHeroSelector = styled.div` ${props => (props.isFiltered || props.selected) && `pointer-events: none; filter: grayscale(1) brightness(0.4); opacity: 0.5;` } height: 60px; overflow: hidden; border-radius: 4px; backface-visibility: hidden; box-sizing: border-box; transition: transform .1s ease-in-out; border: 1px solid transparent; @media screen and (min-width: ${constants.wrapMobile}) { :hover { transform: scale(2); box-shadow: 0px 0px 8px 5px #000000b0; z-index: 100; border: 1px solid #d2d2d2a6; & img { opacity: 1 !important; } } } display: flex; justify-content: center; align-items: center; border: 1px solid #ffffff1a; position: relative; line-height: 0px; width: 100%; img { width: 100%; height: 100%; } .ts-container { z-index: 1000; outline: none; opacity: 0; position: absolute; top: 0; width: 100%; height: 100%; white-space: normal; transition: opacity 0.2s ease-out; &:hover { opacity: 1; background-color: #0000005e; } @media screen and (max-width: ${constants.wrapMobile}) { opacity: 1; } } .name-overlay { position: absolute; top: 0; bottom: 0; right: 0; left: 0; background: linear-gradient(to bottom, transparent 60%, rgba(0, 0, 0, 0.7)); & .name { position: relative; text-align: center; font-size: 10px; white-space: nowrap; line-height: 12px; overflow: hidden; text-overflow: ellipsis; top: 75%; } & .team-indicator { position: absolute; top: 10px; opacity: 0.8; text-shadow: 1px 1px 2px black; font-size: 15px; &.team-a { left: 10px; } &.team-b { right: 10px; } } } &:hover .name { display: none; } &:hover .team-indicator { display: none; } .ts { display: inline-flex; align-items: center; justify-content: center; width: 50%; height: 100%; font-size: 15px; text-align: center; cursor: pointer; transition: all 0.1s ease-out; vertical-align: top; outline: none; color: #ffffffeb; text-shadow: 1px 1px black; &:hover { color: white; text-shadow: 1px 1px 1px black; &.ts-left { background: linear-gradient(to left,rgb(17 84 115 / 74%) 40%, transparent); } &.ts-right { background: linear-gradient(to right,rgb(191 74 26 / 65%) 40%, transparent); } } } .ts.no-event { pointer-events: none; } `; export const StyledSelectedHeroes = styled.div` display: flex; justify-content: center; margin-top: 30px; margin-bottom: 30px; .hero-placeholder { display: inline-block; height: 60px; width: 106px; background: rgba(18, 24, 37, 0.98); box-shadow: inset 0px 0px 5px rgba(21, 21, 21, 0.61); border-radius: 4px; } .hero-img { margin-top: 3px; margin-right: 5px; position: relative; border-radius: 4px; } img { height: 60px; width: 106px; cursor: pointer; backface-visibility: hidden; &:hover { opacity: 0.3; } } .seperator { font-size: 20px; letter-spacing: 1px; font-weight: bold; display: flex; align-items: center; padding-top: 10px; flex-basis: 60px; justify-content: center; flex-shrink: 0; } .team-container { margin-top: -3px; margin-right: -5px; display: flex; flex-wrap: wrap; justify-content: center; border-radius: 5px; &.left { background: linear-gradient(45deg, rgb(48 241 241 / 16%), transparent); border-top: 3px solid #087f9263; } &.right { background: linear-gradient(225deg, rgb(189 98 3 / 16%), transparent); border-top: 3px solid #a22f0c63; } & div { text-align: center; } & .team-title { flex-basis: 100%; font-size: 20px; opacity: 0.6; &.team-a { color : #5dfff8; } &.team-b { color: #ff815b; } } } `;
odota/web/src/components/Combos/Styles.jsx/0
{ "file_path": "odota/web/src/components/Combos/Styles.jsx", "repo_id": "odota", "token_count": 2344 }
245
import heroData from 'dotaconstants/build/heroes.json'; import patchData from 'dotaconstants/build/patch.json'; import regionData from 'dotaconstants/build/region.json'; import clusterData from 'dotaconstants/build/cluster.json'; import store from '../../store'; import { formatTemplateToString } from '../../utility'; // import { isActiveItem } from '../../utility'; const items = (await import('dotaconstants/build/items.json')).default; const getItemSuffix = itemKey => (['_2', '_3', '_4', '_5'].some(suffix => itemKey.indexOf(suffix) !== -1) ? itemKey[itemKey.length - 1] : ''); const getFields = (players = [], leagues = [], teams = []) => { const { strings } = store.getState().app; const jsonSelect = { value: 'key', groupValue: 'value::text::int', groupKey: 'key', avgPerMatch: true, bundle: 'json_select', singleSelection: 'true', }; const usesSelect = itemKey => ({ text: `${strings.explorer_uses} - ${items[itemKey].dname} ${getItemSuffix(itemKey)}`, value: `(item_uses->>'${itemKey}')::int`, key: `uses_${itemKey}`, alias: 'uses', bundle: 'uses', }); // const timingSelect = itemKey => ({ // text: `${strings.explorer_timing} - ${items[itemKey].dname} ${getItemSuffix(itemKey)}`, // value: 'match_logs.time', // order: 'ASC', // join: `JOIN match_logs // ON match_logs.match_id = matches.match_id // AND player_matches.player_slot = match_logs.targetname_slot // AND match_logs.type = 'DOTA_COMBATLOG_PURCHASE' // AND match_logs.valuename = 'item_${itemKey}'`, // key: `timing_${itemKey}`, // formatSeconds: true, // bundle: 'timing', // singleSelection: true, // }); // const killSelect = ({ // text, // unitKey, // }) => ({ // text: `${strings.explorer_kill} - ${text}`, // value: 'match_logs.time', // order: 'ASC', // join: `JOIN match_logs // ON match_logs.match_id = matches.match_id // AND player_matches.player_slot = match_logs.sourcename_slot // AND match_logs.type = 'DOTA_COMBATLOG_DEATH' // AND match_logs.targetname LIKE '${unitKey}'`, // key: `kill_${unitKey}`, // bundle: 'kill', // singleSelection: true, // }); const singleFields = [{ text: strings.heading_kills, value: 'kills', key: 'kills', }, { text: strings.heading_deaths, value: 'deaths', key: 'deaths', }, { text: strings.heading_assists, value: 'assists', key: 'assists', }, { text: strings.heading_gold_per_min, value: 'gold_per_min', bucket: 50, key: 'gold_per_min', }, { text: strings.heading_xp_per_min, value: 'xp_per_min', bucket: 50, key: 'xp_per_min', }, { text: strings.heading_last_hits, value: 'last_hits', bucket: 10, key: 'last_hits', }, { text: strings.heading_denies, value: 'denies', key: 'denies', }, { text: strings.heading_hero_damage, value: 'hero_damage', bucket: 1000, key: 'hero_damage', }, { text: strings.heading_tower_damage, value: 'tower_damage', bucket: 1000, key: 'tower_damage', }, { text: strings.heading_hero_healing, value: 'hero_healing', bucket: 1000, key: 'hero_healing', }, { text: strings.heading_level, value: 'level', key: 'level', }, { text: strings.heading_stuns, value: 'stuns', bucket: 1, key: 'stuns', }, { text: strings.heading_camps_stacked, value: 'camps_stacked', key: 'camps_stacked', }, { text: strings.heading_lhten, value: 'lh_t[11]', bucket: 10, key: 'lh10', }, { text: strings.heading_lhtwenty, value: 'lh_t[21]', bucket: 10, key: 'lh20', }, { text: strings.heading_lhthirty, value: 'lh_t[31]', bucket: 10, key: 'lh30', }, { text: strings.heading_lhforty, value: 'lh_t[41]', bucket: 10, key: 'lh40', }, { text: strings.heading_lhfifty, value: 'lh_t[51]', bucket: 10, key: 'lh50', }, { text: strings.th_buybacks, value: 'array_length(buyback_log, 1)', key: 'buybacks', }, { text: strings.th_scans_used, value: '(actions->>\'31\')::int', key: 'scans_used', }, { text: strings.th_glyphs_used, value: '(actions->>\'24\')::int', key: 'glyphs_used', }, { text: strings.th_obs_placed, value: 'array_length(obs_log, 1)', key: 'obs_placed', }, { text: strings.th_sen_placed, value: 'array_length(sen_log, 1)', key: 'sen_placed', }, { text: strings.th_obs_destroyed, value: '(killed->>\'npc_dota_observer_wards\')::int', key: 'obs_destroyed', }, { text: strings.th_sen_destroyed, value: '(killed->>\'npc_dota_sentry_wards\')::int', key: 'sen_destroyed', }, { text: strings.th_legs, value: 'heroes.legs', key: 'legs', }, { text: strings.th_fantasy_points, value: 'round((0.3 * kills + (3 - 0.3 * deaths) + 0.003 * (last_hits + denies) + 0.002 * gold_per_min + towers_killed + roshans_killed + 3 * teamfight_participation + 0.5 * observers_placed + 0.5 * camps_stacked + 0.25 * rune_pickups + 4 * firstblood_claimed + 0.05 * stuns)::numeric, 1)', key: 'fantasy_points', bucket: 1, }, { text: strings.heading_damage_dealt, value: '(SELECT SUM(value::text::int) FROM json_each(damage_inflictor))', key: 'dmg_dealt', }, { text: strings.heading_damage_received, value: '(SELECT SUM(value::text::int) FROM json_each(damage_inflictor_received))', key: 'dmg_received', }].map(select => ({ ...select, alias: select.alias || select.key, bundle: 'single', })); const patches = patchData.reverse().map(patch => ({ text: patch.name, value: patch.name, key: patch.name, })); const durations = Array(10).fill().map((e, i) => i * 10).map(duration => ({ text: `${formatTemplateToString(strings.time_mm, duration)}`, searchText: formatTemplateToString(strings.time_mm, duration), value: duration * 60, key: String(duration), })); const having = Array(5).fill().map((e, i) => (i + 1) * 5).map(element => ({ text: String(element), value: element, key: String(element), })); const limit = [100, 200, 500, 1000].map(element => ({ text: String(element), value: element, key: String(element), })); const goldAdvantage = Array(31).fill().map((_, i) => i * 1000).map(element => ({ text: String(element), value: element, key: String(element), })); return { select: [ { text: strings.heading_duration, value: 'duration', alias: 'as time', key: 'duration', formatSeconds: true, bundle: 'duration', }, { text: strings.heading_distinct_heroes, value: 'player_matches.hero_id', countValue: 'count(distinct player_matches.hero_id) distinct_heroes', key: 'distinct_heroes', distinct: true, bundle: 'distinct_heroes', }, { ...jsonSelect, text: strings.heading_item_purchased, alias: 'item_name', join: ', json_each(player_matches.purchase)', key: 'item_purchased', }, { ...jsonSelect, text: strings.heading_ability_used, alias: 'ability_name', join: ', json_each(player_matches.ability_uses)', key: 'ability_used', }, { ...jsonSelect, text: strings.heading_item_used, alias: 'item_name', join: ', json_each(player_matches.item_uses)', key: 'item_used', }, { ...jsonSelect, text: strings.heading_damage_inflictor, alias: 'inflictor', join: ', json_each(player_matches.damage_inflictor)', key: 'damage_inflictor', }, { ...jsonSelect, text: strings.heading_damage_inflictor_received, alias: 'inflictor', join: ', json_each(player_matches.damage_inflictor_received)', key: 'damage_inflictor_received', }, { ...jsonSelect, text: strings.heading_runes, alias: 'rune_id', join: ', json_each(player_matches.runes)', key: 'runes', }, { ...jsonSelect, text: strings.heading_unit_kills, join: ', json_each(player_matches.killed)', key: 'unit_kills', }, { ...jsonSelect, text: strings.heading_damage_instances, join: ', json_each(player_matches.hero_hits)', key: 'damage_instances', }, // killSelect({ // text: strings.heading_courier, // unitKey: 'npc_dota_courier', // }), // killSelect({ // text: strings.heading_roshan, // unitKey: 'npc_dota_roshan', // }), // killSelect({ // text: strings.heading_tower, // unitKey: '%tower%', // }), // killSelect({ // text: strings.heading_barracks, // unitKey: '%rax%', // }), // killSelect({ // text: strings.heading_shrine, // unitKey: '%healers%', // }), { text: strings.explorer_hero_combos, value: 1, groupValue: 1, groupKeySelect: 'player_matches.hero_id, player_matches2.hero_id hero_id2', groupKey: 'player_matches.hero_id, player_matches2.hero_id', joinFn: props => `JOIN player_matches player_matches2 ON player_matches.match_id = player_matches2.match_id AND player_matches.hero_id != player_matches2.hero_id AND abs(player_matches.player_slot - player_matches2.player_slot) < 10 ${props.hero && props.hero.value ? '' : 'AND player_matches.hero_id < player_matches2.hero_id'}`, key: 'hero_combos', bundle: 'combinations', }, { text: strings.explorer_hero_player, value: 1, groupValue: 1, groupKey: 'player_matches.hero_id, player_matches.account_id', key: 'hero_player', bundle: 'combinations', }, { text: strings.explorer_player_player, value: 1, groupValue: 1, groupKeySelect: 'player_matches.account_id, player_matches2.account_id account_id2', groupKey: 'player_matches.account_id, player_matches2.account_id', joinFn: props => `JOIN player_matches player_matches2 ON player_matches.match_id = player_matches2.match_id AND player_matches.account_id != player_matches2.account_id AND abs(player_matches.player_slot - player_matches2.player_slot) < 10 ${props.player && props.player.value ? '' : 'AND player_matches.account_id < player_matches2.account_id'}`, key: 'player_player', bundle: 'combinations', }, { text: strings.explorer_picks_bans, template: 'picks_bans', key: 'picks_bans', // picks_bans.team is 0 for radiant, 1 for dire where: 'AND team_match.radiant::int != picks_bans.team', value: 1, bundle: 'picks_bans', }, { text: strings.explorer_counter_picks_bans, template: 'picks_bans', key: 'counter_picks_bans', where: 'AND team_match.radiant::int = picks_bans.team', value: 1, bundle: 'picks_bans', }, ] .concat(Object.keys(items).filter(itemKey => items[itemKey].cd).map(usesSelect)) // .concat(Object.keys(items).filter(itemKey => items[itemKey].cost > 2000).map(timingSelect)) .concat(singleFields) .sort((a, b) => a.text && a.text.localeCompare(b.text)), group: [{ text: strings.explorer_player, value: 'notable_players.name', key: 'player', }, { text: strings.th_hero_id, value: 'heroes.localized_name', key: 'hero', }, { text: strings.explorer_league, value: 'leagues.name', alias: 'leaguename', key: 'league', }, { text: strings.explorer_patch, value: 'patch', key: 'patch', }, { text: strings.heading_duration, value: 'duration/300*5', alias: 'minutes', key: 'duration', }, { text: strings.explorer_side, value: '(player_matches.player_slot < 128)', alias: 'is_radiant', key: 'side', }, { text: strings.th_result, value: '((player_matches.player_slot < 128) = matches.radiant_win)', alias: 'win', key: 'result', }, { text: strings.explorer_team, value: 'teams.name', key: 'team', }, { text: strings.explorer_organization, value: 'teams2.name', key: 'organization', }, { text: strings.explorer_match, value: 'matches.match_id', key: 'match', }, ].concat(singleFields), minPatch: patches, maxPatch: patches, hero: Object.keys(heroData).map(heroId => ({ text: `[${heroId}] ${heroData[heroId].localized_name}`, searchText: heroData[heroId].localized_name, value: heroData[heroId].id, key: String(heroData[heroId].id), })), playerPurchased: Object.keys(items).map(itemName => ({ text: items[itemName].dname, value: itemName, key: itemName, })), minDuration: durations, maxDuration: durations, side: [{ text: strings.general_radiant, value: true, key: 'radiant', }, { text: strings.general_dire, value: false, key: 'dire', }], result: [{ text: strings.td_win, value: true, key: 'win', }, { text: strings.td_loss, value: false, key: 'loss', }], region: Object.keys(regionData).map(regionKey => ({ text: strings[`region_${regionKey}`], value: Object.keys(clusterData).filter(key => String(clusterData[key]) === regionKey), key: String(regionKey), })), league: leagues.map(league => ({ text: `[${league.leagueid}] ${league.name}`, searchText: league.name, value: league.leagueid, key: String(league.leagueid), })), team: teams.map(team => ({ text: `[${team.team_id}] ${team.name}`, searchText: team.name, value: team.team_id, key: String(team.team_id), })), organization: teams.map(team => ({ text: `[${team.team_id}] ${team.name}`, searchText: team.name, value: team.team_id, key: String(team.team_id), })), player: players.map(player => ({ text: `[${player.account_id}] ${player.name}`, searchText: player.name, value: player.account_id, key: String(player.account_id), })), tier: ['premium', 'professional'].map(tier => ({ text: strings[`tier_${tier}`], value: tier, key: tier, })), order: [{ text: strings.explorer_asc, value: 'ASC', key: 'asc' }, { text: strings.explorer_desc, value: 'DESC', key: 'desc' }], having, limit, laneRole: Object.keys(strings).filter(str => str.indexOf('lane_role_') === 0).map((str) => { const laneRoleId = Number(str.substring('lane_role_'.length)); return { text: strings[str], value: laneRoleId, key: String(laneRoleId) }; }), isTiTeam: [{ text: 'Yes', value: true, key: 'true' }], megaWin: [{ text: 'Yes', value: true, key: 'true' }], minGoldAdvantage: goldAdvantage, maxGoldAdvantage: goldAdvantage, }; }; export default getFields;
odota/web/src/components/Explorer/fields.js/0
{ "file_path": "odota/web/src/components/Explorer/fields.js", "repo_id": "odota", "token_count": 6798 }
246
import React from 'react'; import PropTypes from 'prop-types'; import Drawer from 'material-ui/Drawer'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton'; import MenuIcon from 'material-ui/svg-icons/navigation/menu'; import styled from 'styled-components'; import constants from '../../constants'; const StyledDrawer = styled(Drawer)` background-color: ${constants.defaultPrimaryColor} !important; `; const StyledMenuItem = styled(MenuItem)` display: block; `; export default class BurgerMenu extends React.Component { static propTypes = { menuItems: PropTypes.arrayOf({}), } constructor() { super(); this.state = { open: false }; this.handleToggle = () => this.setState({ open: !this.state.open }); this.handleClose = () => this.setState({ open: false }); } render() { return ( <div> <IconButton onClick={this.handleToggle}> <MenuIcon /> </IconButton> <StyledDrawer docked={false} width={260} open={this.state.open} onRequestChange={open => this.setState({ open })} > <Menu> {this.props.menuItems.map((item) => { const linkElement = React.cloneElement(item, { style: { width: '100%', display: 'block' } }); return ( <StyledMenuItem key={item.key} onClick={this.handleClose}> {linkElement} </StyledMenuItem> ); })} </Menu> </StyledDrawer> </div> ); } }
odota/web/src/components/Header/BurgerMenu/index.jsx/0
{ "file_path": "odota/web/src/components/Header/BurgerMenu/index.jsx", "repo_id": "odota", "token_count": 688 }
247
import React, { Component } from 'react'; import { shape, func, bool, arrayOf, oneOfType, string } from 'prop-types'; import { connect } from 'react-redux'; import { getBenchmark } from '../../actions'; import BenchmarkTable from './BenchmarkTable'; import BenchmarkGraphs from './BenchmarkGraphs'; import BenchmarkSkeleton from '../Skeletons/BenchmarkSkeleton'; const renderBenchmark = (hero, data, strings) => ( <div> <BenchmarkGraphs data={data} strings={strings} /> <BenchmarkTable data={data} /> </div> ); class Benchmark extends Component { static propTypes = { match: shape({ params: shape({ heroId: string, }), }), strings: shape({}), getBenchmark: func, isLoading: bool, isError: bool, hero: shape({}), result: oneOfType([ arrayOf(shape({})), shape({}), ]), } componentDidMount() { if ( this.props.match.params && this.props.match.params.heroId ) { this.props.getBenchmark(this.props.match.params.heroId); } } render() { const { isLoading, isError, hero, result, } = this.props; return ( <div> {isLoading || isError || result === null ? ( <BenchmarkSkeleton /> ) : ( renderBenchmark(hero, result, this.props.strings) )} </div> ); } } /** HISTOGRAM API <Histogram title: string binWidth: number (px) > <HistogramBin height: number (px) color: hex style: object /> <HistogramLegend position: enum label: string value: array /> </Hisogram> <MultiHistogram> <HistogramItem> </HistogramItem> </MultiHistogram> */ const mapStateToProps = state => ({ isLoading: state.app.heroBenchmark.loading, isError: state.app.heroBenchmark.error, result: state.app.heroBenchmark.data.result, }); const mapDispatchToProps = dispatch => ({ getBenchmark: heroId => dispatch(getBenchmark(heroId)), }); export default connect(mapStateToProps, mapDispatchToProps)(Benchmark);
odota/web/src/components/Hero/Benchmark.jsx/0
{ "file_path": "odota/web/src/components/Hero/Benchmark.jsx", "repo_id": "odota", "token_count": 796 }
248
import React from 'react'; import { Link } from 'react-router-dom'; import FlatButton from 'material-ui/FlatButton'; import { connect } from 'react-redux'; import { IconSteam } from '../Icons'; import { ButtonsDiv } from './Styled'; import config from '../../config'; import { HomePageProps } from './Home'; const Buttons = ({ user, strings }: HomePageProps) => ( <ButtonsDiv> { !user && <div> <FlatButton label={<span className="label"><b>{strings.home_login}</b> {strings.home_login_desc}</span>} icon={<IconSteam />} href={`${config.VITE_API_HOST}/login`} /> </div> } <div className="bottomButtons"> <div> <FlatButton label={<span className="label"><b>{strings.home_parse}</b> {strings.home_parse_desc}</span>} containerElement={<Link to="/request">{strings.home_parse}</Link>} /> </div> </div> </ButtonsDiv> ); const mapStateToProps = (state: any) => { const { data } = state.app.metadata; return { user: data.user, strings: state.app.strings, }; }; export default connect(mapStateToProps, null)(Buttons);
odota/web/src/components/Home/Buttons.tsx/0
{ "file_path": "odota/web/src/components/Home/Buttons.tsx", "repo_id": "odota", "token_count": 487 }
249
import React from 'react'; export default props => ( <svg {...props} viewBox="16 16 96 96"> <path d="M 27 38 c 14 -20 41 -26 62 -12 c 20 14 26 41 12 62 V 108 c 0 1 -1 2 -2 2 H 30 c -1 0 -2 -1 -2 -2 V 89 C 17 73 17 53 27 38 z M 35 89 h 58 c 14 -16 13 -40 -3 -55 c -16 -14 -40 -13 -55 3 C 22 52 22 74 35 89 z M 32 58 c 0 2 1 3 2 3 c 2 0 3 -1 3 -2 c 2 -10 9 -18 18 -21 c 2 0 2 -2 2 -4 c 0 -2 -2 -2 -4 -2 C 43 36 34 46 32 58 z" /> </svg> );
odota/web/src/components/Icons/CrystalBall.jsx/0
{ "file_path": "odota/web/src/components/Icons/CrystalBall.jsx", "repo_id": "odota", "token_count": 221 }
250
import React from 'react'; import styled from 'styled-components'; const icon = props => ( <svg {...props} viewBox="0 0 110 110"> <path d="M55,0C25.881,0,2.062,22.634,0.14,51.267l28.525,11.507C31.172,61.029,34.214,60,37.5,60 c0.706,0,1.396,0.063,2.076,0.155l13.426-19.691C53.021,29.159,62.19,20,73.5,20C84.822,20,94,29.178,94,40.5S84.822,61,73.5,61 c-0.01,0-0.021-0.001-0.031-0.001L52.944,74.385C52.97,74.754,53,75.124,53,75.5C53,84.061,46.061,91,37.5,91 c-7.565,0-13.855-5.422-15.218-12.591L2.118,70.107C8.685,93.134,29.866,110,55,110c30.376,0,55-24.624,55-55 C110,24.625,85.376,0,55,0z M37.5,84c-0.915,0-1.795-0.148-2.621-0.416l-0.004,0.01l-0.252-0.104 c-0.243-0.087-0.48-0.185-0.712-0.293l-6.805-2.801C28.945,84.295,32.902,87,37.5,87C43.851,87,49,81.852,49,75.5 S43.851,64,37.5,64c-1.406,0-2.747,0.265-3.993,0.727l7.2,2.904c0.05,0.021,0.1,0.039,0.149,0.061l0.56,0.226l-0.015,0.037 C44.131,69.368,46,72.213,46,75.5C46,80.194,42.194,84,37.5,84z M88,40.5C88,32.492,81.508,26,73.5,26S59,32.492,59,40.5 S65.492,55,73.5,55S88,48.508,88,40.5z M63,40.5C63,34.701,67.701,30,73.5,30S84,34.701,84,40.5S79.299,51,73.5,51 S63,46.299,63,40.5z" /> </svg> ); export default styled(icon)` fill: #f5f5f5; height: 16px; margin: 0 6px; transition: all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms; vertical-align: middle; width: auto !important; `;
odota/web/src/components/Icons/Steam.jsx/0
{ "file_path": "odota/web/src/components/Icons/Steam.jsx", "repo_id": "odota", "token_count": 875 }
251
import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import heroes from 'dotaconstants/build/heroes.json'; import ReactTooltip from 'react-tooltip'; import { abbreviateNumber } from '../../utility'; import { IconRadiant, IconDire } from '../Icons'; import constants from '../constants'; import HeroImage from '../Visualizations/HeroImage'; const StyledDiv = styled.div` table { border-collapse: separate !important; border-spacing: 0px 0px !important; padding: 3px !important; background-color: ${constants.secondarySurfaceColor}; width: 100%; background-color: rgba(255, 255, 255, 0.03); } tr { background-color: rgba(0, 0, 0, 0.019); } td { padding: 0px !important; height: 48px; white-space: normal !important; text-align: center; &:not(:last-child) { border-right: 1px solid rgba(255, 255, 255, 0.04); } } tr:not(:first-child) td{ @media screen and (max-width: ${constants.wrapMobile}) { padding-top: 5px !important; padding-bottom: 5px !important; } } tr:not(:first-child) td { border-top: 1px solid rgba(255, 255, 255, 0.06); } tr:first-child td:first-child { background-color: rgba(0, 0, 0, 0.27) !important; } tr:first-child td:not(:first-child) { background: linear-gradient(to bottom, ${constants.tableHeaderSurfaceColor} 15% , rgba(35, 0, 0, 0.3) 100%) !important; } td > div { text-align: center; } td:first-child { width: 30px !important; } tr:first-child { height: 30px !important; & td { height: 30px !important; } } tr:not(:first-child) td:first-child { border-right: 1px solid ${constants.colorMutedGreen} !important; background: linear-gradient(to right, ${constants.tableHeaderSurfaceColor} 15% , rgba(0, 35, 0, 0.3) 100%) !important; & > div { position: relative; top: 3px; left: 1px; } } tr:first-child td { & > div { position: relative; top: 2px; } } tr:nth-child(2) td:not(:first-child) { border-top: 1px solid ${constants.colorMutedRed} !important; } .value-1 { display: inline-block; background: rgba(0, 3, 0, 0.3); width: 38px; height: 21px; margin: 1px 1px 1px 1px; text-align: center; border: 1px solid ${constants.colorMutedGreen}; color: ${constants.colorMutedLight}; &:nth-child(2) { border: 1px solid ${constants.colorMutedRed} !important; background: rgba(3, 0, 0, 0.3) !important; } & span { vertical-align: middle; } } .hero img { width: 25px; } .team { margin: auto; width: 25px; & svg { margin: 0 !important; } } `; const CrossTable = ({ match, field1, field2, strings, }) => ( <StyledDiv> <table selectable={false} > <tbody displayRowCheckbox={false}> <tr> <td /> {match.players.slice(match.players.length / 2, match.players.length).map(player => ( <td key={player.hero_id}> <div className="hero"> {heroes[player.hero_id] && <HeroImage id={player.hero_id} isIcon data-tip={heroes[player.hero_id] && heroes[player.hero_id].localized_name} />} </div> </td>))} <td> <div className="team"> <IconDire data-tip={strings.general_dire} /> </div> </td> </tr> {match.players.slice(0, match.players.length / 2).map(player => ( <tr key={player.hero_id}> <td> <div className="hero"> {heroes[player.hero_id] && <HeroImage id={player.hero_id} isIcon data-tip={heroes[player.hero_id] && heroes[player.hero_id].localized_name} />} </div> </td> {match.players.slice(match.players.length / 2, match.players.length).map((player2) => { const hero1 = heroes[player.hero_id] || {}; const hero2 = heroes[player2.hero_id] || {}; const pfield1 = player[field1] || {}; const pfield2 = player[field2] || {}; const pvalue1 = pfield1[hero2.name] || 0; const pvalue2 = pfield2[hero2.name] || 0; return ( <td key={player2.hero_id}> <div data-tip data-for={`${field1}_${field2}_${player.player_slot}_${player2.player_slot}`}> <div className="value-1" style={{ color: pvalue1 > pvalue2 ? constants.primaryTextColor : '' }}><span>{abbreviateNumber(pvalue1)}</span></div> <div className="value-1" style={{ color: pvalue2 > pvalue1 ? constants.primaryTextColor : '' }}><span>{abbreviateNumber(pvalue2)}</span></div> <ReactTooltip id={`${field1}_${field2}_${player.player_slot}_${player2.player_slot}`} place="top" effect="solid"> {`${hero1.localized_name} โ†’ ${hero2.localized_name}: ${pvalue1}`} <br /> {`${hero2.localized_name} โ†’ ${hero1.localized_name}: ${pvalue2}`} </ReactTooltip> </div> </td>); })} {(() => { const hero1 = heroes[player.hero_id] || {}; let ptotal1 = 0; let ptotal2 = 0; match.players.slice(match.players.length / 2, match.players.length).forEach((player2) => { const hero2 = heroes[player2.hero_id] || {}; ptotal1 += (player[field1] && hero2.name in player[field1]) ? player[field1][hero2.name] : 0; ptotal2 += (player[field2] && hero2.name in player[field2]) ? player[field2][hero2.name] : 0; }); return ( <td key={`${player.hero_id}_totals`}> <div data-tip data-for={`${field1}_${field2}_${player.player_slot}_radiant`}> <div className="value-1" style={{ color: ptotal1 > ptotal2 ? constants.primaryTextColor : '' }}><span>{abbreviateNumber(ptotal1)}</span></div> <div className="value-1" style={{ color: ptotal2 > ptotal1 ? constants.primaryTextColor : '' }}><span>{abbreviateNumber(ptotal2)}</span></div> <ReactTooltip id={`${field1}_${field2}_${player.player_slot}_radiant`} place="top" effect="solid"> {`${hero1.localized_name} โ†’ ${strings.general_dire}: ${ptotal1}`} <br /> {`${strings.general_dire} โ†’ ${hero1.localized_name}: ${ptotal2}`} </ReactTooltip> </div> </td> ); })()} </tr>))} <tr> <td> <div className="team"> <IconRadiant data-tip={strings.general_radiant} /> </div> </td> { match.players.slice(match.players.length / 2, match.players.length).map((player) => { const hero1 = heroes[player.hero_id] || {}; let ptotal1 = 0; let ptotal2 = 0; match.players.slice(0, match.players.length / 2).forEach((player2) => { const hero2 = heroes[player2.hero_id] || {}; ptotal1 += (player[field1] && hero2.name in player[field1]) ? player[field1][hero2.name] : 0; ptotal2 += (player[field2] && hero2.name in player[field2]) ? player[field2][hero2.name] : 0; }); return ( <td key={`${player.hero_id}_totals`}> <div data-tip data-for={`${field1}_${field2}_${player.player_slot}_dire`}> <div className="value-1" style={{ color: ptotal2 > ptotal1 ? constants.primaryTextColor : '' }}><span>{abbreviateNumber(ptotal2)}</span></div> <div className="value-1" style={{ color: ptotal1 > ptotal2 ? constants.primaryTextColor : '' }}><span>{abbreviateNumber(ptotal1)}</span></div> <ReactTooltip id={`${field1}_${field2}_${player.player_slot}_dire`} place="top" effect="solid"> {`${strings.general_radiant} โ†’ ${hero1.localized_name}: ${ptotal2}`} <br /> {`${hero1.localized_name} โ†’ ${strings.general_radiant}: ${ptotal1}`} </ReactTooltip> </div> </td> ); }) } {(() => { let radiantTotal = 0; let direTotal = 0; match.players.slice(match.players.length / 2, match.players.length).forEach((player) => { const hero = heroes[player.hero_id] || {}; match.players.slice(0, match.players.length / 2).forEach((player2) => { const hero2 = heroes[player2.hero_id] || {}; radiantTotal += (player2[field1] && hero.name in player2[field1]) ? player2[field1][hero.name] : 0; direTotal += (player[field1] && hero2.name in player[field1]) ? player[field1][hero2.name] : 0; }); }); return ( <td> <div data-tip data-for={`${field1}_${field2}_total`}> <div className="value-1" style={{ color: radiantTotal > direTotal ? constants.primaryTextColor : '' }}><span>{abbreviateNumber(radiantTotal)}</span></div> <div className="value-1" style={{ color: direTotal > radiantTotal ? constants.primaryTextColor : '' }}><span>{abbreviateNumber(direTotal)}</span></div> <ReactTooltip id={`${field1}_${field2}_total`} place="top" effect="solid"> {`${strings.general_radiant} โ†’ ${strings.general_dire}: ${radiantTotal}`} <br /> {`${strings.general_dire} โ†’ ${strings.general_radiant}: ${direTotal}`} </ReactTooltip> </div> </td> ); })()} </tr> </tbody> </table> </StyledDiv>); CrossTable.propTypes = { match: PropTypes.shape({}), field1: PropTypes.string, field2: PropTypes.string, strings: PropTypes.shape({}), }; const mapStateToProps = state => ({ strings: state.app.strings, }); export default connect(mapStateToProps)(CrossTable);
odota/web/src/components/Match/CrossTable.jsx/0
{ "file_path": "odota/web/src/components/Match/CrossTable.jsx", "repo_id": "odota", "token_count": 4867 }
252
import styled from 'styled-components'; import constants from '../constants'; export const StyledAbilityUpgrades = styled.div` margin: -8px; & .ability { position: relative; display: inline-block; &:first-of-type { margin-left: 0; } &:last-of-type { margin-right: 0; } & > div { background-color: ${constants.darkPrimaryColor}; height: 30px; width: 30px; text-align: center; bottom: 0; left: 0; font-size: 10px; } & .placeholder { background-color: transparent; } } /* React-tooltip ability upgrades */ & > div { pointer-events: auto !important; /*margin-left: 3px !important; margin-top: 1px !important; /*padding: 6px 12px 2px !important;*/ &:hover { visibility: visible !important; opacity: 1 !important; } &::after { border-width: 20px !important; right: 0 !important; top: 0 !important; } } & svg { padding-left: 7px; } `; export const StyledAghanimsBuffs = styled.div` min-height: 44px; > img { width: 24px; } .__react_component_tooltip { opacity: 1 !important; padding: 0px !important; } ` export const StyledLevel = styled.div` display: flex; position: relative; align-items: center; justify-content: center; .circular_chart { position: absolute; fill: none; width: 70%; } .circle { stroke: #a9a9a94d; stroke-width: 2.8; stroke-linecap: round; } ` export const StyledCosmetic = styled.div` display: inline-block; margin: 5px; & img { height: 42px; } & > div { font-size: ${constants.fontSizeCommon}; & span > span { font-size: ${constants.fontSizeSmall}; color: ${constants.colorMutedLight}; text-transform: capitalize; display: block; } } & a { transition: ${constants.normalTransition}; position: relative; &:hover { cursor: pointer; opacity: 0.8; & svg { display: block !important; } } } & svg { position: absolute; /* override material-ui */ fill: ${constants.primaryLinkColor} !important; display: none !important; width: 18px !important; height: 18px !important; filter: drop-shadow(0 0 3px ${constants.darkPrimaryColor}); right: 2px; bottom: 6px; } `; export const StyledUnusedItem = styled.div` display: inline-block; vertical-align: middle; `; export const StyledGoldIcon = styled.span` img { height: 10px; margin-right: 4px; } `; export const StyledRunes = styled.div` display: inline-block; & img { height: 24px; vertical-align: middle; margin-right: 5px; filter: drop-shadow(0 0 5px rgba(255, 255, 255, 0.08)); } & span { text-transform: none; font-weight: ${constants.fontWeightNormal}; } `; export const StyledDivClearBoth = styled.div` min-width: 240px; > div { clear: both; } `; export const StyledBackpack = styled.div` display: flex; flex-wrap: wrap; & > div { position: relative; &[data-hint] { &::before { left: 14px; } &::after { margin-left: -34px; } } } & svg { position: relative; top: 2px; width: 17px; height: 16px; fill: ${constants.colorMutedLight}; margin: 0 4px 0 0; } `; export const StyledFlexContainer = styled.div` display: flex; flex-direction: column; flex-wrap: wrap; overflow: visible; @media only screen and (min-width: 800px) { flex-direction: row; } `; export const StyledFlexElement = styled.div` flex: 1; margin-right: 5px; `; export const StyledFlexElementFullWidth = styled.div`- margin-right: 5px; width: 100%; `; export const StyledTeamIconContainer = styled.span` vertical-align: top; height: 26px !important; width: 26px !important; margin-right: 6px; opacity: 0.8; fill: ${constants.textColorPrimary}; `; export const StyledPlayersDeath = styled.div` position: relative; float: left; margin: 1px; height: 29px; & img { height: 29px; } `; export const StyledEmote = styled.img.attrs({ alt: props => props.emote, src: props => `/assets/images/dota2/emoticons/${props.emote}.gif`, })` width: 20px; height: 20px; vertical-align: bottom; `; export const StyledStorySpan = styled.span` white-space: nowrap; color: ${props => (props.isRadiant ? constants.colorGreen : constants.colorRed)}; svg, img { vertical-align: middle; max-height: 20px; margin-right: 2px; fill: ${constants.textColorPrimary}; } svg { opacity: 0.8; height: 20px; } `; export const StyledStoryWrapper = styled.div` line-height: 30px; > div { margin-bottom: 20px; } `; export const StyledStoryNetWorthBar = styled.div` display: flex; position: relative; &::after { content: ""; position: absolute; width: 4px; height: 13px; background-color: white; left: 50%; margin-left: -2px; } > div { display: inline-block; height: 7px; > div:first-child { border-bottom-left-radius: 3px; border-top-left-radius: 3px; > div:last-child { border-bottom-right-radius: 3px; border-top-right-radius: 3px; } `; export const StyledStoryNetWorthText = styled.div` position: relative; display: flex; text-align: center; ${props => (props.color ? `background-color:${props.color}` : '')}; ${props => (props.left ? `left:${props.left}%` : '')}; width: ${props => props.width}%; > div { display: inline-block; } > div:nth-child(2) { position: absolute; transform: translateX(-50%); @media only screen and (max-width: 768px) { display: none; } } `; export const StyledStoryGoldAmount = styled.span` color: ${constants.colorGolden}; `; export const StyledLogFilterForm = styled.div` max-width: 800px; display: flex; flex-direction: row; margin-left: auto; margin-right: auto; margin-top: 50px; flex-wrap: wrap; border-radius: 4px; border: 1px solid rgb(255, 255, 255, 0.06); background: ${constants.colorBoxBlue}; & > div { padding: 10px; } & .title { width: 100%; text-transform: uppercase; font-weight: bold; letter-spacing: 0.08em; color: rgba(255, 255, 255, 0.6); border-bottom: 1px solid rgb(255, 255, 255, 0.06); } `; export const StyledDmgTargetInflictor = styled.div` .inflictorWithValue { object { max-width: 27px !important; } } `; export const StyledDmgTargetRow = styled.div` > div { padding-top: 10px; padding-bottom: 10px; } #heroTargetValue { display: none; } #row:hover { svg { opacity: 1 !important; transition: opacity 0.2s ease !important; backface-visibility: hidden; } #target { img { background: rgba(74, 149, 247, 0.5) !important; transition: background 0.2s ease !important; box-shadow: 0px 0px 10px rgba(74, 149, 247, 0.5); } } #targetvalue { background-color: black !important; } #heroTargetValue { display: inline !important; } #totalValue { display: none !important; } .inflictorWithValue { & .overlay { background-color: black; } } } `; export const StyledLineWinnerSpan = styled.span` & svg { width: 20px !important; height: 20px !important; fill: ${constants.colorGolden}; } `;
odota/web/src/components/Match/StyledMatch.jsx/0
{ "file_path": "odota/web/src/components/Match/StyledMatch.jsx", "repo_id": "odota", "token_count": 3081 }
253
const queryTemplate = (props) => { const { group, minMmr, maxMmr, hero, minDuration, maxDuration, side, result, gameMode, lobbyType, minDate, maxDate, minRankTier, maxRankTier, // having, // limit, } = props; const groupVal = group ? `${group.value}${group.bucket ? ` / ${group.bucket} * ${group.bucket}` : ''}` : 'hero_id'; const query = ` select ${groupVal} ${(group && group.alias) || ''}, count(distinct match_id) games, ${!hero ? `count(distinct match_id)::float/sum(count(1)) OVER() * ${group ? group.groupSize || 1 : 10} pickrate,` : ''} sum(case when radiant_win = (player_slot < 128) then 1 else 0 end)::float/count(1) winrate FROM public_matches JOIN public_player_matches using(match_id) JOIN heroes on public_player_matches.hero_id = heroes.id WHERE start_time >= extract(epoch from ${minDate ? `timestamp '${minDate.value}'` : 'now() - interval \'12 hour\''})::int ${minMmr ? `AND avg_mmr >= '${minMmr.value}'` : ''} ${maxMmr ? `AND avg_mmr <= '${maxMmr.value}'` : ''} ${minRankTier ? `AND floor(avg_rank_tier / 10) >= ${minRankTier.value}` : ''} ${maxRankTier ? `AND floor(avg_rank_tier / 10) <= ${maxRankTier.value}` : ''} ${hero ? `AND public_player_matches.hero_id = ${hero.value}` : ''} ${minDuration ? `AND public_matches.duration >= ${minDuration.value}` : ''} ${maxDuration ? `AND public_matches.duration <= ${maxDuration.value}` : ''} ${side ? `AND (public_player_matches.player_slot < 128) = ${side.value}` : ''} ${result ? `AND ((public_player_matches.player_slot < 128) = public_matches.radiant_win) = ${result.value}` : ''} ${gameMode ? `AND game_mode = '${gameMode.value}'` : ''} ${lobbyType ? `AND lobby_type = '${lobbyType.value}'` : ''} ${maxDate ? `AND start_time <= extract(epoch from timestamp '${maxDate.value}')::int` : ''} GROUP BY ${groupVal} ORDER BY games desc LIMIT 500 `; return query // Remove extra newlines .replace(/\n{2,}/g, '\n'); }; export default queryTemplate; // const minDateThreshold = new Date(new Date()) - (1000 * 60 * 60 * 24 * 30)); // TABLESAMPLE SYSTEM_ROWS(1000) // Postgres query optimizer refuses to use index scan when date range is too large (>3 days or so)
odota/web/src/components/Meta/queryTemplate.js/0
{ "file_path": "odota/web/src/components/Meta/queryTemplate.js", "repo_id": "odota", "token_count": 840 }
254
export default strings => ([{ displayName: strings.th_category, field: 'category', sortFn: true, }, { displayName: strings.th_matches, field: 'matches', sortFn: true, relativeBars: true, }, { displayName: strings.th_win, field: 'winPercent', sortFn: row => row.winPercent / 100, // percentBars expects decimal value percentBars: true, }]);
odota/web/src/components/Player/Pages/Counts/playerCountsColumns.jsx/0
{ "file_path": "odota/web/src/components/Player/Pages/Counts/playerCountsColumns.jsx", "repo_id": "odota", "token_count": 127 }
255
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getPlayerRankings } from '../../../../actions'; import Table from '../../../Table'; import Container from '../../../Container'; import playerRankingsColumns from './playerRankingsColumns'; const Rankings = ({ data, error, loading, strings, }) => ( <div> <Container title={strings.heading_rankings} subtitle={strings.rankings_description} error={error} loading={loading}> <Table columns={playerRankingsColumns(strings)} data={data} placeholderMessage={strings.rankings_none} /> </Container> </div> ); Rankings.propTypes = { data: PropTypes.arrayOf({}), error: PropTypes.string, loading: PropTypes.bool, strings: PropTypes.shape({}), }; const getData = (props) => { props.getPlayerRankings(props.playerId, props.location.search); }; class RequestLayer extends React.Component { static propTypes = { location: PropTypes.shape({ key: PropTypes.string, }), playerId: PropTypes.string, strings: PropTypes.shape({}), } componentDidMount() { getData(this.props); } componentDidUpdate(prevProps) { if (this.props.playerId !== prevProps.playerId || this.props.location.key !== prevProps.location.key) { getData(prevProps); } } render() { return <Rankings {...this.props} />; } } const mapStateToProps = state => ({ data: state.app.playerRankings.data, error: state.app.playerRankings.error, loading: state.app.playerRankings.loading, strings: state.app.strings, }); const mapDispatchToProps = dispatch => ({ getPlayerRankings: (playerId, options) => dispatch(getPlayerRankings(playerId, options)), }); export default connect(mapStateToProps, mapDispatchToProps)(RequestLayer);
odota/web/src/components/Player/Pages/Rankings/Rankings.jsx/0
{ "file_path": "odota/web/src/components/Player/Pages/Rankings/Rankings.jsx", "repo_id": "odota", "token_count": 597 }
256
import React from 'react'; import Helmet from 'react-helmet'; import Table from '../Table'; import Heading from '../Heading'; import Warning from '../Alerts'; // import RaisedButton from 'material-ui/RaisedButton'; // 60 days before const dateCutoff = '2022-08-11T07%3A00%3A00.000Z'; // # of group stage matches: (10 teams * 9 other teams) / 2 (reciprocal plays) * 2 (2 groups) * 2 games each = 180 Group Stage // Tournament predictions use a cutoff where there are around 231 matches played by TI teams (Group Stage + 51 Main Event) const tournamentCutoff = '2022-08-27T07%3A00%3A00.000Z'; // Date at the time the predictions were made const dateMax = '2022-10-12T07%3A00%3A00.000Z'; /* SELECT count(1) FROM matches JOIN team_match using(match_id) JOIN teams using(team_id) WHERE TRUE AND matches.start_time >= extract(epoch from timestamp '2022-08-27T07:00:00.000Z') AND matches.start_time <= extract(epoch from timestamp '2022-10-12T07:00:00.000Z') AND teams.team_id IN (7119388,2586976,6209166,8254400,7391077,7732977,8260983,8291895,8599101,350190,39,7390454,8131728,8605863,8721219,6209804,8597976,2163,1838315,15) */ const predictionArray = [ { title: 'Hero most picked', link: `/explorer?group=hero&isTiTeam=true&minDate=${ dateCutoff }&select=picks_bans`, notes: 'Sort by picks', prediction: 'Tiny', }, { title: 'Hero most banned', link: `/explorer?group=hero&isTiTeam=true&minDate=${ dateCutoff }&select=picks_bans`, notes: 'Sort by bans', prediction: 'Faceless Void', }, { title: 'Hero with the highest winrate', link: `/explorer?order=&group=hero&isTiTeam=true&minDate=${ dateCutoff }&select=kills&having=10`, notes: 'Sort by winrate', prediction: 'Sniper', }, { title: 'Hero with the highest kill avg', link: `/explorer?order=&group=hero&isTiTeam=true&minDate=${ dateCutoff }&select=kills&having=10`, prediction: 'Sniper', }, { title: 'Hero with the highest assist avg', link: `/explorer?order=&group=hero&isTiTeam=true&minDate=${ dateCutoff }&select=assists&having=10`, prediction: 'Venomancer', }, { title: 'Hero with the lowest death avg', link: `/explorer?group=hero&isTiTeam=true&minDate=${ dateCutoff }&select=deaths&having=10&order=asc`, prediction: 'Lycan', }, { title: 'Hero with the highest last hits avg', link: `/explorer?order=&group=hero&isTiTeam=true&minDate=${ dateCutoff }&select=last_hits&having=10`, prediction: 'Terrorblade', }, { title: 'Hero with the highest XPM avg', link: `/explorer?order=&group=hero&isTiTeam=true&minDate=${ dateCutoff }&select=xp_per_min&having=10`, prediction: 'Phantom Assassin', }, { title: 'Hero with the most kills', link: `/explorer?isTiTeam=true&minDate=${ dateCutoff }&select=kills`, prediction: 'Phantom Assassin', }, { title: 'Hero with the most last hits', link: `/explorer?isTiTeam=true&minDate=${ dateCutoff }&select=last_hits`, prediction: 'Naga Siren', }, { title: 'Team that wins', link: '/teams', prediction: 'PSG.LGD', notes: 'Based on team Elo rankings', }, { title: 'Team with the most kills in a game', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=kills`, prediction: 'Soniqs', }, { title: 'Team with the highest kill avg', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=kills`, prediction: 'Soniqs', }, { title: 'Team with the fewest deaths in a game', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=deaths&having=&order=asc`, prediction: 'Soniqs', }, { title: 'Team with the most assists in a game', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=assists`, prediction: 'Royal Never Give Up', }, { title: 'Team winning the longest game', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=duration`, prediction: 'Team Spirit', }, { title: 'Team winning the shortest game', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=duration&order=asc`, prediction: 'Thunder Awaken', }, { title: 'Team with highest game length avg', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=duration`, prediction: 'Team Spirit', }, { title: 'Team with most distinct heroes', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=distinct_heroes`, notes: 'Sort by distinct heroes', prediction: 'Hokori', }, { title: 'Team with fewest distinct heroes', link: `/explorer?group=team&isTiTeam=true&minDate=${ dateCutoff }&select=distinct_heroes`, notes: 'Sort by distinct heroes', prediction: 'Soniqs', }, { title: 'Player with the highest kill avg', link: `/explorer?group=player&isTiTeam=true&minDate=${ dateCutoff }&select=kills&having=10`, prediction: 'Somnus', }, { title: 'Player with the most kills in a game', link: `/explorer?group=&isTiTeam=true&minDate=${ dateCutoff }&select=kills&having=&order=`, prediction: 'Pakazs', }, { title: 'Player with the lowest death avg', link: `/explorer?group=player&isTiTeam=true&minDate=${ dateCutoff }&select=deaths&having=10&order=asc`, prediction: 'Somnus', }, { title: 'Player with the highest assist avg', link: `/explorer?group=player&isTiTeam=true&minDate=${ dateCutoff }&select=assists&having=10`, prediction: 'skem', }, { title: 'Player with the most assists in a game', link: `/explorer?group=&isTiTeam=true&minDate=${ dateCutoff }&select=assists&having=&order=`, prediction: '็šฎ็ƒ', }, { title: 'Player with the highest last hits avg', link: `/explorer?group=player&isTiTeam=true&minDate=${ dateCutoff }&select=last_hits&having=10`, prediction: 'YATOROGOD', }, { title: 'Player with the most last hits in a game', link: `/explorer?group=&isTiTeam=true&minDate=${ dateCutoff }&select=last_hits&having=&order=`, prediction: '่ง็‘Ÿ', }, { title: 'Player with the most GPM in a game', link: `/explorer?group=&isTiTeam=true&minDate=${ dateCutoff }&select=gold_per_min&having=&order=`, prediction: 'Raven', }, { title: 'Player with the highest GPM avg', link: `/explorer?group=player&isTiTeam=true&minDate=${ dateCutoff }&select=gold_per_min&having=10`, prediction: 'Raven', }, { title: 'Player with the most distinct heroes', link: `/explorer?group=player&isTiTeam=true&minDate=${ dateCutoff }&select=distinct_heroes`, prediction: 'Lumiรจre', notes: 'Sort by distinct heroes', }, { title: 'Tournament number of games in Main Event', prediction: '51', notes: '4 Bo1, 17 Bo3, 1 Bo5. (4) + (2.5 * 17) + (4) = 50.5 Main Event', }, { title: 'Tournament heroes picked', prediction: '111', link: `/explorer?group=&isTiTeam=true&minDate=${ tournamentCutoff }&select=picks_bans&having=&order=&maxDate=${ dateMax}`, notes: 'Number of heroes in the table with at least one pick', }, { title: 'Tournament heroes banned', prediction: '106', link: `/explorer?group=&isTiTeam=true&minDate=${ tournamentCutoff }&maxDate=${ dateMax }&select=picks_bans&having=&order=`, notes: 'Number of heroes in the table with at least one ban', }, { title: 'Tournament most kills in a game', prediction: '76', link: `/explorer?group=match&isTiTeam=true&minDate=${ tournamentCutoff }&maxDate=${ dateMax }&select=kills&having=&order=`, notes: 'Sort by SUM', }, { title: 'Tournament longest game', prediction: '69:29', link: `/explorer?group=&isTiTeam=true&minDate=${ tournamentCutoff }&maxDate=${ dateMax }&select=duration`, }, { title: 'Tournament shortest game', prediction: '18:17', link: `/explorer?group=&isTiTeam=true&minDate=${ tournamentCutoff }&maxDate=${ dateMax }&select=duration&having=&order=asc`, }, { title: 'Tournament most kills by a hero in a game', prediction: '28', link: `/explorer?group=&isTiTeam=true&minDate=${ tournamentCutoff }&maxDate=${ dateMax }&select=kills`, }, { title: 'Tournament most deaths by a hero in a game', prediction: '19', link: `/explorer?group=&isTiTeam=true&minDate=${ tournamentCutoff }&maxDate=${ dateMax }&select=deaths`, }, { title: 'Tournament most assists by a hero in a game', prediction: '34', link: `/explorer?group=&isTiTeam=true&minDate=${ tournamentCutoff }&maxDate=${ dateMax }&select=assists`, }, { title: 'Tournament highest GPM by a hero in a game', prediction: '1076', link: `/explorer?group=&isTiTeam=true&minDate=${ tournamentCutoff }&maxDate=${ dateMax }&select=gold_per_min`, }, ]; const predColumns = [ { displayName: 'Title', field: 'title' }, { displayName: 'Prediction', field: 'prediction' }, { displayName: 'Explore', field: 'link', displayFn: (row, col, field) => field ? ( <a href={field} target="_blank" rel="noopener noreferrer"> View in Explorer </a> ) : null, }, { displayName: 'Notes', field: 'notes', displayFn: (row, col, field) => <pre>{field}</pre>, }, ]; const Predictions = () => ( <div> <Helmet title="TI Predictions" /> <Heading title="TI Predictions" subtitle="Based on the last 60 days of games of the participating teams" /> <Warning className=""> These predictions assume future play will be similar to past play, which is not guaranteed! Use the Explorer link for each prediction if you want to examine the data in more detail. </Warning> <br /> <Table data={predictionArray} columns={predColumns} /> </div> ); export default Predictions;
odota/web/src/components/Predictions/index.jsx/0
{ "file_path": "odota/web/src/components/Predictions/index.jsx", "repo_id": "odota", "token_count": 3880 }
257
import React from 'react'; import ContentLoader from 'react-content-loader'; const AbilityBuildTableSkeleton = () => ( <ContentLoader height={600} width={1200} primaryColor="#666" secondaryColor="#ecebeb" animate> <rect x="0" y="0" rx="0" ry="0" width="1200" height="250" /> <rect x="0" y="300" rx="0" ry="0" width="1200" height="250" /> </ContentLoader> ); export default AbilityBuildTableSkeleton;
odota/web/src/components/Skeletons/AbilityBuildTableSkeleton.jsx/0
{ "file_path": "odota/web/src/components/Skeletons/AbilityBuildTableSkeleton.jsx", "repo_id": "odota", "token_count": 143 }
258
import Subscription from './Subscription'; export default Subscription;
odota/web/src/components/Subscription/index.js/0
{ "file_path": "odota/web/src/components/Subscription/index.js", "repo_id": "odota", "token_count": 17 }
259
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import { formatTemplateToString, getTeamLogoUrl } from '../../utility'; import { HeaderContainer, Logo, Column, TeamName, Row, TeamStatsCard } from './TeamStyled'; import config from '../../config'; export default (generalData, strings) => ( <HeaderContainer loading={generalData.loading} error={generalData.error}> <Logo src={getTeamLogoUrl(generalData.data.logo_url)} alt={`Logo for ${generalData.data.name}`} /> <Column> <TeamName>{generalData.data.name}</TeamName> <Row> <TeamStatsCard title={strings.th_wins} subtitle={<div className="textSuccess">{generalData.data.wins}</div>} /> <TeamStatsCard title={strings.th_losses} subtitle={<div className="textDanger">{generalData.data.losses}</div>} /> <TeamStatsCard title={strings.th_rating} subtitle={Math.floor(generalData.data.rating)} /> </Row> <Row> {config.VITE_ENABLE_RIVALRY && <FlatButton label={formatTemplateToString(strings.app_rivalry_team, generalData.data.name)} icon={<img src="/assets/images/rivalry-icon.png" alt="Sponsor logo for Rivalry.com" height="24px" />} href="https://rivalry.com/opendota" target="_blank" rel="noopener noreferrer" />} </Row> </Column> </HeaderContainer> );
odota/web/src/components/Team/TeamHeader.jsx/0
{ "file_path": "odota/web/src/components/Team/TeamHeader.jsx", "repo_id": "odota", "token_count": 628 }
260