text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
<!-- injected in manager head -->
| modernweb-dev/web/packages/dev-server-storybook/demo/wc/.storybook/manager-head.html/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/demo/wc/.storybook/manager-head.html",
"repo_id": "modernweb-dev",
"token_count": 8
} | 189 |
import { Plugin } from 'rollup';
import { injectExportsOrder } from '../../shared/stories/injectExportsOrder.js';
export function injectExportsOrderPlugin(storyFilePaths: string[]): Plugin {
return {
name: 'mdx',
transform(code, id) {
if (storyFilePaths.includes(id)) {
return injectExportsOrder(code, id);
}
},
};
}
| modernweb-dev/web/packages/dev-server-storybook/src/build/rollup/injectExportsOrderPlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/src/build/rollup/injectExportsOrderPlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 132
} | 190 |
declare module '@mdx-js/mdx' {
export default function async(
src: string,
options: { compilers: any; filepath: string },
): Promise<string>;
}
| modernweb-dev/web/packages/dev-server-storybook/types/mdx-js__mdx/index.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/types/mdx-js__mdx/index.d.ts",
"repo_id": "modernweb-dev",
"token_count": 57
} | 191 |
import { fileURLToPath } from 'url';
import { resolve } from 'path';
export default {
rootDir: resolve(fileURLToPath(import.meta.url), '..', '..', '..'),
middleware: [
function rewriteIndex(ctx, next) {
if (ctx.url === '/' || ctx.url === '/index.html') {
ctx.url = '/demo/index-rewrite/index.html';
}
return next();
},
],
};
| modernweb-dev/web/packages/dev-server/demo/index-rewrite/config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/demo/index-rewrite/config.mjs",
"repo_id": "modernweb-dev",
"token_count": 150
} | 192 |
import { DevServerConfig } from './DevServerConfig.js';
const arrayKeys = ['plugins', 'middleware'];
export function mergeConfigs(...configs: Partial<DevServerConfig | undefined>[]) {
const finalConfig: any = {
plugins: [],
middleware: [],
};
for (const config of configs) {
if (config) {
for (const [key, value] of Object.entries(config)) {
if (arrayKeys.includes(key)) {
if (Array.isArray(value)) {
finalConfig[key].push(...value);
}
} else {
finalConfig[key] = value;
}
}
}
}
return finalConfig as Partial<DevServerConfig>;
}
| modernweb-dev/web/packages/dev-server/src/config/mergeConfigs.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/src/config/mergeConfigs.ts",
"repo_id": "modernweb-dev",
"token_count": 263
} | 193 |
# @web/mocks
[`MSW`](https://mswjs.io/) integration layer for usage with [`@web/dev-server`](https://modern-web.dev/docs/dev-server/overview/), [`@web/test-runner`](https://modern-web.dev/docs/test-runner/overview/) and [`@web/dev-server-storybook`](https://modern-web.dev/docs/dev-server/plugins/storybook/#mainjs-and-previewjs).
## Defining mocks
`feature-a/demo/mocks.js`:
```js
import { http } from '@web/mocks/http.js';
import mocksFromAnotherFeature from 'another-feature/demo/mocks.js';
/**
* Define mock scenarios
*/
export default {
/**
* Return an object from the handler
*/
default: [http.get('/api/foo', context => Response.json({ foo: 'bar' }))],
/**
* Return native `Response` object from the handler
*/
error: [http.get('/api/foo', context => new Response('', { status: 400 }))],
/**
* Handle additional custom logic in the handler, based on url, searchparams, whatever
*/
custom: [
/**
* Customize based on searchParams
*/
http.get('/api/users', ({ request }) => {
const searchParams = new URL(request.url).searchParams;
if (searchParams.get('user') === '123') {
return Response.json({ id: '123', name: 'frank' });
}
return Response.json({ id: '456', name: 'bob' });
}),
/**
* Customize based on params
*/
http.get('/api/users/:id', ({ params }) => {
if (params.id === '123') {
return new Response('', { status: 400 });
}
return Response.json({ id: '456', name: 'bob' });
}),
/**
* Customize based on cookies
*/
http.get('/api/abtest', ({ cookies }) => {
return Response.json({ abtest: cookies.segment === 'business' });
}),
],
/**
* Provide an async fn, a fn returning an object, a fn returning a Response, or just an object
*/
returnValues: [
http.get('/api/foo', async context => Response.json({ foo: 'bar' })),
http.get(
'/api/foo',
async context => new Response(JSON.stringify({ foo: 'bar' }), { status: 200 }),
),
http.get('/api/foo', context => Response.json({ foo: 'bar' })),
http.get('/api/foo', context => new Response(JSON.stringify({ foo: 'bar' }), { status: 200 })),
],
importedMocks: [
mocksFromAnotherFeature.default,
http.get('/api/foo', () => Response.json({ foo: 'bar' })),
],
};
```
### Context
The `context` object that gets passed to the handler includes:
```js
http.get('/api/foo', ({ request, cookies, params }) => {
return Response.json({ foo: 'bar' });
});
```
- `request` the native `Request` object
- `cookies` an object based on the request cookies
- `params` an object based on the request params
## `@web/dev-server`/`@web/dev-server-storybook`
`feature-a/web-dev-server.config.mjs`:
```js
import { storybookPlugin } from '@web/dev-server-storybook';
import { mockPlugin } from '@web/mocks/plugins.js';
export default {
nodeResolve: true,
plugins: [mockPlugin(), storybookPlugin({ type: 'web-components' })],
};
```
You can also add the `mockRollupPlugin` to your `.storybook/main.cjs` config for when you're bundling your Storybook to deploy somewhere; your mocks will be deployed along with your Storybook, and will work in whatever environment you deploy them to.
`feature-a/.storybook/main.cjs`:
```diff
module.exports = {
stories: ['../stories/**/*.stories.{js,md,mdx}'],
+ rollupConfig: async config => {
+ const { mockRollupPlugin } = await import('@web/mocks/plugins.js');
+ config.plugins.push(mockRollupPlugin());
+ return config;
+ },
};
```
<details>
<summary>
<b><code>mockRollupPlugin</code> configuration options</b>
</summary>
The rollup plugin also takes an optional <code>interceptor</code>, which can be useful to handle things like rewriting <code>api.</code> prefixes made in requests, for example:
```js
mockRollupPlugin({
interceptor: `
const domain = window.location.hostname;
const apiDomain = "api." + domain;
const { fetch: originalFetch } = window;
async function fetch(request) {
request = new Request(request);
const resolvedURL = new URL(request.url, window.location);
if (resolvedURL.hostname === apiDomain) {
// rewrite hostname without api.
resolvedURL.hostname = domain;
const init = {};
for (const property in request) {
init[property] = request[property];
}
request = new Request(resolvedURL.href, init);
if (request.body != null) {
request = new Request(request, { body: await request.arrayBuffer() });
}
}
return originalFetch(request);
}
window.fetch = fetch;
`,
});
```
This can be used to avoid CORS issues when deploying your Storybooks.
</details>
<br/>
And add the addon:
`feature-a/.storybook/main.cjs`:
```diff
module.exports = {
stories: ['../stories/**/*.stories.{js,md,mdx}'],
// for Storybook 7 (@web/storybook-builder)
+ addons: ['@web/mocks/storybook/addon/manager.js'],
// for Storybook 6 (@web/dev-server-storybook)
+ addons: ['@web/mocks/storybook/addon.js'],
rollupConfig: async config => {
const { mockRollupPlugin } = await import('@web/mocks/plugins.js');
config.plugins.push(mockRollupPlugin());
return config;
},
};
```
`feature-a/.storybook/preview.js`:
```js
// for Storybook 7 (@web/storybook-builder)
import { withMocks } from '@web/mocks/storybook/addon/decorator.js';
// for Storybook 6 (@web/dev-server-storybook)
import { withMocks } from '@web/mocks/storybook/decorator.js';
export const decorators = [withMocks];
```
`feature-a/stories/default.stories.js`:
```js
import { html } from 'lit';
import { http } from '@web/mocks/http.js';
import mocks from '../demo/mocks.js';
export const Default = () => html`<feature-a></feature-a>`;
Default.story = {
parameters: {
mocks: mocks.default,
// or
mocks: [
mocks.default,
otherMocks.error,
http.get('/api/bar', () => Response.json({ bar: 'bar' })),
http.post('/api/baz', () => new Response('', { status: 400 })),
],
// or
mocks: [
http.get('/api/users/:id', ({ params }) => {
if (params.id === '123') {
return Response.json({ name: 'frank' });
}
return Response.json({ name: 'bob' });
}),
],
},
};
```
## `@web/test-runner`
The `registerMockRoutes` function will ensure the service worker is installed, and the `mockPlugin` takes care of resolving the service worker file, so users don't have to keep this one-time generated service worker file in their own project roots.
`feature-a/web-test-runner.config.mjs`:
```js
import { mockPlugin } from '@web/mocks/plugins.js';
export default {
nodeResolve: true,
files: ['test/**/*.test.js'],
plugins: [mockPlugin()],
};
```
`feature-a/test/my-test.test.js`:
```js
import { registerMockRoutes } from '@web/mocks/browser.js';
import { http } from '@web/mocks/http.js';
import mocks from '../demo/mocks.js';
import featureBmocks from 'feature-b/demo/mocks.js';
describe('feature-a', () => {
it('works', async () => {
registerMockRoutes(http.get('/api/foo', () => Response.json({ foo: 'foo' })));
const response = await fetch('/api/foo').then(r => r.json());
expect(response.foo).to.equal('foo');
});
it('works', () => {
registerMockRoutes(
// Current project's mocks
mocks.default, // is an array, arrays get flattened in the integration layer
// Third party project's mocks, that uses a different version of MSW internally
featureBmocks.default,
// Additional mocks
http.get('/api/baz', context => Response.json({ baz: 'baz' })),
);
});
});
```
## Mocking requests in node.js
You can also mock requests in node.js:
```js
import { registerMockRoutes } from '@web/mocks/node.js';
import { http } from '@web/mocks/http.js';
registerMockRoutes(
http.get('/api/foo', () => new Response(JSON.stringify({ foo: 'bar' }), { status: 200 })),
);
const r = await fetch('/api/foo').then(r => r.json());
console.assert(r.foo === 'bar');
```
## Rationale
### Why not use MSW directly?
Large applications may have many features, that themself may depend on other features internally. Consider the following example:
`feature-a` uses `feature-b` internally. `feature-a` wants to reuse the mocks of `feature-b`, but the versions of msw are different.
- `feature-a` uses `msw@1.0.0`
- `feature-b` uses `msw@2.0.0`
```js
import mocks from '../demo/mocks.js';
import featureBmocks from 'feature-b/demo/mocks.js';
const Default = () => html`<feature-a></feature-a>`; // uses `feature-b` internally
Default.story = {
parameters: {
mocks: [
mocks.default, // uses MSW@1.0.0
featureBmocks.default, // ❌ uses MSW@2.0.0, incompatible mocks -> MSW@2.0.0 may expect a different service worker, or different API!
],
},
};
```
`msw@2.0.0` may have a different API or it's service worker may expect a different message, event, or data format. In order to ensure forward compatibility, we expose a "middleman" function:
```js
import { http } from '@web/mocks/http.js';
http.get('/api/foo', () => Response.json({ foo: 'bar' }));
```
The middleware function simply returns an object that looks like:
```js
{
method: 'get',
endpoint: '/api/foo',
handler: () => Response.json({foo: 'bar'})
}
```
This way we can support multiple versions of `msw` inside of our integration layer by acting as a bridge of sorts; the function people define mocks with doesn't directly depend on `msw` itself, it just creates an object with the information we need to pass on to msw.
That way, `feature-a`'s project controls the dependency on `msw` (via the msw integration layer package), while still being able to use mocks from other projects that may use a different version of `msw` themself internally.
In the wrapper, we standardize on native `Request` and `Response` objects; the handler function receives a `Request` object, and returns a `Response` object. For utility, we also pass `cookies` and `params`, since those are often used to conditionally return mocks. This means that the wrapper function only depends on standard, browser-native JS, and itself has no other dependencies, which is a good foundation to ensure forward compatibility.
### Requests/Responses
The `Request` and `Response` objects used are standard JS `Request` and `Response` objects. You can read more about them on MDN.
| modernweb-dev/web/packages/mocks/README.md/0 | {
"file_path": "modernweb-dev/web/packages/mocks/README.md",
"repo_id": "modernweb-dev",
"token_count": 3725
} | 194 |
// @ts-nocheck
import { addons, makeDecorator } from '@storybook/preview-api';
import { createDecorator } from './create-decorator.js';
// Storybook 7
/**
* @type {ReturnType<typeof makeDecorator>}
*/
export const withMocks = createDecorator(addons, makeDecorator);
| modernweb-dev/web/packages/mocks/storybook/addon/decorator.js/0 | {
"file_path": "modernweb-dev/web/packages/mocks/storybook/addon/decorator.js",
"repo_id": "modernweb-dev",
"token_count": 95
} | 195 |
import { expect } from 'chai';
import path from 'path';
import fs from 'fs';
import { injectPolyfillsLoader } from '../src/injectPolyfillsLoader.js';
import { noModuleSupportTest, fileTypes } from '../src/utils.js';
import { PolyfillsLoaderConfig } from '../src/types.js';
const updateSnapshots = process.argv.includes('--update-snapshots');
const defaultConfig = {
modern: { files: [{ type: fileTypes.MODULE, path: 'app.js' }] },
polyfills: {
hash: false,
},
};
async function testSnapshot(name: string, htmlString: string, config: PolyfillsLoaderConfig) {
const snapshotPath = path.join(__dirname, 'snapshots', 'injectPolyfillsLoader', `${name}.html`);
const result = await injectPolyfillsLoader(htmlString, config);
if (updateSnapshots) {
fs.writeFileSync(snapshotPath, result.htmlString, 'utf-8');
} else {
const snapshot = fs.readFileSync(snapshotPath, 'utf-8');
expect(result.htmlString.trim()).to.equal(snapshot.trim());
}
}
describe('injectPolyfillsLoader', () => {
it('injects a polyfills loader script', async () => {
const html = `
<html>
<head></head>
<body>
<div>Hello world</div>
</body>
</html>
`;
await await testSnapshot('no-polyfills-no-legacy', html, defaultConfig);
});
it('injects a loader with module and polyfills', async () => {
const html = `
<div>before</div>
<script type="module" src="./app.js"></script>
<div>after</div>
`;
await testSnapshot('module-and-polyfills', html, {
...defaultConfig,
polyfills: {
hash: false,
webcomponents: true,
fetch: true,
intersectionObserver: true,
},
});
});
it('injects a loader with module and legacy', async () => {
const html = `
<div>before</div>
<script type="module" src="./app.js"></script>
<div>after</div>
`;
await testSnapshot('module-and-legacy', html, {
...defaultConfig,
legacy: [
{
test: noModuleSupportTest,
files: [
{
path: 'a.js',
type: fileTypes.SYSTEMJS,
},
{
path: 'b.js',
type: fileTypes.SYSTEMJS,
},
],
},
],
});
});
it('injects a loader with module, legacy and polyfills', async () => {
const html = `
<div>before</div>
<script type="module" src="./app.js"></script>
<div>after</div>
`;
await testSnapshot('module-polyfills-and-legacy', html, {
...defaultConfig,
legacy: [
{
test: noModuleSupportTest,
files: [
{
path: 'a.js',
type: fileTypes.SYSTEMJS,
},
{
path: 'b.js',
type: fileTypes.SYSTEMJS,
},
],
},
],
polyfills: {
hash: false,
fetch: true,
intersectionObserver: true,
},
});
});
it('injects a loader with multiple legacy', async () => {
const html = `
<div>before</div>
<script type="module" src="./app.js"></script>
<div>after</div>
`;
await testSnapshot('multiple-legacy', html, {
...defaultConfig,
legacy: [
{
test: "'foo' in bar",
files: [
{
path: 'a.js',
type: fileTypes.MODULE,
},
{
path: 'b.js',
type: fileTypes.MODULE,
},
],
},
{
test: 'window.x',
files: [
{
path: 'a.js',
type: fileTypes.SYSTEMJS,
},
{
path: 'b.js',
type: fileTypes.SYSTEMJS,
},
],
},
],
});
});
it('does not polyfill import maps', async () => {
const html = `
<head>
<script type="importmap">{ "imports": { "foo": "bar" } }</script>
</head>
<div>before</div>
<script type="module" src="./module-a.js"></script>
<div>after</div>
`;
await testSnapshot('no-importmap-polyfill', html, defaultConfig);
});
it('polyfills importmaps when main module type is systemjs', async () => {
const html = `
<head>
<script type="importmap">{ "imports": { "foo": "bar" } }</script>
</head>
<div>before</div>
<script type="module" src="./module-a.js"></script>
<div>after</div>
`;
await testSnapshot('systemjs-polyfill-importmap-modern', html, {
...defaultConfig,
legacy: [
{
test: noModuleSupportTest,
files: [
{
path: 'a.js',
type: fileTypes.SYSTEMJS,
},
{
path: 'b.js',
type: fileTypes.SYSTEMJS,
},
],
},
],
});
});
it('polyfills importmaps when legacy is systemjs', async () => {
const html = `
<head>
<script type="importmap">{ "imports": { "foo": "bar" } }</script>
</head>
<div>before</div>
<script type="module" src="./module-a.js"></script>
<div>after</div>
`;
await testSnapshot('systemjs-polyfill-importmap-legacy', html, {
...defaultConfig,
legacy: [
{
test: noModuleSupportTest,
files: [
{
path: 'a.js',
type: fileTypes.SYSTEMJS,
},
{
path: 'b.js',
type: fileTypes.SYSTEMJS,
},
],
},
],
});
});
it('can injects a loader externally', async () => {
const html = `
<div>before</div>
<script type="module" src="./app.js"></script>
<div>after</div>
`;
await testSnapshot('external-loader', html, {
...defaultConfig,
polyfills: {
hash: false,
webcomponents: true,
fetch: true,
intersectionObserver: true,
},
externalLoaderScript: true,
});
});
});
| modernweb-dev/web/packages/polyfills-loader/test/injectPolyfillsLoader.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/polyfills-loader/test/injectPolyfillsLoader.test.ts",
"repo_id": "modernweb-dev",
"token_count": 3040
} | 196 |
const fs = require('fs');
const path = require('path');
const { patternsToFiles } = require('./patternsToFiles.js');
/**
* Copies all files from the given patterns retaining relative paths relative to the root directory.
*
* @example
* // Copy all svg, jpg and json files
* copy({ patterns: '**\/*.{svg,jpg,json}' })
* // Copy svg files from two different folders
* copy({ patterns: ['icons\/*.svg', 'test/icons\/*.svg'] })
* // Copy all svg files relative to given rootDir
* copy({ patterns: '**\/*.svg', rootDir: './my-path/' })
* // you can combine it with path.resolve
* copy({ patterns: '**\/*.svg', rootDir: path.resolve('./my-path/') })
*
* @param {object} options
* @param {string|string[]} options.patterns Single glob or an array of globs
* @param {string|string[]} options.exclude Single glob or an array of globs
* @param {string} [options.rootDir] Defaults to current working directory
* @return {import('rollup').Plugin} A Rollup Plugin
*/
function copy({ patterns = [], rootDir = process.cwd(), exclude }) {
const resolvedRootDir = path.resolve(rootDir);
/** @type {string[]} */
let filesToCopy = [];
return {
name: '@web/rollup-plugin-copy',
async buildStart() {
filesToCopy = await patternsToFiles(patterns, rootDir, exclude);
for (const filePath of filesToCopy) {
this.addWatchFile(filePath);
}
},
async generateBundle() {
for (const filePath of filesToCopy) {
const fileName = path.relative(resolvedRootDir, filePath);
this.emitFile({
type: 'asset',
fileName,
source: fs.readFileSync(filePath),
});
}
},
};
}
module.exports = { copy };
| modernweb-dev/web/packages/rollup-plugin-copy/src/copy.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-copy/src/copy.js",
"repo_id": "modernweb-dev",
"token_count": 602
} | 197 |
# Rollup Plugin HTML
Plugin for bundling HTML files. Bundles module scripts and linked assets in HTML files and injects the hashed filenames.
See [our website](https://modern-web.dev/docs/building/rollup-plugin-html/) for full documentation.
| modernweb-dev/web/packages/rollup-plugin-html/README.md/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/README.md",
"repo_id": "modernweb-dev",
"token_count": 65
} | 198 |
console.log('no-module.js');
| modernweb-dev/web/packages/rollup-plugin-html/demo/spa/src/no-module.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/demo/spa/src/no-module.js",
"repo_id": "modernweb-dev",
"token_count": 11
} | 199 |
import { Attribute } from 'parse5';
import path from 'path';
import { OutputChunk } from 'rollup';
import {
EntrypointBundle,
GeneratedBundle,
RollupPluginHTMLOptions,
ScriptModuleTag,
} from '../RollupPluginHTMLOptions';
import { createError, NOOP_IMPORT } from '../utils.js';
import { toBrowserPath } from './utils.js';
export interface CreateImportPathParams {
publicPath?: string;
outputDir: string;
fileOutputDir: string;
htmlFileName: string;
fileName: string;
}
export function createImportPath(params: CreateImportPathParams) {
const { publicPath, outputDir, fileOutputDir, htmlFileName, fileName } = params;
const pathFromMainToFileDir = path.relative(outputDir, fileOutputDir);
let importPath;
if (publicPath) {
importPath = toBrowserPath(path.join(publicPath, pathFromMainToFileDir, fileName));
} else {
const pathFromHtmlToOutputDir = path.relative(
path.dirname(htmlFileName),
pathFromMainToFileDir,
);
importPath = toBrowserPath(path.join(pathFromHtmlToOutputDir, fileName));
}
if (importPath.startsWith('http') || importPath.startsWith('/') || importPath.startsWith('.')) {
return importPath;
}
return `./${importPath}`;
}
export interface GetEntrypointBundlesParams {
pluginOptions: RollupPluginHTMLOptions;
generatedBundles: GeneratedBundle[];
outputDir: string;
inputModuleIds: ScriptModuleTag[];
htmlFileName: string;
}
interface Entrypoint {
importPath: string;
chunk: OutputChunk;
attributes?: Attribute[];
}
export function getEntrypointBundles(params: GetEntrypointBundlesParams) {
const { pluginOptions, generatedBundles, inputModuleIds, outputDir, htmlFileName } = params;
const entrypointBundles: Record<string, EntrypointBundle> = {};
for (const { name, options, bundle } of generatedBundles) {
if (!options.format) {
throw createError('Missing module format');
}
const entrypoints: Entrypoint[] = [];
for (const chunkOrAsset of Object.values(bundle)) {
if (chunkOrAsset.type === 'chunk') {
const chunk = chunkOrAsset;
if (chunk.isEntry && chunk.facadeModuleId !== NOOP_IMPORT.importPath) {
const found = inputModuleIds.find(mod => mod.importPath === chunk.facadeModuleId);
if (chunk.facadeModuleId && found) {
const importPath = createImportPath({
publicPath: pluginOptions.publicPath,
outputDir,
fileOutputDir: options.dir ?? '',
htmlFileName,
fileName: chunkOrAsset.fileName,
});
entrypoints.push({ importPath, chunk: chunkOrAsset, attributes: found.attributes });
}
}
}
}
entrypointBundles[name] = { name, options, bundle, entrypoints };
}
return entrypointBundles;
}
| modernweb-dev/web/packages/rollup-plugin-html/src/output/getEntrypointBundles.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/src/output/getEntrypointBundles.ts",
"repo_id": "modernweb-dev",
"token_count": 1017
} | 200 |
<svg xmlns="http://www.w3.org/2000/svg">y</svg>
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/assets/x/foo.svg/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/assets/x/foo.svg",
"repo_id": "modernweb-dev",
"token_count": 26
} | 201 |
console.log('sub-with-js');
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/inject-service-worker/sub-with-js/sub-js.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/inject-service-worker/sub-with-js/sub-js.js",
"repo_id": "modernweb-dev",
"token_count": 11
} | 202 |
import './shared-module.js';
console.log('module-b.js');
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/modules/module-c.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/modules/module-c.js",
"repo_id": "modernweb-dev",
"token_count": 22
} | 203 |
import { expect } from 'chai';
import { parse } from 'parse5';
import path from 'path';
import { extractAssets } from '../../../../src/input/extract/extractAssets.js';
const rootDir = path.resolve(__dirname, '..', '..', '..', 'fixtures', 'assets');
describe('extractAssets', () => {
it('extracts assets from a document', () => {
const document = parse(`
<html>
<head>
<link rel="apple-touch-icon" sizes="180x180" href="./image-a.png">
<link rel="icon" type="image/png" sizes="32x32" href="./image-b.png">
<link rel="manifest" href="./webmanifest.json">
<link rel="mask-icon" href="./image-a.svg" color="#3f93ce">
<link rel="stylesheet" href="./styles.css">
<meta property="og:image" content="/image-social.png">
</head>
<body>
<img src="./image-c.png" />
<div>
<img src="./image-b.svg" />
</div>
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'index.html'),
htmlDir: rootDir,
rootDir,
});
const assetsWithoutcontent = assets.map(a => ({ ...a, content: undefined }));
expect(assetsWithoutcontent).to.eql([
{
content: undefined,
filePath: path.join(rootDir, 'image-a.png'),
hashed: false,
},
{
content: undefined,
filePath: path.join(rootDir, 'image-b.png'),
hashed: false,
},
{
content: undefined,
filePath: path.join(rootDir, 'webmanifest.json'),
hashed: false,
},
{
content: undefined,
filePath: path.join(rootDir, 'image-a.svg'),
hashed: false,
},
{
content: undefined,
filePath: path.join(rootDir, 'styles.css'),
hashed: true,
},
{
content: undefined,
filePath: path.join(rootDir, 'image-social.png'),
hashed: true,
},
{
content: undefined,
filePath: path.join(rootDir, 'image-c.png'),
hashed: true,
},
{
content: undefined,
filePath: path.join(rootDir, 'image-b.svg'),
hashed: true,
},
]);
});
it('reads file sources', () => {
const document = parse(`
<html>
<head>
<link rel="manifest" href="./webmanifest.json">
<link rel="mask-icon" href="./image-a.svg" color="#3f93ce">
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<div>
<img src="./image-b.svg" />
</div>
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'index.html'),
htmlDir: rootDir,
rootDir,
});
const transformedAssets = assets.map(asset => ({
...asset,
content: asset.content.toString('utf-8').replace(/\s/g, ''),
}));
expect(transformedAssets).to.eql([
{
content: '{"message":"helloworld"}',
filePath: path.join(rootDir, 'webmanifest.json'),
hashed: false,
},
{
content:
'<svgxmlns="http://www.w3.org/2000/svg"><pathd="M436124H12c-6.6270-12-5.373-12-12V80c0-6.627"></path></svg>',
filePath: path.join(rootDir, 'image-a.svg'),
hashed: false,
},
{
content: ':root{color:blue;}',
filePath: path.join(rootDir, 'styles.css'),
hashed: true,
},
{
content:
'<svgxmlns="http://www.w3.org/2000/svg"><pathd="M7.7753.275a.75.750001.061.06l1.25-1.25a2"></path></svg>',
filePath: path.join(rootDir, 'image-b.svg'),
hashed: true,
},
]);
});
it('handles paths into directories', () => {
const document = parse(`
<html>
<body>
<link rel="stylesheet" href="./foo/x.css">
<link rel="stylesheet" href="./foo/bar/y.css">
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'index.html'),
htmlDir: rootDir,
rootDir,
});
expect(assets.length).to.equal(2);
expect(assets[0].filePath).to.equal(path.join(rootDir, 'foo', 'x.css'));
expect(assets[1].filePath).to.equal(path.join(rootDir, 'foo', 'bar', 'y.css'));
expect(assets[0].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:x;}');
expect(assets[1].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:y;}');
});
it('resolves relative to HTML file location', () => {
const document = parse(`
<html>
<body>
<link rel="stylesheet" href="./x.css">
<link rel="stylesheet" href="../styles.css">
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'foo', 'index.html'),
htmlDir: path.join(rootDir, 'foo'),
rootDir,
});
expect(assets.length).to.equal(2);
expect(assets[0].filePath).to.equal(path.join(rootDir, 'foo', 'x.css'));
expect(assets[1].filePath).to.equal(path.join(rootDir, 'styles.css'));
expect(assets[0].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:x;}');
expect(assets[1].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:blue;}');
});
it('resolves absolute paths relative to root dir', () => {
const document = parse(`
<html>
<body>
<link rel="stylesheet" href="/foo/x.css">
<link rel="stylesheet" href="/styles.css">
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'foo', 'index.html'),
htmlDir: path.join(rootDir, 'foo'),
rootDir,
});
expect(assets.length).to.equal(2);
expect(assets[0].filePath).to.equal(path.join(rootDir, 'foo', 'x.css'));
expect(assets[1].filePath).to.equal(path.join(rootDir, 'styles.css'));
expect(assets[0].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:x;}');
expect(assets[1].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:blue;}');
});
it('can reference the same asset with a hashed and non-hashed node', () => {
const document = parse(`
<html>
<body>
<link rel="stylesheet" href="image-a.png">
<link rel="icon" href="image-a.png">
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'index.html'),
htmlDir: rootDir,
rootDir,
});
expect(assets.length).to.equal(2);
const assetsWithoutcontent = assets.map(a => ({ ...a, content: undefined }));
expect(assetsWithoutcontent).to.eql([
{
content: undefined,
filePath: path.join(rootDir, 'image-a.png'),
hashed: true,
},
{
content: undefined,
filePath: path.join(rootDir, 'image-a.png'),
hashed: false,
},
]);
});
it('does not count remote URLs as assets', () => {
const document = parse(`
<html>
<body>
<link rel="stylesheet" href="https://fonts.googleapis.com/">
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'foo', 'index.html'),
htmlDir: path.join(rootDir, 'foo'),
rootDir,
});
expect(assets.length).to.equal(0);
});
it('does treat non module script tags as assets', () => {
const document = parse(`
<html>
<body>
<script src="./no-module.js"></script>
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'index.html'),
htmlDir: path.join(rootDir),
rootDir,
});
expect(assets.length).to.equal(1);
expect(assets[0].filePath).to.equal(path.join(rootDir, 'no-module.js'));
expect(assets[0].content.toString('utf-8')).to.equal('/* no module script file */\n');
});
it('handles a picture tag using source tags with srcset', () => {
const document = parse(`
<html>
<body>
<picture>
<source
type="image/avif"
srcset="./images/eb26e6ca-30.avif 30w, /images/eb26e6ca-60.avif 60w"
sizes="30px"
/>
<source
type="image/jpeg"
srcset="./images/eb26e6ca-30.jpeg 30w, /images/eb26e6ca-60.jpeg 60w"
sizes="30px"
/>
<img
alt="My Image Alternative Text"
rocket-image="responsive"
src="./images/eb26e6ca-30.jpeg"
width="30"
height="15"
loading="lazy"
decoding="async"
/>
</picture>
</body>
</html>
`);
const assets = extractAssets({
document,
htmlFilePath: path.join(rootDir, 'index.html'),
htmlDir: path.join(rootDir),
rootDir,
});
// the <img> src is not the same as the small jpeg image
expect(assets.length).to.equal(4);
expect(assets[0].filePath).to.equal(path.join(rootDir, 'images', 'eb26e6ca-30.avif'));
expect(assets[1].filePath).to.equal(path.join(rootDir, 'images', 'eb26e6ca-60.avif'));
expect(assets[2].filePath).to.equal(path.join(rootDir, 'images', 'eb26e6ca-30.jpeg'));
expect(assets[3].filePath).to.equal(path.join(rootDir, 'images', 'eb26e6ca-60.jpeg'));
});
});
| modernweb-dev/web/packages/rollup-plugin-html/test/src/input/extract/extractAssets.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/src/input/extract/extractAssets.test.ts",
"repo_id": "modernweb-dev",
"token_count": 4569
} | 204 |
const nameOne = 'one-name';
const imageOne = new URL('../one.svg', import.meta.url).href;
export { imageOne, nameOne };
| modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/snapshots/one-bundle.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/snapshots/one-bundle.js",
"repo_id": "modernweb-dev",
"token_count": 42
} | 205 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const { polyfillsLoader } = cjsEntrypoint;
export { polyfillsLoader };
| modernweb-dev/web/packages/rollup-plugin-polyfills-loader/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-polyfills-loader/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 61
} | 206 |
import { generateSW, injectManifest } from '../index.mjs';
export default {
input: 'demo/main.js',
output: {
file: 'demo/dist/bundle.js',
format: 'esm',
},
plugins: [
generateSW({
swDest: 'demo/dist/generateSW_sw.js',
globDirectory: 'demo/dist/',
globIgnores: ['injectManifest_sw.js'],
},
{
render: ({ swDest, count, size }) => {
console.log(`\nCustom render! ${swDest}`);
console.log(`Custom render! The service worker will precache ${count} URLs, totaling ${size}.\n`);
}
}),
injectManifest({
swSrc: 'demo/injectManifestSwSrc.js',
swDest: 'demo/dist/injectManifest_sw.js',
globDirectory: 'demo/dist/',
globIgnores: ['generateSW_sw.js'],
}, {esbuild: {minify: false}}),
],
};
| modernweb-dev/web/packages/rollup-plugin-workbox/demo/rollup.config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-workbox/demo/rollup.config.mjs",
"repo_id": "modernweb-dev",
"token_count": 354
} | 207 |
// based on https://github.com/storybookjs/storybook/blob/v7.0.9/code/lib/builder-vite/src/codegen-set-addon-channel.ts
export async function generateSetupAddonsScript() {
return `
import { createChannel as createPostMessageChannel } from '@storybook/channel-postmessage';
import { createChannel as createWebSocketChannel } from '@storybook/channel-websocket';
import { addons } from '@storybook/preview-api';
const channel = createPostMessageChannel({ page: 'preview' });
addons.setChannel(channel);
window.__STORYBOOK_ADDONS_CHANNEL__ = channel;
const { SERVER_CHANNEL_URL } = globalThis;
if (SERVER_CHANNEL_URL) {
const serverChannel = createWebSocketChannel({ url: SERVER_CHANNEL_URL });
addons.setServerChannel(serverChannel);
window.__STORYBOOK_SERVER_CHANNEL__ = serverChannel;
}
`.trim();
}
| modernweb-dev/web/packages/storybook-builder/src/generate-setup-addons-script.ts/0 | {
"file_path": "modernweb-dev/web/packages/storybook-builder/src/generate-setup-addons-script.ts",
"repo_id": "modernweb-dev",
"token_count": 264
} | 208 |
import { runIntegrationTests } from '../../../integration/test-runner/index.js';
import { browserstackLauncher } from '../src/index.js';
if (!process.env.BROWSER_STACK_USERNAME) {
throw new Error('Missing env var BROWSER_STACK_USERNAME');
}
if (!process.env.BROWSER_STACK_ACCESS_KEY) {
throw new Error('Missing env var BROWSER_STACK_ACCESS_KEY');
}
const sharedCapabilities = {
'browserstack.user': process.env.BROWSER_STACK_USERNAME,
'browserstack.key': process.env.BROWSER_STACK_ACCESS_KEY,
project: '@web/test-runner-browserstack',
name: 'integration test',
build: `modern-web ${process.env.GITHUB_REF ?? 'local'} build ${
process.env.GITHUB_RUN_NUMBER ?? ''
}`,
};
describe('test-runner-browserstack', function () {
this.timeout(200000);
function createConfig() {
return {
browserStartTimeout: 1000 * 60 * 2,
testsStartTimeout: 1000 * 60 * 2,
testsFinishTimeout: 1000 * 60 * 2,
browsers: [
browserstackLauncher({
capabilities: {
...sharedCapabilities,
browserName: 'Chrome',
browser_version: 'latest',
os: 'windows',
os_version: '10',
},
}),
// browserstackLauncher({
// capabilities: {
// ...sharedCapabilities,
// browserName: 'Firefox',
// browser_version: 'latest',
// os: 'windows',
// os_version: '10',
// },
// }),
browserstackLauncher({
capabilities: {
...sharedCapabilities,
browserName: 'IE',
browser_version: '11.0',
os: 'Windows',
os_version: '7',
},
}),
],
};
}
runIntegrationTests(createConfig, {
basic: true,
many: true,
focus: true,
groups: false,
parallel: false,
testFailure: false,
locationChanged: false,
});
});
| modernweb-dev/web/packages/test-runner-browserstack/test-remote/browserstackLauncher.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-browserstack/test-remote/browserstackLauncher.test.ts",
"repo_id": "modernweb-dev",
"token_count": 861
} | 209 |
# @web/test-runner-chrome
## 0.16.0
### Minor Changes
- 4cc90648: Update Puppeteer to version 22. Remove Puppeteer KnownDevices, before the update named devices, export.
## 0.15.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.14.4
### Patch Changes
- Updated dependencies [43be7391]
- @web/test-runner-core@0.12.0
- @web/test-runner-coverage-v8@0.7.3
## 0.14.3
### 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.14.2
### Patch Changes
- 165c8134: return inner timer result
- @web/test-runner-core@0.11.5
## 0.14.1
### Patch Changes
- be105a69: Fix debug mode
## 0.14.0
### Minor Changes
- 0c87f59e: feat/various fixes
- Update puppeteer to `20.0.0`, fixes #2282
- Use puppeteer's new `page.mouse.reset()` in sendMousePlugin, fixes #2262
- Use `development` export condition by default
## 0.13.4
### Patch Changes
- 5c02eca2: fix(test-runner-chrome): add mutex when bringing tabs to front
## 0.13.3
### Patch Changes
- 18d4a631: fix: add workaround for headless issue
This will patch `window.requestAnimationFrame` and `window.requestIdleCallback` and make sure that the tab running the test code is brought back to the front.
## 0.13.2
### Patch Changes
- 015766e9: Use new headless chrome mode
- Updated dependencies [015766e9]
- @web/test-runner-core@0.11.2
## 0.13.1
### Patch Changes
- 9ae77c47: Acquire raw v8 coverage via puppeteer API rather than CDP calls
- Updated dependencies [3c33d74a]
- @web/test-runner-coverage-v8@0.7.0
## 0.13.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.12.1
### Patch Changes
- 77e413d9: fix(test-runner-chrome): fix broken test coverage. fixes #2186
- bd12ff9b: Update `rollup/plugin-replace`
- 8128ca53: Update @rollup/plugin-replace
- Updated dependencies [cdeafe4a]
- Updated dependencies [1113fa09]
- Updated dependencies [817d674b]
- Updated dependencies [445b20e6]
- Updated dependencies [bd12ff9b]
- Updated dependencies [8128ca53]
- @web/test-runner-core@0.10.29
## 0.12.0
### Minor Changes
- 0e198dcc: Update `puppeteer-core` dependency to v18
## 0.11.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.10.7
### Patch Changes
- 3192c9ff: Update puppeteer-core dependency to 13.1.3
## 0.10.6
### Patch Changes
- 7c2fa463: Update puppeteer-core and puppeteer to v13
## 0.10.5
### Patch Changes
- 3f79c247: Update dependency chrome-launcher to ^0.15.0
## 0.10.4
### Patch Changes
- aab9a42f: Update dependency puppeteer-core to v11
## 0.10.3
### Patch Changes
- de756b28: Update dependency puppeteer-core to v10
## 0.10.2
### Patch Changes
- 33ada3d8: Align @web/test-runner-core version
- Updated dependencies [33ada3d8]
- @web/test-runner-coverage-v8@0.4.8
## 0.10.1
### Patch Changes
- 06e612d5: Bump chrome-launcher to 0.14.0
## 0.10.0
### Minor Changes
- 2c06f31e: Update puppeteer and puppeteer-core to 8.0.0
### Patch Changes
- a6a018da: fix type references
## 0.9.4
### Patch Changes
- 4a609a18: skip non-http coverage files
- Updated dependencies [4a609a18]
- @web/test-runner-coverage-v8@0.4.5
## 0.9.3
### Patch Changes
- 9ecb49f4: release test coverage package
- Updated dependencies [9ecb49f4]
- @web/test-runner-coverage-v8@0.4.3
## 0.9.2
### Patch Changes
- 83e0757e: handle cases when userAgent is not defined
- Updated dependencies [83e0757e]
- @web/test-runner-core@0.10.8
## 0.9.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.9.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.8.2
### Patch Changes
- cbbeae3f: allow configuring puppeteer and playwright browser context
## 0.8.1
### Patch Changes
- 69b2d13d: use about:blank to kill stale browser pages, this makes tests that rely on browser focus work with puppeteer
- 005ab9ae: use fast chrome-launcher installation finder
## 0.8.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.7.3
### 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.7.2
### 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.7.1
### Patch Changes
- c256a08: allow configuring concurrency per browser launcher
- Updated dependencies [c256a08]
- @web/test-runner-core@0.8.3
## 0.7.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.6.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.6.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.6.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.6.5
### Patch Changes
- 41d895f: capture native browser errors
## 0.6.4
### Patch Changes
- ce2a2e6: align dependencies
- Updated dependencies [ce2a2e6]
- @web/test-runner-coverage-v8@0.1.2
## 0.6.3
### Patch Changes
- 22c85b5: fix handle race condition when starting browser
- da80c1d: fixed collecting test coverage on chrome/puppeteer
## 0.6.2
### Patch Changes
- 4d29bb4: restart browser after timeout
- Updated dependencies [60de9b5]
- @web/browser-logs@0.1.2
## 0.6.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.6.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.5.21
### Patch Changes
- f924a9b: improve support for puppeteer firefox
## 0.5.20
### Patch Changes
- d77093b: allow code coverage instrumentation through JS
## 0.5.19
### Patch Changes
- 02a3926: expose browser name from BrowserLauncher
- 74cc129: implement commands API
## 0.5.18
### Patch Changes
- cbdf3c7: chore: merge browser lib into test-runner-core
## 0.5.17
### Patch Changes
- 432f090: expose browser name from BrowserLauncher
## 0.5.16
### Patch Changes
- 736d101: improve scheduling logic and error handling
## 0.5.15
### Patch Changes
- 4e3de03: fix a potential race condition when starting a new test
## 0.5.14
### Patch Changes
- 7c25ba4: guard against the logs script being unavailable
## 0.5.13
### Patch Changes
- Updated dependencies [ad11e36]
- @web/test-runner-coverage-v8@0.0.4
## 0.5.12
### Patch Changes
- 5fada4a: improve logging and error reporting
- Updated dependencies [5fada4a]
- @web/browser-logs@0.0.1
## 0.5.11
### Patch Changes
- 7a22269: allow customize browser page creation
## 0.5.10
### Patch Changes
- 7db1da1: open debug in a larger browser window
## 0.5.9
### Patch Changes
- Updated dependencies [db5baff]
- @web/test-runner-coverage-v8@0.0.3
## 0.5.8
### Patch Changes
- cfa4738: remove puppeteer dependency
## 0.5.7
### Patch Changes
- c72ea22: allow configuring browser launch options
## 0.5.6
### Patch Changes
- 4a6b9c2: make coverage work in watch mode
## 0.5.5
### Patch Changes
- 1d6d498: allow changing viewport in tests
## 0.5.4
### Patch Changes
- afc3cc7: update dependencies
## 0.5.3
### Patch Changes
- Updated dependencies [835b30c]
- @web/test-runner-coverage-v8@0.0.2
## 0.5.2
### Patch Changes
- 5ab18d8: feat(test-runner-core): batch v8 test coverage
## 0.5.1
### Patch Changes
- 3dab600: profile test coverage through v8/chromium
- Updated dependencies [3dab600]
- @web/test-runner-coverage-v8@0.0.1
## 0.5.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`.
## 0.4.4
### Patch Changes
- 14b7fae: handle errors in mocha hooks
## 0.4.3
### Patch Changes
- 56ed519: open browser windows sequentially in selenium
## 0.4.2
### Patch Changes
- 0f8935d: make going to a URL non-blocking
## 0.4.1
### Patch Changes
- 45a2f21: add ability to run HTML tests
## 0.4.0
### Minor Changes
- 1d277e9: rename framework to browser-lib
## 0.3.0
### Minor Changes
- ccb63df: @web/test-runner-dev-server to @web/test-runner-server
## 0.2.2
### Patch Changes
- 115442b: add readme, package tags and description
## 0.2.1
### Patch Changes
- 6b06aca: Speed up chrome installation lookup on mac
## 0.2.0
### Minor Changes
- 79f9e6b: open browser in debug
## 0.1.0
### Minor Changes
- 97e85e6: first setup
| modernweb-dev/web/packages/test-runner-chrome/CHANGELOG.md/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-chrome/CHANGELOG.md",
"repo_id": "modernweb-dev",
"token_count": 4439
} | 210 |
import { TestRunnerPlugin } from '@web/test-runner-core';
import type { ChromeLauncher } from '@web/test-runner-chrome';
import type { PlaywrightLauncher } from '@web/test-runner-playwright';
export interface Media {
media?: 'screen' | 'print';
colorScheme?: 'dark' | 'light' | 'no-preference';
reducedMotion?: 'reduce' | 'no-preference';
forcedColors?: 'active' | 'none';
}
function isObject(payload: unknown): payload is Record<string, unknown> {
return payload != null && typeof payload === 'object';
}
function isMediaObject(payload: unknown): payload is Media {
if (!isObject(payload)) throw new Error('You must provide a viewport object');
if (payload.media != null && !(typeof payload.media === 'string')) {
throw new Error('media should be a string.');
}
if (payload.colorScheme != null && !(typeof payload.colorScheme === 'string')) {
throw new Error('colorScheme should be a string.');
}
if (payload.reducedMotion != null && !(typeof payload.reducedMotion === 'string')) {
throw new Error('reducedMotion should be a string.');
}
return true;
}
export function emulateMediaPlugin(): TestRunnerPlugin {
return {
name: 'emulate-media-command',
async executeCommand({ command, payload, session }) {
if (command === 'emulate-media') {
if (!isMediaObject(payload)) {
throw new Error('You must provide a viewport object');
}
if (session.browser.type === 'puppeteer') {
const page = (session.browser as ChromeLauncher).getPage(session.id);
const features = [];
if (payload.colorScheme != null) {
features.push({ name: 'prefers-color-scheme', value: payload.colorScheme });
}
if (payload.reducedMotion != null) {
features.push({ name: 'prefers-reduced-motion', value: payload.reducedMotion });
}
await page.emulateMediaFeatures(features);
if (payload.media) {
await page.emulateMediaType(payload.media);
}
return true;
}
if (session.browser.type === 'playwright') {
const page = (session.browser as PlaywrightLauncher).getPage(session.id);
await page.emulateMedia(payload as any);
return true;
}
throw new Error(
`Setting viewport is not supported for browser type ${session.browser.type}.`,
);
}
},
};
}
| modernweb-dev/web/packages/test-runner-commands/src/emulateMediaPlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/src/emulateMediaPlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 917
} | 211 |
import path from 'path';
import { runTests } from '@web/test-runner-core/test-helpers';
import { chromeLauncher } from '@web/test-runner-chrome';
import { playwrightLauncher } from '@web/test-runner-playwright';
import { setViewportPlugin } from '../../src/setViewportPlugin.js';
describe('setViewportPlugin', function test() {
this.timeout(20000);
it('can set the viewport on puppeteer', async () => {
await runTests({
files: [path.join(__dirname, 'browser-test.js')],
browsers: [chromeLauncher()],
plugins: [setViewportPlugin()],
});
});
it('can set the viewport on playwright', async () => {
await runTests({
files: [path.join(__dirname, 'browser-test.js')],
browsers: [
playwrightLauncher({ product: 'chromium' }),
playwrightLauncher({ product: 'firefox' }),
playwrightLauncher({ product: 'webkit' }),
],
plugins: [setViewportPlugin()],
});
});
});
| modernweb-dev/web/packages/test-runner-commands/test/set-viewport/setViewportPlugin.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/test/set-viewport/setViewportPlugin.test.ts",
"repo_id": "modernweb-dev",
"token_count": 357
} | 212 |
import { Logger, ErrorWithLocation } from '../logger/Logger';
export class BufferedLogger implements Logger {
public buffer: { method: keyof Logger; args?: any[] }[] = [];
constructor(private parent: Logger) {}
log(...messages: unknown[]) {
this.buffer.push({ method: 'log', args: messages });
}
debug(...messages: unknown[]) {
this.buffer.push({ method: 'debug', args: messages });
}
error(...messages: unknown[]) {
this.buffer.push({ method: 'error', args: messages });
}
warn(...messages: unknown[]) {
this.buffer.push({ method: 'warn', args: messages });
}
group() {
this.buffer.push({ method: 'group' });
}
groupEnd() {
this.buffer.push({ method: 'groupEnd' });
}
logSyntaxError(error: ErrorWithLocation) {
this.buffer.push({ method: 'logSyntaxError', args: [error] });
}
logBufferedMessages() {
for (const { method, args = [] } of this.buffer) {
(this.parent[method] as any)(...args);
}
}
}
| modernweb-dev/web/packages/test-runner-core/src/cli/BufferedLogger.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/cli/BufferedLogger.ts",
"repo_id": "modernweb-dev",
"token_count": 348
} | 213 |
import { TestRunnerCoreConfig } from '../config/TestRunnerCoreConfig.js';
import { TestSessionManager } from '../test-session/TestSessionManager.js';
import { TestSession, TestResultError } from '../test-session/TestSession.js';
import { SESSION_STATUS } from '../test-session/TestSessionStatus.js';
import { TestScheduler } from './TestScheduler.js';
export class TestSessionTimeoutHandler {
private timeoutIdsPerSession = new Map<string, NodeJS.Timeout[]>();
private config: TestRunnerCoreConfig;
private sessions: TestSessionManager;
private scheduler: TestScheduler;
constructor(
config: TestRunnerCoreConfig,
sessions: TestSessionManager,
scheduler: TestScheduler,
) {
this.config = config;
this.sessions = sessions;
this.scheduler = scheduler;
}
waitForTestsStarted(testRun: number, sessionId: string) {
const timeoutId = setTimeout(() => {
const session = this.sessions.get(sessionId)!;
if (session.testRun !== testRun) {
// session reloaded in the meantime
return;
}
if (session.status === SESSION_STATUS.INITIALIZING) {
this.setSessionFailed(session, {
message:
`Browser tests did not start after ${this.config.testsStartTimeout}ms ` +
'You can increase this timeout with the testsStartTimeout option. ' +
'Check the browser logs or open the browser in debug mode for more information.',
});
return;
}
}, this.config.testsStartTimeout);
this.addTimeoutId(sessionId, timeoutId);
}
waitForTestsFinished(testRun: number, sessionId: string) {
const timeoutId = setTimeout(() => {
const session = this.sessions.get(sessionId)!;
if (session.testRun !== testRun) {
// session reloaded in the meantime
return;
}
if (session.status !== SESSION_STATUS.TEST_FINISHED) {
this.setSessionFailed(session, {
message:
`Browser tests did not finish within ${this.config.testsFinishTimeout}ms. ` +
'You can increase this timeout with the testsFinishTimeout option. ' +
'Check the browser logs or open the browser in debug mode for more information.',
});
}
}, this.config.testsFinishTimeout);
this.addTimeoutId(sessionId, timeoutId);
}
/**
* Returns whether the session has gone stale. Sessions are immutable, this takes in a
* snapshot of a session and returns whether the session has since changed test run or status.
* This can be used to decide whether perform side effects like logging or changing status.
*/
isStale(session: TestSession): boolean {
const currentSession = this.sessions.get(session.id);
return (
!currentSession ||
currentSession.testRun !== session.testRun ||
currentSession.status !== session.status
);
}
addTimeoutId(sessionId: string, id: any) {
let timeoutIds = this.timeoutIdsPerSession.get(sessionId);
if (!timeoutIds) {
timeoutIds = [];
this.timeoutIdsPerSession.set(sessionId, timeoutIds);
}
timeoutIds.push(id);
}
private setSessionFailed(session: TestSession, ...errors: TestResultError[]) {
this.scheduler.stopSession(session, errors);
}
clearTimeoutsForSession(session: TestSession) {
// the session is full finished, clear any related timeouts
const timeoutIds = this.timeoutIdsPerSession.get(session.id);
if (timeoutIds) {
this.clearTimeouts(timeoutIds);
}
}
clearAllTimeouts() {
for (const ids of this.timeoutIdsPerSession.values()) {
this.clearTimeouts(ids);
}
}
clearTimeouts(timeoutIds: NodeJS.Timeout[]) {
for (const id of timeoutIds) {
clearTimeout(id);
}
}
}
| modernweb-dev/web/packages/test-runner-core/src/runner/TestSessionTimeoutHandler.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/runner/TestSessionTimeoutHandler.ts",
"repo_id": "modernweb-dev",
"token_count": 1334
} | 214 |
import { browserScript } from '@web/browser-logs';
export const trackBrowserLogs = `<script type="module">(function () {
${browserScript}
window.__wtr_browser_logs__.logs = [];
var types = ['log', 'debug', 'warn', 'error'];
types.forEach(function (type) {
var original = console[type];
console[type] = function () {
var args = [];
for (let i = 0; i < arguments.length; i ++) {
args.push(window.__wtr_browser_logs__.serialize(arguments[i]));
}
window.__wtr_browser_logs__.logs.push({ type: type, args: args });
original.apply(console, arguments);
};
});
})();</script>`;
| modernweb-dev/web/packages/test-runner-core/src/server/plugins/trackBrowserLogs.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/server/plugins/trackBrowserLogs.ts",
"repo_id": "modernweb-dev",
"token_count": 248
} | 215 |
describe('suite a', () => {
it('test a 1', () => {});
it('test a 2', () => {
throw new Error('test a 2 error');
});
describe('suite b', () => {
it('test b 1', () => {});
it('test b 2', () => {});
});
});
it('test 1', () => {});
it('test 2', () => {
throw new Error('test 2 error');
});
| modernweb-dev/web/packages/test-runner-mocha/test/fixtures/autorun.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-mocha/test/fixtures/autorun.js",
"repo_id": "modernweb-dev",
"token_count": 126
} | 216 |
import playwright, { Browser, Page, LaunchOptions, BrowserContext } from 'playwright';
import { BrowserLauncher, TestRunnerCoreConfig, CoverageMapData } from '@web/test-runner-core';
import { PlaywrightLauncherPage } from './PlaywrightLauncherPage.js';
function capitalize(str: string) {
return `${str[0].toUpperCase()}${str.substring(1)}`;
}
export type ProductType = 'chromium' | 'firefox' | 'webkit';
interface CreateArgs {
browser: Browser;
config: TestRunnerCoreConfig;
}
export type CreateBrowserContextFn = (args: CreateArgs) => BrowserContext | Promise<BrowserContext>;
export type CreatePageFn = (args: CreateArgs & { context: BrowserContext }) => Promise<Page>;
export class PlaywrightLauncher implements BrowserLauncher {
public name: string;
public type = 'playwright';
public concurrency?: number;
private product: ProductType;
private launchOptions: LaunchOptions;
private createBrowserContextFn: CreateBrowserContextFn;
private createPageFn: CreatePageFn;
private config?: TestRunnerCoreConfig;
private testFiles?: string[];
private browser?: Browser;
private debugBrowser?: Browser;
private activePages = new Map<string, PlaywrightLauncherPage>();
private activeDebugPages = new Map<string, PlaywrightLauncherPage>();
private testCoveragePerSession = new Map<string, CoverageMapData>();
private __launchBrowserPromise?: Promise<Browser>;
public __experimentalWindowFocus__: boolean;
constructor(
product: ProductType,
launchOptions: LaunchOptions,
createBrowserContextFn: CreateBrowserContextFn,
createPageFn: CreatePageFn,
__experimentalWindowFocus__?: boolean,
concurrency?: number,
) {
this.product = product;
this.launchOptions = launchOptions;
this.createBrowserContextFn = createBrowserContextFn;
this.createPageFn = createPageFn;
this.concurrency = concurrency;
this.name = capitalize(product);
this.__experimentalWindowFocus__ = !!__experimentalWindowFocus__;
}
async initialize(config: TestRunnerCoreConfig, testFiles: string[]) {
this.config = config;
this.testFiles = testFiles;
}
async stop() {
if (this.browser?.isConnected()) {
await this.browser.close();
}
if (this.debugBrowser?.isConnected()) {
await this.debugBrowser.close();
}
}
async startSession(sessionId: string, url: string) {
const browser = await this.getOrStartBrowser();
const page = await this.createNewPage(browser);
this.activePages.set(sessionId, page);
this.testCoveragePerSession.delete(sessionId);
await page.runSession(url, !!this.config?.coverage);
}
isActive(sessionId: string) {
return this.activePages.has(sessionId);
}
getBrowserUrl(sessionId: string) {
return this.getPage(sessionId).url();
}
async startDebugSession(sessionId: string, url: string) {
if (!this.debugBrowser) {
this.debugBrowser = await playwright[this.product].launch({
...this.launchOptions,
// devtools is only supported on chromium
devtools: this.product === 'chromium',
headless: false,
});
}
const page = await this.createNewPage(this.debugBrowser);
this.activeDebugPages.set(sessionId, page);
page.playwrightPage.on('close', () => {
this.activeDebugPages.delete(sessionId);
});
await page.runSession(url, false);
}
async createNewPage(browser: Browser) {
const playwrightContext = await this.createBrowserContextFn({ config: this.config!, browser });
const playwrightPage = await this.createPageFn({
config: this.config!,
browser,
context: playwrightContext,
});
return new PlaywrightLauncherPage(
this.config!,
this.product,
this.testFiles!,
playwrightContext,
playwrightPage,
);
}
async stopSession(sessionId: string) {
const page = this.activePages.get(sessionId);
if (!page) {
throw new Error(`No page for session ${sessionId}`);
}
if (page.playwrightPage.isClosed()) {
throw new Error(`Session ${sessionId} is already stopped`);
}
const result = await page.stopSession();
this.activePages.delete(sessionId);
return result;
}
private async getOrStartBrowser(): Promise<Browser> {
if (this.__launchBrowserPromise) {
return this.__launchBrowserPromise;
}
if (!this.browser || !this.browser?.isConnected()) {
this.__launchBrowserPromise = (async () => {
const browser = await playwright[this.product].launch(this.launchOptions);
return browser;
})();
const browser = await this.__launchBrowserPromise;
this.browser = browser;
this.__launchBrowserPromise = undefined;
}
return this.browser;
}
getPage(sessionId: string) {
const page =
this.activePages.get(sessionId)?.playwrightPage ??
this.activeDebugPages.get(sessionId)?.playwrightPage;
if (!page) {
throw new Error(`Could not find a page for session ${sessionId}`);
}
return page;
}
}
| modernweb-dev/web/packages/test-runner-playwright/src/PlaywrightLauncher.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-playwright/src/PlaywrightLauncher.ts",
"repo_id": "modernweb-dev",
"token_count": 1701
} | 217 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const { puppeteerLauncher } = cjsEntrypoint;
export { puppeteerLauncher };
| modernweb-dev/web/packages/test-runner-puppeteer/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-puppeteer/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 63
} | 218 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const { createSauceLabsLauncher } = cjsEntrypoint;
export { createSauceLabsLauncher };
| modernweb-dev/web/packages/test-runner-saucelabs/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-saucelabs/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 69
} | 219 |
export default 'moduleFeaturesA';
| modernweb-dev/web/packages/test-runner-saucelabs/test-remote/fixtures/module-features-a.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-saucelabs/test-remote/fixtures/module-features-a.js",
"repo_id": "modernweb-dev",
"token_count": 8
} | 220 |
# Test Runner Visual Regression
Plugin for visual regression testing with Web Test Runner.
> This project is experimental. We are testing out different approaches and gathering feedback, let us know what you think and [join the discussion!](https://github.com/modernweb-dev/web/discussions/427).
## Usage
Install the package:
```
npm i --save-dev @web/test-runner-visual-regression
```
Add the plugin to you `web-test-runner.config.mjs`:
```js
import { visualRegressionPlugin } from '@web/test-runner-visual-regression/plugin';
export default {
plugins: [
visualRegressionPlugin({
update: process.argv.includes('--update-visual-baseline'),
}),
],
};
```
Run a visual diff in your browser test:
```js
import { visualDiff } from '@web/test-runner-visual-regression';
it('can diff an element', async () => {
const element = document.createElement('p');
element.textContent = 'Hello world';
element.style.color = 'blue';
document.body.appendChild(element);
await visualDiff(element, 'my-element');
});
```
## How it works
### Element
You call the `visualDiff` function with a reference to a DOM element. The element must be connected to the DOM, in the same document the tests are run in. You can also take a screenshot of the whole body for a full-page screenshot by passing in `document.body`. The element can also be in shadow DOM.
### Diffing
When you run a diff test for the first time, a baseline image is saved to `screenshots/baseline/${browser}/${name}.png`. Afterward, every time you do a diff it is compared to this baseline images.
If the difference between the two images is larger than the configured threshold, the test fails. The failed screenshot is saved as `screenshots/${browser}/failed/${name}.png` and an image illustrating the differences between the two images is saved as `screenshots/${browser}/failed/${name}-diff.png`.
### Updating diffs
When tests are run with the `update` option set to `true`, the new image will be saved as a baseline and the test will always pass.
In the example config, we read the command line args for a `--update-visual-baseline` flag, you can use this when running tests:
```
web-test-runner test/**/*.test.js --update-visual-baseline
```
## Configuration
These are all the possible configuration options. All options are optional:
```ts
import pixelmatch from 'pixelmatch';
type PixelMatchParams = Parameters<typeof pixelmatch>;
type PixelMatchOptions = PixelMatchParams[5];
export interface GetNameArgs {
browser: string;
name: string;
testFile: string;
}
export interface ImageArgs {
filePath: string;
baseDir: string;
name: string;
}
export interface SaveImageArgs extends ImageArgs {
content: Buffer;
}
export type OptionalImage = Buffer | undefined | Promise<Buffer | undefined>;
export interface DiffResult {
diffPercentage: number;
diffImage: Buffer;
}
export interface DiffArgs {
name: string;
baselineImage: Buffer;
image: Buffer;
options: PixelMatchOptions;
}
export interface VisualRegressionPluginOptions {
/**
* Whether to update the baseline image instead of comparing
* the image with the current baseline.
*/
update: boolean;
/**
* The base directory to write images to.
*/
baseDir: string;
/**
* Options to use when diffing images.
*/
diffOptions: PixelMatchOptions;
/**
* Returns the name of the baseline image file. The name
* is a path relative to the baseDir
*/
getBaselineName: (args: GetNameArgs) => string;
/**
* Returns the name of the image file representing the difference
* between the baseline and the new image. The name is a path
* relative to the baseDir
*/
getDiffName: (args: GetNameArgs) => string;
/**
* Returns the name of the failed image file. The name is a path
* relative to the baseDir
*/
getFailedName: (args: GetNameArgs) => string;
/**
* Returns the baseline image.
*/
getBaseline: (args: ImageArgs) => OptionalImage;
/**
* Saves the baseline image.
*/
saveBaseline: (args: SaveImageArgs) => void | Promise<void>;
/**
* Saves the image representing the difference between the
* baseline and the new image.
*/
saveDiff: (args: SaveImageArgs) => void | Promise<void>;
/**
* Saves the failed image file.
*/
saveFailed: (args: SaveImageArgs) => void | Promise<void>;
/**
* Gets the difference between two images.
*/
getImageDiff: (args: DiffArgs) => DiffResult | Promise<DiffResult>;
/**
* The threshold after which a diff is considered a failure, depending on the failureThresholdType.
* For `failureThresholdType` of "percentage", this should be a number between 0-100.
* For `failureThresholdType` of "pixels", this should be a positive integer.
*/
failureThreshold: number;
/**
* The type of threshold that would trigger a failure.
*/
failureThresholdType: 'percent' | 'pixel';
}
```
### Diffing options
We use the [pixelmatch](https://www.npmjs.com/package/pixelmatch) library for diffing images. You can configure the diffing options in the config.
```js
import { visualRegressionPlugin } from '@web/test-runner-visual-regression/plugin';
import path from 'path';
export default {
plugins: [
visualRegressionPlugin({
diffOptions: {
threshold: 0.2,
includeAA: false,
},
}),
],
};
```
### Names and directories
By default images are saved to disk to the `screenshots/${browser}/baseline` and `screenshots/${browser}/failed` directories. You can configure different directories or name patterns.
```js
import { visualRegressionPlugin } from '@web/test-runner-visual-regression/plugin';
import path from 'path';
export default {
plugins: [
visualRegressionPlugin({
update: process.argv.includes('--update-visual-baseline'),
// configure the directory to output screenshots into
// can also be an absolute path
baseDir: 'screenshots',
// configure the path relative to the basedir where to store individual screenshots
// this can be used to configure different directories, or to change the names
getBaselineName: ({ browser, name }) => path.join(browser, 'baseline', name),
getDiffName: ({ browser, name }) => path.join(browser, 'failed', `${name}-diff`),
getFailedName: ({ browser, name }) => path.join(browser, 'failed', name),
}),
],
};
```
### Storing images externally
By default, we write files on disk, but you can configure this behavior from the config. This way you can, for example, upload images to an external service.
```js
import { visualRegressionPlugin } from '@web/test-runner-visual-regression/plugin';
import path from 'path';
export default {
plugins: [
visualRegressionPlugin({
update: process.argv.includes('--update-visual-baseline'),
getBaseline({ filePath, baseDir, name }) {
// read the baseline image from somewhere. this function can be async, and should
// return a Buffer with the image data
},
saveBaseline({ filePath, content, baseDir, name }) {
// save the baseline image somewhere. this function can be async.
},
saveDiff({ filePath, content, baseDir, name }) {
// save the diff image somewhere. this function can be async.
},
saveFailed({ filePath, content, baseDir, name }) {
// save the failed image somewhere. this function can be async.
},
}),
],
};
```
### Custom diffing
You can implement custom image diffing logic in the config. Use this to implement different diffing libraries.
```js
import { visualRegressionPlugin } from '@web/test-runner-visual-regression/plugin';
import path from 'path';
export default {
plugins: [
visualRegressionPlugin({
update: process.argv.includes('--update-visual-baseline'),
getImageDiff({
options: VisualRegressionPluginOptions,
image: Buffer,
browser: string,
name: string,
}) {
// read the baseline image from somewhere. this function can be async, and should
// return a Buffer with the image data
return {
// return the diff percentage as a number between 0 and 100
diffPercentage,
// return the image representing the diff between the two images
// this helps the user with debugging
diffImage,
};
},
}),
],
};
```
| modernweb-dev/web/packages/test-runner-visual-regression/README.md/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-visual-regression/README.md",
"repo_id": "modernweb-dev",
"token_count": 2606
} | 221 |
import fs from 'fs';
import { promisify } from 'util';
export const readFile = promisify(fs.readFile);
export const writeFile = promisify(fs.writeFile);
export const fsAccess = promisify(fs.access);
export async function fileExists(filePath: string) {
try {
await fsAccess(filePath);
return true;
} catch {
return false;
}
}
| modernweb-dev/web/packages/test-runner-visual-regression/src/fs.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-visual-regression/src/fs.ts",
"repo_id": "modernweb-dev",
"token_count": 117
} | 222 |
import { CoverageMapData } from '@web/test-runner-core';
export interface BrowserResult {
testCoverage?: CoverageMapData;
url: string;
}
export 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;
}
| modernweb-dev/web/packages/test-runner-webdriver/src/coverage.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-webdriver/src/coverage.ts",
"repo_id": "modernweb-dev",
"token_count": 131
} | 223 |
import selenium from 'selenium-standalone';
console.log('Installing Selenium...');
export async function runSelenium() {
await selenium.install({
drivers: {
chrome: { version: 'latest' },
firefox: { version: 'latest' },
},
});
return await selenium.start({
drivers: {
chrome: { version: 'latest' },
firefox: { version: 'latest' },
},
});
}
| modernweb-dev/web/packages/test-runner/demo/runSelenium.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/runSelenium.mjs",
"repo_id": "modernweb-dev",
"token_count": 148
} | 224 |
import { calledThrice, PublicClass } from './pass-coverage.js';
calledThrice();
const publicClass = new PublicClass();
publicClass.calledThrice();
| modernweb-dev/web/packages/test-runner/demo/test/pass-coverage-c.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/pass-coverage-c.test.js",
"repo_id": "modernweb-dev",
"token_count": 43
} | 225 |
import { b } from './b.js';
b();
| modernweb-dev/web/packages/test-runner/demo/test/virtual-files/b.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/virtual-files/b.test.js",
"repo_id": "modernweb-dev",
"token_count": 16
} | 226 |
import './shared-a.js';
| modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-20.test.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-20.test.d.ts",
"repo_id": "modernweb-dev",
"token_count": 10
} | 227 |
import { TestRunnerConfig } from './TestRunnerConfig.js';
const arrayKeys = ['plugins', 'middleware'];
export function mergeConfigs(...configs: Partial<TestRunnerConfig | undefined>[]) {
const finalConfig: any = {
plugins: [],
middleware: [],
};
for (const config of configs) {
if (config) {
for (const [key, value] of Object.entries(config)) {
if (arrayKeys.includes(key)) {
if (Array.isArray(value)) {
finalConfig[key].push(...value);
}
} else {
finalConfig[key] = value;
}
}
}
}
return finalConfig as Partial<TestRunnerConfig>;
}
| modernweb-dev/web/packages/test-runner/src/config/mergeConfigs.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/src/config/mergeConfigs.ts",
"repo_id": "modernweb-dev",
"token_count": 263
} | 228 |
import type {
BrowserLauncher,
Logger,
Reporter,
ReporterArgs,
TestSuiteResult,
} from '@web/test-runner-core';
import { reportTestsErrors } from './reportTestsErrors.js';
import { reportTestFileErrors } from './reportTestFileErrors.js';
import { reportBrowserLogs } from './reportBrowserLogs.js';
interface Options {
flatten?: boolean;
}
const color =
([x, y]: [number, number]) =>
(z: string) =>
`\x1b[${x}m${z}\x1b[${y}m${reset}`;
const reset = `\x1b[0m\x1b[0m`;
const green = color([32, 89]);
const red = color([31, 89]);
const dim = color([2, 0]);
/** Test reporter that summarizes all test for a given run */
export function summaryReporter(opts: Options): Reporter {
const { flatten = false } = opts ?? {};
let args: ReporterArgs;
let favoriteBrowser: string;
function log(logger: Logger, name: string, passed: boolean, prefix = ' ', postfix = '') {
const sign = passed ? green('✓') : red('𐄂');
if (flatten) logger.log(`${sign} ${name}${postfix}`);
else logger.log(`${prefix} ${sign} ${name}`);
}
function logResults(
logger: Logger,
results?: TestSuiteResult,
prefix?: string,
browser?: BrowserLauncher,
) {
const browserName = browser?.name ? ` ${dim(`[${browser.name}]`)}` : '';
for (const result of results?.tests ?? []) {
log(logger, result.name, result.passed, prefix, browserName);
}
for (const suite of results?.suites ?? []) {
logSuite(logger, suite, prefix, browser);
}
}
function logSuite(
logger: Logger,
suite: TestSuiteResult,
parent?: string,
browser?: BrowserLauncher,
) {
const browserName = browser?.name ? ` ${dim(`[${browser.name}]`)}` : '';
let pref = parent ? `${parent} ` : ' ';
if (flatten) pref += `${suite.name}`;
else logger.log(`${pref}${suite.name}${browserName}`);
logResults(logger, suite, pref, browser);
}
let cachedLogger: Logger;
return {
start(_args) {
args = _args;
favoriteBrowser =
args.browserNames.find(name => {
const n = name.toLowerCase();
return n.includes('chrome') || n.includes('chromium') || n.includes('firefox');
}) ?? args.browserNames[0];
},
reportTestFileResults({ logger, sessionsForTestFile }) {
cachedLogger = logger;
for (const session of sessionsForTestFile) {
logResults(logger, session.testResults, '', session.browser);
logger.log('');
}
reportBrowserLogs(logger, sessionsForTestFile);
},
onTestRunFinished({ sessions }) {
const failedSessions = sessions.filter(s => !s.passed);
if (failedSessions.length > 0) {
cachedLogger.log('\n\nErrors Reported in Tests:\n\n');
reportTestsErrors(cachedLogger, args.browserNames, favoriteBrowser, failedSessions);
reportTestFileErrors(
cachedLogger,
args.browserNames,
favoriteBrowser,
failedSessions,
true,
);
}
},
};
}
| modernweb-dev/web/packages/test-runner/src/reporter/summaryReporter.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/src/reporter/summaryReporter.ts",
"repo_id": "modernweb-dev",
"token_count": 1192
} | 229 |
import fs from 'fs';
import { join, dirname, basename } from 'path';
import { fileURLToPath } from 'url';
import concurrently from 'concurrently';
import { green, red, yellow } from 'nanocolors';
export function runWorkspacesScripts({ script, concurrency, filteredPackages = [] }) {
const moduleDir = dirname(fileURLToPath(import.meta.url));
function findPackagesWithScript(directory) {
const packages = [];
for (const name of fs.readdirSync(directory)) {
if (!filteredPackages.includes(name)) {
const pkgPath = join(directory, name);
const pkgJsonPath = join(pkgPath, 'package.json');
if (fs.existsSync(pkgJsonPath)) {
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
if (pkgJson && pkgJson.scripts && pkgJson.scripts[script]) {
packages.push(pkgPath);
}
}
}
}
return packages;
}
const packagesDir = join(moduleDir, '..', 'packages');
const packagesWithScript = findPackagesWithScript(packagesDir);
const commands = packagesWithScript.map(pkgPath => ({
name: basename(pkgPath),
command: `cd ${pkgPath} && npm run ${script}`,
}));
const { result } = concurrently(commands, { maxProcesses: concurrency });
result
.then(() => {
console.log(
green(
`Successfully executed command ${yellow(script)} for packages: ${yellow(
commands.map(c => c.name).join(', '),
)}`,
),
);
console.log();
})
.catch(error => {
if (error instanceof Error) {
console.error(error);
} else if (Array.isArray(error)) {
const count = error.filter(error => error !== 0).length;
console.log('');
console.log(
red(
`Failed to execute command ${yellow(
script,
)} for ${count} packages. But we don't know which ones, because concurrently doesn't say.`,
),
);
console.log();
}
process.exit(1);
});
}
| modernweb-dev/web/scripts/runWorkspacesScripts.mjs/0 | {
"file_path": "modernweb-dev/web/scripts/runWorkspacesScripts.mjs",
"repo_id": "modernweb-dev",
"token_count": 833
} | 230 |
{
"name": "opendota-web",
"description": "Dota 2 Data Web UI",
"version": "1.0.1",
"private": true,
"license": "MIT",
"scripts": {
"start": "vite --host",
"start:install": "npm install && npm run lint && npm run start",
"preview": "vite preview --host",
"build": "vite build && npm run typecheck",
"build:install": "npm install && npm run lint && npm run build",
"test": "testcafe -c 4 chrome testcafe/ --app \"serve -s build\"",
"analyze": "source-map-explorer build/static/js/main.* --html > analyze.html",
"typecheck": "tsc --project tsconfig.json --noEmit",
"lintfix": "eslint . --ext .ts,.tsx,.js,.jsx --fix",
"lint": "eslint . --ext .ts,.tsx,.js,.jsx",
"update:emoticons": "npm r dota2-emoticons && npm i dota2-emoticons && node dev/updateEmoticons.js"
},
"repository": {
"type": "git",
"url": "http://github.com/odota/web"
},
"dependencies": {
"@material-ui/core": "^4.5.0",
"@material-ui/icons": "^4.5.1",
"@material-ui/styles": "^4.5.0",
"@stripe/stripe-js": "^1.32.0",
"abcolor": "^0.5.5",
"ace-builds": "^1.4.7",
"core-js": "^3.6.4",
"dota2-emoticons": "^1.0.3",
"dotaconstants": "^8.5.0",
"fuzzy": "^0.1.3",
"heatmap.js": "github:muyao1987/heatmap.js",
"history": "^4.10.1",
"lodash": "^4.17.15",
"long": "^4.0.0",
"material-ui": "^0.20.2",
"nanoid": "^2.1.8",
"papaparse": "^5.1.1",
"prop-types": "^15.7.2",
"querystring": "^0.2.1",
"react": "^17.0.2",
"react-content-loader": "^3.1.2",
"react-countup": "^6.5.0",
"react-dom": "^17.0.2",
"react-ga": "^2.7.0",
"react-helmet": "^5.2.1",
"react-lazylog": "^4.5.3",
"react-markdown": "^4.0.3",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-stripe-checkout": "^2.6.3",
"react-tooltip": "3.11.1",
"react-transition-group": "^2.5.0",
"recharts": "^2.4.3",
"redux": "^4.0.5",
"redux-responsive": "^4.3.8",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0",
"seamless-immutable": "^7.1.3",
"styled-components": "^4.4.1",
"use-react-router": "^1.0.7",
"vite": "^4.5.0",
"wordcloud": "^1.1.1"
},
"devDependencies": {
"@babel/core": "^7.23.7",
"@babel/eslint-parser": "^7.23.3",
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/plugin-transform-runtime": "^7.23.7",
"@babel/preset-env": "^7.23.7",
"@babel/preset-react": "^7.23.3",
"@types/core-js": "^2.5.2",
"@types/eslint": "^6.1.3",
"@types/heatmap.js": "^2.0.36",
"@types/history": "^4.7.3",
"@types/hoist-non-react-statics": "^3.3.1",
"@types/isomorphic-fetch": "^0.0.35",
"@types/jest": "^24.0.24",
"@types/lodash": "^4.14.149",
"@types/long": "^4.0.0",
"@types/material-ui": "^0.20.8",
"@types/nanoid": "^2.1.0",
"@types/node": "^12.12.20",
"@types/papaparse": "^5.0.3",
"@types/prop-types": "^15.7.3",
"@types/react": "^17.0.40",
"@types/react-content-loader": "^3.1.4",
"@types/react-dom": "^17.0.13",
"@types/react-helmet": "^5.0.11",
"@types/react-redux": "^7.1.4",
"@types/react-router-dom": "^4.3.5",
"@types/react-tooltip": "3.9.3",
"@types/react-transition-group": "^2.9.2",
"@types/recharts": "^1.8.27",
"@types/seamless-immutable": "^7.1.11",
"@types/styled-components": "4.0.3",
"@types/wordcloud": "^1.1.1",
"@typescript-eslint/eslint-plugin": "^6.18.0",
"@typescript-eslint/parser": "^4.33.0",
"babel-preset-es2015": "^6.24.1",
"cross-env": "^6.0.3",
"eslint": "^7.32.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-prettier": "^7.2.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-jsx-a11y": "^6.8.0",
"eslint-plugin-react": "^7.33.2",
"hoist-non-react-statics": "^3.3.1",
"husky": "^3.1.0",
"isomorphic-fetch": "^2.2.1",
"sanitize-filename": "^1.6.3",
"simple-vdf": "^1.1.1",
"testcafe": "^1.7.1",
"testcafe-react-selectors": "^3.3.0",
"typescript": "^5.2.2"
},
"overrides": {
"react-error-overlay": "6.0.9"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
| odota/web/package.json/0 | {
"file_path": "odota/web/package.json",
"repo_id": "odota",
"token_count": 2239
} | 231 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd">
<path fill="#fff" d="M640 480H0V0h640z"/>
<path fill="#df0000" d="M640 480H0V319.997h640zm0-319.875H0V.122h640z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/at.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/at.svg",
"repo_id": "odota",
"token_count": 121
} | 232 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd">
<path fill="#00cd00" d="M426.83 0H640v480H426.83z"/>
<path fill="#ff9a00" d="M0 0h212.88v480H0z"/>
<path fill="#fff" d="M212.88 0h213.95v480H212.88z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/ci.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/ci.svg",
"repo_id": "odota",
"token_count": 144
} | 233 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd" stroke-width="1pt">
<path fill="red" d="M0 0h213.333v480H0z"/>
<path fill="#ff0" d="M213.333 0h213.333v480H213.333z"/>
<path fill="#090" d="M426.666 0H640v480H426.665z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/gn.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/gn.svg",
"repo_id": "odota",
"token_count": 147
} | 234 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd" stroke-width="1pt">
<path fill="#fff" d="M0 0h639.995v480.004H0z"/>
<path fill="#009A49" d="M0 0h213.334v480.004H0z"/>
<path fill="#FF7900" d="M426.668 0h213.334v480.004H426.668z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/ie.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/ie.svg",
"repo_id": "odota",
"token_count": 155
} | 235 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<path fill="#00a1de" d="M0 240h640v240H0z"/>
<path fill="#ed2939" d="M0 0h640v240H0z"/>
<path fill="#fff" d="M0 160h640v160H0z"/>
</svg>
| odota/web/public/assets/images/flags/lu.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/lu.svg",
"repo_id": "odota",
"token_count": 110
} | 236 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g stroke-width="1pt" fill-rule="evenodd">
<path fill="#fff" d="M0 0h640v480H0z"/>
<path fill="#00267f" d="M0 0h213.33v480H0z"/>
<path fill="#f31830" d="M426.67 0H640v480H426.67z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/mq.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/mq.svg",
"repo_id": "odota",
"token_count": 144
} | 237 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd" stroke-width="1pt" transform="scale(1.25 .9375)">
<rect rx="0" ry="0" height="509.76" width="512" fill="#fff"/>
<rect rx="0" ry="0" height="169.92" width="512" y="342.08" fill="#21468b"/>
<path fill="#ae1c28" d="M0 0h512v169.92H0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/nl.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/nl.svg",
"repo_id": "odota",
"token_count": 173
} | 238 |
<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-37.298 0h682.67v512h-682.67z"/>
</clipPath>
</defs>
<g fill-rule="evenodd" clip-path="url(#a)" transform="translate(34.967) scale(.9375)">
<path fill="#ed0000" d="M-37.298 0h768v512h-768z"/>
<path fill="#fff" d="M-37.298 102.4h768v102.4h-768zM-37.298 307.2h768v102.4h-768z"/>
<path d="M-37.298 0l440.69 255.67-440.69 255.34V0z" fill="#0050f0"/>
<path d="M156.45 325.47l-47.447-35.432-47.214 35.78 17.56-58.144-47.128-35.904 58.305-.5L108.61 173.3l18.472 57.835 58.305.077-46.886 36.243 17.947 58.016z" fill="#fff"/>
</g>
</svg>
| odota/web/public/assets/images/flags/pr.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/pr.svg",
"repo_id": "odota",
"token_count": 361
} | 239 |
<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" clip-path="url(#a)">
<path fill="#fff" d="M-20 0h720v480H-20z"/>
<path fill="#df0000" d="M-20 0h720v240H-20z"/>
<path d="M146.05 40.227c-33.243 7.622-57.944 32.237-64.927 65.701-9.488 45.469 20.124 89.99 65.687 99.488-46.031 13.125-93.59-13.332-106.594-58.932-12.996-45.6 13.46-93.16 59.063-106.162 16.007-4.565 30.745-4.594 46.773-.095z" fill="#fff"/>
<path fill="#fff" d="M132.98 109.953l4.894 15.119-12.932-9.23-12.87 9.317 4.783-15.144-12.833-9.354 15.876-.137 4.932-15.106 5.031 15.069 15.889.025zM150.539 162.012l4.894 15.119-12.932-9.23-12.87 9.317 4.783-15.143-12.833-9.355 15.877-.137 4.931-15.106 5.032 15.07 15.888.024zM208.964 161.637l4.894 15.119-12.932-9.23-12.87 9.317 4.783-15.143-12.833-9.355 15.877-.137 4.931-15.106 5.032 15.07 15.888.024zM226.392 110l4.894 15.118-12.932-9.23-12.87 9.317 4.783-15.143-12.833-9.354 15.877-.137 4.932-15.106 5.03 15.069 15.89.025zM180.136 75.744l4.894 15.118-12.932-9.23-12.87 9.317 4.783-15.143-12.833-9.355 15.876-.136 4.932-15.106 5.032 15.068 15.888.025z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/sg.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/sg.svg",
"repo_id": "odota",
"token_count": 686
} | 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="M10 0h160v120H10z"/>
</clipPath>
</defs>
<g clip-path="url(#a)" fill-rule="evenodd" transform="matrix(4 0 0 4 -40 0)" stroke-width="1pt">
<path fill="#09f" d="M0 0h180v120H0z"/>
<path d="M0 0h180L0 120V0z" fill="#090"/>
<path d="M0 120h40l140-95V0h-40L0 95v25z"/>
<path d="M0 91.456L137.18 0h13.52L0 100.47v-9.014zM29.295 120l150.7-100.47v9.014L42.815 120h-13.52z" fill="#ff0"/>
</g>
</svg>
| odota/web/public/assets/images/flags/tz.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/tz.svg",
"repo_id": "odota",
"token_count": 291
} | 241 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd" stroke-width="1pt">
<path fill="red" d="M0 0h640v480H0z"/>
<path fill="#00006b" d="M0 0h314.407v157.21H0z"/>
<g fill="#fff">
<path d="M162.77 144.4l-12.468-8.415-11.95 8.555 3.795-15.007-11.471-9.25 14.817-.858 4.862-14.274 5.357 14.477 14.477.427-11.504 9.81zM160.634 44.574l-9.975-6.41-9.795 6.362 2.72-11.953-8.781-7.817 11.66-.977 4.357-11.192 4.49 11.349 11.48.9-8.888 7.99zM116.551 80.496l-9.708-6.66-9.922 6.658 3.089-11.673-9.147-7.768 11.607-.554 4.273-11.46 4.091 11.33 11.781.687-9.08 7.556zM204.934 72.47l-9.315-6.01-9.064 6.083 2.608-11.083-8.35-7.096 10.926-.841 3.899-10.468 4.143 10.564 10.763.625-8.362 7.37zM178.882 98.717l-6.21-3.868-6.188 3.907 1.613-7.347-5.482-4.924 7.208-.673 2.804-6.95 2.841 6.93 7.213.63-5.453 4.956z"/>
</g>
</g>
</svg>
| odota/web/public/assets/images/flags/ws.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/ws.svg",
"repo_id": "odota",
"token_count": 509
} | 242 |
export default function transformRankings(json) {
return json;
}
| odota/web/src/actions/transformRankings.js/0 | {
"file_path": "odota/web/src/actions/transformRankings.js",
"repo_id": "odota",
"token_count": 18
} | 243 |
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import React, { Suspense } from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { Route, Switch, withRouter } from 'react-router-dom';
import styled from 'styled-components';
import Combos from './../Combos/Combos';
import Api from '../Api';
import Subscription from '../Subscription';
import constants from '../constants';
import Distributions from '../Distributions';
import Footer from '../Footer';
import FourOhFour from '../FourOhFour';
import Header from '../Header';
import Home from '../Home';
import Matches from '../Matches';
import Player from '../Player';
// import Predictions from '../Predictions';
// import Assistant from "../Assistant";
import Records from '../Records';
import Request from '../Request';
import Scenarios from '../Scenarios';
import Search from '../Search';
import Teams from '../Teams';
import GlobalStyle from './GlobalStyle';
import muiTheme from './muiTheme';
import config from '../../config';
import Spinner from '../Spinner';
const Status = React.lazy(() => import('../Status'));
const Explorer = React.lazy(() => import('../Explorer'));
const Heroes = React.lazy(() => import('../Heroes'));
const StyledDiv = styled.div`
transition: ${constants.normalTransition};
position: relative;
display: flex;
flex-direction: column;
height: 100%;
left: ${(props) => (props.open ? '256px' : '0px')};
margin-top: 0px;
background-image: ${(props) =>
props.location.pathname === '/'
? 'url("/assets/images/home-background.png")'
: ''};
background-position: center top -56px;
background-repeat: ${(props) =>
props.location.pathname === '/' ? 'no-repeat' : ''};
#back2Top {
position: fixed;
left: auto;
right: 0px;
top: auto;
bottom: 20px;
outline: none;
color: rgb(196, 196, 196);
text-align: center;
outline: none;
border: none;
background-color: rgba(0, 0, 0, 0.3);
width: 40px;
font-size: 14px;
border-radius: 2px;
cursor: pointer;
z-index: 999999;
opacity: 0;
display: block;
pointer-events: none;
-webkit-transform: translate3d(0, 0, 0);
padding: 3px;
transition: opacity 0.3s ease-in-out;
& #back2TopTxt {
font-size: 10px;
line-height: 12px;
text-align: center;
margin-bottom: 3px;
}
}
#back2Top:hover {
background-color: rgb(26, 108, 239);
}
`;
const StyledBodyDiv = styled.div`
padding: 0px 25px 25px 25px;
flex-grow: 1;
@media only screen and (min-width: ${constants.appWidth}px) {
width: ${constants.appWidth}px;
margin: auto;
}
`;
const AdBannerDiv = styled.div`
text-align: center;
margin-bottom: 5px;
& img {
margin-top: 10px;
max-width: 100%;
}
`;
const App = (props) => {
const { strings, location } = props;
const back2Top = React.useRef();
React.useEffect(() => {
const handleScroll = () => {
let wait = false;
const { current } = back2Top;
if (!wait) {
if (
document.body.scrollTop > 1000 ||
document.documentElement.scrollTop > 1000
) {
current.style.opacity = 1;
current.style.pointerEvents = 'auto';
} else {
current.style.opacity = 0;
current.style.pointerEvents = 'none';
}
}
setTimeout(() => {
wait = !wait;
}, 300);
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
});
React.useLayoutEffect(() => {
window.scrollTo(0, 0);
}, [location]);
const includeAds = !['/', '/api-keys', '/status'].includes(location.pathname);
React.useEffect(() => {
if (includeAds) {
(window.adsbygoogle = window.adsbygoogle || []).push({});
}
}, []);
return (
<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme, muiTheme)}>
<Suspense fallback={<Spinner />}>
<GlobalStyle />
<StyledDiv {...props}>
<Helmet
defaultTitle={strings.title_default}
titleTemplate={strings.title_template}
/>
<Header location={location} />
<StyledBodyDiv {...props}>
<AdBannerDiv>
{includeAds && config.VITE_ENABLE_ADSENSE && (
<ins
className="adsbygoogle"
style={{display: 'block', width: 728, height: 90, margin: 'auto'}}
data-ad-client="ca-pub-5591574346816667"
data-ad-slot="9789745633"
/>)}
</AdBannerDiv>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/matches/:matchId?/:info?" component={Matches} />
<Route
exact
path="/players/:playerId/:info?/:subInfo?"
component={Player}
/>
<Route exact path="/heroes/:heroId?/:info?" component={Heroes} />
<Route exact path="/teams/:teamId?/:info?" component={Teams} />
<Route
exact
path="/distributions/:info?"
component={Distributions}
/>
<Route exact path="/request" component={Request} />
<Route exact path="/status" component={Status} />
<Route exact path="/explorer" component={Explorer} />
<Route exact path="/combos" component={Combos} />
<Route exact path="/search" component={Search} />
<Route exact path="/records/:info?" component={Records} />
{/* <Route exact path="/meta" component={Meta} /> */}
<Route exact path="/scenarios/:info?" component={Scenarios} />
{/* <Route exact path="/predictions" component={Predictions} /> */}
<Route exact path="/api-keys" component={Api} />
<Route exact path="/subscribe" component={Subscription} />
<Route component={FourOhFour} />
</Switch>
</StyledBodyDiv>
<AdBannerDiv>
{includeAds && config.VITE_ENABLE_RIVALRY && (
<div style={{ fontSize: '12px' }}>
<a href="https://www.rivalry.com/opendota">
<img src="/assets/images/rivalry-banner.gif" alt="Logo for Rivalry.com" />
</a>
<div>
{strings.home_sponsored_by}{' '}
<a href="https://www.rivalry.com/opendota">Rivalry</a>
</div>
</div>
)}
{includeAds && config.VITE_ENABLE_ADSENSE && (
<ins
className="adsbygoogle"
style={{display: 'block', width: 728, height: 90, margin: 'auto'}}
data-ad-client="ca-pub-5591574346816667"
data-ad-slot="7739169508"
/>
)}
</AdBannerDiv>
<Footer />
<button
ref={back2Top}
id="back2Top"
title={strings.back2Top}
onClick={() => {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}}
>
<div>▲</div>
<div id="back2TopTxt">{strings.back2Top}</div>
</button>
</StyledDiv>
</Suspense>
</MuiThemeProvider>
);
};
const mapStateToProps = (state) => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(withRouter(App));
| odota/web/src/components/App/App.jsx/0 | {
"file_path": "odota/web/src/components/App/App.jsx",
"repo_id": "odota",
"token_count": 3295
} | 244 |
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { patchDate } from '../../utility';
const setMapSizeStyle = (width, maxWidth) => ({
width,
height: width,
maxWidth,
maxHeight: maxWidth,
});
const dotaMaps = [
{ patch: '7.33', images: { jpg: '/assets/images/dota2/map/detailed_733.jpg', webp: '/assets/images/dota2/map/detailed_733.webp' } },
{ patch: '7.32', images: { jpg: '/assets/images/dota2/map/detailed_732.jpg', webp: '/assets/images/dota2/map/detailed_732.webp' } },
{ patch: '7.23', images: { jpg: '/assets/images/dota2/map/detailed_723.jpg', webp: '/assets/images/dota2/map/detailed_723.webp' } },
{ patch: '7.20', images: { jpg: '/assets/images/dota2/map/detailed_720.jpg', webp: '/assets/images/dota2/map/detailed_720.webp' } },
{ patch: '7.07', images: { jpg: '/assets/images/dota2/map/detailed_707.jpg', webp: '/assets/images/dota2/map/detailed_707.webp' } },
{ patch: '7.00', images: { jpg: '/assets/images/dota2/map/detailed_700.jpg', webp: '/assets/images/dota2/map/detailed_700.webp' } },
{ patch: '6.86', images: { jpg: '/assets/images/dota2/map/detailed_686.jpg', webp: '/assets/images/dota2/map/detailed_686.webp' } },
{ patch: '6.82', images: { jpg: '/assets/images/dota2/map/detailed_682.jpg', webp: '/assets/images/dota2/map/detailed_682.webp' } },
{ patch: '6.70', images: { jpg: '/assets/images/dota2/map/detailed_pre682.jpg', webp: '/assets/images/dota2/map/detailed_pre682.webp' } },
];
const getPatchMap = (startTime) => {
if (!startTime) return dotaMaps[0];
const patchMap = dotaMaps.find(dotaMap => startTime >= patchDate[dotaMap.patch]);
return patchMap || dotaMaps[0];
};
const MapContainer = styled.div`
position: relative;
`;
const MapImage = styled.picture`
position: relative;
img {
height: 100%;
max-width: 100%;
}
`;
const MapContent = styled.div`
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
z-index: 2;
`;
const DotaMap = ({
startTime = null,
maxWidth = 400,
width = 400,
children,
}) => {
const mapData = getPatchMap(startTime);
return (
<MapContainer style={setMapSizeStyle(width, maxWidth)}>
<MapImage>
<source srcSet={mapData.images.webp} type="image/webp" />
<source srcSet={mapData.images.jpg} type="image/jpeg" />
<img src={mapData.images.jpg} alt={`Dota 2 Map - ${mapData.patch}`} />
</MapImage>
<MapContent>
{children}
</MapContent>
</MapContainer>
);
};
const {
number, node, string, oneOfType,
} = PropTypes;
DotaMap.propTypes = {
startTime: number,
maxWidth: oneOfType([number, string]),
width: oneOfType([number, string]),
children: oneOfType([node, string]),
};
export default DotaMap;
| odota/web/src/components/DotaMap/index.jsx/0 | {
"file_path": "odota/web/src/components/DotaMap/index.jsx",
"repo_id": "odota",
"token_count": 1117
} | 245 |
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import CheeseCircle from '../Cheese';
const Cheese = ({ strings }) => (
<div className="cheese">
<CheeseCircle />
<section>
<span style={{ fontSize: 'larger' }} >
{strings.app_donation_goal}
</span>
<p style={{ marginTop: 5 }}>
<a href="//carry.opendota.com">
{strings.app_sponsorship}
</a>
</p>
</section>
</div>
);
Cheese.propTypes = {
strings: PropTypes.shape({}),
};
const mapStateToProps = state => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(Cheese);
| odota/web/src/components/Footer/Cheese.jsx/0 | {
"file_path": "odota/web/src/components/Footer/Cheese.jsx",
"repo_id": "odota",
"token_count": 275
} | 246 |
import styled from 'styled-components';
import constants from '../constants';
export const StyledDiv = styled.div`
margin-top: 15px;
margin-bottom: 4px;
margin-left: 3px;
&.top-heading {
width: 100vw;
margin: -57px -50vw 50px -50vw;
margin-top: 0px;
position: relative;
left: 50%;
right: 50%;
padding: 15px 0px 15px 20px;
display: flex;
flex-direction: column;
justify-content: left;
align-items: baseline;
letter-spacing: 10px;
font-weight: bold;
background-color: rgba(14, 84, 113, 37%);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
&.with-tabbar {
margin-top: -30px;
}
}
.winner {
position: relative;
bottom: 1px;
background: rgb(25, 25, 25);
font-size: 10px;
padding: 1px;
padding-right: 4px;
margin-left: 10px;
margin-right: 5px;
letter-spacing: 1px;
text-transform: uppercase;
opacity: 0.6;
}
.winner:after {
right: 100%;
top: 50%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-right-color: rgb(25, 25, 25);
border-width: 8px;
margin-top: -8px;
}
& svg {
height: 20px !important;
width: 20px !important;
position: relative;
margin-right: 6px;
top: 2px;
opacity: 0.8;
fill: ${constants.textColorPrimary};
}
& a {
color: ${constants.primaryTextColor};
text-decoration: none;
&:hover {
color: ${constants.primaryLinkColor};
}
}
& .title {
font-size: 14px;
font-weight: 500;
letter-spacing: 1px;
}
&.top-heading .title {
font-size: 20px;
font-weight: 500;
letter-spacing: 1px;
margin-left: 52px;
&::before {
content: "▶";
margin-right: 4px;
}
}
& .subtitle {
margin-left: 5px;
font-size: ${constants.fontSizeMedium};
color: ${constants.colorMutedLight};
}
&.top-heading .subtitle {
margin-left: 10px;
font-size: 14px;
color: rgba(255,255,255,0.6);
letter-spacing: normal;
font-weight: normal;
margin-left: 51px;
}
.sponsor-button {
margin: 0px 5px;
/* Material-ui buttons */
@media only screen and (max-width: 620px) {
& a {
min-width: 24px !important;
& span {
font-size: 0 !important;
padding-left: 0 !important;
padding-right: 12px !important;
}
}
}
}
& .info {
margin-left: 5px;
font-size: ${constants.fontSizeMedium};
color: ${constants.colorMuted};
border-bottom: 1px dotted ${constants.colorMuted};
}
`;
export const TwoLineDiv = styled(StyledDiv)`
text-align: center;
padding: 10px 0 15px;
& span:last-child {
display: block;
text-transform: lowercase;
}
`;
| odota/web/src/components/Heading/Styled.jsx/0 | {
"file_path": "odota/web/src/components/Heading/Styled.jsx",
"repo_id": "odota",
"token_count": 1262
} | 247 |
import React from 'react';
import styled from 'styled-components';
import { shape } from 'prop-types';
import constants from '../constants';
import AttributesMain from './AttributesMain';
import Abilities from './Abilities';
import config from '../../config';
const getHeroImgSrc = (src) => config.VITE_IMAGE_CDN + src;
const HeroProfile = styled.div`
background: ${constants.almostBlack};
overflow: hidden;
position: relative;
border-radius: 8px;
`;
const HeroProfileBackground = styled.img`
background-repeat: no-repeat;
filter: blur(25px);
height: 125%;
left: -12.5%;
object-fit: cover;
opacity: 0.35;
position: absolute;
top: -12.5%;
width: 125%;
`;
const HeroProfileContent = styled.div`
align-items: center;
box-shadow: inset 0 0 125px rgba(0, 0, 0, 0.25);
display: flex;
padding: 56px;
position: relative;
@media screen and (max-width: ${constants.wrapTablet}) {
padding: 16px;
}
@media screen and (max-width: ${constants.wrapMobile}) {
display: block;
text-align: center;
}
`;
const HeroDetails = styled.div`
flex: 1 1 100%;
margin: 0 24px;
@media screen and (max-width: ${constants.wrapMobile}) {
margin: 12px 0;
}
`;
const HeroAvatar = styled.img`
border-radius: 16px;
border: solid 1px rgba(0, 0, 0, 0.3);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.3);
display: block;
flex-shrink: 0;
height: 128px;
object-fit: cover;
width: 180px;
@media screen and (max-width: ${constants.wrapTablet}) {
height: 64px;
width: 120px;
}
@media screen and (max-width: ${constants.wrapMobile}) {
margin: auto;
}
`;
const HeroName = styled.div`
font-size: 40px;
font-weight: ${constants.fontWeightMedium};
line-height: 40px;
@media screen and (max-width: ${constants.wrapTablet}) {
font-size: 28px;
line-height: 28px;
}
`;
const HeroRoleInformations = styled.div`
color: ${constants.primaryTextColor};
font-size: 12px;
letter-spacing: 1px;
margin: 8px 0;
text-transform: uppercase;
@media screen and (max-width: ${constants.wrapTablet}) {
font-size: 10px;
}
`;
const HeroRoles = styled.span`
color: ${constants.colorMutedLight};
word-wrap: break-word;
`;
const HeroDescription = styled.div`
display: flex;
flex-direction: column;
flex-grow: 1;
`;
const HeroStatsWrapper = styled.div`
flex: 1 1 100%;
`;
const Header = ({ hero }) => (
<HeroDescription>
<HeroProfile>
<HeroProfileBackground
alt={hero.localized_name}
src={getHeroImgSrc(hero.img)}
/>
<HeroProfileContent>
<HeroAvatar alt={hero.localized_name} src={getHeroImgSrc(hero.img)} />
<HeroDetails>
<HeroName>{hero.localized_name}</HeroName>
<HeroRoleInformations>
{hero.attack_type} - <HeroRoles>{hero.roles.join(', ')}</HeroRoles>
</HeroRoleInformations>
</HeroDetails>
<HeroStatsWrapper>
<AttributesMain hero={hero} />
<Abilities hero={hero} />
</HeroStatsWrapper>
</HeroProfileContent>
</HeroProfile>
</HeroDescription>
);
Header.propTypes = {
hero: shape({}),
};
export default Header;
| odota/web/src/components/Hero/Header.jsx/0 | {
"file_path": "odota/web/src/components/Hero/Header.jsx",
"repo_id": "odota",
"token_count": 1245
} | 248 |
import Home from './Home';
export default Home;
| odota/web/src/components/Home/index.ts/0 | {
"file_path": "odota/web/src/components/Home/index.ts",
"repo_id": "odota",
"token_count": 14
} | 249 |
import React from 'react';
export default props => (
<svg {...props} viewBox="0 0 300 300">
<path
d="M150,4C67.3,4,0.3,71,0.3,153.7c0,66.1,42.9,122.2,102.4,142c7.5,1.4,10.2-3.2,10.2-7.2c0-3.6-0.1-13-0.2-25.5
c-41.6,9-50.4-20.1-50.4-20.1c-6.8-17.3-16.6-21.9-16.6-21.9c-13.6-9.3,1-9.1,1-9.1c15,1.1,22.9,15.4,22.9,15.4
c13.4,22.9,35,16.3,43.6,12.4c1.4-9.7,5.2-16.3,9.5-20c-33.2-3.8-68.2-16.6-68.2-74c0-16.3,5.8-29.7,15.4-40.2
c-1.5-3.8-6.7-19,1.5-39.6c0,0,12.6-4,41.2,15.3c11.9-3.3,24.7-5,37.5-5c12.7,0.1,25.5,1.7,37.5,5c28.6-19.4,41.1-15.3,41.1-15.3
c8.2,20.6,3,35.8,1.5,39.6c9.6,10.5,15.4,23.8,15.4,40.2c0,57.5-35,70.2-68.4,73.9c5.4,4.6,10.2,13.8,10.2,27.7
c0,20-0.2,36.2-0.2,41.1c0,4,2.7,8.7,10.3,7.2c59.4-19.8,102.3-75.9,102.3-142C299.7,71,232.7,4,150,4z"
/>
</svg>
);
| odota/web/src/components/Icons/Github.jsx/0 | {
"file_path": "odota/web/src/components/Icons/Github.jsx",
"repo_id": "odota",
"token_count": 634
} | 250 |
export { default as IconCheese } from './Cheese';
export { default as IconSteam } from './Steam';
export { default as IconGithub } from './Github';
export { default as IconTwitter } from './Twitter';
export { default as IconDiscord } from './Discord';
export { default as IconTrophy } from './Trophy';
export { default as IconLogout } from './Logout';
export { default as IconOpenSource } from './OpenSource';
export { default as IconStatsBars } from './StatsBars';
export { default as IconWand } from './Wand';
export { default as IconRadiant } from './Radiant';
export { default as IconDire } from './Dire';
export { default as IconLightbulb } from './Lightbulb';
export { default as IconBloodDrop } from './BloodDrop';
export { default as IconRoshan } from './Roshan';
export { default as IconBattle } from './Battle';
export { default as IconDot } from './Dot';
export { default as IconBackpack } from './Backpack';
export { default as IconDice } from './Dice';
export { default as IconCrystalBall } from './CrystalBall';
export { default as IconCheckCircle } from './CheckCircle';
export { default as IconLaneRoles } from './LaneRoles';
export { default as IconContributor } from './Contributor';
export { default as IconPlusSquare } from './PlusSquare';
export { default as IconMinusSquare } from './MinusSquare';
| odota/web/src/components/Icons/index.js/0 | {
"file_path": "odota/web/src/components/Icons/index.js",
"repo_id": "odota",
"token_count": 383
} | 251 |
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { List } from 'react-content-loader';
import TabbedContent from '../TabbedContent';
import { getMatch } from '../../actions';
import MatchHeader from './MatchHeader';
import matchPages from './matchPages';
import FourOhFour from '../../components/FourOhFour';
class RequestLayer extends React.Component {
static propTypes = {
loading: PropTypes.bool,
error: PropTypes.bool,
matchData: PropTypes.shape({}),
match: PropTypes.shape({
params: PropTypes.shape({
info: PropTypes.string,
}),
}),
user: PropTypes.shape({}),
getMatch: PropTypes.func,
matchId: PropTypes.string,
strings: PropTypes.shape({}),
}
componentDidMount() {
this.props.getMatch(this.props.matchId);
}
componentDidUpdate(prevProps) {
if (this.props.matchId !== prevProps.matchId) {
this.props.getMatch(this.props.matchId);
}
}
render() {
const {
loading, matchId, matchData, error, strings, match, user,
} = this.props;
const info = match.params.info || 'overview';
const page = matchPages(matchId, null, strings).find(_page => _page.key.toLowerCase() === info);
const pageTitle = page ? `${matchId} - ${page.name}` : matchId;
if (error && !loading) {
return <FourOhFour msg={strings.request_invalid_match_id} />;
}
return loading ? <List primaryColor="#666" width={250} height={120} /> :
(
<div>
<Helmet title={pageTitle} />
<MatchHeader
match={matchData}
user={user}
/>
<TabbedContent
info={info}
tabs={matchPages(matchId, matchData, strings)}
match={matchData}
content={page && page.content(matchData)}
skeleton={page && page.skeleton}
/>
</div>);
}
}
const mapStateToProps = state => ({
matchData: state.app.match.data,
loading: state.app.match.loading,
error: state.app.match.error,
user: state.app.metadata.data.user,
strings: state.app.strings,
});
const mapDispatchToProps = dispatch => ({
getMatch: matchId => dispatch(getMatch(matchId)),
});
export default connect(mapStateToProps, mapDispatchToProps)(RequestLayer);
| odota/web/src/components/Match/Match.jsx/0 | {
"file_path": "odota/web/src/components/Match/Match.jsx",
"repo_id": "odota",
"token_count": 916
} | 252 |
import React from 'react';
import PropTypes from 'prop-types';
import Checkbox from 'material-ui/Checkbox';
import Table from '../../Table';
import Heading from '../../Heading';
import PlayerThumb from '../PlayerThumb';
import config from '../../../config';
const data = [
{
type: 'observer',
image: <img height="24" src={`${config.VITE_IMAGE_CDN}/apps/dota2/images/dota_react/items/ward_observer.png`} alt="Observer ward" />,
},
{
type: 'sentry',
image: <img height="24" src={`${config.VITE_IMAGE_CDN}/apps/dota2/images/dota_react/items/ward_sentry.png`} alt="Sentry ward" />,
},
];
class VisionFilter extends React.Component {
static propTypes = {
match: PropTypes.shape({
players: PropTypes.arrayOf({}),
}),
parent: PropTypes.shape({
state: PropTypes.shape({
players: PropTypes.arrayOf({}),
teams: PropTypes.arrayOf({}),
}),
setPlayer: PropTypes.func,
teams: PropTypes.arrayOf({}),
setTeam: PropTypes.func,
setTypeWard: PropTypes.func,
checkedTypeWard: PropTypes.func,
onCheckAllWardsTeam: PropTypes.func,
}),
strings: PropTypes.shape({}),
};
columns(index) {
const { teams } = this.props.parent.state;
const { strings } = this.props;
return [
{
displayName: <Checkbox
checked={teams[index === 0 ? 'radiant' : 'dire']}
onCheck={(event, checked) => {
this.props.parent.setTeam(index === 0 ? 'radiant' : 'dire', checked);
}
}
/>,
displayFn: row => row.image,
},
this.playerColumn(0 + index),
this.playerColumn(1 + index),
this.playerColumn(2 + index),
this.playerColumn(3 + index),
this.playerColumn(4 + index),
{
displayName: strings.chat_filter_all,
displayFn: row => (<Checkbox
checked={this.props.parent.checkedTypeWard(index, row.type)}
onCheck={() => {
this.props.parent.setTypeWard(index, row.type);
}
}
/>),
},
];
}
playerColumn(playerNumber) {
return {
displayName: <PlayerThumb {...this.props.match.players[playerNumber]} hideText />,
displayFn: row => (<Checkbox
checked={this.props.parent.state.players[row.type][playerNumber]}
onCheck={(event, checked) => {
this.props.parent.setPlayer(playerNumber, row.type, checked);
}
}
/>),
};
}
render() {
const { strings } = this.props;
return (
<div>
<Heading title={strings.general_radiant} />
<Table data={data} columns={this.columns(0)} />
<Heading title={strings.general_dire} />
<Table data={data} columns={this.columns(5)} />
</div>
);
}
}
export default VisionFilter;
| odota/web/src/components/Match/Vision/VisionFilter.jsx/0 | {
"file_path": "odota/web/src/components/Match/Vision/VisionFilter.jsx",
"repo_id": "odota",
"token_count": 1231
} | 253 |
import React from 'react';
export default () => (
<div
style={{ backgroundImage: 'url(/assets/images/logo.png)' }}
/>
);
| odota/web/src/components/Player/Header/AppBadge.jsx/0 | {
"file_path": "odota/web/src/components/Player/Header/AppBadge.jsx",
"repo_id": "odota",
"token_count": 47
} | 254 |
const playerItemsColumns = strings => ([{
displayName: 'Name',
tooltip: strings.items_name,
field: 'name',
width: 1,
}]);
export default playerItemsColumns;
// "items_built"
// "items_matches": "Number of matches where this item was built",
// "items_uses": "Number of times this item was used",
// "items_uses_per_match": "Mean number of times this item was used in matches where it was built",
// "items_timing": "Mean time this item was built at",
// "items_build_pct": "Percentage of matches this item was built in",
// "items_win_pct": "Percentage of matches won where this item was built",
| odota/web/src/components/Player/Pages/Items/playerItemsColumns.jsx/0 | {
"file_path": "odota/web/src/components/Player/Pages/Items/playerItemsColumns.jsx",
"repo_id": "odota",
"token_count": 185
} | 255 |
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Card from './Card';
import { getPlayerTotals } from '../../../../actions';
import Container from '../../../Container';
const CardContainer = styled.div`
display: flex;
flex-wrap: wrap;
margin-left: -8px;
margin-right: -8px;
`;
const totalsToShow = {
kills: 1,
deaths: 1,
assists: 1,
last_hits: 1,
denies: 1,
duration: 1,
level: 1,
hero_damage: 1,
tower_damage: 1,
hero_healing: 1,
stuns: 'parsed',
tower_kills: 'parsed',
neutral_kills: 'parsed',
courier_kills: 'parsed',
purchase_tpscroll: 'parsed',
purchase_ward_observer: 'parsed',
purchase_ward_sentry: 'parsed',
purchase_gem: 'parsed',
purchase_rapier: 'parsed',
pings: 'parsed',
};
const drawElement = (element, type) => {
if (totalsToShow[element.field] === type) {
return <Card total={element} />;
}
return null;
};
const Totals = ({
data, error, loading, strings,
}) => (
<div>
<Container title={strings.heading_all_matches} error={error} loading={loading}>
<CardContainer>
{data.map(element => drawElement(element, 1))}
</CardContainer>
</Container>
<Container title={strings.heading_parsed_matches} error={error} loading={loading}>
<CardContainer>
{data.map(element => drawElement(element, 'parsed'))}
</CardContainer>
</Container>
</div>);
Totals.propTypes = {
data: PropTypes.arrayOf({}),
error: PropTypes.string,
loading: PropTypes.bool,
strings: PropTypes.shape({}),
};
const getData = (props) => {
props.getPlayerTotals(props.playerId, props.location.search);
};
class RequestLayer extends React.Component {
static propTypes = {
playerId: PropTypes.string,
location: PropTypes.shape({
key: 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(this.props);
}
}
render() {
return <Totals {...this.props} />;
}
}
const mapStateToProps = state => ({
data: state.app.playerTotals.data,
error: state.app.playerTotals.error,
loading: state.app.playerTotals.loading,
strings: state.app.strings,
});
const mapDispatchToProps = dispatch => ({
getPlayerTotals: (playerId, options) => dispatch(getPlayerTotals(playerId, options)),
});
export default connect(mapStateToProps, mapDispatchToProps)(RequestLayer);
| odota/web/src/components/Player/Pages/Totals/Totals.jsx/0 | {
"file_path": "odota/web/src/components/Player/Pages/Totals/Totals.jsx",
"repo_id": "odota",
"token_count": 986
} | 256 |
import Request from './Request';
export default Request;
| odota/web/src/components/Request/index.js/0 | {
"file_path": "odota/web/src/components/Request/index.js",
"repo_id": "odota",
"token_count": 14
} | 257 |
import React from 'react';
import ContentLoader from 'react-content-loader';
const MatchupsSkeleton = props => (
<ContentLoader
primaryColor="#666"
secondaryColor="#ecebeb"
width={400}
animate
{...props}
>
<rect x="0" y="10" rx="5" ry="5" width="300" height="5" />
<rect x="0" y="25" rx="5" ry="5" width="300" height="5" />
<rect x="0" y="40" rx="5" ry="5" width="300" height="5" />
<rect x="0" y="55" rx="5" ry="5" width="300" height="5" />
<rect x="0" y="70" rx="5" ry="5" width="300" height="5" />
</ContentLoader>
);
export default MatchupsSkeleton;
| odota/web/src/components/Skeletons/MatchupsSkeleton.jsx/0 | {
"file_path": "odota/web/src/components/Skeletons/MatchupsSkeleton.jsx",
"repo_id": "odota",
"token_count": 263
} | 258 |
import React from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import FlatButton from 'material-ui/FlatButton';
import Next from 'material-ui/svg-icons/hardware/keyboard-arrow-right';
import Prev from 'material-ui/svg-icons/hardware/keyboard-arrow-left';
import constants from '../../constants';
const StyledContainer = styled.div`
display: flex;
flex-direction: column;
align-items: ${props => (props.top ? 'flex-end' : 'center')};
${props => (props.top && `position:relative;
@media only screen and (max-width: 767px) {
align-items: center;
}
`)};
`;
const StyledPagination = styled.div`
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin-bottom: 10px;
& > div {
display: flex;
}
@media only screen and (max-width: 511px) {
flex-direction: column;
}
${props => props.top && `position: absolute;
right: 0;
top: -32px;
font-size: ${constants.fontSizeMedium};
@media only screen and (max-width: 767px) {
position: initial;
}
`}
`;
const pageStyle = `
color: ${constants.primaryLinkColor}!important;
min-width: 20px !important;
padding: 0 10px !important;
margin: 0 2px !important;
@media only screen and (max-width: 511px) {
/* Override material-ui */
min-width: 14px !important;
padding: 0 6px !important;
margin: 0 1px !important;
}
`;
const StyledPage = styled(FlatButton)`
${pageStyle}
`;
const arrowStyle = `
vertical-align: text-top;
/* Override material-ui */
color:${constants.colorYelor} !important;
padding: 0 !important;`;
const StyledArrowButton = styled(FlatButton)`
min-width: 20px !important;
${arrowStyle}
`;
const StyledPrev = styled(Prev)`
${arrowStyle}
`;
const StyledNext = styled(Next)`
${arrowStyle}
`;
const StyledCurrentPage = styled(FlatButton)`
${pageStyle}
/* Override material-ui */
color:${constants.colorMutedLight} !important;
pointer-events: none;
`;
const StyledInfo = styled.div`
font-size: ${constants.fontSizeMedium};
color: ${constants.colorMutedLight};
`;
const getPages = ({ currentPage, numPages, setCurrentPage }) => {
// let i = currentPage - 4 > 0 ? currentPage - 4 : 0;
const pages = [];
const minStart = Math.max(numPages - 5, 0);
const minEnd = Math.min(4, numPages - 1);
const targetStart = Math.max(currentPage - 2, 0);
const targetEnd = Math.min(currentPage + 2, numPages - 1);
const start = Math.min(targetStart, minStart);
const end = Math.max(targetEnd, minEnd);
for (let i = start; i <= end; i += 1) {
pages.push(i === currentPage ?
<StyledCurrentPage
key={i}
onClick={i === currentPage ? () => {} : () => setCurrentPage(i)}
>
{i + 1}
</StyledCurrentPage> :
<StyledPage
key={i}
onClick={i === currentPage ? () => {} : () => setCurrentPage(i)}
>
{i + 1}
</StyledPage>);
}
return pages;
};
const Pagination = ({
currentPage,
nextPage,
prevPage,
setCurrentPage,
numPages,
pageLength,
length,
place,
strings,
}) =>
numPages > 1 && (
<StyledContainer top={place === 'top'}>
<StyledPagination top={place === 'top'}>
{currentPage > 0 &&
<StyledPage onClick={() => setCurrentPage(0)}>
{strings.pagination_first}
</StyledPage>
}
<div>
{currentPage > 0 &&
<StyledArrowButton onClick={currentPage > 0 ? prevPage : () => {}}>
<StyledPrev />
</StyledArrowButton>
}
{currentPage > 2 && numPages > 2 &&
<StyledCurrentPage disabled>
...
</StyledCurrentPage>
}
{getPages({ currentPage, numPages, setCurrentPage })}
{numPages > currentPage + 3 &&
<StyledCurrentPage disabled>
...
</StyledCurrentPage>
}
{currentPage < numPages - 1 &&
<StyledArrowButton onClick={currentPage < (numPages - 1) ? nextPage : () => {}}>
<StyledNext />
</StyledArrowButton>
}
</div>
{currentPage < numPages - 1 &&
<StyledPage onClick={() => setCurrentPage(numPages - 1)}>
{strings.pagination_last}
</StyledPage>
}
</StyledPagination>
{place === 'bot' &&
<StyledInfo>
{((pageLength * currentPage) + 1).toLocaleString('en-US')}
{' - '}
{Math.min((pageLength * currentPage) + pageLength, length).toLocaleString('en-US')} {strings.pagination_of} {length.toLocaleString('en-US')}
</StyledInfo>
}
</StyledContainer>
);
const mapStateToProps = state => ({
strings: state.app.strings,
});
const mapDispatchToProps = () => ({
/*
nextPage: () => dispatch(nextPage(id)),
prevPage: () => dispatch(prevPage(id)),
setCurrentPage: pageNumber => dispatch(setCurrentPage(id, pageNumber)),
*/
});
export default connect(mapStateToProps, mapDispatchToProps)(Pagination);
| odota/web/src/components/Table/PaginatedTable/Pagination.jsx/0 | {
"file_path": "odota/web/src/components/Table/PaginatedTable/Pagination.jsx",
"repo_id": "odota",
"token_count": 2037
} | 259 |
import React from 'react';
import Container from '../Container';
import Table from '../Table';
import Overview from './Overview';
import { matchColumns, memberColumns, heroColumns } from './teamDataColumns';
const teamPages = strings => [Overview(strings), {
name: strings.tab_matches,
key: 'matches',
content: (generalData, matchData) => (
<Container
title={strings.heading_matches}
loading={matchData.loading}
error={matchData.error}
>
<Table
columns={matchColumns(strings)}
data={matchData.data}
paginated
key="matches"
/>
</Container>
),
}, {
name: strings.tab_heroes,
key: 'heroes',
content: (generalData, matchData, heroData) => (
<Container
title={strings.heading_heroes}
loading={heroData.loading}
error={heroData.error}
>
<Table
columns={heroColumns(strings)}
data={heroData.data}
paginated
key="heroes"
/>
</Container>
),
}, {
name: strings.tab_players,
key: 'players',
content: (generalData, matchData, heroData, playerData) => (
<div>
<Container
title={strings.heading_current_players}
loading={playerData.loading}
error={playerData.error}
>
<Table
columns={memberColumns(strings)}
data={playerData.data.filter(player => player.is_current_team_member)}
/>
</Container>
<Container
title={strings.heading_former_players}
loading={playerData.loading}
error={playerData.error}
>
<Table
columns={memberColumns(strings)}
data={playerData.data.filter(player => !player.is_current_team_member)}
paginated
key="players"
/>
</Container>
</div>
),
}];
export default (teamId, strings) => teamPages(strings).map(page => ({
...page,
route: `/teams/${teamId}/${page.key}`,
}));
| odota/web/src/components/Team/teamPages.jsx/0 | {
"file_path": "odota/web/src/components/Team/teamPages.jsx",
"repo_id": "odota",
"token_count": 815
} | 260 |
import React from 'react';
import PropTypes from 'prop-types';
import { gradient } from 'abcolor';
import { StyledContainer, PercentContainer, TitleContainer } from './Styled';
import constants from '../../constants';
const Percent = ({
percent, altValue, valEl, inverse = false,
}) => (
<StyledContainer>
<TitleContainer>
{valEl || percent} {altValue && <small>{altValue}</small>}
</TitleContainer>
<PercentContainer>
<div
style={{
width: `${percent}%`,
backgroundColor: gradient(percent, {
css: true,
from: inverse ? constants.colorGreen : constants.colorRed,
to: inverse ? constants.colorRed : constants.colorGreen,
}),
}}
/>
</PercentContainer>
</StyledContainer>
);
const {
number, oneOfType, string, node, bool,
} = PropTypes;
Percent.propTypes = {
percent: oneOfType([number, bool]),
altValue: oneOfType([string, number, bool]),
valEl: node,
inverse: bool,
};
Percent.tdStyle = {
paddingTop: 12,
paddingBottom: 12,
};
export default Percent;
| odota/web/src/components/Visualizations/Table/Percent.jsx/0 | {
"file_path": "odota/web/src/components/Visualizations/Table/Percent.jsx",
"repo_id": "odota",
"token_count": 411
} | 261 |
{
"yes": "sim",
"no": "não",
"abbr_thousand": "k",
"abbr_million": "m",
"abbr_billion": "b",
"abbr_trillion": "t",
"abbr_quadrillion": "q",
"abbr_not_available": "N/D",
"abbr_pick": "P",
"abbr_win": "V",
"abbr_number": "Nº.",
"analysis_eff": "Eficiência",
"analysis_farm_drought": "Menor OPM no intervalo de 5 minutos",
"analysis_skillshot": "Habilidades certeiras",
"analysis_late_courier": "Atraso no upgrade do courier",
"analysis_wards": "Sentinelas colocadas",
"analysis_roshan": "Roshans mortos",
"analysis_rune_control": "Runas obtidas",
"analysis_unused_item": "Itens com habilidade ativa não utilizados",
"analysis_expected": "de",
"announce_dismiss": "Cancelar",
"announce_github_more": "Ver no GitHub",
"api_meta_description": "A API da OpenDota fornece acesso à todas as estatísticas avançadas de Dota 2 oferecidas pela plataforma da OpenDota. Acesse gráficos de performance, calor, nuvem de palavras e mais. Comece já, é GRÁTIS!",
"api_title": "A API da OpenDota",
"api_subtitle": "Construa sobre a excelente plataforma OpenDota. Leve estatísticas avançadas, completas e profundas aos seus usuários.",
"api_details_free_tier": "Nível Grátis",
"api_details_premium_tier": "Nível Premium",
"api_details_price": "Preço",
"api_details_price_free": "Grátis",
"api_details_price_prem": "$price por $unit chamadas",
"api_details_key_required": "Chave necessária?",
"api_details_key_required_free": "Não",
"api_details_key_required_prem": "Sim - requer método de pagamento",
"api_details_call_limit": "Limite de chamadas",
"api_details_call_limit_free": "$limit por mês",
"api_details_call_limit_prem": "Sem limites",
"api_details_rate_limit": "Taxa limite",
"api_details_rate_limit_val": "$num chamadas por minuto",
"api_details_support": "Suporte",
"api_details_support_free": "Suporte da Comunidade através de grupo no Discord",
"api_details_support_prem": "Suporte prioritário pelos principais desenvolvedores",
"api_get_key": "Obter chave",
"api_docs": "Ler documentos",
"api_header_details": "Detalhes",
"api_charging": "Taxa cobrada: $cost por chamada, arredondada para o centavo mais próximo.",
"api_credit_required": "Obter uma chave de API requer um método de pagamento vinculado. Será debitado no cartão o valor de todas as taxas no começo do mês.",
"api_failure": "Erros 500 não contam como uso, já que isso significa que nós que erramos!",
"api_error": "Houve um erro com a solicitação. Por favor, tente novamente. Se continuar, contate-nos em support@opendota.com.",
"api_login": "Login para acessar a chave de API",
"api_update_billing": "Atualizar método de pagamento",
"api_delete": "Apagar chave",
"api_key_usage": "Para usar sua chave, adicione $param como um parâmetro de consulta à sua solicitação de API:",
"api_billing_cycle": "O ciclo de cobrança atual termina em $date.",
"api_billed_to": "Nós vamos cobrar automaticamente o cartão $brand terminado em $last4.",
"api_support": "Precisa de suporte? Email $email.",
"api_header_usage": "Uso",
"api_usage_calls": "# Chamadas de API",
"api_usage_fees": "Taxa estimada",
"api_month": "Mês",
"api_header_key": "Sua chave",
"api_header_table": "Comece grátis! E incremente por um preço muito baixo.",
"app_name": "OpenDota",
"app_language": "Idioma",
"app_localization": "Localização",
"app_description": "Plataforma de código aberto para Dota 2",
"app_about": "Sobre",
"app_privacy_terms": "Termos de uso & Privacidade",
"app_api_docs": "Documentos da API",
"app_blog": "Blog",
"app_translate": "Traduzir",
"app_donate": "Doar",
"app_gravitech": "Site do Grupo Gravitech LLC",
"app_powered_by": "mantido através de",
"app_donation_goal": "Meta de Doação Mensal",
"app_sponsorship": "Seu patrocínio ajuda a manter o serviço grátis para todos.",
"app_twitter": "Siga no Twitter",
"app_github": "Código fonte no GitHub",
"app_discord": "Chat no Discord",
"app_steam_profile": "Perfil Steam",
"app_confirmed_as": "Confirmado como",
"app_untracked": "O usuário não visitou o site recentemente, os replay de novas partidas não serão analisados automaticamente.",
"app_tracked": "Esse usuário visitou o site recentemente, os replays de novas partidas serão analizados automáticamente.",
"app_cheese_bought": "Queijo comprado",
"app_contributor": "Este usuário contribui para o desenvolvimento do projeto OpenDota",
"app_dotacoach": "Pergunte a um treinador",
"app_pvgna": "Encontre um guia",
"app_pvgna_alt": "Encontre um guia de Dota 2 na Pvgna",
"app_rivalry": "Apostar em partidas profissionais",
"app_rivalry_team": "Apostar em {0} partidas",
"app_refresh": "Atualizar o Histórico de Partidas: Agendar uma varredura para encontrar as partidas que faltam devido às configurações de privacidade",
"app_refresh_label": "Atualizar",
"app_login": "Entrar",
"app_logout": "Sair",
"app_results": "resultado(s)",
"app_report_bug": "Reportar Erro",
"app_pro_players": "Jogadores Profissionais",
"app_public_players": "Jogadores Públicos",
"app_my_profile": "Meu perfil",
"barracks_value_1": "Barraca de baixo dos guerreiros dos Temidos",
"barracks_value_2": "Barraca de baixo dos magos do Temidos",
"barracks_value_4": "Barraca do meio dos guerreiros dos temidos",
"barracks_value_8": "Barraca do meio dos magos dos Temidos",
"barracks_value_16": "Barraca de cima dos guerreiros dos Temidos",
"barracks_value_32": "Barraca de cima dos guerreiros dos Temidos",
"barracks_value_64": "Barraca de baixo dos guerreiros dos Iluminados",
"barracks_value_128": "Barraca de baixo dos magos dos Iluminados",
"barracks_value_256": "Barraca do meio dos guerreiros dos Iluminados",
"barracks_value_512": "Barraca de baixo dos magos dos Iluminados",
"barracks_value_1024": "Barraca de cima dos guerreiros dos Iluminados",
"barracks_value_2048": "Barraca de cima dos magos dos Iluminados",
"benchmarks_description": "{0} {1} é igual ou maior que {2}% das performances recentes neste herói",
"fantasy_description": "{0} para {1} pontos",
"building_melee_rax": "Barraca dos Guerreiros",
"building_range_rax": "Barraca dos magos",
"building_lasthit": "deu o último golpe",
"building_damage": "dano recebido",
"building_hint": "Os ícones no mapa possuem legenda",
"building_denied": "negado",
"building_ancient": "Ancestral",
"CHAT_MESSAGE_TOWER_KILL": "Torre",
"CHAT_MESSAGE_BARRACKS_KILL": "Barracas",
"CHAT_MESSAGE_ROSHAN_KILL": "Roshan",
"CHAT_MESSAGE_AEGIS": "Pegou aegis",
"CHAT_MESSAGE_FIRSTBLOOD": "Primeira vítima",
"CHAT_MESSAGE_TOWER_DENY": "Torre negada",
"CHAT_MESSAGE_AEGIS_STOLEN": "Roubou o aegis",
"CHAT_MESSAGE_DENIED_AEGIS": "Negou o aegis",
"distributions_heading_ranks": "Distribuição do Ranking",
"distributions_heading_mmr": "Distribuição de MMR Individual",
"distributions_heading_country_mmr": "Média de MMR Individual por País",
"distributions_tab_ranks": "Níveis de Rank",
"distributions_tab_mmr": "MMR Individual",
"distributions_tab_country_mmr": "MMR Individual por País",
"distributions_warning_1": "Este tipo de analise é limitada a jogadores exibindo o MMR no perfil e com o compartilhamento de dados de partidas públicas ativado.",
"distributions_warning_2": "Jogadores não precisam registrar-se, mas devido a natureza dos dados coletados, as médias são maiores do que o esperado.",
"error": "Erro",
"error_message": "Ops! Algo deu errado.",
"error_four_oh_four_message": "A página que você está procurando não pode ser encontrada.",
"explorer_title": "Explorador de Dados",
"explorer_subtitle": "Estatísticas dos Profissionais",
"explorer_description": "Executar consulta avançada em partidas profissionais (exclui ligas amadoras)",
"explorer_schema": "Esquema",
"explorer_results": "Resultados",
"explorer_num_rows": "linha(s)",
"explorer_select": "Selecione",
"explorer_group_by": "Agrupar Por",
"explorer_hero": "Herói",
"explorer_patch": "Versão",
"explorer_min_patch": "Versão Mínima",
"explorer_max_patch": "Versão Máxima",
"explorer_min_mmr": "MMR Mínimo",
"explorer_max_mmr": "MMR Máximo",
"explorer_min_rank_tier": "Rank Mínimo",
"explorer_max_rank_tier": "Rank Máximo",
"explorer_player": "Jogador",
"explorer_league": "Liga",
"explorer_player_purchased": "Jogador Comprou",
"explorer_duration": "Duração",
"explorer_min_duration": "Duração Mínima",
"explorer_max_duration": "Duração Máxima",
"explorer_timing": "Tempo",
"explorer_uses": "Usos",
"explorer_kill": "Tempo da morte",
"explorer_side": "Facção",
"explorer_toggle_sql": "Alternar SQL",
"explorer_team": "Equipe atual",
"explorer_lane_role": "Trilha",
"explorer_min_date": "Data Min",
"explorer_max_date": "Data Max",
"explorer_hero_combos": "Combo de Heróis",
"explorer_hero_player": "Herói-Jogador",
"explorer_player_player": "Jogador-Jogador",
"explorer_sql": "SQL",
"explorer_postgresql_function": "Função de PostgreSQL",
"explorer_table": "Tabela",
"explorer_column": "Coluna",
"explorer_query_button": "Tabela",
"explorer_cancel_button": "Cancelar",
"explorer_table_button": "Tabela",
"explorer_api_button": "API",
"explorer_json_button": "JSON",
"explorer_csv_button": "CSV",
"explorer_donut_button": "Rosquinha",
"explorer_bar_button": "Barra",
"explorer_timeseries_button": "Séries",
"explorer_chart_unavailable": "Gráfico não disponível, tente adicionar um GRUPO",
"explorer_value": "Valor",
"explorer_category": "Categoria",
"explorer_region": "Região",
"explorer_picks_bans": "Escolhas/Bans",
"explorer_counter_picks_bans": "Contra-escolhas/bans",
"explorer_organization": "Organização",
"explorer_order": "Ordenar",
"explorer_asc": "Crescente",
"explorer_desc": "Decrescente",
"explorer_tier": "Nível",
"explorer_having": "Pelo Menos Essas Partidas",
"explorer_limit": "Limite",
"explorer_match": "Partida",
"explorer_is_ti_team": "Time do TI{number}",
"explorer_mega_comeback": "Venceu contra Mega Criaturas",
"explorer_max_gold_adv": "Vantagem Máxima de Ouro",
"explorer_min_gold_adv": "Vantagem Mínima de Ouro",
"farm_heroes": "Heróis mortos",
"farm_creeps": "Creeps das lanes mortos",
"farm_neutrals": "Creeps neutros mortos (incluindo Anciões)",
"farm_ancients": "Creeps Anciões mortos",
"farm_towers": "Torres Destruidas",
"farm_couriers": "Entregadores mortos",
"farm_observers": "Sentinela Observadora Destruidas",
"farm_sentries": "Sentinelas reveladora destruídas",
"farm_roshan": "Roshans mortos",
"farm_necronomicon": "Unidades do Necronomicon destruidas",
"filter_button_text_open": "Filtro",
"filter_button_text_close": "Fechar",
"filter_hero_id": "Herói",
"filter_is_radiant": "Facção",
"filter_win": "Resultado",
"filter_lane_role": "Lane",
"filter_patch": "Versão",
"filter_game_mode": "Modo de jogo",
"filter_lobby_type": "Tipo de sala",
"filter_date": "Data",
"filter_region": "Região",
"filter_with_hero_id": "Heróis Aliados",
"filter_against_hero_id": "Heróis Adversários",
"filter_included_account_id": "Contas incluídas",
"filter_excluded_account_id": "Contas excluídas",
"filter_significant": "Insignificante",
"filter_significant_include": "Incluir",
"filter_last_week": "Última semana",
"filter_last_month": "Último mês",
"filter_last_3_months": "Últimos 3 meses",
"filter_last_6_months": "Últimos 6 meses",
"filter_error": "Selecione um item no menu suspenso",
"filter_party_size": "Tamanho da equipe",
"game_mode_0": "Desconhecido",
"game_mode_1": "Escolha livre",
"game_mode_2": "Modo de capitães",
"game_mode_3": "Seleção Aleatória",
"game_mode_4": "Seleção Individual",
"game_mode_5": "Todos aleatórios",
"game_mode_6": "Introdução",
"game_mode_7": "Diretide",
"game_mode_8": "Modo de Capitães Inverso",
"game_mode_9": "O Greeviling",
"game_mode_10": "Tutorial",
"game_mode_11": "Somente linha do meio",
"game_mode_12": "Menos jogados",
"game_mode_13": "Heróis Limitados",
"game_mode_14": "Compêndio",
"game_mode_15": "Personalizado",
"game_mode_16": "Seleção de Capitães",
"game_mode_17": "Escolha Balanceada",
"game_mode_18": "Seleção de Habilidades",
"game_mode_19": "Evento",
"game_mode_20": "Mata-mata aleatório",
"game_mode_21": "1v1 Solo no Meio",
"game_mode_22": "Escolha Livre",
"game_mode_23": "Turbo",
"game_mode_24": "Mutação",
"general_unknown": "Desconhecido",
"general_no_hero": "Sem herói",
"general_anonymous": "Anônimo",
"general_radiant": "Iluminados",
"general_dire": "Temidos",
"general_standard_deviation": "Desvio Padrão",
"general_matches": "Partidas",
"general_league": "Liga",
"general_randomed": "Selecionou aleatoriamente",
"general_repicked": "Reescolheu",
"general_predicted_victory": "Vitória Prevista",
"general_show": "Exibir",
"general_hide": "Ocultar",
"gold_reasons_0": "Outro",
"gold_reasons_1": "Morte(s)",
"gold_reasons_2": "Buyback",
"NULL_gold_reasons_5": "Abandono",
"NULL_gold_reasons_6": "Venda",
"gold_reasons_11": "Estrutura",
"gold_reasons_12": "Herói",
"gold_reasons_13": "Creep",
"gold_reasons_14": "Roshan",
"NULL_gold_reasons_15": "Entregador",
"header_request": "Solicitar",
"header_distributions": "Ranks",
"header_heroes": "Heróis",
"header_blog": "Blog",
"header_ingame": "Em Jogo",
"header_matches": "Partidas",
"header_records": "Recordes",
"header_explorer": "Navegador",
"header_teams": "Equipes",
"header_meta": "Meta",
"header_scenarios": "Cenários",
"header_api": "API",
"heading_lhten": "Últimos Golpes @ 10",
"heading_lhtwenty": "Últimos Golpes @ 20",
"heading_lhthirty": "Últimos Golpes @ 30",
"heading_lhforty": "Últimos Golpes @ 40",
"heading_lhfifty": "Últimos Golpes @ 50",
"heading_courier": "Entregador",
"heading_roshan": "Roshan",
"heading_tower": "Torre",
"heading_barracks": "Barracas",
"heading_shrine": "Santuário",
"heading_item_purchased": "Item Comprado",
"heading_ability_used": "Habilidade Usada",
"heading_item_used": "Item Usado",
"heading_damage_inflictor": "Dano infligido",
"heading_damage_inflictor_received": "Dano recebido",
"heading_damage_instances": "Instâncias de Danos",
"heading_camps_stacked": "Campos acumulados",
"heading_matches": "Partidas Recentes",
"heading_heroes": "Heróis jogados",
"heading_mmr": "Histórico de MMR",
"heading_peers": "Jogadores com quem jogou",
"heading_pros": "Jogadores profissionais com quem já jogou",
"heading_rankings": "Ranking de Heróis",
"heading_all_matches": "Todas as partidas",
"heading_parsed_matches": "Partidas analisadas",
"heading_records": "Recordes",
"heading_teamfights": "Teamfights",
"heading_graph_difference": "Vantagem dos Iluminados",
"heading_graph_gold": "Ouro",
"heading_graph_xp": "Experiência",
"heading_graph_lh": "Finalizações",
"heading_overview": "Geral",
"heading_ability_draft": "Seleção de Habilidades",
"heading_buildings": "Mapa das estruturas",
"heading_benchmarks": "Referência",
"heading_laning": "Laning",
"heading_overall": "Total",
"heading_kills": "Abates",
"heading_deaths": "Mortes",
"heading_assists": "Assistências",
"heading_damage": "Dano",
"heading_unit_kills": "Unidades Mortas",
"heading_last_hits": "Finalizações",
"heading_gold_reasons": "Fontes de Ouro",
"heading_xp_reasons": "Fontes de Experiência",
"heading_performances": "Desempenhos",
"heading_support": "Suporte",
"heading_purchase_log": "Histórico de Compras",
"heading_casts": "Casts",
"heading_objective_damage": "Dano a Estruturas",
"heading_runes": "Runas",
"heading_vision": "Visão",
"heading_actions": "Ações",
"heading_analysis": "Análise",
"heading_cosmetics": "Cosméticos",
"heading_log": "Log",
"heading_chat": "Conversa",
"heading_story": "História",
"heading_fantasy": "Pontuação",
"heading_wardmap": "Wardmap",
"heading_wordcloud": "Wordcloud",
"heading_wordcloud_said": "Palavras ditas (Chat p/ todos)",
"heading_wordcloud_read": "Palavras lidas (Chat p/ todos)",
"heading_kda": "KMA",
"heading_gold_per_min": "Ouro por Min",
"heading_xp_per_min": "Exp por min",
"heading_denies": "Negados",
"heading_lane_efficiency_pct": "EFI@10",
"heading_duration": "Duração",
"heading_level": "Nível",
"heading_hero_damage": "Dano à Heróis",
"heading_tower_damage": "Dano à torres",
"heading_hero_healing": "Cura causada por herói",
"heading_tower_kills": "Finalizações de Torres",
"heading_stuns": "Atordoamentos",
"heading_neutral_kills": "Criaturas Neutras Mortas",
"heading_courier_kills": "Entregadores mortos",
"heading_purchase_tpscroll": "Pergaminho de Teleporte Comprados",
"heading_purchase_ward_observer": "Sentinelas Observadoras Compradas",
"heading_purchase_ward_sentry": "Sentinelas Reveladoras compradas",
"heading_purchase_gem": "Gemas Compradas",
"heading_purchase_rapier": "Rapieiras Divinas Compradas",
"heading_pings": "Alertas no Mapa",
"heading_throw": "Throw",
"heading_comeback": "Virada",
"heading_stomp": "Massacre",
"heading_loss": "Derrota",
"heading_actions_per_min": "Ações por Minuto",
"heading_leaver_status": "Status de Abandono",
"heading_game_mode": "Modo de jogo",
"heading_lobby_type": "Tipo de sala",
"heading_lane_role": "Posição na Linha",
"heading_region": "Região",
"heading_patch": "Versão",
"heading_win_rate": "% Vitórias",
"heading_is_radiant": "Facção",
"heading_avg_and_max": "Médias/Melhores",
"heading_total_matches": "Todas as partidas",
"heading_median": "Mediana",
"heading_distinct_heroes": "Heróis distintos",
"heading_team_elo_rankings": "Ranking de Equipes",
"heading_ability_build": "Construção de habilidades",
"heading_attack": "Ataque Base",
"heading_attack_range": "Alcance de ataque",
"heading_attack_speed": "Velocidade de ataque",
"heading_projectile_speed": "Velocidade do projétil",
"heading_base_health": "Vida",
"heading_base_health_regen": "Regeneração de vida",
"heading_base_mana": "Mana",
"heading_base_mana_regen": "Regeneração de mana",
"heading_base_armor": "Armadura base",
"heading_base_mr": "Resistência mágica",
"heading_move_speed": "Velocidade de movimento",
"heading_turn_rate": "Velocidade de giro",
"heading_legs": "Número de pernas",
"heading_cm_enabled": "CM ativado",
"heading_current_players": "Jogadores atuais",
"heading_former_players": "Ex-jogadores",
"heading_damage_dealt": "Dano Causado",
"heading_damage_received": "Dano Sofrido",
"show_details": "Exibir detalhes",
"hide_details": "Ocultar detalhes",
"subheading_avg_and_max": "na(s) última(s) {0} partida(s) exibida(s)",
"subheading_records": "Em partidas ranqueadas. Recordes reiniciam mensalmente.",
"subheading_team_elo_rankings": "k = 32, init = 1000",
"hero_pro_tab": "Profissional",
"hero_public_tab": "Público",
"hero_pro_heading": "Heróis em partidas profissionais",
"hero_public_heading": "Heróis em Partidas Públicas (Amostras)",
"hero_this_month": "partidas nos últimos 30 dias",
"hero_pick_ban_rate": "Pro P+B%",
"hero_pick_rate": "Pro Pick%",
"hero_ban_rate": "Pro Ban%",
"hero_win_rate": "Pro Win%",
"hero_5000_pick_rate": "> 5K P%",
"hero_5000_win_rate": "> 5K W%",
"hero_4000_pick_rate": "4K P%",
"hero_4000_win_rate": "4K W%",
"hero_3000_pick_rate": "3K P%",
"hero_3000_win_rate": "3K W%",
"hero_2000_pick_rate": "2K P%",
"hero_2000_win_rate": "2K W%",
"hero_1000_pick_rate": "<2K P%",
"hero_1000_win_rate": "<2K P%",
"home_login": "Entrar",
"home_login_desc": "para análise de replay automática",
"home_parse": "Solicitar",
"home_parse_desc": "uma partida específica",
"home_why": "",
"home_opensource_title": "Código aberto",
"home_opensource_desc": "O código do projeto é inteiramente aberto e disponível para contribuidores melhorarem e modificarem.",
"home_indepth_title": "Dados Detalhados",
"home_indepth_desc": "Analisar arquivos de replay fornece dados mais detalhados da partida.",
"home_free_title": "Gratuito",
"home_free_desc": "Os servidores são financiados por patrocinadores e voluntários, então o serviço é oferecido gratuitamente.",
"home_background_by": "Imagem de fundo por",
"home_sponsored_by": "Patrocinado por",
"home_become_sponsor": "Seja um Patrocinador",
"items_name": "Nome do item",
"items_built": "Número de vezes que este item foi feito",
"items_matches": "Número de partidas em que este item foi feito",
"items_uses": "Número de vezes que este item foi utilizado",
"items_uses_per_match": "Média de número de vezes que este item foi utilizado em partidas",
"items_timing": "Tempo médio que este item foi feito",
"items_build_pct": "Porcentagem de partidas que este item foi feito",
"items_win_pct": "Porcentagem de partidas em que este item foi feito",
"lane_role_0": "Desconhecida",
"lane_role_1": "Linha Segura",
"lane_role_2": "Meio",
"lane_role_3": "Linha Difícil",
"lane_role_4": "Selva",
"lane_pos_1": "Trilha de baixo",
"lane_pos_2": "Trilha do meio",
"lane_pos_3": "Trilha de cima",
"lane_pos_4": "Selva dos Iluminados",
"lane_pos_5": "Selva dos Temidos",
"leaver_status_0": "Nenhum",
"leaver_status_1": "Desconsideradas",
"leaver_status_2": "Abandonou (DC)",
"leaver_status_3": "Abandonou",
"leaver_status_4": "Abandonou (AFK)",
"leaver_status_5": "Nunca Conectou",
"leaver_status_6": "Nunca Conectou (Timeout)",
"lobby_type_0": "Normal",
"lobby_type_1": "Prática",
"lobby_type_2": "Torneio",
"lobby_type_3": "Tutorial",
"lobby_type_4": "Cooperativo com Bots",
"lobby_type_5": "MM de Time Ranqueado (Legacy)",
"lobby_type_6": "MM Ranqueado Solo (Legacy)",
"lobby_type_7": "Competitiva",
"lobby_type_8": "1v1 Meio",
"lobby_type_9": "Copa de batalha",
"match_radiant_win": "Vitória dos Iluminados",
"match_dire_win": "Vitória dos Temidos",
"match_team_win": "Vitória",
"match_ended": "Finalizado",
"match_id": "ID da Partida",
"match_region": "Região",
"match_avg_mmr": "Média de MMR",
"match_button_parse": "Analisar",
"match_button_reparse": "Reanalisar",
"match_button_replay": "Replay",
"match_button_video": "Obter vídeo",
"match_first_tower": "Primeira torre",
"match_first_barracks": "Primeiro quartel",
"match_pick": "Pick",
"match_ban": "Ban",
"matches_highest_mmr": "Maiores MMRs Públicos",
"matches_lowest_mmr": "MMR Baixo",
"meta_title": "Meta",
"meta_description": "Executar consultas avançadas nos dados de jogos públicos das últimas 24h",
"mmr_not_up_to_date": "Por que o MMR não está atualizado?",
"npc_dota_beastmaster_boar_#": "Javali",
"npc_dota_lesser_eidolon": "Eidolon Pequeno",
"npc_dota_eidolon": "Eidolon",
"npc_dota_greater_eidolon": "Grande Eidolon",
"npc_dota_dire_eidolon": "Eidolon dos Temidos",
"npc_dota_invoker_forged_spirit": "Espíritos Forjados",
"npc_dota_furion_treant_large": "Treant Maior",
"npc_dota_beastmaster_hawk_#": "Águia",
"npc_dota_lycan_wolf#": "Lobos do Lycan",
"npc_dota_neutral_mud_golem_split_doom": "Fragmento do Doom",
"npc_dota_broodmother_spiderling": "Aranhinha",
"npc_dota_broodmother_spiderite": "Aranhazinha",
"npc_dota_furion_treant": "Treant",
"npc_dota_unit_undying_zombie": "Zumbi do Undying",
"npc_dota_unit_undying_zombie_torso": "Zumbi do Undying",
"npc_dota_brewmaster_earth_#": "Terra",
"npc_dota_brewmaster_fire_#": "Fogo",
"npc_dota_lone_druid_bear#": "Espirito Urso",
"npc_dota_brewmaster_storm_#": "Tempestade",
"npc_dota_visage_familiar#": "Familiares",
"npc_dota_warlock_golem_#": "Golem do Warlock",
"npc_dota_warlock_golem_scepter_#": "Golem do Warlock",
"npc_dota_witch_doctor_death_ward": "Sentinela da Morte",
"npc_dota_tusk_frozen_sigil#": "Signo Gélido",
"npc_dota_juggernaut_healing_ward": "Sentinela de Cura",
"npc_dota_techies_land_mine": "Mina de proximidade",
"npc_dota_shadow_shaman_ward_#": "Serpente Sentinela",
"npc_dota_pugna_nether_ward_#": "Sentinela Antimagia",
"npc_dota_venomancer_plague_ward_#": "Sentinela de Praga",
"npc_dota_rattletrap_cog": "Engrenagens Elétricas",
"npc_dota_templar_assassin_psionic_trap": "Armadilha Psiônica",
"npc_dota_techies_remote_mine": "Minas Remotas",
"npc_dota_techies_stasis_trap": "Armadilha Imobilizante",
"npc_dota_phoenix_sun": "Supernova",
"npc_dota_unit_tombstone#": "Lápide",
"npc_dota_treant_eyes": "Olhos na Floresta",
"npc_dota_gyrocopter_homing_missile": "Míssil Teleguiado",
"npc_dota_weaver_swarm": "O Enxame",
"objective_tower1_top": "T1",
"objective_tower1_mid": "M1",
"objective_tower1_bot": "B1",
"objective_tower2_top": "T2",
"objective_tower2_mid": "M2",
"objective_tower2_bot": "B2",
"objective_tower3_top": "T3",
"objective_tower3_mid": "M3",
"objective_tower3_bot": "B3",
"objective_rax_top": "Barraca Superior",
"objective_rax_mid": "Barraca Meio",
"objective_rax_bot": "Barraca Inferior",
"objective_tower4": "T4",
"objective_fort": "Ancião",
"objective_shrine": "Fonte",
"objective_roshan": "Roshan",
"tooltip_objective_tower1_top": "Dano causado à primeira torre da trilha de cima",
"tooltip_objective_tower1_mid": "Dano causado à primeira torre da trilha do meio",
"tooltip_objective_tower1_bot": "Dano causado à primeira torre da trilha de baixo",
"tooltip_objective_tower2_top": "Dano causado à segunda torre da trilha de cima",
"tooltip_objective_tower2_mid": "Dano causado à segunda torre da trilha do meio",
"tooltip_objective_tower2_bot": "Dano causado à segunda torre da trilha de baixo",
"tooltip_objective_tower3_top": "Dano causado à terceira torre da trilha de cima",
"tooltip_objective_tower3_mid": "Dano causado à terceira torre da trilha do meio",
"tooltip_objective_tower3_bot": "Dano causado à terceira torre da trilha de baixo",
"tooltip_objective_rax_top": "Dano causado aos quarteis da trilha de cima",
"tooltip_objective_rax_mid": "Dano causado aos quarteis da trilha do meio",
"tooltip_objective_rax_bot": "Dano causado aos quarteis da trilha de baixo",
"tooltip_objective_tower4": "Dano causado às torres do ancestral",
"tooltip_objective_fort": "Dano causado ao ancestral",
"tooltip_objective_shrine": "Dano causado aos santuários",
"tooltip_objective_roshan": "Dano causado ao Roshan",
"pagination_first": "Primeiro",
"pagination_last": "Última",
"pagination_of": "de",
"peers_none": "Esse jogador é um forever alone.",
"rank_tier_0": "Não-calibrado",
"rank_tier_1": "Arauto",
"rank_tier_2": "Guardião",
"rank_tier_3": "Cruzado",
"rank_tier_4": "Arconte",
"rank_tier_5": "Lenda",
"rank_tier_6": "Ancestral",
"rank_tier_7": "Divino",
"rank_tier_8": "Imortal",
"request_title": "Solicitar análise",
"request_match_id": "ID da partida",
"request_invalid_match_id": "ID de partida inválido",
"request_error": "Falha em obter dados da partida",
"request_submit": "Enviar",
"roaming": "Movimento contínuo",
"rune_0": "Dano Duplo",
"rune_1": "Ímpeto",
"rune_2": "Ilusão",
"rune_3": "Invisibilidade",
"rune_4": "Regeneração",
"rune_5": "Recompensa",
"rune_6": "Arcana",
"rune_7": "Água",
"search_title": "Pesquisar por nome de jogador, ID de partida...",
"skill_0": "Nível de habilidade desconhecido",
"skill_1": "Habilidade normal",
"skill_2": "Habilidade alta",
"skill_3": "Habilidade muito alta",
"story_invalid_template": "(Modelo inválido)",
"story_error": "Ocorreu um erro ao tentar formular a história dessa partida",
"story_intro": "em {date}, as duas equipes decidiram jogar {game_mode_article} {game_mode} a partida de Dota 2 na {region}. Porém, eles não sabiam que o jogo iria durar {duration_in_words}",
"story_invalid_hero": "Herói não reconhecido",
"story_fullstop": ".",
"story_list_2": "{1} e {2}",
"story_list_3": "{1}, {2} e {3}",
"story_list_n": "{i}, {rest}",
"story_firstblood": "primeira eliminação feita quando {killer} matou {victim} aos {time} de jogo",
"story_chatmessage": "\"{message}\", {player} {said_verb}",
"story_teamfight": "{winning_team} ganhou um batalha ao trocar {win_dead} por {lose_dead}, resultando em um aumento de {net_change} no patrimônio líquido",
"story_teamfight_none_dead": "{winning_team} venceu a batalha ao matar {lose_dead} sem perder qualquer herói, resultando num aumento de patrimônio líquido de {net_change}",
"story_teamfight_none_dead_loss": "{winning_team} de alguma for venceu a teamfight, sem matar nenhum herói, perdendo {win_dead}, resultando no ganho de {net_change} ouro",
"story_lane_intro": "Aos 10 minutos de jogo, as lanes ficaram da seguinte forma:",
"story_lane_radiant_win": "{radiant_players} venceram na {lane} contra {dire_players}",
"story_lane_radiant_lose": "{radiant_players} perderam na {lane} contra {dire_players}",
"story_lane_draw": "{radiant_players} empataram na {lane} com {dire_players}",
"story_lane_free": "{players} ficaram livres na {lane}",
"story_lane_empty": "não tinha ninguém na {lane}",
"story_lane_jungle": "{players} farmaram na floresta",
"story_lane_roam": "{players} rotacionaram",
"story_roshan": "{team} matou Roshan",
"story_aegis": "{player} {action} o aegis",
"story_gameover": "A partida acabou com vitória dos {winning_team} após {duration} com um placar de {radiant_score} x {dire_score}",
"story_during_teamfight": "durante a luta, {events}",
"story_after_teamfight": "após a luta, {events}",
"story_expensive_item": "aos {time}, {player} comprou {item}, sendo esse o primeiro item na partida com preço maior que {price_limit}",
"story_building_destroy": "{building} foi destruída",
"story_building_destroy_player": "{player} destruiu {building}",
"story_building_deny_player": "{player} negou {building}",
"story_building_list_destroy": "{buildings} foram destruídas",
"story_courier_kill": "courier dos {team} foi morto",
"story_tower": "Torre {tier} da {lane} dos {team}",
"story_tower_simple": "uma das torres dos {team}",
"story_towers_n": "{n} das torres dos {team}",
"story_barracks": "{rax_type} {lane} dos {team}",
"story_barracks_both": "as duas barracas do {lane} dos {team}",
"story_time_marker": "Aos {minutes} minutos",
"story_item_purchase": "aos {time}, {player} comprou {item}",
"story_predicted_victory": "{players} previu(ram) que {team} iria ganhar",
"story_predicted_victory_empty": "Ninguém",
"story_networth_diff": "Vantagem: {percent}% / Diferença de ouro: {gold}",
"story_gold": "ouro",
"story_chat_asked": "perguntou",
"story_chat_said": "disse",
"tab_overview": "Geral",
"tab_matches": "Partidas",
"tab_heroes": "Heróis",
"tab_peers": "Parceiros",
"tab_pros": "Profissionais",
"tab_activity": "Atividade",
"tab_records": "Recordes",
"tab_totals": "Totais",
"tab_counts": "Contagens",
"tab_histograms": "Histogramas",
"tab_trends": "Tendências",
"tab_items": "Itens",
"tab_wardmap": "Pontos de Wards",
"tab_wordcloud": "Nuvem de Palavras",
"tab_mmr": "MMR",
"tab_rankings": "Classificações",
"tab_drafts": "Escolhas",
"tab_benchmarks": "Referências",
"tab_performances": "Desempenhos",
"tab_damage": "Dano",
"tab_purchases": "Compras",
"tab_farm": "Finalizações",
"tab_combat": "Combate",
"tab_graphs": "Gráficos",
"tab_casts": "Uso de magias",
"tab_vision": "Visão",
"tab_objectives": "Objetivos",
"tab_teamfights": "Combates em grupo",
"tab_actions": "Ações",
"tab_analysis": "Análise",
"tab_cosmetics": "Cosméticos",
"tab_log": "Registro",
"tab_chat": "Conversa",
"tab_story": "História",
"tab_fantasy": "Pontuação",
"tab_laning": "Fase de trilhas",
"tab_recent": "Recente",
"tab_matchups": "Combinações",
"tab_durations": "Durações",
"tab_players": "Jogadores",
"placeholder_filter_heroes": "Filtrar Heróis",
"td_win": "Venceu a partida",
"td_loss": "Perdeu a partida",
"td_no_result": "Nenhum resultado",
"th_hero_id": "Herói",
"th_match_id": "ID",
"th_account_id": "ID da conta",
"th_result": "Resultado",
"th_skill": "Habilidade",
"th_duration": "Duração",
"th_games": "MP",
"th_games_played": "Jogos",
"th_win": "% de Vitórias",
"th_advantage": "Vantagem",
"th_with_games": "Com",
"th_with_win": "% de vitórias com",
"th_against_games": "Contra",
"th_against_win": "% de vitórias contra",
"th_gpm_with": "OPM com",
"th_xpm_with": "EXPM com",
"th_avatar": "Jogador",
"th_last_played": "Última",
"th_record": "Recorde",
"th_title": "Título",
"th_category": "Categoria",
"th_matches": "Partidas",
"th_percentile": "Percentagem",
"th_rank": "Colocação",
"th_items": "Itens",
"th_stacked": "Acumulado",
"th_multikill": "Multikill",
"th_killstreak": "Sequência de Assasinatos",
"th_stuns": "Atordoamentos",
"th_dead": "Morto",
"th_buybacks": "Recompras",
"th_biggest_hit": "Maior hit",
"th_lane": "Trilha",
"th_map": "Mapa",
"th_lane_efficiency": "EFI@10",
"th_lhten": "FN@10",
"th_dnten": "N@10",
"th_tpscroll": "TP",
"th_ward_observer": "Sentinela Observadora",
"th_ward_sentry": "Sentinela Reveladora",
"th_smoke_of_deceit": "Smoke",
"th_dust": "Dust",
"th_gem": "Gema",
"th_time": "Tempo",
"th_message": "Mensagem",
"th_heroes": "Heróis",
"th_creeps": "Creeps",
"th_neutrals": "Neutrals",
"th_ancients": "Ancients",
"th_towers": "Torres",
"th_couriers": "Entregadores",
"th_roshan": "Roshan",
"th_necronomicon": "Necronomicon",
"th_other": "Outro",
"th_cosmetics": "Cosméticos",
"th_damage_received": "Recebido",
"th_damage_dealt": "Aflingido",
"th_players": "Jogadores",
"th_analysis": "Análise",
"th_death": "Morte",
"th_damage": "Dano",
"th_healing": "Cura",
"th_gold": "O",
"th_xp": "Exp",
"th_abilities": "Habilidades",
"th_target_abilities": "Habilidades com alvos",
"th_mmr": "MMR",
"th_level": "LVL",
"th_kills": "K",
"th_kills_per_min": "KPM",
"th_deaths": "M",
"th_assists": "A",
"th_last_hits": "FN",
"th_last_hits_per_min": "FNM",
"th_denies": "N",
"th_gold_per_min": "OPM",
"th_xp_per_min": "XPM",
"th_stuns_per_min": "SPM",
"th_hero_damage": "DH",
"th_hero_damage_per_min": "DHM",
"th_hero_healing": "CH",
"th_hero_healing_per_min": "CHM",
"th_tower_damage": "DT",
"th_tower_damage_per_min": "DTM",
"th_kda": "KMA",
"th_actions_per_min": "APM",
"th_pings": "PNG(M)",
"th_DOTA_UNIT_ORDER_MOVE_TO_POSITION": "MV(P)",
"th_DOTA_UNIT_ORDER_MOVE_TO_TARGET": "MV(A)",
"th_DOTA_UNIT_ORDER_ATTACK_TARGET": "ATK(A)",
"th_DOTA_UNIT_ORDER_ATTACK_MOVE": "ATQ(P)",
"th_DOTA_UNIT_ORDER_CAST_POSITION": "CST(P)",
"th_DOTA_UNIT_ORDER_CAST_TARGET": "CST(A)",
"th_DOTA_UNIT_ORDER_CAST_NO_TARGET": "CST(SA)",
"th_DOTA_UNIT_ORDER_HOLD_POSITION": "PM",
"th_DOTA_UNIT_ORDER_GLYPH": "GLIFO",
"th_DOTA_UNIT_ORDER_RADAR": "SCN",
"th_ability_builds": "PH",
"th_purchase_shorthand": "COMPRAS",
"th_use_shorthand": "USOS",
"th_duration_shorthand": "Tempo",
"th_country": "País",
"th_count": "Contagem",
"th_sum": "Soma",
"th_average": "Média",
"th_name": "Nome",
"th_team_name": "Nome da Equipe",
"th_score": "Pontuação",
"th_casts": "Casts",
"th_hits": "Golpes",
"th_wins": "Vitórias",
"th_losses": "Derrotas",
"th_winrate": "Taxa de Vitórias",
"th_solo_mmr": "MMR Individual",
"th_party_mmr": "MMR em Grupo",
"th_estimated_mmr": "MMR Estimado",
"th_permanent_buffs": "Buffs",
"th_winner": "Vencedor",
"th_played_with": "Minhas partidas com este jogador",
"th_obs_placed": "Sentinelas Observadoras Colocadas",
"th_sen_placed": "Sentinelas Reveladoras Colocadas",
"th_obs_destroyed": "Sentinelas Observadoras destruidas",
"th_sen_destroyed": "Sentinelas Reveladoras destruídas",
"th_scans_used": "Escaneamentos Utilizados",
"th_glyphs_used": "Glifos Utilizados",
"th_legs": "Pernas",
"th_fantasy_points": "Cartola (Versão Dota)",
"th_rating": "Avaliação",
"th_teamfight_participation": "Participação",
"th_firstblood_claimed": "Primeiro abate",
"th_observers_placed": "Sentinelas Observadoras",
"th_camps_stacked": "Acúmulos",
"th_league": "Liga",
"th_attack_type": "Tipo de ataque",
"th_primary_attr": "Atributo Primário",
"th_opposing_team": "Equipe adversária",
"ward_log_type": "Tipo",
"ward_log_owner": "Dono",
"ward_log_entered_at": "Colocado",
"ward_log_left_at": "Acabou",
"ward_log_duration": "Duração",
"ward_log_killed_by": "Destruída por",
"log_detail": "Detalhes",
"log_heroes": "Especifique os heróis",
"tier_professional": "Profissional",
"tier_premium": "Premium",
"time_past": "{0} atrás",
"time_just_now": "neste momento",
"time_s": "um segundo",
"time_abbr_s": "{0}s",
"time_ss": "{0} segundos",
"time_abbr_ss": "{0}s",
"time_m": "um minuto",
"time_abbr_m": "{0}m",
"time_mm": "{0} minutos",
"time_abbr_mm": "{0}m",
"time_h": "uma hora",
"time_abbr_h": "{0}h",
"time_hh": "{0} horas",
"time_abbr_hh": "{0}h",
"time_d": "um dia",
"time_abbr_d": "{0}dia",
"time_dd": "{0} dias",
"time_abbr_dd": "{0}dias",
"time_M": "um mês",
"time_abbr_M": "{0}mês",
"time_MM": "{0} meses",
"time_abbr_MM": "{0}meses",
"time_y": "um ano",
"time_abbr_y": "{0}ano",
"time_yy": "{0} anos",
"time_abbr_yy": "{0}anos",
"timeline_firstblood": "deu o first blood",
"timeline_firstblood_key": "deu o first blood matando",
"timeline_aegis_picked_up": "pegou",
"timeline_aegis_snatched": "roubado",
"timeline_aegis_denied": "negado",
"timeline_teamfight_deaths": "Mortes",
"timeline_teamfight_gold_delta": "variação de ouro",
"title_default": "OpenDota - Estatísticas de Dota 2",
"title_template": "%s - OpenDota - Estatísticas de Dota 2",
"title_matches": "Partidas",
"title_request": "Solicitar análise completa",
"title_search": "Buscar",
"title_status": "Status",
"title_explorer": "Explorador de Dados",
"title_meta": "Meta",
"title_records": "Recordes",
"title_api": "Opendota API: Estatísticas avançadas de Dota 2 stats para seu app",
"tooltip_mmr": "MMR Individual do jogador",
"tooltip_abilitydraft": "Seleção de Habilidades",
"tooltip_level": "Nível alcançado pelo herói",
"tooltip_kills": "Número de abates por herói",
"tooltip_deaths": "Número de mortes por herói",
"tooltip_assists": "Número de assistências por herói",
"tooltip_last_hits": "Número de finalizações por herói",
"tooltip_denies": "Número de creeps negados",
"tooltip_gold": "Total de ouro obtido",
"tooltip_gold_per_min": "Ouro obtido por minuto",
"tooltip_xp_per_min": "Experiência obtida por minuto",
"tooltip_stuns_per_min": "Segundos de inimigos atordoados por minuto",
"tooltip_last_hits_per_min": "Finalizações por minuto",
"tooltip_kills_per_min": "Abates por minuto",
"tooltip_hero_damage_per_min": "Dano a heróis por minuto",
"tooltip_hero_healing_per_min": "Cura do Herói por Minuto",
"tooltip_tower_damage_per_min": "Dano a torres por minuto",
"tooltip_actions_per_min": "Ações executadas por minuto",
"tooltip_hero_damage": "Quantidade de dano causado a heróis",
"tooltip_tower_damage": "Quantidade de dano a torres",
"tooltip_hero_healing": "Quantidade de vida regenerada em heróis",
"tooltip_duration": "A duração da partida",
"tooltip_first_blood_time": "Tempo em que o primeiro abate aconteceu",
"tooltip_kda": "(Abates + Assistências) / (Mortes + 1)",
"tooltip_stuns": "Segundos de desativação em heróis",
"tooltip_dead": "Tempo morto",
"tooltip_buybacks": "Número de recompras",
"tooltip_camps_stacked": "Campos acumulados",
"tooltip_tower_kills": "Número de torres destruídas",
"tooltip_neutral_kills": "Número de neutral creeps mortos",
"tooltip_courier_kills": "Número de couriers mortos",
"tooltip_purchase_tpscroll": "Pergaminhos de Teletransporte comprados",
"tooltip_purchase_ward_observer": "Sentinelas Observadoras compradas",
"tooltip_purchase_ward_sentry": "Sentinelas Reveladoras compradas",
"tooltip_purchase_smoke_of_deceit": "Fumaças da Enganação compradas",
"tooltip_purchase_dust": "Areias da Revelação compradas",
"tooltip_purchase_gem": "Gemas da Visão Verdadeira compradas",
"tooltip_purchase_rapier": "Rapieiras Divinas compradas",
"tooltip_purchase_buyback": "Buybacks comprados",
"tooltip_duration_observer": "Duração média das sentinelas observadoras",
"tooltip_duration_sentry": "Duração média das Sentinelas Reveladoras",
"tooltip_used_ward_observer": "Número de Sentinelas Observadoras colocadas durante o jogo",
"tooltip_used_ward_sentry": "Número de Sentinelas Reveladoras colocadas durante o jogo",
"tooltip_used_dust": "Quantidade de Areias da Revelação utilizadas",
"tooltip_used_smoke_of_deceit": "Quantidade de Fumaças da Enganação utilizadas durante a partida",
"tooltip_parsed": "Replay analisado para obtenção de dados adicionais",
"tooltip_unparsed": "O replay para esta partida ainda não foi analisado. Nem todos os dados podem estar disponíveis.",
"tooltip_hero_id": "Herói jogado",
"tooltip_result": "Se o jogador ganhou ou perdeu",
"tooltip_match_id": "O ID da partida",
"tooltip_game_mode": "O modo de jogo da partida",
"tooltip_skill": "O MMR inicial aproximado de cada nível de habilidade é aproximadamente 0 (normal), 3200 (alta) e 3700 (muito alta)",
"tooltip_ended": "O tempo que a partida terminou",
"tooltip_pick_order": "Ordem em que o jogador escolheu",
"tooltip_throw": "Maior vantagem de ouro em uma partida perdida",
"tooltip_comeback": "Maior desvantagem de ouro em uma partida ganha",
"tooltip_stomp": "Maior vantagem de ouro em uma partida ganha",
"tooltip_loss": "Maior desvantagem de ouro em uma partida perdida",
"tooltip_items": "Itens",
"tooltip_permanent_buffs": "Melhorias permanentes como acúmulos na Armadura de Carne (Pudge) ou Tomos da sabedoria utilizados",
"tooltip_lane": "Lane, com base no early game do jogo",
"tooltip_map": "Mapa do posicionamento do jogador nos primeiros 10 minutos",
"tooltip_lane_efficiency": "Porcentagem de gold na lane (Creeps+Passivo+Inicial) obtido nos 10 minutos",
"tooltip_lane_efficiency_pct": "Porcentagem de gold na lane (Creeps+Passivo+Inicial) obtido nos 10 minutos",
"tooltip_pings": "Número de vezes que o jogador usou o ping no mapa",
"tooltip_DOTA_UNIT_ORDER_MOVE_TO_POSITION": "Número de vezes que o jogador moveu-se para uma posição",
"tooltip_DOTA_UNIT_ORDER_MOVE_TO_TARGET": "Número de vezes que o jogador moveu-se para um alvo",
"tooltip_DOTA_UNIT_ORDER_ATTACK_MOVE": "Número de vezes que o jogador atacou uma posição (mover e atacar)",
"tooltip_DOTA_UNIT_ORDER_ATTACK_TARGET": "Número de vezes que o jogador atacou um alvo",
"tooltip_DOTA_UNIT_ORDER_CAST_POSITION": "Número de vezes que o jogador lançou uma magia/item em uma posição",
"tooltip_DOTA_UNIT_ORDER_CAST_TARGET": "Número de vezes que o jogador lançou uma magia/item em um alvo",
"tooltip_DOTA_UNIT_ORDER_CAST_NO_TARGET": "Número de vezes que o jogador lançou uma magia/item sem alvo",
"tooltip_DOTA_UNIT_ORDER_HOLD_POSITION": "Número de vezes que o jogador manteve-se em posição",
"tooltip_DOTA_UNIT_ORDER_GLYPH": "Número de vezes que o jogador utilizou o glifo de fortificação",
"tooltip_DOTA_UNIT_ORDER_RADAR": "Número de vezes que o jogador utilizou o scaneamento no mapa",
"tooltip_last_played": "A última vez que uma partida foi jogada com este herói/jogador",
"tooltip_matches": "Partidas jogadas com/contra este jogador",
"tooltip_played_as": "Número de partidas jogadas com este herói",
"tooltip_played_with": "Número de jogos com este herói/jogador no time",
"tooltip_played_against": "Número de jogos com este herói/jogador na equipe adversária",
"tooltip_tombstone_victim": "Aqui jaz",
"tooltip_tombstone_killer": "destruída por",
"tooltip_win_pct_as": "Porcentagem de vitória com este herói",
"tooltip_win_pct_with": "Porcentagem de vitória com este jogador/herói",
"tooltip_win_pct_against": "Porcentagem de vitória contra este jogador/herói",
"tooltip_lhten": "Finalizações aos 10 minutos",
"tooltip_dnten": "Negações aos 10 minutos",
"tooltip_biggest_hit": "Instância maior de dano em um herói",
"tooltip_damage_dealt": "Dano causado a heróis por itens/habilidades",
"tooltip_damage_received": "Dano recebido de heróis por itens/habilidades",
"tooltip_registered_user": "Usuário registrado",
"tooltip_ability_builds": "Habilidades",
"tooltip_ability_builds_expired": "A habilidade de atualizar dados foi expirada para esta partida. Use o formulário de requisição para recarregar os dados.",
"tooltip_multikill": "Multi-kill mais longo",
"tooltip_killstreak": "Sequência de abates mais Longa",
"tooltip_casts": "Número de vezes que este item/habilidade foi utilizado",
"tooltip_target_abilities": "Quantas vezes cada herói foi alvo das habilidades deste herói",
"tooltip_hits": "Número de instâncias de dano em heróis causadas por este item/habilidade",
"tooltip_damage": "Quantidade de dano causado em heróis por este item/habilidade",
"tooltip_autoattack_other": "Auto Ataque/Outros",
"tooltip_estimated_mmr": "Estimativa de MMR baseada na média visível de MMR dos jogos mais recentes deste usuário",
"tooltip_backpack": "Mochila",
"tooltip_others_tracked_deaths": "mortes rastreadas",
"tooltip_others_track_gold": "ouro obtido com rastreio",
"tooltip_others_greevils_gold": "ouro obtido com Greevil's Greed",
"tooltip_advantage": "Calculado pelo método Wilson",
"tooltip_winrate_samplesize": "Taxa de vitórias e tamanho da amostra",
"tooltip_teamfight_participation": "Participação nas batalhas em equipe",
"histograms_name": "Histogramas",
"histograms_description": "Percentagens indicam taxas de vitórias para o intervalo rotulado",
"histograms_actions_per_min_description": "Ações por minuto",
"histograms_comeback_description": "Desvantagem de ouro máxima em um jogo ganho",
"histograms_lane_efficiency_pct_description": "Porcentagem de ouro na lane (Creeps+Passivo+Inicial) obtido em 10 minutos",
"histograms_gold_per_min_description": "Ouro obtido por minuto",
"histograms_hero_damage_description": "Quantidade de dano causado em heróis",
"histograms_hero_healing_description": "Quantidade de vida restaurada em heróis",
"histograms_level_description": "Nível alcançado em uma partida",
"histograms_loss_description": "Déficit máximo de ouro em uma derrota",
"histograms_pings_description": "Pings no mapa",
"histograms_stomp_description": "Vantagem máxima de ouro em um jogo ganho",
"histograms_stuns_description": "Segundos de disable em heróis",
"histograms_throw_description": "Vantagem máxima de ouro em um jogo ganho",
"histograms_purchase_tpscroll_description": "Pergaminho de Teletransporte comprados",
"histograms_xp_per_min_description": "Experiência obtida por minuto",
"trends_name": "Tendências",
"trends_description": "Média acumulada dos últimos 500 jogos",
"trends_tooltip_average": "Méd.",
"trends_no_data": "Desculpe, não há dados para este gráfico",
"xp_reasons_0": "Outro",
"xp_reasons_1": "Herói",
"xp_reasons_2": "Creep",
"xp_reasons_3": "Roshan",
"rankings_description": "",
"rankings_none": "Este jogador não é classificado em nenhum herói.",
"region_0": "Automático",
"region_1": "Oeste dos EUA",
"region_2": "Leste dos EUA",
"region_3": "Luxemburgo",
"region_5": "Singapura",
"region_6": "Dubai",
"region_7": "Austrália",
"region_8": "Estocolmo",
"region_9": "Áustria",
"region_10": "Brasil",
"region_11": "África do Sul",
"region_12": "China TC (Xangai)",
"region_13": "China",
"region_14": "Chile",
"region_15": "Peru",
"region_16": "Índia",
"region_17": "China TC (Guangdong)",
"region_18": "China TC (Zhejiang)",
"region_19": "Japão",
"region_20": "China TC (Wuhan)",
"region_25": "China",
"vision_expired": "Expira em",
"vision_destroyed": "Destruído em",
"vision_all_time": "Todo o Tempo",
"vision_placed_observer": "colocou uma sentinela observadora em",
"vision_placed_sentry": "colocou uma Sentinela Reveladora em",
"vision_ward_log": "Histórico de Wards",
"chat_category_faction": "Facção",
"chat_category_type": "Tipo",
"chat_category_target": "Destino",
"chat_category_other": "Outros",
"chat_filter_text": "Texto",
"chat_filter_phrases": "Frases",
"chat_filter_audio": "Áudio",
"chat_filter_spam": "Spam",
"chat_filter_all": "Todos",
"chat_filter_allies": "Aliados",
"chat_filter_spectator": "Espectador",
"chat_filtered": "Filtrado",
"advb_almost": "quase",
"advb_over": "sobre",
"advb_about": "sobre",
"article_before_consonant_sound": "um",
"article_before_vowel_sound": "um",
"statement_long": "questionou hipotético",
"statement_shouted": "gritou",
"statement_excited": "exclamou",
"statement_normal": "disse",
"statement_laughed": "riu",
"question_long": "questionou, precisando de respostas",
"question_shouted": "inquiriu",
"question_excited": "interrogou",
"question_normal": "perguntou",
"question_laughed": "riu debochadamente",
"statement_response_long": "avisou",
"statement_response_shouted": "respondeu frustrado",
"statement_response_excited": "exclamou",
"statement_response_normal": "respondeu",
"statement_response_laughed": "riu",
"statement_continued_long": "falaram",
"statement_continued_shouted": "continuou furiosamente",
"statement_continued_excited": "continuou",
"statement_continued_normal": "adicionou",
"statement_continued_laughed": "continuou",
"question_response_long": "avisou",
"question_response_shouted": "perguntou de volta, com bastante frustração",
"question_response_excited": "disputou",
"question_response_normal": "retrucou",
"question_response_laughed": "riu",
"question_continued_long": "propôs",
"question_continued_shouted": "perguntou com fúria",
"question_continued_excited": "perguntou carinhosamente",
"question_continued_normal": "perguntou",
"question_continued_laughed": "perguntou com bastante entusiamo",
"hero_disclaimer_pro": "Dados de partidas profissionais",
"hero_disclaimer_public": "Dados de partidas públicas",
"hero_duration_x_axis": "Minutos",
"top_tower": "Torre de cima",
"bot_tower": "Torre de baixo",
"mid_tower": "Torre do meio",
"top_rax": "Quartel de cima",
"bot_rax": "Quartel de baixo",
"mid_rax": "Quartel do meio",
"tier1": "Primeira",
"tier2": "Segunda",
"tier3": "Terceira",
"tier4": "Quarta",
"show_consumables_items": "Exibir consumíveis",
"activated": "Ativado(a)",
"rune": "Runa",
"placement": "Posição",
"exclude_turbo_matches": "Não contar partidas Turbo",
"scenarios_subtitle": "Explorar taxa de vitórias de combinação de fatores que ocorrem em nas partidas",
"scenarios_info": "Dados obtidos de partidas das últimas {0} semanas",
"scenarios_item_timings": "Tempo dos itens",
"scenarios_misc": "Diversos",
"scenarios_time": "Tempo",
"scenarios_item": "Item",
"scenarios_game_duration": "Duração do jogo",
"scenarios_scenario": "Cenário",
"scenarios_first_blood": "Time conseguiu primeiro abate",
"scenarios_courier_kill": "Time matou o courier inimigo antes dos 3 minutos",
"scenarios_pos_chat_1min": "Time mandou mensagens positivas para todos antes de 1 minuto",
"scenarios_neg_chat_1min": "Time mandou palavras negativas no chat para todos antes de 1 minuto",
"gosu_default": "Obtenha recomendações pessoais",
"gosu_benchmarks": "Obter referências detalhadas para o seu herói, linha e posição",
"gosu_performances": "Obter seu desempenho de controle de mapa",
"gosu_laning": "Entenda porque você perdeu os últimos hits",
"gosu_combat": "Entenda porque suas tentativas de eliminação falharam",
"gosu_farm": "Entenda porque errou os last hits",
"gosu_vision": "Entenda quantos heróis morreram sob visão de suas sentinelas",
"gosu_actions": "Entenda o tempo perdido usando o mouse ao invés dos atalhos do teclado",
"gosu_teamfights": "Entenda quem focar durante as batalhas de equipe",
"gosu_analysis": "Obter seu ranking real",
"back2Top": "Topo",
"activity_subtitle": "Clique no dia para informações detalhadas"
} | odota/web/src/lang/pt-BR.json/0 | {
"file_path": "odota/web/src/lang/pt-BR.json",
"repo_id": "odota",
"token_count": 21714
} | 262 |
import { requestActions } from '../actions/requestActions';
const initialState = {
progress: 0,
error: '',
loading: false,
};
export default (state = initialState, action) => {
switch (action.type) {
case requestActions.START:
return {
...state,
loading: true,
};
case requestActions.ERROR:
return {
...initialState,
error: action.error || true,
};
case requestActions.OK:
return initialState;
case requestActions.PROGRESS:
return {
...state,
progress: action.progress,
};
default:
return state;
}
};
| odota/web/src/reducers/request.js/0 | {
"file_path": "odota/web/src/reducers/request.js",
"repo_id": "odota",
"token_count": 264
} | 263 |
{
"tracked_until": null,
"profile": {
"account_id": 101695162,
"personaname": "Mbappé",
"name": "fy",
"cheese": 0,
"steamid": "76561198061960890",
"avatar": "https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/avatars/71/7137bb86c5fdbd79bd37222438a7b903f87fbbc3.jpg",
"avatarmedium": "https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/avatars/71/7137bb86c5fdbd79bd37222438a7b903f87fbbc3_medium.jpg",
"avatarfull": "https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/avatars/71/7137bb86c5fdbd79bd37222438a7b903f87fbbc3_full.jpg",
"profileurl": "https://steamcommunity.com/profiles/76561198061960890/",
"last_login": null,
"loccountrycode": null
},
"competitive_rank": null,
"solo_competitive_rank": 8143,
"leaderboard_rank": 32,
"rank_tier": 80,
"mmr_estimate": {
"estimate": 6479
}
} | odota/web/testcafe/cachedAjax/players_101695162_.json/0 | {
"file_path": "odota/web/testcafe/cachedAjax/players_101695162_.json",
"repo_id": "odota",
"token_count": 381
} | 264 |
{
"win": 3747,
"lose": 2328
} | odota/web/testcafe/cachedAjax/players_101695162_wl_.json/0 | {
"file_path": "odota/web/testcafe/cachedAjax/players_101695162_wl_.json",
"repo_id": "odota",
"token_count": 19
} | 265 |
[
{
"match_id": "4095440370",
"start_time": "1535849203",
"hero_id": "36",
"score": "1645"
},
{
"match_id": "4095440370",
"start_time": "1535849203",
"hero_id": "67",
"score": "1592"
},
{
"match_id": "4093423096",
"start_time": "1535763309",
"hero_id": "82",
"score": "1569"
},
{
"match_id": "4102064682",
"start_time": "1536171439",
"hero_id": "82",
"score": "1546"
},
{
"match_id": "4095440370",
"start_time": "1535849203",
"hero_id": "104",
"score": "1521"
},
{
"match_id": "4103236305",
"start_time": "1536238026",
"hero_id": "82",
"score": "1510"
},
{
"match_id": "4107427039",
"start_time": "1536429024",
"hero_id": "82",
"score": "1499"
},
{
"match_id": "4097216934",
"start_time": "1535920008",
"hero_id": "82",
"score": "1490"
},
{
"match_id": "4095440370",
"start_time": "1535849203",
"hero_id": "88",
"score": "1490"
},
{
"match_id": "4108677235",
"start_time": "1536486954",
"hero_id": "82",
"score": "1489"
},
{
"match_id": "4109595470",
"start_time": "1536516470",
"hero_id": "14",
"score": "1488"
},
{
"match_id": "4101369220",
"start_time": "1536148108",
"hero_id": "61",
"score": "1486"
},
{
"match_id": "4100161507",
"start_time": "1536079541",
"hero_id": "82",
"score": "1480"
},
{
"match_id": "4102663117",
"start_time": "1536212620",
"hero_id": "82",
"score": "1475"
},
{
"match_id": "4105088862",
"start_time": "1536330139",
"hero_id": "82",
"score": "1474"
},
{
"match_id": "4110568771",
"start_time": "1536576900",
"hero_id": "82",
"score": "1473"
},
{
"match_id": "4103023327",
"start_time": "1536230109",
"hero_id": "82",
"score": "1473"
},
{
"match_id": "4097681366",
"start_time": "1535955920",
"hero_id": "82",
"score": "1473"
},
{
"match_id": "4100094893",
"start_time": "1536076871",
"hero_id": "82",
"score": "1467"
},
{
"match_id": "4109581441",
"start_time": "1536515836",
"hero_id": "82",
"score": "1466"
},
{
"match_id": "4111500781",
"start_time": "1536615278",
"hero_id": "82",
"score": "1462"
},
{
"match_id": "4099948368",
"start_time": "1536071738",
"hero_id": "82",
"score": "1460"
},
{
"match_id": "4100054831",
"start_time": "1536075368",
"hero_id": "82",
"score": "1456"
},
{
"match_id": "4108735168",
"start_time": "1536488854",
"hero_id": "82",
"score": "1450"
},
{
"match_id": "4095766759",
"start_time": "1535867343",
"hero_id": "82",
"score": "1449"
},
{
"match_id": "4095440370",
"start_time": "1535849203",
"hero_id": "21",
"score": "1447"
},
{
"match_id": "4110859342",
"start_time": "1536586930",
"hero_id": "82",
"score": "1446"
},
{
"match_id": "4105955997",
"start_time": "1536373892",
"hero_id": "82",
"score": "1444"
},
{
"match_id": "4103350090",
"start_time": "1536241570",
"hero_id": "82",
"score": "1444"
},
{
"match_id": "4102506619",
"start_time": "1536203201",
"hero_id": "82",
"score": "1444"
},
{
"match_id": "4107306541",
"start_time": "1536424648",
"hero_id": "82",
"score": "1439"
},
{
"match_id": "4105407830",
"start_time": "1536340510",
"hero_id": "82",
"score": "1438"
},
{
"match_id": "4105312356",
"start_time": "1536337135",
"hero_id": "82",
"score": "1438"
},
{
"match_id": "4097936671",
"start_time": "1535969951",
"hero_id": "82",
"score": "1437"
},
{
"match_id": "4097366815",
"start_time": "1535931885",
"hero_id": "82",
"score": "1437"
},
{
"match_id": "4111126960",
"start_time": "1536595604",
"hero_id": "82",
"score": "1436"
},
{
"match_id": "4095095464",
"start_time": "1535827758",
"hero_id": "82",
"score": "1436"
},
{
"match_id": "4105453628",
"start_time": "1536342243",
"hero_id": "82",
"score": "1435"
},
{
"match_id": "4108380772",
"start_time": "1536477452",
"hero_id": "82",
"score": "1434"
},
{
"match_id": "4105345641",
"start_time": "1536338281",
"hero_id": "82",
"score": "1434"
},
{
"match_id": "4101942164",
"start_time": "1536166010",
"hero_id": "82",
"score": "1434"
},
{
"match_id": "4108969530",
"start_time": "1536496087",
"hero_id": "82",
"score": "1428"
},
{
"match_id": "4104788163",
"start_time": "1536321254",
"hero_id": "82",
"score": "1428"
},
{
"match_id": "4110895425",
"start_time": "1536587992",
"hero_id": "82",
"score": "1426"
},
{
"match_id": "4109689908",
"start_time": "1536520974",
"hero_id": "82",
"score": "1426"
},
{
"match_id": "4099349495",
"start_time": "1536046545",
"hero_id": "82",
"score": "1426"
},
{
"match_id": "4102398983",
"start_time": "1536196291",
"hero_id": "82",
"score": "1425"
},
{
"match_id": "4097244552",
"start_time": "1535921793",
"hero_id": "82",
"score": "1425"
},
{
"match_id": "4093556491",
"start_time": "1535771883",
"hero_id": "82",
"score": "1424"
},
{
"match_id": "4109623943",
"start_time": "1536517732",
"hero_id": "82",
"score": "1422"
},
{
"match_id": "4094735986",
"start_time": "1535815405",
"hero_id": "82",
"score": "1422"
},
{
"match_id": "4108526706",
"start_time": "1536482160",
"hero_id": "82",
"score": "1421"
},
{
"match_id": "4105264766",
"start_time": "1536335617",
"hero_id": "82",
"score": "1419"
},
{
"match_id": "4102561376",
"start_time": "1536206586",
"hero_id": "82",
"score": "1419"
},
{
"match_id": "4106254001",
"start_time": "1536387960",
"hero_id": "82",
"score": "1417"
},
{
"match_id": "4096061043",
"start_time": "1535878205",
"hero_id": "82",
"score": "1417"
},
{
"match_id": "4094727435",
"start_time": "1535815140",
"hero_id": "82",
"score": "1415"
},
{
"match_id": "4108693659",
"start_time": "1536487464",
"hero_id": "61",
"score": "1414"
},
{
"match_id": "4102827085",
"start_time": "1536221154",
"hero_id": "82",
"score": "1414"
},
{
"match_id": "4096591547",
"start_time": "1535895314",
"hero_id": "82",
"score": "1414"
},
{
"match_id": "4108384482",
"start_time": "1536477572",
"hero_id": "82",
"score": "1412"
},
{
"match_id": "4107656423",
"start_time": "1536438890",
"hero_id": "82",
"score": "1411"
},
{
"match_id": "4106877364",
"start_time": "1536409602",
"hero_id": "82",
"score": "1410"
},
{
"match_id": "4099871525",
"start_time": "1536069267",
"hero_id": "82",
"score": "1410"
},
{
"match_id": "4108255539",
"start_time": "1536473053",
"hero_id": "82",
"score": "1409"
},
{
"match_id": "4098121786",
"start_time": "1535977608",
"hero_id": "82",
"score": "1409"
},
{
"match_id": "4097677439",
"start_time": "1535955710",
"hero_id": "82",
"score": "1409"
},
{
"match_id": "4097810864",
"start_time": "1535963479",
"hero_id": "82",
"score": "1408"
},
{
"match_id": "4110488836",
"start_time": "1536573338",
"hero_id": "82",
"score": "1407"
},
{
"match_id": "4103863911",
"start_time": "1536265108",
"hero_id": "82",
"score": "1407"
},
{
"match_id": "4109021241",
"start_time": "1536497535",
"hero_id": "82",
"score": "1406"
},
{
"match_id": "4101847124",
"start_time": "1536162439",
"hero_id": "82",
"score": "1406"
},
{
"match_id": "4098625630",
"start_time": "1535995413",
"hero_id": "11",
"score": "1406"
},
{
"match_id": "4102824399",
"start_time": "1536221040",
"hero_id": "82",
"score": "1405"
},
{
"match_id": "4101227762",
"start_time": "1536142878",
"hero_id": "82",
"score": "1405"
},
{
"match_id": "4098134379",
"start_time": "1535978044",
"hero_id": "82",
"score": "1405"
},
{
"match_id": "4099571495",
"start_time": "1536058305",
"hero_id": "82",
"score": "1403"
},
{
"match_id": "4110353374",
"start_time": "1536566821",
"hero_id": "82",
"score": "1402"
},
{
"match_id": "4107889909",
"start_time": "1536455167",
"hero_id": "82",
"score": "1401"
},
{
"match_id": "4101895074",
"start_time": "1536164155",
"hero_id": "82",
"score": "1401"
},
{
"match_id": "4101534766",
"start_time": "1536153174",
"hero_id": "82",
"score": "1401"
},
{
"match_id": "4099688181",
"start_time": "1536063125",
"hero_id": "82",
"score": "1399"
},
{
"match_id": "4111488365",
"start_time": "1536614259",
"hero_id": "82",
"score": "1398"
},
{
"match_id": "4106904521",
"start_time": "1536410396",
"hero_id": "82",
"score": "1398"
},
{
"match_id": "4104813745",
"start_time": "1536322116",
"hero_id": "82",
"score": "1395"
},
{
"match_id": "4109394720",
"start_time": "1536508571",
"hero_id": "82",
"score": "1394"
},
{
"match_id": "4108701258",
"start_time": "1536487744",
"hero_id": "61",
"score": "1394"
},
{
"match_id": "4104623135",
"start_time": "1536314625",
"hero_id": "82",
"score": "1394"
},
{
"match_id": "4094541139",
"start_time": "1535809995",
"hero_id": "82",
"score": "1394"
},
{
"match_id": "4105599811",
"start_time": "1536348789",
"hero_id": "82",
"score": "1393"
},
{
"match_id": "4102674458",
"start_time": "1536213246",
"hero_id": "82",
"score": "1393"
},
{
"match_id": "4094213937",
"start_time": "1535799643",
"hero_id": "82",
"score": "1393"
},
{
"match_id": "4100125035",
"start_time": "1536078047",
"hero_id": "82",
"score": "1392"
},
{
"match_id": "4096810655",
"start_time": "1535901866",
"hero_id": "82",
"score": "1391"
},
{
"match_id": "4108304480",
"start_time": "1536474816",
"hero_id": "82",
"score": "1390"
},
{
"match_id": "4093674734",
"start_time": "1535778222",
"hero_id": "82",
"score": "1390"
},
{
"match_id": "4105718602",
"start_time": "1536355695",
"hero_id": "82",
"score": "1389"
},
{
"match_id": "4104720038",
"start_time": "1536318738",
"hero_id": "82",
"score": "1388"
},
{
"match_id": "4104365400",
"start_time": "1536302055",
"hero_id": "82",
"score": "1388"
},
{
"match_id": "4103245255",
"start_time": "1536238309",
"hero_id": "82",
"score": "1388"
}
] | odota/web/testcafe/cachedAjax/records_xp_per_min_.json/0 | {
"file_path": "odota/web/testcafe/cachedAjax/records_xp_per_min_.json",
"repo_id": "odota",
"token_count": 5567
} | 266 |
FROM node:16-alpine AS deps
RUN apk add --no-cache libc6-compat git
WORKDIR /app
COPY frontend/package.json frontend/yarn.lock ./frontend/
RUN cd frontend && yarn install --frozen-lockfile
FROM node:16-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
# Copy everything
COPY . .
COPY --from=deps /app/frontend/node_modules ./frontend/node_modules
RUN cd frontend && yarn build && yarn install --production --ignore-scripts --prefer-offline
# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
COPY --from=builder --chown=nextjs:nodejs /app/ .
WORKDIR /app/frontend
USER nextjs
EXPOSE 3000
CMD ["yarn", "start"]
| openmultiplayer/web/Dockerfile.frontend/0 | {
"file_path": "openmultiplayer/web/Dockerfile.frontend",
"repo_id": "openmultiplayer",
"token_count": 275
} | 267 |
package server
import (
"context"
"os"
"strings"
"time"
"github.com/goccy/go-json"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/openmultiplayer/web/internal/config"
"github.com/openmultiplayer/web/internal/db"
)
var _ Repository = &DB{}
type DB struct {
client *db.PrismaClient
cfg config.Config
}
func New(client *db.PrismaClient, cfg config.Config) Repository {
return &DB{client, cfg}
}
func (s *DB) Upsert(ctx context.Context, e All) error {
var svr *db.ServerModel
var err error
// Check whether an IP is blocked or not, not port specific
blockedServer, err := s.client.ServerIPBlacklist.
FindUnique(db.ServerIPBlacklist.IP.Equals(strings.Split(e.IP, ":")[0])).
Exec(ctx)
if blockedServer != nil {
return errors.Wrapf(err, "IP address is blocked")
}
if !e.Active {
// If a server is inactive and it doesn't already exist in the database
// then no data needs to be written and this is not an error. This only
// happens during seeding where a server from the initial seed list is
// offline during the first-time query and DB seed process.
//nolint:errcheck
s.client.Server.
FindUnique(db.Server.IP.Equals(e.IP)).
Update(db.Server.Active.Set(false)).
Exec(ctx)
return nil
}
svr, err = s.client.Server.
FindUnique(db.Server.IP.Equals(e.IP)).
Update(
db.Server.IP.Set(e.IP),
db.Server.Hn.Set(e.Core.Hostname),
db.Server.Pc.Set(db.BigInt(e.Core.Players)),
db.Server.Pm.Set(db.BigInt(e.Core.MaxPlayers)),
db.Server.Gm.Set(e.Core.Gamemode),
db.Server.La.Set(e.Core.Language),
db.Server.Pa.Set(e.Core.Password),
db.Server.Vn.Set(e.Core.Version),
db.Server.Omp.Set(e.Core.IsOmp),
db.Server.Domain.SetOptional(e.Domain),
db.Server.Description.SetOptional(e.Description),
db.Server.Banner.SetOptional(e.Banner),
db.Server.Active.Set(e.Active),
db.Server.LastActive.Set(time.Now()),
).Exec(ctx)
if errors.Is(err, db.ErrNotFound) {
if !e.Active {
// don't store inactive servers that don't exist.
return nil
} else {
if svr, err = s.client.Server.CreateOne(
db.Server.IP.Set(e.IP),
db.Server.Hn.Set(e.Core.Hostname),
db.Server.Pc.Set(db.BigInt(e.Core.Players)),
db.Server.Pm.Set(db.BigInt(e.Core.MaxPlayers)),
db.Server.Gm.Set(e.Core.Gamemode),
db.Server.La.Set(e.Core.Language),
db.Server.Pa.Set(e.Core.Password),
db.Server.Vn.Set(e.Core.Version),
db.Server.Active.Set(e.Active),
db.Server.Omp.Set(e.Core.IsOmp),
db.Server.Pending.Set(true),
db.Server.Domain.SetOptional(e.Domain),
db.Server.Description.SetOptional(e.Description),
db.Server.Banner.SetOptional(e.Banner),
db.Server.LastActive.Set(time.Now()),
).Exec(ctx); err != nil {
return errors.Wrapf(err, "failed to create '%v'", e)
}
}
} else if err != nil {
return errors.Wrapf(err, "failed to update '%v'", e)
}
for k, v := range e.Rules {
_, err := s.client.Rule.
FindUnique(db.Rule.RuleServerIDRuleNameIndex(
db.Rule.Name.Equals(k),
db.Rule.ServerID.Equals(svr.ID),
)).
Update(db.Rule.Value.Set(v)).
Exec(ctx)
if err != nil {
_, err = s.client.Rule.CreateOne(
db.Rule.Name.Set(k),
db.Rule.Value.Set(v),
db.Rule.Server.Link(db.Server.ID.Equals(svr.ID)),
).Exec(ctx)
if err != nil {
return errors.Wrapf(err, "failed to create rule '%s': '%s' for %s", k, v, svr.ID)
}
}
}
return nil
}
func (s *DB) GetByID(ctx context.Context, id string) (*All, error) {
r, err := s.client.Server.FindUnique(db.Server.ID.Equals(id)).Exec(ctx)
if err != nil {
return nil, err
}
return dbToAPI(*r), nil
}
func (s *DB) GetByAddress(ctx context.Context, address string) (*All, error) {
r, err := s.client.Server.
FindUnique(db.Server.IP.Equals(address)).
With(db.Server.Ru.Fetch()).
Exec(ctx)
if err != nil {
return nil, err
}
return dbToAPI(*r), nil
}
func (s *DB) GetEssential(context.Context, string) (*Essential, error) {
return nil, nil
}
func (s *DB) GetServersToQuery(ctx context.Context, before time.Duration) ([]string, error) {
result, err := s.client.Server.
FindMany(db.Server.UpdatedAt.Before(time.Now().Add(-before)), db.Server.DeletedAt.IsNull(), db.Server.Pending.Equals(false)).
OrderBy(db.Server.UpdatedAt.Order(db.SortOrderDesc)).
Exec(ctx)
if err != nil {
return nil, err
}
addresses := []string{}
for _, r := range result {
addresses = append(addresses, r.IP)
}
return addresses, nil
}
func (s *DB) GetAll(ctx context.Context, lastActive time.Duration) ([]All, error) {
result, err := s.client.Server.
FindMany(db.Server.LastActive.After(time.Now().Add(lastActive)), db.Server.DeletedAt.IsNull(), db.Server.Pending.Equals(false)).
OrderBy(db.Server.UpdatedAt.Order(db.SortOrderAsc)).
With(db.Server.Ru.Fetch()).
Exec(ctx)
if err != nil {
return nil, err
}
return dbToAPISlice(result), err
}
func (s *DB) SetDeleted(ctx context.Context, ip string, at *time.Time) (*All, error) {
result, err := s.client.Server.
FindUnique(db.Server.IP.Equals(ip)).
With(db.Server.Ru.Fetch()).
Update(db.Server.DeletedAt.SetOptional(at)).
Exec(ctx)
if err != nil {
return nil, err
}
return dbToAPI(*result), err
}
func (s *DB) GetAllCached(ctx context.Context, lastActive time.Duration) ([]All, error) {
result := []All{}
list := []All{}
s.GenerateCacheIfNeeded(ctx, lastActive)
dat, err := os.ReadFile(s.cfg.CachedServers)
if err != nil {
return nil, err
}
err = json.Unmarshal(dat, &result)
if err != nil {
return nil, err
}
for idx := range result {
if result[idx].LastActive != nil && result[idx].LastActive.After(time.Now().Add(lastActive)) {
list = append(list, result[idx])
}
}
return list, nil
}
func (s *DB) GetByAddressCached(ctx context.Context, address string) (*All, error) {
result, err := s.GetAllCached(ctx, -120*time.Hour)
if err != nil {
return nil, err
}
for _, n := range result {
if address == n.IP {
return &n, nil
}
}
return nil, errors.New("server_not_found")
}
func (s *DB) GenerateCacheIfNeeded(ctx context.Context, lastActive time.Duration) error {
_, err := os.Stat(s.cfg.CachedServers)
if errors.Is(err, os.ErrNotExist) {
return s.GenerateCache(ctx, lastActive)
}
return nil
}
func (s *DB) GenerateCache(ctx context.Context, lastActive time.Duration) error {
result, err := s.GetAll(ctx, lastActive)
if err != nil {
zap.L().Error("There was an error converting native array of servers to JSON data",
zap.Error(err))
return err
}
return s.GenerateCacheFromData(ctx, result)
}
func (s *DB) GenerateCacheFromData(ctx context.Context, servers []All) error {
// Let's save all servers info our cache file to be used in our API data processing instead of DB
jsonData, err := json.Marshal(servers)
if err != nil {
zap.L().Error("There was an error converting native array of servers to JSON data",
zap.Error(err))
return err
}
cacheFile, err := os.Create(s.cfg.CachedServers)
if err != nil {
zap.L().Error("Could not create server cache file",
zap.Error(err))
return err
}
_, err = cacheFile.Write(jsonData)
if err != nil {
zap.L().Error("There was an error writing collected servers into cache file",
zap.Error(err))
return err
}
return nil
}
| openmultiplayer/web/app/resources/server/db.go/0 | {
"file_path": "openmultiplayer/web/app/resources/server/db.go",
"repo_id": "openmultiplayer",
"token_count": 2954
} | 268 |
package scraper
import (
"context"
"github.com/openmultiplayer/web/app/resources/server"
)
type Scraper interface {
Scrape(context.Context, []string) chan server.All
}
type MockScraper struct{}
func (s *MockScraper) Scrape(ctx context.Context, addresses []string) chan server.All {
ch := make(chan server.All)
go func() {
ch <- server.All{
IP: "127.0.0.1:7777",
Core: server.Essential{
Hostname: "SA-MP SERVER CLAN tdm [NGRP] [GF EDIT] [Y_INI] [RUS] [BASIC] [GODFATHER] [REFUNDING] [STRCMP]",
Players: 32,
MaxPlayers: 128,
Gamemode: "Grand Larceny",
Language: "English",
Password: false,
Version: "0.3.7-R2",
},
}
ch <- server.All{
IP: "127.0.0.2:7777",
Core: server.Essential{
Hostname: "my cool server",
Players: 3,
MaxPlayers: 5,
Gamemode: "cool",
Language: "English",
Password: false,
Version: "0.3.7-R2",
},
}
ch <- server.All{
IP: "127.0.0.3:7777",
Core: server.Essential{
Hostname: "godfather v194",
Players: 1,
MaxPlayers: 999,
Gamemode: "godfather",
Language: "foriegn",
Password: false,
Version: "0.1b",
},
}
close(ch)
}()
return ch
}
| openmultiplayer/web/app/services/scraper/scraper.go/0 | {
"file_path": "openmultiplayer/web/app/services/scraper/scraper.go",
"repo_id": "openmultiplayer",
"token_count": 604
} | 269 |
package pawndex
import (
"github.com/go-chi/chi"
"go.uber.org/fx"
"github.com/openmultiplayer/web/app/resources/pawndex"
)
type service struct {
store pawndex.Repository
}
func Build() fx.Option {
return fx.Options(
fx.Provide(func(repo pawndex.Repository) *service { return &service{repo} }),
fx.Invoke(func(
r chi.Router,
s *service,
) {
rtr := chi.NewRouter()
r.Mount("/pawndex", rtr)
rtr.Get("/", s.list)
rtr.Get("/{user}/{repo}", s.get)
rtr.Get("/{user}/{repo}/latest", s.getLatest)
}),
)
}
| openmultiplayer/web/app/transports/api/pawndex/api.go/0 | {
"file_path": "openmultiplayer/web/app/transports/api/pawndex/api.go",
"repo_id": "openmultiplayer",
"token_count": 260
} | 270 |
package users
import (
"errors"
"net/http"
"github.com/go-chi/chi"
"github.com/openmultiplayer/web/app/services/authentication"
"github.com/openmultiplayer/web/internal/db"
"github.com/openmultiplayer/web/internal/web"
)
func (s *service) get(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
// context is public, hide sensitive PII like email
public := true
if auth, ok := authentication.GetAuthenticationInfoFromContext(r.Context()); ok {
if auth.Cookie.UserID == id || auth.Cookie.Admin {
// context is owner/admin, reveal sensitive PII
public = false
}
}
user, err := s.repo.GetUser(r.Context(), id, public)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
web.StatusNotFound(w, err)
} else {
web.StatusInternalServerError(w, err)
}
return
}
web.Write(w, user) //nolint:errcheck
}
| openmultiplayer/web/app/transports/api/users/h_get.go/0 | {
"file_path": "openmultiplayer/web/app/transports/api/users/h_get.go",
"repo_id": "openmultiplayer",
"token_count": 327
} | 271 |
---
title: Contributing
description: How to contribute to the SA-MP Wiki and open.mp documentation.
---
This documentation source is open for anyone to contribute changes to! All you need is a [GitHub](https://github.com) account and some spare time. You don't even need to know Git, you can do it all from the web interface!
If you want to help maintain a specific language, open a PR against the [`CODEOWNERS`](https://github.com/openmultiplayer/web/blob/master/CODEOWNERS) file and add a line for your language directory with your username.
## Editing Content
On each page, there's a button that takes you to the GitHub page for editing:

For example, clicking this on [SetVehicleAngularVelocity](../scripting/functions/SetVehicleAngularVelocity) takes you to [this page](https://github.com/openmultiplayer/web/blob/master/docs/scripting/functions/SetVehicleAngularVelocity.md) which presents you with a text editor to make changes to the file (assuming you're logged in to GitHub).
Make your edit and submit a "Pull Request" this means the Wiki maintainers and other community members can review your change, discuss whether it needs additional changes and then merge it.
## Adding New Content
Adding new content is a little more involved. You can do it two ways:
### GitHub Interface
When browsing a directory on GitHub, there's an Add file button on the top right corner of the file list:

You can either upload a Markdown file you've written already or write it directly into the GitHub text editor.
The file _must_ have a `.md` extension and contain Markdown. For more information about Markdown, check out [this guide](https://guides.github.com/features/mastering-markdown/).
Once that's done, hit "Propose new file" and a Pull Request will be opened for review.
### Git
If you want to use Git, all you need to do is clone the Wiki repository with:
```sh
git clone https://github.com/openmultiplayer/wiki.git
```
Open it in your favourite editor. I recommend Visual Studio Code as it has some great tooling for editing and formatting Markdown files. As you can see, I'm writing this using Visual Studio Code!

I recommend two extensions to make your experience better:
- [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint) by David Anson - this is an extension that makes sure your Markdown is formatted correctly. It prevents some syntactical and semantic mistakes. Not all the warnings are important, but some can help improve readability. Use best judgement and if in doubt, just ask a reviewer!
- [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) by the Prettier.js Team - this is a formatter that will automatically format your Markdown files so they all use a consistent style. The Wiki repository has some settings in its `package.json` that the extension should automatically use. Be sure to enable "Format On Save" in your editor settings so your Markdown files will be automatically formatted every time you save!
## Notes, Tips and Conventions
### Internal Links
Don't use absolute URLs for inter-site links. Use relative paths.
- ❌
```md
To be used with [OnPlayerClickPlayer](https://www.open.mp/docs/scripting/callbacks/OnPlayerClickPlayer)
```
- ✔
```md
To be used with [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer)
```
`../` means "go up one directory" so if the file you're editing is inside the `functions` directory and you're linking to `callbacks` you use `../` to go up to `scripting/` then `callbacks/` to enter the callbacks directory, then the filename (without `.md`) of the callback you want to link.
### Images
Images go inside a subdirectory inside `/static/images`. Then when you link an image in a `![]()` you just use `/images/` as the base path (no need for `static` that's just for the repository).
If in doubt, read another page that uses images and copy how its done there.
### Metadata
The first thing in _any_ document here should be metadata:
```mdx
---
title: My Documentation
description: This is a page about stuff and things and burgers, yay!
---
```
Every page should include a title and a description.
For a full list of what can go between the `---`, check out [the Docusaurus documentation](https://v2.docusaurus.io/docs/markdown-features#markdown-headers).
### Headings
Don't create a level 1 heading (`<h1>`) with `#` as this is generated automatically. Your first heading should _always_ be `##`
- ❌
```md
# My Title
This is documentation for ...
# Sub-Section
```
- ✔
```md
This is documentation for ...
## Sub-Section
```
### Use `Code` Snippets For Technical References
When writing a paragraph that contains function names, numbers, expressions or anything that's not standard written language, surround them with \`backticks\` like that. This makes it easier to separate language for describing things from references to technical elements such as function names and pieces of code.
- ❌
> The fopen function will return a value with a tag of type File:, there is no problem on that line as the return value is being stored to a variable also with a tag of File: (note the cases are the same too). However on the next line the value 4 is added to the file handle. 4 has no tag [...]
- ✔
> The `fopen` function will return a value with a tag of type `File:`, there is no problem on that line as the return value is being stored to a variable also with a tag of `File:` (note the cases are the same too). However on the next line the value `4` is added to the file handle. `4` has no tag
In the above example, `fopen` is a function name, not an English word, so surrounding it with `code` snippet markers helps distinguish it from other content.
Also, if the paragraph is referring to a block of example code, this helps the reader associate the words with the example.
### Tables
If a table has headings, they go in the top part:
- ❌
```md
| | |
| ------- | ------------------------------------ |
| Health | Engine Status |
| 650 | Undamaged |
| 650-550 | White Smoke |
| 550-390 | Grey Smoke |
| 390-250 | Black Smoke |
| < 250 | On fire (will explode seconds later) |
```
- ✔
```md
| Health | Engine Status |
| ------- | ------------------------------------ |
| 650 | Undamaged |
| 650-550 | White Smoke |
| 550-390 | Grey Smoke |
| 390-250 | Black Smoke |
| < 250 | On fire (will explode seconds later) |
```
## Migrating from SA-MP Wiki
Most of the content has been moved, but if you find a page that's missing, here's a short guide for converting content to Markdown.
### Getting the HTML
1. Click this button
(Firefox)

(Chrome)

2. Hover the top left of the main wiki page, in the left margin or the corner until you see `#content`

Or search for `<div id=content>`

3. Copy the inner HTML of that element

Now you have _only_ the HTML code for the actual _content_ of the page, the stuff we care about, and you can convert it to Markdown.
### Converting HTML to Markdown
For converting basic HTML (no tables) to Markdown use:
https://domchristie.github.io/turndown/

^^ Notice now it screwed up the table completely...
### HTML Tables to Markdown Tables
Because the above tool does not support tables, use this tool:
https://jmalarcon.github.io/markdowntables/
And copy only the `<table>` element in:

### Cleaning Up
The conversion likely won't be perfect. So you'll have to do a bit of manual cleanup. The formatting extensions listed above should help with that but you may still need to just spend some time doing manual work.
If you don't have time, don't worry! Submit an unfinished draft and someone else can pick up where you left off!
## License Agreement
All open.mp projects have a [Contributor License Agreement](https://cla-assistant.io/openmultiplayer/homepage). This basically just means you agree to let us use your work, and put it under an open-source license. When you open a Pull Request for the first time, the CLA-Assistant bot will post a link where you can sign the agreement.
| openmultiplayer/web/docs/meta/Contributing.md/0 | {
"file_path": "openmultiplayer/web/docs/meta/Contributing.md",
"repo_id": "openmultiplayer",
"token_count": 2712
} | 272 |
---
title: OnNPCModeExit
description: This callback is called when a NPC script unloaded.
tags: ["npc"]
---
## Description
This callback is called when a NPC script unloaded.
## Examples
```c
public OnNPCModeExit()
{
print("NPC script unloaded");
return 1;
}
```
## Related Callbacks
The following callbacks might be useful, as they're related to this callback in one way or another.
- [OnNPCModeInit](OnNPCModeInit): This callback is called when a NPC script loaded.
| openmultiplayer/web/docs/scripting/callbacks/OnNPCModeExit.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/callbacks/OnNPCModeExit.md",
"repo_id": "openmultiplayer",
"token_count": 146
} | 273 |
---
title: OnPlayerEditAttachedObject
description: This callback is called when a player ends attached object edition mode.
tags: ["player", "object", "attachment"]
---
## Description
This callback is called when a player ends attached object edition mode.
| Name | Description |
|------------------------|--------------------------------------------------------------|
| playerid | The ID of the player that ended edition mode |
| EDIT_RESPONSE:response | 0 if they cancelled (ESC) or 1 if they clicked the save icon |
| index | The index of the attached object (0-9) |
| modelid | The model of the attached object that was edited |
| boneid | The bone of the attached object that was edited |
| Float:fOffsetX | The X offset for the attached object that was edited |
| Float:fOffsetY | The Y offset for the attached object that was edited |
| Float:fOffsetZ | The Z offset for the attached object that was edited |
| Float:fRotX | The X rotation for the attached object that was edited |
| Float:fRotY | The Y rotation for the attached object that was edited |
| Float:fRotZ | The Z rotation for the attached object that was edited |
| Float:fScaleX | The X scale for the attached object that was edited |
| Float:fScaleY | The Y scale for the attached object that was edited |
| Float:fScaleZ | The Z scale for the attached object that was edited |
## Returns
1 - Will prevent other scripts from receiving this callback.
0 - Indicates that this callback will be passed to the next script.
It is always called first in filterscripts.
## Examples
```c
enum attached_object_data
{
Float:ao_x,
Float:ao_y,
Float:ao_z,
Float:ao_rx,
Float:ao_ry,
Float:ao_rz,
Float:ao_sx,
Float:ao_sy,
Float:ao_sz
}
new ao[MAX_PLAYERS][MAX_PLAYER_ATTACHED_OBJECTS][attached_object_data];
// The data should be stored in the above array when attached objects are attached.
public OnPlayerEditAttachedObject(playerid, EDIT_RESPONSE:response, index, modelid, boneid, Float:fOffsetX, Float:fOffsetY, Float:fOffsetZ, Float:fRotX, Float:fRotY, Float:fRotZ, Float:fScaleX, Float:fScaleY, Float:fScaleZ)
{
if (response == EDIT_RESPONSE_FINAL)
{
SendClientMessage(playerid, COLOR_GREEN, "Attached object edition saved.");
ao[playerid][index][ao_x] = fOffsetX;
ao[playerid][index][ao_y] = fOffsetY;
ao[playerid][index][ao_z] = fOffsetZ;
ao[playerid][index][ao_rx] = fRotX;
ao[playerid][index][ao_ry] = fRotY;
ao[playerid][index][ao_rz] = fRotZ;
ao[playerid][index][ao_sx] = fScaleX;
ao[playerid][index][ao_sy] = fScaleY;
ao[playerid][index][ao_sz] = fScaleZ;
}
else if (response == EDIT_RESPONSE_CANCEL)
{
SendClientMessage(playerid, COLOR_RED, "Attached object edition not saved.");
new i = index;
SetPlayerAttachedObject(playerid, index, modelid, boneid, ao[playerid][i][ao_x], ao[playerid][i][ao_y], ao[playerid][i][ao_z], ao[playerid][i][ao_rx], ao[playerid][i][ao_ry], ao[playerid][i][ao_rz], ao[playerid][i][ao_sx], ao[playerid][i][ao_sy], ao[playerid][i][ao_sz]);
}
return 1;
}
```
## Notes
:::warning
Editions should be discarded if response was '0' (cancelled). This must be done by storing the offsets etc. in an array BEFORE using [EditAttachedObject](../functions/EditAttachedObject).
:::
## Related Functions
The following functions might be useful, as they're related to this callback in one way or another.
- [EditAttachedObject](../functions/EditAttachedObject): Edit an attached object.
- [SetPlayerAttachedObject](../functions/SetPlayerAttachedObject): Attach an object to a player
| openmultiplayer/web/docs/scripting/callbacks/OnPlayerEditAttachedObject.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/callbacks/OnPlayerEditAttachedObject.md",
"repo_id": "openmultiplayer",
"token_count": 1616
} | 274 |
---
title: OnPlayerLeavePlayerGangZone
description: This callback is called when a player exited a player gangzone
tags: ["player", "gangzone"]
---
<VersionWarn version='omp v1.1.0.2612' />
## Description
This callback is called when a player exited a player gangzone.
| Name | Description |
| -------- | ----------------------------------------------------- |
| playerid | The ID of the player that exited the player gangzone. |
| zoneid | The ID of the player gangzone the player exited. |
## Returns
It is always called first in gamemode.
## Examples
```c
public OnPlayerLeavePlayerGangZone(playerid, zoneid)
{
new string[128];
format(string, sizeof(string), "You are leaving player gangzone %i", zoneid);
SendClientMessage(playerid, 0xFFFFFFFF, string);
return 1;
}
```
## Related Callbacks
The following callbacks might be useful, as they're related to this callback in one way or another.
- [OnPlayerEnterPlayerGangZone](OnPlayerEnterPlayerGangZone): This callback is called when a player exited a player gangzone.
## Related Functions
The following functions might be useful, as they're related to this callback in one way or another.
- [CreatePlayerGangZone](../functions/CreatePlayerGangZone): Create player gangzone.
- [PlayerGangZoneDestroy](../functions/PlayerGangZoneDestroy): Destroy player gangzone.
- [UsePlayerGangZoneCheck](../functions/UsePlayerGangZoneCheck): Enables the callback when a player exited this zone. | openmultiplayer/web/docs/scripting/callbacks/OnPlayerLeavePlayerGangZone.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/callbacks/OnPlayerLeavePlayerGangZone.md",
"repo_id": "openmultiplayer",
"token_count": 460
} | 275 |
---
title: OnVehicleSpawn
description: This callback is called when a vehicle respawns.
tags: ["vehicle"]
---
:::warning
This callback is called **only** when vehicle **re**spawns! CreateVehicle and AddStaticVehicle(Ex) **won't** trigger this callback.
:::
## Description
This callback is called when a vehicle respawns.
| Name | Description |
| --------- | ----------------------------------- |
| vehicleid | The ID of the vehicle that spawned. |
## Returns
0 - Will prevent other filterscripts from receiving this callback.
1 - Indicates that this callback will be passed to the next filterscript.
It is always called first in filterscripts.
## Examples
```c
public OnVehicleSpawn(vehicleid)
{
printf("Vehicle %i spawned!",vehicleid);
return 1;
}
```
## Related Callbacks
The following callbacks might be useful, as they're related to this callback in one way or another.
- [OnVehicleDeath](OnVehicleDeath): This callback is called when a vehicle is destroyed.
- [OnPlayerSpawn](OnPlayerSpawn): This callback is called when a player spawns.
## Related Functions
The following functions might be useful, as they're related to this callback in one way or another.
- [SetVehicleToRespawn](../functions/SetVehicleToRespawn): Respawn a vehicle.
- [CreateVehicle](../functions/CreateVehicle): Create a vehicle.
| openmultiplayer/web/docs/scripting/callbacks/OnVehicleSpawn.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/callbacks/OnVehicleSpawn.md",
"repo_id": "openmultiplayer",
"token_count": 398
} | 276 |
---
title: AllowNickNameCharacter
description: Allows a character to be used in the nick name.
tags: []
---
<VersionWarn version='omp v1.1.0.2612' />
## Description
Allows a character to be used in the nick name.
| Name | Description |
| ---------- | ----------------------------------- |
| character | The character to allow or disallow. |
| bool:allow | true-Allow, false-Disallow |
## Returns
This function does not return any specific values.
## Examples
```c
public OnGameModeInit()
{
AllowNickNameCharacter('*', true); // Allow char *
AllowNickNameCharacter('[', false); // Disallow char [
AllowNickNameCharacter(']', false); // Disallow char ]
return 1;
}
```
## Related Functions
- [IsNickNameCharacterAllowed](IsNickNameCharacterAllowed): Checks if a character is allowed in nickname.
- [IsValidNickName](IsValidNickName): Checks if a nick name is valid.
- [SetPlayerName](SetPlayerName): Sets the name of a player.
- [GetPlayerName](GetPlayerName): Gets the name of a player.
| openmultiplayer/web/docs/scripting/functions/AllowNickNameCharacter.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/AllowNickNameCharacter.md",
"repo_id": "openmultiplayer",
"token_count": 336
} | 277 |
---
title: AttachPlayerObjectToPlayer
description: The same as AttachObjectToPlayer but for objects which were created for player.
tags: ["player", "object", "playerobject"]
---
## Description
The same as [AttachObjectToPlayer](AttachObjectToPlayer) but for objects which were created for player.
| Name | Description |
| --------------- | ------------------------------------------------------------------ |
| playerid | The id of the player which is linked with the object. |
| objectid | The objectid you want to attach to the player. |
| parentid | The id of the player you want to attach to the object. |
| Float:offsetX | The distance between the player and the object in the X direction. |
| Float:offsetY | The distance between the player and the object in the Y direction. |
| Float:offsetZ | The distance between the player and the object in the Z direction. |
| Float:rotationX | The X rotation. |
| Float:rotationY | The Y rotation. |
| Float:rotationZ | The Z rotation. |
## Returns
This function does not return any specific values.
## Examples
```c
new gPlayerObject[MAX_PLAYERS];
public OnPlayerSpawn(playerid)
{
gPlayerObject[playerid] = CreatePlayerObject(playerid, 2587, 2001.195679, 1547.113892, 14.283400, 0.0, 0.0, 96.0);
AttachPlayerObjectToPlayer(playerid, gPlayerObject[playerid], other_playerid, 1.5, 0.5, 0.0, 0.0, 1.5, 2.0);
return 1;
}
```
## Notes
:::warning
This function was removed in SA-MP 0.3.
:::
## Related Functions
- [CreatePlayerObject](CreatePlayerObject): Create an object for only one player.
- [DestroyPlayerObject](DestroyPlayerObject): Destroy a player object.
- [IsValidPlayerObject](IsValidPlayerObject): Checks if a certain player object is vaild.
- [MovePlayerObject](MovePlayerObject): Move a player object.
- [StopPlayerObject](StopPlayerObject): Stop a player object from moving.
- [SetPlayerObjectRot](SetPlayerObjectRot): Set the rotation of a player object.
- [GetPlayerObjectPos](GetPlayerObjectPos): Locate a player object.
- [SetPlayerObjectPos](SetPlayerObjectPos): Set the position of a player object.
- [GetPlayerObjectRot](GetPlayerObjectRot): Check the rotation of a player object.
- [SetPlayerAttachedObject](SetPlayerAttachedObject): Attach an object to a player
- [RemovePlayerAttachedObject](RemovePlayerAttachedObject): Remove an attached object from a player
- [IsPlayerAttachedObjectSlotUsed](IsPlayerAttachedObjectSlotUsed): Check whether an object is attached to a player in a specified index
- [CreateObject](CreateObject): Create an object.
- [DestroyObject](DestroyObject): Destroy an object.
- [IsValidObject](IsValidObject): Checks if a certain object is vaild.
- [MoveObject](MoveObject): Move a object.
- [StopObject](StopObject): Stop an object from moving.
- [SetObjectPos](SetObjectPos): Set the position of an object.
- [SetObjectRot](SetObjectRot): Set the rotation of an object.
- [GetObjectPos](GetObjectPos): Locate an object.
- [GetObjectRot](GetObjectRot): Check the rotation of an object.
- [AttachObjectToPlayer](AttachObjectToPlayer): Attach an object to a player.
| openmultiplayer/web/docs/scripting/functions/AttachPlayerObjectToPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/AttachPlayerObjectToPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 1146
} | 278 |
---
title: ChatTextReplacementToggled
description: Checks if the chat input filtering is enabled or disabled.
tags: []
---
<VersionWarn version='omp v1.1.0.2612' />
## Description
Checks if the chat input filtering is enabled or disabled.
## Returns
true: Enable.
false: Disable.
## Examples
```c
printf("Chat input filter is %s", ChatTextReplacementToggled() ? "Enable" : "Disable");
```
## Related Functions
- [ToggleChatTextReplacement](ToggleChatTextReplacement): Toggles the chat input filter.
| openmultiplayer/web/docs/scripting/functions/ChatTextReplacementToggled.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/ChatTextReplacementToggled.md",
"repo_id": "openmultiplayer",
"token_count": 154
} | 279 |
---
title: CreatePlayerObject
description: Creates an object which will be visible to only one player.
tags: ["player", "object", "playerobject"]
---
## Description
Creates an object which will be visible to only one player.
| Name | Description |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | The ID of the player to create the object for. |
| modelid | The model to create. |
| Float:x | The X coordinate to create the object at. |
| Float:y | The Y coordinate to create the object at. |
| Float:z | The Z coordinate to create the object at. |
| Float:rotationX | The X rotation of the object. |
| Float:rotationY | The Y rotation of the object. |
| Float:rotationZ | The Z rotation of the object. |
| Float:drawDistance | The distance from which objects will appear to players. 0.0 will cause an object to render at its default distance. Leaving this parameter out will cause objects to be rendered at their default distance. |
## Returns
The ID of the object that was created, or INVALID_OBJECT_ID if the object limit (MAX_OBJECTS) was reached.
## Examples
```c
new gPlayerObject[MAX_PLAYERS];
public OnPlayerConnect(playerid)
{
gPlayerObject[playerid] = CreatePlayerObject(playerid, 2587, 2001.195679, 1547.113892, 14.283400, 0.0, 0.0, 96.0);
// Or alternatively, using the DrawDistance parameter to show it from as far away as possible:
gPlayerObject[playerid] = CreatePlayerObject(playerid, 2587, 2001.195679, 1547.113892, 14.283400, 0.0, 0.0, 96.0, 300.0);
return 1;
}
public OnPlayerDisconnect(playerid, reason)
{
DestroyPlayerObject(playerid, gPlayerObject[playerid]);
return 1;
}
```
## Related Functions
- [DestroyPlayerObject](DestroyPlayerObject): Destroy a player object.
- [IsValidPlayerObject](IsValidPlayerObject): Checks if a certain player object is vaild.
- [MovePlayerObject](MovePlayerObject): Move a player object.
- [StopPlayerObject](StopPlayerObject): Stop a player object from moving.
- [SetPlayerObjectPos](SetPlayerObjectPos): Set the position of a player object.
- [SetPlayerObjectRot](SetPlayerObjectRot): Set the rotation of a player object.
- [GetPlayerObjectPos](GetPlayerObjectPos): Locate a player object.
- [GetPlayerObjectRot](GetPlayerObjectRot): Check the rotation of a player object.
- [AttachPlayerObjectToPlayer](AttachPlayerObjectToPlayer): Attach a player object to a player.
- [CreateObject](CreateObject): Create an object.
- [DestroyObject](DestroyObject): Destroy an object.
- [IsValidObject](IsValidObject): Checks if a certain object is vaild.
- [MoveObject](MoveObject): Move an object.
- [StopObject](StopObject): Stop an object from moving.
- [SetObjectPos](SetObjectPos): Set the position of an object.
- [SetObjectRot](SetObjectRot): Set the rotation of an object.
- [GetObjectPos](GetObjectPos): Locate an object.
- [GetObjectRot](GetObjectRot): Check the rotation of an object.
- [AttachObjectToPlayer](AttachObjectToPlayer): Attach an object to a player.
| openmultiplayer/web/docs/scripting/functions/CreatePlayerObject.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/CreatePlayerObject.md",
"repo_id": "openmultiplayer",
"token_count": 2469
} | 280 |
---
title: DisableInteriorEnterExits
description: Disable all the interior entrances and exits in the game (the yellow arrows at doors).
tags: ["interior"]
---
## Description
Disable all the interior entrances and exits in the game (the yellow arrows at doors).
## Examples
```c
public OnGameModeInit()
{
DisableInteriorEnterExits();
return 1;
}
```
## Notes
:::warning
This function will only work if it has been used BEFORE a player connects (it is recommended to use it in [OnGameModeInit](../callbacks/OnGameModeInit)). It will not remove a connected player's markers.
If the gamemode is changed after this function has been used, and the new gamemode doesn't disable markers, the markers will NOT reappear for already-connected players (but will for newly connected players).
:::
:::tip
You can also disable interior entrance markers via [config.json](../../server/config.json)
```json
"use_entry_exit_markers": false,
```
:::
## Related Functions
- [AllowInteriorWeapons](AllowInteriorWeapons): Determine if weapons can be used in interiors.
| openmultiplayer/web/docs/scripting/functions/DisableInteriorEnterExits.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/DisableInteriorEnterExits.md",
"repo_id": "openmultiplayer",
"token_count": 295
} | 281 |
---
title: EnableVehicleFriendlyFire
description: Enable friendly fire for team vehicles.
tags: ["vehicle"]
---
## Description
Enable friendly fire for team vehicles. Players will be unable to damage teammates' vehicles (SetPlayerTeam must be used!).
## Examples
```c
public OnGameModeInit()
{
EnableVehicleFriendlyFire();
return 1;
}
```
## Related Functions
- [SetPlayerTeam](SetPlayerTeam): Set a player's team.
| openmultiplayer/web/docs/scripting/functions/EnableVehicleFriendlyFire.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/EnableVehicleFriendlyFire.md",
"repo_id": "openmultiplayer",
"token_count": 124
} | 282 |
---
title: GangZoneHideForAll
description: GangZoneHideForAll hides a gangzone from all players.
tags: ["gangzone"]
---
## Description
GangZoneHideForAll hides a gangzone from all players.
| Name | Description |
| ------ | ----------------- |
| zoneid | The zone to hide. |
## Returns
This function does not return any specific values.
## Examples
```c
new gGangZoneId;
public OnGameModeInit()
{
gGangZoneId = GangZoneCreate(1248.011, 2072.804, 1439.348, 2204.319);
return 1;
}
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/hidezone", true))
{
GangZoneHideForAll(gGangZoneId);
return 1;
}
return 0;
}
```
## Related Functions
- [GangZoneCreate](GangZoneCreate): Create a gangzone.
- [GangZoneDestroy](GangZoneDestroy): Destroy a gangzone.
- [GangZoneShowForPlayer](GangZoneShowForPlayer): Show a gangzone for a player.
- [GangZoneShowForAll](GangZoneShowForAll): Show a gangzone for all players.
- [GangZoneHideForPlayer](GangZoneHideForPlayer): Hide a gangzone for a player.
- [GangZoneFlashForPlayer](GangZoneFlashForPlayer): Make a gangzone flash for a player.
- [GangZoneFlashForAll](GangZoneFlashForAll): Make a gangzone flash for all players.
- [GangZoneStopFlashForPlayer](GangZoneStopFlashForPlayer): Stop a gangzone flashing for a player.
- [GangZoneStopFlashForAll](GangZoneStopFlashForAll): Stop a gangzone flashing for all players.
| openmultiplayer/web/docs/scripting/functions/GangZoneHideForAll.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/GangZoneHideForAll.md",
"repo_id": "openmultiplayer",
"token_count": 486
} | 283 |
---
title: GetActorHealth
description: Get the health of an actor.
tags: ["actor"]
---
<VersionWarn version='SA-MP 0.3.7' />
## Description
Get the health of an actor.
| Name | Description |
| ------------- | ------------------------------------------------------------------------------- |
| actorid | The ID of the actor to get the health of. |
| &Float:health | A float variable, passed by reference, in to which to store the actor's health. |
## Returns
**true** - success
**false** - failure (i.e. actor is not created).
NOTE: The actor's health is stored in the specified variable, not in the return value.
## Examples
```c
new gMyActor;
public OnGameModeInit()
{
gMyActor = CreateActor(179, 316.1, -134.0, 999.6, 90.0); // Actor as salesperson in Ammunation
SetActorHealth(gMyActor, 100.0);
new Float:actorHealth;
GetActorHealth(gMyActor, actorHealth);
printf("Actor ID %d has %.2f health.", gMyActor, actorHealth);
return 1;
}
```
## Related Functions
- [CreateActor](CreateActor): Create an actor (static NPC).
- [SetActorHealth](SetActorHealth): Set the health of an actor.
- [SetActorInvulnerable](SetActorInvulnerable): Set actor invulnerable.
- [IsActorInvulnerable](IsActorInvulnerable): Check if actor is invulnerable.
| openmultiplayer/web/docs/scripting/functions/GetActorHealth.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/GetActorHealth.md",
"repo_id": "openmultiplayer",
"token_count": 509
} | 284 |
---
title: GetGravity
description: Get the currently global gravity.
tags: []
---
## Description
Get the currently global gravity.
## Examples
**SA-MP server:**
```c
#include <a_samp>
#if !defined GetGravity
native Float:GetGravity();
#endif
public OnGameModeInit()
{
printf("Current gravity: %f", GetGravity());
return 1;
}
```
**open.mp server:**
```c
#include <open.mp>
public OnGameModeInit()
{
printf("Current gravity: %f", GetGravity());
return 1;
}
```
## Notes
:::warning
In SA-MP Server this function is not defined by default. Add 'native Float:GetGravity();' under the inclusion of a_samp.inc to use it.
:::
## Related Functions
- [SetGravity](SetGravity): Set the global gravity.
- [GetPlayerGravity](GetPlayerGravity): Get a player's gravity.
| openmultiplayer/web/docs/scripting/functions/GetGravity.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/GetGravity.md",
"repo_id": "openmultiplayer",
"token_count": 277
} | 285 |
---
title: GetObjectMaterialText
description: Get the material text data from an index of the object.
tags: ["object"]
---
<VersionWarn version='omp v1.1.0.2612' />
## Description
Get the material text data from an index of the object.
| Name | Description |
|-------------------------------------------|-------------------------------------------------------------------------|
| objectid | The ID of the object. |
| materialIndex | The material index on the object. (0 to 15) |
| text[] | An array into which to store the text, passed by reference. |
| textSize | The size of the text. |
| &OBJECT_MATERIAL_SIZE:materialSize | A variable in which to store the materialSize, passed by reference. |
| fontFace[] | An array into which to store the fontFace, passed by reference. |
| fontFaceSize | The size of the fontFace. |
| &fontSize | A variable in which to store the fontSize, passed by reference. |
| &bool:bold | A boolean variable in which to store the bold, passed by reference. |
| &fontColour | A variable in which to store the fontColour, passed by reference. |
| &backgroundColour | A variable in which to store the backgroundColour, passed by reference. |
| &OBJECT_MATERIAL_TEXT_ALIGN:textAlignment | A variable in which to store the textAlignment, passed by reference. |
## Returns
`true` - The function was executed successfully.
`false` - The function failed to execute. The object specified does not exist or an invalid material index is specified.
## Examples
```c
new objectid = CreateObject(19174, 986.42767, -983.14850, 40.95220, 0.00000, 0.00000, 186.00000);
SetObjectMaterialText(objectid, "OPEN.MP", 0, OBJECT_MATERIAL_SIZE_256x128, "Arial", 38, true, 0xFF0000FF, 0x00000000, OBJECT_MATERIAL_TEXT_ALIGN_LEFT);
new
text[16],
OBJECT_MATERIAL_SIZE:materialSize,
fontFace[16],
fontSize,
bool:bold,
fontColour,
backgroundColour,
OBJECT_MATERIAL_TEXT_ALIGN:textAlignment;
GetObjectMaterialText(objectid, 0, text, sizeof(text), materialSize, fontFace, sizeof(fontFace), fontSize, bold, fontColour, backgroundColour, textAlignment);
// text = "OPEN.MP"
// materialSize = OBJECT_MATERIAL_SIZE_256x128
// fontFace = "Arial"
// fontSize = 38
// bold = true
// fontColour = 0xFF0000FF
// backgroundColour = 0x00000000
// textAlignment = OBJECT_MATERIAL_TEXT_ALIGN_LEFT
```
## Related Functions
- [SetObjectMaterial](SetObjectMaterial): Replace the texture of an object with the texture from another model in the game.
- [SetObjectMaterialText](SetObjectMaterialText): Replace the texture of an object with text.
- [IsObjectMaterialSlotUsed](IsObjectMaterialSlotUsed): Checks if a slot of object material is used.
- [GetObjectMaterial](GetObjectMaterial): Get the material data from an index of the object.
- [GetPlayerObjectMaterialText](GetPlayerObjectMaterialText): Get the material text data from an index of the player-object.
| openmultiplayer/web/docs/scripting/functions/GetObjectMaterialText.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/GetObjectMaterialText.md",
"repo_id": "openmultiplayer",
"token_count": 1476
} | 286 |
---
title: GetPickupPos
description: Gets the coordinates of a pickup.
tags: ["pickup"]
---
<VersionWarn version='omp v1.1.0.2612' />
## Description
Gets the coordinates of a pickup.
| Name | Description |
|----------|---------------------------------------------------------------------------|
| pickupid | The ID of the pickup to get the position of. |
| &Float:x | A float variable in which to store the x coordinate, passed by reference. |
| &Float:y | A float variable in which to store the y coordinate, passed by reference. |
| &Float:z | A float variable in which to store the z coordinate, passed by reference. |
## Returns
**true** - The function executed successfully.
**false** - The function failed to execute. The pickup specified doesn't exist.
## Examples
```c
new g_Pickup;
public OnGameModeInit()
{
g_Pickup = CreatePickup(1239, 1, 1686.6160, 1455.4277, 10.7705, -1);
new
Float:x,
Float:y,
Float:z;
GetPickupPos(g_Pickup, x, y, z);
// x = 1686.6160
// y = 1455.4277
// z = 10.7705
return 1;
}
```
## Related Functions
- [CreatePickup](CreatePickup): Create a pickup.
- [AddStaticPickup](AddStaticPickup): Add a static pickup.
- [DestroyPickup](DestroyPickup): Destroy a pickup.
- [IsValidPickup](IsValidPickup): Checks if a pickup is valid.
- [IsPickupStreamedIn](IsPickupStreamedIn): Checks if a pickup is streamed in for a specific player.
- [IsPickupHiddenForPlayer](IsPickupHiddenForPlayer): Checks if a pickup is hidden for a specific player.
- [SetPickupPos](SetPickupPos): Sets the position of a pickup.
- [SetPickupModel](SetPickupModel): Sets the model of a pickup.
- [GetPickupModel](GetPickupModel): Gets the model ID of a pickup.
- [SetPickupType](SetPickupType): Sets the type of a pickup.
- [GetPickupType](GetPickupType): Gets the type of a pickup.
- [SetPickupVirtualWorld](SetPickupVirtualWorld): Sets the virtual world ID of a pickup.
- [GetPickupVirtualWorld](GetPickupVirtualWorld): Gets the virtual world ID of a pickup.
- [ShowPickupForPlayer](ShowPickupForPlayer): Shows a pickup for a specific player.
- [HidePickupForPlayer](HidePickupForPlayer): Hides a pickup for a specific player.
- [SetPickupForPlayer](SetPickupForPlayer): Adjusts the pickup model, type, and position for a specific player.
| openmultiplayer/web/docs/scripting/functions/GetPickupPos.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/GetPickupPos.md",
"repo_id": "openmultiplayer",
"token_count": 819
} | 287 |
---
title: GetPlayerAnimationIndex
description: Returns the index of any running applied animations.
tags: ["player", "animation"]
---
## Description
Returns the index of any running applied animations.
| Name | Description |
| -------- | ---------------------------------------------------------------- |
| playerid | ID of the player of whom you want to get the animation index of. |
## Returns
0 if there is no animation applied.
## Examples
```c
public OnPlayerUpdate(playerid)
{
if (GetPlayerAnimationIndex(playerid))
{
new
animationLibrary[32],
animationName[32],
string[128];
GetAnimationName(GetPlayerAnimationIndex(playerid), animationLibrary, sizeof (animationLibrary), animationName, sizeof (animationName));
format(string, sizeof (string), "Running anim: %s %s", animationLibrary, animationName);
SendClientMessage(playerid, 0xFFFFFFFF, string);
}
return 1;
}
```
## Related Functions
- [ApplyAnimation](ApplyAnimation): Apply an animation to a player.
- [GetAnimationName](GetAnimationName): Get the animation library/name for the index.
| openmultiplayer/web/docs/scripting/functions/GetPlayerAnimationIndex.md/0 | {
"file_path": "openmultiplayer/web/docs/scripting/functions/GetPlayerAnimationIndex.md",
"repo_id": "openmultiplayer",
"token_count": 411
} | 288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.