hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 3,
"code_window": [
"import { unmountComponentAtNode } from 'react-dom';\n",
"import { mount as enzymeMount } from 'enzyme';\n",
"\n",
"// Generate an enhanced mount function.\n",
"export default function createMount(options: Object = {}) {\n",
" const { mount = enzymeMount } = options;\n",
"\n",
" const attachTo = window.document.createElement('div');\n",
" attachTo.className = 'app';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default function createMount(options1: Object = {}) {\n",
" const { mount = enzymeMount, ...other1 } = options1;\n"
],
"file_path": "src/test-utils/createMount.js",
"type": "replace",
"edit_start_line_idx": 6
} | <!--- This documentation is automatically generated, do not try to edit it. -->
---
filename: /src/Chip/Chip.js
---
# Chip
Chips represent complex entities in small blocks, such as a contact.
## Props
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| avatar | Element | | Avatar element. |
| classes | Object | | Useful to extend the style applied to components. |
| deleteIcon | Element | | Custom delete icon. Will be shown only if `onRequestDelete` is set. |
| label | union: string<br> Element<any><br> | | The content of the label. |
| onRequestDelete | signature | | Callback function fired when the delete icon is clicked. If set, the delete icon will be shown. |
Any other properties supplied will be [spread to the root element](/customization/api#spread).
## CSS API
You can override all the class names injected by Material-UI thanks to the `classes` property.
This property accepts the following keys:
- `root`
- `clickable`
- `deletable`
- `avatar`
- `avatarChildren`
- `label`
- `deleteIcon`
Have a look at [overriding with classes](/customization/overrides#overriding-with-classes) section
and the [implementation of the component](https://github.com/callemall/material-ui/tree/v1-beta/src/Chip/Chip.js)
for more detail.
If using the `overrides` key of the theme as documented
[here](/customization/themes#customizing-all-instances-of-a-component-type),
you need to use the following style sheet name: `MuiChip`.
## Demos
- [Chips](/demos/chips)
| pages/api/chip.md | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017095213115680963,
0.00016732361109461635,
0.0001620291150175035,
0.00016648854943923652,
0.0000033072446967707947
]
|
{
"id": 3,
"code_window": [
"import { unmountComponentAtNode } from 'react-dom';\n",
"import { mount as enzymeMount } from 'enzyme';\n",
"\n",
"// Generate an enhanced mount function.\n",
"export default function createMount(options: Object = {}) {\n",
" const { mount = enzymeMount } = options;\n",
"\n",
" const attachTo = window.document.createElement('div');\n",
" attachTo.className = 'app';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default function createMount(options1: Object = {}) {\n",
" const { mount = enzymeMount, ...other1 } = options1;\n"
],
"file_path": "src/test-utils/createMount.js",
"type": "replace",
"edit_start_line_idx": 6
} | // @flow
import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './avatar.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
| pages/api/avatar.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017183742602355778,
0.0001702634326647967,
0.0001686894247541204,
0.0001702634326647967,
0.0000015740006347186863
]
|
{
"id": 4,
"code_window": [
" ) {\n",
" return mount(node, {\n",
" attachTo,\n",
" ...options2,\n",
" });\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...other1,\n"
],
"file_path": "src/test-utils/createMount.js",
"type": "add",
"edit_start_line_idx": 20
} | # Installation
Material-UI is available as an [npm package](https://www.npmjs.org/package/material-ui).
## npm
To install and save in your `package.json` dependencies, run:
```
npm install material-ui@next
```
## Roboto Font
Material-UI was designed with the [Roboto](http://www.google.com/fonts/specimen/Roboto)
font in mind. So be sure to follow [these instructions](/style/typography#general).
## Icon Font
In order to use the font `Icon` component, or to use icon names (ligatures) directly in components
that support them, you must first add the [Material icons](https://material.io/icons/) font.
Here are [some instructions](http://google.github.io/material-design-icons/#icon-font-for-the-web)
on how to do so.
## SVG Icons
In order to use prebuilt SVG Material icons, such as those found in the [component demos](/component-demos)
you must first install the [material-ui-icons](https://www.npmjs.org/package/material-ui-icons) package:
```
npm install material-ui-icons
```
This package replaces the `svg-icons` previously included with Material-UI.
| docs/src/pages/getting-started/installation.md | 1 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00016907363897189498,
0.00016774791583884507,
0.00016643234994262457,
0.00016774282266851515,
9.539423899695976e-7
]
|
{
"id": 4,
"code_window": [
" ) {\n",
" return mount(node, {\n",
" attachTo,\n",
" ...options2,\n",
" });\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...other1,\n"
],
"file_path": "src/test-utils/createMount.js",
"type": "add",
"edit_start_line_idx": 20
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon;
let FileUpload = props =>
<SvgIconCustom {...props}>
<path d="M9 16h6v-6h4l-7-7-7 7h4zm-4 2h14v2H5z" />
</SvgIconCustom>;
FileUpload = pure(FileUpload);
FileUpload.muiName = 'SvgIcon';
export default FileUpload;
| packages/material-ui-icons/src/FileUpload.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017178794951178133,
0.00017107526946347207,
0.0001703625894151628,
0.00017107526946347207,
7.126800483092666e-7
]
|
{
"id": 4,
"code_window": [
" ) {\n",
" return mount(node, {\n",
" attachTo,\n",
" ...options2,\n",
" });\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...other1,\n"
],
"file_path": "src/test-utils/createMount.js",
"type": "add",
"edit_start_line_idx": 20
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon;
let ExpandMore = props =>
<SvgIconCustom {...props}>
<path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z" />
</SvgIconCustom>;
ExpandMore = pure(ExpandMore);
ExpandMore.muiName = 'SvgIcon';
export default ExpandMore;
| packages/material-ui-icons/src/ExpandMore.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017191313963849097,
0.00017015976482070982,
0.0001684064045548439,
0.00017015976482070982,
0.0000017533675418235362
]
|
{
"id": 4,
"code_window": [
" ) {\n",
" return mount(node, {\n",
" attachTo,\n",
" ...options2,\n",
" });\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...other1,\n"
],
"file_path": "src/test-utils/createMount.js",
"type": "add",
"edit_start_line_idx": 20
} | export { default as FormGroup } from './FormGroup';
export * from './FormGroup';
export { default as FormLabel } from './FormLabel';
export * from './FormLabel';
export { default as FormControl } from './FormControl';
export * from './FormControl';
export { default as FormHelperText } from './FormHelperText';
export * from './FormHelperText';
export { default as FormControlLabel } from './FormControlLabel';
export * from './FormControlLabel';
| src/Form/index.d.ts | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017862929962575436,
0.0001739065337460488,
0.0001691837824182585,
0.0001739065337460488,
0.000004722758603747934
]
|
{
"id": 5,
"code_window": [
"\n",
"import { shallow as enzymeShallow } from 'enzyme';\n",
"import until from './until';\n",
"\n",
"// Generate an enhanced shallow function.\n",
"export default function createShallow(options: Object = {}) {\n",
" const { shallow = enzymeShallow, context, dive = false, untilSelector = false } = options;\n",
"\n",
" const shallowWithContext = function shallowWithContext(\n",
" node: React$Element<any>,\n",
" options2: Object = {},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default function createShallow(options1: Object = {}) {\n",
" const { shallow = enzymeShallow, dive = false, untilSelector = false, ...other1 } = options1;\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 6
} | // @flow
// @inheritedComponent TableRow
import React from 'react';
import type { Node } from 'react';
import withStyles from '../styles/withStyles';
import IconButton from '../IconButton';
import Input from '../Input';
import { MenuItem } from '../Menu';
import Select from '../Select';
import TableCell from './TableCell';
import TableRow from './TableRow';
import Toolbar from '../Toolbar';
import Typography from '../Typography';
import KeyboardArrowLeft from '../svg-icons/KeyboardArrowLeft';
import KeyboardArrowRight from '../svg-icons/KeyboardArrowRight';
export const styles = (theme: Object) => ({
cell: {
// Increase the specificity to override TableCell.
'&:last-child': {
padding: '0',
},
},
toolbar: {
height: 56,
minHeight: 56,
paddingRight: 2,
},
spacer: {
flex: '1 1 100%',
},
select: {
marginLeft: theme.spacing.unit,
width: 34,
textAlign: 'right',
paddingRight: 22,
color: theme.palette.text.secondary,
height: 32,
lineHeight: '32px',
},
selectRoot: {
marginRight: theme.spacing.unit * 4,
},
actions: {
color: theme.palette.text.secondary,
marginLeft: theme.spacing.unit * 2.5,
},
});
export type LabelDisplayedRowsArgs = {
from: number,
to: number,
count: number,
page: number,
};
type ProvidedProps = {
classes: Object,
labelRowsPerPage: string,
labelDisplayedRows: (paginationInfo: LabelDisplayedRowsArgs) => string,
rowsPerPageOptions: number[],
};
export type Props = {
/**
* Useful to extend the style applied to components.
*/
classes?: Object,
/**
* @ignore
*/
className?: string,
/**
* The total number of rows.
*/
count: number,
/**
* Useful to customize the displayed rows label.
*/
labelDisplayedRows?: (paginationInfo: LabelDisplayedRowsArgs) => Node,
/**
* Useful to customize the rows per page label. Invoked with a `{ from, to, count, page }`
* object.
*/
labelRowsPerPage?: Node,
/**
* Callback fired when the page is changed. Invoked with two arguments: the event and the
* page to show.
*/
onChangePage: (event: SyntheticInputEvent<> | null, page: number) => void,
/**
* Callback fired when the number of rows per page is changed. Invoked with two arguments: the
* event.
*/
onChangeRowsPerPage: (event: SyntheticInputEvent<>) => void,
/**
* The zero-based index of the current page.
*/
page: number,
/**
* The number of rows per page.
*/
rowsPerPage: number,
/**
* Customizes the options of the rows per page select field.
*/
rowsPerPageOptions?: number[],
};
/**
* A `TableRow` based component for placing inside `TableFooter` for pagination.
*/
class TablePagination extends React.Component<ProvidedProps & Props> {
static defaultProps = {
labelRowsPerPage: 'Rows per page:',
labelDisplayedRows: ({ from, to, count }) => `${from}-${to} of ${count}`,
rowsPerPageOptions: [5, 10, 25],
};
componentWillReceiveProps({ count, onChangePage, rowsPerPage }) {
const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1);
if (this.props.page > newLastPage) {
onChangePage(null, newLastPage);
}
}
handleBackButtonClick = event => {
this.props.onChangePage(event, this.props.page - 1);
};
handleNextButtonClick = event => {
this.props.onChangePage(event, this.props.page + 1);
};
render() {
const {
classes,
className,
count,
labelDisplayedRows,
labelRowsPerPage,
onChangePage,
onChangeRowsPerPage,
page,
rowsPerPage,
rowsPerPageOptions,
...other
} = this.props;
return (
<TableRow className={className} {...other}>
<TableCell
className={classes.cell}
colSpan={9001} // col-span over everything
>
<Toolbar className={classes.toolbar}>
<div className={classes.spacer} />
<Typography type="caption">{labelRowsPerPage}</Typography>
<Select
classes={{ root: classes.selectRoot, select: classes.select }}
input={<Input disableUnderline />}
value={rowsPerPage}
onChange={onChangeRowsPerPage}
>
{rowsPerPageOptions.map(rowsPerPageOption => (
<MenuItem key={rowsPerPageOption} value={rowsPerPageOption}>
{rowsPerPageOption}
</MenuItem>
))}
</Select>
<Typography type="caption">
{labelDisplayedRows({
from: count === 0 ? 0 : page * rowsPerPage + 1,
to: Math.min(count, (page + 1) * rowsPerPage),
count,
page,
})}
</Typography>
<div className={classes.actions}>
<IconButton onClick={this.handleBackButtonClick} disabled={page === 0}>
<KeyboardArrowLeft />
</IconButton>
<IconButton
onClick={this.handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
>
<KeyboardArrowRight />
</IconButton>
</div>
</Toolbar>
</TableCell>
</TableRow>
);
}
}
export default withStyles(styles, { name: 'MuiTablePagination' })(TablePagination);
| src/Table/TablePagination.js | 1 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.0018654881278052926,
0.0002596421691123396,
0.00016514919116161764,
0.0001744679466355592,
0.0003684709081426263
]
|
{
"id": 5,
"code_window": [
"\n",
"import { shallow as enzymeShallow } from 'enzyme';\n",
"import until from './until';\n",
"\n",
"// Generate an enhanced shallow function.\n",
"export default function createShallow(options: Object = {}) {\n",
" const { shallow = enzymeShallow, context, dive = false, untilSelector = false } = options;\n",
"\n",
" const shallowWithContext = function shallowWithContext(\n",
" node: React$Element<any>,\n",
" options2: Object = {},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default function createShallow(options1: Object = {}) {\n",
" const { shallow = enzymeShallow, dive = false, untilSelector = false, ...other1 } = options1;\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 6
} | // flow-typed signature: 2b6b2a1fdf337b9e3981e2badf2331af
// flow-typed version: <<STUB>>/@types/react_v^16.0.5/flow_v0.55.0
/**
* This is an autogenerated libdef stub for:
*
* '@types/react'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module '@types/react' {
declare module.exports: any;
}
| flow-typed/npm/@types/react_vx.x.x.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00016470604168716818,
0.0001634498912608251,
0.00016219374083448201,
0.0001634498912608251,
0.0000012561504263430834
]
|
{
"id": 5,
"code_window": [
"\n",
"import { shallow as enzymeShallow } from 'enzyme';\n",
"import until from './until';\n",
"\n",
"// Generate an enhanced shallow function.\n",
"export default function createShallow(options: Object = {}) {\n",
" const { shallow = enzymeShallow, context, dive = false, untilSelector = false } = options;\n",
"\n",
" const shallowWithContext = function shallowWithContext(\n",
" node: React$Element<any>,\n",
" options2: Object = {},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default function createShallow(options1: Object = {}) {\n",
" const { shallow = enzymeShallow, dive = false, untilSelector = false, ...other1 } = options1;\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 6
} | const pathConversion = {
'app-bar': 'AppBar',
'auto-complete': 'AutoComplete',
avatar: 'Avatar',
badge: 'Badge',
'flat-button': 'FlatButton',
'raised-button': 'RaisedButton',
'floating-action-button': 'FloatingActionButton',
'icon-button': 'IconButton',
'card/card': 'Card/Card',
'card/card-actions': 'Card/CardActions',
'card/card-header': 'Card/CardHeader',
'card/card-media': 'Card/CardMedia',
'card/card-title': 'Card/CardTitle',
'card/card-text': 'Card/CardText',
'date-picker/date-picker': 'DatePicker',
dialog: 'Dialog',
divider: 'Divider',
'grid-list/grid-list': 'GridList/GridList',
'grid-list/grid-tile': 'GridList/GridTile',
'font-icon': 'FontIcon',
'svg-icon': 'SvgIcon',
'left-nav': 'Drawer',
'lists/list': 'List/List',
'lists/list-item': 'List/ListItem',
'menus/menu': 'Menu',
'menus/menu-item': 'MenuItem',
'menus/icon-menu': 'IconMenu',
paper: 'Paper',
'popover/popover': 'Popover',
'circular-progress': 'CircularProgress',
'linear-progress': 'LinearProgress',
'refresh-indicator': 'RefreshIndicator',
'select-field': 'SelectField',
slider: 'Slider',
checkbox: 'Checkbox',
'radio-button': 'RadioButton',
'radio-button-group': 'RadioButton/RadioButtonGroup',
toggle: 'Toggle',
snackbar: 'Snackbar',
'table/table': 'Table/Table',
'table/table-header-column': 'Table/TableHeaderColumn',
'table/table-row': 'Table/TableRow',
'table/table-header': 'Table/TableHeader',
'table/table-row-column': 'Table/TableRowColumn',
'table/table-body': 'Table/TableBody',
'table/table-footer': 'Table/TableFooter',
'tabs/tab': 'Tabs/Tab',
'tabs/tabs': 'Tabs/Tabs',
'text-field': 'TextField',
'time-picker/time-picker': 'TimePicker',
'toolbar/toolbar': 'Toolbar/Toolbar',
'toolbar/toolbar-group': 'Toolbar/ToolbarGroup',
'toolbar/toolbar-separator': 'Toolbar/ToolbarSeparator',
'toolbar/toolbar-title': 'Toolbar/ToolbarTitle',
MuiThemeProvider: 'styles/MuiThemeProvider',
};
const pathBaseSource = ['material-ui/src/', 'material-ui/src/'];
const pathBasePackage = ['material-ui/lib/', 'material-ui/'];
function getPathsBase(path) {
if (path.indexOf(pathBaseSource[0]) === 0) {
return pathBaseSource;
} else if (path.indexOf(pathBasePackage[0]) === 0) {
return pathBasePackage;
}
return new Error('Wrong path');
}
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.ImportDeclaration)
.filter(path => {
// Only consider Material-UI imports
return path.value.source.value.indexOf('material-ui/') === 0;
})
.replaceWith(path => {
const pathOld = path.value.source.value;
const pathsBase = getPathsBase(pathOld);
const pathSuffix = pathOld.substring(pathsBase[0].length);
let pathNew;
if (pathConversion[pathSuffix]) {
pathNew = pathsBase[1] + pathConversion[pathSuffix];
} else {
pathNew = pathsBase[1] + pathSuffix;
}
return j.importDeclaration(path.node.specifiers, j.literal(pathNew));
})
.toSource({
quote: 'single',
});
}
| packages/material-ui-codemod/src/v0.15.0/import-path.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017712608678266406,
0.0001736319827614352,
0.00016799566219560802,
0.0001748096547089517,
0.000003182252157785115
]
|
{
"id": 5,
"code_window": [
"\n",
"import { shallow as enzymeShallow } from 'enzyme';\n",
"import until from './until';\n",
"\n",
"// Generate an enhanced shallow function.\n",
"export default function createShallow(options: Object = {}) {\n",
" const { shallow = enzymeShallow, context, dive = false, untilSelector = false } = options;\n",
"\n",
" const shallowWithContext = function shallowWithContext(\n",
" node: React$Element<any>,\n",
" options2: Object = {},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default function createShallow(options1: Object = {}) {\n",
" const { shallow = enzymeShallow, dive = false, untilSelector = false, ...other1 } = options1;\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 6
} | // @flow
import React from 'react';
import { assert } from 'chai';
import { createShallow, getClasses } from '../test-utils';
import DialogActions from './DialogActions';
describe('<DialogActions />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallow({ dive: true });
classes = getClasses(<DialogActions />);
});
it('should render a div', () => {
const wrapper = shallow(<DialogActions />);
assert.strictEqual(wrapper.name(), 'div');
});
it('should spread custom props on the root node', () => {
const wrapper = shallow(<DialogActions data-my-prop="woofDialogActions" />);
assert.strictEqual(
wrapper.prop('data-my-prop'),
'woofDialogActions',
'custom prop should be woofDialogActions',
);
});
it('should render with the user and root classes', () => {
const wrapper = shallow(<DialogActions className="woofDialogActions" />);
assert.strictEqual(wrapper.hasClass('woofDialogActions'), true);
assert.strictEqual(wrapper.hasClass(classes.root), true);
});
it('should render children with the button class wrapped in a div with the action class', () => {
const wrapper = shallow(
<DialogActions>
<button className="woofDialogActions">Hello</button>
</DialogActions>,
);
const container = wrapper.childAt(0);
assert.strictEqual(container.hasClass(classes.action), true, 'should have the action wrapper');
assert.strictEqual(container.is('div'), true, 'should be a div');
const button = container.childAt(0);
assert.strictEqual(button.is('button'), true, 'should be a button');
assert.strictEqual(button.hasClass('woofDialogActions'), true, 'should have the user class');
assert.strictEqual(button.hasClass(classes.button), true, 'should have the button class');
});
it('should render children with the conditional buttons', () => {
const showButton = true;
const wrapper = shallow(
<DialogActions>
{showButton ? <button className="woofDialogActions">Hello</button> : null}
{!showButton ? <button>false button</button> : null}
</DialogActions>,
);
const container = wrapper.childAt(0);
assert.strictEqual(container.hasClass(classes.action), true, 'should have the action wrapper');
assert.strictEqual(container.is('div'), true, 'should be a div');
const button = container.childAt(0);
assert.strictEqual(button.is('button'), true, 'should be a button');
assert.strictEqual(button.hasClass('woofDialogActions'), true, 'should have the user class');
assert.strictEqual(button.hasClass(classes.button), true, 'should have the button class');
});
});
| src/Dialog/DialogActions.spec.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.9991647005081177,
0.6945853233337402,
0.00017453086911700666,
0.9712340831756592,
0.4401361048221588
]
|
{
"id": 6,
"code_window": [
" node: React$Element<any>,\n",
" options2: Object = {},\n",
" ) {\n",
" const { context: context2, ...other } = options2;\n",
"\n",
" const wrapper = shallow(node, {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 13
} | // @flow weak
import { shallow as enzymeShallow } from 'enzyme';
import until from './until';
// Generate an enhanced shallow function.
export default function createShallow(options: Object = {}) {
const { shallow = enzymeShallow, context, dive = false, untilSelector = false } = options;
const shallowWithContext = function shallowWithContext(
node: React$Element<any>,
options2: Object = {},
) {
const { context: context2, ...other } = options2;
const wrapper = shallow(node, {
...other,
context: {
...context,
...context2,
},
});
if (dive) {
return wrapper.dive();
}
if (untilSelector) {
return until.call(wrapper, untilSelector);
}
return wrapper;
};
return shallowWithContext;
}
| src/test-utils/createShallow.js | 1 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.9983525276184082,
0.7224384546279907,
0.0030612419359385967,
0.9441699981689453,
0.4176131784915924
]
|
{
"id": 6,
"code_window": [
" node: React$Element<any>,\n",
" options2: Object = {},\n",
" ) {\n",
" const { context: context2, ...other } = options2;\n",
"\n",
" const wrapper = shallow(node, {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 13
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon;
let LightbulbOutline = props =>
<SvgIconCustom {...props}>
<path d="M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9v1zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7zm2.85 11.1l-.85.6V16h-4v-2.3l-.85-.6C7.8 12.16 7 10.63 7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 1.63-.8 3.16-2.15 4.1z" />
</SvgIconCustom>;
LightbulbOutline = pure(LightbulbOutline);
LightbulbOutline.muiName = 'SvgIcon';
export default LightbulbOutline;
| packages/material-ui-icons/src/LightbulbOutline.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00019377717399038374,
0.0001793979317881167,
0.00016501868958584964,
0.0001793979317881167,
0.00001437924220226705
]
|
{
"id": 6,
"code_window": [
" node: React$Element<any>,\n",
" options2: Object = {},\n",
" ) {\n",
" const { context: context2, ...other } = options2;\n",
"\n",
" const wrapper = shallow(node, {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 13
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon;
let SettingsInputHdmi = props =>
<SvgIconCustom {...props}>
<path d="M18 7V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v3H5v6l3 6v3h8v-3l3-6V7h-1zM8 4h8v3h-2V5h-1v2h-2V5h-1v2H8V4z" />
</SvgIconCustom>;
SettingsInputHdmi = pure(SettingsInputHdmi);
SettingsInputHdmi.muiName = 'SvgIcon';
export default SettingsInputHdmi;
| packages/material-ui-icons/src/SettingsInputHdmi.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017183840100187808,
0.000170368846738711,
0.00016889929247554392,
0.000170368846738711,
0.0000014695542631670833
]
|
{
"id": 6,
"code_window": [
" node: React$Element<any>,\n",
" options2: Object = {},\n",
" ) {\n",
" const { context: context2, ...other } = options2;\n",
"\n",
" const wrapper = shallow(node, {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 13
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon;
let CameraEnhance = props =>
<SvgIconCustom {...props}>
<path d="M9 3L7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2h-3.17L15 3H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-1l1.25-2.75L16 13l-2.75-1.25L12 9l-1.25 2.75L8 13l2.75 1.25z" />
</SvgIconCustom>;
CameraEnhance = pure(CameraEnhance);
CameraEnhance.muiName = 'SvgIcon';
export default CameraEnhance;
| packages/material-ui-icons/src/CameraEnhance.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017691290122456849,
0.00017149841005448252,
0.00016608391888439655,
0.00017149841005448252,
0.000005414491170085967
]
|
{
"id": 7,
"code_window": [
" const wrapper = shallow(node, {\n",
" ...other,\n",
" context: {\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" ...other1,\n",
" ...options2,\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 16
} | // @flow weak
import { shallow as enzymeShallow } from 'enzyme';
import until from './until';
// Generate an enhanced shallow function.
export default function createShallow(options: Object = {}) {
const { shallow = enzymeShallow, context, dive = false, untilSelector = false } = options;
const shallowWithContext = function shallowWithContext(
node: React$Element<any>,
options2: Object = {},
) {
const { context: context2, ...other } = options2;
const wrapper = shallow(node, {
...other,
context: {
...context,
...context2,
},
});
if (dive) {
return wrapper.dive();
}
if (untilSelector) {
return until.call(wrapper, untilSelector);
}
return wrapper;
};
return shallowWithContext;
}
| src/test-utils/createShallow.js | 1 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.9976319074630737,
0.7469776272773743,
0.0023109049070626497,
0.9939838647842407,
0.4299382269382477
]
|
{
"id": 7,
"code_window": [
" const wrapper = shallow(node, {\n",
" ...other,\n",
" context: {\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" ...other1,\n",
" ...options2,\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 16
} | import { Theme } from './createMuiTheme';
export default function withTheme<P = {}, T extends Theme = Theme>(
component: React.ComponentType<P & { theme: T }>
): React.ComponentClass<P>;
| src/styles/withTheme.d.ts | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00017225607007276267,
0.00017225607007276267,
0.00017225607007276267,
0.00017225607007276267,
0
]
|
{
"id": 7,
"code_window": [
" const wrapper = shallow(node, {\n",
" ...other,\n",
" context: {\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" ...other1,\n",
" ...options2,\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 16
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon;
let Replay30 = props =>
<SvgIconCustom {...props}>
<path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-2.4 8.5h.4c.2 0 .4-.1.5-.2s.2-.2.2-.4v-.2s-.1-.1-.1-.2-.1-.1-.2-.1h-.5s-.1.1-.2.1-.1.1-.1.2v.2h-1c0-.2 0-.3.1-.5s.2-.3.3-.4.3-.2.4-.2.4-.1.5-.1c.2 0 .4 0 .6.1s.3.1.5.2.2.2.3.4.1.3.1.5v.3s-.1.2-.1.3-.1.2-.2.2-.2.1-.3.2c.2.1.4.2.5.4s.2.4.2.6c0 .2 0 .4-.1.5s-.2.3-.3.4-.3.2-.5.2-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.4-.1-.6h.8v.2s.1.1.1.2.1.1.2.1h.5s.1-.1.2-.1.1-.1.1-.2v-.5s-.1-.1-.1-.2-.1-.1-.2-.1h-.6v-.7zm5.7.7c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5c0-.1-.1-.2-.1-.3s-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z" />
</SvgIconCustom>;
Replay30 = pure(Replay30);
Replay30.muiName = 'SvgIcon';
export default Replay30;
| packages/material-ui-icons/src/Replay30.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.0030990703962743282,
0.0016373267862945795,
0.00017558310355525464,
0.0016373267862945795,
0.0014617436099797487
]
|
{
"id": 7,
"code_window": [
" const wrapper = shallow(node, {\n",
" ...other,\n",
" context: {\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" ...other1,\n",
" ...options2,\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 16
} | // @flow
export default {
// All components align to an 8dp square baseline grid for mobile, tablet, and desktop.
// https://material.io/guidelines/layout/metrics-keylines.html#metrics-keylines-baseline-grids
unit: 8,
};
| src/styles/spacing.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.00016905074880924076,
0.00016905074880924076,
0.00016905074880924076,
0.00016905074880924076,
0
]
|
{
"id": 8,
"code_window": [
" context: {\n",
" ...context,\n",
" ...context2,\n",
" },\n",
" });\n",
"\n",
" if (dive) {\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...other1.context,\n",
" ...options2.context,\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 18
} | // @flow weak
import { shallow as enzymeShallow } from 'enzyme';
import until from './until';
// Generate an enhanced shallow function.
export default function createShallow(options: Object = {}) {
const { shallow = enzymeShallow, context, dive = false, untilSelector = false } = options;
const shallowWithContext = function shallowWithContext(
node: React$Element<any>,
options2: Object = {},
) {
const { context: context2, ...other } = options2;
const wrapper = shallow(node, {
...other,
context: {
...context,
...context2,
},
});
if (dive) {
return wrapper.dive();
}
if (untilSelector) {
return until.call(wrapper, untilSelector);
}
return wrapper;
};
return shallowWithContext;
}
| src/test-utils/createShallow.js | 1 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.25072598457336426,
0.06441406160593033,
0.00016627722652629018,
0.0033819950185716152,
0.10757569968700409
]
|
{
"id": 8,
"code_window": [
" context: {\n",
" ...context,\n",
" ...context2,\n",
" },\n",
" });\n",
"\n",
" if (dive) {\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...other1.context,\n",
" ...options2.context,\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 18
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon;
let ChildCare = props =>
<SvgIconCustom {...props}>
<circle cx="14.5" cy="10.5" r="1.25" /><circle cx="9.5" cy="10.5" r="1.25" /><path d="M22.94 12.66c.04-.21.06-.43.06-.66s-.02-.45-.06-.66c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66s.02.45.06.66c.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2zM7.5 14c.76 1.77 2.49 3 4.5 3s3.74-1.23 4.5-3h-9z" />
</SvgIconCustom>;
ChildCare = pure(ChildCare);
ChildCare.muiName = 'SvgIcon';
export default ChildCare;
| packages/material-ui-icons/src/ChildCare.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.0005235318676568568,
0.00034749071346595883,
0.00017144954472314566,
0.00034749071346595883,
0.00017604116874281317
]
|
{
"id": 8,
"code_window": [
" context: {\n",
" ...context,\n",
" ...context2,\n",
" },\n",
" });\n",
"\n",
" if (dive) {\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...other1.context,\n",
" ...options2.context,\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 18
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon;
let SignalCellularOff = props =>
<SvgIconCustom {...props}>
<path d="M21 1l-8.59 8.59L21 18.18V1zM4.77 4.5L3.5 5.77l6.36 6.36L1 21h17.73l2 2L22 21.73 4.77 4.5z" />
</SvgIconCustom>;
SignalCellularOff = pure(SignalCellularOff);
SignalCellularOff.muiName = 'SvgIcon';
export default SignalCellularOff;
| packages/material-ui-icons/src/SignalCellularOff.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.0002027024602284655,
0.00018590845866128802,
0.00016911444254219532,
0.00018590845866128802,
0.00001679400884313509
]
|
{
"id": 8,
"code_window": [
" context: {\n",
" ...context,\n",
" ...context2,\n",
" },\n",
" });\n",
"\n",
" if (dive) {\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...other1.context,\n",
" ...options2.context,\n"
],
"file_path": "src/test-utils/createShallow.js",
"type": "replace",
"edit_start_line_idx": 18
} | // @flow
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import compose from 'recompose/compose';
import NProgress from 'nprogress';
import Router from 'next/router';
import { withStyles } from 'material-ui/styles';
import Typography from 'material-ui/Typography';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui-icons/Menu';
import LightbulbOutline from 'material-ui-icons/LightbulbOutline';
import Github from 'docs/src/modules/components/GitHub';
import AppDrawer from 'docs/src/modules/components/AppDrawer';
import AppSearch from 'docs/src/modules/components/AppSearch';
import Tooltip from 'material-ui/Tooltip';
import { pageToTitle } from 'docs/src/modules/utils/helpers';
// Disaply a progress bar between route transitions
NProgress.configure({
template: `
<div class="bar" role="bar">
<dt></dt>
<dd></dd>
</div>
`,
});
Router.onRouteChangeStart = () => {
NProgress.start();
};
Router.onRouteChangeComplete = () => {
NProgress.done();
};
Router.onRouteChangeError = () => {
NProgress.done();
};
const styles = theme => ({
'@global': {
html: {
background: theme.palette.background.default,
WebkitFontSmoothing: 'antialiased', // Antialiasing.
MozOsxFontSmoothing: 'grayscale', // Antialiasing.
boxSizing: 'border-box',
},
'*, *:before, *:after': {
boxSizing: 'inherit',
},
body: {
margin: 0,
},
'#nprogress': {
pointerEvents: 'none',
'& .bar': {
position: 'fixed',
background:
theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white,
borderRadius: 1,
zIndex: theme.zIndex.tooltip,
top: 0,
left: 0,
width: '100%',
height: 2,
},
'& dd, & dt': {
position: 'absolute',
top: 0,
height: 2,
boxShadow: `${theme.palette.type === 'light'
? theme.palette.common.black
: theme.palette.common.white} 1px 0 6px 1px`,
borderRadius: '100%',
animation: 'nprogress-pulse 2s ease-out 0s infinite',
},
'& dd': {
opacity: 0.6,
width: 20,
right: 0,
clip: 'rect(-6px,22px,14px,10px)',
},
'& dt': {
opacity: 0.6,
width: 180,
right: -80,
clip: 'rect(-6px,90px,14px,-6px)',
},
},
'@keyframes nprogress-pulse': {
'30%': {
opacity: 0.6,
},
'60%': {
opacity: 0,
},
to: {
opacity: 0.6,
},
},
},
root: {
display: 'flex',
alignItems: 'stretch',
minHeight: '100vh',
width: '100%',
},
grow: {
flex: '1 1 auto',
},
title: {
marginLeft: 24,
flex: '0 1 auto',
},
appBar: {
transition: theme.transitions.create('width'),
},
appBarHome: {
boxShadow: 'none',
},
appBarShift: {
[theme.breakpoints.up('lg')]: {
width: 'calc(100% - 250px)',
},
},
drawer: {
[theme.breakpoints.up('lg')]: {
width: 250,
},
},
navIconHide: {
[theme.breakpoints.up('lg')]: {
display: 'none',
},
},
});
class AppFrame extends React.Component<any, any> {
state = {
mobileOpen: false,
};
handleDrawerToggle = () => {
this.setState({ mobileOpen: !this.state.mobileOpen });
};
handleToggleShade = () => {
this.props.dispatch({ type: 'TOGGLE_THEME_SHADE' });
};
render() {
const { children, classes } = this.props;
const title =
this.context.activePage.title !== false ? pageToTitle(this.context.activePage) : null;
let disablePermanent = false;
let navIconClassName = '';
let appBarClassName = classes.appBar;
if (title === null) {
// home route, don't shift app bar or dock drawer
disablePermanent = true;
appBarClassName += ` ${classes.appBarHome}`;
} else {
navIconClassName = classes.navIconHide;
appBarClassName += ` ${classes.appBarShift}`;
}
return (
<div className={classes.root}>
<AppBar className={appBarClassName}>
<Toolbar>
<IconButton
color="contrast"
aria-label="open drawer"
onClick={this.handleDrawerToggle}
className={navIconClassName}
>
<MenuIcon />
</IconButton>
{title !== null && (
<Typography className={classes.title} type="title" color="inherit" noWrap>
{title}
</Typography>
)}
<div className={classes.grow} />
<AppSearch />
<Tooltip title="Toggle light/dark theme" enterDelay={300}>
<IconButton
color="contrast"
aria-label="change theme"
onClick={this.handleToggleShade}
>
<LightbulbOutline />
</IconButton>
</Tooltip>
<IconButton
component="a"
title="GitHub"
color="contrast"
href="https://github.com/callemall/material-ui/tree/v1-beta"
>
<Github />
</IconButton>
</Toolbar>
</AppBar>
<AppDrawer
className={classes.drawer}
disablePermanent={disablePermanent}
onRequestClose={this.handleDrawerToggle}
mobileOpen={this.state.mobileOpen}
/>
{children}
</div>
);
}
}
AppFrame.propTypes = {
children: PropTypes.node.isRequired,
classes: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
};
AppFrame.contextTypes = {
activePage: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}),
};
export default compose(
withStyles(styles, {
name: 'AppFrame',
}),
connect(),
)(AppFrame);
| docs/src/modules/components/AppFrame.js | 0 | https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816 | [
0.0023481447715312243,
0.0002593001117929816,
0.00016305202734656632,
0.00017257618310395628,
0.000426397193223238
]
|
{
"id": 0,
"code_window": [
" }\n",
" // Redirect all other pages to the login.\n",
" return redirect(req, res, \"login\", {\n",
" to: req.path,\n",
" })\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" to: req.path !== \"/\" ? req.path : undefined,\n"
],
"file_path": "src/node/routes/domainProxy.ts",
"type": "replace",
"edit_start_line_idx": 57
} | import { Request, Router } from "express"
import qs from "qs"
import { HttpCode, HttpError } from "../../common/http"
import { authenticated, ensureAuthenticated, redirect } from "../http"
import { proxy } from "../proxy"
import { Router as WsRouter } from "../wsRouter"
export const router = Router()
const getProxyTarget = (req: Request, rewrite: boolean): string => {
if (rewrite) {
const query = qs.stringify(req.query)
return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
}
return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
}
router.all("/(:port)(/*)?", (req, res) => {
if (!authenticated(req)) {
// If visiting the root (/proxy/:port and nothing else) redirect to the
// login page.
if (!req.params[0] || req.params[0] === "/") {
return redirect(req, res, "login", {
to: `${req.baseUrl}${req.path}` || "/",
})
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
// Absolute redirects need to be based on the subpath when rewriting.
;(req as any).base = `${req.baseUrl}/${req.params.port}`
proxy.web(req, res, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})
export const wsRouter = WsRouter()
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
proxy.ws(req, req.ws, req.head, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})
| src/node/routes/pathProxy.ts | 1 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.28945720195770264,
0.05885791778564453,
0.00016447485540993512,
0.0003161613130941987,
0.11530910432338715
]
|
{
"id": 0,
"code_window": [
" }\n",
" // Redirect all other pages to the login.\n",
" return redirect(req, res, \"login\", {\n",
" to: req.path,\n",
" })\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" to: req.path !== \"/\" ? req.path : undefined,\n"
],
"file_path": "src/node/routes/domainProxy.ts",
"type": "replace",
"edit_start_line_idx": 57
} | #!/bin/sh
set -eu
# This isn't set by default.
USER="$(whoami)"
export USER
if [ "${DOCKER_USER-}" ] && [ "$DOCKER_USER" != "$USER" ]; then
echo "$DOCKER_USER ALL=(ALL) NOPASSWD:ALL" | sudo tee -a /etc/sudoers.d/nopasswd > /dev/null
# Unfortunately we cannot change $HOME as we cannot move any bind mounts
# nor can we bind mount $HOME into a new home as that requires a privileged container.
sudo usermod --login "$DOCKER_USER" coder
sudo groupmod -n "$DOCKER_USER" coder
USER="$DOCKER_USER"
sudo sed -i "/coder/d" /etc/sudoers.d/nopasswd
sudo sed -i "s/coder/$DOCKER_USER/g" /etc/fixuid/config.yml
fi
dumb-init fixuid -q /usr/bin/code-server "$@"
| ci/release-image/entrypoint.sh | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00027721942751668394,
0.00020524316641967744,
0.00016859197057783604,
0.00016991805750876665,
0.00005089779369882308
]
|
{
"id": 0,
"code_window": [
" }\n",
" // Redirect all other pages to the login.\n",
" return redirect(req, res, \"login\", {\n",
" to: req.path,\n",
" })\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" to: req.path !== \"/\" ? req.path : undefined,\n"
],
"file_path": "src/node/routes/domainProxy.ts",
"type": "replace",
"edit_start_line_idx": 57
} | ---
name: Bug report
about: Report a bug and help us improve
title: ""
labels: ""
assignees: ""
---
<!--
Please see https://github.com/cdr/code-server/blob/master/doc/FAQ.md#how-do-i-debug-issues-with-code-server
and include any logging information relevant to the issue.
Please search for existing issues before filing.
If you can reproduce the issue on vanilla VS Code,
please file the issue at the VS Code repository instead.
Provide screenshots if applicable.
Please fill in the issue template and try to be as detailed
and clear as possible!
-->
- Web Browser:
- Local OS:
- Remote OS:
- Remote Architecture:
- `code-server --version`:
| .github/ISSUE_TEMPLATE/bug-report.md | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00017426328849978745,
0.00017014396144077182,
0.00016496051102876663,
0.00017120808479376137,
0.000003871665285259951
]
|
{
"id": 0,
"code_window": [
" }\n",
" // Redirect all other pages to the login.\n",
" return redirect(req, res, \"login\", {\n",
" to: req.path,\n",
" })\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" to: req.path !== \"/\" ? req.path : undefined,\n"
],
"file_path": "src/node/routes/domainProxy.ts",
"type": "replace",
"edit_start_line_idx": 57
} | ---
name: Documentation improvement
about: Suggest a documentation improvement
title: ""
labels: "docs"
assignees: ""
---
| .github/ISSUE_TEMPLATE/doc.md | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00017529906472191215,
0.00017529906472191215,
0.00017529906472191215,
0.00017529906472191215,
0
]
|
{
"id": 1,
"code_window": [
"import { Request, Router } from \"express\"\n",
"import qs from \"qs\"\n",
"import { HttpCode, HttpError } from \"../../common/http\"\n",
"import { authenticated, ensureAuthenticated, redirect } from \"../http\"\n",
"import { proxy } from \"../proxy\"\n",
"import { Router as WsRouter } from \"../wsRouter\"\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { normalize } from \"../../common/util\"\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "add",
"edit_start_line_idx": 3
} | import { Request, Router } from "express"
import qs from "qs"
import { HttpCode, HttpError } from "../../common/http"
import { authenticated, ensureAuthenticated, redirect } from "../http"
import { proxy } from "../proxy"
import { Router as WsRouter } from "../wsRouter"
export const router = Router()
const getProxyTarget = (req: Request, rewrite: boolean): string => {
if (rewrite) {
const query = qs.stringify(req.query)
return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
}
return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
}
router.all("/(:port)(/*)?", (req, res) => {
if (!authenticated(req)) {
// If visiting the root (/proxy/:port and nothing else) redirect to the
// login page.
if (!req.params[0] || req.params[0] === "/") {
return redirect(req, res, "login", {
to: `${req.baseUrl}${req.path}` || "/",
})
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
// Absolute redirects need to be based on the subpath when rewriting.
;(req as any).base = `${req.baseUrl}/${req.params.port}`
proxy.web(req, res, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})
export const wsRouter = WsRouter()
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
proxy.ws(req, req.ws, req.head, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})
| src/node/routes/pathProxy.ts | 1 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.9741699695587158,
0.36837512254714966,
0.0011215460253879428,
0.013497235253453255,
0.4452972114086151
]
|
{
"id": 1,
"code_window": [
"import { Request, Router } from \"express\"\n",
"import qs from \"qs\"\n",
"import { HttpCode, HttpError } from \"../../common/http\"\n",
"import { authenticated, ensureAuthenticated, redirect } from \"../http\"\n",
"import { proxy } from \"../proxy\"\n",
"import { Router as WsRouter } from \"../wsRouter\"\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { normalize } from \"../../common/util\"\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "add",
"edit_start_line_idx": 3
} | import { Router } from "express"
import { version } from "../constants"
import { ensureAuthenticated } from "../http"
import { UpdateProvider } from "../update"
export const router = Router()
const provider = new UpdateProvider()
router.get("/", ensureAuthenticated, async (req, res) => {
const update = await provider.getUpdate(req.query.force === "true")
res.json({
checked: update.checked,
latest: update.version,
current: version,
isLatest: provider.isLatestVersion(update),
})
})
| src/node/routes/update.ts | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.004705794155597687,
0.0024411273188889027,
0.00017646038031671196,
0.0024411273188889027,
0.002264666836708784
]
|
{
"id": 1,
"code_window": [
"import { Request, Router } from \"express\"\n",
"import qs from \"qs\"\n",
"import { HttpCode, HttpError } from \"../../common/http\"\n",
"import { authenticated, ensureAuthenticated, redirect } from \"../http\"\n",
"import { proxy } from \"../proxy\"\n",
"import { Router as WsRouter } from \"../wsRouter\"\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { normalize } from \"../../common/util\"\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "add",
"edit_start_line_idx": 3
} | import { logger } from "@coder/logger"
import express, { Express } from "express"
import { promises as fs } from "fs"
import http from "http"
import * as httpolyglot from "httpolyglot"
import { DefaultedArgs } from "./cli"
import { handleUpgrade } from "./wsRouter"
/**
* Create an Express app and an HTTP/S server to serve it.
*/
export const createApp = async (args: DefaultedArgs): Promise<[Express, Express, http.Server]> => {
const app = express()
const server = args.cert
? httpolyglot.createServer(
{
cert: args.cert && (await fs.readFile(args.cert.value)),
key: args["cert-key"] && (await fs.readFile(args["cert-key"])),
},
app,
)
: http.createServer(app)
await new Promise<http.Server>(async (resolve, reject) => {
server.on("error", reject)
if (args.socket) {
try {
await fs.unlink(args.socket)
} catch (error) {
if (error.code !== "ENOENT") {
logger.error(error.message)
}
}
server.listen(args.socket, resolve)
} else {
// [] is the correct format when using :: but Node errors with them.
server.listen(args.port, args.host.replace(/^\[|\]$/g, ""), resolve)
}
})
const wsApp = express()
handleUpgrade(wsApp, server)
return [app, wsApp, server]
}
/**
* Get the address of a server as a string (protocol *is* included) while
* ensuring there is one (will throw if there isn't).
*/
export const ensureAddress = (server: http.Server): string => {
const addr = server.address()
if (!addr) {
throw new Error("server has no address")
}
if (typeof addr !== "string") {
return `http://${addr.address}:${addr.port}`
}
return addr
}
| src/node/app.ts | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.0004908401169814169,
0.0002553447266109288,
0.0001679860579315573,
0.00017620650760363787,
0.00012326231808401644
]
|
{
"id": 1,
"code_window": [
"import { Request, Router } from \"express\"\n",
"import qs from \"qs\"\n",
"import { HttpCode, HttpError } from \"../../common/http\"\n",
"import { authenticated, ensureAuthenticated, redirect } from \"../http\"\n",
"import { proxy } from \"../proxy\"\n",
"import { Router as WsRouter } from \"../wsRouter\"\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { normalize } from \"../../common/util\"\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "add",
"edit_start_line_idx": 3
} | #!/usr/bin/env bash
set -euo pipefail
main() {
cd "$(dirname "$0")/../.."
cd ./lib/vscode
git apply ../../ci/dev/vscode.patch
}
main "$@"
| ci/dev/patch-vscode.sh | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00017054902855306864,
0.0001685066381469369,
0.00016646426229272038,
0.0001685066381469369,
0.00000204238313017413
]
|
{
"id": 2,
"code_window": [
"\n",
"router.all(\"/(:port)(/*)?\", (req, res) => {\n",
" if (!authenticated(req)) {\n",
" // If visiting the root (/proxy/:port and nothing else) redirect to the\n",
" // login page.\n",
" if (!req.params[0] || req.params[0] === \"/\") {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" // If visiting the root (/:port only) redirect to the login page.\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "replace",
"edit_start_line_idx": 19
} | import * as crypto from "crypto"
import { Router } from "express"
import { promises as fs } from "fs"
import * as path from "path"
import { commit, rootPath, version } from "../constants"
import { authenticated, ensureAuthenticated, redirect, replaceTemplates } from "../http"
import { getMediaMime, pathToFsPath } from "../util"
import { VscodeProvider } from "../vscode"
import { Router as WsRouter } from "../wsRouter"
export const router = Router()
const vscode = new VscodeProvider()
router.get("/", async (req, res) => {
if (!authenticated(req)) {
return redirect(req, res, "login", {
to: req.baseUrl,
})
}
const [content, options] = await Promise.all([
await fs.readFile(path.join(rootPath, "src/browser/pages/vscode.html"), "utf8"),
vscode
.initialize(
{
args: req.args,
remoteAuthority: req.headers.host || "",
},
req.query,
)
.catch((error) => {
const devMessage = commit === "development" ? "It might not have finished compiling." : ""
throw new Error(`VS Code failed to load. ${devMessage} ${error.message}`)
}),
])
options.productConfiguration.codeServerVersion = version
res.send(
replaceTemplates(
req,
// Uncomment prod blocks if not in development. TODO: Would this be
// better as a build step? Or maintain two HTML files again?
commit !== "development" ? content.replace(/<!-- PROD_ONLY/g, "").replace(/END_PROD_ONLY -->/g, "") : content,
{
disableTelemetry: !!req.args["disable-telemetry"],
},
)
.replace(`"{{REMOTE_USER_DATA_URI}}"`, `'${JSON.stringify(options.remoteUserDataUri)}'`)
.replace(`"{{PRODUCT_CONFIGURATION}}"`, `'${JSON.stringify(options.productConfiguration)}'`)
.replace(`"{{WORKBENCH_WEB_CONFIGURATION}}"`, `'${JSON.stringify(options.workbenchWebConfiguration)}'`)
.replace(`"{{NLS_CONFIGURATION}}"`, `'${JSON.stringify(options.nlsConfiguration)}'`),
)
})
/**
* TODO: Might currently be unused.
*/
router.get("/resource(/*)?", ensureAuthenticated, async (req, res) => {
if (typeof req.query.path === "string") {
res.set("Content-Type", getMediaMime(req.query.path))
res.send(await fs.readFile(pathToFsPath(req.query.path)))
}
})
/**
* Used by VS Code to load files.
*/
router.get("/vscode-remote-resource(/*)?", ensureAuthenticated, async (req, res) => {
if (typeof req.query.path === "string") {
res.set("Content-Type", getMediaMime(req.query.path))
res.send(await fs.readFile(pathToFsPath(req.query.path)))
}
})
/**
* VS Code webviews use these paths to load files and to load webview assets
* like HTML and JavaScript.
*/
router.get("/webview/*", ensureAuthenticated, async (req, res) => {
res.set("Content-Type", getMediaMime(req.path))
if (/^vscode-resource/.test(req.params[0])) {
return res.send(await fs.readFile(req.params[0].replace(/^vscode-resource(\/file)?/, "")))
}
return res.send(
await fs.readFile(path.join(vscode.vsRootPath, "out/vs/workbench/contrib/webview/browser/pre", req.params[0])),
)
})
export const wsRouter = WsRouter()
wsRouter.ws("/", ensureAuthenticated, async (req) => {
const magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
const reply = crypto
.createHash("sha1")
.update(req.headers["sec-websocket-key"] + magic)
.digest("base64")
req.ws.write(
[
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${reply}`,
].join("\r\n") + "\r\n\r\n",
)
await vscode.sendWebsocket(req.ws, req.query)
})
| src/node/routes/vscode.ts | 1 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.9909583330154419,
0.4405747354030609,
0.00016871659317985177,
0.006402071099728346,
0.4807063043117523
]
|
{
"id": 2,
"code_window": [
"\n",
"router.all(\"/(:port)(/*)?\", (req, res) => {\n",
" if (!authenticated(req)) {\n",
" // If visiting the root (/proxy/:port and nothing else) redirect to the\n",
" // login page.\n",
" if (!req.params[0] || req.params[0] === \"/\") {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" // If visiting the root (/:port only) redirect to the login page.\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "replace",
"edit_start_line_idx": 19
} | ---
name: Bug report
about: Report a bug and help us improve
title: ""
labels: ""
assignees: ""
---
<!--
Please see https://github.com/cdr/code-server/blob/master/doc/FAQ.md#how-do-i-debug-issues-with-code-server
and include any logging information relevant to the issue.
Please search for existing issues before filing.
If you can reproduce the issue on vanilla VS Code,
please file the issue at the VS Code repository instead.
Provide screenshots if applicable.
Please fill in the issue template and try to be as detailed
and clear as possible!
-->
- Web Browser:
- Local OS:
- Remote OS:
- Remote Architecture:
- `code-server --version`:
| .github/ISSUE_TEMPLATE/bug-report.md | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00017530826153233647,
0.00017092966299969703,
0.0001682678994257003,
0.00016921281348913908,
0.000003120079327345593
]
|
{
"id": 2,
"code_window": [
"\n",
"router.all(\"/(:port)(/*)?\", (req, res) => {\n",
" if (!authenticated(req)) {\n",
" // If visiting the root (/proxy/:port and nothing else) redirect to the\n",
" // login page.\n",
" if (!req.params[0] || req.params[0] === \"/\") {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" // If visiting the root (/:port only) redirect to the login page.\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "replace",
"edit_start_line_idx": 19
} | parser: "@typescript-eslint/parser"
env:
browser: true
es6: true # Map, etc.
mocha: true
node: true
parserOptions:
ecmaVersion: 2018
sourceType: module
extends:
- eslint:recommended
- plugin:@typescript-eslint/recommended
- plugin:import/recommended
- plugin:import/typescript
- plugin:prettier/recommended
- prettier # Removes eslint rules that conflict with prettier.
- prettier/@typescript-eslint # Remove conflicts again.
rules:
# For overloads.
no-dupe-class-members: off
"@typescript-eslint/no-use-before-define": off
"@typescript-eslint/no-non-null-assertion": off
"@typescript-eslint/ban-types": off
"@typescript-eslint/no-var-requires": off
"@typescript-eslint/explicit-module-boundary-types": off
"@typescript-eslint/no-explicit-any": off
eqeqeq: error
import/order:
[error, { alphabetize: { order: "asc" }, groups: [["builtin", "external", "internal"], "parent", "sibling"] }]
no-async-promise-executor: off
# This isn't a real module, just types, which apparently doesn't resolve.
import/no-unresolved: [error, { ignore: ["express-serve-static-core"] }]
settings:
# Does not work with CommonJS unfortunately.
import/ignore:
- env-paths
- xdg-basedir
| .eslintrc.yaml | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00017561626737006009,
0.00017260941967833787,
0.00016864438657648861,
0.0001743984321365133,
0.000002828582410074887
]
|
{
"id": 2,
"code_window": [
"\n",
"router.all(\"/(:port)(/*)?\", (req, res) => {\n",
" if (!authenticated(req)) {\n",
" // If visiting the root (/proxy/:port and nothing else) redirect to the\n",
" // login page.\n",
" if (!req.params[0] || req.params[0] === \"/\") {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" // If visiting the root (/:port only) redirect to the login page.\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "replace",
"edit_start_line_idx": 19
} | import * as cp from "child_process"
import Bundler from "parcel-bundler"
import * as path from "path"
async function main(): Promise<void> {
try {
const watcher = new Watcher()
await watcher.watch()
} catch (error) {
console.error(error.message)
process.exit(1)
}
}
class Watcher {
private readonly rootPath = path.resolve(__dirname, "../..")
private readonly vscodeSourcePath = path.join(this.rootPath, "lib/vscode")
private static log(message: string, skipNewline = false): void {
process.stdout.write(message)
if (!skipNewline) {
process.stdout.write("\n")
}
}
public async watch(): Promise<void> {
let server: cp.ChildProcess | undefined
const restartServer = (): void => {
if (server) {
server.kill()
}
const s = cp.fork(path.join(this.rootPath, "out/node/entry.js"), process.argv.slice(2))
console.log(`[server] spawned process ${s.pid}`)
s.on("exit", () => console.log(`[server] process ${s.pid} exited`))
server = s
}
const vscode = cp.spawn("yarn", ["watch"], { cwd: this.vscodeSourcePath })
const tsc = cp.spawn("tsc", ["--watch", "--pretty", "--preserveWatchOutput"], { cwd: this.rootPath })
const plugin = process.env.PLUGIN_DIR
? cp.spawn("yarn", ["build", "--watch"], { cwd: process.env.PLUGIN_DIR })
: undefined
const bundler = this.createBundler()
const cleanup = (code?: number | null): void => {
Watcher.log("killing vs code watcher")
vscode.removeAllListeners()
vscode.kill()
Watcher.log("killing tsc")
tsc.removeAllListeners()
tsc.kill()
if (plugin) {
Watcher.log("killing plugin")
plugin.removeAllListeners()
plugin.kill()
}
if (server) {
Watcher.log("killing server")
server.removeAllListeners()
server.kill()
}
Watcher.log("killing bundler")
process.exit(code || 0)
}
process.on("SIGINT", () => cleanup())
process.on("SIGTERM", () => cleanup())
vscode.on("exit", (code) => {
Watcher.log("vs code watcher terminated unexpectedly")
cleanup(code)
})
tsc.on("exit", (code) => {
Watcher.log("tsc terminated unexpectedly")
cleanup(code)
})
if (plugin) {
plugin.on("exit", (code) => {
Watcher.log("plugin terminated unexpectedly")
cleanup(code)
})
}
const bundle = bundler.bundle().catch(() => {
Watcher.log("parcel watcher terminated unexpectedly")
cleanup(1)
})
bundler.on("buildEnd", () => {
console.log("[parcel] bundled")
})
bundler.on("buildError", (error) => {
console.error("[parcel]", error)
})
vscode.stderr.on("data", (d) => process.stderr.write(d))
tsc.stderr.on("data", (d) => process.stderr.write(d))
if (plugin) {
plugin.stderr.on("data", (d) => process.stderr.write(d))
}
// From https://github.com/chalk/ansi-regex
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))",
].join("|")
const re = new RegExp(pattern, "g")
/**
* Split stdout on newlines and strip ANSI codes.
*/
const onLine = (proc: cp.ChildProcess, callback: (strippedLine: string, originalLine: string) => void): void => {
let buffer = ""
if (!proc.stdout) {
throw new Error("no stdout")
}
proc.stdout.setEncoding("utf8")
proc.stdout.on("data", (d) => {
const data = buffer + d
const split = data.split("\n")
const last = split.length - 1
for (let i = 0; i < last; ++i) {
callback(split[i].replace(re, ""), split[i])
}
// The last item will either be an empty string (the data ended with a
// newline) or a partial line (did not end with a newline) and we must
// wait to parse it until we get a full line.
buffer = split[last]
})
}
let startingVscode = false
let startedVscode = false
onLine(vscode, (line, original) => {
console.log("[vscode]", original)
// Wait for watch-client since "Finished compilation" will appear multiple
// times before the client starts building.
if (!startingVscode && line.includes("Starting watch-client")) {
startingVscode = true
} else if (startingVscode && line.includes("Finished compilation")) {
if (startedVscode) {
bundle.then(restartServer)
}
startedVscode = true
}
})
onLine(tsc, (line, original) => {
// tsc outputs blank lines; skip them.
if (line !== "") {
console.log("[tsc]", original)
}
if (line.includes("Watching for file changes")) {
bundle.then(restartServer)
}
})
if (plugin) {
onLine(plugin, (line, original) => {
// tsc outputs blank lines; skip them.
if (line !== "") {
console.log("[plugin]", original)
}
if (line.includes("Watching for file changes")) {
bundle.then(restartServer)
}
})
}
}
private createBundler(out = "dist"): Bundler {
return new Bundler(
[
path.join(this.rootPath, "src/browser/register.ts"),
path.join(this.rootPath, "src/browser/serviceWorker.ts"),
path.join(this.rootPath, "src/browser/pages/login.ts"),
path.join(this.rootPath, "src/browser/pages/vscode.ts"),
],
{
outDir: path.join(this.rootPath, out),
cacheDir: path.join(this.rootPath, ".cache"),
minify: !!process.env.MINIFY,
logLevel: 1,
publicUrl: ".",
},
)
}
}
main()
| ci/dev/watch.ts | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00035898073110729456,
0.00018309969163965434,
0.00017118816322181374,
0.00017416826449334621,
0.00004038161932840012
]
|
{
"id": 3,
"code_window": [
" if (!req.params[0] || req.params[0] === \"/\") {\n",
" return redirect(req, res, \"login\", {\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
" const to = normalize(`${req.baseUrl}${req.path}`)\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "add",
"edit_start_line_idx": 22
} | import { Request, Router } from "express"
import qs from "qs"
import { HttpCode, HttpError } from "../../common/http"
import { authenticated, ensureAuthenticated, redirect } from "../http"
import { proxy } from "../proxy"
import { Router as WsRouter } from "../wsRouter"
export const router = Router()
const getProxyTarget = (req: Request, rewrite: boolean): string => {
if (rewrite) {
const query = qs.stringify(req.query)
return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
}
return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
}
router.all("/(:port)(/*)?", (req, res) => {
if (!authenticated(req)) {
// If visiting the root (/proxy/:port and nothing else) redirect to the
// login page.
if (!req.params[0] || req.params[0] === "/") {
return redirect(req, res, "login", {
to: `${req.baseUrl}${req.path}` || "/",
})
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
// Absolute redirects need to be based on the subpath when rewriting.
;(req as any).base = `${req.baseUrl}/${req.params.port}`
proxy.web(req, res, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})
export const wsRouter = WsRouter()
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
proxy.ws(req, req.ws, req.head, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})
| src/node/routes/pathProxy.ts | 1 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.9950226545333862,
0.2339150607585907,
0.0003749355091713369,
0.03638579323887825,
0.38371753692626953
]
|
{
"id": 3,
"code_window": [
" if (!req.params[0] || req.params[0] === \"/\") {\n",
" return redirect(req, res, \"login\", {\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
" const to = normalize(`${req.baseUrl}${req.path}`)\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "add",
"edit_start_line_idx": 22
} | FROM debian:10
RUN apt-get update \
&& apt-get install -y \
curl \
dumb-init \
htop \
locales \
man \
nano \
git \
procps \
ssh \
sudo \
vim \
lsb-release \
&& rm -rf /var/lib/apt/lists/*
# https://wiki.debian.org/Locale#Manually
RUN sed -i "s/# en_US.UTF-8/en_US.UTF-8/" /etc/locale.gen \
&& locale-gen
ENV LANG=en_US.UTF-8
RUN chsh -s /bin/bash
ENV SHELL=/bin/bash
RUN adduser --gecos '' --disabled-password coder && \
echo "coder ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/nopasswd
RUN ARCH="$(dpkg --print-architecture)" && \
curl -fsSL "https://github.com/boxboat/fixuid/releases/download/v0.4.1/fixuid-0.4.1-linux-$ARCH.tar.gz" | tar -C /usr/local/bin -xzf - && \
chown root:root /usr/local/bin/fixuid && \
chmod 4755 /usr/local/bin/fixuid && \
mkdir -p /etc/fixuid && \
printf "user: coder\ngroup: coder\n" > /etc/fixuid/config.yml
COPY release-packages/code-server*.deb /tmp/
COPY ci/release-image/entrypoint.sh /usr/bin/entrypoint.sh
RUN dpkg -i /tmp/code-server*$(dpkg --print-architecture).deb && rm /tmp/code-server*.deb
EXPOSE 8080
# This way, if someone sets $DOCKER_USER, docker-exec will still work as
# the uid will remain the same. note: only relevant if -u isn't passed to
# docker-run.
USER 1000
WORKDIR /home/coder
ENTRYPOINT ["/usr/bin/entrypoint.sh", "--bind-addr", "0.0.0.0:8080", "."]
| ci/release-image/Dockerfile | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00018009409541264176,
0.00017221513553522527,
0.00016795034753158689,
0.00017104785365518183,
0.000004224890744808363
]
|
{
"id": 3,
"code_window": [
" if (!req.params[0] || req.params[0] === \"/\") {\n",
" return redirect(req, res, \"login\", {\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
" const to = normalize(`${req.baseUrl}${req.path}`)\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "add",
"edit_start_line_idx": 22
} | <!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
# FAQ
- [Questions?](#questions)
- [How can I reuse my VS Code configuration?](#how-can-i-reuse-my-vs-code-configuration)
- [Differences compared to VS Code?](#differences-compared-to-vs-code)
- [How can I request a missing extension?](#how-can-i-request-a-missing-extension)
- [How do I configure the marketplace URL?](#how-do-i-configure-the-marketplace-url)
- [Where are extensions stored?](#where-are-extensions-stored)
- [How is this different from VS Code Codespaces?](#how-is-this-different-from-vs-code-codespaces)
- [How should I expose code-server to the internet?](#how-should-i-expose-code-server-to-the-internet)
- [How do I securely access web services?](#how-do-i-securely-access-web-services)
- [Sub-paths](#sub-paths)
- [Sub-domains](#sub-domains)
- [Multi-tenancy](#multi-tenancy)
- [Docker in code-server container?](#docker-in-code-server-container)
- [How can I disable telemetry?](#how-can-i-disable-telemetry)
- [How does code-server decide what workspace or folder to open?](#how-does-code-server-decide-what-workspace-or-folder-to-open)
- [How do I debug issues with code-server?](#how-do-i-debug-issues-with-code-server)
- [Heartbeat File](#heartbeat-file)
- [Healthz endpoint](#healthz-endpoint)
- [How does the config file work?](#how-does-the-config-file-work)
- [Blank screen on iPad?](#blank-screen-on-ipad)
- [Isn't an install script piped into sh insecure?](#isnt-an-install-script-piped-into-sh-insecure)
- [How do I make my keyboard shortcuts work?](#how-do-i-make-my-keyboard-shortcuts-work)
- [Differences compared to Theia?](#differences-compared-to-theia)
- [Enterprise](#enterprise)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Questions?
Please file all questions and support requests at https://github.com/cdr/code-server/discussions.
## How can I reuse my VS Code configuration?
The very popular [Settings Sync](https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync) extension works.
You can also pass `--user-data-dir ~/.vscode` to reuse your existing VS Code extensions and configuration.
Or copy `~/.vscode` into `~/.local/share/code-server`.
## Differences compared to VS Code?
`code-server` takes the open source core of VS Code and allows you to run it in the browser.
However, it is not entirely equivalent to Microsoft's VS Code.
While the core of VS Code is open source, the marketplace and many published Microsoft extensions are not.
Furthermore, Microsoft prohibits the use of any non-Microsoft VS Code from accessing their marketplace.
See the [TOS](https://cdn.vsassets.io/v/M146_20190123.39/_content/Microsoft-Visual-Studio-Marketplace-Terms-of-Use.pdf).
> Marketplace Offerings are intended for use only with Visual Studio Products and Services
> and you may only install and use Marketplace Offerings with Visual Studio Products and Services.
As a result, we cannot offer any extensions on the Microsoft marketplace. Instead,
we have created our own marketplace for open source extensions.
It works by scraping GitHub for VS Code extensions and building them. It's not perfect but getting
better by the day with more and more extensions.
These are the closed source extensions presently unavailable:
1. [Live Share](https://visualstudio.microsoft.com/services/live-share)
- We may implement something similar, see [#33](https://github.com/cdr/code-server/issues/33)
1. [Remote Extensions (SSH, Containers, WSL)](https://github.com/microsoft/vscode-remote-release)
- We may reimplement these at some point, see [#1315](https://github.com/cdr/code-server/issues/1315)
For more about the closed source parts of VS Code, see [vscodium/vscodium](https://github.com/VSCodium/vscodium#why-does-this-exist).
## How can I request a missing extension?
Please open a new issue and select the `Extension request` template.
If an extension is not available or does not work, you can grab its VSIX from its Github releases or
build it yourself. Then run the `Extensions: Install from VSIX` command in the Command Palette and
point to the .vsix file.
See below for installing an extension from the cli.
## How do I configure the marketplace URL?
If you have your own marketplace that implements the VS Code Extension Gallery API, it is possible to
point code-server to it by setting `$SERVICE_URL` and `$ITEM_URL`. These correspond directly
to `serviceUrl` and `itemUrl` in VS Code's `product.json`.
e.g. to use [open-vsx.org](https://open-vsx.org):
```bash
export SERVICE_URL=https://open-vsx.org/vscode/gallery
export ITEM_URL=https://open-vsx.org/vscode/item
```
While you can technically use Microsoft's marketplace with these, please do not do so as it
is against their terms of use. See [above](#differences-compared-to-vs-code) and this
discussion regarding the use of the Microsoft URLs in forks:
https://github.com/microsoft/vscode/issues/31168#issue-244533026
These variables are most valuable to our enterprise customers for whom we have a self hosted marketplace product.
## Where are extensions stored?
Defaults to `~/.local/share/code-server/extensions`.
If the `XDG_DATA_HOME` environment variable is set the data directory will be
`$XDG_DATA_HOME/code-server/extensions`. In general we try to follow the XDG directory spec.
You can install an extension on the CLI with:
```bash
# From the Coder extension marketplace
code-server --install-extension ms-python.python
# From a downloaded VSIX on the file system
code-server --install-extension downloaded-ms-python.python.vsix
```
## How is this different from VS Code Codespaces?
VS Code Codespaces is a closed source and paid service by Microsoft. It also allows you to access
VS Code via the browser.
However, code-server is free, open source and can be run on any machine without any limitations.
While you can self host environments with VS Code Codespaces, you still need an Azure billing
account and you have to access VS Code via the Codespaces web dashboard instead of directly
connecting to your instance.
## How should I expose code-server to the internet?
Please follow [./guide.md](./guide.md) for our recommendations on setting up and using code-server.
code-server only supports password authentication natively.
**note**: code-server will rate limit password authentication attempts at 2 a minute and 12 an hour.
If you want to use external authentication (i.e sign in with Google) you should handle this
with a reverse proxy using something like [oauth2_proxy](https://github.com/pusher/oauth2_proxy)
or [Cloudflare Access](https://teams.cloudflare.com/access).
For HTTPS, you can use a self signed certificate by passing in just `--cert` or
pass in an existing certificate by providing the path to `--cert` and the path to
the key with `--cert-key`.
If `code-server` has been passed a certificate it will also respond to HTTPS
requests and will redirect all HTTP requests to HTTPS.
You can use [Let's Encrypt](https://letsencrypt.org/) to get a TLS certificate
for free.
Again, please follow [./guide.md](./guide.md) for our recommendations on setting up and using code-server.
## How do I securely access web services?
code-server is capable of proxying to any port using either a subdomain or a
subpath which means you can securely access these services using code-server's
built-in authentication.
### Sub-paths
Just browse to `/proxy/<port>/`.
### Sub-domains
You will need a DNS entry that points to your server for each port you want to
access. You can either set up a wildcard DNS entry for `*.<domain>` if your domain
name registrar supports it or you can create one for every port you want to
access (`3000.<domain>`, `8080.<domain>`, etc).
You should also set up TLS certificates for these subdomains, either using a
wildcard certificate for `*.<domain>` or individual certificates for each port.
Start code-server with the `--proxy-domain` flag set to your domain.
```
code-server --proxy-domain <domain>
```
Now you can browse to `<port>.<domain>`. Note that this uses the host header so
ensure your reverse proxy forwards that information if you are using one.
## Multi-tenancy
If you want to run multiple code-servers on shared infrastructure, we recommend using virtual
machines with a VM per user. This will easily allow users to run a docker daemon. If you want
to use kubernetes, you'll definitely want to use [kubevirt](https://kubevirt.io) to give each
user a virtual machine instead of just a container.
## Docker in code-server container?
If you'd like to access docker inside of code-server, mount the docker socket in from `/var/run/docker.sock`.
Install the docker CLI in the code-server container and you should be able to access the daemon!
You can even make volume mounts work. Lets say you want to run a container and mount in
`/home/coder/myproject` into it from inside the `code-server` container. You need to make sure
the docker daemon's `/home/coder/myproject` is the same as the one mounted inside the `code-server`
container and the mount will just work.
## How can I disable telemetry?
Use the `--disable-telemetry` flag to completely disable telemetry. We use the
data collected only to improve code-server.
## How does code-server decide what workspace or folder to open?
code-server tries the following in order:
1. The `workspace` query parameter.
2. The `folder` query parameter.
3. The workspace or directory passed on the command line.
4. The last opened workspace or directory.
## How do I debug issues with code-server?
First run code-server with at least `debug` logging (or `trace` to be really
thorough) by setting the `--log` flag or the `LOG_LEVEL` environment variable.
`-vvv` and `--verbose` are aliases for `--log trace`.
```
code-server --log debug
```
Once this is done, replicate the issue you're having then collect logging
information from the following places:
1. stdout
2. The most recently created directory in the `~/.local/share/code-server/logs` directory.
3. The browser console and network tabs.
Additionally, collecting core dumps (you may need to enable them first) if
code-server crashes can be helpful.
## Heartbeat File
`code-server` touches `~/.local/share/code-server/heartbeat` once a minute as long
as there is an active browser connection.
If you want to shutdown `code-server` if there hasn't been an active connection in X minutes
you can do so by continuously checking the last modified time on the heartbeat file and if it is
older than X minutes, kill `code-server`.
[#1636](https://github.com/cdr/code-server/issues/1636) will make the experience here better.
## Healthz endpoint
`code-server` exposes an endpoint at `/healthz` which can be used to check
whether `code-server` is up without triggering a heartbeat. The response will
include a status (`alive` or `expired`) and a timestamp for the last heartbeat
(defaults to `0`). This endpoint does not require authentication.
```json
{
"status": "alive",
"lastHeartbeat": 1599166210566
}
```
## How does the config file work?
When `code-server` starts up, it creates a default config file in `~/.config/code-server/config.yaml` that looks
like this:
```yaml
bind-addr: 127.0.0.1:8080
auth: password
password: mewkmdasosafuio3422 # This is randomly generated for each config.yaml
cert: false
```
Each key in the file maps directly to a `code-server` flag. Run `code-server --help` to see
a listing of all the flags.
The default config here says to listen on the loopback IP port 8080, enable password authorization
and no TLS. Any flags passed to `code-server` will take priority over the config file.
The `--config` flag or `$CODE_SERVER_CONFIG` can be used to change the config file's location.
The default location also respects `$XDG_CONFIG_HOME`.
## Blank screen on iPad?
Unfortunately at the moment self signed certificates cause a blank screen on iPadOS
There does seem to be a way to get it to work if you create your own CA and create a
certificate using the CA and then import the CA onto your iPad.
See [#1566](https://github.com/cdr/code-server/issues/1566#issuecomment-623159434).
## Isn't an install script piped into sh insecure?
Please give
[this wonderful blogpost](https://sandstorm.io/news/2015-09-24-is-curl-bash-insecure-pgp-verified-install) by
[sandstorm.io](https://sandstorm.io) a read.
## How do I make my keyboard shortcuts work?
Many shortcuts will not work by default as they'll be caught by the browser.
If you use Chrome you can get around this by installing the PWA.
Once you've entered the editor, click the "plus" icon present in the URL toolbar area.
This will install a Chrome PWA and now all keybindings will work!
For other browsers you'll have to remap keybindings unfortunately.
## Differences compared to Theia?
[Theia](https://github.com/eclipse-theia/theia) is a browser IDE loosely based on VS Code. It uses the same
text editor library named [Monaco](https://github.com/Microsoft/monaco-editor) and the same
extension API but everything else is very different. It also uses [open-vsx.org](https://open-vsx.org)
for extensions which has an order of magnitude less extensions than our marketplace.
See [#1473](https://github.com/cdr/code-server/issues/1473).
You can't just use your VS Code config in Theia like you can with code-server.
To summarize, code-server is a patched fork of VS Code to run in the browser whereas
Theia takes some parts of VS Code but is an entirely different editor.
## Enterprise
Visit [our enterprise page](https://coder.com) for more information about our
enterprise offerings.
| doc/FAQ.md | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00017158297123387456,
0.00016751501243561506,
0.00016367461648769677,
0.0001678217959124595,
0.0000017691888842819026
]
|
{
"id": 3,
"code_window": [
" if (!req.params[0] || req.params[0] === \"/\") {\n",
" return redirect(req, res, \"login\", {\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
" const to = normalize(`${req.baseUrl}${req.path}`)\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "add",
"edit_start_line_idx": 22
} | import { logger } from "@coder/logger"
import * as path from "path"
let pkg: { version?: string; commit?: string } = {}
try {
pkg = require("../../package.json")
} catch (error) {
logger.warn(error.message)
}
export const version = pkg.version || "development"
export const commit = pkg.commit || "development"
export const rootPath = path.resolve(__dirname, "../..")
| src/node/constants.ts | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.0001747448113746941,
0.00017324885993730277,
0.00017175290849991143,
0.00017324885993730277,
0.0000014959514373913407
]
|
{
"id": 4,
"code_window": [
" return redirect(req, res, \"login\", {\n",
" to: `${req.baseUrl}${req.path}` || \"/\",\n",
" })\n",
" }\n",
" throw new HttpError(\"Unauthorized\", HttpCode.Unauthorized)\n",
" }\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" to: to !== \"/\" ? to : undefined,\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "replace",
"edit_start_line_idx": 23
} | import * as crypto from "crypto"
import { Router } from "express"
import { promises as fs } from "fs"
import * as path from "path"
import { commit, rootPath, version } from "../constants"
import { authenticated, ensureAuthenticated, redirect, replaceTemplates } from "../http"
import { getMediaMime, pathToFsPath } from "../util"
import { VscodeProvider } from "../vscode"
import { Router as WsRouter } from "../wsRouter"
export const router = Router()
const vscode = new VscodeProvider()
router.get("/", async (req, res) => {
if (!authenticated(req)) {
return redirect(req, res, "login", {
to: req.baseUrl,
})
}
const [content, options] = await Promise.all([
await fs.readFile(path.join(rootPath, "src/browser/pages/vscode.html"), "utf8"),
vscode
.initialize(
{
args: req.args,
remoteAuthority: req.headers.host || "",
},
req.query,
)
.catch((error) => {
const devMessage = commit === "development" ? "It might not have finished compiling." : ""
throw new Error(`VS Code failed to load. ${devMessage} ${error.message}`)
}),
])
options.productConfiguration.codeServerVersion = version
res.send(
replaceTemplates(
req,
// Uncomment prod blocks if not in development. TODO: Would this be
// better as a build step? Or maintain two HTML files again?
commit !== "development" ? content.replace(/<!-- PROD_ONLY/g, "").replace(/END_PROD_ONLY -->/g, "") : content,
{
disableTelemetry: !!req.args["disable-telemetry"],
},
)
.replace(`"{{REMOTE_USER_DATA_URI}}"`, `'${JSON.stringify(options.remoteUserDataUri)}'`)
.replace(`"{{PRODUCT_CONFIGURATION}}"`, `'${JSON.stringify(options.productConfiguration)}'`)
.replace(`"{{WORKBENCH_WEB_CONFIGURATION}}"`, `'${JSON.stringify(options.workbenchWebConfiguration)}'`)
.replace(`"{{NLS_CONFIGURATION}}"`, `'${JSON.stringify(options.nlsConfiguration)}'`),
)
})
/**
* TODO: Might currently be unused.
*/
router.get("/resource(/*)?", ensureAuthenticated, async (req, res) => {
if (typeof req.query.path === "string") {
res.set("Content-Type", getMediaMime(req.query.path))
res.send(await fs.readFile(pathToFsPath(req.query.path)))
}
})
/**
* Used by VS Code to load files.
*/
router.get("/vscode-remote-resource(/*)?", ensureAuthenticated, async (req, res) => {
if (typeof req.query.path === "string") {
res.set("Content-Type", getMediaMime(req.query.path))
res.send(await fs.readFile(pathToFsPath(req.query.path)))
}
})
/**
* VS Code webviews use these paths to load files and to load webview assets
* like HTML and JavaScript.
*/
router.get("/webview/*", ensureAuthenticated, async (req, res) => {
res.set("Content-Type", getMediaMime(req.path))
if (/^vscode-resource/.test(req.params[0])) {
return res.send(await fs.readFile(req.params[0].replace(/^vscode-resource(\/file)?/, "")))
}
return res.send(
await fs.readFile(path.join(vscode.vsRootPath, "out/vs/workbench/contrib/webview/browser/pre", req.params[0])),
)
})
export const wsRouter = WsRouter()
wsRouter.ws("/", ensureAuthenticated, async (req) => {
const magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
const reply = crypto
.createHash("sha1")
.update(req.headers["sec-websocket-key"] + magic)
.digest("base64")
req.ws.write(
[
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${reply}`,
].join("\r\n") + "\r\n\r\n",
)
await vscode.sendWebsocket(req.ws, req.query)
})
| src/node/routes/vscode.ts | 1 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.3195416331291199,
0.029294339939951897,
0.0001645528245717287,
0.00020026747370138764,
0.09178437292575836
]
|
{
"id": 4,
"code_window": [
" return redirect(req, res, \"login\", {\n",
" to: `${req.baseUrl}${req.path}` || \"/\",\n",
" })\n",
" }\n",
" throw new HttpError(\"Unauthorized\", HttpCode.Unauthorized)\n",
" }\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" to: to !== \"/\" ? to : undefined,\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "replace",
"edit_start_line_idx": 23
} | #!/usr/bin/env bash
set -euo pipefail
main() {
cd "$(dirname "${0}")/../.."
source ./ci/lib.sh
git clean -Xffd
pushd lib/vscode
git clean -xffd
git reset --hard
popd
}
main "$@"
| ci/build/clean.sh | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00017546862363815308,
0.00017280993051826954,
0.00017015122284647077,
0.00017280993051826954,
0.0000026587003958411515
]
|
{
"id": 4,
"code_window": [
" return redirect(req, res, \"login\", {\n",
" to: `${req.baseUrl}${req.path}` || \"/\",\n",
" })\n",
" }\n",
" throw new HttpError(\"Unauthorized\", HttpCode.Unauthorized)\n",
" }\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" to: to !== \"/\" ? to : undefined,\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "replace",
"edit_start_line_idx": 23
} | #!/usr/bin/env bash
set -euo pipefail
main() {
cd "$(dirname "$0")/../.."
yarn --frozen-lockfile
git submodule update --init
# We do not `yarn vscode` to make test.sh faster.
# If the patch fails to apply, then it's likely already applied
yarn vscode:patch &> /dev/null || true
yarn lint
}
main "$@"
| ci/steps/lint.sh | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.0001737229322316125,
0.0001718424609862268,
0.0001699619897408411,
0.0001718424609862268,
0.0000018804712453857064
]
|
{
"id": 4,
"code_window": [
" return redirect(req, res, \"login\", {\n",
" to: `${req.baseUrl}${req.path}` || \"/\",\n",
" })\n",
" }\n",
" throw new HttpError(\"Unauthorized\", HttpCode.Unauthorized)\n",
" }\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" to: to !== \"/\" ? to : undefined,\n"
],
"file_path": "src/node/routes/pathProxy.ts",
"type": "replace",
"edit_start_line_idx": 23
} | <!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
# Contributing
- [Pull Requests](#pull-requests)
- [Requirements](#requirements)
- [Development Workflow](#development-workflow)
- [Build](#build)
- [Structure](#structure)
- [VS Code Patch](#vs-code-patch)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
- [Detailed CI and build process docs](../ci)
## Pull Requests
Please link to the issue each PR solves.
If there is no existing issue, please first create one unless the fix is minor.
Please make sure the base of your PR is the master branch. We keep the GitHub
default branch the latest release branch to avoid confusion as the
documentation is on GitHub and we don't want users to see docs on unreleased
features.
## Requirements
Please refer to [VS Code's prerequisites](https://github.com/Microsoft/vscode/wiki/How-to-Contribute#prerequisites).
Differences:
- We require a minimum of node v12 but later versions should work.
- We use [nfpm](https://github.com/goreleaser/nfpm) to build `.deb` and `.rpm` packages.
- We use [jq](https://stedolan.github.io/jq/) to build code-server releases.
- The [CI container](../ci/images/debian10/Dockerfile) is a useful reference for all our dependencies.
## Development Workflow
```shell
yarn
yarn vscode
yarn watch
# Visit http://localhost:8080 once the build completed.
```
To develop inside of an isolated docker container:
```shell
./ci/dev/image/run.sh yarn
./ci/dev/image/run.sh yarn vscode
./ci/dev/image/run.sh yarn watch
```
`yarn watch` will live reload changes to the source.
If changes are made to the patch and you've built previously you must manually
reset VS Code then run `yarn vscode:patch`.
## Build
You can build with:
```shell
./ci/dev/image/run.sh ./ci/steps/release.sh
```
Run your build with:
```
cd release
yarn --production
# Runs the built JavaScript with Node.
node .
```
Build release packages (make sure you run `./ci/steps/release.sh` first):
```
IMAGE=centos7 ./ci/dev/image/run.sh ./ci/steps/release-packages.sh
# The standalone release is in ./release-standalone
# .deb, .rpm and the standalone archive are in ./release-packages
```
The `release.sh` script is the equivalent of:
```shell
yarn
yarn vscode
yarn build
yarn build:vscode
yarn release
```
And `release-packages.sh` is:
```
yarn release:standalone
yarn test:standalone-release
yarn package
```
For a faster release build you can also run:
```
KEEP_MODULES=1 ./ci/steps/release.sh
node ./release
```
## Structure
The `code-server` script serves an HTTP API to login and start a remote VS Code process.
The CLI code is in [./src/node](./src/node) and the HTTP routes are implemented in
[./src/node/app](./src/node/app).
Most of the meaty parts are in our VS Code patch which is described next.
### VS Code Patch
Back in v1 of code-server, we had an extensive patch of VS Code that split the codebase
into a frontend and server. The frontend consisted of all UI code and the server ran
the extensions and exposed an API to the frontend for file access and everything else
that the UI needed.
This worked but eventually Microsoft added support to VS Code to run it in the web.
They have open sourced the frontend but have kept the server closed source.
So in interest of piggy backing off their work, v2 and beyond use the VS Code
web frontend and fill in the server. This is contained in our
[./ci/dev/vscode.patch](../ci/dev/vscode.patch) under the path `src/vs/server`.
Other notable changes in our patch include:
- Add our own build file which includes our code and VS Code's web code.
- Allow multiple extension directories (both user and built-in).
- Modify the loader, websocket, webview, service worker, and asset requests to
use the URL of the page as a base (and TLS if necessary for the websocket).
- Send client-side telemetry through the server.
- Allow modification of the display language.
- Make it possible for us to load code on the client.
- Make extensions work in the browser.
- Make it possible to install extensions of any kind.
- Fix getting permanently disconnected when you sleep or hibernate for a while.
- Add connection type to web socket query parameters.
Some known issues presently:
- Creating custom VS Code extensions and debugging them doesn't work.
- Extension profiling and tips are currently disabled.
As the web portion of VS Code matures, we'll be able to shrink and maybe even entirely
eliminate our patch. In the meantime, however, upgrading the VS Code version requires
ensuring that the patch still applies and has the intended effects.
To generate a new patch run `yarn vscode:diff`.
**note**: We have extension docs on the CI and build system at [./ci/README.md](../ci/README.md)
If functionality doesn't depend on code from VS Code then it should be moved
into code-server otherwise it should be in the patch.
In the future we'd like to run VS Code unit tests against our builds to ensure features
work as expected.
| doc/CONTRIBUTING.md | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.0003656098560895771,
0.00017936799849849194,
0.00016298628179356456,
0.00016741215949878097,
0.00004663981235353276
]
|
{
"id": 5,
"code_window": [
"\n",
"router.get(\"/\", async (req, res) => {\n",
" if (!authenticated(req)) {\n",
" return redirect(req, res, \"login\", {\n",
" to: req.baseUrl,\n",
" })\n",
" }\n",
"\n",
" const [content, options] = await Promise.all([\n",
" await fs.readFile(path.join(rootPath, \"src/browser/pages/vscode.html\"), \"utf8\"),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // req.baseUrl can be blank if already at the root.\n",
" to: req.baseUrl && req.baseUrl !== \"/\" ? req.baseUrl : undefined,\n"
],
"file_path": "src/node/routes/vscode.ts",
"type": "replace",
"edit_start_line_idx": 17
} | import { Request, Router } from "express"
import qs from "qs"
import { HttpCode, HttpError } from "../../common/http"
import { authenticated, ensureAuthenticated, redirect } from "../http"
import { proxy } from "../proxy"
import { Router as WsRouter } from "../wsRouter"
export const router = Router()
const getProxyTarget = (req: Request, rewrite: boolean): string => {
if (rewrite) {
const query = qs.stringify(req.query)
return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
}
return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
}
router.all("/(:port)(/*)?", (req, res) => {
if (!authenticated(req)) {
// If visiting the root (/proxy/:port and nothing else) redirect to the
// login page.
if (!req.params[0] || req.params[0] === "/") {
return redirect(req, res, "login", {
to: `${req.baseUrl}${req.path}` || "/",
})
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
// Absolute redirects need to be based on the subpath when rewriting.
;(req as any).base = `${req.baseUrl}/${req.params.port}`
proxy.web(req, res, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})
export const wsRouter = WsRouter()
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
proxy.ws(req, req.ws, req.head, {
ignorePath: true,
target: getProxyTarget(req, true),
})
})
| src/node/routes/pathProxy.ts | 1 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.06511491537094116,
0.016696374863386154,
0.00019837381842080504,
0.0030137442518025637,
0.024771645665168762
]
|
{
"id": 5,
"code_window": [
"\n",
"router.get(\"/\", async (req, res) => {\n",
" if (!authenticated(req)) {\n",
" return redirect(req, res, \"login\", {\n",
" to: req.baseUrl,\n",
" })\n",
" }\n",
"\n",
" const [content, options] = await Promise.all([\n",
" await fs.readFile(path.join(rootPath, \"src/browser/pages/vscode.html\"), \"utf8\"),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // req.baseUrl can be blank if already at the root.\n",
" to: req.baseUrl && req.baseUrl !== \"/\" ? req.baseUrl : undefined,\n"
],
"file_path": "src/node/routes/vscode.ts",
"type": "replace",
"edit_start_line_idx": 17
} | export enum HttpCode {
Ok = 200,
Redirect = 302,
NotFound = 404,
BadRequest = 400,
Unauthorized = 401,
LargePayload = 413,
ServerError = 500,
}
/**
* Represents an error with a message and an HTTP status code. This code will be
* used in the HTTP response.
*/
export class HttpError extends Error {
public constructor(message: string, public readonly status: HttpCode, public readonly details?: object) {
super(message)
this.name = this.constructor.name
}
}
| src/common/http.ts | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00020574397058226168,
0.0001913183368742466,
0.00017007385031320155,
0.0001981371606234461,
0.000015339745004894212
]
|
{
"id": 5,
"code_window": [
"\n",
"router.get(\"/\", async (req, res) => {\n",
" if (!authenticated(req)) {\n",
" return redirect(req, res, \"login\", {\n",
" to: req.baseUrl,\n",
" })\n",
" }\n",
"\n",
" const [content, options] = await Promise.all([\n",
" await fs.readFile(path.join(rootPath, \"src/browser/pages/vscode.html\"), \"utf8\"),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // req.baseUrl can be blank if already at the root.\n",
" to: req.baseUrl && req.baseUrl !== \"/\" ? req.baseUrl : undefined,\n"
],
"file_path": "src/node/routes/vscode.ts",
"type": "replace",
"edit_start_line_idx": 17
} | import * as cp from "child_process"
import Bundler from "parcel-bundler"
import * as path from "path"
async function main(): Promise<void> {
try {
const watcher = new Watcher()
await watcher.watch()
} catch (error) {
console.error(error.message)
process.exit(1)
}
}
class Watcher {
private readonly rootPath = path.resolve(__dirname, "../..")
private readonly vscodeSourcePath = path.join(this.rootPath, "lib/vscode")
private static log(message: string, skipNewline = false): void {
process.stdout.write(message)
if (!skipNewline) {
process.stdout.write("\n")
}
}
public async watch(): Promise<void> {
let server: cp.ChildProcess | undefined
const restartServer = (): void => {
if (server) {
server.kill()
}
const s = cp.fork(path.join(this.rootPath, "out/node/entry.js"), process.argv.slice(2))
console.log(`[server] spawned process ${s.pid}`)
s.on("exit", () => console.log(`[server] process ${s.pid} exited`))
server = s
}
const vscode = cp.spawn("yarn", ["watch"], { cwd: this.vscodeSourcePath })
const tsc = cp.spawn("tsc", ["--watch", "--pretty", "--preserveWatchOutput"], { cwd: this.rootPath })
const plugin = process.env.PLUGIN_DIR
? cp.spawn("yarn", ["build", "--watch"], { cwd: process.env.PLUGIN_DIR })
: undefined
const bundler = this.createBundler()
const cleanup = (code?: number | null): void => {
Watcher.log("killing vs code watcher")
vscode.removeAllListeners()
vscode.kill()
Watcher.log("killing tsc")
tsc.removeAllListeners()
tsc.kill()
if (plugin) {
Watcher.log("killing plugin")
plugin.removeAllListeners()
plugin.kill()
}
if (server) {
Watcher.log("killing server")
server.removeAllListeners()
server.kill()
}
Watcher.log("killing bundler")
process.exit(code || 0)
}
process.on("SIGINT", () => cleanup())
process.on("SIGTERM", () => cleanup())
vscode.on("exit", (code) => {
Watcher.log("vs code watcher terminated unexpectedly")
cleanup(code)
})
tsc.on("exit", (code) => {
Watcher.log("tsc terminated unexpectedly")
cleanup(code)
})
if (plugin) {
plugin.on("exit", (code) => {
Watcher.log("plugin terminated unexpectedly")
cleanup(code)
})
}
const bundle = bundler.bundle().catch(() => {
Watcher.log("parcel watcher terminated unexpectedly")
cleanup(1)
})
bundler.on("buildEnd", () => {
console.log("[parcel] bundled")
})
bundler.on("buildError", (error) => {
console.error("[parcel]", error)
})
vscode.stderr.on("data", (d) => process.stderr.write(d))
tsc.stderr.on("data", (d) => process.stderr.write(d))
if (plugin) {
plugin.stderr.on("data", (d) => process.stderr.write(d))
}
// From https://github.com/chalk/ansi-regex
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))",
].join("|")
const re = new RegExp(pattern, "g")
/**
* Split stdout on newlines and strip ANSI codes.
*/
const onLine = (proc: cp.ChildProcess, callback: (strippedLine: string, originalLine: string) => void): void => {
let buffer = ""
if (!proc.stdout) {
throw new Error("no stdout")
}
proc.stdout.setEncoding("utf8")
proc.stdout.on("data", (d) => {
const data = buffer + d
const split = data.split("\n")
const last = split.length - 1
for (let i = 0; i < last; ++i) {
callback(split[i].replace(re, ""), split[i])
}
// The last item will either be an empty string (the data ended with a
// newline) or a partial line (did not end with a newline) and we must
// wait to parse it until we get a full line.
buffer = split[last]
})
}
let startingVscode = false
let startedVscode = false
onLine(vscode, (line, original) => {
console.log("[vscode]", original)
// Wait for watch-client since "Finished compilation" will appear multiple
// times before the client starts building.
if (!startingVscode && line.includes("Starting watch-client")) {
startingVscode = true
} else if (startingVscode && line.includes("Finished compilation")) {
if (startedVscode) {
bundle.then(restartServer)
}
startedVscode = true
}
})
onLine(tsc, (line, original) => {
// tsc outputs blank lines; skip them.
if (line !== "") {
console.log("[tsc]", original)
}
if (line.includes("Watching for file changes")) {
bundle.then(restartServer)
}
})
if (plugin) {
onLine(plugin, (line, original) => {
// tsc outputs blank lines; skip them.
if (line !== "") {
console.log("[plugin]", original)
}
if (line.includes("Watching for file changes")) {
bundle.then(restartServer)
}
})
}
}
private createBundler(out = "dist"): Bundler {
return new Bundler(
[
path.join(this.rootPath, "src/browser/register.ts"),
path.join(this.rootPath, "src/browser/serviceWorker.ts"),
path.join(this.rootPath, "src/browser/pages/login.ts"),
path.join(this.rootPath, "src/browser/pages/vscode.ts"),
],
{
outDir: path.join(this.rootPath, out),
cacheDir: path.join(this.rootPath, ".cache"),
minify: !!process.env.MINIFY,
logLevel: 1,
publicUrl: ".",
},
)
}
}
main()
| ci/dev/watch.ts | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.00224047782830894,
0.00032910885056480765,
0.0001668827171670273,
0.0001738731807563454,
0.0004746667400468141
]
|
{
"id": 5,
"code_window": [
"\n",
"router.get(\"/\", async (req, res) => {\n",
" if (!authenticated(req)) {\n",
" return redirect(req, res, \"login\", {\n",
" to: req.baseUrl,\n",
" })\n",
" }\n",
"\n",
" const [content, options] = await Promise.all([\n",
" await fs.readFile(path.join(rootPath, \"src/browser/pages/vscode.html\"), \"utf8\"),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // req.baseUrl can be blank if already at the root.\n",
" to: req.baseUrl && req.baseUrl !== \"/\" ? req.baseUrl : undefined,\n"
],
"file_path": "src/node/routes/vscode.ts",
"type": "replace",
"edit_start_line_idx": 17
} | import { Router } from "express"
export const router = Router()
router.get("/", (req, res) => {
res.json({
status: req.heart.alive() ? "alive" : "expired",
lastHeartbeat: req.heart.lastHeartbeat,
})
})
| src/node/routes/health.ts | 0 | https://github.com/coder/code-server/commit/71850e312bc981a62af80f96d64c4fef39706b62 | [
0.005292113870382309,
0.002731093904003501,
0.00017007385031320155,
0.002731093904003501,
0.002561019966378808
]
|
{
"id": 0,
"code_window": [
" LiveQueryDataOptions,\n",
" StreamingFrameAction,\n",
" StreamingFrameOptions,\n",
"} from '@grafana/runtime/src/services/live';\n",
"import { BackendDataSourceResponse } from '@grafana/runtime/src/utils/queryResponse';\n",
"import { loadUrlToken } from 'app/core/utils/urlToken';\n",
"\n",
"import { StreamingResponseData } from '../data/utils';\n",
"\n",
"import { LiveDataStream } from './LiveDataStream';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { config, getBackendSrv, getGrafanaLiveSrv, setGrafanaLiveSrv } from '@grafana/runtime';
import { liveTimer } from 'app/features/dashboard/dashgrid/liveTimer';
import { contextSrv } from '../../core/services/context_srv';
import { CentrifugeService } from './centrifuge/service';
import { CentrifugeServiceWorkerProxy } from './centrifuge/serviceWorkerProxy';
import { GrafanaLiveService } from './live';
export const sessionId =
(window as any)?.grafanaBootData?.user?.id +
'/' +
Date.now().toString(16) +
'/' +
Math.random().toString(36).substring(2, 15);
export function initGrafanaLive() {
const centrifugeServiceDeps = {
appUrl: `${window.location.origin}${config.appSubUrl}`,
orgId: contextSrv.user.orgId,
orgRole: contextSrv.user.orgRole,
liveEnabled: config.liveEnabled,
sessionId,
dataStreamSubscriberReadiness: liveTimer.ok.asObservable(),
};
const centrifugeSrv = config.featureToggles['live-service-web-worker']
? new CentrifugeServiceWorkerProxy(centrifugeServiceDeps)
: new CentrifugeService(centrifugeServiceDeps);
setGrafanaLiveSrv(
new GrafanaLiveService({
centrifugeSrv,
backendSrv: getBackendSrv(),
})
);
}
export function getGrafanaLiveCentrifugeSrv() {
return getGrafanaLiveSrv() as GrafanaLiveService;
}
| public/app/features/live/index.ts | 1 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.00021888056653551757,
0.0001863075594883412,
0.00016938699991442263,
0.0001791184622561559,
0.000017917316654347815
]
|
{
"id": 0,
"code_window": [
" LiveQueryDataOptions,\n",
" StreamingFrameAction,\n",
" StreamingFrameOptions,\n",
"} from '@grafana/runtime/src/services/live';\n",
"import { BackendDataSourceResponse } from '@grafana/runtime/src/utils/queryResponse';\n",
"import { loadUrlToken } from 'app/core/utils/urlToken';\n",
"\n",
"import { StreamingResponseData } from '../data/utils';\n",
"\n",
"import { LiveDataStream } from './LiveDataStream';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "replace",
"edit_start_line_idx": 20
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { css } from '@emotion/css';
import cx from 'classnames';
import * as React from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { useStyles2 } from '@grafana/ui';
import { autoColor } from '../Theme';
import { TNil } from '../types';
import { formatDuration } from './utils';
const getStyles = (theme: GrafanaTheme2) => {
return {
Ticks: css`
label: Ticks;
pointer-events: none;
`,
TicksTick: css`
label: TicksTick;
position: absolute;
height: 100%;
width: 1px;
background: ${autoColor(theme, '#d8d8d8')};
&:last-child {
width: 0;
}
`,
TicksTickLabel: css`
label: TicksTickLabel;
left: 0.25rem;
position: absolute;
`,
TicksTickLabelEndAnchor: css`
label: TicksTickLabelEndAnchor;
left: initial;
right: 0.25rem;
`,
};
};
type TicksProps = {
endTime?: number | TNil;
numTicks: number;
showLabels?: boolean | TNil;
startTime?: number | TNil;
};
export default function Ticks(props: TicksProps) {
const { endTime, numTicks, showLabels, startTime } = props;
let labels: undefined | string[];
if (showLabels) {
labels = [];
const viewingDuration = (endTime || 0) - (startTime || 0);
for (let i = 0; i < numTicks; i++) {
const durationAtTick = (startTime || 0) + (i / (numTicks - 1)) * viewingDuration;
labels.push(formatDuration(durationAtTick));
}
}
const styles = useStyles2(getStyles);
const ticks: React.ReactNode[] = [];
for (let i = 0; i < numTicks; i++) {
const portion = i / (numTicks - 1);
ticks.push(
<div
data-testid="TicksID"
key={portion}
className={styles.TicksTick}
style={{
left: `${portion * 100}%`,
}}
>
{labels && (
<span className={cx(styles.TicksTickLabel, { [styles.TicksTickLabelEndAnchor]: portion >= 1 })}>
{labels[i]}
</span>
)}
</div>
);
}
return <div className={styles.Ticks}>{ticks}</div>;
}
Ticks.defaultProps = {
endTime: null,
showLabels: null,
startTime: null,
};
| packages/jaeger-ui-components/src/TraceTimelineViewer/Ticks.tsx | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.00017947901505976915,
0.0001737052807584405,
0.00016808940563350916,
0.00017332567949779332,
0.000003918337824870832
]
|
{
"id": 0,
"code_window": [
" LiveQueryDataOptions,\n",
" StreamingFrameAction,\n",
" StreamingFrameOptions,\n",
"} from '@grafana/runtime/src/services/live';\n",
"import { BackendDataSourceResponse } from '@grafana/runtime/src/utils/queryResponse';\n",
"import { loadUrlToken } from 'app/core/utils/urlToken';\n",
"\n",
"import { StreamingResponseData } from '../data/utils';\n",
"\n",
"import { LiveDataStream } from './LiveDataStream';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { AGGREGATIONS, SYSTEM_LABELS } from './constants';
import {
extractServicesFromMetricDescriptors,
getAggregationOptionsByMetric,
getAlignmentOptionsByMetric,
getAlignmentPickerData,
getLabelKeys,
getMetricTypes,
getMetricTypesByService,
labelsToGroupedOptions,
stringArrayToFilters,
alignmentPeriodLabel,
} from './functions';
import { newMockDatasource } from './specs/testData';
import { AlignmentTypes, MetricDescriptor, MetricKind, ValueTypes } from './types';
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getTemplateSrv: () => ({
replace: jest.fn().mockImplementation((s: string) => s),
}),
}));
describe('functions', () => {
describe('extractServicesFromMetricDescriptors', () => {
it('should return unique metric descriptors', () => {
const desc: MetricDescriptor = {
valueType: '',
metricKind: MetricKind.CUMULATIVE,
type: '',
unit: '',
service: '1',
serviceShortName: '',
displayName: '',
description: '',
};
expect(extractServicesFromMetricDescriptors([desc, desc])).toEqual([desc]);
});
});
describe('getMetricTypesByService', () => {
it('filters by metric descriptiors', () => {
const desc1: MetricDescriptor = {
valueType: '',
metricKind: MetricKind.CUMULATIVE,
type: '',
unit: '',
service: '1',
serviceShortName: '',
displayName: '',
description: '',
};
const desc2: MetricDescriptor = {
valueType: '',
metricKind: MetricKind.CUMULATIVE,
type: '',
unit: '',
service: '2',
serviceShortName: '',
displayName: '',
description: '',
};
expect(getMetricTypesByService([desc1, desc2], '1')).toEqual([desc1]);
});
});
describe('getMetricTypes', () => {
it('gets metric type that exists in the array', () => {
const desc1: MetricDescriptor = {
valueType: '',
metricKind: MetricKind.CUMULATIVE,
type: '1',
unit: '',
service: 'svc1',
serviceShortName: '',
displayName: 'uno',
description: '',
};
const desc2: MetricDescriptor = {
valueType: '',
metricKind: MetricKind.CUMULATIVE,
type: '2',
unit: '',
service: 'svc2',
serviceShortName: '',
displayName: 'dos',
description: '',
};
expect(getMetricTypes([desc1, desc2], '1', '1', 'svc1')).toEqual({
metricTypes: [{ name: 'uno', value: '1' }],
selectedMetricType: '1',
});
});
it('gets metric type that does not exist in the array', () => {
const desc1: MetricDescriptor = {
valueType: '',
metricKind: MetricKind.CUMULATIVE,
type: '1',
unit: '',
service: 'svc1',
serviceShortName: '',
displayName: 'uno',
description: '',
};
const desc2: MetricDescriptor = {
valueType: '',
metricKind: MetricKind.CUMULATIVE,
type: '2',
unit: '',
service: 'svc2',
serviceShortName: '',
displayName: 'dos',
description: '',
};
expect(getMetricTypes([desc1, desc2], '3', '4', 'svc1')).toEqual({
metricTypes: [{ name: 'uno', value: '1' }],
selectedMetricType: '1',
});
});
});
describe('getAlignmentOptionsByMetric', () => {
let result: any;
describe('when double and gauge is passed', () => {
beforeEach(() => {
result = getAlignmentOptionsByMetric(ValueTypes.DOUBLE, MetricKind.GAUGE);
});
it('should return all alignment options except two', () => {
expect(result.length).toBe(10);
expect(result.map((o: any) => o.value)).toEqual(
expect.not.arrayContaining(['REDUCE_COUNT_TRUE', 'REDUCE_COUNT_FALSE'])
);
});
});
describe('when double and delta is passed', () => {
beforeEach(() => {
result = getAlignmentOptionsByMetric(ValueTypes.DOUBLE, MetricKind.DELTA);
});
it('should return all alignment options except four', () => {
expect(result.length).toBe(9);
expect(result.map((o: any) => o.value)).toEqual(
expect.not.arrayContaining([
'ALIGN_COUNT_TRUE',
'ALIGN_COUNT_FALSE',
'ALIGN_FRACTION_TRUE',
'ALIGN_INTERPOLATE',
])
);
});
});
});
describe('getAggregationOptionsByMetric', () => {
it('gets a result for a type and a metric kind', () => {
expect(getAggregationOptionsByMetric(ValueTypes.BOOL, MetricKind.CUMULATIVE)).toEqual([
AGGREGATIONS[0],
AGGREGATIONS[6],
]);
});
});
describe('getLabelKeys', () => {
it('should return labels', async () => {
const ds = newMockDatasource();
ds.getLabels = jest.fn().mockResolvedValue({ l1: true, l2: true });
expect(await getLabelKeys(ds, 'type', 'project')).toEqual(['l1', 'l2', ...SYSTEM_LABELS]);
});
});
describe('getAlignmentPickerData', () => {
it('should return default data', () => {
const res = getAlignmentPickerData();
expect(res.alignOptions).toHaveLength(10);
expect(res.perSeriesAligner).toEqual(AlignmentTypes.ALIGN_MEAN);
});
it('should use provided data', () => {
const res = getAlignmentPickerData(ValueTypes.BOOL, MetricKind.CUMULATIVE);
expect(res.alignOptions).toHaveLength(0);
expect(res.perSeriesAligner).toEqual(AlignmentTypes.ALIGN_MEAN);
});
});
describe('labelsToGroupedOptions', () => {
it('should group in the same label', () => {
expect(labelsToGroupedOptions(['foo', 'bar'])).toEqual([
{
expanded: true,
label: '',
options: [
{ label: 'foo', value: 'foo' },
{ label: 'bar', value: 'bar' },
],
},
]);
});
it('should group in different labels', () => {
expect(labelsToGroupedOptions(['foo.bar', 'foobar'])).toEqual([
{
expanded: true,
label: 'Foo Bar',
options: [{ label: 'foo.bar', value: 'foo.bar' }],
},
{
expanded: true,
label: '',
options: [{ label: 'foobar', value: 'foobar' }],
},
]);
});
});
describe('stringArrayToFilters', () => {
it('chunks an array', () => {
expect(stringArrayToFilters(['key', 'operator', 'value', 'condition'])).toEqual([
{
condition: 'condition',
key: 'key',
operator: 'operator',
value: 'value',
},
]);
});
});
describe('alignmentPeriodLabel', () => {
it('returns period label if alignment period and per series aligner is set', () => {
const datasource = newMockDatasource();
const label = alignmentPeriodLabel({ perSeriesAligner: 'ALIGN_DELTA', alignmentPeriod: '10' }, datasource);
expect(label).toBe('10s interval (delta)');
});
});
});
| public/app/plugins/datasource/cloud-monitoring/functions.test.ts | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.00024276830663438886,
0.0001783571788109839,
0.00016755062097217888,
0.00017583760200068355,
0.000013634396964334883
]
|
{
"id": 0,
"code_window": [
" LiveQueryDataOptions,\n",
" StreamingFrameAction,\n",
" StreamingFrameOptions,\n",
"} from '@grafana/runtime/src/services/live';\n",
"import { BackendDataSourceResponse } from '@grafana/runtime/src/utils/queryResponse';\n",
"import { loadUrlToken } from 'app/core/utils/urlToken';\n",
"\n",
"import { StreamingResponseData } from '../data/utils';\n",
"\n",
"import { LiveDataStream } from './LiveDataStream';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { groupBy } from 'lodash';
import { DataFrame, Field, FieldType, ArrayVector } from '@grafana/data';
export function makeTableFrames(instantMetricFrames: DataFrame[]): DataFrame[] {
// first we remove frames that have no refId
// (we will group them by refId, so we need it to be set)
const framesWithRefId = instantMetricFrames.filter((f) => f.refId !== undefined);
const framesByRefId = groupBy(framesWithRefId, (frame) => frame.refId);
return Object.entries(framesByRefId).map(([refId, frames]) => makeTableFrame(frames, refId));
}
type NumberField = Field<number, ArrayVector<number>>;
type StringField = Field<string, ArrayVector<string>>;
function makeTableFrame(instantMetricFrames: DataFrame[], refId: string): DataFrame {
const tableTimeField: NumberField = { name: 'Time', config: {}, values: new ArrayVector(), type: FieldType.time };
const tableValueField: NumberField = {
name: `Value #${refId}`,
config: {},
values: new ArrayVector(),
type: FieldType.number,
};
// Sort metric labels, create columns for them and record their index
const allLabelNames = new Set(
instantMetricFrames.map((frame) => frame.fields.map((field) => Object.keys(field.labels ?? {})).flat()).flat()
);
const sortedLabelNames = Array.from(allLabelNames).sort();
const labelFields: StringField[] = sortedLabelNames.map((labelName) => ({
name: labelName,
config: { filterable: true },
values: new ArrayVector(),
type: FieldType.string,
}));
instantMetricFrames.forEach((frame) => {
const timeField = frame.fields.find((field) => field.type === FieldType.time);
const valueField = frame.fields.find((field) => field.type === FieldType.number);
if (timeField == null || valueField == null) {
return;
}
const timeArray = timeField.values.toArray();
const valueArray = valueField.values.toArray();
for (let x of timeArray) {
tableTimeField.values.add(x);
}
for (let x of valueArray) {
tableValueField.values.add(x);
}
const labels = valueField.labels ?? {};
for (let f of labelFields) {
const text = labels[f.name] ?? '';
// we insert the labels as many times as we have values
for (let i = 0; i < valueArray.length; i++) {
f.values.add(text);
}
}
});
return {
fields: [tableTimeField, ...labelFields, tableValueField],
refId,
meta: { preferredVisualisationType: 'table' },
length: tableTimeField.values.length,
};
}
| public/app/plugins/datasource/loki/makeTableFrames.ts | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.00017518075765110552,
0.00017129344632849097,
0.00016718165716156363,
0.0001718275307212025,
0.0000027264597974863136
]
|
{
"id": 1,
"code_window": [
"import { LiveDataStream } from './LiveDataStream';\n",
"import { CentrifugeLiveChannel } from './channel';\n",
"\n",
"export type CentrifugeSrvDeps = {\n",
" appUrl: string;\n",
" orgId: number;\n",
" orgRole: string;\n",
" sessionId: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grafanaAuthToken: string | null;\n"
],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "add",
"edit_start_line_idx": 28
} | import { Centrifuge, State } from 'centrifuge';
import { BehaviorSubject, Observable, share, startWith } from 'rxjs';
import {
DataQueryError,
DataQueryResponse,
LiveChannelAddress,
LiveChannelConnectionState,
LiveChannelId,
toLiveChannelId,
} from '@grafana/data';
import { FetchResponse } from '@grafana/runtime/src/services/backendSrv';
import {
GrafanaLiveSrv,
LiveDataStreamOptions,
LiveQueryDataOptions,
StreamingFrameAction,
StreamingFrameOptions,
} from '@grafana/runtime/src/services/live';
import { BackendDataSourceResponse } from '@grafana/runtime/src/utils/queryResponse';
import { loadUrlToken } from 'app/core/utils/urlToken';
import { StreamingResponseData } from '../data/utils';
import { LiveDataStream } from './LiveDataStream';
import { CentrifugeLiveChannel } from './channel';
export type CentrifugeSrvDeps = {
appUrl: string;
orgId: number;
orgRole: string;
sessionId: string;
liveEnabled: boolean;
dataStreamSubscriberReadiness: Observable<boolean>;
};
export type StreamingDataQueryResponse = Omit<DataQueryResponse, 'data'> & { data: [StreamingResponseData] };
export type CentrifugeSrv = Omit<GrafanaLiveSrv, 'publish' | 'getDataStream' | 'getQueryData'> & {
getDataStream: (options: LiveDataStreamOptions) => Observable<StreamingDataQueryResponse>;
getQueryData: (
options: LiveQueryDataOptions
) => Promise<
| { data: BackendDataSourceResponse | undefined }
| FetchResponse<BackendDataSourceResponse | undefined>
| DataQueryError
>;
};
export type DataStreamSubscriptionKey = string;
const defaultStreamingFrameOptions: Readonly<StreamingFrameOptions> = {
maxLength: 100,
maxDelta: Infinity,
action: StreamingFrameAction.Append,
};
const dataStreamShutdownDelayInMs = 5000;
export class CentrifugeService implements CentrifugeSrv {
readonly open = new Map<string, CentrifugeLiveChannel>();
private readonly liveDataStreamByChannelId: Record<LiveChannelId, LiveDataStream> = {};
readonly centrifuge: Centrifuge;
readonly connectionState: BehaviorSubject<boolean>;
readonly connectionBlocker: Promise<void>;
private readonly dataStreamSubscriberReadiness: Observable<boolean>;
constructor(private deps: CentrifugeSrvDeps) {
this.dataStreamSubscriberReadiness = deps.dataStreamSubscriberReadiness.pipe(share(), startWith(true));
let liveUrl = `${deps.appUrl.replace(/^http/, 'ws')}/api/live/ws`;
const token = loadUrlToken();
if (token !== null && token !== '') {
liveUrl += '?auth_token=' + token;
}
this.centrifuge = new Centrifuge(liveUrl, {
timeout: 30000,
});
// orgRole is set when logged in *or* anonymous users can use grafana
if (deps.liveEnabled && deps.orgRole !== '') {
this.centrifuge.connect(); // do connection
}
this.connectionState = new BehaviorSubject<boolean>(this.centrifuge.state === State.Connected);
this.connectionBlocker = new Promise<void>((resolve) => {
if (this.centrifuge.state === State.Connected) {
return resolve();
}
const connectListener = () => {
resolve();
this.centrifuge.removeListener('connected', connectListener);
};
this.centrifuge.addListener('connected', connectListener);
});
// Register global listeners
this.centrifuge.on('connected', this.onConnect);
this.centrifuge.on('connecting', this.onDisconnect);
this.centrifuge.on('disconnected', this.onDisconnect);
this.centrifuge.on('publication', this.onServerSideMessage);
}
//----------------------------------------------------------
// Internal functions
//----------------------------------------------------------
private onConnect = (context: any) => {
this.connectionState.next(true);
};
private onDisconnect = (context: any) => {
this.connectionState.next(false);
};
private onServerSideMessage = (context: any) => {
console.log('Publication from server-side channel', context);
};
/**
* Get a channel. If the scope, namespace, or path is invalid, a shutdown
* channel will be returned with an error state indicated in its status
*/
private getChannel<TMessage>(addr: LiveChannelAddress): CentrifugeLiveChannel<TMessage> {
const id = `${this.deps.orgId}/${addr.scope}/${addr.namespace}/${addr.path}`;
let channel = this.open.get(id);
if (channel != null) {
return channel;
}
channel = new CentrifugeLiveChannel(id, addr);
if (channel.currentStatus.state === LiveChannelConnectionState.Invalid) {
return channel;
}
channel.shutdownCallback = () => {
this.open.delete(id); // remove it from the list of open channels
};
this.open.set(id, channel);
// Initialize the channel in the background
this.initChannel(channel).catch((err) => {
if (channel) {
channel.currentStatus.state = LiveChannelConnectionState.Invalid;
channel.shutdownWithError(err);
}
this.open.delete(id);
});
// return the not-yet initialized channel
return channel;
}
private async initChannel(channel: CentrifugeLiveChannel): Promise<void> {
if (this.centrifuge.state !== State.Connected) {
await this.connectionBlocker;
}
const subscription = this.centrifuge.newSubscription(channel.id, {
data: channel.addr.data,
});
channel.subscription = subscription;
channel.initalize();
subscription.subscribe();
return;
}
//----------------------------------------------------------
// Exported functions
//----------------------------------------------------------
/**
* Listen for changes to the connection state
*/
getConnectionState = () => {
return this.connectionState.asObservable();
};
/**
* Watch for messages in a channel
*/
getStream: CentrifugeSrv['getStream'] = <T>(address: LiveChannelAddress) => {
return this.getChannel<T>(address).getStream();
};
private createSubscriptionKey = (options: LiveDataStreamOptions): DataStreamSubscriptionKey =>
options.key ?? `xstr/${streamCounter++}`;
private getLiveDataStream = (options: LiveDataStreamOptions): LiveDataStream => {
const channelId = toLiveChannelId(options.addr);
const existingStream = this.liveDataStreamByChannelId[channelId];
if (existingStream) {
return existingStream;
}
const channel = this.getChannel(options.addr);
this.liveDataStreamByChannelId[channelId] = new LiveDataStream({
channelId,
onShutdown: () => {
delete this.liveDataStreamByChannelId[channelId];
},
liveEventsObservable: channel.getStream(),
subscriberReadiness: this.dataStreamSubscriberReadiness,
defaultStreamingFrameOptions,
shutdownDelayInMs: dataStreamShutdownDelayInMs,
});
return this.liveDataStreamByChannelId[channelId];
};
/**
* Connect to a channel and return results as DataFrames
*/
getDataStream: CentrifugeSrv['getDataStream'] = (options) => {
const subscriptionKey = this.createSubscriptionKey(options);
const stream = this.getLiveDataStream(options);
return stream.get(options, subscriptionKey);
};
/**
* Executes a query over the live websocket. Query response can contain live channels we can subscribe to for further updates
*
* Since the initial request and subscription are on the same socket, this will support HA setups
*/
getQueryData: CentrifugeSrv['getQueryData'] = async (options) => {
if (this.centrifuge.state !== State.Connected) {
await this.connectionBlocker;
}
return this.centrifuge.rpc('grafana.query', options.body);
};
/**
* For channels that support presence, this will request the current state from the server.
*
* Join and leave messages will be sent to the open stream
*/
getPresence: CentrifugeSrv['getPresence'] = (address) => {
return this.getChannel(address).getPresence();
};
}
// This is used to give a unique key for each stream. The actual value does not matter
let streamCounter = 0;
| public/app/features/live/centrifuge/service.ts | 1 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.9992830157279968,
0.3624190390110016,
0.00016499808407388628,
0.027380749583244324,
0.4475356936454773
]
|
{
"id": 1,
"code_window": [
"import { LiveDataStream } from './LiveDataStream';\n",
"import { CentrifugeLiveChannel } from './channel';\n",
"\n",
"export type CentrifugeSrvDeps = {\n",
" appUrl: string;\n",
" orgId: number;\n",
" orgRole: string;\n",
" sessionId: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grafanaAuthToken: string | null;\n"
],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "add",
"edit_start_line_idx": 28
} | import { DataFrame, DataLink, DataQueryRequest, DataQueryResponse, ScopedVars, TimeRange } from '@grafana/data';
import { getDataSourceSrv } from '@grafana/runtime';
import { AwsUrl, encodeUrl } from '../aws_url';
import { CloudWatchLogsQuery, CloudWatchQuery } from '../types';
type ReplaceFn = (
target?: string,
scopedVars?: ScopedVars,
displayErrorIfIsMultiTemplateVariable?: boolean,
fieldName?: string
) => string;
export async function addDataLinksToLogsResponse(
response: DataQueryResponse,
request: DataQueryRequest<CloudWatchQuery>,
range: TimeRange,
replaceFn: ReplaceFn,
getVariableValueFn: (value: string, scopedVars: ScopedVars) => string[],
getRegion: (region: string) => string,
tracingDatasourceUid?: string
): Promise<void> {
const replace = (target: string, fieldName?: string) => replaceFn(target, request.scopedVars, true, fieldName);
const getVariableValue = (target: string) => getVariableValueFn(target, request.scopedVars);
for (const dataFrame of response.data as DataFrame[]) {
const curTarget = request.targets.find((target) => target.refId === dataFrame.refId) as CloudWatchLogsQuery;
const interpolatedRegion = getRegion(replace(curTarget.region ?? '', 'region'));
for (const field of dataFrame.fields) {
if (field.name === '@xrayTraceId' && tracingDatasourceUid) {
getRegion(replace(curTarget.region ?? '', 'region'));
const xrayLink = await createInternalXrayLink(tracingDatasourceUid, interpolatedRegion);
if (xrayLink) {
field.config.links = [xrayLink];
}
} else {
// Right now we add generic link to open the query in xray console to every field so it shows in the logs row
// details. Unfortunately this also creates link for all values inside table which look weird.
field.config.links = [createAwsConsoleLink(curTarget, range, interpolatedRegion, replace, getVariableValue)];
}
}
}
}
async function createInternalXrayLink(datasourceUid: string, region: string) {
let ds;
try {
ds = await getDataSourceSrv().get(datasourceUid);
} catch (e) {
console.error('Could not load linked xray data source, it was probably deleted after it was linked', e);
return undefined;
}
return {
title: ds.name,
url: '',
internal: {
query: { query: '${__value.raw}', queryType: 'getTrace', region: region },
datasourceUid: datasourceUid,
datasourceName: ds.name,
},
} as DataLink;
}
function createAwsConsoleLink(
target: CloudWatchLogsQuery,
range: TimeRange,
region: string,
replace: (target: string, fieldName?: string) => string,
getVariableValue: (value: string) => string[]
) {
const interpolatedExpression = target.expression ? replace(target.expression) : '';
const interpolatedGroups = target.logGroupNames?.flatMap(getVariableValue) ?? [];
const urlProps: AwsUrl = {
end: range.to.toISOString(),
start: range.from.toISOString(),
timeType: 'ABSOLUTE',
tz: 'UTC',
editorString: interpolatedExpression,
isLiveTail: false,
source: interpolatedGroups,
};
const encodedUrl = encodeUrl(urlProps, region);
return {
url: encodedUrl,
title: 'View in CloudWatch console',
targetBlank: true,
};
}
| public/app/plugins/datasource/cloudwatch/utils/datalinks.ts | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.00017755762382876128,
0.00017022943939082325,
0.0001648762117838487,
0.00017056072829291224,
0.000003857529009110294
]
|
{
"id": 1,
"code_window": [
"import { LiveDataStream } from './LiveDataStream';\n",
"import { CentrifugeLiveChannel } from './channel';\n",
"\n",
"export type CentrifugeSrvDeps = {\n",
" appUrl: string;\n",
" orgId: number;\n",
" orgRole: string;\n",
" sessionId: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grafanaAuthToken: string | null;\n"
],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "add",
"edit_start_line_idx": 28
} | ---
_build:
list: false
aliases:
- /docs/grafana/latest/release-notes/release-notes-8-2-0/
title: Release notes for Grafana 8.2.0
---
<!-- Auto generated by update changelog github action -->
# Release notes for Grafana 8.2.0
### Features and enhancements
- **AWS:** Updated AWS authentication documentation. [#39236](https://github.com/grafana/grafana/pull/39236), [@sunker](https://github.com/sunker)
- **Alerting:** Added support Alertmanager data source for upstream Prometheus AM implementation. [#39775](https://github.com/grafana/grafana/pull/39775), [@domasx2](https://github.com/domasx2)
- **Alerting:** Allows more characters in label names so notifications are sent. [#38629](https://github.com/grafana/grafana/pull/38629), [@gotjosh](https://github.com/gotjosh)
- **Alerting:** Get alert rules for a dashboard or a panel using /api/v1/rules endpoints. [#39476](https://github.com/grafana/grafana/pull/39476), [@gerobinson](https://github.com/gerobinson)
- **Annotations:** Improved rendering performance of event markers. [#39984](https://github.com/grafana/grafana/pull/39984), [@torkelo](https://github.com/torkelo)
- **CloudWatch Logs:** Skip caching for log queries. [#39860](https://github.com/grafana/grafana/pull/39860), [@aocenas](https://github.com/aocenas)
- **Explore:** Added an opt-in configuration for Node Graph in Jaeger, Zipkin, and Tempo. [#39958](https://github.com/grafana/grafana/pull/39958), [@connorlindsey](https://github.com/connorlindsey)
- **Packaging:** Add stricter systemd unit options. [#38109](https://github.com/grafana/grafana/pull/38109), [@erdnaxe](https://github.com/erdnaxe)
- **Prometheus:** Metrics browser can now handle label values with special characters. [#39713](https://github.com/grafana/grafana/pull/39713), [@gabor](https://github.com/gabor)
### Bug fixes
- **CodeEditor:** Ensure that we trigger the latest onSave callback provided to the component. [#39835](https://github.com/grafana/grafana/pull/39835), [@mckn](https://github.com/mckn)
- **DashboardList/AlertList:** Fix for missing All folder value. [#39772](https://github.com/grafana/grafana/pull/39772), [@hugohaggmark](https://github.com/hugohaggmark)
### Breaking changes
#### Potential failure to start in Ubuntu 18.04 / Debian 9 / CentOS
- In Grafana v8.2.0, this change can prevent the `grafana-server` service from starting on older versions of systemd, present on Ubuntu 18.04 and slightly older versions of Debian. If running one of those versions, please wait until v8.2.1 is released before upgrading. If you still want to upgrade or have already ugpraded, a simple fix is available here: https://github.com/grafana/grafana/issues/40162#issuecomment-938060240 Issue [#38109](https://github.com/grafana/grafana/issues/38109)
### Plugin development fixes & changes
- **Plugins:** Create a mock icon component to prevent console errors. [#39901](https://github.com/grafana/grafana/pull/39901), [@jackw](https://github.com/jackw)
| docs/sources/release-notes/release-notes-8-2-0.md | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.0001709140051389113,
0.00016860727919265628,
0.00016508542466908693,
0.0001692148216534406,
0.000002164142870242358
]
|
{
"id": 1,
"code_window": [
"import { LiveDataStream } from './LiveDataStream';\n",
"import { CentrifugeLiveChannel } from './channel';\n",
"\n",
"export type CentrifugeSrvDeps = {\n",
" appUrl: string;\n",
" orgId: number;\n",
" orgRole: string;\n",
" sessionId: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grafanaAuthToken: string | null;\n"
],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "add",
"edit_start_line_idx": 28
} | import { v5 as uuidv5 } from 'uuid';
import { MutableDataFrame } from '@grafana/data';
import { LokiStreamResult, LokiTailResponse } from './types';
const UUID_NAMESPACE = '6ec946da-0f49-47a8-983a-1d76d17e7c92';
/**
* Transform LokiResponse data and appends it to MutableDataFrame. Used for streaming where the dataFrame can be
* a CircularDataFrame creating a fixed size rolling buffer.
* TODO: Probably could be unified with the logStreamToDataFrame function.
* @param response
* @param data Needs to have ts, line, labels, id as fields
*/
export function appendResponseToBufferedData(response: LokiTailResponse, data: MutableDataFrame) {
// Should we do anything with: response.dropped_entries?
const streams: LokiStreamResult[] = response.streams;
if (!streams || !streams.length) {
return;
}
const tsField = data.fields[0];
const lineField = data.fields[1];
const idField = data.fields[2];
// We are comparing used ids only within the received stream. This could be a problem if the same line + labels + nanosecond timestamp came in 2 separate batches.
// As this is very unlikely, and the result would only affect live-tailing css animation we have decided to not compare all received uids from data param as this would slow down processing.
const usedUids: { string?: number } = {};
for (const stream of streams) {
// Find unique labels
const allLabelsString = Object.entries(stream.stream)
.map(([key, val]) => `${key}="${val}"`)
.sort()
.join('');
// Add each line
for (const [ts, line] of stream.values) {
tsField.values.add(new Date(parseInt(ts.slice(0, -6), 10)).toISOString());
lineField.values.add(line);
idField.values.add(createUid(ts, allLabelsString, line, usedUids, data.refId));
}
}
}
function createUid(ts: string, labelsString: string, line: string, usedUids: any, refId?: string): string {
// Generate id as hashed nanosecond timestamp, labels and line (this does not have to be unique)
let id = uuidv5(`${ts}_${labelsString}_${line}`, UUID_NAMESPACE);
// Check if generated id is unique
// If not and we've already used it, append its count after it
if (id in usedUids) {
// Increase the count
const newCount = usedUids[id] + 1;
usedUids[id] = newCount;
// Append count to generated id to make it unique
id = `${id}_${newCount}`;
} else {
// If id is unique and wasn't used, add it to usedUids and start count at 0
usedUids[id] = 0;
}
// Return unique id
if (refId) {
return `${id}_${refId}`;
}
return id;
}
| public/app/plugins/datasource/loki/liveStreamsResultTransformer.ts | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.00017482481780461967,
0.0001701526780379936,
0.00016391201643273234,
0.00017250295786652714,
0.000003995630322606303
]
|
{
"id": 2,
"code_window": [
" constructor(private deps: CentrifugeSrvDeps) {\n",
" this.dataStreamSubscriberReadiness = deps.dataStreamSubscriberReadiness.pipe(share(), startWith(true));\n",
"\n",
" let liveUrl = `${deps.appUrl.replace(/^http/, 'ws')}/api/live/ws`;\n",
"\n",
" const token = loadUrlToken();\n",
" if (token !== null && token !== '') {\n",
" liveUrl += '?auth_token=' + token;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const token = deps.grafanaAuthToken;\n"
],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "replace",
"edit_start_line_idx": 72
} | import { config, getBackendSrv, getGrafanaLiveSrv, setGrafanaLiveSrv } from '@grafana/runtime';
import { liveTimer } from 'app/features/dashboard/dashgrid/liveTimer';
import { contextSrv } from '../../core/services/context_srv';
import { CentrifugeService } from './centrifuge/service';
import { CentrifugeServiceWorkerProxy } from './centrifuge/serviceWorkerProxy';
import { GrafanaLiveService } from './live';
export const sessionId =
(window as any)?.grafanaBootData?.user?.id +
'/' +
Date.now().toString(16) +
'/' +
Math.random().toString(36).substring(2, 15);
export function initGrafanaLive() {
const centrifugeServiceDeps = {
appUrl: `${window.location.origin}${config.appSubUrl}`,
orgId: contextSrv.user.orgId,
orgRole: contextSrv.user.orgRole,
liveEnabled: config.liveEnabled,
sessionId,
dataStreamSubscriberReadiness: liveTimer.ok.asObservable(),
};
const centrifugeSrv = config.featureToggles['live-service-web-worker']
? new CentrifugeServiceWorkerProxy(centrifugeServiceDeps)
: new CentrifugeService(centrifugeServiceDeps);
setGrafanaLiveSrv(
new GrafanaLiveService({
centrifugeSrv,
backendSrv: getBackendSrv(),
})
);
}
export function getGrafanaLiveCentrifugeSrv() {
return getGrafanaLiveSrv() as GrafanaLiveService;
}
| public/app/features/live/index.ts | 1 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.007456640247255564,
0.002780276583507657,
0.00017506637959741056,
0.0021515183616429567,
0.0027179878670722246
]
|
{
"id": 2,
"code_window": [
" constructor(private deps: CentrifugeSrvDeps) {\n",
" this.dataStreamSubscriberReadiness = deps.dataStreamSubscriberReadiness.pipe(share(), startWith(true));\n",
"\n",
" let liveUrl = `${deps.appUrl.replace(/^http/, 'ws')}/api/live/ws`;\n",
"\n",
" const token = loadUrlToken();\n",
" if (token !== null && token !== '') {\n",
" liveUrl += '?auth_token=' + token;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const token = deps.grafanaAuthToken;\n"
],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "replace",
"edit_start_line_idx": 72
} | import { getBackendSrv, locationService } from '@grafana/runtime';
import { accessControlQueryParam } from 'app/core/utils/accessControl';
import { ServiceAccountDTO, ThunkResult } from 'app/types';
import { ServiceAccountToken } from '../components/CreateTokenModal';
import {
serviceAccountFetchBegin,
serviceAccountFetchEnd,
serviceAccountLoaded,
serviceAccountTokensLoaded,
} from './reducers';
const BASE_URL = `/api/serviceaccounts`;
export function loadServiceAccount(saID: number): ThunkResult<void> {
return async (dispatch) => {
dispatch(serviceAccountFetchBegin());
try {
const response = await getBackendSrv().get(`${BASE_URL}/${saID}`, accessControlQueryParam());
dispatch(serviceAccountLoaded(response));
} catch (error) {
console.error(error);
} finally {
dispatch(serviceAccountFetchEnd());
}
};
}
export function updateServiceAccount(serviceAccount: ServiceAccountDTO): ThunkResult<void> {
return async (dispatch) => {
await getBackendSrv().patch(`${BASE_URL}/${serviceAccount.id}?accesscontrol=true`, {
...serviceAccount,
});
dispatch(loadServiceAccount(serviceAccount.id));
};
}
export function deleteServiceAccount(serviceAccountId: number): ThunkResult<void> {
return async () => {
await getBackendSrv().delete(`${BASE_URL}/${serviceAccountId}`);
locationService.push('/org/serviceaccounts');
};
}
export function createServiceAccountToken(
saID: number,
token: ServiceAccountToken,
onTokenCreated: (key: string) => void
): ThunkResult<void> {
return async (dispatch) => {
const result = await getBackendSrv().post(`${BASE_URL}/${saID}/tokens`, token);
onTokenCreated(result.key);
dispatch(loadServiceAccountTokens(saID));
};
}
export function deleteServiceAccountToken(saID: number, id: number): ThunkResult<void> {
return async (dispatch) => {
await getBackendSrv().delete(`${BASE_URL}/${saID}/tokens/${id}`);
dispatch(loadServiceAccountTokens(saID));
};
}
export function loadServiceAccountTokens(saID: number): ThunkResult<void> {
return async (dispatch) => {
try {
const response = await getBackendSrv().get(`${BASE_URL}/${saID}/tokens`);
dispatch(serviceAccountTokensLoaded(response));
} catch (error) {
console.error(error);
}
};
}
| public/app/features/serviceaccounts/state/actionsServiceAccountPage.ts | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.30596017837524414,
0.03841044753789902,
0.00016513597802259028,
0.00017170388309750706,
0.10112430155277252
]
|
{
"id": 2,
"code_window": [
" constructor(private deps: CentrifugeSrvDeps) {\n",
" this.dataStreamSubscriberReadiness = deps.dataStreamSubscriberReadiness.pipe(share(), startWith(true));\n",
"\n",
" let liveUrl = `${deps.appUrl.replace(/^http/, 'ws')}/api/live/ws`;\n",
"\n",
" const token = loadUrlToken();\n",
" if (token !== null && token !== '') {\n",
" liveUrl += '?auth_token=' + token;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const token = deps.grafanaAuthToken;\n"
],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "replace",
"edit_start_line_idx": 72
} | import { toDataFrame, FieldType, DataFrame } from '@grafana/data';
import { joinByLabels } from './joinByLabels';
describe('Join by labels', () => {
it('Simple join', () => {
const input = [
toDataFrame({
fields: [
{ name: 'Time', type: FieldType.time, values: [1, 2] },
{
name: 'Value',
type: FieldType.number,
config: {
displayNameFromDS: '111',
},
values: [10, 200],
labels: { what: 'Temp', cluster: 'A', job: 'J1' },
},
],
}),
toDataFrame({
fields: [
{ name: 'Time', type: FieldType.time, values: [1, 2] },
{
name: 'Value',
type: FieldType.number,
config: {
displayNameFromDS: '222',
},
values: [10, 200],
labels: { what: 'Temp', cluster: 'B', job: 'J1' },
},
],
}),
toDataFrame({
fields: [
{ name: 'Time', type: FieldType.time, values: [22, 28] },
{
name: 'Value',
type: FieldType.number,
config: {
displayNameFromDS: '333',
},
values: [22, 77],
labels: { what: 'Speed', cluster: 'B', job: 'J1' },
},
],
}),
];
const result = joinByLabels(
{
value: 'what',
},
input
);
expect(result.fields[result.fields.length - 1].config).toMatchInlineSnapshot(`Object {}`);
expect(toRowsSnapshow(result)).toMatchInlineSnapshot(`
Object {
"columns": Array [
"cluster",
"job",
"Temp",
"Speed",
],
"rows": Array [
Array [
"A",
"J1",
10,
undefined,
],
Array [
"A",
"J1",
200,
undefined,
],
Array [
"B",
"J1",
10,
22,
],
Array [
"B",
"J1",
200,
77,
],
],
}
`);
});
it('Error handling (no labels)', () => {
const input = [
toDataFrame({
fields: [
{ name: 'Time', type: FieldType.time, values: [1, 2] },
{
name: 'Value',
type: FieldType.number,
values: [10, 200],
},
],
}),
];
const result = joinByLabels(
{
value: 'what',
},
input
);
expect(result).toMatchInlineSnapshot(`
Object {
"fields": Array [
Object {
"config": Object {},
"name": "Error",
"type": "string",
"values": Array [
"No labels in result",
],
},
],
"length": 0,
"meta": Object {
"notices": Array [
Object {
"severity": "error",
"text": "No labels in result",
},
],
},
}
`);
});
});
function toRowsSnapshow(frame: DataFrame) {
const columns = frame.fields.map((f) => f.name);
const rows = frame.fields[0].values.toArray().map((v, idx) => {
return frame.fields.map((f) => f.values.get(idx));
});
return {
columns,
rows,
};
}
| public/app/features/transformers/joinByLabels/joinByLabels.test.ts | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.00017791468417271972,
0.00017533282516524196,
0.00017254342674277723,
0.00017514036153443158,
0.0000015087990732354228
]
|
{
"id": 2,
"code_window": [
" constructor(private deps: CentrifugeSrvDeps) {\n",
" this.dataStreamSubscriberReadiness = deps.dataStreamSubscriberReadiness.pipe(share(), startWith(true));\n",
"\n",
" let liveUrl = `${deps.appUrl.replace(/^http/, 'ws')}/api/live/ws`;\n",
"\n",
" const token = loadUrlToken();\n",
" if (token !== null && token !== '') {\n",
" liveUrl += '?auth_token=' + token;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const token = deps.grafanaAuthToken;\n"
],
"file_path": "public/app/features/live/centrifuge/service.ts",
"type": "replace",
"edit_start_line_idx": 72
} | import { screen, render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { DashboardModel } from 'app/features/dashboard/state';
import * as api from 'app/features/manage-dashboards/state/actions';
import { SaveDashboardAsForm, SaveDashboardAsFormProps } from './SaveDashboardAsForm';
jest.mock('app/features/plugins/datasource_srv', () => ({}));
jest.mock('app/features/expressions/ExpressionDatasource', () => ({}));
jest.mock('app/features/manage-dashboards/services/ValidationSrv', () => ({
validationSrv: {
validateNewDashboardName: () => true,
},
}));
jest.spyOn(api, 'searchFolders').mockResolvedValue([]);
const prepareDashboardMock = (panel: any) => {
const json = {
title: 'name',
panels: [panel],
};
return {
id: 5,
meta: {},
...json,
getSaveModelClone: () => json,
};
};
const renderAndSubmitForm = async (
dashboard: unknown,
submitSpy: jest.Mock,
otherProps: Partial<SaveDashboardAsFormProps> = {}
) => {
render(
<SaveDashboardAsForm
dashboard={dashboard as DashboardModel}
onCancel={() => {}}
onSuccess={() => {}}
onSubmit={async (jsonModel) => {
submitSpy(jsonModel);
return {};
}}
{...otherProps}
/>
);
const button = screen.getByRole('button', { name: 'Save dashboard button' });
await userEvent.click(button);
};
describe('SaveDashboardAsForm', () => {
describe('default values', () => {
it('applies default dashboard properties', async () => {
jest.spyOn(api, 'searchFolders').mockResolvedValue([]);
const spy = jest.fn();
await renderAndSubmitForm(prepareDashboardMock({}), spy, {
isNew: true,
});
expect(spy).toBeCalledTimes(1);
const savedDashboardModel = spy.mock.calls[0][0];
expect(savedDashboardModel.id).toBe(null);
expect(savedDashboardModel.title).toBe('name');
expect(savedDashboardModel.editable).toBe(true);
});
it("appends 'Copy' to the name when the dashboard isnt new", async () => {
jest.spyOn(api, 'searchFolders').mockResolvedValue([]);
const spy = jest.fn();
await renderAndSubmitForm(prepareDashboardMock({}), spy, {
isNew: false,
});
expect(spy).toBeCalledTimes(1);
const savedDashboardModel = spy.mock.calls[0][0];
expect(savedDashboardModel.title).toBe('name Copy');
});
});
describe('graph panel', () => {
const panel = {
id: 1,
type: 'graph',
alert: { rule: 1 },
thresholds: { value: 3000 },
};
it('should remove alerts and thresholds from panel', async () => {
const spy = jest.fn();
await renderAndSubmitForm(prepareDashboardMock(panel), spy);
expect(spy).toBeCalledTimes(1);
const savedDashboardModel = spy.mock.calls[0][0];
expect(savedDashboardModel.panels[0]).toEqual({ id: 1, type: 'graph' });
});
});
describe('singestat panel', () => {
const panel = { id: 1, type: 'singlestat', thresholds: { value: 3000 } };
it('should keep thresholds', async () => {
const spy = jest.fn();
await renderAndSubmitForm(prepareDashboardMock(panel), spy);
expect(spy).toBeCalledTimes(1);
const savedDashboardModel = spy.mock.calls[0][0];
expect(savedDashboardModel.panels[0].thresholds).not.toBe(undefined);
});
});
describe('table panel', () => {
const panel = { id: 1, type: 'table', thresholds: { value: 3000 } };
it('should keep thresholds', async () => {
const spy = jest.fn();
await renderAndSubmitForm(prepareDashboardMock(panel), spy);
expect(spy).toBeCalledTimes(1);
const savedDashboardModel = spy.mock.calls[0][0];
expect(savedDashboardModel.panels[0].thresholds).not.toBe(undefined);
});
});
});
| public/app/features/dashboard/components/SaveDashboard/forms/SaveDashboardAsForm.test.tsx | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.0001782089238986373,
0.00017559622938279063,
0.00017308224050793797,
0.0001754002005327493,
0.0000014150600691209547
]
|
{
"id": 3,
"code_window": [
"import { liveTimer } from 'app/features/dashboard/dashgrid/liveTimer';\n",
"\n",
"import { contextSrv } from '../../core/services/context_srv';\n",
"\n",
"import { CentrifugeService } from './centrifuge/service';\n",
"import { CentrifugeServiceWorkerProxy } from './centrifuge/serviceWorkerProxy';\n",
"import { GrafanaLiveService } from './live';\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { loadUrlToken } from '../../core/utils/urlToken';\n"
],
"file_path": "public/app/features/live/index.ts",
"type": "add",
"edit_start_line_idx": 4
} | import { Centrifuge, State } from 'centrifuge';
import { BehaviorSubject, Observable, share, startWith } from 'rxjs';
import {
DataQueryError,
DataQueryResponse,
LiveChannelAddress,
LiveChannelConnectionState,
LiveChannelId,
toLiveChannelId,
} from '@grafana/data';
import { FetchResponse } from '@grafana/runtime/src/services/backendSrv';
import {
GrafanaLiveSrv,
LiveDataStreamOptions,
LiveQueryDataOptions,
StreamingFrameAction,
StreamingFrameOptions,
} from '@grafana/runtime/src/services/live';
import { BackendDataSourceResponse } from '@grafana/runtime/src/utils/queryResponse';
import { loadUrlToken } from 'app/core/utils/urlToken';
import { StreamingResponseData } from '../data/utils';
import { LiveDataStream } from './LiveDataStream';
import { CentrifugeLiveChannel } from './channel';
export type CentrifugeSrvDeps = {
appUrl: string;
orgId: number;
orgRole: string;
sessionId: string;
liveEnabled: boolean;
dataStreamSubscriberReadiness: Observable<boolean>;
};
export type StreamingDataQueryResponse = Omit<DataQueryResponse, 'data'> & { data: [StreamingResponseData] };
export type CentrifugeSrv = Omit<GrafanaLiveSrv, 'publish' | 'getDataStream' | 'getQueryData'> & {
getDataStream: (options: LiveDataStreamOptions) => Observable<StreamingDataQueryResponse>;
getQueryData: (
options: LiveQueryDataOptions
) => Promise<
| { data: BackendDataSourceResponse | undefined }
| FetchResponse<BackendDataSourceResponse | undefined>
| DataQueryError
>;
};
export type DataStreamSubscriptionKey = string;
const defaultStreamingFrameOptions: Readonly<StreamingFrameOptions> = {
maxLength: 100,
maxDelta: Infinity,
action: StreamingFrameAction.Append,
};
const dataStreamShutdownDelayInMs = 5000;
export class CentrifugeService implements CentrifugeSrv {
readonly open = new Map<string, CentrifugeLiveChannel>();
private readonly liveDataStreamByChannelId: Record<LiveChannelId, LiveDataStream> = {};
readonly centrifuge: Centrifuge;
readonly connectionState: BehaviorSubject<boolean>;
readonly connectionBlocker: Promise<void>;
private readonly dataStreamSubscriberReadiness: Observable<boolean>;
constructor(private deps: CentrifugeSrvDeps) {
this.dataStreamSubscriberReadiness = deps.dataStreamSubscriberReadiness.pipe(share(), startWith(true));
let liveUrl = `${deps.appUrl.replace(/^http/, 'ws')}/api/live/ws`;
const token = loadUrlToken();
if (token !== null && token !== '') {
liveUrl += '?auth_token=' + token;
}
this.centrifuge = new Centrifuge(liveUrl, {
timeout: 30000,
});
// orgRole is set when logged in *or* anonymous users can use grafana
if (deps.liveEnabled && deps.orgRole !== '') {
this.centrifuge.connect(); // do connection
}
this.connectionState = new BehaviorSubject<boolean>(this.centrifuge.state === State.Connected);
this.connectionBlocker = new Promise<void>((resolve) => {
if (this.centrifuge.state === State.Connected) {
return resolve();
}
const connectListener = () => {
resolve();
this.centrifuge.removeListener('connected', connectListener);
};
this.centrifuge.addListener('connected', connectListener);
});
// Register global listeners
this.centrifuge.on('connected', this.onConnect);
this.centrifuge.on('connecting', this.onDisconnect);
this.centrifuge.on('disconnected', this.onDisconnect);
this.centrifuge.on('publication', this.onServerSideMessage);
}
//----------------------------------------------------------
// Internal functions
//----------------------------------------------------------
private onConnect = (context: any) => {
this.connectionState.next(true);
};
private onDisconnect = (context: any) => {
this.connectionState.next(false);
};
private onServerSideMessage = (context: any) => {
console.log('Publication from server-side channel', context);
};
/**
* Get a channel. If the scope, namespace, or path is invalid, a shutdown
* channel will be returned with an error state indicated in its status
*/
private getChannel<TMessage>(addr: LiveChannelAddress): CentrifugeLiveChannel<TMessage> {
const id = `${this.deps.orgId}/${addr.scope}/${addr.namespace}/${addr.path}`;
let channel = this.open.get(id);
if (channel != null) {
return channel;
}
channel = new CentrifugeLiveChannel(id, addr);
if (channel.currentStatus.state === LiveChannelConnectionState.Invalid) {
return channel;
}
channel.shutdownCallback = () => {
this.open.delete(id); // remove it from the list of open channels
};
this.open.set(id, channel);
// Initialize the channel in the background
this.initChannel(channel).catch((err) => {
if (channel) {
channel.currentStatus.state = LiveChannelConnectionState.Invalid;
channel.shutdownWithError(err);
}
this.open.delete(id);
});
// return the not-yet initialized channel
return channel;
}
private async initChannel(channel: CentrifugeLiveChannel): Promise<void> {
if (this.centrifuge.state !== State.Connected) {
await this.connectionBlocker;
}
const subscription = this.centrifuge.newSubscription(channel.id, {
data: channel.addr.data,
});
channel.subscription = subscription;
channel.initalize();
subscription.subscribe();
return;
}
//----------------------------------------------------------
// Exported functions
//----------------------------------------------------------
/**
* Listen for changes to the connection state
*/
getConnectionState = () => {
return this.connectionState.asObservable();
};
/**
* Watch for messages in a channel
*/
getStream: CentrifugeSrv['getStream'] = <T>(address: LiveChannelAddress) => {
return this.getChannel<T>(address).getStream();
};
private createSubscriptionKey = (options: LiveDataStreamOptions): DataStreamSubscriptionKey =>
options.key ?? `xstr/${streamCounter++}`;
private getLiveDataStream = (options: LiveDataStreamOptions): LiveDataStream => {
const channelId = toLiveChannelId(options.addr);
const existingStream = this.liveDataStreamByChannelId[channelId];
if (existingStream) {
return existingStream;
}
const channel = this.getChannel(options.addr);
this.liveDataStreamByChannelId[channelId] = new LiveDataStream({
channelId,
onShutdown: () => {
delete this.liveDataStreamByChannelId[channelId];
},
liveEventsObservable: channel.getStream(),
subscriberReadiness: this.dataStreamSubscriberReadiness,
defaultStreamingFrameOptions,
shutdownDelayInMs: dataStreamShutdownDelayInMs,
});
return this.liveDataStreamByChannelId[channelId];
};
/**
* Connect to a channel and return results as DataFrames
*/
getDataStream: CentrifugeSrv['getDataStream'] = (options) => {
const subscriptionKey = this.createSubscriptionKey(options);
const stream = this.getLiveDataStream(options);
return stream.get(options, subscriptionKey);
};
/**
* Executes a query over the live websocket. Query response can contain live channels we can subscribe to for further updates
*
* Since the initial request and subscription are on the same socket, this will support HA setups
*/
getQueryData: CentrifugeSrv['getQueryData'] = async (options) => {
if (this.centrifuge.state !== State.Connected) {
await this.connectionBlocker;
}
return this.centrifuge.rpc('grafana.query', options.body);
};
/**
* For channels that support presence, this will request the current state from the server.
*
* Join and leave messages will be sent to the open stream
*/
getPresence: CentrifugeSrv['getPresence'] = (address) => {
return this.getChannel(address).getPresence();
};
}
// This is used to give a unique key for each stream. The actual value does not matter
let streamCounter = 0;
| public/app/features/live/centrifuge/service.ts | 1 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.014558766037225723,
0.0016003322089090943,
0.00016583214164711535,
0.0002758313494268805,
0.0029778622556477785
]
|
{
"id": 3,
"code_window": [
"import { liveTimer } from 'app/features/dashboard/dashgrid/liveTimer';\n",
"\n",
"import { contextSrv } from '../../core/services/context_srv';\n",
"\n",
"import { CentrifugeService } from './centrifuge/service';\n",
"import { CentrifugeServiceWorkerProxy } from './centrifuge/serviceWorkerProxy';\n",
"import { GrafanaLiveService } from './live';\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { loadUrlToken } from '../../core/utils/urlToken';\n"
],
"file_path": "public/app/features/live/index.ts",
"type": "add",
"edit_start_line_idx": 4
} | import { of } from 'rxjs';
import {
DataSourceInstanceSettings,
DataSourcePluginMeta,
PluginMetaInfo,
PluginType,
VariableHide,
} from '@grafana/data';
import { getBackendSrv, setBackendSrv } from '@grafana/runtime';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { TemplateSrv } from 'app/features/templating/template_srv';
import { initialCustomVariableModelState } from 'app/features/variables/custom/reducer';
import { CustomVariableModel } from 'app/features/variables/types';
import { CloudWatchDatasource } from '../datasource';
import { CloudWatchJsonData } from '../types';
export function setupMockedTemplateService(variables: CustomVariableModel[]) {
const templateService = new TemplateSrv();
templateService.init(variables);
templateService.getVariables = jest.fn().mockReturnValue(variables);
return templateService;
}
const info: PluginMetaInfo = {
author: {
name: '',
},
description: '',
links: [],
logos: {
large: '',
small: '',
},
screenshots: [],
updated: '',
version: '',
};
export const meta: DataSourcePluginMeta<CloudWatchJsonData> = {
id: '',
name: '',
type: PluginType.datasource,
info,
module: '',
baseUrl: '',
};
export const CloudWatchSettings: DataSourceInstanceSettings<CloudWatchJsonData> = {
jsonData: { defaultRegion: 'us-west-1', tracingDatasourceUid: 'xray' },
id: 0,
uid: '',
type: '',
name: 'CloudWatch Test Datasource',
meta,
readOnly: false,
access: 'direct',
};
export function setupMockedDataSource({
variables,
mockGetVariableName = true,
}: {
variables?: CustomVariableModel[];
mockGetVariableName?: boolean;
} = {}) {
let templateService = new TemplateSrv();
if (variables) {
templateService = setupMockedTemplateService(variables);
if (mockGetVariableName) {
templateService.getVariableName = (name: string) => name;
}
}
const timeSrv = getTimeSrv();
const datasource = new CloudWatchDatasource(CloudWatchSettings, templateService, timeSrv);
datasource.getVariables = () => ['test'];
datasource.api.describeLogGroups = jest.fn().mockResolvedValue([]);
datasource.api.getNamespaces = jest.fn().mockResolvedValue([]);
datasource.api.getRegions = jest.fn().mockResolvedValue([]);
datasource.logsQueryRunner.defaultLogGroups = [];
const fetchMock = jest.fn().mockReturnValue(of({}));
setBackendSrv({
...getBackendSrv(),
fetch: fetchMock,
get: jest.fn(),
});
return { datasource, fetchMock, templateService, timeSrv };
}
export const metricVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'metric',
name: 'metric',
current: { value: 'CPUUtilization', text: 'CPUUtilizationEC2', selected: true },
options: [
{ value: 'DroppedBytes', text: 'DroppedBytes', selected: false },
{ value: 'CPUUtilization', text: 'CPUUtilization', selected: false },
],
multi: false,
};
export const namespaceVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'namespace',
name: 'namespace',
query: 'namespaces()',
current: { value: 'AWS/EC2', text: 'AWS/EC2', selected: true },
options: [
{ value: 'AWS/Redshift', text: 'AWS/Redshift', selected: false },
{ value: 'AWS/EC2', text: 'AWS/EC2', selected: false },
{ value: 'AWS/MQ', text: 'AWS/MQ', selected: false },
],
multi: false,
};
export const labelsVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'labels',
name: 'labels',
current: {
value: ['InstanceId', 'InstanceType'],
text: ['InstanceId', 'InstanceType'].toString(),
selected: true,
},
options: [
{ value: 'InstanceId', text: 'InstanceId', selected: false },
{ value: 'InstanceType', text: 'InstanceType', selected: false },
],
multi: true,
};
export const limitVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'limit',
name: 'limit',
current: {
value: '100',
text: '100',
selected: true,
},
options: [
{ value: '10', text: '10', selected: false },
{ value: '100', text: '100', selected: false },
{ value: '1000', text: '1000', selected: false },
],
multi: false,
};
export const aggregationvariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'aggregation',
name: 'aggregation',
current: {
value: 'AVG',
text: 'AVG',
selected: true,
},
options: [
{ value: 'AVG', text: 'AVG', selected: false },
{ value: 'SUM', text: 'SUM', selected: false },
{ value: 'MIN', text: 'MIN', selected: false },
],
multi: false,
};
export const dimensionVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'dimension',
name: 'dimension',
current: {
value: 'env',
text: 'env',
selected: true,
},
options: [
{ value: 'env', text: 'env', selected: false },
{ value: 'tag', text: 'tag', selected: false },
],
multi: false,
};
export const logGroupNamesVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'groups',
name: 'groups',
current: {
value: ['templatedGroup-1', 'templatedGroup-2'],
text: ['templatedGroup-1', 'templatedGroup-2'],
selected: true,
},
options: [
{ value: 'templatedGroup-1', text: 'templatedGroup-1', selected: true },
{ value: 'templatedGroup-2', text: 'templatedGroup-2', selected: true },
],
multi: true,
};
export const regionVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'region',
name: 'region',
current: {
value: 'templatedRegion',
text: 'templatedRegion',
selected: true,
},
options: [{ value: 'templatedRegion', text: 'templatedRegion', selected: true }],
multi: false,
};
export const fieldsVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'fields',
name: 'fields',
current: {
value: 'templatedField',
text: 'templatedField',
selected: true,
},
options: [{ value: 'templatedField', text: 'templatedField', selected: true }],
multi: false,
};
export const periodIntervalVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'period',
name: 'period',
index: 0,
current: { value: '10m', text: '10m', selected: true },
options: [{ value: '10m', text: '10m', selected: true }],
multi: false,
includeAll: false,
query: '',
hide: VariableHide.dontHide,
type: 'custom',
};
| public/app/plugins/datasource/cloudwatch/__mocks__/CloudWatchDataSource.ts | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.000216634914977476,
0.00017689098604023457,
0.00016550767759326845,
0.00017651442612987012,
0.000009269196198147256
]
|
{
"id": 3,
"code_window": [
"import { liveTimer } from 'app/features/dashboard/dashgrid/liveTimer';\n",
"\n",
"import { contextSrv } from '../../core/services/context_srv';\n",
"\n",
"import { CentrifugeService } from './centrifuge/service';\n",
"import { CentrifugeServiceWorkerProxy } from './centrifuge/serviceWorkerProxy';\n",
"import { GrafanaLiveService } from './live';\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { loadUrlToken } from '../../core/utils/urlToken';\n"
],
"file_path": "public/app/features/live/index.ts",
"type": "add",
"edit_start_line_idx": 4
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M17,11H5.41l2.3-2.29A1,1,0,1,0,6.29,7.29l-4,4a1,1,0,0,0-.21.33,1,1,0,0,0,0,.76,1,1,0,0,0,.21.33l4,4a1,1,0,0,0,1.42,0,1,1,0,0,0,0-1.42L5.41,13H17a1,1,0,0,0,0-2Zm4-7a1,1,0,0,0-1,1V19a1,1,0,0,0,2,0V5A1,1,0,0,0,21,4Z"/></svg> | public/img/icons/unicons/left-arrow-from-left.svg | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.0001739244908094406,
0.0001739244908094406,
0.0001739244908094406,
0.0001739244908094406,
0
]
|
{
"id": 3,
"code_window": [
"import { liveTimer } from 'app/features/dashboard/dashgrid/liveTimer';\n",
"\n",
"import { contextSrv } from '../../core/services/context_srv';\n",
"\n",
"import { CentrifugeService } from './centrifuge/service';\n",
"import { CentrifugeServiceWorkerProxy } from './centrifuge/serviceWorkerProxy';\n",
"import { GrafanaLiveService } from './live';\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { loadUrlToken } from '../../core/utils/urlToken';\n"
],
"file_path": "public/app/features/live/index.ts",
"type": "add",
"edit_start_line_idx": 4
} | import React from 'react';
import { FieldSet, InlineField } from '@grafana/ui';
import { NumberInput } from 'app/core/components/OptionsUI/NumberInput';
import { SQLConnectionLimits } from '../../types';
interface Props<T> {
onPropertyChanged: (property: keyof T, value?: number) => void;
labelWidth: number;
jsonData: SQLConnectionLimits;
}
export const ConnectionLimits = <T extends SQLConnectionLimits>(props: Props<T>) => {
const { onPropertyChanged, labelWidth, jsonData } = props;
const onJSONDataNumberChanged = (property: keyof SQLConnectionLimits) => {
return (number?: number) => {
if (onPropertyChanged) {
onPropertyChanged(property, number);
}
};
};
return (
<FieldSet label="Connection limits">
<InlineField
tooltip={
<span>
The maximum number of open connections to the database.If <i>Max idle connections</i> is greater than 0 and
the <i>Max open connections</i> is less than <i>Max idle connections</i>, then
<i>Max idle connections</i> will be reduced to match the <i>Max open connections</i> limit. If set to 0,
there is no limit on the number of open connections.
</span>
}
labelWidth={labelWidth}
label="Max open"
>
<NumberInput
placeholder="unlimited"
value={jsonData.maxOpenConns}
onChange={onJSONDataNumberChanged('maxOpenConns')}
></NumberInput>
</InlineField>
<InlineField
tooltip={
<span>
The maximum number of connections in the idle connection pool.If <i>Max open connections</i> is greater than
0 but less than the <i>Max idle connections</i>, then the <i>Max idle connections</i> will be reduced to
match the <i>Max open connections</i> limit. If set to 0, no idle connections are retained.
</span>
}
labelWidth={labelWidth}
label="Max idle"
>
<NumberInput
placeholder="2"
value={jsonData.maxIdleConns}
onChange={onJSONDataNumberChanged('maxIdleConns')}
></NumberInput>
</InlineField>
<InlineField
tooltip="The maximum amount of time in seconds a connection may be reused. If set to 0, connections are reused forever."
labelWidth={labelWidth}
label="Max lifetime"
>
<NumberInput
placeholder="14400"
value={jsonData.connMaxLifetime}
onChange={onJSONDataNumberChanged('connMaxLifetime')}
></NumberInput>
</InlineField>
</FieldSet>
);
};
| public/app/features/plugins/sql/components/configuration/ConnectionLimits.tsx | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.00017693027621135116,
0.00017205778567586094,
0.00016522069927304983,
0.00017384852981194854,
0.000004666387212637346
]
|
{
"id": 4,
"code_window": [
" orgId: contextSrv.user.orgId,\n",
" orgRole: contextSrv.user.orgRole,\n",
" liveEnabled: config.liveEnabled,\n",
" sessionId,\n",
" dataStreamSubscriberReadiness: liveTimer.ok.asObservable(),\n",
" };\n",
"\n",
" const centrifugeSrv = config.featureToggles['live-service-web-worker']\n",
" ? new CentrifugeServiceWorkerProxy(centrifugeServiceDeps)\n",
" : new CentrifugeService(centrifugeServiceDeps);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grafanaAuthToken: loadUrlToken(),\n"
],
"file_path": "public/app/features/live/index.ts",
"type": "add",
"edit_start_line_idx": 24
} | import { Centrifuge, State } from 'centrifuge';
import { BehaviorSubject, Observable, share, startWith } from 'rxjs';
import {
DataQueryError,
DataQueryResponse,
LiveChannelAddress,
LiveChannelConnectionState,
LiveChannelId,
toLiveChannelId,
} from '@grafana/data';
import { FetchResponse } from '@grafana/runtime/src/services/backendSrv';
import {
GrafanaLiveSrv,
LiveDataStreamOptions,
LiveQueryDataOptions,
StreamingFrameAction,
StreamingFrameOptions,
} from '@grafana/runtime/src/services/live';
import { BackendDataSourceResponse } from '@grafana/runtime/src/utils/queryResponse';
import { loadUrlToken } from 'app/core/utils/urlToken';
import { StreamingResponseData } from '../data/utils';
import { LiveDataStream } from './LiveDataStream';
import { CentrifugeLiveChannel } from './channel';
export type CentrifugeSrvDeps = {
appUrl: string;
orgId: number;
orgRole: string;
sessionId: string;
liveEnabled: boolean;
dataStreamSubscriberReadiness: Observable<boolean>;
};
export type StreamingDataQueryResponse = Omit<DataQueryResponse, 'data'> & { data: [StreamingResponseData] };
export type CentrifugeSrv = Omit<GrafanaLiveSrv, 'publish' | 'getDataStream' | 'getQueryData'> & {
getDataStream: (options: LiveDataStreamOptions) => Observable<StreamingDataQueryResponse>;
getQueryData: (
options: LiveQueryDataOptions
) => Promise<
| { data: BackendDataSourceResponse | undefined }
| FetchResponse<BackendDataSourceResponse | undefined>
| DataQueryError
>;
};
export type DataStreamSubscriptionKey = string;
const defaultStreamingFrameOptions: Readonly<StreamingFrameOptions> = {
maxLength: 100,
maxDelta: Infinity,
action: StreamingFrameAction.Append,
};
const dataStreamShutdownDelayInMs = 5000;
export class CentrifugeService implements CentrifugeSrv {
readonly open = new Map<string, CentrifugeLiveChannel>();
private readonly liveDataStreamByChannelId: Record<LiveChannelId, LiveDataStream> = {};
readonly centrifuge: Centrifuge;
readonly connectionState: BehaviorSubject<boolean>;
readonly connectionBlocker: Promise<void>;
private readonly dataStreamSubscriberReadiness: Observable<boolean>;
constructor(private deps: CentrifugeSrvDeps) {
this.dataStreamSubscriberReadiness = deps.dataStreamSubscriberReadiness.pipe(share(), startWith(true));
let liveUrl = `${deps.appUrl.replace(/^http/, 'ws')}/api/live/ws`;
const token = loadUrlToken();
if (token !== null && token !== '') {
liveUrl += '?auth_token=' + token;
}
this.centrifuge = new Centrifuge(liveUrl, {
timeout: 30000,
});
// orgRole is set when logged in *or* anonymous users can use grafana
if (deps.liveEnabled && deps.orgRole !== '') {
this.centrifuge.connect(); // do connection
}
this.connectionState = new BehaviorSubject<boolean>(this.centrifuge.state === State.Connected);
this.connectionBlocker = new Promise<void>((resolve) => {
if (this.centrifuge.state === State.Connected) {
return resolve();
}
const connectListener = () => {
resolve();
this.centrifuge.removeListener('connected', connectListener);
};
this.centrifuge.addListener('connected', connectListener);
});
// Register global listeners
this.centrifuge.on('connected', this.onConnect);
this.centrifuge.on('connecting', this.onDisconnect);
this.centrifuge.on('disconnected', this.onDisconnect);
this.centrifuge.on('publication', this.onServerSideMessage);
}
//----------------------------------------------------------
// Internal functions
//----------------------------------------------------------
private onConnect = (context: any) => {
this.connectionState.next(true);
};
private onDisconnect = (context: any) => {
this.connectionState.next(false);
};
private onServerSideMessage = (context: any) => {
console.log('Publication from server-side channel', context);
};
/**
* Get a channel. If the scope, namespace, or path is invalid, a shutdown
* channel will be returned with an error state indicated in its status
*/
private getChannel<TMessage>(addr: LiveChannelAddress): CentrifugeLiveChannel<TMessage> {
const id = `${this.deps.orgId}/${addr.scope}/${addr.namespace}/${addr.path}`;
let channel = this.open.get(id);
if (channel != null) {
return channel;
}
channel = new CentrifugeLiveChannel(id, addr);
if (channel.currentStatus.state === LiveChannelConnectionState.Invalid) {
return channel;
}
channel.shutdownCallback = () => {
this.open.delete(id); // remove it from the list of open channels
};
this.open.set(id, channel);
// Initialize the channel in the background
this.initChannel(channel).catch((err) => {
if (channel) {
channel.currentStatus.state = LiveChannelConnectionState.Invalid;
channel.shutdownWithError(err);
}
this.open.delete(id);
});
// return the not-yet initialized channel
return channel;
}
private async initChannel(channel: CentrifugeLiveChannel): Promise<void> {
if (this.centrifuge.state !== State.Connected) {
await this.connectionBlocker;
}
const subscription = this.centrifuge.newSubscription(channel.id, {
data: channel.addr.data,
});
channel.subscription = subscription;
channel.initalize();
subscription.subscribe();
return;
}
//----------------------------------------------------------
// Exported functions
//----------------------------------------------------------
/**
* Listen for changes to the connection state
*/
getConnectionState = () => {
return this.connectionState.asObservable();
};
/**
* Watch for messages in a channel
*/
getStream: CentrifugeSrv['getStream'] = <T>(address: LiveChannelAddress) => {
return this.getChannel<T>(address).getStream();
};
private createSubscriptionKey = (options: LiveDataStreamOptions): DataStreamSubscriptionKey =>
options.key ?? `xstr/${streamCounter++}`;
private getLiveDataStream = (options: LiveDataStreamOptions): LiveDataStream => {
const channelId = toLiveChannelId(options.addr);
const existingStream = this.liveDataStreamByChannelId[channelId];
if (existingStream) {
return existingStream;
}
const channel = this.getChannel(options.addr);
this.liveDataStreamByChannelId[channelId] = new LiveDataStream({
channelId,
onShutdown: () => {
delete this.liveDataStreamByChannelId[channelId];
},
liveEventsObservable: channel.getStream(),
subscriberReadiness: this.dataStreamSubscriberReadiness,
defaultStreamingFrameOptions,
shutdownDelayInMs: dataStreamShutdownDelayInMs,
});
return this.liveDataStreamByChannelId[channelId];
};
/**
* Connect to a channel and return results as DataFrames
*/
getDataStream: CentrifugeSrv['getDataStream'] = (options) => {
const subscriptionKey = this.createSubscriptionKey(options);
const stream = this.getLiveDataStream(options);
return stream.get(options, subscriptionKey);
};
/**
* Executes a query over the live websocket. Query response can contain live channels we can subscribe to for further updates
*
* Since the initial request and subscription are on the same socket, this will support HA setups
*/
getQueryData: CentrifugeSrv['getQueryData'] = async (options) => {
if (this.centrifuge.state !== State.Connected) {
await this.connectionBlocker;
}
return this.centrifuge.rpc('grafana.query', options.body);
};
/**
* For channels that support presence, this will request the current state from the server.
*
* Join and leave messages will be sent to the open stream
*/
getPresence: CentrifugeSrv['getPresence'] = (address) => {
return this.getChannel(address).getPresence();
};
}
// This is used to give a unique key for each stream. The actual value does not matter
let streamCounter = 0;
| public/app/features/live/centrifuge/service.ts | 1 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.9991371035575867,
0.16150125861167908,
0.0001632920902920887,
0.0006397548713721335,
0.36493319272994995
]
|
{
"id": 4,
"code_window": [
" orgId: contextSrv.user.orgId,\n",
" orgRole: contextSrv.user.orgRole,\n",
" liveEnabled: config.liveEnabled,\n",
" sessionId,\n",
" dataStreamSubscriberReadiness: liveTimer.ok.asObservable(),\n",
" };\n",
"\n",
" const centrifugeSrv = config.featureToggles['live-service-web-worker']\n",
" ? new CentrifugeServiceWorkerProxy(centrifugeServiceDeps)\n",
" : new CentrifugeService(centrifugeServiceDeps);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grafanaAuthToken: loadUrlToken(),\n"
],
"file_path": "public/app/features/live/index.ts",
"type": "add",
"edit_start_line_idx": 24
} | import { fireEvent } from '@testing-library/dom';
import { render, screen } from '@testing-library/react';
import React from 'react';
import { selectors } from '@grafana/e2e-selectors';
import { MenuItem, MenuItemProps } from './MenuItem';
describe('MenuItem', () => {
const getMenuItem = (props?: Partial<MenuItemProps>) => (
<MenuItem ariaLabel={selectors.components.Menu.MenuItem('Test')} label="item1" icon="history" {...props} />
);
it('renders correct element type', () => {
const { rerender } = render(getMenuItem({ onClick: jest.fn() }));
expect(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')).nodeName).toBe('BUTTON');
rerender(getMenuItem({ url: 'test' }));
expect(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')).nodeName).toBe('A');
});
it('calls onClick when item is clicked', () => {
const onClick = jest.fn();
render(getMenuItem({ onClick }));
fireEvent.click(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')));
expect(onClick).toHaveBeenCalled();
});
it('renders and opens subMenu correctly', async () => {
const childItems = [
<MenuItem key="subitem1" label="subitem1" icon="history" />,
<MenuItem key="subitem2" label="subitem2" icon="apps" />,
];
render(getMenuItem({ childItems }));
expect(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')).nodeName).toBe('DIV');
expect(screen.getByLabelText(selectors.components.Menu.SubMenu.icon)).toBeInTheDocument();
expect(screen.queryByLabelText(selectors.components.Menu.SubMenu.container)).not.toBeInTheDocument();
fireEvent.mouseOver(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')));
const subMenuContainer = await screen.findByLabelText(selectors.components.Menu.SubMenu.container);
expect(subMenuContainer).toBeInTheDocument();
expect(subMenuContainer.firstChild?.childNodes.length).toBe(2);
});
it('opens subMenu on ArrowRight', async () => {
const childItems = [
<MenuItem key="subitem1" label="subitem1" icon="history" />,
<MenuItem key="subitem2" label="subitem2" icon="apps" />,
];
render(getMenuItem({ childItems }));
expect(screen.queryByLabelText(selectors.components.Menu.SubMenu.container)).not.toBeInTheDocument();
fireEvent.keyDown(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')), { key: 'ArrowRight' });
expect(await screen.findByLabelText(selectors.components.Menu.SubMenu.container)).toBeInTheDocument();
});
});
| packages/grafana-ui/src/components/Menu/MenuItem.test.tsx | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.0001771978713804856,
0.00017637650307733566,
0.00017523771384730935,
0.0001764460903359577,
7.003892505963449e-7
]
|
{
"id": 4,
"code_window": [
" orgId: contextSrv.user.orgId,\n",
" orgRole: contextSrv.user.orgRole,\n",
" liveEnabled: config.liveEnabled,\n",
" sessionId,\n",
" dataStreamSubscriberReadiness: liveTimer.ok.asObservable(),\n",
" };\n",
"\n",
" const centrifugeSrv = config.featureToggles['live-service-web-worker']\n",
" ? new CentrifugeServiceWorkerProxy(centrifugeServiceDeps)\n",
" : new CentrifugeService(centrifugeServiceDeps);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grafanaAuthToken: loadUrlToken(),\n"
],
"file_path": "public/app/features/live/index.ts",
"type": "add",
"edit_start_line_idx": 24
} | import { isEqualWith } from 'lodash';
import { PanelModel as IPanelModel } from '@grafana/data';
import { PanelModel } from '../state';
export interface PanelMergeInfo {
changed: boolean;
panels: PanelModel[];
actions: Record<string, number[]>;
}
// Values that are safe to change without a full panel unmount/remount
// TODO: options and fieldConfig should also be supported
const mutableKeys = new Set<keyof PanelModel>(['gridPos', 'title', 'description', 'transparent']);
export function mergePanels(current: PanelModel[], data: IPanelModel[]): PanelMergeInfo {
const panels: PanelModel[] = [];
const info = {
changed: false,
actions: {
add: [] as number[],
remove: [] as number[],
replace: [] as number[],
update: [] as number[],
noop: [] as number[],
},
panels,
};
let nextId = 0;
const inputPanels = new Map<number, IPanelModel>();
for (let p of data) {
let { id } = p;
if (!id) {
if (!nextId) {
nextId = findNextPanelID([current, data]);
}
id = nextId++;
p = { ...p, id }; // clone with new ID
}
inputPanels.set(id, p);
}
for (const panel of current) {
const target = inputPanels.get(panel.id) as PanelModel;
if (!target) {
info.changed = true;
info.actions.remove.push(panel.id);
panel.destroy();
continue;
}
inputPanels.delete(panel.id);
// Fast comparison when working with the same panel objects
if (target === panel) {
panels.push(panel);
info.actions.noop.push(panel.id);
continue;
}
// Check if it is the same type
if (panel.type === target.type) {
const save = panel.getSaveModel();
let isNoop = true;
let doUpdate = false;
for (const [key, value] of Object.entries(target)) {
if (!isEqualWith(value, save[key], infinityEqualsNull)) {
info.changed = true;
isNoop = false;
if (mutableKeys.has(key as any)) {
(panel as any)[key] = value;
doUpdate = true;
} else {
doUpdate = false;
break; // needs full replace
}
}
}
if (isNoop) {
panels.push(panel);
info.actions.noop.push(panel.id);
continue;
}
if (doUpdate) {
panels.push(panel);
info.actions.update.push(panel.id);
continue;
}
}
panel.destroy();
const next = new PanelModel(target);
next.key = `${next.id}-update-${Date.now()}`; // force react invalidate
panels.push(next);
info.changed = true;
info.actions.replace.push(panel.id);
}
// Add the new panels
for (const t of inputPanels.values()) {
panels.push(new PanelModel(t));
info.changed = true;
info.actions.add.push(t.id);
}
return info;
}
// Since +- Infinity are saved as null in JSON, we need to make them equal here also
function infinityEqualsNull(a: any, b: any) {
if (a == null && (b === Infinity || b === -Infinity || b == null)) {
return true;
}
if (b == null && (a === Infinity || a === -Infinity || a == null)) {
return true;
}
return undefined; // use default comparison
}
function findNextPanelID(args: IPanelModel[][]): number {
let max = 0;
for (const panels of args) {
for (const panel of panels) {
if (panel.id > max) {
max = panel.id;
}
}
}
return max + 1;
}
| public/app/features/dashboard/utils/panelMerge.ts | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.0001769216760294512,
0.00017440412193536758,
0.00016738071280997247,
0.0001754739205352962,
0.0000029026393804088
]
|
{
"id": 4,
"code_window": [
" orgId: contextSrv.user.orgId,\n",
" orgRole: contextSrv.user.orgRole,\n",
" liveEnabled: config.liveEnabled,\n",
" sessionId,\n",
" dataStreamSubscriberReadiness: liveTimer.ok.asObservable(),\n",
" };\n",
"\n",
" const centrifugeSrv = config.featureToggles['live-service-web-worker']\n",
" ? new CentrifugeServiceWorkerProxy(centrifugeServiceDeps)\n",
" : new CentrifugeService(centrifugeServiceDeps);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grafanaAuthToken: loadUrlToken(),\n"
],
"file_path": "public/app/features/live/index.ts",
"type": "add",
"edit_start_line_idx": 24
} | prom:$apr1$bfu32njz$HHDDTjaeWHDzQs2UMXP.C1
| devenv/docker/blocks/auth/prometheus_basic_auth_proxy/htpasswd | 0 | https://github.com/grafana/grafana/commit/5a1f004fb100a8add5f5eff80ddf6e169ec17844 | [
0.0001729418581817299,
0.0001729418581817299,
0.0001729418581817299,
0.0001729418581817299,
0
]
|
{
"id": 0,
"code_window": [
" this.rightBrace();\n",
" }\n",
"};\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"exports.MethodDefinition = function (node, print) {\n",
" if (node.static) {\n",
" this.push(\"static \");\n",
" }\n",
"\n",
" this._method(node, print);\n",
"};"
],
"file_path": "lib/6to5/generation/generators/classes.js",
"type": "add",
"edit_start_line_idx": 32
} | var t = require("../../types");
exports._params = function (node, print) {
var self = this;
this.push("(");
print.join(node.params, {
separator: ", ",
iterator: function (param, i) {
var def = node.defaults && node.defaults[i];
if (def) {
self.push(" = ");
print(def);
}
}
});
if (node.rest) {
if (node.params.length) {
this.push(", ");
}
this.push("...");
print(node.rest);
}
this.push(")");
};
exports._method = function (node, print) {
var value = node.value;
var kind = node.kind;
var key = node.key;
if (!kind || kind === "init") {
if (value.generator) {
this.push("*");
}
} else {
this.push(kind + " ");
}
if (node.computed) {
this.push("[");
print(key);
this.push("]");
} else {
print(key);
}
this._params(value, print);
this.space();
print(value.body);
};
exports.MethodDefinition = function (node, print) {
if (node.static) {
this.push("static ");
}
this._method(node, print);
};
exports.FunctionDeclaration =
exports.FunctionExpression = function (node, print) {
this.push("function");
if (node.generator) this.push("*");
this.space();
if (node.id) print(node.id);
this._params(node, print);
this.space();
print(node.body);
};
exports.ArrowFunctionExpression = function (node, print) {
if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {
print(node.params[0]);
} else {
this._params(node, print);
}
this.push(" => ");
print(node.body);
};
| lib/6to5/generation/generators/methods.js | 1 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.00032403276418335736,
0.0001891505962703377,
0.00016547470295336097,
0.00016952966689132154,
0.000048098369006766006
]
|
{
"id": 0,
"code_window": [
" this.rightBrace();\n",
" }\n",
"};\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"exports.MethodDefinition = function (node, print) {\n",
" if (node.static) {\n",
" this.push(\"static \");\n",
" }\n",
"\n",
" this._method(node, print);\n",
"};"
],
"file_path": "lib/6to5/generation/generators/classes.js",
"type": "add",
"edit_start_line_idx": 32
} | var transform = require("./transformation/transform");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
exports.runtime = require("./runtime");
exports.register = function (opts) {
var register = require("./register");
if (opts != null) register(opts);
return register;
};
exports.polyfill = function () {
require("./polyfill");
};
exports.canCompile = util.canCompile;
exports.transform = transform;
exports.transformFile = function (filename, opts, callback) {
if (_.isFunction(opts)) {
callback = opts;
opts = {};
}
opts.filename = filename;
fs.readFile(filename, function (err, code) {
if (err) return callback(err);
var result;
try {
result = transform(code, opts);
} catch (err) {
return callback(err);
}
callback(null, result);
});
};
exports.transformFileSync = function (filename, opts) {
opts = opts || {};
opts.filename = filename;
return transform(fs.readFileSync(filename), opts);
};
| lib/6to5/index.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.00017330849368590862,
0.00016919703921303153,
0.00016603719268459827,
0.0001680884452071041,
0.000002630622702781693
]
|
{
"id": 0,
"code_window": [
" this.rightBrace();\n",
" }\n",
"};\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"exports.MethodDefinition = function (node, print) {\n",
" if (node.static) {\n",
" this.push(\"static \");\n",
" }\n",
"\n",
" this._method(node, print);\n",
"};"
],
"file_path": "lib/6to5/generation/generators/classes.js",
"type": "add",
"edit_start_line_idx": 32
} | (function (factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
}
})(function (exports) {
"use strict";
exports.foo7 = foo7;
var foo = exports.foo = 1;
var foo2 = exports.foo2 = function () {};
var foo3;
var foo4 = exports.foo4 = 2;
var foo5;
var foo6 = exports.foo6 = 3;
function foo7() {}
var foo8 = function foo8() {};
exports.foo8 = foo8;
});
| test/fixtures/transformation/modules-umd/exports-variable/expected.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.00017912188195623457,
0.00017288071103394032,
0.00016717480320949107,
0.0001723454479360953,
0.0000048920378503680695
]
|
{
"id": 0,
"code_window": [
" this.rightBrace();\n",
" }\n",
"};\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"exports.MethodDefinition = function (node, print) {\n",
" if (node.static) {\n",
" this.push(\"static \");\n",
" }\n",
"\n",
" this._method(node, print);\n",
"};"
],
"file_path": "lib/6to5/generation/generators/classes.js",
"type": "add",
"edit_start_line_idx": 32
} | foo;
undefined;
| test/fixtures/generation/types/Identifier/expected.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.00017467736324761063,
0.00017467736324761063,
0.00017467736324761063,
0.00017467736324761063,
0
]
|
{
"id": 1,
"code_window": [
" } else {\n",
" this.push(kind + \" \");\n",
" }\n",
"\n",
" if (node.computed) {\n",
" this.push(\"[\");\n",
" print(key);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (value.async) this.push(\"async \");\n",
"\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 43
} | exports.ClassExpression =
exports.ClassDeclaration = function (node, print) {
this.push("class");
if (node.id) {
this.space();
print(node.id);
}
if (node.superClass) {
this.push(" extends ");
print(node.superClass);
}
this.space();
print(node.body);
};
exports.ClassBody = function (node, print) {
if (node.body.length === 0) {
this.push("{}");
} else {
this.push("{");
this.newline();
this.indent();
print.sequence(node.body);
this.dedent();
this.rightBrace();
}
};
| lib/6to5/generation/generators/classes.js | 1 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.3796555697917938,
0.09696619212627411,
0.00017254376143682748,
0.004018325824290514,
0.16322162747383118
]
|
{
"id": 1,
"code_window": [
" } else {\n",
" this.push(kind + \" \");\n",
" }\n",
"\n",
" if (node.computed) {\n",
" this.push(\"[\");\n",
" print(key);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (value.async) this.push(\"async \");\n",
"\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 43
} | <html>
<head>
<meta charset="utf-8">
<title>Mocha</title>
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="../node_modules/lodash/lodash.js"></script>
<script src="../node_modules/mocha/mocha.js"></script>
<script>mocha.setup("tdd");</script>
<script src="../dist/6to5-test.js"></script>
<script>
mocha.globals(["regeneratorRuntime"]);
mocha.checkLeaks();
mocha.run();
</script>
</body>
</html>
| test/browser.html | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.0001735868281684816,
0.0001717687409836799,
0.00016995063924696296,
0.0001717687409836799,
0.000001818094460759312
]
|
{
"id": 1,
"code_window": [
" } else {\n",
" this.push(kind + \" \");\n",
" }\n",
"\n",
" if (node.computed) {\n",
" this.push(\"[\");\n",
" print(key);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (value.async) this.push(\"async \");\n",
"\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 43
} | for (var i = 0;;) {}
for (var i = 0; i < 5;) {}
for (var i = 0; i < 5; i++) {}
| test/fixtures/generation/types/ForStatement/actual.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.0001686812174739316,
0.0001686812174739316,
0.0001686812174739316,
0.0001686812174739316,
0
]
|
{
"id": 1,
"code_window": [
" } else {\n",
" this.push(kind + \" \");\n",
" }\n",
"\n",
" if (node.computed) {\n",
" this.push(\"[\");\n",
" print(key);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (value.async) this.push(\"async \");\n",
"\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 43
} | foo["bar"];
foo.bar;
foo.bar.foo;
foo.bar["foo"];
foo["foo"]["bar"];
foo[test()][bar()];
| test/fixtures/generation/types/MemberExpression/expected.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.0001706891052890569,
0.0001706891052890569,
0.0001706891052890569,
0.0001706891052890569,
0
]
|
{
"id": 2,
"code_window": [
" this.space();\n",
" print(value.body);\n",
"};\n",
"\n",
"exports.MethodDefinition = function (node, print) {\n",
" if (node.static) {\n",
" this.push(\"static \");\n",
" }\n",
"\n",
" this._method(node, print);\n",
"};\n",
"\n",
"exports.FunctionDeclaration =\n",
"exports.FunctionExpression = function (node, print) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "replace",
"edit_start_line_idx": 56
} | var t = require("../../types");
exports._params = function (node, print) {
var self = this;
this.push("(");
print.join(node.params, {
separator: ", ",
iterator: function (param, i) {
var def = node.defaults && node.defaults[i];
if (def) {
self.push(" = ");
print(def);
}
}
});
if (node.rest) {
if (node.params.length) {
this.push(", ");
}
this.push("...");
print(node.rest);
}
this.push(")");
};
exports._method = function (node, print) {
var value = node.value;
var kind = node.kind;
var key = node.key;
if (!kind || kind === "init") {
if (value.generator) {
this.push("*");
}
} else {
this.push(kind + " ");
}
if (node.computed) {
this.push("[");
print(key);
this.push("]");
} else {
print(key);
}
this._params(value, print);
this.space();
print(value.body);
};
exports.MethodDefinition = function (node, print) {
if (node.static) {
this.push("static ");
}
this._method(node, print);
};
exports.FunctionDeclaration =
exports.FunctionExpression = function (node, print) {
this.push("function");
if (node.generator) this.push("*");
this.space();
if (node.id) print(node.id);
this._params(node, print);
this.space();
print(node.body);
};
exports.ArrowFunctionExpression = function (node, print) {
if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {
print(node.params[0]);
} else {
this._params(node, print);
}
this.push(" => ");
print(node.body);
};
| lib/6to5/generation/generators/methods.js | 1 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.9974023699760437,
0.22091035544872284,
0.0016647125594317913,
0.025989791378378868,
0.33014097809791565
]
|
{
"id": 2,
"code_window": [
" this.space();\n",
" print(value.body);\n",
"};\n",
"\n",
"exports.MethodDefinition = function (node, print) {\n",
" if (node.static) {\n",
" this.push(\"static \");\n",
" }\n",
"\n",
" this._method(node, print);\n",
"};\n",
"\n",
"exports.FunctionDeclaration =\n",
"exports.FunctionExpression = function (node, print) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "replace",
"edit_start_line_idx": 56
} | arr.map(x => x * MULTIPLIER);
| test/fixtures/bin/6to5/filenames --out-file --source-maps-inline/in-files/script2.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.0001730169024085626,
0.0001730169024085626,
0.0001730169024085626,
0.0001730169024085626,
0
]
|
{
"id": 2,
"code_window": [
" this.space();\n",
" print(value.body);\n",
"};\n",
"\n",
"exports.MethodDefinition = function (node, print) {\n",
" if (node.static) {\n",
" this.push(\"static \");\n",
" }\n",
"\n",
" this._method(node, print);\n",
"};\n",
"\n",
"exports.FunctionDeclaration =\n",
"exports.FunctionExpression = function (node, print) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "replace",
"edit_start_line_idx": 56
} | src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
| test/fixtures/bin/6to5/dir --out-dir --source-maps/stdout.txt | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.00017239163571503013,
0.00017239163571503013,
0.00017239163571503013,
0.00017239163571503013,
0
]
|
{
"id": 2,
"code_window": [
" this.space();\n",
" print(value.body);\n",
"};\n",
"\n",
"exports.MethodDefinition = function (node, print) {\n",
" if (node.static) {\n",
" this.push(\"static \");\n",
" }\n",
"\n",
" this._method(node, print);\n",
"};\n",
"\n",
"exports.FunctionDeclaration =\n",
"exports.FunctionExpression = function (node, print) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "replace",
"edit_start_line_idx": 56
} | (function (Constructor, args) {
var bindArgs = [null].concat(args);
var Factory = Constructor.bind.apply(Constructor, bindArgs);
return new Factory;
});
| lib/6to5/templates/apply-constructor.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.0001599102542968467,
0.0001599102542968467,
0.0001599102542968467,
0.0001599102542968467,
0
]
|
{
"id": 3,
"code_window": [
"exports.FunctionDeclaration =\n",
"exports.FunctionExpression = function (node, print) {\n",
" this.push(\"function\");\n",
" if (node.generator) this.push(\"*\");\n",
" this.space();\n",
" if (node.id) print(node.id);\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (node.async) this.push(\"async \");\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 66
} | var t = require("../../types");
exports._params = function (node, print) {
var self = this;
this.push("(");
print.join(node.params, {
separator: ", ",
iterator: function (param, i) {
var def = node.defaults && node.defaults[i];
if (def) {
self.push(" = ");
print(def);
}
}
});
if (node.rest) {
if (node.params.length) {
this.push(", ");
}
this.push("...");
print(node.rest);
}
this.push(")");
};
exports._method = function (node, print) {
var value = node.value;
var kind = node.kind;
var key = node.key;
if (!kind || kind === "init") {
if (value.generator) {
this.push("*");
}
} else {
this.push(kind + " ");
}
if (node.computed) {
this.push("[");
print(key);
this.push("]");
} else {
print(key);
}
this._params(value, print);
this.space();
print(value.body);
};
exports.MethodDefinition = function (node, print) {
if (node.static) {
this.push("static ");
}
this._method(node, print);
};
exports.FunctionDeclaration =
exports.FunctionExpression = function (node, print) {
this.push("function");
if (node.generator) this.push("*");
this.space();
if (node.id) print(node.id);
this._params(node, print);
this.space();
print(node.body);
};
exports.ArrowFunctionExpression = function (node, print) {
if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {
print(node.params[0]);
} else {
this._params(node, print);
}
this.push(" => ");
print(node.body);
};
| lib/6to5/generation/generators/methods.js | 1 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.9980878233909607,
0.5790282487869263,
0.009378815069794655,
0.8854901790618896,
0.4217889904975891
]
|
{
"id": 3,
"code_window": [
"exports.FunctionDeclaration =\n",
"exports.FunctionExpression = function (node, print) {\n",
" this.push(\"function\");\n",
" if (node.generator) this.push(\"*\");\n",
" this.space();\n",
" if (node.id) print(node.id);\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (node.async) this.push(\"async \");\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 66
} | # Differences
## Philosophy
The fundamental concept behind 6to5 is that the generated code must be close as
possible to the original, retaining all the same formatting and readability.
Many other transpilers are just concerned with making the code work while 6to5
is concerned with making sure it works **and** is readable at the same time.
For example, given the following array comprehension:
```javascript
var seattlers = [for (c of customers) if (c.city == "Seattle") { name: c.name, age: c.age }];
```
is generated to the following with 6to5:
```javascript
var seattlers = customers.filter(function (c) {
return c.city == "Seattle";
}).map(function (c) {
return {
name: c.name,
age: c.age
};
});
```
The following is what Traceur generates:
```javascript
var seattlers = (function() {
var c;
var $__20 = 0,
$__21 = [];
for (var $__22 = customers[$traceurRuntime.toProperty(Symbol.iterator)](),
$__23; !($__23 = $__22.next()).done; ) {
c = $__23.value;
if (c.city == "Seattle")
$traceurRuntime.setProperty($__21, $__20++, {
name: c.name,
age: c.age
});
}
return $__21;
}());
```
As you can tell, it's not very pretty, unreadable even. Instead of mapping
directly to a runtime, like other transpilers, 6to5 maps directly to the
equivalent ES5.
I'm not saying 6to5 is for everyone or even suited for everything. Traceur is
better suited if you'd like a full ES6 environment with polyfills and all.
## Comparison to other transpilers
| | 6to5 | Traceur | esnext | es6now | es6-transpiler | jstransform |
| ---------------------------- | ---- | ------- | ------ | ------ | -------------- | ----------- |
| No runtime | ✓ | | | | ✓ | ✓ |
| Source maps | ✓ | ✓ | ✓ | | ✓ | ✓ |
| No compiler global pollution | ✓ | | ✓ | | ✓ | ✓ |
| Browser support | ✓ | ✓ | ✓ | | | |
| Array comprehension | ✓ | ✓ | | | ✓ | |
| Arrow functions | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Async functions | ✓ | ✓ | ✓ | | | |
| Classes | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Computed property names | ✓ | ✓ | ✓ | ✓ | ✓ | |
| Constants | ✓ | ✓ | | | ✓ | |
| Default parameters | ✓ | ✓ | ✓ | ✓ | ✓ | |
| Destructuring | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| For-of | ✓ | ✓ | ✓ | ✓ | ✓ | |
| Generators | ✓ | ✓ | ✓ | | | |
| Generator comprehension | ✓ | ✓ | | | | |
| Let scoping | ✓ | ✓ | | | ✓ | |
| Modules | ✓ | ✓ | | ✓ | | |
| Property method assignment | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Property name shorthand | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Rest parameters | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Spread | ✓ | ✓ | ✓ | ✓ | ✓ | |
| Template literals | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Unicode regex | ✓ | ✓ | | | ✓ | |
### [Traceur](https://github.com/google/traceur-compiler)
Traceur requires quite a bulky runtime (~75KB) and produces quite verbose code.
While this can be trimmed down by selectively building the runtime, it's an
unneccesary step when a runtime can be eliminated entirely.
### [es6now](https://github.com/zenparsing/es6now)
es6now doesn't output sourcemaps. This is cited as a positive as line-to-line
mapping is the goal. This however obviously doesn't retain column mapping
resulting in the output code not being very pleasant.
### [es6-transpiler](https://github.com/termi/es6-transpiler)
The es6-transpiler compiler requires shims to operate which pollutes the global
scope resulting in possible collisions.
es6-transpiler maps line-by-line, just like es6now, this results in the same
issues such as lack of column information and unpleasant code output.
| doc/differences.md | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.0001768044603522867,
0.00017097365343943238,
0.00016546175174880773,
0.00017065818246919662,
0.0000030722208066435996
]
|
{
"id": 3,
"code_window": [
"exports.FunctionDeclaration =\n",
"exports.FunctionExpression = function (node, print) {\n",
" this.push(\"function\");\n",
" if (node.generator) this.push(\"*\");\n",
" this.space();\n",
" if (node.id) print(node.id);\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (node.async) this.push(\"async \");\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 66
} | function test() {
var
/*
* Leading to VariableDeclarator
* Leading to VariableDeclarator
*/
i = 20,
/*
* Leading to VariableDeclarator
* Leading to VariableDeclarator
*/
j = 20;
}
| test/fixtures/generation/comments/variable-declarator-multi-comment/actual.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.00017745624063536525,
0.00017180436407215893,
0.00016615248750895262,
0.00017180436407215893,
0.000005651876563206315
]
|
{
"id": 3,
"code_window": [
"exports.FunctionDeclaration =\n",
"exports.FunctionExpression = function (node, print) {\n",
" this.push(\"function\");\n",
" if (node.generator) this.push(\"*\");\n",
" this.space();\n",
" if (node.id) print(node.id);\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (node.async) this.push(\"async \");\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 66
} | "use strict";
var foo = 1;
var foo2 = function () {};
var foo3;
var foo4 = 2;
var foo5;
var foo6 = 3;
function foo7() {}
var foo8 = function foo8() {};
| test/fixtures/transformation/modules-ignore/exports-variable/expected.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.00020003481768071651,
0.000188954989425838,
0.0001778751757228747,
0.000188954989425838,
0.000011079820978920907
]
|
{
"id": 4,
"code_window": [
" print(node.body);\n",
"};\n",
"\n",
"exports.ArrowFunctionExpression = function (node, print) {\n",
" if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {\n",
" print(node.params[0]);\n",
" } else {\n",
" this._params(node, print);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (node.async) this.push(\"async \");\n",
"\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 76
} | var t = require("../../types");
exports._params = function (node, print) {
var self = this;
this.push("(");
print.join(node.params, {
separator: ", ",
iterator: function (param, i) {
var def = node.defaults && node.defaults[i];
if (def) {
self.push(" = ");
print(def);
}
}
});
if (node.rest) {
if (node.params.length) {
this.push(", ");
}
this.push("...");
print(node.rest);
}
this.push(")");
};
exports._method = function (node, print) {
var value = node.value;
var kind = node.kind;
var key = node.key;
if (!kind || kind === "init") {
if (value.generator) {
this.push("*");
}
} else {
this.push(kind + " ");
}
if (node.computed) {
this.push("[");
print(key);
this.push("]");
} else {
print(key);
}
this._params(value, print);
this.space();
print(value.body);
};
exports.MethodDefinition = function (node, print) {
if (node.static) {
this.push("static ");
}
this._method(node, print);
};
exports.FunctionDeclaration =
exports.FunctionExpression = function (node, print) {
this.push("function");
if (node.generator) this.push("*");
this.space();
if (node.id) print(node.id);
this._params(node, print);
this.space();
print(node.body);
};
exports.ArrowFunctionExpression = function (node, print) {
if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {
print(node.params[0]);
} else {
this._params(node, print);
}
this.push(" => ");
print(node.body);
};
| lib/6to5/generation/generators/methods.js | 1 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.9982131719589233,
0.5704700946807861,
0.013659913092851639,
0.9705154895782471,
0.4659554660320282
]
|
{
"id": 4,
"code_window": [
" print(node.body);\n",
"};\n",
"\n",
"exports.ArrowFunctionExpression = function (node, print) {\n",
" if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {\n",
" print(node.params[0]);\n",
" } else {\n",
" this._params(node, print);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (node.async) this.push(\"async \");\n",
"\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 76
} | switch (foo) {}
switch (foo) {
case "foo":
}
switch (foo) {
default:
}
switch (foo) {
case "foo":
default:
}
switch (foo) {
case "foo":
case "bar":
default:
}
switch (foo) {
case "foo":
foo();
break;
case "bar":
bar();
break;
default:
yay();
}
switch (foo) {
case "foo": foo();
case "bar": bar();
default: yay();
}
| test/fixtures/generation/types/SwitchStatement-SwitchCase/actual.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.0001743460597936064,
0.00017305114306509495,
0.00017175616812892258,
0.00017305115761701018,
9.169472150460933e-7
]
|
{
"id": 4,
"code_window": [
" print(node.body);\n",
"};\n",
"\n",
"exports.ArrowFunctionExpression = function (node, print) {\n",
" if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {\n",
" print(node.params[0]);\n",
" } else {\n",
" this._params(node, print);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (node.async) this.push(\"async \");\n",
"\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 76
} | (foo());
(5 * 6);
| test/fixtures/generation/types/ParenthesizedExpression/expected.js | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.0001714588433969766,
0.0001714588433969766,
0.0001714588433969766,
0.0001714588433969766,
0
]
|
{
"id": 4,
"code_window": [
" print(node.body);\n",
"};\n",
"\n",
"exports.ArrowFunctionExpression = function (node, print) {\n",
" if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {\n",
" print(node.params[0]);\n",
" } else {\n",
" this._params(node, print);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (node.async) this.push(\"async \");\n",
"\n"
],
"file_path": "lib/6to5/generation/generators/methods.js",
"type": "add",
"edit_start_line_idx": 76
} | {
"args": ["foo"]
}
| test/fixtures/bin/6to5-node/filename/options.json | 0 | https://github.com/babel/babel/commit/d4deb18975a7898c741fe76707822bb25d72f3f4 | [
0.00017040791863109916,
0.00017040791863109916,
0.00017040791863109916,
0.00017040791863109916,
0
]
|
{
"id": 0,
"code_window": [
"// TypeScript Version: 2.3\n",
"\n",
"declare module 'jquery' {\n",
" function factory(window: Window): JQueryStatic & JQuery;\n",
"\n",
" const factoryOrJQuery: typeof factory & JQueryStatic;\n",
" export = factoryOrJQuery;\n",
"}\n",
"\n",
"declare module 'jquery/dist/jquery.slim' {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" export = jQuery;\n"
],
"file_path": "types/jquery/index.d.ts",
"type": "replace",
"edit_start_line_idx": 27
} | import * as jq from 'jquery/dist/jquery.slim';
const $window = jq(window);
// ExpectType will report 'jq' as 'JQueryStatic<HTMLElement> & JQuery<HTMLElement>' even though the compiler seems to know that 'jq' is 'JQuery<HTMLElement>'
// // $ExpectType JQuery<HTMLElement>
// $window;
// $window === jq;
$window === jq();
| types/jquery/test/jquery-slim-window-module-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/aa437becb7ae856f221f69d9b4fa917a7b3e1ed7 | [
0.004304992500692606,
0.004304992500692606,
0.004304992500692606,
0.004304992500692606,
0
]
|
{
"id": 0,
"code_window": [
"// TypeScript Version: 2.3\n",
"\n",
"declare module 'jquery' {\n",
" function factory(window: Window): JQueryStatic & JQuery;\n",
"\n",
" const factoryOrJQuery: typeof factory & JQueryStatic;\n",
" export = factoryOrJQuery;\n",
"}\n",
"\n",
"declare module 'jquery/dist/jquery.slim' {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" export = jQuery;\n"
],
"file_path": "types/jquery/index.d.ts",
"type": "replace",
"edit_start_line_idx": 27
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"riot-games-api-tests.ts"
]
} | types/riot-games-api/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/aa437becb7ae856f221f69d9b4fa917a7b3e1ed7 | [
0.00017353057046420872,
0.00017248699441552162,
0.00017194986867252737,
0.00017198052955791354,
7.380292572634062e-7
]
|
{
"id": 0,
"code_window": [
"// TypeScript Version: 2.3\n",
"\n",
"declare module 'jquery' {\n",
" function factory(window: Window): JQueryStatic & JQuery;\n",
"\n",
" const factoryOrJQuery: typeof factory & JQueryStatic;\n",
" export = factoryOrJQuery;\n",
"}\n",
"\n",
"declare module 'jquery/dist/jquery.slim' {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" export = jQuery;\n"
],
"file_path": "types/jquery/index.d.ts",
"type": "replace",
"edit_start_line_idx": 27
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"uk.co.workingedge.phonegap.plugin.launchnavigator-tests.ts"
]
} | types/uk.co.workingedge.phonegap.plugin.launchnavigator/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/aa437becb7ae856f221f69d9b4fa917a7b3e1ed7 | [
0.00017209781799465418,
0.00017158826813101768,
0.00017103561549447477,
0.0001716314145596698,
4.3471354160828923e-7
]
|
{
"id": 0,
"code_window": [
"// TypeScript Version: 2.3\n",
"\n",
"declare module 'jquery' {\n",
" function factory(window: Window): JQueryStatic & JQuery;\n",
"\n",
" const factoryOrJQuery: typeof factory & JQueryStatic;\n",
" export = factoryOrJQuery;\n",
"}\n",
"\n",
"declare module 'jquery/dist/jquery.slim' {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" export = jQuery;\n"
],
"file_path": "types/jquery/index.d.ts",
"type": "replace",
"edit_start_line_idx": 27
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cannon-tests.ts"
]
} | types/cannon/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/aa437becb7ae856f221f69d9b4fa917a7b3e1ed7 | [
0.00017353057046420872,
0.0001727783092064783,
0.0001719259307719767,
0.00017287836817558855,
6.589025360881351e-7
]
|
{
"id": 8,
"code_window": [
"import * as jq from 'jquery';\n",
"\n",
"const $window = jq(window);\n",
"// ExpectType will report 'jq' as 'JQueryStatic<HTMLElement> & JQuery<HTMLElement>' even though the compiler seems to know that 'jq' is 'JQuery<HTMLElement>'\n",
"// // $ExpectType JQuery<HTMLElement>\n",
"// $window;\n",
"// $window === jq;\n",
"$window === jq();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"// $ExpectType JQuery<HTMLElement>\n",
"$window;\n",
"\n",
"class CanvasLayersDirective {\n",
" private readonly $renderingCanvas: JQuery<HTMLCanvasElement>;\n",
" private readonly $offscreenCanvas: JQuery<HTMLCanvasElement>;\n",
"\n",
" constructor(elementRef: { nativeElement: any; }) {\n",
" // This type assertion results in an error when exporting 'typeof factory & JQueryStatic' where\n",
" // 'factory' is jQuery's factory function.\n",
" const $Canvas = $ as JQueryStatic<HTMLCanvasElement>;\n",
" this.$renderingCanvas = $Canvas(elementRef.nativeElement);\n",
" this.$offscreenCanvas = $Canvas(document.createElement('canvas'));\n",
" }\n",
"}"
],
"file_path": "types/jquery/test/jquery-window-module-tests.ts",
"type": "replace",
"edit_start_line_idx": 3
} | import jQueryFactory = require('jquery');
const jq = jQueryFactory(window);
// ExpectType will report 'jq' as 'JQueryStatic<HTMLElement> & JQuery<HTMLElement>' even though the compiler seems to know that 'jq' is 'JQueryStatic<HTMLElement>'
// // $ExpectType JQueryStatic<HTMLElement>
// jq;
// jq === jQuery();
jq === jQuery;
| types/jquery/test/jquery-no-window-module-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/aa437becb7ae856f221f69d9b4fa917a7b3e1ed7 | [
0.9974693059921265,
0.9974693059921265,
0.9974693059921265,
0.9974693059921265,
0
]
|
{
"id": 8,
"code_window": [
"import * as jq from 'jquery';\n",
"\n",
"const $window = jq(window);\n",
"// ExpectType will report 'jq' as 'JQueryStatic<HTMLElement> & JQuery<HTMLElement>' even though the compiler seems to know that 'jq' is 'JQuery<HTMLElement>'\n",
"// // $ExpectType JQuery<HTMLElement>\n",
"// $window;\n",
"// $window === jq;\n",
"$window === jq();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"// $ExpectType JQuery<HTMLElement>\n",
"$window;\n",
"\n",
"class CanvasLayersDirective {\n",
" private readonly $renderingCanvas: JQuery<HTMLCanvasElement>;\n",
" private readonly $offscreenCanvas: JQuery<HTMLCanvasElement>;\n",
"\n",
" constructor(elementRef: { nativeElement: any; }) {\n",
" // This type assertion results in an error when exporting 'typeof factory & JQueryStatic' where\n",
" // 'factory' is jQuery's factory function.\n",
" const $Canvas = $ as JQueryStatic<HTMLCanvasElement>;\n",
" this.$renderingCanvas = $Canvas(elementRef.nativeElement);\n",
" this.$offscreenCanvas = $Canvas(document.createElement('canvas'));\n",
" }\n",
"}"
],
"file_path": "types/jquery/test/jquery-window-module-tests.ts",
"type": "replace",
"edit_start_line_idx": 3
} | import * as _ from "lodash";
declare const dropRight: typeof _.dropRight;
export default dropRight;
| types/lodash-es/dropRight/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/aa437becb7ae856f221f69d9b4fa917a7b3e1ed7 | [
0.0001682266447460279,
0.0001682266447460279,
0.0001682266447460279,
0.0001682266447460279,
0
]
|
{
"id": 8,
"code_window": [
"import * as jq from 'jquery';\n",
"\n",
"const $window = jq(window);\n",
"// ExpectType will report 'jq' as 'JQueryStatic<HTMLElement> & JQuery<HTMLElement>' even though the compiler seems to know that 'jq' is 'JQuery<HTMLElement>'\n",
"// // $ExpectType JQuery<HTMLElement>\n",
"// $window;\n",
"// $window === jq;\n",
"$window === jq();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"// $ExpectType JQuery<HTMLElement>\n",
"$window;\n",
"\n",
"class CanvasLayersDirective {\n",
" private readonly $renderingCanvas: JQuery<HTMLCanvasElement>;\n",
" private readonly $offscreenCanvas: JQuery<HTMLCanvasElement>;\n",
"\n",
" constructor(elementRef: { nativeElement: any; }) {\n",
" // This type assertion results in an error when exporting 'typeof factory & JQueryStatic' where\n",
" // 'factory' is jQuery's factory function.\n",
" const $Canvas = $ as JQueryStatic<HTMLCanvasElement>;\n",
" this.$renderingCanvas = $Canvas(elementRef.nativeElement);\n",
" this.$offscreenCanvas = $Canvas(document.createElement('canvas'));\n",
" }\n",
"}"
],
"file_path": "types/jquery/test/jquery-window-module-tests.ts",
"type": "replace",
"edit_start_line_idx": 3
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"table-tests.ts"
]
} | types/table/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/aa437becb7ae856f221f69d9b4fa917a7b3e1ed7 | [
0.00017580758139956743,
0.00017249358643312007,
0.00016833047266118228,
0.0001733427052386105,
0.0000031110064355743816
]
|
{
"id": 8,
"code_window": [
"import * as jq from 'jquery';\n",
"\n",
"const $window = jq(window);\n",
"// ExpectType will report 'jq' as 'JQueryStatic<HTMLElement> & JQuery<HTMLElement>' even though the compiler seems to know that 'jq' is 'JQuery<HTMLElement>'\n",
"// // $ExpectType JQuery<HTMLElement>\n",
"// $window;\n",
"// $window === jq;\n",
"$window === jq();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"// $ExpectType JQuery<HTMLElement>\n",
"$window;\n",
"\n",
"class CanvasLayersDirective {\n",
" private readonly $renderingCanvas: JQuery<HTMLCanvasElement>;\n",
" private readonly $offscreenCanvas: JQuery<HTMLCanvasElement>;\n",
"\n",
" constructor(elementRef: { nativeElement: any; }) {\n",
" // This type assertion results in an error when exporting 'typeof factory & JQueryStatic' where\n",
" // 'factory' is jQuery's factory function.\n",
" const $Canvas = $ as JQueryStatic<HTMLCanvasElement>;\n",
" this.$renderingCanvas = $Canvas(elementRef.nativeElement);\n",
" this.$offscreenCanvas = $Canvas(document.createElement('canvas'));\n",
" }\n",
"}"
],
"file_path": "types/jquery/test/jquery-window-module-tests.ts",
"type": "replace",
"edit_start_line_idx": 3
} | $("#picker").spectrum();
$("#picker").spectrum({
color: "yellow"
});
$("#picker").spectrum({
allowEmpty: true
});
$("#picker").spectrum({
flat: true,
});
$("#picker").spectrum({
showInput: true
});
$("#picker").spectrum({
showAlpha: true
});
$("#picker").spectrum({
disabled: true
});
$("#picker").spectrum({
showPalette: true,
});
$("#picker").spectrum({
showPaletteOnly: true,
togglePaletteOnly: true,
togglePaletteMoreText: "more",
togglePaletteLessText: "less",
color: "blanchedalmond",
palette: [
["#000", "#444", "#666", "#999", "#ccc", "#eee", "#f3f3f3", "#fff"],
["#f00", "#f90", "#ff0", "#0f0", "#0ff", "#00f", "#90f", "#f0f"],
["#f4cccc", "#fce5cd", "#fff2cc", "#d9ead3", "#d0e0e3", "#cfe2f3", "#d9d2e9", "#ead1dc"],
["#ea9999", "#f9cb9c", "#ffe599", "#b6d7a8", "#a2c4c9", "#9fc5e8", "#b4a7d6", "#d5a6bd"],
["#e06666", "#f6b26b", "#ffd966", "#93c47d", "#76a5af", "#6fa8dc", "#8e7cc3", "#c27ba0"],
["#c00", "#e69138", "#f1c232", "#6aa84f", "#45818e", "#3d85c6", "#674ea7", "#a64d79"],
["#900", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#0b5394", "#351c75", "#741b47"],
["#600", "#783f04", "#7f6000", "#274e13", "#0c343d", "#073763", "#20124d", "#4c1130"]
]
});
$("#picker").spectrum({
showPalette: true,
showSelectionPalette: true,
localStorageKey: "spectrum.homepage",
});
$("#picker").spectrum({
hideAfterPaletteSelect: true,
});
$("#picker").spectrum({
clickoutFiresChange: true
});
$("#picker").spectrum({
showInitial: true,
showInput: true
});
$("#picker").spectrum({
chooseText: "Alright",
cancelText: "No way"
});
$("#picker").spectrum({
showButtons: false
});
$("#picker").spectrum({
containerClassName: "awesome"
});
$("#picker").spectrum({
replacerClassName: "awesome"
});
$("#picker").spectrum({
preferredFormat: "hex"
});
$("#picker").spectrum({
appendTo: "body"
});
$("#picker").spectrum({
appendTo: $("#otherPicker")
});
$("#picker").spectrum({
change: function (color) {
console.log(color);
}
});
$("#picker").spectrum({
move: function (color) {
console.log(color);
}
});
$("#picker").spectrum({
hide: function (color) {
console.log(color);
}
});
$("#picker").spectrum({
show: function (color) {
console.log(color);
}
});
$("#picker").spectrum({
beforeShow: function (color) {
console.log(color);
}
});
$("#picker").spectrum("show");
$("#picker").spectrum("hide");
$("#picker").spectrum("toggle");
$("#picker").spectrum("get");
$("#picker").spectrum("set", "#dddddd");
$("#picker").spectrum("container");
$("#picker").spectrum("reflow");
$("#picker").spectrum("destroy");
$("#picker").spectrum("enable");
$("#picker").spectrum("disable");
$("#picker").spectrum("option", "show");
$("#picker").spectrum("option", "color", "#ededed"); | types/spectrum/spectrum-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/aa437becb7ae856f221f69d9b4fa917a7b3e1ed7 | [
0.00017538967949803919,
0.00016984784451778978,
0.00016005699581000954,
0.00017184542957693338,
0.000004698599241237389
]
|
{
"id": 0,
"code_window": [
" render() {\n",
" const { id, toolbar = true, location = '/', getElements, actions, options } = this.props;\n",
" const { zoom, grid } = this.state;\n",
" const panels = getElements(types.PANEL);\n",
"\n",
" const toolbarHeight = toolbar ? 40 : 0;\n",
" const panelList = Object.entries(panels).map(([key, value]) => ({ ...value, key }));\n",
" const tabsList = [{ route: '/components/', title: 'Canvas', key: 'canvas' }].concat(\n",
" getElements(types.TAB)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const panels = getElements(types.TAB);\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 74
} | import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';
import { Tabs, Icons } from '@storybook/components';
class SafeTab extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
this.setState({ hasError: true });
console.error(error, info);
}
render() {
const { hasError } = this.state;
const { children, title, id } = this.props;
if (hasError) {
return <h1>Something went wrong.</h1>;
}
return (
<div id={id} title={title}>
{children}
</div>
);
}
}
SafeTab.propTypes = {
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
title: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
};
const ToolButton = styled.button({
background: 'none',
border: '0 none',
padding: 0,
color: 'inherit',
'&:hover, &:focus': {
color: '#300aaff',
outline: '0 none',
cursor: 'pointer',
},
});
export const Separator = styled.span({
width: 1,
height: 24,
background: '#eee',
});
const AddonPanel = ({ panels, actions, selectedPanel, panelPosition, ...rest }) => (
<Tabs
{...rest}
absolute
selected={selectedPanel}
actions={actions}
flex
tools={
<Fragment>
<Separator key="1" />
<ToolButton key="position" onClick={actions.togglePosition}>
<Icons icon={panelPosition === 'bottom' ? 'bottombar' : 'sidebaralt'} />
</ToolButton>
<ToolButton key="visibility" onClick={actions.toggleVisibility}>
<Icons icon="close" />
</ToolButton>
</Fragment>
}
id="storybook-panel-root"
>
{Object.entries(panels).map(([k, v]) => (
<SafeTab key={k} id={k} title={v.title}>
{v.render}
</SafeTab>
))}
</Tabs>
);
AddonPanel.propTypes = {
selectedPanel: PropTypes.string,
actions: PropTypes.shape({}).isRequired,
panels: PropTypes.objectOf(
PropTypes.shape({
title: PropTypes.string,
render: PropTypes.func,
})
).isRequired,
};
AddonPanel.defaultProps = {
selectedPanel: null,
};
export default AddonPanel;
| lib/ui/src/components/panel/panel.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.9970268607139587,
0.3029884994029999,
0.0001676215761108324,
0.00020811503054574132,
0.4503629505634308
]
|
{
"id": 0,
"code_window": [
" render() {\n",
" const { id, toolbar = true, location = '/', getElements, actions, options } = this.props;\n",
" const { zoom, grid } = this.state;\n",
" const panels = getElements(types.PANEL);\n",
"\n",
" const toolbarHeight = toolbar ? 40 : 0;\n",
" const panelList = Object.entries(panels).map(([key, value]) => ({ ...value, key }));\n",
" const tabsList = [{ route: '/components/', title: 'Canvas', key: 'canvas' }].concat(\n",
" getElements(types.TAB)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const panels = getElements(types.TAB);\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 74
} | #app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
.text-align-center {
text-align: center;
}
.main {
margin: 15px;
max-width: 600;
line-height: 1.4;
font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif;
}
.logo {
height: 150px;
}
.link {
color: #1474f3;
text-decoration: none;
border-bottom: 1px solid #1474f3;
padding-bottom: 2px;
}
.code {
font-size: 15;
font-weight: 600;
padding: 2px 5px;
border: 1px solid #eae9e9;
border-radius: 4px;
background-color: #f3f2f2;
color: #3a3a3a;
}
.codeBlock {
background-color: #f3f2f2;
padding: 1px 10px;
margin: 10px 0;
}
.note {
opacity: 0.5;
}
.banner {
padding: 10px;
border-radius: 5px;
}
| examples/ember-cli/app/styles/app.css | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017487350851297379,
0.0001720085710985586,
0.00016289039922412485,
0.0001731524826027453,
0.0000035373161608731607
]
|
{
"id": 0,
"code_window": [
" render() {\n",
" const { id, toolbar = true, location = '/', getElements, actions, options } = this.props;\n",
" const { zoom, grid } = this.state;\n",
" const panels = getElements(types.PANEL);\n",
"\n",
" const toolbarHeight = toolbar ? 40 : 0;\n",
" const panelList = Object.entries(panels).map(([key, value]) => ({ ...value, key }));\n",
" const tabsList = [{ route: '/components/', title: 'Canvas', key: 'canvas' }].concat(\n",
" getElements(types.TAB)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const panels = getElements(types.TAB);\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 74
} | import React from 'react';
import Svg from './util/svg';
const Check = props => (
<Svg height="24" width="24" viewBox="0 0 24 24" {...props}>
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" fill="currentColor" />
</Svg>
);
export { Check as default };
| lib/components/src/icons/check.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017011731688398868,
0.00016982357192318887,
0.00016952982696238905,
0.00016982357192318887,
2.9374496079981327e-7
]
|
{
"id": 0,
"code_window": [
" render() {\n",
" const { id, toolbar = true, location = '/', getElements, actions, options } = this.props;\n",
" const { zoom, grid } = this.state;\n",
" const panels = getElements(types.PANEL);\n",
"\n",
" const toolbarHeight = toolbar ? 40 : 0;\n",
" const panelList = Object.entries(panels).map(([key, value]) => ({ ...value, key }));\n",
" const tabsList = [{ route: '/components/', title: 'Canvas', key: 'canvas' }].concat(\n",
" getElements(types.TAB)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const panels = getElements(types.TAB);\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 74
} | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'customPipe',
})
export class CustomPipePipe implements PipeTransform {
transform(value: any, args?: any): any {
return `CustomPipe: ${value}`;
}
}
| examples/angular-cli/src/stories/moduleMetadata/custom.pipe.ts | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001703369343886152,
0.00016845704521983862,
0.00016657715605106205,
0.00016845704521983862,
0.0000018798891687765718
]
|
{
"id": 1,
"code_window": [
" <Toolbar\n",
" key=\"toolbar\"\n",
" left={[\n",
" <TabBar key=\"tabs\" scroll={false}>\n",
" {tabsList.map(t => (\n",
" <S.UnstyledLink\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" {tabsList.map((t, index) => (\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 90
} | import addons from '@storybook/addons';
import { navigator, window, document } from 'global';
import createChannel from '@storybook/channel-postmessage';
import { handleKeyboardShortcuts } from '@storybook/ui/dist/libs/key_events';
import { logger } from '@storybook/client-logger';
import Events from '@storybook/core-events';
import StoryStore from './story_store';
import ClientApi from './client_api';
import ConfigApi from './config_api';
const classes = {
MAIN: 'sb-show-main',
NOPREVIEW: 'sb-show-nopreview',
ERROR: 'sb-show-errordisplay',
};
function showMain() {
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.MAIN);
}
function showNopreview() {
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.NOPREVIEW);
}
function showErrorDisplay({ message, stack }) {
document.getElementById('error-message').textContent = message;
document.getElementById('error-stack').textContent = stack;
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.add(classes.ERROR);
}
// showError is used by the various app layers to inform the user they have done something
// wrong -- for instance returned the wrong thing from a story
function showError({ title, description }) {
addons.getChannel().emit(Events.STORY_ERRORED, { title, description });
showErrorDisplay({
message: title,
stack: description,
});
}
// showException is used if we fail to render the story and it is uncaught by the app layer
function showException(exception) {
addons.getChannel().emit(Events.STORY_THREW_EXCEPTION, exception);
showErrorDisplay(exception);
// Log the stack to the console. So, user could check the source code.
logger.error(exception.stack);
}
const isBrowser =
navigator &&
navigator.userAgent &&
navigator.userAgent !== 'storyshots' &&
!(navigator.userAgent.indexOf('Node.js') > -1) &&
!(navigator.userAgent.indexOf('jsdom') > -1);
const getContext = (() => {
let cache;
return decorateStory => {
if (cache) {
return cache;
}
let channel = null;
if (isBrowser) {
try {
channel = addons.getChannel();
} catch (e) {
channel = createChannel({ page: 'preview' });
addons.setChannel(channel);
}
}
const storyStore = new StoryStore({ channel });
const clientApi = new ClientApi({ storyStore, decorateStory });
const { clearDecorators } = clientApi;
const configApi = new ConfigApi({ clearDecorators, storyStore, channel, clientApi });
return {
configApi,
storyStore,
channel,
clientApi,
showMain,
showError,
showException,
};
};
})();
export default function start(render, { decorateStory } = {}) {
const context = getContext(decorateStory);
const { clientApi, channel, configApi, storyStore } = context;
// Provide access to external scripts if `window` is defined.
// NOTE this is different to isBrowser, primarily for the JSDOM use case
let previousKind = '';
let previousStory = '';
let previousRevision = -1;
const renderMain = forceRender => {
const revision = storyStore.getRevision();
const { kind, name, story } = storyStore.getSelection() || {};
if (story) {
// Render story only if selectedKind or selectedStory have changed.
// However, we DO want the story to re-render if the store itself has changed
// (which happens at the moment when HMR occurs)
if (
!forceRender &&
revision === previousRevision &&
kind === previousKind &&
previousStory === name
) {
return;
}
if (!forceRender) {
// Scroll to top of the page when changing story
document.documentElement.scrollTop = 0;
}
render({
...context,
story,
selectedKind: kind,
selectedStory: name,
forceRender,
});
addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection());
} else {
showNopreview();
addons.getChannel().emit(Events.STORY_MISSING, storyStore.getSelection());
}
previousRevision = revision;
previousKind = kind;
previousStory = name;
};
// initialize the UI
const renderUI = forceRender => {
if (isBrowser) {
try {
renderMain(forceRender);
} catch (ex) {
showException(ex);
}
}
};
const forceReRender = () => renderUI(true);
// channel can be null in NodeJS
if (isBrowser) {
channel.on(Events.FORCE_RE_RENDER, forceReRender);
channel.on(Events.SET_CURRENT_STORY, ({ location }) => {
if (!location) {
throw new Error('should have location');
}
const data = storyStore.fromPath(location);
console.log('here', location);
storyStore.setSelection(data);
storyStore.setPath(location);
});
// Handle keyboard shortcuts
window.onkeydown = handleKeyboardShortcuts(channel);
}
storyStore.on(Events.STORY_RENDER, renderUI);
if (typeof window !== 'undefined') {
window.__STORYBOOK_CLIENT_API__ = clientApi;
window.__STORYBOOK_ADDONS_CHANNEL__ = channel; // may not be defined
}
return { context, clientApi, configApi, forceReRender };
}
| lib/core/src/client/preview/start.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001765605411492288,
0.00017212754755746573,
0.00016635414795018733,
0.00017300799663644284,
0.0000029700540835619904
]
|
{
"id": 1,
"code_window": [
" <Toolbar\n",
" key=\"toolbar\"\n",
" left={[\n",
" <TabBar key=\"tabs\" scroll={false}>\n",
" {tabsList.map(t => (\n",
" <S.UnstyledLink\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" {tabsList.map((t, index) => (\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 90
} | const projectTypes = {
UNDETECTED: 'UNDETECTED',
REACT_SCRIPTS: 'REACT_SCRIPTS',
METEOR: 'METEOR',
REACT: 'REACT',
REACT_NATIVE: 'REACT_NATIVE',
REACT_PROJECT: 'REACT_PROJECT',
WEBPACK_REACT: 'WEBPACK_REACT',
VUE: 'VUE',
SFC_VUE: 'SFC_VUE',
ANGULAR: 'ANGULAR',
EMBER: 'EMBER',
ALREADY_HAS_STORYBOOK: 'ALREADY_HAS_STORYBOOK',
UPDATE_PACKAGE_ORGANIZATIONS: 'UPDATE_PACKAGE_ORGANIZATIONS',
POLYMER: 'POLYMER',
MITHRIL: 'MITHRIL',
MARKO: 'MARKO',
HTML: 'HTML',
RIOT: 'RIOT',
};
export default projectTypes;
export const supportedFrameworks = [
'react',
'react-native',
'vue',
'angular',
'polymer',
'mithril',
'riot',
'ember',
'marko',
'meteor',
];
const notInstallableProjectTypes = [
projectTypes.UNDETECTED,
projectTypes.ALREADY_HAS_STORYBOOK,
projectTypes.UPDATE_PACKAGE_ORGANIZATIONS,
];
export const installableProjectTypes = Object.values(projectTypes)
.filter(type => !notInstallableProjectTypes.includes(type))
.map(type => type.toLowerCase());
| lib/cli/lib/project_types.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0002317071775905788,
0.00018271952285431325,
0.00016560412768740207,
0.00017196314001921564,
0.000024629762265249155
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.